872689f313629f8556d5af62dc74c31ba2485fc6
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-tsserver / lib / index.js
1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/        // The module cache
3 /******/        var installedModules = {};
4 /******/
5 /******/        // The require function
6 /******/        function __webpack_require__(moduleId) {
7 /******/
8 /******/                // Check if module is in cache
9 /******/                if(installedModules[moduleId]) {
10 /******/                        return installedModules[moduleId].exports;
11 /******/                }
12 /******/                // Create a new module (and put it into the cache)
13 /******/                var module = installedModules[moduleId] = {
14 /******/                        i: moduleId,
15 /******/                        l: false,
16 /******/                        exports: {}
17 /******/                };
18 /******/
19 /******/                // Execute the module function
20 /******/                modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
21 /******/
22 /******/                // Flag the module as loaded
23 /******/                module.l = true;
24 /******/
25 /******/                // Return the exports of the module
26 /******/                return module.exports;
27 /******/        }
28 /******/
29 /******/
30 /******/        // expose the modules object (__webpack_modules__)
31 /******/        __webpack_require__.m = modules;
32 /******/
33 /******/        // expose the module cache
34 /******/        __webpack_require__.c = installedModules;
35 /******/
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 });
40 /******/                }
41 /******/        };
42 /******/
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' });
47 /******/                }
48 /******/                Object.defineProperty(exports, '__esModule', { value: true });
49 /******/        };
50 /******/
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));
64 /******/                return ns;
65 /******/        };
66 /******/
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;
74 /******/        };
75 /******/
76 /******/        // Object.prototype.hasOwnProperty.call
77 /******/        __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
78 /******/
79 /******/        // __webpack_public_path__
80 /******/        __webpack_require__.p = "";
81 /******/
82 /******/
83 /******/        // Load entry module and return exports
84 /******/        return __webpack_require__(__webpack_require__.s = 0);
85 /******/ })
86 /************************************************************************/
87 /******/ ([
88 /* 0 */
89 /***/ (function(module, exports, __webpack_require__) {
90
91 "use strict";
92
93 var __importDefault = (this && this.__importDefault) || function (mod) {
94     return (mod && mod.__esModule) ? mod : { "default": mod };
95 };
96 Object.defineProperty(exports, "__esModule", { value: true });
97 exports.activate = void 0;
98 const coc_nvim_1 = __webpack_require__(1);
99 const server_1 = __importDefault(__webpack_require__(2));
100 const commands_1 = __webpack_require__(141);
101 const organizeImports_1 = __webpack_require__(112);
102 const plugins_1 = __webpack_require__(142);
103 async function activate(context) {
104     let { subscriptions, logger } = context;
105     const config = coc_nvim_1.workspace.getConfiguration().get('tsserver', {});
106     if (!config.enable)
107         return;
108     const pluginManager = new plugins_1.PluginManager();
109     const service = new server_1.default(pluginManager);
110     function registCommand(cmd) {
111         let { id, execute } = cmd;
112         subscriptions.push(coc_nvim_1.commands.registerCommand(id, execute, cmd));
113     }
114     registCommand(new commands_1.ConfigurePluginCommand(pluginManager));
115     registCommand(new commands_1.AutoFixCommand(service));
116     registCommand(new commands_1.ReloadProjectsCommand(service));
117     registCommand(new commands_1.OpenTsServerLogCommand(service));
118     registCommand(new commands_1.TypeScriptGoToProjectConfigCommand(service));
119     registCommand(new organizeImports_1.OrganizeImportsCommand(service));
120     service.start().then(() => {
121         subscriptions.push(coc_nvim_1.services.regist(service));
122         registCommand(coc_nvim_1.commands.register({
123             id: 'tsserver.restart',
124             execute: () => {
125                 // tslint:disable-next-line:no-floating-promises
126                 service.stop().then(() => {
127                     setTimeout(() => {
128                         service.restart();
129                     }, 100);
130                 });
131             }
132         }));
133     }, e => {
134         logger.error(`Error on service start:`, e);
135     });
136     return {
137         configurePlugin: (pluginId, configuration) => {
138             pluginManager.setConfiguration(pluginId, configuration);
139         }
140     };
141 }
142 exports.activate = activate;
143
144
145 /***/ }),
146 /* 1 */
147 /***/ (function(module, exports) {
148
149 module.exports = require("coc.nvim");
150
151 /***/ }),
152 /* 2 */
153 /***/ (function(module, exports, __webpack_require__) {
154
155 "use strict";
156
157 var __importDefault = (this && this.__importDefault) || function (mod) {
158     return (mod && mod.__esModule) ? mod : { "default": mod };
159 };
160 Object.defineProperty(exports, "__esModule", { value: true });
161 const coc_nvim_1 = __webpack_require__(1);
162 const vscode_languageserver_protocol_1 = __webpack_require__(3);
163 const typescriptServiceClientHost_1 = __importDefault(__webpack_require__(33));
164 const languageDescription_1 = __webpack_require__(140);
165 class TsserverService {
166     constructor(pluginManager) {
167         this.pluginManager = pluginManager;
168         this.id = 'tsserver';
169         this.name = 'tsserver';
170         this.state = coc_nvim_1.ServiceStat.Initial;
171         this._onDidServiceReady = new vscode_languageserver_protocol_1.Emitter();
172         this.onServiceReady = this._onDidServiceReady.event;
173         this.disposables = [];
174         this.descriptions = [];
175         const config = coc_nvim_1.workspace.getConfiguration('tsserver');
176         const enableJavascript = !!config.get('enableJavascript');
177         this.enable = config.get('enable');
178         this.descriptions = languageDescription_1.standardLanguageDescriptions.filter(o => {
179             return enableJavascript ? true : o.id != 'javascript';
180         });
181         this.selector = this.descriptions.reduce((arr, c) => {
182             return arr.concat(c.modeIds);
183         }, []);
184     }
185     get config() {
186         return coc_nvim_1.workspace.getConfiguration('tsserver');
187     }
188     /**
189      * Get running client host.
190      */
191     getClientHost() {
192         if (this.state == coc_nvim_1.ServiceStat.Running)
193             return Promise.resolve(this.clientHost);
194         this.start();
195         return new Promise((resolve, reject) => {
196             let timer = setTimeout(() => {
197                 reject(new Error(`Server not started after 5s`));
198             }, 5000);
199             let disposable = this.onServiceReady(() => {
200                 clearTimeout(timer);
201                 disposable.dispose();
202                 resolve(this.clientHost);
203             });
204         });
205     }
206     start() {
207         if (this.clientHost)
208             return;
209         this.state = coc_nvim_1.ServiceStat.Starting;
210         this.clientHost = new typescriptServiceClientHost_1.default(this.descriptions, this.pluginManager);
211         this.disposables.push(this.clientHost);
212         let client = this.clientHost.serviceClient;
213         return new Promise(resolve => {
214             let started = false;
215             client.onTsServerStarted(() => {
216                 Object.defineProperty(this, 'state', {
217                     get: () => {
218                         return this.clientHost.serviceClient.state;
219                     }
220                 });
221                 this._onDidServiceReady.fire(void 0);
222                 if (!started) {
223                     started = true;
224                     resolve();
225                 }
226             });
227         });
228     }
229     dispose() {
230         coc_nvim_1.disposeAll(this.disposables);
231     }
232     async restart() {
233         if (!this.clientHost)
234             return;
235         let client = this.clientHost.serviceClient;
236         await client.restartTsServer();
237     }
238     async stop() {
239         if (!this.clientHost)
240             return;
241         this.clientHost.reset();
242         let client = this.clientHost.serviceClient;
243         await client.stop();
244         return;
245     }
246 }
247 exports.default = TsserverService;
248
249
250 /***/ }),
251 /* 3 */
252 /***/ (function(module, exports, __webpack_require__) {
253
254 "use strict";
255 /* --------------------------------------------------------------------------------------------\r
256  * Copyright (c) Microsoft Corporation. All rights reserved.\r
257  * Licensed under the MIT License. See License.txt in the project root for license information.\r
258  * ------------------------------------------------------------------------------------------ */\r
259 \r
260 function __export(m) {\r
261     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
262 }\r
263 Object.defineProperty(exports, "__esModule", { value: true });\r
264 const vscode_jsonrpc_1 = __webpack_require__(4);\r
265 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;\r
266 exports.ResponseError = vscode_jsonrpc_1.ResponseError;\r
267 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;\r
268 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;\r
269 exports.Disposable = vscode_jsonrpc_1.Disposable;\r
270 exports.Event = vscode_jsonrpc_1.Event;\r
271 exports.Emitter = vscode_jsonrpc_1.Emitter;\r
272 exports.Trace = vscode_jsonrpc_1.Trace;\r
273 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;\r
274 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;\r
275 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;\r
276 exports.RequestType = vscode_jsonrpc_1.RequestType;\r
277 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;\r
278 exports.NotificationType = vscode_jsonrpc_1.NotificationType;\r
279 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;\r
280 exports.MessageReader = vscode_jsonrpc_1.MessageReader;\r
281 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;\r
282 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;\r
283 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;\r
284 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;\r
285 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;\r
286 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;\r
287 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;\r
288 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;\r
289 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;\r
290 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;\r
291 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;\r
292 exports.ProgressType = vscode_jsonrpc_1.ProgressType;\r
293 __export(__webpack_require__(18));\r
294 __export(__webpack_require__(19));\r
295 const callHierarchy = __webpack_require__(31);\r
296 const st = __webpack_require__(32);\r
297 var Proposed;\r
298 (function (Proposed) {\r
299     let CallHierarchyPrepareRequest;\r
300     (function (CallHierarchyPrepareRequest) {\r
301         CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;\r
302         CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;\r
303     })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));\r
304     let CallHierarchyIncomingCallsRequest;\r
305     (function (CallHierarchyIncomingCallsRequest) {\r
306         CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;\r
307         CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;\r
308     })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));\r
309     let CallHierarchyOutgoingCallsRequest;\r
310     (function (CallHierarchyOutgoingCallsRequest) {\r
311         CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;\r
312         CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;\r
313     })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));\r
314     Proposed.SemanticTokenTypes = st.SemanticTokenTypes;\r
315     Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;\r
316     Proposed.SemanticTokens = st.SemanticTokens;\r
317     let SemanticTokensRequest;\r
318     (function (SemanticTokensRequest) {\r
319         SemanticTokensRequest.method = st.SemanticTokensRequest.method;\r
320         SemanticTokensRequest.type = st.SemanticTokensRequest.type;\r
321     })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));\r
322     let SemanticTokensEditsRequest;\r
323     (function (SemanticTokensEditsRequest) {\r
324         SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;\r
325         SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;\r
326     })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));\r
327     let SemanticTokensRangeRequest;\r
328     (function (SemanticTokensRangeRequest) {\r
329         SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;\r
330         SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;\r
331     })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));\r
332 })(Proposed = exports.Proposed || (exports.Proposed = {}));\r
333 function createProtocolConnection(reader, writer, logger, strategy) {\r
334     return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);\r
335 }\r
336 exports.createProtocolConnection = createProtocolConnection;\r
337
338
339 /***/ }),
340 /* 4 */
341 /***/ (function(module, exports, __webpack_require__) {
342
343 "use strict";
344 /* --------------------------------------------------------------------------------------------\r
345  * Copyright (c) Microsoft Corporation. All rights reserved.\r
346  * Licensed under the MIT License. See License.txt in the project root for license information.\r
347  * ------------------------------------------------------------------------------------------ */\r
348 /// <reference path="../typings/thenable.d.ts" />\r
349 \r
350 function __export(m) {\r
351     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r
352 }\r
353 Object.defineProperty(exports, "__esModule", { value: true });\r
354 const Is = __webpack_require__(5);\r
355 const messages_1 = __webpack_require__(6);\r
356 exports.RequestType = messages_1.RequestType;\r
357 exports.RequestType0 = messages_1.RequestType0;\r
358 exports.RequestType1 = messages_1.RequestType1;\r
359 exports.RequestType2 = messages_1.RequestType2;\r
360 exports.RequestType3 = messages_1.RequestType3;\r
361 exports.RequestType4 = messages_1.RequestType4;\r
362 exports.RequestType5 = messages_1.RequestType5;\r
363 exports.RequestType6 = messages_1.RequestType6;\r
364 exports.RequestType7 = messages_1.RequestType7;\r
365 exports.RequestType8 = messages_1.RequestType8;\r
366 exports.RequestType9 = messages_1.RequestType9;\r
367 exports.ResponseError = messages_1.ResponseError;\r
368 exports.ErrorCodes = messages_1.ErrorCodes;\r
369 exports.NotificationType = messages_1.NotificationType;\r
370 exports.NotificationType0 = messages_1.NotificationType0;\r
371 exports.NotificationType1 = messages_1.NotificationType1;\r
372 exports.NotificationType2 = messages_1.NotificationType2;\r
373 exports.NotificationType3 = messages_1.NotificationType3;\r
374 exports.NotificationType4 = messages_1.NotificationType4;\r
375 exports.NotificationType5 = messages_1.NotificationType5;\r
376 exports.NotificationType6 = messages_1.NotificationType6;\r
377 exports.NotificationType7 = messages_1.NotificationType7;\r
378 exports.NotificationType8 = messages_1.NotificationType8;\r
379 exports.NotificationType9 = messages_1.NotificationType9;\r
380 const messageReader_1 = __webpack_require__(7);\r
381 exports.MessageReader = messageReader_1.MessageReader;\r
382 exports.StreamMessageReader = messageReader_1.StreamMessageReader;\r
383 exports.IPCMessageReader = messageReader_1.IPCMessageReader;\r
384 exports.SocketMessageReader = messageReader_1.SocketMessageReader;\r
385 const messageWriter_1 = __webpack_require__(9);\r
386 exports.MessageWriter = messageWriter_1.MessageWriter;\r
387 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;\r
388 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;\r
389 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;\r
390 const events_1 = __webpack_require__(8);\r
391 exports.Disposable = events_1.Disposable;\r
392 exports.Event = events_1.Event;\r
393 exports.Emitter = events_1.Emitter;\r
394 const cancellation_1 = __webpack_require__(10);\r
395 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;\r
396 exports.CancellationToken = cancellation_1.CancellationToken;\r
397 const linkedMap_1 = __webpack_require__(11);\r
398 __export(__webpack_require__(12));\r
399 __export(__webpack_require__(17));\r
400 var CancelNotification;\r
401 (function (CancelNotification) {\r
402     CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');\r
403 })(CancelNotification || (CancelNotification = {}));\r
404 var ProgressNotification;\r
405 (function (ProgressNotification) {\r
406     ProgressNotification.type = new messages_1.NotificationType('$/progress');\r
407 })(ProgressNotification || (ProgressNotification = {}));\r
408 class ProgressType {\r
409     constructor() {\r
410     }\r
411 }\r
412 exports.ProgressType = ProgressType;\r
413 exports.NullLogger = Object.freeze({\r
414     error: () => { },\r
415     warn: () => { },\r
416     info: () => { },\r
417     log: () => { }\r
418 });\r
419 var Trace;\r
420 (function (Trace) {\r
421     Trace[Trace["Off"] = 0] = "Off";\r
422     Trace[Trace["Messages"] = 1] = "Messages";\r
423     Trace[Trace["Verbose"] = 2] = "Verbose";\r
424 })(Trace = exports.Trace || (exports.Trace = {}));\r
425 (function (Trace) {\r
426     function fromString(value) {\r
427         if (!Is.string(value)) {\r
428             return Trace.Off;\r
429         }\r
430         value = value.toLowerCase();\r
431         switch (value) {\r
432             case 'off':\r
433                 return Trace.Off;\r
434             case 'messages':\r
435                 return Trace.Messages;\r
436             case 'verbose':\r
437                 return Trace.Verbose;\r
438             default:\r
439                 return Trace.Off;\r
440         }\r
441     }\r
442     Trace.fromString = fromString;\r
443     function toString(value) {\r
444         switch (value) {\r
445             case Trace.Off:\r
446                 return 'off';\r
447             case Trace.Messages:\r
448                 return 'messages';\r
449             case Trace.Verbose:\r
450                 return 'verbose';\r
451             default:\r
452                 return 'off';\r
453         }\r
454     }\r
455     Trace.toString = toString;\r
456 })(Trace = exports.Trace || (exports.Trace = {}));\r
457 var TraceFormat;\r
458 (function (TraceFormat) {\r
459     TraceFormat["Text"] = "text";\r
460     TraceFormat["JSON"] = "json";\r
461 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
462 (function (TraceFormat) {\r
463     function fromString(value) {\r
464         value = value.toLowerCase();\r
465         if (value === 'json') {\r
466             return TraceFormat.JSON;\r
467         }\r
468         else {\r
469             return TraceFormat.Text;\r
470         }\r
471     }\r
472     TraceFormat.fromString = fromString;\r
473 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));\r
474 var SetTraceNotification;\r
475 (function (SetTraceNotification) {\r
476     SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');\r
477 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));\r
478 var LogTraceNotification;\r
479 (function (LogTraceNotification) {\r
480     LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');\r
481 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));\r
482 var ConnectionErrors;\r
483 (function (ConnectionErrors) {\r
484     /**\r
485      * The connection is closed.\r
486      */\r
487     ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";\r
488     /**\r
489      * The connection got disposed.\r
490      */\r
491     ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";\r
492     /**\r
493      * The connection is already in listening mode.\r
494      */\r
495     ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";\r
496 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));\r
497 class ConnectionError extends Error {\r
498     constructor(code, message) {\r
499         super(message);\r
500         this.code = code;\r
501         Object.setPrototypeOf(this, ConnectionError.prototype);\r
502     }\r
503 }\r
504 exports.ConnectionError = ConnectionError;\r
505 var ConnectionStrategy;\r
506 (function (ConnectionStrategy) {\r
507     function is(value) {\r
508         let candidate = value;\r
509         return candidate && Is.func(candidate.cancelUndispatched);\r
510     }\r
511     ConnectionStrategy.is = is;\r
512 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));\r
513 var ConnectionState;\r
514 (function (ConnectionState) {\r
515     ConnectionState[ConnectionState["New"] = 1] = "New";\r
516     ConnectionState[ConnectionState["Listening"] = 2] = "Listening";\r
517     ConnectionState[ConnectionState["Closed"] = 3] = "Closed";\r
518     ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";\r
519 })(ConnectionState || (ConnectionState = {}));\r
520 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {\r
521     let sequenceNumber = 0;\r
522     let notificationSquenceNumber = 0;\r
523     let unknownResponseSquenceNumber = 0;\r
524     const version = '2.0';\r
525     let starRequestHandler = undefined;\r
526     let requestHandlers = Object.create(null);\r
527     let starNotificationHandler = undefined;\r
528     let notificationHandlers = Object.create(null);\r
529     let progressHandlers = new Map();\r
530     let timer;\r
531     let messageQueue = new linkedMap_1.LinkedMap();\r
532     let responsePromises = Object.create(null);\r
533     let requestTokens = Object.create(null);\r
534     let trace = Trace.Off;\r
535     let traceFormat = TraceFormat.Text;\r
536     let tracer;\r
537     let state = ConnectionState.New;\r
538     let errorEmitter = new events_1.Emitter();\r
539     let closeEmitter = new events_1.Emitter();\r
540     let unhandledNotificationEmitter = new events_1.Emitter();\r
541     let unhandledProgressEmitter = new events_1.Emitter();\r
542     let disposeEmitter = new events_1.Emitter();\r
543     function createRequestQueueKey(id) {\r
544         return 'req-' + id.toString();\r
545     }\r
546     function createResponseQueueKey(id) {\r
547         if (id === null) {\r
548             return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();\r
549         }\r
550         else {\r
551             return 'res-' + id.toString();\r
552         }\r
553     }\r
554     function createNotificationQueueKey() {\r
555         return 'not-' + (++notificationSquenceNumber).toString();\r
556     }\r
557     function addMessageToQueue(queue, message) {\r
558         if (messages_1.isRequestMessage(message)) {\r
559             queue.set(createRequestQueueKey(message.id), message);\r
560         }\r
561         else if (messages_1.isResponseMessage(message)) {\r
562             queue.set(createResponseQueueKey(message.id), message);\r
563         }\r
564         else {\r
565             queue.set(createNotificationQueueKey(), message);\r
566         }\r
567     }\r
568     function cancelUndispatched(_message) {\r
569         return undefined;\r
570     }\r
571     function isListening() {\r
572         return state === ConnectionState.Listening;\r
573     }\r
574     function isClosed() {\r
575         return state === ConnectionState.Closed;\r
576     }\r
577     function isDisposed() {\r
578         return state === ConnectionState.Disposed;\r
579     }\r
580     function closeHandler() {\r
581         if (state === ConnectionState.New || state === ConnectionState.Listening) {\r
582             state = ConnectionState.Closed;\r
583             closeEmitter.fire(undefined);\r
584         }\r
585         // If the connection is disposed don't sent close events.\r
586     }\r
587     function readErrorHandler(error) {\r
588         errorEmitter.fire([error, undefined, undefined]);\r
589     }\r
590     function writeErrorHandler(data) {\r
591         errorEmitter.fire(data);\r
592     }\r
593     messageReader.onClose(closeHandler);\r
594     messageReader.onError(readErrorHandler);\r
595     messageWriter.onClose(closeHandler);\r
596     messageWriter.onError(writeErrorHandler);\r
597     function triggerMessageQueue() {\r
598         if (timer || messageQueue.size === 0) {\r
599             return;\r
600         }\r
601         timer = setImmediate(() => {\r
602             timer = undefined;\r
603             processMessageQueue();\r
604         });\r
605     }\r
606     function processMessageQueue() {\r
607         if (messageQueue.size === 0) {\r
608             return;\r
609         }\r
610         let message = messageQueue.shift();\r
611         try {\r
612             if (messages_1.isRequestMessage(message)) {\r
613                 handleRequest(message);\r
614             }\r
615             else if (messages_1.isNotificationMessage(message)) {\r
616                 handleNotification(message);\r
617             }\r
618             else if (messages_1.isResponseMessage(message)) {\r
619                 handleResponse(message);\r
620             }\r
621             else {\r
622                 handleInvalidMessage(message);\r
623             }\r
624         }\r
625         finally {\r
626             triggerMessageQueue();\r
627         }\r
628     }\r
629     let callback = (message) => {\r
630         try {\r
631             // We have received a cancellation message. Check if the message is still in the queue\r
632             // and cancel it if allowed to do so.\r
633             if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {\r
634                 let key = createRequestQueueKey(message.params.id);\r
635                 let toCancel = messageQueue.get(key);\r
636                 if (messages_1.isRequestMessage(toCancel)) {\r
637                     let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);\r
638                     if (response && (response.error !== void 0 || response.result !== void 0)) {\r
639                         messageQueue.delete(key);\r
640                         response.id = toCancel.id;\r
641                         traceSendingResponse(response, message.method, Date.now());\r
642                         messageWriter.write(response);\r
643                         return;\r
644                     }\r
645                 }\r
646             }\r
647             addMessageToQueue(messageQueue, message);\r
648         }\r
649         finally {\r
650             triggerMessageQueue();\r
651         }\r
652     };\r
653     function handleRequest(requestMessage) {\r
654         if (isDisposed()) {\r
655             // we return here silently since we fired an event when the\r
656             // connection got disposed.\r
657             return;\r
658         }\r
659         function reply(resultOrError, method, startTime) {\r
660             let message = {\r
661                 jsonrpc: version,\r
662                 id: requestMessage.id\r
663             };\r
664             if (resultOrError instanceof messages_1.ResponseError) {\r
665                 message.error = resultOrError.toJson();\r
666             }\r
667             else {\r
668                 message.result = resultOrError === void 0 ? null : resultOrError;\r
669             }\r
670             traceSendingResponse(message, method, startTime);\r
671             messageWriter.write(message);\r
672         }\r
673         function replyError(error, method, startTime) {\r
674             let message = {\r
675                 jsonrpc: version,\r
676                 id: requestMessage.id,\r
677                 error: error.toJson()\r
678             };\r
679             traceSendingResponse(message, method, startTime);\r
680             messageWriter.write(message);\r
681         }\r
682         function replySuccess(result, method, startTime) {\r
683             // The JSON RPC defines that a response must either have a result or an error\r
684             // So we can't treat undefined as a valid response result.\r
685             if (result === void 0) {\r
686                 result = null;\r
687             }\r
688             let message = {\r
689                 jsonrpc: version,\r
690                 id: requestMessage.id,\r
691                 result: result\r
692             };\r
693             traceSendingResponse(message, method, startTime);\r
694             messageWriter.write(message);\r
695         }\r
696         traceReceivedRequest(requestMessage);\r
697         let element = requestHandlers[requestMessage.method];\r
698         let type;\r
699         let requestHandler;\r
700         if (element) {\r
701             type = element.type;\r
702             requestHandler = element.handler;\r
703         }\r
704         let startTime = Date.now();\r
705         if (requestHandler || starRequestHandler) {\r
706             let cancellationSource = new cancellation_1.CancellationTokenSource();\r
707             let tokenKey = String(requestMessage.id);\r
708             requestTokens[tokenKey] = cancellationSource;\r
709             try {\r
710                 let handlerResult;\r
711                 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
712                     handlerResult = requestHandler\r
713                         ? requestHandler(cancellationSource.token)\r
714                         : starRequestHandler(requestMessage.method, cancellationSource.token);\r
715                 }\r
716                 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {\r
717                     handlerResult = requestHandler\r
718                         ? requestHandler(...requestMessage.params, cancellationSource.token)\r
719                         : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);\r
720                 }\r
721                 else {\r
722                     handlerResult = requestHandler\r
723                         ? requestHandler(requestMessage.params, cancellationSource.token)\r
724                         : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);\r
725                 }\r
726                 let promise = handlerResult;\r
727                 if (!handlerResult) {\r
728                     delete requestTokens[tokenKey];\r
729                     replySuccess(handlerResult, requestMessage.method, startTime);\r
730                 }\r
731                 else if (promise.then) {\r
732                     promise.then((resultOrError) => {\r
733                         delete requestTokens[tokenKey];\r
734                         reply(resultOrError, requestMessage.method, startTime);\r
735                     }, error => {\r
736                         delete requestTokens[tokenKey];\r
737                         if (error instanceof messages_1.ResponseError) {\r
738                             replyError(error, requestMessage.method, startTime);\r
739                         }\r
740                         else if (error && Is.string(error.message)) {\r
741                             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
742                         }\r
743                         else {\r
744                             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
745                         }\r
746                     });\r
747                 }\r
748                 else {\r
749                     delete requestTokens[tokenKey];\r
750                     reply(handlerResult, requestMessage.method, startTime);\r
751                 }\r
752             }\r
753             catch (error) {\r
754                 delete requestTokens[tokenKey];\r
755                 if (error instanceof messages_1.ResponseError) {\r
756                     reply(error, requestMessage.method, startTime);\r
757                 }\r
758                 else if (error && Is.string(error.message)) {\r
759                     replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);\r
760                 }\r
761                 else {\r
762                     replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);\r
763                 }\r
764             }\r
765         }\r
766         else {\r
767             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);\r
768         }\r
769     }\r
770     function handleResponse(responseMessage) {\r
771         if (isDisposed()) {\r
772             // See handle request.\r
773             return;\r
774         }\r
775         if (responseMessage.id === null) {\r
776             if (responseMessage.error) {\r
777                 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);\r
778             }\r
779             else {\r
780                 logger.error(`Received response message without id. No further error information provided.`);\r
781             }\r
782         }\r
783         else {\r
784             let key = String(responseMessage.id);\r
785             let responsePromise = responsePromises[key];\r
786             traceReceivedResponse(responseMessage, responsePromise);\r
787             if (responsePromise) {\r
788                 delete responsePromises[key];\r
789                 try {\r
790                     if (responseMessage.error) {\r
791                         let error = responseMessage.error;\r
792                         responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));\r
793                     }\r
794                     else if (responseMessage.result !== void 0) {\r
795                         responsePromise.resolve(responseMessage.result);\r
796                     }\r
797                     else {\r
798                         throw new Error('Should never happen.');\r
799                     }\r
800                 }\r
801                 catch (error) {\r
802                     if (error.message) {\r
803                         logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);\r
804                     }\r
805                     else {\r
806                         logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);\r
807                     }\r
808                 }\r
809             }\r
810         }\r
811     }\r
812     function handleNotification(message) {\r
813         if (isDisposed()) {\r
814             // See handle request.\r
815             return;\r
816         }\r
817         let type = undefined;\r
818         let notificationHandler;\r
819         if (message.method === CancelNotification.type.method) {\r
820             notificationHandler = (params) => {\r
821                 let id = params.id;\r
822                 let source = requestTokens[String(id)];\r
823                 if (source) {\r
824                     source.cancel();\r
825                 }\r
826             };\r
827         }\r
828         else {\r
829             let element = notificationHandlers[message.method];\r
830             if (element) {\r
831                 notificationHandler = element.handler;\r
832                 type = element.type;\r
833             }\r
834         }\r
835         if (notificationHandler || starNotificationHandler) {\r
836             try {\r
837                 traceReceivedNotification(message);\r
838                 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {\r
839                     notificationHandler ? notificationHandler() : starNotificationHandler(message.method);\r
840                 }\r
841                 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {\r
842                     notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);\r
843                 }\r
844                 else {\r
845                     notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);\r
846                 }\r
847             }\r
848             catch (error) {\r
849                 if (error.message) {\r
850                     logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);\r
851                 }\r
852                 else {\r
853                     logger.error(`Notification handler '${message.method}' failed unexpectedly.`);\r
854                 }\r
855             }\r
856         }\r
857         else {\r
858             unhandledNotificationEmitter.fire(message);\r
859         }\r
860     }\r
861     function handleInvalidMessage(message) {\r
862         if (!message) {\r
863             logger.error('Received empty message.');\r
864             return;\r
865         }\r
866         logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);\r
867         // Test whether we find an id to reject the promise\r
868         let responseMessage = message;\r
869         if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {\r
870             let key = String(responseMessage.id);\r
871             let responseHandler = responsePromises[key];\r
872             if (responseHandler) {\r
873                 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));\r
874             }\r
875         }\r
876     }\r
877     function traceSendingRequest(message) {\r
878         if (trace === Trace.Off || !tracer) {\r
879             return;\r
880         }\r
881         if (traceFormat === TraceFormat.Text) {\r
882             let data = undefined;\r
883             if (trace === Trace.Verbose && message.params) {\r
884                 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
885             }\r
886             tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);\r
887         }\r
888         else {\r
889             logLSPMessage('send-request', message);\r
890         }\r
891     }\r
892     function traceSendingNotification(message) {\r
893         if (trace === Trace.Off || !tracer) {\r
894             return;\r
895         }\r
896         if (traceFormat === TraceFormat.Text) {\r
897             let data = undefined;\r
898             if (trace === Trace.Verbose) {\r
899                 if (message.params) {\r
900                     data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
901                 }\r
902                 else {\r
903                     data = 'No parameters provided.\n\n';\r
904                 }\r
905             }\r
906             tracer.log(`Sending notification '${message.method}'.`, data);\r
907         }\r
908         else {\r
909             logLSPMessage('send-notification', message);\r
910         }\r
911     }\r
912     function traceSendingResponse(message, method, startTime) {\r
913         if (trace === Trace.Off || !tracer) {\r
914             return;\r
915         }\r
916         if (traceFormat === TraceFormat.Text) {\r
917             let data = undefined;\r
918             if (trace === Trace.Verbose) {\r
919                 if (message.error && message.error.data) {\r
920                     data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
921                 }\r
922                 else {\r
923                     if (message.result) {\r
924                         data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
925                     }\r
926                     else if (message.error === void 0) {\r
927                         data = 'No result returned.\n\n';\r
928                     }\r
929                 }\r
930             }\r
931             tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);\r
932         }\r
933         else {\r
934             logLSPMessage('send-response', message);\r
935         }\r
936     }\r
937     function traceReceivedRequest(message) {\r
938         if (trace === Trace.Off || !tracer) {\r
939             return;\r
940         }\r
941         if (traceFormat === TraceFormat.Text) {\r
942             let data = undefined;\r
943             if (trace === Trace.Verbose && message.params) {\r
944                 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
945             }\r
946             tracer.log(`Received request '${message.method} - (${message.id})'.`, data);\r
947         }\r
948         else {\r
949             logLSPMessage('receive-request', message);\r
950         }\r
951     }\r
952     function traceReceivedNotification(message) {\r
953         if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {\r
954             return;\r
955         }\r
956         if (traceFormat === TraceFormat.Text) {\r
957             let data = undefined;\r
958             if (trace === Trace.Verbose) {\r
959                 if (message.params) {\r
960                     data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;\r
961                 }\r
962                 else {\r
963                     data = 'No parameters provided.\n\n';\r
964                 }\r
965             }\r
966             tracer.log(`Received notification '${message.method}'.`, data);\r
967         }\r
968         else {\r
969             logLSPMessage('receive-notification', message);\r
970         }\r
971     }\r
972     function traceReceivedResponse(message, responsePromise) {\r
973         if (trace === Trace.Off || !tracer) {\r
974             return;\r
975         }\r
976         if (traceFormat === TraceFormat.Text) {\r
977             let data = undefined;\r
978             if (trace === Trace.Verbose) {\r
979                 if (message.error && message.error.data) {\r
980                     data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;\r
981                 }\r
982                 else {\r
983                     if (message.result) {\r
984                         data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;\r
985                     }\r
986                     else if (message.error === void 0) {\r
987                         data = 'No result returned.\n\n';\r
988                     }\r
989                 }\r
990             }\r
991             if (responsePromise) {\r
992                 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';\r
993                 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);\r
994             }\r
995             else {\r
996                 tracer.log(`Received response ${message.id} without active response promise.`, data);\r
997             }\r
998         }\r
999         else {\r
1000             logLSPMessage('receive-response', message);\r
1001         }\r
1002     }\r
1003     function logLSPMessage(type, message) {\r
1004         if (!tracer || trace === Trace.Off) {\r
1005             return;\r
1006         }\r
1007         const lspMessage = {\r
1008             isLSPMessage: true,\r
1009             type,\r
1010             message,\r
1011             timestamp: Date.now()\r
1012         };\r
1013         tracer.log(lspMessage);\r
1014     }\r
1015     function throwIfClosedOrDisposed() {\r
1016         if (isClosed()) {\r
1017             throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');\r
1018         }\r
1019         if (isDisposed()) {\r
1020             throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');\r
1021         }\r
1022     }\r
1023     function throwIfListening() {\r
1024         if (isListening()) {\r
1025             throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');\r
1026         }\r
1027     }\r
1028     function throwIfNotListening() {\r
1029         if (!isListening()) {\r
1030             throw new Error('Call listen() first.');\r
1031         }\r
1032     }\r
1033     function undefinedToNull(param) {\r
1034         if (param === void 0) {\r
1035             return null;\r
1036         }\r
1037         else {\r
1038             return param;\r
1039         }\r
1040     }\r
1041     function computeMessageParams(type, params) {\r
1042         let result;\r
1043         let numberOfParams = type.numberOfParams;\r
1044         switch (numberOfParams) {\r
1045             case 0:\r
1046                 result = null;\r
1047                 break;\r
1048             case 1:\r
1049                 result = undefinedToNull(params[0]);\r
1050                 break;\r
1051             default:\r
1052                 result = [];\r
1053                 for (let i = 0; i < params.length && i < numberOfParams; i++) {\r
1054                     result.push(undefinedToNull(params[i]));\r
1055                 }\r
1056                 if (params.length < numberOfParams) {\r
1057                     for (let i = params.length; i < numberOfParams; i++) {\r
1058                         result.push(null);\r
1059                     }\r
1060                 }\r
1061                 break;\r
1062         }\r
1063         return result;\r
1064     }\r
1065     let connection = {\r
1066         sendNotification: (type, ...params) => {\r
1067             throwIfClosedOrDisposed();\r
1068             let method;\r
1069             let messageParams;\r
1070             if (Is.string(type)) {\r
1071                 method = type;\r
1072                 switch (params.length) {\r
1073                     case 0:\r
1074                         messageParams = null;\r
1075                         break;\r
1076                     case 1:\r
1077                         messageParams = params[0];\r
1078                         break;\r
1079                     default:\r
1080                         messageParams = params;\r
1081                         break;\r
1082                 }\r
1083             }\r
1084             else {\r
1085                 method = type.method;\r
1086                 messageParams = computeMessageParams(type, params);\r
1087             }\r
1088             let notificationMessage = {\r
1089                 jsonrpc: version,\r
1090                 method: method,\r
1091                 params: messageParams\r
1092             };\r
1093             traceSendingNotification(notificationMessage);\r
1094             messageWriter.write(notificationMessage);\r
1095         },\r
1096         onNotification: (type, handler) => {\r
1097             throwIfClosedOrDisposed();\r
1098             if (Is.func(type)) {\r
1099                 starNotificationHandler = type;\r
1100             }\r
1101             else if (handler) {\r
1102                 if (Is.string(type)) {\r
1103                     notificationHandlers[type] = { type: undefined, handler };\r
1104                 }\r
1105                 else {\r
1106                     notificationHandlers[type.method] = { type, handler };\r
1107                 }\r
1108             }\r
1109         },\r
1110         onProgress: (_type, token, handler) => {\r
1111             if (progressHandlers.has(token)) {\r
1112                 throw new Error(`Progress handler for token ${token} already registered`);\r
1113             }\r
1114             progressHandlers.set(token, handler);\r
1115             return {\r
1116                 dispose: () => {\r
1117                     progressHandlers.delete(token);\r
1118                 }\r
1119             };\r
1120         },\r
1121         sendProgress: (_type, token, value) => {\r
1122             connection.sendNotification(ProgressNotification.type, { token, value });\r
1123         },\r
1124         onUnhandledProgress: unhandledProgressEmitter.event,\r
1125         sendRequest: (type, ...params) => {\r
1126             throwIfClosedOrDisposed();\r
1127             throwIfNotListening();\r
1128             let method;\r
1129             let messageParams;\r
1130             let token = undefined;\r
1131             if (Is.string(type)) {\r
1132                 method = type;\r
1133                 switch (params.length) {\r
1134                     case 0:\r
1135                         messageParams = null;\r
1136                         break;\r
1137                     case 1:\r
1138                         // The cancellation token is optional so it can also be undefined.\r
1139                         if (cancellation_1.CancellationToken.is(params[0])) {\r
1140                             messageParams = null;\r
1141                             token = params[0];\r
1142                         }\r
1143                         else {\r
1144                             messageParams = undefinedToNull(params[0]);\r
1145                         }\r
1146                         break;\r
1147                     default:\r
1148                         const last = params.length - 1;\r
1149                         if (cancellation_1.CancellationToken.is(params[last])) {\r
1150                             token = params[last];\r
1151                             if (params.length === 2) {\r
1152                                 messageParams = undefinedToNull(params[0]);\r
1153                             }\r
1154                             else {\r
1155                                 messageParams = params.slice(0, last).map(value => undefinedToNull(value));\r
1156                             }\r
1157                         }\r
1158                         else {\r
1159                             messageParams = params.map(value => undefinedToNull(value));\r
1160                         }\r
1161                         break;\r
1162                 }\r
1163             }\r
1164             else {\r
1165                 method = type.method;\r
1166                 messageParams = computeMessageParams(type, params);\r
1167                 let numberOfParams = type.numberOfParams;\r
1168                 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;\r
1169             }\r
1170             let id = sequenceNumber++;\r
1171             let result = new Promise((resolve, reject) => {\r
1172                 let requestMessage = {\r
1173                     jsonrpc: version,\r
1174                     id: id,\r
1175                     method: method,\r
1176                     params: messageParams\r
1177                 };\r
1178                 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };\r
1179                 traceSendingRequest(requestMessage);\r
1180                 try {\r
1181                     messageWriter.write(requestMessage);\r
1182                 }\r
1183                 catch (e) {\r
1184                     // Writing the message failed. So we need to reject the promise.\r
1185                     responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));\r
1186                     responsePromise = null;\r
1187                 }\r
1188                 if (responsePromise) {\r
1189                     responsePromises[String(id)] = responsePromise;\r
1190                 }\r
1191             });\r
1192             if (token) {\r
1193                 token.onCancellationRequested(() => {\r
1194                     connection.sendNotification(CancelNotification.type, { id });\r
1195                 });\r
1196             }\r
1197             return result;\r
1198         },\r
1199         onRequest: (type, handler) => {\r
1200             throwIfClosedOrDisposed();\r
1201             if (Is.func(type)) {\r
1202                 starRequestHandler = type;\r
1203             }\r
1204             else if (handler) {\r
1205                 if (Is.string(type)) {\r
1206                     requestHandlers[type] = { type: undefined, handler };\r
1207                 }\r
1208                 else {\r
1209                     requestHandlers[type.method] = { type, handler };\r
1210                 }\r
1211             }\r
1212         },\r
1213         trace: (_value, _tracer, sendNotificationOrTraceOptions) => {\r
1214             let _sendNotification = false;\r
1215             let _traceFormat = TraceFormat.Text;\r
1216             if (sendNotificationOrTraceOptions !== void 0) {\r
1217                 if (Is.boolean(sendNotificationOrTraceOptions)) {\r
1218                     _sendNotification = sendNotificationOrTraceOptions;\r
1219                 }\r
1220                 else {\r
1221                     _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;\r
1222                     _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;\r
1223                 }\r
1224             }\r
1225             trace = _value;\r
1226             traceFormat = _traceFormat;\r
1227             if (trace === Trace.Off) {\r
1228                 tracer = undefined;\r
1229             }\r
1230             else {\r
1231                 tracer = _tracer;\r
1232             }\r
1233             if (_sendNotification && !isClosed() && !isDisposed()) {\r
1234                 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });\r
1235             }\r
1236         },\r
1237         onError: errorEmitter.event,\r
1238         onClose: closeEmitter.event,\r
1239         onUnhandledNotification: unhandledNotificationEmitter.event,\r
1240         onDispose: disposeEmitter.event,\r
1241         dispose: () => {\r
1242             if (isDisposed()) {\r
1243                 return;\r
1244             }\r
1245             state = ConnectionState.Disposed;\r
1246             disposeEmitter.fire(undefined);\r
1247             let error = new Error('Connection got disposed.');\r
1248             Object.keys(responsePromises).forEach((key) => {\r
1249                 responsePromises[key].reject(error);\r
1250             });\r
1251             responsePromises = Object.create(null);\r
1252             requestTokens = Object.create(null);\r
1253             messageQueue = new linkedMap_1.LinkedMap();\r
1254             // Test for backwards compatibility\r
1255             if (Is.func(messageWriter.dispose)) {\r
1256                 messageWriter.dispose();\r
1257             }\r
1258             if (Is.func(messageReader.dispose)) {\r
1259                 messageReader.dispose();\r
1260             }\r
1261         },\r
1262         listen: () => {\r
1263             throwIfClosedOrDisposed();\r
1264             throwIfListening();\r
1265             state = ConnectionState.Listening;\r
1266             messageReader.listen(callback);\r
1267         },\r
1268         inspect: () => {\r
1269             // eslint-disable-next-line no-console\r
1270             console.log('inspect');\r
1271         }\r
1272     };\r
1273     connection.onNotification(LogTraceNotification.type, (params) => {\r
1274         if (trace === Trace.Off || !tracer) {\r
1275             return;\r
1276         }\r
1277         tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);\r
1278     });\r
1279     connection.onNotification(ProgressNotification.type, (params) => {\r
1280         const handler = progressHandlers.get(params.token);\r
1281         if (handler) {\r
1282             handler(params.value);\r
1283         }\r
1284         else {\r
1285             unhandledProgressEmitter.fire(params);\r
1286         }\r
1287     });\r
1288     return connection;\r
1289 }\r
1290 function isMessageReader(value) {\r
1291     return value.listen !== void 0 && value.read === void 0;\r
1292 }\r
1293 function isMessageWriter(value) {\r
1294     return value.write !== void 0 && value.end === void 0;\r
1295 }\r
1296 function createMessageConnection(input, output, logger, strategy) {\r
1297     if (!logger) {\r
1298         logger = exports.NullLogger;\r
1299     }\r
1300     let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);\r
1301     let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);\r
1302     return _createMessageConnection(reader, writer, logger, strategy);\r
1303 }\r
1304 exports.createMessageConnection = createMessageConnection;\r
1305
1306
1307 /***/ }),
1308 /* 5 */
1309 /***/ (function(module, exports, __webpack_require__) {
1310
1311 "use strict";
1312 /* --------------------------------------------------------------------------------------------\r
1313  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1314  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1315  * ------------------------------------------------------------------------------------------ */\r
1316 \r
1317 Object.defineProperty(exports, "__esModule", { value: true });\r
1318 function boolean(value) {\r
1319     return value === true || value === false;\r
1320 }\r
1321 exports.boolean = boolean;\r
1322 function string(value) {\r
1323     return typeof value === 'string' || value instanceof String;\r
1324 }\r
1325 exports.string = string;\r
1326 function number(value) {\r
1327     return typeof value === 'number' || value instanceof Number;\r
1328 }\r
1329 exports.number = number;\r
1330 function error(value) {\r
1331     return value instanceof Error;\r
1332 }\r
1333 exports.error = error;\r
1334 function func(value) {\r
1335     return typeof value === 'function';\r
1336 }\r
1337 exports.func = func;\r
1338 function array(value) {\r
1339     return Array.isArray(value);\r
1340 }\r
1341 exports.array = array;\r
1342 function stringArray(value) {\r
1343     return array(value) && value.every(elem => string(elem));\r
1344 }\r
1345 exports.stringArray = stringArray;\r
1346
1347
1348 /***/ }),
1349 /* 6 */
1350 /***/ (function(module, exports, __webpack_require__) {
1351
1352 "use strict";
1353 /* --------------------------------------------------------------------------------------------\r
1354  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1355  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1356  * ------------------------------------------------------------------------------------------ */\r
1357 \r
1358 Object.defineProperty(exports, "__esModule", { value: true });\r
1359 const is = __webpack_require__(5);\r
1360 /**\r
1361  * Predefined error codes.\r
1362  */\r
1363 var ErrorCodes;\r
1364 (function (ErrorCodes) {\r
1365     // Defined by JSON RPC\r
1366     ErrorCodes.ParseError = -32700;\r
1367     ErrorCodes.InvalidRequest = -32600;\r
1368     ErrorCodes.MethodNotFound = -32601;\r
1369     ErrorCodes.InvalidParams = -32602;\r
1370     ErrorCodes.InternalError = -32603;\r
1371     ErrorCodes.serverErrorStart = -32099;\r
1372     ErrorCodes.serverErrorEnd = -32000;\r
1373     ErrorCodes.ServerNotInitialized = -32002;\r
1374     ErrorCodes.UnknownErrorCode = -32001;\r
1375     // Defined by the protocol.\r
1376     ErrorCodes.RequestCancelled = -32800;\r
1377     ErrorCodes.ContentModified = -32801;\r
1378     // Defined by VSCode library.\r
1379     ErrorCodes.MessageWriteError = 1;\r
1380     ErrorCodes.MessageReadError = 2;\r
1381 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));\r
1382 /**\r
1383  * An error object return in a response in case a request\r
1384  * has failed.\r
1385  */\r
1386 class ResponseError extends Error {\r
1387     constructor(code, message, data) {\r
1388         super(message);\r
1389         this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;\r
1390         this.data = data;\r
1391         Object.setPrototypeOf(this, ResponseError.prototype);\r
1392     }\r
1393     toJson() {\r
1394         return {\r
1395             code: this.code,\r
1396             message: this.message,\r
1397             data: this.data,\r
1398         };\r
1399     }\r
1400 }\r
1401 exports.ResponseError = ResponseError;\r
1402 /**\r
1403  * An abstract implementation of a MessageType.\r
1404  */\r
1405 class AbstractMessageType {\r
1406     constructor(_method, _numberOfParams) {\r
1407         this._method = _method;\r
1408         this._numberOfParams = _numberOfParams;\r
1409     }\r
1410     get method() {\r
1411         return this._method;\r
1412     }\r
1413     get numberOfParams() {\r
1414         return this._numberOfParams;\r
1415     }\r
1416 }\r
1417 exports.AbstractMessageType = AbstractMessageType;\r
1418 /**\r
1419  * Classes to type request response pairs\r
1420  *\r
1421  * The type parameter RO will be removed in the next major version\r
1422  * of the JSON RPC library since it is a LSP concept and doesn't\r
1423  * belong here. For now it is tagged as default never.\r
1424  */\r
1425 class RequestType0 extends AbstractMessageType {\r
1426     constructor(method) {\r
1427         super(method, 0);\r
1428     }\r
1429 }\r
1430 exports.RequestType0 = RequestType0;\r
1431 class RequestType extends AbstractMessageType {\r
1432     constructor(method) {\r
1433         super(method, 1);\r
1434     }\r
1435 }\r
1436 exports.RequestType = RequestType;\r
1437 class RequestType1 extends AbstractMessageType {\r
1438     constructor(method) {\r
1439         super(method, 1);\r
1440     }\r
1441 }\r
1442 exports.RequestType1 = RequestType1;\r
1443 class RequestType2 extends AbstractMessageType {\r
1444     constructor(method) {\r
1445         super(method, 2);\r
1446     }\r
1447 }\r
1448 exports.RequestType2 = RequestType2;\r
1449 class RequestType3 extends AbstractMessageType {\r
1450     constructor(method) {\r
1451         super(method, 3);\r
1452     }\r
1453 }\r
1454 exports.RequestType3 = RequestType3;\r
1455 class RequestType4 extends AbstractMessageType {\r
1456     constructor(method) {\r
1457         super(method, 4);\r
1458     }\r
1459 }\r
1460 exports.RequestType4 = RequestType4;\r
1461 class RequestType5 extends AbstractMessageType {\r
1462     constructor(method) {\r
1463         super(method, 5);\r
1464     }\r
1465 }\r
1466 exports.RequestType5 = RequestType5;\r
1467 class RequestType6 extends AbstractMessageType {\r
1468     constructor(method) {\r
1469         super(method, 6);\r
1470     }\r
1471 }\r
1472 exports.RequestType6 = RequestType6;\r
1473 class RequestType7 extends AbstractMessageType {\r
1474     constructor(method) {\r
1475         super(method, 7);\r
1476     }\r
1477 }\r
1478 exports.RequestType7 = RequestType7;\r
1479 class RequestType8 extends AbstractMessageType {\r
1480     constructor(method) {\r
1481         super(method, 8);\r
1482     }\r
1483 }\r
1484 exports.RequestType8 = RequestType8;\r
1485 class RequestType9 extends AbstractMessageType {\r
1486     constructor(method) {\r
1487         super(method, 9);\r
1488     }\r
1489 }\r
1490 exports.RequestType9 = RequestType9;\r
1491 /**\r
1492  * The type parameter RO will be removed in the next major version\r
1493  * of the JSON RPC library since it is a LSP concept and doesn't\r
1494  * belong here. For now it is tagged as default never.\r
1495  */\r
1496 class NotificationType extends AbstractMessageType {\r
1497     constructor(method) {\r
1498         super(method, 1);\r
1499         this._ = undefined;\r
1500     }\r
1501 }\r
1502 exports.NotificationType = NotificationType;\r
1503 class NotificationType0 extends AbstractMessageType {\r
1504     constructor(method) {\r
1505         super(method, 0);\r
1506     }\r
1507 }\r
1508 exports.NotificationType0 = NotificationType0;\r
1509 class NotificationType1 extends AbstractMessageType {\r
1510     constructor(method) {\r
1511         super(method, 1);\r
1512     }\r
1513 }\r
1514 exports.NotificationType1 = NotificationType1;\r
1515 class NotificationType2 extends AbstractMessageType {\r
1516     constructor(method) {\r
1517         super(method, 2);\r
1518     }\r
1519 }\r
1520 exports.NotificationType2 = NotificationType2;\r
1521 class NotificationType3 extends AbstractMessageType {\r
1522     constructor(method) {\r
1523         super(method, 3);\r
1524     }\r
1525 }\r
1526 exports.NotificationType3 = NotificationType3;\r
1527 class NotificationType4 extends AbstractMessageType {\r
1528     constructor(method) {\r
1529         super(method, 4);\r
1530     }\r
1531 }\r
1532 exports.NotificationType4 = NotificationType4;\r
1533 class NotificationType5 extends AbstractMessageType {\r
1534     constructor(method) {\r
1535         super(method, 5);\r
1536     }\r
1537 }\r
1538 exports.NotificationType5 = NotificationType5;\r
1539 class NotificationType6 extends AbstractMessageType {\r
1540     constructor(method) {\r
1541         super(method, 6);\r
1542     }\r
1543 }\r
1544 exports.NotificationType6 = NotificationType6;\r
1545 class NotificationType7 extends AbstractMessageType {\r
1546     constructor(method) {\r
1547         super(method, 7);\r
1548     }\r
1549 }\r
1550 exports.NotificationType7 = NotificationType7;\r
1551 class NotificationType8 extends AbstractMessageType {\r
1552     constructor(method) {\r
1553         super(method, 8);\r
1554     }\r
1555 }\r
1556 exports.NotificationType8 = NotificationType8;\r
1557 class NotificationType9 extends AbstractMessageType {\r
1558     constructor(method) {\r
1559         super(method, 9);\r
1560     }\r
1561 }\r
1562 exports.NotificationType9 = NotificationType9;\r
1563 /**\r
1564  * Tests if the given message is a request message\r
1565  */\r
1566 function isRequestMessage(message) {\r
1567     let candidate = message;\r
1568     return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));\r
1569 }\r
1570 exports.isRequestMessage = isRequestMessage;\r
1571 /**\r
1572  * Tests if the given message is a notification message\r
1573  */\r
1574 function isNotificationMessage(message) {\r
1575     let candidate = message;\r
1576     return candidate && is.string(candidate.method) && message.id === void 0;\r
1577 }\r
1578 exports.isNotificationMessage = isNotificationMessage;\r
1579 /**\r
1580  * Tests if the given message is a response message\r
1581  */\r
1582 function isResponseMessage(message) {\r
1583     let candidate = message;\r
1584     return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);\r
1585 }\r
1586 exports.isResponseMessage = isResponseMessage;\r
1587
1588
1589 /***/ }),
1590 /* 7 */
1591 /***/ (function(module, exports, __webpack_require__) {
1592
1593 "use strict";
1594 /* --------------------------------------------------------------------------------------------\r
1595  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1596  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1597  * ------------------------------------------------------------------------------------------ */\r
1598 \r
1599 Object.defineProperty(exports, "__esModule", { value: true });\r
1600 const events_1 = __webpack_require__(8);\r
1601 const Is = __webpack_require__(5);\r
1602 let DefaultSize = 8192;\r
1603 let CR = Buffer.from('\r', 'ascii')[0];\r
1604 let LF = Buffer.from('\n', 'ascii')[0];\r
1605 let CRLF = '\r\n';\r
1606 class MessageBuffer {\r
1607     constructor(encoding = 'utf8') {\r
1608         this.encoding = encoding;\r
1609         this.index = 0;\r
1610         this.buffer = Buffer.allocUnsafe(DefaultSize);\r
1611     }\r
1612     append(chunk) {\r
1613         var toAppend = chunk;\r
1614         if (typeof (chunk) === 'string') {\r
1615             var str = chunk;\r
1616             var bufferLen = Buffer.byteLength(str, this.encoding);\r
1617             toAppend = Buffer.allocUnsafe(bufferLen);\r
1618             toAppend.write(str, 0, bufferLen, this.encoding);\r
1619         }\r
1620         if (this.buffer.length - this.index >= toAppend.length) {\r
1621             toAppend.copy(this.buffer, this.index, 0, toAppend.length);\r
1622         }\r
1623         else {\r
1624             var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;\r
1625             if (this.index === 0) {\r
1626                 this.buffer = Buffer.allocUnsafe(newSize);\r
1627                 toAppend.copy(this.buffer, 0, 0, toAppend.length);\r
1628             }\r
1629             else {\r
1630                 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);\r
1631             }\r
1632         }\r
1633         this.index += toAppend.length;\r
1634     }\r
1635     tryReadHeaders() {\r
1636         let result = undefined;\r
1637         let current = 0;\r
1638         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
1639             current++;\r
1640         }\r
1641         // No header / body separator found (e.g CRLFCRLF)\r
1642         if (current + 3 >= this.index) {\r
1643             return result;\r
1644         }\r
1645         result = Object.create(null);\r
1646         let headers = this.buffer.toString('ascii', 0, current).split(CRLF);\r
1647         headers.forEach((header) => {\r
1648             let index = header.indexOf(':');\r
1649             if (index === -1) {\r
1650                 throw new Error('Message header must separate key and value using :');\r
1651             }\r
1652             let key = header.substr(0, index);\r
1653             let value = header.substr(index + 1).trim();\r
1654             result[key] = value;\r
1655         });\r
1656         let nextStart = current + 4;\r
1657         this.buffer = this.buffer.slice(nextStart);\r
1658         this.index = this.index - nextStart;\r
1659         return result;\r
1660     }\r
1661     tryReadContent(length) {\r
1662         if (this.index < length) {\r
1663             return null;\r
1664         }\r
1665         let result = this.buffer.toString(this.encoding, 0, length);\r
1666         let nextStart = length;\r
1667         this.buffer.copy(this.buffer, 0, nextStart);\r
1668         this.index = this.index - nextStart;\r
1669         return result;\r
1670     }\r
1671     get numberOfBytes() {\r
1672         return this.index;\r
1673     }\r
1674 }\r
1675 var MessageReader;\r
1676 (function (MessageReader) {\r
1677     function is(value) {\r
1678         let candidate = value;\r
1679         return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&\r
1680             Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);\r
1681     }\r
1682     MessageReader.is = is;\r
1683 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));\r
1684 class AbstractMessageReader {\r
1685     constructor() {\r
1686         this.errorEmitter = new events_1.Emitter();\r
1687         this.closeEmitter = new events_1.Emitter();\r
1688         this.partialMessageEmitter = new events_1.Emitter();\r
1689     }\r
1690     dispose() {\r
1691         this.errorEmitter.dispose();\r
1692         this.closeEmitter.dispose();\r
1693     }\r
1694     get onError() {\r
1695         return this.errorEmitter.event;\r
1696     }\r
1697     fireError(error) {\r
1698         this.errorEmitter.fire(this.asError(error));\r
1699     }\r
1700     get onClose() {\r
1701         return this.closeEmitter.event;\r
1702     }\r
1703     fireClose() {\r
1704         this.closeEmitter.fire(undefined);\r
1705     }\r
1706     get onPartialMessage() {\r
1707         return this.partialMessageEmitter.event;\r
1708     }\r
1709     firePartialMessage(info) {\r
1710         this.partialMessageEmitter.fire(info);\r
1711     }\r
1712     asError(error) {\r
1713         if (error instanceof Error) {\r
1714             return error;\r
1715         }\r
1716         else {\r
1717             return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
1718         }\r
1719     }\r
1720 }\r
1721 exports.AbstractMessageReader = AbstractMessageReader;\r
1722 class StreamMessageReader extends AbstractMessageReader {\r
1723     constructor(readable, encoding = 'utf8') {\r
1724         super();\r
1725         this.readable = readable;\r
1726         this.buffer = new MessageBuffer(encoding);\r
1727         this._partialMessageTimeout = 10000;\r
1728     }\r
1729     set partialMessageTimeout(timeout) {\r
1730         this._partialMessageTimeout = timeout;\r
1731     }\r
1732     get partialMessageTimeout() {\r
1733         return this._partialMessageTimeout;\r
1734     }\r
1735     listen(callback) {\r
1736         this.nextMessageLength = -1;\r
1737         this.messageToken = 0;\r
1738         this.partialMessageTimer = undefined;\r
1739         this.callback = callback;\r
1740         this.readable.on('data', (data) => {\r
1741             this.onData(data);\r
1742         });\r
1743         this.readable.on('error', (error) => this.fireError(error));\r
1744         this.readable.on('close', () => this.fireClose());\r
1745     }\r
1746     onData(data) {\r
1747         this.buffer.append(data);\r
1748         while (true) {\r
1749             if (this.nextMessageLength === -1) {\r
1750                 let headers = this.buffer.tryReadHeaders();\r
1751                 if (!headers) {\r
1752                     return;\r
1753                 }\r
1754                 let contentLength = headers['Content-Length'];\r
1755                 if (!contentLength) {\r
1756                     throw new Error('Header must provide a Content-Length property.');\r
1757                 }\r
1758                 let length = parseInt(contentLength);\r
1759                 if (isNaN(length)) {\r
1760                     throw new Error('Content-Length value must be a number.');\r
1761                 }\r
1762                 this.nextMessageLength = length;\r
1763                 // Take the encoding form the header. For compatibility\r
1764                 // treat both utf-8 and utf8 as node utf8\r
1765             }\r
1766             var msg = this.buffer.tryReadContent(this.nextMessageLength);\r
1767             if (msg === null) {\r
1768                 /** We haven't received the full message yet. */\r
1769                 this.setPartialMessageTimer();\r
1770                 return;\r
1771             }\r
1772             this.clearPartialMessageTimer();\r
1773             this.nextMessageLength = -1;\r
1774             this.messageToken++;\r
1775             var json = JSON.parse(msg);\r
1776             this.callback(json);\r
1777         }\r
1778     }\r
1779     clearPartialMessageTimer() {\r
1780         if (this.partialMessageTimer) {\r
1781             clearTimeout(this.partialMessageTimer);\r
1782             this.partialMessageTimer = undefined;\r
1783         }\r
1784     }\r
1785     setPartialMessageTimer() {\r
1786         this.clearPartialMessageTimer();\r
1787         if (this._partialMessageTimeout <= 0) {\r
1788             return;\r
1789         }\r
1790         this.partialMessageTimer = setTimeout((token, timeout) => {\r
1791             this.partialMessageTimer = undefined;\r
1792             if (token === this.messageToken) {\r
1793                 this.firePartialMessage({ messageToken: token, waitingTime: timeout });\r
1794                 this.setPartialMessageTimer();\r
1795             }\r
1796         }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);\r
1797     }\r
1798 }\r
1799 exports.StreamMessageReader = StreamMessageReader;\r
1800 class IPCMessageReader extends AbstractMessageReader {\r
1801     constructor(process) {\r
1802         super();\r
1803         this.process = process;\r
1804         let eventEmitter = this.process;\r
1805         eventEmitter.on('error', (error) => this.fireError(error));\r
1806         eventEmitter.on('close', () => this.fireClose());\r
1807     }\r
1808     listen(callback) {\r
1809         this.process.on('message', callback);\r
1810     }\r
1811 }\r
1812 exports.IPCMessageReader = IPCMessageReader;\r
1813 class SocketMessageReader extends StreamMessageReader {\r
1814     constructor(socket, encoding = 'utf-8') {\r
1815         super(socket, encoding);\r
1816     }\r
1817 }\r
1818 exports.SocketMessageReader = SocketMessageReader;\r
1819
1820
1821 /***/ }),
1822 /* 8 */
1823 /***/ (function(module, exports, __webpack_require__) {
1824
1825 "use strict";
1826 /* --------------------------------------------------------------------------------------------\r
1827  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1828  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1829  * ------------------------------------------------------------------------------------------ */\r
1830 \r
1831 Object.defineProperty(exports, "__esModule", { value: true });\r
1832 var Disposable;\r
1833 (function (Disposable) {\r
1834     function create(func) {\r
1835         return {\r
1836             dispose: func\r
1837         };\r
1838     }\r
1839     Disposable.create = create;\r
1840 })(Disposable = exports.Disposable || (exports.Disposable = {}));\r
1841 var Event;\r
1842 (function (Event) {\r
1843     const _disposable = { dispose() { } };\r
1844     Event.None = function () { return _disposable; };\r
1845 })(Event = exports.Event || (exports.Event = {}));\r
1846 class CallbackList {\r
1847     add(callback, context = null, bucket) {\r
1848         if (!this._callbacks) {\r
1849             this._callbacks = [];\r
1850             this._contexts = [];\r
1851         }\r
1852         this._callbacks.push(callback);\r
1853         this._contexts.push(context);\r
1854         if (Array.isArray(bucket)) {\r
1855             bucket.push({ dispose: () => this.remove(callback, context) });\r
1856         }\r
1857     }\r
1858     remove(callback, context = null) {\r
1859         if (!this._callbacks) {\r
1860             return;\r
1861         }\r
1862         var foundCallbackWithDifferentContext = false;\r
1863         for (var i = 0, len = this._callbacks.length; i < len; i++) {\r
1864             if (this._callbacks[i] === callback) {\r
1865                 if (this._contexts[i] === context) {\r
1866                     // callback & context match => remove it\r
1867                     this._callbacks.splice(i, 1);\r
1868                     this._contexts.splice(i, 1);\r
1869                     return;\r
1870                 }\r
1871                 else {\r
1872                     foundCallbackWithDifferentContext = true;\r
1873                 }\r
1874             }\r
1875         }\r
1876         if (foundCallbackWithDifferentContext) {\r
1877             throw new Error('When adding a listener with a context, you should remove it with the same context');\r
1878         }\r
1879     }\r
1880     invoke(...args) {\r
1881         if (!this._callbacks) {\r
1882             return [];\r
1883         }\r
1884         var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);\r
1885         for (var i = 0, len = callbacks.length; i < len; i++) {\r
1886             try {\r
1887                 ret.push(callbacks[i].apply(contexts[i], args));\r
1888             }\r
1889             catch (e) {\r
1890                 // eslint-disable-next-line no-console\r
1891                 console.error(e);\r
1892             }\r
1893         }\r
1894         return ret;\r
1895     }\r
1896     isEmpty() {\r
1897         return !this._callbacks || this._callbacks.length === 0;\r
1898     }\r
1899     dispose() {\r
1900         this._callbacks = undefined;\r
1901         this._contexts = undefined;\r
1902     }\r
1903 }\r
1904 class Emitter {\r
1905     constructor(_options) {\r
1906         this._options = _options;\r
1907     }\r
1908     /**\r
1909      * For the public to allow to subscribe\r
1910      * to events from this Emitter\r
1911      */\r
1912     get event() {\r
1913         if (!this._event) {\r
1914             this._event = (listener, thisArgs, disposables) => {\r
1915                 if (!this._callbacks) {\r
1916                     this._callbacks = new CallbackList();\r
1917                 }\r
1918                 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {\r
1919                     this._options.onFirstListenerAdd(this);\r
1920                 }\r
1921                 this._callbacks.add(listener, thisArgs);\r
1922                 let result;\r
1923                 result = {\r
1924                     dispose: () => {\r
1925                         this._callbacks.remove(listener, thisArgs);\r
1926                         result.dispose = Emitter._noop;\r
1927                         if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {\r
1928                             this._options.onLastListenerRemove(this);\r
1929                         }\r
1930                     }\r
1931                 };\r
1932                 if (Array.isArray(disposables)) {\r
1933                     disposables.push(result);\r
1934                 }\r
1935                 return result;\r
1936             };\r
1937         }\r
1938         return this._event;\r
1939     }\r
1940     /**\r
1941      * To be kept private to fire an event to\r
1942      * subscribers\r
1943      */\r
1944     fire(event) {\r
1945         if (this._callbacks) {\r
1946             this._callbacks.invoke.call(this._callbacks, event);\r
1947         }\r
1948     }\r
1949     dispose() {\r
1950         if (this._callbacks) {\r
1951             this._callbacks.dispose();\r
1952             this._callbacks = undefined;\r
1953         }\r
1954     }\r
1955 }\r
1956 exports.Emitter = Emitter;\r
1957 Emitter._noop = function () { };\r
1958
1959
1960 /***/ }),
1961 /* 9 */
1962 /***/ (function(module, exports, __webpack_require__) {
1963
1964 "use strict";
1965 /* --------------------------------------------------------------------------------------------\r
1966  * Copyright (c) Microsoft Corporation. All rights reserved.\r
1967  * Licensed under the MIT License. See License.txt in the project root for license information.\r
1968  * ------------------------------------------------------------------------------------------ */\r
1969 \r
1970 Object.defineProperty(exports, "__esModule", { value: true });\r
1971 const events_1 = __webpack_require__(8);\r
1972 const Is = __webpack_require__(5);\r
1973 let ContentLength = 'Content-Length: ';\r
1974 let CRLF = '\r\n';\r
1975 var MessageWriter;\r
1976 (function (MessageWriter) {\r
1977     function is(value) {\r
1978         let candidate = value;\r
1979         return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&\r
1980             Is.func(candidate.onError) && Is.func(candidate.write);\r
1981     }\r
1982     MessageWriter.is = is;\r
1983 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));\r
1984 class AbstractMessageWriter {\r
1985     constructor() {\r
1986         this.errorEmitter = new events_1.Emitter();\r
1987         this.closeEmitter = new events_1.Emitter();\r
1988     }\r
1989     dispose() {\r
1990         this.errorEmitter.dispose();\r
1991         this.closeEmitter.dispose();\r
1992     }\r
1993     get onError() {\r
1994         return this.errorEmitter.event;\r
1995     }\r
1996     fireError(error, message, count) {\r
1997         this.errorEmitter.fire([this.asError(error), message, count]);\r
1998     }\r
1999     get onClose() {\r
2000         return this.closeEmitter.event;\r
2001     }\r
2002     fireClose() {\r
2003         this.closeEmitter.fire(undefined);\r
2004     }\r
2005     asError(error) {\r
2006         if (error instanceof Error) {\r
2007             return error;\r
2008         }\r
2009         else {\r
2010             return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);\r
2011         }\r
2012     }\r
2013 }\r
2014 exports.AbstractMessageWriter = AbstractMessageWriter;\r
2015 class StreamMessageWriter extends AbstractMessageWriter {\r
2016     constructor(writable, encoding = 'utf8') {\r
2017         super();\r
2018         this.writable = writable;\r
2019         this.encoding = encoding;\r
2020         this.errorCount = 0;\r
2021         this.writable.on('error', (error) => this.fireError(error));\r
2022         this.writable.on('close', () => this.fireClose());\r
2023     }\r
2024     write(msg) {\r
2025         let json = JSON.stringify(msg);\r
2026         let contentLength = Buffer.byteLength(json, this.encoding);\r
2027         let headers = [\r
2028             ContentLength, contentLength.toString(), CRLF,\r
2029             CRLF\r
2030         ];\r
2031         try {\r
2032             // Header must be written in ASCII encoding\r
2033             this.writable.write(headers.join(''), 'ascii');\r
2034             // Now write the content. This can be written in any encoding\r
2035             this.writable.write(json, this.encoding);\r
2036             this.errorCount = 0;\r
2037         }\r
2038         catch (error) {\r
2039             this.errorCount++;\r
2040             this.fireError(error, msg, this.errorCount);\r
2041         }\r
2042     }\r
2043 }\r
2044 exports.StreamMessageWriter = StreamMessageWriter;\r
2045 class IPCMessageWriter extends AbstractMessageWriter {\r
2046     constructor(process) {\r
2047         super();\r
2048         this.process = process;\r
2049         this.errorCount = 0;\r
2050         this.queue = [];\r
2051         this.sending = false;\r
2052         let eventEmitter = this.process;\r
2053         eventEmitter.on('error', (error) => this.fireError(error));\r
2054         eventEmitter.on('close', () => this.fireClose);\r
2055     }\r
2056     write(msg) {\r
2057         if (!this.sending && this.queue.length === 0) {\r
2058             // See https://github.com/nodejs/node/issues/7657\r
2059             this.doWriteMessage(msg);\r
2060         }\r
2061         else {\r
2062             this.queue.push(msg);\r
2063         }\r
2064     }\r
2065     doWriteMessage(msg) {\r
2066         try {\r
2067             if (this.process.send) {\r
2068                 this.sending = true;\r
2069                 this.process.send(msg, undefined, undefined, (error) => {\r
2070                     this.sending = false;\r
2071                     if (error) {\r
2072                         this.errorCount++;\r
2073                         this.fireError(error, msg, this.errorCount);\r
2074                     }\r
2075                     else {\r
2076                         this.errorCount = 0;\r
2077                     }\r
2078                     if (this.queue.length > 0) {\r
2079                         this.doWriteMessage(this.queue.shift());\r
2080                     }\r
2081                 });\r
2082             }\r
2083         }\r
2084         catch (error) {\r
2085             this.errorCount++;\r
2086             this.fireError(error, msg, this.errorCount);\r
2087         }\r
2088     }\r
2089 }\r
2090 exports.IPCMessageWriter = IPCMessageWriter;\r
2091 class SocketMessageWriter extends AbstractMessageWriter {\r
2092     constructor(socket, encoding = 'utf8') {\r
2093         super();\r
2094         this.socket = socket;\r
2095         this.queue = [];\r
2096         this.sending = false;\r
2097         this.encoding = encoding;\r
2098         this.errorCount = 0;\r
2099         this.socket.on('error', (error) => this.fireError(error));\r
2100         this.socket.on('close', () => this.fireClose());\r
2101     }\r
2102     dispose() {\r
2103         super.dispose();\r
2104         this.socket.destroy();\r
2105     }\r
2106     write(msg) {\r
2107         if (!this.sending && this.queue.length === 0) {\r
2108             // See https://github.com/nodejs/node/issues/7657\r
2109             this.doWriteMessage(msg);\r
2110         }\r
2111         else {\r
2112             this.queue.push(msg);\r
2113         }\r
2114     }\r
2115     doWriteMessage(msg) {\r
2116         let json = JSON.stringify(msg);\r
2117         let contentLength = Buffer.byteLength(json, this.encoding);\r
2118         let headers = [\r
2119             ContentLength, contentLength.toString(), CRLF,\r
2120             CRLF\r
2121         ];\r
2122         try {\r
2123             // Header must be written in ASCII encoding\r
2124             this.sending = true;\r
2125             this.socket.write(headers.join(''), 'ascii', (error) => {\r
2126                 if (error) {\r
2127                     this.handleError(error, msg);\r
2128                 }\r
2129                 try {\r
2130                     // Now write the content. This can be written in any encoding\r
2131                     this.socket.write(json, this.encoding, (error) => {\r
2132                         this.sending = false;\r
2133                         if (error) {\r
2134                             this.handleError(error, msg);\r
2135                         }\r
2136                         else {\r
2137                             this.errorCount = 0;\r
2138                         }\r
2139                         if (this.queue.length > 0) {\r
2140                             this.doWriteMessage(this.queue.shift());\r
2141                         }\r
2142                     });\r
2143                 }\r
2144                 catch (error) {\r
2145                     this.handleError(error, msg);\r
2146                 }\r
2147             });\r
2148         }\r
2149         catch (error) {\r
2150             this.handleError(error, msg);\r
2151         }\r
2152     }\r
2153     handleError(error, msg) {\r
2154         this.errorCount++;\r
2155         this.fireError(error, msg, this.errorCount);\r
2156     }\r
2157 }\r
2158 exports.SocketMessageWriter = SocketMessageWriter;\r
2159
2160
2161 /***/ }),
2162 /* 10 */
2163 /***/ (function(module, exports, __webpack_require__) {
2164
2165 "use strict";
2166 /*---------------------------------------------------------------------------------------------\r
2167  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
2168  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
2169  *--------------------------------------------------------------------------------------------*/\r
2170 \r
2171 Object.defineProperty(exports, "__esModule", { value: true });\r
2172 const events_1 = __webpack_require__(8);\r
2173 const Is = __webpack_require__(5);\r
2174 var CancellationToken;\r
2175 (function (CancellationToken) {\r
2176     CancellationToken.None = Object.freeze({\r
2177         isCancellationRequested: false,\r
2178         onCancellationRequested: events_1.Event.None\r
2179     });\r
2180     CancellationToken.Cancelled = Object.freeze({\r
2181         isCancellationRequested: true,\r
2182         onCancellationRequested: events_1.Event.None\r
2183     });\r
2184     function is(value) {\r
2185         let candidate = value;\r
2186         return candidate && (candidate === CancellationToken.None\r
2187             || candidate === CancellationToken.Cancelled\r
2188             || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));\r
2189     }\r
2190     CancellationToken.is = is;\r
2191 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));\r
2192 const shortcutEvent = Object.freeze(function (callback, context) {\r
2193     let handle = setTimeout(callback.bind(context), 0);\r
2194     return { dispose() { clearTimeout(handle); } };\r
2195 });\r
2196 class MutableToken {\r
2197     constructor() {\r
2198         this._isCancelled = false;\r
2199     }\r
2200     cancel() {\r
2201         if (!this._isCancelled) {\r
2202             this._isCancelled = true;\r
2203             if (this._emitter) {\r
2204                 this._emitter.fire(undefined);\r
2205                 this.dispose();\r
2206             }\r
2207         }\r
2208     }\r
2209     get isCancellationRequested() {\r
2210         return this._isCancelled;\r
2211     }\r
2212     get onCancellationRequested() {\r
2213         if (this._isCancelled) {\r
2214             return shortcutEvent;\r
2215         }\r
2216         if (!this._emitter) {\r
2217             this._emitter = new events_1.Emitter();\r
2218         }\r
2219         return this._emitter.event;\r
2220     }\r
2221     dispose() {\r
2222         if (this._emitter) {\r
2223             this._emitter.dispose();\r
2224             this._emitter = undefined;\r
2225         }\r
2226     }\r
2227 }\r
2228 class CancellationTokenSource {\r
2229     get token() {\r
2230         if (!this._token) {\r
2231             // be lazy and create the token only when\r
2232             // actually needed\r
2233             this._token = new MutableToken();\r
2234         }\r
2235         return this._token;\r
2236     }\r
2237     cancel() {\r
2238         if (!this._token) {\r
2239             // save an object by returning the default\r
2240             // cancelled token when cancellation happens\r
2241             // before someone asks for the token\r
2242             this._token = CancellationToken.Cancelled;\r
2243         }\r
2244         else {\r
2245             this._token.cancel();\r
2246         }\r
2247     }\r
2248     dispose() {\r
2249         if (!this._token) {\r
2250             // ensure to initialize with an empty token if we had none\r
2251             this._token = CancellationToken.None;\r
2252         }\r
2253         else if (this._token instanceof MutableToken) {\r
2254             // actually dispose\r
2255             this._token.dispose();\r
2256         }\r
2257     }\r
2258 }\r
2259 exports.CancellationTokenSource = CancellationTokenSource;\r
2260
2261
2262 /***/ }),
2263 /* 11 */
2264 /***/ (function(module, exports, __webpack_require__) {
2265
2266 "use strict";
2267 \r
2268 /*---------------------------------------------------------------------------------------------\r
2269  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
2270  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
2271  *--------------------------------------------------------------------------------------------*/\r
2272 Object.defineProperty(exports, "__esModule", { value: true });\r
2273 var Touch;\r
2274 (function (Touch) {\r
2275     Touch.None = 0;\r
2276     Touch.First = 1;\r
2277     Touch.Last = 2;\r
2278 })(Touch = exports.Touch || (exports.Touch = {}));\r
2279 class LinkedMap {\r
2280     constructor() {\r
2281         this._map = new Map();\r
2282         this._head = undefined;\r
2283         this._tail = undefined;\r
2284         this._size = 0;\r
2285     }\r
2286     clear() {\r
2287         this._map.clear();\r
2288         this._head = undefined;\r
2289         this._tail = undefined;\r
2290         this._size = 0;\r
2291     }\r
2292     isEmpty() {\r
2293         return !this._head && !this._tail;\r
2294     }\r
2295     get size() {\r
2296         return this._size;\r
2297     }\r
2298     has(key) {\r
2299         return this._map.has(key);\r
2300     }\r
2301     get(key) {\r
2302         const item = this._map.get(key);\r
2303         if (!item) {\r
2304             return undefined;\r
2305         }\r
2306         return item.value;\r
2307     }\r
2308     set(key, value, touch = Touch.None) {\r
2309         let item = this._map.get(key);\r
2310         if (item) {\r
2311             item.value = value;\r
2312             if (touch !== Touch.None) {\r
2313                 this.touch(item, touch);\r
2314             }\r
2315         }\r
2316         else {\r
2317             item = { key, value, next: undefined, previous: undefined };\r
2318             switch (touch) {\r
2319                 case Touch.None:\r
2320                     this.addItemLast(item);\r
2321                     break;\r
2322                 case Touch.First:\r
2323                     this.addItemFirst(item);\r
2324                     break;\r
2325                 case Touch.Last:\r
2326                     this.addItemLast(item);\r
2327                     break;\r
2328                 default:\r
2329                     this.addItemLast(item);\r
2330                     break;\r
2331             }\r
2332             this._map.set(key, item);\r
2333             this._size++;\r
2334         }\r
2335     }\r
2336     delete(key) {\r
2337         const item = this._map.get(key);\r
2338         if (!item) {\r
2339             return false;\r
2340         }\r
2341         this._map.delete(key);\r
2342         this.removeItem(item);\r
2343         this._size--;\r
2344         return true;\r
2345     }\r
2346     shift() {\r
2347         if (!this._head && !this._tail) {\r
2348             return undefined;\r
2349         }\r
2350         if (!this._head || !this._tail) {\r
2351             throw new Error('Invalid list');\r
2352         }\r
2353         const item = this._head;\r
2354         this._map.delete(item.key);\r
2355         this.removeItem(item);\r
2356         this._size--;\r
2357         return item.value;\r
2358     }\r
2359     forEach(callbackfn, thisArg) {\r
2360         let current = this._head;\r
2361         while (current) {\r
2362             if (thisArg) {\r
2363                 callbackfn.bind(thisArg)(current.value, current.key, this);\r
2364             }\r
2365             else {\r
2366                 callbackfn(current.value, current.key, this);\r
2367             }\r
2368             current = current.next;\r
2369         }\r
2370     }\r
2371     forEachReverse(callbackfn, thisArg) {\r
2372         let current = this._tail;\r
2373         while (current) {\r
2374             if (thisArg) {\r
2375                 callbackfn.bind(thisArg)(current.value, current.key, this);\r
2376             }\r
2377             else {\r
2378                 callbackfn(current.value, current.key, this);\r
2379             }\r
2380             current = current.previous;\r
2381         }\r
2382     }\r
2383     values() {\r
2384         let result = [];\r
2385         let current = this._head;\r
2386         while (current) {\r
2387             result.push(current.value);\r
2388             current = current.next;\r
2389         }\r
2390         return result;\r
2391     }\r
2392     keys() {\r
2393         let result = [];\r
2394         let current = this._head;\r
2395         while (current) {\r
2396             result.push(current.key);\r
2397             current = current.next;\r
2398         }\r
2399         return result;\r
2400     }\r
2401     /* JSON RPC run on es5 which has no Symbol.iterator\r
2402     public keys(): IterableIterator<K> {\r
2403         let current = this._head;\r
2404         let iterator: IterableIterator<K> = {\r
2405             [Symbol.iterator]() {\r
2406                 return iterator;\r
2407             },\r
2408             next():IteratorResult<K> {\r
2409                 if (current) {\r
2410                     let result = { value: current.key, done: false };\r
2411                     current = current.next;\r
2412                     return result;\r
2413                 } else {\r
2414                     return { value: undefined, done: true };\r
2415                 }\r
2416             }\r
2417         };\r
2418         return iterator;\r
2419     }\r
2420 \r
2421     public values(): IterableIterator<V> {\r
2422         let current = this._head;\r
2423         let iterator: IterableIterator<V> = {\r
2424             [Symbol.iterator]() {\r
2425                 return iterator;\r
2426             },\r
2427             next():IteratorResult<V> {\r
2428                 if (current) {\r
2429                     let result = { value: current.value, done: false };\r
2430                     current = current.next;\r
2431                     return result;\r
2432                 } else {\r
2433                     return { value: undefined, done: true };\r
2434                 }\r
2435             }\r
2436         };\r
2437         return iterator;\r
2438     }\r
2439     */\r
2440     addItemFirst(item) {\r
2441         // First time Insert\r
2442         if (!this._head && !this._tail) {\r
2443             this._tail = item;\r
2444         }\r
2445         else if (!this._head) {\r
2446             throw new Error('Invalid list');\r
2447         }\r
2448         else {\r
2449             item.next = this._head;\r
2450             this._head.previous = item;\r
2451         }\r
2452         this._head = item;\r
2453     }\r
2454     addItemLast(item) {\r
2455         // First time Insert\r
2456         if (!this._head && !this._tail) {\r
2457             this._head = item;\r
2458         }\r
2459         else if (!this._tail) {\r
2460             throw new Error('Invalid list');\r
2461         }\r
2462         else {\r
2463             item.previous = this._tail;\r
2464             this._tail.next = item;\r
2465         }\r
2466         this._tail = item;\r
2467     }\r
2468     removeItem(item) {\r
2469         if (item === this._head && item === this._tail) {\r
2470             this._head = undefined;\r
2471             this._tail = undefined;\r
2472         }\r
2473         else if (item === this._head) {\r
2474             this._head = item.next;\r
2475         }\r
2476         else if (item === this._tail) {\r
2477             this._tail = item.previous;\r
2478         }\r
2479         else {\r
2480             const next = item.next;\r
2481             const previous = item.previous;\r
2482             if (!next || !previous) {\r
2483                 throw new Error('Invalid list');\r
2484             }\r
2485             next.previous = previous;\r
2486             previous.next = next;\r
2487         }\r
2488     }\r
2489     touch(item, touch) {\r
2490         if (!this._head || !this._tail) {\r
2491             throw new Error('Invalid list');\r
2492         }\r
2493         if ((touch !== Touch.First && touch !== Touch.Last)) {\r
2494             return;\r
2495         }\r
2496         if (touch === Touch.First) {\r
2497             if (item === this._head) {\r
2498                 return;\r
2499             }\r
2500             const next = item.next;\r
2501             const previous = item.previous;\r
2502             // Unlink the item\r
2503             if (item === this._tail) {\r
2504                 // previous must be defined since item was not head but is tail\r
2505                 // So there are more than on item in the map\r
2506                 previous.next = undefined;\r
2507                 this._tail = previous;\r
2508             }\r
2509             else {\r
2510                 // Both next and previous are not undefined since item was neither head nor tail.\r
2511                 next.previous = previous;\r
2512                 previous.next = next;\r
2513             }\r
2514             // Insert the node at head\r
2515             item.previous = undefined;\r
2516             item.next = this._head;\r
2517             this._head.previous = item;\r
2518             this._head = item;\r
2519         }\r
2520         else if (touch === Touch.Last) {\r
2521             if (item === this._tail) {\r
2522                 return;\r
2523             }\r
2524             const next = item.next;\r
2525             const previous = item.previous;\r
2526             // Unlink the item.\r
2527             if (item === this._head) {\r
2528                 // next must be defined since item was not tail but is head\r
2529                 // So there are more than on item in the map\r
2530                 next.previous = undefined;\r
2531                 this._head = next;\r
2532             }\r
2533             else {\r
2534                 // Both next and previous are not undefined since item was neither head nor tail.\r
2535                 next.previous = previous;\r
2536                 previous.next = next;\r
2537             }\r
2538             item.next = undefined;\r
2539             item.previous = this._tail;\r
2540             this._tail.next = item;\r
2541             this._tail = item;\r
2542         }\r
2543     }\r
2544 }\r
2545 exports.LinkedMap = LinkedMap;\r
2546
2547
2548 /***/ }),
2549 /* 12 */
2550 /***/ (function(module, exports, __webpack_require__) {
2551
2552 "use strict";
2553 /* --------------------------------------------------------------------------------------------\r
2554  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2555  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2556  * ------------------------------------------------------------------------------------------ */\r
2557 \r
2558 Object.defineProperty(exports, "__esModule", { value: true });\r
2559 const path_1 = __webpack_require__(13);\r
2560 const os_1 = __webpack_require__(14);\r
2561 const crypto_1 = __webpack_require__(15);\r
2562 const net_1 = __webpack_require__(16);\r
2563 const messageReader_1 = __webpack_require__(7);\r
2564 const messageWriter_1 = __webpack_require__(9);\r
2565 function generateRandomPipeName() {\r
2566     const randomSuffix = crypto_1.randomBytes(21).toString('hex');\r
2567     if (process.platform === 'win32') {\r
2568         return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;\r
2569     }\r
2570     else {\r
2571         // Mac/Unix: use socket file\r
2572         return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);\r
2573     }\r
2574 }\r
2575 exports.generateRandomPipeName = generateRandomPipeName;\r
2576 function createClientPipeTransport(pipeName, encoding = 'utf-8') {\r
2577     let connectResolve;\r
2578     let connected = new Promise((resolve, _reject) => {\r
2579         connectResolve = resolve;\r
2580     });\r
2581     return new Promise((resolve, reject) => {\r
2582         let server = net_1.createServer((socket) => {\r
2583             server.close();\r
2584             connectResolve([\r
2585                 new messageReader_1.SocketMessageReader(socket, encoding),\r
2586                 new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2587             ]);\r
2588         });\r
2589         server.on('error', reject);\r
2590         server.listen(pipeName, () => {\r
2591             server.removeListener('error', reject);\r
2592             resolve({\r
2593                 onConnected: () => { return connected; }\r
2594             });\r
2595         });\r
2596     });\r
2597 }\r
2598 exports.createClientPipeTransport = createClientPipeTransport;\r
2599 function createServerPipeTransport(pipeName, encoding = 'utf-8') {\r
2600     const socket = net_1.createConnection(pipeName);\r
2601     return [\r
2602         new messageReader_1.SocketMessageReader(socket, encoding),\r
2603         new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2604     ];\r
2605 }\r
2606 exports.createServerPipeTransport = createServerPipeTransport;\r
2607
2608
2609 /***/ }),
2610 /* 13 */
2611 /***/ (function(module, exports) {
2612
2613 module.exports = require("path");
2614
2615 /***/ }),
2616 /* 14 */
2617 /***/ (function(module, exports) {
2618
2619 module.exports = require("os");
2620
2621 /***/ }),
2622 /* 15 */
2623 /***/ (function(module, exports) {
2624
2625 module.exports = require("crypto");
2626
2627 /***/ }),
2628 /* 16 */
2629 /***/ (function(module, exports) {
2630
2631 module.exports = require("net");
2632
2633 /***/ }),
2634 /* 17 */
2635 /***/ (function(module, exports, __webpack_require__) {
2636
2637 "use strict";
2638 /* --------------------------------------------------------------------------------------------\r
2639  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2640  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2641  * ------------------------------------------------------------------------------------------ */\r
2642 \r
2643 Object.defineProperty(exports, "__esModule", { value: true });\r
2644 const net_1 = __webpack_require__(16);\r
2645 const messageReader_1 = __webpack_require__(7);\r
2646 const messageWriter_1 = __webpack_require__(9);\r
2647 function createClientSocketTransport(port, encoding = 'utf-8') {\r
2648     let connectResolve;\r
2649     let connected = new Promise((resolve, _reject) => {\r
2650         connectResolve = resolve;\r
2651     });\r
2652     return new Promise((resolve, reject) => {\r
2653         let server = net_1.createServer((socket) => {\r
2654             server.close();\r
2655             connectResolve([\r
2656                 new messageReader_1.SocketMessageReader(socket, encoding),\r
2657                 new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2658             ]);\r
2659         });\r
2660         server.on('error', reject);\r
2661         server.listen(port, '127.0.0.1', () => {\r
2662             server.removeListener('error', reject);\r
2663             resolve({\r
2664                 onConnected: () => { return connected; }\r
2665             });\r
2666         });\r
2667     });\r
2668 }\r
2669 exports.createClientSocketTransport = createClientSocketTransport;\r
2670 function createServerSocketTransport(port, encoding = 'utf-8') {\r
2671     const socket = net_1.createConnection(port, '127.0.0.1');\r
2672     return [\r
2673         new messageReader_1.SocketMessageReader(socket, encoding),\r
2674         new messageWriter_1.SocketMessageWriter(socket, encoding)\r
2675     ];\r
2676 }\r
2677 exports.createServerSocketTransport = createServerSocketTransport;\r
2678
2679
2680 /***/ }),
2681 /* 18 */
2682 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2683
2684 "use strict";
2685 __webpack_require__.r(__webpack_exports__);
2686 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2687 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2688 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2689 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2690 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2691 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2692 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2693 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2694 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2695 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2696 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2697 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2698 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2699 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2700 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2701 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2702 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2703 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2704 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2705 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2706 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2707 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2708 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2709 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2710 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2711 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2712 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2713 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2714 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
2715 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2716 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2717 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2718 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2719 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2720 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2721 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2722 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2723 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2724 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
2725 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2726 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2727 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2728 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2729 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2730 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2731 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2732 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2733 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
2734 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2735 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2736 /* --------------------------------------------------------------------------------------------\r
2737  * Copyright (c) Microsoft Corporation. All rights reserved.\r
2738  * Licensed under the MIT License. See License.txt in the project root for license information.\r
2739  * ------------------------------------------------------------------------------------------ */\r
2740 \r
2741 /**\r
2742  * The Position namespace provides helper functions to work with\r
2743  * [Position](#Position) literals.\r
2744  */\r
2745 var Position;\r
2746 (function (Position) {\r
2747     /**\r
2748      * Creates a new Position literal from the given line and character.\r
2749      * @param line The position's line.\r
2750      * @param character The position's character.\r
2751      */\r
2752     function create(line, character) {\r
2753         return { line: line, character: character };\r
2754     }\r
2755     Position.create = create;\r
2756     /**\r
2757      * Checks whether the given liternal conforms to the [Position](#Position) interface.\r
2758      */\r
2759     function is(value) {\r
2760         var candidate = value;\r
2761         return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);\r
2762     }\r
2763     Position.is = is;\r
2764 })(Position || (Position = {}));\r
2765 /**\r
2766  * The Range namespace provides helper functions to work with\r
2767  * [Range](#Range) literals.\r
2768  */\r
2769 var Range;\r
2770 (function (Range) {\r
2771     function create(one, two, three, four) {\r
2772         if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {\r
2773             return { start: Position.create(one, two), end: Position.create(three, four) };\r
2774         }\r
2775         else if (Position.is(one) && Position.is(two)) {\r
2776             return { start: one, end: two };\r
2777         }\r
2778         else {\r
2779             throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");\r
2780         }\r
2781     }\r
2782     Range.create = create;\r
2783     /**\r
2784      * Checks whether the given literal conforms to the [Range](#Range) interface.\r
2785      */\r
2786     function is(value) {\r
2787         var candidate = value;\r
2788         return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);\r
2789     }\r
2790     Range.is = is;\r
2791 })(Range || (Range = {}));\r
2792 /**\r
2793  * The Location namespace provides helper functions to work with\r
2794  * [Location](#Location) literals.\r
2795  */\r
2796 var Location;\r
2797 (function (Location) {\r
2798     /**\r
2799      * Creates a Location literal.\r
2800      * @param uri The location's uri.\r
2801      * @param range The location's range.\r
2802      */\r
2803     function create(uri, range) {\r
2804         return { uri: uri, range: range };\r
2805     }\r
2806     Location.create = create;\r
2807     /**\r
2808      * Checks whether the given literal conforms to the [Location](#Location) interface.\r
2809      */\r
2810     function is(value) {\r
2811         var candidate = value;\r
2812         return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));\r
2813     }\r
2814     Location.is = is;\r
2815 })(Location || (Location = {}));\r
2816 /**\r
2817  * The LocationLink namespace provides helper functions to work with\r
2818  * [LocationLink](#LocationLink) literals.\r
2819  */\r
2820 var LocationLink;\r
2821 (function (LocationLink) {\r
2822     /**\r
2823      * Creates a LocationLink literal.\r
2824      * @param targetUri The definition's uri.\r
2825      * @param targetRange The full range of the definition.\r
2826      * @param targetSelectionRange The span of the symbol definition at the target.\r
2827      * @param originSelectionRange The span of the symbol being defined in the originating source file.\r
2828      */\r
2829     function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {\r
2830         return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };\r
2831     }\r
2832     LocationLink.create = create;\r
2833     /**\r
2834      * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.\r
2835      */\r
2836     function is(value) {\r
2837         var candidate = value;\r
2838         return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)\r
2839             && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))\r
2840             && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));\r
2841     }\r
2842     LocationLink.is = is;\r
2843 })(LocationLink || (LocationLink = {}));\r
2844 /**\r
2845  * The Color namespace provides helper functions to work with\r
2846  * [Color](#Color) literals.\r
2847  */\r
2848 var Color;\r
2849 (function (Color) {\r
2850     /**\r
2851      * Creates a new Color literal.\r
2852      */\r
2853     function create(red, green, blue, alpha) {\r
2854         return {\r
2855             red: red,\r
2856             green: green,\r
2857             blue: blue,\r
2858             alpha: alpha,\r
2859         };\r
2860     }\r
2861     Color.create = create;\r
2862     /**\r
2863      * Checks whether the given literal conforms to the [Color](#Color) interface.\r
2864      */\r
2865     function is(value) {\r
2866         var candidate = value;\r
2867         return Is.number(candidate.red)\r
2868             && Is.number(candidate.green)\r
2869             && Is.number(candidate.blue)\r
2870             && Is.number(candidate.alpha);\r
2871     }\r
2872     Color.is = is;\r
2873 })(Color || (Color = {}));\r
2874 /**\r
2875  * The ColorInformation namespace provides helper functions to work with\r
2876  * [ColorInformation](#ColorInformation) literals.\r
2877  */\r
2878 var ColorInformation;\r
2879 (function (ColorInformation) {\r
2880     /**\r
2881      * Creates a new ColorInformation literal.\r
2882      */\r
2883     function create(range, color) {\r
2884         return {\r
2885             range: range,\r
2886             color: color,\r
2887         };\r
2888     }\r
2889     ColorInformation.create = create;\r
2890     /**\r
2891      * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
2892      */\r
2893     function is(value) {\r
2894         var candidate = value;\r
2895         return Range.is(candidate.range) && Color.is(candidate.color);\r
2896     }\r
2897     ColorInformation.is = is;\r
2898 })(ColorInformation || (ColorInformation = {}));\r
2899 /**\r
2900  * The Color namespace provides helper functions to work with\r
2901  * [ColorPresentation](#ColorPresentation) literals.\r
2902  */\r
2903 var ColorPresentation;\r
2904 (function (ColorPresentation) {\r
2905     /**\r
2906      * Creates a new ColorInformation literal.\r
2907      */\r
2908     function create(label, textEdit, additionalTextEdits) {\r
2909         return {\r
2910             label: label,\r
2911             textEdit: textEdit,\r
2912             additionalTextEdits: additionalTextEdits,\r
2913         };\r
2914     }\r
2915     ColorPresentation.create = create;\r
2916     /**\r
2917      * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.\r
2918      */\r
2919     function is(value) {\r
2920         var candidate = value;\r
2921         return Is.string(candidate.label)\r
2922             && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))\r
2923             && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));\r
2924     }\r
2925     ColorPresentation.is = is;\r
2926 })(ColorPresentation || (ColorPresentation = {}));\r
2927 /**\r
2928  * Enum of known range kinds\r
2929  */\r
2930 var FoldingRangeKind;\r
2931 (function (FoldingRangeKind) {\r
2932     /**\r
2933      * Folding range for a comment\r
2934      */\r
2935     FoldingRangeKind["Comment"] = "comment";\r
2936     /**\r
2937      * Folding range for a imports or includes\r
2938      */\r
2939     FoldingRangeKind["Imports"] = "imports";\r
2940     /**\r
2941      * Folding range for a region (e.g. `#region`)\r
2942      */\r
2943     FoldingRangeKind["Region"] = "region";\r
2944 })(FoldingRangeKind || (FoldingRangeKind = {}));\r
2945 /**\r
2946  * The folding range namespace provides helper functions to work with\r
2947  * [FoldingRange](#FoldingRange) literals.\r
2948  */\r
2949 var FoldingRange;\r
2950 (function (FoldingRange) {\r
2951     /**\r
2952      * Creates a new FoldingRange literal.\r
2953      */\r
2954     function create(startLine, endLine, startCharacter, endCharacter, kind) {\r
2955         var result = {\r
2956             startLine: startLine,\r
2957             endLine: endLine\r
2958         };\r
2959         if (Is.defined(startCharacter)) {\r
2960             result.startCharacter = startCharacter;\r
2961         }\r
2962         if (Is.defined(endCharacter)) {\r
2963             result.endCharacter = endCharacter;\r
2964         }\r
2965         if (Is.defined(kind)) {\r
2966             result.kind = kind;\r
2967         }\r
2968         return result;\r
2969     }\r
2970     FoldingRange.create = create;\r
2971     /**\r
2972      * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.\r
2973      */\r
2974     function is(value) {\r
2975         var candidate = value;\r
2976         return Is.number(candidate.startLine) && Is.number(candidate.startLine)\r
2977             && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))\r
2978             && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))\r
2979             && (Is.undefined(candidate.kind) || Is.string(candidate.kind));\r
2980     }\r
2981     FoldingRange.is = is;\r
2982 })(FoldingRange || (FoldingRange = {}));\r
2983 /**\r
2984  * The DiagnosticRelatedInformation namespace provides helper functions to work with\r
2985  * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.\r
2986  */\r
2987 var DiagnosticRelatedInformation;\r
2988 (function (DiagnosticRelatedInformation) {\r
2989     /**\r
2990      * Creates a new DiagnosticRelatedInformation literal.\r
2991      */\r
2992     function create(location, message) {\r
2993         return {\r
2994             location: location,\r
2995             message: message\r
2996         };\r
2997     }\r
2998     DiagnosticRelatedInformation.create = create;\r
2999     /**\r
3000      * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.\r
3001      */\r
3002     function is(value) {\r
3003         var candidate = value;\r
3004         return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);\r
3005     }\r
3006     DiagnosticRelatedInformation.is = is;\r
3007 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));\r
3008 /**\r
3009  * The diagnostic's severity.\r
3010  */\r
3011 var DiagnosticSeverity;\r
3012 (function (DiagnosticSeverity) {\r
3013     /**\r
3014      * Reports an error.\r
3015      */\r
3016     DiagnosticSeverity.Error = 1;\r
3017     /**\r
3018      * Reports a warning.\r
3019      */\r
3020     DiagnosticSeverity.Warning = 2;\r
3021     /**\r
3022      * Reports an information.\r
3023      */\r
3024     DiagnosticSeverity.Information = 3;\r
3025     /**\r
3026      * Reports a hint.\r
3027      */\r
3028     DiagnosticSeverity.Hint = 4;\r
3029 })(DiagnosticSeverity || (DiagnosticSeverity = {}));\r
3030 /**\r
3031  * The diagnostic tags.\r
3032  *\r
3033  * @since 3.15.0\r
3034  */\r
3035 var DiagnosticTag;\r
3036 (function (DiagnosticTag) {\r
3037     /**\r
3038      * Unused or unnecessary code.\r
3039      *\r
3040      * Clients are allowed to render diagnostics with this tag faded out instead of having\r
3041      * an error squiggle.\r
3042      */\r
3043     DiagnosticTag.Unnecessary = 1;\r
3044     /**\r
3045      * Deprecated or obsolete code.\r
3046      *\r
3047      * Clients are allowed to rendered diagnostics with this tag strike through.\r
3048      */\r
3049     DiagnosticTag.Deprecated = 2;\r
3050 })(DiagnosticTag || (DiagnosticTag = {}));\r
3051 /**\r
3052  * The Diagnostic namespace provides helper functions to work with\r
3053  * [Diagnostic](#Diagnostic) literals.\r
3054  */\r
3055 var Diagnostic;\r
3056 (function (Diagnostic) {\r
3057     /**\r
3058      * Creates a new Diagnostic literal.\r
3059      */\r
3060     function create(range, message, severity, code, source, relatedInformation) {\r
3061         var result = { range: range, message: message };\r
3062         if (Is.defined(severity)) {\r
3063             result.severity = severity;\r
3064         }\r
3065         if (Is.defined(code)) {\r
3066             result.code = code;\r
3067         }\r
3068         if (Is.defined(source)) {\r
3069             result.source = source;\r
3070         }\r
3071         if (Is.defined(relatedInformation)) {\r
3072             result.relatedInformation = relatedInformation;\r
3073         }\r
3074         return result;\r
3075     }\r
3076     Diagnostic.create = create;\r
3077     /**\r
3078      * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.\r
3079      */\r
3080     function is(value) {\r
3081         var candidate = value;\r
3082         return Is.defined(candidate)\r
3083             && Range.is(candidate.range)\r
3084             && Is.string(candidate.message)\r
3085             && (Is.number(candidate.severity) || Is.undefined(candidate.severity))\r
3086             && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))\r
3087             && (Is.string(candidate.source) || Is.undefined(candidate.source))\r
3088             && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));\r
3089     }\r
3090     Diagnostic.is = is;\r
3091 })(Diagnostic || (Diagnostic = {}));\r
3092 /**\r
3093  * The Command namespace provides helper functions to work with\r
3094  * [Command](#Command) literals.\r
3095  */\r
3096 var Command;\r
3097 (function (Command) {\r
3098     /**\r
3099      * Creates a new Command literal.\r
3100      */\r
3101     function create(title, command) {\r
3102         var args = [];\r
3103         for (var _i = 2; _i < arguments.length; _i++) {\r
3104             args[_i - 2] = arguments[_i];\r
3105         }\r
3106         var result = { title: title, command: command };\r
3107         if (Is.defined(args) && args.length > 0) {\r
3108             result.arguments = args;\r
3109         }\r
3110         return result;\r
3111     }\r
3112     Command.create = create;\r
3113     /**\r
3114      * Checks whether the given literal conforms to the [Command](#Command) interface.\r
3115      */\r
3116     function is(value) {\r
3117         var candidate = value;\r
3118         return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);\r
3119     }\r
3120     Command.is = is;\r
3121 })(Command || (Command = {}));\r
3122 /**\r
3123  * The TextEdit namespace provides helper function to create replace,\r
3124  * insert and delete edits more easily.\r
3125  */\r
3126 var TextEdit;\r
3127 (function (TextEdit) {\r
3128     /**\r
3129      * Creates a replace text edit.\r
3130      * @param range The range of text to be replaced.\r
3131      * @param newText The new text.\r
3132      */\r
3133     function replace(range, newText) {\r
3134         return { range: range, newText: newText };\r
3135     }\r
3136     TextEdit.replace = replace;\r
3137     /**\r
3138      * Creates a insert text edit.\r
3139      * @param position The position to insert the text at.\r
3140      * @param newText The text to be inserted.\r
3141      */\r
3142     function insert(position, newText) {\r
3143         return { range: { start: position, end: position }, newText: newText };\r
3144     }\r
3145     TextEdit.insert = insert;\r
3146     /**\r
3147      * Creates a delete text edit.\r
3148      * @param range The range of text to be deleted.\r
3149      */\r
3150     function del(range) {\r
3151         return { range: range, newText: '' };\r
3152     }\r
3153     TextEdit.del = del;\r
3154     function is(value) {\r
3155         var candidate = value;\r
3156         return Is.objectLiteral(candidate)\r
3157             && Is.string(candidate.newText)\r
3158             && Range.is(candidate.range);\r
3159     }\r
3160     TextEdit.is = is;\r
3161 })(TextEdit || (TextEdit = {}));\r
3162 /**\r
3163  * The TextDocumentEdit namespace provides helper function to create\r
3164  * an edit that manipulates a text document.\r
3165  */\r
3166 var TextDocumentEdit;\r
3167 (function (TextDocumentEdit) {\r
3168     /**\r
3169      * Creates a new `TextDocumentEdit`\r
3170      */\r
3171     function create(textDocument, edits) {\r
3172         return { textDocument: textDocument, edits: edits };\r
3173     }\r
3174     TextDocumentEdit.create = create;\r
3175     function is(value) {\r
3176         var candidate = value;\r
3177         return Is.defined(candidate)\r
3178             && VersionedTextDocumentIdentifier.is(candidate.textDocument)\r
3179             && Array.isArray(candidate.edits);\r
3180     }\r
3181     TextDocumentEdit.is = is;\r
3182 })(TextDocumentEdit || (TextDocumentEdit = {}));\r
3183 var CreateFile;\r
3184 (function (CreateFile) {\r
3185     function create(uri, options) {\r
3186         var result = {\r
3187             kind: 'create',\r
3188             uri: uri\r
3189         };\r
3190         if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
3191             result.options = options;\r
3192         }\r
3193         return result;\r
3194     }\r
3195     CreateFile.create = create;\r
3196     function is(value) {\r
3197         var candidate = value;\r
3198         return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&\r
3199             (candidate.options === void 0 ||\r
3200                 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
3201     }\r
3202     CreateFile.is = is;\r
3203 })(CreateFile || (CreateFile = {}));\r
3204 var RenameFile;\r
3205 (function (RenameFile) {\r
3206     function create(oldUri, newUri, options) {\r
3207         var result = {\r
3208             kind: 'rename',\r
3209             oldUri: oldUri,\r
3210             newUri: newUri\r
3211         };\r
3212         if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {\r
3213             result.options = options;\r
3214         }\r
3215         return result;\r
3216     }\r
3217     RenameFile.create = create;\r
3218     function is(value) {\r
3219         var candidate = value;\r
3220         return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&\r
3221             (candidate.options === void 0 ||\r
3222                 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));\r
3223     }\r
3224     RenameFile.is = is;\r
3225 })(RenameFile || (RenameFile = {}));\r
3226 var DeleteFile;\r
3227 (function (DeleteFile) {\r
3228     function create(uri, options) {\r
3229         var result = {\r
3230             kind: 'delete',\r
3231             uri: uri\r
3232         };\r
3233         if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {\r
3234             result.options = options;\r
3235         }\r
3236         return result;\r
3237     }\r
3238     DeleteFile.create = create;\r
3239     function is(value) {\r
3240         var candidate = value;\r
3241         return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&\r
3242             (candidate.options === void 0 ||\r
3243                 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));\r
3244     }\r
3245     DeleteFile.is = is;\r
3246 })(DeleteFile || (DeleteFile = {}));\r
3247 var WorkspaceEdit;\r
3248 (function (WorkspaceEdit) {\r
3249     function is(value) {\r
3250         var candidate = value;\r
3251         return candidate &&\r
3252             (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&\r
3253             (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {\r
3254                 if (Is.string(change.kind)) {\r
3255                     return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);\r
3256                 }\r
3257                 else {\r
3258                     return TextDocumentEdit.is(change);\r
3259                 }\r
3260             }));\r
3261     }\r
3262     WorkspaceEdit.is = is;\r
3263 })(WorkspaceEdit || (WorkspaceEdit = {}));\r
3264 var TextEditChangeImpl = /** @class */ (function () {\r
3265     function TextEditChangeImpl(edits) {\r
3266         this.edits = edits;\r
3267     }\r
3268     TextEditChangeImpl.prototype.insert = function (position, newText) {\r
3269         this.edits.push(TextEdit.insert(position, newText));\r
3270     };\r
3271     TextEditChangeImpl.prototype.replace = function (range, newText) {\r
3272         this.edits.push(TextEdit.replace(range, newText));\r
3273     };\r
3274     TextEditChangeImpl.prototype.delete = function (range) {\r
3275         this.edits.push(TextEdit.del(range));\r
3276     };\r
3277     TextEditChangeImpl.prototype.add = function (edit) {\r
3278         this.edits.push(edit);\r
3279     };\r
3280     TextEditChangeImpl.prototype.all = function () {\r
3281         return this.edits;\r
3282     };\r
3283     TextEditChangeImpl.prototype.clear = function () {\r
3284         this.edits.splice(0, this.edits.length);\r
3285     };\r
3286     return TextEditChangeImpl;\r
3287 }());\r
3288 /**\r
3289  * A workspace change helps constructing changes to a workspace.\r
3290  */\r
3291 var WorkspaceChange = /** @class */ (function () {\r
3292     function WorkspaceChange(workspaceEdit) {\r
3293         var _this = this;\r
3294         this._textEditChanges = Object.create(null);\r
3295         if (workspaceEdit) {\r
3296             this._workspaceEdit = workspaceEdit;\r
3297             if (workspaceEdit.documentChanges) {\r
3298                 workspaceEdit.documentChanges.forEach(function (change) {\r
3299                     if (TextDocumentEdit.is(change)) {\r
3300                         var textEditChange = new TextEditChangeImpl(change.edits);\r
3301                         _this._textEditChanges[change.textDocument.uri] = textEditChange;\r
3302                     }\r
3303                 });\r
3304             }\r
3305             else if (workspaceEdit.changes) {\r
3306                 Object.keys(workspaceEdit.changes).forEach(function (key) {\r
3307                     var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);\r
3308                     _this._textEditChanges[key] = textEditChange;\r
3309                 });\r
3310             }\r
3311         }\r
3312     }\r
3313     Object.defineProperty(WorkspaceChange.prototype, "edit", {\r
3314         /**\r
3315          * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal\r
3316          * use to be returned from a workspace edit operation like rename.\r
3317          */\r
3318         get: function () {\r
3319             return this._workspaceEdit;\r
3320         },\r
3321         enumerable: true,\r
3322         configurable: true\r
3323     });\r
3324     WorkspaceChange.prototype.getTextEditChange = function (key) {\r
3325         if (VersionedTextDocumentIdentifier.is(key)) {\r
3326             if (!this._workspaceEdit) {\r
3327                 this._workspaceEdit = {\r
3328                     documentChanges: []\r
3329                 };\r
3330             }\r
3331             if (!this._workspaceEdit.documentChanges) {\r
3332                 throw new Error('Workspace edit is not configured for document changes.');\r
3333             }\r
3334             var textDocument = key;\r
3335             var result = this._textEditChanges[textDocument.uri];\r
3336             if (!result) {\r
3337                 var edits = [];\r
3338                 var textDocumentEdit = {\r
3339                     textDocument: textDocument,\r
3340                     edits: edits\r
3341                 };\r
3342                 this._workspaceEdit.documentChanges.push(textDocumentEdit);\r
3343                 result = new TextEditChangeImpl(edits);\r
3344                 this._textEditChanges[textDocument.uri] = result;\r
3345             }\r
3346             return result;\r
3347         }\r
3348         else {\r
3349             if (!this._workspaceEdit) {\r
3350                 this._workspaceEdit = {\r
3351                     changes: Object.create(null)\r
3352                 };\r
3353             }\r
3354             if (!this._workspaceEdit.changes) {\r
3355                 throw new Error('Workspace edit is not configured for normal text edit changes.');\r
3356             }\r
3357             var result = this._textEditChanges[key];\r
3358             if (!result) {\r
3359                 var edits = [];\r
3360                 this._workspaceEdit.changes[key] = edits;\r
3361                 result = new TextEditChangeImpl(edits);\r
3362                 this._textEditChanges[key] = result;\r
3363             }\r
3364             return result;\r
3365         }\r
3366     };\r
3367     WorkspaceChange.prototype.createFile = function (uri, options) {\r
3368         this.checkDocumentChanges();\r
3369         this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));\r
3370     };\r
3371     WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {\r
3372         this.checkDocumentChanges();\r
3373         this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));\r
3374     };\r
3375     WorkspaceChange.prototype.deleteFile = function (uri, options) {\r
3376         this.checkDocumentChanges();\r
3377         this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));\r
3378     };\r
3379     WorkspaceChange.prototype.checkDocumentChanges = function () {\r
3380         if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {\r
3381             throw new Error('Workspace edit is not configured for document changes.');\r
3382         }\r
3383     };\r
3384     return WorkspaceChange;\r
3385 }());\r
3386 \r
3387 /**\r
3388  * The TextDocumentIdentifier namespace provides helper functions to work with\r
3389  * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.\r
3390  */\r
3391 var TextDocumentIdentifier;\r
3392 (function (TextDocumentIdentifier) {\r
3393     /**\r
3394      * Creates a new TextDocumentIdentifier literal.\r
3395      * @param uri The document's uri.\r
3396      */\r
3397     function create(uri) {\r
3398         return { uri: uri };\r
3399     }\r
3400     TextDocumentIdentifier.create = create;\r
3401     /**\r
3402      * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.\r
3403      */\r
3404     function is(value) {\r
3405         var candidate = value;\r
3406         return Is.defined(candidate) && Is.string(candidate.uri);\r
3407     }\r
3408     TextDocumentIdentifier.is = is;\r
3409 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));\r
3410 /**\r
3411  * The VersionedTextDocumentIdentifier namespace provides helper functions to work with\r
3412  * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.\r
3413  */\r
3414 var VersionedTextDocumentIdentifier;\r
3415 (function (VersionedTextDocumentIdentifier) {\r
3416     /**\r
3417      * Creates a new VersionedTextDocumentIdentifier literal.\r
3418      * @param uri The document's uri.\r
3419      * @param uri The document's text.\r
3420      */\r
3421     function create(uri, version) {\r
3422         return { uri: uri, version: version };\r
3423     }\r
3424     VersionedTextDocumentIdentifier.create = create;\r
3425     /**\r
3426      * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.\r
3427      */\r
3428     function is(value) {\r
3429         var candidate = value;\r
3430         return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));\r
3431     }\r
3432     VersionedTextDocumentIdentifier.is = is;\r
3433 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));\r
3434 /**\r
3435  * The TextDocumentItem namespace provides helper functions to work with\r
3436  * [TextDocumentItem](#TextDocumentItem) literals.\r
3437  */\r
3438 var TextDocumentItem;\r
3439 (function (TextDocumentItem) {\r
3440     /**\r
3441      * Creates a new TextDocumentItem literal.\r
3442      * @param uri The document's uri.\r
3443      * @param languageId The document's language identifier.\r
3444      * @param version The document's version number.\r
3445      * @param text The document's text.\r
3446      */\r
3447     function create(uri, languageId, version, text) {\r
3448         return { uri: uri, languageId: languageId, version: version, text: text };\r
3449     }\r
3450     TextDocumentItem.create = create;\r
3451     /**\r
3452      * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.\r
3453      */\r
3454     function is(value) {\r
3455         var candidate = value;\r
3456         return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);\r
3457     }\r
3458     TextDocumentItem.is = is;\r
3459 })(TextDocumentItem || (TextDocumentItem = {}));\r
3460 /**\r
3461  * Describes the content type that a client supports in various\r
3462  * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.\r
3463  *\r
3464  * Please note that `MarkupKinds` must not start with a `$`. This kinds\r
3465  * are reserved for internal usage.\r
3466  */\r
3467 var MarkupKind;\r
3468 (function (MarkupKind) {\r
3469     /**\r
3470      * Plain text is supported as a content format\r
3471      */\r
3472     MarkupKind.PlainText = 'plaintext';\r
3473     /**\r
3474      * Markdown is supported as a content format\r
3475      */\r
3476     MarkupKind.Markdown = 'markdown';\r
3477 })(MarkupKind || (MarkupKind = {}));\r
3478 (function (MarkupKind) {\r
3479     /**\r
3480      * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.\r
3481      */\r
3482     function is(value) {\r
3483         var candidate = value;\r
3484         return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;\r
3485     }\r
3486     MarkupKind.is = is;\r
3487 })(MarkupKind || (MarkupKind = {}));\r
3488 var MarkupContent;\r
3489 (function (MarkupContent) {\r
3490     /**\r
3491      * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.\r
3492      */\r
3493     function is(value) {\r
3494         var candidate = value;\r
3495         return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);\r
3496     }\r
3497     MarkupContent.is = is;\r
3498 })(MarkupContent || (MarkupContent = {}));\r
3499 /**\r
3500  * The kind of a completion entry.\r
3501  */\r
3502 var CompletionItemKind;\r
3503 (function (CompletionItemKind) {\r
3504     CompletionItemKind.Text = 1;\r
3505     CompletionItemKind.Method = 2;\r
3506     CompletionItemKind.Function = 3;\r
3507     CompletionItemKind.Constructor = 4;\r
3508     CompletionItemKind.Field = 5;\r
3509     CompletionItemKind.Variable = 6;\r
3510     CompletionItemKind.Class = 7;\r
3511     CompletionItemKind.Interface = 8;\r
3512     CompletionItemKind.Module = 9;\r
3513     CompletionItemKind.Property = 10;\r
3514     CompletionItemKind.Unit = 11;\r
3515     CompletionItemKind.Value = 12;\r
3516     CompletionItemKind.Enum = 13;\r
3517     CompletionItemKind.Keyword = 14;\r
3518     CompletionItemKind.Snippet = 15;\r
3519     CompletionItemKind.Color = 16;\r
3520     CompletionItemKind.File = 17;\r
3521     CompletionItemKind.Reference = 18;\r
3522     CompletionItemKind.Folder = 19;\r
3523     CompletionItemKind.EnumMember = 20;\r
3524     CompletionItemKind.Constant = 21;\r
3525     CompletionItemKind.Struct = 22;\r
3526     CompletionItemKind.Event = 23;\r
3527     CompletionItemKind.Operator = 24;\r
3528     CompletionItemKind.TypeParameter = 25;\r
3529 })(CompletionItemKind || (CompletionItemKind = {}));\r
3530 /**\r
3531  * Defines whether the insert text in a completion item should be interpreted as\r
3532  * plain text or a snippet.\r
3533  */\r
3534 var InsertTextFormat;\r
3535 (function (InsertTextFormat) {\r
3536     /**\r
3537      * The primary text to be inserted is treated as a plain string.\r
3538      */\r
3539     InsertTextFormat.PlainText = 1;\r
3540     /**\r
3541      * The primary text to be inserted is treated as a snippet.\r
3542      *\r
3543      * A snippet can define tab stops and placeholders with `$1`, `$2`\r
3544      * and `${3:foo}`. `$0` defines the final tab stop, it defaults to\r
3545      * the end of the snippet. Placeholders with equal identifiers are linked,\r
3546      * that is typing in one will update others too.\r
3547      *\r
3548      * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md\r
3549      */\r
3550     InsertTextFormat.Snippet = 2;\r
3551 })(InsertTextFormat || (InsertTextFormat = {}));\r
3552 /**\r
3553  * Completion item tags are extra annotations that tweak the rendering of a completion\r
3554  * item.\r
3555  *\r
3556  * @since 3.15.0\r
3557  */\r
3558 var CompletionItemTag;\r
3559 (function (CompletionItemTag) {\r
3560     /**\r
3561      * Render a completion as obsolete, usually using a strike-out.\r
3562      */\r
3563     CompletionItemTag.Deprecated = 1;\r
3564 })(CompletionItemTag || (CompletionItemTag = {}));\r
3565 /**\r
3566  * The CompletionItem namespace provides functions to deal with\r
3567  * completion items.\r
3568  */\r
3569 var CompletionItem;\r
3570 (function (CompletionItem) {\r
3571     /**\r
3572      * Create a completion item and seed it with a label.\r
3573      * @param label The completion item's label\r
3574      */\r
3575     function create(label) {\r
3576         return { label: label };\r
3577     }\r
3578     CompletionItem.create = create;\r
3579 })(CompletionItem || (CompletionItem = {}));\r
3580 /**\r
3581  * The CompletionList namespace provides functions to deal with\r
3582  * completion lists.\r
3583  */\r
3584 var CompletionList;\r
3585 (function (CompletionList) {\r
3586     /**\r
3587      * Creates a new completion list.\r
3588      *\r
3589      * @param items The completion items.\r
3590      * @param isIncomplete The list is not complete.\r
3591      */\r
3592     function create(items, isIncomplete) {\r
3593         return { items: items ? items : [], isIncomplete: !!isIncomplete };\r
3594     }\r
3595     CompletionList.create = create;\r
3596 })(CompletionList || (CompletionList = {}));\r
3597 var MarkedString;\r
3598 (function (MarkedString) {\r
3599     /**\r
3600      * Creates a marked string from plain text.\r
3601      *\r
3602      * @param plainText The plain text.\r
3603      */\r
3604     function fromPlainText(plainText) {\r
3605         return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash\r
3606     }\r
3607     MarkedString.fromPlainText = fromPlainText;\r
3608     /**\r
3609      * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.\r
3610      */\r
3611     function is(value) {\r
3612         var candidate = value;\r
3613         return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));\r
3614     }\r
3615     MarkedString.is = is;\r
3616 })(MarkedString || (MarkedString = {}));\r
3617 var Hover;\r
3618 (function (Hover) {\r
3619     /**\r
3620      * Checks whether the given value conforms to the [Hover](#Hover) interface.\r
3621      */\r
3622     function is(value) {\r
3623         var candidate = value;\r
3624         return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||\r
3625             MarkedString.is(candidate.contents) ||\r
3626             Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));\r
3627     }\r
3628     Hover.is = is;\r
3629 })(Hover || (Hover = {}));\r
3630 /**\r
3631  * The ParameterInformation namespace provides helper functions to work with\r
3632  * [ParameterInformation](#ParameterInformation) literals.\r
3633  */\r
3634 var ParameterInformation;\r
3635 (function (ParameterInformation) {\r
3636     /**\r
3637      * Creates a new parameter information literal.\r
3638      *\r
3639      * @param label A label string.\r
3640      * @param documentation A doc string.\r
3641      */\r
3642     function create(label, documentation) {\r
3643         return documentation ? { label: label, documentation: documentation } : { label: label };\r
3644     }\r
3645     ParameterInformation.create = create;\r
3646 })(ParameterInformation || (ParameterInformation = {}));\r
3647 /**\r
3648  * The SignatureInformation namespace provides helper functions to work with\r
3649  * [SignatureInformation](#SignatureInformation) literals.\r
3650  */\r
3651 var SignatureInformation;\r
3652 (function (SignatureInformation) {\r
3653     function create(label, documentation) {\r
3654         var parameters = [];\r
3655         for (var _i = 2; _i < arguments.length; _i++) {\r
3656             parameters[_i - 2] = arguments[_i];\r
3657         }\r
3658         var result = { label: label };\r
3659         if (Is.defined(documentation)) {\r
3660             result.documentation = documentation;\r
3661         }\r
3662         if (Is.defined(parameters)) {\r
3663             result.parameters = parameters;\r
3664         }\r
3665         else {\r
3666             result.parameters = [];\r
3667         }\r
3668         return result;\r
3669     }\r
3670     SignatureInformation.create = create;\r
3671 })(SignatureInformation || (SignatureInformation = {}));\r
3672 /**\r
3673  * A document highlight kind.\r
3674  */\r
3675 var DocumentHighlightKind;\r
3676 (function (DocumentHighlightKind) {\r
3677     /**\r
3678      * A textual occurrence.\r
3679      */\r
3680     DocumentHighlightKind.Text = 1;\r
3681     /**\r
3682      * Read-access of a symbol, like reading a variable.\r
3683      */\r
3684     DocumentHighlightKind.Read = 2;\r
3685     /**\r
3686      * Write-access of a symbol, like writing to a variable.\r
3687      */\r
3688     DocumentHighlightKind.Write = 3;\r
3689 })(DocumentHighlightKind || (DocumentHighlightKind = {}));\r
3690 /**\r
3691  * DocumentHighlight namespace to provide helper functions to work with\r
3692  * [DocumentHighlight](#DocumentHighlight) literals.\r
3693  */\r
3694 var DocumentHighlight;\r
3695 (function (DocumentHighlight) {\r
3696     /**\r
3697      * Create a DocumentHighlight object.\r
3698      * @param range The range the highlight applies to.\r
3699      */\r
3700     function create(range, kind) {\r
3701         var result = { range: range };\r
3702         if (Is.number(kind)) {\r
3703             result.kind = kind;\r
3704         }\r
3705         return result;\r
3706     }\r
3707     DocumentHighlight.create = create;\r
3708 })(DocumentHighlight || (DocumentHighlight = {}));\r
3709 /**\r
3710  * A symbol kind.\r
3711  */\r
3712 var SymbolKind;\r
3713 (function (SymbolKind) {\r
3714     SymbolKind.File = 1;\r
3715     SymbolKind.Module = 2;\r
3716     SymbolKind.Namespace = 3;\r
3717     SymbolKind.Package = 4;\r
3718     SymbolKind.Class = 5;\r
3719     SymbolKind.Method = 6;\r
3720     SymbolKind.Property = 7;\r
3721     SymbolKind.Field = 8;\r
3722     SymbolKind.Constructor = 9;\r
3723     SymbolKind.Enum = 10;\r
3724     SymbolKind.Interface = 11;\r
3725     SymbolKind.Function = 12;\r
3726     SymbolKind.Variable = 13;\r
3727     SymbolKind.Constant = 14;\r
3728     SymbolKind.String = 15;\r
3729     SymbolKind.Number = 16;\r
3730     SymbolKind.Boolean = 17;\r
3731     SymbolKind.Array = 18;\r
3732     SymbolKind.Object = 19;\r
3733     SymbolKind.Key = 20;\r
3734     SymbolKind.Null = 21;\r
3735     SymbolKind.EnumMember = 22;\r
3736     SymbolKind.Struct = 23;\r
3737     SymbolKind.Event = 24;\r
3738     SymbolKind.Operator = 25;\r
3739     SymbolKind.TypeParameter = 26;\r
3740 })(SymbolKind || (SymbolKind = {}));\r
3741 /**\r
3742  * Symbol tags are extra annotations that tweak the rendering of a symbol.\r
3743  * @since 3.15\r
3744  */\r
3745 var SymbolTag;\r
3746 (function (SymbolTag) {\r
3747     /**\r
3748      * Render a symbol as obsolete, usually using a strike-out.\r
3749      */\r
3750     SymbolTag.Deprecated = 1;\r
3751 })(SymbolTag || (SymbolTag = {}));\r
3752 var SymbolInformation;\r
3753 (function (SymbolInformation) {\r
3754     /**\r
3755      * Creates a new symbol information literal.\r
3756      *\r
3757      * @param name The name of the symbol.\r
3758      * @param kind The kind of the symbol.\r
3759      * @param range The range of the location of the symbol.\r
3760      * @param uri The resource of the location of symbol, defaults to the current document.\r
3761      * @param containerName The name of the symbol containing the symbol.\r
3762      */\r
3763     function create(name, kind, range, uri, containerName) {\r
3764         var result = {\r
3765             name: name,\r
3766             kind: kind,\r
3767             location: { uri: uri, range: range }\r
3768         };\r
3769         if (containerName) {\r
3770             result.containerName = containerName;\r
3771         }\r
3772         return result;\r
3773     }\r
3774     SymbolInformation.create = create;\r
3775 })(SymbolInformation || (SymbolInformation = {}));\r
3776 var DocumentSymbol;\r
3777 (function (DocumentSymbol) {\r
3778     /**\r
3779      * Creates a new symbol information literal.\r
3780      *\r
3781      * @param name The name of the symbol.\r
3782      * @param detail The detail of the symbol.\r
3783      * @param kind The kind of the symbol.\r
3784      * @param range The range of the symbol.\r
3785      * @param selectionRange The selectionRange of the symbol.\r
3786      * @param children Children of the symbol.\r
3787      */\r
3788     function create(name, detail, kind, range, selectionRange, children) {\r
3789         var result = {\r
3790             name: name,\r
3791             detail: detail,\r
3792             kind: kind,\r
3793             range: range,\r
3794             selectionRange: selectionRange\r
3795         };\r
3796         if (children !== void 0) {\r
3797             result.children = children;\r
3798         }\r
3799         return result;\r
3800     }\r
3801     DocumentSymbol.create = create;\r
3802     /**\r
3803      * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.\r
3804      */\r
3805     function is(value) {\r
3806         var candidate = value;\r
3807         return candidate &&\r
3808             Is.string(candidate.name) && Is.number(candidate.kind) &&\r
3809             Range.is(candidate.range) && Range.is(candidate.selectionRange) &&\r
3810             (candidate.detail === void 0 || Is.string(candidate.detail)) &&\r
3811             (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&\r
3812             (candidate.children === void 0 || Array.isArray(candidate.children));\r
3813     }\r
3814     DocumentSymbol.is = is;\r
3815 })(DocumentSymbol || (DocumentSymbol = {}));\r
3816 /**\r
3817  * A set of predefined code action kinds\r
3818  */\r
3819 var CodeActionKind;\r
3820 (function (CodeActionKind) {\r
3821     /**\r
3822      * Empty kind.\r
3823      */\r
3824     CodeActionKind.Empty = '';\r
3825     /**\r
3826      * Base kind for quickfix actions: 'quickfix'\r
3827      */\r
3828     CodeActionKind.QuickFix = 'quickfix';\r
3829     /**\r
3830      * Base kind for refactoring actions: 'refactor'\r
3831      */\r
3832     CodeActionKind.Refactor = 'refactor';\r
3833     /**\r
3834      * Base kind for refactoring extraction actions: 'refactor.extract'\r
3835      *\r
3836      * Example extract actions:\r
3837      *\r
3838      * - Extract method\r
3839      * - Extract function\r
3840      * - Extract variable\r
3841      * - Extract interface from class\r
3842      * - ...\r
3843      */\r
3844     CodeActionKind.RefactorExtract = 'refactor.extract';\r
3845     /**\r
3846      * Base kind for refactoring inline actions: 'refactor.inline'\r
3847      *\r
3848      * Example inline actions:\r
3849      *\r
3850      * - Inline function\r
3851      * - Inline variable\r
3852      * - Inline constant\r
3853      * - ...\r
3854      */\r
3855     CodeActionKind.RefactorInline = 'refactor.inline';\r
3856     /**\r
3857      * Base kind for refactoring rewrite actions: 'refactor.rewrite'\r
3858      *\r
3859      * Example rewrite actions:\r
3860      *\r
3861      * - Convert JavaScript function to class\r
3862      * - Add or remove parameter\r
3863      * - Encapsulate field\r
3864      * - Make method static\r
3865      * - Move method to base class\r
3866      * - ...\r
3867      */\r
3868     CodeActionKind.RefactorRewrite = 'refactor.rewrite';\r
3869     /**\r
3870      * Base kind for source actions: `source`\r
3871      *\r
3872      * Source code actions apply to the entire file.\r
3873      */\r
3874     CodeActionKind.Source = 'source';\r
3875     /**\r
3876      * Base kind for an organize imports source action: `source.organizeImports`\r
3877      */\r
3878     CodeActionKind.SourceOrganizeImports = 'source.organizeImports';\r
3879     /**\r
3880      * Base kind for auto-fix source actions: `source.fixAll`.\r
3881      *\r
3882      * Fix all actions automatically fix errors that have a clear fix that do not require user input.\r
3883      * They should not suppress errors or perform unsafe fixes such as generating new types or classes.\r
3884      *\r
3885      * @since 3.15.0\r
3886      */\r
3887     CodeActionKind.SourceFixAll = 'source.fixAll';\r
3888 })(CodeActionKind || (CodeActionKind = {}));\r
3889 /**\r
3890  * The CodeActionContext namespace provides helper functions to work with\r
3891  * [CodeActionContext](#CodeActionContext) literals.\r
3892  */\r
3893 var CodeActionContext;\r
3894 (function (CodeActionContext) {\r
3895     /**\r
3896      * Creates a new CodeActionContext literal.\r
3897      */\r
3898     function create(diagnostics, only) {\r
3899         var result = { diagnostics: diagnostics };\r
3900         if (only !== void 0 && only !== null) {\r
3901             result.only = only;\r
3902         }\r
3903         return result;\r
3904     }\r
3905     CodeActionContext.create = create;\r
3906     /**\r
3907      * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.\r
3908      */\r
3909     function is(value) {\r
3910         var candidate = value;\r
3911         return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));\r
3912     }\r
3913     CodeActionContext.is = is;\r
3914 })(CodeActionContext || (CodeActionContext = {}));\r
3915 var CodeAction;\r
3916 (function (CodeAction) {\r
3917     function create(title, commandOrEdit, kind) {\r
3918         var result = { title: title };\r
3919         if (Command.is(commandOrEdit)) {\r
3920             result.command = commandOrEdit;\r
3921         }\r
3922         else {\r
3923             result.edit = commandOrEdit;\r
3924         }\r
3925         if (kind !== void 0) {\r
3926             result.kind = kind;\r
3927         }\r
3928         return result;\r
3929     }\r
3930     CodeAction.create = create;\r
3931     function is(value) {\r
3932         var candidate = value;\r
3933         return candidate && Is.string(candidate.title) &&\r
3934             (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&\r
3935             (candidate.kind === void 0 || Is.string(candidate.kind)) &&\r
3936             (candidate.edit !== void 0 || candidate.command !== void 0) &&\r
3937             (candidate.command === void 0 || Command.is(candidate.command)) &&\r
3938             (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&\r
3939             (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));\r
3940     }\r
3941     CodeAction.is = is;\r
3942 })(CodeAction || (CodeAction = {}));\r
3943 /**\r
3944  * The CodeLens namespace provides helper functions to work with\r
3945  * [CodeLens](#CodeLens) literals.\r
3946  */\r
3947 var CodeLens;\r
3948 (function (CodeLens) {\r
3949     /**\r
3950      * Creates a new CodeLens literal.\r
3951      */\r
3952     function create(range, data) {\r
3953         var result = { range: range };\r
3954         if (Is.defined(data)) {\r
3955             result.data = data;\r
3956         }\r
3957         return result;\r
3958     }\r
3959     CodeLens.create = create;\r
3960     /**\r
3961      * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.\r
3962      */\r
3963     function is(value) {\r
3964         var candidate = value;\r
3965         return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));\r
3966     }\r
3967     CodeLens.is = is;\r
3968 })(CodeLens || (CodeLens = {}));\r
3969 /**\r
3970  * The FormattingOptions namespace provides helper functions to work with\r
3971  * [FormattingOptions](#FormattingOptions) literals.\r
3972  */\r
3973 var FormattingOptions;\r
3974 (function (FormattingOptions) {\r
3975     /**\r
3976      * Creates a new FormattingOptions literal.\r
3977      */\r
3978     function create(tabSize, insertSpaces) {\r
3979         return { tabSize: tabSize, insertSpaces: insertSpaces };\r
3980     }\r
3981     FormattingOptions.create = create;\r
3982     /**\r
3983      * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.\r
3984      */\r
3985     function is(value) {\r
3986         var candidate = value;\r
3987         return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);\r
3988     }\r
3989     FormattingOptions.is = is;\r
3990 })(FormattingOptions || (FormattingOptions = {}));\r
3991 /**\r
3992  * The DocumentLink namespace provides helper functions to work with\r
3993  * [DocumentLink](#DocumentLink) literals.\r
3994  */\r
3995 var DocumentLink;\r
3996 (function (DocumentLink) {\r
3997     /**\r
3998      * Creates a new DocumentLink literal.\r
3999      */\r
4000     function create(range, target, data) {\r
4001         return { range: range, target: target, data: data };\r
4002     }\r
4003     DocumentLink.create = create;\r
4004     /**\r
4005      * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.\r
4006      */\r
4007     function is(value) {\r
4008         var candidate = value;\r
4009         return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));\r
4010     }\r
4011     DocumentLink.is = is;\r
4012 })(DocumentLink || (DocumentLink = {}));\r
4013 /**\r
4014  * The SelectionRange namespace provides helper function to work with\r
4015  * SelectionRange literals.\r
4016  */\r
4017 var SelectionRange;\r
4018 (function (SelectionRange) {\r
4019     /**\r
4020      * Creates a new SelectionRange\r
4021      * @param range the range.\r
4022      * @param parent an optional parent.\r
4023      */\r
4024     function create(range, parent) {\r
4025         return { range: range, parent: parent };\r
4026     }\r
4027     SelectionRange.create = create;\r
4028     function is(value) {\r
4029         var candidate = value;\r
4030         return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));\r
4031     }\r
4032     SelectionRange.is = is;\r
4033 })(SelectionRange || (SelectionRange = {}));\r
4034 var EOL = ['\n', '\r\n', '\r'];\r
4035 /**\r
4036  * @deprecated Use the text document from the new vscode-languageserver-textdocument package.\r
4037  */\r
4038 var TextDocument;\r
4039 (function (TextDocument) {\r
4040     /**\r
4041      * Creates a new ITextDocument literal from the given uri and content.\r
4042      * @param uri The document's uri.\r
4043      * @param languageId  The document's language Id.\r
4044      * @param content The document's content.\r
4045      */\r
4046     function create(uri, languageId, version, content) {\r
4047         return new FullTextDocument(uri, languageId, version, content);\r
4048     }\r
4049     TextDocument.create = create;\r
4050     /**\r
4051      * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.\r
4052      */\r
4053     function is(value) {\r
4054         var candidate = value;\r
4055         return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)\r
4056             && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;\r
4057     }\r
4058     TextDocument.is = is;\r
4059     function applyEdits(document, edits) {\r
4060         var text = document.getText();\r
4061         var sortedEdits = mergeSort(edits, function (a, b) {\r
4062             var diff = a.range.start.line - b.range.start.line;\r
4063             if (diff === 0) {\r
4064                 return a.range.start.character - b.range.start.character;\r
4065             }\r
4066             return diff;\r
4067         });\r
4068         var lastModifiedOffset = text.length;\r
4069         for (var i = sortedEdits.length - 1; i >= 0; i--) {\r
4070             var e = sortedEdits[i];\r
4071             var startOffset = document.offsetAt(e.range.start);\r
4072             var endOffset = document.offsetAt(e.range.end);\r
4073             if (endOffset <= lastModifiedOffset) {\r
4074                 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);\r
4075             }\r
4076             else {\r
4077                 throw new Error('Overlapping edit');\r
4078             }\r
4079             lastModifiedOffset = startOffset;\r
4080         }\r
4081         return text;\r
4082     }\r
4083     TextDocument.applyEdits = applyEdits;\r
4084     function mergeSort(data, compare) {\r
4085         if (data.length <= 1) {\r
4086             // sorted\r
4087             return data;\r
4088         }\r
4089         var p = (data.length / 2) | 0;\r
4090         var left = data.slice(0, p);\r
4091         var right = data.slice(p);\r
4092         mergeSort(left, compare);\r
4093         mergeSort(right, compare);\r
4094         var leftIdx = 0;\r
4095         var rightIdx = 0;\r
4096         var i = 0;\r
4097         while (leftIdx < left.length && rightIdx < right.length) {\r
4098             var ret = compare(left[leftIdx], right[rightIdx]);\r
4099             if (ret <= 0) {\r
4100                 // smaller_equal -> take left to preserve order\r
4101                 data[i++] = left[leftIdx++];\r
4102             }\r
4103             else {\r
4104                 // greater -> take right\r
4105                 data[i++] = right[rightIdx++];\r
4106             }\r
4107         }\r
4108         while (leftIdx < left.length) {\r
4109             data[i++] = left[leftIdx++];\r
4110         }\r
4111         while (rightIdx < right.length) {\r
4112             data[i++] = right[rightIdx++];\r
4113         }\r
4114         return data;\r
4115     }\r
4116 })(TextDocument || (TextDocument = {}));\r
4117 var FullTextDocument = /** @class */ (function () {\r
4118     function FullTextDocument(uri, languageId, version, content) {\r
4119         this._uri = uri;\r
4120         this._languageId = languageId;\r
4121         this._version = version;\r
4122         this._content = content;\r
4123         this._lineOffsets = undefined;\r
4124     }\r
4125     Object.defineProperty(FullTextDocument.prototype, "uri", {\r
4126         get: function () {\r
4127             return this._uri;\r
4128         },\r
4129         enumerable: true,\r
4130         configurable: true\r
4131     });\r
4132     Object.defineProperty(FullTextDocument.prototype, "languageId", {\r
4133         get: function () {\r
4134             return this._languageId;\r
4135         },\r
4136         enumerable: true,\r
4137         configurable: true\r
4138     });\r
4139     Object.defineProperty(FullTextDocument.prototype, "version", {\r
4140         get: function () {\r
4141             return this._version;\r
4142         },\r
4143         enumerable: true,\r
4144         configurable: true\r
4145     });\r
4146     FullTextDocument.prototype.getText = function (range) {\r
4147         if (range) {\r
4148             var start = this.offsetAt(range.start);\r
4149             var end = this.offsetAt(range.end);\r
4150             return this._content.substring(start, end);\r
4151         }\r
4152         return this._content;\r
4153     };\r
4154     FullTextDocument.prototype.update = function (event, version) {\r
4155         this._content = event.text;\r
4156         this._version = version;\r
4157         this._lineOffsets = undefined;\r
4158     };\r
4159     FullTextDocument.prototype.getLineOffsets = function () {\r
4160         if (this._lineOffsets === undefined) {\r
4161             var lineOffsets = [];\r
4162             var text = this._content;\r
4163             var isLineStart = true;\r
4164             for (var i = 0; i < text.length; i++) {\r
4165                 if (isLineStart) {\r
4166                     lineOffsets.push(i);\r
4167                     isLineStart = false;\r
4168                 }\r
4169                 var ch = text.charAt(i);\r
4170                 isLineStart = (ch === '\r' || ch === '\n');\r
4171                 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {\r
4172                     i++;\r
4173                 }\r
4174             }\r
4175             if (isLineStart && text.length > 0) {\r
4176                 lineOffsets.push(text.length);\r
4177             }\r
4178             this._lineOffsets = lineOffsets;\r
4179         }\r
4180         return this._lineOffsets;\r
4181     };\r
4182     FullTextDocument.prototype.positionAt = function (offset) {\r
4183         offset = Math.max(Math.min(offset, this._content.length), 0);\r
4184         var lineOffsets = this.getLineOffsets();\r
4185         var low = 0, high = lineOffsets.length;\r
4186         if (high === 0) {\r
4187             return Position.create(0, offset);\r
4188         }\r
4189         while (low < high) {\r
4190             var mid = Math.floor((low + high) / 2);\r
4191             if (lineOffsets[mid] > offset) {\r
4192                 high = mid;\r
4193             }\r
4194             else {\r
4195                 low = mid + 1;\r
4196             }\r
4197         }\r
4198         // low is the least x for which the line offset is larger than the current offset\r
4199         // or array.length if no line offset is larger than the current offset\r
4200         var line = low - 1;\r
4201         return Position.create(line, offset - lineOffsets[line]);\r
4202     };\r
4203     FullTextDocument.prototype.offsetAt = function (position) {\r
4204         var lineOffsets = this.getLineOffsets();\r
4205         if (position.line >= lineOffsets.length) {\r
4206             return this._content.length;\r
4207         }\r
4208         else if (position.line < 0) {\r
4209             return 0;\r
4210         }\r
4211         var lineOffset = lineOffsets[position.line];\r
4212         var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;\r
4213         return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);\r
4214     };\r
4215     Object.defineProperty(FullTextDocument.prototype, "lineCount", {\r
4216         get: function () {\r
4217             return this.getLineOffsets().length;\r
4218         },\r
4219         enumerable: true,\r
4220         configurable: true\r
4221     });\r
4222     return FullTextDocument;\r
4223 }());\r
4224 var Is;\r
4225 (function (Is) {\r
4226     var toString = Object.prototype.toString;\r
4227     function defined(value) {\r
4228         return typeof value !== 'undefined';\r
4229     }\r
4230     Is.defined = defined;\r
4231     function undefined(value) {\r
4232         return typeof value === 'undefined';\r
4233     }\r
4234     Is.undefined = undefined;\r
4235     function boolean(value) {\r
4236         return value === true || value === false;\r
4237     }\r
4238     Is.boolean = boolean;\r
4239     function string(value) {\r
4240         return toString.call(value) === '[object String]';\r
4241     }\r
4242     Is.string = string;\r
4243     function number(value) {\r
4244         return toString.call(value) === '[object Number]';\r
4245     }\r
4246     Is.number = number;\r
4247     function func(value) {\r
4248         return toString.call(value) === '[object Function]';\r
4249     }\r
4250     Is.func = func;\r
4251     function objectLiteral(value) {\r
4252         // Strictly speaking class instances pass this check as well. Since the LSP\r
4253         // doesn't use classes we ignore this for now. If we do we need to add something\r
4254         // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
4255         return value !== null && typeof value === 'object';\r
4256     }\r
4257     Is.objectLiteral = objectLiteral;\r
4258     function typedArray(value, check) {\r
4259         return Array.isArray(value) && value.every(check);\r
4260     }\r
4261     Is.typedArray = typedArray;\r
4262 })(Is || (Is = {}));\r
4263
4264
4265 /***/ }),
4266 /* 19 */
4267 /***/ (function(module, exports, __webpack_require__) {
4268
4269 "use strict";
4270 /* --------------------------------------------------------------------------------------------\r
4271  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4272  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4273  * ------------------------------------------------------------------------------------------ */\r
4274 \r
4275 Object.defineProperty(exports, "__esModule", { value: true });\r
4276 const Is = __webpack_require__(20);\r
4277 const vscode_jsonrpc_1 = __webpack_require__(4);\r
4278 const messages_1 = __webpack_require__(21);\r
4279 const protocol_implementation_1 = __webpack_require__(22);\r
4280 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;\r
4281 const protocol_typeDefinition_1 = __webpack_require__(23);\r
4282 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;\r
4283 const protocol_workspaceFolders_1 = __webpack_require__(24);\r
4284 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;\r
4285 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;\r
4286 const protocol_configuration_1 = __webpack_require__(25);\r
4287 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;\r
4288 const protocol_colorProvider_1 = __webpack_require__(26);\r
4289 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;\r
4290 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;\r
4291 const protocol_foldingRange_1 = __webpack_require__(27);\r
4292 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;\r
4293 const protocol_declaration_1 = __webpack_require__(28);\r
4294 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;\r
4295 const protocol_selectionRange_1 = __webpack_require__(29);\r
4296 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;\r
4297 const protocol_progress_1 = __webpack_require__(30);\r
4298 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;\r
4299 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;\r
4300 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;\r
4301 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
4302 let __noDynamicImport;\r
4303 /**\r
4304  * The DocumentFilter namespace provides helper functions to work with\r
4305  * [DocumentFilter](#DocumentFilter) literals.\r
4306  */\r
4307 var DocumentFilter;\r
4308 (function (DocumentFilter) {\r
4309     function is(value) {\r
4310         const candidate = value;\r
4311         return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);\r
4312     }\r
4313     DocumentFilter.is = is;\r
4314 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));\r
4315 /**\r
4316  * The DocumentSelector namespace provides helper functions to work with\r
4317  * [DocumentSelector](#DocumentSelector)s.\r
4318  */\r
4319 var DocumentSelector;\r
4320 (function (DocumentSelector) {\r
4321     function is(value) {\r
4322         if (!Array.isArray(value)) {\r
4323             return false;\r
4324         }\r
4325         for (let elem of value) {\r
4326             if (!Is.string(elem) && !DocumentFilter.is(elem)) {\r
4327                 return false;\r
4328             }\r
4329         }\r
4330         return true;\r
4331     }\r
4332     DocumentSelector.is = is;\r
4333 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));\r
4334 /**\r
4335  * The `client/registerCapability` request is sent from the server to the client to register a new capability\r
4336  * handler on the client side.\r
4337  */\r
4338 var RegistrationRequest;\r
4339 (function (RegistrationRequest) {\r
4340     RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');\r
4341 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));\r
4342 /**\r
4343  * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability\r
4344  * handler on the client side.\r
4345  */\r
4346 var UnregistrationRequest;\r
4347 (function (UnregistrationRequest) {\r
4348     UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');\r
4349 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));\r
4350 var ResourceOperationKind;\r
4351 (function (ResourceOperationKind) {\r
4352     /**\r
4353      * Supports creating new files and folders.\r
4354      */\r
4355     ResourceOperationKind.Create = 'create';\r
4356     /**\r
4357      * Supports renaming existing files and folders.\r
4358      */\r
4359     ResourceOperationKind.Rename = 'rename';\r
4360     /**\r
4361      * Supports deleting existing files and folders.\r
4362      */\r
4363     ResourceOperationKind.Delete = 'delete';\r
4364 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));\r
4365 var FailureHandlingKind;\r
4366 (function (FailureHandlingKind) {\r
4367     /**\r
4368      * Applying the workspace change is simply aborted if one of the changes provided\r
4369      * fails. All operations executed before the failing operation stay executed.\r
4370      */\r
4371     FailureHandlingKind.Abort = 'abort';\r
4372     /**\r
4373      * All operations are executed transactional. That means they either all\r
4374      * succeed or no changes at all are applied to the workspace.\r
4375      */\r
4376     FailureHandlingKind.Transactional = 'transactional';\r
4377     /**\r
4378      * If the workspace edit contains only textual file changes they are executed transactional.\r
4379      * If resource changes (create, rename or delete file) are part of the change the failure\r
4380      * handling startegy is abort.\r
4381      */\r
4382     FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';\r
4383     /**\r
4384      * The client tries to undo the operations already executed. But there is no\r
4385      * guarantee that this is succeeding.\r
4386      */\r
4387     FailureHandlingKind.Undo = 'undo';\r
4388 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));\r
4389 /**\r
4390  * The StaticRegistrationOptions namespace provides helper functions to work with\r
4391  * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.\r
4392  */\r
4393 var StaticRegistrationOptions;\r
4394 (function (StaticRegistrationOptions) {\r
4395     function hasId(value) {\r
4396         const candidate = value;\r
4397         return candidate && Is.string(candidate.id) && candidate.id.length > 0;\r
4398     }\r
4399     StaticRegistrationOptions.hasId = hasId;\r
4400 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));\r
4401 /**\r
4402  * The TextDocumentRegistrationOptions namespace provides helper functions to work with\r
4403  * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.\r
4404  */\r
4405 var TextDocumentRegistrationOptions;\r
4406 (function (TextDocumentRegistrationOptions) {\r
4407     function is(value) {\r
4408         const candidate = value;\r
4409         return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));\r
4410     }\r
4411     TextDocumentRegistrationOptions.is = is;\r
4412 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));\r
4413 /**\r
4414  * The WorkDoneProgressOptions namespace provides helper functions to work with\r
4415  * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.\r
4416  */\r
4417 var WorkDoneProgressOptions;\r
4418 (function (WorkDoneProgressOptions) {\r
4419     function is(value) {\r
4420         const candidate = value;\r
4421         return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));\r
4422     }\r
4423     WorkDoneProgressOptions.is = is;\r
4424     function hasWorkDoneProgress(value) {\r
4425         const candidate = value;\r
4426         return candidate && Is.boolean(candidate.workDoneProgress);\r
4427     }\r
4428     WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;\r
4429 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));\r
4430 /**\r
4431  * The initialize request is sent from the client to the server.\r
4432  * It is sent once as the request after starting up the server.\r
4433  * The requests parameter is of type [InitializeParams](#InitializeParams)\r
4434  * the response if of type [InitializeResult](#InitializeResult) of a Thenable that\r
4435  * resolves to such.\r
4436  */\r
4437 var InitializeRequest;\r
4438 (function (InitializeRequest) {\r
4439     InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');\r
4440 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));\r
4441 /**\r
4442  * Known error codes for an `InitializeError`;\r
4443  */\r
4444 var InitializeError;\r
4445 (function (InitializeError) {\r
4446     /**\r
4447      * If the protocol version provided by the client can't be handled by the server.\r
4448      * @deprecated This initialize error got replaced by client capabilities. There is\r
4449      * no version handshake in version 3.0x\r
4450      */\r
4451     InitializeError.unknownProtocolVersion = 1;\r
4452 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));\r
4453 /**\r
4454  * The intialized notification is sent from the client to the\r
4455  * server after the client is fully initialized and the server\r
4456  * is allowed to send requests from the server to the client.\r
4457  */\r
4458 var InitializedNotification;\r
4459 (function (InitializedNotification) {\r
4460     InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');\r
4461 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));\r
4462 //---- Shutdown Method ----\r
4463 /**\r
4464  * A shutdown request is sent from the client to the server.\r
4465  * It is sent once when the client decides to shutdown the\r
4466  * server. The only notification that is sent after a shutdown request\r
4467  * is the exit event.\r
4468  */\r
4469 var ShutdownRequest;\r
4470 (function (ShutdownRequest) {\r
4471     ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');\r
4472 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));\r
4473 //---- Exit Notification ----\r
4474 /**\r
4475  * The exit event is sent from the client to the server to\r
4476  * ask the server to exit its process.\r
4477  */\r
4478 var ExitNotification;\r
4479 (function (ExitNotification) {\r
4480     ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');\r
4481 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));\r
4482 /**\r
4483  * The configuration change notification is sent from the client to the server\r
4484  * when the client's configuration has changed. The notification contains\r
4485  * the changed configuration as defined by the language client.\r
4486  */\r
4487 var DidChangeConfigurationNotification;\r
4488 (function (DidChangeConfigurationNotification) {\r
4489     DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');\r
4490 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));\r
4491 //---- Message show and log notifications ----\r
4492 /**\r
4493  * The message type\r
4494  */\r
4495 var MessageType;\r
4496 (function (MessageType) {\r
4497     /**\r
4498      * An error message.\r
4499      */\r
4500     MessageType.Error = 1;\r
4501     /**\r
4502      * A warning message.\r
4503      */\r
4504     MessageType.Warning = 2;\r
4505     /**\r
4506      * An information message.\r
4507      */\r
4508     MessageType.Info = 3;\r
4509     /**\r
4510      * A log message.\r
4511      */\r
4512     MessageType.Log = 4;\r
4513 })(MessageType = exports.MessageType || (exports.MessageType = {}));\r
4514 /**\r
4515  * The show message notification is sent from a server to a client to ask\r
4516  * the client to display a particular message in the user interface.\r
4517  */\r
4518 var ShowMessageNotification;\r
4519 (function (ShowMessageNotification) {\r
4520     ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');\r
4521 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));\r
4522 /**\r
4523  * The show message request is sent from the server to the client to show a message\r
4524  * and a set of options actions to the user.\r
4525  */\r
4526 var ShowMessageRequest;\r
4527 (function (ShowMessageRequest) {\r
4528     ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');\r
4529 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));\r
4530 /**\r
4531  * The log message notification is sent from the server to the client to ask\r
4532  * the client to log a particular message.\r
4533  */\r
4534 var LogMessageNotification;\r
4535 (function (LogMessageNotification) {\r
4536     LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');\r
4537 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));\r
4538 //---- Telemetry notification\r
4539 /**\r
4540  * The telemetry event notification is sent from the server to the client to ask\r
4541  * the client to log telemetry data.\r
4542  */\r
4543 var TelemetryEventNotification;\r
4544 (function (TelemetryEventNotification) {\r
4545     TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');\r
4546 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));\r
4547 /**\r
4548  * Defines how the host (editor) should sync\r
4549  * document changes to the language server.\r
4550  */\r
4551 var TextDocumentSyncKind;\r
4552 (function (TextDocumentSyncKind) {\r
4553     /**\r
4554      * Documents should not be synced at all.\r
4555      */\r
4556     TextDocumentSyncKind.None = 0;\r
4557     /**\r
4558      * Documents are synced by always sending the full content\r
4559      * of the document.\r
4560      */\r
4561     TextDocumentSyncKind.Full = 1;\r
4562     /**\r
4563      * Documents are synced by sending the full content on open.\r
4564      * After that only incremental updates to the document are\r
4565      * send.\r
4566      */\r
4567     TextDocumentSyncKind.Incremental = 2;\r
4568 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));\r
4569 /**\r
4570  * The document open notification is sent from the client to the server to signal\r
4571  * newly opened text documents. The document's truth is now managed by the client\r
4572  * and the server must not try to read the document's truth using the document's\r
4573  * uri. Open in this sense means it is managed by the client. It doesn't necessarily\r
4574  * mean that its content is presented in an editor. An open notification must not\r
4575  * be sent more than once without a corresponding close notification send before.\r
4576  * This means open and close notification must be balanced and the max open count\r
4577  * is one.\r
4578  */\r
4579 var DidOpenTextDocumentNotification;\r
4580 (function (DidOpenTextDocumentNotification) {\r
4581     DidOpenTextDocumentNotification.method = 'textDocument/didOpen';\r
4582     DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);\r
4583 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));\r
4584 /**\r
4585  * The document change notification is sent from the client to the server to signal\r
4586  * changes to a text document.\r
4587  */\r
4588 var DidChangeTextDocumentNotification;\r
4589 (function (DidChangeTextDocumentNotification) {\r
4590     DidChangeTextDocumentNotification.method = 'textDocument/didChange';\r
4591     DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);\r
4592 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));\r
4593 /**\r
4594  * The document close notification is sent from the client to the server when\r
4595  * the document got closed in the client. The document's truth now exists where\r
4596  * the document's uri points to (e.g. if the document's uri is a file uri the\r
4597  * truth now exists on disk). As with the open notification the close notification\r
4598  * is about managing the document's content. Receiving a close notification\r
4599  * doesn't mean that the document was open in an editor before. A close\r
4600  * notification requires a previous open notification to be sent.\r
4601  */\r
4602 var DidCloseTextDocumentNotification;\r
4603 (function (DidCloseTextDocumentNotification) {\r
4604     DidCloseTextDocumentNotification.method = 'textDocument/didClose';\r
4605     DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);\r
4606 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));\r
4607 /**\r
4608  * The document save notification is sent from the client to the server when\r
4609  * the document got saved in the client.\r
4610  */\r
4611 var DidSaveTextDocumentNotification;\r
4612 (function (DidSaveTextDocumentNotification) {\r
4613     DidSaveTextDocumentNotification.method = 'textDocument/didSave';\r
4614     DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);\r
4615 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));\r
4616 /**\r
4617  * Represents reasons why a text document is saved.\r
4618  */\r
4619 var TextDocumentSaveReason;\r
4620 (function (TextDocumentSaveReason) {\r
4621     /**\r
4622      * Manually triggered, e.g. by the user pressing save, by starting debugging,\r
4623      * or by an API call.\r
4624      */\r
4625     TextDocumentSaveReason.Manual = 1;\r
4626     /**\r
4627      * Automatic after a delay.\r
4628      */\r
4629     TextDocumentSaveReason.AfterDelay = 2;\r
4630     /**\r
4631      * When the editor lost focus.\r
4632      */\r
4633     TextDocumentSaveReason.FocusOut = 3;\r
4634 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));\r
4635 /**\r
4636  * A document will save notification is sent from the client to the server before\r
4637  * the document is actually saved.\r
4638  */\r
4639 var WillSaveTextDocumentNotification;\r
4640 (function (WillSaveTextDocumentNotification) {\r
4641     WillSaveTextDocumentNotification.method = 'textDocument/willSave';\r
4642     WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);\r
4643 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));\r
4644 /**\r
4645  * A document will save request is sent from the client to the server before\r
4646  * the document is actually saved. The request can return an array of TextEdits\r
4647  * which will be applied to the text document before it is saved. Please note that\r
4648  * clients might drop results if computing the text edits took too long or if a\r
4649  * server constantly fails on this request. This is done to keep the save fast and\r
4650  * reliable.\r
4651  */\r
4652 var WillSaveTextDocumentWaitUntilRequest;\r
4653 (function (WillSaveTextDocumentWaitUntilRequest) {\r
4654     WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';\r
4655     WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);\r
4656 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));\r
4657 /**\r
4658  * The watched files notification is sent from the client to the server when\r
4659  * the client detects changes to file watched by the language client.\r
4660  */\r
4661 var DidChangeWatchedFilesNotification;\r
4662 (function (DidChangeWatchedFilesNotification) {\r
4663     DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');\r
4664 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));\r
4665 /**\r
4666  * The file event type\r
4667  */\r
4668 var FileChangeType;\r
4669 (function (FileChangeType) {\r
4670     /**\r
4671      * The file got created.\r
4672      */\r
4673     FileChangeType.Created = 1;\r
4674     /**\r
4675      * The file got changed.\r
4676      */\r
4677     FileChangeType.Changed = 2;\r
4678     /**\r
4679      * The file got deleted.\r
4680      */\r
4681     FileChangeType.Deleted = 3;\r
4682 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));\r
4683 var WatchKind;\r
4684 (function (WatchKind) {\r
4685     /**\r
4686      * Interested in create events.\r
4687      */\r
4688     WatchKind.Create = 1;\r
4689     /**\r
4690      * Interested in change events\r
4691      */\r
4692     WatchKind.Change = 2;\r
4693     /**\r
4694      * Interested in delete events\r
4695      */\r
4696     WatchKind.Delete = 4;\r
4697 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));\r
4698 /**\r
4699  * Diagnostics notification are sent from the server to the client to signal\r
4700  * results of validation runs.\r
4701  */\r
4702 var PublishDiagnosticsNotification;\r
4703 (function (PublishDiagnosticsNotification) {\r
4704     PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');\r
4705 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));\r
4706 /**\r
4707  * How a completion was triggered\r
4708  */\r
4709 var CompletionTriggerKind;\r
4710 (function (CompletionTriggerKind) {\r
4711     /**\r
4712      * Completion was triggered by typing an identifier (24x7 code\r
4713      * complete), manual invocation (e.g Ctrl+Space) or via API.\r
4714      */\r
4715     CompletionTriggerKind.Invoked = 1;\r
4716     /**\r
4717      * Completion was triggered by a trigger character specified by\r
4718      * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.\r
4719      */\r
4720     CompletionTriggerKind.TriggerCharacter = 2;\r
4721     /**\r
4722      * Completion was re-triggered as current completion list is incomplete\r
4723      */\r
4724     CompletionTriggerKind.TriggerForIncompleteCompletions = 3;\r
4725 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));\r
4726 /**\r
4727  * Request to request completion at a given text document position. The request's\r
4728  * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response\r
4729  * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)\r
4730  * or a Thenable that resolves to such.\r
4731  *\r
4732  * The request can delay the computation of the [`detail`](#CompletionItem.detail)\r
4733  * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`\r
4734  * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,\r
4735  * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.\r
4736  */\r
4737 var CompletionRequest;\r
4738 (function (CompletionRequest) {\r
4739     CompletionRequest.method = 'textDocument/completion';\r
4740     CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);\r
4741     /** @deprecated Use CompletionRequest.type */\r
4742     CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4743 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));\r
4744 /**\r
4745  * Request to resolve additional information for a given completion item.The request's\r
4746  * parameter is of type [CompletionItem](#CompletionItem) the response\r
4747  * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.\r
4748  */\r
4749 var CompletionResolveRequest;\r
4750 (function (CompletionResolveRequest) {\r
4751     CompletionResolveRequest.method = 'completionItem/resolve';\r
4752     CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);\r
4753 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));\r
4754 /**\r
4755  * Request to request hover information at a given text document position. The request's\r
4756  * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of\r
4757  * type [Hover](#Hover) or a Thenable that resolves to such.\r
4758  */\r
4759 var HoverRequest;\r
4760 (function (HoverRequest) {\r
4761     HoverRequest.method = 'textDocument/hover';\r
4762     HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);\r
4763 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));\r
4764 /**\r
4765  * How a signature help was triggered.\r
4766  *\r
4767  * @since 3.15.0\r
4768  */\r
4769 var SignatureHelpTriggerKind;\r
4770 (function (SignatureHelpTriggerKind) {\r
4771     /**\r
4772      * Signature help was invoked manually by the user or by a command.\r
4773      */\r
4774     SignatureHelpTriggerKind.Invoked = 1;\r
4775     /**\r
4776      * Signature help was triggered by a trigger character.\r
4777      */\r
4778     SignatureHelpTriggerKind.TriggerCharacter = 2;\r
4779     /**\r
4780      * Signature help was triggered by the cursor moving or by the document content changing.\r
4781      */\r
4782     SignatureHelpTriggerKind.ContentChange = 3;\r
4783 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));\r
4784 var SignatureHelpRequest;\r
4785 (function (SignatureHelpRequest) {\r
4786     SignatureHelpRequest.method = 'textDocument/signatureHelp';\r
4787     SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);\r
4788 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));\r
4789 /**\r
4790  * A request to resolve the definition location of a symbol at a given text\r
4791  * document position. The request's parameter is of type [TextDocumentPosition]\r
4792  * (#TextDocumentPosition) the response is of either type [Definition](#Definition)\r
4793  * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves\r
4794  * to such.\r
4795  */\r
4796 var DefinitionRequest;\r
4797 (function (DefinitionRequest) {\r
4798     DefinitionRequest.method = 'textDocument/definition';\r
4799     DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);\r
4800     /** @deprecated Use DefinitionRequest.type */\r
4801     DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4802 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));\r
4803 /**\r
4804  * A request to resolve project-wide references for the symbol denoted\r
4805  * by the given text document position. The request's parameter is of\r
4806  * type [ReferenceParams](#ReferenceParams) the response is of type\r
4807  * [Location[]](#Location) or a Thenable that resolves to such.\r
4808  */\r
4809 var ReferencesRequest;\r
4810 (function (ReferencesRequest) {\r
4811     ReferencesRequest.method = 'textDocument/references';\r
4812     ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);\r
4813     /** @deprecated Use ReferencesRequest.type */\r
4814     ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4815 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));\r
4816 /**\r
4817  * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given\r
4818  * text document position. The request's parameter is of type [TextDocumentPosition]\r
4819  * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]\r
4820  * (#DocumentHighlight) or a Thenable that resolves to such.\r
4821  */\r
4822 var DocumentHighlightRequest;\r
4823 (function (DocumentHighlightRequest) {\r
4824     DocumentHighlightRequest.method = 'textDocument/documentHighlight';\r
4825     DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);\r
4826     /** @deprecated Use DocumentHighlightRequest.type */\r
4827     DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4828 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));\r
4829 /**\r
4830  * A request to list all symbols found in a given text document. The request's\r
4831  * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the\r
4832  * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable\r
4833  * that resolves to such.\r
4834  */\r
4835 var DocumentSymbolRequest;\r
4836 (function (DocumentSymbolRequest) {\r
4837     DocumentSymbolRequest.method = 'textDocument/documentSymbol';\r
4838     DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);\r
4839     /** @deprecated Use DocumentSymbolRequest.type */\r
4840     DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4841 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));\r
4842 /**\r
4843  * A request to provide commands for the given text document and range.\r
4844  */\r
4845 var CodeActionRequest;\r
4846 (function (CodeActionRequest) {\r
4847     CodeActionRequest.method = 'textDocument/codeAction';\r
4848     CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);\r
4849     /** @deprecated Use CodeActionRequest.type */\r
4850     CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4851 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));\r
4852 /**\r
4853  * A request to list project-wide symbols matching the query string given\r
4854  * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is\r
4855  * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that\r
4856  * resolves to such.\r
4857  */\r
4858 var WorkspaceSymbolRequest;\r
4859 (function (WorkspaceSymbolRequest) {\r
4860     WorkspaceSymbolRequest.method = 'workspace/symbol';\r
4861     WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);\r
4862     /** @deprecated Use WorkspaceSymbolRequest.type */\r
4863     WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4864 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));\r
4865 /**\r
4866  * A request to provide code lens for the given text document.\r
4867  */\r
4868 var CodeLensRequest;\r
4869 (function (CodeLensRequest) {\r
4870     CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');\r
4871     /** @deprecated Use CodeLensRequest.type */\r
4872     CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4873 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));\r
4874 /**\r
4875  * A request to resolve a command for a given code lens.\r
4876  */\r
4877 var CodeLensResolveRequest;\r
4878 (function (CodeLensResolveRequest) {\r
4879     CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');\r
4880 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));\r
4881 /**\r
4882  * A request to provide document links\r
4883  */\r
4884 var DocumentLinkRequest;\r
4885 (function (DocumentLinkRequest) {\r
4886     DocumentLinkRequest.method = 'textDocument/documentLink';\r
4887     DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);\r
4888     /** @deprecated Use DocumentLinkRequest.type */\r
4889     DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
4890 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));\r
4891 /**\r
4892  * Request to resolve additional information for a given document link. The request's\r
4893  * parameter is of type [DocumentLink](#DocumentLink) the response\r
4894  * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.\r
4895  */\r
4896 var DocumentLinkResolveRequest;\r
4897 (function (DocumentLinkResolveRequest) {\r
4898     DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');\r
4899 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));\r
4900 /**\r
4901  * A request to to format a whole document.\r
4902  */\r
4903 var DocumentFormattingRequest;\r
4904 (function (DocumentFormattingRequest) {\r
4905     DocumentFormattingRequest.method = 'textDocument/formatting';\r
4906     DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);\r
4907 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));\r
4908 /**\r
4909  * A request to to format a range in a document.\r
4910  */\r
4911 var DocumentRangeFormattingRequest;\r
4912 (function (DocumentRangeFormattingRequest) {\r
4913     DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';\r
4914     DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);\r
4915 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));\r
4916 /**\r
4917  * A request to format a document on type.\r
4918  */\r
4919 var DocumentOnTypeFormattingRequest;\r
4920 (function (DocumentOnTypeFormattingRequest) {\r
4921     DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';\r
4922     DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);\r
4923 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));\r
4924 /**\r
4925  * A request to rename a symbol.\r
4926  */\r
4927 var RenameRequest;\r
4928 (function (RenameRequest) {\r
4929     RenameRequest.method = 'textDocument/rename';\r
4930     RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);\r
4931 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));\r
4932 /**\r
4933  * A request to test and perform the setup necessary for a rename.\r
4934  */\r
4935 var PrepareRenameRequest;\r
4936 (function (PrepareRenameRequest) {\r
4937     PrepareRenameRequest.method = 'textDocument/prepareRename';\r
4938     PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);\r
4939 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));\r
4940 /**\r
4941  * A request send from the client to the server to execute a command. The request might return\r
4942  * a workspace edit which the client will apply to the workspace.\r
4943  */\r
4944 var ExecuteCommandRequest;\r
4945 (function (ExecuteCommandRequest) {\r
4946     ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');\r
4947 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));\r
4948 /**\r
4949  * A request sent from the server to the client to modified certain resources.\r
4950  */\r
4951 var ApplyWorkspaceEditRequest;\r
4952 (function (ApplyWorkspaceEditRequest) {\r
4953     ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');\r
4954 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));\r
4955
4956
4957 /***/ }),
4958 /* 20 */
4959 /***/ (function(module, exports, __webpack_require__) {
4960
4961 "use strict";
4962 /* --------------------------------------------------------------------------------------------\r
4963  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4964  * Licensed under the MIT License. See License.txt in the project root for license information.\r
4965  * ------------------------------------------------------------------------------------------ */\r
4966 \r
4967 Object.defineProperty(exports, "__esModule", { value: true });\r
4968 function boolean(value) {\r
4969     return value === true || value === false;\r
4970 }\r
4971 exports.boolean = boolean;\r
4972 function string(value) {\r
4973     return typeof value === 'string' || value instanceof String;\r
4974 }\r
4975 exports.string = string;\r
4976 function number(value) {\r
4977     return typeof value === 'number' || value instanceof Number;\r
4978 }\r
4979 exports.number = number;\r
4980 function error(value) {\r
4981     return value instanceof Error;\r
4982 }\r
4983 exports.error = error;\r
4984 function func(value) {\r
4985     return typeof value === 'function';\r
4986 }\r
4987 exports.func = func;\r
4988 function array(value) {\r
4989     return Array.isArray(value);\r
4990 }\r
4991 exports.array = array;\r
4992 function stringArray(value) {\r
4993     return array(value) && value.every(elem => string(elem));\r
4994 }\r
4995 exports.stringArray = stringArray;\r
4996 function typedArray(value, check) {\r
4997     return Array.isArray(value) && value.every(check);\r
4998 }\r
4999 exports.typedArray = typedArray;\r
5000 function objectLiteral(value) {\r
5001     // Strictly speaking class instances pass this check as well. Since the LSP\r
5002     // doesn't use classes we ignore this for now. If we do we need to add something\r
5003     // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`\r
5004     return value !== null && typeof value === 'object';\r
5005 }\r
5006 exports.objectLiteral = objectLiteral;\r
5007
5008
5009 /***/ }),
5010 /* 21 */
5011 /***/ (function(module, exports, __webpack_require__) {
5012
5013 "use strict";
5014 /* --------------------------------------------------------------------------------------------\r
5015  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5016  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5017  * ------------------------------------------------------------------------------------------ */\r
5018 \r
5019 Object.defineProperty(exports, "__esModule", { value: true });\r
5020 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5021 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {\r
5022     constructor(method) {\r
5023         super(method);\r
5024     }\r
5025 }\r
5026 exports.ProtocolRequestType0 = ProtocolRequestType0;\r
5027 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {\r
5028     constructor(method) {\r
5029         super(method);\r
5030     }\r
5031 }\r
5032 exports.ProtocolRequestType = ProtocolRequestType;\r
5033 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {\r
5034     constructor(method) {\r
5035         super(method);\r
5036     }\r
5037 }\r
5038 exports.ProtocolNotificationType = ProtocolNotificationType;\r
5039 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {\r
5040     constructor(method) {\r
5041         super(method);\r
5042     }\r
5043 }\r
5044 exports.ProtocolNotificationType0 = ProtocolNotificationType0;\r
5045
5046
5047 /***/ }),
5048 /* 22 */
5049 /***/ (function(module, exports, __webpack_require__) {
5050
5051 "use strict";
5052 /* --------------------------------------------------------------------------------------------\r
5053  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5054  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5055  * ------------------------------------------------------------------------------------------ */\r
5056 \r
5057 Object.defineProperty(exports, "__esModule", { value: true });\r
5058 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5059 const messages_1 = __webpack_require__(21);\r
5060 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
5061 let __noDynamicImport;\r
5062 /**\r
5063  * A request to resolve the implementation locations of a symbol at a given text\r
5064  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
5065  * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
5066  * Thenable that resolves to such.\r
5067  */\r
5068 var ImplementationRequest;\r
5069 (function (ImplementationRequest) {\r
5070     ImplementationRequest.method = 'textDocument/implementation';\r
5071     ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);\r
5072     /** @deprecated Use ImplementationRequest.type */\r
5073     ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5074 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));\r
5075
5076
5077 /***/ }),
5078 /* 23 */
5079 /***/ (function(module, exports, __webpack_require__) {
5080
5081 "use strict";
5082 /* --------------------------------------------------------------------------------------------\r
5083  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5084  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5085  * ------------------------------------------------------------------------------------------ */\r
5086 \r
5087 Object.defineProperty(exports, "__esModule", { value: true });\r
5088 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5089 const messages_1 = __webpack_require__(21);\r
5090 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
5091 let __noDynamicImport;\r
5092 /**\r
5093  * A request to resolve the type definition locations of a symbol at a given text\r
5094  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
5095  * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\r
5096  * Thenable that resolves to such.\r
5097  */\r
5098 var TypeDefinitionRequest;\r
5099 (function (TypeDefinitionRequest) {\r
5100     TypeDefinitionRequest.method = 'textDocument/typeDefinition';\r
5101     TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);\r
5102     /** @deprecated Use TypeDefinitionRequest.type */\r
5103     TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5104 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));\r
5105
5106
5107 /***/ }),
5108 /* 24 */
5109 /***/ (function(module, exports, __webpack_require__) {
5110
5111 "use strict";
5112 /* --------------------------------------------------------------------------------------------\r
5113  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5114  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5115  * ------------------------------------------------------------------------------------------ */\r
5116 \r
5117 Object.defineProperty(exports, "__esModule", { value: true });\r
5118 const messages_1 = __webpack_require__(21);\r
5119 /**\r
5120  * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.\r
5121  */\r
5122 var WorkspaceFoldersRequest;\r
5123 (function (WorkspaceFoldersRequest) {\r
5124     WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');\r
5125 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));\r
5126 /**\r
5127  * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace\r
5128  * folder configuration changes.\r
5129  */\r
5130 var DidChangeWorkspaceFoldersNotification;\r
5131 (function (DidChangeWorkspaceFoldersNotification) {\r
5132     DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');\r
5133 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));\r
5134
5135
5136 /***/ }),
5137 /* 25 */
5138 /***/ (function(module, exports, __webpack_require__) {
5139
5140 "use strict";
5141 /* --------------------------------------------------------------------------------------------\r
5142  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5143  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5144  * ------------------------------------------------------------------------------------------ */\r
5145 \r
5146 Object.defineProperty(exports, "__esModule", { value: true });\r
5147 const messages_1 = __webpack_require__(21);\r
5148 /**\r
5149  * The 'workspace/configuration' request is sent from the server to the client to fetch a certain\r
5150  * configuration setting.\r
5151  *\r
5152  * This pull model replaces the old push model were the client signaled configuration change via an\r
5153  * event. If the server still needs to react to configuration changes (since the server caches the\r
5154  * result of `workspace/configuration` requests) the server should register for an empty configuration\r
5155  * change event and empty the cache if such an event is received.\r
5156  */\r
5157 var ConfigurationRequest;\r
5158 (function (ConfigurationRequest) {\r
5159     ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');\r
5160 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));\r
5161
5162
5163 /***/ }),
5164 /* 26 */
5165 /***/ (function(module, exports, __webpack_require__) {
5166
5167 "use strict";
5168 /* --------------------------------------------------------------------------------------------\r
5169  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5170  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5171  * ------------------------------------------------------------------------------------------ */\r
5172 \r
5173 Object.defineProperty(exports, "__esModule", { value: true });\r
5174 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5175 const messages_1 = __webpack_require__(21);\r
5176 /**\r
5177  * A request to list all color symbols found in a given text document. The request's\r
5178  * parameter is of type [DocumentColorParams](#DocumentColorParams) the\r
5179  * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
5180  * that resolves to such.\r
5181  */\r
5182 var DocumentColorRequest;\r
5183 (function (DocumentColorRequest) {\r
5184     DocumentColorRequest.method = 'textDocument/documentColor';\r
5185     DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);\r
5186     /** @deprecated Use DocumentColorRequest.type */\r
5187     DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5188 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));\r
5189 /**\r
5190  * A request to list all presentation for a color. The request's\r
5191  * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the\r
5192  * response is of type [ColorInformation[]](#ColorInformation) or a Thenable\r
5193  * that resolves to such.\r
5194  */\r
5195 var ColorPresentationRequest;\r
5196 (function (ColorPresentationRequest) {\r
5197     ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');\r
5198 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));\r
5199
5200
5201 /***/ }),
5202 /* 27 */
5203 /***/ (function(module, exports, __webpack_require__) {
5204
5205 "use strict";
5206 \r
5207 /*---------------------------------------------------------------------------------------------\r
5208  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
5209  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
5210  *--------------------------------------------------------------------------------------------*/\r
5211 Object.defineProperty(exports, "__esModule", { value: true });\r
5212 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5213 const messages_1 = __webpack_require__(21);\r
5214 /**\r
5215  * Enum of known range kinds\r
5216  */\r
5217 var FoldingRangeKind;\r
5218 (function (FoldingRangeKind) {\r
5219     /**\r
5220      * Folding range for a comment\r
5221      */\r
5222     FoldingRangeKind["Comment"] = "comment";\r
5223     /**\r
5224      * Folding range for a imports or includes\r
5225      */\r
5226     FoldingRangeKind["Imports"] = "imports";\r
5227     /**\r
5228      * Folding range for a region (e.g. `#region`)\r
5229      */\r
5230     FoldingRangeKind["Region"] = "region";\r
5231 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));\r
5232 /**\r
5233  * A request to provide folding ranges in a document. The request's\r
5234  * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the\r
5235  * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable\r
5236  * that resolves to such.\r
5237  */\r
5238 var FoldingRangeRequest;\r
5239 (function (FoldingRangeRequest) {\r
5240     FoldingRangeRequest.method = 'textDocument/foldingRange';\r
5241     FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);\r
5242     /** @deprecated Use FoldingRangeRequest.type */\r
5243     FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5244 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));\r
5245
5246
5247 /***/ }),
5248 /* 28 */
5249 /***/ (function(module, exports, __webpack_require__) {
5250
5251 "use strict";
5252 /* --------------------------------------------------------------------------------------------\r
5253  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5254  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5255  * ------------------------------------------------------------------------------------------ */\r
5256 \r
5257 Object.defineProperty(exports, "__esModule", { value: true });\r
5258 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5259 const messages_1 = __webpack_require__(21);\r
5260 // @ts-ignore: to avoid inlining LocatioLink as dynamic import\r
5261 let __noDynamicImport;\r
5262 /**\r
5263  * A request to resolve the type definition locations of a symbol at a given text\r
5264  * document position. The request's parameter is of type [TextDocumentPositioParams]\r
5265  * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)\r
5266  * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves\r
5267  * to such.\r
5268  */\r
5269 var DeclarationRequest;\r
5270 (function (DeclarationRequest) {\r
5271     DeclarationRequest.method = 'textDocument/declaration';\r
5272     DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);\r
5273     /** @deprecated Use DeclarationRequest.type */\r
5274     DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5275 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));\r
5276
5277
5278 /***/ }),
5279 /* 29 */
5280 /***/ (function(module, exports, __webpack_require__) {
5281
5282 "use strict";
5283 \r
5284 /*---------------------------------------------------------------------------------------------\r
5285  *  Copyright (c) Microsoft Corporation. All rights reserved.\r
5286  *  Licensed under the MIT License. See License.txt in the project root for license information.\r
5287  *--------------------------------------------------------------------------------------------*/\r
5288 Object.defineProperty(exports, "__esModule", { value: true });\r
5289 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5290 const messages_1 = __webpack_require__(21);\r
5291 /**\r
5292  * A request to provide selection ranges in a document. The request's\r
5293  * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the\r
5294  * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable\r
5295  * that resolves to such.\r
5296  */\r
5297 var SelectionRangeRequest;\r
5298 (function (SelectionRangeRequest) {\r
5299     SelectionRangeRequest.method = 'textDocument/selectionRange';\r
5300     SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);\r
5301     /** @deprecated  Use SelectionRangeRequest.type */\r
5302     SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();\r
5303 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));\r
5304
5305
5306 /***/ }),
5307 /* 30 */
5308 /***/ (function(module, exports, __webpack_require__) {
5309
5310 "use strict";
5311 /* --------------------------------------------------------------------------------------------\r
5312  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5313  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5314  * ------------------------------------------------------------------------------------------ */\r
5315 \r
5316 Object.defineProperty(exports, "__esModule", { value: true });\r
5317 const vscode_jsonrpc_1 = __webpack_require__(4);\r
5318 const messages_1 = __webpack_require__(21);\r
5319 var WorkDoneProgress;\r
5320 (function (WorkDoneProgress) {\r
5321     WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();\r
5322 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));\r
5323 /**\r
5324  * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress\r
5325  * reporting from the server.\r
5326  */\r
5327 var WorkDoneProgressCreateRequest;\r
5328 (function (WorkDoneProgressCreateRequest) {\r
5329     WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');\r
5330 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));\r
5331 /**\r
5332  * The `window/workDoneProgress/cancel` notification is sent from  the client to the server to cancel a progress\r
5333  * initiated on the server side.\r
5334  */\r
5335 var WorkDoneProgressCancelNotification;\r
5336 (function (WorkDoneProgressCancelNotification) {\r
5337     WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');\r
5338 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));\r
5339
5340
5341 /***/ }),
5342 /* 31 */
5343 /***/ (function(module, exports, __webpack_require__) {
5344
5345 "use strict";
5346 /* --------------------------------------------------------------------------------------------\r
5347  * Copyright (c) TypeFox and others. All rights reserved.\r
5348  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5349  * ------------------------------------------------------------------------------------------ */\r
5350 \r
5351 Object.defineProperty(exports, "__esModule", { value: true });\r
5352 const messages_1 = __webpack_require__(21);\r
5353 /**\r
5354  * A request to result a `CallHierarchyItem` in a document at a given position.\r
5355  * Can be used as an input to a incoming or outgoing call hierarchy.\r
5356  *\r
5357  * @since 3.16.0 - Proposed state\r
5358  */\r
5359 var CallHierarchyPrepareRequest;\r
5360 (function (CallHierarchyPrepareRequest) {\r
5361     CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';\r
5362     CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);\r
5363 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));\r
5364 /**\r
5365  * A request to resolve the incoming calls for a given `CallHierarchyItem`.\r
5366  *\r
5367  * @since 3.16.0 - Proposed state\r
5368  */\r
5369 var CallHierarchyIncomingCallsRequest;\r
5370 (function (CallHierarchyIncomingCallsRequest) {\r
5371     CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';\r
5372     CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);\r
5373 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));\r
5374 /**\r
5375  * A request to resolve the outgoing calls for a given `CallHierarchyItem`.\r
5376  *\r
5377  * @since 3.16.0 - Proposed state\r
5378  */\r
5379 var CallHierarchyOutgoingCallsRequest;\r
5380 (function (CallHierarchyOutgoingCallsRequest) {\r
5381     CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';\r
5382     CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);\r
5383 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));\r
5384
5385
5386 /***/ }),
5387 /* 32 */
5388 /***/ (function(module, exports, __webpack_require__) {
5389
5390 "use strict";
5391 /* --------------------------------------------------------------------------------------------\r
5392  * Copyright (c) Microsoft Corporation. All rights reserved.\r
5393  * Licensed under the MIT License. See License.txt in the project root for license information.\r
5394  * ------------------------------------------------------------------------------------------ */\r
5395 \r
5396 Object.defineProperty(exports, "__esModule", { value: true });\r
5397 const messages_1 = __webpack_require__(21);\r
5398 /**\r
5399  * A set of predefined token types. This set is not fixed\r
5400  * an clients can specify additional token types via the\r
5401  * corresponding client capabilities.\r
5402  *\r
5403  * @since 3.16.0 - Proposed state\r
5404  */\r
5405 var SemanticTokenTypes;\r
5406 (function (SemanticTokenTypes) {\r
5407     SemanticTokenTypes["comment"] = "comment";\r
5408     SemanticTokenTypes["keyword"] = "keyword";\r
5409     SemanticTokenTypes["string"] = "string";\r
5410     SemanticTokenTypes["number"] = "number";\r
5411     SemanticTokenTypes["regexp"] = "regexp";\r
5412     SemanticTokenTypes["operator"] = "operator";\r
5413     SemanticTokenTypes["namespace"] = "namespace";\r
5414     SemanticTokenTypes["type"] = "type";\r
5415     SemanticTokenTypes["struct"] = "struct";\r
5416     SemanticTokenTypes["class"] = "class";\r
5417     SemanticTokenTypes["interface"] = "interface";\r
5418     SemanticTokenTypes["enum"] = "enum";\r
5419     SemanticTokenTypes["typeParameter"] = "typeParameter";\r
5420     SemanticTokenTypes["function"] = "function";\r
5421     SemanticTokenTypes["member"] = "member";\r
5422     SemanticTokenTypes["property"] = "property";\r
5423     SemanticTokenTypes["macro"] = "macro";\r
5424     SemanticTokenTypes["variable"] = "variable";\r
5425     SemanticTokenTypes["parameter"] = "parameter";\r
5426     SemanticTokenTypes["label"] = "label";\r
5427 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));\r
5428 /**\r
5429  * A set of predefined token modifiers. This set is not fixed\r
5430  * an clients can specify additional token types via the\r
5431  * corresponding client capabilities.\r
5432  *\r
5433  * @since 3.16.0 - Proposed state\r
5434  */\r
5435 var SemanticTokenModifiers;\r
5436 (function (SemanticTokenModifiers) {\r
5437     SemanticTokenModifiers["documentation"] = "documentation";\r
5438     SemanticTokenModifiers["declaration"] = "declaration";\r
5439     SemanticTokenModifiers["definition"] = "definition";\r
5440     SemanticTokenModifiers["reference"] = "reference";\r
5441     SemanticTokenModifiers["static"] = "static";\r
5442     SemanticTokenModifiers["abstract"] = "abstract";\r
5443     SemanticTokenModifiers["deprecated"] = "deprecated";\r
5444     SemanticTokenModifiers["async"] = "async";\r
5445     SemanticTokenModifiers["volatile"] = "volatile";\r
5446     SemanticTokenModifiers["readonly"] = "readonly";\r
5447 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));\r
5448 /**\r
5449  * @since 3.16.0 - Proposed state\r
5450  */\r
5451 var SemanticTokens;\r
5452 (function (SemanticTokens) {\r
5453     function is(value) {\r
5454         const candidate = value;\r
5455         return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&\r
5456             Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');\r
5457     }\r
5458     SemanticTokens.is = is;\r
5459 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));\r
5460 /**\r
5461  * @since 3.16.0 - Proposed state\r
5462  */\r
5463 var SemanticTokensRequest;\r
5464 (function (SemanticTokensRequest) {\r
5465     SemanticTokensRequest.method = 'textDocument/semanticTokens';\r
5466     SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);\r
5467 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));\r
5468 /**\r
5469  * @since 3.16.0 - Proposed state\r
5470  */\r
5471 var SemanticTokensEditsRequest;\r
5472 (function (SemanticTokensEditsRequest) {\r
5473     SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';\r
5474     SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);\r
5475 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));\r
5476 /**\r
5477  * @since 3.16.0 - Proposed state\r
5478  */\r
5479 var SemanticTokensRangeRequest;\r
5480 (function (SemanticTokensRangeRequest) {\r
5481     SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';\r
5482     SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);\r
5483 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));\r
5484
5485
5486 /***/ }),
5487 /* 33 */
5488 /***/ (function(module, exports, __webpack_require__) {
5489
5490 "use strict";
5491
5492 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5493     if (k2 === undefined) k2 = k;
5494     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5495 }) : (function(o, m, k, k2) {
5496     if (k2 === undefined) k2 = k;
5497     o[k2] = m[k];
5498 }));
5499 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5500     Object.defineProperty(o, "default", { enumerable: true, value: v });
5501 }) : function(o, v) {
5502     o["default"] = v;
5503 });
5504 var __importStar = (this && this.__importStar) || function (mod) {
5505     if (mod && mod.__esModule) return mod;
5506     var result = {};
5507     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5508     __setModuleDefault(result, mod);
5509     return result;
5510 };
5511 var __importDefault = (this && this.__importDefault) || function (mod) {
5512     return (mod && mod.__esModule) ? mod : { "default": mod };
5513 };
5514 Object.defineProperty(exports, "__esModule", { value: true });
5515 /*---------------------------------------------------------------------------------------------
5516  *  Copyright (c) Microsoft Corporation. All rights reserved.
5517  *  Licensed under the MIT License. See License.txt in the project root for license information.
5518  *--------------------------------------------------------------------------------------------*/
5519 const coc_nvim_1 = __webpack_require__(1);
5520 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5521 const languageProvider_1 = __importDefault(__webpack_require__(34));
5522 const PConst = __importStar(__webpack_require__(39));
5523 const fileConfigurationManager_1 = __importDefault(__webpack_require__(113));
5524 const typescriptServiceClient_1 = __importDefault(__webpack_require__(114));
5525 const typeConverters = __importStar(__webpack_require__(37));
5526 const typingsStatus_1 = __importStar(__webpack_require__(137));
5527 const arrays_1 = __webpack_require__(91);
5528 const watchBuild_1 = __importDefault(__webpack_require__(138));
5529 const workspaceSymbols_1 = __importDefault(__webpack_require__(139));
5530 // Style check diagnostics that can be reported as warnings
5531 const styleCheckDiagnostics = [
5532     6133,
5533     6138,
5534     7027,
5535     7028,
5536     7029,
5537     7030 // not all code paths return a value
5538 ];
5539 class TypeScriptServiceClientHost {
5540     constructor(descriptions, pluginManager) {
5541         this.languagePerId = new Map();
5542         this.disposables = [];
5543         this.reportStyleCheckAsWarnings = true;
5544         let timer;
5545         const handleProjectChange = () => {
5546             if (timer)
5547                 clearTimeout(timer);
5548             timer = setTimeout(() => {
5549                 this.triggerAllDiagnostics();
5550             }, 1500);
5551         };
5552         const configFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/[tj]sconfig.json');
5553         this.disposables.push(configFileWatcher);
5554         configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5555         configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
5556         configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5557         const packageFileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/package.json');
5558         packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
5559         packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
5560         const allModeIds = this.getAllModeIds(descriptions, pluginManager);
5561         this.client = new typescriptServiceClient_1.default(pluginManager, allModeIds);
5562         this.disposables.push(this.client);
5563         this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
5564             this.diagnosticsReceived(kind, resource, diagnostics).catch(e => {
5565                 console.error(e);
5566             });
5567         }, null, this.disposables);
5568         // features
5569         this.disposables.push(new watchBuild_1.default(this.client));
5570         this.disposables.push(coc_nvim_1.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_1.default(this.client, allModeIds)));
5571         this.client.onConfigDiagnosticsReceived(diag => {
5572             let { body } = diag;
5573             if (body) {
5574                 let { configFile, diagnostics } = body;
5575                 let uri = coc_nvim_1.Uri.file(configFile);
5576                 if (diagnostics.length == 0) {
5577                     this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
5578                 }
5579                 else {
5580                     let diagnosticList = diagnostics.map(o => {
5581                         let { text, code, category, start, end } = o;
5582                         let range;
5583                         if (!start || !end) {
5584                             range = vscode_languageserver_protocol_1.Range.create(vscode_languageserver_protocol_1.Position.create(0, 0), vscode_languageserver_protocol_1.Position.create(0, 1));
5585                         }
5586                         else {
5587                             range = vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
5588                         }
5589                         let severity = category == 'error' ? vscode_languageserver_protocol_1.DiagnosticSeverity.Error : vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5590                         return vscode_languageserver_protocol_1.Diagnostic.create(range, text, severity, code);
5591                     });
5592                     this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
5593                 }
5594             }
5595         }, null, this.disposables);
5596         this.typingsStatus = new typingsStatus_1.default(this.client);
5597         this.ataProgressReporter = new typingsStatus_1.AtaProgressReporter(this.client);
5598         this.fileConfigurationManager = new fileConfigurationManager_1.default(this.client);
5599         for (const description of descriptions) { // tslint:disable-line
5600             const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
5601             this.languagePerId.set(description.id, manager);
5602         }
5603         const languageIds = new Set();
5604         for (const plugin of pluginManager.plugins) {
5605             if (plugin.configNamespace && plugin.languages.length) {
5606                 this.registerExtensionLanguageProvider({
5607                     id: plugin.configNamespace,
5608                     modeIds: Array.from(plugin.languages),
5609                     diagnosticSource: 'ts-plugin',
5610                     diagnosticLanguage: 1 /* TypeScript */,
5611                     diagnosticOwner: 'typescript',
5612                     isExternal: true
5613                 });
5614             }
5615             else {
5616                 for (const language of plugin.languages) {
5617                     languageIds.add(language);
5618                 }
5619             }
5620         }
5621         if (languageIds.size) {
5622             this.registerExtensionLanguageProvider({
5623                 id: 'typescript-plugins',
5624                 modeIds: Array.from(languageIds.values()),
5625                 diagnosticSource: 'ts-plugin',
5626                 diagnosticLanguage: 1 /* TypeScript */,
5627                 diagnosticOwner: 'typescript',
5628                 isExternal: true
5629             });
5630         }
5631         this.client.ensureServiceStarted();
5632         this.client.onTsServerStarted(() => {
5633             this.triggerAllDiagnostics();
5634         });
5635         coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5636         this.configurationChanged();
5637     }
5638     registerExtensionLanguageProvider(description) {
5639         const manager = new languageProvider_1.default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
5640         this.languagePerId.set(description.id, manager);
5641     }
5642     dispose() {
5643         coc_nvim_1.disposeAll(this.disposables);
5644         for (let language of this.languagePerId.values()) {
5645             language.dispose();
5646         }
5647         this.languagePerId.clear();
5648         this.fileConfigurationManager.dispose();
5649         this.typingsStatus.dispose();
5650         this.ataProgressReporter.dispose();
5651     }
5652     reset() {
5653         this.fileConfigurationManager.reset();
5654     }
5655     get serviceClient() {
5656         return this.client;
5657     }
5658     reloadProjects() {
5659         this.client.diagnosticsManager.reInitialize();
5660         this.client.execute('reloadProjects', null, vscode_languageserver_protocol_1.CancellationToken.None);
5661         this.triggerAllDiagnostics();
5662     }
5663     // typescript or javascript
5664     getProvider(languageId) {
5665         return this.languagePerId.get(languageId);
5666     }
5667     configurationChanged() {
5668         const config = coc_nvim_1.workspace.getConfiguration('tsserver');
5669         this.reportStyleCheckAsWarnings = config.get('reportStyleChecksAsWarnings', true);
5670     }
5671     async findLanguage(uri) {
5672         try {
5673             let doc = await coc_nvim_1.workspace.loadFile(uri);
5674             if (!doc)
5675                 return undefined;
5676             let languages = Array.from(this.languagePerId.values());
5677             return languages.find(language => language.handles(uri, doc.textDocument));
5678         }
5679         catch (_a) {
5680             return undefined;
5681         }
5682     }
5683     async handles(doc) {
5684         let languages = Array.from(this.languagePerId.values());
5685         let idx = languages.findIndex(language => language.handles(doc.uri, doc));
5686         if (idx != -1)
5687             return true;
5688         return this.client.bufferSyncSupport.handles(doc.uri);
5689     }
5690     triggerAllDiagnostics() {
5691         for (const language of this.languagePerId.values()) {
5692             language.triggerAllDiagnostics();
5693         }
5694     }
5695     async diagnosticsReceived(kind, resource, diagnostics) {
5696         const language = await this.findLanguage(resource.toString());
5697         if (language) {
5698             language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
5699         }
5700     }
5701     createMarkerDatas(diagnostics) {
5702         return diagnostics.map(tsDiag => this.tsDiagnosticToLspDiagnostic(tsDiag));
5703     }
5704     tsDiagnosticToLspDiagnostic(diagnostic) {
5705         const { start, end, text } = diagnostic;
5706         const range = {
5707             start: typeConverters.Position.fromLocation(start),
5708             end: typeConverters.Position.fromLocation(end)
5709         };
5710         let relatedInformation;
5711         if (diagnostic.relatedInformation) {
5712             relatedInformation = diagnostic.relatedInformation.map(o => {
5713                 let { span, message } = o;
5714                 return {
5715                     location: typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span),
5716                     message
5717                 };
5718             });
5719         }
5720         return {
5721             range,
5722             message: text,
5723             code: diagnostic.code ? diagnostic.code : null,
5724             severity: this.getDiagnosticSeverity(diagnostic),
5725             reportUnnecessary: diagnostic.reportsUnnecessary,
5726             source: diagnostic.source || 'tsserver',
5727             relatedInformation
5728         };
5729     }
5730     getDiagnosticSeverity(diagnostic) {
5731         if (this.reportStyleCheckAsWarnings &&
5732             this.isStyleCheckDiagnostic(diagnostic.code) &&
5733             diagnostic.category === PConst.DiagnosticCategory.error) {
5734             return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5735         }
5736         switch (diagnostic.category) {
5737             case PConst.DiagnosticCategory.error:
5738                 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5739             case PConst.DiagnosticCategory.warning:
5740                 return vscode_languageserver_protocol_1.DiagnosticSeverity.Warning;
5741             case PConst.DiagnosticCategory.suggestion:
5742                 return vscode_languageserver_protocol_1.DiagnosticSeverity.Information;
5743             default:
5744                 return vscode_languageserver_protocol_1.DiagnosticSeverity.Error;
5745         }
5746     }
5747     isStyleCheckDiagnostic(code) {
5748         return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
5749     }
5750     getAllModeIds(descriptions, pluginManager) {
5751         const allModeIds = arrays_1.flatten([
5752             ...descriptions.map(x => x.modeIds),
5753             ...pluginManager.plugins.map(x => x.languages)
5754         ]);
5755         return allModeIds;
5756     }
5757 }
5758 exports.default = TypeScriptServiceClientHost;
5759
5760
5761 /***/ }),
5762 /* 34 */
5763 /***/ (function(module, exports, __webpack_require__) {
5764
5765 "use strict";
5766
5767 var __importDefault = (this && this.__importDefault) || function (mod) {
5768     return (mod && mod.__esModule) ? mod : { "default": mod };
5769 };
5770 Object.defineProperty(exports, "__esModule", { value: true });
5771 /*---------------------------------------------------------------------------------------------
5772  *  Copyright (c) Microsoft Corporation. All rights reserved.
5773  *  Licensed under the MIT License. See License.txt in the project root for license information.
5774  *--------------------------------------------------------------------------------------------*/
5775 const coc_nvim_1 = __webpack_require__(1);
5776 const path_1 = __importDefault(__webpack_require__(13));
5777 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5778 const baseCodeLensProvider_1 = __webpack_require__(35);
5779 const completionItemProvider_1 = __importDefault(__webpack_require__(38));
5780 const definitionProvider_1 = __importDefault(__webpack_require__(88));
5781 const directiveCommentCompletions_1 = __importDefault(__webpack_require__(89));
5782 const documentHighlight_1 = __importDefault(__webpack_require__(90));
5783 const documentSymbol_1 = __importDefault(__webpack_require__(92));
5784 const folding_1 = __importDefault(__webpack_require__(93));
5785 const formatting_1 = __importDefault(__webpack_require__(94));
5786 const hover_1 = __importDefault(__webpack_require__(95));
5787 const implementationsCodeLens_1 = __importDefault(__webpack_require__(96));
5788 const importFix_1 = __importDefault(__webpack_require__(97));
5789 const moduleInstall_1 = __importDefault(__webpack_require__(99));
5790 // import TagCompletionProvider from './features/tagCompletion'
5791 const quickfix_1 = __importDefault(__webpack_require__(103));
5792 const refactor_1 = __importDefault(__webpack_require__(104));
5793 const references_1 = __importDefault(__webpack_require__(105));
5794 const referencesCodeLens_1 = __importDefault(__webpack_require__(106));
5795 const rename_1 = __importDefault(__webpack_require__(107));
5796 const signatureHelp_1 = __importDefault(__webpack_require__(108));
5797 const smartSelect_1 = __importDefault(__webpack_require__(109));
5798 const updatePathOnRename_1 = __importDefault(__webpack_require__(110));
5799 const organizeImports_1 = __webpack_require__(112);
5800 const api_1 = __importDefault(__webpack_require__(40));
5801 const suggestionSetting = 'suggestionActions.enabled';
5802 class LanguageProvider {
5803     constructor(client, fileConfigurationManager, description, typingsStatus) {
5804         this.client = client;
5805         this.fileConfigurationManager = fileConfigurationManager;
5806         this.description = description;
5807         this.typingsStatus = typingsStatus;
5808         this.disposables = [];
5809         coc_nvim_1.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
5810         this.configurationChanged();
5811         let initialized = false;
5812         client.onTsServerStarted(async () => {
5813             if (!initialized) {
5814                 initialized = true;
5815                 this.registerProviders(client, typingsStatus);
5816             }
5817         });
5818     }
5819     configurationChanged() {
5820         const config = coc_nvim_1.workspace.getConfiguration(this.id, null);
5821         this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
5822     }
5823     dispose() {
5824         coc_nvim_1.disposeAll(this.disposables);
5825     }
5826     _register(disposable) {
5827         this.disposables.push(disposable);
5828     }
5829     registerProviders(client, typingsStatus) {
5830         let languageIds = this.description.modeIds;
5831         let clientId = `tsserver-${this.description.id}`;
5832         this._register(coc_nvim_1.languages.registerCompletionItemProvider(clientId, 'TSC', languageIds, new completionItemProvider_1.default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_1.default.triggerCharacters));
5833         if (this.client.apiVersion.gte(api_1.default.v230)) {
5834             this._register(coc_nvim_1.languages.registerCompletionItemProvider(`${this.description.id}-directive`, 'TSC', languageIds, new directiveCommentCompletions_1.default(client), ['@']));
5835         }
5836         let definitionProvider = new definitionProvider_1.default(client);
5837         this._register(coc_nvim_1.languages.registerDefinitionProvider(languageIds, definitionProvider));
5838         this._register(coc_nvim_1.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
5839         this._register(coc_nvim_1.languages.registerImplementationProvider(languageIds, definitionProvider));
5840         this._register(coc_nvim_1.languages.registerReferencesProvider(languageIds, new references_1.default(client)));
5841         this._register(coc_nvim_1.languages.registerHoverProvider(languageIds, new hover_1.default(client)));
5842         this._register(coc_nvim_1.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_1.default(this.client)));
5843         this._register(coc_nvim_1.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_1.default(client), ['(', ',', '<', ')']));
5844         this._register(coc_nvim_1.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_1.default(client)));
5845         this._register(coc_nvim_1.languages.registerRenameProvider(languageIds, new rename_1.default(client, this.fileConfigurationManager)));
5846         let formatProvider = new formatting_1.default(client, this.fileConfigurationManager);
5847         this._register(coc_nvim_1.languages.registerDocumentFormatProvider(languageIds, formatProvider));
5848         this._register(coc_nvim_1.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
5849         this._register(coc_nvim_1.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [';', '}', '\n', String.fromCharCode(27)]));
5850         this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new moduleInstall_1.default(client), 'tsserver'));
5851         let { fileConfigurationManager } = this;
5852         let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
5853         if (['javascript', 'typescript'].includes(this.id)) {
5854             if (this.client.apiVersion.gte(api_1.default.v290) && conf.get('updateImportsOnFileMove.enable')) {
5855                 this._register(new updatePathOnRename_1.default(client, this.fileConfigurationManager, this.id));
5856             }
5857         }
5858         if (this.client.apiVersion.gte(api_1.default.v280)) {
5859             this._register(coc_nvim_1.languages.registerFoldingRangeProvider(languageIds, new folding_1.default(this.client)));
5860             this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new organizeImports_1.OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]));
5861         }
5862         if (this.client.apiVersion.gte(api_1.default.v240)) {
5863             this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new refactor_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.Refactor]));
5864         }
5865         this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new quickfix_1.default(client, this.fileConfigurationManager), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5866         this._register(coc_nvim_1.languages.registerCodeActionProvider(languageIds, new importFix_1.default(this.client.bufferSyncSupport), 'tsserver', [vscode_languageserver_protocol_1.CodeActionKind.QuickFix]));
5867         let cachedResponse = new baseCodeLensProvider_1.CachedNavTreeResponse();
5868         if (this.client.apiVersion.gte(api_1.default.v206) && conf.get('referencesCodeLens.enable')) {
5869             this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_1.default(client, cachedResponse)));
5870         }
5871         if (this.client.apiVersion.gte(api_1.default.v220) && conf.get('implementationsCodeLens.enable')) {
5872             this._register(coc_nvim_1.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_1.default(client, cachedResponse)));
5873         }
5874         if (this.client.apiVersion.gte(api_1.default.v350)) {
5875             this._register(coc_nvim_1.languages.registerSelectionRangeProvider(languageIds, new smartSelect_1.default(this.client)));
5876         }
5877         // if (this.client.apiVersion.gte(API.v300)) {
5878         //   this._register(
5879         //     languages.registerCompletionItemProvider(
5880         //       `tsserver-${this.description.id}-tag`,
5881         //       'TSC',
5882         //       languageIds,
5883         //       new TagCompletionProvider(client),
5884         //       ['>']
5885         //     )
5886         //   )
5887         // }
5888     }
5889     handles(resource, doc) {
5890         if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
5891             return true;
5892         }
5893         const base = path_1.default.basename(coc_nvim_1.Uri.parse(resource).fsPath);
5894         return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
5895     }
5896     get id() {
5897         return this.description.id;
5898     }
5899     get diagnosticSource() {
5900         return this.description.diagnosticSource;
5901     }
5902     triggerAllDiagnostics() {
5903         this.client.bufferSyncSupport.requestAllDiagnostics();
5904     }
5905     diagnosticsReceived(diagnosticsKind, file, diagnostics) {
5906         const config = coc_nvim_1.workspace.getConfiguration(this.id, file.toString());
5907         const reportUnnecessary = config.get('showUnused', true);
5908         this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file.toString(), diagnostics.filter(diag => {
5909             if (!reportUnnecessary) {
5910                 diag.tags = undefined;
5911                 if (diag.reportUnnecessary && diag.severity === vscode_languageserver_protocol_1.DiagnosticSeverity.Information) {
5912                     return false;
5913                 }
5914             }
5915             return true;
5916         }));
5917     }
5918 }
5919 exports.default = LanguageProvider;
5920
5921
5922 /***/ }),
5923 /* 35 */
5924 /***/ (function(module, exports, __webpack_require__) {
5925
5926 "use strict";
5927
5928 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5929     if (k2 === undefined) k2 = k;
5930     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5931 }) : (function(o, m, k, k2) {
5932     if (k2 === undefined) k2 = k;
5933     o[k2] = m[k];
5934 }));
5935 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5936     Object.defineProperty(o, "default", { enumerable: true, value: v });
5937 }) : function(o, v) {
5938     o["default"] = v;
5939 });
5940 var __importStar = (this && this.__importStar) || function (mod) {
5941     if (mod && mod.__esModule) return mod;
5942     var result = {};
5943     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5944     __setModuleDefault(result, mod);
5945     return result;
5946 };
5947 Object.defineProperty(exports, "__esModule", { value: true });
5948 exports.TypeScriptBaseCodeLensProvider = exports.CachedNavTreeResponse = void 0;
5949 /*---------------------------------------------------------------------------------------------
5950  *  Copyright (c) Microsoft Corporation. All rights reserved.
5951  *  Licensed under the MIT License. See License.txt in the project root for license information.
5952  *--------------------------------------------------------------------------------------------*/
5953 const vscode_languageserver_protocol_1 = __webpack_require__(3);
5954 const regexp_1 = __webpack_require__(36);
5955 const typeConverters = __importStar(__webpack_require__(37));
5956 class CachedNavTreeResponse {
5957     constructor() {
5958         this.version = -1;
5959         this.document = '';
5960     }
5961     execute(document, f) {
5962         if (this.matches(document)) {
5963             return this.response;
5964         }
5965         return this.update(document, f());
5966     }
5967     matches(document) {
5968         return (this.version === document.version &&
5969             this.document === document.uri.toString());
5970     }
5971     update(document, response) {
5972         this.response = response;
5973         this.version = document.version;
5974         this.document = document.uri.toString();
5975         return response;
5976     }
5977 }
5978 exports.CachedNavTreeResponse = CachedNavTreeResponse;
5979 class TypeScriptBaseCodeLensProvider {
5980     constructor(client, cachedResponse) {
5981         this.client = client;
5982         this.cachedResponse = cachedResponse;
5983         this.onDidChangeCodeLensesEmitter = new vscode_languageserver_protocol_1.Emitter();
5984     }
5985     get onDidChangeCodeLenses() {
5986         return this.onDidChangeCodeLensesEmitter.event;
5987     }
5988     async provideCodeLenses(document, token) {
5989         const filepath = this.client.toPath(document.uri);
5990         if (!filepath) {
5991             return [];
5992         }
5993         try {
5994             const response = await this.cachedResponse.execute(document, () => this.client.execute('navtree', { file: filepath }, token));
5995             if (!response) {
5996                 return [];
5997             }
5998             const tree = response.body;
5999             const referenceableSpans = [];
6000             if (tree && tree.childItems) {
6001                 tree.childItems.forEach(item => this.walkNavTree(document, item, null, referenceableSpans));
6002             }
6003             return referenceableSpans.map(range => {
6004                 return {
6005                     range,
6006                     data: { uri: document.uri }
6007                 };
6008             });
6009         }
6010         catch (_a) {
6011             return [];
6012         }
6013     }
6014     walkNavTree(document, item, parent, results) {
6015         if (!item) {
6016             return;
6017         }
6018         const range = this.extractSymbol(document, item, parent);
6019         if (range) {
6020             results.push(range);
6021         }
6022         if (item.childItems) {
6023             item.childItems.forEach(child => this.walkNavTree(document, child, item, results));
6024         }
6025     }
6026     getSymbolRange(document, item) {
6027         if (!item) {
6028             return null;
6029         }
6030         // TS 3.0+ provides a span for just the symbol
6031         if (item.nameSpan) {
6032             return typeConverters.Range.fromTextSpan(item.nameSpan);
6033         }
6034         // In older versions, we have to calculate this manually. See #23924
6035         const span = item.spans && item.spans[0];
6036         if (!span) {
6037             return null;
6038         }
6039         const range = typeConverters.Range.fromTextSpan(span);
6040         const text = document.getText(range);
6041         const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${regexp_1.escapeRegExp(item.text || '')}(\\b|\\W)`, 'gm');
6042         const match = identifierMatch.exec(text);
6043         const prefixLength = match ? match.index + match[1].length : 0;
6044         const startOffset = document.offsetAt(range.start) + prefixLength;
6045         return {
6046             start: document.positionAt(startOffset),
6047             end: document.positionAt(startOffset + item.text.length)
6048         };
6049     }
6050 }
6051 exports.TypeScriptBaseCodeLensProvider = TypeScriptBaseCodeLensProvider;
6052
6053
6054 /***/ }),
6055 /* 36 */
6056 /***/ (function(module, exports, __webpack_require__) {
6057
6058 "use strict";
6059
6060 /*---------------------------------------------------------------------------------------------
6061  *  Copyright (c) Microsoft Corporation. All rights reserved.
6062  *  Licensed under the MIT License. See License.txt in the project root for license information.
6063  *--------------------------------------------------------------------------------------------*/
6064 Object.defineProperty(exports, "__esModule", { value: true });
6065 exports.escapeRegExp = void 0;
6066 function escapeRegExp(text) {
6067     return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
6068 }
6069 exports.escapeRegExp = escapeRegExp;
6070
6071
6072 /***/ }),
6073 /* 37 */
6074 /***/ (function(module, exports, __webpack_require__) {
6075
6076 "use strict";
6077
6078 Object.defineProperty(exports, "__esModule", { value: true });
6079 exports.WorkspaceEdit = exports.TextEdit = exports.Location = exports.Position = exports.Range = void 0;
6080 var Range;
6081 (function (Range) {
6082     Range.fromTextSpan = (span) => {
6083         return {
6084             start: {
6085                 line: span.start.line - 1,
6086                 character: span.start.offset - 1
6087             },
6088             end: {
6089                 line: span.end.line - 1,
6090                 character: span.end.offset - 1
6091             }
6092         };
6093     };
6094     Range.toFormattingRequestArgs = (file, range) => ({
6095         file,
6096         line: range.start.line + 1,
6097         offset: range.start.character + 1,
6098         endLine: range.end.line + 1,
6099         endOffset: range.end.character + 1
6100     });
6101     Range.toFileRangeRequestArgs = (file, range) => ({
6102         file,
6103         startLine: range.start.line + 1,
6104         startOffset: range.start.character + 1,
6105         endLine: range.end.line + 1,
6106         endOffset: range.end.character + 1
6107     });
6108 })(Range = exports.Range || (exports.Range = {}));
6109 var Position;
6110 (function (Position) {
6111     Position.fromLocation = (tslocation) => {
6112         return {
6113             line: tslocation.line - 1,
6114             character: tslocation.offset - 1
6115         };
6116     };
6117     Position.toLocation = (position) => ({
6118         line: position.line + 1,
6119         offset: position.character + 1,
6120     });
6121     Position.toFileLocationRequestArgs = (file, position) => ({
6122         file,
6123         line: position.line + 1,
6124         offset: position.character + 1
6125     });
6126 })(Position = exports.Position || (exports.Position = {}));
6127 var Location;
6128 (function (Location) {
6129     Location.fromTextSpan = (uri, tsTextSpan) => {
6130         return {
6131             uri,
6132             range: Range.fromTextSpan(tsTextSpan)
6133         };
6134     };
6135 })(Location = exports.Location || (exports.Location = {}));
6136 var TextEdit;
6137 (function (TextEdit) {
6138     TextEdit.fromCodeEdit = (edit) => {
6139         return {
6140             range: Range.fromTextSpan(edit),
6141             newText: edit.newText
6142         };
6143     };
6144 })(TextEdit = exports.TextEdit || (exports.TextEdit = {}));
6145 var WorkspaceEdit;
6146 (function (WorkspaceEdit) {
6147     function fromFileCodeEdits(client, edits) {
6148         let changes = {};
6149         for (const edit of edits) {
6150             let uri = client.toResource(edit.fileName);
6151             changes[uri] = edit.textChanges.map(change => {
6152                 return TextEdit.fromCodeEdit(change);
6153             });
6154         }
6155         return { changes };
6156     }
6157     WorkspaceEdit.fromFileCodeEdits = fromFileCodeEdits;
6158 })(WorkspaceEdit = exports.WorkspaceEdit || (exports.WorkspaceEdit = {}));
6159
6160
6161 /***/ }),
6162 /* 38 */
6163 /***/ (function(module, exports, __webpack_require__) {
6164
6165 "use strict";
6166
6167 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6168     if (k2 === undefined) k2 = k;
6169     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6170 }) : (function(o, m, k, k2) {
6171     if (k2 === undefined) k2 = k;
6172     o[k2] = m[k];
6173 }));
6174 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6175     Object.defineProperty(o, "default", { enumerable: true, value: v });
6176 }) : function(o, v) {
6177     o["default"] = v;
6178 });
6179 var __importStar = (this && this.__importStar) || function (mod) {
6180     if (mod && mod.__esModule) return mod;
6181     var result = {};
6182     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6183     __setModuleDefault(result, mod);
6184     return result;
6185 };
6186 var __importDefault = (this && this.__importDefault) || function (mod) {
6187     return (mod && mod.__esModule) ? mod : { "default": mod };
6188 };
6189 Object.defineProperty(exports, "__esModule", { value: true });
6190 /*---------------------------------------------------------------------------------------------
6191  *  Copyright (c) Microsoft Corporation. All rights reserved.
6192  *  Licensed under the MIT License. See License.txt in the project root for license information.
6193  *--------------------------------------------------------------------------------------------*/
6194 const vscode_languageserver_protocol_1 = __webpack_require__(3);
6195 const coc_nvim_1 = __webpack_require__(1);
6196 const PConst = __importStar(__webpack_require__(39));
6197 const api_1 = __importDefault(__webpack_require__(40));
6198 const codeAction_1 = __webpack_require__(84);
6199 const completionItem_1 = __webpack_require__(85);
6200 const Previewer = __importStar(__webpack_require__(86));
6201 const typeConverters = __importStar(__webpack_require__(37));
6202 const SnippetString_1 = __importDefault(__webpack_require__(87));
6203 class ApplyCompletionCodeActionCommand {
6204     constructor(client) {
6205         this.client = client;
6206         this.id = ApplyCompletionCodeActionCommand.ID;
6207     }
6208     // apply code action on complete
6209     async execute(codeActions) {
6210         if (codeActions.length === 0) {
6211             return;
6212         }
6213         if (codeActions.length === 1) {
6214             await codeAction_1.applyCodeAction(this.client, codeActions[0]);
6215             return;
6216         }
6217         const idx = await coc_nvim_1.workspace.showQuickpick(codeActions.map(o => o.description), 'Select code action to apply');
6218         if (idx < 0)
6219             return;
6220         const action = codeActions[idx];
6221         await codeAction_1.applyCodeAction(this.client, action);
6222         return;
6223     }
6224 }
6225 ApplyCompletionCodeActionCommand.ID = '_typescript.applyCompletionCodeAction';
6226 class TypeScriptCompletionItemProvider {
6227     constructor(client, typingsStatus, fileConfigurationManager, languageId) {
6228         this.client = client;
6229         this.typingsStatus = typingsStatus;
6230         this.fileConfigurationManager = fileConfigurationManager;
6231         this.setCompleteOption(languageId);
6232         coc_nvim_1.commands.register(new ApplyCompletionCodeActionCommand(this.client));
6233         coc_nvim_1.workspace.onDidChangeConfiguration(_e => {
6234             this.setCompleteOption(languageId);
6235         });
6236     }
6237     setCompleteOption(languageId) {
6238         this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
6239     }
6240     /**
6241      * Get completionItems
6242      *
6243      * @public
6244      * @param {TextDocument} document
6245      * @param {Position} position
6246      * @param {CancellationToken} token
6247      * @param {string} triggerCharacter
6248      * @returns {Promise<CompletionItem[]>}
6249      */
6250     async provideCompletionItems(document, position, token, context) {
6251         if (this.typingsStatus.isAcquiringTypings) {
6252             return Promise.resolve({
6253                 isIncomplete: true,
6254                 items: [{
6255                         label: 'Acquiring typings...',
6256                         detail: 'Acquiring typings definitions for IntelliSense.'
6257                     }]
6258             });
6259         }
6260         let { uri } = document;
6261         const file = this.client.toPath(document.uri);
6262         if (!file)
6263             return null;
6264         let preText = document.getText({
6265             start: { line: position.line, character: 0 },
6266             end: position
6267         });
6268         let { triggerCharacter, option } = context;
6269         if (!this.shouldTrigger(triggerCharacter, preText, option)) {
6270             return null;
6271         }
6272         await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
6273         const { completeOption } = this;
6274         const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { includeExternalModuleExports: completeOption.autoImports, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions });
6275         let entries;
6276         let dotAccessorContext;
6277         let isNewIdentifierLocation = true;
6278         let isMemberCompletion = false;
6279         let isIncomplete = false;
6280         const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
6281         if (this.client.apiVersion.gte(api_1.default.v300)) {
6282             try {
6283                 const response = await this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token));
6284                 if (response.type !== 'response' || !response.body) {
6285                     return null;
6286                 }
6287                 isNewIdentifierLocation = response.body.isNewIdentifierLocation;
6288                 isMemberCompletion = response.body.isMemberCompletion;
6289                 if (isMemberCompletion) {
6290                     const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || undefined;
6291                     if (dotMatch) {
6292                         const range = vscode_languageserver_protocol_1.Range.create({
6293                             line: position.line,
6294                             character: position.character - dotMatch.length
6295                         }, position);
6296                         const text = document.getText(range);
6297                         dotAccessorContext = { range, text };
6298                     }
6299                 }
6300                 isIncomplete = response.metadata && response.metadata.isIncomplete;
6301                 entries = response.body.entries;
6302             }
6303             catch (e) {
6304                 if (e.message == 'No content available.') {
6305                     return null;
6306                 }
6307                 throw e;
6308             }
6309         }
6310         else {
6311             const response = await this.client.interruptGetErr(() => this.client.execute('completions', args, token));
6312             if (response.type !== 'response' || !response.body) {
6313                 return null;
6314             }
6315             entries = response.body;
6316         }
6317         const completionItems = [];
6318         for (const element of entries) {
6319             if (shouldExcludeCompletionEntry(element, completeOption)) {
6320                 continue;
6321             }
6322             const item = completionItem_1.convertCompletionEntry(element, uri, position, {
6323                 isNewIdentifierLocation,
6324                 isMemberCompletion,
6325                 enableCallCompletions: completeOption.completeFunctionCalls,
6326                 isInValidCommitCharacterContext,
6327                 dotAccessorContext,
6328             });
6329             completionItems.push(item);
6330         }
6331         return { isIncomplete, items: completionItems };
6332     }
6333     getTsTriggerCharacter(context) {
6334         // return context.triggerCharacter as Proto.CompletionsTriggerCharacter
6335         switch (context.triggerCharacter) {
6336             case '@': // Workaround for https://github.com/Microsoft/TypeScript/issues/27321
6337                 return this.client.apiVersion.gte(api_1.default.v310) && this.client.apiVersion.lt(api_1.default.v320) ? undefined : '@';
6338             case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
6339                 return this.client.apiVersion.lt(api_1.default.v381) ? undefined : '#';
6340             case '.':
6341             case '"':
6342             case '\'':
6343             case '`':
6344             case '/':
6345             case '<':
6346                 return context.triggerCharacter;
6347         }
6348         return undefined;
6349     }
6350     /**
6351      * Resolve complete item, could have documentation added
6352      *
6353      * @public
6354      * @param {CompletionItem} item
6355      * @param {CancellationToken} token
6356      * @returns {Promise<CompletionItem>}
6357      */
6358     async resolveCompletionItem(item, token) {
6359         if (item == null)
6360             return undefined;
6361         let { uri, position, source, name } = item.data;
6362         const filepath = this.client.toPath(uri);
6363         if (!filepath)
6364             return undefined;
6365         let document = coc_nvim_1.workspace.getDocument(uri);
6366         if (!document)
6367             return undefined;
6368         const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(filepath, position)), { entryNames: [source ? { name, source } : name] });
6369         let response;
6370         try {
6371             response = await this.client.interruptGetErr(() => this.client.execute('completionEntryDetails', args, token));
6372         }
6373         catch (_a) {
6374             return item;
6375         }
6376         if (response.type !== 'response' || !response.body || !response.body.length) {
6377             return item;
6378         }
6379         const details = response.body;
6380         if (!details || !details.length || !details[0]) {
6381             return item;
6382         }
6383         const detail = details[0];
6384         if (!item.detail && detail.displayParts.length) {
6385             item.detail = Previewer.plain(detail.displayParts);
6386         }
6387         item.documentation = this.getDocumentation(detail);
6388         const { command, additionalTextEdits } = this.getCodeActions(detail, filepath);
6389         if (command)
6390             item.command = command;
6391         item.additionalTextEdits = additionalTextEdits;
6392         if (detail && item.insertTextFormat == vscode_languageserver_protocol_1.InsertTextFormat.Snippet) {
6393             const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token);
6394             if (shouldCompleteFunction) {
6395                 this.createSnippetOfFunctionCall(item, detail);
6396             }
6397         }
6398         return item;
6399     }
6400     getCodeActions(detail, filepath) {
6401         if (!detail.codeActions || !detail.codeActions.length) {
6402             return {};
6403         }
6404         // Try to extract out the additionalTextEdits for the current file.
6405         // Also check if we still have to apply other workspace edits
6406         const additionalTextEdits = [];
6407         let hasRemainingCommandsOrEdits = false;
6408         for (const tsAction of detail.codeActions) {
6409             if (tsAction.commands) {
6410                 hasRemainingCommandsOrEdits = true;
6411             }
6412             // Convert all edits in the current file using `additionalTextEdits`
6413             if (tsAction.changes) {
6414                 for (const change of tsAction.changes) {
6415                     if (change.fileName === filepath) {
6416                         additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit));
6417                     }
6418                     else {
6419                         hasRemainingCommandsOrEdits = true;
6420                     }
6421                 }
6422             }
6423         }
6424         let command = null;
6425         if (hasRemainingCommandsOrEdits) {
6426             // Create command that applies all edits not in the current file.
6427             command = {
6428                 title: '',
6429                 command: ApplyCompletionCodeActionCommand.ID,
6430                 arguments: [
6431                     detail.codeActions.map((x) => ({
6432                         commands: x.commands,
6433                         description: x.description,
6434                         changes: x.changes.filter(x => x.fileName !== filepath)
6435                     }))
6436                 ]
6437             };
6438         }
6439         return {
6440             command,
6441             additionalTextEdits: additionalTextEdits.length
6442                 ? additionalTextEdits
6443                 : undefined
6444         };
6445     }
6446     shouldTrigger(triggerCharacter, pre, option) {
6447         if (triggerCharacter && this.client.apiVersion.lt(api_1.default.v290)) {
6448             if (triggerCharacter === '@') {
6449                 // trigger in string
6450                 if (option.synname && /string/i.test(option.synname)) {
6451                     return true;
6452                 }
6453                 // make sure we are in something that looks like the start of a jsdoc comment
6454                 if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
6455                     return false;
6456                 }
6457             }
6458             else if (triggerCharacter === '<') {
6459                 return false;
6460             }
6461         }
6462         return true;
6463     }
6464     // complete item documentation
6465     getDocumentation(detail) {
6466         let documentation = '';
6467         if (detail.source) {
6468             const importPath = `'${Previewer.plain(detail.source)}'`;
6469             const autoImportLabel = `Auto import from ${importPath}`;
6470             documentation += `${autoImportLabel}\n`;
6471         }
6472         let parts = [
6473             Previewer.plain(detail.documentation),
6474             Previewer.tagsMarkdownPreview(detail.tags)
6475         ];
6476         parts = parts.filter(s => s && s.trim() != '');
6477         documentation += parts.join('\n\n');
6478         if (documentation.length) {
6479             return {
6480                 kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
6481                 value: documentation
6482             };
6483         }
6484         return undefined;
6485     }
6486     createSnippetOfFunctionCall(item, detail) {
6487         let { displayParts } = detail;
6488         const parameterListParts = completionItem_1.getParameterListParts(displayParts);
6489         const snippet = new SnippetString_1.default();
6490         snippet.appendText(`${item.insertText || item.label}(`);
6491         appendJoinedPlaceholders(snippet, parameterListParts.parts, ', ');
6492         if (parameterListParts.hasOptionalParameters) {
6493             snippet.appendTabstop();
6494         }
6495         snippet.appendText(')');
6496         snippet.appendTabstop(0);
6497         item.insertText = snippet.value;
6498     }
6499     async isValidFunctionCompletionContext(filepath, position, token) {
6500         // Workaround for https://github.com/Microsoft/TypeScript/issues/12677
6501         // Don't complete function calls inside of destructive assigments or imports
6502         try {
6503             const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
6504             const response = await this.client.execute('quickinfo', args, token);
6505             if (response.type !== 'response') {
6506                 return true;
6507             }
6508             const { body } = response;
6509             switch (body && body.kind) {
6510                 case 'var':
6511                 case 'let':
6512                 case 'const':
6513                 case 'alias':
6514                     return false;
6515                 default:
6516                     return true;
6517             }
6518         }
6519         catch (e) {
6520             return true;
6521         }
6522     }
6523     isInValidCommitCharacterContext(document, position) {
6524         if (this.client.apiVersion.lt(api_1.default.v320)) {
6525             // Workaround for https://github.com/Microsoft/TypeScript/issues/27742
6526             // Only enable dot completions when previous character not a dot preceded by whitespace.
6527             // Prevents incorrectly completing while typing spread operators.
6528             if (position.character > 1) {
6529                 const preText = document.getText(vscode_languageserver_protocol_1.Range.create(position.line, 0, position.line, position.character));
6530                 return preText.match(/(\s|^)\.$/ig) === null;
6531             }
6532         }
6533         return true;
6534     }
6535 }
6536 exports.default = TypeScriptCompletionItemProvider;
6537 TypeScriptCompletionItemProvider.triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#'];
6538 function shouldExcludeCompletionEntry(element, completionConfiguration) {
6539     return ((!completionConfiguration.names && element.kind === PConst.Kind.warning)
6540         || (!completionConfiguration.paths &&
6541             (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName))
6542         || (!completionConfiguration.autoImports && element.hasAction));
6543 }
6544 function appendJoinedPlaceholders(snippet, parts, joiner) {
6545     for (let i = 0; i < parts.length; ++i) {
6546         const paramterPart = parts[i];
6547         snippet.appendPlaceholder(paramterPart.text);
6548         if (i !== parts.length - 1) {
6549             snippet.appendText(joiner);
6550         }
6551     }
6552 }
6553
6554
6555 /***/ }),
6556 /* 39 */
6557 /***/ (function(module, exports, __webpack_require__) {
6558
6559 "use strict";
6560
6561 /*---------------------------------------------------------------------------------------------
6562  *  Copyright (c) Microsoft Corporation. All rights reserved.
6563  *  Licensed under the MIT License. See License.txt in the project root for license information.
6564  *--------------------------------------------------------------------------------------------*/
6565 Object.defineProperty(exports, "__esModule", { value: true });
6566 exports.DisplayPartKind = exports.KindModifiers = exports.DiagnosticCategory = exports.Kind = void 0;
6567 class Kind {
6568 }
6569 exports.Kind = Kind;
6570 Kind.alias = 'alias';
6571 Kind.callSignature = 'call';
6572 Kind.class = 'class';
6573 Kind.const = 'const';
6574 Kind.constructorImplementation = 'constructor';
6575 Kind.constructSignature = 'construct';
6576 Kind.directory = 'directory';
6577 Kind.enum = 'enum';
6578 Kind.enumMember = 'enum member';
6579 Kind.externalModuleName = 'external module name';
6580 Kind.function = 'function';
6581 Kind.indexSignature = 'index';
6582 Kind.interface = 'interface';
6583 Kind.keyword = 'keyword';
6584 Kind.let = 'let';
6585 Kind.localFunction = 'local function';
6586 Kind.localVariable = 'local var';
6587 Kind.method = 'method';
6588 Kind.memberGetAccessor = 'getter';
6589 Kind.memberSetAccessor = 'setter';
6590 Kind.memberVariable = 'property';
6591 Kind.module = 'module';
6592 Kind.primitiveType = 'primitive type';
6593 Kind.script = 'script';
6594 Kind.type = 'type';
6595 Kind.variable = 'var';
6596 Kind.warning = 'warning';
6597 Kind.string = 'string';
6598 Kind.parameter = 'parameter';
6599 Kind.typeParameter = 'type parameter';
6600 class DiagnosticCategory {
6601 }
6602 exports.DiagnosticCategory = DiagnosticCategory;
6603 DiagnosticCategory.error = 'error';
6604 DiagnosticCategory.warning = 'warning';
6605 DiagnosticCategory.suggestion = 'suggestion';
6606 class KindModifiers {
6607 }
6608 exports.KindModifiers = KindModifiers;
6609 KindModifiers.optional = 'optional';
6610 KindModifiers.color = 'color';
6611 KindModifiers.dtsFile = '.d.ts';
6612 KindModifiers.tsFile = '.ts';
6613 KindModifiers.tsxFile = '.tsx';
6614 KindModifiers.jsFile = '.js';
6615 KindModifiers.jsxFile = '.jsx';
6616 KindModifiers.jsonFile = '.json';
6617 KindModifiers.fileExtensionKindModifiers = [
6618     KindModifiers.dtsFile,
6619     KindModifiers.tsFile,
6620     KindModifiers.tsxFile,
6621     KindModifiers.jsFile,
6622     KindModifiers.jsxFile,
6623     KindModifiers.jsonFile,
6624 ];
6625 class DisplayPartKind {
6626 }
6627 exports.DisplayPartKind = DisplayPartKind;
6628 DisplayPartKind.functionName = 'functionName';
6629 DisplayPartKind.methodName = 'methodName';
6630 DisplayPartKind.parameterName = 'parameterName';
6631 DisplayPartKind.propertyName = 'propertyName';
6632 DisplayPartKind.punctuation = 'punctuation';
6633 DisplayPartKind.text = 'text';
6634
6635
6636 /***/ }),
6637 /* 40 */
6638 /***/ (function(module, exports, __webpack_require__) {
6639
6640 "use strict";
6641
6642 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6643     if (k2 === undefined) k2 = k;
6644     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
6645 }) : (function(o, m, k, k2) {
6646     if (k2 === undefined) k2 = k;
6647     o[k2] = m[k];
6648 }));
6649 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
6650     Object.defineProperty(o, "default", { enumerable: true, value: v });
6651 }) : function(o, v) {
6652     o["default"] = v;
6653 });
6654 var __importStar = (this && this.__importStar) || function (mod) {
6655     if (mod && mod.__esModule) return mod;
6656     var result = {};
6657     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
6658     __setModuleDefault(result, mod);
6659     return result;
6660 };
6661 Object.defineProperty(exports, "__esModule", { value: true });
6662 /*---------------------------------------------------------------------------------------------
6663  *  Copyright (c) Microsoft Corporation. All rights reserved.
6664  *  Licensed under the MIT License. See License.txt in the project root for license information.
6665  *--------------------------------------------------------------------------------------------*/
6666 const semver = __importStar(__webpack_require__(41));
6667 class API {
6668     constructor(versionString, version) {
6669         this.versionString = versionString;
6670         this.version = version;
6671     }
6672     static fromSimpleString(value) {
6673         return new API(value, value);
6674     }
6675     static fromVersionString(versionString) {
6676         let version = semver.valid(versionString);
6677         if (!version) {
6678             return new API('invalid version', '1.0.0');
6679         }
6680         // Cut off any prerelease tag since we sometimes consume those on purpose.
6681         const index = versionString.indexOf('-');
6682         if (index >= 0) {
6683             version = version.substr(0, index);
6684         }
6685         return new API(versionString, version);
6686     }
6687     gte(other) {
6688         return semver.gte(this.version, other.version);
6689     }
6690     lt(other) {
6691         return !this.gte(other);
6692     }
6693 }
6694 exports.default = API;
6695 API.defaultVersion = API.fromSimpleString('1.0.0');
6696 API.v203 = API.fromSimpleString('2.0.3');
6697 API.v206 = API.fromSimpleString('2.0.6');
6698 API.v208 = API.fromSimpleString('2.0.8');
6699 API.v213 = API.fromSimpleString('2.1.3');
6700 API.v220 = API.fromSimpleString('2.2.0');
6701 API.v222 = API.fromSimpleString('2.2.2');
6702 API.v230 = API.fromSimpleString('2.3.0');
6703 API.v234 = API.fromSimpleString('2.3.4');
6704 API.v240 = API.fromSimpleString('2.4.0');
6705 API.v250 = API.fromSimpleString('2.5.0');
6706 API.v260 = API.fromSimpleString('2.6.0');
6707 API.v270 = API.fromSimpleString('2.7.0');
6708 API.v280 = API.fromSimpleString('2.8.0');
6709 API.v290 = API.fromSimpleString('2.9.0');
6710 API.v291 = API.fromSimpleString('2.9.1');
6711 API.v292 = API.fromSimpleString('2.9.2');
6712 API.v300 = API.fromSimpleString('3.0.0');
6713 API.v310 = API.fromSimpleString('3.1.0');
6714 API.v314 = API.fromSimpleString('3.1.4');
6715 API.v320 = API.fromSimpleString('3.2.0');
6716 API.v330 = API.fromSimpleString('3.3.0');
6717 API.v333 = API.fromSimpleString('3.3.3');
6718 API.v340 = API.fromSimpleString('3.4.0');
6719 API.v345 = API.fromSimpleString('3.4.5');
6720 API.v350 = API.fromSimpleString('3.5.0');
6721 API.v380 = API.fromSimpleString('3.8.0');
6722 API.v381 = API.fromSimpleString('3.8.1');
6723 API.v390 = API.fromSimpleString('3.9.0');
6724 API.v400 = API.fromSimpleString('4.0.0');
6725 API.v401 = API.fromSimpleString('4.0.1');
6726
6727
6728 /***/ }),
6729 /* 41 */
6730 /***/ (function(module, exports, __webpack_require__) {
6731
6732 // just pre-load all the stuff that index.js lazily exports
6733 const internalRe = __webpack_require__(42)
6734 module.exports = {
6735   re: internalRe.re,
6736   src: internalRe.src,
6737   tokens: internalRe.t,
6738   SEMVER_SPEC_VERSION: __webpack_require__(43).SEMVER_SPEC_VERSION,
6739   SemVer: __webpack_require__(45),
6740   compareIdentifiers: __webpack_require__(46).compareIdentifiers,
6741   rcompareIdentifiers: __webpack_require__(46).rcompareIdentifiers,
6742   parse: __webpack_require__(47),
6743   valid: __webpack_require__(48),
6744   clean: __webpack_require__(49),
6745   inc: __webpack_require__(50),
6746   diff: __webpack_require__(51),
6747   major: __webpack_require__(54),
6748   minor: __webpack_require__(55),
6749   patch: __webpack_require__(56),
6750   prerelease: __webpack_require__(57),
6751   compare: __webpack_require__(53),
6752   rcompare: __webpack_require__(58),
6753   compareLoose: __webpack_require__(59),
6754   compareBuild: __webpack_require__(60),
6755   sort: __webpack_require__(61),
6756   rsort: __webpack_require__(62),
6757   gt: __webpack_require__(63),
6758   lt: __webpack_require__(64),
6759   eq: __webpack_require__(52),
6760   neq: __webpack_require__(65),
6761   gte: __webpack_require__(66),
6762   lte: __webpack_require__(67),
6763   cmp: __webpack_require__(68),
6764   coerce: __webpack_require__(69),
6765   Comparator: __webpack_require__(70),
6766   Range: __webpack_require__(71),
6767   satisfies: __webpack_require__(72),
6768   toComparators: __webpack_require__(73),
6769   maxSatisfying: __webpack_require__(74),
6770   minSatisfying: __webpack_require__(75),
6771   minVersion: __webpack_require__(76),
6772   validRange: __webpack_require__(77),
6773   outside: __webpack_require__(78),
6774   gtr: __webpack_require__(79),
6775   ltr: __webpack_require__(80),
6776   intersects: __webpack_require__(81),
6777   simplifyRange: __webpack_require__(82),
6778   subset: __webpack_require__(83),
6779 }
6780
6781
6782 /***/ }),
6783 /* 42 */
6784 /***/ (function(module, exports, __webpack_require__) {
6785
6786 const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(43)
6787 const debug = __webpack_require__(44)
6788 exports = module.exports = {}
6789
6790 // The actual regexps go on exports.re
6791 const re = exports.re = []
6792 const src = exports.src = []
6793 const t = exports.t = {}
6794 let R = 0
6795
6796 const createToken = (name, value, isGlobal) => {
6797   const index = R++
6798   debug(index, value)
6799   t[name] = index
6800   src[index] = value
6801   re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
6802 }
6803
6804 // The following Regular Expressions can be used for tokenizing,
6805 // validating, and parsing SemVer version strings.
6806
6807 // ## Numeric Identifier
6808 // A single `0`, or a non-zero digit followed by zero or more digits.
6809
6810 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
6811 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
6812
6813 // ## Non-numeric Identifier
6814 // Zero or more digits, followed by a letter or hyphen, and then zero or
6815 // more letters, digits, or hyphens.
6816
6817 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
6818
6819 // ## Main Version
6820 // Three dot-separated numeric identifiers.
6821
6822 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
6823                    `(${src[t.NUMERICIDENTIFIER]})\\.` +
6824                    `(${src[t.NUMERICIDENTIFIER]})`)
6825
6826 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6827                         `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
6828                         `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
6829
6830 // ## Pre-release Version Identifier
6831 // A numeric identifier, or a non-numeric identifier.
6832
6833 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
6834 }|${src[t.NONNUMERICIDENTIFIER]})`)
6835
6836 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
6837 }|${src[t.NONNUMERICIDENTIFIER]})`)
6838
6839 // ## Pre-release Version
6840 // Hyphen, followed by one or more dot-separated pre-release version
6841 // identifiers.
6842
6843 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
6844 }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
6845
6846 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
6847 }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
6848
6849 // ## Build Metadata Identifier
6850 // Any combination of digits, letters, or hyphens.
6851
6852 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
6853
6854 // ## Build Metadata
6855 // Plus sign, followed by one or more period-separated build metadata
6856 // identifiers.
6857
6858 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
6859 }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
6860
6861 // ## Full Version String
6862 // A main version, followed optionally by a pre-release version and
6863 // build metadata.
6864
6865 // Note that the only major, minor, patch, and pre-release sections of
6866 // the version string are capturing groups.  The build metadata is not a
6867 // capturing group, because it should not ever be used in version
6868 // comparison.
6869
6870 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
6871 }${src[t.PRERELEASE]}?${
6872   src[t.BUILD]}?`)
6873
6874 createToken('FULL', `^${src[t.FULLPLAIN]}$`)
6875
6876 // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
6877 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
6878 // common in the npm registry.
6879 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
6880 }${src[t.PRERELEASELOOSE]}?${
6881   src[t.BUILD]}?`)
6882
6883 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
6884
6885 createToken('GTLT', '((?:<|>)?=?)')
6886
6887 // Something like "2.*" or "1.2.x".
6888 // Note that "x.x" is a valid xRange identifer, meaning "any version"
6889 // Only the first item is strictly required.
6890 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
6891 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
6892
6893 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
6894                    `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6895                    `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
6896                    `(?:${src[t.PRERELEASE]})?${
6897                      src[t.BUILD]}?` +
6898                    `)?)?`)
6899
6900 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6901                         `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6902                         `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
6903                         `(?:${src[t.PRERELEASELOOSE]})?${
6904                           src[t.BUILD]}?` +
6905                         `)?)?`)
6906
6907 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
6908 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
6909
6910 // Coercion.
6911 // Extract anything that could conceivably be a part of a valid semver
6912 createToken('COERCE', `${'(^|[^\\d])' +
6913               '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
6914               `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6915               `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
6916               `(?:$|[^\\d])`)
6917 createToken('COERCERTL', src[t.COERCE], true)
6918
6919 // Tilde ranges.
6920 // Meaning is "reasonably at or greater than"
6921 createToken('LONETILDE', '(?:~>?)')
6922
6923 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
6924 exports.tildeTrimReplace = '$1~'
6925
6926 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
6927 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
6928
6929 // Caret ranges.
6930 // Meaning is "at least and backwards compatible with"
6931 createToken('LONECARET', '(?:\\^)')
6932
6933 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
6934 exports.caretTrimReplace = '$1^'
6935
6936 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
6937 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
6938
6939 // A simple gt/lt/eq thing, or just "" to indicate "any version"
6940 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
6941 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
6942
6943 // An expression to strip any whitespace between the gtlt and the thing
6944 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
6945 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
6946 }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
6947 exports.comparatorTrimReplace = '$1$2$3'
6948
6949 // Something like `1.2.3 - 1.2.4`
6950 // Note that these all use the loose form, because they'll be
6951 // checked against either the strict or loose comparator form
6952 // later.
6953 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
6954                    `\\s+-\\s+` +
6955                    `(${src[t.XRANGEPLAIN]})` +
6956                    `\\s*$`)
6957
6958 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
6959                         `\\s+-\\s+` +
6960                         `(${src[t.XRANGEPLAINLOOSE]})` +
6961                         `\\s*$`)
6962
6963 // Star ranges basically just allow anything at all.
6964 createToken('STAR', '(<|>)?=?\\s*\\*')
6965 // >=0.0.0 is like a star
6966 createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
6967 createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
6968
6969
6970 /***/ }),
6971 /* 43 */
6972 /***/ (function(module, exports) {
6973
6974 // Note: this is the semver.org version of the spec that it implements
6975 // Not necessarily the package version of this code.
6976 const SEMVER_SPEC_VERSION = '2.0.0'
6977
6978 const MAX_LENGTH = 256
6979 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
6980   /* istanbul ignore next */ 9007199254740991
6981
6982 // Max safe segment length for coercion.
6983 const MAX_SAFE_COMPONENT_LENGTH = 16
6984
6985 module.exports = {
6986   SEMVER_SPEC_VERSION,
6987   MAX_LENGTH,
6988   MAX_SAFE_INTEGER,
6989   MAX_SAFE_COMPONENT_LENGTH
6990 }
6991
6992
6993 /***/ }),
6994 /* 44 */
6995 /***/ (function(module, exports) {
6996
6997 const debug = (
6998   typeof process === 'object' &&
6999   process.env &&
7000   process.env.NODE_DEBUG &&
7001   /\bsemver\b/i.test(process.env.NODE_DEBUG)
7002 ) ? (...args) => console.error('SEMVER', ...args)
7003   : () => {}
7004
7005 module.exports = debug
7006
7007
7008 /***/ }),
7009 /* 45 */
7010 /***/ (function(module, exports, __webpack_require__) {
7011
7012 const debug = __webpack_require__(44)
7013 const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(43)
7014 const { re, t } = __webpack_require__(42)
7015
7016 const { compareIdentifiers } = __webpack_require__(46)
7017 class SemVer {
7018   constructor (version, options) {
7019     if (!options || typeof options !== 'object') {
7020       options = {
7021         loose: !!options,
7022         includePrerelease: false
7023       }
7024     }
7025     if (version instanceof SemVer) {
7026       if (version.loose === !!options.loose &&
7027           version.includePrerelease === !!options.includePrerelease) {
7028         return version
7029       } else {
7030         version = version.version
7031       }
7032     } else if (typeof version !== 'string') {
7033       throw new TypeError(`Invalid Version: ${version}`)
7034     }
7035
7036     if (version.length > MAX_LENGTH) {
7037       throw new TypeError(
7038         `version is longer than ${MAX_LENGTH} characters`
7039       )
7040     }
7041
7042     debug('SemVer', version, options)
7043     this.options = options
7044     this.loose = !!options.loose
7045     // this isn't actually relevant for versions, but keep it so that we
7046     // don't run into trouble passing this.options around.
7047     this.includePrerelease = !!options.includePrerelease
7048
7049     const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
7050
7051     if (!m) {
7052       throw new TypeError(`Invalid Version: ${version}`)
7053     }
7054
7055     this.raw = version
7056
7057     // these are actually numbers
7058     this.major = +m[1]
7059     this.minor = +m[2]
7060     this.patch = +m[3]
7061
7062     if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
7063       throw new TypeError('Invalid major version')
7064     }
7065
7066     if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
7067       throw new TypeError('Invalid minor version')
7068     }
7069
7070     if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
7071       throw new TypeError('Invalid patch version')
7072     }
7073
7074     // numberify any prerelease numeric ids
7075     if (!m[4]) {
7076       this.prerelease = []
7077     } else {
7078       this.prerelease = m[4].split('.').map((id) => {
7079         if (/^[0-9]+$/.test(id)) {
7080           const num = +id
7081           if (num >= 0 && num < MAX_SAFE_INTEGER) {
7082             return num
7083           }
7084         }
7085         return id
7086       })
7087     }
7088
7089     this.build = m[5] ? m[5].split('.') : []
7090     this.format()
7091   }
7092
7093   format () {
7094     this.version = `${this.major}.${this.minor}.${this.patch}`
7095     if (this.prerelease.length) {
7096       this.version += `-${this.prerelease.join('.')}`
7097     }
7098     return this.version
7099   }
7100
7101   toString () {
7102     return this.version
7103   }
7104
7105   compare (other) {
7106     debug('SemVer.compare', this.version, this.options, other)
7107     if (!(other instanceof SemVer)) {
7108       if (typeof other === 'string' && other === this.version) {
7109         return 0
7110       }
7111       other = new SemVer(other, this.options)
7112     }
7113
7114     if (other.version === this.version) {
7115       return 0
7116     }
7117
7118     return this.compareMain(other) || this.comparePre(other)
7119   }
7120
7121   compareMain (other) {
7122     if (!(other instanceof SemVer)) {
7123       other = new SemVer(other, this.options)
7124     }
7125
7126     return (
7127       compareIdentifiers(this.major, other.major) ||
7128       compareIdentifiers(this.minor, other.minor) ||
7129       compareIdentifiers(this.patch, other.patch)
7130     )
7131   }
7132
7133   comparePre (other) {
7134     if (!(other instanceof SemVer)) {
7135       other = new SemVer(other, this.options)
7136     }
7137
7138     // NOT having a prerelease is > having one
7139     if (this.prerelease.length && !other.prerelease.length) {
7140       return -1
7141     } else if (!this.prerelease.length && other.prerelease.length) {
7142       return 1
7143     } else if (!this.prerelease.length && !other.prerelease.length) {
7144       return 0
7145     }
7146
7147     let i = 0
7148     do {
7149       const a = this.prerelease[i]
7150       const b = other.prerelease[i]
7151       debug('prerelease compare', i, a, b)
7152       if (a === undefined && b === undefined) {
7153         return 0
7154       } else if (b === undefined) {
7155         return 1
7156       } else if (a === undefined) {
7157         return -1
7158       } else if (a === b) {
7159         continue
7160       } else {
7161         return compareIdentifiers(a, b)
7162       }
7163     } while (++i)
7164   }
7165
7166   compareBuild (other) {
7167     if (!(other instanceof SemVer)) {
7168       other = new SemVer(other, this.options)
7169     }
7170
7171     let i = 0
7172     do {
7173       const a = this.build[i]
7174       const b = other.build[i]
7175       debug('prerelease compare', i, a, b)
7176       if (a === undefined && b === undefined) {
7177         return 0
7178       } else if (b === undefined) {
7179         return 1
7180       } else if (a === undefined) {
7181         return -1
7182       } else if (a === b) {
7183         continue
7184       } else {
7185         return compareIdentifiers(a, b)
7186       }
7187     } while (++i)
7188   }
7189
7190   // preminor will bump the version up to the next minor release, and immediately
7191   // down to pre-release. premajor and prepatch work the same way.
7192   inc (release, identifier) {
7193     switch (release) {
7194       case 'premajor':
7195         this.prerelease.length = 0
7196         this.patch = 0
7197         this.minor = 0
7198         this.major++
7199         this.inc('pre', identifier)
7200         break
7201       case 'preminor':
7202         this.prerelease.length = 0
7203         this.patch = 0
7204         this.minor++
7205         this.inc('pre', identifier)
7206         break
7207       case 'prepatch':
7208         // If this is already a prerelease, it will bump to the next version
7209         // drop any prereleases that might already exist, since they are not
7210         // relevant at this point.
7211         this.prerelease.length = 0
7212         this.inc('patch', identifier)
7213         this.inc('pre', identifier)
7214         break
7215       // If the input is a non-prerelease version, this acts the same as
7216       // prepatch.
7217       case 'prerelease':
7218         if (this.prerelease.length === 0) {
7219           this.inc('patch', identifier)
7220         }
7221         this.inc('pre', identifier)
7222         break
7223
7224       case 'major':
7225         // If this is a pre-major version, bump up to the same major version.
7226         // Otherwise increment major.
7227         // 1.0.0-5 bumps to 1.0.0
7228         // 1.1.0 bumps to 2.0.0
7229         if (
7230           this.minor !== 0 ||
7231           this.patch !== 0 ||
7232           this.prerelease.length === 0
7233         ) {
7234           this.major++
7235         }
7236         this.minor = 0
7237         this.patch = 0
7238         this.prerelease = []
7239         break
7240       case 'minor':
7241         // If this is a pre-minor version, bump up to the same minor version.
7242         // Otherwise increment minor.
7243         // 1.2.0-5 bumps to 1.2.0
7244         // 1.2.1 bumps to 1.3.0
7245         if (this.patch !== 0 || this.prerelease.length === 0) {
7246           this.minor++
7247         }
7248         this.patch = 0
7249         this.prerelease = []
7250         break
7251       case 'patch':
7252         // If this is not a pre-release version, it will increment the patch.
7253         // If it is a pre-release it will bump up to the same patch version.
7254         // 1.2.0-5 patches to 1.2.0
7255         // 1.2.0 patches to 1.2.1
7256         if (this.prerelease.length === 0) {
7257           this.patch++
7258         }
7259         this.prerelease = []
7260         break
7261       // This probably shouldn't be used publicly.
7262       // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
7263       case 'pre':
7264         if (this.prerelease.length === 0) {
7265           this.prerelease = [0]
7266         } else {
7267           let i = this.prerelease.length
7268           while (--i >= 0) {
7269             if (typeof this.prerelease[i] === 'number') {
7270               this.prerelease[i]++
7271               i = -2
7272             }
7273           }
7274           if (i === -1) {
7275             // didn't increment anything
7276             this.prerelease.push(0)
7277           }
7278         }
7279         if (identifier) {
7280           // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
7281           // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
7282           if (this.prerelease[0] === identifier) {
7283             if (isNaN(this.prerelease[1])) {
7284               this.prerelease = [identifier, 0]
7285             }
7286           } else {
7287             this.prerelease = [identifier, 0]
7288           }
7289         }
7290         break
7291
7292       default:
7293         throw new Error(`invalid increment argument: ${release}`)
7294     }
7295     this.format()
7296     this.raw = this.version
7297     return this
7298   }
7299 }
7300
7301 module.exports = SemVer
7302
7303
7304 /***/ }),
7305 /* 46 */
7306 /***/ (function(module, exports) {
7307
7308 const numeric = /^[0-9]+$/
7309 const compareIdentifiers = (a, b) => {
7310   const anum = numeric.test(a)
7311   const bnum = numeric.test(b)
7312
7313   if (anum && bnum) {
7314     a = +a
7315     b = +b
7316   }
7317
7318   return a === b ? 0
7319     : (anum && !bnum) ? -1
7320     : (bnum && !anum) ? 1
7321     : a < b ? -1
7322     : 1
7323 }
7324
7325 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
7326
7327 module.exports = {
7328   compareIdentifiers,
7329   rcompareIdentifiers
7330 }
7331
7332
7333 /***/ }),
7334 /* 47 */
7335 /***/ (function(module, exports, __webpack_require__) {
7336
7337 const {MAX_LENGTH} = __webpack_require__(43)
7338 const { re, t } = __webpack_require__(42)
7339 const SemVer = __webpack_require__(45)
7340
7341 const parse = (version, options) => {
7342   if (!options || typeof options !== 'object') {
7343     options = {
7344       loose: !!options,
7345       includePrerelease: false
7346     }
7347   }
7348
7349   if (version instanceof SemVer) {
7350     return version
7351   }
7352
7353   if (typeof version !== 'string') {
7354     return null
7355   }
7356
7357   if (version.length > MAX_LENGTH) {
7358     return null
7359   }
7360
7361   const r = options.loose ? re[t.LOOSE] : re[t.FULL]
7362   if (!r.test(version)) {
7363     return null
7364   }
7365
7366   try {
7367     return new SemVer(version, options)
7368   } catch (er) {
7369     return null
7370   }
7371 }
7372
7373 module.exports = parse
7374
7375
7376 /***/ }),
7377 /* 48 */
7378 /***/ (function(module, exports, __webpack_require__) {
7379
7380 const parse = __webpack_require__(47)
7381 const valid = (version, options) => {
7382   const v = parse(version, options)
7383   return v ? v.version : null
7384 }
7385 module.exports = valid
7386
7387
7388 /***/ }),
7389 /* 49 */
7390 /***/ (function(module, exports, __webpack_require__) {
7391
7392 const parse = __webpack_require__(47)
7393 const clean = (version, options) => {
7394   const s = parse(version.trim().replace(/^[=v]+/, ''), options)
7395   return s ? s.version : null
7396 }
7397 module.exports = clean
7398
7399
7400 /***/ }),
7401 /* 50 */
7402 /***/ (function(module, exports, __webpack_require__) {
7403
7404 const SemVer = __webpack_require__(45)
7405
7406 const inc = (version, release, options, identifier) => {
7407   if (typeof (options) === 'string') {
7408     identifier = options
7409     options = undefined
7410   }
7411
7412   try {
7413     return new SemVer(version, options).inc(release, identifier).version
7414   } catch (er) {
7415     return null
7416   }
7417 }
7418 module.exports = inc
7419
7420
7421 /***/ }),
7422 /* 51 */
7423 /***/ (function(module, exports, __webpack_require__) {
7424
7425 const parse = __webpack_require__(47)
7426 const eq = __webpack_require__(52)
7427
7428 const diff = (version1, version2) => {
7429   if (eq(version1, version2)) {
7430     return null
7431   } else {
7432     const v1 = parse(version1)
7433     const v2 = parse(version2)
7434     const hasPre = v1.prerelease.length || v2.prerelease.length
7435     const prefix = hasPre ? 'pre' : ''
7436     const defaultResult = hasPre ? 'prerelease' : ''
7437     for (const key in v1) {
7438       if (key === 'major' || key === 'minor' || key === 'patch') {
7439         if (v1[key] !== v2[key]) {
7440           return prefix + key
7441         }
7442       }
7443     }
7444     return defaultResult // may be undefined
7445   }
7446 }
7447 module.exports = diff
7448
7449
7450 /***/ }),
7451 /* 52 */
7452 /***/ (function(module, exports, __webpack_require__) {
7453
7454 const compare = __webpack_require__(53)
7455 const eq = (a, b, loose) => compare(a, b, loose) === 0
7456 module.exports = eq
7457
7458
7459 /***/ }),
7460 /* 53 */
7461 /***/ (function(module, exports, __webpack_require__) {
7462
7463 const SemVer = __webpack_require__(45)
7464 const compare = (a, b, loose) =>
7465   new SemVer(a, loose).compare(new SemVer(b, loose))
7466
7467 module.exports = compare
7468
7469
7470 /***/ }),
7471 /* 54 */
7472 /***/ (function(module, exports, __webpack_require__) {
7473
7474 const SemVer = __webpack_require__(45)
7475 const major = (a, loose) => new SemVer(a, loose).major
7476 module.exports = major
7477
7478
7479 /***/ }),
7480 /* 55 */
7481 /***/ (function(module, exports, __webpack_require__) {
7482
7483 const SemVer = __webpack_require__(45)
7484 const minor = (a, loose) => new SemVer(a, loose).minor
7485 module.exports = minor
7486
7487
7488 /***/ }),
7489 /* 56 */
7490 /***/ (function(module, exports, __webpack_require__) {
7491
7492 const SemVer = __webpack_require__(45)
7493 const patch = (a, loose) => new SemVer(a, loose).patch
7494 module.exports = patch
7495
7496
7497 /***/ }),
7498 /* 57 */
7499 /***/ (function(module, exports, __webpack_require__) {
7500
7501 const parse = __webpack_require__(47)
7502 const prerelease = (version, options) => {
7503   const parsed = parse(version, options)
7504   return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
7505 }
7506 module.exports = prerelease
7507
7508
7509 /***/ }),
7510 /* 58 */
7511 /***/ (function(module, exports, __webpack_require__) {
7512
7513 const compare = __webpack_require__(53)
7514 const rcompare = (a, b, loose) => compare(b, a, loose)
7515 module.exports = rcompare
7516
7517
7518 /***/ }),
7519 /* 59 */
7520 /***/ (function(module, exports, __webpack_require__) {
7521
7522 const compare = __webpack_require__(53)
7523 const compareLoose = (a, b) => compare(a, b, true)
7524 module.exports = compareLoose
7525
7526
7527 /***/ }),
7528 /* 60 */
7529 /***/ (function(module, exports, __webpack_require__) {
7530
7531 const SemVer = __webpack_require__(45)
7532 const compareBuild = (a, b, loose) => {
7533   const versionA = new SemVer(a, loose)
7534   const versionB = new SemVer(b, loose)
7535   return versionA.compare(versionB) || versionA.compareBuild(versionB)
7536 }
7537 module.exports = compareBuild
7538
7539
7540 /***/ }),
7541 /* 61 */
7542 /***/ (function(module, exports, __webpack_require__) {
7543
7544 const compareBuild = __webpack_require__(60)
7545 const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
7546 module.exports = sort
7547
7548
7549 /***/ }),
7550 /* 62 */
7551 /***/ (function(module, exports, __webpack_require__) {
7552
7553 const compareBuild = __webpack_require__(60)
7554 const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
7555 module.exports = rsort
7556
7557
7558 /***/ }),
7559 /* 63 */
7560 /***/ (function(module, exports, __webpack_require__) {
7561
7562 const compare = __webpack_require__(53)
7563 const gt = (a, b, loose) => compare(a, b, loose) > 0
7564 module.exports = gt
7565
7566
7567 /***/ }),
7568 /* 64 */
7569 /***/ (function(module, exports, __webpack_require__) {
7570
7571 const compare = __webpack_require__(53)
7572 const lt = (a, b, loose) => compare(a, b, loose) < 0
7573 module.exports = lt
7574
7575
7576 /***/ }),
7577 /* 65 */
7578 /***/ (function(module, exports, __webpack_require__) {
7579
7580 const compare = __webpack_require__(53)
7581 const neq = (a, b, loose) => compare(a, b, loose) !== 0
7582 module.exports = neq
7583
7584
7585 /***/ }),
7586 /* 66 */
7587 /***/ (function(module, exports, __webpack_require__) {
7588
7589 const compare = __webpack_require__(53)
7590 const gte = (a, b, loose) => compare(a, b, loose) >= 0
7591 module.exports = gte
7592
7593
7594 /***/ }),
7595 /* 67 */
7596 /***/ (function(module, exports, __webpack_require__) {
7597
7598 const compare = __webpack_require__(53)
7599 const lte = (a, b, loose) => compare(a, b, loose) <= 0
7600 module.exports = lte
7601
7602
7603 /***/ }),
7604 /* 68 */
7605 /***/ (function(module, exports, __webpack_require__) {
7606
7607 const eq = __webpack_require__(52)
7608 const neq = __webpack_require__(65)
7609 const gt = __webpack_require__(63)
7610 const gte = __webpack_require__(66)
7611 const lt = __webpack_require__(64)
7612 const lte = __webpack_require__(67)
7613
7614 const cmp = (a, op, b, loose) => {
7615   switch (op) {
7616     case '===':
7617       if (typeof a === 'object')
7618         a = a.version
7619       if (typeof b === 'object')
7620         b = b.version
7621       return a === b
7622
7623     case '!==':
7624       if (typeof a === 'object')
7625         a = a.version
7626       if (typeof b === 'object')
7627         b = b.version
7628       return a !== b
7629
7630     case '':
7631     case '=':
7632     case '==':
7633       return eq(a, b, loose)
7634
7635     case '!=':
7636       return neq(a, b, loose)
7637
7638     case '>':
7639       return gt(a, b, loose)
7640
7641     case '>=':
7642       return gte(a, b, loose)
7643
7644     case '<':
7645       return lt(a, b, loose)
7646
7647     case '<=':
7648       return lte(a, b, loose)
7649
7650     default:
7651       throw new TypeError(`Invalid operator: ${op}`)
7652   }
7653 }
7654 module.exports = cmp
7655
7656
7657 /***/ }),
7658 /* 69 */
7659 /***/ (function(module, exports, __webpack_require__) {
7660
7661 const SemVer = __webpack_require__(45)
7662 const parse = __webpack_require__(47)
7663 const {re, t} = __webpack_require__(42)
7664
7665 const coerce = (version, options) => {
7666   if (version instanceof SemVer) {
7667     return version
7668   }
7669
7670   if (typeof version === 'number') {
7671     version = String(version)
7672   }
7673
7674   if (typeof version !== 'string') {
7675     return null
7676   }
7677
7678   options = options || {}
7679
7680   let match = null
7681   if (!options.rtl) {
7682     match = version.match(re[t.COERCE])
7683   } else {
7684     // Find the right-most coercible string that does not share
7685     // a terminus with a more left-ward coercible string.
7686     // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
7687     //
7688     // Walk through the string checking with a /g regexp
7689     // Manually set the index so as to pick up overlapping matches.
7690     // Stop when we get a match that ends at the string end, since no
7691     // coercible string can be more right-ward without the same terminus.
7692     let next
7693     while ((next = re[t.COERCERTL].exec(version)) &&
7694         (!match || match.index + match[0].length !== version.length)
7695     ) {
7696       if (!match ||
7697             next.index + next[0].length !== match.index + match[0].length) {
7698         match = next
7699       }
7700       re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
7701     }
7702     // leave it in a clean state
7703     re[t.COERCERTL].lastIndex = -1
7704   }
7705
7706   if (match === null)
7707     return null
7708
7709   return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
7710 }
7711 module.exports = coerce
7712
7713
7714 /***/ }),
7715 /* 70 */
7716 /***/ (function(module, exports, __webpack_require__) {
7717
7718 const ANY = Symbol('SemVer ANY')
7719 // hoisted class for cyclic dependency
7720 class Comparator {
7721   static get ANY () {
7722     return ANY
7723   }
7724   constructor (comp, options) {
7725     if (!options || typeof options !== 'object') {
7726       options = {
7727         loose: !!options,
7728         includePrerelease: false
7729       }
7730     }
7731
7732     if (comp instanceof Comparator) {
7733       if (comp.loose === !!options.loose) {
7734         return comp
7735       } else {
7736         comp = comp.value
7737       }
7738     }
7739
7740     debug('comparator', comp, options)
7741     this.options = options
7742     this.loose = !!options.loose
7743     this.parse(comp)
7744
7745     if (this.semver === ANY) {
7746       this.value = ''
7747     } else {
7748       this.value = this.operator + this.semver.version
7749     }
7750
7751     debug('comp', this)
7752   }
7753
7754   parse (comp) {
7755     const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7756     const m = comp.match(r)
7757
7758     if (!m) {
7759       throw new TypeError(`Invalid comparator: ${comp}`)
7760     }
7761
7762     this.operator = m[1] !== undefined ? m[1] : ''
7763     if (this.operator === '=') {
7764       this.operator = ''
7765     }
7766
7767     // if it literally is just '>' or '' then allow anything.
7768     if (!m[2]) {
7769       this.semver = ANY
7770     } else {
7771       this.semver = new SemVer(m[2], this.options.loose)
7772     }
7773   }
7774
7775   toString () {
7776     return this.value
7777   }
7778
7779   test (version) {
7780     debug('Comparator.test', version, this.options.loose)
7781
7782     if (this.semver === ANY || version === ANY) {
7783       return true
7784     }
7785
7786     if (typeof version === 'string') {
7787       try {
7788         version = new SemVer(version, this.options)
7789       } catch (er) {
7790         return false
7791       }
7792     }
7793
7794     return cmp(version, this.operator, this.semver, this.options)
7795   }
7796
7797   intersects (comp, options) {
7798     if (!(comp instanceof Comparator)) {
7799       throw new TypeError('a Comparator is required')
7800     }
7801
7802     if (!options || typeof options !== 'object') {
7803       options = {
7804         loose: !!options,
7805         includePrerelease: false
7806       }
7807     }
7808
7809     if (this.operator === '') {
7810       if (this.value === '') {
7811         return true
7812       }
7813       return new Range(comp.value, options).test(this.value)
7814     } else if (comp.operator === '') {
7815       if (comp.value === '') {
7816         return true
7817       }
7818       return new Range(this.value, options).test(comp.semver)
7819     }
7820
7821     const sameDirectionIncreasing =
7822       (this.operator === '>=' || this.operator === '>') &&
7823       (comp.operator === '>=' || comp.operator === '>')
7824     const sameDirectionDecreasing =
7825       (this.operator === '<=' || this.operator === '<') &&
7826       (comp.operator === '<=' || comp.operator === '<')
7827     const sameSemVer = this.semver.version === comp.semver.version
7828     const differentDirectionsInclusive =
7829       (this.operator === '>=' || this.operator === '<=') &&
7830       (comp.operator === '>=' || comp.operator === '<=')
7831     const oppositeDirectionsLessThan =
7832       cmp(this.semver, '<', comp.semver, options) &&
7833       (this.operator === '>=' || this.operator === '>') &&
7834         (comp.operator === '<=' || comp.operator === '<')
7835     const oppositeDirectionsGreaterThan =
7836       cmp(this.semver, '>', comp.semver, options) &&
7837       (this.operator === '<=' || this.operator === '<') &&
7838         (comp.operator === '>=' || comp.operator === '>')
7839
7840     return (
7841       sameDirectionIncreasing ||
7842       sameDirectionDecreasing ||
7843       (sameSemVer && differentDirectionsInclusive) ||
7844       oppositeDirectionsLessThan ||
7845       oppositeDirectionsGreaterThan
7846     )
7847   }
7848 }
7849
7850 module.exports = Comparator
7851
7852 const {re, t} = __webpack_require__(42)
7853 const cmp = __webpack_require__(68)
7854 const debug = __webpack_require__(44)
7855 const SemVer = __webpack_require__(45)
7856 const Range = __webpack_require__(71)
7857
7858
7859 /***/ }),
7860 /* 71 */
7861 /***/ (function(module, exports, __webpack_require__) {
7862
7863 // hoisted class for cyclic dependency
7864 class Range {
7865   constructor (range, options) {
7866     if (!options || typeof options !== 'object') {
7867       options = {
7868         loose: !!options,
7869         includePrerelease: false
7870       }
7871     }
7872
7873     if (range instanceof Range) {
7874       if (
7875         range.loose === !!options.loose &&
7876         range.includePrerelease === !!options.includePrerelease
7877       ) {
7878         return range
7879       } else {
7880         return new Range(range.raw, options)
7881       }
7882     }
7883
7884     if (range instanceof Comparator) {
7885       // just put it in the set and return
7886       this.raw = range.value
7887       this.set = [[range]]
7888       this.format()
7889       return this
7890     }
7891
7892     this.options = options
7893     this.loose = !!options.loose
7894     this.includePrerelease = !!options.includePrerelease
7895
7896     // First, split based on boolean or ||
7897     this.raw = range
7898     this.set = range
7899       .split(/\s*\|\|\s*/)
7900       // map the range to a 2d array of comparators
7901       .map(range => this.parseRange(range.trim()))
7902       // throw out any comparator lists that are empty
7903       // this generally means that it was not a valid range, which is allowed
7904       // in loose mode, but will still throw if the WHOLE range is invalid.
7905       .filter(c => c.length)
7906
7907     if (!this.set.length) {
7908       throw new TypeError(`Invalid SemVer Range: ${range}`)
7909     }
7910
7911     this.format()
7912   }
7913
7914   format () {
7915     this.range = this.set
7916       .map((comps) => {
7917         return comps.join(' ').trim()
7918       })
7919       .join('||')
7920       .trim()
7921     return this.range
7922   }
7923
7924   toString () {
7925     return this.range
7926   }
7927
7928   parseRange (range) {
7929     const loose = this.options.loose
7930     range = range.trim()
7931     // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
7932     const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
7933     range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
7934     debug('hyphen replace', range)
7935     // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
7936     range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
7937     debug('comparator trim', range, re[t.COMPARATORTRIM])
7938
7939     // `~ 1.2.3` => `~1.2.3`
7940     range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
7941
7942     // `^ 1.2.3` => `^1.2.3`
7943     range = range.replace(re[t.CARETTRIM], caretTrimReplace)
7944
7945     // normalize spaces
7946     range = range.split(/\s+/).join(' ')
7947
7948     // At this point, the range is completely trimmed and
7949     // ready to be split into comparators.
7950
7951     const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
7952     return range
7953       .split(' ')
7954       .map(comp => parseComparator(comp, this.options))
7955       .join(' ')
7956       .split(/\s+/)
7957       .map(comp => replaceGTE0(comp, this.options))
7958       // in loose mode, throw out any that are not valid comparators
7959       .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
7960       .map(comp => new Comparator(comp, this.options))
7961   }
7962
7963   intersects (range, options) {
7964     if (!(range instanceof Range)) {
7965       throw new TypeError('a Range is required')
7966     }
7967
7968     return this.set.some((thisComparators) => {
7969       return (
7970         isSatisfiable(thisComparators, options) &&
7971         range.set.some((rangeComparators) => {
7972           return (
7973             isSatisfiable(rangeComparators, options) &&
7974             thisComparators.every((thisComparator) => {
7975               return rangeComparators.every((rangeComparator) => {
7976                 return thisComparator.intersects(rangeComparator, options)
7977               })
7978             })
7979           )
7980         })
7981       )
7982     })
7983   }
7984
7985   // if ANY of the sets match ALL of its comparators, then pass
7986   test (version) {
7987     if (!version) {
7988       return false
7989     }
7990
7991     if (typeof version === 'string') {
7992       try {
7993         version = new SemVer(version, this.options)
7994       } catch (er) {
7995         return false
7996       }
7997     }
7998
7999     for (let i = 0; i < this.set.length; i++) {
8000       if (testSet(this.set[i], version, this.options)) {
8001         return true
8002       }
8003     }
8004     return false
8005   }
8006 }
8007 module.exports = Range
8008
8009 const Comparator = __webpack_require__(70)
8010 const debug = __webpack_require__(44)
8011 const SemVer = __webpack_require__(45)
8012 const {
8013   re,
8014   t,
8015   comparatorTrimReplace,
8016   tildeTrimReplace,
8017   caretTrimReplace
8018 } = __webpack_require__(42)
8019
8020 // take a set of comparators and determine whether there
8021 // exists a version which can satisfy it
8022 const isSatisfiable = (comparators, options) => {
8023   let result = true
8024   const remainingComparators = comparators.slice()
8025   let testComparator = remainingComparators.pop()
8026
8027   while (result && remainingComparators.length) {
8028     result = remainingComparators.every((otherComparator) => {
8029       return testComparator.intersects(otherComparator, options)
8030     })
8031
8032     testComparator = remainingComparators.pop()
8033   }
8034
8035   return result
8036 }
8037
8038 // comprised of xranges, tildes, stars, and gtlt's at this point.
8039 // already replaced the hyphen ranges
8040 // turn into a set of JUST comparators.
8041 const parseComparator = (comp, options) => {
8042   debug('comp', comp, options)
8043   comp = replaceCarets(comp, options)
8044   debug('caret', comp)
8045   comp = replaceTildes(comp, options)
8046   debug('tildes', comp)
8047   comp = replaceXRanges(comp, options)
8048   debug('xrange', comp)
8049   comp = replaceStars(comp, options)
8050   debug('stars', comp)
8051   return comp
8052 }
8053
8054 const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
8055
8056 // ~, ~> --> * (any, kinda silly)
8057 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
8058 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
8059 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
8060 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
8061 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
8062 const replaceTildes = (comp, options) =>
8063   comp.trim().split(/\s+/).map((comp) => {
8064     return replaceTilde(comp, options)
8065   }).join(' ')
8066
8067 const replaceTilde = (comp, options) => {
8068   const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
8069   return comp.replace(r, (_, M, m, p, pr) => {
8070     debug('tilde', comp, _, M, m, p, pr)
8071     let ret
8072
8073     if (isX(M)) {
8074       ret = ''
8075     } else if (isX(m)) {
8076       ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
8077     } else if (isX(p)) {
8078       // ~1.2 == >=1.2.0 <1.3.0-0
8079       ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
8080     } else if (pr) {
8081       debug('replaceTilde pr', pr)
8082       ret = `>=${M}.${m}.${p}-${pr
8083       } <${M}.${+m + 1}.0-0`
8084     } else {
8085       // ~1.2.3 == >=1.2.3 <1.3.0-0
8086       ret = `>=${M}.${m}.${p
8087       } <${M}.${+m + 1}.0-0`
8088     }
8089
8090     debug('tilde return', ret)
8091     return ret
8092   })
8093 }
8094
8095 // ^ --> * (any, kinda silly)
8096 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
8097 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
8098 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
8099 // ^1.2.3 --> >=1.2.3 <2.0.0-0
8100 // ^1.2.0 --> >=1.2.0 <2.0.0-0
8101 const replaceCarets = (comp, options) =>
8102   comp.trim().split(/\s+/).map((comp) => {
8103     return replaceCaret(comp, options)
8104   }).join(' ')
8105
8106 const replaceCaret = (comp, options) => {
8107   debug('caret', comp, options)
8108   const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
8109   const z = options.includePrerelease ? '-0' : ''
8110   return comp.replace(r, (_, M, m, p, pr) => {
8111     debug('caret', comp, _, M, m, p, pr)
8112     let ret
8113
8114     if (isX(M)) {
8115       ret = ''
8116     } else if (isX(m)) {
8117       ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
8118     } else if (isX(p)) {
8119       if (M === '0') {
8120         ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
8121       } else {
8122         ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
8123       }
8124     } else if (pr) {
8125       debug('replaceCaret pr', pr)
8126       if (M === '0') {
8127         if (m === '0') {
8128           ret = `>=${M}.${m}.${p}-${pr
8129           } <${M}.${m}.${+p + 1}-0`
8130         } else {
8131           ret = `>=${M}.${m}.${p}-${pr
8132           } <${M}.${+m + 1}.0-0`
8133         }
8134       } else {
8135         ret = `>=${M}.${m}.${p}-${pr
8136         } <${+M + 1}.0.0-0`
8137       }
8138     } else {
8139       debug('no pr')
8140       if (M === '0') {
8141         if (m === '0') {
8142           ret = `>=${M}.${m}.${p
8143           }${z} <${M}.${m}.${+p + 1}-0`
8144         } else {
8145           ret = `>=${M}.${m}.${p
8146           }${z} <${M}.${+m + 1}.0-0`
8147         }
8148       } else {
8149         ret = `>=${M}.${m}.${p
8150         } <${+M + 1}.0.0-0`
8151       }
8152     }
8153
8154     debug('caret return', ret)
8155     return ret
8156   })
8157 }
8158
8159 const replaceXRanges = (comp, options) => {
8160   debug('replaceXRanges', comp, options)
8161   return comp.split(/\s+/).map((comp) => {
8162     return replaceXRange(comp, options)
8163   }).join(' ')
8164 }
8165
8166 const replaceXRange = (comp, options) => {
8167   comp = comp.trim()
8168   const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
8169   return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
8170     debug('xRange', comp, ret, gtlt, M, m, p, pr)
8171     const xM = isX(M)
8172     const xm = xM || isX(m)
8173     const xp = xm || isX(p)
8174     const anyX = xp
8175
8176     if (gtlt === '=' && anyX) {
8177       gtlt = ''
8178     }
8179
8180     // if we're including prereleases in the match, then we need
8181     // to fix this to -0, the lowest possible prerelease value
8182     pr = options.includePrerelease ? '-0' : ''
8183
8184     if (xM) {
8185       if (gtlt === '>' || gtlt === '<') {
8186         // nothing is allowed
8187         ret = '<0.0.0-0'
8188       } else {
8189         // nothing is forbidden
8190         ret = '*'
8191       }
8192     } else if (gtlt && anyX) {
8193       // we know patch is an x, because we have any x at all.
8194       // replace X with 0
8195       if (xm) {
8196         m = 0
8197       }
8198       p = 0
8199
8200       if (gtlt === '>') {
8201         // >1 => >=2.0.0
8202         // >1.2 => >=1.3.0
8203         gtlt = '>='
8204         if (xm) {
8205           M = +M + 1
8206           m = 0
8207           p = 0
8208         } else {
8209           m = +m + 1
8210           p = 0
8211         }
8212       } else if (gtlt === '<=') {
8213         // <=0.7.x is actually <0.8.0, since any 0.7.x should
8214         // pass.  Similarly, <=7.x is actually <8.0.0, etc.
8215         gtlt = '<'
8216         if (xm) {
8217           M = +M + 1
8218         } else {
8219           m = +m + 1
8220         }
8221       }
8222
8223       if (gtlt === '<')
8224         pr = '-0'
8225
8226       ret = `${gtlt + M}.${m}.${p}${pr}`
8227     } else if (xm) {
8228       ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
8229     } else if (xp) {
8230       ret = `>=${M}.${m}.0${pr
8231       } <${M}.${+m + 1}.0-0`
8232     }
8233
8234     debug('xRange return', ret)
8235
8236     return ret
8237   })
8238 }
8239
8240 // Because * is AND-ed with everything else in the comparator,
8241 // and '' means "any version", just remove the *s entirely.
8242 const replaceStars = (comp, options) => {
8243   debug('replaceStars', comp, options)
8244   // Looseness is ignored here.  star is always as loose as it gets!
8245   return comp.trim().replace(re[t.STAR], '')
8246 }
8247
8248 const replaceGTE0 = (comp, options) => {
8249   debug('replaceGTE0', comp, options)
8250   return comp.trim()
8251     .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
8252 }
8253
8254 // This function is passed to string.replace(re[t.HYPHENRANGE])
8255 // M, m, patch, prerelease, build
8256 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
8257 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
8258 // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
8259 const hyphenReplace = incPr => ($0,
8260   from, fM, fm, fp, fpr, fb,
8261   to, tM, tm, tp, tpr, tb) => {
8262   if (isX(fM)) {
8263     from = ''
8264   } else if (isX(fm)) {
8265     from = `>=${fM}.0.0${incPr ? '-0' : ''}`
8266   } else if (isX(fp)) {
8267     from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
8268   } else if (fpr) {
8269     from = `>=${from}`
8270   } else {
8271     from = `>=${from}${incPr ? '-0' : ''}`
8272   }
8273
8274   if (isX(tM)) {
8275     to = ''
8276   } else if (isX(tm)) {
8277     to = `<${+tM + 1}.0.0-0`
8278   } else if (isX(tp)) {
8279     to = `<${tM}.${+tm + 1}.0-0`
8280   } else if (tpr) {
8281     to = `<=${tM}.${tm}.${tp}-${tpr}`
8282   } else if (incPr) {
8283     to = `<${tM}.${tm}.${+tp + 1}-0`
8284   } else {
8285     to = `<=${to}`
8286   }
8287
8288   return (`${from} ${to}`).trim()
8289 }
8290
8291 const testSet = (set, version, options) => {
8292   for (let i = 0; i < set.length; i++) {
8293     if (!set[i].test(version)) {
8294       return false
8295     }
8296   }
8297
8298   if (version.prerelease.length && !options.includePrerelease) {
8299     // Find the set of versions that are allowed to have prereleases
8300     // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
8301     // That should allow `1.2.3-pr.2` to pass.
8302     // However, `1.2.4-alpha.notready` should NOT be allowed,
8303     // even though it's within the range set by the comparators.
8304     for (let i = 0; i < set.length; i++) {
8305       debug(set[i].semver)
8306       if (set[i].semver === Comparator.ANY) {
8307         continue
8308       }
8309
8310       if (set[i].semver.prerelease.length > 0) {
8311         const allowed = set[i].semver
8312         if (allowed.major === version.major &&
8313             allowed.minor === version.minor &&
8314             allowed.patch === version.patch) {
8315           return true
8316         }
8317       }
8318     }
8319
8320     // Version has a -pre, but it's not one of the ones we like.
8321     return false
8322   }
8323
8324   return true
8325 }
8326
8327
8328 /***/ }),
8329 /* 72 */
8330 /***/ (function(module, exports, __webpack_require__) {
8331
8332 const Range = __webpack_require__(71)
8333 const satisfies = (version, range, options) => {
8334   try {
8335     range = new Range(range, options)
8336   } catch (er) {
8337     return false
8338   }
8339   return range.test(version)
8340 }
8341 module.exports = satisfies
8342
8343
8344 /***/ }),
8345 /* 73 */
8346 /***/ (function(module, exports, __webpack_require__) {
8347
8348 const Range = __webpack_require__(71)
8349
8350 // Mostly just for testing and legacy API reasons
8351 const toComparators = (range, options) =>
8352   new Range(range, options).set
8353     .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
8354
8355 module.exports = toComparators
8356
8357
8358 /***/ }),
8359 /* 74 */
8360 /***/ (function(module, exports, __webpack_require__) {
8361
8362 const SemVer = __webpack_require__(45)
8363 const Range = __webpack_require__(71)
8364
8365 const maxSatisfying = (versions, range, options) => {
8366   let max = null
8367   let maxSV = null
8368   let rangeObj = null
8369   try {
8370     rangeObj = new Range(range, options)
8371   } catch (er) {
8372     return null
8373   }
8374   versions.forEach((v) => {
8375     if (rangeObj.test(v)) {
8376       // satisfies(v, range, options)
8377       if (!max || maxSV.compare(v) === -1) {
8378         // compare(max, v, true)
8379         max = v
8380         maxSV = new SemVer(max, options)
8381       }
8382     }
8383   })
8384   return max
8385 }
8386 module.exports = maxSatisfying
8387
8388
8389 /***/ }),
8390 /* 75 */
8391 /***/ (function(module, exports, __webpack_require__) {
8392
8393 const SemVer = __webpack_require__(45)
8394 const Range = __webpack_require__(71)
8395 const minSatisfying = (versions, range, options) => {
8396   let min = null
8397   let minSV = null
8398   let rangeObj = null
8399   try {
8400     rangeObj = new Range(range, options)
8401   } catch (er) {
8402     return null
8403   }
8404   versions.forEach((v) => {
8405     if (rangeObj.test(v)) {
8406       // satisfies(v, range, options)
8407       if (!min || minSV.compare(v) === 1) {
8408         // compare(min, v, true)
8409         min = v
8410         minSV = new SemVer(min, options)
8411       }
8412     }
8413   })
8414   return min
8415 }
8416 module.exports = minSatisfying
8417
8418
8419 /***/ }),
8420 /* 76 */
8421 /***/ (function(module, exports, __webpack_require__) {
8422
8423 const SemVer = __webpack_require__(45)
8424 const Range = __webpack_require__(71)
8425 const gt = __webpack_require__(63)
8426
8427 const minVersion = (range, loose) => {
8428   range = new Range(range, loose)
8429
8430   let minver = new SemVer('0.0.0')
8431   if (range.test(minver)) {
8432     return minver
8433   }
8434
8435   minver = new SemVer('0.0.0-0')
8436   if (range.test(minver)) {
8437     return minver
8438   }
8439
8440   minver = null
8441   for (let i = 0; i < range.set.length; ++i) {
8442     const comparators = range.set[i]
8443
8444     comparators.forEach((comparator) => {
8445       // Clone to avoid manipulating the comparator's semver object.
8446       const compver = new SemVer(comparator.semver.version)
8447       switch (comparator.operator) {
8448         case '>':
8449           if (compver.prerelease.length === 0) {
8450             compver.patch++
8451           } else {
8452             compver.prerelease.push(0)
8453           }
8454           compver.raw = compver.format()
8455           /* fallthrough */
8456         case '':
8457         case '>=':
8458           if (!minver || gt(minver, compver)) {
8459             minver = compver
8460           }
8461           break
8462         case '<':
8463         case '<=':
8464           /* Ignore maximum versions */
8465           break
8466         /* istanbul ignore next */
8467         default:
8468           throw new Error(`Unexpected operation: ${comparator.operator}`)
8469       }
8470     })
8471   }
8472
8473   if (minver && range.test(minver)) {
8474     return minver
8475   }
8476
8477   return null
8478 }
8479 module.exports = minVersion
8480
8481
8482 /***/ }),
8483 /* 77 */
8484 /***/ (function(module, exports, __webpack_require__) {
8485
8486 const Range = __webpack_require__(71)
8487 const validRange = (range, options) => {
8488   try {
8489     // Return '*' instead of '' so that truthiness works.
8490     // This will throw if it's invalid anyway
8491     return new Range(range, options).range || '*'
8492   } catch (er) {
8493     return null
8494   }
8495 }
8496 module.exports = validRange
8497
8498
8499 /***/ }),
8500 /* 78 */
8501 /***/ (function(module, exports, __webpack_require__) {
8502
8503 const SemVer = __webpack_require__(45)
8504 const Comparator = __webpack_require__(70)
8505 const {ANY} = Comparator
8506 const Range = __webpack_require__(71)
8507 const satisfies = __webpack_require__(72)
8508 const gt = __webpack_require__(63)
8509 const lt = __webpack_require__(64)
8510 const lte = __webpack_require__(67)
8511 const gte = __webpack_require__(66)
8512
8513 const outside = (version, range, hilo, options) => {
8514   version = new SemVer(version, options)
8515   range = new Range(range, options)
8516
8517   let gtfn, ltefn, ltfn, comp, ecomp
8518   switch (hilo) {
8519     case '>':
8520       gtfn = gt
8521       ltefn = lte
8522       ltfn = lt
8523       comp = '>'
8524       ecomp = '>='
8525       break
8526     case '<':
8527       gtfn = lt
8528       ltefn = gte
8529       ltfn = gt
8530       comp = '<'
8531       ecomp = '<='
8532       break
8533     default:
8534       throw new TypeError('Must provide a hilo val of "<" or ">"')
8535   }
8536
8537   // If it satisifes the range it is not outside
8538   if (satisfies(version, range, options)) {
8539     return false
8540   }
8541
8542   // From now on, variable terms are as if we're in "gtr" mode.
8543   // but note that everything is flipped for the "ltr" function.
8544
8545   for (let i = 0; i < range.set.length; ++i) {
8546     const comparators = range.set[i]
8547
8548     let high = null
8549     let low = null
8550
8551     comparators.forEach((comparator) => {
8552       if (comparator.semver === ANY) {
8553         comparator = new Comparator('>=0.0.0')
8554       }
8555       high = high || comparator
8556       low = low || comparator
8557       if (gtfn(comparator.semver, high.semver, options)) {
8558         high = comparator
8559       } else if (ltfn(comparator.semver, low.semver, options)) {
8560         low = comparator
8561       }
8562     })
8563
8564     // If the edge version comparator has a operator then our version
8565     // isn't outside it
8566     if (high.operator === comp || high.operator === ecomp) {
8567       return false
8568     }
8569
8570     // If the lowest version comparator has an operator and our version
8571     // is less than it then it isn't higher than the range
8572     if ((!low.operator || low.operator === comp) &&
8573         ltefn(version, low.semver)) {
8574       return false
8575     } else if (low.operator === ecomp && ltfn(version, low.semver)) {
8576       return false
8577     }
8578   }
8579   return true
8580 }
8581
8582 module.exports = outside
8583
8584
8585 /***/ }),
8586 /* 79 */
8587 /***/ (function(module, exports, __webpack_require__) {
8588
8589 // Determine if version is greater than all the versions possible in the range.
8590 const outside = __webpack_require__(78)
8591 const gtr = (version, range, options) => outside(version, range, '>', options)
8592 module.exports = gtr
8593
8594
8595 /***/ }),
8596 /* 80 */
8597 /***/ (function(module, exports, __webpack_require__) {
8598
8599 const outside = __webpack_require__(78)
8600 // Determine if version is less than all the versions possible in the range
8601 const ltr = (version, range, options) => outside(version, range, '<', options)
8602 module.exports = ltr
8603
8604
8605 /***/ }),
8606 /* 81 */
8607 /***/ (function(module, exports, __webpack_require__) {
8608
8609 const Range = __webpack_require__(71)
8610 const intersects = (r1, r2, options) => {
8611   r1 = new Range(r1, options)
8612   r2 = new Range(r2, options)
8613   return r1.intersects(r2)
8614 }
8615 module.exports = intersects
8616
8617
8618 /***/ }),
8619 /* 82 */
8620 /***/ (function(module, exports, __webpack_require__) {
8621
8622 // given a set of versions and a range, create a "simplified" range
8623 // that includes the same versions that the original range does
8624 // If the original range is shorter than the simplified one, return that.
8625 const satisfies = __webpack_require__(72)
8626 const compare = __webpack_require__(53)
8627 module.exports = (versions, range, options) => {
8628   const set = []
8629   let min = null
8630   let prev = null
8631   const v = versions.sort((a, b) => compare(a, b, options))
8632   for (const version of v) {
8633     const included = satisfies(version, range, options)
8634     if (included) {
8635       prev = version
8636       if (!min)
8637         min = version
8638     } else {
8639       if (prev) {
8640         set.push([min, prev])
8641       }
8642       prev = null
8643       min = null
8644     }
8645   }
8646   if (min)
8647     set.push([min, null])
8648
8649   const ranges = []
8650   for (const [min, max] of set) {
8651     if (min === max)
8652       ranges.push(min)
8653     else if (!max && min === v[0])
8654       ranges.push('*')
8655     else if (!max)
8656       ranges.push(`>=${min}`)
8657     else if (min === v[0])
8658       ranges.push(`<=${max}`)
8659     else
8660       ranges.push(`${min} - ${max}`)
8661   }
8662   const simplified = ranges.join(' || ')
8663   const original = typeof range.raw === 'string' ? range.raw : String(range)
8664   return simplified.length < original.length ? simplified : range
8665 }
8666
8667
8668 /***/ }),
8669 /* 83 */
8670 /***/ (function(module, exports, __webpack_require__) {
8671
8672 const Range = __webpack_require__(71)
8673 const { ANY } = __webpack_require__(70)
8674 const satisfies = __webpack_require__(72)
8675 const compare = __webpack_require__(53)
8676
8677 // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
8678 // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
8679 //
8680 // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
8681 // - If c is only the ANY comparator
8682 //   - If C is only the ANY comparator, return true
8683 //   - Else return false
8684 // - Let EQ be the set of = comparators in c
8685 // - If EQ is more than one, return true (null set)
8686 // - Let GT be the highest > or >= comparator in c
8687 // - Let LT be the lowest < or <= comparator in c
8688 // - If GT and LT, and GT.semver > LT.semver, return true (null set)
8689 // - If EQ
8690 //   - If GT, and EQ does not satisfy GT, return true (null set)
8691 //   - If LT, and EQ does not satisfy LT, return true (null set)
8692 //   - If EQ satisfies every C, return true
8693 //   - Else return false
8694 // - If GT
8695 //   - If GT is lower than any > or >= comp in C, return false
8696 //   - If GT is >=, and GT.semver does not satisfy every C, return false
8697 // - If LT
8698 //   - If LT.semver is greater than that of any > comp in C, return false
8699 //   - If LT is <=, and LT.semver does not satisfy every C, return false
8700 // - If any C is a = range, and GT or LT are set, return false
8701 // - Else return true
8702
8703 const subset = (sub, dom, options) => {
8704   sub = new Range(sub, options)
8705   dom = new Range(dom, options)
8706   let sawNonNull = false
8707
8708   OUTER: for (const simpleSub of sub.set) {
8709     for (const simpleDom of dom.set) {
8710       const isSub = simpleSubset(simpleSub, simpleDom, options)
8711       sawNonNull = sawNonNull || isSub !== null
8712       if (isSub)
8713         continue OUTER
8714     }
8715     // the null set is a subset of everything, but null simple ranges in
8716     // a complex range should be ignored.  so if we saw a non-null range,
8717     // then we know this isn't a subset, but if EVERY simple range was null,
8718     // then it is a subset.
8719     if (sawNonNull)
8720       return false
8721   }
8722   return true
8723 }
8724
8725 const simpleSubset = (sub, dom, options) => {
8726   if (sub.length === 1 && sub[0].semver === ANY)
8727     return dom.length === 1 && dom[0].semver === ANY
8728
8729   const eqSet = new Set()
8730   let gt, lt
8731   for (const c of sub) {
8732     if (c.operator === '>' || c.operator === '>=')
8733       gt = higherGT(gt, c, options)
8734     else if (c.operator === '<' || c.operator === '<=')
8735       lt = lowerLT(lt, c, options)
8736     else
8737       eqSet.add(c.semver)
8738   }
8739
8740   if (eqSet.size > 1)
8741     return null
8742
8743   let gtltComp
8744   if (gt && lt) {
8745     gtltComp = compare(gt.semver, lt.semver, options)
8746     if (gtltComp > 0)
8747       return null
8748     else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
8749       return null
8750   }
8751
8752   // will iterate one or zero times
8753   for (const eq of eqSet) {
8754     if (gt && !satisfies(eq, String(gt), options))
8755       return null
8756
8757     if (lt && !satisfies(eq, String(lt), options))
8758       return null
8759
8760     for (const c of dom) {
8761       if (!satisfies(eq, String(c), options))
8762         return false
8763     }
8764     return true
8765   }
8766
8767   let higher, lower
8768   let hasDomLT, hasDomGT
8769   for (const c of dom) {
8770     hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
8771     hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
8772     if (gt) {
8773       if (c.operator === '>' || c.operator === '>=') {
8774         higher = higherGT(gt, c, options)
8775         if (higher === c)
8776           return false
8777       } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
8778         return false
8779     }
8780     if (lt) {
8781       if (c.operator === '<' || c.operator === '<=') {
8782         lower = lowerLT(lt, c, options)
8783         if (lower === c)
8784           return false
8785       } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
8786         return false
8787     }
8788     if (!c.operator && (lt || gt) && gtltComp !== 0)
8789       return false
8790   }
8791
8792   // if there was a < or >, and nothing in the dom, then must be false
8793   // UNLESS it was limited by another range in the other direction.
8794   // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
8795   if (gt && hasDomLT && !lt && gtltComp !== 0)
8796     return false
8797
8798   if (lt && hasDomGT && !gt && gtltComp !== 0)
8799     return false
8800
8801   return true
8802 }
8803
8804 // >=1.2.3 is lower than >1.2.3
8805 const higherGT = (a, b, options) => {
8806   if (!a)
8807     return b
8808   const comp = compare(a.semver, b.semver, options)
8809   return comp > 0 ? a
8810     : comp < 0 ? b
8811     : b.operator === '>' && a.operator === '>=' ? b
8812     : a
8813 }
8814
8815 // <=1.2.3 is higher than <1.2.3
8816 const lowerLT = (a, b, options) => {
8817   if (!a)
8818     return b
8819   const comp = compare(a.semver, b.semver, options)
8820   return comp < 0 ? a
8821     : comp > 0 ? b
8822     : b.operator === '<' && a.operator === '<=' ? b
8823     : a
8824 }
8825
8826 module.exports = subset
8827
8828
8829 /***/ }),
8830 /* 84 */
8831 /***/ (function(module, exports, __webpack_require__) {
8832
8833 "use strict";
8834
8835 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8836     if (k2 === undefined) k2 = k;
8837     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8838 }) : (function(o, m, k, k2) {
8839     if (k2 === undefined) k2 = k;
8840     o[k2] = m[k];
8841 }));
8842 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8843     Object.defineProperty(o, "default", { enumerable: true, value: v });
8844 }) : function(o, v) {
8845     o["default"] = v;
8846 });
8847 var __importStar = (this && this.__importStar) || function (mod) {
8848     if (mod && mod.__esModule) return mod;
8849     var result = {};
8850     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8851     __setModuleDefault(result, mod);
8852     return result;
8853 };
8854 Object.defineProperty(exports, "__esModule", { value: true });
8855 exports.applyCodeActionCommands = exports.applyCodeAction = exports.getEditForCodeAction = void 0;
8856 /*---------------------------------------------------------------------------------------------
8857  *  Copyright (c) Microsoft Corporation. All rights reserved.
8858  *  Licensed under the MIT License. See License.txt in the project root for license information.
8859  *--------------------------------------------------------------------------------------------*/
8860 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8861 const coc_nvim_1 = __webpack_require__(1);
8862 const typeConverters = __importStar(__webpack_require__(37));
8863 function getEditForCodeAction(client, action) {
8864     return action.changes && action.changes.length
8865         ? typeConverters.WorkspaceEdit.fromFileCodeEdits(client, action.changes)
8866         : undefined;
8867 }
8868 exports.getEditForCodeAction = getEditForCodeAction;
8869 async function applyCodeAction(client, action) {
8870     const workspaceEdit = getEditForCodeAction(client, action);
8871     if (workspaceEdit) {
8872         if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
8873             return false;
8874         }
8875     }
8876     return applyCodeActionCommands(client, action);
8877 }
8878 exports.applyCodeAction = applyCodeAction;
8879 async function applyCodeActionCommands(client, action) {
8880     // make sure there is command
8881     if (action.commands && action.commands.length) {
8882         for (const command of action.commands) {
8883             const response = await client.execute('applyCodeActionCommand', { command }, vscode_languageserver_protocol_1.CancellationToken.None);
8884             if (!response || response.type != 'response' || !response.body) {
8885                 return false;
8886             }
8887         }
8888     }
8889     return true;
8890 }
8891 exports.applyCodeActionCommands = applyCodeActionCommands;
8892
8893
8894 /***/ }),
8895 /* 85 */
8896 /***/ (function(module, exports, __webpack_require__) {
8897
8898 "use strict";
8899
8900 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8901     if (k2 === undefined) k2 = k;
8902     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
8903 }) : (function(o, m, k, k2) {
8904     if (k2 === undefined) k2 = k;
8905     o[k2] = m[k];
8906 }));
8907 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
8908     Object.defineProperty(o, "default", { enumerable: true, value: v });
8909 }) : function(o, v) {
8910     o["default"] = v;
8911 });
8912 var __importStar = (this && this.__importStar) || function (mod) {
8913     if (mod && mod.__esModule) return mod;
8914     var result = {};
8915     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
8916     __setModuleDefault(result, mod);
8917     return result;
8918 };
8919 Object.defineProperty(exports, "__esModule", { value: true });
8920 exports.getParameterListParts = exports.convertCompletionEntry = void 0;
8921 /*---------------------------------------------------------------------------------------------
8922  *  Copyright (c) Microsoft Corporation. All rights reserved.
8923  *  Licensed under the MIT License. See License.txt in the project root for license information.
8924  *--------------------------------------------------------------------------------------------*/
8925 const vscode_languageserver_protocol_1 = __webpack_require__(3);
8926 const PConst = __importStar(__webpack_require__(39));
8927 function convertCompletionEntry(tsEntry, uri, position, context) {
8928     let label = tsEntry.name;
8929     let sortText = tsEntry.sortText;
8930     let preselect = false;
8931     let detail;
8932     if (tsEntry.isRecommended) {
8933         preselect = true;
8934     }
8935     if (tsEntry.source) {
8936         // De-prioritze auto-imports https://github.com/Microsoft/vscode/issues/40311
8937         sortText = '\uffff' + sortText;
8938     }
8939     else {
8940         sortText = tsEntry.sortText;
8941     }
8942     let kind = convertKind(tsEntry.kind);
8943     let insertTextFormat = (context.enableCallCompletions &&
8944         (kind === vscode_languageserver_protocol_1.CompletionItemKind.Function ||
8945             kind === vscode_languageserver_protocol_1.CompletionItemKind.Method)) ? vscode_languageserver_protocol_1.InsertTextFormat.Snippet : vscode_languageserver_protocol_1.InsertTextFormat.PlainText;
8946     let insertText = tsEntry.insertText;
8947     let commitCharacters = getCommitCharacters(tsEntry, context);
8948     let textEdit = null;
8949     if (tsEntry.replacementSpan) {
8950         let { start, end } = tsEntry.replacementSpan;
8951         if (start.line == end.line) {
8952             textEdit = {
8953                 range: vscode_languageserver_protocol_1.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
8954                 newText: insertText || label
8955             };
8956         }
8957     }
8958     if (tsEntry.kindModifiers) {
8959         const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
8960         if (kindModifiers.has(PConst.KindModifiers.optional)) {
8961             insertText = label;
8962             label += '?';
8963         }
8964         if (kindModifiers.has(PConst.KindModifiers.color)) {
8965             kind = vscode_languageserver_protocol_1.CompletionItemKind.Color;
8966         }
8967         if (tsEntry.kind === PConst.Kind.script) {
8968             for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) {
8969                 if (kindModifiers.has(extModifier)) {
8970                     if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
8971                         detail = tsEntry.name;
8972                     }
8973                     else {
8974                         detail = tsEntry.name + extModifier;
8975                     }
8976                     break;
8977                 }
8978             }
8979         }
8980     }
8981     return {
8982         label,
8983         insertText,
8984         textEdit,
8985         kind,
8986         preselect,
8987         insertTextFormat,
8988         sortText,
8989         commitCharacters,
8990         detail,
8991         data: {
8992             uri,
8993             position,
8994             name: tsEntry.name,
8995             source: tsEntry.source || ''
8996         }
8997     };
8998 }
8999 exports.convertCompletionEntry = convertCompletionEntry;
9000 function convertKind(kind) {
9001     switch (kind) {
9002         case PConst.Kind.primitiveType:
9003         case PConst.Kind.keyword:
9004             return vscode_languageserver_protocol_1.CompletionItemKind.Keyword;
9005         case PConst.Kind.const:
9006             return vscode_languageserver_protocol_1.CompletionItemKind.Constant;
9007         case PConst.Kind.let:
9008         case PConst.Kind.variable:
9009         case PConst.Kind.localVariable:
9010         case PConst.Kind.alias:
9011             return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9012         case PConst.Kind.memberVariable:
9013         case PConst.Kind.memberGetAccessor:
9014         case PConst.Kind.memberSetAccessor:
9015             return vscode_languageserver_protocol_1.CompletionItemKind.Field;
9016         case PConst.Kind.function:
9017             return vscode_languageserver_protocol_1.CompletionItemKind.Function;
9018         case PConst.Kind.method:
9019         case PConst.Kind.constructSignature:
9020         case PConst.Kind.callSignature:
9021         case PConst.Kind.indexSignature:
9022             return vscode_languageserver_protocol_1.CompletionItemKind.Method;
9023         case PConst.Kind.enum:
9024             return vscode_languageserver_protocol_1.CompletionItemKind.Enum;
9025         case PConst.Kind.module:
9026         case PConst.Kind.externalModuleName:
9027             return vscode_languageserver_protocol_1.CompletionItemKind.Module;
9028         case PConst.Kind.class:
9029         case PConst.Kind.type:
9030             return vscode_languageserver_protocol_1.CompletionItemKind.Class;
9031         case PConst.Kind.interface:
9032             return vscode_languageserver_protocol_1.CompletionItemKind.Interface;
9033         case PConst.Kind.warning:
9034         case PConst.Kind.script:
9035             return vscode_languageserver_protocol_1.CompletionItemKind.File;
9036         case PConst.Kind.directory:
9037             return vscode_languageserver_protocol_1.CompletionItemKind.Folder;
9038     }
9039     return vscode_languageserver_protocol_1.CompletionItemKind.Variable;
9040 }
9041 function getCommitCharacters(tsEntry, context) {
9042     if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
9043         return undefined;
9044     }
9045     const commitCharacters = [];
9046     switch (tsEntry.kind) {
9047         case PConst.Kind.memberGetAccessor:
9048         case PConst.Kind.memberSetAccessor:
9049         case PConst.Kind.constructSignature:
9050         case PConst.Kind.callSignature:
9051         case PConst.Kind.indexSignature:
9052         case PConst.Kind.enum:
9053         case PConst.Kind.interface:
9054             commitCharacters.push('.', ';');
9055             break;
9056         case PConst.Kind.module:
9057         case PConst.Kind.alias:
9058         case PConst.Kind.const:
9059         case PConst.Kind.let:
9060         case PConst.Kind.variable:
9061         case PConst.Kind.localVariable:
9062         case PConst.Kind.memberVariable:
9063         case PConst.Kind.class:
9064         case PConst.Kind.function:
9065         case PConst.Kind.method:
9066         case PConst.Kind.keyword:
9067         case PConst.Kind.parameter:
9068             commitCharacters.push('.', ',', ';');
9069             if (context.enableCallCompletions) {
9070                 commitCharacters.push('(');
9071             }
9072             break;
9073     }
9074     return commitCharacters.length === 0 ? undefined : commitCharacters;
9075 }
9076 function getParameterListParts(displayParts) {
9077     const parts = [];
9078     let isInMethod = false;
9079     let hasOptionalParameters = false;
9080     let parenCount = 0;
9081     let braceCount = 0;
9082     outer: for (let i = 0; i < displayParts.length; ++i) {
9083         const part = displayParts[i];
9084         switch (part.kind) {
9085             case PConst.DisplayPartKind.methodName:
9086             case PConst.DisplayPartKind.functionName:
9087             case PConst.DisplayPartKind.text:
9088             case PConst.DisplayPartKind.propertyName:
9089                 if (parenCount === 0 && braceCount === 0) {
9090                     isInMethod = true;
9091                 }
9092                 break;
9093             case PConst.DisplayPartKind.parameterName:
9094                 if (parenCount === 1 && braceCount === 0 && isInMethod) {
9095                     // Only take top level paren names
9096                     const next = displayParts[i + 1];
9097                     // Skip optional parameters
9098                     const nameIsFollowedByOptionalIndicator = next && next.text === '?';
9099                     // Skip this parameter
9100                     const nameIsThis = part.text === 'this';
9101                     if (!nameIsFollowedByOptionalIndicator && !nameIsThis) {
9102                         parts.push(part);
9103                     }
9104                     hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
9105                 }
9106                 break;
9107             case PConst.DisplayPartKind.punctuation:
9108                 if (part.text === '(') {
9109                     ++parenCount;
9110                 }
9111                 else if (part.text === ')') {
9112                     --parenCount;
9113                     if (parenCount <= 0 && isInMethod) {
9114                         break outer;
9115                     }
9116                 }
9117                 else if (part.text === '...' && parenCount === 1) {
9118                     // Found rest parmeter. Do not fill in any further arguments
9119                     hasOptionalParameters = true;
9120                     break outer;
9121                 }
9122                 else if (part.text === '{') {
9123                     ++braceCount;
9124                 }
9125                 else if (part.text === '}') {
9126                     --braceCount;
9127                 }
9128                 break;
9129         }
9130     }
9131     return { hasOptionalParameters, parts };
9132 }
9133 exports.getParameterListParts = getParameterListParts;
9134
9135
9136 /***/ }),
9137 /* 86 */
9138 /***/ (function(module, exports, __webpack_require__) {
9139
9140 "use strict";
9141
9142 /*---------------------------------------------------------------------------------------------
9143  *  Copyright (c) Microsoft Corporation. All rights reserved.
9144  *  Licensed under the MIT License. See License.txt in the project root for license information.
9145  *--------------------------------------------------------------------------------------------*/
9146 Object.defineProperty(exports, "__esModule", { value: true });
9147 exports.markdownDocumentation = exports.tagsMarkdownPreview = exports.plain = void 0;
9148 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9149 function getTagBodyText(tag) {
9150     if (!tag.text) {
9151         return undefined;
9152     }
9153     switch (tag.name) {
9154         case 'example':
9155         case 'default':
9156             // Convert to markdown code block if it not already one
9157             if (tag.text.match(/^\s*[~`]{3}/g)) {
9158                 return tag.text;
9159             }
9160             return '```\n' + tag.text + '\n```';
9161     }
9162     return tag.text;
9163 }
9164 function getTagDocumentation(tag) {
9165     switch (tag.name) {
9166         case 'param':
9167             const body = (tag.text || '').split(/^([\w\.]+)\s*/);
9168             if (body && body.length === 3) {
9169                 const param = body[1];
9170                 const doc = body[2];
9171                 const label = `*@${tag.name}* \`${param}\``;
9172                 if (!doc) {
9173                     return label;
9174                 }
9175                 return label + (doc.match(/\r\n|\n/g) ? '\n' + doc : ` â€” ${doc}`);
9176             }
9177     }
9178     // Generic tag
9179     const label = `*@${tag.name}*`;
9180     const text = getTagBodyText(tag);
9181     if (!text) {
9182         return label;
9183     }
9184     return label + (text.match(/\r\n|\n/g) ? '\n' + text : ` â€” ${text}`);
9185 }
9186 function plain(parts) {
9187     if (!parts || !parts.length)
9188         return '';
9189     return parts.map(part => part.text).join('');
9190 }
9191 exports.plain = plain;
9192 function tagsMarkdownPreview(tags) {
9193     return (tags || []).map(getTagDocumentation).join('  \n\n');
9194 }
9195 exports.tagsMarkdownPreview = tagsMarkdownPreview;
9196 function markdownDocumentation(documentation, tags) {
9197     let out = plain(documentation);
9198     const tagsPreview = tagsMarkdownPreview(tags);
9199     if (tagsPreview) {
9200         out = out + ('\n\n' + tagsPreview);
9201     }
9202     return {
9203         kind: vscode_languageserver_protocol_1.MarkupKind.Markdown,
9204         value: out
9205     };
9206 }
9207 exports.markdownDocumentation = markdownDocumentation;
9208
9209
9210 /***/ }),
9211 /* 87 */
9212 /***/ (function(module, exports, __webpack_require__) {
9213
9214 "use strict";
9215
9216 Object.defineProperty(exports, "__esModule", { value: true });
9217 class SnippetString {
9218     constructor(value) {
9219         this._tabstop = 1;
9220         this.value = value || '';
9221     }
9222     static isSnippetString(thing) {
9223         if (thing instanceof SnippetString) {
9224             return true;
9225         }
9226         if (!thing) {
9227             return false;
9228         }
9229         return typeof thing.value === 'string';
9230     }
9231     static _escape(value) {
9232         return value.replace(/\$|}|\\/g, '\\$&');
9233     }
9234     appendText(str) {
9235         this.value += SnippetString._escape(str);
9236         return this;
9237     }
9238     appendTabstop(n = this._tabstop++) {
9239         this.value += '$';
9240         this.value += n;
9241         return this;
9242     }
9243     appendPlaceholder(value, n = this._tabstop++) {
9244         if (typeof value === 'function') {
9245             const nested = new SnippetString();
9246             nested._tabstop = this._tabstop;
9247             value(nested);
9248             this._tabstop = nested._tabstop;
9249             value = nested.value;
9250         }
9251         else {
9252             value = SnippetString._escape(value);
9253         }
9254         this.value += '${';
9255         this.value += n;
9256         this.value += ':';
9257         this.value += value;
9258         this.value += '}';
9259         return this;
9260     }
9261     appendVariable(name, defaultValue) {
9262         if (typeof defaultValue === 'function') {
9263             const nested = new SnippetString();
9264             nested._tabstop = this._tabstop;
9265             defaultValue(nested);
9266             this._tabstop = nested._tabstop;
9267             defaultValue = nested.value;
9268         }
9269         else if (typeof defaultValue === 'string') {
9270             defaultValue = defaultValue.replace(/\$|}/g, '\\$&');
9271         }
9272         this.value += '${';
9273         this.value += name;
9274         if (defaultValue) {
9275             this.value += ':';
9276             this.value += defaultValue;
9277         }
9278         this.value += '}';
9279         return this;
9280     }
9281 }
9282 exports.default = SnippetString;
9283
9284
9285 /***/ }),
9286 /* 88 */
9287 /***/ (function(module, exports, __webpack_require__) {
9288
9289 "use strict";
9290
9291 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9292     if (k2 === undefined) k2 = k;
9293     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9294 }) : (function(o, m, k, k2) {
9295     if (k2 === undefined) k2 = k;
9296     o[k2] = m[k];
9297 }));
9298 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9299     Object.defineProperty(o, "default", { enumerable: true, value: v });
9300 }) : function(o, v) {
9301     o["default"] = v;
9302 });
9303 var __importStar = (this && this.__importStar) || function (mod) {
9304     if (mod && mod.__esModule) return mod;
9305     var result = {};
9306     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9307     __setModuleDefault(result, mod);
9308     return result;
9309 };
9310 Object.defineProperty(exports, "__esModule", { value: true });
9311 const typeConverters = __importStar(__webpack_require__(37));
9312 class TypeScriptDefinitionProvider {
9313     constructor(client) {
9314         this.client = client;
9315     }
9316     async getSymbolLocations(definitionType, document, position, token) {
9317         const filepath = this.client.toPath(document.uri);
9318         if (!filepath) {
9319             return undefined;
9320         }
9321         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
9322         try {
9323             const response = await this.client.execute(definitionType, args, token);
9324             const locations = (response.type == 'response' && response.body) || [];
9325             return locations.map(location => typeConverters.Location.fromTextSpan(this.client.toResource(location.file), location));
9326         }
9327         catch (_a) {
9328             return [];
9329         }
9330     }
9331     provideDefinition(document, position, token) {
9332         return this.getSymbolLocations('definition', document, position, token);
9333     }
9334     provideTypeDefinition(document, position, token) {
9335         return this.getSymbolLocations('typeDefinition', document, position, token);
9336     }
9337     provideImplementation(document, position, token) {
9338         return this.getSymbolLocations('implementation', document, position, token);
9339     }
9340 }
9341 exports.default = TypeScriptDefinitionProvider;
9342
9343
9344 /***/ }),
9345 /* 89 */
9346 /***/ (function(module, exports, __webpack_require__) {
9347
9348 "use strict";
9349
9350 var __importDefault = (this && this.__importDefault) || function (mod) {
9351     return (mod && mod.__esModule) ? mod : { "default": mod };
9352 };
9353 Object.defineProperty(exports, "__esModule", { value: true });
9354 /*---------------------------------------------------------------------------------------------
9355  *  Copyright (c) Microsoft Corporation. All rights reserved.
9356  *  Licensed under the MIT License. See License.txt in the project root for license information.
9357  *--------------------------------------------------------------------------------------------*/
9358 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9359 const coc_nvim_1 = __webpack_require__(1);
9360 const api_1 = __importDefault(__webpack_require__(40));
9361 const tsDirectives = [
9362     {
9363         value: '@ts-check',
9364         description: 'Enables semantic checking in a JavaScript file. Must be at the top of a file.'
9365     },
9366     {
9367         value: '@ts-nocheck',
9368         description: 'Disables semantic checking in a JavaScript file. Must be at the top of a file.'
9369     },
9370     {
9371         value: '@ts-ignore',
9372         description: 'Suppresses @ts-check errors on the next line of a file.'
9373     }
9374 ];
9375 const tsDirectives390 = [
9376     ...tsDirectives,
9377     {
9378         value: '@ts-expect-error',
9379         description: 'Suppresses @ts-check errors on the next line of a file, expecting at least one to exist.'
9380     }
9381 ];
9382 class DirectiveCommentCompletionProvider {
9383     constructor(client) {
9384         this.client = client;
9385     }
9386     provideCompletionItems(document, position, _token, context) {
9387         if (context.triggerCharacter != '@') {
9388             return [];
9389         }
9390         const file = this.client.toPath(document.uri);
9391         if (!file) {
9392             return [];
9393         }
9394         const doc = coc_nvim_1.workspace.getDocument(document.uri);
9395         const line = doc.getline(position.line);
9396         const prefix = line.slice(0, position.character);
9397         const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
9398         if (match) {
9399             const directives = this.client.apiVersion.gte(api_1.default.v390)
9400                 ? tsDirectives390
9401                 : tsDirectives;
9402             let items = directives.map(directive => {
9403                 const item = vscode_languageserver_protocol_1.CompletionItem.create(directive.value);
9404                 item.kind = vscode_languageserver_protocol_1.CompletionItemKind.Snippet;
9405                 item.detail = directive.description;
9406                 item.textEdit = {
9407                     range: vscode_languageserver_protocol_1.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
9408                     newText: directive.value
9409                 };
9410                 return item;
9411             });
9412             let res = {
9413                 isIncomplete: false,
9414                 items
9415             };
9416             res.startcol = doc.fixStartcol(position, ['@']);
9417             return res;
9418         }
9419         return [];
9420     }
9421 }
9422 exports.default = DirectiveCommentCompletionProvider;
9423
9424
9425 /***/ }),
9426 /* 90 */
9427 /***/ (function(module, exports, __webpack_require__) {
9428
9429 "use strict";
9430
9431 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9432     if (k2 === undefined) k2 = k;
9433     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9434 }) : (function(o, m, k, k2) {
9435     if (k2 === undefined) k2 = k;
9436     o[k2] = m[k];
9437 }));
9438 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9439     Object.defineProperty(o, "default", { enumerable: true, value: v });
9440 }) : function(o, v) {
9441     o["default"] = v;
9442 });
9443 var __importStar = (this && this.__importStar) || function (mod) {
9444     if (mod && mod.__esModule) return mod;
9445     var result = {};
9446     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9447     __setModuleDefault(result, mod);
9448     return result;
9449 };
9450 Object.defineProperty(exports, "__esModule", { value: true });
9451 /*---------------------------------------------------------------------------------------------
9452  *  Copyright (c) Microsoft Corporation. All rights reserved.
9453  *  Licensed under the MIT License. See License.txt in the project root for license information.
9454  *--------------------------------------------------------------------------------------------*/
9455 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9456 const typeConverters = __importStar(__webpack_require__(37));
9457 const arrays_1 = __webpack_require__(91);
9458 class TypeScriptDocumentHighlightProvider {
9459     constructor(client) {
9460         this.client = client;
9461     }
9462     async provideDocumentHighlights(resource, position, token) {
9463         const file = this.client.toPath(resource.uri);
9464         if (!file)
9465             return [];
9466         const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { filesToSearch: [file] });
9467         try {
9468             const response = await this.client.execute('documentHighlights', args, token);
9469             if (response.type !== 'response' || !response.body) {
9470                 return [];
9471             }
9472             return arrays_1.flatten(response.body
9473                 .filter(highlight => highlight.file === file)
9474                 .map(convertDocumentHighlight));
9475         }
9476         catch (_e) {
9477             return [];
9478         }
9479     }
9480 }
9481 exports.default = TypeScriptDocumentHighlightProvider;
9482 function convertDocumentHighlight(highlight) {
9483     return highlight.highlightSpans.map(span => {
9484         return {
9485             range: typeConverters.Range.fromTextSpan(span),
9486             kind: span.kind === 'writtenReference' ? vscode_languageserver_protocol_1.DocumentHighlightKind.Write : vscode_languageserver_protocol_1.DocumentHighlightKind.Read
9487         };
9488     });
9489 }
9490
9491
9492 /***/ }),
9493 /* 91 */
9494 /***/ (function(module, exports, __webpack_require__) {
9495
9496 "use strict";
9497
9498 Object.defineProperty(exports, "__esModule", { value: true });
9499 exports.flatten = exports.equals = void 0;
9500 /*---------------------------------------------------------------------------------------------
9501  *  Copyright (c) Microsoft Corporation. All rights reserved.
9502  *  Licensed under the MIT License. See License.txt in the project root for license information.
9503  *--------------------------------------------------------------------------------------------*/
9504 function equals(one, other, itemEquals = (a, b) => a === b) {
9505     if (one.length !== other.length) {
9506         return false;
9507     }
9508     for (let i = 0, len = one.length; i < len; i++) {
9509         if (!itemEquals(one[i], other[i])) {
9510             return false;
9511         }
9512     }
9513     return true;
9514 }
9515 exports.equals = equals;
9516 function flatten(arr) {
9517     return [].concat.apply([], arr);
9518 }
9519 exports.flatten = flatten;
9520
9521
9522 /***/ }),
9523 /* 92 */
9524 /***/ (function(module, exports, __webpack_require__) {
9525
9526 "use strict";
9527
9528 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9529     if (k2 === undefined) k2 = k;
9530     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9531 }) : (function(o, m, k, k2) {
9532     if (k2 === undefined) k2 = k;
9533     o[k2] = m[k];
9534 }));
9535 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9536     Object.defineProperty(o, "default", { enumerable: true, value: v });
9537 }) : function(o, v) {
9538     o["default"] = v;
9539 });
9540 var __importStar = (this && this.__importStar) || function (mod) {
9541     if (mod && mod.__esModule) return mod;
9542     var result = {};
9543     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9544     __setModuleDefault(result, mod);
9545     return result;
9546 };
9547 Object.defineProperty(exports, "__esModule", { value: true });
9548 /*---------------------------------------------------------------------------------------------
9549  *  Copyright (c) Microsoft Corporation. All rights reserved.
9550  *  Licensed under the MIT License. See License.txt in the project root for license information.
9551  *--------------------------------------------------------------------------------------------*/
9552 const vscode_languageserver_protocol_1 = __webpack_require__(3);
9553 const PConst = __importStar(__webpack_require__(39));
9554 const typeConverters = __importStar(__webpack_require__(37));
9555 const getSymbolKind = (kind) => {
9556     switch (kind) {
9557         case PConst.Kind.module:
9558             return vscode_languageserver_protocol_1.SymbolKind.Module;
9559         case PConst.Kind.class:
9560             return vscode_languageserver_protocol_1.SymbolKind.Class;
9561         case PConst.Kind.enum:
9562             return vscode_languageserver_protocol_1.SymbolKind.Enum;
9563         case PConst.Kind.interface:
9564             return vscode_languageserver_protocol_1.SymbolKind.Interface;
9565         case PConst.Kind.method:
9566             return vscode_languageserver_protocol_1.SymbolKind.Method;
9567         case PConst.Kind.memberVariable:
9568             return vscode_languageserver_protocol_1.SymbolKind.Property;
9569         case PConst.Kind.memberGetAccessor:
9570             return vscode_languageserver_protocol_1.SymbolKind.Property;
9571         case PConst.Kind.memberSetAccessor:
9572             return vscode_languageserver_protocol_1.SymbolKind.Property;
9573         case PConst.Kind.variable:
9574             return vscode_languageserver_protocol_1.SymbolKind.Variable;
9575         case PConst.Kind.const:
9576             return vscode_languageserver_protocol_1.SymbolKind.Variable;
9577         case PConst.Kind.localVariable:
9578             return vscode_languageserver_protocol_1.SymbolKind.Variable;
9579         case PConst.Kind.variable:
9580             return vscode_languageserver_protocol_1.SymbolKind.Variable;
9581         case PConst.Kind.constructSignature:
9582         case PConst.Kind.constructorImplementation:
9583         case PConst.Kind.function:
9584         case PConst.Kind.localFunction:
9585             return vscode_languageserver_protocol_1.SymbolKind.Function;
9586     }
9587     return vscode_languageserver_protocol_1.SymbolKind.Variable;
9588 };
9589 class TypeScriptDocumentSymbolProvider {
9590     constructor(client) {
9591         this.client = client;
9592     }
9593     async provideDocumentSymbols(resource, token) {
9594         const filepath = this.client.toPath(resource.uri);
9595         if (!filepath)
9596             return [];
9597         const args = {
9598             file: filepath
9599         };
9600         try {
9601             const response = await this.client.execute('navtree', args, token);
9602             if (response.type == 'response' && response.body) {
9603                 // The root represents the file. Ignore this when showing in the UI
9604                 const tree = response.body;
9605                 if (tree.childItems) {
9606                     const result = new Array();
9607                     tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
9608                     return result;
9609                 }
9610             }
9611             return [];
9612         }
9613         catch (e) {
9614             return [];
9615         }
9616     }
9617     static convertNavTree(bucket, item) {
9618         let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
9619         const children = new Set(item.childItems || []);
9620         for (const span of item.spans) {
9621             const range = typeConverters.Range.fromTextSpan(span);
9622             const symbolInfo = vscode_languageserver_protocol_1.DocumentSymbol.create(item.text, '', getSymbolKind(item.kind), range, range);
9623             symbolInfo.children = children.size > 0 ? [] : null;
9624             for (const child of children) {
9625                 if (child.spans.some(span => !!containsRange(range, typeConverters.Range.fromTextSpan(span)))) {
9626                     const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
9627                     shouldInclude = shouldInclude || includedChild;
9628                     children.delete(child);
9629                 }
9630             }
9631             if (shouldInclude) {
9632                 bucket.push(symbolInfo);
9633             }
9634         }
9635         return shouldInclude;
9636     }
9637     static shouldInclueEntry(item) {
9638         if (item.kind === PConst.Kind.alias) {
9639             return false;
9640         }
9641         return !!(item.text &&
9642             item.text !== '<function>' &&
9643             item.text !== '<class>');
9644     }
9645 }
9646 exports.default = TypeScriptDocumentSymbolProvider;
9647 function containsRange(range, otherRange) {
9648     if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
9649         return false;
9650     }
9651     if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
9652         return false;
9653     }
9654     if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
9655         return false;
9656     }
9657     if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
9658         return false;
9659     }
9660     return true;
9661 }
9662
9663
9664 /***/ }),
9665 /* 93 */
9666 /***/ (function(module, exports, __webpack_require__) {
9667
9668 "use strict";
9669
9670 /*---------------------------------------------------------------------------------------------
9671  *  Copyright (c) Microsoft Corporation. All rights reserved.
9672  *  Licensed under the MIT License. See License.txt in the project root for license information.
9673  *--------------------------------------------------------------------------------------------*/
9674 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9675     if (k2 === undefined) k2 = k;
9676     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9677 }) : (function(o, m, k, k2) {
9678     if (k2 === undefined) k2 = k;
9679     o[k2] = m[k];
9680 }));
9681 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9682     Object.defineProperty(o, "default", { enumerable: true, value: v });
9683 }) : function(o, v) {
9684     o["default"] = v;
9685 });
9686 var __importStar = (this && this.__importStar) || function (mod) {
9687     if (mod && mod.__esModule) return mod;
9688     var result = {};
9689     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9690     __setModuleDefault(result, mod);
9691     return result;
9692 };
9693 Object.defineProperty(exports, "__esModule", { value: true });
9694 const vscode_languageserver_types_1 = __webpack_require__(18);
9695 const coc_nvim_1 = __webpack_require__(1);
9696 const typeConverters = __importStar(__webpack_require__(37));
9697 class TypeScriptFoldingProvider {
9698     constructor(client) {
9699         this.client = client;
9700     }
9701     async provideFoldingRanges(document, _context, token) {
9702         const file = this.client.toPath(document.uri);
9703         if (!file) {
9704             return;
9705         }
9706         const args = { file };
9707         const res = await this.client.execute('getOutliningSpans', args, token);
9708         if (res.type != 'response') {
9709             return;
9710         }
9711         const { body } = res;
9712         if (!body) {
9713             return;
9714         }
9715         return body
9716             .map(span => this.convertOutliningSpan(span, document))
9717             .filter(foldingRange => !!foldingRange);
9718     }
9719     convertOutliningSpan(span, document) {
9720         const range = typeConverters.Range.fromTextSpan(span.textSpan);
9721         const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
9722         // Workaround for #49904
9723         if (span.kind === 'comment') {
9724             let doc = coc_nvim_1.workspace.getDocument(document.uri);
9725             const line = doc.getline(range.start.line);
9726             if (line.match(/\/\/\s*#endregion/gi)) {
9727                 return undefined;
9728             }
9729         }
9730         let { start, end } = range;
9731         return vscode_languageserver_types_1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
9732     }
9733     static getFoldingRangeKind(span) {
9734         switch (span.kind) {
9735             case 'comment':
9736             case 'region':
9737             case 'imports':
9738             case 'code':
9739                 return span.kind;
9740             default:
9741                 return undefined;
9742         }
9743     }
9744 }
9745 exports.default = TypeScriptFoldingProvider;
9746
9747
9748 /***/ }),
9749 /* 94 */
9750 /***/ (function(module, exports, __webpack_require__) {
9751
9752 "use strict";
9753
9754 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9755     if (k2 === undefined) k2 = k;
9756     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9757 }) : (function(o, m, k, k2) {
9758     if (k2 === undefined) k2 = k;
9759     o[k2] = m[k];
9760 }));
9761 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9762     Object.defineProperty(o, "default", { enumerable: true, value: v });
9763 }) : function(o, v) {
9764     o["default"] = v;
9765 });
9766 var __importStar = (this && this.__importStar) || function (mod) {
9767     if (mod && mod.__esModule) return mod;
9768     var result = {};
9769     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9770     __setModuleDefault(result, mod);
9771     return result;
9772 };
9773 Object.defineProperty(exports, "__esModule", { value: true });
9774 /*---------------------------------------------------------------------------------------------
9775  *  Copyright (c) Microsoft Corporation. All rights reserved.
9776  *  Licensed under the MIT License. See License.txt in the project root for license information.
9777  *--------------------------------------------------------------------------------------------*/
9778 const coc_nvim_1 = __webpack_require__(1);
9779 const typeConverters = __importStar(__webpack_require__(37));
9780 class TypeScriptFormattingProvider {
9781     constructor(client, formattingOptionsManager) {
9782         this.client = client;
9783         this.formattingOptionsManager = formattingOptionsManager;
9784     }
9785     enabled(document) {
9786         return this.formattingOptionsManager.formatEnabled(document);
9787     }
9788     async doFormat(document, options, args, token) {
9789         if (!this.enabled(document))
9790             return [];
9791         await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
9792         try {
9793             const response = await this.client.execute('format', args, token);
9794             if (response.type == 'response' && response.body) {
9795                 let edits = response.body.map(typeConverters.TextEdit.fromCodeEdit);
9796                 return edits;
9797             }
9798         }
9799         catch (_a) {
9800             // noop
9801         }
9802         return [];
9803     }
9804     async provideDocumentRangeFormattingEdits(document, range, options, token) {
9805         if (!this.enabled(document))
9806             return [];
9807         const filepath = this.client.toPath(document.uri);
9808         if (!filepath)
9809             return [];
9810         const args = {
9811             file: filepath,
9812             line: range.start.line + 1,
9813             offset: range.start.character + 1,
9814             endLine: range.end.line + 1,
9815             endOffset: range.end.character + 1
9816         };
9817         return this.doFormat(document, options, args, token);
9818     }
9819     async provideDocumentFormattingEdits(document, options, token) {
9820         if (!this.enabled(document))
9821             return [];
9822         const filepath = this.client.toPath(document.uri);
9823         if (!filepath)
9824             return [];
9825         const args = {
9826             file: filepath,
9827             line: 1,
9828             offset: 1,
9829             endLine: document.lineCount + 1,
9830             endOffset: 1
9831         };
9832         return this.doFormat(document, options, args, token);
9833     }
9834     async provideOnTypeFormattingEdits(document, position, ch, options, token) {
9835         if (!this.enabled(document))
9836             return [];
9837         if (!this.client.configuration.formatOnType)
9838             return [];
9839         const file = this.client.toPath(document.uri);
9840         if (!file)
9841             return [];
9842         await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
9843         const doc = coc_nvim_1.workspace.getDocument(document.uri);
9844         const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { key: ch });
9845         try {
9846             const res = await this.client.execute('formatonkey', args, token);
9847             if (res.type != 'response') {
9848                 return [];
9849             }
9850             const { body } = res;
9851             const edits = body;
9852             const result = [];
9853             if (!edits) {
9854                 return result;
9855             }
9856             for (const edit of edits) {
9857                 const textEdit = typeConverters.TextEdit.fromCodeEdit(edit);
9858                 const range = textEdit.range;
9859                 // Work around for https://github.com/Microsoft/TypeScript/issues/6700.
9860                 // Check if we have an edit at the beginning of the line which only removes white spaces and leaves
9861                 // an empty line. Drop those edits
9862                 if (range.start.character === 0 &&
9863                     range.start.line === range.end.line &&
9864                     textEdit.newText === '') {
9865                     const lText = doc.getline(range.start.line);
9866                     // If the edit leaves something on the line keep the edit (note that the end character is exclusive).
9867                     // Keep it also if it removes something else than whitespace
9868                     if (lText.trim().length > 0 || lText.length > range.end.character) {
9869                         result.push(textEdit);
9870                     }
9871                 }
9872                 else {
9873                     result.push(textEdit);
9874                 }
9875             }
9876             return result;
9877         }
9878         catch (_a) {
9879             // noop
9880         }
9881         return [];
9882     }
9883 }
9884 exports.default = TypeScriptFormattingProvider;
9885
9886
9887 /***/ }),
9888 /* 95 */
9889 /***/ (function(module, exports, __webpack_require__) {
9890
9891 "use strict";
9892
9893 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9894     if (k2 === undefined) k2 = k;
9895     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9896 }) : (function(o, m, k, k2) {
9897     if (k2 === undefined) k2 = k;
9898     o[k2] = m[k];
9899 }));
9900 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9901     Object.defineProperty(o, "default", { enumerable: true, value: v });
9902 }) : function(o, v) {
9903     o["default"] = v;
9904 });
9905 var __importStar = (this && this.__importStar) || function (mod) {
9906     if (mod && mod.__esModule) return mod;
9907     var result = {};
9908     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9909     __setModuleDefault(result, mod);
9910     return result;
9911 };
9912 Object.defineProperty(exports, "__esModule", { value: true });
9913 const previewer_1 = __webpack_require__(86);
9914 const typeConverters = __importStar(__webpack_require__(37));
9915 class TypeScriptHoverProvider {
9916     constructor(client) {
9917         this.client = client;
9918     }
9919     async provideHover(document, position, token) {
9920         const filepath = this.client.toPath(document.uri);
9921         if (!filepath) {
9922             return undefined;
9923         }
9924         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
9925         try {
9926             const response = await this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
9927             if (response && response.type == 'response' && response.body) {
9928                 const data = response.body;
9929                 return {
9930                     contents: TypeScriptHoverProvider.getContents(data),
9931                     range: typeConverters.Range.fromTextSpan(data)
9932                 };
9933             }
9934         }
9935         catch (e) {
9936             // noop
9937         }
9938         return undefined;
9939     }
9940     static getContents(data) {
9941         const parts = [];
9942         if (data.displayString) {
9943             parts.push({ language: 'typescript', value: data.displayString });
9944         }
9945         const tags = previewer_1.tagsMarkdownPreview(data.tags);
9946         parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
9947         return parts;
9948     }
9949 }
9950 exports.default = TypeScriptHoverProvider;
9951
9952
9953 /***/ }),
9954 /* 96 */
9955 /***/ (function(module, exports, __webpack_require__) {
9956
9957 "use strict";
9958
9959 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9960     if (k2 === undefined) k2 = k;
9961     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9962 }) : (function(o, m, k, k2) {
9963     if (k2 === undefined) k2 = k;
9964     o[k2] = m[k];
9965 }));
9966 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
9967     Object.defineProperty(o, "default", { enumerable: true, value: v });
9968 }) : function(o, v) {
9969     o["default"] = v;
9970 });
9971 var __importStar = (this && this.__importStar) || function (mod) {
9972     if (mod && mod.__esModule) return mod;
9973     var result = {};
9974     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9975     __setModuleDefault(result, mod);
9976     return result;
9977 };
9978 Object.defineProperty(exports, "__esModule", { value: true });
9979 const PConst = __importStar(__webpack_require__(39));
9980 const typeConverters = __importStar(__webpack_require__(37));
9981 const baseCodeLensProvider_1 = __webpack_require__(35);
9982 class TypeScriptImplementationsCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
9983     async resolveCodeLens(codeLens, token) {
9984         let { uri } = codeLens.data;
9985         let filepath = this.client.toPath(uri);
9986         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
9987         try {
9988             const response = await this.client.execute('implementation', args, token, { lowPriority: true });
9989             if (response && response.type == 'response' && response.body) {
9990                 const locations = response.body
9991                     .map(reference => {
9992                     return {
9993                         uri: this.client.toResource(reference.file),
9994                         range: {
9995                             start: typeConverters.Position.fromLocation(reference.start),
9996                             end: {
9997                                 line: reference.start.line,
9998                                 character: 0
9999                             }
10000                         }
10001                     };
10002                 })
10003                     // Exclude original from implementations
10004                     .filter(location => !(location.uri.toString() === uri &&
10005                     location.range.start.line === codeLens.range.start.line &&
10006                     location.range.start.character ===
10007                         codeLens.range.start.character));
10008                 codeLens.command = this.getCommand(locations, codeLens);
10009                 return codeLens;
10010             }
10011         }
10012         catch (_a) {
10013             // noop
10014         }
10015         codeLens.command = {
10016             title: '0 implementations',
10017             command: ''
10018         };
10019         return codeLens;
10020     }
10021     getCommand(locations, codeLens) {
10022         let { uri } = codeLens.data;
10023         return {
10024             title: this.getTitle(locations),
10025             command: locations.length ? 'editor.action.showReferences' : '',
10026             arguments: [uri, codeLens.range.start, locations]
10027         };
10028     }
10029     getTitle(locations) {
10030         return locations.length === 1 ? '1 implementation' : `${locations.length} implementations`;
10031     }
10032     extractSymbol(document, item, _parent) {
10033         switch (item.kind) {
10034             case PConst.Kind.interface:
10035                 return super.getSymbolRange(document, item);
10036             case PConst.Kind.class:
10037             case PConst.Kind.method:
10038             case PConst.Kind.memberVariable:
10039             case PConst.Kind.memberGetAccessor:
10040             case PConst.Kind.memberSetAccessor:
10041                 if (item.kindModifiers.match(/\babstract\b/g)) {
10042                     return super.getSymbolRange(document, item);
10043                 }
10044                 break;
10045         }
10046         return null;
10047     }
10048 }
10049 exports.default = TypeScriptImplementationsCodeLensProvider;
10050
10051
10052 /***/ }),
10053 /* 97 */
10054 /***/ (function(module, exports, __webpack_require__) {
10055
10056 "use strict";
10057
10058 Object.defineProperty(exports, "__esModule", { value: true });
10059 const coc_nvim_1 = __webpack_require__(1);
10060 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10061 const helper_1 = __webpack_require__(98);
10062 class ImportFixProvider {
10063     constructor(bufferSyncSupport) {
10064         this.bufferSyncSupport = bufferSyncSupport;
10065     }
10066     async provideCodeActions(document, _range, context, _token) {
10067         if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10068             return [];
10069         }
10070         let diagnostics = context.diagnostics.filter(d => d.code == 2304);
10071         if (!diagnostics.length)
10072             return [];
10073         let edits = [];
10074         let names = [];
10075         let doc = coc_nvim_1.workspace.getDocument(document.uri);
10076         let command;
10077         for (const diagnostic of diagnostics) {
10078             let { range } = diagnostic;
10079             let line = doc.getline(range.start.line);
10080             let name = line.slice(range.start.character, range.end.character);
10081             if (names.indexOf(name) !== -1)
10082                 continue;
10083             if (helper_1.nodeModules.indexOf(name) !== -1) {
10084                 names.push(name);
10085                 edits.push({
10086                     range: vscode_languageserver_protocol_1.Range.create(0, 0, 0, 0),
10087                     newText: `import ${name} from '${name}'\n`
10088                 });
10089                 command = 'tsserver.organizeImports';
10090             }
10091         }
10092         let edit = {
10093             changes: {
10094                 [document.uri]: edits
10095             }
10096         };
10097         let cmd = null;
10098         if (command)
10099             cmd = {
10100                 title: `fix import`,
10101                 command: 'tsserver.organizeImports'
10102             };
10103         return [{
10104                 title: `Add import ${names.join(', ')}`,
10105                 edit,
10106                 command: cmd
10107             }];
10108     }
10109 }
10110 exports.default = ImportFixProvider;
10111
10112
10113 /***/ }),
10114 /* 98 */
10115 /***/ (function(module, exports, __webpack_require__) {
10116
10117 "use strict";
10118
10119 Object.defineProperty(exports, "__esModule", { value: true });
10120 exports.nodeModules = void 0;
10121 exports.nodeModules = [
10122     'assert',
10123     'cluster',
10124     'crypto',
10125     'dns',
10126     'domain',
10127     'events',
10128     'fs',
10129     'http',
10130     'http2',
10131     'https',
10132     'inspector',
10133     'net',
10134     'os',
10135     'path',
10136     'punycode',
10137     'querystring',
10138     'readline',
10139     'repl',
10140     'stream',
10141     'string_decoder',
10142     'tls',
10143     'tty',
10144     'url',
10145     'util',
10146     'v8',
10147     'vm',
10148     'zlib',
10149     'perf_hooks'
10150 ];
10151
10152
10153 /***/ }),
10154 /* 99 */
10155 /***/ (function(module, exports, __webpack_require__) {
10156
10157 "use strict";
10158
10159 Object.defineProperty(exports, "__esModule", { value: true });
10160 const coc_nvim_1 = __webpack_require__(1);
10161 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10162 const modules_1 = __webpack_require__(100);
10163 class InstallModuleCommand {
10164     constructor() {
10165         this.id = InstallModuleCommand.ID;
10166     }
10167     async execute(uri, name) {
10168         await modules_1.installModules(uri, [name]);
10169     }
10170 }
10171 InstallModuleCommand.ID = '_tsserver.installModule';
10172 class InstallModuleProvider {
10173     constructor(client) {
10174         this.client = client;
10175         coc_nvim_1.commands.register(new InstallModuleCommand(), true);
10176     }
10177     async provideCodeActions(document, _range, context, _token) {
10178         const uri = coc_nvim_1.Uri.parse(document.uri);
10179         if (uri.scheme != 'file')
10180             return null;
10181         let { diagnostics } = context;
10182         let diags = diagnostics.filter(s => s.code == 2307);
10183         let names = diags.map(o => {
10184             let ms = o.message.match(/module\s'(.+)'/);
10185             return ms ? ms[1] : null;
10186         });
10187         names = names.filter(s => s != null);
10188         if (!names.length)
10189             return null;
10190         let actions = [];
10191         for (let name of names) {
10192             let title = `install ${name}`;
10193             let command = {
10194                 title: `install ${name}`,
10195                 command: InstallModuleCommand.ID,
10196                 arguments: [document.uri, name]
10197             };
10198             let codeAction = vscode_languageserver_protocol_1.CodeAction.create(title, command, vscode_languageserver_protocol_1.CodeActionKind.QuickFix);
10199             actions.push(codeAction);
10200         }
10201         return actions;
10202     }
10203 }
10204 exports.default = InstallModuleProvider;
10205
10206
10207 /***/ }),
10208 /* 100 */
10209 /***/ (function(module, exports, __webpack_require__) {
10210
10211 "use strict";
10212
10213 var __importDefault = (this && this.__importDefault) || function (mod) {
10214     return (mod && mod.__esModule) ? mod : { "default": mod };
10215 };
10216 Object.defineProperty(exports, "__esModule", { value: true });
10217 exports.installModules = exports.distinct = exports.moduleExists = exports.runCommand = void 0;
10218 const child_process_1 = __webpack_require__(101);
10219 const coc_nvim_1 = __webpack_require__(1);
10220 const fs_1 = __importDefault(__webpack_require__(102));
10221 const path_1 = __importDefault(__webpack_require__(13));
10222 function runCommand(cmd, cwd, timeout) {
10223     return new Promise((resolve, reject) => {
10224         let timer;
10225         if (timeout) {
10226             timer = setTimeout(() => {
10227                 reject(new Error(`timeout after ${timeout}s`));
10228             }, timeout * 1000);
10229         }
10230         child_process_1.exec(cmd, { cwd }, (err, stdout) => {
10231             if (timer)
10232                 clearTimeout(timer);
10233             if (err) {
10234                 reject(new Error(`exited with ${err.code}`));
10235                 return;
10236             }
10237             resolve(stdout);
10238         });
10239     });
10240 }
10241 exports.runCommand = runCommand;
10242 async function getManager() {
10243     let res = await coc_nvim_1.workspace.findUp(['yarn.lock', 'package-lock.json']);
10244     if (!res)
10245         return 'yarn';
10246     return res.endsWith('yarn.lock') ? 'yarn' : 'npm';
10247 }
10248 async function getRoot() {
10249     let res = await coc_nvim_1.workspace.findUp(['package.json']);
10250     if (!res)
10251         return null;
10252     return path_1.default.dirname(res);
10253 }
10254 async function moduleExists(name) {
10255     try {
10256         let content = await runCommand(`npm info ${name} --json`, process.cwd());
10257         if (!content)
10258             return false;
10259         let obj = JSON.parse(content);
10260         if (obj.error != null)
10261             return false;
10262         return true;
10263     }
10264     catch (e) {
10265         return false;
10266     }
10267     return false;
10268 }
10269 exports.moduleExists = moduleExists;
10270 /**
10271  * Removes duplicates from the given array. The optional keyFn allows to specify
10272  * how elements are checked for equalness by returning a unique string for each.
10273  */
10274 function distinct(array, keyFn) {
10275     if (!keyFn) {
10276         return array.filter((element, position) => {
10277             return array.indexOf(element) === position;
10278         });
10279     }
10280     const seen = Object.create(null);
10281     return array.filter(elem => {
10282         const key = keyFn(elem);
10283         if (seen[key]) {
10284             return false;
10285         }
10286         seen[key] = true;
10287         return true;
10288     });
10289 }
10290 exports.distinct = distinct;
10291 async function installModules(uri, names) {
10292     names = distinct(names);
10293     let workspaceFolder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
10294     let root = workspaceFolder ? coc_nvim_1.Uri.parse(workspaceFolder.uri).fsPath : undefined;
10295     if (!root || !fs_1.default.existsSync(path_1.default.join(root, 'package.json'))) {
10296         coc_nvim_1.workspace.showMessage(`package.json not found from workspaceFolder: ${root}`, 'error');
10297         return;
10298     }
10299     let arr = names.concat(names.map(s => `@types/${s}`));
10300     let statusItem = coc_nvim_1.workspace.createStatusBarItem(99, { progress: true });
10301     statusItem.text = `Checking module ${arr.join(' ')}`;
10302     statusItem.show();
10303     let exists = await Promise.all(arr.map(name => {
10304         return moduleExists(name).then(exists => {
10305             return exists ? name : null;
10306         });
10307     }));
10308     let manager = await getManager();
10309     exists = exists.filter(s => s != null);
10310     if (!exists.length)
10311         return;
10312     let devs = exists.filter(s => s.startsWith('@types'));
10313     let deps = exists.filter(s => devs.indexOf(s) == -1);
10314     statusItem.text = `Installing ${exists.join(' ')}`;
10315     try {
10316         let cmd = manager == 'npm' ? `npm i ${deps.join(' ')}` : `yarn add ${deps.join(' ')}`;
10317         await runCommand(cmd, root);
10318         cmd = manager == 'npm' ? `npm i ${deps.join(' ')} --save-dev` : `yarn add ${deps.join(' ')} --save-dev`;
10319         await runCommand(cmd, root);
10320     }
10321     catch (e) {
10322         statusItem.dispose();
10323         coc_nvim_1.workspace.showMessage(`Install error ${e.message}`, 'error');
10324         return;
10325     }
10326     statusItem.dispose();
10327     coc_nvim_1.workspace.showMessage(`Installed: ${exists.join(' ')}`, 'more');
10328 }
10329 exports.installModules = installModules;
10330
10331
10332 /***/ }),
10333 /* 101 */
10334 /***/ (function(module, exports) {
10335
10336 module.exports = require("child_process");
10337
10338 /***/ }),
10339 /* 102 */
10340 /***/ (function(module, exports) {
10341
10342 module.exports = require("fs");
10343
10344 /***/ }),
10345 /* 103 */
10346 /***/ (function(module, exports, __webpack_require__) {
10347
10348 "use strict";
10349
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;
10355     o[k2] = m[k];
10356 }));
10357 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10358     Object.defineProperty(o, "default", { enumerable: true, value: v });
10359 }) : function(o, v) {
10360     o["default"] = v;
10361 });
10362 var __importStar = (this && this.__importStar) || function (mod) {
10363     if (mod && mod.__esModule) return mod;
10364     var result = {};
10365     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10366     __setModuleDefault(result, mod);
10367     return result;
10368 };
10369 var __importDefault = (this && this.__importDefault) || function (mod) {
10370     return (mod && mod.__esModule) ? mod : { "default": mod };
10371 };
10372 Object.defineProperty(exports, "__esModule", { value: true });
10373 /*---------------------------------------------------------------------------------------------
10374  *  Copyright (c) Microsoft Corporation. All rights reserved.
10375  *  Licensed under the MIT License. See License.txt in the project root for license information.
10376  *--------------------------------------------------------------------------------------------*/
10377 const coc_nvim_1 = __webpack_require__(1);
10378 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10379 const api_1 = __importDefault(__webpack_require__(40));
10380 const codeAction_1 = __webpack_require__(84);
10381 const typeConverters = __importStar(__webpack_require__(37));
10382 class ApplyCodeActionCommand {
10383     constructor(client, formattingConfigurationManager) {
10384         this.client = client;
10385         this.formattingConfigurationManager = formattingConfigurationManager;
10386         this.id = ApplyCodeActionCommand.ID;
10387     }
10388     async execute(action) {
10389         return codeAction_1.applyCodeActionCommands(this.client, action);
10390     }
10391 }
10392 ApplyCodeActionCommand.ID = '_typescript.applyCodeActionCommand';
10393 class ApplyFixAllCodeAction {
10394     constructor(client, formattingConfigurationManager) {
10395         this.client = client;
10396         this.formattingConfigurationManager = formattingConfigurationManager;
10397         this.id = ApplyFixAllCodeAction.ID;
10398     }
10399     async execute(document, file, tsAction) {
10400         if (!tsAction.fixId) {
10401             return;
10402         }
10403         await this.formattingConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
10404         const args = {
10405             scope: {
10406                 type: 'file',
10407                 args: { file }
10408             },
10409             fixId: tsAction.fixId
10410         };
10411         try {
10412             const res = await this.client.execute('getCombinedCodeFix', args, vscode_languageserver_protocol_1.CancellationToken.None);
10413             if (res.type != 'response') {
10414                 return;
10415             }
10416             let { body } = res;
10417             const edit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
10418             await coc_nvim_1.workspace.applyEdit(edit);
10419             const token = vscode_languageserver_protocol_1.CancellationToken.None;
10420             const { commands } = body;
10421             if (commands && commands.length) {
10422                 for (const command of commands) {
10423                     await this.client.execute('applyCodeActionCommand', { command }, token);
10424                 }
10425             }
10426         }
10427         catch (_a) {
10428             // noop
10429         }
10430     }
10431 }
10432 ApplyFixAllCodeAction.ID = '_typescript.applyFixAllCodeAction';
10433 /**
10434  * Unique set of diagnostics keyed on diagnostic range and error code.
10435  */
10436 class DiagnosticsSet {
10437     constructor(_values) {
10438         this._values = _values;
10439     }
10440     static from(diagnostics) {
10441         const values = new Map();
10442         for (const diagnostic of diagnostics) {
10443             values.set(DiagnosticsSet.key(diagnostic), diagnostic);
10444         }
10445         return new DiagnosticsSet(values);
10446     }
10447     static key(diagnostic) {
10448         const { start, end } = diagnostic.range;
10449         return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
10450     }
10451     get values() {
10452         return this._values.values();
10453     }
10454 }
10455 class SupportedCodeActionProvider {
10456     constructor(client) {
10457         this.client = client;
10458     }
10459     async getFixableDiagnosticsForContext(context) {
10460         const supportedActions = await this.supportedCodeActions;
10461         const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter(diagnostic => supportedActions.has(+diagnostic.code)));
10462         return Array.from(fixableDiagnostics.values);
10463     }
10464     get supportedCodeActions() {
10465         if (!this._supportedCodeActions) {
10466             return new Promise((resolve, reject) => {
10467                 this.client.execute('getSupportedCodeFixes', null, vscode_languageserver_protocol_1.CancellationToken.None).then(res => {
10468                     if (res.type !== 'response') {
10469                         resolve(new Set());
10470                         return;
10471                     }
10472                     let codes = res.body.map(code => +code).filter(code => !isNaN(code));
10473                     resolve(new Set(codes));
10474                 }, reject);
10475             });
10476         }
10477         return Promise.resolve(this._supportedCodeActions);
10478     }
10479 }
10480 class TypeScriptQuickFixProvider {
10481     constructor(client, formattingConfigurationManager) {
10482         this.client = client;
10483         this.formattingConfigurationManager = formattingConfigurationManager;
10484         coc_nvim_1.commands.register(new ApplyCodeActionCommand(client, formattingConfigurationManager));
10485         coc_nvim_1.commands.register(new ApplyFixAllCodeAction(client, formattingConfigurationManager));
10486         this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
10487     }
10488     async provideCodeActions(document, _range, context, token) {
10489         const file = this.client.toPath(document.uri);
10490         if (!file) {
10491             return [];
10492         }
10493         await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
10494         const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
10495         if (!fixableDiagnostics.length) {
10496             return [];
10497         }
10498         if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
10499             return [];
10500         }
10501         const results = [];
10502         for (const diagnostic of fixableDiagnostics) {
10503             results.push(...(await this.getFixesForDiagnostic(document, file, diagnostic, token)));
10504         }
10505         return results;
10506     }
10507     async getFixesForDiagnostic(document, file, diagnostic, token) {
10508         const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+diagnostic.code] });
10509         const codeFixesResponse = await this.client.execute('getCodeFixes', args, token);
10510         if (codeFixesResponse.type != 'response') {
10511             return [];
10512         }
10513         if (codeFixesResponse.body) {
10514             const results = [];
10515             for (const tsCodeFix of codeFixesResponse.body) {
10516                 results.push(...(await this.getAllFixesForTsCodeAction(document, file, diagnostic, tsCodeFix)));
10517             }
10518             return results;
10519         }
10520         return [];
10521     }
10522     async getAllFixesForTsCodeAction(document, file, diagnostic, tsAction) {
10523         const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
10524         const fixAll = await this.getFixAllForTsCodeAction(document, file, diagnostic, tsAction);
10525         return fixAll ? [singleFix, fixAll] : [singleFix];
10526     }
10527     getSingleFixForTsCodeAction(diagnostic, tsAction) {
10528         const codeAction = {
10529             title: tsAction.description,
10530             kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10531         };
10532         codeAction.edit = codeAction_1.getEditForCodeAction(this.client, tsAction);
10533         codeAction.diagnostics = [diagnostic];
10534         codeAction.isPreferred = true;
10535         if (tsAction.commands) {
10536             codeAction.command = {
10537                 command: ApplyCodeActionCommand.ID,
10538                 arguments: [tsAction],
10539                 title: tsAction.description
10540             };
10541         }
10542         return codeAction;
10543     }
10544     async getFixAllForTsCodeAction(document, file, diagnostic, tsAction) {
10545         if (!tsAction.fixId || !this.client.apiVersion.gte(api_1.default.v270)) {
10546             return undefined;
10547         }
10548         // Make sure there are multiple diagnostics of the same type in the file
10549         if (!this.client.diagnosticsManager
10550             .getDiagnostics(document.uri)
10551             .some(x => x.code === diagnostic.code && x !== diagnostic)) {
10552             return;
10553         }
10554         const action = {
10555             title: tsAction.fixAllDescription || 'Fix all in file',
10556             kind: vscode_languageserver_protocol_1.CodeActionKind.QuickFix
10557         };
10558         action.diagnostics = [diagnostic];
10559         action.command = {
10560             command: ApplyFixAllCodeAction.ID,
10561             arguments: [document, file, tsAction],
10562             title: ''
10563         };
10564         return action;
10565     }
10566 }
10567 exports.default = TypeScriptQuickFixProvider;
10568
10569
10570 /***/ }),
10571 /* 104 */
10572 /***/ (function(module, exports, __webpack_require__) {
10573
10574 "use strict";
10575
10576 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10577     if (k2 === undefined) k2 = k;
10578     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10579 }) : (function(o, m, k, k2) {
10580     if (k2 === undefined) k2 = k;
10581     o[k2] = m[k];
10582 }));
10583 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10584     Object.defineProperty(o, "default", { enumerable: true, value: v });
10585 }) : function(o, v) {
10586     o["default"] = v;
10587 });
10588 var __importStar = (this && this.__importStar) || function (mod) {
10589     if (mod && mod.__esModule) return mod;
10590     var result = {};
10591     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10592     __setModuleDefault(result, mod);
10593     return result;
10594 };
10595 Object.defineProperty(exports, "__esModule", { value: true });
10596 /*---------------------------------------------------------------------------------------------
10597  *  Copyright (c) Microsoft Corporation. All rights reserved.
10598  *  Licensed under the MIT License. See License.txt in the project root for license information.
10599  *--------------------------------------------------------------------------------------------*/
10600 const vscode_languageserver_protocol_1 = __webpack_require__(3);
10601 const coc_nvim_1 = __webpack_require__(1);
10602 const typeConverters = __importStar(__webpack_require__(37));
10603 class ApplyRefactoringCommand {
10604     constructor(client) {
10605         this.client = client;
10606         this.id = ApplyRefactoringCommand.ID;
10607     }
10608     async execute(document, file, refactor, action, range) {
10609         const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, range)), { refactor,
10610             action });
10611         const response = await this.client.execute('getEditsForRefactor', args, vscode_languageserver_protocol_1.CancellationToken.None);
10612         const body = response && response.body;
10613         if (!body || !body.edits.length) {
10614             return false;
10615         }
10616         const workspaceEdit = await this.toWorkspaceEdit(body);
10617         if (!(await coc_nvim_1.workspace.applyEdit(workspaceEdit))) {
10618             return false;
10619         }
10620         const renameLocation = body.renameLocation;
10621         if (renameLocation) {
10622             coc_nvim_1.commands.executeCommand('editor.action.rename', document.uri, typeConverters.Position.fromLocation(renameLocation));
10623         }
10624         return true;
10625     }
10626     async toWorkspaceEdit(body) {
10627         for (const edit of body.edits) {
10628             await coc_nvim_1.workspace.createFile(edit.fileName, { ignoreIfExists: true });
10629         }
10630         let workspaceEdit = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
10631         return workspaceEdit;
10632     }
10633 }
10634 ApplyRefactoringCommand.ID = '_typescript.applyRefactoring';
10635 class SelectRefactorCommand {
10636     constructor(doRefactoring) {
10637         this.doRefactoring = doRefactoring;
10638         this.id = SelectRefactorCommand.ID;
10639     }
10640     async execute(document, file, info, range) {
10641         let { actions } = info;
10642         const idx = actions.length == 1 ? 0 : await coc_nvim_1.workspace.showQuickpick(actions.map(action => action.description || action.name));
10643         if (idx == -1)
10644             return false;
10645         let label = info.actions[idx].name;
10646         if (!label)
10647             return false;
10648         return this.doRefactoring.execute(document, file, info.name, label, range);
10649     }
10650 }
10651 SelectRefactorCommand.ID = '_typescript.selectRefactoring';
10652 class TypeScriptRefactorProvider {
10653     constructor(client, formattingOptionsManager) {
10654         this.client = client;
10655         this.formattingOptionsManager = formattingOptionsManager;
10656         const doRefactoringCommand = coc_nvim_1.commands.register(new ApplyRefactoringCommand(this.client));
10657         coc_nvim_1.commands.register(new SelectRefactorCommand(doRefactoringCommand));
10658     }
10659     async provideCodeActions(document, range, context, token) {
10660         if (!this.shouldTrigger(context)) {
10661             return undefined;
10662         }
10663         const file = this.client.toPath(document.uri);
10664         if (!file)
10665             return undefined;
10666         await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
10667         const args = typeConverters.Range.toFileRangeRequestArgs(file, range);
10668         let response;
10669         try {
10670             response = await this.client.interruptGetErr(() => {
10671                 return this.client.execute('getApplicableRefactors', args, token);
10672             });
10673             if (!response || !response.body) {
10674                 return undefined;
10675             }
10676         }
10677         catch (_a) {
10678             return undefined;
10679         }
10680         return this.convertApplicableRefactors(response.body, document, file, range, context.only && context.only.some(v => v.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor)));
10681     }
10682     convertApplicableRefactors(body, document, file, rangeOrSelection, setPrefrred) {
10683         const actions = [];
10684         for (const info of body) {
10685             // ignore not refactor that not applicable
10686             if (info.notApplicableReason)
10687                 continue;
10688             if (!info.inlineable) {
10689                 const codeAction = {
10690                     title: info.description,
10691                     kind: vscode_languageserver_protocol_1.CodeActionKind.Refactor
10692                 };
10693                 codeAction.command = {
10694                     title: info.description,
10695                     command: SelectRefactorCommand.ID,
10696                     arguments: [document, file, info, rangeOrSelection]
10697                 };
10698                 actions.push(codeAction);
10699             }
10700             else {
10701                 for (const action of info.actions) {
10702                     let codeAction = this.refactorActionToCodeAction(action, document, file, info, rangeOrSelection);
10703                     if (setPrefrred) {
10704                         codeAction.isPreferred = TypeScriptRefactorProvider.isPreferred(action, info.actions);
10705                     }
10706                     actions.push(codeAction);
10707                 }
10708             }
10709         }
10710         return actions;
10711     }
10712     refactorActionToCodeAction(action, document, file, info, rangeOrSelection) {
10713         const codeAction = {
10714             title: action.description,
10715             kind: TypeScriptRefactorProvider.getKind(action)
10716         };
10717         codeAction.command = {
10718             title: action.description,
10719             command: ApplyRefactoringCommand.ID,
10720             arguments: [document, file, info.name, action.name, rangeOrSelection]
10721         };
10722         return codeAction;
10723     }
10724     shouldTrigger(context) {
10725         if (context.only &&
10726             context.only.every(o => !o.includes(vscode_languageserver_protocol_1.CodeActionKind.Refactor))) {
10727             return false;
10728         }
10729         return true;
10730     }
10731     static getKind(refactor) {
10732         if (refactor.name.startsWith('function_')) {
10733             return TypeScriptRefactorProvider.extractFunctionKind;
10734         }
10735         else if (refactor.name.startsWith('constant_')) {
10736             return TypeScriptRefactorProvider.extractConstantKind;
10737         }
10738         else if (refactor.name.startsWith('Move')) {
10739             return TypeScriptRefactorProvider.moveKind;
10740         }
10741         return vscode_languageserver_protocol_1.CodeActionKind.Refactor;
10742     }
10743     static isPreferred(action, allActions) {
10744         let kind = TypeScriptRefactorProvider.getKind(action);
10745         if (TypeScriptRefactorProvider.extractConstantKind == kind) {
10746             // Only mark the action with the lowest scope as preferred
10747             const getScope = (name) => {
10748                 var _a;
10749                 const scope = (_a = name.match(/scope_(\d)/)) === null || _a === void 0 ? void 0 : _a[1];
10750                 return scope ? +scope : undefined;
10751             };
10752             const scope = getScope(action.name);
10753             if (typeof scope !== 'number') {
10754                 return false;
10755             }
10756             return allActions
10757                 .filter(otherAtion => otherAtion !== action && otherAtion.name.startsWith('constant_'))
10758                 .every(otherAction => {
10759                 const otherScope = getScope(otherAction.name);
10760                 return typeof otherScope === 'number' ? scope < otherScope : true;
10761             });
10762         }
10763         let { name } = action;
10764         if (name.startsWith('Extract to type alias') || name.startsWith('Extract to interface')) {
10765             return true;
10766         }
10767         return false;
10768     }
10769 }
10770 exports.default = TypeScriptRefactorProvider;
10771 TypeScriptRefactorProvider.extractFunctionKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.function';
10772 TypeScriptRefactorProvider.extractConstantKind = vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract + '.constant';
10773 TypeScriptRefactorProvider.moveKind = vscode_languageserver_protocol_1.CodeActionKind.Refactor + '.move';
10774 TypeScriptRefactorProvider.metadata = {
10775     providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.Refactor]
10776 };
10777
10778
10779 /***/ }),
10780 /* 105 */
10781 /***/ (function(module, exports, __webpack_require__) {
10782
10783 "use strict";
10784
10785 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10786     if (k2 === undefined) k2 = k;
10787     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10788 }) : (function(o, m, k, k2) {
10789     if (k2 === undefined) k2 = k;
10790     o[k2] = m[k];
10791 }));
10792 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10793     Object.defineProperty(o, "default", { enumerable: true, value: v });
10794 }) : function(o, v) {
10795     o["default"] = v;
10796 });
10797 var __importStar = (this && this.__importStar) || function (mod) {
10798     if (mod && mod.__esModule) return mod;
10799     var result = {};
10800     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10801     __setModuleDefault(result, mod);
10802     return result;
10803 };
10804 Object.defineProperty(exports, "__esModule", { value: true });
10805 const typeConverters = __importStar(__webpack_require__(37));
10806 class TypeScriptReferences {
10807     constructor(client) {
10808         this.client = client;
10809     }
10810     async provideReferences(document, position, context, token) {
10811         const filepath = this.client.toPath(document.uri);
10812         if (!filepath)
10813             return [];
10814         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
10815         try {
10816             const msg = await this.client.execute('references', args, token);
10817             if (!msg || msg.type != 'response' || !msg.body) {
10818                 return [];
10819             }
10820             const result = [];
10821             for (const ref of msg.body.refs) {
10822                 if (!context.includeDeclaration && ref.isDefinition) {
10823                     continue;
10824                 }
10825                 const url = this.client.toResource(ref.file);
10826                 const location = typeConverters.Location.fromTextSpan(url, ref);
10827                 result.push(location);
10828             }
10829             return result;
10830         }
10831         catch (_a) {
10832             return [];
10833         }
10834     }
10835 }
10836 exports.default = TypeScriptReferences;
10837
10838
10839 /***/ }),
10840 /* 106 */
10841 /***/ (function(module, exports, __webpack_require__) {
10842
10843 "use strict";
10844
10845 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10846     if (k2 === undefined) k2 = k;
10847     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10848 }) : (function(o, m, k, k2) {
10849     if (k2 === undefined) k2 = k;
10850     o[k2] = m[k];
10851 }));
10852 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10853     Object.defineProperty(o, "default", { enumerable: true, value: v });
10854 }) : function(o, v) {
10855     o["default"] = v;
10856 });
10857 var __importStar = (this && this.__importStar) || function (mod) {
10858     if (mod && mod.__esModule) return mod;
10859     var result = {};
10860     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10861     __setModuleDefault(result, mod);
10862     return result;
10863 };
10864 Object.defineProperty(exports, "__esModule", { value: true });
10865 const PConst = __importStar(__webpack_require__(39));
10866 const typeConverters = __importStar(__webpack_require__(37));
10867 const baseCodeLensProvider_1 = __webpack_require__(35);
10868 class TypeScriptReferencesCodeLensProvider extends baseCodeLensProvider_1.TypeScriptBaseCodeLensProvider {
10869     resolveCodeLens(codeLens, token) {
10870         let { uri } = codeLens.data;
10871         let filepath = this.client.toPath(uri);
10872         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
10873         return this.client
10874             .execute('references', args, token, {
10875             lowPriority: true
10876         })
10877             .then(response => {
10878             if (!response || response.type != 'response' || !response.body) {
10879                 throw codeLens;
10880             }
10881             const locations = response.body.refs
10882                 .map(reference => typeConverters.Location.fromTextSpan(this.client.toResource(reference.file), reference))
10883                 .filter(location => 
10884             // Exclude original definition from references
10885             !(location.uri.toString() === uri &&
10886                 location.range.start.line === codeLens.range.start.line &&
10887                 location.range.start.character ===
10888                     codeLens.range.start.character));
10889             codeLens.command = {
10890                 title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
10891                 command: locations.length ? 'editor.action.showReferences' : '',
10892                 arguments: [uri, codeLens.range.start, locations]
10893             };
10894             return codeLens;
10895         })
10896             .catch(() => {
10897             codeLens.command = {
10898                 title: '0 references',
10899                 command: ''
10900             };
10901             return codeLens;
10902         });
10903     }
10904     extractSymbol(document, item, parent) {
10905         if (parent && parent.kind === PConst.Kind.enum) {
10906             return super.getSymbolRange(document, item);
10907         }
10908         switch (item.kind) {
10909             case PConst.Kind.const:
10910             case PConst.Kind.let:
10911             case PConst.Kind.variable:
10912             case PConst.Kind.function:
10913                 // Only show references for exported variables
10914                 if (!item.kindModifiers.match(/\bexport\b/)) {
10915                     break;
10916                 }
10917             // fallthrough
10918             case PConst.Kind.class:
10919                 if (item.text === '<class>') {
10920                     break;
10921                 }
10922             // fallthrough
10923             case PConst.Kind.method:
10924             case PConst.Kind.memberVariable:
10925             case PConst.Kind.memberGetAccessor:
10926             case PConst.Kind.memberSetAccessor:
10927             case PConst.Kind.constructorImplementation:
10928             case PConst.Kind.interface:
10929             case PConst.Kind.type:
10930             case PConst.Kind.enum:
10931                 return super.getSymbolRange(document, item);
10932         }
10933         return null;
10934     }
10935 }
10936 exports.default = TypeScriptReferencesCodeLensProvider;
10937
10938
10939 /***/ }),
10940 /* 107 */
10941 /***/ (function(module, exports, __webpack_require__) {
10942
10943 "use strict";
10944
10945 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10946     if (k2 === undefined) k2 = k;
10947     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10948 }) : (function(o, m, k, k2) {
10949     if (k2 === undefined) k2 = k;
10950     o[k2] = m[k];
10951 }));
10952 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10953     Object.defineProperty(o, "default", { enumerable: true, value: v });
10954 }) : function(o, v) {
10955     o["default"] = v;
10956 });
10957 var __importStar = (this && this.__importStar) || function (mod) {
10958     if (mod && mod.__esModule) return mod;
10959     var result = {};
10960     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10961     __setModuleDefault(result, mod);
10962     return result;
10963 };
10964 var __importDefault = (this && this.__importDefault) || function (mod) {
10965     return (mod && mod.__esModule) ? mod : { "default": mod };
10966 };
10967 Object.defineProperty(exports, "__esModule", { value: true });
10968 /*---------------------------------------------------------------------------------------------
10969  *  Copyright (c) Microsoft Corporation. All rights reserved.
10970  *  Licensed under the MIT License. See License.txt in the project root for license information.
10971  *--------------------------------------------------------------------------------------------*/
10972 const coc_nvim_1 = __webpack_require__(1);
10973 const path_1 = __importDefault(__webpack_require__(13));
10974 const api_1 = __importDefault(__webpack_require__(40));
10975 const typeConverters = __importStar(__webpack_require__(37));
10976 class TypeScriptRenameProvider {
10977     constructor(client, fileConfigurationManager) {
10978         this.client = client;
10979         this.fileConfigurationManager = fileConfigurationManager;
10980     }
10981     async prepareRename(document, position, token) {
10982         const response = await this.execRename(document, position, token);
10983         if (!response || response.type !== 'response' || !response.body) {
10984             return null;
10985         }
10986         const renameInfo = response.body.info;
10987         if (!renameInfo.canRename) {
10988             return Promise.reject(new Error('Invalid location for rename.'));
10989         }
10990         if (this.client.apiVersion.gte(api_1.default.v310)) {
10991             const triggerSpan = renameInfo.triggerSpan;
10992             if (triggerSpan) {
10993                 const range = typeConverters.Range.fromTextSpan(triggerSpan);
10994                 return range;
10995             }
10996         }
10997         return null;
10998     }
10999     async provideRenameEdits(document, position, newName, token) {
11000         const response = await this.execRename(document, position, token);
11001         if (!response || response.type !== 'response' || !response.body) {
11002             return null;
11003         }
11004         const renameInfo = response.body.info;
11005         if (!renameInfo.canRename) {
11006             return Promise.reject(new Error('Invalid location for rename.'));
11007         }
11008         if (this.client.apiVersion.gte(api_1.default.v310)) {
11009             if (renameInfo.fileToRename) {
11010                 const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
11011                 if (edits) {
11012                     return edits;
11013                 }
11014                 else {
11015                     return Promise.reject(new Error('An error occurred while renaming file'));
11016                 }
11017             }
11018         }
11019         return this.toWorkspaceEdit(response.body.locs, newName);
11020     }
11021     async execRename(document, position, token) {
11022         const file = this.client.toPath(document.uri);
11023         if (!file)
11024             return undefined;
11025         const args = Object.assign(Object.assign({}, typeConverters.Position.toFileLocationRequestArgs(file, position)), { findInStrings: false, findInComments: false });
11026         await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
11027         return this.client.interruptGetErr(() => {
11028             return this.client.execute('rename', args, token);
11029         });
11030     }
11031     toWorkspaceEdit(locations, newName) {
11032         let changes = {};
11033         for (const spanGroup of locations) {
11034             const uri = this.client.toResource(spanGroup.file);
11035             if (uri) {
11036                 changes[uri] = [];
11037                 for (const textSpan of spanGroup.locs) {
11038                     changes[uri].push({
11039                         range: typeConverters.Range.fromTextSpan(textSpan),
11040                         newText: (textSpan.prefixText || '') + newName + (textSpan.suffixText || '')
11041                     });
11042                 }
11043             }
11044         }
11045         return { changes };
11046     }
11047     async renameFile(fileToRename, newName, token) {
11048         // Make sure we preserve file exension if none provided
11049         if (!path_1.default.extname(newName)) {
11050             newName += path_1.default.extname(fileToRename);
11051         }
11052         const dirname = path_1.default.dirname(fileToRename);
11053         const newFilePath = path_1.default.join(dirname, newName);
11054         const args = {
11055             file: fileToRename,
11056             oldFilePath: fileToRename,
11057             newFilePath
11058         };
11059         const response = await this.client.execute('getEditsForFileRename', args, token);
11060         if (response.type !== 'response' || !response.body) {
11061             return undefined;
11062         }
11063         const edits = typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
11064         edits.documentChanges = edits.documentChanges || [];
11065         edits.documentChanges.push({
11066             kind: 'rename',
11067             oldUri: coc_nvim_1.Uri.file(fileToRename).toString(),
11068             newUri: coc_nvim_1.Uri.file(newFilePath).toString(),
11069             options: {
11070                 overwrite: false,
11071                 ignoreIfExists: true
11072             }
11073         });
11074         return edits;
11075     }
11076 }
11077 exports.default = TypeScriptRenameProvider;
11078
11079
11080 /***/ }),
11081 /* 108 */
11082 /***/ (function(module, exports, __webpack_require__) {
11083
11084 "use strict";
11085
11086 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11087     if (k2 === undefined) k2 = k;
11088     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11089 }) : (function(o, m, k, k2) {
11090     if (k2 === undefined) k2 = k;
11091     o[k2] = m[k];
11092 }));
11093 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11094     Object.defineProperty(o, "default", { enumerable: true, value: v });
11095 }) : function(o, v) {
11096     o["default"] = v;
11097 });
11098 var __importStar = (this && this.__importStar) || function (mod) {
11099     if (mod && mod.__esModule) return mod;
11100     var result = {};
11101     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11102     __setModuleDefault(result, mod);
11103     return result;
11104 };
11105 Object.defineProperty(exports, "__esModule", { value: true });
11106 const Previewer = __importStar(__webpack_require__(86));
11107 const typeConverters = __importStar(__webpack_require__(37));
11108 class TypeScriptSignatureHelpProvider {
11109     constructor(client) {
11110         this.client = client;
11111     }
11112     async provideSignatureHelp(document, position, token) {
11113         const filepath = this.client.toPath(document.uri);
11114         if (!filepath) {
11115             return undefined;
11116         }
11117         const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
11118         let response;
11119         try {
11120             response = await this.client.interruptGetErr(() => this.client.execute('signatureHelp', args, token));
11121         }
11122         catch (e) {
11123             return undefined;
11124         }
11125         if (response.type !== 'response' || !response.body) {
11126             return undefined;
11127         }
11128         let info = response.body;
11129         const result = {
11130             activeSignature: info.selectedItemIndex,
11131             activeParameter: this.getActiveParmeter(info),
11132             signatures: info.items.map(signature => {
11133                 return this.convertSignature(signature);
11134             })
11135         };
11136         return result;
11137     }
11138     getActiveParmeter(info) {
11139         const activeSignature = info.items[info.selectedItemIndex];
11140         if (activeSignature && activeSignature.isVariadic) {
11141             return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
11142         }
11143         return info.argumentIndex;
11144     }
11145     convertSignature(item) {
11146         let parameters = item.parameters.map(p => {
11147             return {
11148                 label: Previewer.plain(p.displayParts),
11149                 documentation: Previewer.markdownDocumentation(p.documentation, [])
11150             };
11151         });
11152         let label = Previewer.plain(item.prefixDisplayParts);
11153         label += parameters.map(parameter => parameter.label).join(Previewer.plain(item.separatorDisplayParts));
11154         label += Previewer.plain(item.suffixDisplayParts);
11155         return {
11156             label,
11157             documentation: Previewer.markdownDocumentation(item.documentation, item.tags.filter(x => x.name !== 'param')),
11158             parameters
11159         };
11160     }
11161 }
11162 exports.default = TypeScriptSignatureHelpProvider;
11163 TypeScriptSignatureHelpProvider.triggerCharacters = ['(', ',', '<'];
11164
11165
11166 /***/ }),
11167 /* 109 */
11168 /***/ (function(module, exports, __webpack_require__) {
11169
11170 "use strict";
11171
11172 /*---------------------------------------------------------------------------------------------
11173  *  Copyright (c) Microsoft Corporation. All rights reserved.
11174  *  Licensed under the MIT License. See License.txt in the project root for license information.
11175  *--------------------------------------------------------------------------------------------*/
11176 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11177     if (k2 === undefined) k2 = k;
11178     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11179 }) : (function(o, m, k, k2) {
11180     if (k2 === undefined) k2 = k;
11181     o[k2] = m[k];
11182 }));
11183 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11184     Object.defineProperty(o, "default", { enumerable: true, value: v });
11185 }) : function(o, v) {
11186     o["default"] = v;
11187 });
11188 var __importStar = (this && this.__importStar) || function (mod) {
11189     if (mod && mod.__esModule) return mod;
11190     var result = {};
11191     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11192     __setModuleDefault(result, mod);
11193     return result;
11194 };
11195 Object.defineProperty(exports, "__esModule", { value: true });
11196 const typeConverters = __importStar(__webpack_require__(37));
11197 class SmartSelection {
11198     constructor(client) {
11199         this.client = client;
11200     }
11201     async provideSelectionRanges(document, positions, token) {
11202         const file = this.client.toPath(document.uri);
11203         if (!file) {
11204             return undefined;
11205         }
11206         const args = {
11207             file,
11208             locations: positions.map(typeConverters.Position.toLocation)
11209         };
11210         const response = await this.client.execute('selectionRange', args, token);
11211         if (response.type !== 'response' || !response.body) {
11212             return undefined;
11213         }
11214         return response.body.map(SmartSelection.convertSelectionRange);
11215     }
11216     static convertSelectionRange(selectionRange) {
11217         return {
11218             range: typeConverters.Range.fromTextSpan(selectionRange.textSpan),
11219             parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : undefined,
11220         };
11221     }
11222 }
11223 exports.default = SmartSelection;
11224
11225
11226 /***/ }),
11227 /* 110 */
11228 /***/ (function(module, exports, __webpack_require__) {
11229
11230 "use strict";
11231
11232 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11233     if (k2 === undefined) k2 = k;
11234     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11235 }) : (function(o, m, k, k2) {
11236     if (k2 === undefined) k2 = k;
11237     o[k2] = m[k];
11238 }));
11239 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11240     Object.defineProperty(o, "default", { enumerable: true, value: v });
11241 }) : function(o, v) {
11242     o["default"] = v;
11243 });
11244 var __importStar = (this && this.__importStar) || function (mod) {
11245     if (mod && mod.__esModule) return mod;
11246     var result = {};
11247     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11248     __setModuleDefault(result, mod);
11249     return result;
11250 };
11251 Object.defineProperty(exports, "__esModule", { value: true });
11252 /*---------------------------------------------------------------------------------------------
11253  *  Copyright (c) Microsoft Corporation. All rights reserved.
11254  *  Licensed under the MIT License. See License.txt in the project root for license information.
11255  *--------------------------------------------------------------------------------------------*/
11256 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11257 const coc_nvim_1 = __webpack_require__(1);
11258 const typeConverters = __importStar(__webpack_require__(37));
11259 const mutex_1 = __webpack_require__(111);
11260 function wait(ms) {
11261     return new Promise(resolve => {
11262         setTimeout(() => {
11263             resolve();
11264         }, ms);
11265     });
11266 }
11267 class UpdateImportsOnFileRenameHandler {
11268     constructor(client, fileConfigurationManager, languageId) {
11269         this.client = client;
11270         this.fileConfigurationManager = fileConfigurationManager;
11271         this.disposables = [];
11272         let glob = languageId == 'typescript' ? '**/*.{ts,tsx}' : '**/*.{js,jsx}';
11273         const watcher = coc_nvim_1.workspace.createFileSystemWatcher(glob);
11274         this.disposables.push(watcher);
11275         let mutex = new mutex_1.Mutex();
11276         watcher.onDidRename(async (e) => {
11277             let release = await mutex.acquire();
11278             try {
11279                 await this.doRename(e.oldUri, e.newUri);
11280                 release();
11281             }
11282             catch (e) {
11283                 this.client.logger.error('Error on rename:', e);
11284                 release();
11285             }
11286         }, null, this.disposables);
11287     }
11288     dispose() {
11289         coc_nvim_1.disposeAll(this.disposables);
11290     }
11291     async doRename(oldResource, newResource) {
11292         if (oldResource.scheme !== 'file' || newResource.scheme !== 'file') {
11293             return;
11294         }
11295         const targetFile = newResource.fsPath;
11296         const oldFile = oldResource.fsPath;
11297         const newUri = newResource.toString();
11298         let oldDocument = coc_nvim_1.workspace.getDocument(oldResource.toString());
11299         if (oldDocument) {
11300             await coc_nvim_1.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
11301         }
11302         let document = coc_nvim_1.workspace.getDocument(newUri);
11303         if (document) {
11304             await coc_nvim_1.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
11305             await wait(30);
11306         }
11307         document = await coc_nvim_1.workspace.loadFile(newUri);
11308         if (!document)
11309             return;
11310         await wait(50);
11311         const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
11312         if (!edits)
11313             return;
11314         if (await this.promptUser(newResource)) {
11315             await coc_nvim_1.workspace.applyEdit(edits);
11316         }
11317     }
11318     async promptUser(newResource) {
11319         return await coc_nvim_1.workspace.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
11320     }
11321     async getEditsForFileRename(document, oldFile, newFile) {
11322         await this.fileConfigurationManager.ensureConfigurationForDocument(document, vscode_languageserver_protocol_1.CancellationToken.None);
11323         const response = await this.client.interruptGetErr(() => {
11324             const args = {
11325                 oldFilePath: oldFile,
11326                 newFilePath: newFile,
11327             };
11328             return this.client.execute('getEditsForFileRename', args, vscode_languageserver_protocol_1.CancellationToken.None);
11329         });
11330         if (!response || response.type != 'response' || !response.body) {
11331             return;
11332         }
11333         const edits = [];
11334         for (const edit of response.body) {
11335             // Workaround for https://github.com/Microsoft/vscode/issues/52675
11336             if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
11337                 continue;
11338             }
11339             for (const change of edit.textChanges) {
11340                 if (change.newText.match(/\/node_modules\//gi)) {
11341                     continue;
11342                 }
11343             }
11344             edits.push(edit);
11345         }
11346         return typeConverters.WorkspaceEdit.fromFileCodeEdits(this.client, edits);
11347     }
11348 }
11349 exports.default = UpdateImportsOnFileRenameHandler;
11350
11351
11352 /***/ }),
11353 /* 111 */
11354 /***/ (function(module, exports, __webpack_require__) {
11355
11356 "use strict";
11357
11358 Object.defineProperty(exports, "__esModule", { value: true });
11359 exports.Mutex = void 0;
11360 class Mutex {
11361     constructor() {
11362         this.tasks = [];
11363         this.count = 1;
11364     }
11365     sched() {
11366         if (this.count > 0 && this.tasks.length > 0) {
11367             this.count--;
11368             let next = this.tasks.shift();
11369             next();
11370         }
11371     }
11372     get busy() {
11373         return this.count == 0;
11374     }
11375     // tslint:disable-next-line: typedef
11376     acquire() {
11377         return new Promise(res => {
11378             let task = () => {
11379                 let released = false;
11380                 res(() => {
11381                     if (!released) {
11382                         released = true;
11383                         this.count++;
11384                         this.sched();
11385                     }
11386                 });
11387             };
11388             this.tasks.push(task);
11389             process.nextTick(this.sched.bind(this));
11390         });
11391     }
11392     use(f) {
11393         return this.acquire()
11394             .then(release => {
11395             return f()
11396                 .then(res => {
11397                 release();
11398                 return res;
11399             })
11400                 .catch(err => {
11401                 release();
11402                 throw err;
11403             });
11404         });
11405     }
11406 }
11407 exports.Mutex = Mutex;
11408
11409
11410 /***/ }),
11411 /* 112 */
11412 /***/ (function(module, exports, __webpack_require__) {
11413
11414 "use strict";
11415
11416 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11417     if (k2 === undefined) k2 = k;
11418     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11419 }) : (function(o, m, k, k2) {
11420     if (k2 === undefined) k2 = k;
11421     o[k2] = m[k];
11422 }));
11423 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11424     Object.defineProperty(o, "default", { enumerable: true, value: v });
11425 }) : function(o, v) {
11426     o["default"] = v;
11427 });
11428 var __importStar = (this && this.__importStar) || function (mod) {
11429     if (mod && mod.__esModule) return mod;
11430     var result = {};
11431     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11432     __setModuleDefault(result, mod);
11433     return result;
11434 };
11435 Object.defineProperty(exports, "__esModule", { value: true });
11436 exports.OrganizeImportsCodeActionProvider = exports.OrganizeImportsCommand = void 0;
11437 /*---------------------------------------------------------------------------------------------
11438  *  Copyright (c) Microsoft Corporation. All rights reserved.
11439  *  Licensed under the MIT License. See License.txt in the project root for license information.
11440  *--------------------------------------------------------------------------------------------*/
11441 const coc_nvim_1 = __webpack_require__(1);
11442 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11443 const typeconverts = __importStar(__webpack_require__(37));
11444 class OrganizeImportsCommand {
11445     constructor(service) {
11446         this.service = service;
11447         this.id = 'tsserver.organizeImports';
11448     }
11449     async _execute(client, document) {
11450         let file = client.toPath(document.uri);
11451         const args = {
11452             scope: {
11453                 type: 'file',
11454                 args: {
11455                     file
11456                 }
11457             }
11458         };
11459         const response = await client.interruptGetErr(() => client.execute('organizeImports', args, vscode_languageserver_protocol_1.CancellationToken.None));
11460         if (!response || response.type != 'response' || !response.success) {
11461             return;
11462         }
11463         const edit = typeconverts.WorkspaceEdit.fromFileCodeEdits(client, response.body);
11464         let keys = Object.keys(edit.changes);
11465         if (keys.length == 1) {
11466             let doc = coc_nvim_1.workspace.getDocument(keys[0]);
11467             if (doc) {
11468                 await doc.applyEdits(edit.changes[keys[0]]);
11469                 return;
11470             }
11471         }
11472         if (edit)
11473             await coc_nvim_1.workspace.applyEdit(edit);
11474     }
11475     async execute(document) {
11476         let client = await this.service.getClientHost();
11477         if (!document) {
11478             let doc = await coc_nvim_1.workspace.document;
11479             if (!doc.attached) {
11480                 throw new Error(`Document not attached.`);
11481             }
11482             if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
11483                 throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
11484             }
11485             document = doc.textDocument;
11486         }
11487         await this._execute(client.serviceClient, document);
11488     }
11489 }
11490 exports.OrganizeImportsCommand = OrganizeImportsCommand;
11491 class OrganizeImportsCodeActionProvider {
11492     // public static readonly minVersion = API.v280
11493     constructor(client, fileConfigManager) {
11494         this.client = client;
11495         this.fileConfigManager = fileConfigManager;
11496         this.metadata = {
11497             providedCodeActionKinds: [vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports]
11498         };
11499     }
11500     async provideCodeActions(document, _range, context, token) {
11501         if (this.client.modeIds.indexOf(document.languageId) == -1)
11502             return;
11503         if (!context.only || !context.only.includes(vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports)) {
11504             return [];
11505         }
11506         await this.fileConfigManager.ensureConfigurationForDocument(document, token);
11507         const action = vscode_languageserver_protocol_1.CodeAction.create('Organize Imports', {
11508             title: '',
11509             command: 'tsserver.organizeImports',
11510             arguments: [document]
11511         }, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports);
11512         return [action];
11513     }
11514 }
11515 exports.OrganizeImportsCodeActionProvider = OrganizeImportsCodeActionProvider;
11516
11517
11518 /***/ }),
11519 /* 113 */
11520 /***/ (function(module, exports, __webpack_require__) {
11521
11522 "use strict";
11523
11524 var __importDefault = (this && this.__importDefault) || function (mod) {
11525     return (mod && mod.__esModule) ? mod : { "default": mod };
11526 };
11527 Object.defineProperty(exports, "__esModule", { value: true });
11528 /*---------------------------------------------------------------------------------------------
11529  *  Copyright (c) Microsoft Corporation. All rights reserved.
11530  *  Licensed under the MIT License. See License.txt in the project root for license information.
11531  *--------------------------------------------------------------------------------------------*/
11532 const coc_nvim_1 = __webpack_require__(1);
11533 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11534 const api_1 = __importDefault(__webpack_require__(40));
11535 function objAreEqual(a, b) {
11536     let keys = Object.keys(a);
11537     for (let i = 0; i < keys.length; i++) { // tslint:disable-line
11538         let key = keys[i];
11539         if (a[key] !== b[key]) {
11540             return false;
11541         }
11542     }
11543     return true;
11544 }
11545 class FileConfigurationManager {
11546     constructor(client) {
11547         this.client = client;
11548         this.cachedMap = new Map();
11549         this.disposables = [];
11550         coc_nvim_1.workspace.onDidCloseTextDocument(textDocument => {
11551             // When a document gets closed delete the cached formatting options.
11552             // This is necessary since the tsserver now closed a project when its
11553             // last file in it closes which drops the stored formatting options
11554             // as well.
11555             this.cachedMap.delete(textDocument.uri);
11556         }, undefined, this.disposables);
11557     }
11558     async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
11559         const file = this.client.toPath(document.uri);
11560         let options = {
11561             tabSize,
11562             insertSpaces
11563         };
11564         let cachedOption = this.cachedMap.get(document.uri);
11565         const currentOptions = this.getFileOptions(options, document);
11566         if (cachedOption
11567             && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions)
11568             && objAreEqual(cachedOption.preferences, currentOptions.preferences))
11569             return;
11570         this.cachedMap.set(document.uri, currentOptions);
11571         const args = Object.assign({ file }, currentOptions);
11572         await this.client.execute('configure', args, vscode_languageserver_protocol_1.CancellationToken.None);
11573         try {
11574             const response = await this.client.execute('configure', args, token);
11575             if (response.type !== 'response') {
11576                 this.cachedMap.delete(document.uri);
11577             }
11578         }
11579         catch (_e) {
11580             this.cachedMap.delete(document.uri);
11581         }
11582     }
11583     async ensureConfigurationForDocument(document, token) {
11584         let opts = await coc_nvim_1.workspace.getFormatOptions(document.uri);
11585         return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token);
11586     }
11587     reset() {
11588         this.cachedMap.clear();
11589     }
11590     getLanguageConfiguration(languageId) {
11591         return coc_nvim_1.workspace.getConfiguration(languageId);
11592     }
11593     isTypeScriptDocument(languageId) {
11594         return languageId.startsWith('typescript');
11595     }
11596     formatEnabled(document) {
11597         let { languageId, uri } = document;
11598         let language = languageId.startsWith('typescript') ? 'typescript' : 'javascript';
11599         const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
11600         return config.get('enabled');
11601     }
11602     enableJavascript() {
11603         const config = coc_nvim_1.workspace.getConfiguration('tsserver');
11604         return !!config.get('enableJavascript');
11605     }
11606     getFileOptions(options, document) {
11607         const lang = this.isTypeScriptDocument(document.languageId) ? 'typescript' : 'javascript';
11608         return {
11609             formatOptions: this.getFormatOptions(options, lang, document.uri),
11610             preferences: this.getPreferences(lang, document.uri)
11611         };
11612     }
11613     getFormatOptions(options, language, uri) {
11614         const config = coc_nvim_1.workspace.getConfiguration(`${language}.format`, uri);
11615         return {
11616             tabSize: options.tabSize,
11617             indentSize: options.tabSize,
11618             convertTabsToSpaces: options.insertSpaces,
11619             // We can use \n here since the editor normalizes later on to its line endings.
11620             newLineCharacter: '\n',
11621             insertSpaceAfterCommaDelimiter: config.get('insertSpaceAfterCommaDelimiter'),
11622             insertSpaceAfterConstructor: config.get('insertSpaceAfterConstructor'),
11623             insertSpaceAfterSemicolonInForStatements: config.get('insertSpaceAfterSemicolonInForStatements'),
11624             insertSpaceBeforeAndAfterBinaryOperators: config.get('insertSpaceBeforeAndAfterBinaryOperators'),
11625             insertSpaceAfterKeywordsInControlFlowStatements: config.get('insertSpaceAfterKeywordsInControlFlowStatements'),
11626             insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get('insertSpaceAfterFunctionKeywordForAnonymousFunctions'),
11627             insertSpaceBeforeFunctionParenthesis: config.get('insertSpaceBeforeFunctionParenthesis'),
11628             insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'),
11629             insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'),
11630             insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingEmptyBraces'),
11631             insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'),
11632             insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'),
11633             insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'),
11634             insertSpaceAfterTypeAssertion: config.get('insertSpaceAfterTypeAssertion'),
11635             placeOpenBraceOnNewLineForFunctions: config.get('placeOpenBraceOnNewLineForFunctions'),
11636             placeOpenBraceOnNewLineForControlBlocks: config.get('placeOpenBraceOnNewLineForControlBlocks'),
11637             semicolons: config.get('semicolons', undefined)
11638         };
11639     }
11640     getCompleteOptions(languageId) {
11641         const lang = this.isTypeScriptDocument(languageId) ? 'typescript' : 'javascript';
11642         const config = coc_nvim_1.workspace.getConfiguration(`${lang}.suggest`);
11643         return {
11644             enabled: config.get('enabled', true),
11645             names: config.get('names', true),
11646             paths: config.get('paths', true),
11647             completeFunctionCalls: config.get('completeFunctionCalls', true),
11648             autoImports: config.get('autoImports', true),
11649             includeAutomaticOptionalChainCompletions: config.get('includeAutomaticOptionalChainCompletions', true)
11650         };
11651     }
11652     getPreferences(language, uri) {
11653         if (this.client.apiVersion.lt(api_1.default.v290)) {
11654             return {};
11655         }
11656         const config = coc_nvim_1.workspace.getConfiguration(`${language}.preferences`, uri);
11657         // getImportModuleSpecifierEndingPreference available on ts 2.9.0
11658         const preferences = {
11659             quotePreference: this.getQuoteStyle(config),
11660             importModuleSpecifierPreference: getImportModuleSpecifier(config),
11661             importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
11662             allowTextChangesInNewFiles: uri.startsWith('file:'),
11663             allowRenameOfImportPath: true,
11664             providePrefixAndSuffixTextForRename: config.get('renameShorthandProperties', true) === false ? false : config.get('useAliasesForRenames', true),
11665         };
11666         return preferences;
11667     }
11668     getQuoteStyle(config) {
11669         let quoteStyle = config.get('quoteStyle', 'auto');
11670         if (this.client.apiVersion.gte(api_1.default.v333) || quoteStyle != 'auto')
11671             return quoteStyle;
11672         return 'single';
11673     }
11674     dispose() {
11675         coc_nvim_1.disposeAll(this.disposables);
11676     }
11677 }
11678 exports.default = FileConfigurationManager;
11679 function getImportModuleSpecifier(config) {
11680     let val = config.get('importModuleSpecifier');
11681     switch (val) {
11682         case 'relative':
11683             return 'relative';
11684         case 'non-relative':
11685             return 'non-relative';
11686         default:
11687             return 'auto';
11688     }
11689 }
11690 function getImportModuleSpecifierEndingPreference(config) {
11691     switch (config.get('importModuleSpecifierEnding')) {
11692         case 'minimal': return 'minimal';
11693         case 'index': return 'index';
11694         case 'js': return 'js';
11695         default: return 'auto';
11696     }
11697 }
11698
11699
11700 /***/ }),
11701 /* 114 */
11702 /***/ (function(module, exports, __webpack_require__) {
11703
11704 "use strict";
11705
11706 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11707     if (k2 === undefined) k2 = k;
11708     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
11709 }) : (function(o, m, k, k2) {
11710     if (k2 === undefined) k2 = k;
11711     o[k2] = m[k];
11712 }));
11713 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
11714     Object.defineProperty(o, "default", { enumerable: true, value: v });
11715 }) : function(o, v) {
11716     o["default"] = v;
11717 });
11718 var __importStar = (this && this.__importStar) || function (mod) {
11719     if (mod && mod.__esModule) return mod;
11720     var result = {};
11721     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
11722     __setModuleDefault(result, mod);
11723     return result;
11724 };
11725 var __importDefault = (this && this.__importDefault) || function (mod) {
11726     return (mod && mod.__esModule) ? mod : { "default": mod };
11727 };
11728 Object.defineProperty(exports, "__esModule", { value: true });
11729 const coc_nvim_1 = __webpack_require__(1);
11730 const fs_1 = __importDefault(__webpack_require__(102));
11731 const os_1 = __importDefault(__webpack_require__(14));
11732 const path_1 = __importDefault(__webpack_require__(13));
11733 const vscode_languageserver_protocol_1 = __webpack_require__(3);
11734 const fileSchemes = __importStar(__webpack_require__(115));
11735 const callbackMap_1 = __webpack_require__(116);
11736 const bufferSyncSupport_1 = __importDefault(__webpack_require__(118));
11737 const diagnostics_1 = __webpack_require__(122);
11738 const fileConfigurationManager_1 = __importDefault(__webpack_require__(113));
11739 const requestQueue_1 = __webpack_require__(123);
11740 const typescriptService_1 = __webpack_require__(117);
11741 const api_1 = __importDefault(__webpack_require__(40));
11742 const configuration_1 = __webpack_require__(124);
11743 const logger_1 = __importDefault(__webpack_require__(129));
11744 const process_1 = __webpack_require__(131);
11745 const tracer_1 = __importDefault(__webpack_require__(132));
11746 const tsconfig_1 = __webpack_require__(133);
11747 const versionProvider_1 = __webpack_require__(134);
11748 const versionStatus_1 = __importDefault(__webpack_require__(135));
11749 const wireProtocol_1 = __webpack_require__(136);
11750 class ForkedTsServerProcess {
11751     constructor(childProcess) {
11752         this.childProcess = childProcess;
11753         this.toCancelOnResourceChange = new Set();
11754     }
11755     onError(cb) {
11756         this.childProcess.on('error', cb);
11757     }
11758     onExit(cb) {
11759         this.childProcess.on('exit', cb);
11760     }
11761     write(serverRequest) {
11762         this.childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8');
11763     }
11764     createReader(callback, onError) {
11765         // tslint:disable-next-line:no-unused-expression
11766         new wireProtocol_1.Reader(this.childProcess.stdout, callback, onError);
11767     }
11768     kill() {
11769         this.childProcess.kill();
11770     }
11771 }
11772 class TypeScriptServiceClient {
11773     constructor(pluginManager, modeIds) {
11774         this.pluginManager = pluginManager;
11775         this.modeIds = modeIds;
11776         this.state = coc_nvim_1.ServiceStat.Initial;
11777         this.logger = new logger_1.default();
11778         this.tsServerLogFile = null;
11779         this.cancellationPipeName = null;
11780         this._callbacks = new callbackMap_1.CallbackMap();
11781         this._requestQueue = new requestQueue_1.RequestQueue();
11782         this._pendingResponses = new Set();
11783         this._onTsServerStarted = new vscode_languageserver_protocol_1.Emitter();
11784         this._onProjectLanguageServiceStateChanged = new vscode_languageserver_protocol_1.Emitter();
11785         this._onDidBeginInstallTypings = new vscode_languageserver_protocol_1.Emitter();
11786         this._onDidEndInstallTypings = new vscode_languageserver_protocol_1.Emitter();
11787         this._onTypesInstallerInitializationFailed = new vscode_languageserver_protocol_1.Emitter();
11788         this.disposables = [];
11789         this.isRestarting = false;
11790         this._onDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
11791         this._onConfigDiagnosticsReceived = new vscode_languageserver_protocol_1.Emitter();
11792         this._onResendModelsRequested = new vscode_languageserver_protocol_1.Emitter();
11793         this.pathSeparator = path_1.default.sep;
11794         this.lastStart = Date.now();
11795         this.servicePromise = null;
11796         this.lastError = null;
11797         this.numberRestarts = 0;
11798         this.fileConfigurationManager = new fileConfigurationManager_1.default(this);
11799         this._configuration = configuration_1.TypeScriptServiceConfiguration.loadFromWorkspace();
11800         this.versionProvider = new versionProvider_1.TypeScriptVersionProvider(this._configuration);
11801         this._apiVersion = api_1.default.defaultVersion;
11802         this.tracer = new tracer_1.default(this.logger);
11803         this.versionStatus = new versionStatus_1.default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
11804         pluginManager.onDidUpdateConfig(update => {
11805             this.configurePlugin(update.pluginId, update.config);
11806         }, null, this.disposables);
11807         pluginManager.onDidChangePlugins(() => {
11808             this.restartTsServer();
11809         }, null, this.disposables);
11810         this.bufferSyncSupport = new bufferSyncSupport_1.default(this, modeIds);
11811         this.onTsServerStarted(() => {
11812             this.bufferSyncSupport.listen();
11813         });
11814         this.diagnosticsManager = new diagnostics_1.DiagnosticsManager();
11815         this.bufferSyncSupport.onDelete(resource => {
11816             this.cancelInflightRequestsForResource(resource);
11817             this.diagnosticsManager.delete(resource);
11818         }, null, this.disposables);
11819         this.bufferSyncSupport.onWillChange(resource => {
11820             this.cancelInflightRequestsForResource(resource);
11821         });
11822     }
11823     get onDiagnosticsReceived() {
11824         return this._onDiagnosticsReceived.event;
11825     }
11826     get onConfigDiagnosticsReceived() {
11827         return this._onConfigDiagnosticsReceived.event;
11828     }
11829     get onResendModelsRequested() {
11830         return this._onResendModelsRequested.event;
11831     }
11832     get configuration() {
11833         return this._configuration;
11834     }
11835     dispose() {
11836         if (this.servicePromise) {
11837             this.servicePromise
11838                 .then(childProcess => {
11839                 childProcess.kill();
11840             })
11841                 .then(undefined, () => void 0);
11842         }
11843         this.bufferSyncSupport.dispose();
11844         this.logger.dispose();
11845         this._onTsServerStarted.dispose();
11846         this._onResendModelsRequested.dispose();
11847         this.versionStatus.dispose();
11848     }
11849     info(message, data) {
11850         this.logger.info(message, data);
11851     }
11852     error(message, data) {
11853         this.logger.error(message, data);
11854     }
11855     restartTsServer() {
11856         const start = () => {
11857             this.servicePromise = this.startService(true);
11858             return this.servicePromise;
11859         };
11860         if (this.servicePromise) {
11861             return Promise.resolve(this.servicePromise.then(childProcess => {
11862                 this.state = coc_nvim_1.ServiceStat.Stopping;
11863                 this.info('Killing TS Server');
11864                 this.isRestarting = true;
11865                 childProcess.kill();
11866                 this.servicePromise = null;
11867             }).then(start));
11868         }
11869         else {
11870             return Promise.resolve(start());
11871         }
11872     }
11873     stop() {
11874         if (!this.servicePromise)
11875             return;
11876         return new Promise((resolve, reject) => {
11877             this.servicePromise.then(childProcess => {
11878                 if (this.state == coc_nvim_1.ServiceStat.Running) {
11879                     this.info('Killing TS Server');
11880                     childProcess.onExit(() => {
11881                         resolve();
11882                     });
11883                     childProcess.kill();
11884                     this.servicePromise = null;
11885                 }
11886                 else {
11887                     resolve();
11888                 }
11889             }, reject);
11890         });
11891     }
11892     get onTsServerStarted() {
11893         return this._onTsServerStarted.event;
11894     }
11895     get onProjectLanguageServiceStateChanged() {
11896         return this._onProjectLanguageServiceStateChanged.event;
11897     }
11898     get onDidBeginInstallTypings() {
11899         return this._onDidBeginInstallTypings.event;
11900     }
11901     get onDidEndInstallTypings() {
11902         return this._onDidEndInstallTypings.event;
11903     }
11904     get onTypesInstallerInitializationFailed() {
11905         return this._onTypesInstallerInitializationFailed.event;
11906     }
11907     get apiVersion() {
11908         return this._apiVersion;
11909     }
11910     get tscPath() {
11911         return this._tscPath;
11912     }
11913     service() {
11914         if (this.servicePromise) {
11915             return this.servicePromise;
11916         }
11917         if (this.lastError) {
11918             return Promise.reject(this.lastError);
11919         }
11920         return this.startService().then(() => {
11921             if (this.servicePromise) {
11922                 return this.servicePromise;
11923             }
11924         });
11925     }
11926     ensureServiceStarted() {
11927         if (!this.servicePromise) {
11928             this.startService().catch(err => {
11929                 coc_nvim_1.workspace.showMessage(`TSServer start failed: ${err.message}`, 'error');
11930                 this.error(`Service start failed: ${err.stack}`);
11931             });
11932         }
11933     }
11934     async startService(resendModels = false) {
11935         const { ignoreLocalTsserver } = this.configuration;
11936         let currentVersion;
11937         if (!ignoreLocalTsserver)
11938             currentVersion = this.versionProvider.getLocalVersion();
11939         if (!currentVersion || !fs_1.default.existsSync(currentVersion.tsServerPath)) {
11940             currentVersion = this.versionProvider.getDefaultVersion();
11941         }
11942         if (!currentVersion || !currentVersion.isValid) {
11943             if (this.configuration.globalTsdk) {
11944                 coc_nvim_1.workspace.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error');
11945             }
11946             else {
11947                 coc_nvim_1.workspace.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error');
11948             }
11949             return;
11950         }
11951         this._apiVersion = currentVersion.version;
11952         this._tscPath = currentVersion.tscPath;
11953         this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
11954         this.lastError = null;
11955         const tsServerForkArgs = await this.getTsServerArgs(currentVersion);
11956         const debugPort = this._configuration.debugPort;
11957         const maxTsServerMemory = this._configuration.maxTsServerMemory;
11958         const options = {
11959             execArgv: [
11960                 ...(debugPort ? [`--inspect=${debugPort}`] : []),
11961                 ...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
11962             ],
11963             cwd: coc_nvim_1.workspace.root
11964         };
11965         this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
11966         return this.servicePromise;
11967     }
11968     startProcess(currentVersion, args, options, resendModels) {
11969         this.state = coc_nvim_1.ServiceStat.Starting;
11970         return new Promise((resolve, reject) => {
11971             try {
11972                 process_1.fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
11973                     if (err || !childProcess) {
11974                         this.state = coc_nvim_1.ServiceStat.StartFailed;
11975                         this.lastError = err;
11976                         this.error('Starting TSServer failed with error.', err.stack);
11977                         return;
11978                     }
11979                     this.state = coc_nvim_1.ServiceStat.Running;
11980                     this.info('Started TSServer', JSON.stringify(currentVersion, null, 2));
11981                     const handle = new ForkedTsServerProcess(childProcess);
11982                     this.tsServerProcess = handle;
11983                     this.lastStart = Date.now();
11984                     handle.onError((err) => {
11985                         this.lastError = err;
11986                         this.error('TSServer errored with error.', err);
11987                         this.error(`TSServer log file: ${this.tsServerLogFile || ''}`);
11988                         coc_nvim_1.workspace.showMessage(`TSServer errored with error. ${err.message}`, 'error');
11989                         this.serviceExited(false);
11990                     });
11991                     handle.onExit((code) => {
11992                         if (code == null) {
11993                             this.info('TSServer normal exit');
11994                         }
11995                         else {
11996                             this.error(`TSServer exited with code: ${code}`);
11997                         }
11998                         this.info(`TSServer log file: ${this.tsServerLogFile || ''}`);
11999                         this.serviceExited(!this.isRestarting);
12000                         this.isRestarting = false;
12001                     });
12002                     handle.createReader(msg => {
12003                         this.dispatchMessage(msg);
12004                     }, error => {
12005                         this.error('ReaderError', error);
12006                     });
12007                     resolve(handle);
12008                     this.serviceStarted(resendModels);
12009                     this._onTsServerStarted.fire(currentVersion.version);
12010                 });
12011             }
12012             catch (e) {
12013                 reject(e);
12014             }
12015         });
12016     }
12017     async openTsServerLogFile() {
12018         const isRoot = process.getuid && process.getuid() == 0;
12019         let echoErr = (msg) => {
12020             coc_nvim_1.workspace.showMessage(msg, 'error');
12021         };
12022         if (isRoot) {
12023             echoErr('Log disabled for root user.');
12024             return false;
12025         }
12026         if (!this.apiVersion.gte(api_1.default.v222)) {
12027             echoErr('TS Server logging requires TS 2.2.2+');
12028             return false;
12029         }
12030         if (this._configuration.tsServerLogLevel === configuration_1.TsServerLogLevel.Off) {
12031             echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
12032             return false;
12033         }
12034         if (!this.tsServerLogFile) {
12035             echoErr('TS Server has not started logging.');
12036             return false;
12037         }
12038         try {
12039             await coc_nvim_1.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
12040             return true;
12041         }
12042         catch (_a) {
12043             echoErr('Could not open TS Server log file');
12044             return false;
12045         }
12046     }
12047     serviceStarted(resendModels) {
12048         this.bufferSyncSupport.reset();
12049         const watchOptions = this.apiVersion.gte(api_1.default.v380)
12050             ? this.configuration.watchOptions
12051             : undefined;
12052         const configureOptions = {
12053             hostInfo: 'coc-nvim',
12054             preferences: {
12055                 providePrefixAndSuffixTextForRename: true,
12056                 allowRenameOfImportPath: true,
12057             },
12058             watchOptions
12059         };
12060         this.executeWithoutWaitingForResponse('configure', configureOptions); // tslint:disable-line
12061         this.setCompilerOptionsForInferredProjects(this._configuration);
12062         if (resendModels) {
12063             this._onResendModelsRequested.fire(void 0);
12064             this.fileConfigurationManager.reset();
12065             this.diagnosticsManager.reInitialize();
12066             this.bufferSyncSupport.reinitialize();
12067         }
12068         // Reconfigure any plugins
12069         for (const [config, pluginName] of this.pluginManager.configurations()) {
12070             this.configurePlugin(config, pluginName);
12071         }
12072     }
12073     setCompilerOptionsForInferredProjects(configuration) {
12074         if (!this.apiVersion.gte(api_1.default.v206))
12075             return;
12076         const args = {
12077             options: this.getCompilerOptionsForInferredProjects(configuration)
12078         };
12079         this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); // tslint:disable-line
12080     }
12081     getCompilerOptionsForInferredProjects(configuration) {
12082         return Object.assign(Object.assign({}, tsconfig_1.inferredProjectConfig(configuration)), { allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true });
12083     }
12084     serviceExited(restart) {
12085         this.state = coc_nvim_1.ServiceStat.Stopped;
12086         this.servicePromise = null;
12087         this.tsServerLogFile = null;
12088         this._callbacks.destroy('Service died.');
12089         this._callbacks = new callbackMap_1.CallbackMap();
12090         this._requestQueue = new requestQueue_1.RequestQueue();
12091         this._pendingResponses = new Set();
12092         if (restart) {
12093             const diff = Date.now() - this.lastStart;
12094             this.numberRestarts++;
12095             let startService = true;
12096             if (this.numberRestarts > 5) {
12097                 this.numberRestarts = 0;
12098                 if (diff < 10 * 1000 /* 10 seconds */) {
12099                     this.lastStart = Date.now();
12100                     startService = false;
12101                     coc_nvim_1.workspace.showMessage('The TypeScript language service died 5 times right after it got started.', 'error'); // tslint:disable-line
12102                 }
12103                 else if (diff < 60 * 1000 /* 1 Minutes */) {
12104                     this.lastStart = Date.now();
12105                     coc_nvim_1.workspace.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error'); // tslint:disable-line
12106                 }
12107             }
12108             if (startService) {
12109                 this.startService(true); // tslint:disable-line
12110             }
12111         }
12112     }
12113     toPath(uri) {
12114         return this.normalizePath(coc_nvim_1.Uri.parse(uri));
12115     }
12116     toOpenedFilePath(uri, options = {}) {
12117         if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
12118             if (!options.suppressAlertOnFailure) {
12119                 console.error(`Unexpected resource ${uri}`);
12120             }
12121             return undefined;
12122         }
12123         return this.toPath(uri);
12124     }
12125     toResource(filepath) {
12126         if (this._apiVersion.gte(api_1.default.v213)) {
12127             if (filepath.startsWith('untitled:')) {
12128                 let resource = coc_nvim_1.Uri.parse(filepath);
12129                 if (this.inMemoryResourcePrefix) {
12130                     const dirName = path_1.default.dirname(resource.path);
12131                     const fileName = path_1.default.basename(resource.path);
12132                     if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12133                         resource = resource.with({ path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) });
12134                     }
12135                 }
12136                 return resource.toString();
12137             }
12138         }
12139         return coc_nvim_1.Uri.file(filepath).toString();
12140     }
12141     normalizePath(resource) {
12142         if (fileSchemes.disabledSchemes.has(resource.scheme)) {
12143             return undefined;
12144         }
12145         switch (resource.scheme) {
12146             case fileSchemes.file: {
12147                 let result = resource.fsPath;
12148                 if (!result)
12149                     return undefined;
12150                 result = path_1.default.normalize(result);
12151                 // Both \ and / must be escaped in regular expressions
12152                 return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/');
12153             }
12154             default: {
12155                 return this.inMemoryResourcePrefix + resource.toString(true);
12156             }
12157         }
12158     }
12159     get inMemoryResourcePrefix() {
12160         return this._apiVersion.gte(api_1.default.v270) ? '^' : '';
12161     }
12162     asUrl(filepath) {
12163         if (this._apiVersion.gte(api_1.default.v213)) {
12164             if (filepath.startsWith('untitled:')) {
12165                 let resource = coc_nvim_1.Uri.parse(filepath);
12166                 if (this.inMemoryResourcePrefix) {
12167                     const dirName = path_1.default.dirname(resource.path);
12168                     const fileName = path_1.default.basename(resource.path);
12169                     if (fileName.startsWith(this.inMemoryResourcePrefix)) {
12170                         resource = resource.with({
12171                             path: path_1.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
12172                         });
12173                     }
12174                 }
12175                 return resource;
12176             }
12177         }
12178         return coc_nvim_1.Uri.file(filepath);
12179     }
12180     execute(command, args, token, config) {
12181         var _a;
12182         let execution;
12183         if (config === null || config === void 0 ? void 0 : config.cancelOnResourceChange) {
12184             const source = new vscode_languageserver_protocol_1.CancellationTokenSource();
12185             token.onCancellationRequested(() => source.cancel());
12186             const inFlight = {
12187                 resource: config.cancelOnResourceChange,
12188                 cancel: () => source.cancel(),
12189             };
12190             (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
12191             execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token: source.token, expectsResult: true }, config)).finally(() => {
12192                 var _a;
12193                 (_a = this.tsServerProcess) === null || _a === void 0 ? void 0 : _a.toCancelOnResourceChange.delete(inFlight);
12194                 source.dispose();
12195             });
12196         }
12197         else {
12198             execution = this.executeImpl(command, args, Object.assign({ isAsync: false, token, expectsResult: true }, config));
12199         }
12200         if (config === null || config === void 0 ? void 0 : config.nonRecoverable) {
12201             execution.catch(err => this.fatalError(command, err));
12202         }
12203         return execution;
12204     }
12205     fatalError(command, error) {
12206         console.error(`A non-recoverable error occured while executing tsserver command: ${command}`);
12207         if (this.state === coc_nvim_1.ServiceStat.Running) {
12208             this.info('Killing TS Server by fatal error:', error);
12209             this.service().then(service => {
12210                 service.kill();
12211             });
12212         }
12213     }
12214     executeAsync(command, args, token) {
12215         return this.executeImpl(command, args, {
12216             isAsync: true,
12217             token,
12218             expectsResult: true
12219         });
12220     }
12221     executeWithoutWaitingForResponse(command, args) {
12222         this.executeImpl(command, args, {
12223             isAsync: false,
12224             token: undefined,
12225             expectsResult: false
12226         });
12227     }
12228     executeImpl(command, args, executeInfo) {
12229         if (this.servicePromise == null) {
12230             return Promise.resolve(undefined);
12231         }
12232         this.bufferSyncSupport.beforeCommand(command);
12233         const request = this._requestQueue.createRequest(command, args);
12234         const requestInfo = {
12235             request,
12236             expectsResponse: executeInfo.expectsResult,
12237             isAsync: executeInfo.isAsync,
12238             queueingType: getQueueingType(command, executeInfo.lowPriority)
12239         };
12240         let result;
12241         if (executeInfo.expectsResult) {
12242             result = new Promise((resolve, reject) => {
12243                 this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync);
12244                 if (executeInfo.token) {
12245                     executeInfo.token.onCancellationRequested(() => {
12246                         this.tryCancelRequest(request.seq, command);
12247                     });
12248                 }
12249             }).catch((err) => {
12250                 throw err;
12251             });
12252         }
12253         this._requestQueue.enqueue(requestInfo);
12254         this.sendNextRequests();
12255         return result;
12256     }
12257     sendNextRequests() {
12258         while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
12259             const item = this._requestQueue.dequeue();
12260             if (item) {
12261                 this.sendRequest(item);
12262             }
12263         }
12264     }
12265     sendRequest(requestItem) {
12266         const serverRequest = requestItem.request;
12267         this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
12268         if (requestItem.expectsResponse && !requestItem.isAsync) {
12269             this._pendingResponses.add(requestItem.request.seq);
12270         }
12271         this.service().then(childProcess => {
12272             try {
12273                 childProcess.write(serverRequest);
12274             }
12275             catch (err) {
12276                 const callback = this.fetchCallback(serverRequest.seq);
12277                 if (callback) {
12278                     callback.onError(err);
12279                 }
12280             }
12281         });
12282     }
12283     tryCancelRequest(seq, command) {
12284         try {
12285             if (this._requestQueue.tryDeletePendingRequest(seq)) {
12286                 this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
12287                 return true;
12288             }
12289             if (this.cancellationPipeName) {
12290                 this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
12291                 try {
12292                     fs_1.default.writeFileSync(this.cancellationPipeName + seq, '');
12293                 }
12294                 catch (_a) {
12295                     // noop
12296                 }
12297                 return true;
12298             }
12299             this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
12300             return false;
12301         }
12302         finally {
12303             const callback = this.fetchCallback(seq);
12304             if (callback) {
12305                 callback.onSuccess(new typescriptService_1.ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
12306             }
12307         }
12308     }
12309     fetchCallback(seq) {
12310         const callback = this._callbacks.fetch(seq);
12311         if (!callback) {
12312             return undefined;
12313         }
12314         this._pendingResponses.delete(seq);
12315         return callback;
12316     }
12317     dispatchMessage(message) {
12318         try {
12319             switch (message.type) {
12320                 case 'response':
12321                     this.dispatchResponse(message);
12322                     break;
12323                 case 'event':
12324                     const event = message;
12325                     if (event.event === 'requestCompleted') {
12326                         const seq = event.body.request_seq;
12327                         const p = this._callbacks.fetch(seq);
12328                         if (p) {
12329                             this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime);
12330                             p.onSuccess(undefined);
12331                         }
12332                     }
12333                     else {
12334                         this.tracer.traceEvent(event);
12335                         this.dispatchEvent(event);
12336                     }
12337                     break;
12338                 default:
12339                     throw new Error(`Unknown message type ${message.type} received`);
12340             }
12341         }
12342         finally {
12343             this.sendNextRequests();
12344         }
12345     }
12346     dispatchResponse(response) {
12347         const callback = this.fetchCallback(response.request_seq);
12348         if (!callback) {
12349             return;
12350         }
12351         this.tracer.traceResponse(response, callback.startTime);
12352         if (response.success) {
12353             callback.onSuccess(response);
12354         }
12355         else if (response.message === 'No content available.') {
12356             // Special case where response itself is successful but there is not any data to return.
12357             callback.onSuccess(typescriptService_1.ServerResponse.NoContent);
12358         }
12359         else {
12360             callback.onError(new Error(response.message));
12361         }
12362     }
12363     dispatchEvent(event) {
12364         switch (event.event) {
12365             case 'syntaxDiag':
12366             case 'semanticDiag':
12367             case 'suggestionDiag':
12368                 const diagnosticEvent = event;
12369                 if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
12370                     this._onDiagnosticsReceived.fire({
12371                         kind: getDiagnosticsKind(event),
12372                         resource: this.asUrl(diagnosticEvent.body.file),
12373                         diagnostics: diagnosticEvent.body.diagnostics
12374                     });
12375                 }
12376                 break;
12377             case 'configFileDiag':
12378                 this._onConfigDiagnosticsReceived.fire(event);
12379                 break;
12380             case 'projectLanguageServiceState':
12381                 if (event.body) {
12382                     this._onProjectLanguageServiceStateChanged.fire(event.body);
12383                 }
12384                 break;
12385             case 'beginInstallTypes':
12386                 if (event.body) {
12387                     this._onDidBeginInstallTypings.fire(event.body);
12388                 }
12389                 break;
12390             case 'endInstallTypes':
12391                 if (event.body) {
12392                     this._onDidEndInstallTypings.fire(event.body);
12393                 }
12394                 break;
12395             case 'projectsUpdatedInBackground':
12396                 const body = event.body;
12397                 const resources = body.openFiles.map(coc_nvim_1.Uri.file);
12398                 this.bufferSyncSupport.getErr(resources);
12399                 break;
12400             case 'typesInstallerInitializationFailed':
12401                 if (event.body) {
12402                     this._onTypesInstallerInitializationFailed.fire(event.body);
12403                 }
12404                 break;
12405             case 'projectLoadingStart':
12406                 this.versionStatus.loading = true;
12407                 break;
12408             case 'projectLoadingFinish':
12409                 this.versionStatus.loading = false;
12410                 break;
12411         }
12412     }
12413     async getTsServerArgs(currentVersion) {
12414         const args = [];
12415         args.push('--allowLocalPluginLoads');
12416         if (this.apiVersion.gte(api_1.default.v250)) {
12417             args.push('--useInferredProjectPerProjectRoot');
12418         }
12419         else {
12420             args.push('--useSingleInferredProject');
12421         }
12422         if (this.apiVersion.gte(api_1.default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
12423             args.push('--disableAutomaticTypingAcquisition');
12424         }
12425         if (this.apiVersion.gte(api_1.default.v222)) {
12426             this.cancellationPipeName = process_1.getTempFile(`tscancellation-${process_1.makeRandomHexString(20)}`);
12427             args.push('--cancellationPipeName', this.cancellationPipeName + '*');
12428         }
12429         if (this.apiVersion.gte(api_1.default.v222)) {
12430             const isRoot = process.getuid && process.getuid() == 0;
12431             if (this._configuration.tsServerLogLevel !== configuration_1.TsServerLogLevel.Off && !isRoot) {
12432                 const logDir = process_1.getTempDirectory();
12433                 if (logDir) {
12434                     this.tsServerLogFile = path_1.default.join(logDir, `tsserver.log`);
12435                     this.info('TSServer log file :', this.tsServerLogFile);
12436                 }
12437                 else {
12438                     this.tsServerLogFile = null;
12439                     this.error('Could not create TSServer log directory');
12440                 }
12441                 if (this.tsServerLogFile) {
12442                     args.push('--logVerbosity', configuration_1.TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
12443                     args.push('--logFile', this.tsServerLogFile);
12444                 }
12445             }
12446         }
12447         if (this.apiVersion.gte(api_1.default.v230)) {
12448             const pluginNames = this.pluginManager.plugins.map(x => x.name);
12449             let pluginPaths = this._configuration.tsServerPluginPaths;
12450             pluginPaths = pluginPaths.reduce((p, c) => {
12451                 if (path_1.default.isAbsolute(c)) {
12452                     p.push(c);
12453                 }
12454                 else {
12455                     let roots = coc_nvim_1.workspace.workspaceFolders.map(o => coc_nvim_1.Uri.parse(o.uri).fsPath);
12456                     p.push(...roots.map(r => path_1.default.join(r, c)));
12457                 }
12458                 return p;
12459             }, []);
12460             if (pluginNames.length) {
12461                 const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path;
12462                 args.push('--globalPlugins', pluginNames.join(','));
12463                 for (const plugin of this.pluginManager.plugins) {
12464                     if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
12465                         pluginPaths.push(plugin.path);
12466                     }
12467                 }
12468             }
12469             if (pluginPaths.length) {
12470                 args.push('--pluginProbeLocations', pluginPaths.join(','));
12471             }
12472         }
12473         if (this._configuration.locale) {
12474             args.push('--locale', this._configuration.locale);
12475         }
12476         if (this._configuration.typingsCacheLocation) {
12477             args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`);
12478         }
12479         if (this.apiVersion.gte(api_1.default.v234)) {
12480             let { npmLocation } = this._configuration;
12481             if (npmLocation) {
12482                 this.logger.info(`using npm from ${npmLocation}`);
12483                 args.push('--npmLocation', `"${npmLocation}"`);
12484             }
12485         }
12486         if (this.apiVersion.gte(api_1.default.v291)) {
12487             args.push('--noGetErrOnBackgroundUpdate');
12488         }
12489         if (this.apiVersion.gte(api_1.default.v345)) {
12490             args.push('--validateDefaultNpmLocation');
12491         }
12492         return args;
12493     }
12494     getProjectRootPath(uri) {
12495         let root = coc_nvim_1.workspace.cwd;
12496         let u = coc_nvim_1.Uri.parse(uri);
12497         if (u.scheme !== 'file')
12498             return undefined;
12499         let folder = coc_nvim_1.workspace.getWorkspaceFolder(uri);
12500         if (folder) {
12501             root = coc_nvim_1.Uri.parse(folder.uri).fsPath;
12502         }
12503         else {
12504             let filepath = coc_nvim_1.Uri.parse(uri).fsPath;
12505             if (!filepath.startsWith(root)) {
12506                 root = path_1.default.dirname(filepath);
12507             }
12508         }
12509         if (root == os_1.default.homedir())
12510             return undefined;
12511         return root;
12512     }
12513     configurePlugin(pluginName, configuration) {
12514         if (this.apiVersion.gte(api_1.default.v314)) {
12515             if (!this.servicePromise)
12516                 return;
12517             this.servicePromise.then(() => {
12518                 // tslint:disable-next-line: no-floating-promises
12519                 this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration });
12520             });
12521         }
12522     }
12523     interruptGetErr(f) {
12524         return this.bufferSyncSupport.interuptGetErr(f);
12525     }
12526     cancelInflightRequestsForResource(resource) {
12527         if (this.state !== coc_nvim_1.ServiceStat.Running || !this.tsServerProcess) {
12528             return;
12529         }
12530         for (const request of this.tsServerProcess.toCancelOnResourceChange) {
12531             if (request.resource.toString() === resource.toString()) {
12532                 request.cancel();
12533             }
12534         }
12535     }
12536 }
12537 exports.default = TypeScriptServiceClient;
12538 function getDiagnosticsKind(event) {
12539     switch (event.event) {
12540         case 'syntaxDiag':
12541             return diagnostics_1.DiagnosticKind.Syntax;
12542         case 'semanticDiag':
12543             return diagnostics_1.DiagnosticKind.Semantic;
12544         case 'suggestionDiag':
12545             return diagnostics_1.DiagnosticKind.Suggestion;
12546     }
12547     throw new Error('Unknown dignostics kind');
12548 }
12549 const fenceCommands = new Set(['change', 'close', 'open']);
12550 function getQueueingType(command, lowPriority) {
12551     if (fenceCommands.has(command)) {
12552         return requestQueue_1.RequestQueueingType.Fence;
12553     }
12554     return lowPriority ? requestQueue_1.RequestQueueingType.LowPriority : requestQueue_1.RequestQueueingType.Normal;
12555 }
12556
12557
12558 /***/ }),
12559 /* 115 */
12560 /***/ (function(module, exports, __webpack_require__) {
12561
12562 "use strict";
12563
12564 /*---------------------------------------------------------------------------------------------
12565  *  Copyright (c) Microsoft Corporation. All rights reserved.
12566  *  Licensed under the MIT License. See License.txt in the project root for license information.
12567  *--------------------------------------------------------------------------------------------*/
12568 Object.defineProperty(exports, "__esModule", { value: true });
12569 exports.disabledSchemes = exports.semanticSupportedSchemes = exports.walkThroughSnippet = exports.vsls = exports.git = exports.untitled = exports.file = void 0;
12570 exports.file = 'file';
12571 exports.untitled = 'untitled';
12572 exports.git = 'git';
12573 /** Live share scheme */
12574 exports.vsls = 'vsls';
12575 exports.walkThroughSnippet = 'walkThroughSnippet';
12576 exports.semanticSupportedSchemes = [
12577     exports.file,
12578     exports.untitled,
12579     exports.walkThroughSnippet,
12580 ];
12581 /**
12582  * File scheme for which JS/TS language feature should be disabled
12583  */
12584 exports.disabledSchemes = new Set([
12585     exports.git,
12586     exports.vsls
12587 ]);
12588
12589
12590 /***/ }),
12591 /* 116 */
12592 /***/ (function(module, exports, __webpack_require__) {
12593
12594 "use strict";
12595
12596 /*---------------------------------------------------------------------------------------------
12597  *  Copyright (c) Microsoft Corporation. All rights reserved.
12598  *  Licensed under the MIT License. See License.txt in the project root for license information.
12599  *--------------------------------------------------------------------------------------------*/
12600 Object.defineProperty(exports, "__esModule", { value: true });
12601 exports.CallbackMap = void 0;
12602 const typescriptService_1 = __webpack_require__(117);
12603 class CallbackMap {
12604     constructor() {
12605         this._callbacks = new Map();
12606         this._asyncCallbacks = new Map();
12607     }
12608     destroy(cause) {
12609         const cancellation = new typescriptService_1.ServerResponse.Cancelled(cause);
12610         for (const callback of this._callbacks.values()) {
12611             callback.onSuccess(cancellation);
12612         }
12613         this._callbacks.clear();
12614         for (const callback of this._asyncCallbacks.values()) {
12615             callback.onSuccess(cancellation);
12616         }
12617         this._asyncCallbacks.clear();
12618     }
12619     add(seq, callback, isAsync) {
12620         if (isAsync) {
12621             this._asyncCallbacks.set(seq, callback);
12622         }
12623         else {
12624             this._callbacks.set(seq, callback);
12625         }
12626     }
12627     fetch(seq) {
12628         const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
12629         this.delete(seq);
12630         return callback;
12631     }
12632     delete(seq) {
12633         if (!this._callbacks.delete(seq)) {
12634             this._asyncCallbacks.delete(seq);
12635         }
12636     }
12637 }
12638 exports.CallbackMap = CallbackMap;
12639
12640
12641 /***/ }),
12642 /* 117 */
12643 /***/ (function(module, exports, __webpack_require__) {
12644
12645 "use strict";
12646
12647 Object.defineProperty(exports, "__esModule", { value: true });
12648 exports.ExectuionTarget = exports.ServerResponse = void 0;
12649 var ServerResponse;
12650 (function (ServerResponse) {
12651     class Cancelled {
12652         constructor(reason) {
12653             this.reason = reason;
12654             this.type = 'cancelled';
12655         }
12656     }
12657     ServerResponse.Cancelled = Cancelled;
12658     // tslint:disable-next-line: new-parens
12659     ServerResponse.NoContent = new class {
12660         constructor() {
12661             this.type = 'noContent';
12662         }
12663     };
12664 })(ServerResponse = exports.ServerResponse || (exports.ServerResponse = {}));
12665 var ExectuionTarget;
12666 (function (ExectuionTarget) {
12667     ExectuionTarget[ExectuionTarget["Semantic"] = 0] = "Semantic";
12668     ExectuionTarget[ExectuionTarget["Syntax"] = 1] = "Syntax";
12669 })(ExectuionTarget = exports.ExectuionTarget || (exports.ExectuionTarget = {}));
12670
12671
12672 /***/ }),
12673 /* 118 */
12674 /***/ (function(module, exports, __webpack_require__) {
12675
12676 "use strict";
12677
12678 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12679     if (k2 === undefined) k2 = k;
12680     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12681 }) : (function(o, m, k, k2) {
12682     if (k2 === undefined) k2 = k;
12683     o[k2] = m[k];
12684 }));
12685 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
12686     Object.defineProperty(o, "default", { enumerable: true, value: v });
12687 }) : function(o, v) {
12688     o["default"] = v;
12689 });
12690 var __importStar = (this && this.__importStar) || function (mod) {
12691     if (mod && mod.__esModule) return mod;
12692     var result = {};
12693     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12694     __setModuleDefault(result, mod);
12695     return result;
12696 };
12697 var __importDefault = (this && this.__importDefault) || function (mod) {
12698     return (mod && mod.__esModule) ? mod : { "default": mod };
12699 };
12700 Object.defineProperty(exports, "__esModule", { value: true });
12701 /*---------------------------------------------------------------------------------------------
12702  *  Copyright (c) Microsoft Corporation. All rights reserved.
12703  *  Licensed under the MIT License. See License.txt in the project root for license information.
12704  *--------------------------------------------------------------------------------------------*/
12705 const coc_nvim_1 = __webpack_require__(1);
12706 const vscode_languageserver_protocol_1 = __webpack_require__(3);
12707 const api_1 = __importDefault(__webpack_require__(40));
12708 const async_1 = __webpack_require__(119);
12709 const typeConverters = __importStar(__webpack_require__(37));
12710 const languageModeIds_1 = __webpack_require__(120);
12711 const resourceMap_1 = __webpack_require__(121);
12712 class CloseOperation {
12713     constructor(args) {
12714         this.args = args;
12715         this.type = 0 /* Close */;
12716     }
12717 }
12718 class OpenOperation {
12719     constructor(args) {
12720         this.args = args;
12721         this.type = 1 /* Open */;
12722     }
12723 }
12724 class ChangeOperation {
12725     constructor(args) {
12726         this.args = args;
12727         this.type = 2 /* Change */;
12728     }
12729 }
12730 class SyncedBuffer {
12731     constructor(document, filepath, client, synchronizer) {
12732         this.document = document;
12733         this.filepath = filepath;
12734         this.client = client;
12735         this.synchronizer = synchronizer;
12736         this.state = 1 /* Initial */;
12737     }
12738     open() {
12739         const args = {
12740             file: this.filepath,
12741             fileContent: this.document.getText(),
12742             projectRootPath: this.client.getProjectRootPath(this.document.uri),
12743         };
12744         const scriptKind = languageModeIds_1.mode2ScriptKind(this.document.languageId);
12745         if (scriptKind) {
12746             args.scriptKindName = scriptKind;
12747         }
12748         if (this.client.apiVersion.gte(api_1.default.v240)) {
12749             // plugin managed.
12750             const tsPluginsForDocument = this.client.pluginManager.plugins
12751                 .filter(x => x.languages.indexOf(this.document.languageId) >= 0);
12752             if (tsPluginsForDocument.length) {
12753                 args.plugins = tsPluginsForDocument.map(plugin => plugin.name);
12754             }
12755         }
12756         this.synchronizer.open(this.resource, args);
12757         this.state = 2 /* Open */;
12758     }
12759     get resource() {
12760         return this.document.uri;
12761     }
12762     get lineCount() {
12763         return this.document.lineCount;
12764     }
12765     get kind() {
12766         if (this.document.languageId.startsWith('javascript')) {
12767             return 2 /* JavaScript */;
12768         }
12769         return 1 /* TypeScript */;
12770     }
12771     /**
12772      * @return Was the buffer open?
12773      */
12774     close() {
12775         if (this.state !== 2 /* Open */) {
12776             this.state = 2 /* Closed */;
12777             return false;
12778         }
12779         this.state = 2 /* Closed */;
12780         return this.synchronizer.close(this.resource, this.filepath);
12781     }
12782     onContentChanged(events) {
12783         if (this.state !== 2 /* Open */) {
12784             console.error(`Unexpected buffer state: ${this.state}`);
12785         }
12786         this.synchronizer.change(this.resource, this.filepath, events);
12787     }
12788 }
12789 class SyncedBufferMap extends resourceMap_1.ResourceMap {
12790     getForPath(filePath) {
12791         return this.get(coc_nvim_1.Uri.file(filePath).toString());
12792     }
12793     get allBuffers() {
12794         return this.values;
12795     }
12796 }
12797 class PendingDiagnostics extends resourceMap_1.ResourceMap {
12798     getOrderedFileSet() {
12799         const orderedResources = Array.from(this.entries)
12800             .sort((a, b) => a.value - b.value)
12801             .map(entry => entry.uri);
12802         const map = new resourceMap_1.ResourceMap(this._normalizePath);
12803         for (const resource of orderedResources) {
12804             map.set(resource, undefined);
12805         }
12806         return map;
12807     }
12808 }
12809 /**
12810  * Manages synchronization of buffers with the TS server.
12811  *
12812  * If supported, batches together file changes. This allows the TS server to more efficiently process changes.
12813  */
12814 class BufferSynchronizer {
12815     constructor(client, pathNormalizer) {
12816         this.client = client;
12817         this._pending = new resourceMap_1.ResourceMap(pathNormalizer);
12818     }
12819     open(resource, args) {
12820         if (this.supportsBatching) {
12821             this.updatePending(resource, new OpenOperation(args));
12822         }
12823         else {
12824             this.client.executeWithoutWaitingForResponse('open', args);
12825         }
12826     }
12827     /**
12828      * @return Was the buffer open?
12829      */
12830     close(resource, filepath) {
12831         if (this.supportsBatching) {
12832             return this.updatePending(resource, new CloseOperation(filepath));
12833         }
12834         else {
12835             const args = { file: filepath };
12836             this.client.executeWithoutWaitingForResponse('close', args);
12837             return true;
12838         }
12839     }
12840     change(resource, filepath, events) {
12841         if (!events.length) {
12842             return;
12843         }
12844         if (this.supportsBatching) {
12845             this.updatePending(resource, new ChangeOperation({
12846                 fileName: filepath,
12847                 textChanges: events.map((change) => ({
12848                     newText: change.text,
12849                     start: typeConverters.Position.toLocation(change.range.start),
12850                     end: typeConverters.Position.toLocation(change.range.end),
12851                 })).reverse(),
12852             }));
12853         }
12854         else {
12855             for (const { range, text } of events) {
12856                 const args = Object.assign({ insertString: text }, typeConverters.Range.toFormattingRequestArgs(filepath, range));
12857                 this.client.executeWithoutWaitingForResponse('change', args);
12858             }
12859         }
12860     }
12861     reset() {
12862         this._pending.clear();
12863     }
12864     beforeCommand(command) {
12865         if (command === 'updateOpen') {
12866             return;
12867         }
12868         this.flush();
12869     }
12870     flush() {
12871         if (!this.supportsBatching) {
12872             // We've already eagerly synchronized
12873             this._pending.clear();
12874             return;
12875         }
12876         if (this._pending.size > 0) {
12877             const closedFiles = [];
12878             const openFiles = [];
12879             const changedFiles = [];
12880             for (const change of this._pending.values) {
12881                 switch (change.type) {
12882                     case 2 /* Change */:
12883                         changedFiles.push(change.args);
12884                         break;
12885                     case 1 /* Open */:
12886                         openFiles.push(change.args);
12887                         break;
12888                     case 0 /* Close */:
12889                         closedFiles.push(change.args);
12890                         break;
12891                 }
12892             }
12893             this.client.execute('updateOpen', { changedFiles, closedFiles, openFiles }, vscode_languageserver_protocol_1.CancellationToken.None, { nonRecoverable: true });
12894             this._pending.clear();
12895         }
12896     }
12897     get supportsBatching() {
12898         return this.client.apiVersion.gte(api_1.default.v340);
12899     }
12900     updatePending(resource, op) {
12901         switch (op.type) {
12902             case 0 /* Close */:
12903                 const existing = this._pending.get(resource);
12904                 switch (existing === null || existing === void 0 ? void 0 : existing.type) {
12905                     case 1 /* Open */:
12906                         this._pending.delete(resource);
12907                         return false; // Open then close. No need to do anything
12908                 }
12909                 break;
12910         }
12911         if (this._pending.has(resource)) {
12912             // we saw this file before, make sure we flush before working with it again
12913             this.flush();
12914         }
12915         this._pending.set(resource, op);
12916         return true;
12917     }
12918 }
12919 class GetErrRequest {
12920     constructor(client, uris, _token, onDone) {
12921         this.uris = uris;
12922         this._token = _token;
12923         this._done = false;
12924         let files = uris.map(uri => client.normalizePath(uri));
12925         const args = {
12926             delay: 0,
12927             files
12928         };
12929         const done = () => {
12930             if (this._done) {
12931                 return;
12932             }
12933             this._done = true;
12934             onDone();
12935         };
12936         client.executeAsync('geterr', args, _token.token).then(done, done);
12937     }
12938     static executeGetErrRequest(client, uris, onDone) {
12939         const token = new vscode_languageserver_protocol_1.CancellationTokenSource();
12940         return new GetErrRequest(client, uris, token, onDone);
12941     }
12942     cancel() {
12943         if (!this._done) {
12944             this._token.cancel();
12945         }
12946         this._token.dispose();
12947     }
12948 }
12949 class BufferSyncSupport {
12950     constructor(client, modeIds) {
12951         this.disposables = [];
12952         this._validateJavaScript = true;
12953         this._validateTypeScript = true;
12954         this.listening = false;
12955         this._onDelete = new vscode_languageserver_protocol_1.Emitter();
12956         this.onDelete = this._onDelete.event;
12957         this._onWillChange = new vscode_languageserver_protocol_1.Emitter();
12958         this.onWillChange = this._onWillChange.event;
12959         this.client = client;
12960         this.modeIds = new Set(modeIds);
12961         this.diagnosticDelayer = new async_1.Delayer(300);
12962         const pathNormalizer = (path) => this.client.toPath(path);
12963         this.syncedBuffers = new SyncedBufferMap(pathNormalizer);
12964         this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer);
12965         this.synchronizer = new BufferSynchronizer(client, pathNormalizer);
12966         this.updateConfiguration();
12967         coc_nvim_1.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
12968     }
12969     listen() {
12970         if (this.listening) {
12971             return;
12972         }
12973         this.listening = true;
12974         coc_nvim_1.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables);
12975         coc_nvim_1.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
12976         coc_nvim_1.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
12977         coc_nvim_1.workspace.textDocuments.forEach(this.openTextDocument, this);
12978     }
12979     handles(resource) {
12980         return this.syncedBuffers.has(resource);
12981     }
12982     dispose() {
12983         this.pendingDiagnostics.clear();
12984         coc_nvim_1.disposeAll(this.disposables);
12985         this._onWillChange.dispose();
12986         this._onDelete.dispose();
12987     }
12988     ensureHasBuffer(resource) {
12989         if (this.syncedBuffers.has(resource)) {
12990             return true;
12991         }
12992         const existingDocument = coc_nvim_1.workspace.textDocuments.find(doc => doc.uri.toString() === resource);
12993         if (existingDocument) {
12994             return this.openTextDocument(existingDocument);
12995         }
12996         return false;
12997     }
12998     toResource(filePath) {
12999         const buffer = this.syncedBuffers.getForPath(filePath);
13000         if (buffer)
13001             return buffer.resource;
13002         return coc_nvim_1.Uri.file(filePath).toString();
13003     }
13004     reset() {
13005         var _a;
13006         (_a = this.pendingGetErr) === null || _a === void 0 ? void 0 : _a.cancel();
13007         this.pendingDiagnostics.clear();
13008         this.synchronizer.reset();
13009     }
13010     reinitialize() {
13011         this.reset();
13012         for (const buffer of this.syncedBuffers.allBuffers) {
13013             buffer.open();
13014         }
13015     }
13016     openTextDocument(document) {
13017         if (!this.modeIds.has(document.languageId)) {
13018             // can't handle
13019             return false;
13020         }
13021         const resource = document.uri;
13022         const filepath = this.client.normalizePath(coc_nvim_1.Uri.parse(resource));
13023         if (!filepath) {
13024             return false;
13025         }
13026         if (this.syncedBuffers.has(resource)) {
13027             return true;
13028         }
13029         const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
13030         this.syncedBuffers.set(resource, syncedBuffer);
13031         syncedBuffer.open();
13032         this.requestDiagnostic(syncedBuffer);
13033         return true;
13034     }
13035     closeResource(resource) {
13036         const syncedBuffer = this.syncedBuffers.get(resource);
13037         if (!syncedBuffer) {
13038             return;
13039         }
13040         this.pendingDiagnostics.delete(resource);
13041         this.syncedBuffers.delete(resource);
13042         const wasBufferOpen = syncedBuffer.close();
13043         this._onDelete.fire(resource);
13044         if (wasBufferOpen) {
13045             this.requestAllDiagnostics();
13046         }
13047     }
13048     onDidCloseTextDocument(document) {
13049         this.closeResource(document.uri);
13050     }
13051     onDidChangeTextDocument(e) {
13052         const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
13053         if (!syncedBuffer) {
13054             return;
13055         }
13056         this._onWillChange.fire(syncedBuffer.resource);
13057         syncedBuffer.onContentChanged(e.contentChanges);
13058         const didTrigger = this.requestDiagnostic(syncedBuffer);
13059         if (!didTrigger && this.pendingGetErr) {
13060             // In this case we always want to re-trigger all diagnostics
13061             this.pendingGetErr.cancel();
13062             this.pendingGetErr = undefined;
13063             this.triggerDiagnostics();
13064         }
13065     }
13066     beforeCommand(command) {
13067         this.synchronizer.beforeCommand(command);
13068     }
13069     interuptGetErr(f) {
13070         if (!this.pendingGetErr) {
13071             return f();
13072         }
13073         this.pendingGetErr.cancel();
13074         this.pendingGetErr = undefined;
13075         const result = f();
13076         this.triggerDiagnostics();
13077         return result;
13078     }
13079     getErr(resources) {
13080         const handledResources = resources.filter(resource => {
13081             let syncedBuffer = this.syncedBuffers.get(resource.toString());
13082             return syncedBuffer && this.shouldValidate(syncedBuffer);
13083         });
13084         if (!handledResources.length) {
13085             return;
13086         }
13087         for (const resource of handledResources) {
13088             this.pendingDiagnostics.set(resource.toString(), Date.now());
13089         }
13090         this.triggerDiagnostics();
13091     }
13092     triggerDiagnostics(delay = 200) {
13093         this.diagnosticDelayer.trigger(() => {
13094             this.sendPendingDiagnostics();
13095         }, delay);
13096     }
13097     requestAllDiagnostics() {
13098         for (const buffer of this.syncedBuffers.allBuffers) {
13099             if (this.shouldValidate(buffer)) {
13100                 this.pendingDiagnostics.set(buffer.resource, Date.now());
13101             }
13102         }
13103         this.triggerDiagnostics();
13104     }
13105     requestDiagnostic(buffer) {
13106         if (!this.shouldValidate(buffer)) {
13107             return false;
13108         }
13109         this.pendingDiagnostics.set(buffer.resource, Date.now());
13110         const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800);
13111         this.triggerDiagnostics(delay);
13112         return true;
13113     }
13114     hasPendingDiagnostics(uri) {
13115         return this.pendingDiagnostics.has(uri);
13116     }
13117     sendPendingDiagnostics() {
13118         const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet();
13119         if (this.pendingGetErr) {
13120             this.pendingGetErr.cancel();
13121             for (const uri of this.pendingGetErr.uris) {
13122                 let resource = uri.toString();
13123                 let syncedBuffer = this.syncedBuffers.get(resource);
13124                 if (syncedBuffer && this.shouldValidate(syncedBuffer)) {
13125                     orderedFileSet.set(resource, undefined);
13126                 }
13127                 else {
13128                     orderedFileSet.delete(resource);
13129                 }
13130             }
13131             this.pendingGetErr = undefined;
13132         }
13133         // Add all open TS buffers to the geterr request. They might be visible
13134         for (const buffer of this.syncedBuffers.values) {
13135             if (this.shouldValidate(buffer)) {
13136                 orderedFileSet.set(buffer.resource, undefined);
13137             }
13138         }
13139         if (orderedFileSet.size) {
13140             let uris = Array.from(orderedFileSet.uris).map(uri => coc_nvim_1.Uri.parse(uri));
13141             const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => {
13142                 if (this.pendingGetErr === getErr) {
13143                     this.pendingGetErr = undefined;
13144                 }
13145             });
13146         }
13147         this.pendingDiagnostics.clear();
13148     }
13149     updateConfiguration() {
13150         const jsConfig = coc_nvim_1.workspace.getConfiguration('javascript', null);
13151         const tsConfig = coc_nvim_1.workspace.getConfiguration('typescript', null);
13152         this._validateJavaScript = jsConfig.get('validate.enable', true);
13153         this._validateTypeScript = tsConfig.get('validate.enable', true);
13154     }
13155     shouldValidate(buffer) {
13156         switch (buffer.kind) {
13157             case 2 /* JavaScript */:
13158                 return this._validateJavaScript;
13159             case 1 /* TypeScript */:
13160             default:
13161                 return this._validateTypeScript;
13162         }
13163     }
13164 }
13165 exports.default = BufferSyncSupport;
13166
13167
13168 /***/ }),
13169 /* 119 */
13170 /***/ (function(module, exports, __webpack_require__) {
13171
13172 "use strict";
13173
13174 Object.defineProperty(exports, "__esModule", { value: true });
13175 exports.Delayer = void 0;
13176 class Delayer {
13177     constructor(defaultDelay) {
13178         this.defaultDelay = defaultDelay;
13179         this.timeout = null;
13180         this.completionPromise = null;
13181         this.onSuccess = null;
13182         this.task = null;
13183     }
13184     trigger(task, delay = this.defaultDelay) {
13185         this.task = task;
13186         if (delay >= 0) {
13187             this.cancelTimeout();
13188         }
13189         if (!this.completionPromise) {
13190             this.completionPromise = new Promise(resolve => {
13191                 this.onSuccess = resolve;
13192             }).then(() => {
13193                 this.completionPromise = null;
13194                 this.onSuccess = null;
13195                 let result = this.task && this.task();
13196                 this.task = null;
13197                 return result;
13198             });
13199         }
13200         if (delay >= 0 || this.timeout === null) {
13201             this.timeout = setTimeout(() => {
13202                 this.timeout = null;
13203                 if (this.onSuccess) {
13204                     this.onSuccess(undefined);
13205                 }
13206             }, delay >= 0 ? delay : this.defaultDelay);
13207         }
13208         return this.completionPromise;
13209     }
13210     cancelTimeout() {
13211         if (this.timeout !== null) {
13212             clearTimeout(this.timeout);
13213             this.timeout = null;
13214         }
13215     }
13216 }
13217 exports.Delayer = Delayer;
13218
13219
13220 /***/ }),
13221 /* 120 */
13222 /***/ (function(module, exports, __webpack_require__) {
13223
13224 "use strict";
13225
13226 /*---------------------------------------------------------------------------------------------
13227  *  Copyright (c) Microsoft Corporation. All rights reserved.
13228  *  Licensed under the MIT License. See License.txt in the project root for license information.
13229  *--------------------------------------------------------------------------------------------*/
13230 Object.defineProperty(exports, "__esModule", { value: true });
13231 exports.mode2ScriptKind = exports.languageIds = exports.jsxTags = exports.javascriptjsx = exports.javascriptreact = exports.javascript = exports.typescriptjsx = exports.typescripttsx = exports.typescriptreact = exports.typescript = void 0;
13232 exports.typescript = 'typescript';
13233 exports.typescriptreact = 'typescriptreact';
13234 exports.typescripttsx = 'typescript.tsx';
13235 exports.typescriptjsx = 'typescript.jsx';
13236 exports.javascript = 'javascript';
13237 exports.javascriptreact = 'javascriptreact';
13238 exports.javascriptjsx = 'javascript.jsx';
13239 exports.jsxTags = 'jsx-tags';
13240 exports.languageIds = [exports.typescript, exports.typescriptreact, exports.javascript, exports.javascriptreact, exports.javascriptjsx, exports.typescripttsx, exports.jsxTags];
13241 function mode2ScriptKind(mode) {
13242     switch (mode) {
13243         case exports.typescript:
13244             return 'TS';
13245         case exports.typescripttsx:
13246             return 'TSX';
13247         case exports.typescriptjsx:
13248             return 'TSX';
13249         case exports.typescriptreact:
13250             return 'TSX';
13251         case exports.javascript:
13252             return 'JS';
13253         case exports.javascriptreact:
13254             return 'JSX';
13255     }
13256     return undefined;
13257 }
13258 exports.mode2ScriptKind = mode2ScriptKind;
13259
13260
13261 /***/ }),
13262 /* 121 */
13263 /***/ (function(module, exports, __webpack_require__) {
13264
13265 "use strict";
13266
13267 Object.defineProperty(exports, "__esModule", { value: true });
13268 exports.isWindowsPath = exports.ResourceMap = void 0;
13269 /*---------------------------------------------------------------------------------------------
13270  *  Copyright (c) Microsoft Corporation. All rights reserved.
13271  *  Licensed under the MIT License. See License.txt in the project root for license information.
13272  *--------------------------------------------------------------------------------------------*/
13273 const coc_nvim_1 = __webpack_require__(1);
13274 function defaultPathNormalizer(resource) {
13275     let u = coc_nvim_1.Uri.parse(resource);
13276     if (u.scheme === 'file') {
13277         return u.fsPath;
13278     }
13279     return resource.toString();
13280 }
13281 /**
13282  * Maps of file uris
13283  *
13284  * Attempts to handle correct mapping on both case sensitive and case in-sensitive
13285  * file systems.
13286  */
13287 class ResourceMap {
13288     constructor(_normalizePath = defaultPathNormalizer) {
13289         this._normalizePath = _normalizePath;
13290         this._map = new Map();
13291     }
13292     get size() {
13293         return this._map.size;
13294     }
13295     get entries() {
13296         return this._map.values();
13297     }
13298     has(uri) {
13299         const file = this.toKey(uri);
13300         return !!file && this._map.has(file);
13301     }
13302     get(uri) {
13303         const file = this.toKey(uri);
13304         if (!file)
13305             return undefined;
13306         let entry = this._map.get(file);
13307         return entry ? entry.value : undefined;
13308     }
13309     set(uri, value) {
13310         const file = this.toKey(uri);
13311         if (file) {
13312             this._map.set(file, { uri, value });
13313         }
13314     }
13315     delete(uri) {
13316         const file = this.toKey(uri);
13317         if (file) {
13318             this._map.delete(file);
13319         }
13320     }
13321     get values() {
13322         return Array.from(this._map.values()).map(x => x.value);
13323     }
13324     get uris() {
13325         return Array.from(this._map.values()).map(x => x.uri);
13326     }
13327     clear() {
13328         this._map.clear();
13329     }
13330     toKey(uri) {
13331         const key = this._normalizePath
13332             ? this._normalizePath(uri)
13333             : uri;
13334         if (!key) {
13335             return key;
13336         }
13337         return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
13338     }
13339     isCaseInsensitivePath(path) {
13340         if (isWindowsPath(path)) {
13341             return true;
13342         }
13343         return path[0] === '/' && this.onIsCaseInsenitiveFileSystem;
13344     }
13345     get onIsCaseInsenitiveFileSystem() {
13346         if (process.platform === 'win32') {
13347             return true;
13348         }
13349         if (process.platform === 'darwin') {
13350             return true;
13351         }
13352         return false;
13353     }
13354 }
13355 exports.ResourceMap = ResourceMap;
13356 function isWindowsPath(path) {
13357     return /^[a-zA-Z]:\\/.test(path);
13358 }
13359 exports.isWindowsPath = isWindowsPath;
13360
13361
13362 /***/ }),
13363 /* 122 */
13364 /***/ (function(module, exports, __webpack_require__) {
13365
13366 "use strict";
13367
13368 Object.defineProperty(exports, "__esModule", { value: true });
13369 exports.DiagnosticsManager = exports.DiagnosticKind = exports.DiagnosticSet = void 0;
13370 const coc_nvim_1 = __webpack_require__(1);
13371 const resourceMap_1 = __webpack_require__(121);
13372 class DiagnosticSet {
13373     constructor() {
13374         this._map = new resourceMap_1.ResourceMap();
13375     }
13376     set(uri, diagnostics) {
13377         this._map.set(uri, diagnostics);
13378     }
13379     get(uri) {
13380         return this._map.get(uri) || [];
13381     }
13382     clear() {
13383         this._map = new resourceMap_1.ResourceMap();
13384     }
13385 }
13386 exports.DiagnosticSet = DiagnosticSet;
13387 var DiagnosticKind;
13388 (function (DiagnosticKind) {
13389     DiagnosticKind[DiagnosticKind["Syntax"] = 0] = "Syntax";
13390     DiagnosticKind[DiagnosticKind["Semantic"] = 1] = "Semantic";
13391     DiagnosticKind[DiagnosticKind["Suggestion"] = 2] = "Suggestion";
13392 })(DiagnosticKind = exports.DiagnosticKind || (exports.DiagnosticKind = {}));
13393 const allDiagnosticKinds = [
13394     DiagnosticKind.Syntax,
13395     DiagnosticKind.Semantic,
13396     DiagnosticKind.Suggestion
13397 ];
13398 class DiagnosticsManager {
13399     constructor() {
13400         this._diagnostics = new Map();
13401         this._pendingUpdates = new resourceMap_1.ResourceMap();
13402         this._enableJavascriptSuggestions = true;
13403         this._enableTypescriptSuggestions = true;
13404         this.updateDelay = 200;
13405         for (const kind of allDiagnosticKinds) {
13406             this._diagnostics.set(kind, new DiagnosticSet());
13407         }
13408         this._currentDiagnostics = coc_nvim_1.languages.createDiagnosticCollection('tsserver');
13409     }
13410     dispose() {
13411         this._currentDiagnostics.dispose();
13412         for (const value of this._pendingUpdates.values) {
13413             clearTimeout(value);
13414         }
13415         this._pendingUpdates = new resourceMap_1.ResourceMap();
13416     }
13417     reInitialize() {
13418         this._currentDiagnostics.clear();
13419         for (const diagnosticSet of this._diagnostics.values()) {
13420             diagnosticSet.clear();
13421         }
13422     }
13423     setEnableSuggestions(languageId, value) {
13424         let curr = languageId == 'javascript' ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
13425         if (curr == value) {
13426             return;
13427         }
13428         if (languageId == 'javascript') {
13429             this._enableJavascriptSuggestions = value;
13430         }
13431         else {
13432             this._enableTypescriptSuggestions = value;
13433         }
13434     }
13435     diagnosticsReceived(kind, uri, diagnostics) {
13436         const collection = this._diagnostics.get(kind);
13437         if (!collection)
13438             return;
13439         let doc = coc_nvim_1.workspace.getDocument(uri);
13440         if (doc)
13441             uri = doc.uri;
13442         if (diagnostics.length === 0) {
13443             const existing = collection.get(uri);
13444             if (existing.length === 0) {
13445                 // No need to update
13446                 return;
13447             }
13448         }
13449         collection.set(uri, diagnostics);
13450         this.scheduleDiagnosticsUpdate(uri);
13451     }
13452     configFileDiagnosticsReceived(uri, diagnostics) {
13453         this._currentDiagnostics.set(uri, diagnostics);
13454     }
13455     delete(uri) {
13456         this._currentDiagnostics.delete(uri);
13457     }
13458     getDiagnostics(uri) {
13459         return this._currentDiagnostics.get(uri) || [];
13460         return [];
13461     }
13462     scheduleDiagnosticsUpdate(uri) {
13463         if (!this._pendingUpdates.has(uri)) {
13464             this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
13465         }
13466     }
13467     updateCurrentDiagnostics(uri) {
13468         if (this._pendingUpdates.has(uri)) {
13469             clearTimeout(this._pendingUpdates.get(uri));
13470             this._pendingUpdates.delete(uri);
13471         }
13472         const allDiagnostics = [
13473             ...this._diagnostics.get(DiagnosticKind.Syntax).get(uri),
13474             ...this._diagnostics.get(DiagnosticKind.Semantic).get(uri),
13475             ...this.getSuggestionDiagnostics(uri)
13476         ];
13477         this._currentDiagnostics.set(uri, allDiagnostics);
13478     }
13479     getSuggestionDiagnostics(uri) {
13480         const enabled = this.suggestionsEnabled(uri);
13481         return this._diagnostics
13482             .get(DiagnosticKind.Suggestion)
13483             .get(uri)
13484             .filter(x => {
13485             if (!enabled) {
13486                 // Still show unused
13487                 return x.code == 6133;
13488             }
13489             return enabled;
13490         });
13491     }
13492     suggestionsEnabled(uri) {
13493         let doc = coc_nvim_1.workspace.getDocument(uri);
13494         if (!doc)
13495             return false;
13496         if (doc.filetype.startsWith('javascript')) {
13497             return this._enableJavascriptSuggestions;
13498         }
13499         if (doc.filetype.startsWith('typescript')) {
13500             return this._enableTypescriptSuggestions;
13501         }
13502         return true;
13503     }
13504 }
13505 exports.DiagnosticsManager = DiagnosticsManager;
13506
13507
13508 /***/ }),
13509 /* 123 */
13510 /***/ (function(module, exports, __webpack_require__) {
13511
13512 "use strict";
13513
13514 /*---------------------------------------------------------------------------------------------
13515  *  Copyright (c) Microsoft Corporation. All rights reserved.
13516  *  Licensed under the MIT License. See License.txt in the project root for license information.
13517  *--------------------------------------------------------------------------------------------*/
13518 Object.defineProperty(exports, "__esModule", { value: true });
13519 exports.RequestQueue = exports.RequestQueueingType = void 0;
13520 var RequestQueueingType;
13521 (function (RequestQueueingType) {
13522     /**
13523      * Normal request that is executed in order.
13524      */
13525     RequestQueueingType[RequestQueueingType["Normal"] = 1] = "Normal";
13526     /**
13527      * Request that normal requests jump in front of in the queue.
13528      */
13529     RequestQueueingType[RequestQueueingType["LowPriority"] = 2] = "LowPriority";
13530     /**
13531      * A fence that blocks request reordering.
13532      *
13533      * Fences are not reordered. Unlike a normal request, a fence will never jump in front of a low priority request
13534      * in the request queue.
13535      */
13536     RequestQueueingType[RequestQueueingType["Fence"] = 3] = "Fence";
13537 })(RequestQueueingType = exports.RequestQueueingType || (exports.RequestQueueingType = {}));
13538 class RequestQueue {
13539     constructor() {
13540         this.queue = [];
13541         this.sequenceNumber = 0;
13542     }
13543     get length() {
13544         return this.queue.length;
13545     }
13546     enqueue(item) {
13547         if (item.queueingType === RequestQueueingType.Normal) {
13548             let index = this.queue.length - 1;
13549             while (index >= 0) {
13550                 if (this.queue[index].queueingType !== RequestQueueingType.LowPriority) {
13551                     break;
13552                 }
13553                 --index;
13554             }
13555             this.queue.splice(index + 1, 0, item);
13556         }
13557         else {
13558             // Only normal priority requests can be reordered. All other requests just go to the end.
13559             this.queue.push(item);
13560         }
13561     }
13562     dequeue() {
13563         return this.queue.shift();
13564     }
13565     tryDeletePendingRequest(seq) {
13566         for (let i = 0; i < this.queue.length; i++) {
13567             if (this.queue[i].request.seq === seq) {
13568                 this.queue.splice(i, 1);
13569                 return true;
13570             }
13571         }
13572         return false;
13573     }
13574     createRequest(command, args) {
13575         return {
13576             seq: this.sequenceNumber++,
13577             type: 'request',
13578             command,
13579             arguments: args
13580         };
13581     }
13582 }
13583 exports.RequestQueue = RequestQueue;
13584
13585
13586 /***/ }),
13587 /* 124 */
13588 /***/ (function(module, exports, __webpack_require__) {
13589
13590 "use strict";
13591
13592 var __importDefault = (this && this.__importDefault) || function (mod) {
13593     return (mod && mod.__esModule) ? mod : { "default": mod };
13594 };
13595 Object.defineProperty(exports, "__esModule", { value: true });
13596 exports.TypeScriptServiceConfiguration = exports.TsServerLogLevel = void 0;
13597 const coc_nvim_1 = __webpack_require__(1);
13598 const which_1 = __importDefault(__webpack_require__(125));
13599 var TsServerLogLevel;
13600 (function (TsServerLogLevel) {
13601     TsServerLogLevel[TsServerLogLevel["Off"] = 0] = "Off";
13602     TsServerLogLevel[TsServerLogLevel["Normal"] = 1] = "Normal";
13603     TsServerLogLevel[TsServerLogLevel["Terse"] = 2] = "Terse";
13604     TsServerLogLevel[TsServerLogLevel["Verbose"] = 3] = "Verbose";
13605 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13606 (function (TsServerLogLevel) {
13607     function fromString(value) {
13608         switch (value && value.toLowerCase()) {
13609             case 'normal':
13610                 return TsServerLogLevel.Normal;
13611             case 'terse':
13612                 return TsServerLogLevel.Terse;
13613             case 'verbose':
13614                 return TsServerLogLevel.Verbose;
13615             case 'off':
13616             default:
13617                 return TsServerLogLevel.Off;
13618         }
13619     }
13620     TsServerLogLevel.fromString = fromString;
13621     function toString(value) {
13622         switch (value) {
13623             case TsServerLogLevel.Normal:
13624                 return 'normal';
13625             case TsServerLogLevel.Terse:
13626                 return 'terse';
13627             case TsServerLogLevel.Verbose:
13628                 return 'verbose';
13629             case TsServerLogLevel.Off:
13630             default:
13631                 return 'off';
13632         }
13633     }
13634     TsServerLogLevel.toString = toString;
13635 })(TsServerLogLevel = exports.TsServerLogLevel || (exports.TsServerLogLevel = {}));
13636 class TypeScriptServiceConfiguration {
13637     constructor() {
13638         this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13639         coc_nvim_1.workspace.onDidChangeConfiguration(() => {
13640             this._configuration = coc_nvim_1.workspace.getConfiguration('tsserver');
13641         });
13642     }
13643     get locale() {
13644         return this._configuration.get('locale', null);
13645     }
13646     get globalTsdk() {
13647         return this._configuration.get('tsdk', null);
13648     }
13649     get ignoreLocalTsserver() {
13650         return this._configuration.get('ignoreLocalTsserver', false);
13651     }
13652     get tsServerLogLevel() {
13653         return TsServerLogLevel.fromString(this._configuration.get('log', null));
13654     }
13655     // public readonly watchOptions: protocol.WatchOptions | undefined;
13656     get watchOptions() {
13657         return this._configuration.get('watchOptions');
13658     }
13659     get typingsCacheLocation() {
13660         return this._configuration.get('typingsCacheLocation', '');
13661     }
13662     get tsServerPluginPaths() {
13663         return this._configuration.get('pluginPaths', []);
13664     }
13665     get checkJs() {
13666         return this._configuration.get('implicitProjectConfig.checkJs', false);
13667     }
13668     get experimentalDecorators() {
13669         return this._configuration.get('implicitProjectConfig.experimentalDecorators', false);
13670     }
13671     get disableAutomaticTypeAcquisition() {
13672         return this._configuration.get('disableAutomaticTypeAcquisition', false);
13673     }
13674     get formatOnType() {
13675         return this._configuration.get('formatOnType', false);
13676     }
13677     get maxTsServerMemory() {
13678         return this._configuration.get('maxTsServerMemory', 0);
13679     }
13680     get debugPort() {
13681         return this._configuration.get('debugPort', parseInt(process.env['TSS_DEBUG'], 10));
13682     }
13683     get npmLocation() {
13684         let path = this._configuration.get('npm', '');
13685         if (path)
13686             return coc_nvim_1.workspace.expand(path);
13687         try {
13688             path = which_1.default.sync('npm');
13689         }
13690         catch (e) {
13691             return null;
13692         }
13693         return path;
13694     }
13695     static loadFromWorkspace() {
13696         return new TypeScriptServiceConfiguration();
13697     }
13698 }
13699 exports.TypeScriptServiceConfiguration = TypeScriptServiceConfiguration;
13700
13701
13702 /***/ }),
13703 /* 125 */
13704 /***/ (function(module, exports, __webpack_require__) {
13705
13706 const isWindows = process.platform === 'win32' ||
13707     process.env.OSTYPE === 'cygwin' ||
13708     process.env.OSTYPE === 'msys'
13709
13710 const path = __webpack_require__(13)
13711 const COLON = isWindows ? ';' : ':'
13712 const isexe = __webpack_require__(126)
13713
13714 const getNotFoundError = (cmd) =>
13715   Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
13716
13717 const getPathInfo = (cmd, opt) => {
13718   const colon = opt.colon || COLON
13719
13720   // If it has a slash, then we don't bother searching the pathenv.
13721   // just check the file itself, and that's it.
13722   const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
13723     : (
13724       [
13725         // windows always checks the cwd first
13726         ...(isWindows ? [process.cwd()] : []),
13727         ...(opt.path || process.env.PATH ||
13728           /* istanbul ignore next: very unusual */ '').split(colon),
13729       ]
13730     )
13731   const pathExtExe = isWindows
13732     ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
13733     : ''
13734   const pathExt = isWindows ? pathExtExe.split(colon) : ['']
13735
13736   if (isWindows) {
13737     if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
13738       pathExt.unshift('')
13739   }
13740
13741   return {
13742     pathEnv,
13743     pathExt,
13744     pathExtExe,
13745   }
13746 }
13747
13748 const which = (cmd, opt, cb) => {
13749   if (typeof opt === 'function') {
13750     cb = opt
13751     opt = {}
13752   }
13753   if (!opt)
13754     opt = {}
13755
13756   const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13757   const found = []
13758
13759   const step = i => new Promise((resolve, reject) => {
13760     if (i === pathEnv.length)
13761       return opt.all && found.length ? resolve(found)
13762         : reject(getNotFoundError(cmd))
13763
13764     const ppRaw = pathEnv[i]
13765     const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13766
13767     const pCmd = path.join(pathPart, cmd)
13768     const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13769       : pCmd
13770
13771     resolve(subStep(p, i, 0))
13772   })
13773
13774   const subStep = (p, i, ii) => new Promise((resolve, reject) => {
13775     if (ii === pathExt.length)
13776       return resolve(step(i + 1))
13777     const ext = pathExt[ii]
13778     isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
13779       if (!er && is) {
13780         if (opt.all)
13781           found.push(p + ext)
13782         else
13783           return resolve(p + ext)
13784       }
13785       return resolve(subStep(p, i, ii + 1))
13786     })
13787   })
13788
13789   return cb ? step(0).then(res => cb(null, res), cb) : step(0)
13790 }
13791
13792 const whichSync = (cmd, opt) => {
13793   opt = opt || {}
13794
13795   const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
13796   const found = []
13797
13798   for (let i = 0; i < pathEnv.length; i ++) {
13799     const ppRaw = pathEnv[i]
13800     const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
13801
13802     const pCmd = path.join(pathPart, cmd)
13803     const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
13804       : pCmd
13805
13806     for (let j = 0; j < pathExt.length; j ++) {
13807       const cur = p + pathExt[j]
13808       try {
13809         const is = isexe.sync(cur, { pathExt: pathExtExe })
13810         if (is) {
13811           if (opt.all)
13812             found.push(cur)
13813           else
13814             return cur
13815         }
13816       } catch (ex) {}
13817     }
13818   }
13819
13820   if (opt.all && found.length)
13821     return found
13822
13823   if (opt.nothrow)
13824     return null
13825
13826   throw getNotFoundError(cmd)
13827 }
13828
13829 module.exports = which
13830 which.sync = whichSync
13831
13832
13833 /***/ }),
13834 /* 126 */
13835 /***/ (function(module, exports, __webpack_require__) {
13836
13837 var fs = __webpack_require__(102)
13838 var core
13839 if (process.platform === 'win32' || global.TESTING_WINDOWS) {
13840   core = __webpack_require__(127)
13841 } else {
13842   core = __webpack_require__(128)
13843 }
13844
13845 module.exports = isexe
13846 isexe.sync = sync
13847
13848 function isexe (path, options, cb) {
13849   if (typeof options === 'function') {
13850     cb = options
13851     options = {}
13852   }
13853
13854   if (!cb) {
13855     if (typeof Promise !== 'function') {
13856       throw new TypeError('callback not provided')
13857     }
13858
13859     return new Promise(function (resolve, reject) {
13860       isexe(path, options || {}, function (er, is) {
13861         if (er) {
13862           reject(er)
13863         } else {
13864           resolve(is)
13865         }
13866       })
13867     })
13868   }
13869
13870   core(path, options || {}, function (er, is) {
13871     // ignore EACCES because that just means we aren't allowed to run it
13872     if (er) {
13873       if (er.code === 'EACCES' || options && options.ignoreErrors) {
13874         er = null
13875         is = false
13876       }
13877     }
13878     cb(er, is)
13879   })
13880 }
13881
13882 function sync (path, options) {
13883   // my kingdom for a filtered catch
13884   try {
13885     return core.sync(path, options || {})
13886   } catch (er) {
13887     if (options && options.ignoreErrors || er.code === 'EACCES') {
13888       return false
13889     } else {
13890       throw er
13891     }
13892   }
13893 }
13894
13895
13896 /***/ }),
13897 /* 127 */
13898 /***/ (function(module, exports, __webpack_require__) {
13899
13900 module.exports = isexe
13901 isexe.sync = sync
13902
13903 var fs = __webpack_require__(102)
13904
13905 function checkPathExt (path, options) {
13906   var pathext = options.pathExt !== undefined ?
13907     options.pathExt : process.env.PATHEXT
13908
13909   if (!pathext) {
13910     return true
13911   }
13912
13913   pathext = pathext.split(';')
13914   if (pathext.indexOf('') !== -1) {
13915     return true
13916   }
13917   for (var i = 0; i < pathext.length; i++) {
13918     var p = pathext[i].toLowerCase()
13919     if (p && path.substr(-p.length).toLowerCase() === p) {
13920       return true
13921     }
13922   }
13923   return false
13924 }
13925
13926 function checkStat (stat, path, options) {
13927   if (!stat.isSymbolicLink() && !stat.isFile()) {
13928     return false
13929   }
13930   return checkPathExt(path, options)
13931 }
13932
13933 function isexe (path, options, cb) {
13934   fs.stat(path, function (er, stat) {
13935     cb(er, er ? false : checkStat(stat, path, options))
13936   })
13937 }
13938
13939 function sync (path, options) {
13940   return checkStat(fs.statSync(path), path, options)
13941 }
13942
13943
13944 /***/ }),
13945 /* 128 */
13946 /***/ (function(module, exports, __webpack_require__) {
13947
13948 module.exports = isexe
13949 isexe.sync = sync
13950
13951 var fs = __webpack_require__(102)
13952
13953 function isexe (path, options, cb) {
13954   fs.stat(path, function (er, stat) {
13955     cb(er, er ? false : checkStat(stat, options))
13956   })
13957 }
13958
13959 function sync (path, options) {
13960   return checkStat(fs.statSync(path), options)
13961 }
13962
13963 function checkStat (stat, options) {
13964   return stat.isFile() && checkMode(stat, options)
13965 }
13966
13967 function checkMode (stat, options) {
13968   var mod = stat.mode
13969   var uid = stat.uid
13970   var gid = stat.gid
13971
13972   var myUid = options.uid !== undefined ?
13973     options.uid : process.getuid && process.getuid()
13974   var myGid = options.gid !== undefined ?
13975     options.gid : process.getgid && process.getgid()
13976
13977   var u = parseInt('100', 8)
13978   var g = parseInt('010', 8)
13979   var o = parseInt('001', 8)
13980   var ug = u | g
13981
13982   var ret = (mod & o) ||
13983     (mod & g) && gid === myGid ||
13984     (mod & u) && uid === myUid ||
13985     (mod & ug) && myUid === 0
13986
13987   return ret
13988 }
13989
13990
13991 /***/ }),
13992 /* 129 */
13993 /***/ (function(module, exports, __webpack_require__) {
13994
13995 "use strict";
13996
13997 /*---------------------------------------------------------------------------------------------
13998  *  Copyright (c) Microsoft Corporation. All rights reserved.
13999  *  Licensed under the MIT License. See License.txt in the project root for license information.
14000  *--------------------------------------------------------------------------------------------*/
14001 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14002     if (k2 === undefined) k2 = k;
14003     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
14004 }) : (function(o, m, k, k2) {
14005     if (k2 === undefined) k2 = k;
14006     o[k2] = m[k];
14007 }));
14008 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14009     Object.defineProperty(o, "default", { enumerable: true, value: v });
14010 }) : function(o, v) {
14011     o["default"] = v;
14012 });
14013 var __importStar = (this && this.__importStar) || function (mod) {
14014     if (mod && mod.__esModule) return mod;
14015     var result = {};
14016     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14017     __setModuleDefault(result, mod);
14018     return result;
14019 };
14020 Object.defineProperty(exports, "__esModule", { value: true });
14021 const coc_nvim_1 = __webpack_require__(1);
14022 const is = __importStar(__webpack_require__(130));
14023 class Logger {
14024     get output() {
14025         if (this._channel) {
14026             return this._channel;
14027         }
14028         this._channel = coc_nvim_1.workspace.createOutputChannel('tsserver');
14029         return this._channel;
14030     }
14031     dispose() {
14032         if (this._channel) {
14033             this._channel.dispose();
14034         }
14035     }
14036     data2String(data) {
14037         if (data instanceof Error) {
14038             if (is.string(data.stack)) {
14039                 return data.stack;
14040             }
14041             return data.message;
14042         }
14043         if (is.boolean(data.success) && !data.success && is.string(data.message)) {
14044             return data.message;
14045         }
14046         if (is.string(data)) {
14047             return data;
14048         }
14049         return data.toString();
14050     }
14051     info(message, data) {
14052         this.logLevel('Info', message, data);
14053     }
14054     warn(message, data) {
14055         this.logLevel('Warn', message, data);
14056     }
14057     error(message, data) {
14058         // See https://github.com/Microsoft/TypeScript/issues/10496
14059         if (data && data.message === 'No content available.') {
14060             return;
14061         }
14062         this.logLevel('Error', message, data);
14063     }
14064     logLevel(level, message, data) {
14065         this.output.appendLine(`[${level}  - ${new Date().toLocaleTimeString()}] ${message}`);
14066         if (data) {
14067             this.output.appendLine(this.data2String(data));
14068         }
14069     }
14070 }
14071 exports.default = Logger;
14072
14073
14074 /***/ }),
14075 /* 130 */
14076 /***/ (function(module, exports, __webpack_require__) {
14077
14078 "use strict";
14079
14080 /*---------------------------------------------------------------------------------------------
14081  *  Copyright (c) Microsoft Corporation. All rights reserved.
14082  *  Licensed under the MIT License. See License.txt in the project root for license information.
14083  *--------------------------------------------------------------------------------------------*/
14084 Object.defineProperty(exports, "__esModule", { value: true });
14085 exports.string = exports.boolean = exports.defined = void 0;
14086 const toString = Object.prototype.toString;
14087 function defined(value) {
14088     return typeof value !== 'undefined';
14089 }
14090 exports.defined = defined;
14091 function boolean(value) {
14092     return value === true || value === false;
14093 }
14094 exports.boolean = boolean;
14095 function string(value) {
14096     return toString.call(value) === '[object String]';
14097 }
14098 exports.string = string;
14099
14100
14101 /***/ }),
14102 /* 131 */
14103 /***/ (function(module, exports, __webpack_require__) {
14104
14105 "use strict";
14106
14107 var __importDefault = (this && this.__importDefault) || function (mod) {
14108     return (mod && mod.__esModule) ? mod : { "default": mod };
14109 };
14110 Object.defineProperty(exports, "__esModule", { value: true });
14111 exports.fork = exports.getTempFile = exports.getTempDirectory = exports.makeRandomHexString = void 0;
14112 /*---------------------------------------------------------------------------------------------
14113  *  Copyright (c) Microsoft Corporation. All rights reserved.
14114  *  Licensed under the MIT License. See License.txt in the project root for license information.
14115  *--------------------------------------------------------------------------------------------*/
14116 const child_process_1 = __importDefault(__webpack_require__(101));
14117 const net_1 = __importDefault(__webpack_require__(16));
14118 const os_1 = __importDefault(__webpack_require__(14));
14119 const path_1 = __importDefault(__webpack_require__(13));
14120 const fs_1 = __importDefault(__webpack_require__(102));
14121 function makeRandomHexString(length) {
14122     let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
14123     let result = '';
14124     for (let i = 0; i < length; i++) {
14125         const idx = Math.floor(chars.length * Math.random());
14126         result += chars[idx];
14127     }
14128     return result;
14129 }
14130 exports.makeRandomHexString = makeRandomHexString;
14131 function getTempDirectory() {
14132     let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
14133     if (!fs_1.default.existsSync(dir)) {
14134         fs_1.default.mkdirSync(dir);
14135     }
14136     return dir;
14137 }
14138 exports.getTempDirectory = getTempDirectory;
14139 function generatePipeName() {
14140     return getPipeName(makeRandomHexString(40));
14141 }
14142 function getPipeName(name) {
14143     const fullName = 'coc-tsc-' + name;
14144     if (process.platform === 'win32') {
14145         return '\\\\.\\pipe\\' + fullName + '-sock';
14146     }
14147     const tmpdir = getTempDirectory();
14148     // Mac/Unix: use socket file
14149     return path_1.default.join(tmpdir, fullName + '.sock');
14150 }
14151 function getTempFile(name) {
14152     const fullName = 'coc-nvim-' + name;
14153     return path_1.default.join(getTempDirectory(), fullName + '.sock');
14154 }
14155 exports.getTempFile = getTempFile;
14156 function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
14157     const newEnv = Object.assign({}, env);
14158     // Set the two unique pipe names and the electron flag as process env
14159     newEnv['STDIN_PIPE_NAME'] = stdInPipeName; // tslint:disable-line
14160     newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName; // tslint:disable-line
14161     newEnv['STDERR_PIPE_NAME'] = stdErrPipeName; // tslint:disable-line
14162     newEnv['TSS_LOG'] = `-level verbose -file ${path_1.default.join(os_1.default.tmpdir(), 'coc-nvim-tsc.log')}`; // tslint:disable-line
14163     // Ensure we always have a PATH set
14164     newEnv['PATH'] = newEnv['PATH'] || process.env.PATH; // tslint:disable-line
14165     return newEnv;
14166 }
14167 function fork(modulePath, args, options, logger, callback) {
14168     let callbackCalled = false;
14169     const resolve = (result) => {
14170         if (callbackCalled) {
14171             return;
14172         }
14173         callbackCalled = true;
14174         callback(null, result);
14175     };
14176     const reject = (err) => {
14177         if (callbackCalled) {
14178             return;
14179         }
14180         callbackCalled = true;
14181         callback(err, null);
14182     };
14183     // Generate three unique pipe names
14184     const stdInPipeName = generatePipeName();
14185     const stdOutPipeName = generatePipeName();
14186     const stdErrPipeName = generatePipeName();
14187     const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
14188     newEnv['NODE_PATH'] = path_1.default.join(modulePath, '..', '..', '..'); // tslint:disable-line
14189     let childProcess;
14190     // Begin listening to stderr pipe
14191     let stdErrServer = net_1.default.createServer(stdErrStream => {
14192         // From now on the childProcess.stderr is available for reading
14193         childProcess.stderr = stdErrStream;
14194     });
14195     stdErrServer.listen(stdErrPipeName);
14196     // Begin listening to stdout pipe
14197     let stdOutServer = net_1.default.createServer(stdOutStream => {
14198         // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe
14199         stdOutStream.once('data', (_chunk) => {
14200             // The child process is sending me the `ready` chunk, time to connect to the stdin pipe
14201             childProcess.stdin = net_1.default.connect(stdInPipeName);
14202             // From now on the childProcess.stdout is available for reading
14203             childProcess.stdout = stdOutStream;
14204             resolve(childProcess);
14205         });
14206     });
14207     stdOutServer.listen(stdOutPipeName);
14208     let serverClosed = false;
14209     const closeServer = () => {
14210         if (serverClosed) {
14211             return;
14212         }
14213         serverClosed = true;
14214         stdOutServer.close();
14215         stdErrServer.close();
14216     };
14217     // Create the process
14218     logger.info('Forking TSServer', `PATH: ${newEnv['PATH']} `);
14219     const bootstrapperPath = path_1.default.resolve(__dirname, '../bin/tsserverForkStart');
14220     childProcess = child_process_1.default.fork(bootstrapperPath, [modulePath].concat(args), {
14221         silent: true,
14222         env: newEnv,
14223         execArgv: options.execArgv
14224     });
14225     childProcess.once('error', (err) => {
14226         closeServer();
14227         reject(err);
14228     });
14229     childProcess.once('exit', (err) => {
14230         closeServer();
14231         reject(err);
14232     });
14233 }
14234 exports.fork = fork;
14235
14236
14237 /***/ }),
14238 /* 132 */
14239 /***/ (function(module, exports, __webpack_require__) {
14240
14241 "use strict";
14242
14243 Object.defineProperty(exports, "__esModule", { value: true });
14244 /*---------------------------------------------------------------------------------------------
14245  *  Copyright (c) Microsoft Corporation. All rights reserved.
14246  *  Licensed under the MIT License. See License.txt in the project root for license information.
14247  *--------------------------------------------------------------------------------------------*/
14248 const coc_nvim_1 = __webpack_require__(1);
14249 var Trace;
14250 (function (Trace) {
14251     Trace[Trace["Off"] = 0] = "Off";
14252     Trace[Trace["Messages"] = 1] = "Messages";
14253     Trace[Trace["Verbose"] = 2] = "Verbose";
14254 })(Trace || (Trace = {}));
14255 (function (Trace) {
14256     function fromString(value) {
14257         value = value || '';
14258         value = value.toLowerCase();
14259         switch (value) {
14260             case 'off':
14261                 return Trace.Off;
14262             case 'messages':
14263                 return Trace.Messages;
14264             case 'verbose':
14265                 return Trace.Verbose;
14266             default:
14267                 return Trace.Off;
14268         }
14269     }
14270     Trace.fromString = fromString;
14271 })(Trace || (Trace = {}));
14272 class Tracer {
14273     constructor(logger) {
14274         this.logger = logger;
14275         this.trace = Tracer.readTrace();
14276     }
14277     static readTrace() {
14278         let result = Trace.fromString(coc_nvim_1.workspace.getConfiguration('tsserver').get('trace.server', 'off'));
14279         if (result === Trace.Off && !!process.env.TSS_TRACE) {
14280             result = Trace.Messages;
14281         }
14282         return result;
14283     }
14284     traceRequest(request, responseExpected, queueLength) {
14285         if (this.trace === Trace.Off)
14286             return;
14287         let data;
14288         if (this.trace === Trace.Verbose && request.arguments) {
14289             data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
14290         }
14291         this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);
14292     }
14293     traceResponse(response, startTime) {
14294         if (this.trace === Trace.Off) {
14295             return;
14296         }
14297         let data;
14298         if (this.trace === Trace.Verbose && response.body) {
14299             data = `Result: ${JSON.stringify(response.body, null, 4)}`;
14300         }
14301         this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);
14302     }
14303     traceEvent(event) {
14304         if (this.trace === Trace.Off) {
14305             return;
14306         }
14307         let data;
14308         if (this.trace === Trace.Verbose && event.body) {
14309             data = `Data: ${JSON.stringify(event.body, null, 4)}`;
14310         }
14311         this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
14312     }
14313     logTrace(message, data) {
14314         if (this.trace !== Trace.Off) {
14315             this.logger.logLevel('Trace', message, data);
14316         }
14317     }
14318     traceRequestCompleted(command, request_seq, startTime) {
14319         if (this.trace === Trace.Off) {
14320             return;
14321         }
14322         this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
14323     }
14324 }
14325 exports.default = Tracer;
14326
14327
14328 /***/ }),
14329 /* 133 */
14330 /***/ (function(module, exports, __webpack_require__) {
14331
14332 "use strict";
14333
14334 Object.defineProperty(exports, "__esModule", { value: true });
14335 exports.inferredProjectConfig = void 0;
14336 function inferredProjectConfig(config) {
14337     const base = {
14338         module: 'commonjs',
14339         target: 'es2016',
14340         jsx: 'preserve'
14341     };
14342     if (config.checkJs) {
14343         base.checkJs = true;
14344     }
14345     if (config.experimentalDecorators) {
14346         base.experimentalDecorators = true;
14347     }
14348     return base;
14349 }
14350 exports.inferredProjectConfig = inferredProjectConfig;
14351
14352
14353 /***/ }),
14354 /* 134 */
14355 /***/ (function(module, exports, __webpack_require__) {
14356
14357 "use strict";
14358
14359 var __importDefault = (this && this.__importDefault) || function (mod) {
14360     return (mod && mod.__esModule) ? mod : { "default": mod };
14361 };
14362 Object.defineProperty(exports, "__esModule", { value: true });
14363 exports.TypeScriptVersionProvider = exports.TypeScriptVersion = void 0;
14364 /*---------------------------------------------------------------------------------------------
14365  *  Copyright (c) Microsoft Corporation. All rights reserved.
14366  *  Licensed under the MIT License. See License.txt in the project root for license information.
14367  *--------------------------------------------------------------------------------------------*/
14368 const fs_1 = __importDefault(__webpack_require__(102));
14369 const path_1 = __importDefault(__webpack_require__(13));
14370 const coc_nvim_1 = __webpack_require__(1);
14371 const api_1 = __importDefault(__webpack_require__(40));
14372 const requireFunc =  true ? require : undefined;
14373 class TypeScriptVersion {
14374     constructor(path, _pathLabel) {
14375         this.path = path;
14376         this._pathLabel = _pathLabel;
14377         this._api = null;
14378     }
14379     get tscPath() {
14380         return path_1.default.resolve(this.path, '../bin/tsc');
14381     }
14382     get tsServerPath() {
14383         return path_1.default.resolve(this.path, 'tsserver.js');
14384     }
14385     get pathLabel() {
14386         return typeof this._pathLabel === 'undefined' ? this.path : this._pathLabel;
14387     }
14388     get isValid() {
14389         return this.version != null;
14390     }
14391     get version() {
14392         if (this._api)
14393             return this._api;
14394         let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
14395         return api;
14396     }
14397     get versionString() {
14398         const version = this.version;
14399         return version ? version.versionString : null;
14400     }
14401     getTypeScriptVersion(serverPath) {
14402         if (!fs_1.default.existsSync(serverPath)) {
14403             return undefined;
14404         }
14405         const p = serverPath.split(path_1.default.sep);
14406         if (p.length <= 2) {
14407             return undefined;
14408         }
14409         const p2 = p.slice(0, -2);
14410         const modulePath = p2.join(path_1.default.sep);
14411         let fileName = path_1.default.join(modulePath, 'package.json');
14412         if (!fs_1.default.existsSync(fileName)) {
14413             // Special case for ts dev versions
14414             if (path_1.default.basename(modulePath) === 'built') {
14415                 fileName = path_1.default.join(modulePath, '..', 'package.json');
14416             }
14417         }
14418         if (!fs_1.default.existsSync(fileName)) {
14419             return undefined;
14420         }
14421         const contents = fs_1.default.readFileSync(fileName).toString();
14422         let desc = null;
14423         try {
14424             desc = JSON.parse(contents);
14425         }
14426         catch (err) {
14427             return undefined;
14428         }
14429         if (!desc || !desc.version) {
14430             return undefined;
14431         }
14432         return desc.version ? api_1.default.fromVersionString(desc.version) : undefined;
14433     }
14434 }
14435 exports.TypeScriptVersion = TypeScriptVersion;
14436 const MODULE_FOLDERS = ['node_modules/typescript/lib', '.vscode/pnpify/typescript/lib', '.yarn/sdks/typescript/lib'];
14437 class TypeScriptVersionProvider {
14438     constructor(configuration) {
14439         this.configuration = configuration;
14440     }
14441     updateConfiguration(configuration) {
14442         this.configuration = configuration;
14443     }
14444     getDefaultVersion() {
14445         // tsdk from configuration
14446         let { globalTsdk } = this.configuration;
14447         if (globalTsdk)
14448             return new TypeScriptVersion(globalTsdk);
14449         return this.bundledVersion;
14450     }
14451     get globalVersion() {
14452         let { globalTsdk } = this.configuration;
14453         if (globalTsdk)
14454             return new TypeScriptVersion(coc_nvim_1.workspace.expand(globalTsdk));
14455         return undefined;
14456     }
14457     getLocalVersion() {
14458         let folders = coc_nvim_1.workspace.workspaceFolders.map(f => coc_nvim_1.Uri.parse(f.uri).fsPath);
14459         for (let p of folders) {
14460             for (let folder of MODULE_FOLDERS) {
14461                 let libFolder = path_1.default.join(p, folder);
14462                 if (fs_1.default.existsSync(libFolder)) {
14463                     let version = new TypeScriptVersion(libFolder);
14464                     if (version.isValid)
14465                         return version;
14466                 }
14467             }
14468         }
14469         return null;
14470     }
14471     get bundledVersion() {
14472         try {
14473             const file = requireFunc.resolve('typescript');
14474             const bundledVersion = new TypeScriptVersion(path_1.default.dirname(file), '');
14475             return bundledVersion;
14476         }
14477         catch (e) {
14478             coc_nvim_1.workspace.showMessage('Bundled typescript module not found', 'error');
14479             return null;
14480         }
14481     }
14482 }
14483 exports.TypeScriptVersionProvider = TypeScriptVersionProvider;
14484
14485
14486 /***/ }),
14487 /* 135 */
14488 /***/ (function(module, exports, __webpack_require__) {
14489
14490 "use strict";
14491
14492 Object.defineProperty(exports, "__esModule", { value: true });
14493 const coc_nvim_1 = __webpack_require__(1);
14494 class VersionStatus {
14495     constructor(_normalizePath, enableJavascript) {
14496         this._normalizePath = _normalizePath;
14497         this.enableJavascript = enableJavascript;
14498         this._versionBarEntry = coc_nvim_1.workspace.createStatusBarItem(99);
14499         this._onChangeEditorSub = coc_nvim_1.events.on('BufEnter', this.onBufEnter, this);
14500         this._versionBarEntry.show();
14501     }
14502     dispose() {
14503         this._versionBarEntry.dispose();
14504         this._onChangeEditorSub.dispose();
14505     }
14506     onDidChangeTypeScriptVersion(_version) {
14507         this._versionBarEntry.text = `TSC`;
14508     }
14509     set loading(isLoading) {
14510         this._versionBarEntry.isProgress = isLoading;
14511     }
14512     checkFiletype(filetype) {
14513         if (filetype.startsWith('javascript') && this.enableJavascript) {
14514             return true;
14515         }
14516         return filetype.startsWith('typescript');
14517     }
14518     async onBufEnter(bufnr) {
14519         let filetype = await coc_nvim_1.workspace.nvim.call('getbufvar', [bufnr, '&filetype', '']);
14520         if (this.checkFiletype(filetype)) {
14521             this._versionBarEntry.show();
14522         }
14523         else {
14524             this._versionBarEntry.hide();
14525         }
14526     }
14527 }
14528 exports.default = VersionStatus;
14529
14530
14531 /***/ }),
14532 /* 136 */
14533 /***/ (function(module, exports, __webpack_require__) {
14534
14535 "use strict";
14536
14537 Object.defineProperty(exports, "__esModule", { value: true });
14538 exports.Reader = void 0;
14539 const DefaultSize = 8192;
14540 const ContentLength = 'Content-Length: ';
14541 const ContentLengthSize = Buffer.byteLength(ContentLength, 'utf8');
14542 const Blank = Buffer.from(' ', 'utf8')[0];
14543 const BackslashR = Buffer.from('\r', 'utf8')[0];
14544 const BackslashN = Buffer.from('\n', 'utf8')[0];
14545 class ProtocolBuffer {
14546     constructor() {
14547         this.index = 0;
14548         this.buffer = Buffer.allocUnsafe(DefaultSize);
14549     }
14550     append(data) {
14551         let toAppend = null;
14552         if (Buffer.isBuffer(data)) {
14553             toAppend = data;
14554         }
14555         else {
14556             toAppend = Buffer.from(data, 'utf8');
14557         }
14558         if (this.buffer.length - this.index >= toAppend.length) {
14559             toAppend.copy(this.buffer, this.index, 0, toAppend.length);
14560         }
14561         else {
14562             let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) *
14563                 DefaultSize;
14564             if (this.index === 0) {
14565                 this.buffer = Buffer.allocUnsafe(newSize);
14566                 toAppend.copy(this.buffer, 0, 0, toAppend.length);
14567             }
14568             else {
14569                 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
14570             }
14571         }
14572         this.index += toAppend.length;
14573     }
14574     tryReadContentLength() {
14575         let result = -1;
14576         let current = 0;
14577         // we are utf8 encoding...
14578         while (current < this.index &&
14579             (this.buffer[current] === Blank ||
14580                 this.buffer[current] === BackslashR ||
14581                 this.buffer[current] === BackslashN)) {
14582             current++;
14583         }
14584         if (this.index < current + ContentLengthSize) {
14585             return result;
14586         }
14587         current += ContentLengthSize;
14588         let start = current;
14589         while (current < this.index && this.buffer[current] !== BackslashR) {
14590             current++;
14591         }
14592         if (current + 3 >= this.index ||
14593             this.buffer[current + 1] !== BackslashN ||
14594             this.buffer[current + 2] !== BackslashR ||
14595             this.buffer[current + 3] !== BackslashN) {
14596             return result;
14597         }
14598         let data = this.buffer.toString('utf8', start, current);
14599         result = parseInt(data, 10);
14600         this.buffer = this.buffer.slice(current + 4);
14601         this.index = this.index - (current + 4);
14602         return result;
14603     }
14604     tryReadContent(length) {
14605         if (this.index < length) {
14606             return null;
14607         }
14608         let result = this.buffer.toString('utf8', 0, length);
14609         let sourceStart = length;
14610         while (sourceStart < this.index &&
14611             (this.buffer[sourceStart] === BackslashR ||
14612                 this.buffer[sourceStart] === BackslashN)) {
14613             sourceStart++;
14614         }
14615         this.buffer.copy(this.buffer, 0, sourceStart);
14616         this.index = this.index - sourceStart;
14617         return result;
14618     }
14619 }
14620 class Reader {
14621     constructor(readable, callback, onError) {
14622         this.readable = readable;
14623         this.callback = callback;
14624         this.onError = onError;
14625         this.buffer = new ProtocolBuffer();
14626         this.nextMessageLength = -1;
14627         this.readable.on('data', (data) => {
14628             this.onLengthData(data);
14629         });
14630     }
14631     onLengthData(data) {
14632         try {
14633             this.buffer.append(data);
14634             while (true) {
14635                 if (this.nextMessageLength === -1) {
14636                     this.nextMessageLength = this.buffer.tryReadContentLength();
14637                     if (this.nextMessageLength === -1) {
14638                         return;
14639                     }
14640                 }
14641                 const msg = this.buffer.tryReadContent(this.nextMessageLength);
14642                 if (msg === null) {
14643                     return;
14644                 }
14645                 this.nextMessageLength = -1;
14646                 const json = JSON.parse(msg);
14647                 this.callback(json);
14648             }
14649         }
14650         catch (e) {
14651             this.onError(e);
14652         }
14653     }
14654 }
14655 exports.Reader = Reader;
14656
14657
14658 /***/ }),
14659 /* 137 */
14660 /***/ (function(module, exports, __webpack_require__) {
14661
14662 "use strict";
14663
14664 Object.defineProperty(exports, "__esModule", { value: true });
14665 exports.AtaProgressReporter = void 0;
14666 /*---------------------------------------------------------------------------------------------
14667  *  Copyright (c) Microsoft Corporation. All rights reserved.
14668  *  Licensed under the MIT License. See License.txt in the project root for license information.
14669  *--------------------------------------------------------------------------------------------*/
14670 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14671 const coc_nvim_1 = __webpack_require__(1);
14672 const typingsInstallTimeout = 30 * 1000;
14673 class TypingsStatus {
14674     constructor(client) {
14675         this._acquiringTypings = Object.create({});
14676         this._subscriptions = [];
14677         this._client = client;
14678         this._subscriptions.push(this._client.onDidBeginInstallTypings(event => this.onBeginInstallTypings(event.eventId)));
14679         this._subscriptions.push(this._client.onDidEndInstallTypings(event => this.onEndInstallTypings(event.eventId)));
14680     }
14681     dispose() {
14682         this._subscriptions.forEach(x => x.dispose());
14683         for (const eventId of Object.keys(this._acquiringTypings)) {
14684             clearTimeout(this._acquiringTypings[eventId]);
14685         }
14686     }
14687     get isAcquiringTypings() {
14688         return Object.keys(this._acquiringTypings).length > 0;
14689     }
14690     onBeginInstallTypings(eventId) {
14691         if (this._acquiringTypings[eventId]) {
14692             return;
14693         }
14694         this._acquiringTypings[eventId] = setTimeout(() => {
14695             this.onEndInstallTypings(eventId);
14696         }, typingsInstallTimeout);
14697     }
14698     onEndInstallTypings(eventId) {
14699         const timer = this._acquiringTypings[eventId];
14700         if (timer) {
14701             clearTimeout(timer);
14702         }
14703         delete this._acquiringTypings[eventId];
14704     }
14705 }
14706 exports.default = TypingsStatus;
14707 class AtaProgressReporter {
14708     constructor(client) {
14709         this._promises = new Map();
14710         this._invalid = false;
14711         this.statusItem = coc_nvim_1.workspace.createStatusBarItem(10, { progress: true });
14712         const disposables = [];
14713         disposables.push(client.onDidBeginInstallTypings(e => this._onBegin(e.eventId)));
14714         disposables.push(client.onDidEndInstallTypings(e => this._onEndOrTimeout(e.eventId)));
14715         disposables.push(client.onTypesInstallerInitializationFailed(_ => this.onTypesInstallerInitializationFailed()));
14716         this._disposable = vscode_languageserver_protocol_1.Disposable.create(() => {
14717             disposables.forEach(disposable => {
14718                 disposable.dispose();
14719             });
14720         });
14721     }
14722     dispose() {
14723         this._disposable.dispose();
14724         this._promises.forEach(value => value());
14725     }
14726     _onBegin(eventId) {
14727         const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
14728         new Promise(resolve => {
14729             this._promises.set(eventId, () => {
14730                 clearTimeout(handle);
14731                 resolve();
14732             });
14733         });
14734         this.statusItem.text = 'Fetching data for better TypeScript IntelliSense';
14735         this.statusItem.show();
14736     }
14737     _onEndOrTimeout(eventId) {
14738         this.statusItem.hide();
14739         const resolve = this._promises.get(eventId);
14740         if (resolve) {
14741             this._promises.delete(eventId);
14742             resolve();
14743         }
14744     }
14745     onTypesInstallerInitializationFailed() {
14746         this.statusItem.hide();
14747         if (!this._invalid) {
14748             coc_nvim_1.workspace.showMessage('Could not install typings files for JavaScript language features. Please ensure that NPM is installed', 'error');
14749         }
14750         this._invalid = true;
14751     }
14752 }
14753 exports.AtaProgressReporter = AtaProgressReporter;
14754
14755
14756 /***/ }),
14757 /* 138 */
14758 /***/ (function(module, exports, __webpack_require__) {
14759
14760 "use strict";
14761
14762 var __importDefault = (this && this.__importDefault) || function (mod) {
14763     return (mod && mod.__esModule) ? mod : { "default": mod };
14764 };
14765 Object.defineProperty(exports, "__esModule", { value: true });
14766 const coc_nvim_1 = __webpack_require__(1);
14767 const path_1 = __importDefault(__webpack_require__(13));
14768 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14769 const countRegex = /Found\s+(\d+)\s+error/;
14770 const errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
14771 var TscStatus;
14772 (function (TscStatus) {
14773     TscStatus[TscStatus["INIT"] = 0] = "INIT";
14774     TscStatus[TscStatus["COMPILING"] = 1] = "COMPILING";
14775     TscStatus[TscStatus["RUNNING"] = 2] = "RUNNING";
14776     TscStatus[TscStatus["ERROR"] = 3] = "ERROR";
14777 })(TscStatus || (TscStatus = {}));
14778 class WatchProject {
14779     constructor(client) {
14780         this.client = client;
14781         this.disposables = [];
14782         this.statusItem = coc_nvim_1.workspace.createStatusBarItem(1, { progress: true });
14783         let task = this.task = coc_nvim_1.workspace.createTask('TSC');
14784         this.disposables.push(coc_nvim_1.commands.registerCommand(WatchProject.id, async () => {
14785             let opts = this.options = await this.getOptions();
14786             await this.start(opts);
14787         }));
14788         task.onExit(code => {
14789             if (code != 0) {
14790                 coc_nvim_1.workspace.showMessage(`TSC exit with code ${code}`, 'warning');
14791             }
14792             this.onStop();
14793         });
14794         task.onStdout(lines => {
14795             for (let line of lines) {
14796                 this.onLine(line);
14797             }
14798         });
14799         task.onStderr(lines => {
14800             coc_nvim_1.workspace.showMessage(`TSC error: ` + lines.join('\n'), 'error');
14801         });
14802         this.disposables.push(vscode_languageserver_protocol_1.Disposable.create(() => {
14803             task.dispose();
14804         }));
14805         this.check().catch(_e => {
14806             // noop
14807         });
14808     }
14809     async check() {
14810         let running = await this.task.running;
14811         if (running) {
14812             this.options = await this.getOptions();
14813             this.statusItem.isProgress = false;
14814             this.statusItem.text = '?';
14815             this.statusItem.show();
14816         }
14817         else {
14818             this.onStop();
14819         }
14820     }
14821     async start(options) {
14822         await this.task.start(options);
14823     }
14824     onStop() {
14825         this.statusItem.hide();
14826     }
14827     onStart() {
14828         this.statusItem.text = 'compiling';
14829         this.statusItem.isProgress = true;
14830         this.statusItem.show();
14831         coc_nvim_1.workspace.nvim.call('setqflist', [[]], true);
14832     }
14833     onLine(line) {
14834         if (countRegex.test(line)) {
14835             let ms = line.match(countRegex);
14836             this.statusItem.text = ms[1] == '0' ? '✓' : '✗';
14837             this.statusItem.isProgress = false;
14838         }
14839         else if (WatchProject.startTexts.findIndex(s => line.indexOf(s) !== -1) != -1) {
14840             this.onStart();
14841         }
14842         else {
14843             let ms = line.match(errorRegex);
14844             if (!ms)
14845                 return;
14846             let fullpath = path_1.default.join(this.options.cwd, ms[1]);
14847             let uri = coc_nvim_1.Uri.file(fullpath).toString();
14848             let doc = coc_nvim_1.workspace.getDocument(uri);
14849             let bufnr = doc ? doc.bufnr : null;
14850             let item = {
14851                 filename: fullpath,
14852                 lnum: Number(ms[2]),
14853                 col: Number(ms[3]),
14854                 text: `[tsc ${ms[5]}] ${ms[6]}`,
14855                 type: /error/i.test(ms[4]) ? 'E' : 'W'
14856             };
14857             if (bufnr)
14858                 item.bufnr = bufnr;
14859             coc_nvim_1.workspace.nvim.call('setqflist', [[item], 'a']);
14860         }
14861     }
14862     async getOptions() {
14863         let { tscPath } = this.client;
14864         if (!tscPath) {
14865             coc_nvim_1.workspace.showMessage(`Local & global tsc not found`, 'error');
14866             return;
14867         }
14868         let find = await coc_nvim_1.workspace.findUp(['tsconfig.json']);
14869         if (!find) {
14870             coc_nvim_1.workspace.showMessage('tsconfig.json not found!', 'error');
14871             return;
14872         }
14873         let root = path_1.default.dirname(find);
14874         return {
14875             cmd: tscPath,
14876             args: ['-p', 'tsconfig.json', '--watch', 'true', '--pretty', 'false'],
14877             cwd: root
14878         };
14879     }
14880     dispose() {
14881         coc_nvim_1.disposeAll(this.disposables);
14882     }
14883 }
14884 exports.default = WatchProject;
14885 WatchProject.id = 'tsserver.watchBuild';
14886 WatchProject.startTexts = ['Starting compilation in watch mode', 'Starting incremental compilation'];
14887
14888
14889 /***/ }),
14890 /* 139 */
14891 /***/ (function(module, exports, __webpack_require__) {
14892
14893 "use strict";
14894
14895 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14896     if (k2 === undefined) k2 = k;
14897     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
14898 }) : (function(o, m, k, k2) {
14899     if (k2 === undefined) k2 = k;
14900     o[k2] = m[k];
14901 }));
14902 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14903     Object.defineProperty(o, "default", { enumerable: true, value: v });
14904 }) : function(o, v) {
14905     o["default"] = v;
14906 });
14907 var __importStar = (this && this.__importStar) || function (mod) {
14908     if (mod && mod.__esModule) return mod;
14909     var result = {};
14910     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
14911     __setModuleDefault(result, mod);
14912     return result;
14913 };
14914 var __importDefault = (this && this.__importDefault) || function (mod) {
14915     return (mod && mod.__esModule) ? mod : { "default": mod };
14916 };
14917 Object.defineProperty(exports, "__esModule", { value: true });
14918 /*---------------------------------------------------------------------------------------------
14919  *  Copyright (c) Microsoft Corporation. All rights reserved.
14920  *  Licensed under the MIT License. See License.txt in the project root for license information.
14921  *--------------------------------------------------------------------------------------------*/
14922 const vscode_languageserver_protocol_1 = __webpack_require__(3);
14923 const coc_nvim_1 = __webpack_require__(1);
14924 const typeConverters = __importStar(__webpack_require__(37));
14925 const api_1 = __importDefault(__webpack_require__(40));
14926 function getSymbolKind(item) {
14927     switch (item.kind) {
14928         case 'method':
14929             return vscode_languageserver_protocol_1.SymbolKind.Method;
14930         case 'enum':
14931             return vscode_languageserver_protocol_1.SymbolKind.Enum;
14932         case 'function':
14933             return vscode_languageserver_protocol_1.SymbolKind.Function;
14934         case 'class':
14935             return vscode_languageserver_protocol_1.SymbolKind.Class;
14936         case 'interface':
14937             return vscode_languageserver_protocol_1.SymbolKind.Interface;
14938         case 'var':
14939             return vscode_languageserver_protocol_1.SymbolKind.Variable;
14940         default:
14941             return vscode_languageserver_protocol_1.SymbolKind.Variable;
14942     }
14943 }
14944 class TypeScriptWorkspaceSymbolProvider {
14945     constructor(client, languageIds) {
14946         this.client = client;
14947         this.languageIds = languageIds;
14948     }
14949     async provideWorkspaceSymbols(search, token) {
14950         let filepath;
14951         if (this.searchAllOpenProjects) {
14952             filepath = undefined;
14953         }
14954         else {
14955             let uri = this.getUri();
14956             filepath = uri ? this.client.toPath(uri) : undefined;
14957             if (!filepath && this.client.apiVersion.lt(api_1.default.v390)) {
14958                 return [];
14959             }
14960         }
14961         const args = {
14962             file: filepath,
14963             searchValue: search,
14964             maxResultCount: 256,
14965         };
14966         const response = await this.client.execute('navto', args, token);
14967         if (response.type !== 'response' || response.body == null)
14968             return [];
14969         const result = [];
14970         for (const item of response.body) {
14971             if (!item.containerName && item.kind === 'alias') {
14972                 continue;
14973             }
14974             const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
14975             const range = {
14976                 start: typeConverters.Position.fromLocation(item.start),
14977                 end: typeConverters.Position.fromLocation(item.end),
14978             };
14979             const symbolInfo = vscode_languageserver_protocol_1.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
14980             result.push(symbolInfo);
14981         }
14982         return result;
14983     }
14984     static getLabel(item) {
14985         let label = item.name;
14986         if (item.kind === 'method' || item.kind === 'function') {
14987             label += '()';
14988         }
14989         return label;
14990     }
14991     getUri() {
14992         // typescript wants to have a resource even when asking
14993         // general questions so we check the active editor. If this
14994         // doesn't match we take the first TS document.
14995         const documents = coc_nvim_1.workspace.textDocuments;
14996         for (const document of documents) {
14997             if (this.languageIds.indexOf(document.languageId) >= 0) {
14998                 return document.uri;
14999             }
15000         }
15001         return undefined;
15002     }
15003     get searchAllOpenProjects() {
15004         return this.client.apiVersion.gte(api_1.default.v390)
15005             && coc_nvim_1.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects';
15006     }
15007 }
15008 exports.default = TypeScriptWorkspaceSymbolProvider;
15009
15010
15011 /***/ }),
15012 /* 140 */
15013 /***/ (function(module, exports, __webpack_require__) {
15014
15015 "use strict";
15016
15017 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15018     if (k2 === undefined) k2 = k;
15019     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15020 }) : (function(o, m, k, k2) {
15021     if (k2 === undefined) k2 = k;
15022     o[k2] = m[k];
15023 }));
15024 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15025     Object.defineProperty(o, "default", { enumerable: true, value: v });
15026 }) : function(o, v) {
15027     o["default"] = v;
15028 });
15029 var __importStar = (this && this.__importStar) || function (mod) {
15030     if (mod && mod.__esModule) return mod;
15031     var result = {};
15032     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15033     __setModuleDefault(result, mod);
15034     return result;
15035 };
15036 Object.defineProperty(exports, "__esModule", { value: true });
15037 exports.standardLanguageDescriptions = void 0;
15038 /*---------------------------------------------------------------------------------------------
15039  *  Copyright (c) Microsoft Corporation. All rights reserved.
15040  *  Licensed under the MIT License. See License.txt in the project root for license information.
15041  *--------------------------------------------------------------------------------------------*/
15042 const languageModeIds = __importStar(__webpack_require__(120));
15043 exports.standardLanguageDescriptions = [
15044     {
15045         id: 'typescript',
15046         diagnosticSource: 'ts',
15047         diagnosticOwner: 'typescript',
15048         modeIds: [languageModeIds.typescript, languageModeIds.typescriptreact,
15049             languageModeIds.typescripttsx, languageModeIds.typescriptjsx],
15050         diagnosticLanguage: 1 /* TypeScript */,
15051         configFile: 'tsconfig.json',
15052         configFilePattern: /^tsconfig(\..*)?\.json$/gi
15053     },
15054     {
15055         id: 'javascript',
15056         diagnosticSource: 'ts',
15057         diagnosticOwner: 'typescript',
15058         modeIds: [languageModeIds.javascript, languageModeIds.javascriptreact, languageModeIds.javascriptjsx],
15059         diagnosticLanguage: 0 /* JavaScript */,
15060         configFile: 'jsconfig.json',
15061         configFilePattern: /^jsconfig(\..*)?\.json$/gi
15062     }
15063 ];
15064
15065
15066 /***/ }),
15067 /* 141 */
15068 /***/ (function(module, exports, __webpack_require__) {
15069
15070 "use strict";
15071
15072 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15073     if (k2 === undefined) k2 = k;
15074     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15075 }) : (function(o, m, k, k2) {
15076     if (k2 === undefined) k2 = k;
15077     o[k2] = m[k];
15078 }));
15079 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15080     Object.defineProperty(o, "default", { enumerable: true, value: v });
15081 }) : function(o, v) {
15082     o["default"] = v;
15083 });
15084 var __importStar = (this && this.__importStar) || function (mod) {
15085     if (mod && mod.__esModule) return mod;
15086     var result = {};
15087     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15088     __setModuleDefault(result, mod);
15089     return result;
15090 };
15091 Object.defineProperty(exports, "__esModule", { value: true });
15092 exports.ConfigurePluginCommand = exports.AutoFixCommand = exports.TypeScriptGoToProjectConfigCommand = exports.OpenTsServerLogCommand = exports.ReloadProjectsCommand = void 0;
15093 const coc_nvim_1 = __webpack_require__(1);
15094 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15095 const typeConverters = __importStar(__webpack_require__(37));
15096 const vscode_languageserver_types_1 = __webpack_require__(18);
15097 const modules_1 = __webpack_require__(100);
15098 const helper_1 = __webpack_require__(98);
15099 class ReloadProjectsCommand {
15100     constructor(service) {
15101         this.service = service;
15102         this.id = 'tsserver.reloadProjects';
15103     }
15104     async execute() {
15105         let client = await this.service.getClientHost();
15106         client.reloadProjects();
15107         coc_nvim_1.workspace.showMessage('projects reloaded');
15108     }
15109 }
15110 exports.ReloadProjectsCommand = ReloadProjectsCommand;
15111 class OpenTsServerLogCommand {
15112     constructor(service) {
15113         this.service = service;
15114         this.id = 'tsserver.openTsServerLog';
15115     }
15116     async execute() {
15117         let client = await this.service.getClientHost();
15118         client.serviceClient.openTsServerLogFile(); // tslint:disable-line
15119     }
15120 }
15121 exports.OpenTsServerLogCommand = OpenTsServerLogCommand;
15122 class TypeScriptGoToProjectConfigCommand {
15123     constructor(service) {
15124         this.service = service;
15125         this.id = 'tsserver.goToProjectConfig';
15126     }
15127     async execute() {
15128         let client = await this.service.getClientHost();
15129         let doc = await coc_nvim_1.workspace.document;
15130         let { languageId } = doc.textDocument;
15131         if (client.serviceClient.modeIds.indexOf(languageId) == -1) {
15132             throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`);
15133             return;
15134         }
15135         await goToProjectConfig(client, doc.uri);
15136     }
15137 }
15138 exports.TypeScriptGoToProjectConfigCommand = TypeScriptGoToProjectConfigCommand;
15139 async function goToProjectConfig(clientHost, uri) {
15140     const client = clientHost.serviceClient;
15141     const file = client.toPath(uri);
15142     let res;
15143     try {
15144         res = await client.execute('projectInfo', { file, needFileNameList: false }, vscode_languageserver_protocol_1.CancellationToken.None);
15145     }
15146     catch (_a) {
15147         // noop
15148     }
15149     if (!res || !res.body) {
15150         coc_nvim_1.workspace.showMessage('Could not determine TypeScript or JavaScript project.', 'warning');
15151         return;
15152     }
15153     const { configFileName } = res.body;
15154     if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
15155         await coc_nvim_1.workspace.openResource(coc_nvim_1.Uri.file(configFileName).toString());
15156         return;
15157     }
15158     coc_nvim_1.workspace.showMessage('Config file not found', 'warning');
15159 }
15160 function isImplicitProjectConfigFile(configFileName) {
15161     return configFileName.indexOf('/dev/null/') === 0;
15162 }
15163 const autoFixableDiagnosticCodes = new Set([
15164     2420,
15165     2552,
15166     2304,
15167 ]);
15168 class AutoFixCommand {
15169     constructor(service) {
15170         this.service = service;
15171         this.id = 'tsserver.executeAutofix';
15172     }
15173     async execute() {
15174         if (this.service.state != coc_nvim_1.ServiceStat.Running) {
15175             throw new Error('service not running');
15176             return;
15177         }
15178         let client = await this.service.getClientHost();
15179         let document = await coc_nvim_1.workspace.document;
15180         let handles = await client.handles(document.textDocument);
15181         if (!handles) {
15182             throw new Error(`Document ${document.uri} is not handled by tsserver.`);
15183             return;
15184         }
15185         let file = client.serviceClient.toPath(document.uri);
15186         let diagnostics = coc_nvim_1.diagnosticManager.getDiagnostics(document.uri);
15187         let missingDiagnostics = diagnostics.filter(o => o.code == 2307);
15188         if (missingDiagnostics.length) {
15189             let names = missingDiagnostics.map(o => {
15190                 let ms = o.message.match(/module\s'(.+)'\./);
15191                 return ms ? ms[1] : null;
15192             });
15193             names = names.filter(s => s != null);
15194             if (names.length) {
15195                 modules_1.installModules(document.uri, names).catch(e => {
15196                     console.error(e.message); // tslint:disable-line
15197                 });
15198             }
15199         }
15200         diagnostics = diagnostics.filter(x => autoFixableDiagnosticCodes.has(x.code));
15201         if (diagnostics.length == 0)
15202             return;
15203         diagnostics = diagnostics.reduce((arr, curr) => {
15204             if (curr.code == 2304 && arr.findIndex(o => o.message == curr.message) != -1)
15205                 return arr;
15206             arr.push(curr);
15207             return arr;
15208         }, []);
15209         let edits = [];
15210         let command;
15211         let names = [];
15212         for (let diagnostic of diagnostics) {
15213             const args = Object.assign(Object.assign({}, typeConverters.Range.toFileRangeRequestArgs(file, diagnostic.range)), { errorCodes: [+(diagnostic.code)] });
15214             const response = await client.serviceClient.execute('getCodeFixes', args, vscode_languageserver_protocol_1.CancellationToken.None);
15215             if (response.type !== 'response' || !response.body || response.body.length < 1) {
15216                 if (diagnostic.code == 2304) {
15217                     let { range } = diagnostic;
15218                     let line = document.getline(range.start.line);
15219                     let name = line.slice(range.start.character, range.end.character);
15220                     if (helper_1.nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
15221                         names.push(name);
15222                         edits.push({
15223                             range: vscode_languageserver_types_1.Range.create(0, 0, 0, 0),
15224                             newText: `import ${name} from '${name}'\n`
15225                         });
15226                         command = 'tsserver.organizeImports';
15227                     }
15228                 }
15229                 continue;
15230             }
15231             const fix = response.body[0];
15232             for (let change of fix.changes) {
15233                 if (change.fileName != file)
15234                     continue;
15235                 // change.fileName
15236                 for (let ch of change.textChanges) {
15237                     edits.push({
15238                         range: typeConverters.Range.fromTextSpan(ch),
15239                         newText: ch.newText
15240                     });
15241                 }
15242             }
15243         }
15244         if (edits.length)
15245             await document.applyEdits(edits);
15246         if (command)
15247             coc_nvim_1.commands.executeCommand(command);
15248     }
15249 }
15250 exports.AutoFixCommand = AutoFixCommand;
15251 class ConfigurePluginCommand {
15252     constructor(pluginManager) {
15253         this.pluginManager = pluginManager;
15254         this.id = '_typescript.configurePlugin';
15255     }
15256     execute(pluginId, configuration) {
15257         this.pluginManager.setConfiguration(pluginId, configuration);
15258     }
15259 }
15260 exports.ConfigurePluginCommand = ConfigurePluginCommand;
15261
15262
15263 /***/ }),
15264 /* 142 */
15265 /***/ (function(module, exports, __webpack_require__) {
15266
15267 "use strict";
15268
15269 /*---------------------------------------------------------------------------------------------
15270  *  Copyright (c) Microsoft Corporation. All rights reserved.
15271  *  Licensed under the MIT License. See License.txt in the project root for license information.
15272  *--------------------------------------------------------------------------------------------*/
15273 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15274     if (k2 === undefined) k2 = k;
15275     Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
15276 }) : (function(o, m, k, k2) {
15277     if (k2 === undefined) k2 = k;
15278     o[k2] = m[k];
15279 }));
15280 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15281     Object.defineProperty(o, "default", { enumerable: true, value: v });
15282 }) : function(o, v) {
15283     o["default"] = v;
15284 });
15285 var __importStar = (this && this.__importStar) || function (mod) {
15286     if (mod && mod.__esModule) return mod;
15287     var result = {};
15288     if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
15289     __setModuleDefault(result, mod);
15290     return result;
15291 };
15292 Object.defineProperty(exports, "__esModule", { value: true });
15293 exports.PluginManager = void 0;
15294 const coc_nvim_1 = __webpack_require__(1);
15295 const arrays = __importStar(__webpack_require__(91));
15296 const vscode_languageserver_protocol_1 = __webpack_require__(3);
15297 var TypeScriptServerPlugin;
15298 (function (TypeScriptServerPlugin) {
15299     function equals(a, b) {
15300         return a.path === b.path
15301             && a.name === b.name
15302             && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
15303             && arrays.equals(a.languages, b.languages);
15304     }
15305     TypeScriptServerPlugin.equals = equals;
15306 })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
15307 class PluginManager {
15308     constructor() {
15309         this._pluginConfigurations = new Map();
15310         this._disposables = [];
15311         this._onDidUpdatePlugins = this._register(new vscode_languageserver_protocol_1.Emitter());
15312         this.onDidChangePlugins = this._onDidUpdatePlugins.event;
15313         this._onDidUpdateConfig = this._register(new vscode_languageserver_protocol_1.Emitter());
15314         this.onDidUpdateConfig = this._onDidUpdateConfig.event;
15315         let loadPlugins = () => {
15316             if (!this._plugins) {
15317                 return;
15318             }
15319             const newPlugins = this.readPlugins();
15320             if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
15321                 this._plugins = newPlugins;
15322                 this._onDidUpdatePlugins.fire(this);
15323             }
15324         };
15325         coc_nvim_1.extensions.onDidActiveExtension(loadPlugins, undefined, this._disposables);
15326         coc_nvim_1.extensions.onDidUnloadExtension(loadPlugins, undefined, this._disposables);
15327     }
15328     dispose() {
15329         coc_nvim_1.disposeAll(this._disposables);
15330     }
15331     get plugins() {
15332         if (!this._plugins) {
15333             this._plugins = this.readPlugins();
15334         }
15335         return arrays.flatten(Array.from(this._plugins.values()));
15336     }
15337     _register(value) {
15338         this._disposables.push(value);
15339         return value;
15340     }
15341     setConfiguration(pluginId, config) {
15342         this._pluginConfigurations.set(pluginId, config);
15343         this._onDidUpdateConfig.fire({ pluginId, config });
15344     }
15345     configurations() {
15346         return this._pluginConfigurations.entries();
15347     }
15348     readPlugins() {
15349         const pluginMap = new Map();
15350         for (const extension of coc_nvim_1.extensions.all) {
15351             const pack = extension.packageJSON;
15352             if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
15353                 const plugins = [];
15354                 for (const plugin of pack.contributes.typescriptServerPlugins) {
15355                     plugins.push({
15356                         name: plugin.name,
15357                         enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
15358                         path: extension.extensionPath,
15359                         languages: Array.isArray(plugin.languages) ? plugin.languages : [],
15360                     });
15361                 }
15362                 if (plugins.length) {
15363                     pluginMap.set(extension.id, plugins);
15364                 }
15365             }
15366         }
15367         return pluginMap;
15368     }
15369 }
15370 exports.PluginManager = PluginManager;
15371
15372
15373 /***/ })
15374 /******/ ])));