.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-tsserver / lib / index.js
1 var __create = Object.create;
2 var __defProp = Object.defineProperty;
3 var __getProtoOf = Object.getPrototypeOf;
4 var __hasOwnProp = Object.prototype.hasOwnProperty;
5 var __getOwnPropNames = Object.getOwnPropertyNames;
6 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7 var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
8 var __commonJS = (callback, module2) => () => {
9   if (!module2) {
10     module2 = {exports: {}};
11     callback(module2.exports, module2);
12   }
13   return module2.exports;
14 };
15 var __export = (target, all) => {
16   __markAsModule(target);
17   for (var name in all)
18     __defProp(target, name, {get: all[name], enumerable: true});
19 };
20 var __exportStar = (target, module2, desc) => {
21   __markAsModule(target);
22   if (module2 && typeof module2 === "object" || typeof module2 === "function") {
23     for (let key of __getOwnPropNames(module2))
24       if (!__hasOwnProp.call(target, key) && key !== "default")
25         __defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
26   }
27   return target;
28 };
29 var __toModule = (module2) => {
30   if (module2 && module2.__esModule)
31     return module2;
32   return __exportStar(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", {value: module2, enumerable: true}), module2);
33 };
34
35 // node_modules/vscode-jsonrpc/lib/is.js
36 var require_is = __commonJS((exports2) => {
37   "use strict";
38   Object.defineProperty(exports2, "__esModule", {value: true});
39   function boolean2(value) {
40     return value === true || value === false;
41   }
42   exports2.boolean = boolean2;
43   function string2(value) {
44     return typeof value === "string" || value instanceof String;
45   }
46   exports2.string = string2;
47   function number(value) {
48     return typeof value === "number" || value instanceof Number;
49   }
50   exports2.number = number;
51   function error(value) {
52     return value instanceof Error;
53   }
54   exports2.error = error;
55   function func(value) {
56     return typeof value === "function";
57   }
58   exports2.func = func;
59   function array(value) {
60     return Array.isArray(value);
61   }
62   exports2.array = array;
63   function stringArray(value) {
64     return array(value) && value.every((elem) => string2(elem));
65   }
66   exports2.stringArray = stringArray;
67 });
68
69 // node_modules/vscode-jsonrpc/lib/messages.js
70 var require_messages = __commonJS((exports2) => {
71   "use strict";
72   Object.defineProperty(exports2, "__esModule", {value: true});
73   var is2 = require_is();
74   var ErrorCodes;
75   (function(ErrorCodes2) {
76     ErrorCodes2.ParseError = -32700;
77     ErrorCodes2.InvalidRequest = -32600;
78     ErrorCodes2.MethodNotFound = -32601;
79     ErrorCodes2.InvalidParams = -32602;
80     ErrorCodes2.InternalError = -32603;
81     ErrorCodes2.serverErrorStart = -32099;
82     ErrorCodes2.serverErrorEnd = -32e3;
83     ErrorCodes2.ServerNotInitialized = -32002;
84     ErrorCodes2.UnknownErrorCode = -32001;
85     ErrorCodes2.RequestCancelled = -32800;
86     ErrorCodes2.ContentModified = -32801;
87     ErrorCodes2.MessageWriteError = 1;
88     ErrorCodes2.MessageReadError = 2;
89   })(ErrorCodes = exports2.ErrorCodes || (exports2.ErrorCodes = {}));
90   var ResponseError = class extends Error {
91     constructor(code, message, data) {
92       super(message);
93       this.code = is2.number(code) ? code : ErrorCodes.UnknownErrorCode;
94       this.data = data;
95       Object.setPrototypeOf(this, ResponseError.prototype);
96     }
97     toJson() {
98       return {
99         code: this.code,
100         message: this.message,
101         data: this.data
102       };
103     }
104   };
105   exports2.ResponseError = ResponseError;
106   var AbstractMessageType = class {
107     constructor(_method, _numberOfParams) {
108       this._method = _method;
109       this._numberOfParams = _numberOfParams;
110     }
111     get method() {
112       return this._method;
113     }
114     get numberOfParams() {
115       return this._numberOfParams;
116     }
117   };
118   exports2.AbstractMessageType = AbstractMessageType;
119   var RequestType0 = class extends AbstractMessageType {
120     constructor(method) {
121       super(method, 0);
122     }
123   };
124   exports2.RequestType0 = RequestType0;
125   var RequestType = class extends AbstractMessageType {
126     constructor(method) {
127       super(method, 1);
128     }
129   };
130   exports2.RequestType = RequestType;
131   var RequestType1 = class extends AbstractMessageType {
132     constructor(method) {
133       super(method, 1);
134     }
135   };
136   exports2.RequestType1 = RequestType1;
137   var RequestType2 = class extends AbstractMessageType {
138     constructor(method) {
139       super(method, 2);
140     }
141   };
142   exports2.RequestType2 = RequestType2;
143   var RequestType3 = class extends AbstractMessageType {
144     constructor(method) {
145       super(method, 3);
146     }
147   };
148   exports2.RequestType3 = RequestType3;
149   var RequestType4 = class extends AbstractMessageType {
150     constructor(method) {
151       super(method, 4);
152     }
153   };
154   exports2.RequestType4 = RequestType4;
155   var RequestType5 = class extends AbstractMessageType {
156     constructor(method) {
157       super(method, 5);
158     }
159   };
160   exports2.RequestType5 = RequestType5;
161   var RequestType6 = class extends AbstractMessageType {
162     constructor(method) {
163       super(method, 6);
164     }
165   };
166   exports2.RequestType6 = RequestType6;
167   var RequestType7 = class extends AbstractMessageType {
168     constructor(method) {
169       super(method, 7);
170     }
171   };
172   exports2.RequestType7 = RequestType7;
173   var RequestType8 = class extends AbstractMessageType {
174     constructor(method) {
175       super(method, 8);
176     }
177   };
178   exports2.RequestType8 = RequestType8;
179   var RequestType9 = class extends AbstractMessageType {
180     constructor(method) {
181       super(method, 9);
182     }
183   };
184   exports2.RequestType9 = RequestType9;
185   var NotificationType = class extends AbstractMessageType {
186     constructor(method) {
187       super(method, 1);
188       this._ = void 0;
189     }
190   };
191   exports2.NotificationType = NotificationType;
192   var NotificationType0 = class extends AbstractMessageType {
193     constructor(method) {
194       super(method, 0);
195     }
196   };
197   exports2.NotificationType0 = NotificationType0;
198   var NotificationType1 = class extends AbstractMessageType {
199     constructor(method) {
200       super(method, 1);
201     }
202   };
203   exports2.NotificationType1 = NotificationType1;
204   var NotificationType2 = class extends AbstractMessageType {
205     constructor(method) {
206       super(method, 2);
207     }
208   };
209   exports2.NotificationType2 = NotificationType2;
210   var NotificationType3 = class extends AbstractMessageType {
211     constructor(method) {
212       super(method, 3);
213     }
214   };
215   exports2.NotificationType3 = NotificationType3;
216   var NotificationType4 = class extends AbstractMessageType {
217     constructor(method) {
218       super(method, 4);
219     }
220   };
221   exports2.NotificationType4 = NotificationType4;
222   var NotificationType5 = class extends AbstractMessageType {
223     constructor(method) {
224       super(method, 5);
225     }
226   };
227   exports2.NotificationType5 = NotificationType5;
228   var NotificationType6 = class extends AbstractMessageType {
229     constructor(method) {
230       super(method, 6);
231     }
232   };
233   exports2.NotificationType6 = NotificationType6;
234   var NotificationType7 = class extends AbstractMessageType {
235     constructor(method) {
236       super(method, 7);
237     }
238   };
239   exports2.NotificationType7 = NotificationType7;
240   var NotificationType8 = class extends AbstractMessageType {
241     constructor(method) {
242       super(method, 8);
243     }
244   };
245   exports2.NotificationType8 = NotificationType8;
246   var NotificationType9 = class extends AbstractMessageType {
247     constructor(method) {
248       super(method, 9);
249     }
250   };
251   exports2.NotificationType9 = NotificationType9;
252   function isRequestMessage(message) {
253     let candidate = message;
254     return candidate && is2.string(candidate.method) && (is2.string(candidate.id) || is2.number(candidate.id));
255   }
256   exports2.isRequestMessage = isRequestMessage;
257   function isNotificationMessage(message) {
258     let candidate = message;
259     return candidate && is2.string(candidate.method) && message.id === void 0;
260   }
261   exports2.isNotificationMessage = isNotificationMessage;
262   function isResponseMessage(message) {
263     let candidate = message;
264     return candidate && (candidate.result !== void 0 || !!candidate.error) && (is2.string(candidate.id) || is2.number(candidate.id) || candidate.id === null);
265   }
266   exports2.isResponseMessage = isResponseMessage;
267 });
268
269 // node_modules/vscode-jsonrpc/lib/events.js
270 var require_events = __commonJS((exports2) => {
271   "use strict";
272   Object.defineProperty(exports2, "__esModule", {value: true});
273   var Disposable12;
274   (function(Disposable13) {
275     function create(func) {
276       return {
277         dispose: func
278       };
279     }
280     Disposable13.create = create;
281   })(Disposable12 = exports2.Disposable || (exports2.Disposable = {}));
282   var Event5;
283   (function(Event6) {
284     const _disposable = {dispose() {
285     }};
286     Event6.None = function() {
287       return _disposable;
288     };
289   })(Event5 = exports2.Event || (exports2.Event = {}));
290   var CallbackList = class {
291     add(callback, context = null, bucket) {
292       if (!this._callbacks) {
293         this._callbacks = [];
294         this._contexts = [];
295       }
296       this._callbacks.push(callback);
297       this._contexts.push(context);
298       if (Array.isArray(bucket)) {
299         bucket.push({dispose: () => this.remove(callback, context)});
300       }
301     }
302     remove(callback, context = null) {
303       if (!this._callbacks) {
304         return;
305       }
306       var foundCallbackWithDifferentContext = false;
307       for (var i = 0, len = this._callbacks.length; i < len; i++) {
308         if (this._callbacks[i] === callback) {
309           if (this._contexts[i] === context) {
310             this._callbacks.splice(i, 1);
311             this._contexts.splice(i, 1);
312             return;
313           } else {
314             foundCallbackWithDifferentContext = true;
315           }
316         }
317       }
318       if (foundCallbackWithDifferentContext) {
319         throw new Error("When adding a listener with a context, you should remove it with the same context");
320       }
321     }
322     invoke(...args) {
323       if (!this._callbacks) {
324         return [];
325       }
326       var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
327       for (var i = 0, len = callbacks.length; i < len; i++) {
328         try {
329           ret.push(callbacks[i].apply(contexts[i], args));
330         } catch (e) {
331           console.error(e);
332         }
333       }
334       return ret;
335     }
336     isEmpty() {
337       return !this._callbacks || this._callbacks.length === 0;
338     }
339     dispose() {
340       this._callbacks = void 0;
341       this._contexts = void 0;
342     }
343   };
344   var Emitter6 = class {
345     constructor(_options) {
346       this._options = _options;
347     }
348     get event() {
349       if (!this._event) {
350         this._event = (listener, thisArgs, disposables) => {
351           if (!this._callbacks) {
352             this._callbacks = new CallbackList();
353           }
354           if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
355             this._options.onFirstListenerAdd(this);
356           }
357           this._callbacks.add(listener, thisArgs);
358           let result;
359           result = {
360             dispose: () => {
361               this._callbacks.remove(listener, thisArgs);
362               result.dispose = Emitter6._noop;
363               if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
364                 this._options.onLastListenerRemove(this);
365               }
366             }
367           };
368           if (Array.isArray(disposables)) {
369             disposables.push(result);
370           }
371           return result;
372         };
373       }
374       return this._event;
375     }
376     fire(event) {
377       if (this._callbacks) {
378         this._callbacks.invoke.call(this._callbacks, event);
379       }
380     }
381     dispose() {
382       if (this._callbacks) {
383         this._callbacks.dispose();
384         this._callbacks = void 0;
385       }
386     }
387   };
388   exports2.Emitter = Emitter6;
389   Emitter6._noop = function() {
390   };
391 });
392
393 // node_modules/vscode-jsonrpc/lib/messageReader.js
394 var require_messageReader = __commonJS((exports2) => {
395   "use strict";
396   Object.defineProperty(exports2, "__esModule", {value: true});
397   var events_1 = require_events();
398   var Is = require_is();
399   var DefaultSize2 = 8192;
400   var CR = Buffer.from("\r", "ascii")[0];
401   var LF = Buffer.from("\n", "ascii")[0];
402   var CRLF = "\r\n";
403   var MessageBuffer = class {
404     constructor(encoding = "utf8") {
405       this.encoding = encoding;
406       this.index = 0;
407       this.buffer = Buffer.allocUnsafe(DefaultSize2);
408     }
409     append(chunk) {
410       var toAppend = chunk;
411       if (typeof chunk === "string") {
412         var str = chunk;
413         var bufferLen = Buffer.byteLength(str, this.encoding);
414         toAppend = Buffer.allocUnsafe(bufferLen);
415         toAppend.write(str, 0, bufferLen, this.encoding);
416       }
417       if (this.buffer.length - this.index >= toAppend.length) {
418         toAppend.copy(this.buffer, this.index, 0, toAppend.length);
419       } else {
420         var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize2) + 1) * DefaultSize2;
421         if (this.index === 0) {
422           this.buffer = Buffer.allocUnsafe(newSize);
423           toAppend.copy(this.buffer, 0, 0, toAppend.length);
424         } else {
425           this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
426         }
427       }
428       this.index += toAppend.length;
429     }
430     tryReadHeaders() {
431       let result = void 0;
432       let current = 0;
433       while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
434         current++;
435       }
436       if (current + 3 >= this.index) {
437         return result;
438       }
439       result = Object.create(null);
440       let headers = this.buffer.toString("ascii", 0, current).split(CRLF);
441       headers.forEach((header) => {
442         let index = header.indexOf(":");
443         if (index === -1) {
444           throw new Error("Message header must separate key and value using :");
445         }
446         let key = header.substr(0, index);
447         let value = header.substr(index + 1).trim();
448         result[key] = value;
449       });
450       let nextStart = current + 4;
451       this.buffer = this.buffer.slice(nextStart);
452       this.index = this.index - nextStart;
453       return result;
454     }
455     tryReadContent(length) {
456       if (this.index < length) {
457         return null;
458       }
459       let result = this.buffer.toString(this.encoding, 0, length);
460       let nextStart = length;
461       this.buffer.copy(this.buffer, 0, nextStart);
462       this.index = this.index - nextStart;
463       return result;
464     }
465     get numberOfBytes() {
466       return this.index;
467     }
468   };
469   var MessageReader;
470   (function(MessageReader2) {
471     function is2(value) {
472       let candidate = value;
473       return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
474     }
475     MessageReader2.is = is2;
476   })(MessageReader = exports2.MessageReader || (exports2.MessageReader = {}));
477   var AbstractMessageReader = class {
478     constructor() {
479       this.errorEmitter = new events_1.Emitter();
480       this.closeEmitter = new events_1.Emitter();
481       this.partialMessageEmitter = new events_1.Emitter();
482     }
483     dispose() {
484       this.errorEmitter.dispose();
485       this.closeEmitter.dispose();
486     }
487     get onError() {
488       return this.errorEmitter.event;
489     }
490     fireError(error) {
491       this.errorEmitter.fire(this.asError(error));
492     }
493     get onClose() {
494       return this.closeEmitter.event;
495     }
496     fireClose() {
497       this.closeEmitter.fire(void 0);
498     }
499     get onPartialMessage() {
500       return this.partialMessageEmitter.event;
501     }
502     firePartialMessage(info) {
503       this.partialMessageEmitter.fire(info);
504     }
505     asError(error) {
506       if (error instanceof Error) {
507         return error;
508       } else {
509         return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
510       }
511     }
512   };
513   exports2.AbstractMessageReader = AbstractMessageReader;
514   var StreamMessageReader = class extends AbstractMessageReader {
515     constructor(readable, encoding = "utf8") {
516       super();
517       this.readable = readable;
518       this.buffer = new MessageBuffer(encoding);
519       this._partialMessageTimeout = 1e4;
520     }
521     set partialMessageTimeout(timeout) {
522       this._partialMessageTimeout = timeout;
523     }
524     get partialMessageTimeout() {
525       return this._partialMessageTimeout;
526     }
527     listen(callback) {
528       this.nextMessageLength = -1;
529       this.messageToken = 0;
530       this.partialMessageTimer = void 0;
531       this.callback = callback;
532       this.readable.on("data", (data) => {
533         this.onData(data);
534       });
535       this.readable.on("error", (error) => this.fireError(error));
536       this.readable.on("close", () => this.fireClose());
537     }
538     onData(data) {
539       this.buffer.append(data);
540       while (true) {
541         if (this.nextMessageLength === -1) {
542           let headers = this.buffer.tryReadHeaders();
543           if (!headers) {
544             return;
545           }
546           let contentLength = headers["Content-Length"];
547           if (!contentLength) {
548             throw new Error("Header must provide a Content-Length property.");
549           }
550           let length = parseInt(contentLength);
551           if (isNaN(length)) {
552             throw new Error("Content-Length value must be a number.");
553           }
554           this.nextMessageLength = length;
555         }
556         var msg = this.buffer.tryReadContent(this.nextMessageLength);
557         if (msg === null) {
558           this.setPartialMessageTimer();
559           return;
560         }
561         this.clearPartialMessageTimer();
562         this.nextMessageLength = -1;
563         this.messageToken++;
564         var json = JSON.parse(msg);
565         this.callback(json);
566       }
567     }
568     clearPartialMessageTimer() {
569       if (this.partialMessageTimer) {
570         clearTimeout(this.partialMessageTimer);
571         this.partialMessageTimer = void 0;
572       }
573     }
574     setPartialMessageTimer() {
575       this.clearPartialMessageTimer();
576       if (this._partialMessageTimeout <= 0) {
577         return;
578       }
579       this.partialMessageTimer = setTimeout((token, timeout) => {
580         this.partialMessageTimer = void 0;
581         if (token === this.messageToken) {
582           this.firePartialMessage({messageToken: token, waitingTime: timeout});
583           this.setPartialMessageTimer();
584         }
585       }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
586     }
587   };
588   exports2.StreamMessageReader = StreamMessageReader;
589   var IPCMessageReader = class extends AbstractMessageReader {
590     constructor(process2) {
591       super();
592       this.process = process2;
593       let eventEmitter = this.process;
594       eventEmitter.on("error", (error) => this.fireError(error));
595       eventEmitter.on("close", () => this.fireClose());
596     }
597     listen(callback) {
598       this.process.on("message", callback);
599     }
600   };
601   exports2.IPCMessageReader = IPCMessageReader;
602   var SocketMessageReader = class extends StreamMessageReader {
603     constructor(socket, encoding = "utf-8") {
604       super(socket, encoding);
605     }
606   };
607   exports2.SocketMessageReader = SocketMessageReader;
608 });
609
610 // node_modules/vscode-jsonrpc/lib/messageWriter.js
611 var require_messageWriter = __commonJS((exports2) => {
612   "use strict";
613   Object.defineProperty(exports2, "__esModule", {value: true});
614   var events_1 = require_events();
615   var Is = require_is();
616   var ContentLength2 = "Content-Length: ";
617   var CRLF = "\r\n";
618   var MessageWriter;
619   (function(MessageWriter2) {
620     function is2(value) {
621       let candidate = value;
622       return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
623     }
624     MessageWriter2.is = is2;
625   })(MessageWriter = exports2.MessageWriter || (exports2.MessageWriter = {}));
626   var AbstractMessageWriter = class {
627     constructor() {
628       this.errorEmitter = new events_1.Emitter();
629       this.closeEmitter = new events_1.Emitter();
630     }
631     dispose() {
632       this.errorEmitter.dispose();
633       this.closeEmitter.dispose();
634     }
635     get onError() {
636       return this.errorEmitter.event;
637     }
638     fireError(error, message, count) {
639       this.errorEmitter.fire([this.asError(error), message, count]);
640     }
641     get onClose() {
642       return this.closeEmitter.event;
643     }
644     fireClose() {
645       this.closeEmitter.fire(void 0);
646     }
647     asError(error) {
648       if (error instanceof Error) {
649         return error;
650       } else {
651         return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
652       }
653     }
654   };
655   exports2.AbstractMessageWriter = AbstractMessageWriter;
656   var StreamMessageWriter = class extends AbstractMessageWriter {
657     constructor(writable, encoding = "utf8") {
658       super();
659       this.writable = writable;
660       this.encoding = encoding;
661       this.errorCount = 0;
662       this.writable.on("error", (error) => this.fireError(error));
663       this.writable.on("close", () => this.fireClose());
664     }
665     write(msg) {
666       let json = JSON.stringify(msg);
667       let contentLength = Buffer.byteLength(json, this.encoding);
668       let headers = [
669         ContentLength2,
670         contentLength.toString(),
671         CRLF,
672         CRLF
673       ];
674       try {
675         this.writable.write(headers.join(""), "ascii");
676         this.writable.write(json, this.encoding);
677         this.errorCount = 0;
678       } catch (error) {
679         this.errorCount++;
680         this.fireError(error, msg, this.errorCount);
681       }
682     }
683   };
684   exports2.StreamMessageWriter = StreamMessageWriter;
685   var IPCMessageWriter = class extends AbstractMessageWriter {
686     constructor(process2) {
687       super();
688       this.process = process2;
689       this.errorCount = 0;
690       this.queue = [];
691       this.sending = false;
692       let eventEmitter = this.process;
693       eventEmitter.on("error", (error) => this.fireError(error));
694       eventEmitter.on("close", () => this.fireClose);
695     }
696     write(msg) {
697       if (!this.sending && this.queue.length === 0) {
698         this.doWriteMessage(msg);
699       } else {
700         this.queue.push(msg);
701       }
702     }
703     doWriteMessage(msg) {
704       try {
705         if (this.process.send) {
706           this.sending = true;
707           this.process.send(msg, void 0, void 0, (error) => {
708             this.sending = false;
709             if (error) {
710               this.errorCount++;
711               this.fireError(error, msg, this.errorCount);
712             } else {
713               this.errorCount = 0;
714             }
715             if (this.queue.length > 0) {
716               this.doWriteMessage(this.queue.shift());
717             }
718           });
719         }
720       } catch (error) {
721         this.errorCount++;
722         this.fireError(error, msg, this.errorCount);
723       }
724     }
725   };
726   exports2.IPCMessageWriter = IPCMessageWriter;
727   var SocketMessageWriter = class extends AbstractMessageWriter {
728     constructor(socket, encoding = "utf8") {
729       super();
730       this.socket = socket;
731       this.queue = [];
732       this.sending = false;
733       this.encoding = encoding;
734       this.errorCount = 0;
735       this.socket.on("error", (error) => this.fireError(error));
736       this.socket.on("close", () => this.fireClose());
737     }
738     dispose() {
739       super.dispose();
740       this.socket.destroy();
741     }
742     write(msg) {
743       if (!this.sending && this.queue.length === 0) {
744         this.doWriteMessage(msg);
745       } else {
746         this.queue.push(msg);
747       }
748     }
749     doWriteMessage(msg) {
750       let json = JSON.stringify(msg);
751       let contentLength = Buffer.byteLength(json, this.encoding);
752       let headers = [
753         ContentLength2,
754         contentLength.toString(),
755         CRLF,
756         CRLF
757       ];
758       try {
759         this.sending = true;
760         this.socket.write(headers.join(""), "ascii", (error) => {
761           if (error) {
762             this.handleError(error, msg);
763           }
764           try {
765             this.socket.write(json, this.encoding, (error2) => {
766               this.sending = false;
767               if (error2) {
768                 this.handleError(error2, msg);
769               } else {
770                 this.errorCount = 0;
771               }
772               if (this.queue.length > 0) {
773                 this.doWriteMessage(this.queue.shift());
774               }
775             });
776           } catch (error2) {
777             this.handleError(error2, msg);
778           }
779         });
780       } catch (error) {
781         this.handleError(error, msg);
782       }
783     }
784     handleError(error, msg) {
785       this.errorCount++;
786       this.fireError(error, msg, this.errorCount);
787     }
788   };
789   exports2.SocketMessageWriter = SocketMessageWriter;
790 });
791
792 // node_modules/vscode-jsonrpc/lib/cancellation.js
793 var require_cancellation = __commonJS((exports2) => {
794   "use strict";
795   Object.defineProperty(exports2, "__esModule", {value: true});
796   var events_1 = require_events();
797   var Is = require_is();
798   var CancellationToken19;
799   (function(CancellationToken20) {
800     CancellationToken20.None = Object.freeze({
801       isCancellationRequested: false,
802       onCancellationRequested: events_1.Event.None
803     });
804     CancellationToken20.Cancelled = Object.freeze({
805       isCancellationRequested: true,
806       onCancellationRequested: events_1.Event.None
807     });
808     function is2(value) {
809       let candidate = value;
810       return candidate && (candidate === CancellationToken20.None || candidate === CancellationToken20.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
811     }
812     CancellationToken20.is = is2;
813   })(CancellationToken19 = exports2.CancellationToken || (exports2.CancellationToken = {}));
814   var shortcutEvent = Object.freeze(function(callback, context) {
815     let handle = setTimeout(callback.bind(context), 0);
816     return {dispose() {
817       clearTimeout(handle);
818     }};
819   });
820   var MutableToken = class {
821     constructor() {
822       this._isCancelled = false;
823     }
824     cancel() {
825       if (!this._isCancelled) {
826         this._isCancelled = true;
827         if (this._emitter) {
828           this._emitter.fire(void 0);
829           this.dispose();
830         }
831       }
832     }
833     get isCancellationRequested() {
834       return this._isCancelled;
835     }
836     get onCancellationRequested() {
837       if (this._isCancelled) {
838         return shortcutEvent;
839       }
840       if (!this._emitter) {
841         this._emitter = new events_1.Emitter();
842       }
843       return this._emitter.event;
844     }
845     dispose() {
846       if (this._emitter) {
847         this._emitter.dispose();
848         this._emitter = void 0;
849       }
850     }
851   };
852   var CancellationTokenSource3 = class {
853     get token() {
854       if (!this._token) {
855         this._token = new MutableToken();
856       }
857       return this._token;
858     }
859     cancel() {
860       if (!this._token) {
861         this._token = CancellationToken19.Cancelled;
862       } else {
863         this._token.cancel();
864       }
865     }
866     dispose() {
867       if (!this._token) {
868         this._token = CancellationToken19.None;
869       } else if (this._token instanceof MutableToken) {
870         this._token.dispose();
871       }
872     }
873   };
874   exports2.CancellationTokenSource = CancellationTokenSource3;
875 });
876
877 // node_modules/vscode-jsonrpc/lib/linkedMap.js
878 var require_linkedMap = __commonJS((exports2) => {
879   "use strict";
880   Object.defineProperty(exports2, "__esModule", {value: true});
881   var Touch;
882   (function(Touch2) {
883     Touch2.None = 0;
884     Touch2.First = 1;
885     Touch2.Last = 2;
886   })(Touch = exports2.Touch || (exports2.Touch = {}));
887   var LinkedMap = class {
888     constructor() {
889       this._map = new Map();
890       this._head = void 0;
891       this._tail = void 0;
892       this._size = 0;
893     }
894     clear() {
895       this._map.clear();
896       this._head = void 0;
897       this._tail = void 0;
898       this._size = 0;
899     }
900     isEmpty() {
901       return !this._head && !this._tail;
902     }
903     get size() {
904       return this._size;
905     }
906     has(key) {
907       return this._map.has(key);
908     }
909     get(key) {
910       const item = this._map.get(key);
911       if (!item) {
912         return void 0;
913       }
914       return item.value;
915     }
916     set(key, value, touch = Touch.None) {
917       let item = this._map.get(key);
918       if (item) {
919         item.value = value;
920         if (touch !== Touch.None) {
921           this.touch(item, touch);
922         }
923       } else {
924         item = {key, value, next: void 0, previous: void 0};
925         switch (touch) {
926           case Touch.None:
927             this.addItemLast(item);
928             break;
929           case Touch.First:
930             this.addItemFirst(item);
931             break;
932           case Touch.Last:
933             this.addItemLast(item);
934             break;
935           default:
936             this.addItemLast(item);
937             break;
938         }
939         this._map.set(key, item);
940         this._size++;
941       }
942     }
943     delete(key) {
944       const item = this._map.get(key);
945       if (!item) {
946         return false;
947       }
948       this._map.delete(key);
949       this.removeItem(item);
950       this._size--;
951       return true;
952     }
953     shift() {
954       if (!this._head && !this._tail) {
955         return void 0;
956       }
957       if (!this._head || !this._tail) {
958         throw new Error("Invalid list");
959       }
960       const item = this._head;
961       this._map.delete(item.key);
962       this.removeItem(item);
963       this._size--;
964       return item.value;
965     }
966     forEach(callbackfn, thisArg) {
967       let current = this._head;
968       while (current) {
969         if (thisArg) {
970           callbackfn.bind(thisArg)(current.value, current.key, this);
971         } else {
972           callbackfn(current.value, current.key, this);
973         }
974         current = current.next;
975       }
976     }
977     forEachReverse(callbackfn, thisArg) {
978       let current = this._tail;
979       while (current) {
980         if (thisArg) {
981           callbackfn.bind(thisArg)(current.value, current.key, this);
982         } else {
983           callbackfn(current.value, current.key, this);
984         }
985         current = current.previous;
986       }
987     }
988     values() {
989       let result = [];
990       let current = this._head;
991       while (current) {
992         result.push(current.value);
993         current = current.next;
994       }
995       return result;
996     }
997     keys() {
998       let result = [];
999       let current = this._head;
1000       while (current) {
1001         result.push(current.key);
1002         current = current.next;
1003       }
1004       return result;
1005     }
1006     addItemFirst(item) {
1007       if (!this._head && !this._tail) {
1008         this._tail = item;
1009       } else if (!this._head) {
1010         throw new Error("Invalid list");
1011       } else {
1012         item.next = this._head;
1013         this._head.previous = item;
1014       }
1015       this._head = item;
1016     }
1017     addItemLast(item) {
1018       if (!this._head && !this._tail) {
1019         this._head = item;
1020       } else if (!this._tail) {
1021         throw new Error("Invalid list");
1022       } else {
1023         item.previous = this._tail;
1024         this._tail.next = item;
1025       }
1026       this._tail = item;
1027     }
1028     removeItem(item) {
1029       if (item === this._head && item === this._tail) {
1030         this._head = void 0;
1031         this._tail = void 0;
1032       } else if (item === this._head) {
1033         this._head = item.next;
1034       } else if (item === this._tail) {
1035         this._tail = item.previous;
1036       } else {
1037         const next = item.next;
1038         const previous = item.previous;
1039         if (!next || !previous) {
1040           throw new Error("Invalid list");
1041         }
1042         next.previous = previous;
1043         previous.next = next;
1044       }
1045     }
1046     touch(item, touch) {
1047       if (!this._head || !this._tail) {
1048         throw new Error("Invalid list");
1049       }
1050       if (touch !== Touch.First && touch !== Touch.Last) {
1051         return;
1052       }
1053       if (touch === Touch.First) {
1054         if (item === this._head) {
1055           return;
1056         }
1057         const next = item.next;
1058         const previous = item.previous;
1059         if (item === this._tail) {
1060           previous.next = void 0;
1061           this._tail = previous;
1062         } else {
1063           next.previous = previous;
1064           previous.next = next;
1065         }
1066         item.previous = void 0;
1067         item.next = this._head;
1068         this._head.previous = item;
1069         this._head = item;
1070       } else if (touch === Touch.Last) {
1071         if (item === this._tail) {
1072           return;
1073         }
1074         const next = item.next;
1075         const previous = item.previous;
1076         if (item === this._head) {
1077           next.previous = void 0;
1078           this._head = next;
1079         } else {
1080           next.previous = previous;
1081           previous.next = next;
1082         }
1083         item.next = void 0;
1084         item.previous = this._tail;
1085         this._tail.next = item;
1086         this._tail = item;
1087       }
1088     }
1089   };
1090   exports2.LinkedMap = LinkedMap;
1091 });
1092
1093 // node_modules/vscode-jsonrpc/lib/pipeSupport.js
1094 var require_pipeSupport = __commonJS((exports2) => {
1095   "use strict";
1096   Object.defineProperty(exports2, "__esModule", {value: true});
1097   var path_1 = require("path");
1098   var os_1 = require("os");
1099   var crypto_1 = require("crypto");
1100   var net_1 = require("net");
1101   var messageReader_1 = require_messageReader();
1102   var messageWriter_1 = require_messageWriter();
1103   function generateRandomPipeName() {
1104     const randomSuffix = crypto_1.randomBytes(21).toString("hex");
1105     if (process.platform === "win32") {
1106       return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
1107     } else {
1108       return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
1109     }
1110   }
1111   exports2.generateRandomPipeName = generateRandomPipeName;
1112   function createClientPipeTransport(pipeName, encoding = "utf-8") {
1113     let connectResolve;
1114     let connected = new Promise((resolve, _reject) => {
1115       connectResolve = resolve;
1116     });
1117     return new Promise((resolve, reject) => {
1118       let server = net_1.createServer((socket) => {
1119         server.close();
1120         connectResolve([
1121           new messageReader_1.SocketMessageReader(socket, encoding),
1122           new messageWriter_1.SocketMessageWriter(socket, encoding)
1123         ]);
1124       });
1125       server.on("error", reject);
1126       server.listen(pipeName, () => {
1127         server.removeListener("error", reject);
1128         resolve({
1129           onConnected: () => {
1130             return connected;
1131           }
1132         });
1133       });
1134     });
1135   }
1136   exports2.createClientPipeTransport = createClientPipeTransport;
1137   function createServerPipeTransport(pipeName, encoding = "utf-8") {
1138     const socket = net_1.createConnection(pipeName);
1139     return [
1140       new messageReader_1.SocketMessageReader(socket, encoding),
1141       new messageWriter_1.SocketMessageWriter(socket, encoding)
1142     ];
1143   }
1144   exports2.createServerPipeTransport = createServerPipeTransport;
1145 });
1146
1147 // node_modules/vscode-jsonrpc/lib/socketSupport.js
1148 var require_socketSupport = __commonJS((exports2) => {
1149   "use strict";
1150   Object.defineProperty(exports2, "__esModule", {value: true});
1151   var net_1 = require("net");
1152   var messageReader_1 = require_messageReader();
1153   var messageWriter_1 = require_messageWriter();
1154   function createClientSocketTransport(port, encoding = "utf-8") {
1155     let connectResolve;
1156     let connected = new Promise((resolve, _reject) => {
1157       connectResolve = resolve;
1158     });
1159     return new Promise((resolve, reject) => {
1160       let server = net_1.createServer((socket) => {
1161         server.close();
1162         connectResolve([
1163           new messageReader_1.SocketMessageReader(socket, encoding),
1164           new messageWriter_1.SocketMessageWriter(socket, encoding)
1165         ]);
1166       });
1167       server.on("error", reject);
1168       server.listen(port, "127.0.0.1", () => {
1169         server.removeListener("error", reject);
1170         resolve({
1171           onConnected: () => {
1172             return connected;
1173           }
1174         });
1175       });
1176     });
1177   }
1178   exports2.createClientSocketTransport = createClientSocketTransport;
1179   function createServerSocketTransport(port, encoding = "utf-8") {
1180     const socket = net_1.createConnection(port, "127.0.0.1");
1181     return [
1182       new messageReader_1.SocketMessageReader(socket, encoding),
1183       new messageWriter_1.SocketMessageWriter(socket, encoding)
1184     ];
1185   }
1186   exports2.createServerSocketTransport = createServerSocketTransport;
1187 });
1188
1189 // node_modules/vscode-jsonrpc/lib/main.js
1190 var require_main = __commonJS((exports2) => {
1191   "use strict";
1192   function __export2(m) {
1193     for (var p in m)
1194       if (!exports2.hasOwnProperty(p))
1195         exports2[p] = m[p];
1196   }
1197   Object.defineProperty(exports2, "__esModule", {value: true});
1198   var Is = require_is();
1199   var messages_1 = require_messages();
1200   exports2.RequestType = messages_1.RequestType;
1201   exports2.RequestType0 = messages_1.RequestType0;
1202   exports2.RequestType1 = messages_1.RequestType1;
1203   exports2.RequestType2 = messages_1.RequestType2;
1204   exports2.RequestType3 = messages_1.RequestType3;
1205   exports2.RequestType4 = messages_1.RequestType4;
1206   exports2.RequestType5 = messages_1.RequestType5;
1207   exports2.RequestType6 = messages_1.RequestType6;
1208   exports2.RequestType7 = messages_1.RequestType7;
1209   exports2.RequestType8 = messages_1.RequestType8;
1210   exports2.RequestType9 = messages_1.RequestType9;
1211   exports2.ResponseError = messages_1.ResponseError;
1212   exports2.ErrorCodes = messages_1.ErrorCodes;
1213   exports2.NotificationType = messages_1.NotificationType;
1214   exports2.NotificationType0 = messages_1.NotificationType0;
1215   exports2.NotificationType1 = messages_1.NotificationType1;
1216   exports2.NotificationType2 = messages_1.NotificationType2;
1217   exports2.NotificationType3 = messages_1.NotificationType3;
1218   exports2.NotificationType4 = messages_1.NotificationType4;
1219   exports2.NotificationType5 = messages_1.NotificationType5;
1220   exports2.NotificationType6 = messages_1.NotificationType6;
1221   exports2.NotificationType7 = messages_1.NotificationType7;
1222   exports2.NotificationType8 = messages_1.NotificationType8;
1223   exports2.NotificationType9 = messages_1.NotificationType9;
1224   var messageReader_1 = require_messageReader();
1225   exports2.MessageReader = messageReader_1.MessageReader;
1226   exports2.StreamMessageReader = messageReader_1.StreamMessageReader;
1227   exports2.IPCMessageReader = messageReader_1.IPCMessageReader;
1228   exports2.SocketMessageReader = messageReader_1.SocketMessageReader;
1229   var messageWriter_1 = require_messageWriter();
1230   exports2.MessageWriter = messageWriter_1.MessageWriter;
1231   exports2.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
1232   exports2.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
1233   exports2.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
1234   var events_1 = require_events();
1235   exports2.Disposable = events_1.Disposable;
1236   exports2.Event = events_1.Event;
1237   exports2.Emitter = events_1.Emitter;
1238   var cancellation_1 = require_cancellation();
1239   exports2.CancellationTokenSource = cancellation_1.CancellationTokenSource;
1240   exports2.CancellationToken = cancellation_1.CancellationToken;
1241   var linkedMap_1 = require_linkedMap();
1242   __export2(require_pipeSupport());
1243   __export2(require_socketSupport());
1244   var CancelNotification;
1245   (function(CancelNotification2) {
1246     CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
1247   })(CancelNotification || (CancelNotification = {}));
1248   var ProgressNotification;
1249   (function(ProgressNotification2) {
1250     ProgressNotification2.type = new messages_1.NotificationType("$/progress");
1251   })(ProgressNotification || (ProgressNotification = {}));
1252   var ProgressType = class {
1253     constructor() {
1254     }
1255   };
1256   exports2.ProgressType = ProgressType;
1257   exports2.NullLogger = Object.freeze({
1258     error: () => {
1259     },
1260     warn: () => {
1261     },
1262     info: () => {
1263     },
1264     log: () => {
1265     }
1266   });
1267   var Trace2;
1268   (function(Trace3) {
1269     Trace3[Trace3["Off"] = 0] = "Off";
1270     Trace3[Trace3["Messages"] = 1] = "Messages";
1271     Trace3[Trace3["Verbose"] = 2] = "Verbose";
1272   })(Trace2 = exports2.Trace || (exports2.Trace = {}));
1273   (function(Trace3) {
1274     function fromString(value) {
1275       if (!Is.string(value)) {
1276         return Trace3.Off;
1277       }
1278       value = value.toLowerCase();
1279       switch (value) {
1280         case "off":
1281           return Trace3.Off;
1282         case "messages":
1283           return Trace3.Messages;
1284         case "verbose":
1285           return Trace3.Verbose;
1286         default:
1287           return Trace3.Off;
1288       }
1289     }
1290     Trace3.fromString = fromString;
1291     function toString2(value) {
1292       switch (value) {
1293         case Trace3.Off:
1294           return "off";
1295         case Trace3.Messages:
1296           return "messages";
1297         case Trace3.Verbose:
1298           return "verbose";
1299         default:
1300           return "off";
1301       }
1302     }
1303     Trace3.toString = toString2;
1304   })(Trace2 = exports2.Trace || (exports2.Trace = {}));
1305   var TraceFormat;
1306   (function(TraceFormat2) {
1307     TraceFormat2["Text"] = "text";
1308     TraceFormat2["JSON"] = "json";
1309   })(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
1310   (function(TraceFormat2) {
1311     function fromString(value) {
1312       value = value.toLowerCase();
1313       if (value === "json") {
1314         return TraceFormat2.JSON;
1315       } else {
1316         return TraceFormat2.Text;
1317       }
1318     }
1319     TraceFormat2.fromString = fromString;
1320   })(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
1321   var SetTraceNotification;
1322   (function(SetTraceNotification2) {
1323     SetTraceNotification2.type = new messages_1.NotificationType("$/setTraceNotification");
1324   })(SetTraceNotification = exports2.SetTraceNotification || (exports2.SetTraceNotification = {}));
1325   var LogTraceNotification;
1326   (function(LogTraceNotification2) {
1327     LogTraceNotification2.type = new messages_1.NotificationType("$/logTraceNotification");
1328   })(LogTraceNotification = exports2.LogTraceNotification || (exports2.LogTraceNotification = {}));
1329   var ConnectionErrors;
1330   (function(ConnectionErrors2) {
1331     ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
1332     ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
1333     ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
1334   })(ConnectionErrors = exports2.ConnectionErrors || (exports2.ConnectionErrors = {}));
1335   var ConnectionError = class extends Error {
1336     constructor(code, message) {
1337       super(message);
1338       this.code = code;
1339       Object.setPrototypeOf(this, ConnectionError.prototype);
1340     }
1341   };
1342   exports2.ConnectionError = ConnectionError;
1343   var ConnectionStrategy;
1344   (function(ConnectionStrategy2) {
1345     function is2(value) {
1346       let candidate = value;
1347       return candidate && Is.func(candidate.cancelUndispatched);
1348     }
1349     ConnectionStrategy2.is = is2;
1350   })(ConnectionStrategy = exports2.ConnectionStrategy || (exports2.ConnectionStrategy = {}));
1351   var ConnectionState;
1352   (function(ConnectionState2) {
1353     ConnectionState2[ConnectionState2["New"] = 1] = "New";
1354     ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
1355     ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
1356     ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
1357   })(ConnectionState || (ConnectionState = {}));
1358   function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
1359     let sequenceNumber = 0;
1360     let notificationSquenceNumber = 0;
1361     let unknownResponseSquenceNumber = 0;
1362     const version = "2.0";
1363     let starRequestHandler = void 0;
1364     let requestHandlers = Object.create(null);
1365     let starNotificationHandler = void 0;
1366     let notificationHandlers = Object.create(null);
1367     let progressHandlers = new Map();
1368     let timer;
1369     let messageQueue = new linkedMap_1.LinkedMap();
1370     let responsePromises = Object.create(null);
1371     let requestTokens = Object.create(null);
1372     let trace = Trace2.Off;
1373     let traceFormat = TraceFormat.Text;
1374     let tracer;
1375     let state = ConnectionState.New;
1376     let errorEmitter = new events_1.Emitter();
1377     let closeEmitter = new events_1.Emitter();
1378     let unhandledNotificationEmitter = new events_1.Emitter();
1379     let unhandledProgressEmitter = new events_1.Emitter();
1380     let disposeEmitter = new events_1.Emitter();
1381     function createRequestQueueKey(id) {
1382       return "req-" + id.toString();
1383     }
1384     function createResponseQueueKey(id) {
1385       if (id === null) {
1386         return "res-unknown-" + (++unknownResponseSquenceNumber).toString();
1387       } else {
1388         return "res-" + id.toString();
1389       }
1390     }
1391     function createNotificationQueueKey() {
1392       return "not-" + (++notificationSquenceNumber).toString();
1393     }
1394     function addMessageToQueue(queue, message) {
1395       if (messages_1.isRequestMessage(message)) {
1396         queue.set(createRequestQueueKey(message.id), message);
1397       } else if (messages_1.isResponseMessage(message)) {
1398         queue.set(createResponseQueueKey(message.id), message);
1399       } else {
1400         queue.set(createNotificationQueueKey(), message);
1401       }
1402     }
1403     function cancelUndispatched(_message) {
1404       return void 0;
1405     }
1406     function isListening() {
1407       return state === ConnectionState.Listening;
1408     }
1409     function isClosed() {
1410       return state === ConnectionState.Closed;
1411     }
1412     function isDisposed() {
1413       return state === ConnectionState.Disposed;
1414     }
1415     function closeHandler() {
1416       if (state === ConnectionState.New || state === ConnectionState.Listening) {
1417         state = ConnectionState.Closed;
1418         closeEmitter.fire(void 0);
1419       }
1420     }
1421     function readErrorHandler(error) {
1422       errorEmitter.fire([error, void 0, void 0]);
1423     }
1424     function writeErrorHandler(data) {
1425       errorEmitter.fire(data);
1426     }
1427     messageReader.onClose(closeHandler);
1428     messageReader.onError(readErrorHandler);
1429     messageWriter.onClose(closeHandler);
1430     messageWriter.onError(writeErrorHandler);
1431     function triggerMessageQueue() {
1432       if (timer || messageQueue.size === 0) {
1433         return;
1434       }
1435       timer = setImmediate(() => {
1436         timer = void 0;
1437         processMessageQueue();
1438       });
1439     }
1440     function processMessageQueue() {
1441       if (messageQueue.size === 0) {
1442         return;
1443       }
1444       let message = messageQueue.shift();
1445       try {
1446         if (messages_1.isRequestMessage(message)) {
1447           handleRequest(message);
1448         } else if (messages_1.isNotificationMessage(message)) {
1449           handleNotification(message);
1450         } else if (messages_1.isResponseMessage(message)) {
1451           handleResponse(message);
1452         } else {
1453           handleInvalidMessage(message);
1454         }
1455       } finally {
1456         triggerMessageQueue();
1457       }
1458     }
1459     let callback = (message) => {
1460       try {
1461         if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
1462           let key = createRequestQueueKey(message.params.id);
1463           let toCancel = messageQueue.get(key);
1464           if (messages_1.isRequestMessage(toCancel)) {
1465             let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
1466             if (response && (response.error !== void 0 || response.result !== void 0)) {
1467               messageQueue.delete(key);
1468               response.id = toCancel.id;
1469               traceSendingResponse(response, message.method, Date.now());
1470               messageWriter.write(response);
1471               return;
1472             }
1473           }
1474         }
1475         addMessageToQueue(messageQueue, message);
1476       } finally {
1477         triggerMessageQueue();
1478       }
1479     };
1480     function handleRequest(requestMessage) {
1481       if (isDisposed()) {
1482         return;
1483       }
1484       function reply(resultOrError, method, startTime2) {
1485         let message = {
1486           jsonrpc: version,
1487           id: requestMessage.id
1488         };
1489         if (resultOrError instanceof messages_1.ResponseError) {
1490           message.error = resultOrError.toJson();
1491         } else {
1492           message.result = resultOrError === void 0 ? null : resultOrError;
1493         }
1494         traceSendingResponse(message, method, startTime2);
1495         messageWriter.write(message);
1496       }
1497       function replyError(error, method, startTime2) {
1498         let message = {
1499           jsonrpc: version,
1500           id: requestMessage.id,
1501           error: error.toJson()
1502         };
1503         traceSendingResponse(message, method, startTime2);
1504         messageWriter.write(message);
1505       }
1506       function replySuccess(result, method, startTime2) {
1507         if (result === void 0) {
1508           result = null;
1509         }
1510         let message = {
1511           jsonrpc: version,
1512           id: requestMessage.id,
1513           result
1514         };
1515         traceSendingResponse(message, method, startTime2);
1516         messageWriter.write(message);
1517       }
1518       traceReceivedRequest(requestMessage);
1519       let element = requestHandlers[requestMessage.method];
1520       let type;
1521       let requestHandler;
1522       if (element) {
1523         type = element.type;
1524         requestHandler = element.handler;
1525       }
1526       let startTime = Date.now();
1527       if (requestHandler || starRequestHandler) {
1528         let cancellationSource = new cancellation_1.CancellationTokenSource();
1529         let tokenKey = String(requestMessage.id);
1530         requestTokens[tokenKey] = cancellationSource;
1531         try {
1532           let handlerResult;
1533           if (requestMessage.params === void 0 || type !== void 0 && type.numberOfParams === 0) {
1534             handlerResult = requestHandler ? requestHandler(cancellationSource.token) : starRequestHandler(requestMessage.method, cancellationSource.token);
1535           } else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
1536             handlerResult = requestHandler ? requestHandler(...requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
1537           } else {
1538             handlerResult = requestHandler ? requestHandler(requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
1539           }
1540           let promise = handlerResult;
1541           if (!handlerResult) {
1542             delete requestTokens[tokenKey];
1543             replySuccess(handlerResult, requestMessage.method, startTime);
1544           } else if (promise.then) {
1545             promise.then((resultOrError) => {
1546               delete requestTokens[tokenKey];
1547               reply(resultOrError, requestMessage.method, startTime);
1548             }, (error) => {
1549               delete requestTokens[tokenKey];
1550               if (error instanceof messages_1.ResponseError) {
1551                 replyError(error, requestMessage.method, startTime);
1552               } else if (error && Is.string(error.message)) {
1553                 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1554               } else {
1555                 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1556               }
1557             });
1558           } else {
1559             delete requestTokens[tokenKey];
1560             reply(handlerResult, requestMessage.method, startTime);
1561           }
1562         } catch (error) {
1563           delete requestTokens[tokenKey];
1564           if (error instanceof messages_1.ResponseError) {
1565             reply(error, requestMessage.method, startTime);
1566           } else if (error && Is.string(error.message)) {
1567             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1568           } else {
1569             replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1570           }
1571         }
1572       } else {
1573         replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
1574       }
1575     }
1576     function handleResponse(responseMessage) {
1577       if (isDisposed()) {
1578         return;
1579       }
1580       if (responseMessage.id === null) {
1581         if (responseMessage.error) {
1582           logger.error(`Received response message without id: Error is: 
1583 ${JSON.stringify(responseMessage.error, void 0, 4)}`);
1584         } else {
1585           logger.error(`Received response message without id. No further error information provided.`);
1586         }
1587       } else {
1588         let key = String(responseMessage.id);
1589         let responsePromise = responsePromises[key];
1590         traceReceivedResponse(responseMessage, responsePromise);
1591         if (responsePromise) {
1592           delete responsePromises[key];
1593           try {
1594             if (responseMessage.error) {
1595               let error = responseMessage.error;
1596               responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
1597             } else if (responseMessage.result !== void 0) {
1598               responsePromise.resolve(responseMessage.result);
1599             } else {
1600               throw new Error("Should never happen.");
1601             }
1602           } catch (error) {
1603             if (error.message) {
1604               logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
1605             } else {
1606               logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
1607             }
1608           }
1609         }
1610       }
1611     }
1612     function handleNotification(message) {
1613       if (isDisposed()) {
1614         return;
1615       }
1616       let type = void 0;
1617       let notificationHandler;
1618       if (message.method === CancelNotification.type.method) {
1619         notificationHandler = (params) => {
1620           let id = params.id;
1621           let source = requestTokens[String(id)];
1622           if (source) {
1623             source.cancel();
1624           }
1625         };
1626       } else {
1627         let element = notificationHandlers[message.method];
1628         if (element) {
1629           notificationHandler = element.handler;
1630           type = element.type;
1631         }
1632       }
1633       if (notificationHandler || starNotificationHandler) {
1634         try {
1635           traceReceivedNotification(message);
1636           if (message.params === void 0 || type !== void 0 && type.numberOfParams === 0) {
1637             notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
1638           } else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
1639             notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
1640           } else {
1641             notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
1642           }
1643         } catch (error) {
1644           if (error.message) {
1645             logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
1646           } else {
1647             logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
1648           }
1649         }
1650       } else {
1651         unhandledNotificationEmitter.fire(message);
1652       }
1653     }
1654     function handleInvalidMessage(message) {
1655       if (!message) {
1656         logger.error("Received empty message.");
1657         return;
1658       }
1659       logger.error(`Received message which is neither a response nor a notification message:
1660 ${JSON.stringify(message, null, 4)}`);
1661       let responseMessage = message;
1662       if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
1663         let key = String(responseMessage.id);
1664         let responseHandler = responsePromises[key];
1665         if (responseHandler) {
1666           responseHandler.reject(new Error("The received response has neither a result nor an error property."));
1667         }
1668       }
1669     }
1670     function traceSendingRequest(message) {
1671       if (trace === Trace2.Off || !tracer) {
1672         return;
1673       }
1674       if (traceFormat === TraceFormat.Text) {
1675         let data = void 0;
1676         if (trace === Trace2.Verbose && message.params) {
1677           data = `Params: ${JSON.stringify(message.params, null, 4)}
1678
1679 `;
1680         }
1681         tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
1682       } else {
1683         logLSPMessage("send-request", message);
1684       }
1685     }
1686     function traceSendingNotification(message) {
1687       if (trace === Trace2.Off || !tracer) {
1688         return;
1689       }
1690       if (traceFormat === TraceFormat.Text) {
1691         let data = void 0;
1692         if (trace === Trace2.Verbose) {
1693           if (message.params) {
1694             data = `Params: ${JSON.stringify(message.params, null, 4)}
1695
1696 `;
1697           } else {
1698             data = "No parameters provided.\n\n";
1699           }
1700         }
1701         tracer.log(`Sending notification '${message.method}'.`, data);
1702       } else {
1703         logLSPMessage("send-notification", message);
1704       }
1705     }
1706     function traceSendingResponse(message, method, startTime) {
1707       if (trace === Trace2.Off || !tracer) {
1708         return;
1709       }
1710       if (traceFormat === TraceFormat.Text) {
1711         let data = void 0;
1712         if (trace === Trace2.Verbose) {
1713           if (message.error && message.error.data) {
1714             data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
1715
1716 `;
1717           } else {
1718             if (message.result) {
1719               data = `Result: ${JSON.stringify(message.result, null, 4)}
1720
1721 `;
1722             } else if (message.error === void 0) {
1723               data = "No result returned.\n\n";
1724             }
1725           }
1726         }
1727         tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
1728       } else {
1729         logLSPMessage("send-response", message);
1730       }
1731     }
1732     function traceReceivedRequest(message) {
1733       if (trace === Trace2.Off || !tracer) {
1734         return;
1735       }
1736       if (traceFormat === TraceFormat.Text) {
1737         let data = void 0;
1738         if (trace === Trace2.Verbose && message.params) {
1739           data = `Params: ${JSON.stringify(message.params, null, 4)}
1740
1741 `;
1742         }
1743         tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
1744       } else {
1745         logLSPMessage("receive-request", message);
1746       }
1747     }
1748     function traceReceivedNotification(message) {
1749       if (trace === Trace2.Off || !tracer || message.method === LogTraceNotification.type.method) {
1750         return;
1751       }
1752       if (traceFormat === TraceFormat.Text) {
1753         let data = void 0;
1754         if (trace === Trace2.Verbose) {
1755           if (message.params) {
1756             data = `Params: ${JSON.stringify(message.params, null, 4)}
1757
1758 `;
1759           } else {
1760             data = "No parameters provided.\n\n";
1761           }
1762         }
1763         tracer.log(`Received notification '${message.method}'.`, data);
1764       } else {
1765         logLSPMessage("receive-notification", message);
1766       }
1767     }
1768     function traceReceivedResponse(message, responsePromise) {
1769       if (trace === Trace2.Off || !tracer) {
1770         return;
1771       }
1772       if (traceFormat === TraceFormat.Text) {
1773         let data = void 0;
1774         if (trace === Trace2.Verbose) {
1775           if (message.error && message.error.data) {
1776             data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
1777
1778 `;
1779           } else {
1780             if (message.result) {
1781               data = `Result: ${JSON.stringify(message.result, null, 4)}
1782
1783 `;
1784             } else if (message.error === void 0) {
1785               data = "No result returned.\n\n";
1786             }
1787           }
1788         }
1789         if (responsePromise) {
1790           let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
1791           tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
1792         } else {
1793           tracer.log(`Received response ${message.id} without active response promise.`, data);
1794         }
1795       } else {
1796         logLSPMessage("receive-response", message);
1797       }
1798     }
1799     function logLSPMessage(type, message) {
1800       if (!tracer || trace === Trace2.Off) {
1801         return;
1802       }
1803       const lspMessage = {
1804         isLSPMessage: true,
1805         type,
1806         message,
1807         timestamp: Date.now()
1808       };
1809       tracer.log(lspMessage);
1810     }
1811     function throwIfClosedOrDisposed() {
1812       if (isClosed()) {
1813         throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
1814       }
1815       if (isDisposed()) {
1816         throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
1817       }
1818     }
1819     function throwIfListening() {
1820       if (isListening()) {
1821         throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
1822       }
1823     }
1824     function throwIfNotListening() {
1825       if (!isListening()) {
1826         throw new Error("Call listen() first.");
1827       }
1828     }
1829     function undefinedToNull(param) {
1830       if (param === void 0) {
1831         return null;
1832       } else {
1833         return param;
1834       }
1835     }
1836     function computeMessageParams(type, params) {
1837       let result;
1838       let numberOfParams = type.numberOfParams;
1839       switch (numberOfParams) {
1840         case 0:
1841           result = null;
1842           break;
1843         case 1:
1844           result = undefinedToNull(params[0]);
1845           break;
1846         default:
1847           result = [];
1848           for (let i = 0; i < params.length && i < numberOfParams; i++) {
1849             result.push(undefinedToNull(params[i]));
1850           }
1851           if (params.length < numberOfParams) {
1852             for (let i = params.length; i < numberOfParams; i++) {
1853               result.push(null);
1854             }
1855           }
1856           break;
1857       }
1858       return result;
1859     }
1860     let connection = {
1861       sendNotification: (type, ...params) => {
1862         throwIfClosedOrDisposed();
1863         let method;
1864         let messageParams;
1865         if (Is.string(type)) {
1866           method = type;
1867           switch (params.length) {
1868             case 0:
1869               messageParams = null;
1870               break;
1871             case 1:
1872               messageParams = params[0];
1873               break;
1874             default:
1875               messageParams = params;
1876               break;
1877           }
1878         } else {
1879           method = type.method;
1880           messageParams = computeMessageParams(type, params);
1881         }
1882         let notificationMessage = {
1883           jsonrpc: version,
1884           method,
1885           params: messageParams
1886         };
1887         traceSendingNotification(notificationMessage);
1888         messageWriter.write(notificationMessage);
1889       },
1890       onNotification: (type, handler) => {
1891         throwIfClosedOrDisposed();
1892         if (Is.func(type)) {
1893           starNotificationHandler = type;
1894         } else if (handler) {
1895           if (Is.string(type)) {
1896             notificationHandlers[type] = {type: void 0, handler};
1897           } else {
1898             notificationHandlers[type.method] = {type, handler};
1899           }
1900         }
1901       },
1902       onProgress: (_type, token, handler) => {
1903         if (progressHandlers.has(token)) {
1904           throw new Error(`Progress handler for token ${token} already registered`);
1905         }
1906         progressHandlers.set(token, handler);
1907         return {
1908           dispose: () => {
1909             progressHandlers.delete(token);
1910           }
1911         };
1912       },
1913       sendProgress: (_type, token, value) => {
1914         connection.sendNotification(ProgressNotification.type, {token, value});
1915       },
1916       onUnhandledProgress: unhandledProgressEmitter.event,
1917       sendRequest: (type, ...params) => {
1918         throwIfClosedOrDisposed();
1919         throwIfNotListening();
1920         let method;
1921         let messageParams;
1922         let token = void 0;
1923         if (Is.string(type)) {
1924           method = type;
1925           switch (params.length) {
1926             case 0:
1927               messageParams = null;
1928               break;
1929             case 1:
1930               if (cancellation_1.CancellationToken.is(params[0])) {
1931                 messageParams = null;
1932                 token = params[0];
1933               } else {
1934                 messageParams = undefinedToNull(params[0]);
1935               }
1936               break;
1937             default:
1938               const last = params.length - 1;
1939               if (cancellation_1.CancellationToken.is(params[last])) {
1940                 token = params[last];
1941                 if (params.length === 2) {
1942                   messageParams = undefinedToNull(params[0]);
1943                 } else {
1944                   messageParams = params.slice(0, last).map((value) => undefinedToNull(value));
1945                 }
1946               } else {
1947                 messageParams = params.map((value) => undefinedToNull(value));
1948               }
1949               break;
1950           }
1951         } else {
1952           method = type.method;
1953           messageParams = computeMessageParams(type, params);
1954           let numberOfParams = type.numberOfParams;
1955           token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
1956         }
1957         let id = sequenceNumber++;
1958         let result = new Promise((resolve, reject) => {
1959           let requestMessage = {
1960             jsonrpc: version,
1961             id,
1962             method,
1963             params: messageParams
1964           };
1965           let responsePromise = {method, timerStart: Date.now(), resolve, reject};
1966           traceSendingRequest(requestMessage);
1967           try {
1968             messageWriter.write(requestMessage);
1969           } catch (e) {
1970             responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : "Unknown reason"));
1971             responsePromise = null;
1972           }
1973           if (responsePromise) {
1974             responsePromises[String(id)] = responsePromise;
1975           }
1976         });
1977         if (token) {
1978           token.onCancellationRequested(() => {
1979             connection.sendNotification(CancelNotification.type, {id});
1980           });
1981         }
1982         return result;
1983       },
1984       onRequest: (type, handler) => {
1985         throwIfClosedOrDisposed();
1986         if (Is.func(type)) {
1987           starRequestHandler = type;
1988         } else if (handler) {
1989           if (Is.string(type)) {
1990             requestHandlers[type] = {type: void 0, handler};
1991           } else {
1992             requestHandlers[type.method] = {type, handler};
1993           }
1994         }
1995       },
1996       trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
1997         let _sendNotification = false;
1998         let _traceFormat = TraceFormat.Text;
1999         if (sendNotificationOrTraceOptions !== void 0) {
2000           if (Is.boolean(sendNotificationOrTraceOptions)) {
2001             _sendNotification = sendNotificationOrTraceOptions;
2002           } else {
2003             _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
2004             _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
2005           }
2006         }
2007         trace = _value;
2008         traceFormat = _traceFormat;
2009         if (trace === Trace2.Off) {
2010           tracer = void 0;
2011         } else {
2012           tracer = _tracer;
2013         }
2014         if (_sendNotification && !isClosed() && !isDisposed()) {
2015           connection.sendNotification(SetTraceNotification.type, {value: Trace2.toString(_value)});
2016         }
2017       },
2018       onError: errorEmitter.event,
2019       onClose: closeEmitter.event,
2020       onUnhandledNotification: unhandledNotificationEmitter.event,
2021       onDispose: disposeEmitter.event,
2022       dispose: () => {
2023         if (isDisposed()) {
2024           return;
2025         }
2026         state = ConnectionState.Disposed;
2027         disposeEmitter.fire(void 0);
2028         let error = new Error("Connection got disposed.");
2029         Object.keys(responsePromises).forEach((key) => {
2030           responsePromises[key].reject(error);
2031         });
2032         responsePromises = Object.create(null);
2033         requestTokens = Object.create(null);
2034         messageQueue = new linkedMap_1.LinkedMap();
2035         if (Is.func(messageWriter.dispose)) {
2036           messageWriter.dispose();
2037         }
2038         if (Is.func(messageReader.dispose)) {
2039           messageReader.dispose();
2040         }
2041       },
2042       listen: () => {
2043         throwIfClosedOrDisposed();
2044         throwIfListening();
2045         state = ConnectionState.Listening;
2046         messageReader.listen(callback);
2047       },
2048       inspect: () => {
2049         console.log("inspect");
2050       }
2051     };
2052     connection.onNotification(LogTraceNotification.type, (params) => {
2053       if (trace === Trace2.Off || !tracer) {
2054         return;
2055       }
2056       tracer.log(params.message, trace === Trace2.Verbose ? params.verbose : void 0);
2057     });
2058     connection.onNotification(ProgressNotification.type, (params) => {
2059       const handler = progressHandlers.get(params.token);
2060       if (handler) {
2061         handler(params.value);
2062       } else {
2063         unhandledProgressEmitter.fire(params);
2064       }
2065     });
2066     return connection;
2067   }
2068   function isMessageReader(value) {
2069     return value.listen !== void 0 && value.read === void 0;
2070   }
2071   function isMessageWriter(value) {
2072     return value.write !== void 0 && value.end === void 0;
2073   }
2074   function createMessageConnection(input, output, logger, strategy) {
2075     if (!logger) {
2076       logger = exports2.NullLogger;
2077     }
2078     let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
2079     let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
2080     return _createMessageConnection(reader, writer, logger, strategy);
2081   }
2082   exports2.createMessageConnection = createMessageConnection;
2083 });
2084
2085 // node_modules/vscode-languageserver-types/lib/esm/main.js
2086 var require_main2 = __commonJS((exports2) => {
2087   __export(exports2, {
2088     CodeAction: () => CodeAction6,
2089     CodeActionContext: () => CodeActionContext6,
2090     CodeActionKind: () => CodeActionKind6,
2091     CodeLens: () => CodeLens2,
2092     Color: () => Color,
2093     ColorInformation: () => ColorInformation,
2094     ColorPresentation: () => ColorPresentation,
2095     Command: () => Command5,
2096     CompletionItem: () => CompletionItem4,
2097     CompletionItemKind: () => CompletionItemKind3,
2098     CompletionItemTag: () => CompletionItemTag,
2099     CompletionList: () => CompletionList3,
2100     CreateFile: () => CreateFile,
2101     DeleteFile: () => DeleteFile,
2102     Diagnostic: () => Diagnostic5,
2103     DiagnosticRelatedInformation: () => DiagnosticRelatedInformation2,
2104     DiagnosticSeverity: () => DiagnosticSeverity3,
2105     DiagnosticTag: () => DiagnosticTag,
2106     DocumentHighlight: () => DocumentHighlight2,
2107     DocumentHighlightKind: () => DocumentHighlightKind2,
2108     DocumentLink: () => DocumentLink,
2109     DocumentSymbol: () => DocumentSymbol2,
2110     EOL: () => EOL,
2111     FoldingRange: () => FoldingRange2,
2112     FoldingRangeKind: () => FoldingRangeKind,
2113     FormattingOptions: () => FormattingOptions,
2114     Hover: () => Hover,
2115     InsertTextFormat: () => InsertTextFormat3,
2116     Location: () => Location3,
2117     LocationLink: () => LocationLink,
2118     MarkedString: () => MarkedString,
2119     MarkupContent: () => MarkupContent3,
2120     MarkupKind: () => MarkupKind3,
2121     ParameterInformation: () => ParameterInformation,
2122     Position: () => Position7,
2123     Range: () => Range15,
2124     RenameFile: () => RenameFile,
2125     SelectionRange: () => SelectionRange,
2126     SignatureInformation: () => SignatureInformation,
2127     SymbolInformation: () => SymbolInformation2,
2128     SymbolKind: () => SymbolKind3,
2129     SymbolTag: () => SymbolTag,
2130     TextDocument: () => TextDocument11,
2131     TextDocumentEdit: () => TextDocumentEdit,
2132     TextDocumentIdentifier: () => TextDocumentIdentifier,
2133     TextDocumentItem: () => TextDocumentItem,
2134     TextEdit: () => TextEdit6,
2135     VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier,
2136     WorkspaceChange: () => WorkspaceChange,
2137     WorkspaceEdit: () => WorkspaceEdit6
2138   });
2139   "use strict";
2140   var Position7;
2141   (function(Position8) {
2142     function create(line, character) {
2143       return {line, character};
2144     }
2145     Position8.create = create;
2146     function is2(value) {
2147       var candidate = value;
2148       return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
2149     }
2150     Position8.is = is2;
2151   })(Position7 || (Position7 = {}));
2152   var Range15;
2153   (function(Range16) {
2154     function create(one, two, three, four) {
2155       if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
2156         return {start: Position7.create(one, two), end: Position7.create(three, four)};
2157       } else if (Position7.is(one) && Position7.is(two)) {
2158         return {start: one, end: two};
2159       } else {
2160         throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
2161       }
2162     }
2163     Range16.create = create;
2164     function is2(value) {
2165       var candidate = value;
2166       return Is.objectLiteral(candidate) && Position7.is(candidate.start) && Position7.is(candidate.end);
2167     }
2168     Range16.is = is2;
2169   })(Range15 || (Range15 = {}));
2170   var Location3;
2171   (function(Location4) {
2172     function create(uri, range) {
2173       return {uri, range};
2174     }
2175     Location4.create = create;
2176     function is2(value) {
2177       var candidate = value;
2178       return Is.defined(candidate) && Range15.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
2179     }
2180     Location4.is = is2;
2181   })(Location3 || (Location3 = {}));
2182   var LocationLink;
2183   (function(LocationLink2) {
2184     function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
2185       return {targetUri, targetRange, targetSelectionRange, originSelectionRange};
2186     }
2187     LocationLink2.create = create;
2188     function is2(value) {
2189       var candidate = value;
2190       return Is.defined(candidate) && Range15.is(candidate.targetRange) && Is.string(candidate.targetUri) && (Range15.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange)) && (Range15.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
2191     }
2192     LocationLink2.is = is2;
2193   })(LocationLink || (LocationLink = {}));
2194   var Color;
2195   (function(Color2) {
2196     function create(red, green, blue, alpha) {
2197       return {
2198         red,
2199         green,
2200         blue,
2201         alpha
2202       };
2203     }
2204     Color2.create = create;
2205     function is2(value) {
2206       var candidate = value;
2207       return Is.number(candidate.red) && Is.number(candidate.green) && Is.number(candidate.blue) && Is.number(candidate.alpha);
2208     }
2209     Color2.is = is2;
2210   })(Color || (Color = {}));
2211   var ColorInformation;
2212   (function(ColorInformation2) {
2213     function create(range, color) {
2214       return {
2215         range,
2216         color
2217       };
2218     }
2219     ColorInformation2.create = create;
2220     function is2(value) {
2221       var candidate = value;
2222       return Range15.is(candidate.range) && Color.is(candidate.color);
2223     }
2224     ColorInformation2.is = is2;
2225   })(ColorInformation || (ColorInformation = {}));
2226   var ColorPresentation;
2227   (function(ColorPresentation2) {
2228     function create(label, textEdit, additionalTextEdits) {
2229       return {
2230         label,
2231         textEdit,
2232         additionalTextEdits
2233       };
2234     }
2235     ColorPresentation2.create = create;
2236     function is2(value) {
2237       var candidate = value;
2238       return Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit6.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit6.is));
2239     }
2240     ColorPresentation2.is = is2;
2241   })(ColorPresentation || (ColorPresentation = {}));
2242   var FoldingRangeKind;
2243   (function(FoldingRangeKind2) {
2244     FoldingRangeKind2["Comment"] = "comment";
2245     FoldingRangeKind2["Imports"] = "imports";
2246     FoldingRangeKind2["Region"] = "region";
2247   })(FoldingRangeKind || (FoldingRangeKind = {}));
2248   var FoldingRange2;
2249   (function(FoldingRange3) {
2250     function create(startLine, endLine, startCharacter, endCharacter, kind) {
2251       var result = {
2252         startLine,
2253         endLine
2254       };
2255       if (Is.defined(startCharacter)) {
2256         result.startCharacter = startCharacter;
2257       }
2258       if (Is.defined(endCharacter)) {
2259         result.endCharacter = endCharacter;
2260       }
2261       if (Is.defined(kind)) {
2262         result.kind = kind;
2263       }
2264       return result;
2265     }
2266     FoldingRange3.create = create;
2267     function is2(value) {
2268       var candidate = value;
2269       return Is.number(candidate.startLine) && Is.number(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
2270     }
2271     FoldingRange3.is = is2;
2272   })(FoldingRange2 || (FoldingRange2 = {}));
2273   var DiagnosticRelatedInformation2;
2274   (function(DiagnosticRelatedInformation3) {
2275     function create(location, message) {
2276       return {
2277         location,
2278         message
2279       };
2280     }
2281     DiagnosticRelatedInformation3.create = create;
2282     function is2(value) {
2283       var candidate = value;
2284       return Is.defined(candidate) && Location3.is(candidate.location) && Is.string(candidate.message);
2285     }
2286     DiagnosticRelatedInformation3.is = is2;
2287   })(DiagnosticRelatedInformation2 || (DiagnosticRelatedInformation2 = {}));
2288   var DiagnosticSeverity3;
2289   (function(DiagnosticSeverity4) {
2290     DiagnosticSeverity4.Error = 1;
2291     DiagnosticSeverity4.Warning = 2;
2292     DiagnosticSeverity4.Information = 3;
2293     DiagnosticSeverity4.Hint = 4;
2294   })(DiagnosticSeverity3 || (DiagnosticSeverity3 = {}));
2295   var DiagnosticTag;
2296   (function(DiagnosticTag2) {
2297     DiagnosticTag2.Unnecessary = 1;
2298     DiagnosticTag2.Deprecated = 2;
2299   })(DiagnosticTag || (DiagnosticTag = {}));
2300   var Diagnostic5;
2301   (function(Diagnostic6) {
2302     function create(range, message, severity, code, source, relatedInformation) {
2303       var result = {range, message};
2304       if (Is.defined(severity)) {
2305         result.severity = severity;
2306       }
2307       if (Is.defined(code)) {
2308         result.code = code;
2309       }
2310       if (Is.defined(source)) {
2311         result.source = source;
2312       }
2313       if (Is.defined(relatedInformation)) {
2314         result.relatedInformation = relatedInformation;
2315       }
2316       return result;
2317     }
2318     Diagnostic6.create = create;
2319     function is2(value) {
2320       var candidate = value;
2321       return Is.defined(candidate) && Range15.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation2.is));
2322     }
2323     Diagnostic6.is = is2;
2324   })(Diagnostic5 || (Diagnostic5 = {}));
2325   var Command5;
2326   (function(Command6) {
2327     function create(title, command) {
2328       var args = [];
2329       for (var _i = 2; _i < arguments.length; _i++) {
2330         args[_i - 2] = arguments[_i];
2331       }
2332       var result = {title, command};
2333       if (Is.defined(args) && args.length > 0) {
2334         result.arguments = args;
2335       }
2336       return result;
2337     }
2338     Command6.create = create;
2339     function is2(value) {
2340       var candidate = value;
2341       return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
2342     }
2343     Command6.is = is2;
2344   })(Command5 || (Command5 = {}));
2345   var TextEdit6;
2346   (function(TextEdit7) {
2347     function replace(range, newText) {
2348       return {range, newText};
2349     }
2350     TextEdit7.replace = replace;
2351     function insert(position, newText) {
2352       return {range: {start: position, end: position}, newText};
2353     }
2354     TextEdit7.insert = insert;
2355     function del(range) {
2356       return {range, newText: ""};
2357     }
2358     TextEdit7.del = del;
2359     function is2(value) {
2360       var candidate = value;
2361       return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range15.is(candidate.range);
2362     }
2363     TextEdit7.is = is2;
2364   })(TextEdit6 || (TextEdit6 = {}));
2365   var TextDocumentEdit;
2366   (function(TextDocumentEdit2) {
2367     function create(textDocument, edits) {
2368       return {textDocument, edits};
2369     }
2370     TextDocumentEdit2.create = create;
2371     function is2(value) {
2372       var candidate = value;
2373       return Is.defined(candidate) && VersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
2374     }
2375     TextDocumentEdit2.is = is2;
2376   })(TextDocumentEdit || (TextDocumentEdit = {}));
2377   var CreateFile;
2378   (function(CreateFile2) {
2379     function create(uri, options) {
2380       var result = {
2381         kind: "create",
2382         uri
2383       };
2384       if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
2385         result.options = options;
2386       }
2387       return result;
2388     }
2389     CreateFile2.create = create;
2390     function is2(value) {
2391       var candidate = value;
2392       return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)));
2393     }
2394     CreateFile2.is = is2;
2395   })(CreateFile || (CreateFile = {}));
2396   var RenameFile;
2397   (function(RenameFile2) {
2398     function create(oldUri, newUri, options) {
2399       var result = {
2400         kind: "rename",
2401         oldUri,
2402         newUri
2403       };
2404       if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
2405         result.options = options;
2406       }
2407       return result;
2408     }
2409     RenameFile2.create = create;
2410     function is2(value) {
2411       var candidate = value;
2412       return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists)));
2413     }
2414     RenameFile2.is = is2;
2415   })(RenameFile || (RenameFile = {}));
2416   var DeleteFile;
2417   (function(DeleteFile2) {
2418     function create(uri, options) {
2419       var result = {
2420         kind: "delete",
2421         uri
2422       };
2423       if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
2424         result.options = options;
2425       }
2426       return result;
2427     }
2428     DeleteFile2.create = create;
2429     function is2(value) {
2430       var candidate = value;
2431       return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists)));
2432     }
2433     DeleteFile2.is = is2;
2434   })(DeleteFile || (DeleteFile = {}));
2435   var WorkspaceEdit6;
2436   (function(WorkspaceEdit7) {
2437     function is2(value) {
2438       var candidate = value;
2439       return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) {
2440         if (Is.string(change.kind)) {
2441           return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
2442         } else {
2443           return TextDocumentEdit.is(change);
2444         }
2445       }));
2446     }
2447     WorkspaceEdit7.is = is2;
2448   })(WorkspaceEdit6 || (WorkspaceEdit6 = {}));
2449   var TextEditChangeImpl = function() {
2450     function TextEditChangeImpl2(edits) {
2451       this.edits = edits;
2452     }
2453     TextEditChangeImpl2.prototype.insert = function(position, newText) {
2454       this.edits.push(TextEdit6.insert(position, newText));
2455     };
2456     TextEditChangeImpl2.prototype.replace = function(range, newText) {
2457       this.edits.push(TextEdit6.replace(range, newText));
2458     };
2459     TextEditChangeImpl2.prototype.delete = function(range) {
2460       this.edits.push(TextEdit6.del(range));
2461     };
2462     TextEditChangeImpl2.prototype.add = function(edit) {
2463       this.edits.push(edit);
2464     };
2465     TextEditChangeImpl2.prototype.all = function() {
2466       return this.edits;
2467     };
2468     TextEditChangeImpl2.prototype.clear = function() {
2469       this.edits.splice(0, this.edits.length);
2470     };
2471     return TextEditChangeImpl2;
2472   }();
2473   var WorkspaceChange = function() {
2474     function WorkspaceChange2(workspaceEdit) {
2475       var _this = this;
2476       this._textEditChanges = Object.create(null);
2477       if (workspaceEdit) {
2478         this._workspaceEdit = workspaceEdit;
2479         if (workspaceEdit.documentChanges) {
2480           workspaceEdit.documentChanges.forEach(function(change) {
2481             if (TextDocumentEdit.is(change)) {
2482               var textEditChange = new TextEditChangeImpl(change.edits);
2483               _this._textEditChanges[change.textDocument.uri] = textEditChange;
2484             }
2485           });
2486         } else if (workspaceEdit.changes) {
2487           Object.keys(workspaceEdit.changes).forEach(function(key) {
2488             var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
2489             _this._textEditChanges[key] = textEditChange;
2490           });
2491         }
2492       }
2493     }
2494     Object.defineProperty(WorkspaceChange2.prototype, "edit", {
2495       get: function() {
2496         return this._workspaceEdit;
2497       },
2498       enumerable: true,
2499       configurable: true
2500     });
2501     WorkspaceChange2.prototype.getTextEditChange = function(key) {
2502       if (VersionedTextDocumentIdentifier.is(key)) {
2503         if (!this._workspaceEdit) {
2504           this._workspaceEdit = {
2505             documentChanges: []
2506           };
2507         }
2508         if (!this._workspaceEdit.documentChanges) {
2509           throw new Error("Workspace edit is not configured for document changes.");
2510         }
2511         var textDocument = key;
2512         var result = this._textEditChanges[textDocument.uri];
2513         if (!result) {
2514           var edits = [];
2515           var textDocumentEdit = {
2516             textDocument,
2517             edits
2518           };
2519           this._workspaceEdit.documentChanges.push(textDocumentEdit);
2520           result = new TextEditChangeImpl(edits);
2521           this._textEditChanges[textDocument.uri] = result;
2522         }
2523         return result;
2524       } else {
2525         if (!this._workspaceEdit) {
2526           this._workspaceEdit = {
2527             changes: Object.create(null)
2528           };
2529         }
2530         if (!this._workspaceEdit.changes) {
2531           throw new Error("Workspace edit is not configured for normal text edit changes.");
2532         }
2533         var result = this._textEditChanges[key];
2534         if (!result) {
2535           var edits = [];
2536           this._workspaceEdit.changes[key] = edits;
2537           result = new TextEditChangeImpl(edits);
2538           this._textEditChanges[key] = result;
2539         }
2540         return result;
2541       }
2542     };
2543     WorkspaceChange2.prototype.createFile = function(uri, options) {
2544       this.checkDocumentChanges();
2545       this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
2546     };
2547     WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, options) {
2548       this.checkDocumentChanges();
2549       this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
2550     };
2551     WorkspaceChange2.prototype.deleteFile = function(uri, options) {
2552       this.checkDocumentChanges();
2553       this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
2554     };
2555     WorkspaceChange2.prototype.checkDocumentChanges = function() {
2556       if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
2557         throw new Error("Workspace edit is not configured for document changes.");
2558       }
2559     };
2560     return WorkspaceChange2;
2561   }();
2562   var TextDocumentIdentifier;
2563   (function(TextDocumentIdentifier2) {
2564     function create(uri) {
2565       return {uri};
2566     }
2567     TextDocumentIdentifier2.create = create;
2568     function is2(value) {
2569       var candidate = value;
2570       return Is.defined(candidate) && Is.string(candidate.uri);
2571     }
2572     TextDocumentIdentifier2.is = is2;
2573   })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
2574   var VersionedTextDocumentIdentifier;
2575   (function(VersionedTextDocumentIdentifier2) {
2576     function create(uri, version) {
2577       return {uri, version};
2578     }
2579     VersionedTextDocumentIdentifier2.create = create;
2580     function is2(value) {
2581       var candidate = value;
2582       return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
2583     }
2584     VersionedTextDocumentIdentifier2.is = is2;
2585   })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
2586   var TextDocumentItem;
2587   (function(TextDocumentItem2) {
2588     function create(uri, languageId, version, text) {
2589       return {uri, languageId, version, text};
2590     }
2591     TextDocumentItem2.create = create;
2592     function is2(value) {
2593       var candidate = value;
2594       return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
2595     }
2596     TextDocumentItem2.is = is2;
2597   })(TextDocumentItem || (TextDocumentItem = {}));
2598   var MarkupKind3;
2599   (function(MarkupKind4) {
2600     MarkupKind4.PlainText = "plaintext";
2601     MarkupKind4.Markdown = "markdown";
2602   })(MarkupKind3 || (MarkupKind3 = {}));
2603   (function(MarkupKind4) {
2604     function is2(value) {
2605       var candidate = value;
2606       return candidate === MarkupKind4.PlainText || candidate === MarkupKind4.Markdown;
2607     }
2608     MarkupKind4.is = is2;
2609   })(MarkupKind3 || (MarkupKind3 = {}));
2610   var MarkupContent3;
2611   (function(MarkupContent4) {
2612     function is2(value) {
2613       var candidate = value;
2614       return Is.objectLiteral(value) && MarkupKind3.is(candidate.kind) && Is.string(candidate.value);
2615     }
2616     MarkupContent4.is = is2;
2617   })(MarkupContent3 || (MarkupContent3 = {}));
2618   var CompletionItemKind3;
2619   (function(CompletionItemKind4) {
2620     CompletionItemKind4.Text = 1;
2621     CompletionItemKind4.Method = 2;
2622     CompletionItemKind4.Function = 3;
2623     CompletionItemKind4.Constructor = 4;
2624     CompletionItemKind4.Field = 5;
2625     CompletionItemKind4.Variable = 6;
2626     CompletionItemKind4.Class = 7;
2627     CompletionItemKind4.Interface = 8;
2628     CompletionItemKind4.Module = 9;
2629     CompletionItemKind4.Property = 10;
2630     CompletionItemKind4.Unit = 11;
2631     CompletionItemKind4.Value = 12;
2632     CompletionItemKind4.Enum = 13;
2633     CompletionItemKind4.Keyword = 14;
2634     CompletionItemKind4.Snippet = 15;
2635     CompletionItemKind4.Color = 16;
2636     CompletionItemKind4.File = 17;
2637     CompletionItemKind4.Reference = 18;
2638     CompletionItemKind4.Folder = 19;
2639     CompletionItemKind4.EnumMember = 20;
2640     CompletionItemKind4.Constant = 21;
2641     CompletionItemKind4.Struct = 22;
2642     CompletionItemKind4.Event = 23;
2643     CompletionItemKind4.Operator = 24;
2644     CompletionItemKind4.TypeParameter = 25;
2645   })(CompletionItemKind3 || (CompletionItemKind3 = {}));
2646   var InsertTextFormat3;
2647   (function(InsertTextFormat4) {
2648     InsertTextFormat4.PlainText = 1;
2649     InsertTextFormat4.Snippet = 2;
2650   })(InsertTextFormat3 || (InsertTextFormat3 = {}));
2651   var CompletionItemTag;
2652   (function(CompletionItemTag2) {
2653     CompletionItemTag2.Deprecated = 1;
2654   })(CompletionItemTag || (CompletionItemTag = {}));
2655   var CompletionItem4;
2656   (function(CompletionItem5) {
2657     function create(label) {
2658       return {label};
2659     }
2660     CompletionItem5.create = create;
2661   })(CompletionItem4 || (CompletionItem4 = {}));
2662   var CompletionList3;
2663   (function(CompletionList4) {
2664     function create(items, isIncomplete) {
2665       return {items: items ? items : [], isIncomplete: !!isIncomplete};
2666     }
2667     CompletionList4.create = create;
2668   })(CompletionList3 || (CompletionList3 = {}));
2669   var MarkedString;
2670   (function(MarkedString2) {
2671     function fromPlainText(plainText) {
2672       return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
2673     }
2674     MarkedString2.fromPlainText = fromPlainText;
2675     function is2(value) {
2676       var candidate = value;
2677       return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
2678     }
2679     MarkedString2.is = is2;
2680   })(MarkedString || (MarkedString = {}));
2681   var Hover;
2682   (function(Hover2) {
2683     function is2(value) {
2684       var candidate = value;
2685       return !!candidate && Is.objectLiteral(candidate) && (MarkupContent3.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range15.is(value.range));
2686     }
2687     Hover2.is = is2;
2688   })(Hover || (Hover = {}));
2689   var ParameterInformation;
2690   (function(ParameterInformation2) {
2691     function create(label, documentation) {
2692       return documentation ? {label, documentation} : {label};
2693     }
2694     ParameterInformation2.create = create;
2695   })(ParameterInformation || (ParameterInformation = {}));
2696   var SignatureInformation;
2697   (function(SignatureInformation2) {
2698     function create(label, documentation) {
2699       var parameters = [];
2700       for (var _i = 2; _i < arguments.length; _i++) {
2701         parameters[_i - 2] = arguments[_i];
2702       }
2703       var result = {label};
2704       if (Is.defined(documentation)) {
2705         result.documentation = documentation;
2706       }
2707       if (Is.defined(parameters)) {
2708         result.parameters = parameters;
2709       } else {
2710         result.parameters = [];
2711       }
2712       return result;
2713     }
2714     SignatureInformation2.create = create;
2715   })(SignatureInformation || (SignatureInformation = {}));
2716   var DocumentHighlightKind2;
2717   (function(DocumentHighlightKind3) {
2718     DocumentHighlightKind3.Text = 1;
2719     DocumentHighlightKind3.Read = 2;
2720     DocumentHighlightKind3.Write = 3;
2721   })(DocumentHighlightKind2 || (DocumentHighlightKind2 = {}));
2722   var DocumentHighlight2;
2723   (function(DocumentHighlight3) {
2724     function create(range, kind) {
2725       var result = {range};
2726       if (Is.number(kind)) {
2727         result.kind = kind;
2728       }
2729       return result;
2730     }
2731     DocumentHighlight3.create = create;
2732   })(DocumentHighlight2 || (DocumentHighlight2 = {}));
2733   var SymbolKind3;
2734   (function(SymbolKind4) {
2735     SymbolKind4.File = 1;
2736     SymbolKind4.Module = 2;
2737     SymbolKind4.Namespace = 3;
2738     SymbolKind4.Package = 4;
2739     SymbolKind4.Class = 5;
2740     SymbolKind4.Method = 6;
2741     SymbolKind4.Property = 7;
2742     SymbolKind4.Field = 8;
2743     SymbolKind4.Constructor = 9;
2744     SymbolKind4.Enum = 10;
2745     SymbolKind4.Interface = 11;
2746     SymbolKind4.Function = 12;
2747     SymbolKind4.Variable = 13;
2748     SymbolKind4.Constant = 14;
2749     SymbolKind4.String = 15;
2750     SymbolKind4.Number = 16;
2751     SymbolKind4.Boolean = 17;
2752     SymbolKind4.Array = 18;
2753     SymbolKind4.Object = 19;
2754     SymbolKind4.Key = 20;
2755     SymbolKind4.Null = 21;
2756     SymbolKind4.EnumMember = 22;
2757     SymbolKind4.Struct = 23;
2758     SymbolKind4.Event = 24;
2759     SymbolKind4.Operator = 25;
2760     SymbolKind4.TypeParameter = 26;
2761   })(SymbolKind3 || (SymbolKind3 = {}));
2762   var SymbolTag;
2763   (function(SymbolTag2) {
2764     SymbolTag2.Deprecated = 1;
2765   })(SymbolTag || (SymbolTag = {}));
2766   var SymbolInformation2;
2767   (function(SymbolInformation3) {
2768     function create(name, kind, range, uri, containerName) {
2769       var result = {
2770         name,
2771         kind,
2772         location: {uri, range}
2773       };
2774       if (containerName) {
2775         result.containerName = containerName;
2776       }
2777       return result;
2778     }
2779     SymbolInformation3.create = create;
2780   })(SymbolInformation2 || (SymbolInformation2 = {}));
2781   var DocumentSymbol2;
2782   (function(DocumentSymbol3) {
2783     function create(name, detail, kind, range, selectionRange, children) {
2784       var result = {
2785         name,
2786         detail,
2787         kind,
2788         range,
2789         selectionRange
2790       };
2791       if (children !== void 0) {
2792         result.children = children;
2793       }
2794       return result;
2795     }
2796     DocumentSymbol3.create = create;
2797     function is2(value) {
2798       var candidate = value;
2799       return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range15.is(candidate.range) && Range15.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children));
2800     }
2801     DocumentSymbol3.is = is2;
2802   })(DocumentSymbol2 || (DocumentSymbol2 = {}));
2803   var CodeActionKind6;
2804   (function(CodeActionKind7) {
2805     CodeActionKind7.Empty = "";
2806     CodeActionKind7.QuickFix = "quickfix";
2807     CodeActionKind7.Refactor = "refactor";
2808     CodeActionKind7.RefactorExtract = "refactor.extract";
2809     CodeActionKind7.RefactorInline = "refactor.inline";
2810     CodeActionKind7.RefactorRewrite = "refactor.rewrite";
2811     CodeActionKind7.Source = "source";
2812     CodeActionKind7.SourceOrganizeImports = "source.organizeImports";
2813     CodeActionKind7.SourceFixAll = "source.fixAll";
2814   })(CodeActionKind6 || (CodeActionKind6 = {}));
2815   var CodeActionContext6;
2816   (function(CodeActionContext7) {
2817     function create(diagnostics, only) {
2818       var result = {diagnostics};
2819       if (only !== void 0 && only !== null) {
2820         result.only = only;
2821       }
2822       return result;
2823     }
2824     CodeActionContext7.create = create;
2825     function is2(value) {
2826       var candidate = value;
2827       return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic5.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
2828     }
2829     CodeActionContext7.is = is2;
2830   })(CodeActionContext6 || (CodeActionContext6 = {}));
2831   var CodeAction6;
2832   (function(CodeAction7) {
2833     function create(title, commandOrEdit, kind) {
2834       var result = {title};
2835       if (Command5.is(commandOrEdit)) {
2836         result.command = commandOrEdit;
2837       } else {
2838         result.edit = commandOrEdit;
2839       }
2840       if (kind !== void 0) {
2841         result.kind = kind;
2842       }
2843       return result;
2844     }
2845     CodeAction7.create = create;
2846     function is2(value) {
2847       var candidate = value;
2848       return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic5.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command5.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit6.is(candidate.edit));
2849     }
2850     CodeAction7.is = is2;
2851   })(CodeAction6 || (CodeAction6 = {}));
2852   var CodeLens2;
2853   (function(CodeLens3) {
2854     function create(range, data) {
2855       var result = {range};
2856       if (Is.defined(data)) {
2857         result.data = data;
2858       }
2859       return result;
2860     }
2861     CodeLens3.create = create;
2862     function is2(value) {
2863       var candidate = value;
2864       return Is.defined(candidate) && Range15.is(candidate.range) && (Is.undefined(candidate.command) || Command5.is(candidate.command));
2865     }
2866     CodeLens3.is = is2;
2867   })(CodeLens2 || (CodeLens2 = {}));
2868   var FormattingOptions;
2869   (function(FormattingOptions2) {
2870     function create(tabSize, insertSpaces) {
2871       return {tabSize, insertSpaces};
2872     }
2873     FormattingOptions2.create = create;
2874     function is2(value) {
2875       var candidate = value;
2876       return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
2877     }
2878     FormattingOptions2.is = is2;
2879   })(FormattingOptions || (FormattingOptions = {}));
2880   var DocumentLink;
2881   (function(DocumentLink2) {
2882     function create(range, target, data) {
2883       return {range, target, data};
2884     }
2885     DocumentLink2.create = create;
2886     function is2(value) {
2887       var candidate = value;
2888       return Is.defined(candidate) && Range15.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
2889     }
2890     DocumentLink2.is = is2;
2891   })(DocumentLink || (DocumentLink = {}));
2892   var SelectionRange;
2893   (function(SelectionRange2) {
2894     function create(range, parent) {
2895       return {range, parent};
2896     }
2897     SelectionRange2.create = create;
2898     function is2(value) {
2899       var candidate = value;
2900       return candidate !== void 0 && Range15.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
2901     }
2902     SelectionRange2.is = is2;
2903   })(SelectionRange || (SelectionRange = {}));
2904   var EOL = ["\n", "\r\n", "\r"];
2905   var TextDocument11;
2906   (function(TextDocument12) {
2907     function create(uri, languageId, version, content) {
2908       return new FullTextDocument(uri, languageId, version, content);
2909     }
2910     TextDocument12.create = create;
2911     function is2(value) {
2912       var candidate = value;
2913       return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
2914     }
2915     TextDocument12.is = is2;
2916     function applyEdits(document, edits) {
2917       var text = document.getText();
2918       var sortedEdits = mergeSort(edits, function(a, b) {
2919         var diff = a.range.start.line - b.range.start.line;
2920         if (diff === 0) {
2921           return a.range.start.character - b.range.start.character;
2922         }
2923         return diff;
2924       });
2925       var lastModifiedOffset = text.length;
2926       for (var i = sortedEdits.length - 1; i >= 0; i--) {
2927         var e = sortedEdits[i];
2928         var startOffset = document.offsetAt(e.range.start);
2929         var endOffset = document.offsetAt(e.range.end);
2930         if (endOffset <= lastModifiedOffset) {
2931           text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
2932         } else {
2933           throw new Error("Overlapping edit");
2934         }
2935         lastModifiedOffset = startOffset;
2936       }
2937       return text;
2938     }
2939     TextDocument12.applyEdits = applyEdits;
2940     function mergeSort(data, compare) {
2941       if (data.length <= 1) {
2942         return data;
2943       }
2944       var p = data.length / 2 | 0;
2945       var left = data.slice(0, p);
2946       var right = data.slice(p);
2947       mergeSort(left, compare);
2948       mergeSort(right, compare);
2949       var leftIdx = 0;
2950       var rightIdx = 0;
2951       var i = 0;
2952       while (leftIdx < left.length && rightIdx < right.length) {
2953         var ret = compare(left[leftIdx], right[rightIdx]);
2954         if (ret <= 0) {
2955           data[i++] = left[leftIdx++];
2956         } else {
2957           data[i++] = right[rightIdx++];
2958         }
2959       }
2960       while (leftIdx < left.length) {
2961         data[i++] = left[leftIdx++];
2962       }
2963       while (rightIdx < right.length) {
2964         data[i++] = right[rightIdx++];
2965       }
2966       return data;
2967     }
2968   })(TextDocument11 || (TextDocument11 = {}));
2969   var FullTextDocument = function() {
2970     function FullTextDocument2(uri, languageId, version, content) {
2971       this._uri = uri;
2972       this._languageId = languageId;
2973       this._version = version;
2974       this._content = content;
2975       this._lineOffsets = void 0;
2976     }
2977     Object.defineProperty(FullTextDocument2.prototype, "uri", {
2978       get: function() {
2979         return this._uri;
2980       },
2981       enumerable: true,
2982       configurable: true
2983     });
2984     Object.defineProperty(FullTextDocument2.prototype, "languageId", {
2985       get: function() {
2986         return this._languageId;
2987       },
2988       enumerable: true,
2989       configurable: true
2990     });
2991     Object.defineProperty(FullTextDocument2.prototype, "version", {
2992       get: function() {
2993         return this._version;
2994       },
2995       enumerable: true,
2996       configurable: true
2997     });
2998     FullTextDocument2.prototype.getText = function(range) {
2999       if (range) {
3000         var start = this.offsetAt(range.start);
3001         var end = this.offsetAt(range.end);
3002         return this._content.substring(start, end);
3003       }
3004       return this._content;
3005     };
3006     FullTextDocument2.prototype.update = function(event, version) {
3007       this._content = event.text;
3008       this._version = version;
3009       this._lineOffsets = void 0;
3010     };
3011     FullTextDocument2.prototype.getLineOffsets = function() {
3012       if (this._lineOffsets === void 0) {
3013         var lineOffsets = [];
3014         var text = this._content;
3015         var isLineStart = true;
3016         for (var i = 0; i < text.length; i++) {
3017           if (isLineStart) {
3018             lineOffsets.push(i);
3019             isLineStart = false;
3020           }
3021           var ch = text.charAt(i);
3022           isLineStart = ch === "\r" || ch === "\n";
3023           if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
3024             i++;
3025           }
3026         }
3027         if (isLineStart && text.length > 0) {
3028           lineOffsets.push(text.length);
3029         }
3030         this._lineOffsets = lineOffsets;
3031       }
3032       return this._lineOffsets;
3033     };
3034     FullTextDocument2.prototype.positionAt = function(offset) {
3035       offset = Math.max(Math.min(offset, this._content.length), 0);
3036       var lineOffsets = this.getLineOffsets();
3037       var low = 0, high = lineOffsets.length;
3038       if (high === 0) {
3039         return Position7.create(0, offset);
3040       }
3041       while (low < high) {
3042         var mid = Math.floor((low + high) / 2);
3043         if (lineOffsets[mid] > offset) {
3044           high = mid;
3045         } else {
3046           low = mid + 1;
3047         }
3048       }
3049       var line = low - 1;
3050       return Position7.create(line, offset - lineOffsets[line]);
3051     };
3052     FullTextDocument2.prototype.offsetAt = function(position) {
3053       var lineOffsets = this.getLineOffsets();
3054       if (position.line >= lineOffsets.length) {
3055         return this._content.length;
3056       } else if (position.line < 0) {
3057         return 0;
3058       }
3059       var lineOffset = lineOffsets[position.line];
3060       var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
3061       return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
3062     };
3063     Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
3064       get: function() {
3065         return this.getLineOffsets().length;
3066       },
3067       enumerable: true,
3068       configurable: true
3069     });
3070     return FullTextDocument2;
3071   }();
3072   var Is;
3073   (function(Is2) {
3074     var toString2 = Object.prototype.toString;
3075     function defined(value) {
3076       return typeof value !== "undefined";
3077     }
3078     Is2.defined = defined;
3079     function undefined2(value) {
3080       return typeof value === "undefined";
3081     }
3082     Is2.undefined = undefined2;
3083     function boolean2(value) {
3084       return value === true || value === false;
3085     }
3086     Is2.boolean = boolean2;
3087     function string2(value) {
3088       return toString2.call(value) === "[object String]";
3089     }
3090     Is2.string = string2;
3091     function number(value) {
3092       return toString2.call(value) === "[object Number]";
3093     }
3094     Is2.number = number;
3095     function func(value) {
3096       return toString2.call(value) === "[object Function]";
3097     }
3098     Is2.func = func;
3099     function objectLiteral(value) {
3100       return value !== null && typeof value === "object";
3101     }
3102     Is2.objectLiteral = objectLiteral;
3103     function typedArray(value, check) {
3104       return Array.isArray(value) && value.every(check);
3105     }
3106     Is2.typedArray = typedArray;
3107   })(Is || (Is = {}));
3108 });
3109
3110 // node_modules/vscode-languageserver-protocol/lib/utils/is.js
3111 var require_is2 = __commonJS((exports2) => {
3112   "use strict";
3113   Object.defineProperty(exports2, "__esModule", {value: true});
3114   function boolean2(value) {
3115     return value === true || value === false;
3116   }
3117   exports2.boolean = boolean2;
3118   function string2(value) {
3119     return typeof value === "string" || value instanceof String;
3120   }
3121   exports2.string = string2;
3122   function number(value) {
3123     return typeof value === "number" || value instanceof Number;
3124   }
3125   exports2.number = number;
3126   function error(value) {
3127     return value instanceof Error;
3128   }
3129   exports2.error = error;
3130   function func(value) {
3131     return typeof value === "function";
3132   }
3133   exports2.func = func;
3134   function array(value) {
3135     return Array.isArray(value);
3136   }
3137   exports2.array = array;
3138   function stringArray(value) {
3139     return array(value) && value.every((elem) => string2(elem));
3140   }
3141   exports2.stringArray = stringArray;
3142   function typedArray(value, check) {
3143     return Array.isArray(value) && value.every(check);
3144   }
3145   exports2.typedArray = typedArray;
3146   function objectLiteral(value) {
3147     return value !== null && typeof value === "object";
3148   }
3149   exports2.objectLiteral = objectLiteral;
3150 });
3151
3152 // node_modules/vscode-languageserver-protocol/lib/messages.js
3153 var require_messages2 = __commonJS((exports2) => {
3154   "use strict";
3155   Object.defineProperty(exports2, "__esModule", {value: true});
3156   var vscode_jsonrpc_1 = require_main();
3157   var ProtocolRequestType0 = class extends vscode_jsonrpc_1.RequestType0 {
3158     constructor(method) {
3159       super(method);
3160     }
3161   };
3162   exports2.ProtocolRequestType0 = ProtocolRequestType0;
3163   var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType {
3164     constructor(method) {
3165       super(method);
3166     }
3167   };
3168   exports2.ProtocolRequestType = ProtocolRequestType;
3169   var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType {
3170     constructor(method) {
3171       super(method);
3172     }
3173   };
3174   exports2.ProtocolNotificationType = ProtocolNotificationType;
3175   var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 {
3176     constructor(method) {
3177       super(method);
3178     }
3179   };
3180   exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
3181 });
3182
3183 // node_modules/vscode-languageserver-protocol/lib/protocol.implementation.js
3184 var require_protocol_implementation = __commonJS((exports2) => {
3185   "use strict";
3186   Object.defineProperty(exports2, "__esModule", {value: true});
3187   var vscode_jsonrpc_1 = require_main();
3188   var messages_1 = require_messages2();
3189   var ImplementationRequest;
3190   (function(ImplementationRequest2) {
3191     ImplementationRequest2.method = "textDocument/implementation";
3192     ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
3193     ImplementationRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3194   })(ImplementationRequest = exports2.ImplementationRequest || (exports2.ImplementationRequest = {}));
3195 });
3196
3197 // node_modules/vscode-languageserver-protocol/lib/protocol.typeDefinition.js
3198 var require_protocol_typeDefinition = __commonJS((exports2) => {
3199   "use strict";
3200   Object.defineProperty(exports2, "__esModule", {value: true});
3201   var vscode_jsonrpc_1 = require_main();
3202   var messages_1 = require_messages2();
3203   var TypeDefinitionRequest;
3204   (function(TypeDefinitionRequest2) {
3205     TypeDefinitionRequest2.method = "textDocument/typeDefinition";
3206     TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
3207     TypeDefinitionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3208   })(TypeDefinitionRequest = exports2.TypeDefinitionRequest || (exports2.TypeDefinitionRequest = {}));
3209 });
3210
3211 // node_modules/vscode-languageserver-protocol/lib/protocol.workspaceFolders.js
3212 var require_protocol_workspaceFolders = __commonJS((exports2) => {
3213   "use strict";
3214   Object.defineProperty(exports2, "__esModule", {value: true});
3215   var messages_1 = require_messages2();
3216   var WorkspaceFoldersRequest;
3217   (function(WorkspaceFoldersRequest2) {
3218     WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0("workspace/workspaceFolders");
3219   })(WorkspaceFoldersRequest = exports2.WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = {}));
3220   var DidChangeWorkspaceFoldersNotification;
3221   (function(DidChangeWorkspaceFoldersNotification2) {
3222     DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWorkspaceFolders");
3223   })(DidChangeWorkspaceFoldersNotification = exports2.DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = {}));
3224 });
3225
3226 // node_modules/vscode-languageserver-protocol/lib/protocol.configuration.js
3227 var require_protocol_configuration = __commonJS((exports2) => {
3228   "use strict";
3229   Object.defineProperty(exports2, "__esModule", {value: true});
3230   var messages_1 = require_messages2();
3231   var ConfigurationRequest;
3232   (function(ConfigurationRequest2) {
3233     ConfigurationRequest2.type = new messages_1.ProtocolRequestType("workspace/configuration");
3234   })(ConfigurationRequest = exports2.ConfigurationRequest || (exports2.ConfigurationRequest = {}));
3235 });
3236
3237 // node_modules/vscode-languageserver-protocol/lib/protocol.colorProvider.js
3238 var require_protocol_colorProvider = __commonJS((exports2) => {
3239   "use strict";
3240   Object.defineProperty(exports2, "__esModule", {value: true});
3241   var vscode_jsonrpc_1 = require_main();
3242   var messages_1 = require_messages2();
3243   var DocumentColorRequest;
3244   (function(DocumentColorRequest2) {
3245     DocumentColorRequest2.method = "textDocument/documentColor";
3246     DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
3247     DocumentColorRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3248   })(DocumentColorRequest = exports2.DocumentColorRequest || (exports2.DocumentColorRequest = {}));
3249   var ColorPresentationRequest;
3250   (function(ColorPresentationRequest2) {
3251     ColorPresentationRequest2.type = new messages_1.ProtocolRequestType("textDocument/colorPresentation");
3252   })(ColorPresentationRequest = exports2.ColorPresentationRequest || (exports2.ColorPresentationRequest = {}));
3253 });
3254
3255 // node_modules/vscode-languageserver-protocol/lib/protocol.foldingRange.js
3256 var require_protocol_foldingRange = __commonJS((exports2) => {
3257   "use strict";
3258   Object.defineProperty(exports2, "__esModule", {value: true});
3259   var vscode_jsonrpc_1 = require_main();
3260   var messages_1 = require_messages2();
3261   var FoldingRangeKind;
3262   (function(FoldingRangeKind2) {
3263     FoldingRangeKind2["Comment"] = "comment";
3264     FoldingRangeKind2["Imports"] = "imports";
3265     FoldingRangeKind2["Region"] = "region";
3266   })(FoldingRangeKind = exports2.FoldingRangeKind || (exports2.FoldingRangeKind = {}));
3267   var FoldingRangeRequest;
3268   (function(FoldingRangeRequest2) {
3269     FoldingRangeRequest2.method = "textDocument/foldingRange";
3270     FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
3271     FoldingRangeRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3272   })(FoldingRangeRequest = exports2.FoldingRangeRequest || (exports2.FoldingRangeRequest = {}));
3273 });
3274
3275 // node_modules/vscode-languageserver-protocol/lib/protocol.declaration.js
3276 var require_protocol_declaration = __commonJS((exports2) => {
3277   "use strict";
3278   Object.defineProperty(exports2, "__esModule", {value: true});
3279   var vscode_jsonrpc_1 = require_main();
3280   var messages_1 = require_messages2();
3281   var DeclarationRequest;
3282   (function(DeclarationRequest2) {
3283     DeclarationRequest2.method = "textDocument/declaration";
3284     DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
3285     DeclarationRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3286   })(DeclarationRequest = exports2.DeclarationRequest || (exports2.DeclarationRequest = {}));
3287 });
3288
3289 // node_modules/vscode-languageserver-protocol/lib/protocol.selectionRange.js
3290 var require_protocol_selectionRange = __commonJS((exports2) => {
3291   "use strict";
3292   Object.defineProperty(exports2, "__esModule", {value: true});
3293   var vscode_jsonrpc_1 = require_main();
3294   var messages_1 = require_messages2();
3295   var SelectionRangeRequest;
3296   (function(SelectionRangeRequest2) {
3297     SelectionRangeRequest2.method = "textDocument/selectionRange";
3298     SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
3299     SelectionRangeRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3300   })(SelectionRangeRequest = exports2.SelectionRangeRequest || (exports2.SelectionRangeRequest = {}));
3301 });
3302
3303 // node_modules/vscode-languageserver-protocol/lib/protocol.progress.js
3304 var require_protocol_progress = __commonJS((exports2) => {
3305   "use strict";
3306   Object.defineProperty(exports2, "__esModule", {value: true});
3307   var vscode_jsonrpc_1 = require_main();
3308   var messages_1 = require_messages2();
3309   var WorkDoneProgress;
3310   (function(WorkDoneProgress2) {
3311     WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
3312   })(WorkDoneProgress = exports2.WorkDoneProgress || (exports2.WorkDoneProgress = {}));
3313   var WorkDoneProgressCreateRequest;
3314   (function(WorkDoneProgressCreateRequest2) {
3315     WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType("window/workDoneProgress/create");
3316   })(WorkDoneProgressCreateRequest = exports2.WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = {}));
3317   var WorkDoneProgressCancelNotification;
3318   (function(WorkDoneProgressCancelNotification2) {
3319     WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType("window/workDoneProgress/cancel");
3320   })(WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = {}));
3321 });
3322
3323 // node_modules/vscode-languageserver-protocol/lib/protocol.js
3324 var require_protocol = __commonJS((exports2) => {
3325   "use strict";
3326   Object.defineProperty(exports2, "__esModule", {value: true});
3327   var Is = require_is2();
3328   var vscode_jsonrpc_1 = require_main();
3329   var messages_1 = require_messages2();
3330   var protocol_implementation_1 = require_protocol_implementation();
3331   exports2.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
3332   var protocol_typeDefinition_1 = require_protocol_typeDefinition();
3333   exports2.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
3334   var protocol_workspaceFolders_1 = require_protocol_workspaceFolders();
3335   exports2.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
3336   exports2.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
3337   var protocol_configuration_1 = require_protocol_configuration();
3338   exports2.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
3339   var protocol_colorProvider_1 = require_protocol_colorProvider();
3340   exports2.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
3341   exports2.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
3342   var protocol_foldingRange_1 = require_protocol_foldingRange();
3343   exports2.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
3344   var protocol_declaration_1 = require_protocol_declaration();
3345   exports2.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
3346   var protocol_selectionRange_1 = require_protocol_selectionRange();
3347   exports2.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
3348   var protocol_progress_1 = require_protocol_progress();
3349   exports2.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
3350   exports2.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
3351   exports2.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
3352   var DocumentFilter;
3353   (function(DocumentFilter2) {
3354     function is2(value) {
3355       const candidate = value;
3356       return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
3357     }
3358     DocumentFilter2.is = is2;
3359   })(DocumentFilter = exports2.DocumentFilter || (exports2.DocumentFilter = {}));
3360   var DocumentSelector2;
3361   (function(DocumentSelector3) {
3362     function is2(value) {
3363       if (!Array.isArray(value)) {
3364         return false;
3365       }
3366       for (let elem of value) {
3367         if (!Is.string(elem) && !DocumentFilter.is(elem)) {
3368           return false;
3369         }
3370       }
3371       return true;
3372     }
3373     DocumentSelector3.is = is2;
3374   })(DocumentSelector2 = exports2.DocumentSelector || (exports2.DocumentSelector = {}));
3375   var RegistrationRequest;
3376   (function(RegistrationRequest2) {
3377     RegistrationRequest2.type = new messages_1.ProtocolRequestType("client/registerCapability");
3378   })(RegistrationRequest = exports2.RegistrationRequest || (exports2.RegistrationRequest = {}));
3379   var UnregistrationRequest;
3380   (function(UnregistrationRequest2) {
3381     UnregistrationRequest2.type = new messages_1.ProtocolRequestType("client/unregisterCapability");
3382   })(UnregistrationRequest = exports2.UnregistrationRequest || (exports2.UnregistrationRequest = {}));
3383   var ResourceOperationKind;
3384   (function(ResourceOperationKind2) {
3385     ResourceOperationKind2.Create = "create";
3386     ResourceOperationKind2.Rename = "rename";
3387     ResourceOperationKind2.Delete = "delete";
3388   })(ResourceOperationKind = exports2.ResourceOperationKind || (exports2.ResourceOperationKind = {}));
3389   var FailureHandlingKind;
3390   (function(FailureHandlingKind2) {
3391     FailureHandlingKind2.Abort = "abort";
3392     FailureHandlingKind2.Transactional = "transactional";
3393     FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
3394     FailureHandlingKind2.Undo = "undo";
3395   })(FailureHandlingKind = exports2.FailureHandlingKind || (exports2.FailureHandlingKind = {}));
3396   var StaticRegistrationOptions;
3397   (function(StaticRegistrationOptions2) {
3398     function hasId(value) {
3399       const candidate = value;
3400       return candidate && Is.string(candidate.id) && candidate.id.length > 0;
3401     }
3402     StaticRegistrationOptions2.hasId = hasId;
3403   })(StaticRegistrationOptions = exports2.StaticRegistrationOptions || (exports2.StaticRegistrationOptions = {}));
3404   var TextDocumentRegistrationOptions;
3405   (function(TextDocumentRegistrationOptions2) {
3406     function is2(value) {
3407       const candidate = value;
3408       return candidate && (candidate.documentSelector === null || DocumentSelector2.is(candidate.documentSelector));
3409     }
3410     TextDocumentRegistrationOptions2.is = is2;
3411   })(TextDocumentRegistrationOptions = exports2.TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = {}));
3412   var WorkDoneProgressOptions;
3413   (function(WorkDoneProgressOptions2) {
3414     function is2(value) {
3415       const candidate = value;
3416       return Is.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is.boolean(candidate.workDoneProgress));
3417     }
3418     WorkDoneProgressOptions2.is = is2;
3419     function hasWorkDoneProgress(value) {
3420       const candidate = value;
3421       return candidate && Is.boolean(candidate.workDoneProgress);
3422     }
3423     WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
3424   })(WorkDoneProgressOptions = exports2.WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = {}));
3425   var InitializeRequest;
3426   (function(InitializeRequest2) {
3427     InitializeRequest2.type = new messages_1.ProtocolRequestType("initialize");
3428   })(InitializeRequest = exports2.InitializeRequest || (exports2.InitializeRequest = {}));
3429   var InitializeError;
3430   (function(InitializeError2) {
3431     InitializeError2.unknownProtocolVersion = 1;
3432   })(InitializeError = exports2.InitializeError || (exports2.InitializeError = {}));
3433   var InitializedNotification;
3434   (function(InitializedNotification2) {
3435     InitializedNotification2.type = new messages_1.ProtocolNotificationType("initialized");
3436   })(InitializedNotification = exports2.InitializedNotification || (exports2.InitializedNotification = {}));
3437   var ShutdownRequest;
3438   (function(ShutdownRequest2) {
3439     ShutdownRequest2.type = new messages_1.ProtocolRequestType0("shutdown");
3440   })(ShutdownRequest = exports2.ShutdownRequest || (exports2.ShutdownRequest = {}));
3441   var ExitNotification;
3442   (function(ExitNotification2) {
3443     ExitNotification2.type = new messages_1.ProtocolNotificationType0("exit");
3444   })(ExitNotification = exports2.ExitNotification || (exports2.ExitNotification = {}));
3445   var DidChangeConfigurationNotification;
3446   (function(DidChangeConfigurationNotification2) {
3447     DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeConfiguration");
3448   })(DidChangeConfigurationNotification = exports2.DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = {}));
3449   var MessageType;
3450   (function(MessageType2) {
3451     MessageType2.Error = 1;
3452     MessageType2.Warning = 2;
3453     MessageType2.Info = 3;
3454     MessageType2.Log = 4;
3455   })(MessageType = exports2.MessageType || (exports2.MessageType = {}));
3456   var ShowMessageNotification;
3457   (function(ShowMessageNotification2) {
3458     ShowMessageNotification2.type = new messages_1.ProtocolNotificationType("window/showMessage");
3459   })(ShowMessageNotification = exports2.ShowMessageNotification || (exports2.ShowMessageNotification = {}));
3460   var ShowMessageRequest;
3461   (function(ShowMessageRequest2) {
3462     ShowMessageRequest2.type = new messages_1.ProtocolRequestType("window/showMessageRequest");
3463   })(ShowMessageRequest = exports2.ShowMessageRequest || (exports2.ShowMessageRequest = {}));
3464   var LogMessageNotification;
3465   (function(LogMessageNotification2) {
3466     LogMessageNotification2.type = new messages_1.ProtocolNotificationType("window/logMessage");
3467   })(LogMessageNotification = exports2.LogMessageNotification || (exports2.LogMessageNotification = {}));
3468   var TelemetryEventNotification;
3469   (function(TelemetryEventNotification2) {
3470     TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType("telemetry/event");
3471   })(TelemetryEventNotification = exports2.TelemetryEventNotification || (exports2.TelemetryEventNotification = {}));
3472   var TextDocumentSyncKind;
3473   (function(TextDocumentSyncKind2) {
3474     TextDocumentSyncKind2.None = 0;
3475     TextDocumentSyncKind2.Full = 1;
3476     TextDocumentSyncKind2.Incremental = 2;
3477   })(TextDocumentSyncKind = exports2.TextDocumentSyncKind || (exports2.TextDocumentSyncKind = {}));
3478   var DidOpenTextDocumentNotification;
3479   (function(DidOpenTextDocumentNotification2) {
3480     DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
3481     DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
3482   })(DidOpenTextDocumentNotification = exports2.DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = {}));
3483   var DidChangeTextDocumentNotification;
3484   (function(DidChangeTextDocumentNotification2) {
3485     DidChangeTextDocumentNotification2.method = "textDocument/didChange";
3486     DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
3487   })(DidChangeTextDocumentNotification = exports2.DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = {}));
3488   var DidCloseTextDocumentNotification;
3489   (function(DidCloseTextDocumentNotification2) {
3490     DidCloseTextDocumentNotification2.method = "textDocument/didClose";
3491     DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
3492   })(DidCloseTextDocumentNotification = exports2.DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = {}));
3493   var DidSaveTextDocumentNotification;
3494   (function(DidSaveTextDocumentNotification2) {
3495     DidSaveTextDocumentNotification2.method = "textDocument/didSave";
3496     DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
3497   })(DidSaveTextDocumentNotification = exports2.DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = {}));
3498   var TextDocumentSaveReason;
3499   (function(TextDocumentSaveReason2) {
3500     TextDocumentSaveReason2.Manual = 1;
3501     TextDocumentSaveReason2.AfterDelay = 2;
3502     TextDocumentSaveReason2.FocusOut = 3;
3503   })(TextDocumentSaveReason = exports2.TextDocumentSaveReason || (exports2.TextDocumentSaveReason = {}));
3504   var WillSaveTextDocumentNotification;
3505   (function(WillSaveTextDocumentNotification2) {
3506     WillSaveTextDocumentNotification2.method = "textDocument/willSave";
3507     WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
3508   })(WillSaveTextDocumentNotification = exports2.WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = {}));
3509   var WillSaveTextDocumentWaitUntilRequest;
3510   (function(WillSaveTextDocumentWaitUntilRequest2) {
3511     WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
3512     WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
3513   })(WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = {}));
3514   var DidChangeWatchedFilesNotification;
3515   (function(DidChangeWatchedFilesNotification2) {
3516     DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWatchedFiles");
3517   })(DidChangeWatchedFilesNotification = exports2.DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = {}));
3518   var FileChangeType;
3519   (function(FileChangeType2) {
3520     FileChangeType2.Created = 1;
3521     FileChangeType2.Changed = 2;
3522     FileChangeType2.Deleted = 3;
3523   })(FileChangeType = exports2.FileChangeType || (exports2.FileChangeType = {}));
3524   var WatchKind;
3525   (function(WatchKind2) {
3526     WatchKind2.Create = 1;
3527     WatchKind2.Change = 2;
3528     WatchKind2.Delete = 4;
3529   })(WatchKind = exports2.WatchKind || (exports2.WatchKind = {}));
3530   var PublishDiagnosticsNotification;
3531   (function(PublishDiagnosticsNotification2) {
3532     PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType("textDocument/publishDiagnostics");
3533   })(PublishDiagnosticsNotification = exports2.PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = {}));
3534   var CompletionTriggerKind;
3535   (function(CompletionTriggerKind2) {
3536     CompletionTriggerKind2.Invoked = 1;
3537     CompletionTriggerKind2.TriggerCharacter = 2;
3538     CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
3539   })(CompletionTriggerKind = exports2.CompletionTriggerKind || (exports2.CompletionTriggerKind = {}));
3540   var CompletionRequest;
3541   (function(CompletionRequest2) {
3542     CompletionRequest2.method = "textDocument/completion";
3543     CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
3544     CompletionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3545   })(CompletionRequest = exports2.CompletionRequest || (exports2.CompletionRequest = {}));
3546   var CompletionResolveRequest;
3547   (function(CompletionResolveRequest2) {
3548     CompletionResolveRequest2.method = "completionItem/resolve";
3549     CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
3550   })(CompletionResolveRequest = exports2.CompletionResolveRequest || (exports2.CompletionResolveRequest = {}));
3551   var HoverRequest;
3552   (function(HoverRequest2) {
3553     HoverRequest2.method = "textDocument/hover";
3554     HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
3555   })(HoverRequest = exports2.HoverRequest || (exports2.HoverRequest = {}));
3556   var SignatureHelpTriggerKind;
3557   (function(SignatureHelpTriggerKind2) {
3558     SignatureHelpTriggerKind2.Invoked = 1;
3559     SignatureHelpTriggerKind2.TriggerCharacter = 2;
3560     SignatureHelpTriggerKind2.ContentChange = 3;
3561   })(SignatureHelpTriggerKind = exports2.SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = {}));
3562   var SignatureHelpRequest;
3563   (function(SignatureHelpRequest2) {
3564     SignatureHelpRequest2.method = "textDocument/signatureHelp";
3565     SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
3566   })(SignatureHelpRequest = exports2.SignatureHelpRequest || (exports2.SignatureHelpRequest = {}));
3567   var DefinitionRequest;
3568   (function(DefinitionRequest2) {
3569     DefinitionRequest2.method = "textDocument/definition";
3570     DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
3571     DefinitionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3572   })(DefinitionRequest = exports2.DefinitionRequest || (exports2.DefinitionRequest = {}));
3573   var ReferencesRequest;
3574   (function(ReferencesRequest2) {
3575     ReferencesRequest2.method = "textDocument/references";
3576     ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
3577     ReferencesRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3578   })(ReferencesRequest = exports2.ReferencesRequest || (exports2.ReferencesRequest = {}));
3579   var DocumentHighlightRequest;
3580   (function(DocumentHighlightRequest2) {
3581     DocumentHighlightRequest2.method = "textDocument/documentHighlight";
3582     DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
3583     DocumentHighlightRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3584   })(DocumentHighlightRequest = exports2.DocumentHighlightRequest || (exports2.DocumentHighlightRequest = {}));
3585   var DocumentSymbolRequest;
3586   (function(DocumentSymbolRequest2) {
3587     DocumentSymbolRequest2.method = "textDocument/documentSymbol";
3588     DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
3589     DocumentSymbolRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3590   })(DocumentSymbolRequest = exports2.DocumentSymbolRequest || (exports2.DocumentSymbolRequest = {}));
3591   var CodeActionRequest;
3592   (function(CodeActionRequest2) {
3593     CodeActionRequest2.method = "textDocument/codeAction";
3594     CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
3595     CodeActionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3596   })(CodeActionRequest = exports2.CodeActionRequest || (exports2.CodeActionRequest = {}));
3597   var WorkspaceSymbolRequest;
3598   (function(WorkspaceSymbolRequest2) {
3599     WorkspaceSymbolRequest2.method = "workspace/symbol";
3600     WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
3601     WorkspaceSymbolRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3602   })(WorkspaceSymbolRequest = exports2.WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = {}));
3603   var CodeLensRequest;
3604   (function(CodeLensRequest2) {
3605     CodeLensRequest2.type = new messages_1.ProtocolRequestType("textDocument/codeLens");
3606     CodeLensRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3607   })(CodeLensRequest = exports2.CodeLensRequest || (exports2.CodeLensRequest = {}));
3608   var CodeLensResolveRequest;
3609   (function(CodeLensResolveRequest2) {
3610     CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType("codeLens/resolve");
3611   })(CodeLensResolveRequest = exports2.CodeLensResolveRequest || (exports2.CodeLensResolveRequest = {}));
3612   var DocumentLinkRequest;
3613   (function(DocumentLinkRequest2) {
3614     DocumentLinkRequest2.method = "textDocument/documentLink";
3615     DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
3616     DocumentLinkRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
3617   })(DocumentLinkRequest = exports2.DocumentLinkRequest || (exports2.DocumentLinkRequest = {}));
3618   var DocumentLinkResolveRequest;
3619   (function(DocumentLinkResolveRequest2) {
3620     DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType("documentLink/resolve");
3621   })(DocumentLinkResolveRequest = exports2.DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = {}));
3622   var DocumentFormattingRequest;
3623   (function(DocumentFormattingRequest2) {
3624     DocumentFormattingRequest2.method = "textDocument/formatting";
3625     DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
3626   })(DocumentFormattingRequest = exports2.DocumentFormattingRequest || (exports2.DocumentFormattingRequest = {}));
3627   var DocumentRangeFormattingRequest;
3628   (function(DocumentRangeFormattingRequest2) {
3629     DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
3630     DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
3631   })(DocumentRangeFormattingRequest = exports2.DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = {}));
3632   var DocumentOnTypeFormattingRequest;
3633   (function(DocumentOnTypeFormattingRequest2) {
3634     DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
3635     DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
3636   })(DocumentOnTypeFormattingRequest = exports2.DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = {}));
3637   var RenameRequest;
3638   (function(RenameRequest2) {
3639     RenameRequest2.method = "textDocument/rename";
3640     RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
3641   })(RenameRequest = exports2.RenameRequest || (exports2.RenameRequest = {}));
3642   var PrepareRenameRequest;
3643   (function(PrepareRenameRequest2) {
3644     PrepareRenameRequest2.method = "textDocument/prepareRename";
3645     PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
3646   })(PrepareRenameRequest = exports2.PrepareRenameRequest || (exports2.PrepareRenameRequest = {}));
3647   var ExecuteCommandRequest;
3648   (function(ExecuteCommandRequest2) {
3649     ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType("workspace/executeCommand");
3650   })(ExecuteCommandRequest = exports2.ExecuteCommandRequest || (exports2.ExecuteCommandRequest = {}));
3651   var ApplyWorkspaceEditRequest;
3652   (function(ApplyWorkspaceEditRequest2) {
3653     ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
3654   })(ApplyWorkspaceEditRequest = exports2.ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = {}));
3655 });
3656
3657 // node_modules/vscode-languageserver-protocol/lib/protocol.callHierarchy.proposed.js
3658 var require_protocol_callHierarchy_proposed = __commonJS((exports2) => {
3659   "use strict";
3660   Object.defineProperty(exports2, "__esModule", {value: true});
3661   var messages_1 = require_messages2();
3662   var CallHierarchyPrepareRequest;
3663   (function(CallHierarchyPrepareRequest2) {
3664     CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
3665     CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
3666   })(CallHierarchyPrepareRequest = exports2.CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = {}));
3667   var CallHierarchyIncomingCallsRequest;
3668   (function(CallHierarchyIncomingCallsRequest2) {
3669     CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
3670     CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
3671   })(CallHierarchyIncomingCallsRequest = exports2.CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = {}));
3672   var CallHierarchyOutgoingCallsRequest;
3673   (function(CallHierarchyOutgoingCallsRequest2) {
3674     CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
3675     CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
3676   })(CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = {}));
3677 });
3678
3679 // node_modules/vscode-languageserver-protocol/lib/protocol.sematicTokens.proposed.js
3680 var require_protocol_sematicTokens_proposed = __commonJS((exports2) => {
3681   "use strict";
3682   Object.defineProperty(exports2, "__esModule", {value: true});
3683   var messages_1 = require_messages2();
3684   var SemanticTokenTypes;
3685   (function(SemanticTokenTypes2) {
3686     SemanticTokenTypes2["comment"] = "comment";
3687     SemanticTokenTypes2["keyword"] = "keyword";
3688     SemanticTokenTypes2["string"] = "string";
3689     SemanticTokenTypes2["number"] = "number";
3690     SemanticTokenTypes2["regexp"] = "regexp";
3691     SemanticTokenTypes2["operator"] = "operator";
3692     SemanticTokenTypes2["namespace"] = "namespace";
3693     SemanticTokenTypes2["type"] = "type";
3694     SemanticTokenTypes2["struct"] = "struct";
3695     SemanticTokenTypes2["class"] = "class";
3696     SemanticTokenTypes2["interface"] = "interface";
3697     SemanticTokenTypes2["enum"] = "enum";
3698     SemanticTokenTypes2["typeParameter"] = "typeParameter";
3699     SemanticTokenTypes2["function"] = "function";
3700     SemanticTokenTypes2["member"] = "member";
3701     SemanticTokenTypes2["property"] = "property";
3702     SemanticTokenTypes2["macro"] = "macro";
3703     SemanticTokenTypes2["variable"] = "variable";
3704     SemanticTokenTypes2["parameter"] = "parameter";
3705     SemanticTokenTypes2["label"] = "label";
3706   })(SemanticTokenTypes = exports2.SemanticTokenTypes || (exports2.SemanticTokenTypes = {}));
3707   var SemanticTokenModifiers;
3708   (function(SemanticTokenModifiers2) {
3709     SemanticTokenModifiers2["documentation"] = "documentation";
3710     SemanticTokenModifiers2["declaration"] = "declaration";
3711     SemanticTokenModifiers2["definition"] = "definition";
3712     SemanticTokenModifiers2["reference"] = "reference";
3713     SemanticTokenModifiers2["static"] = "static";
3714     SemanticTokenModifiers2["abstract"] = "abstract";
3715     SemanticTokenModifiers2["deprecated"] = "deprecated";
3716     SemanticTokenModifiers2["async"] = "async";
3717     SemanticTokenModifiers2["volatile"] = "volatile";
3718     SemanticTokenModifiers2["readonly"] = "readonly";
3719   })(SemanticTokenModifiers = exports2.SemanticTokenModifiers || (exports2.SemanticTokenModifiers = {}));
3720   var SemanticTokens;
3721   (function(SemanticTokens2) {
3722     function is2(value) {
3723       const candidate = value;
3724       return candidate !== void 0 && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
3725     }
3726     SemanticTokens2.is = is2;
3727   })(SemanticTokens = exports2.SemanticTokens || (exports2.SemanticTokens = {}));
3728   var SemanticTokensRequest;
3729   (function(SemanticTokensRequest2) {
3730     SemanticTokensRequest2.method = "textDocument/semanticTokens";
3731     SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
3732   })(SemanticTokensRequest = exports2.SemanticTokensRequest || (exports2.SemanticTokensRequest = {}));
3733   var SemanticTokensEditsRequest;
3734   (function(SemanticTokensEditsRequest2) {
3735     SemanticTokensEditsRequest2.method = "textDocument/semanticTokens/edits";
3736     SemanticTokensEditsRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest2.method);
3737   })(SemanticTokensEditsRequest = exports2.SemanticTokensEditsRequest || (exports2.SemanticTokensEditsRequest = {}));
3738   var SemanticTokensRangeRequest;
3739   (function(SemanticTokensRangeRequest2) {
3740     SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
3741     SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
3742   })(SemanticTokensRangeRequest = exports2.SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = {}));
3743 });
3744
3745 // node_modules/vscode-languageserver-protocol/lib/main.js
3746 var require_main3 = __commonJS((exports2) => {
3747   "use strict";
3748   function __export2(m) {
3749     for (var p in m)
3750       if (!exports2.hasOwnProperty(p))
3751         exports2[p] = m[p];
3752   }
3753   Object.defineProperty(exports2, "__esModule", {value: true});
3754   var vscode_jsonrpc_1 = require_main();
3755   exports2.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
3756   exports2.ResponseError = vscode_jsonrpc_1.ResponseError;
3757   exports2.CancellationToken = vscode_jsonrpc_1.CancellationToken;
3758   exports2.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
3759   exports2.Disposable = vscode_jsonrpc_1.Disposable;
3760   exports2.Event = vscode_jsonrpc_1.Event;
3761   exports2.Emitter = vscode_jsonrpc_1.Emitter;
3762   exports2.Trace = vscode_jsonrpc_1.Trace;
3763   exports2.TraceFormat = vscode_jsonrpc_1.TraceFormat;
3764   exports2.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
3765   exports2.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
3766   exports2.RequestType = vscode_jsonrpc_1.RequestType;
3767   exports2.RequestType0 = vscode_jsonrpc_1.RequestType0;
3768   exports2.NotificationType = vscode_jsonrpc_1.NotificationType;
3769   exports2.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
3770   exports2.MessageReader = vscode_jsonrpc_1.MessageReader;
3771   exports2.MessageWriter = vscode_jsonrpc_1.MessageWriter;
3772   exports2.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
3773   exports2.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
3774   exports2.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
3775   exports2.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
3776   exports2.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
3777   exports2.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
3778   exports2.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
3779   exports2.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
3780   exports2.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
3781   exports2.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
3782   exports2.ProgressType = vscode_jsonrpc_1.ProgressType;
3783   __export2(require_main2());
3784   __export2(require_protocol());
3785   var callHierarchy = require_protocol_callHierarchy_proposed();
3786   var st = require_protocol_sematicTokens_proposed();
3787   var Proposed;
3788   (function(Proposed2) {
3789     let CallHierarchyPrepareRequest;
3790     (function(CallHierarchyPrepareRequest2) {
3791       CallHierarchyPrepareRequest2.method = callHierarchy.CallHierarchyPrepareRequest.method;
3792       CallHierarchyPrepareRequest2.type = callHierarchy.CallHierarchyPrepareRequest.type;
3793     })(CallHierarchyPrepareRequest = Proposed2.CallHierarchyPrepareRequest || (Proposed2.CallHierarchyPrepareRequest = {}));
3794     let CallHierarchyIncomingCallsRequest;
3795     (function(CallHierarchyIncomingCallsRequest2) {
3796       CallHierarchyIncomingCallsRequest2.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
3797       CallHierarchyIncomingCallsRequest2.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
3798     })(CallHierarchyIncomingCallsRequest = Proposed2.CallHierarchyIncomingCallsRequest || (Proposed2.CallHierarchyIncomingCallsRequest = {}));
3799     let CallHierarchyOutgoingCallsRequest;
3800     (function(CallHierarchyOutgoingCallsRequest2) {
3801       CallHierarchyOutgoingCallsRequest2.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
3802       CallHierarchyOutgoingCallsRequest2.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
3803     })(CallHierarchyOutgoingCallsRequest = Proposed2.CallHierarchyOutgoingCallsRequest || (Proposed2.CallHierarchyOutgoingCallsRequest = {}));
3804     Proposed2.SemanticTokenTypes = st.SemanticTokenTypes;
3805     Proposed2.SemanticTokenModifiers = st.SemanticTokenModifiers;
3806     Proposed2.SemanticTokens = st.SemanticTokens;
3807     let SemanticTokensRequest;
3808     (function(SemanticTokensRequest2) {
3809       SemanticTokensRequest2.method = st.SemanticTokensRequest.method;
3810       SemanticTokensRequest2.type = st.SemanticTokensRequest.type;
3811     })(SemanticTokensRequest = Proposed2.SemanticTokensRequest || (Proposed2.SemanticTokensRequest = {}));
3812     let SemanticTokensEditsRequest;
3813     (function(SemanticTokensEditsRequest2) {
3814       SemanticTokensEditsRequest2.method = st.SemanticTokensEditsRequest.method;
3815       SemanticTokensEditsRequest2.type = st.SemanticTokensEditsRequest.type;
3816     })(SemanticTokensEditsRequest = Proposed2.SemanticTokensEditsRequest || (Proposed2.SemanticTokensEditsRequest = {}));
3817     let SemanticTokensRangeRequest;
3818     (function(SemanticTokensRangeRequest2) {
3819       SemanticTokensRangeRequest2.method = st.SemanticTokensRangeRequest.method;
3820       SemanticTokensRangeRequest2.type = st.SemanticTokensRangeRequest.type;
3821     })(SemanticTokensRangeRequest = Proposed2.SemanticTokensRangeRequest || (Proposed2.SemanticTokensRangeRequest = {}));
3822   })(Proposed = exports2.Proposed || (exports2.Proposed = {}));
3823   function createProtocolConnection(reader, writer, logger, strategy) {
3824     return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
3825   }
3826   exports2.createProtocolConnection = createProtocolConnection;
3827 });
3828
3829 // node_modules/semver/internal/constants.js
3830 var require_constants = __commonJS((exports2, module2) => {
3831   var SEMVER_SPEC_VERSION = "2.0.0";
3832   var MAX_LENGTH = 256;
3833   var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
3834   var MAX_SAFE_COMPONENT_LENGTH = 16;
3835   module2.exports = {
3836     SEMVER_SPEC_VERSION,
3837     MAX_LENGTH,
3838     MAX_SAFE_INTEGER,
3839     MAX_SAFE_COMPONENT_LENGTH
3840   };
3841 });
3842
3843 // node_modules/semver/internal/debug.js
3844 var require_debug = __commonJS((exports2, module2) => {
3845   var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
3846   };
3847   module2.exports = debug;
3848 });
3849
3850 // node_modules/semver/internal/re.js
3851 var require_re = __commonJS((exports2, module2) => {
3852   var {MAX_SAFE_COMPONENT_LENGTH} = require_constants();
3853   var debug = require_debug();
3854   exports2 = module2.exports = {};
3855   var re = exports2.re = [];
3856   var src = exports2.src = [];
3857   var t = exports2.t = {};
3858   var R = 0;
3859   var createToken = (name, value, isGlobal) => {
3860     const index = R++;
3861     debug(index, value);
3862     t[name] = index;
3863     src[index] = value;
3864     re[index] = new RegExp(value, isGlobal ? "g" : void 0);
3865   };
3866   createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
3867   createToken("NUMERICIDENTIFIERLOOSE", "[0-9]+");
3868   createToken("NONNUMERICIDENTIFIER", "\\d*[a-zA-Z-][a-zA-Z0-9-]*");
3869   createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
3870   createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
3871   createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
3872   createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`);
3873   createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
3874   createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
3875   createToken("BUILDIDENTIFIER", "[0-9A-Za-z-]+");
3876   createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
3877   createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
3878   createToken("FULL", `^${src[t.FULLPLAIN]}$`);
3879   createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
3880   createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
3881   createToken("GTLT", "((?:<|>)?=?)");
3882   createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
3883   createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
3884   createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
3885   createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
3886   createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
3887   createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
3888   createToken("COERCE", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:$|[^\\d])`);
3889   createToken("COERCERTL", src[t.COERCE], true);
3890   createToken("LONETILDE", "(?:~>?)");
3891   createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
3892   exports2.tildeTrimReplace = "$1~";
3893   createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
3894   createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
3895   createToken("LONECARET", "(?:\\^)");
3896   createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
3897   exports2.caretTrimReplace = "$1^";
3898   createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
3899   createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
3900   createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
3901   createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
3902   createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
3903   exports2.comparatorTrimReplace = "$1$2$3";
3904   createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
3905   createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
3906   createToken("STAR", "(<|>)?=?\\s*\\*");
3907   createToken("GTE0", "^\\s*>=\\s*0.0.0\\s*$");
3908   createToken("GTE0PRE", "^\\s*>=\\s*0.0.0-0\\s*$");
3909 });
3910
3911 // node_modules/semver/internal/identifiers.js
3912 var require_identifiers = __commonJS((exports2, module2) => {
3913   var numeric = /^[0-9]+$/;
3914   var compareIdentifiers = (a, b) => {
3915     const anum = numeric.test(a);
3916     const bnum = numeric.test(b);
3917     if (anum && bnum) {
3918       a = +a;
3919       b = +b;
3920     }
3921     return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
3922   };
3923   var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
3924   module2.exports = {
3925     compareIdentifiers,
3926     rcompareIdentifiers
3927   };
3928 });
3929
3930 // node_modules/semver/classes/semver.js
3931 var require_semver = __commonJS((exports2, module2) => {
3932   var debug = require_debug();
3933   var {MAX_LENGTH, MAX_SAFE_INTEGER} = require_constants();
3934   var {re, t} = require_re();
3935   var {compareIdentifiers} = require_identifiers();
3936   var SemVer = class {
3937     constructor(version, options) {
3938       if (!options || typeof options !== "object") {
3939         options = {
3940           loose: !!options,
3941           includePrerelease: false
3942         };
3943       }
3944       if (version instanceof SemVer) {
3945         if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
3946           return version;
3947         } else {
3948           version = version.version;
3949         }
3950       } else if (typeof version !== "string") {
3951         throw new TypeError(`Invalid Version: ${version}`);
3952       }
3953       if (version.length > MAX_LENGTH) {
3954         throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
3955       }
3956       debug("SemVer", version, options);
3957       this.options = options;
3958       this.loose = !!options.loose;
3959       this.includePrerelease = !!options.includePrerelease;
3960       const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
3961       if (!m) {
3962         throw new TypeError(`Invalid Version: ${version}`);
3963       }
3964       this.raw = version;
3965       this.major = +m[1];
3966       this.minor = +m[2];
3967       this.patch = +m[3];
3968       if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
3969         throw new TypeError("Invalid major version");
3970       }
3971       if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
3972         throw new TypeError("Invalid minor version");
3973       }
3974       if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
3975         throw new TypeError("Invalid patch version");
3976       }
3977       if (!m[4]) {
3978         this.prerelease = [];
3979       } else {
3980         this.prerelease = m[4].split(".").map((id) => {
3981           if (/^[0-9]+$/.test(id)) {
3982             const num = +id;
3983             if (num >= 0 && num < MAX_SAFE_INTEGER) {
3984               return num;
3985             }
3986           }
3987           return id;
3988         });
3989       }
3990       this.build = m[5] ? m[5].split(".") : [];
3991       this.format();
3992     }
3993     format() {
3994       this.version = `${this.major}.${this.minor}.${this.patch}`;
3995       if (this.prerelease.length) {
3996         this.version += `-${this.prerelease.join(".")}`;
3997       }
3998       return this.version;
3999     }
4000     toString() {
4001       return this.version;
4002     }
4003     compare(other) {
4004       debug("SemVer.compare", this.version, this.options, other);
4005       if (!(other instanceof SemVer)) {
4006         if (typeof other === "string" && other === this.version) {
4007           return 0;
4008         }
4009         other = new SemVer(other, this.options);
4010       }
4011       if (other.version === this.version) {
4012         return 0;
4013       }
4014       return this.compareMain(other) || this.comparePre(other);
4015     }
4016     compareMain(other) {
4017       if (!(other instanceof SemVer)) {
4018         other = new SemVer(other, this.options);
4019       }
4020       return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
4021     }
4022     comparePre(other) {
4023       if (!(other instanceof SemVer)) {
4024         other = new SemVer(other, this.options);
4025       }
4026       if (this.prerelease.length && !other.prerelease.length) {
4027         return -1;
4028       } else if (!this.prerelease.length && other.prerelease.length) {
4029         return 1;
4030       } else if (!this.prerelease.length && !other.prerelease.length) {
4031         return 0;
4032       }
4033       let i = 0;
4034       do {
4035         const a = this.prerelease[i];
4036         const b = other.prerelease[i];
4037         debug("prerelease compare", i, a, b);
4038         if (a === void 0 && b === void 0) {
4039           return 0;
4040         } else if (b === void 0) {
4041           return 1;
4042         } else if (a === void 0) {
4043           return -1;
4044         } else if (a === b) {
4045           continue;
4046         } else {
4047           return compareIdentifiers(a, b);
4048         }
4049       } while (++i);
4050     }
4051     compareBuild(other) {
4052       if (!(other instanceof SemVer)) {
4053         other = new SemVer(other, this.options);
4054       }
4055       let i = 0;
4056       do {
4057         const a = this.build[i];
4058         const b = other.build[i];
4059         debug("prerelease compare", i, a, b);
4060         if (a === void 0 && b === void 0) {
4061           return 0;
4062         } else if (b === void 0) {
4063           return 1;
4064         } else if (a === void 0) {
4065           return -1;
4066         } else if (a === b) {
4067           continue;
4068         } else {
4069           return compareIdentifiers(a, b);
4070         }
4071       } while (++i);
4072     }
4073     inc(release, identifier) {
4074       switch (release) {
4075         case "premajor":
4076           this.prerelease.length = 0;
4077           this.patch = 0;
4078           this.minor = 0;
4079           this.major++;
4080           this.inc("pre", identifier);
4081           break;
4082         case "preminor":
4083           this.prerelease.length = 0;
4084           this.patch = 0;
4085           this.minor++;
4086           this.inc("pre", identifier);
4087           break;
4088         case "prepatch":
4089           this.prerelease.length = 0;
4090           this.inc("patch", identifier);
4091           this.inc("pre", identifier);
4092           break;
4093         case "prerelease":
4094           if (this.prerelease.length === 0) {
4095             this.inc("patch", identifier);
4096           }
4097           this.inc("pre", identifier);
4098           break;
4099         case "major":
4100           if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
4101             this.major++;
4102           }
4103           this.minor = 0;
4104           this.patch = 0;
4105           this.prerelease = [];
4106           break;
4107         case "minor":
4108           if (this.patch !== 0 || this.prerelease.length === 0) {
4109             this.minor++;
4110           }
4111           this.patch = 0;
4112           this.prerelease = [];
4113           break;
4114         case "patch":
4115           if (this.prerelease.length === 0) {
4116             this.patch++;
4117           }
4118           this.prerelease = [];
4119           break;
4120         case "pre":
4121           if (this.prerelease.length === 0) {
4122             this.prerelease = [0];
4123           } else {
4124             let i = this.prerelease.length;
4125             while (--i >= 0) {
4126               if (typeof this.prerelease[i] === "number") {
4127                 this.prerelease[i]++;
4128                 i = -2;
4129               }
4130             }
4131             if (i === -1) {
4132               this.prerelease.push(0);
4133             }
4134           }
4135           if (identifier) {
4136             if (this.prerelease[0] === identifier) {
4137               if (isNaN(this.prerelease[1])) {
4138                 this.prerelease = [identifier, 0];
4139               }
4140             } else {
4141               this.prerelease = [identifier, 0];
4142             }
4143           }
4144           break;
4145         default:
4146           throw new Error(`invalid increment argument: ${release}`);
4147       }
4148       this.format();
4149       this.raw = this.version;
4150       return this;
4151     }
4152   };
4153   module2.exports = SemVer;
4154 });
4155
4156 // node_modules/semver/functions/parse.js
4157 var require_parse = __commonJS((exports2, module2) => {
4158   var {MAX_LENGTH} = require_constants();
4159   var {re, t} = require_re();
4160   var SemVer = require_semver();
4161   var parse = (version, options) => {
4162     if (!options || typeof options !== "object") {
4163       options = {
4164         loose: !!options,
4165         includePrerelease: false
4166       };
4167     }
4168     if (version instanceof SemVer) {
4169       return version;
4170     }
4171     if (typeof version !== "string") {
4172       return null;
4173     }
4174     if (version.length > MAX_LENGTH) {
4175       return null;
4176     }
4177     const r = options.loose ? re[t.LOOSE] : re[t.FULL];
4178     if (!r.test(version)) {
4179       return null;
4180     }
4181     try {
4182       return new SemVer(version, options);
4183     } catch (er) {
4184       return null;
4185     }
4186   };
4187   module2.exports = parse;
4188 });
4189
4190 // node_modules/semver/functions/valid.js
4191 var require_valid = __commonJS((exports2, module2) => {
4192   var parse = require_parse();
4193   var valid2 = (version, options) => {
4194     const v = parse(version, options);
4195     return v ? v.version : null;
4196   };
4197   module2.exports = valid2;
4198 });
4199
4200 // node_modules/semver/functions/clean.js
4201 var require_clean = __commonJS((exports2, module2) => {
4202   var parse = require_parse();
4203   var clean = (version, options) => {
4204     const s = parse(version.trim().replace(/^[=v]+/, ""), options);
4205     return s ? s.version : null;
4206   };
4207   module2.exports = clean;
4208 });
4209
4210 // node_modules/semver/functions/inc.js
4211 var require_inc = __commonJS((exports2, module2) => {
4212   var SemVer = require_semver();
4213   var inc = (version, release, options, identifier) => {
4214     if (typeof options === "string") {
4215       identifier = options;
4216       options = void 0;
4217     }
4218     try {
4219       return new SemVer(version, options).inc(release, identifier).version;
4220     } catch (er) {
4221       return null;
4222     }
4223   };
4224   module2.exports = inc;
4225 });
4226
4227 // node_modules/semver/functions/compare.js
4228 var require_compare = __commonJS((exports2, module2) => {
4229   var SemVer = require_semver();
4230   var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
4231   module2.exports = compare;
4232 });
4233
4234 // node_modules/semver/functions/eq.js
4235 var require_eq = __commonJS((exports2, module2) => {
4236   var compare = require_compare();
4237   var eq = (a, b, loose) => compare(a, b, loose) === 0;
4238   module2.exports = eq;
4239 });
4240
4241 // node_modules/semver/functions/diff.js
4242 var require_diff = __commonJS((exports2, module2) => {
4243   var parse = require_parse();
4244   var eq = require_eq();
4245   var diff = (version1, version2) => {
4246     if (eq(version1, version2)) {
4247       return null;
4248     } else {
4249       const v1 = parse(version1);
4250       const v2 = parse(version2);
4251       const hasPre = v1.prerelease.length || v2.prerelease.length;
4252       const prefix = hasPre ? "pre" : "";
4253       const defaultResult = hasPre ? "prerelease" : "";
4254       for (const key in v1) {
4255         if (key === "major" || key === "minor" || key === "patch") {
4256           if (v1[key] !== v2[key]) {
4257             return prefix + key;
4258           }
4259         }
4260       }
4261       return defaultResult;
4262     }
4263   };
4264   module2.exports = diff;
4265 });
4266
4267 // node_modules/semver/functions/major.js
4268 var require_major = __commonJS((exports2, module2) => {
4269   var SemVer = require_semver();
4270   var major = (a, loose) => new SemVer(a, loose).major;
4271   module2.exports = major;
4272 });
4273
4274 // node_modules/semver/functions/minor.js
4275 var require_minor = __commonJS((exports2, module2) => {
4276   var SemVer = require_semver();
4277   var minor = (a, loose) => new SemVer(a, loose).minor;
4278   module2.exports = minor;
4279 });
4280
4281 // node_modules/semver/functions/patch.js
4282 var require_patch = __commonJS((exports2, module2) => {
4283   var SemVer = require_semver();
4284   var patch = (a, loose) => new SemVer(a, loose).patch;
4285   module2.exports = patch;
4286 });
4287
4288 // node_modules/semver/functions/prerelease.js
4289 var require_prerelease = __commonJS((exports2, module2) => {
4290   var parse = require_parse();
4291   var prerelease = (version, options) => {
4292     const parsed = parse(version, options);
4293     return parsed && parsed.prerelease.length ? parsed.prerelease : null;
4294   };
4295   module2.exports = prerelease;
4296 });
4297
4298 // node_modules/semver/functions/rcompare.js
4299 var require_rcompare = __commonJS((exports2, module2) => {
4300   var compare = require_compare();
4301   var rcompare = (a, b, loose) => compare(b, a, loose);
4302   module2.exports = rcompare;
4303 });
4304
4305 // node_modules/semver/functions/compare-loose.js
4306 var require_compare_loose = __commonJS((exports2, module2) => {
4307   var compare = require_compare();
4308   var compareLoose = (a, b) => compare(a, b, true);
4309   module2.exports = compareLoose;
4310 });
4311
4312 // node_modules/semver/functions/compare-build.js
4313 var require_compare_build = __commonJS((exports2, module2) => {
4314   var SemVer = require_semver();
4315   var compareBuild = (a, b, loose) => {
4316     const versionA = new SemVer(a, loose);
4317     const versionB = new SemVer(b, loose);
4318     return versionA.compare(versionB) || versionA.compareBuild(versionB);
4319   };
4320   module2.exports = compareBuild;
4321 });
4322
4323 // node_modules/semver/functions/sort.js
4324 var require_sort = __commonJS((exports2, module2) => {
4325   var compareBuild = require_compare_build();
4326   var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
4327   module2.exports = sort;
4328 });
4329
4330 // node_modules/semver/functions/rsort.js
4331 var require_rsort = __commonJS((exports2, module2) => {
4332   var compareBuild = require_compare_build();
4333   var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
4334   module2.exports = rsort;
4335 });
4336
4337 // node_modules/semver/functions/gt.js
4338 var require_gt = __commonJS((exports2, module2) => {
4339   var compare = require_compare();
4340   var gt = (a, b, loose) => compare(a, b, loose) > 0;
4341   module2.exports = gt;
4342 });
4343
4344 // node_modules/semver/functions/lt.js
4345 var require_lt = __commonJS((exports2, module2) => {
4346   var compare = require_compare();
4347   var lt = (a, b, loose) => compare(a, b, loose) < 0;
4348   module2.exports = lt;
4349 });
4350
4351 // node_modules/semver/functions/neq.js
4352 var require_neq = __commonJS((exports2, module2) => {
4353   var compare = require_compare();
4354   var neq = (a, b, loose) => compare(a, b, loose) !== 0;
4355   module2.exports = neq;
4356 });
4357
4358 // node_modules/semver/functions/gte.js
4359 var require_gte = __commonJS((exports2, module2) => {
4360   var compare = require_compare();
4361   var gte2 = (a, b, loose) => compare(a, b, loose) >= 0;
4362   module2.exports = gte2;
4363 });
4364
4365 // node_modules/semver/functions/lte.js
4366 var require_lte = __commonJS((exports2, module2) => {
4367   var compare = require_compare();
4368   var lte = (a, b, loose) => compare(a, b, loose) <= 0;
4369   module2.exports = lte;
4370 });
4371
4372 // node_modules/semver/functions/cmp.js
4373 var require_cmp = __commonJS((exports2, module2) => {
4374   var eq = require_eq();
4375   var neq = require_neq();
4376   var gt = require_gt();
4377   var gte2 = require_gte();
4378   var lt = require_lt();
4379   var lte = require_lte();
4380   var cmp = (a, op, b, loose) => {
4381     switch (op) {
4382       case "===":
4383         if (typeof a === "object")
4384           a = a.version;
4385         if (typeof b === "object")
4386           b = b.version;
4387         return a === b;
4388       case "!==":
4389         if (typeof a === "object")
4390           a = a.version;
4391         if (typeof b === "object")
4392           b = b.version;
4393         return a !== b;
4394       case "":
4395       case "=":
4396       case "==":
4397         return eq(a, b, loose);
4398       case "!=":
4399         return neq(a, b, loose);
4400       case ">":
4401         return gt(a, b, loose);
4402       case ">=":
4403         return gte2(a, b, loose);
4404       case "<":
4405         return lt(a, b, loose);
4406       case "<=":
4407         return lte(a, b, loose);
4408       default:
4409         throw new TypeError(`Invalid operator: ${op}`);
4410     }
4411   };
4412   module2.exports = cmp;
4413 });
4414
4415 // node_modules/semver/functions/coerce.js
4416 var require_coerce = __commonJS((exports2, module2) => {
4417   var SemVer = require_semver();
4418   var parse = require_parse();
4419   var {re, t} = require_re();
4420   var coerce = (version, options) => {
4421     if (version instanceof SemVer) {
4422       return version;
4423     }
4424     if (typeof version === "number") {
4425       version = String(version);
4426     }
4427     if (typeof version !== "string") {
4428       return null;
4429     }
4430     options = options || {};
4431     let match = null;
4432     if (!options.rtl) {
4433       match = version.match(re[t.COERCE]);
4434     } else {
4435       let next;
4436       while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
4437         if (!match || next.index + next[0].length !== match.index + match[0].length) {
4438           match = next;
4439         }
4440         re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
4441       }
4442       re[t.COERCERTL].lastIndex = -1;
4443     }
4444     if (match === null)
4445       return null;
4446     return parse(`${match[2]}.${match[3] || "0"}.${match[4] || "0"}`, options);
4447   };
4448   module2.exports = coerce;
4449 });
4450
4451 // node_modules/semver/classes/range.js
4452 var require_range = __commonJS((exports2, module2) => {
4453   var Range15 = class {
4454     constructor(range, options) {
4455       if (!options || typeof options !== "object") {
4456         options = {
4457           loose: !!options,
4458           includePrerelease: false
4459         };
4460       }
4461       if (range instanceof Range15) {
4462         if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
4463           return range;
4464         } else {
4465           return new Range15(range.raw, options);
4466         }
4467       }
4468       if (range instanceof Comparator) {
4469         this.raw = range.value;
4470         this.set = [[range]];
4471         this.format();
4472         return this;
4473       }
4474       this.options = options;
4475       this.loose = !!options.loose;
4476       this.includePrerelease = !!options.includePrerelease;
4477       this.raw = range;
4478       this.set = range.split(/\s*\|\|\s*/).map((range2) => this.parseRange(range2.trim())).filter((c) => c.length);
4479       if (!this.set.length) {
4480         throw new TypeError(`Invalid SemVer Range: ${range}`);
4481       }
4482       this.format();
4483     }
4484     format() {
4485       this.range = this.set.map((comps) => {
4486         return comps.join(" ").trim();
4487       }).join("||").trim();
4488       return this.range;
4489     }
4490     toString() {
4491       return this.range;
4492     }
4493     parseRange(range) {
4494       const loose = this.options.loose;
4495       range = range.trim();
4496       const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
4497       range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
4498       debug("hyphen replace", range);
4499       range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
4500       debug("comparator trim", range, re[t.COMPARATORTRIM]);
4501       range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
4502       range = range.replace(re[t.CARETTRIM], caretTrimReplace);
4503       range = range.split(/\s+/).join(" ");
4504       const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
4505       return range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)).filter(this.options.loose ? (comp) => !!comp.match(compRe) : () => true).map((comp) => new Comparator(comp, this.options));
4506     }
4507     intersects(range, options) {
4508       if (!(range instanceof Range15)) {
4509         throw new TypeError("a Range is required");
4510       }
4511       return this.set.some((thisComparators) => {
4512         return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
4513           return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
4514             return rangeComparators.every((rangeComparator) => {
4515               return thisComparator.intersects(rangeComparator, options);
4516             });
4517           });
4518         });
4519       });
4520     }
4521     test(version) {
4522       if (!version) {
4523         return false;
4524       }
4525       if (typeof version === "string") {
4526         try {
4527           version = new SemVer(version, this.options);
4528         } catch (er) {
4529           return false;
4530         }
4531       }
4532       for (let i = 0; i < this.set.length; i++) {
4533         if (testSet(this.set[i], version, this.options)) {
4534           return true;
4535         }
4536       }
4537       return false;
4538     }
4539   };
4540   module2.exports = Range15;
4541   var Comparator = require_comparator();
4542   var debug = require_debug();
4543   var SemVer = require_semver();
4544   var {
4545     re,
4546     t,
4547     comparatorTrimReplace,
4548     tildeTrimReplace,
4549     caretTrimReplace
4550   } = require_re();
4551   var isSatisfiable = (comparators, options) => {
4552     let result = true;
4553     const remainingComparators = comparators.slice();
4554     let testComparator = remainingComparators.pop();
4555     while (result && remainingComparators.length) {
4556       result = remainingComparators.every((otherComparator) => {
4557         return testComparator.intersects(otherComparator, options);
4558       });
4559       testComparator = remainingComparators.pop();
4560     }
4561     return result;
4562   };
4563   var parseComparator = (comp, options) => {
4564     debug("comp", comp, options);
4565     comp = replaceCarets(comp, options);
4566     debug("caret", comp);
4567     comp = replaceTildes(comp, options);
4568     debug("tildes", comp);
4569     comp = replaceXRanges(comp, options);
4570     debug("xrange", comp);
4571     comp = replaceStars(comp, options);
4572     debug("stars", comp);
4573     return comp;
4574   };
4575   var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
4576   var replaceTildes = (comp, options) => comp.trim().split(/\s+/).map((comp2) => {
4577     return replaceTilde(comp2, options);
4578   }).join(" ");
4579   var replaceTilde = (comp, options) => {
4580     const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
4581     return comp.replace(r, (_, M, m, p, pr) => {
4582       debug("tilde", comp, _, M, m, p, pr);
4583       let ret;
4584       if (isX(M)) {
4585         ret = "";
4586       } else if (isX(m)) {
4587         ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
4588       } else if (isX(p)) {
4589         ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
4590       } else if (pr) {
4591         debug("replaceTilde pr", pr);
4592         ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
4593       } else {
4594         ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
4595       }
4596       debug("tilde return", ret);
4597       return ret;
4598     });
4599   };
4600   var replaceCarets = (comp, options) => comp.trim().split(/\s+/).map((comp2) => {
4601     return replaceCaret(comp2, options);
4602   }).join(" ");
4603   var replaceCaret = (comp, options) => {
4604     debug("caret", comp, options);
4605     const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
4606     const z = options.includePrerelease ? "-0" : "";
4607     return comp.replace(r, (_, M, m, p, pr) => {
4608       debug("caret", comp, _, M, m, p, pr);
4609       let ret;
4610       if (isX(M)) {
4611         ret = "";
4612       } else if (isX(m)) {
4613         ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
4614       } else if (isX(p)) {
4615         if (M === "0") {
4616           ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
4617         } else {
4618           ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
4619         }
4620       } else if (pr) {
4621         debug("replaceCaret pr", pr);
4622         if (M === "0") {
4623           if (m === "0") {
4624             ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
4625           } else {
4626             ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
4627           }
4628         } else {
4629           ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
4630         }
4631       } else {
4632         debug("no pr");
4633         if (M === "0") {
4634           if (m === "0") {
4635             ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
4636           } else {
4637             ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
4638           }
4639         } else {
4640           ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
4641         }
4642       }
4643       debug("caret return", ret);
4644       return ret;
4645     });
4646   };
4647   var replaceXRanges = (comp, options) => {
4648     debug("replaceXRanges", comp, options);
4649     return comp.split(/\s+/).map((comp2) => {
4650       return replaceXRange(comp2, options);
4651     }).join(" ");
4652   };
4653   var replaceXRange = (comp, options) => {
4654     comp = comp.trim();
4655     const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
4656     return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
4657       debug("xRange", comp, ret, gtlt, M, m, p, pr);
4658       const xM = isX(M);
4659       const xm = xM || isX(m);
4660       const xp = xm || isX(p);
4661       const anyX = xp;
4662       if (gtlt === "=" && anyX) {
4663         gtlt = "";
4664       }
4665       pr = options.includePrerelease ? "-0" : "";
4666       if (xM) {
4667         if (gtlt === ">" || gtlt === "<") {
4668           ret = "<0.0.0-0";
4669         } else {
4670           ret = "*";
4671         }
4672       } else if (gtlt && anyX) {
4673         if (xm) {
4674           m = 0;
4675         }
4676         p = 0;
4677         if (gtlt === ">") {
4678           gtlt = ">=";
4679           if (xm) {
4680             M = +M + 1;
4681             m = 0;
4682             p = 0;
4683           } else {
4684             m = +m + 1;
4685             p = 0;
4686           }
4687         } else if (gtlt === "<=") {
4688           gtlt = "<";
4689           if (xm) {
4690             M = +M + 1;
4691           } else {
4692             m = +m + 1;
4693           }
4694         }
4695         if (gtlt === "<")
4696           pr = "-0";
4697         ret = `${gtlt + M}.${m}.${p}${pr}`;
4698       } else if (xm) {
4699         ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
4700       } else if (xp) {
4701         ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
4702       }
4703       debug("xRange return", ret);
4704       return ret;
4705     });
4706   };
4707   var replaceStars = (comp, options) => {
4708     debug("replaceStars", comp, options);
4709     return comp.trim().replace(re[t.STAR], "");
4710   };
4711   var replaceGTE0 = (comp, options) => {
4712     debug("replaceGTE0", comp, options);
4713     return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
4714   };
4715   var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => {
4716     if (isX(fM)) {
4717       from = "";
4718     } else if (isX(fm)) {
4719       from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
4720     } else if (isX(fp)) {
4721       from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
4722     } else if (fpr) {
4723       from = `>=${from}`;
4724     } else {
4725       from = `>=${from}${incPr ? "-0" : ""}`;
4726     }
4727     if (isX(tM)) {
4728       to = "";
4729     } else if (isX(tm)) {
4730       to = `<${+tM + 1}.0.0-0`;
4731     } else if (isX(tp)) {
4732       to = `<${tM}.${+tm + 1}.0-0`;
4733     } else if (tpr) {
4734       to = `<=${tM}.${tm}.${tp}-${tpr}`;
4735     } else if (incPr) {
4736       to = `<${tM}.${tm}.${+tp + 1}-0`;
4737     } else {
4738       to = `<=${to}`;
4739     }
4740     return `${from} ${to}`.trim();
4741   };
4742   var testSet = (set, version, options) => {
4743     for (let i = 0; i < set.length; i++) {
4744       if (!set[i].test(version)) {
4745         return false;
4746       }
4747     }
4748     if (version.prerelease.length && !options.includePrerelease) {
4749       for (let i = 0; i < set.length; i++) {
4750         debug(set[i].semver);
4751         if (set[i].semver === Comparator.ANY) {
4752           continue;
4753         }
4754         if (set[i].semver.prerelease.length > 0) {
4755           const allowed = set[i].semver;
4756           if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
4757             return true;
4758           }
4759         }
4760       }
4761       return false;
4762     }
4763     return true;
4764   };
4765 });
4766
4767 // node_modules/semver/classes/comparator.js
4768 var require_comparator = __commonJS((exports2, module2) => {
4769   var ANY = Symbol("SemVer ANY");
4770   var Comparator = class {
4771     static get ANY() {
4772       return ANY;
4773     }
4774     constructor(comp, options) {
4775       if (!options || typeof options !== "object") {
4776         options = {
4777           loose: !!options,
4778           includePrerelease: false
4779         };
4780       }
4781       if (comp instanceof Comparator) {
4782         if (comp.loose === !!options.loose) {
4783           return comp;
4784         } else {
4785           comp = comp.value;
4786         }
4787       }
4788       debug("comparator", comp, options);
4789       this.options = options;
4790       this.loose = !!options.loose;
4791       this.parse(comp);
4792       if (this.semver === ANY) {
4793         this.value = "";
4794       } else {
4795         this.value = this.operator + this.semver.version;
4796       }
4797       debug("comp", this);
4798     }
4799     parse(comp) {
4800       const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
4801       const m = comp.match(r);
4802       if (!m) {
4803         throw new TypeError(`Invalid comparator: ${comp}`);
4804       }
4805       this.operator = m[1] !== void 0 ? m[1] : "";
4806       if (this.operator === "=") {
4807         this.operator = "";
4808       }
4809       if (!m[2]) {
4810         this.semver = ANY;
4811       } else {
4812         this.semver = new SemVer(m[2], this.options.loose);
4813       }
4814     }
4815     toString() {
4816       return this.value;
4817     }
4818     test(version) {
4819       debug("Comparator.test", version, this.options.loose);
4820       if (this.semver === ANY || version === ANY) {
4821         return true;
4822       }
4823       if (typeof version === "string") {
4824         try {
4825           version = new SemVer(version, this.options);
4826         } catch (er) {
4827           return false;
4828         }
4829       }
4830       return cmp(version, this.operator, this.semver, this.options);
4831     }
4832     intersects(comp, options) {
4833       if (!(comp instanceof Comparator)) {
4834         throw new TypeError("a Comparator is required");
4835       }
4836       if (!options || typeof options !== "object") {
4837         options = {
4838           loose: !!options,
4839           includePrerelease: false
4840         };
4841       }
4842       if (this.operator === "") {
4843         if (this.value === "") {
4844           return true;
4845         }
4846         return new Range15(comp.value, options).test(this.value);
4847       } else if (comp.operator === "") {
4848         if (comp.value === "") {
4849           return true;
4850         }
4851         return new Range15(this.value, options).test(comp.semver);
4852       }
4853       const sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
4854       const sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
4855       const sameSemVer = this.semver.version === comp.semver.version;
4856       const differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
4857       const oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, options) && (this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<");
4858       const oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, options) && (this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">");
4859       return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
4860     }
4861   };
4862   module2.exports = Comparator;
4863   var {re, t} = require_re();
4864   var cmp = require_cmp();
4865   var debug = require_debug();
4866   var SemVer = require_semver();
4867   var Range15 = require_range();
4868 });
4869
4870 // node_modules/semver/functions/satisfies.js
4871 var require_satisfies = __commonJS((exports2, module2) => {
4872   var Range15 = require_range();
4873   var satisfies = (version, range, options) => {
4874     try {
4875       range = new Range15(range, options);
4876     } catch (er) {
4877       return false;
4878     }
4879     return range.test(version);
4880   };
4881   module2.exports = satisfies;
4882 });
4883
4884 // node_modules/semver/ranges/to-comparators.js
4885 var require_to_comparators = __commonJS((exports2, module2) => {
4886   var Range15 = require_range();
4887   var toComparators = (range, options) => new Range15(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
4888   module2.exports = toComparators;
4889 });
4890
4891 // node_modules/semver/ranges/max-satisfying.js
4892 var require_max_satisfying = __commonJS((exports2, module2) => {
4893   var SemVer = require_semver();
4894   var Range15 = require_range();
4895   var maxSatisfying = (versions, range, options) => {
4896     let max = null;
4897     let maxSV = null;
4898     let rangeObj = null;
4899     try {
4900       rangeObj = new Range15(range, options);
4901     } catch (er) {
4902       return null;
4903     }
4904     versions.forEach((v) => {
4905       if (rangeObj.test(v)) {
4906         if (!max || maxSV.compare(v) === -1) {
4907           max = v;
4908           maxSV = new SemVer(max, options);
4909         }
4910       }
4911     });
4912     return max;
4913   };
4914   module2.exports = maxSatisfying;
4915 });
4916
4917 // node_modules/semver/ranges/min-satisfying.js
4918 var require_min_satisfying = __commonJS((exports2, module2) => {
4919   var SemVer = require_semver();
4920   var Range15 = require_range();
4921   var minSatisfying = (versions, range, options) => {
4922     let min = null;
4923     let minSV = null;
4924     let rangeObj = null;
4925     try {
4926       rangeObj = new Range15(range, options);
4927     } catch (er) {
4928       return null;
4929     }
4930     versions.forEach((v) => {
4931       if (rangeObj.test(v)) {
4932         if (!min || minSV.compare(v) === 1) {
4933           min = v;
4934           minSV = new SemVer(min, options);
4935         }
4936       }
4937     });
4938     return min;
4939   };
4940   module2.exports = minSatisfying;
4941 });
4942
4943 // node_modules/semver/ranges/min-version.js
4944 var require_min_version = __commonJS((exports2, module2) => {
4945   var SemVer = require_semver();
4946   var Range15 = require_range();
4947   var gt = require_gt();
4948   var minVersion = (range, loose) => {
4949     range = new Range15(range, loose);
4950     let minver = new SemVer("0.0.0");
4951     if (range.test(minver)) {
4952       return minver;
4953     }
4954     minver = new SemVer("0.0.0-0");
4955     if (range.test(minver)) {
4956       return minver;
4957     }
4958     minver = null;
4959     for (let i = 0; i < range.set.length; ++i) {
4960       const comparators = range.set[i];
4961       comparators.forEach((comparator) => {
4962         const compver = new SemVer(comparator.semver.version);
4963         switch (comparator.operator) {
4964           case ">":
4965             if (compver.prerelease.length === 0) {
4966               compver.patch++;
4967             } else {
4968               compver.prerelease.push(0);
4969             }
4970             compver.raw = compver.format();
4971           case "":
4972           case ">=":
4973             if (!minver || gt(minver, compver)) {
4974               minver = compver;
4975             }
4976             break;
4977           case "<":
4978           case "<=":
4979             break;
4980           default:
4981             throw new Error(`Unexpected operation: ${comparator.operator}`);
4982         }
4983       });
4984     }
4985     if (minver && range.test(minver)) {
4986       return minver;
4987     }
4988     return null;
4989   };
4990   module2.exports = minVersion;
4991 });
4992
4993 // node_modules/semver/ranges/valid.js
4994 var require_valid2 = __commonJS((exports2, module2) => {
4995   var Range15 = require_range();
4996   var validRange = (range, options) => {
4997     try {
4998       return new Range15(range, options).range || "*";
4999     } catch (er) {
5000       return null;
5001     }
5002   };
5003   module2.exports = validRange;
5004 });
5005
5006 // node_modules/semver/ranges/outside.js
5007 var require_outside = __commonJS((exports2, module2) => {
5008   var SemVer = require_semver();
5009   var Comparator = require_comparator();
5010   var {ANY} = Comparator;
5011   var Range15 = require_range();
5012   var satisfies = require_satisfies();
5013   var gt = require_gt();
5014   var lt = require_lt();
5015   var lte = require_lte();
5016   var gte2 = require_gte();
5017   var outside = (version, range, hilo, options) => {
5018     version = new SemVer(version, options);
5019     range = new Range15(range, options);
5020     let gtfn, ltefn, ltfn, comp, ecomp;
5021     switch (hilo) {
5022       case ">":
5023         gtfn = gt;
5024         ltefn = lte;
5025         ltfn = lt;
5026         comp = ">";
5027         ecomp = ">=";
5028         break;
5029       case "<":
5030         gtfn = lt;
5031         ltefn = gte2;
5032         ltfn = gt;
5033         comp = "<";
5034         ecomp = "<=";
5035         break;
5036       default:
5037         throw new TypeError('Must provide a hilo val of "<" or ">"');
5038     }
5039     if (satisfies(version, range, options)) {
5040       return false;
5041     }
5042     for (let i = 0; i < range.set.length; ++i) {
5043       const comparators = range.set[i];
5044       let high = null;
5045       let low = null;
5046       comparators.forEach((comparator) => {
5047         if (comparator.semver === ANY) {
5048           comparator = new Comparator(">=0.0.0");
5049         }
5050         high = high || comparator;
5051         low = low || comparator;
5052         if (gtfn(comparator.semver, high.semver, options)) {
5053           high = comparator;
5054         } else if (ltfn(comparator.semver, low.semver, options)) {
5055           low = comparator;
5056         }
5057       });
5058       if (high.operator === comp || high.operator === ecomp) {
5059         return false;
5060       }
5061       if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
5062         return false;
5063       } else if (low.operator === ecomp && ltfn(version, low.semver)) {
5064         return false;
5065       }
5066     }
5067     return true;
5068   };
5069   module2.exports = outside;
5070 });
5071
5072 // node_modules/semver/ranges/gtr.js
5073 var require_gtr = __commonJS((exports2, module2) => {
5074   var outside = require_outside();
5075   var gtr = (version, range, options) => outside(version, range, ">", options);
5076   module2.exports = gtr;
5077 });
5078
5079 // node_modules/semver/ranges/ltr.js
5080 var require_ltr = __commonJS((exports2, module2) => {
5081   var outside = require_outside();
5082   var ltr = (version, range, options) => outside(version, range, "<", options);
5083   module2.exports = ltr;
5084 });
5085
5086 // node_modules/semver/ranges/intersects.js
5087 var require_intersects = __commonJS((exports2, module2) => {
5088   var Range15 = require_range();
5089   var intersects = (r1, r2, options) => {
5090     r1 = new Range15(r1, options);
5091     r2 = new Range15(r2, options);
5092     return r1.intersects(r2);
5093   };
5094   module2.exports = intersects;
5095 });
5096
5097 // node_modules/semver/ranges/simplify.js
5098 var require_simplify = __commonJS((exports2, module2) => {
5099   var satisfies = require_satisfies();
5100   var compare = require_compare();
5101   module2.exports = (versions, range, options) => {
5102     const set = [];
5103     let min = null;
5104     let prev = null;
5105     const v = versions.sort((a, b) => compare(a, b, options));
5106     for (const version of v) {
5107       const included = satisfies(version, range, options);
5108       if (included) {
5109         prev = version;
5110         if (!min)
5111           min = version;
5112       } else {
5113         if (prev) {
5114           set.push([min, prev]);
5115         }
5116         prev = null;
5117         min = null;
5118       }
5119     }
5120     if (min)
5121       set.push([min, null]);
5122     const ranges = [];
5123     for (const [min2, max] of set) {
5124       if (min2 === max)
5125         ranges.push(min2);
5126       else if (!max && min2 === v[0])
5127         ranges.push("*");
5128       else if (!max)
5129         ranges.push(`>=${min2}`);
5130       else if (min2 === v[0])
5131         ranges.push(`<=${max}`);
5132       else
5133         ranges.push(`${min2} - ${max}`);
5134     }
5135     const simplified = ranges.join(" || ");
5136     const original = typeof range.raw === "string" ? range.raw : String(range);
5137     return simplified.length < original.length ? simplified : range;
5138   };
5139 });
5140
5141 // node_modules/semver/ranges/subset.js
5142 var require_subset = __commonJS((exports2, module2) => {
5143   var Range15 = require_range();
5144   var {ANY} = require_comparator();
5145   var satisfies = require_satisfies();
5146   var compare = require_compare();
5147   var subset = (sub, dom, options) => {
5148     sub = new Range15(sub, options);
5149     dom = new Range15(dom, options);
5150     let sawNonNull = false;
5151     OUTER:
5152       for (const simpleSub of sub.set) {
5153         for (const simpleDom of dom.set) {
5154           const isSub = simpleSubset(simpleSub, simpleDom, options);
5155           sawNonNull = sawNonNull || isSub !== null;
5156           if (isSub)
5157             continue OUTER;
5158         }
5159         if (sawNonNull)
5160           return false;
5161       }
5162     return true;
5163   };
5164   var simpleSubset = (sub, dom, options) => {
5165     if (sub.length === 1 && sub[0].semver === ANY)
5166       return dom.length === 1 && dom[0].semver === ANY;
5167     const eqSet = new Set();
5168     let gt, lt;
5169     for (const c of sub) {
5170       if (c.operator === ">" || c.operator === ">=")
5171         gt = higherGT(gt, c, options);
5172       else if (c.operator === "<" || c.operator === "<=")
5173         lt = lowerLT(lt, c, options);
5174       else
5175         eqSet.add(c.semver);
5176     }
5177     if (eqSet.size > 1)
5178       return null;
5179     let gtltComp;
5180     if (gt && lt) {
5181       gtltComp = compare(gt.semver, lt.semver, options);
5182       if (gtltComp > 0)
5183         return null;
5184       else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<="))
5185         return null;
5186     }
5187     for (const eq of eqSet) {
5188       if (gt && !satisfies(eq, String(gt), options))
5189         return null;
5190       if (lt && !satisfies(eq, String(lt), options))
5191         return null;
5192       for (const c of dom) {
5193         if (!satisfies(eq, String(c), options))
5194           return false;
5195       }
5196       return true;
5197     }
5198     let higher, lower;
5199     let hasDomLT, hasDomGT;
5200     for (const c of dom) {
5201       hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
5202       hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
5203       if (gt) {
5204         if (c.operator === ">" || c.operator === ">=") {
5205           higher = higherGT(gt, c, options);
5206           if (higher === c)
5207             return false;
5208         } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options))
5209           return false;
5210       }
5211       if (lt) {
5212         if (c.operator === "<" || c.operator === "<=") {
5213           lower = lowerLT(lt, c, options);
5214           if (lower === c)
5215             return false;
5216         } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options))
5217           return false;
5218       }
5219       if (!c.operator && (lt || gt) && gtltComp !== 0)
5220         return false;
5221     }
5222     if (gt && hasDomLT && !lt && gtltComp !== 0)
5223       return false;
5224     if (lt && hasDomGT && !gt && gtltComp !== 0)
5225       return false;
5226     return true;
5227   };
5228   var higherGT = (a, b, options) => {
5229     if (!a)
5230       return b;
5231     const comp = compare(a.semver, b.semver, options);
5232     return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
5233   };
5234   var lowerLT = (a, b, options) => {
5235     if (!a)
5236       return b;
5237     const comp = compare(a.semver, b.semver, options);
5238     return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
5239   };
5240   module2.exports = subset;
5241 });
5242
5243 // node_modules/semver/index.js
5244 var require_semver2 = __commonJS((exports2, module2) => {
5245   var internalRe = require_re();
5246   module2.exports = {
5247     re: internalRe.re,
5248     src: internalRe.src,
5249     tokens: internalRe.t,
5250     SEMVER_SPEC_VERSION: require_constants().SEMVER_SPEC_VERSION,
5251     SemVer: require_semver(),
5252     compareIdentifiers: require_identifiers().compareIdentifiers,
5253     rcompareIdentifiers: require_identifiers().rcompareIdentifiers,
5254     parse: require_parse(),
5255     valid: require_valid(),
5256     clean: require_clean(),
5257     inc: require_inc(),
5258     diff: require_diff(),
5259     major: require_major(),
5260     minor: require_minor(),
5261     patch: require_patch(),
5262     prerelease: require_prerelease(),
5263     compare: require_compare(),
5264     rcompare: require_rcompare(),
5265     compareLoose: require_compare_loose(),
5266     compareBuild: require_compare_build(),
5267     sort: require_sort(),
5268     rsort: require_rsort(),
5269     gt: require_gt(),
5270     lt: require_lt(),
5271     eq: require_eq(),
5272     neq: require_neq(),
5273     gte: require_gte(),
5274     lte: require_lte(),
5275     cmp: require_cmp(),
5276     coerce: require_coerce(),
5277     Comparator: require_comparator(),
5278     Range: require_range(),
5279     satisfies: require_satisfies(),
5280     toComparators: require_to_comparators(),
5281     maxSatisfying: require_max_satisfying(),
5282     minSatisfying: require_min_satisfying(),
5283     minVersion: require_min_version(),
5284     validRange: require_valid2(),
5285     outside: require_outside(),
5286     gtr: require_gtr(),
5287     ltr: require_ltr(),
5288     intersects: require_intersects(),
5289     simplifyRange: require_simplify(),
5290     subset: require_subset()
5291   };
5292 });
5293
5294 // node_modules/isexe/windows.js
5295 var require_windows = __commonJS((exports2, module2) => {
5296   module2.exports = isexe;
5297   isexe.sync = sync;
5298   var fs5 = require("fs");
5299   function checkPathExt(path8, options) {
5300     var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
5301     if (!pathext) {
5302       return true;
5303     }
5304     pathext = pathext.split(";");
5305     if (pathext.indexOf("") !== -1) {
5306       return true;
5307     }
5308     for (var i = 0; i < pathext.length; i++) {
5309       var p = pathext[i].toLowerCase();
5310       if (p && path8.substr(-p.length).toLowerCase() === p) {
5311         return true;
5312       }
5313     }
5314     return false;
5315   }
5316   function checkStat(stat, path8, options) {
5317     if (!stat.isSymbolicLink() && !stat.isFile()) {
5318       return false;
5319     }
5320     return checkPathExt(path8, options);
5321   }
5322   function isexe(path8, options, cb) {
5323     fs5.stat(path8, function(er, stat) {
5324       cb(er, er ? false : checkStat(stat, path8, options));
5325     });
5326   }
5327   function sync(path8, options) {
5328     return checkStat(fs5.statSync(path8), path8, options);
5329   }
5330 });
5331
5332 // node_modules/isexe/mode.js
5333 var require_mode = __commonJS((exports2, module2) => {
5334   module2.exports = isexe;
5335   isexe.sync = sync;
5336   var fs5 = require("fs");
5337   function isexe(path8, options, cb) {
5338     fs5.stat(path8, function(er, stat) {
5339       cb(er, er ? false : checkStat(stat, options));
5340     });
5341   }
5342   function sync(path8, options) {
5343     return checkStat(fs5.statSync(path8), options);
5344   }
5345   function checkStat(stat, options) {
5346     return stat.isFile() && checkMode(stat, options);
5347   }
5348   function checkMode(stat, options) {
5349     var mod = stat.mode;
5350     var uid = stat.uid;
5351     var gid = stat.gid;
5352     var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
5353     var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
5354     var u = parseInt("100", 8);
5355     var g = parseInt("010", 8);
5356     var o = parseInt("001", 8);
5357     var ug = u | g;
5358     var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
5359     return ret;
5360   }
5361 });
5362
5363 // node_modules/isexe/index.js
5364 var require_isexe = __commonJS((exports2, module2) => {
5365   var fs5 = require("fs");
5366   var core;
5367   if (process.platform === "win32" || global.TESTING_WINDOWS) {
5368     core = require_windows();
5369   } else {
5370     core = require_mode();
5371   }
5372   module2.exports = isexe;
5373   isexe.sync = sync;
5374   function isexe(path8, options, cb) {
5375     if (typeof options === "function") {
5376       cb = options;
5377       options = {};
5378     }
5379     if (!cb) {
5380       if (typeof Promise !== "function") {
5381         throw new TypeError("callback not provided");
5382       }
5383       return new Promise(function(resolve, reject) {
5384         isexe(path8, options || {}, function(er, is2) {
5385           if (er) {
5386             reject(er);
5387           } else {
5388             resolve(is2);
5389           }
5390         });
5391       });
5392     }
5393     core(path8, options || {}, function(er, is2) {
5394       if (er) {
5395         if (er.code === "EACCES" || options && options.ignoreErrors) {
5396           er = null;
5397           is2 = false;
5398         }
5399       }
5400       cb(er, is2);
5401     });
5402   }
5403   function sync(path8, options) {
5404     try {
5405       return core.sync(path8, options || {});
5406     } catch (er) {
5407       if (options && options.ignoreErrors || er.code === "EACCES") {
5408         return false;
5409       } else {
5410         throw er;
5411       }
5412     }
5413   }
5414 });
5415
5416 // node_modules/which/which.js
5417 var require_which = __commonJS((exports2, module2) => {
5418   var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
5419   var path8 = require("path");
5420   var COLON = isWindows ? ";" : ":";
5421   var isexe = require_isexe();
5422   var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), {code: "ENOENT"});
5423   var getPathInfo = (cmd, opt) => {
5424     const colon = opt.colon || COLON;
5425     const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
5426       ...isWindows ? [process.cwd()] : [],
5427       ...(opt.path || process.env.PATH || "").split(colon)
5428     ];
5429     const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
5430     const pathExt = isWindows ? pathExtExe.split(colon) : [""];
5431     if (isWindows) {
5432       if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
5433         pathExt.unshift("");
5434     }
5435     return {
5436       pathEnv,
5437       pathExt,
5438       pathExtExe
5439     };
5440   };
5441   var which2 = (cmd, opt, cb) => {
5442     if (typeof opt === "function") {
5443       cb = opt;
5444       opt = {};
5445     }
5446     if (!opt)
5447       opt = {};
5448     const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
5449     const found = [];
5450     const step = (i) => new Promise((resolve, reject) => {
5451       if (i === pathEnv.length)
5452         return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
5453       const ppRaw = pathEnv[i];
5454       const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
5455       const pCmd = path8.join(pathPart, cmd);
5456       const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
5457       resolve(subStep(p, i, 0));
5458     });
5459     const subStep = (p, i, ii) => new Promise((resolve, reject) => {
5460       if (ii === pathExt.length)
5461         return resolve(step(i + 1));
5462       const ext = pathExt[ii];
5463       isexe(p + ext, {pathExt: pathExtExe}, (er, is2) => {
5464         if (!er && is2) {
5465           if (opt.all)
5466             found.push(p + ext);
5467           else
5468             return resolve(p + ext);
5469         }
5470         return resolve(subStep(p, i, ii + 1));
5471       });
5472     });
5473     return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
5474   };
5475   var whichSync = (cmd, opt) => {
5476     opt = opt || {};
5477     const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
5478     const found = [];
5479     for (let i = 0; i < pathEnv.length; i++) {
5480       const ppRaw = pathEnv[i];
5481       const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
5482       const pCmd = path8.join(pathPart, cmd);
5483       const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
5484       for (let j = 0; j < pathExt.length; j++) {
5485         const cur = p + pathExt[j];
5486         try {
5487           const is2 = isexe.sync(cur, {pathExt: pathExtExe});
5488           if (is2) {
5489             if (opt.all)
5490               found.push(cur);
5491             else
5492               return cur;
5493           }
5494         } catch (ex) {
5495         }
5496       }
5497     }
5498     if (opt.all && found.length)
5499       return found;
5500     if (opt.nothrow)
5501       return null;
5502     throw getNotFoundError(cmd);
5503   };
5504   module2.exports = which2;
5505   which2.sync = whichSync;
5506 });
5507
5508 // src/index.ts
5509 __export(exports, {
5510   activate: () => activate
5511 });
5512 var import_coc32 = __toModule(require("coc.nvim"));
5513
5514 // src/server/index.ts
5515 var import_coc30 = __toModule(require("coc.nvim"));
5516 var import_vscode_languageserver_protocol23 = __toModule(require_main3());
5517
5518 // src/server/typescriptServiceClientHost.ts
5519 var import_coc29 = __toModule(require("coc.nvim"));
5520 var import_vscode_languageserver_protocol22 = __toModule(require_main3());
5521
5522 // src/utils/arrays.ts
5523 function equals(one, other, itemEquals = (a, b) => a === b) {
5524   if (one.length !== other.length) {
5525     return false;
5526   }
5527   for (let i = 0, len = one.length; i < len; i++) {
5528     if (!itemEquals(one[i], other[i])) {
5529       return false;
5530     }
5531   }
5532   return true;
5533 }
5534 function flatten(arr) {
5535   return [].concat.apply([], arr);
5536 }
5537
5538 // src/server/features/fileConfigurationManager.ts
5539 var import_coc = __toModule(require("coc.nvim"));
5540 var import_vscode_languageserver_protocol = __toModule(require_main3());
5541
5542 // src/server/utils/api.ts
5543 var semver = __toModule(require_semver2());
5544 var API2 = class {
5545   constructor(versionString, version) {
5546     this.versionString = versionString;
5547     this.version = version;
5548   }
5549   static fromSimpleString(value) {
5550     return new API2(value, value);
5551   }
5552   static fromVersionString(versionString) {
5553     let version = semver.valid(versionString);
5554     if (!version) {
5555       return new API2("invalid version", "1.0.0");
5556     }
5557     const index = versionString.indexOf("-");
5558     if (index >= 0) {
5559       version = version.substr(0, index);
5560     }
5561     return new API2(versionString, version);
5562   }
5563   gte(other) {
5564     return semver.gte(this.version, other.version);
5565   }
5566   lt(other) {
5567     return !this.gte(other);
5568   }
5569 };
5570 var API = API2;
5571 API.defaultVersion = API2.fromSimpleString("1.0.0");
5572 API.v203 = API2.fromSimpleString("2.0.3");
5573 API.v206 = API2.fromSimpleString("2.0.6");
5574 API.v208 = API2.fromSimpleString("2.0.8");
5575 API.v213 = API2.fromSimpleString("2.1.3");
5576 API.v220 = API2.fromSimpleString("2.2.0");
5577 API.v222 = API2.fromSimpleString("2.2.2");
5578 API.v230 = API2.fromSimpleString("2.3.0");
5579 API.v234 = API2.fromSimpleString("2.3.4");
5580 API.v240 = API2.fromSimpleString("2.4.0");
5581 API.v250 = API2.fromSimpleString("2.5.0");
5582 API.v260 = API2.fromSimpleString("2.6.0");
5583 API.v270 = API2.fromSimpleString("2.7.0");
5584 API.v280 = API2.fromSimpleString("2.8.0");
5585 API.v290 = API2.fromSimpleString("2.9.0");
5586 API.v291 = API2.fromSimpleString("2.9.1");
5587 API.v292 = API2.fromSimpleString("2.9.2");
5588 API.v300 = API2.fromSimpleString("3.0.0");
5589 API.v310 = API2.fromSimpleString("3.1.0");
5590 API.v314 = API2.fromSimpleString("3.1.4");
5591 API.v320 = API2.fromSimpleString("3.2.0");
5592 API.v330 = API2.fromSimpleString("3.3.0");
5593 API.v333 = API2.fromSimpleString("3.3.3");
5594 API.v340 = API2.fromSimpleString("3.4.0");
5595 API.v345 = API2.fromSimpleString("3.4.5");
5596 API.v350 = API2.fromSimpleString("3.5.0");
5597 API.v380 = API2.fromSimpleString("3.8.0");
5598 API.v381 = API2.fromSimpleString("3.8.1");
5599 API.v390 = API2.fromSimpleString("3.9.0");
5600 API.v400 = API2.fromSimpleString("4.0.0");
5601 API.v401 = API2.fromSimpleString("4.0.1");
5602 var api_default = API;
5603
5604 // src/server/features/fileConfigurationManager.ts
5605 function objAreEqual(a, b) {
5606   let keys = Object.keys(a);
5607   for (let i = 0; i < keys.length; i++) {
5608     let key = keys[i];
5609     if (a[key] !== b[key]) {
5610       return false;
5611     }
5612   }
5613   return true;
5614 }
5615 var FileConfigurationManager = class {
5616   constructor(client) {
5617     this.client = client;
5618     this.cachedMap = new Map();
5619     this.disposables = [];
5620     import_coc.workspace.onDidCloseTextDocument((textDocument) => {
5621       this.cachedMap.delete(textDocument.uri);
5622     }, void 0, this.disposables);
5623   }
5624   async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
5625     const file2 = this.client.toPath(document.uri);
5626     let options = {
5627       tabSize,
5628       insertSpaces
5629     };
5630     let cachedOption = this.cachedMap.get(document.uri);
5631     const currentOptions = this.getFileOptions(options, document);
5632     if (cachedOption && objAreEqual(cachedOption.formatOptions, currentOptions.formatOptions) && objAreEqual(cachedOption.preferences, currentOptions.preferences))
5633       return;
5634     this.cachedMap.set(document.uri, currentOptions);
5635     const args = {
5636       file: file2,
5637       ...currentOptions
5638     };
5639     await this.client.execute("configure", args, import_vscode_languageserver_protocol.CancellationToken.None);
5640     try {
5641       const response = await this.client.execute("configure", args, token);
5642       if (response.type !== "response") {
5643         this.cachedMap.delete(document.uri);
5644       }
5645     } catch (_e) {
5646       this.cachedMap.delete(document.uri);
5647     }
5648   }
5649   async ensureConfigurationForDocument(document, token) {
5650     let opts = await import_coc.workspace.getFormatOptions(document.uri);
5651     return this.ensureConfigurationOptions(document, opts.insertSpaces, opts.tabSize, token);
5652   }
5653   reset() {
5654     this.cachedMap.clear();
5655   }
5656   getLanguageConfiguration(languageId) {
5657     return import_coc.workspace.getConfiguration(languageId);
5658   }
5659   isTypeScriptDocument(languageId) {
5660     return languageId.startsWith("typescript");
5661   }
5662   formatEnabled(document) {
5663     let {languageId, uri} = document;
5664     let language = languageId.startsWith("typescript") ? "typescript" : "javascript";
5665     const config = import_coc.workspace.getConfiguration(`${language}.format`, uri);
5666     return config.get("enabled");
5667   }
5668   enableJavascript() {
5669     const config = import_coc.workspace.getConfiguration("tsserver");
5670     return !!config.get("enableJavascript");
5671   }
5672   getFileOptions(options, document) {
5673     const lang = this.isTypeScriptDocument(document.languageId) ? "typescript" : "javascript";
5674     return {
5675       formatOptions: this.getFormatOptions(options, lang, document.uri),
5676       preferences: this.getPreferences(lang, document.uri)
5677     };
5678   }
5679   getFormatOptions(options, language, uri) {
5680     const config = import_coc.workspace.getConfiguration(`${language}.format`, uri);
5681     return {
5682       tabSize: options.tabSize,
5683       indentSize: options.tabSize,
5684       convertTabsToSpaces: options.insertSpaces,
5685       newLineCharacter: "\n",
5686       insertSpaceAfterCommaDelimiter: config.get("insertSpaceAfterCommaDelimiter"),
5687       insertSpaceAfterConstructor: config.get("insertSpaceAfterConstructor"),
5688       insertSpaceAfterSemicolonInForStatements: config.get("insertSpaceAfterSemicolonInForStatements"),
5689       insertSpaceBeforeAndAfterBinaryOperators: config.get("insertSpaceBeforeAndAfterBinaryOperators"),
5690       insertSpaceAfterKeywordsInControlFlowStatements: config.get("insertSpaceAfterKeywordsInControlFlowStatements"),
5691       insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get("insertSpaceAfterFunctionKeywordForAnonymousFunctions"),
5692       insertSpaceBeforeFunctionParenthesis: config.get("insertSpaceBeforeFunctionParenthesis"),
5693       insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"),
5694       insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"),
5695       insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"),
5696       insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"),
5697       insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"),
5698       insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"),
5699       insertSpaceAfterTypeAssertion: config.get("insertSpaceAfterTypeAssertion"),
5700       placeOpenBraceOnNewLineForFunctions: config.get("placeOpenBraceOnNewLineForFunctions"),
5701       placeOpenBraceOnNewLineForControlBlocks: config.get("placeOpenBraceOnNewLineForControlBlocks"),
5702       semicolons: config.get("semicolons", void 0)
5703     };
5704   }
5705   getCompleteOptions(languageId) {
5706     const lang = this.isTypeScriptDocument(languageId) ? "typescript" : "javascript";
5707     const config = import_coc.workspace.getConfiguration(`${lang}.suggest`);
5708     return {
5709       enabled: config.get("enabled", true),
5710       names: config.get("names", true),
5711       paths: config.get("paths", true),
5712       completeFunctionCalls: config.get("completeFunctionCalls", true),
5713       autoImports: config.get("autoImports", true),
5714       includeAutomaticOptionalChainCompletions: config.get("includeAutomaticOptionalChainCompletions", true)
5715     };
5716   }
5717   getPreferences(language, uri) {
5718     if (this.client.apiVersion.lt(api_default.v290)) {
5719       return {};
5720     }
5721     const config = import_coc.workspace.getConfiguration(`${language}.preferences`, uri);
5722     const preferences = {
5723       quotePreference: this.getQuoteStyle(config),
5724       importModuleSpecifierPreference: getImportModuleSpecifier(config),
5725       importModuleSpecifierEnding: getImportModuleSpecifierEndingPreference(config),
5726       allowTextChangesInNewFiles: uri.startsWith("file:"),
5727       allowRenameOfImportPath: true,
5728       providePrefixAndSuffixTextForRename: config.get("renameShorthandProperties", true) === false ? false : config.get("useAliasesForRenames", true)
5729     };
5730     return preferences;
5731   }
5732   getQuoteStyle(config) {
5733     let quoteStyle = config.get("quoteStyle", "auto");
5734     if (this.client.apiVersion.gte(api_default.v333) || quoteStyle != "auto")
5735       return quoteStyle;
5736     return "single";
5737   }
5738   dispose() {
5739     import_coc.disposeAll(this.disposables);
5740   }
5741 };
5742 var fileConfigurationManager_default = FileConfigurationManager;
5743 function getImportModuleSpecifier(config) {
5744   let val = config.get("importModuleSpecifier");
5745   switch (val) {
5746     case "relative":
5747       return "relative";
5748     case "non-relative":
5749       return "non-relative";
5750     default:
5751       return "auto";
5752   }
5753 }
5754 function getImportModuleSpecifierEndingPreference(config) {
5755   switch (config.get("importModuleSpecifierEnding")) {
5756     case "minimal":
5757       return "minimal";
5758     case "index":
5759       return "index";
5760     case "js":
5761       return "js";
5762     default:
5763       return "auto";
5764   }
5765 }
5766
5767 // src/server/features/watchBuild.ts
5768 var import_coc2 = __toModule(require("coc.nvim"));
5769 var import_path = __toModule(require("path"));
5770 var import_vscode_languageserver_protocol2 = __toModule(require_main3());
5771 var countRegex = /Found\s+(\d+)\s+error/;
5772 var errorRegex = /^(.+)\((\d+),(\d+)\):\s(\w+)\sTS(\d+):\s*(.+)$/;
5773 var TscStatus;
5774 (function(TscStatus2) {
5775   TscStatus2[TscStatus2["INIT"] = 0] = "INIT";
5776   TscStatus2[TscStatus2["COMPILING"] = 1] = "COMPILING";
5777   TscStatus2[TscStatus2["RUNNING"] = 2] = "RUNNING";
5778   TscStatus2[TscStatus2["ERROR"] = 3] = "ERROR";
5779 })(TscStatus || (TscStatus = {}));
5780 var WatchProject2 = class {
5781   constructor(client) {
5782     this.client = client;
5783     this.disposables = [];
5784     this.statusItem = import_coc2.window.createStatusBarItem(1, {progress: true});
5785     let task = this.task = import_coc2.workspace.createTask("TSC");
5786     this.disposables.push(import_coc2.commands.registerCommand(WatchProject2.id, async () => {
5787       let opts = this.options = await this.getOptions();
5788       await this.start(opts);
5789     }));
5790     task.onExit((code) => {
5791       if (code != 0) {
5792         import_coc2.window.showMessage(`TSC exit with code ${code}`, "warning");
5793       }
5794       this.onStop();
5795     });
5796     task.onStdout((lines) => {
5797       for (let line of lines) {
5798         this.onLine(line);
5799       }
5800     });
5801     task.onStderr((lines) => {
5802       import_coc2.window.showMessage(`TSC error: ` + lines.join("\n"), "error");
5803     });
5804     this.disposables.push(import_vscode_languageserver_protocol2.Disposable.create(() => {
5805       task.dispose();
5806     }));
5807     this.check().catch((_e) => {
5808     });
5809   }
5810   async check() {
5811     let running = await this.task.running;
5812     if (running) {
5813       this.options = await this.getOptions();
5814       this.statusItem.isProgress = false;
5815       this.statusItem.text = "?";
5816       this.statusItem.show();
5817     } else {
5818       this.onStop();
5819     }
5820   }
5821   async start(options) {
5822     await this.task.start(options);
5823   }
5824   onStop() {
5825     this.statusItem.hide();
5826   }
5827   onStart() {
5828     this.statusItem.text = "compiling";
5829     this.statusItem.isProgress = true;
5830     this.statusItem.show();
5831     import_coc2.workspace.nvim.call("setqflist", [[]], true);
5832   }
5833   onLine(line) {
5834     if (countRegex.test(line)) {
5835       let ms = line.match(countRegex);
5836       this.statusItem.text = ms[1] == "0" ? "\u2713" : "\u2717";
5837       this.statusItem.isProgress = false;
5838     } else if (WatchProject2.startTexts.findIndex((s) => line.indexOf(s) !== -1) != -1) {
5839       this.onStart();
5840     } else {
5841       let ms = line.match(errorRegex);
5842       if (!ms)
5843         return;
5844       let fullpath = import_path.default.join(this.options.cwd, ms[1]);
5845       let uri = import_coc2.Uri.file(fullpath).toString();
5846       let doc = import_coc2.workspace.getDocument(uri);
5847       let bufnr = doc ? doc.bufnr : null;
5848       let item = {
5849         filename: fullpath,
5850         lnum: Number(ms[2]),
5851         col: Number(ms[3]),
5852         text: `[tsc ${ms[5]}] ${ms[6]}`,
5853         type: /error/i.test(ms[4]) ? "E" : "W"
5854       };
5855       if (bufnr)
5856         item.bufnr = bufnr;
5857       import_coc2.workspace.nvim.call("setqflist", [[item], "a"]);
5858     }
5859   }
5860   async getOptions() {
5861     let {tscPath} = this.client;
5862     if (!tscPath) {
5863       import_coc2.window.showMessage(`Local & global tsc not found`, "error");
5864       return;
5865     }
5866     let find = await import_coc2.workspace.findUp(["tsconfig.json"]);
5867     if (!find) {
5868       import_coc2.window.showMessage("tsconfig.json not found!", "error");
5869       return;
5870     }
5871     let root = import_path.default.dirname(find);
5872     return {
5873       cmd: tscPath,
5874       args: ["-p", "tsconfig.json", "--watch", "true", "--pretty", "false"],
5875       cwd: root
5876     };
5877   }
5878   dispose() {
5879     import_coc2.disposeAll(this.disposables);
5880   }
5881 };
5882 var WatchProject = WatchProject2;
5883 WatchProject.id = "tsserver.watchBuild";
5884 WatchProject.startTexts = ["Starting compilation in watch mode", "Starting incremental compilation"];
5885 var watchBuild_default = WatchProject;
5886
5887 // src/server/features/workspaceSymbols.ts
5888 var import_coc3 = __toModule(require("coc.nvim"));
5889 var import_vscode_languageserver_protocol3 = __toModule(require_main3());
5890
5891 // src/server/utils/typeConverters.ts
5892 var Range;
5893 (function(Range15) {
5894   Range15.fromTextSpan = (span) => {
5895     return {
5896       start: {
5897         line: span.start.line - 1,
5898         character: span.start.offset - 1
5899       },
5900       end: {
5901         line: span.end.line - 1,
5902         character: span.end.offset - 1
5903       }
5904     };
5905   };
5906   Range15.toFormattingRequestArgs = (file2, range) => ({
5907     file: file2,
5908     line: range.start.line + 1,
5909     offset: range.start.character + 1,
5910     endLine: range.end.line + 1,
5911     endOffset: range.end.character + 1
5912   });
5913   Range15.toFileRangeRequestArgs = (file2, range) => ({
5914     file: file2,
5915     startLine: range.start.line + 1,
5916     startOffset: range.start.character + 1,
5917     endLine: range.end.line + 1,
5918     endOffset: range.end.character + 1
5919   });
5920 })(Range || (Range = {}));
5921 var Position;
5922 (function(Position7) {
5923   Position7.fromLocation = (tslocation) => {
5924     return {
5925       line: tslocation.line - 1,
5926       character: tslocation.offset - 1
5927     };
5928   };
5929   Position7.toLocation = (position) => ({
5930     line: position.line + 1,
5931     offset: position.character + 1
5932   });
5933   Position7.toFileLocationRequestArgs = (file2, position) => ({
5934     file: file2,
5935     line: position.line + 1,
5936     offset: position.character + 1
5937   });
5938 })(Position || (Position = {}));
5939 var Location2;
5940 (function(Location3) {
5941   Location3.fromTextSpan = (uri, tsTextSpan) => {
5942     return {
5943       uri,
5944       range: Range.fromTextSpan(tsTextSpan)
5945     };
5946   };
5947 })(Location2 || (Location2 = {}));
5948 var TextEdit;
5949 (function(TextEdit6) {
5950   TextEdit6.fromCodeEdit = (edit) => {
5951     return {
5952       range: Range.fromTextSpan(edit),
5953       newText: edit.newText
5954     };
5955   };
5956 })(TextEdit || (TextEdit = {}));
5957 var WorkspaceEdit;
5958 (function(WorkspaceEdit6) {
5959   function fromFileCodeEdits(client, edits) {
5960     let changes = {};
5961     for (const edit of edits) {
5962       let uri = client.toResource(edit.fileName);
5963       changes[uri] = edit.textChanges.map((change) => {
5964         return TextEdit.fromCodeEdit(change);
5965       });
5966     }
5967     return {changes};
5968   }
5969   WorkspaceEdit6.fromFileCodeEdits = fromFileCodeEdits;
5970 })(WorkspaceEdit || (WorkspaceEdit = {}));
5971
5972 // src/server/features/workspaceSymbols.ts
5973 function getSymbolKind(item) {
5974   switch (item.kind) {
5975     case "method":
5976       return import_vscode_languageserver_protocol3.SymbolKind.Method;
5977     case "enum":
5978       return import_vscode_languageserver_protocol3.SymbolKind.Enum;
5979     case "function":
5980       return import_vscode_languageserver_protocol3.SymbolKind.Function;
5981     case "class":
5982       return import_vscode_languageserver_protocol3.SymbolKind.Class;
5983     case "interface":
5984       return import_vscode_languageserver_protocol3.SymbolKind.Interface;
5985     case "var":
5986       return import_vscode_languageserver_protocol3.SymbolKind.Variable;
5987     default:
5988       return import_vscode_languageserver_protocol3.SymbolKind.Variable;
5989   }
5990 }
5991 var TypeScriptWorkspaceSymbolProvider = class {
5992   constructor(client, languageIds) {
5993     this.client = client;
5994     this.languageIds = languageIds;
5995   }
5996   async provideWorkspaceSymbols(search, token) {
5997     let filepath;
5998     if (this.searchAllOpenProjects) {
5999       filepath = void 0;
6000     } else {
6001       let uri = this.getUri();
6002       filepath = uri ? this.client.toPath(uri) : void 0;
6003       if (!filepath && this.client.apiVersion.lt(api_default.v390)) {
6004         return [];
6005       }
6006     }
6007     const args = {
6008       file: filepath,
6009       searchValue: search,
6010       maxResultCount: 256
6011     };
6012     const response = await this.client.execute("navto", args, token);
6013     if (response.type !== "response" || response.body == null)
6014       return [];
6015     const result = [];
6016     for (const item of response.body) {
6017       if (!item.containerName && item.kind === "alias") {
6018         continue;
6019       }
6020       const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
6021       const range = {
6022         start: Position.fromLocation(item.start),
6023         end: Position.fromLocation(item.end)
6024       };
6025       const symbolInfo = import_vscode_languageserver_protocol3.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
6026       result.push(symbolInfo);
6027     }
6028     return result;
6029   }
6030   static getLabel(item) {
6031     let label = item.name;
6032     if (item.kind === "method" || item.kind === "function") {
6033       label += "()";
6034     }
6035     return label;
6036   }
6037   getUri() {
6038     const documents = import_coc3.workspace.textDocuments;
6039     for (const document of documents) {
6040       if (this.languageIds.indexOf(document.languageId) >= 0) {
6041         return document.uri;
6042       }
6043     }
6044     return void 0;
6045   }
6046   get searchAllOpenProjects() {
6047     return this.client.apiVersion.gte(api_default.v390) && import_coc3.workspace.getConfiguration("typescript").get("workspaceSymbols.scope", "allOpenProjects") === "allOpenProjects";
6048   }
6049 };
6050 var workspaceSymbols_default = TypeScriptWorkspaceSymbolProvider;
6051
6052 // src/server/languageProvider.ts
6053 var import_coc18 = __toModule(require("coc.nvim"));
6054 var import_path4 = __toModule(require("path"));
6055 var import_vscode_languageserver_protocol18 = __toModule(require_main3());
6056
6057 // src/server/features/baseCodeLensProvider.ts
6058 var import_vscode_languageserver_protocol4 = __toModule(require_main3());
6059
6060 // src/server/utils/regexp.ts
6061 function escapeRegExp(text) {
6062   return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
6063 }
6064
6065 // src/server/features/baseCodeLensProvider.ts
6066 var CachedNavTreeResponse = class {
6067   constructor() {
6068     this.version = -1;
6069     this.document = "";
6070   }
6071   execute(document, f) {
6072     if (this.matches(document)) {
6073       return this.response;
6074     }
6075     return this.update(document, f());
6076   }
6077   matches(document) {
6078     return this.version === document.version && this.document === document.uri.toString();
6079   }
6080   update(document, response) {
6081     this.response = response;
6082     this.version = document.version;
6083     this.document = document.uri.toString();
6084     return response;
6085   }
6086 };
6087 var TypeScriptBaseCodeLensProvider = class {
6088   constructor(client, cachedResponse) {
6089     this.client = client;
6090     this.cachedResponse = cachedResponse;
6091     this.onDidChangeCodeLensesEmitter = new import_vscode_languageserver_protocol4.Emitter();
6092   }
6093   get onDidChangeCodeLenses() {
6094     return this.onDidChangeCodeLensesEmitter.event;
6095   }
6096   async provideCodeLenses(document, token) {
6097     const filepath = this.client.toPath(document.uri);
6098     if (!filepath) {
6099       return [];
6100     }
6101     try {
6102       const response = await this.cachedResponse.execute(document, () => this.client.execute("navtree", {file: filepath}, token));
6103       if (!response) {
6104         return [];
6105       }
6106       const tree = response.body;
6107       const referenceableSpans = [];
6108       if (tree && tree.childItems) {
6109         tree.childItems.forEach((item) => this.walkNavTree(document, item, null, referenceableSpans));
6110       }
6111       return referenceableSpans.map((range) => {
6112         return {
6113           range,
6114           data: {uri: document.uri}
6115         };
6116       });
6117     } catch {
6118       return [];
6119     }
6120   }
6121   walkNavTree(document, item, parent, results) {
6122     if (!item) {
6123       return;
6124     }
6125     const range = this.extractSymbol(document, item, parent);
6126     if (range) {
6127       results.push(range);
6128     }
6129     if (item.childItems) {
6130       item.childItems.forEach((child) => this.walkNavTree(document, child, item, results));
6131     }
6132   }
6133   getSymbolRange(document, item) {
6134     if (!item) {
6135       return null;
6136     }
6137     if (item.nameSpan) {
6138       return Range.fromTextSpan(item.nameSpan);
6139     }
6140     const span = item.spans && item.spans[0];
6141     if (!span) {
6142       return null;
6143     }
6144     const range = Range.fromTextSpan(span);
6145     const text = document.getText(range);
6146     const identifierMatch = new RegExp(`^(.*?(\\b|\\W))${escapeRegExp(item.text || "")}(\\b|\\W)`, "gm");
6147     const match = identifierMatch.exec(text);
6148     const prefixLength = match ? match.index + match[1].length : 0;
6149     const startOffset = document.offsetAt(range.start) + prefixLength;
6150     return {
6151       start: document.positionAt(startOffset),
6152       end: document.positionAt(startOffset + item.text.length)
6153     };
6154   }
6155 };
6156
6157 // src/server/features/completionItemProvider.ts
6158 var import_coc5 = __toModule(require("coc.nvim"));
6159 var import_vscode_languageserver_protocol8 = __toModule(require_main3());
6160
6161 // src/server/protocol.const.ts
6162 var Kind = class {
6163 };
6164 Kind.alias = "alias";
6165 Kind.callSignature = "call";
6166 Kind.class = "class";
6167 Kind.const = "const";
6168 Kind.constructorImplementation = "constructor";
6169 Kind.constructSignature = "construct";
6170 Kind.directory = "directory";
6171 Kind.enum = "enum";
6172 Kind.enumMember = "enum member";
6173 Kind.externalModuleName = "external module name";
6174 Kind.function = "function";
6175 Kind.indexSignature = "index";
6176 Kind.interface = "interface";
6177 Kind.keyword = "keyword";
6178 Kind.let = "let";
6179 Kind.localFunction = "local function";
6180 Kind.localVariable = "local var";
6181 Kind.method = "method";
6182 Kind.memberGetAccessor = "getter";
6183 Kind.memberSetAccessor = "setter";
6184 Kind.memberVariable = "property";
6185 Kind.module = "module";
6186 Kind.primitiveType = "primitive type";
6187 Kind.script = "script";
6188 Kind.type = "type";
6189 Kind.variable = "var";
6190 Kind.warning = "warning";
6191 Kind.string = "string";
6192 Kind.parameter = "parameter";
6193 Kind.typeParameter = "type parameter";
6194 var DiagnosticCategory = class {
6195 };
6196 DiagnosticCategory.error = "error";
6197 DiagnosticCategory.warning = "warning";
6198 DiagnosticCategory.suggestion = "suggestion";
6199 var KindModifiers2 = class {
6200 };
6201 var KindModifiers = KindModifiers2;
6202 KindModifiers.optional = "optional";
6203 KindModifiers.color = "color";
6204 KindModifiers.dtsFile = ".d.ts";
6205 KindModifiers.tsFile = ".ts";
6206 KindModifiers.tsxFile = ".tsx";
6207 KindModifiers.jsFile = ".js";
6208 KindModifiers.jsxFile = ".jsx";
6209 KindModifiers.jsonFile = ".json";
6210 KindModifiers.fileExtensionKindModifiers = [
6211   KindModifiers2.dtsFile,
6212   KindModifiers2.tsFile,
6213   KindModifiers2.tsxFile,
6214   KindModifiers2.jsFile,
6215   KindModifiers2.jsxFile,
6216   KindModifiers2.jsonFile
6217 ];
6218 var DisplayPartKind = class {
6219 };
6220 DisplayPartKind.functionName = "functionName";
6221 DisplayPartKind.methodName = "methodName";
6222 DisplayPartKind.parameterName = "parameterName";
6223 DisplayPartKind.propertyName = "propertyName";
6224 DisplayPartKind.punctuation = "punctuation";
6225 DisplayPartKind.text = "text";
6226
6227 // src/server/utils/codeAction.ts
6228 var import_vscode_languageserver_protocol5 = __toModule(require_main3());
6229 var import_coc4 = __toModule(require("coc.nvim"));
6230 function getEditForCodeAction(client, action) {
6231   return action.changes && action.changes.length ? WorkspaceEdit.fromFileCodeEdits(client, action.changes) : void 0;
6232 }
6233 async function applyCodeAction(client, action) {
6234   const workspaceEdit = getEditForCodeAction(client, action);
6235   if (workspaceEdit) {
6236     if (!await import_coc4.workspace.applyEdit(workspaceEdit)) {
6237       return false;
6238     }
6239   }
6240   return applyCodeActionCommands(client, action);
6241 }
6242 async function applyCodeActionCommands(client, action) {
6243   if (action.commands && action.commands.length) {
6244     for (const command of action.commands) {
6245       const response = await client.execute("applyCodeActionCommand", {command}, import_vscode_languageserver_protocol5.CancellationToken.None);
6246       if (!response || response.type != "response" || !response.body) {
6247         return false;
6248       }
6249     }
6250   }
6251   return true;
6252 }
6253
6254 // src/server/utils/completionItem.ts
6255 var import_vscode_languageserver_protocol6 = __toModule(require_main3());
6256 function convertCompletionEntry(tsEntry, uri, position, context) {
6257   let label = tsEntry.name;
6258   let sortText = tsEntry.sortText;
6259   let preselect = false;
6260   let detail;
6261   if (tsEntry.isRecommended) {
6262     preselect = true;
6263   }
6264   if (tsEntry.source) {
6265     sortText = "\uFFFF" + sortText;
6266   } else {
6267     sortText = tsEntry.sortText;
6268   }
6269   let kind = convertKind(tsEntry.kind);
6270   let insertTextFormat = context.enableCallCompletions && (kind === import_vscode_languageserver_protocol6.CompletionItemKind.Function || kind === import_vscode_languageserver_protocol6.CompletionItemKind.Method) ? import_vscode_languageserver_protocol6.InsertTextFormat.Snippet : import_vscode_languageserver_protocol6.InsertTextFormat.PlainText;
6271   let insertText = tsEntry.insertText;
6272   let commitCharacters = getCommitCharacters(tsEntry, context);
6273   let textEdit = null;
6274   if (tsEntry.replacementSpan) {
6275     let {start, end} = tsEntry.replacementSpan;
6276     if (start.line == end.line) {
6277       textEdit = {
6278         range: import_vscode_languageserver_protocol6.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
6279         newText: insertText || label
6280       };
6281     }
6282   }
6283   if (tsEntry.kindModifiers) {
6284     const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
6285     if (kindModifiers.has(KindModifiers.optional)) {
6286       insertText = label;
6287       label += "?";
6288     }
6289     if (kindModifiers.has(KindModifiers.color)) {
6290       kind = import_vscode_languageserver_protocol6.CompletionItemKind.Color;
6291     }
6292     if (tsEntry.kind === Kind.script) {
6293       for (const extModifier of KindModifiers.fileExtensionKindModifiers) {
6294         if (kindModifiers.has(extModifier)) {
6295           if (tsEntry.name.toLowerCase().endsWith(extModifier)) {
6296             detail = tsEntry.name;
6297           } else {
6298             detail = tsEntry.name + extModifier;
6299           }
6300           break;
6301         }
6302       }
6303     }
6304   }
6305   return {
6306     label,
6307     insertText,
6308     textEdit,
6309     kind,
6310     preselect,
6311     insertTextFormat,
6312     sortText,
6313     commitCharacters,
6314     detail,
6315     data: {
6316       uri,
6317       position,
6318       name: tsEntry.name,
6319       source: tsEntry.source || ""
6320     }
6321   };
6322 }
6323 function convertKind(kind) {
6324   switch (kind) {
6325     case Kind.primitiveType:
6326     case Kind.keyword:
6327       return import_vscode_languageserver_protocol6.CompletionItemKind.Keyword;
6328     case Kind.const:
6329       return import_vscode_languageserver_protocol6.CompletionItemKind.Constant;
6330     case Kind.let:
6331     case Kind.variable:
6332     case Kind.localVariable:
6333     case Kind.alias:
6334       return import_vscode_languageserver_protocol6.CompletionItemKind.Variable;
6335     case Kind.memberVariable:
6336     case Kind.memberGetAccessor:
6337     case Kind.memberSetAccessor:
6338       return import_vscode_languageserver_protocol6.CompletionItemKind.Field;
6339     case Kind.function:
6340       return import_vscode_languageserver_protocol6.CompletionItemKind.Function;
6341     case Kind.method:
6342     case Kind.constructSignature:
6343     case Kind.callSignature:
6344     case Kind.indexSignature:
6345       return import_vscode_languageserver_protocol6.CompletionItemKind.Method;
6346     case Kind.enum:
6347       return import_vscode_languageserver_protocol6.CompletionItemKind.Enum;
6348     case Kind.module:
6349     case Kind.externalModuleName:
6350       return import_vscode_languageserver_protocol6.CompletionItemKind.Module;
6351     case Kind.class:
6352     case Kind.type:
6353       return import_vscode_languageserver_protocol6.CompletionItemKind.Class;
6354     case Kind.interface:
6355       return import_vscode_languageserver_protocol6.CompletionItemKind.Interface;
6356     case Kind.warning:
6357     case Kind.script:
6358       return import_vscode_languageserver_protocol6.CompletionItemKind.File;
6359     case Kind.directory:
6360       return import_vscode_languageserver_protocol6.CompletionItemKind.Folder;
6361   }
6362   return import_vscode_languageserver_protocol6.CompletionItemKind.Variable;
6363 }
6364 function getCommitCharacters(tsEntry, context) {
6365   if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
6366     return void 0;
6367   }
6368   const commitCharacters = [];
6369   switch (tsEntry.kind) {
6370     case Kind.memberGetAccessor:
6371     case Kind.memberSetAccessor:
6372     case Kind.constructSignature:
6373     case Kind.callSignature:
6374     case Kind.indexSignature:
6375     case Kind.enum:
6376     case Kind.interface:
6377       commitCharacters.push(".", ";");
6378       break;
6379     case Kind.module:
6380     case Kind.alias:
6381     case Kind.const:
6382     case Kind.let:
6383     case Kind.variable:
6384     case Kind.localVariable:
6385     case Kind.memberVariable:
6386     case Kind.class:
6387     case Kind.function:
6388     case Kind.method:
6389     case Kind.keyword:
6390     case Kind.parameter:
6391       commitCharacters.push(".", ",", ";");
6392       if (context.enableCallCompletions) {
6393         commitCharacters.push("(");
6394       }
6395       break;
6396   }
6397   return commitCharacters.length === 0 ? void 0 : commitCharacters;
6398 }
6399 function getParameterListParts(displayParts) {
6400   const parts = [];
6401   let isInMethod = false;
6402   let hasOptionalParameters = false;
6403   let parenCount = 0;
6404   let braceCount = 0;
6405   outer:
6406     for (let i = 0; i < displayParts.length; ++i) {
6407       const part = displayParts[i];
6408       switch (part.kind) {
6409         case DisplayPartKind.methodName:
6410         case DisplayPartKind.functionName:
6411         case DisplayPartKind.text:
6412         case DisplayPartKind.propertyName:
6413           if (parenCount === 0 && braceCount === 0) {
6414             isInMethod = true;
6415           }
6416           break;
6417         case DisplayPartKind.parameterName:
6418           if (parenCount === 1 && braceCount === 0 && isInMethod) {
6419             const next = displayParts[i + 1];
6420             const nameIsFollowedByOptionalIndicator = next && next.text === "?";
6421             const nameIsThis = part.text === "this";
6422             if (!nameIsFollowedByOptionalIndicator && !nameIsThis) {
6423               parts.push(part);
6424             }
6425             hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
6426           }
6427           break;
6428         case DisplayPartKind.punctuation:
6429           if (part.text === "(") {
6430             ++parenCount;
6431           } else if (part.text === ")") {
6432             --parenCount;
6433             if (parenCount <= 0 && isInMethod) {
6434               break outer;
6435             }
6436           } else if (part.text === "..." && parenCount === 1) {
6437             hasOptionalParameters = true;
6438             break outer;
6439           } else if (part.text === "{") {
6440             ++braceCount;
6441           } else if (part.text === "}") {
6442             --braceCount;
6443           }
6444           break;
6445       }
6446     }
6447   return {hasOptionalParameters, parts};
6448 }
6449
6450 // src/server/utils/previewer.ts
6451 var import_vscode_languageserver_protocol7 = __toModule(require_main3());
6452 function getTagBodyText(tag) {
6453   if (!tag.text) {
6454     return void 0;
6455   }
6456   switch (tag.name) {
6457     case "example":
6458     case "default":
6459       if (tag.text.match(/^\s*[~`]{3}/g)) {
6460         return tag.text;
6461       }
6462       return "```\n" + tag.text + "\n```";
6463   }
6464   return tag.text;
6465 }
6466 function getTagDocumentation(tag) {
6467   switch (tag.name) {
6468     case "param":
6469       const body = (tag.text || "").split(/^([\w\.]+)\s*/);
6470       if (body && body.length === 3) {
6471         const param = body[1];
6472         const doc = body[2];
6473         const label2 = `*@${tag.name}* \`${param}\``;
6474         if (!doc) {
6475           return label2;
6476         }
6477         return label2 + (doc.match(/\r\n|\n/g) ? "\n" + doc : ` \u2014 ${doc}`);
6478       }
6479   }
6480   const label = `*@${tag.name}*`;
6481   const text = getTagBodyText(tag);
6482   if (!text) {
6483     return label;
6484   }
6485   return label + (text.match(/\r\n|\n/g) ? "\n" + text : ` \u2014 ${text}`);
6486 }
6487 function plain(parts) {
6488   if (!parts || !parts.length)
6489     return "";
6490   return parts.map((part) => part.text).join("");
6491 }
6492 function tagsMarkdownPreview(tags) {
6493   return (tags || []).map(getTagDocumentation).join("  \n\n");
6494 }
6495 function markdownDocumentation(documentation, tags) {
6496   let out = plain(documentation);
6497   const tagsPreview = tagsMarkdownPreview(tags);
6498   if (tagsPreview) {
6499     out = out + ("\n\n" + tagsPreview);
6500   }
6501   return {
6502     kind: import_vscode_languageserver_protocol7.MarkupKind.Markdown,
6503     value: out
6504   };
6505 }
6506
6507 // src/server/utils/SnippetString.ts
6508 var SnippetString = class {
6509   constructor(value) {
6510     this._tabstop = 1;
6511     this.value = value || "";
6512   }
6513   static isSnippetString(thing) {
6514     if (thing instanceof SnippetString) {
6515       return true;
6516     }
6517     if (!thing) {
6518       return false;
6519     }
6520     return typeof thing.value === "string";
6521   }
6522   static _escape(value) {
6523     return value.replace(/\$|}|\\/g, "\\$&");
6524   }
6525   appendText(str) {
6526     this.value += SnippetString._escape(str);
6527     return this;
6528   }
6529   appendTabstop(n = this._tabstop++) {
6530     this.value += "$";
6531     this.value += n;
6532     return this;
6533   }
6534   appendPlaceholder(value, n = this._tabstop++) {
6535     if (typeof value === "function") {
6536       const nested = new SnippetString();
6537       nested._tabstop = this._tabstop;
6538       value(nested);
6539       this._tabstop = nested._tabstop;
6540       value = nested.value;
6541     } else {
6542       value = SnippetString._escape(value);
6543     }
6544     this.value += "${";
6545     this.value += n;
6546     this.value += ":";
6547     this.value += value;
6548     this.value += "}";
6549     return this;
6550   }
6551   appendVariable(name, defaultValue) {
6552     if (typeof defaultValue === "function") {
6553       const nested = new SnippetString();
6554       nested._tabstop = this._tabstop;
6555       defaultValue(nested);
6556       this._tabstop = nested._tabstop;
6557       defaultValue = nested.value;
6558     } else if (typeof defaultValue === "string") {
6559       defaultValue = defaultValue.replace(/\$|}/g, "\\$&");
6560     }
6561     this.value += "${";
6562     this.value += name;
6563     if (defaultValue) {
6564       this.value += ":";
6565       this.value += defaultValue;
6566     }
6567     this.value += "}";
6568     return this;
6569   }
6570 };
6571 var SnippetString_default = SnippetString;
6572
6573 // src/server/features/completionItemProvider.ts
6574 var ApplyCompletionCodeActionCommand2 = class {
6575   constructor(client) {
6576     this.client = client;
6577     this.id = ApplyCompletionCodeActionCommand2.ID;
6578   }
6579   async execute(codeActions) {
6580     if (codeActions.length === 0) {
6581       return;
6582     }
6583     if (codeActions.length === 1) {
6584       await applyCodeAction(this.client, codeActions[0]);
6585       return;
6586     }
6587     const idx = await import_coc5.window.showQuickpick(codeActions.map((o) => o.description), "Select code action to apply");
6588     if (idx < 0)
6589       return;
6590     const action = codeActions[idx];
6591     await applyCodeAction(this.client, action);
6592     return;
6593   }
6594 };
6595 var ApplyCompletionCodeActionCommand = ApplyCompletionCodeActionCommand2;
6596 ApplyCompletionCodeActionCommand.ID = "_typescript.applyCompletionCodeAction";
6597 var TypeScriptCompletionItemProvider = class {
6598   constructor(client, typingsStatus, fileConfigurationManager, languageId) {
6599     this.client = client;
6600     this.typingsStatus = typingsStatus;
6601     this.fileConfigurationManager = fileConfigurationManager;
6602     this.setCompleteOption(languageId);
6603     import_coc5.commands.registerCommand(ApplyCompletionCodeActionCommand.ID, async (codeActions) => {
6604       let cmd = new ApplyCompletionCodeActionCommand(this.client);
6605       await cmd.execute(codeActions);
6606     });
6607     import_coc5.workspace.onDidChangeConfiguration((_e) => {
6608       this.setCompleteOption(languageId);
6609     });
6610   }
6611   setCompleteOption(languageId) {
6612     this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
6613   }
6614   async provideCompletionItems(document, position, token, context) {
6615     if (this.typingsStatus.isAcquiringTypings) {
6616       return Promise.resolve({
6617         isIncomplete: true,
6618         items: [{
6619           label: "Acquiring typings...",
6620           detail: "Acquiring typings definitions for IntelliSense."
6621         }]
6622       });
6623     }
6624     let {uri} = document;
6625     const file2 = this.client.toPath(document.uri);
6626     if (!file2)
6627       return null;
6628     let preText = document.getText({
6629       start: {line: position.line, character: 0},
6630       end: position
6631     });
6632     let {triggerCharacter, option} = context;
6633     if (!this.shouldTrigger(triggerCharacter, preText, option)) {
6634       return null;
6635     }
6636     await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
6637     const {completeOption} = this;
6638     const args = {
6639       ...Position.toFileLocationRequestArgs(file2, position),
6640       includeExternalModuleExports: completeOption.autoImports,
6641       includeInsertTextCompletions: true,
6642       triggerCharacter: this.getTsTriggerCharacter(context),
6643       includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions
6644     };
6645     let entries;
6646     let dotAccessorContext;
6647     let isNewIdentifierLocation = true;
6648     let isMemberCompletion = false;
6649     let isIncomplete = false;
6650     const isInValidCommitCharacterContext = this.isInValidCommitCharacterContext(document, position);
6651     if (this.client.apiVersion.gte(api_default.v300)) {
6652       try {
6653         const response = await this.client.interruptGetErr(() => this.client.execute("completionInfo", args, token));
6654         if (response.type !== "response" || !response.body) {
6655           return null;
6656         }
6657         isNewIdentifierLocation = response.body.isNewIdentifierLocation;
6658         isMemberCompletion = response.body.isMemberCompletion;
6659         if (isMemberCompletion) {
6660           const dotMatch = preText.slice(0, position.character).match(/\??\.\s*$/) || void 0;
6661           if (dotMatch) {
6662             const range = import_vscode_languageserver_protocol8.Range.create({
6663               line: position.line,
6664               character: position.character - dotMatch.length
6665             }, position);
6666             const text = document.getText(range);
6667             dotAccessorContext = {range, text};
6668           }
6669         }
6670         isIncomplete = response.metadata && response.metadata.isIncomplete;
6671         entries = response.body.entries;
6672       } catch (e) {
6673         if (e.message == "No content available.") {
6674           return null;
6675         }
6676         throw e;
6677       }
6678     } else {
6679       const response = await this.client.interruptGetErr(() => this.client.execute("completions", args, token));
6680       if (response.type !== "response" || !response.body) {
6681         return null;
6682       }
6683       entries = response.body;
6684     }
6685     const completionItems = [];
6686     for (const element of entries) {
6687       if (shouldExcludeCompletionEntry(element, completeOption)) {
6688         continue;
6689       }
6690       const item = convertCompletionEntry(element, uri, position, {
6691         isNewIdentifierLocation,
6692         isMemberCompletion,
6693         enableCallCompletions: completeOption.completeFunctionCalls,
6694         isInValidCommitCharacterContext,
6695         dotAccessorContext
6696       });
6697       completionItems.push(item);
6698     }
6699     return {isIncomplete, items: completionItems};
6700   }
6701   getTsTriggerCharacter(context) {
6702     switch (context.triggerCharacter) {
6703       case "@":
6704         return this.client.apiVersion.gte(api_default.v310) && this.client.apiVersion.lt(api_default.v320) ? void 0 : "@";
6705       case "#":
6706         return this.client.apiVersion.lt(api_default.v381) ? void 0 : "#";
6707       case ".":
6708       case '"':
6709       case "'":
6710       case "`":
6711       case "/":
6712       case "<":
6713         return context.triggerCharacter;
6714     }
6715     return void 0;
6716   }
6717   async resolveCompletionItem(item, token) {
6718     if (item == null)
6719       return void 0;
6720     let {uri, position, source, name} = item.data;
6721     const filepath = this.client.toPath(uri);
6722     if (!filepath)
6723       return void 0;
6724     let document = import_coc5.workspace.getDocument(uri);
6725     if (!document)
6726       return void 0;
6727     const args = {
6728       ...Position.toFileLocationRequestArgs(filepath, position),
6729       entryNames: [source ? {name, source} : name]
6730     };
6731     let response;
6732     try {
6733       response = await this.client.interruptGetErr(() => this.client.execute("completionEntryDetails", args, token));
6734     } catch {
6735       return item;
6736     }
6737     if (response.type !== "response" || !response.body || !response.body.length) {
6738       return item;
6739     }
6740     const details = response.body;
6741     if (!details || !details.length || !details[0]) {
6742       return item;
6743     }
6744     const detail = details[0];
6745     if (!item.detail && detail.displayParts.length) {
6746       item.detail = plain(detail.displayParts);
6747     }
6748     item.documentation = this.getDocumentation(detail);
6749     const {command, additionalTextEdits} = this.getCodeActions(detail, filepath);
6750     if (command)
6751       item.command = command;
6752     item.additionalTextEdits = additionalTextEdits;
6753     if (detail && item.insertTextFormat == import_vscode_languageserver_protocol8.InsertTextFormat.Snippet) {
6754       const shouldCompleteFunction = await this.isValidFunctionCompletionContext(filepath, position, token);
6755       if (shouldCompleteFunction) {
6756         this.createSnippetOfFunctionCall(item, detail);
6757       }
6758     }
6759     return item;
6760   }
6761   getCodeActions(detail, filepath) {
6762     if (!detail.codeActions || !detail.codeActions.length) {
6763       return {};
6764     }
6765     const additionalTextEdits = [];
6766     let hasRemainingCommandsOrEdits = false;
6767     for (const tsAction of detail.codeActions) {
6768       if (tsAction.commands) {
6769         hasRemainingCommandsOrEdits = true;
6770       }
6771       if (tsAction.changes) {
6772         for (const change of tsAction.changes) {
6773           if (change.fileName === filepath) {
6774             additionalTextEdits.push(...change.textChanges.map(TextEdit.fromCodeEdit));
6775           } else {
6776             hasRemainingCommandsOrEdits = true;
6777           }
6778         }
6779       }
6780     }
6781     let command = null;
6782     if (hasRemainingCommandsOrEdits) {
6783       command = {
6784         title: "",
6785         command: ApplyCompletionCodeActionCommand.ID,
6786         arguments: [
6787           detail.codeActions.map((x) => ({
6788             commands: x.commands,
6789             description: x.description,
6790             changes: x.changes.filter((x2) => x2.fileName !== filepath)
6791           }))
6792         ]
6793       };
6794     }
6795     return {
6796       command,
6797       additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : void 0
6798     };
6799   }
6800   shouldTrigger(triggerCharacter, pre, option) {
6801     if (triggerCharacter && this.client.apiVersion.lt(api_default.v290)) {
6802       if (triggerCharacter === "@") {
6803         if (option.synname && /string/i.test(option.synname)) {
6804           return true;
6805         }
6806         if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
6807           return false;
6808         }
6809       } else if (triggerCharacter === "<") {
6810         return false;
6811       }
6812     }
6813     return true;
6814   }
6815   getDocumentation(detail) {
6816     let documentation = "";
6817     if (detail.source) {
6818       const importPath = `'${plain(detail.source)}'`;
6819       const autoImportLabel = `Auto import from ${importPath}`;
6820       documentation += `${autoImportLabel}
6821 `;
6822     }
6823     let parts = [
6824       plain(detail.documentation),
6825       tagsMarkdownPreview(detail.tags)
6826     ];
6827     parts = parts.filter((s) => s && s.trim() != "");
6828     documentation += parts.join("\n\n");
6829     if (documentation.length) {
6830       return {
6831         kind: import_vscode_languageserver_protocol8.MarkupKind.Markdown,
6832         value: documentation
6833       };
6834     }
6835     return void 0;
6836   }
6837   createSnippetOfFunctionCall(item, detail) {
6838     let {displayParts} = detail;
6839     const parameterListParts = getParameterListParts(displayParts);
6840     const snippet = new SnippetString_default();
6841     snippet.appendText(`${item.insertText || item.label}(`);
6842     appendJoinedPlaceholders(snippet, parameterListParts.parts, ", ");
6843     if (parameterListParts.hasOptionalParameters) {
6844       snippet.appendTabstop();
6845     }
6846     snippet.appendText(")");
6847     snippet.appendTabstop(0);
6848     item.insertText = snippet.value;
6849   }
6850   async isValidFunctionCompletionContext(filepath, position, token) {
6851     try {
6852       const args = Position.toFileLocationRequestArgs(filepath, position);
6853       const response = await this.client.execute("quickinfo", args, token);
6854       if (response.type !== "response") {
6855         return true;
6856       }
6857       const {body} = response;
6858       switch (body && body.kind) {
6859         case "var":
6860         case "let":
6861         case "const":
6862         case "alias":
6863           return false;
6864         default:
6865           return true;
6866       }
6867     } catch (e) {
6868       return true;
6869     }
6870   }
6871   isInValidCommitCharacterContext(document, position) {
6872     if (this.client.apiVersion.lt(api_default.v320)) {
6873       if (position.character > 1) {
6874         const preText = document.getText(import_vscode_languageserver_protocol8.Range.create(position.line, 0, position.line, position.character));
6875         return preText.match(/(\s|^)\.$/ig) === null;
6876       }
6877     }
6878     return true;
6879   }
6880 };
6881 TypeScriptCompletionItemProvider.triggerCharacters = [".", '"', "'", "`", "/", "@", "<", "#"];
6882 var completionItemProvider_default = TypeScriptCompletionItemProvider;
6883 function shouldExcludeCompletionEntry(element, completionConfiguration) {
6884   return !completionConfiguration.names && element.kind === Kind.warning || !completionConfiguration.paths && (element.kind === Kind.directory || element.kind === Kind.script || element.kind === Kind.externalModuleName) || !completionConfiguration.autoImports && element.hasAction;
6885 }
6886 function appendJoinedPlaceholders(snippet, parts, joiner) {
6887   for (let i = 0; i < parts.length; ++i) {
6888     const paramterPart = parts[i];
6889     snippet.appendPlaceholder(paramterPart.text);
6890     if (i !== parts.length - 1) {
6891       snippet.appendText(joiner);
6892     }
6893   }
6894 }
6895
6896 // src/server/features/definitionProvider.ts
6897 var TypeScriptDefinitionProvider = class {
6898   constructor(client) {
6899     this.client = client;
6900   }
6901   async getSymbolLocations(definitionType, document, position, token) {
6902     const filepath = this.client.toPath(document.uri);
6903     if (!filepath) {
6904       return void 0;
6905     }
6906     const args = Position.toFileLocationRequestArgs(filepath, position);
6907     try {
6908       const response = await this.client.execute(definitionType, args, token);
6909       const locations = response.type == "response" && response.body || [];
6910       return locations.map((location) => Location2.fromTextSpan(this.client.toResource(location.file), location));
6911     } catch {
6912       return [];
6913     }
6914   }
6915   provideDefinition(document, position, token) {
6916     return this.getSymbolLocations("definition", document, position, token);
6917   }
6918   provideTypeDefinition(document, position, token) {
6919     return this.getSymbolLocations("typeDefinition", document, position, token);
6920   }
6921   provideImplementation(document, position, token) {
6922     return this.getSymbolLocations("implementation", document, position, token);
6923   }
6924 };
6925 var definitionProvider_default = TypeScriptDefinitionProvider;
6926
6927 // src/server/features/directiveCommentCompletions.ts
6928 var import_vscode_languageserver_protocol9 = __toModule(require_main3());
6929 var import_coc6 = __toModule(require("coc.nvim"));
6930 var tsDirectives = [
6931   {
6932     value: "@ts-check",
6933     description: "Enables semantic checking in a JavaScript file. Must be at the top of a file."
6934   },
6935   {
6936     value: "@ts-nocheck",
6937     description: "Disables semantic checking in a JavaScript file. Must be at the top of a file."
6938   },
6939   {
6940     value: "@ts-ignore",
6941     description: "Suppresses @ts-check errors on the next line of a file."
6942   }
6943 ];
6944 var tsDirectives390 = [
6945   ...tsDirectives,
6946   {
6947     value: "@ts-expect-error",
6948     description: "Suppresses @ts-check errors on the next line of a file, expecting at least one to exist."
6949   }
6950 ];
6951 var DirectiveCommentCompletionProvider = class {
6952   constructor(client) {
6953     this.client = client;
6954   }
6955   provideCompletionItems(document, position, _token, context) {
6956     if (context.triggerCharacter != "@") {
6957       return [];
6958     }
6959     const file2 = this.client.toPath(document.uri);
6960     if (!file2) {
6961       return [];
6962     }
6963     const doc = import_coc6.workspace.getDocument(document.uri);
6964     const line = doc.getline(position.line);
6965     const prefix = line.slice(0, position.character);
6966     const match = prefix.match(/^\s*\/\/+\s?(@[a-zA-Z\-]*)?$/);
6967     if (match) {
6968       const directives = this.client.apiVersion.gte(api_default.v390) ? tsDirectives390 : tsDirectives;
6969       let items = directives.map((directive) => {
6970         const item = import_vscode_languageserver_protocol9.CompletionItem.create(directive.value);
6971         item.kind = import_vscode_languageserver_protocol9.CompletionItemKind.Snippet;
6972         item.detail = directive.description;
6973         item.textEdit = {
6974           range: import_vscode_languageserver_protocol9.Range.create(position.line, Math.max(0, position.character - (match[1] ? match[1].length : 0)), position.line, position.character),
6975           newText: directive.value
6976         };
6977         return item;
6978       });
6979       let res = {
6980         isIncomplete: false,
6981         items
6982       };
6983       res.startcol = doc.fixStartcol(position, ["@"]);
6984       return res;
6985     }
6986     return [];
6987   }
6988 };
6989 var directiveCommentCompletions_default = DirectiveCommentCompletionProvider;
6990
6991 // src/server/features/documentHighlight.ts
6992 var import_vscode_languageserver_protocol10 = __toModule(require_main3());
6993 var TypeScriptDocumentHighlightProvider = class {
6994   constructor(client) {
6995     this.client = client;
6996   }
6997   async provideDocumentHighlights(resource, position, token) {
6998     const file2 = this.client.toPath(resource.uri);
6999     if (!file2)
7000       return [];
7001     const args = {
7002       ...Position.toFileLocationRequestArgs(file2, position),
7003       filesToSearch: [file2]
7004     };
7005     try {
7006       const response = await this.client.execute("documentHighlights", args, token);
7007       if (response.type !== "response" || !response.body) {
7008         return [];
7009       }
7010       return flatten(response.body.filter((highlight) => highlight.file === file2).map(convertDocumentHighlight));
7011     } catch (_e) {
7012       return [];
7013     }
7014   }
7015 };
7016 var documentHighlight_default = TypeScriptDocumentHighlightProvider;
7017 function convertDocumentHighlight(highlight) {
7018   return highlight.highlightSpans.map((span) => {
7019     return {
7020       range: Range.fromTextSpan(span),
7021       kind: span.kind === "writtenReference" ? import_vscode_languageserver_protocol10.DocumentHighlightKind.Write : import_vscode_languageserver_protocol10.DocumentHighlightKind.Read
7022     };
7023   });
7024 }
7025
7026 // src/server/features/documentSymbol.ts
7027 var import_vscode_languageserver_protocol11 = __toModule(require_main3());
7028 var getSymbolKind2 = (kind) => {
7029   switch (kind) {
7030     case Kind.module:
7031       return import_vscode_languageserver_protocol11.SymbolKind.Module;
7032     case Kind.class:
7033       return import_vscode_languageserver_protocol11.SymbolKind.Class;
7034     case Kind.enum:
7035       return import_vscode_languageserver_protocol11.SymbolKind.Enum;
7036     case Kind.interface:
7037       return import_vscode_languageserver_protocol11.SymbolKind.Interface;
7038     case Kind.method:
7039       return import_vscode_languageserver_protocol11.SymbolKind.Method;
7040     case Kind.memberVariable:
7041       return import_vscode_languageserver_protocol11.SymbolKind.Property;
7042     case Kind.memberGetAccessor:
7043       return import_vscode_languageserver_protocol11.SymbolKind.Property;
7044     case Kind.memberSetAccessor:
7045       return import_vscode_languageserver_protocol11.SymbolKind.Property;
7046     case Kind.variable:
7047       return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7048     case Kind.const:
7049       return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7050     case Kind.localVariable:
7051       return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7052     case Kind.variable:
7053       return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7054     case Kind.constructSignature:
7055     case Kind.constructorImplementation:
7056     case Kind.function:
7057     case Kind.localFunction:
7058       return import_vscode_languageserver_protocol11.SymbolKind.Function;
7059   }
7060   return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7061 };
7062 var TypeScriptDocumentSymbolProvider = class {
7063   constructor(client) {
7064     this.client = client;
7065   }
7066   async provideDocumentSymbols(resource, token) {
7067     const filepath = this.client.toPath(resource.uri);
7068     if (!filepath)
7069       return [];
7070     const args = {
7071       file: filepath
7072     };
7073     try {
7074       const response = await this.client.execute("navtree", args, token);
7075       if (response.type == "response" && response.body) {
7076         const tree = response.body;
7077         if (tree.childItems) {
7078           const result = new Array();
7079           tree.childItems.forEach((item) => TypeScriptDocumentSymbolProvider.convertNavTree(result, item));
7080           return result;
7081         }
7082       }
7083       return [];
7084     } catch (e) {
7085       return [];
7086     }
7087   }
7088   static convertNavTree(bucket, item) {
7089     let shouldInclude = TypeScriptDocumentSymbolProvider.shouldInclueEntry(item);
7090     const children = new Set(item.childItems || []);
7091     for (const span of item.spans) {
7092       const range = Range.fromTextSpan(span);
7093       const symbolInfo = import_vscode_languageserver_protocol11.DocumentSymbol.create(item.text, "", getSymbolKind2(item.kind), range, range);
7094       symbolInfo.children = children.size > 0 ? [] : null;
7095       for (const child of children) {
7096         if (child.spans.some((span2) => !!containsRange(range, Range.fromTextSpan(span2)))) {
7097           const includedChild = TypeScriptDocumentSymbolProvider.convertNavTree(symbolInfo.children, child);
7098           shouldInclude = shouldInclude || includedChild;
7099           children.delete(child);
7100         }
7101       }
7102       if (shouldInclude) {
7103         bucket.push(symbolInfo);
7104       }
7105     }
7106     return shouldInclude;
7107   }
7108   static shouldInclueEntry(item) {
7109     if (item.kind === Kind.alias) {
7110       return false;
7111     }
7112     return !!(item.text && item.text !== "<function>" && item.text !== "<class>");
7113   }
7114 };
7115 var documentSymbol_default = TypeScriptDocumentSymbolProvider;
7116 function containsRange(range, otherRange) {
7117   if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
7118     return false;
7119   }
7120   if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
7121     return false;
7122   }
7123   if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
7124     return false;
7125   }
7126   if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
7127     return false;
7128   }
7129   return true;
7130 }
7131
7132 // src/server/features/folding.ts
7133 var import_coc7 = __toModule(require("coc.nvim"));
7134 var import_vscode_languageserver_types = __toModule(require_main2());
7135 var TypeScriptFoldingProvider = class {
7136   constructor(client) {
7137     this.client = client;
7138   }
7139   async provideFoldingRanges(document, _context, token) {
7140     const file2 = this.client.toPath(document.uri);
7141     if (!file2) {
7142       return;
7143     }
7144     const args = {file: file2};
7145     const res = await this.client.execute("getOutliningSpans", args, token);
7146     if (res.type != "response") {
7147       return;
7148     }
7149     const {body} = res;
7150     if (!body) {
7151       return;
7152     }
7153     return body.map((span) => this.convertOutliningSpan(span, document)).filter((foldingRange) => !!foldingRange);
7154   }
7155   convertOutliningSpan(span, document) {
7156     const range = Range.fromTextSpan(span.textSpan);
7157     const kind = TypeScriptFoldingProvider.getFoldingRangeKind(span);
7158     if (span.kind === "comment") {
7159       let doc = import_coc7.workspace.getDocument(document.uri);
7160       const line = doc.getline(range.start.line);
7161       if (line.match(/\/\/\s*#endregion/gi)) {
7162         return void 0;
7163       }
7164     }
7165     let {start, end} = range;
7166     return import_vscode_languageserver_types.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
7167   }
7168   static getFoldingRangeKind(span) {
7169     switch (span.kind) {
7170       case "comment":
7171       case "region":
7172       case "imports":
7173       case "code":
7174         return span.kind;
7175       default:
7176         return void 0;
7177     }
7178   }
7179 };
7180 var folding_default = TypeScriptFoldingProvider;
7181
7182 // src/server/features/formatting.ts
7183 var import_coc8 = __toModule(require("coc.nvim"));
7184 var TypeScriptFormattingProvider = class {
7185   constructor(client, formattingOptionsManager) {
7186     this.client = client;
7187     this.formattingOptionsManager = formattingOptionsManager;
7188   }
7189   enabled(document) {
7190     return this.formattingOptionsManager.formatEnabled(document);
7191   }
7192   async doFormat(document, options, args, token) {
7193     if (!this.enabled(document))
7194       return [];
7195     await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
7196     try {
7197       const response = await this.client.execute("format", args, token);
7198       if (response.type == "response" && response.body) {
7199         let edits = response.body.map(TextEdit.fromCodeEdit);
7200         return edits;
7201       }
7202     } catch {
7203     }
7204     return [];
7205   }
7206   async provideDocumentRangeFormattingEdits(document, range, options, token) {
7207     if (!this.enabled(document))
7208       return [];
7209     const filepath = this.client.toPath(document.uri);
7210     if (!filepath)
7211       return [];
7212     const args = {
7213       file: filepath,
7214       line: range.start.line + 1,
7215       offset: range.start.character + 1,
7216       endLine: range.end.line + 1,
7217       endOffset: range.end.character + 1
7218     };
7219     return this.doFormat(document, options, args, token);
7220   }
7221   async provideDocumentFormattingEdits(document, options, token) {
7222     if (!this.enabled(document))
7223       return [];
7224     const filepath = this.client.toPath(document.uri);
7225     if (!filepath)
7226       return [];
7227     const args = {
7228       file: filepath,
7229       line: 1,
7230       offset: 1,
7231       endLine: document.lineCount + 1,
7232       endOffset: 1
7233     };
7234     return this.doFormat(document, options, args, token);
7235   }
7236   async provideOnTypeFormattingEdits(document, position, ch, options, token) {
7237     if (!this.enabled(document))
7238       return [];
7239     if (!this.client.configuration.formatOnType)
7240       return [];
7241     const file2 = this.client.toPath(document.uri);
7242     if (!file2)
7243       return [];
7244     await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
7245     const doc = import_coc8.workspace.getDocument(document.uri);
7246     const args = {
7247       ...Position.toFileLocationRequestArgs(file2, position),
7248       key: ch
7249     };
7250     try {
7251       const res = await this.client.execute("formatonkey", args, token);
7252       if (res.type != "response") {
7253         return [];
7254       }
7255       const {body} = res;
7256       const edits = body;
7257       const result = [];
7258       if (!edits) {
7259         return result;
7260       }
7261       for (const edit of edits) {
7262         const textEdit = TextEdit.fromCodeEdit(edit);
7263         const range = textEdit.range;
7264         if (range.start.character === 0 && range.start.line === range.end.line && textEdit.newText === "") {
7265           const lText = doc.getline(range.start.line);
7266           if (lText.trim().length > 0 || lText.length > range.end.character) {
7267             result.push(textEdit);
7268           }
7269         } else {
7270           result.push(textEdit);
7271         }
7272       }
7273       return result;
7274     } catch {
7275     }
7276     return [];
7277   }
7278 };
7279 var formatting_default = TypeScriptFormattingProvider;
7280
7281 // src/server/features/hover.ts
7282 var TypeScriptHoverProvider = class {
7283   constructor(client) {
7284     this.client = client;
7285   }
7286   async provideHover(document, position, token) {
7287     const filepath = this.client.toPath(document.uri);
7288     if (!filepath) {
7289       return void 0;
7290     }
7291     const args = Position.toFileLocationRequestArgs(filepath, position);
7292     try {
7293       const response = await this.client.interruptGetErr(() => this.client.execute("quickinfo", args, token));
7294       if (response && response.type == "response" && response.body) {
7295         const data = response.body;
7296         return {
7297           contents: TypeScriptHoverProvider.getContents(data),
7298           range: Range.fromTextSpan(data)
7299         };
7300       }
7301     } catch (e) {
7302     }
7303     return void 0;
7304   }
7305   static getContents(data) {
7306     const parts = [];
7307     if (data.displayString) {
7308       parts.push({language: "typescript", value: data.displayString});
7309     }
7310     const tags = tagsMarkdownPreview(data.tags);
7311     parts.push(data.documentation + (tags ? "\n\n" + tags : ""));
7312     return parts;
7313   }
7314 };
7315 var hover_default = TypeScriptHoverProvider;
7316
7317 // src/server/features/implementationsCodeLens.ts
7318 var TypeScriptImplementationsCodeLensProvider = class extends TypeScriptBaseCodeLensProvider {
7319   async resolveCodeLens(codeLens, token) {
7320     let {uri} = codeLens.data;
7321     let filepath = this.client.toPath(uri);
7322     const args = Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
7323     try {
7324       const response = await this.client.execute("implementation", args, token, {lowPriority: true});
7325       if (response && response.type == "response" && response.body) {
7326         const locations = response.body.map((reference) => {
7327           return {
7328             uri: this.client.toResource(reference.file),
7329             range: {
7330               start: Position.fromLocation(reference.start),
7331               end: {
7332                 line: reference.start.line,
7333                 character: 0
7334               }
7335             }
7336           };
7337         }).filter((location) => !(location.uri.toString() === uri && location.range.start.line === codeLens.range.start.line && location.range.start.character === codeLens.range.start.character));
7338         codeLens.command = this.getCommand(locations, codeLens);
7339         return codeLens;
7340       }
7341     } catch {
7342     }
7343     codeLens.command = {
7344       title: "0 implementations",
7345       command: ""
7346     };
7347     return codeLens;
7348   }
7349   getCommand(locations, codeLens) {
7350     let {uri} = codeLens.data;
7351     return {
7352       title: this.getTitle(locations),
7353       command: locations.length ? "editor.action.showReferences" : "",
7354       arguments: [uri, codeLens.range.start, locations]
7355     };
7356   }
7357   getTitle(locations) {
7358     return locations.length === 1 ? "1 implementation" : `${locations.length} implementations`;
7359   }
7360   extractSymbol(document, item, _parent) {
7361     switch (item.kind) {
7362       case Kind.interface:
7363         return super.getSymbolRange(document, item);
7364       case Kind.class:
7365       case Kind.method:
7366       case Kind.memberVariable:
7367       case Kind.memberGetAccessor:
7368       case Kind.memberSetAccessor:
7369         if (item.kindModifiers.match(/\babstract\b/g)) {
7370           return super.getSymbolRange(document, item);
7371         }
7372         break;
7373     }
7374     return null;
7375   }
7376 };
7377 var implementationsCodeLens_default = TypeScriptImplementationsCodeLensProvider;
7378
7379 // src/server/features/importFix.ts
7380 var import_coc9 = __toModule(require("coc.nvim"));
7381 var import_vscode_languageserver_protocol12 = __toModule(require_main3());
7382
7383 // src/server/utils/helper.ts
7384 var nodeModules = [
7385   "assert",
7386   "cluster",
7387   "crypto",
7388   "dns",
7389   "domain",
7390   "events",
7391   "fs",
7392   "http",
7393   "http2",
7394   "https",
7395   "inspector",
7396   "net",
7397   "os",
7398   "path",
7399   "punycode",
7400   "querystring",
7401   "readline",
7402   "repl",
7403   "stream",
7404   "string_decoder",
7405   "tls",
7406   "tty",
7407   "url",
7408   "util",
7409   "v8",
7410   "vm",
7411   "zlib",
7412   "perf_hooks"
7413 ];
7414
7415 // src/server/features/importFix.ts
7416 var ImportFixProvider = class {
7417   constructor(bufferSyncSupport) {
7418     this.bufferSyncSupport = bufferSyncSupport;
7419   }
7420   async provideCodeActions(document, _range, context, _token) {
7421     if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
7422       return [];
7423     }
7424     let diagnostics = context.diagnostics.filter((d) => d.code == 2304);
7425     if (!diagnostics.length)
7426       return [];
7427     let edits = [];
7428     let names = [];
7429     let doc = import_coc9.workspace.getDocument(document.uri);
7430     let command;
7431     for (const diagnostic of diagnostics) {
7432       let {range} = diagnostic;
7433       let line = doc.getline(range.start.line);
7434       let name = line.slice(range.start.character, range.end.character);
7435       if (names.indexOf(name) !== -1)
7436         continue;
7437       if (nodeModules.indexOf(name) !== -1) {
7438         names.push(name);
7439         edits.push({
7440           range: import_vscode_languageserver_protocol12.Range.create(0, 0, 0, 0),
7441           newText: `import ${name} from '${name}'
7442 `
7443         });
7444         command = "tsserver.organizeImports";
7445       }
7446     }
7447     let edit = {
7448       changes: {
7449         [document.uri]: edits
7450       }
7451     };
7452     let cmd = null;
7453     if (command)
7454       cmd = {
7455         title: `fix import`,
7456         command: "tsserver.organizeImports"
7457       };
7458     return [{
7459       title: `Add import ${names.join(", ")}`,
7460       edit,
7461       command: cmd
7462     }];
7463   }
7464 };
7465 var importFix_default = ImportFixProvider;
7466
7467 // src/server/features/moduleInstall.ts
7468 var import_coc11 = __toModule(require("coc.nvim"));
7469 var import_vscode_languageserver_protocol13 = __toModule(require_main3());
7470
7471 // src/server/utils/modules.ts
7472 var import_child_process = __toModule(require("child_process"));
7473 var import_coc10 = __toModule(require("coc.nvim"));
7474 var import_fs = __toModule(require("fs"));
7475 var import_path2 = __toModule(require("path"));
7476 function runCommand(cmd, cwd, timeout) {
7477   return new Promise((resolve, reject) => {
7478     let timer;
7479     if (timeout) {
7480       timer = setTimeout(() => {
7481         reject(new Error(`timeout after ${timeout}s`));
7482       }, timeout * 1e3);
7483     }
7484     import_child_process.exec(cmd, {cwd}, (err, stdout) => {
7485       if (timer)
7486         clearTimeout(timer);
7487       if (err) {
7488         reject(new Error(`exited with ${err.code}`));
7489         return;
7490       }
7491       resolve(stdout);
7492     });
7493   });
7494 }
7495 async function getManager() {
7496   let res = await import_coc10.workspace.findUp(["yarn.lock", "package-lock.json"]);
7497   if (!res)
7498     return "yarn";
7499   return res.endsWith("yarn.lock") ? "yarn" : "npm";
7500 }
7501 async function moduleExists(name) {
7502   try {
7503     let content = await runCommand(`npm info ${name} --json`, process.cwd());
7504     if (!content)
7505       return false;
7506     let obj = JSON.parse(content);
7507     if (obj.error != null)
7508       return false;
7509     return true;
7510   } catch (e) {
7511     return false;
7512   }
7513   return false;
7514 }
7515 function distinct(array, keyFn) {
7516   if (!keyFn) {
7517     return array.filter((element, position) => {
7518       return array.indexOf(element) === position;
7519     });
7520   }
7521   const seen = Object.create(null);
7522   return array.filter((elem) => {
7523     const key = keyFn(elem);
7524     if (seen[key]) {
7525       return false;
7526     }
7527     seen[key] = true;
7528     return true;
7529   });
7530 }
7531 async function installModules(uri, names) {
7532   names = distinct(names);
7533   let workspaceFolder = import_coc10.workspace.getWorkspaceFolder(uri);
7534   let root = workspaceFolder ? import_coc10.Uri.parse(workspaceFolder.uri).fsPath : void 0;
7535   if (!root || !import_fs.default.existsSync(import_path2.default.join(root, "package.json"))) {
7536     import_coc10.window.showMessage(`package.json not found from workspaceFolder: ${root}`, "error");
7537     return;
7538   }
7539   let arr = names.concat(names.map((s) => `@types/${s}`));
7540   let statusItem = import_coc10.window.createStatusBarItem(99, {progress: true});
7541   statusItem.text = `Checking module ${arr.join(" ")}`;
7542   statusItem.show();
7543   let exists = await Promise.all(arr.map((name) => {
7544     return moduleExists(name).then((exists2) => {
7545       return exists2 ? name : null;
7546     });
7547   }));
7548   let manager = await getManager();
7549   exists = exists.filter((s) => s != null);
7550   if (!exists.length)
7551     return;
7552   let devs = exists.filter((s) => s.startsWith("@types"));
7553   let deps = exists.filter((s) => devs.indexOf(s) == -1);
7554   statusItem.text = `Installing ${exists.join(" ")}`;
7555   try {
7556     let cmd = manager == "npm" ? `npm i ${deps.join(" ")}` : `yarn add ${deps.join(" ")}`;
7557     await runCommand(cmd, root);
7558     cmd = manager == "npm" ? `npm i ${deps.join(" ")} --save-dev` : `yarn add ${deps.join(" ")} --save-dev`;
7559     await runCommand(cmd, root);
7560   } catch (e) {
7561     statusItem.dispose();
7562     import_coc10.window.showMessage(`Install error ${e.message}`, "error");
7563     return;
7564   }
7565   statusItem.dispose();
7566   import_coc10.window.showMessage(`Installed: ${exists.join(" ")}`, "more");
7567 }
7568
7569 // src/server/features/moduleInstall.ts
7570 var InstallModuleProvider = class {
7571   constructor(client) {
7572     this.client = client;
7573     import_coc11.commands.registerCommand("_tsserver.installModule", async (uri, name) => {
7574       await installModules(uri, [name]);
7575     });
7576   }
7577   async provideCodeActions(document, _range, context, _token) {
7578     const uri = import_coc11.Uri.parse(document.uri);
7579     if (uri.scheme != "file")
7580       return null;
7581     let {diagnostics} = context;
7582     let diags = diagnostics.filter((s) => s.code == 2307);
7583     let names = diags.map((o) => {
7584       let ms = o.message.match(/module\s'(.+)'/);
7585       return ms ? ms[1] : null;
7586     });
7587     names = names.filter((s) => s != null);
7588     if (!names.length)
7589       return null;
7590     let actions = [];
7591     for (let name of names) {
7592       let title = `install ${name}`;
7593       let command = {
7594         title: `install ${name}`,
7595         command: "_tsserver.installModule",
7596         arguments: [document.uri, name]
7597       };
7598       let codeAction = import_vscode_languageserver_protocol13.CodeAction.create(title, command, import_vscode_languageserver_protocol13.CodeActionKind.QuickFix);
7599       actions.push(codeAction);
7600     }
7601     return actions;
7602   }
7603 };
7604 var moduleInstall_default = InstallModuleProvider;
7605
7606 // src/server/features/quickfix.ts
7607 var import_coc13 = __toModule(require("coc.nvim"));
7608 var import_vscode_languageserver_protocol14 = __toModule(require_main3());
7609
7610 // src/server/commands.ts
7611 var import_coc12 = __toModule(require("coc.nvim"));
7612 var import_vscode_languageserver_types2 = __toModule(require_main2());
7613 var ReloadProjectsCommand = class {
7614   constructor(service) {
7615     this.service = service;
7616     this.id = "tsserver.reloadProjects";
7617   }
7618   async execute() {
7619     let client = await this.service.getClientHost();
7620     client.reloadProjects();
7621     import_coc12.window.showMessage("projects reloaded");
7622   }
7623 };
7624 var OpenTsServerLogCommand = class {
7625   constructor(service) {
7626     this.service = service;
7627     this.id = "tsserver.openTsServerLog";
7628   }
7629   async execute() {
7630     let client = await this.service.getClientHost();
7631     client.serviceClient.openTsServerLogFile();
7632   }
7633 };
7634 var TypeScriptGoToProjectConfigCommand = class {
7635   constructor(service) {
7636     this.service = service;
7637     this.id = "tsserver.goToProjectConfig";
7638   }
7639   async execute() {
7640     let client = await this.service.getClientHost();
7641     let doc = await import_coc12.workspace.document;
7642     let {languageId} = doc.textDocument;
7643     if (client.serviceClient.modeIds.indexOf(languageId) == -1) {
7644       throw new Error(`Could not determine TypeScript or JavaScript project. Unsupported file type: ${languageId}`);
7645       return;
7646     }
7647     await goToProjectConfig(client, doc.uri);
7648   }
7649 };
7650 async function goToProjectConfig(clientHost, uri) {
7651   const client = clientHost.serviceClient;
7652   const file2 = client.toPath(uri);
7653   let res;
7654   try {
7655     res = await client.execute("projectInfo", {file: file2, needFileNameList: false}, import_coc12.CancellationToken.None);
7656   } catch {
7657   }
7658   if (!res || !res.body) {
7659     import_coc12.window.showMessage("Could not determine TypeScript or JavaScript project.", "warning");
7660     return;
7661   }
7662   const {configFileName} = res.body;
7663   if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
7664     await import_coc12.workspace.openResource(import_coc12.Uri.file(configFileName).toString());
7665     return;
7666   }
7667   import_coc12.window.showMessage("Config file not found", "warning");
7668 }
7669 function isImplicitProjectConfigFile(configFileName) {
7670   return configFileName.indexOf("/dev/null/") === 0;
7671 }
7672 var autoFixableDiagnosticCodes = new Set([
7673   2420,
7674   2552,
7675   2304
7676 ]);
7677 var AutoFixCommand = class {
7678   constructor(service) {
7679     this.service = service;
7680     this.id = "tsserver.executeAutofix";
7681   }
7682   async execute() {
7683     if (this.service.state != import_coc12.ServiceStat.Running) {
7684       throw new Error("service not running");
7685       return;
7686     }
7687     let client = await this.service.getClientHost();
7688     let document = await import_coc12.workspace.document;
7689     let handles = await client.handles(document.textDocument);
7690     if (!handles) {
7691       throw new Error(`Document ${document.uri} is not handled by tsserver.`);
7692       return;
7693     }
7694     let file2 = client.serviceClient.toPath(document.uri);
7695     let diagnostics = import_coc12.diagnosticManager.getDiagnostics(document.uri).slice();
7696     let missingDiagnostics = diagnostics.filter((o) => o.code == 2307);
7697     if (missingDiagnostics.length) {
7698       let names2 = missingDiagnostics.map((o) => {
7699         let ms = o.message.match(/module\s'(.+)'\./);
7700         return ms ? ms[1] : null;
7701       });
7702       names2 = names2.filter((s) => s != null);
7703       if (names2.length) {
7704         installModules(document.uri, names2).catch((e) => {
7705           console.error(e.message);
7706         });
7707       }
7708     }
7709     diagnostics = diagnostics.filter((x) => autoFixableDiagnosticCodes.has(x.code));
7710     if (diagnostics.length == 0)
7711       return;
7712     diagnostics = diagnostics.reduce((arr, curr) => {
7713       if (curr.code == 2304 && arr.findIndex((o) => o.message == curr.message) != -1)
7714         return arr;
7715       arr.push(curr);
7716       return arr;
7717     }, []);
7718     let edits = [];
7719     let command;
7720     let names = [];
7721     for (let diagnostic of diagnostics) {
7722       const args = {
7723         ...Range.toFileRangeRequestArgs(file2, diagnostic.range),
7724         errorCodes: [+diagnostic.code]
7725       };
7726       const response = await client.serviceClient.execute("getCodeFixes", args, import_coc12.CancellationToken.None);
7727       if (response.type !== "response" || !response.body || response.body.length < 1) {
7728         if (diagnostic.code == 2304) {
7729           let {range} = diagnostic;
7730           let line = document.getline(range.start.line);
7731           let name = line.slice(range.start.character, range.end.character);
7732           if (nodeModules.indexOf(name) !== -1 && names.indexOf(name) == -1) {
7733             names.push(name);
7734             edits.push({
7735               range: import_vscode_languageserver_types2.Range.create(0, 0, 0, 0),
7736               newText: `import ${name} from '${name}'
7737 `
7738             });
7739             command = "tsserver.organizeImports";
7740           }
7741         }
7742         continue;
7743       }
7744       const fix = response.body[0];
7745       for (let change of fix.changes) {
7746         if (change.fileName != file2)
7747           continue;
7748         for (let ch of change.textChanges) {
7749           edits.push({
7750             range: Range.fromTextSpan(ch),
7751             newText: ch.newText
7752           });
7753         }
7754       }
7755     }
7756     if (edits.length)
7757       await document.applyEdits(edits);
7758     if (command)
7759       import_coc12.commands.executeCommand(command);
7760   }
7761 };
7762 var ConfigurePluginCommand = class {
7763   constructor(pluginManager) {
7764     this.pluginManager = pluginManager;
7765     this.id = "_typescript.configurePlugin";
7766   }
7767   execute(pluginId, configuration) {
7768     this.pluginManager.setConfiguration(pluginId, configuration);
7769   }
7770 };
7771 function registCommand(cmd) {
7772   let {id, execute} = cmd;
7773   return import_coc12.commands.registerCommand(id, execute, cmd);
7774 }
7775
7776 // src/server/features/quickfix.ts
7777 var ApplyCodeActionCommand2 = class {
7778   constructor(client, formattingConfigurationManager) {
7779     this.client = client;
7780     this.formattingConfigurationManager = formattingConfigurationManager;
7781     this.id = ApplyCodeActionCommand2.ID;
7782   }
7783   async execute(action) {
7784     return applyCodeActionCommands(this.client, action);
7785   }
7786 };
7787 var ApplyCodeActionCommand = ApplyCodeActionCommand2;
7788 ApplyCodeActionCommand.ID = "_typescript.applyCodeActionCommand";
7789 var ApplyFixAllCodeAction2 = class {
7790   constructor(client, formattingConfigurationManager) {
7791     this.client = client;
7792     this.formattingConfigurationManager = formattingConfigurationManager;
7793     this.id = ApplyFixAllCodeAction2.ID;
7794   }
7795   async execute(document, file2, tsAction) {
7796     if (!tsAction.fixId) {
7797       return;
7798     }
7799     await this.formattingConfigurationManager.ensureConfigurationForDocument(document, import_vscode_languageserver_protocol14.CancellationToken.None);
7800     const args = {
7801       scope: {
7802         type: "file",
7803         args: {file: file2}
7804       },
7805       fixId: tsAction.fixId
7806     };
7807     try {
7808       const res = await this.client.execute("getCombinedCodeFix", args, import_vscode_languageserver_protocol14.CancellationToken.None);
7809       if (res.type != "response") {
7810         return;
7811       }
7812       let {body} = res;
7813       const edit = WorkspaceEdit.fromFileCodeEdits(this.client, body.changes);
7814       await import_coc13.workspace.applyEdit(edit);
7815       const token = import_vscode_languageserver_protocol14.CancellationToken.None;
7816       const {commands: commands7} = body;
7817       if (commands7 && commands7.length) {
7818         for (const command of commands7) {
7819           await this.client.execute("applyCodeActionCommand", {command}, token);
7820         }
7821       }
7822     } catch {
7823     }
7824   }
7825 };
7826 var ApplyFixAllCodeAction = ApplyFixAllCodeAction2;
7827 ApplyFixAllCodeAction.ID = "_typescript.applyFixAllCodeAction";
7828 var DiagnosticsSet = class {
7829   constructor(_values) {
7830     this._values = _values;
7831   }
7832   static from(diagnostics) {
7833     const values = new Map();
7834     for (const diagnostic of diagnostics) {
7835       values.set(DiagnosticsSet.key(diagnostic), diagnostic);
7836     }
7837     return new DiagnosticsSet(values);
7838   }
7839   static key(diagnostic) {
7840     const {start, end} = diagnostic.range;
7841     return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
7842   }
7843   get values() {
7844     return this._values.values();
7845   }
7846 };
7847 var SupportedCodeActionProvider = class {
7848   constructor(client) {
7849     this.client = client;
7850   }
7851   async getFixableDiagnosticsForContext(context) {
7852     const supportedActions = await this.supportedCodeActions;
7853     const fixableDiagnostics = DiagnosticsSet.from(context.diagnostics.filter((diagnostic) => supportedActions.has(+diagnostic.code)));
7854     return Array.from(fixableDiagnostics.values);
7855   }
7856   get supportedCodeActions() {
7857     if (!this._supportedCodeActions) {
7858       return new Promise((resolve, reject) => {
7859         this.client.execute("getSupportedCodeFixes", null, import_vscode_languageserver_protocol14.CancellationToken.None).then((res) => {
7860           if (res.type !== "response") {
7861             resolve(new Set());
7862             return;
7863           }
7864           let codes = res.body.map((code) => +code).filter((code) => !isNaN(code));
7865           resolve(new Set(codes));
7866         }, reject);
7867       });
7868     }
7869     return Promise.resolve(this._supportedCodeActions);
7870   }
7871 };
7872 var TypeScriptQuickFixProvider = class {
7873   constructor(client, formattingConfigurationManager) {
7874     this.client = client;
7875     this.formattingConfigurationManager = formattingConfigurationManager;
7876     registCommand(new ApplyCodeActionCommand(client, formattingConfigurationManager));
7877     registCommand(new ApplyFixAllCodeAction(client, formattingConfigurationManager));
7878     this.supportedCodeActionProvider = new SupportedCodeActionProvider(client);
7879   }
7880   async provideCodeActions(document, _range, context, token) {
7881     const file2 = this.client.toPath(document.uri);
7882     if (!file2) {
7883       return [];
7884     }
7885     await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
7886     const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
7887     if (!fixableDiagnostics.length) {
7888       return [];
7889     }
7890     if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
7891       return [];
7892     }
7893     const results = [];
7894     for (const diagnostic of fixableDiagnostics) {
7895       results.push(...await this.getFixesForDiagnostic(document, file2, diagnostic, token));
7896     }
7897     return results;
7898   }
7899   async getFixesForDiagnostic(document, file2, diagnostic, token) {
7900     const args = {
7901       ...Range.toFileRangeRequestArgs(file2, diagnostic.range),
7902       errorCodes: [+diagnostic.code]
7903     };
7904     const codeFixesResponse = await this.client.execute("getCodeFixes", args, token);
7905     if (codeFixesResponse.type != "response") {
7906       return [];
7907     }
7908     if (codeFixesResponse.body) {
7909       const results = [];
7910       for (const tsCodeFix of codeFixesResponse.body) {
7911         results.push(...await this.getAllFixesForTsCodeAction(document, file2, diagnostic, tsCodeFix));
7912       }
7913       return results;
7914     }
7915     return [];
7916   }
7917   async getAllFixesForTsCodeAction(document, file2, diagnostic, tsAction) {
7918     const singleFix = this.getSingleFixForTsCodeAction(diagnostic, tsAction);
7919     const fixAll = await this.getFixAllForTsCodeAction(document, file2, diagnostic, tsAction);
7920     return fixAll ? [singleFix, fixAll] : [singleFix];
7921   }
7922   getSingleFixForTsCodeAction(diagnostic, tsAction) {
7923     const codeAction = {
7924       title: tsAction.description,
7925       kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
7926     };
7927     codeAction.edit = getEditForCodeAction(this.client, tsAction);
7928     codeAction.diagnostics = [diagnostic];
7929     codeAction.isPreferred = true;
7930     if (tsAction.commands) {
7931       codeAction.command = {
7932         command: ApplyCodeActionCommand.ID,
7933         arguments: [tsAction],
7934         title: tsAction.description
7935       };
7936     }
7937     return codeAction;
7938   }
7939   async getFixAllForTsCodeAction(document, file2, diagnostic, tsAction) {
7940     if (!tsAction.fixId || !this.client.apiVersion.gte(api_default.v270)) {
7941       return void 0;
7942     }
7943     if (!this.client.diagnosticsManager.getDiagnostics(document.uri).some((x) => x.code === diagnostic.code && x !== diagnostic)) {
7944       return;
7945     }
7946     const action = {
7947       title: tsAction.fixAllDescription || "Fix all in file",
7948       kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
7949     };
7950     action.diagnostics = [diagnostic];
7951     action.command = {
7952       command: ApplyFixAllCodeAction.ID,
7953       arguments: [document, file2, tsAction],
7954       title: ""
7955     };
7956     return action;
7957   }
7958 };
7959 var quickfix_default = TypeScriptQuickFixProvider;
7960
7961 // src/server/features/refactor.ts
7962 var import_coc14 = __toModule(require("coc.nvim"));
7963 var import_vscode_languageserver_protocol15 = __toModule(require_main3());
7964 var ApplyRefactoringCommand2 = class {
7965   constructor(client) {
7966     this.client = client;
7967     this.id = ApplyRefactoringCommand2.ID;
7968   }
7969   async execute(document, file2, refactor, action, range) {
7970     const args = {
7971       ...Range.toFileRangeRequestArgs(file2, range),
7972       refactor,
7973       action
7974     };
7975     const response = await this.client.execute("getEditsForRefactor", args, import_vscode_languageserver_protocol15.CancellationToken.None);
7976     const body = response && response.body;
7977     if (!body || !body.edits.length) {
7978       return false;
7979     }
7980     const workspaceEdit = await this.toWorkspaceEdit(body);
7981     if (!await import_coc14.workspace.applyEdit(workspaceEdit)) {
7982       return false;
7983     }
7984     const renameLocation = body.renameLocation;
7985     if (renameLocation) {
7986       import_coc14.commands.executeCommand("editor.action.rename", document.uri, Position.fromLocation(renameLocation));
7987     }
7988     return true;
7989   }
7990   async toWorkspaceEdit(body) {
7991     for (const edit of body.edits) {
7992       await import_coc14.workspace.createFile(edit.fileName, {ignoreIfExists: true});
7993     }
7994     let workspaceEdit = WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
7995     return workspaceEdit;
7996   }
7997 };
7998 var ApplyRefactoringCommand = ApplyRefactoringCommand2;
7999 ApplyRefactoringCommand.ID = "_typescript.applyRefactoring";
8000 var SelectRefactorCommand2 = class {
8001   constructor(doRefactoring) {
8002     this.doRefactoring = doRefactoring;
8003     this.id = SelectRefactorCommand2.ID;
8004   }
8005   async execute(document, file2, info, range) {
8006     let {actions} = info;
8007     const idx = actions.length == 1 ? 0 : await import_coc14.window.showQuickpick(actions.map((action) => action.description || action.name));
8008     if (idx == -1)
8009       return false;
8010     let label = info.actions[idx].name;
8011     if (!label)
8012       return false;
8013     return this.doRefactoring.execute(document, file2, info.name, label, range);
8014   }
8015 };
8016 var SelectRefactorCommand = SelectRefactorCommand2;
8017 SelectRefactorCommand.ID = "_typescript.selectRefactoring";
8018 var TypeScriptRefactorProvider2 = class {
8019   constructor(client, formattingOptionsManager) {
8020     this.client = client;
8021     this.formattingOptionsManager = formattingOptionsManager;
8022     const doRefactoringCommand = new ApplyRefactoringCommand(this.client);
8023     registCommand(doRefactoringCommand);
8024     registCommand(new SelectRefactorCommand(doRefactoringCommand));
8025   }
8026   async provideCodeActions(document, range, context, token) {
8027     if (!this.shouldTrigger(context)) {
8028       return void 0;
8029     }
8030     const file2 = this.client.toPath(document.uri);
8031     if (!file2)
8032       return void 0;
8033     await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
8034     const args = Range.toFileRangeRequestArgs(file2, range);
8035     let response;
8036     try {
8037       response = await this.client.interruptGetErr(() => {
8038         return this.client.execute("getApplicableRefactors", args, token);
8039       });
8040       if (!response || !response.body) {
8041         return void 0;
8042       }
8043     } catch {
8044       return void 0;
8045     }
8046     return this.convertApplicableRefactors(response.body, document, file2, range, context.only && context.only.some((v) => v.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor)));
8047   }
8048   convertApplicableRefactors(body, document, file2, rangeOrSelection, setPrefrred) {
8049     const actions = [];
8050     for (const info of body) {
8051       if (info.notApplicableReason)
8052         continue;
8053       if (!info.inlineable) {
8054         const codeAction = {
8055           title: info.description,
8056           kind: import_vscode_languageserver_protocol15.CodeActionKind.Refactor
8057         };
8058         codeAction.command = {
8059           title: info.description,
8060           command: SelectRefactorCommand.ID,
8061           arguments: [document, file2, info, rangeOrSelection]
8062         };
8063         actions.push(codeAction);
8064       } else {
8065         for (const action of info.actions) {
8066           let codeAction = this.refactorActionToCodeAction(action, document, file2, info, rangeOrSelection);
8067           if (setPrefrred) {
8068             codeAction.isPreferred = TypeScriptRefactorProvider2.isPreferred(action, info.actions);
8069           }
8070           actions.push(codeAction);
8071         }
8072       }
8073     }
8074     return actions;
8075   }
8076   refactorActionToCodeAction(action, document, file2, info, rangeOrSelection) {
8077     const codeAction = {
8078       title: action.description,
8079       kind: TypeScriptRefactorProvider2.getKind(action)
8080     };
8081     codeAction.command = {
8082       title: action.description,
8083       command: ApplyRefactoringCommand.ID,
8084       arguments: [document, file2, info.name, action.name, rangeOrSelection]
8085     };
8086     return codeAction;
8087   }
8088   shouldTrigger(context) {
8089     if (context.only && context.only.every((o) => !o.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor))) {
8090       return false;
8091     }
8092     return true;
8093   }
8094   static getKind(refactor) {
8095     if (refactor.name.startsWith("function_")) {
8096       return TypeScriptRefactorProvider2.extractFunctionKind;
8097     } else if (refactor.name.startsWith("constant_")) {
8098       return TypeScriptRefactorProvider2.extractConstantKind;
8099     } else if (refactor.name.startsWith("Move")) {
8100       return TypeScriptRefactorProvider2.moveKind;
8101     }
8102     return import_vscode_languageserver_protocol15.CodeActionKind.Refactor;
8103   }
8104   static isPreferred(action, allActions) {
8105     let kind = TypeScriptRefactorProvider2.getKind(action);
8106     if (TypeScriptRefactorProvider2.extractConstantKind == kind) {
8107       const getScope = (name2) => {
8108         var _a;
8109         const scope2 = (_a = name2.match(/scope_(\d)/)) == null ? void 0 : _a[1];
8110         return scope2 ? +scope2 : void 0;
8111       };
8112       const scope = getScope(action.name);
8113       if (typeof scope !== "number") {
8114         return false;
8115       }
8116       return allActions.filter((otherAtion) => otherAtion !== action && otherAtion.name.startsWith("constant_")).every((otherAction) => {
8117         const otherScope = getScope(otherAction.name);
8118         return typeof otherScope === "number" ? scope < otherScope : true;
8119       });
8120     }
8121     let {name} = action;
8122     if (name.startsWith("Extract to type alias") || name.startsWith("Extract to interface")) {
8123       return true;
8124     }
8125     return false;
8126   }
8127 };
8128 var TypeScriptRefactorProvider = TypeScriptRefactorProvider2;
8129 TypeScriptRefactorProvider.extractFunctionKind = import_vscode_languageserver_protocol15.CodeActionKind.RefactorExtract + ".function";
8130 TypeScriptRefactorProvider.extractConstantKind = import_vscode_languageserver_protocol15.CodeActionKind.RefactorExtract + ".constant";
8131 TypeScriptRefactorProvider.moveKind = import_vscode_languageserver_protocol15.CodeActionKind.Refactor + ".move";
8132 TypeScriptRefactorProvider.metadata = {
8133   providedCodeActionKinds: [import_vscode_languageserver_protocol15.CodeActionKind.Refactor]
8134 };
8135 var refactor_default = TypeScriptRefactorProvider;
8136
8137 // src/server/features/references.ts
8138 var TypeScriptReferences = class {
8139   constructor(client) {
8140     this.client = client;
8141   }
8142   async provideReferences(document, position, context, token) {
8143     const filepath = this.client.toPath(document.uri);
8144     if (!filepath)
8145       return [];
8146     const args = Position.toFileLocationRequestArgs(filepath, position);
8147     try {
8148       const msg = await this.client.execute("references", args, token);
8149       if (!msg || msg.type != "response" || !msg.body) {
8150         return [];
8151       }
8152       const result = [];
8153       for (const ref of msg.body.refs) {
8154         if (!context.includeDeclaration && ref.isDefinition) {
8155           continue;
8156         }
8157         const url = this.client.toResource(ref.file);
8158         const location = Location2.fromTextSpan(url, ref);
8159         result.push(location);
8160       }
8161       return result;
8162     } catch {
8163       return [];
8164     }
8165   }
8166 };
8167 var references_default = TypeScriptReferences;
8168
8169 // src/server/features/referencesCodeLens.ts
8170 var TypeScriptReferencesCodeLensProvider = class extends TypeScriptBaseCodeLensProvider {
8171   resolveCodeLens(codeLens, token) {
8172     let {uri} = codeLens.data;
8173     let filepath = this.client.toPath(uri);
8174     const args = Position.toFileLocationRequestArgs(filepath, codeLens.range.start);
8175     return this.client.execute("references", args, token, {
8176       lowPriority: true
8177     }).then((response) => {
8178       if (!response || response.type != "response" || !response.body) {
8179         throw codeLens;
8180       }
8181       const locations = response.body.refs.map((reference) => Location2.fromTextSpan(this.client.toResource(reference.file), reference)).filter((location) => !(location.uri.toString() === uri && location.range.start.line === codeLens.range.start.line && location.range.start.character === codeLens.range.start.character));
8182       codeLens.command = {
8183         title: locations.length === 1 ? "1 reference" : `${locations.length} references`,
8184         command: locations.length ? "editor.action.showReferences" : "",
8185         arguments: [uri, codeLens.range.start, locations]
8186       };
8187       return codeLens;
8188     }).catch(() => {
8189       codeLens.command = {
8190         title: "0 references",
8191         command: ""
8192       };
8193       return codeLens;
8194     });
8195   }
8196   extractSymbol(document, item, parent) {
8197     if (parent && parent.kind === Kind.enum) {
8198       return super.getSymbolRange(document, item);
8199     }
8200     switch (item.kind) {
8201       case Kind.const:
8202       case Kind.let:
8203       case Kind.variable:
8204       case Kind.function:
8205         if (!item.kindModifiers.match(/\bexport\b/)) {
8206           break;
8207         }
8208       case Kind.class:
8209         if (item.text === "<class>") {
8210           break;
8211         }
8212       case Kind.method:
8213       case Kind.memberVariable:
8214       case Kind.memberGetAccessor:
8215       case Kind.memberSetAccessor:
8216       case Kind.constructorImplementation:
8217       case Kind.interface:
8218       case Kind.type:
8219       case Kind.enum:
8220         return super.getSymbolRange(document, item);
8221     }
8222     return null;
8223   }
8224 };
8225 var referencesCodeLens_default = TypeScriptReferencesCodeLensProvider;
8226
8227 // src/server/features/rename.ts
8228 var import_coc15 = __toModule(require("coc.nvim"));
8229 var import_path3 = __toModule(require("path"));
8230 var TypeScriptRenameProvider = class {
8231   constructor(client, fileConfigurationManager) {
8232     this.client = client;
8233     this.fileConfigurationManager = fileConfigurationManager;
8234   }
8235   async prepareRename(document, position, token) {
8236     const response = await this.execRename(document, position, token);
8237     if (!response || response.type !== "response" || !response.body) {
8238       return null;
8239     }
8240     const renameInfo = response.body.info;
8241     if (!renameInfo.canRename) {
8242       return Promise.reject(new Error("Invalid location for rename."));
8243     }
8244     if (this.client.apiVersion.gte(api_default.v310)) {
8245       const triggerSpan = renameInfo.triggerSpan;
8246       if (triggerSpan) {
8247         const range = Range.fromTextSpan(triggerSpan);
8248         return range;
8249       }
8250     }
8251     return null;
8252   }
8253   async provideRenameEdits(document, position, newName, token) {
8254     const response = await this.execRename(document, position, token);
8255     if (!response || response.type !== "response" || !response.body) {
8256       return null;
8257     }
8258     const renameInfo = response.body.info;
8259     if (!renameInfo.canRename) {
8260       return Promise.reject(new Error("Invalid location for rename."));
8261     }
8262     if (this.client.apiVersion.gte(api_default.v310)) {
8263       if (renameInfo.fileToRename) {
8264         const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
8265         if (edits) {
8266           return edits;
8267         } else {
8268           return Promise.reject(new Error("An error occurred while renaming file"));
8269         }
8270       }
8271     }
8272     return this.toWorkspaceEdit(response.body.locs, newName);
8273   }
8274   async execRename(document, position, token) {
8275     const file2 = this.client.toPath(document.uri);
8276     if (!file2)
8277       return void 0;
8278     const args = {
8279       ...Position.toFileLocationRequestArgs(file2, position),
8280       findInStrings: false,
8281       findInComments: false
8282     };
8283     await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
8284     return this.client.interruptGetErr(() => {
8285       return this.client.execute("rename", args, token);
8286     });
8287   }
8288   toWorkspaceEdit(locations, newName) {
8289     let changes = {};
8290     for (const spanGroup of locations) {
8291       const uri = this.client.toResource(spanGroup.file);
8292       if (uri) {
8293         changes[uri] = [];
8294         for (const textSpan of spanGroup.locs) {
8295           changes[uri].push({
8296             range: Range.fromTextSpan(textSpan),
8297             newText: (textSpan.prefixText || "") + newName + (textSpan.suffixText || "")
8298           });
8299         }
8300       }
8301     }
8302     return {changes};
8303   }
8304   async renameFile(fileToRename, newName, token) {
8305     if (!import_path3.default.extname(newName)) {
8306       newName += import_path3.default.extname(fileToRename);
8307     }
8308     const dirname = import_path3.default.dirname(fileToRename);
8309     const newFilePath = import_path3.default.join(dirname, newName);
8310     const args = {
8311       file: fileToRename,
8312       oldFilePath: fileToRename,
8313       newFilePath
8314     };
8315     const response = await this.client.execute("getEditsForFileRename", args, token);
8316     if (response.type !== "response" || !response.body) {
8317       return void 0;
8318     }
8319     const edits = WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
8320     edits.documentChanges = edits.documentChanges || [];
8321     edits.documentChanges.push({
8322       kind: "rename",
8323       oldUri: import_coc15.Uri.file(fileToRename).toString(),
8324       newUri: import_coc15.Uri.file(newFilePath).toString(),
8325       options: {
8326         overwrite: false,
8327         ignoreIfExists: true
8328       }
8329     });
8330     return edits;
8331   }
8332 };
8333 var rename_default = TypeScriptRenameProvider;
8334
8335 // src/server/features/signatureHelp.ts
8336 var TypeScriptSignatureHelpProvider = class {
8337   constructor(client) {
8338     this.client = client;
8339   }
8340   async provideSignatureHelp(document, position, token) {
8341     const filepath = this.client.toPath(document.uri);
8342     if (!filepath) {
8343       return void 0;
8344     }
8345     const args = Position.toFileLocationRequestArgs(filepath, position);
8346     let response;
8347     try {
8348       response = await this.client.interruptGetErr(() => this.client.execute("signatureHelp", args, token));
8349     } catch (e) {
8350       return void 0;
8351     }
8352     if (response.type !== "response" || !response.body) {
8353       return void 0;
8354     }
8355     let info = response.body;
8356     const result = {
8357       activeSignature: info.selectedItemIndex,
8358       activeParameter: this.getActiveParmeter(info),
8359       signatures: info.items.map((signature) => {
8360         return this.convertSignature(signature);
8361       })
8362     };
8363     return result;
8364   }
8365   getActiveParmeter(info) {
8366     const activeSignature = info.items[info.selectedItemIndex];
8367     if (activeSignature && activeSignature.isVariadic) {
8368       return Math.min(info.argumentIndex, activeSignature.parameters.length - 1);
8369     }
8370     return info.argumentIndex;
8371   }
8372   convertSignature(item) {
8373     var _a;
8374     let parameters = item.parameters.map((p) => {
8375       return {
8376         label: plain(p.displayParts),
8377         documentation: markdownDocumentation(p.documentation, [])
8378       };
8379     });
8380     let label = plain(item.prefixDisplayParts);
8381     label += parameters.map((parameter) => parameter.label).join(plain(item.separatorDisplayParts));
8382     label += plain(item.suffixDisplayParts);
8383     return {
8384       label,
8385       documentation: markdownDocumentation(item.documentation, (_a = item.tags) == null ? void 0 : _a.filter((x) => x.name !== "param")),
8386       parameters
8387     };
8388   }
8389 };
8390 TypeScriptSignatureHelpProvider.triggerCharacters = ["(", ",", "<"];
8391 var signatureHelp_default = TypeScriptSignatureHelpProvider;
8392
8393 // src/server/features/smartSelect.ts
8394 var SmartSelection = class {
8395   constructor(client) {
8396     this.client = client;
8397   }
8398   async provideSelectionRanges(document, positions, token) {
8399     const file2 = this.client.toPath(document.uri);
8400     if (!file2) {
8401       return void 0;
8402     }
8403     const args = {
8404       file: file2,
8405       locations: positions.map(Position.toLocation)
8406     };
8407     const response = await this.client.execute("selectionRange", args, token);
8408     if (response.type !== "response" || !response.body) {
8409       return void 0;
8410     }
8411     return response.body.map(SmartSelection.convertSelectionRange);
8412   }
8413   static convertSelectionRange(selectionRange) {
8414     return {
8415       range: Range.fromTextSpan(selectionRange.textSpan),
8416       parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : void 0
8417     };
8418   }
8419 };
8420 var smartSelect_default = SmartSelection;
8421
8422 // src/server/features/updatePathOnRename.ts
8423 var import_coc16 = __toModule(require("coc.nvim"));
8424 var import_vscode_languageserver_protocol16 = __toModule(require_main3());
8425
8426 // src/server/utils/mutex.ts
8427 var Mutex = class {
8428   constructor() {
8429     this.tasks = [];
8430     this.count = 1;
8431   }
8432   sched() {
8433     if (this.count > 0 && this.tasks.length > 0) {
8434       this.count--;
8435       let next = this.tasks.shift();
8436       next();
8437     }
8438   }
8439   get busy() {
8440     return this.count == 0;
8441   }
8442   acquire() {
8443     return new Promise((res) => {
8444       let task = () => {
8445         let released = false;
8446         res(() => {
8447           if (!released) {
8448             released = true;
8449             this.count++;
8450             this.sched();
8451           }
8452         });
8453       };
8454       this.tasks.push(task);
8455       process.nextTick(this.sched.bind(this));
8456     });
8457   }
8458   use(f) {
8459     return this.acquire().then((release) => {
8460       return f().then((res) => {
8461         release();
8462         return res;
8463       }).catch((err) => {
8464         release();
8465         throw err;
8466       });
8467     });
8468   }
8469 };
8470
8471 // src/server/features/updatePathOnRename.ts
8472 function wait(ms) {
8473   return new Promise((resolve) => {
8474     setTimeout(() => {
8475       resolve();
8476     }, ms);
8477   });
8478 }
8479 var UpdateImportsOnFileRenameHandler = class {
8480   constructor(client, fileConfigurationManager, languageId) {
8481     this.client = client;
8482     this.fileConfigurationManager = fileConfigurationManager;
8483     this.disposables = [];
8484     let glob = languageId == "typescript" ? "**/*.{ts,tsx}" : "**/*.{js,jsx}";
8485     const watcher = import_coc16.workspace.createFileSystemWatcher(glob);
8486     this.disposables.push(watcher);
8487     let mutex = new Mutex();
8488     watcher.onDidRename(async (e) => {
8489       let release = await mutex.acquire();
8490       try {
8491         await this.doRename(e.oldUri, e.newUri);
8492         release();
8493       } catch (e2) {
8494         this.client.logger.error("Error on rename:", e2);
8495         release();
8496       }
8497     }, null, this.disposables);
8498   }
8499   dispose() {
8500     import_coc16.disposeAll(this.disposables);
8501   }
8502   async doRename(oldResource, newResource) {
8503     if (oldResource.scheme !== "file" || newResource.scheme !== "file") {
8504       return;
8505     }
8506     const targetFile = newResource.fsPath;
8507     const oldFile = oldResource.fsPath;
8508     const newUri = newResource.toString();
8509     let oldDocument = import_coc16.workspace.getDocument(oldResource.toString());
8510     if (oldDocument) {
8511       await import_coc16.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
8512     }
8513     let document = import_coc16.workspace.getDocument(newUri);
8514     if (document) {
8515       await import_coc16.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
8516       await wait(30);
8517     }
8518     document = await import_coc16.workspace.loadFile(newUri);
8519     if (!document)
8520       return;
8521     await wait(50);
8522     const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
8523     if (!edits)
8524       return;
8525     if (await this.promptUser(newResource)) {
8526       await import_coc16.workspace.applyEdit(edits);
8527     }
8528   }
8529   async promptUser(newResource) {
8530     return await import_coc16.window.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
8531   }
8532   async getEditsForFileRename(document, oldFile, newFile) {
8533     await this.fileConfigurationManager.ensureConfigurationForDocument(document, import_vscode_languageserver_protocol16.CancellationToken.None);
8534     const response = await this.client.interruptGetErr(() => {
8535       const args = {
8536         oldFilePath: oldFile,
8537         newFilePath: newFile
8538       };
8539       return this.client.execute("getEditsForFileRename", args, import_vscode_languageserver_protocol16.CancellationToken.None);
8540     });
8541     if (!response || response.type != "response" || !response.body) {
8542       return;
8543     }
8544     const edits = [];
8545     for (const edit of response.body) {
8546       if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
8547         continue;
8548       }
8549       for (const change of edit.textChanges) {
8550         if (change.newText.match(/\/node_modules\//gi)) {
8551           continue;
8552         }
8553       }
8554       edits.push(edit);
8555     }
8556     return WorkspaceEdit.fromFileCodeEdits(this.client, edits);
8557   }
8558 };
8559 var updatePathOnRename_default = UpdateImportsOnFileRenameHandler;
8560
8561 // src/server/organizeImports.ts
8562 var import_coc17 = __toModule(require("coc.nvim"));
8563 var import_vscode_languageserver_protocol17 = __toModule(require_main3());
8564 var OrganizeImportsCommand = class {
8565   constructor(service) {
8566     this.service = service;
8567     this.id = "tsserver.organizeImports";
8568   }
8569   async _execute(client, document) {
8570     let file2 = client.toPath(document.uri);
8571     const args = {
8572       scope: {
8573         type: "file",
8574         args: {
8575           file: file2
8576         }
8577       }
8578     };
8579     const response = await client.interruptGetErr(() => client.execute("organizeImports", args, import_vscode_languageserver_protocol17.CancellationToken.None));
8580     if (!response || response.type != "response" || !response.success) {
8581       return;
8582     }
8583     const edit = WorkspaceEdit.fromFileCodeEdits(client, response.body);
8584     let keys = Object.keys(edit.changes);
8585     if (keys.length == 1) {
8586       let doc = import_coc17.workspace.getDocument(keys[0]);
8587       if (doc) {
8588         await doc.applyEdits(edit.changes[keys[0]]);
8589         return;
8590       }
8591     }
8592     if (edit)
8593       await import_coc17.workspace.applyEdit(edit);
8594   }
8595   async execute(document) {
8596     let client = await this.service.getClientHost();
8597     if (!document) {
8598       let doc = await import_coc17.workspace.document;
8599       if (!doc.attached) {
8600         throw new Error(`Document not attached.`);
8601       }
8602       if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
8603         throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
8604       }
8605       document = doc.textDocument;
8606     }
8607     await this._execute(client.serviceClient, document);
8608   }
8609 };
8610 var OrganizeImportsCodeActionProvider = class {
8611   constructor(client, fileConfigManager) {
8612     this.client = client;
8613     this.fileConfigManager = fileConfigManager;
8614     this.metadata = {
8615       providedCodeActionKinds: [import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports]
8616     };
8617   }
8618   async provideCodeActions(document, _range, context, token) {
8619     if (this.client.modeIds.indexOf(document.languageId) == -1)
8620       return;
8621     if (!context.only || !context.only.includes(import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports)) {
8622       return [];
8623     }
8624     await this.fileConfigManager.ensureConfigurationForDocument(document, token);
8625     const action = import_vscode_languageserver_protocol17.CodeAction.create("Organize Imports", {
8626       title: "",
8627       command: "tsserver.organizeImports",
8628       arguments: [document]
8629     }, import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports);
8630     return [action];
8631   }
8632 };
8633
8634 // src/server/languageProvider.ts
8635 var suggestionSetting = "suggestionActions.enabled";
8636 var LanguageProvider = class {
8637   constructor(client, fileConfigurationManager, description, typingsStatus) {
8638     this.client = client;
8639     this.fileConfigurationManager = fileConfigurationManager;
8640     this.description = description;
8641     this.typingsStatus = typingsStatus;
8642     this.disposables = [];
8643     import_coc18.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
8644     this.configurationChanged();
8645     let initialized = false;
8646     client.onTsServerStarted(async () => {
8647       if (!initialized) {
8648         initialized = true;
8649         this.registerProviders(client, typingsStatus);
8650       }
8651     });
8652   }
8653   configurationChanged() {
8654     const config = import_coc18.workspace.getConfiguration(this.id, null);
8655     this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
8656   }
8657   dispose() {
8658     import_coc18.disposeAll(this.disposables);
8659   }
8660   _register(disposable) {
8661     this.disposables.push(disposable);
8662   }
8663   registerProviders(client, typingsStatus) {
8664     let languageIds = this.description.modeIds;
8665     let clientId = `tsserver-${this.description.id}`;
8666     this._register(import_coc18.languages.registerCompletionItemProvider(clientId, "TSC", languageIds, new completionItemProvider_default(client, typingsStatus, this.fileConfigurationManager, this.description.id), completionItemProvider_default.triggerCharacters));
8667     if (this.client.apiVersion.gte(api_default.v230)) {
8668       this._register(import_coc18.languages.registerCompletionItemProvider(`${this.description.id}-directive`, "TSC", languageIds, new directiveCommentCompletions_default(client), ["@"]));
8669     }
8670     let definitionProvider = new definitionProvider_default(client);
8671     this._register(import_coc18.languages.registerDefinitionProvider(languageIds, definitionProvider));
8672     this._register(import_coc18.languages.registerTypeDefinitionProvider(languageIds, definitionProvider));
8673     this._register(import_coc18.languages.registerImplementationProvider(languageIds, definitionProvider));
8674     this._register(import_coc18.languages.registerReferencesProvider(languageIds, new references_default(client)));
8675     this._register(import_coc18.languages.registerHoverProvider(languageIds, new hover_default(client)));
8676     this._register(import_coc18.languages.registerDocumentHighlightProvider(languageIds, new documentHighlight_default(this.client)));
8677     this._register(import_coc18.languages.registerSignatureHelpProvider(languageIds, new signatureHelp_default(client), ["(", ",", "<", ")"]));
8678     this._register(import_coc18.languages.registerDocumentSymbolProvider(languageIds, new documentSymbol_default(client)));
8679     this._register(import_coc18.languages.registerRenameProvider(languageIds, new rename_default(client, this.fileConfigurationManager)));
8680     let formatProvider = new formatting_default(client, this.fileConfigurationManager);
8681     this._register(import_coc18.languages.registerDocumentFormatProvider(languageIds, formatProvider));
8682     this._register(import_coc18.languages.registerDocumentRangeFormatProvider(languageIds, formatProvider));
8683     this._register(import_coc18.languages.registerOnTypeFormattingEditProvider(languageIds, formatProvider, [";", "}", "\n", String.fromCharCode(27)]));
8684     this._register(import_coc18.languages.registerCodeActionProvider(languageIds, new moduleInstall_default(client), "tsserver"));
8685     let {fileConfigurationManager} = this;
8686     let conf = fileConfigurationManager.getLanguageConfiguration(this.id);
8687     if (["javascript", "typescript"].includes(this.id)) {
8688       if (this.client.apiVersion.gte(api_default.v290) && conf.get("updateImportsOnFileMove.enable")) {
8689         this._register(new updatePathOnRename_default(client, this.fileConfigurationManager, this.id));
8690       }
8691     }
8692     if (this.client.apiVersion.gte(api_default.v280)) {
8693       this._register(import_coc18.languages.registerFoldingRangeProvider(languageIds, new folding_default(this.client)));
8694       this._register(import_coc18.languages.registerCodeActionProvider(languageIds, new OrganizeImportsCodeActionProvider(this.client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.SourceOrganizeImports]));
8695     }
8696     if (this.client.apiVersion.gte(api_default.v240)) {
8697       this._register(import_coc18.languages.registerCodeActionProvider(languageIds, new refactor_default(client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.Refactor]));
8698     }
8699     this._register(import_coc18.languages.registerCodeActionProvider(languageIds, new quickfix_default(client, this.fileConfigurationManager), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.QuickFix]));
8700     this._register(import_coc18.languages.registerCodeActionProvider(languageIds, new importFix_default(this.client.bufferSyncSupport), "tsserver", [import_vscode_languageserver_protocol18.CodeActionKind.QuickFix]));
8701     let cachedResponse = new CachedNavTreeResponse();
8702     if (this.client.apiVersion.gte(api_default.v206) && conf.get("referencesCodeLens.enable")) {
8703       this._register(import_coc18.languages.registerCodeLensProvider(languageIds, new referencesCodeLens_default(client, cachedResponse)));
8704     }
8705     if (this.client.apiVersion.gte(api_default.v220) && conf.get("implementationsCodeLens.enable")) {
8706       this._register(import_coc18.languages.registerCodeLensProvider(languageIds, new implementationsCodeLens_default(client, cachedResponse)));
8707     }
8708     if (this.client.apiVersion.gte(api_default.v350)) {
8709       this._register(import_coc18.languages.registerSelectionRangeProvider(languageIds, new smartSelect_default(this.client)));
8710     }
8711   }
8712   handles(resource, doc) {
8713     if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
8714       return true;
8715     }
8716     const base = import_path4.default.basename(import_coc18.Uri.parse(resource).fsPath);
8717     return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
8718   }
8719   get id() {
8720     return this.description.id;
8721   }
8722   get diagnosticSource() {
8723     return this.description.diagnosticSource;
8724   }
8725   triggerAllDiagnostics() {
8726     this.client.bufferSyncSupport.requestAllDiagnostics();
8727   }
8728   diagnosticsReceived(diagnosticsKind, file2, diagnostics) {
8729     const config = import_coc18.workspace.getConfiguration(this.id, file2.toString());
8730     const reportUnnecessary = config.get("showUnused", true);
8731     this.client.diagnosticsManager.diagnosticsReceived(diagnosticsKind, file2.toString(), diagnostics.filter((diag) => {
8732       if (!reportUnnecessary) {
8733         diag.tags = void 0;
8734         if (diag.reportUnnecessary && diag.severity === import_vscode_languageserver_protocol18.DiagnosticSeverity.Information) {
8735           return false;
8736         }
8737       }
8738       return true;
8739     }));
8740   }
8741 };
8742 var languageProvider_default = LanguageProvider;
8743
8744 // src/server/typescriptServiceClient.ts
8745 var import_coc27 = __toModule(require("coc.nvim"));
8746 var import_fs4 = __toModule(require("fs"));
8747 var import_os2 = __toModule(require("os"));
8748 var import_path7 = __toModule(require("path"));
8749 var import_vscode_languageserver_protocol20 = __toModule(require_main3());
8750
8751 // src/utils/fileSchemess.ts
8752 var file = "file";
8753 var git = "git";
8754 var vsls = "vsls";
8755 var disabledSchemes = new Set([
8756   git,
8757   vsls
8758 ]);
8759
8760 // src/server/typescriptService.ts
8761 var ServerResponse;
8762 (function(ServerResponse2) {
8763   class Cancelled {
8764     constructor(reason) {
8765       this.reason = reason;
8766       this.type = "cancelled";
8767     }
8768   }
8769   ServerResponse2.Cancelled = Cancelled;
8770   ServerResponse2.NoContent = new class {
8771     constructor() {
8772       this.type = "noContent";
8773     }
8774   }();
8775 })(ServerResponse || (ServerResponse = {}));
8776 var ExectuionTarget;
8777 (function(ExectuionTarget2) {
8778   ExectuionTarget2[ExectuionTarget2["Semantic"] = 0] = "Semantic";
8779   ExectuionTarget2[ExectuionTarget2["Syntax"] = 1] = "Syntax";
8780 })(ExectuionTarget || (ExectuionTarget = {}));
8781
8782 // src/server/callbackMap.ts
8783 var CallbackMap = class {
8784   constructor() {
8785     this._callbacks = new Map();
8786     this._asyncCallbacks = new Map();
8787   }
8788   destroy(cause) {
8789     const cancellation = new ServerResponse.Cancelled(cause);
8790     for (const callback of this._callbacks.values()) {
8791       callback.onSuccess(cancellation);
8792     }
8793     this._callbacks.clear();
8794     for (const callback of this._asyncCallbacks.values()) {
8795       callback.onSuccess(cancellation);
8796     }
8797     this._asyncCallbacks.clear();
8798   }
8799   add(seq, callback, isAsync) {
8800     if (isAsync) {
8801       this._asyncCallbacks.set(seq, callback);
8802     } else {
8803       this._callbacks.set(seq, callback);
8804     }
8805   }
8806   fetch(seq) {
8807     const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
8808     this.delete(seq);
8809     return callback;
8810   }
8811   delete(seq) {
8812     if (!this._callbacks.delete(seq)) {
8813       this._asyncCallbacks.delete(seq);
8814     }
8815   }
8816 };
8817
8818 // src/server/features/bufferSyncSupport.ts
8819 var import_coc20 = __toModule(require("coc.nvim"));
8820 var import_vscode_languageserver_protocol19 = __toModule(require_main3());
8821
8822 // src/server/utils/async.ts
8823 var Delayer = class {
8824   constructor(defaultDelay) {
8825     this.defaultDelay = defaultDelay;
8826     this.timeout = null;
8827     this.completionPromise = null;
8828     this.onSuccess = null;
8829     this.task = null;
8830   }
8831   trigger(task, delay = this.defaultDelay) {
8832     this.task = task;
8833     if (delay >= 0) {
8834       this.cancelTimeout();
8835     }
8836     if (!this.completionPromise) {
8837       this.completionPromise = new Promise((resolve) => {
8838         this.onSuccess = resolve;
8839       }).then(() => {
8840         this.completionPromise = null;
8841         this.onSuccess = null;
8842         let result = this.task && this.task();
8843         this.task = null;
8844         return result;
8845       });
8846     }
8847     if (delay >= 0 || this.timeout === null) {
8848       this.timeout = setTimeout(() => {
8849         this.timeout = null;
8850         if (this.onSuccess) {
8851           this.onSuccess(void 0);
8852         }
8853       }, delay >= 0 ? delay : this.defaultDelay);
8854     }
8855     return this.completionPromise;
8856   }
8857   cancelTimeout() {
8858     if (this.timeout !== null) {
8859       clearTimeout(this.timeout);
8860       this.timeout = null;
8861     }
8862   }
8863 };
8864
8865 // src/server/utils/languageModeIds.ts
8866 var typescript = "typescript";
8867 var typescriptreact = "typescriptreact";
8868 var typescripttsx = "typescript.tsx";
8869 var typescriptjsx = "typescript.jsx";
8870 var javascript = "javascript";
8871 var javascriptreact = "javascriptreact";
8872 var javascriptjsx = "javascript.jsx";
8873 function mode2ScriptKind(mode) {
8874   switch (mode) {
8875     case typescript:
8876       return "TS";
8877     case typescripttsx:
8878       return "TSX";
8879     case typescriptjsx:
8880       return "TSX";
8881     case typescriptreact:
8882       return "TSX";
8883     case javascript:
8884       return "JS";
8885     case javascriptreact:
8886       return "JSX";
8887   }
8888   return void 0;
8889 }
8890
8891 // src/server/features/resourceMap.ts
8892 var import_coc19 = __toModule(require("coc.nvim"));
8893 function defaultPathNormalizer(resource) {
8894   let u = import_coc19.Uri.parse(resource);
8895   if (u.scheme === "file") {
8896     return u.fsPath;
8897   }
8898   return resource.toString();
8899 }
8900 var ResourceMap = class {
8901   constructor(_normalizePath = defaultPathNormalizer) {
8902     this._normalizePath = _normalizePath;
8903     this._map = new Map();
8904   }
8905   get size() {
8906     return this._map.size;
8907   }
8908   get entries() {
8909     return this._map.values();
8910   }
8911   has(uri) {
8912     const file2 = this.toKey(uri);
8913     return !!file2 && this._map.has(file2);
8914   }
8915   get(uri) {
8916     const file2 = this.toKey(uri);
8917     if (!file2)
8918       return void 0;
8919     let entry = this._map.get(file2);
8920     return entry ? entry.value : void 0;
8921   }
8922   set(uri, value) {
8923     const file2 = this.toKey(uri);
8924     if (file2) {
8925       this._map.set(file2, {uri, value});
8926     }
8927   }
8928   delete(uri) {
8929     const file2 = this.toKey(uri);
8930     if (file2) {
8931       this._map.delete(file2);
8932     }
8933   }
8934   get values() {
8935     return Array.from(this._map.values()).map((x) => x.value);
8936   }
8937   get uris() {
8938     return Array.from(this._map.values()).map((x) => x.uri);
8939   }
8940   clear() {
8941     this._map.clear();
8942   }
8943   toKey(uri) {
8944     const key = this._normalizePath ? this._normalizePath(uri) : uri;
8945     if (!key) {
8946       return key;
8947     }
8948     return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
8949   }
8950   isCaseInsensitivePath(path8) {
8951     if (isWindowsPath(path8)) {
8952       return true;
8953     }
8954     return path8[0] === "/" && this.onIsCaseInsenitiveFileSystem;
8955   }
8956   get onIsCaseInsenitiveFileSystem() {
8957     if (process.platform === "win32") {
8958       return true;
8959     }
8960     if (process.platform === "darwin") {
8961       return true;
8962     }
8963     return false;
8964   }
8965 };
8966 function isWindowsPath(path8) {
8967   return /^[a-zA-Z]:\\/.test(path8);
8968 }
8969
8970 // src/server/features/bufferSyncSupport.ts
8971 var BufferKind;
8972 (function(BufferKind2) {
8973   BufferKind2[BufferKind2["TypeScript"] = 1] = "TypeScript";
8974   BufferKind2[BufferKind2["JavaScript"] = 2] = "JavaScript";
8975 })(BufferKind || (BufferKind = {}));
8976 var BufferState;
8977 (function(BufferState2) {
8978   BufferState2[BufferState2["Initial"] = 1] = "Initial";
8979   BufferState2[BufferState2["Open"] = 2] = "Open";
8980   BufferState2[BufferState2["Closed"] = 2] = "Closed";
8981 })(BufferState || (BufferState = {}));
8982 var BufferOperationType;
8983 (function(BufferOperationType2) {
8984   BufferOperationType2[BufferOperationType2["Close"] = 0] = "Close";
8985   BufferOperationType2[BufferOperationType2["Open"] = 1] = "Open";
8986   BufferOperationType2[BufferOperationType2["Change"] = 2] = "Change";
8987 })(BufferOperationType || (BufferOperationType = {}));
8988 var CloseOperation = class {
8989   constructor(args) {
8990     this.args = args;
8991     this.type = 0;
8992   }
8993 };
8994 var OpenOperation = class {
8995   constructor(args) {
8996     this.args = args;
8997     this.type = 1;
8998   }
8999 };
9000 var ChangeOperation = class {
9001   constructor(args) {
9002     this.args = args;
9003     this.type = 2;
9004   }
9005 };
9006 var SyncedBuffer = class {
9007   constructor(document, filepath, client, synchronizer) {
9008     this.document = document;
9009     this.filepath = filepath;
9010     this.client = client;
9011     this.synchronizer = synchronizer;
9012     this.state = 1;
9013   }
9014   open() {
9015     const args = {
9016       file: this.filepath,
9017       fileContent: this.document.getText(),
9018       projectRootPath: this.client.getProjectRootPath(this.document.uri)
9019     };
9020     const scriptKind = mode2ScriptKind(this.document.languageId);
9021     if (scriptKind) {
9022       args.scriptKindName = scriptKind;
9023     }
9024     if (this.client.apiVersion.gte(api_default.v240)) {
9025       const tsPluginsForDocument = this.client.pluginManager.plugins.filter((x) => x.languages.indexOf(this.document.languageId) >= 0);
9026       if (tsPluginsForDocument.length) {
9027         args.plugins = tsPluginsForDocument.map((plugin) => plugin.name);
9028       }
9029     }
9030     this.synchronizer.open(this.resource, args);
9031     this.state = 2;
9032   }
9033   get resource() {
9034     return this.document.uri;
9035   }
9036   get lineCount() {
9037     return this.document.lineCount;
9038   }
9039   get kind() {
9040     if (this.document.languageId.startsWith("javascript")) {
9041       return 2;
9042     }
9043     return 1;
9044   }
9045   close() {
9046     if (this.state !== 2) {
9047       this.state = 2;
9048       return false;
9049     }
9050     this.state = 2;
9051     return this.synchronizer.close(this.resource, this.filepath);
9052   }
9053   onContentChanged(events2) {
9054     if (this.state !== 2) {
9055       console.error(`Unexpected buffer state: ${this.state}`);
9056     }
9057     this.synchronizer.change(this.resource, this.filepath, events2);
9058   }
9059 };
9060 var SyncedBufferMap = class extends ResourceMap {
9061   getForPath(filePath) {
9062     return this.get(import_coc20.Uri.file(filePath).toString());
9063   }
9064   get allBuffers() {
9065     return this.values;
9066   }
9067 };
9068 var PendingDiagnostics = class extends ResourceMap {
9069   getOrderedFileSet() {
9070     const orderedResources = Array.from(this.entries).sort((a, b) => a.value - b.value).map((entry) => entry.uri);
9071     const map = new ResourceMap(this._normalizePath);
9072     for (const resource of orderedResources) {
9073       map.set(resource, void 0);
9074     }
9075     return map;
9076   }
9077 };
9078 var BufferSynchronizer = class {
9079   constructor(client, pathNormalizer) {
9080     this.client = client;
9081     this._pending = new ResourceMap(pathNormalizer);
9082   }
9083   open(resource, args) {
9084     if (this.supportsBatching) {
9085       this.updatePending(resource, new OpenOperation(args));
9086     } else {
9087       this.client.executeWithoutWaitingForResponse("open", args);
9088     }
9089   }
9090   close(resource, filepath) {
9091     if (this.supportsBatching) {
9092       return this.updatePending(resource, new CloseOperation(filepath));
9093     } else {
9094       const args = {file: filepath};
9095       this.client.executeWithoutWaitingForResponse("close", args);
9096       return true;
9097     }
9098   }
9099   change(resource, filepath, events2) {
9100     if (!events2.length) {
9101       return;
9102     }
9103     if (this.supportsBatching) {
9104       this.updatePending(resource, new ChangeOperation({
9105         fileName: filepath,
9106         textChanges: events2.map((change) => ({
9107           newText: change.text,
9108           start: Position.toLocation(change.range.start),
9109           end: Position.toLocation(change.range.end)
9110         })).reverse()
9111       }));
9112     } else {
9113       for (const {range, text} of events2) {
9114         const args = {
9115           insertString: text,
9116           ...Range.toFormattingRequestArgs(filepath, range)
9117         };
9118         this.client.executeWithoutWaitingForResponse("change", args);
9119       }
9120     }
9121   }
9122   reset() {
9123     this._pending.clear();
9124   }
9125   beforeCommand(command) {
9126     if (command === "updateOpen") {
9127       return;
9128     }
9129     this.flush();
9130   }
9131   flush() {
9132     if (!this.supportsBatching) {
9133       this._pending.clear();
9134       return;
9135     }
9136     if (this._pending.size > 0) {
9137       const closedFiles = [];
9138       const openFiles = [];
9139       const changedFiles = [];
9140       for (const change of this._pending.values) {
9141         switch (change.type) {
9142           case 2:
9143             changedFiles.push(change.args);
9144             break;
9145           case 1:
9146             openFiles.push(change.args);
9147             break;
9148           case 0:
9149             closedFiles.push(change.args);
9150             break;
9151         }
9152       }
9153       this.client.execute("updateOpen", {changedFiles, closedFiles, openFiles}, import_vscode_languageserver_protocol19.CancellationToken.None, {nonRecoverable: true});
9154       this._pending.clear();
9155     }
9156   }
9157   get supportsBatching() {
9158     return this.client.apiVersion.gte(api_default.v340);
9159   }
9160   updatePending(resource, op) {
9161     switch (op.type) {
9162       case 0:
9163         const existing = this._pending.get(resource);
9164         switch (existing == null ? void 0 : existing.type) {
9165           case 1:
9166             this._pending.delete(resource);
9167             return false;
9168         }
9169         break;
9170     }
9171     if (this._pending.has(resource)) {
9172       this.flush();
9173     }
9174     this._pending.set(resource, op);
9175     return true;
9176   }
9177 };
9178 var GetErrRequest = class {
9179   constructor(client, uris, _token, onDone) {
9180     this.uris = uris;
9181     this._token = _token;
9182     this._done = false;
9183     let files = uris.map((uri) => client.normalizePath(uri));
9184     const args = {
9185       delay: 0,
9186       files
9187     };
9188     const done = () => {
9189       if (this._done) {
9190         return;
9191       }
9192       this._done = true;
9193       onDone();
9194     };
9195     client.executeAsync("geterr", args, _token.token).then(done, done);
9196   }
9197   static executeGetErrRequest(client, uris, onDone) {
9198     const token = new import_vscode_languageserver_protocol19.CancellationTokenSource();
9199     return new GetErrRequest(client, uris, token, onDone);
9200   }
9201   cancel() {
9202     if (!this._done) {
9203       this._token.cancel();
9204     }
9205     this._token.dispose();
9206   }
9207 };
9208 var BufferSyncSupport = class {
9209   constructor(client, modeIds) {
9210     this.disposables = [];
9211     this._validateJavaScript = true;
9212     this._validateTypeScript = true;
9213     this.listening = false;
9214     this._onDelete = new import_vscode_languageserver_protocol19.Emitter();
9215     this.onDelete = this._onDelete.event;
9216     this._onWillChange = new import_vscode_languageserver_protocol19.Emitter();
9217     this.onWillChange = this._onWillChange.event;
9218     this.client = client;
9219     this.modeIds = new Set(modeIds);
9220     this.diagnosticDelayer = new Delayer(300);
9221     const pathNormalizer = (path8) => this.client.toPath(path8);
9222     this.syncedBuffers = new SyncedBufferMap(pathNormalizer);
9223     this.pendingDiagnostics = new PendingDiagnostics(pathNormalizer);
9224     this.synchronizer = new BufferSynchronizer(client, pathNormalizer);
9225     this.updateConfiguration();
9226     import_coc20.workspace.onDidChangeConfiguration(this.updateConfiguration, this, this.disposables);
9227   }
9228   listen() {
9229     if (this.listening) {
9230       return;
9231     }
9232     this.listening = true;
9233     import_coc20.workspace.onDidOpenTextDocument(this.openTextDocument, this, this.disposables);
9234     import_coc20.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, this.disposables);
9235     import_coc20.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, this.disposables);
9236     import_coc20.workspace.textDocuments.forEach(this.openTextDocument, this);
9237   }
9238   handles(resource) {
9239     return this.syncedBuffers.has(resource);
9240   }
9241   dispose() {
9242     this.pendingDiagnostics.clear();
9243     import_coc20.disposeAll(this.disposables);
9244     this._onWillChange.dispose();
9245     this._onDelete.dispose();
9246   }
9247   ensureHasBuffer(resource) {
9248     if (this.syncedBuffers.has(resource)) {
9249       return true;
9250     }
9251     const existingDocument = import_coc20.workspace.textDocuments.find((doc) => doc.uri.toString() === resource);
9252     if (existingDocument) {
9253       return this.openTextDocument(existingDocument);
9254     }
9255     return false;
9256   }
9257   toResource(filePath) {
9258     const buffer = this.syncedBuffers.getForPath(filePath);
9259     if (buffer)
9260       return buffer.resource;
9261     return import_coc20.Uri.file(filePath).toString();
9262   }
9263   reset() {
9264     var _a;
9265     (_a = this.pendingGetErr) == null ? void 0 : _a.cancel();
9266     this.pendingDiagnostics.clear();
9267     this.synchronizer.reset();
9268   }
9269   reinitialize() {
9270     this.reset();
9271     for (const buffer of this.syncedBuffers.allBuffers) {
9272       buffer.open();
9273     }
9274   }
9275   openTextDocument(document) {
9276     if (!this.modeIds.has(document.languageId)) {
9277       return false;
9278     }
9279     const resource = document.uri;
9280     const filepath = this.client.normalizePath(import_coc20.Uri.parse(resource));
9281     if (!filepath) {
9282       return false;
9283     }
9284     if (this.syncedBuffers.has(resource)) {
9285       return true;
9286     }
9287     const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
9288     this.syncedBuffers.set(resource, syncedBuffer);
9289     syncedBuffer.open();
9290     this.requestDiagnostic(syncedBuffer);
9291     return true;
9292   }
9293   closeResource(resource) {
9294     const syncedBuffer = this.syncedBuffers.get(resource);
9295     if (!syncedBuffer) {
9296       return;
9297     }
9298     this.pendingDiagnostics.delete(resource);
9299     this.syncedBuffers.delete(resource);
9300     const wasBufferOpen = syncedBuffer.close();
9301     this._onDelete.fire(resource);
9302     if (wasBufferOpen) {
9303       this.requestAllDiagnostics();
9304     }
9305   }
9306   onDidCloseTextDocument(document) {
9307     this.closeResource(document.uri);
9308   }
9309   onDidChangeTextDocument(e) {
9310     const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
9311     if (!syncedBuffer) {
9312       return;
9313     }
9314     this._onWillChange.fire(syncedBuffer.resource);
9315     syncedBuffer.onContentChanged(e.contentChanges);
9316     const didTrigger = this.requestDiagnostic(syncedBuffer);
9317     if (!didTrigger && this.pendingGetErr) {
9318       this.pendingGetErr.cancel();
9319       this.pendingGetErr = void 0;
9320       this.triggerDiagnostics();
9321     }
9322   }
9323   beforeCommand(command) {
9324     this.synchronizer.beforeCommand(command);
9325   }
9326   interuptGetErr(f) {
9327     if (!this.pendingGetErr) {
9328       return f();
9329     }
9330     this.pendingGetErr.cancel();
9331     this.pendingGetErr = void 0;
9332     const result = f();
9333     this.triggerDiagnostics();
9334     return result;
9335   }
9336   getErr(resources) {
9337     const handledResources = resources.filter((resource) => {
9338       let syncedBuffer = this.syncedBuffers.get(resource.toString());
9339       return syncedBuffer && this.shouldValidate(syncedBuffer);
9340     });
9341     if (!handledResources.length) {
9342       return;
9343     }
9344     for (const resource of handledResources) {
9345       this.pendingDiagnostics.set(resource.toString(), Date.now());
9346     }
9347     this.triggerDiagnostics();
9348   }
9349   triggerDiagnostics(delay = 200) {
9350     this.diagnosticDelayer.trigger(() => {
9351       this.sendPendingDiagnostics();
9352     }, delay);
9353   }
9354   requestAllDiagnostics() {
9355     for (const buffer of this.syncedBuffers.allBuffers) {
9356       if (this.shouldValidate(buffer)) {
9357         this.pendingDiagnostics.set(buffer.resource, Date.now());
9358       }
9359     }
9360     this.triggerDiagnostics();
9361   }
9362   requestDiagnostic(buffer) {
9363     if (!this.shouldValidate(buffer)) {
9364       return false;
9365     }
9366     this.pendingDiagnostics.set(buffer.resource, Date.now());
9367     const delay = Math.min(Math.max(Math.ceil(buffer.lineCount / 20), 300), 800);
9368     this.triggerDiagnostics(delay);
9369     return true;
9370   }
9371   hasPendingDiagnostics(uri) {
9372     return this.pendingDiagnostics.has(uri);
9373   }
9374   sendPendingDiagnostics() {
9375     const orderedFileSet = this.pendingDiagnostics.getOrderedFileSet();
9376     if (this.pendingGetErr) {
9377       this.pendingGetErr.cancel();
9378       for (const uri of this.pendingGetErr.uris) {
9379         let resource = uri.toString();
9380         let syncedBuffer = this.syncedBuffers.get(resource);
9381         if (syncedBuffer && this.shouldValidate(syncedBuffer)) {
9382           orderedFileSet.set(resource, void 0);
9383         } else {
9384           orderedFileSet.delete(resource);
9385         }
9386       }
9387       this.pendingGetErr = void 0;
9388     }
9389     for (const buffer of this.syncedBuffers.values) {
9390       if (this.shouldValidate(buffer)) {
9391         orderedFileSet.set(buffer.resource, void 0);
9392       }
9393     }
9394     if (orderedFileSet.size) {
9395       let uris = Array.from(orderedFileSet.uris).map((uri) => import_coc20.Uri.parse(uri));
9396       const getErr = this.pendingGetErr = GetErrRequest.executeGetErrRequest(this.client, uris, () => {
9397         if (this.pendingGetErr === getErr) {
9398           this.pendingGetErr = void 0;
9399         }
9400       });
9401     }
9402     this.pendingDiagnostics.clear();
9403   }
9404   updateConfiguration() {
9405     const jsConfig = import_coc20.workspace.getConfiguration("javascript", null);
9406     const tsConfig = import_coc20.workspace.getConfiguration("typescript", null);
9407     this._validateJavaScript = jsConfig.get("validate.enable", true);
9408     this._validateTypeScript = tsConfig.get("validate.enable", true);
9409   }
9410   shouldValidate(buffer) {
9411     switch (buffer.kind) {
9412       case 2:
9413         return this._validateJavaScript;
9414       case 1:
9415       default:
9416         return this._validateTypeScript;
9417     }
9418   }
9419 };
9420 var bufferSyncSupport_default = BufferSyncSupport;
9421
9422 // src/server/features/diagnostics.ts
9423 var import_coc21 = __toModule(require("coc.nvim"));
9424 var DiagnosticSet = class {
9425   constructor() {
9426     this._map = new ResourceMap();
9427   }
9428   set(uri, diagnostics) {
9429     this._map.set(uri, diagnostics);
9430   }
9431   get(uri) {
9432     return this._map.get(uri) || [];
9433   }
9434   clear() {
9435     this._map = new ResourceMap();
9436   }
9437 };
9438 var DiagnosticKind;
9439 (function(DiagnosticKind2) {
9440   DiagnosticKind2[DiagnosticKind2["Syntax"] = 0] = "Syntax";
9441   DiagnosticKind2[DiagnosticKind2["Semantic"] = 1] = "Semantic";
9442   DiagnosticKind2[DiagnosticKind2["Suggestion"] = 2] = "Suggestion";
9443 })(DiagnosticKind || (DiagnosticKind = {}));
9444 var allDiagnosticKinds = [
9445   0,
9446   1,
9447   2
9448 ];
9449 var DiagnosticsManager = class {
9450   constructor() {
9451     this._diagnostics = new Map();
9452     this._pendingUpdates = new ResourceMap();
9453     this._enableJavascriptSuggestions = true;
9454     this._enableTypescriptSuggestions = true;
9455     this.updateDelay = 200;
9456     for (const kind of allDiagnosticKinds) {
9457       this._diagnostics.set(kind, new DiagnosticSet());
9458     }
9459     this._currentDiagnostics = import_coc21.languages.createDiagnosticCollection("tsserver");
9460   }
9461   dispose() {
9462     this._currentDiagnostics.dispose();
9463     for (const value of this._pendingUpdates.values) {
9464       clearTimeout(value);
9465     }
9466     this._pendingUpdates = new ResourceMap();
9467   }
9468   reInitialize() {
9469     this._currentDiagnostics.clear();
9470     for (const diagnosticSet of this._diagnostics.values()) {
9471       diagnosticSet.clear();
9472     }
9473   }
9474   setEnableSuggestions(languageId, value) {
9475     let curr = languageId == "javascript" ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
9476     if (curr == value) {
9477       return;
9478     }
9479     if (languageId == "javascript") {
9480       this._enableJavascriptSuggestions = value;
9481     } else {
9482       this._enableTypescriptSuggestions = value;
9483     }
9484   }
9485   diagnosticsReceived(kind, uri, diagnostics) {
9486     const collection = this._diagnostics.get(kind);
9487     if (!collection)
9488       return;
9489     let doc = import_coc21.workspace.getDocument(uri);
9490     if (doc)
9491       uri = doc.uri;
9492     if (diagnostics.length === 0) {
9493       const existing = collection.get(uri);
9494       if (existing.length === 0) {
9495         return;
9496       }
9497     }
9498     collection.set(uri, diagnostics);
9499     this.scheduleDiagnosticsUpdate(uri);
9500   }
9501   configFileDiagnosticsReceived(uri, diagnostics) {
9502     this._currentDiagnostics.set(uri, diagnostics);
9503   }
9504   delete(uri) {
9505     this._currentDiagnostics.delete(uri);
9506   }
9507   getDiagnostics(uri) {
9508     return this._currentDiagnostics.get(uri) || [];
9509     return [];
9510   }
9511   scheduleDiagnosticsUpdate(uri) {
9512     if (!this._pendingUpdates.has(uri)) {
9513       this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
9514     }
9515   }
9516   updateCurrentDiagnostics(uri) {
9517     if (this._pendingUpdates.has(uri)) {
9518       clearTimeout(this._pendingUpdates.get(uri));
9519       this._pendingUpdates.delete(uri);
9520     }
9521     const allDiagnostics = [
9522       ...this._diagnostics.get(0).get(uri),
9523       ...this._diagnostics.get(1).get(uri),
9524       ...this.getSuggestionDiagnostics(uri)
9525     ];
9526     this._currentDiagnostics.set(uri, allDiagnostics);
9527   }
9528   getSuggestionDiagnostics(uri) {
9529     const enabled = this.suggestionsEnabled(uri);
9530     return this._diagnostics.get(2).get(uri).filter((x) => {
9531       if (!enabled) {
9532         return x.code == 6133;
9533       }
9534       return enabled;
9535     });
9536   }
9537   suggestionsEnabled(uri) {
9538     let doc = import_coc21.workspace.getDocument(uri);
9539     if (!doc)
9540       return false;
9541     if (doc.filetype.startsWith("javascript")) {
9542       return this._enableJavascriptSuggestions;
9543     }
9544     if (doc.filetype.startsWith("typescript")) {
9545       return this._enableTypescriptSuggestions;
9546     }
9547     return true;
9548   }
9549 };
9550
9551 // src/server/requestQueue.ts
9552 var RequestQueueingType;
9553 (function(RequestQueueingType2) {
9554   RequestQueueingType2[RequestQueueingType2["Normal"] = 1] = "Normal";
9555   RequestQueueingType2[RequestQueueingType2["LowPriority"] = 2] = "LowPriority";
9556   RequestQueueingType2[RequestQueueingType2["Fence"] = 3] = "Fence";
9557 })(RequestQueueingType || (RequestQueueingType = {}));
9558 var RequestQueue = class {
9559   constructor() {
9560     this.queue = [];
9561     this.sequenceNumber = 0;
9562   }
9563   get length() {
9564     return this.queue.length;
9565   }
9566   enqueue(item) {
9567     if (item.queueingType === 1) {
9568       let index = this.queue.length - 1;
9569       while (index >= 0) {
9570         if (this.queue[index].queueingType !== 2) {
9571           break;
9572         }
9573         --index;
9574       }
9575       this.queue.splice(index + 1, 0, item);
9576     } else {
9577       this.queue.push(item);
9578     }
9579   }
9580   dequeue() {
9581     return this.queue.shift();
9582   }
9583   tryDeletePendingRequest(seq) {
9584     for (let i = 0; i < this.queue.length; i++) {
9585       if (this.queue[i].request.seq === seq) {
9586         this.queue.splice(i, 1);
9587         return true;
9588       }
9589     }
9590     return false;
9591   }
9592   createRequest(command, args) {
9593     return {
9594       seq: this.sequenceNumber++,
9595       type: "request",
9596       command,
9597       arguments: args
9598     };
9599   }
9600 };
9601
9602 // src/server/utils/configuration.ts
9603 var import_coc22 = __toModule(require("coc.nvim"));
9604 var import_which = __toModule(require_which());
9605 var TsServerLogLevel;
9606 (function(TsServerLogLevel2) {
9607   TsServerLogLevel2[TsServerLogLevel2["Off"] = 0] = "Off";
9608   TsServerLogLevel2[TsServerLogLevel2["Normal"] = 1] = "Normal";
9609   TsServerLogLevel2[TsServerLogLevel2["Terse"] = 2] = "Terse";
9610   TsServerLogLevel2[TsServerLogLevel2["Verbose"] = 3] = "Verbose";
9611 })(TsServerLogLevel || (TsServerLogLevel = {}));
9612 (function(TsServerLogLevel2) {
9613   function fromString(value) {
9614     switch (value && value.toLowerCase()) {
9615       case "normal":
9616         return TsServerLogLevel2.Normal;
9617       case "terse":
9618         return TsServerLogLevel2.Terse;
9619       case "verbose":
9620         return TsServerLogLevel2.Verbose;
9621       case "off":
9622       default:
9623         return TsServerLogLevel2.Off;
9624     }
9625   }
9626   TsServerLogLevel2.fromString = fromString;
9627   function toString2(value) {
9628     switch (value) {
9629       case TsServerLogLevel2.Normal:
9630         return "normal";
9631       case TsServerLogLevel2.Terse:
9632         return "terse";
9633       case TsServerLogLevel2.Verbose:
9634         return "verbose";
9635       case TsServerLogLevel2.Off:
9636       default:
9637         return "off";
9638     }
9639   }
9640   TsServerLogLevel2.toString = toString2;
9641 })(TsServerLogLevel || (TsServerLogLevel = {}));
9642 var TypeScriptServiceConfiguration = class {
9643   constructor() {
9644     this._configuration = import_coc22.workspace.getConfiguration("tsserver");
9645     import_coc22.workspace.onDidChangeConfiguration(() => {
9646       this._configuration = import_coc22.workspace.getConfiguration("tsserver");
9647     });
9648   }
9649   get locale() {
9650     return this._configuration.get("locale", null);
9651   }
9652   get globalTsdk() {
9653     return this._configuration.get("tsdk", null);
9654   }
9655   get ignoreLocalTsserver() {
9656     return this._configuration.get("ignoreLocalTsserver", false);
9657   }
9658   get tsServerLogLevel() {
9659     return TsServerLogLevel.fromString(this._configuration.get("log", null));
9660   }
9661   get watchOptions() {
9662     return this._configuration.get("watchOptions");
9663   }
9664   get typingsCacheLocation() {
9665     return this._configuration.get("typingsCacheLocation", "");
9666   }
9667   get tsServerPluginPaths() {
9668     return this._configuration.get("pluginPaths", []);
9669   }
9670   get checkJs() {
9671     return this._configuration.get("implicitProjectConfig.checkJs", false);
9672   }
9673   get experimentalDecorators() {
9674     return this._configuration.get("implicitProjectConfig.experimentalDecorators", false);
9675   }
9676   get disableAutomaticTypeAcquisition() {
9677     return this._configuration.get("disableAutomaticTypeAcquisition", false);
9678   }
9679   get formatOnType() {
9680     return this._configuration.get("formatOnType", false);
9681   }
9682   get maxTsServerMemory() {
9683     return this._configuration.get("maxTsServerMemory", 0);
9684   }
9685   get debugPort() {
9686     return this._configuration.get("debugPort", parseInt(process.env["TSS_DEBUG"], 10));
9687   }
9688   get npmLocation() {
9689     let path8 = this._configuration.get("npm", "");
9690     if (path8)
9691       return import_coc22.workspace.expand(path8);
9692     try {
9693       path8 = import_which.default.sync("npm");
9694     } catch (e) {
9695       return null;
9696     }
9697     return path8;
9698   }
9699   static loadFromWorkspace() {
9700     return new TypeScriptServiceConfiguration();
9701   }
9702 };
9703
9704 // src/server/utils/logger.ts
9705 var import_coc23 = __toModule(require("coc.nvim"));
9706
9707 // src/server/utils/is.ts
9708 var toString = Object.prototype.toString;
9709 function boolean(value) {
9710   return value === true || value === false;
9711 }
9712 function string(value) {
9713   return toString.call(value) === "[object String]";
9714 }
9715
9716 // src/server/utils/logger.ts
9717 var Logger = class {
9718   get output() {
9719     if (this._channel) {
9720       return this._channel;
9721     }
9722     this._channel = import_coc23.window.createOutputChannel("tsserver");
9723     return this._channel;
9724   }
9725   dispose() {
9726     if (this._channel) {
9727       this._channel.dispose();
9728     }
9729   }
9730   data2String(data) {
9731     if (data instanceof Error) {
9732       if (string(data.stack)) {
9733         return data.stack;
9734       }
9735       return data.message;
9736     }
9737     if (boolean(data.success) && !data.success && string(data.message)) {
9738       return data.message;
9739     }
9740     if (string(data)) {
9741       return data;
9742     }
9743     return data.toString();
9744   }
9745   info(message, data) {
9746     this.logLevel("Info", message, data);
9747   }
9748   warn(message, data) {
9749     this.logLevel("Warn", message, data);
9750   }
9751   error(message, data) {
9752     if (data && data.message === "No content available.") {
9753       return;
9754     }
9755     this.logLevel("Error", message, data);
9756   }
9757   logLevel(level, message, data) {
9758     this.output.appendLine(`[${level}  - ${new Date().toLocaleTimeString()}] ${message}`);
9759     if (data) {
9760       this.output.appendLine(this.data2String(data));
9761     }
9762   }
9763 };
9764 var logger_default = Logger;
9765
9766 // src/server/utils/process.ts
9767 var import_child_process2 = __toModule(require("child_process"));
9768 var import_net = __toModule(require("net"));
9769 var import_os = __toModule(require("os"));
9770 var import_path5 = __toModule(require("path"));
9771 var import_fs2 = __toModule(require("fs"));
9772 function makeRandomHexString(length) {
9773   let chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
9774   let result = "";
9775   for (let i = 0; i < length; i++) {
9776     const idx = Math.floor(chars.length * Math.random());
9777     result += chars[idx];
9778   }
9779   return result;
9780 }
9781 function getTempDirectory() {
9782   let dir = import_path5.default.join(import_os.default.tmpdir(), `coc.nvim-${process.pid}`);
9783   if (!import_fs2.default.existsSync(dir)) {
9784     import_fs2.default.mkdirSync(dir);
9785   }
9786   return dir;
9787 }
9788 function generatePipeName() {
9789   return getPipeName(makeRandomHexString(40));
9790 }
9791 function getPipeName(name) {
9792   const fullName = "coc-tsc-" + name;
9793   if (process.platform === "win32") {
9794     return "\\\\.\\pipe\\" + fullName + "-sock";
9795   }
9796   const tmpdir = getTempDirectory();
9797   return import_path5.default.join(tmpdir, fullName + ".sock");
9798 }
9799 function getTempFile(name) {
9800   const fullName = "coc-nvim-" + name;
9801   return import_path5.default.join(getTempDirectory(), fullName + ".sock");
9802 }
9803 function generatePatchedEnv(env, stdInPipeName, stdOutPipeName, stdErrPipeName) {
9804   const newEnv = Object.assign({}, env);
9805   newEnv["STDIN_PIPE_NAME"] = stdInPipeName;
9806   newEnv["STDOUT_PIPE_NAME"] = stdOutPipeName;
9807   newEnv["STDERR_PIPE_NAME"] = stdErrPipeName;
9808   newEnv["TSS_LOG"] = `-level verbose -file ${import_path5.default.join(import_os.default.tmpdir(), "coc-nvim-tsc.log")}`;
9809   newEnv["PATH"] = newEnv["PATH"] || process.env.PATH;
9810   return newEnv;
9811 }
9812 function fork(modulePath, args, options, logger, callback) {
9813   let callbackCalled = false;
9814   const resolve = (result) => {
9815     if (callbackCalled) {
9816       return;
9817     }
9818     callbackCalled = true;
9819     callback(null, result);
9820   };
9821   const reject = (err) => {
9822     if (callbackCalled) {
9823       return;
9824     }
9825     callbackCalled = true;
9826     callback(err, null);
9827   };
9828   const stdInPipeName = generatePipeName();
9829   const stdOutPipeName = generatePipeName();
9830   const stdErrPipeName = generatePipeName();
9831   const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
9832   newEnv["NODE_PATH"] = import_path5.default.join(modulePath, "..", "..", "..");
9833   let childProcess;
9834   let stdErrServer = import_net.default.createServer((stdErrStream) => {
9835     childProcess.stderr = stdErrStream;
9836   });
9837   stdErrServer.listen(stdErrPipeName);
9838   let stdOutServer = import_net.default.createServer((stdOutStream) => {
9839     stdOutStream.once("data", (_chunk) => {
9840       childProcess.stdin = import_net.default.connect(stdInPipeName);
9841       childProcess.stdout = stdOutStream;
9842       resolve(childProcess);
9843     });
9844   });
9845   stdOutServer.listen(stdOutPipeName);
9846   let serverClosed = false;
9847   const closeServer = () => {
9848     if (serverClosed) {
9849       return;
9850     }
9851     serverClosed = true;
9852     stdOutServer.close();
9853     stdErrServer.close();
9854   };
9855   logger.info("Forking TSServer", `PATH: ${newEnv["PATH"]} `);
9856   const bootstrapperPath = import_path5.default.resolve(__dirname, "../bin/tsserverForkStart");
9857   childProcess = import_child_process2.default.fork(bootstrapperPath, [modulePath].concat(args), {
9858     silent: true,
9859     env: newEnv,
9860     execArgv: options.execArgv
9861   });
9862   childProcess.once("error", (err) => {
9863     closeServer();
9864     reject(err);
9865   });
9866   childProcess.once("exit", (err) => {
9867     closeServer();
9868     reject(err);
9869   });
9870 }
9871
9872 // src/server/utils/tracer.ts
9873 var import_coc24 = __toModule(require("coc.nvim"));
9874 var Trace;
9875 (function(Trace2) {
9876   Trace2[Trace2["Off"] = 0] = "Off";
9877   Trace2[Trace2["Messages"] = 1] = "Messages";
9878   Trace2[Trace2["Verbose"] = 2] = "Verbose";
9879 })(Trace || (Trace = {}));
9880 (function(Trace2) {
9881   function fromString(value) {
9882     value = value || "";
9883     value = value.toLowerCase();
9884     switch (value) {
9885       case "off":
9886         return Trace2.Off;
9887       case "messages":
9888         return Trace2.Messages;
9889       case "verbose":
9890         return Trace2.Verbose;
9891       default:
9892         return Trace2.Off;
9893     }
9894   }
9895   Trace2.fromString = fromString;
9896 })(Trace || (Trace = {}));
9897 var Tracer = class {
9898   constructor(logger) {
9899     this.logger = logger;
9900     this.trace = Tracer.readTrace();
9901   }
9902   static readTrace() {
9903     let result = Trace.fromString(import_coc24.workspace.getConfiguration("tsserver").get("trace.server", "off"));
9904     if (result === 0 && !!process.env.TSS_TRACE) {
9905       result = 1;
9906     }
9907     return result;
9908   }
9909   traceRequest(request, responseExpected, queueLength) {
9910     if (this.trace === 0)
9911       return;
9912     let data;
9913     if (this.trace === 2 && request.arguments) {
9914       data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
9915     }
9916     this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? "yes" : "no"}. Current queue length: ${queueLength}`, data);
9917   }
9918   traceResponse(response, startTime) {
9919     if (this.trace === 0) {
9920       return;
9921     }
9922     let data;
9923     if (this.trace === 2 && response.body) {
9924       data = `Result: ${JSON.stringify(response.body, null, 4)}`;
9925     }
9926     this.logTrace(`Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? ". Message: " + response.message : ""}`, data);
9927   }
9928   traceEvent(event) {
9929     if (this.trace === 0) {
9930       return;
9931     }
9932     let data;
9933     if (this.trace === 2 && event.body) {
9934       data = `Data: ${JSON.stringify(event.body, null, 4)}`;
9935     }
9936     this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
9937   }
9938   logTrace(message, data) {
9939     if (this.trace !== 0) {
9940       this.logger.logLevel("Trace", message, data);
9941     }
9942   }
9943   traceRequestCompleted(command, request_seq, startTime) {
9944     if (this.trace === 0) {
9945       return;
9946     }
9947     this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
9948   }
9949 };
9950 var tracer_default = Tracer;
9951
9952 // src/server/utils/tsconfig.ts
9953 function inferredProjectConfig(config) {
9954   const base = {
9955     module: "commonjs",
9956     target: "es2016",
9957     jsx: "preserve"
9958   };
9959   if (config.checkJs) {
9960     base.checkJs = true;
9961   }
9962   if (config.experimentalDecorators) {
9963     base.experimentalDecorators = true;
9964   }
9965   return base;
9966 }
9967
9968 // src/server/utils/versionProvider.ts
9969 var import_coc25 = __toModule(require("coc.nvim"));
9970 var import_fs3 = __toModule(require("fs"));
9971 var import_path6 = __toModule(require("path"));
9972 var TypeScriptVersion = class {
9973   constructor(path8, _pathLabel) {
9974     this.path = path8;
9975     this._pathLabel = _pathLabel;
9976     this._api = null;
9977   }
9978   get tscPath() {
9979     return import_path6.default.resolve(this.path, "../bin/tsc");
9980   }
9981   get tsServerPath() {
9982     return import_path6.default.resolve(this.path, "tsserver.js");
9983   }
9984   get pathLabel() {
9985     return typeof this._pathLabel === "undefined" ? this.path : this._pathLabel;
9986   }
9987   get isValid() {
9988     return this.version != null;
9989   }
9990   get version() {
9991     if (this._api)
9992       return this._api;
9993     let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
9994     return api;
9995   }
9996   get versionString() {
9997     const version = this.version;
9998     return version ? version.versionString : null;
9999   }
10000   getTypeScriptVersion(serverPath) {
10001     if (!import_fs3.default.existsSync(serverPath)) {
10002       return void 0;
10003     }
10004     const p = serverPath.split(import_path6.default.sep);
10005     if (p.length <= 2) {
10006       return void 0;
10007     }
10008     const p2 = p.slice(0, -2);
10009     const modulePath = p2.join(import_path6.default.sep);
10010     let fileName = import_path6.default.join(modulePath, "package.json");
10011     if (!import_fs3.default.existsSync(fileName)) {
10012       if (import_path6.default.basename(modulePath) === "built") {
10013         fileName = import_path6.default.join(modulePath, "..", "package.json");
10014       }
10015     }
10016     if (!import_fs3.default.existsSync(fileName)) {
10017       return void 0;
10018     }
10019     const contents = import_fs3.default.readFileSync(fileName).toString();
10020     let desc = null;
10021     try {
10022       desc = JSON.parse(contents);
10023     } catch (err) {
10024       return void 0;
10025     }
10026     if (!desc || !desc.version) {
10027       return void 0;
10028     }
10029     return desc.version ? api_default.fromVersionString(desc.version) : void 0;
10030   }
10031 };
10032 var MODULE_FOLDERS = ["node_modules/typescript/lib", ".vscode/pnpify/typescript/lib", ".yarn/sdks/typescript/lib"];
10033 var TypeScriptVersionProvider = class {
10034   constructor(configuration) {
10035     this.configuration = configuration;
10036   }
10037   updateConfiguration(configuration) {
10038     this.configuration = configuration;
10039   }
10040   getDefaultVersion() {
10041     let {globalTsdk} = this.configuration;
10042     if (globalTsdk)
10043       return new TypeScriptVersion(globalTsdk);
10044     return this.bundledVersion;
10045   }
10046   get globalVersion() {
10047     let {globalTsdk} = this.configuration;
10048     if (globalTsdk)
10049       return new TypeScriptVersion(import_coc25.workspace.expand(globalTsdk));
10050     return void 0;
10051   }
10052   getLocalVersion() {
10053     let folders = import_coc25.workspace.workspaceFolders.map((f) => import_coc25.Uri.parse(f.uri).fsPath);
10054     for (let p of folders) {
10055       for (let folder of MODULE_FOLDERS) {
10056         let libFolder = import_path6.default.join(p, folder);
10057         if (import_fs3.default.existsSync(libFolder)) {
10058           let version = new TypeScriptVersion(libFolder);
10059           if (version.isValid)
10060             return version;
10061         }
10062       }
10063     }
10064     return null;
10065   }
10066   get bundledVersion() {
10067     try {
10068       const file2 = require.resolve("typescript");
10069       const bundledVersion = new TypeScriptVersion(import_path6.default.dirname(file2), "");
10070       return bundledVersion;
10071     } catch (e) {
10072       import_coc25.window.showMessage("Bundled typescript module not found", "error");
10073       return null;
10074     }
10075   }
10076 };
10077
10078 // src/server/utils/versionStatus.ts
10079 var import_coc26 = __toModule(require("coc.nvim"));
10080 var VersionStatus = class {
10081   constructor(_normalizePath, enableJavascript) {
10082     this._normalizePath = _normalizePath;
10083     this.enableJavascript = enableJavascript;
10084     this._versionString = "";
10085     this._versionBarEntry = import_coc26.window.createStatusBarItem(99);
10086     this._onChangeEditorSub = import_coc26.events.on("BufEnter", this.onBufEnter, this);
10087     this._versionBarEntry.show();
10088   }
10089   dispose() {
10090     this._versionBarEntry.dispose();
10091     this._onChangeEditorSub.dispose();
10092   }
10093   onDidChangeTypeScriptVersion(version) {
10094     this._versionString = version.versionString;
10095   }
10096   set loading(isLoading) {
10097     if (isLoading) {
10098       this._versionBarEntry.text = `Initialing tsserver ${this._versionString}`;
10099     } else {
10100       this._versionBarEntry.text = `TSC ${this._versionString}`;
10101     }
10102     this._versionBarEntry.isProgress = isLoading;
10103   }
10104   checkFiletype(filetype) {
10105     if (filetype.startsWith("javascript") && this.enableJavascript) {
10106       return true;
10107     }
10108     return filetype.startsWith("typescript");
10109   }
10110   async onBufEnter(bufnr) {
10111     let filetype = await import_coc26.workspace.nvim.call("getbufvar", [bufnr, "&filetype", ""]);
10112     if (this.checkFiletype(filetype)) {
10113       this._versionBarEntry.show();
10114     } else {
10115       this._versionBarEntry.hide();
10116     }
10117   }
10118 };
10119 var versionStatus_default = VersionStatus;
10120
10121 // src/server/utils/wireProtocol.ts
10122 var DefaultSize = 8192;
10123 var ContentLength = "Content-Length: ";
10124 var ContentLengthSize = Buffer.byteLength(ContentLength, "utf8");
10125 var Blank = Buffer.from(" ", "utf8")[0];
10126 var BackslashR = Buffer.from("\r", "utf8")[0];
10127 var BackslashN = Buffer.from("\n", "utf8")[0];
10128 var ProtocolBuffer = class {
10129   constructor() {
10130     this.index = 0;
10131     this.buffer = Buffer.allocUnsafe(DefaultSize);
10132   }
10133   append(data) {
10134     let toAppend = null;
10135     if (Buffer.isBuffer(data)) {
10136       toAppend = data;
10137     } else {
10138       toAppend = Buffer.from(data, "utf8");
10139     }
10140     if (this.buffer.length - this.index >= toAppend.length) {
10141       toAppend.copy(this.buffer, this.index, 0, toAppend.length);
10142     } else {
10143       let newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
10144       if (this.index === 0) {
10145         this.buffer = Buffer.allocUnsafe(newSize);
10146         toAppend.copy(this.buffer, 0, 0, toAppend.length);
10147       } else {
10148         this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
10149       }
10150     }
10151     this.index += toAppend.length;
10152   }
10153   tryReadContentLength() {
10154     let result = -1;
10155     let current = 0;
10156     while (current < this.index && (this.buffer[current] === Blank || this.buffer[current] === BackslashR || this.buffer[current] === BackslashN)) {
10157       current++;
10158     }
10159     if (this.index < current + ContentLengthSize) {
10160       return result;
10161     }
10162     current += ContentLengthSize;
10163     let start = current;
10164     while (current < this.index && this.buffer[current] !== BackslashR) {
10165       current++;
10166     }
10167     if (current + 3 >= this.index || this.buffer[current + 1] !== BackslashN || this.buffer[current + 2] !== BackslashR || this.buffer[current + 3] !== BackslashN) {
10168       return result;
10169     }
10170     let data = this.buffer.toString("utf8", start, current);
10171     result = parseInt(data, 10);
10172     this.buffer = this.buffer.slice(current + 4);
10173     this.index = this.index - (current + 4);
10174     return result;
10175   }
10176   tryReadContent(length) {
10177     if (this.index < length) {
10178       return null;
10179     }
10180     let result = this.buffer.toString("utf8", 0, length);
10181     let sourceStart = length;
10182     while (sourceStart < this.index && (this.buffer[sourceStart] === BackslashR || this.buffer[sourceStart] === BackslashN)) {
10183       sourceStart++;
10184     }
10185     this.buffer.copy(this.buffer, 0, sourceStart);
10186     this.index = this.index - sourceStart;
10187     return result;
10188   }
10189 };
10190 var Reader = class {
10191   constructor(readable, callback, onError) {
10192     this.readable = readable;
10193     this.callback = callback;
10194     this.onError = onError;
10195     this.buffer = new ProtocolBuffer();
10196     this.nextMessageLength = -1;
10197     this.readable.on("data", (data) => {
10198       this.onLengthData(data);
10199     });
10200   }
10201   onLengthData(data) {
10202     try {
10203       this.buffer.append(data);
10204       while (true) {
10205         if (this.nextMessageLength === -1) {
10206           this.nextMessageLength = this.buffer.tryReadContentLength();
10207           if (this.nextMessageLength === -1) {
10208             return;
10209           }
10210         }
10211         const msg = this.buffer.tryReadContent(this.nextMessageLength);
10212         if (msg === null) {
10213           return;
10214         }
10215         this.nextMessageLength = -1;
10216         const json = JSON.parse(msg);
10217         this.callback(json);
10218       }
10219     } catch (e) {
10220       this.onError(e);
10221     }
10222   }
10223 };
10224
10225 // src/server/typescriptServiceClient.ts
10226 var ForkedTsServerProcess = class {
10227   constructor(childProcess) {
10228     this.childProcess = childProcess;
10229     this.toCancelOnResourceChange = new Set();
10230   }
10231   onError(cb) {
10232     this.childProcess.on("error", cb);
10233   }
10234   onExit(cb) {
10235     this.childProcess.on("exit", cb);
10236   }
10237   write(serverRequest) {
10238     this.childProcess.stdin.write(JSON.stringify(serverRequest) + "\r\n", "utf8");
10239   }
10240   createReader(callback, onError) {
10241     new Reader(this.childProcess.stdout, callback, onError);
10242   }
10243   kill() {
10244     this.childProcess.kill();
10245   }
10246 };
10247 var TypeScriptServiceClient = class {
10248   constructor(pluginManager, modeIds) {
10249     this.pluginManager = pluginManager;
10250     this.modeIds = modeIds;
10251     this.state = import_coc27.ServiceStat.Initial;
10252     this.logger = new logger_default();
10253     this.tsServerLogFile = null;
10254     this.cancellationPipeName = null;
10255     this._callbacks = new CallbackMap();
10256     this._requestQueue = new RequestQueue();
10257     this._pendingResponses = new Set();
10258     this._onTsServerStarted = new import_vscode_languageserver_protocol20.Emitter();
10259     this._onProjectLanguageServiceStateChanged = new import_vscode_languageserver_protocol20.Emitter();
10260     this._onDidBeginInstallTypings = new import_vscode_languageserver_protocol20.Emitter();
10261     this._onDidEndInstallTypings = new import_vscode_languageserver_protocol20.Emitter();
10262     this._onTypesInstallerInitializationFailed = new import_vscode_languageserver_protocol20.Emitter();
10263     this.disposables = [];
10264     this.isRestarting = false;
10265     this._onDiagnosticsReceived = new import_vscode_languageserver_protocol20.Emitter();
10266     this._onConfigDiagnosticsReceived = new import_vscode_languageserver_protocol20.Emitter();
10267     this._onResendModelsRequested = new import_vscode_languageserver_protocol20.Emitter();
10268     this.pathSeparator = import_path7.default.sep;
10269     this.lastStart = Date.now();
10270     this.servicePromise = null;
10271     this.lastError = null;
10272     this.numberRestarts = 0;
10273     this.fileConfigurationManager = new fileConfigurationManager_default(this);
10274     this._configuration = TypeScriptServiceConfiguration.loadFromWorkspace();
10275     this.versionProvider = new TypeScriptVersionProvider(this._configuration);
10276     this._apiVersion = api_default.defaultVersion;
10277     this.tracer = new tracer_default(this.logger);
10278     this.versionStatus = new versionStatus_default(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript());
10279     pluginManager.onDidUpdateConfig((update) => {
10280       this.configurePlugin(update.pluginId, update.config);
10281     }, null, this.disposables);
10282     pluginManager.onDidChangePlugins(() => {
10283       this.restartTsServer();
10284     }, null, this.disposables);
10285     this.bufferSyncSupport = new bufferSyncSupport_default(this, modeIds);
10286     this.onTsServerStarted(() => {
10287       this.bufferSyncSupport.listen();
10288     });
10289     this.diagnosticsManager = new DiagnosticsManager();
10290     this.bufferSyncSupport.onDelete((resource) => {
10291       this.cancelInflightRequestsForResource(resource);
10292       this.diagnosticsManager.delete(resource);
10293     }, null, this.disposables);
10294     this.bufferSyncSupport.onWillChange((resource) => {
10295       this.cancelInflightRequestsForResource(resource);
10296     });
10297   }
10298   get onDiagnosticsReceived() {
10299     return this._onDiagnosticsReceived.event;
10300   }
10301   get onConfigDiagnosticsReceived() {
10302     return this._onConfigDiagnosticsReceived.event;
10303   }
10304   get onResendModelsRequested() {
10305     return this._onResendModelsRequested.event;
10306   }
10307   get configuration() {
10308     return this._configuration;
10309   }
10310   dispose() {
10311     if (this.servicePromise) {
10312       this.servicePromise.then((childProcess) => {
10313         childProcess.kill();
10314       }).then(void 0, () => void 0);
10315     }
10316     this.bufferSyncSupport.dispose();
10317     this.logger.dispose();
10318     this._onTsServerStarted.dispose();
10319     this._onResendModelsRequested.dispose();
10320     this.versionStatus.dispose();
10321   }
10322   info(message, data) {
10323     this.logger.info(message, data);
10324   }
10325   error(message, data) {
10326     this.logger.error(message, data);
10327   }
10328   restartTsServer() {
10329     const start = () => {
10330       this.servicePromise = this.startService(true);
10331       return this.servicePromise;
10332     };
10333     if (this.servicePromise) {
10334       return Promise.resolve(this.servicePromise.then((childProcess) => {
10335         this.state = import_coc27.ServiceStat.Stopping;
10336         this.info("Killing TS Server");
10337         this.isRestarting = true;
10338         childProcess.kill();
10339         this.servicePromise = null;
10340       }).then(start));
10341     } else {
10342       return Promise.resolve(start());
10343     }
10344   }
10345   stop() {
10346     if (!this.servicePromise)
10347       return;
10348     return new Promise((resolve, reject) => {
10349       this.servicePromise.then((childProcess) => {
10350         if (this.state == import_coc27.ServiceStat.Running) {
10351           this.info("Killing TS Server");
10352           childProcess.onExit(() => {
10353             resolve();
10354           });
10355           childProcess.kill();
10356           this.servicePromise = null;
10357         } else {
10358           resolve();
10359         }
10360       }, reject);
10361     });
10362   }
10363   get onTsServerStarted() {
10364     return this._onTsServerStarted.event;
10365   }
10366   get onProjectLanguageServiceStateChanged() {
10367     return this._onProjectLanguageServiceStateChanged.event;
10368   }
10369   get onDidBeginInstallTypings() {
10370     return this._onDidBeginInstallTypings.event;
10371   }
10372   get onDidEndInstallTypings() {
10373     return this._onDidEndInstallTypings.event;
10374   }
10375   get onTypesInstallerInitializationFailed() {
10376     return this._onTypesInstallerInitializationFailed.event;
10377   }
10378   get apiVersion() {
10379     return this._apiVersion;
10380   }
10381   get tscPath() {
10382     return this._tscPath;
10383   }
10384   service() {
10385     if (this.servicePromise) {
10386       return this.servicePromise;
10387     }
10388     if (this.lastError) {
10389       return Promise.reject(this.lastError);
10390     }
10391     return this.startService().then(() => {
10392       if (this.servicePromise) {
10393         return this.servicePromise;
10394       }
10395     });
10396   }
10397   ensureServiceStarted() {
10398     if (!this.servicePromise) {
10399       this.startService().catch((err) => {
10400         import_coc27.window.showMessage(`TSServer start failed: ${err.message}`, "error");
10401         this.error(`Service start failed: ${err.stack}`);
10402       });
10403     }
10404   }
10405   async startService(resendModels = false) {
10406     const {ignoreLocalTsserver} = this.configuration;
10407     let currentVersion;
10408     if (!ignoreLocalTsserver)
10409       currentVersion = this.versionProvider.getLocalVersion();
10410     if (!currentVersion || !import_fs4.default.existsSync(currentVersion.tsServerPath)) {
10411       currentVersion = this.versionProvider.getDefaultVersion();
10412     }
10413     if (!currentVersion || !currentVersion.isValid) {
10414       if (this.configuration.globalTsdk) {
10415         import_coc27.window.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, "error");
10416       } else {
10417         import_coc27.window.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, "error");
10418       }
10419       return;
10420     }
10421     this._apiVersion = currentVersion.version;
10422     this._tscPath = currentVersion.tscPath;
10423     this.versionStatus.onDidChangeTypeScriptVersion(currentVersion);
10424     this.lastError = null;
10425     const tsServerForkArgs = await this.getTsServerArgs(currentVersion);
10426     const debugPort = this._configuration.debugPort;
10427     const maxTsServerMemory = this._configuration.maxTsServerMemory;
10428     const options = {
10429       execArgv: [
10430         ...debugPort ? [`--inspect=${debugPort}`] : [],
10431         ...maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []
10432       ],
10433       cwd: import_coc27.workspace.root
10434     };
10435     this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
10436     return this.servicePromise;
10437   }
10438   startProcess(currentVersion, args, options, resendModels) {
10439     this.state = import_coc27.ServiceStat.Starting;
10440     return new Promise((resolve, reject) => {
10441       try {
10442         fork(currentVersion.tsServerPath, args, options, this.logger, (err, childProcess) => {
10443           if (err || !childProcess) {
10444             this.state = import_coc27.ServiceStat.StartFailed;
10445             this.lastError = err;
10446             this.error("Starting TSServer failed with error.", err.stack);
10447             return;
10448           }
10449           this.state = import_coc27.ServiceStat.Running;
10450           this.info("Started TSServer", JSON.stringify(currentVersion, null, 2));
10451           const handle = new ForkedTsServerProcess(childProcess);
10452           this.tsServerProcess = handle;
10453           this.lastStart = Date.now();
10454           handle.onError((err2) => {
10455             this.lastError = err2;
10456             this.error("TSServer errored with error.", err2);
10457             this.error(`TSServer log file: ${this.tsServerLogFile || ""}`);
10458             import_coc27.window.showMessage(`TSServer errored with error. ${err2.message}`, "error");
10459             this.serviceExited(false);
10460           });
10461           handle.onExit((code) => {
10462             if (code == null) {
10463               this.info("TSServer normal exit");
10464             } else {
10465               this.error(`TSServer exited with code: ${code}`);
10466             }
10467             this.info(`TSServer log file: ${this.tsServerLogFile || ""}`);
10468             this.serviceExited(!this.isRestarting);
10469             this.isRestarting = false;
10470           });
10471           handle.createReader((msg) => {
10472             this.dispatchMessage(msg);
10473           }, (error) => {
10474             this.error("ReaderError", error);
10475           });
10476           resolve(handle);
10477           this.serviceStarted(resendModels);
10478           this._onTsServerStarted.fire(currentVersion.version);
10479         });
10480       } catch (e) {
10481         reject(e);
10482       }
10483     });
10484   }
10485   async openTsServerLogFile() {
10486     const isRoot = process.getuid && process.getuid() == 0;
10487     let echoErr = (msg) => {
10488       import_coc27.window.showMessage(msg, "error");
10489     };
10490     if (isRoot) {
10491       echoErr("Log disabled for root user.");
10492       return false;
10493     }
10494     if (!this.apiVersion.gte(api_default.v222)) {
10495       echoErr("TS Server logging requires TS 2.2.2+");
10496       return false;
10497     }
10498     if (this._configuration.tsServerLogLevel === TsServerLogLevel.Off) {
10499       echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
10500       return false;
10501     }
10502     if (!this.tsServerLogFile) {
10503       echoErr("TS Server has not started logging.");
10504       return false;
10505     }
10506     try {
10507       await import_coc27.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
10508       return true;
10509     } catch {
10510       echoErr("Could not open TS Server log file");
10511       return false;
10512     }
10513   }
10514   serviceStarted(resendModels) {
10515     this.bufferSyncSupport.reset();
10516     const watchOptions = this.apiVersion.gte(api_default.v380) ? this.configuration.watchOptions : void 0;
10517     const configureOptions = {
10518       hostInfo: "coc-nvim",
10519       preferences: {
10520         providePrefixAndSuffixTextForRename: true,
10521         allowRenameOfImportPath: true
10522       },
10523       watchOptions
10524     };
10525     this.executeWithoutWaitingForResponse("configure", configureOptions);
10526     this.setCompilerOptionsForInferredProjects(this._configuration);
10527     if (resendModels) {
10528       this._onResendModelsRequested.fire(void 0);
10529       this.fileConfigurationManager.reset();
10530       this.diagnosticsManager.reInitialize();
10531       this.bufferSyncSupport.reinitialize();
10532     }
10533     for (const [config, pluginName] of this.pluginManager.configurations()) {
10534       this.configurePlugin(config, pluginName);
10535     }
10536   }
10537   setCompilerOptionsForInferredProjects(configuration) {
10538     if (!this.apiVersion.gte(api_default.v206))
10539       return;
10540     const args = {
10541       options: this.getCompilerOptionsForInferredProjects(configuration)
10542     };
10543     this.executeWithoutWaitingForResponse("compilerOptionsForInferredProjects", args);
10544   }
10545   getCompilerOptionsForInferredProjects(configuration) {
10546     return {
10547       ...inferredProjectConfig(configuration),
10548       allowJs: true,
10549       allowSyntheticDefaultImports: true,
10550       allowNonTsExtensions: true
10551     };
10552   }
10553   serviceExited(restart) {
10554     this.state = import_coc27.ServiceStat.Stopped;
10555     this.servicePromise = null;
10556     this.tsServerLogFile = null;
10557     this._callbacks.destroy("Service died.");
10558     this._callbacks = new CallbackMap();
10559     this._requestQueue = new RequestQueue();
10560     this._pendingResponses = new Set();
10561     if (restart) {
10562       const diff = Date.now() - this.lastStart;
10563       this.numberRestarts++;
10564       let startService = true;
10565       if (this.numberRestarts > 5) {
10566         this.numberRestarts = 0;
10567         if (diff < 10 * 1e3) {
10568           this.lastStart = Date.now();
10569           startService = false;
10570           import_coc27.window.showMessage("The TypeScript language service died 5 times right after it got started.", "error");
10571         } else if (diff < 60 * 1e3) {
10572           this.lastStart = Date.now();
10573           import_coc27.window.showMessage("The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.", "error");
10574         }
10575       }
10576       if (startService) {
10577         this.startService(true);
10578       }
10579     }
10580   }
10581   toPath(uri) {
10582     return this.normalizePath(import_coc27.Uri.parse(uri));
10583   }
10584   toOpenedFilePath(uri, options = {}) {
10585     if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
10586       if (!options.suppressAlertOnFailure) {
10587         console.error(`Unexpected resource ${uri}`);
10588       }
10589       return void 0;
10590     }
10591     return this.toPath(uri);
10592   }
10593   toResource(filepath) {
10594     if (this._apiVersion.gte(api_default.v213)) {
10595       if (filepath.startsWith(this.inMemoryResourcePrefix + "untitled:")) {
10596         let resource = import_coc27.Uri.parse(filepath);
10597         if (this.inMemoryResourcePrefix) {
10598           const dirName = import_path7.default.dirname(resource.path);
10599           const fileName = import_path7.default.basename(resource.path);
10600           if (fileName.startsWith(this.inMemoryResourcePrefix)) {
10601             resource = resource.with({path: import_path7.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))});
10602           }
10603         }
10604         return resource.toString();
10605       }
10606     }
10607     return import_coc27.Uri.file(filepath).toString();
10608   }
10609   normalizePath(resource) {
10610     if (disabledSchemes.has(resource.scheme)) {
10611       return void 0;
10612     }
10613     switch (resource.scheme) {
10614       case file: {
10615         let result = resource.fsPath;
10616         if (!result)
10617           return void 0;
10618         result = import_path7.default.normalize(result);
10619         return result.replace(new RegExp("\\" + this.pathSeparator, "g"), "/");
10620       }
10621       default: {
10622         return this.inMemoryResourcePrefix + resource.toString(true);
10623       }
10624     }
10625   }
10626   getDocument(resource) {
10627     if (resource.startsWith("untitled:")) {
10628       let bufnr = parseInt(resource.split(":", 2)[1], 10);
10629       return import_coc27.workspace.getDocument(bufnr);
10630     }
10631     return import_coc27.workspace.getDocument(resource);
10632   }
10633   get inMemoryResourcePrefix() {
10634     return this._apiVersion.gte(api_default.v270) ? "^" : "";
10635   }
10636   asUrl(filepath) {
10637     if (this._apiVersion.gte(api_default.v213)) {
10638       if (filepath.startsWith(this.inMemoryResourcePrefix + "untitled:")) {
10639         let resource = import_coc27.Uri.parse(filepath.slice(this.inMemoryResourcePrefix.length));
10640         if (this.inMemoryResourcePrefix) {
10641           const dirName = import_path7.default.dirname(resource.path);
10642           const fileName = import_path7.default.basename(resource.path);
10643           if (fileName.startsWith(this.inMemoryResourcePrefix)) {
10644             resource = resource.with({
10645               path: import_path7.default.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length))
10646             });
10647           }
10648         }
10649         return resource;
10650       }
10651     }
10652     return import_coc27.Uri.file(filepath);
10653   }
10654   execute(command, args, token, config) {
10655     var _a;
10656     let execution;
10657     if (config == null ? void 0 : config.cancelOnResourceChange) {
10658       const source = new import_vscode_languageserver_protocol20.CancellationTokenSource();
10659       token.onCancellationRequested(() => source.cancel());
10660       const inFlight = {
10661         resource: config.cancelOnResourceChange,
10662         cancel: () => source.cancel()
10663       };
10664       (_a = this.tsServerProcess) == null ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
10665       execution = this.executeImpl(command, args, {
10666         isAsync: false,
10667         token: source.token,
10668         expectsResult: true,
10669         ...config
10670       }).finally(() => {
10671         var _a2;
10672         (_a2 = this.tsServerProcess) == null ? void 0 : _a2.toCancelOnResourceChange.delete(inFlight);
10673         source.dispose();
10674       });
10675     } else {
10676       execution = this.executeImpl(command, args, {
10677         isAsync: false,
10678         token,
10679         expectsResult: true,
10680         ...config
10681       });
10682     }
10683     if (config == null ? void 0 : config.nonRecoverable) {
10684       execution.catch((err) => this.fatalError(command, err));
10685     }
10686     return execution;
10687   }
10688   fatalError(command, error) {
10689     console.error(`A non-recoverable error occured while executing tsserver command: ${command}`);
10690     if (this.state === import_coc27.ServiceStat.Running) {
10691       this.info("Killing TS Server by fatal error:", error);
10692       this.service().then((service) => {
10693         service.kill();
10694       });
10695     }
10696   }
10697   executeAsync(command, args, token) {
10698     return this.executeImpl(command, args, {
10699       isAsync: true,
10700       token,
10701       expectsResult: true
10702     });
10703   }
10704   executeWithoutWaitingForResponse(command, args) {
10705     this.executeImpl(command, args, {
10706       isAsync: false,
10707       token: void 0,
10708       expectsResult: false
10709     });
10710   }
10711   executeImpl(command, args, executeInfo) {
10712     if (this.servicePromise == null) {
10713       return Promise.resolve(void 0);
10714     }
10715     this.bufferSyncSupport.beforeCommand(command);
10716     const request = this._requestQueue.createRequest(command, args);
10717     const requestInfo = {
10718       request,
10719       expectsResponse: executeInfo.expectsResult,
10720       isAsync: executeInfo.isAsync,
10721       queueingType: getQueueingType(command, executeInfo.lowPriority)
10722     };
10723     let result;
10724     if (executeInfo.expectsResult) {
10725       result = new Promise((resolve, reject) => {
10726         this._callbacks.add(request.seq, {onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync}, executeInfo.isAsync);
10727         if (executeInfo.token) {
10728           executeInfo.token.onCancellationRequested(() => {
10729             this.tryCancelRequest(request.seq, command);
10730           });
10731         }
10732       }).catch((err) => {
10733         throw err;
10734       });
10735     }
10736     this._requestQueue.enqueue(requestInfo);
10737     this.sendNextRequests();
10738     return result;
10739   }
10740   sendNextRequests() {
10741     while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
10742       const item = this._requestQueue.dequeue();
10743       if (item) {
10744         this.sendRequest(item);
10745       }
10746     }
10747   }
10748   sendRequest(requestItem) {
10749     const serverRequest = requestItem.request;
10750     this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length);
10751     if (requestItem.expectsResponse && !requestItem.isAsync) {
10752       this._pendingResponses.add(requestItem.request.seq);
10753     }
10754     this.service().then((childProcess) => {
10755       try {
10756         childProcess.write(serverRequest);
10757       } catch (err) {
10758         const callback = this.fetchCallback(serverRequest.seq);
10759         if (callback) {
10760           callback.onError(err);
10761         }
10762       }
10763     });
10764   }
10765   tryCancelRequest(seq, command) {
10766     try {
10767       if (this._requestQueue.tryDeletePendingRequest(seq)) {
10768         this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
10769         return true;
10770       }
10771       if (this.cancellationPipeName) {
10772         this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
10773         try {
10774           import_fs4.default.writeFileSync(this.cancellationPipeName + seq, "");
10775         } catch {
10776         }
10777         return true;
10778       }
10779       this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
10780       return false;
10781     } finally {
10782       const callback = this.fetchCallback(seq);
10783       if (callback) {
10784         callback.onSuccess(new ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
10785       }
10786     }
10787   }
10788   fetchCallback(seq) {
10789     const callback = this._callbacks.fetch(seq);
10790     if (!callback) {
10791       return void 0;
10792     }
10793     this._pendingResponses.delete(seq);
10794     return callback;
10795   }
10796   dispatchMessage(message) {
10797     try {
10798       switch (message.type) {
10799         case "response":
10800           this.dispatchResponse(message);
10801           break;
10802         case "event":
10803           const event = message;
10804           if (event.event === "requestCompleted") {
10805             const seq = event.body.request_seq;
10806             const p = this._callbacks.fetch(seq);
10807             if (p) {
10808               this.tracer.traceRequestCompleted("requestCompleted", seq, p.startTime);
10809               p.onSuccess(void 0);
10810             }
10811           } else {
10812             this.tracer.traceEvent(event);
10813             this.dispatchEvent(event);
10814           }
10815           break;
10816         default:
10817           throw new Error(`Unknown message type ${message.type} received`);
10818       }
10819     } finally {
10820       this.sendNextRequests();
10821     }
10822   }
10823   dispatchResponse(response) {
10824     const callback = this.fetchCallback(response.request_seq);
10825     if (!callback) {
10826       return;
10827     }
10828     this.tracer.traceResponse(response, callback.startTime);
10829     if (response.success) {
10830       callback.onSuccess(response);
10831     } else if (response.message === "No content available.") {
10832       callback.onSuccess(ServerResponse.NoContent);
10833     } else {
10834       callback.onError(new Error(response.message));
10835     }
10836   }
10837   dispatchEvent(event) {
10838     switch (event.event) {
10839       case "syntaxDiag":
10840       case "semanticDiag":
10841       case "suggestionDiag":
10842         const diagnosticEvent = event;
10843         if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
10844           this._onDiagnosticsReceived.fire({
10845             kind: getDiagnosticsKind(event),
10846             resource: this.asUrl(diagnosticEvent.body.file),
10847             diagnostics: diagnosticEvent.body.diagnostics
10848           });
10849         }
10850         break;
10851       case "configFileDiag":
10852         this._onConfigDiagnosticsReceived.fire(event);
10853         break;
10854       case "projectLanguageServiceState":
10855         if (event.body) {
10856           this._onProjectLanguageServiceStateChanged.fire(event.body);
10857         }
10858         break;
10859       case "beginInstallTypes":
10860         if (event.body) {
10861           this._onDidBeginInstallTypings.fire(event.body);
10862         }
10863         break;
10864       case "endInstallTypes":
10865         if (event.body) {
10866           this._onDidEndInstallTypings.fire(event.body);
10867         }
10868         break;
10869       case "projectsUpdatedInBackground":
10870         const body = event.body;
10871         const resources = body.openFiles.map(import_coc27.Uri.file);
10872         this.bufferSyncSupport.getErr(resources);
10873         break;
10874       case "typesInstallerInitializationFailed":
10875         if (event.body) {
10876           this._onTypesInstallerInitializationFailed.fire(event.body);
10877         }
10878         break;
10879       case "projectLoadingStart":
10880         this.versionStatus.loading = true;
10881         break;
10882       case "projectLoadingFinish":
10883         this.versionStatus.loading = false;
10884         break;
10885     }
10886   }
10887   async getTsServerArgs(currentVersion) {
10888     const args = [];
10889     args.push("--allowLocalPluginLoads");
10890     if (this.apiVersion.gte(api_default.v250)) {
10891       args.push("--useInferredProjectPerProjectRoot");
10892     } else {
10893       args.push("--useSingleInferredProject");
10894     }
10895     if (this.apiVersion.gte(api_default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
10896       args.push("--disableAutomaticTypingAcquisition");
10897     }
10898     if (this.apiVersion.gte(api_default.v222)) {
10899       this.cancellationPipeName = getTempFile(`tscancellation-${makeRandomHexString(20)}`);
10900       args.push("--cancellationPipeName", this.cancellationPipeName + "*");
10901     }
10902     if (this.apiVersion.gte(api_default.v222)) {
10903       const isRoot = process.getuid && process.getuid() == 0;
10904       if (this._configuration.tsServerLogLevel !== TsServerLogLevel.Off && !isRoot) {
10905         const logDir = getTempDirectory();
10906         if (logDir) {
10907           this.tsServerLogFile = import_path7.default.join(logDir, `tsserver.log`);
10908           this.info("TSServer log file :", this.tsServerLogFile);
10909         } else {
10910           this.tsServerLogFile = null;
10911           this.error("Could not create TSServer log directory");
10912         }
10913         if (this.tsServerLogFile) {
10914           args.push("--logVerbosity", TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
10915           args.push("--logFile", this.tsServerLogFile);
10916         }
10917       }
10918     }
10919     if (this.apiVersion.gte(api_default.v230)) {
10920       const pluginNames = this.pluginManager.plugins.map((x) => x.name);
10921       let pluginPaths = this._configuration.tsServerPluginPaths;
10922       pluginPaths = pluginPaths.reduce((p, c) => {
10923         if (import_path7.default.isAbsolute(c)) {
10924           p.push(c);
10925         } else {
10926           let roots = import_coc27.workspace.workspaceFolders.map((o) => import_coc27.Uri.parse(o.uri).fsPath);
10927           p.push(...roots.map((r) => import_path7.default.join(r, c)));
10928         }
10929         return p;
10930       }, []);
10931       if (pluginNames.length) {
10932         const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path;
10933         args.push("--globalPlugins", pluginNames.join(","));
10934         for (const plugin of this.pluginManager.plugins) {
10935           if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
10936             pluginPaths.push(plugin.path);
10937           }
10938         }
10939       }
10940       if (pluginPaths.length) {
10941         args.push("--pluginProbeLocations", pluginPaths.join(","));
10942       }
10943     }
10944     if (this._configuration.locale) {
10945       args.push("--locale", this._configuration.locale);
10946     }
10947     if (this._configuration.typingsCacheLocation) {
10948       args.push("--globalTypingsCacheLocation", `"${this._configuration.typingsCacheLocation}"`);
10949     }
10950     if (this.apiVersion.gte(api_default.v234)) {
10951       let {npmLocation} = this._configuration;
10952       if (npmLocation) {
10953         this.logger.info(`using npm from ${npmLocation}`);
10954         args.push("--npmLocation", `"${npmLocation}"`);
10955       }
10956     }
10957     if (this.apiVersion.gte(api_default.v291)) {
10958       args.push("--noGetErrOnBackgroundUpdate");
10959     }
10960     if (this.apiVersion.gte(api_default.v345)) {
10961       args.push("--validateDefaultNpmLocation");
10962     }
10963     return args;
10964   }
10965   getProjectRootPath(uri) {
10966     let root = import_coc27.workspace.cwd;
10967     let u = import_coc27.Uri.parse(uri);
10968     if (u.scheme !== "file")
10969       return void 0;
10970     let folder = import_coc27.workspace.getWorkspaceFolder(uri);
10971     if (folder) {
10972       root = import_coc27.Uri.parse(folder.uri).fsPath;
10973     } else {
10974       let filepath = import_coc27.Uri.parse(uri).fsPath;
10975       if (!filepath.startsWith(root)) {
10976         root = import_path7.default.dirname(filepath);
10977       }
10978     }
10979     if (root == import_os2.default.homedir())
10980       return void 0;
10981     return root;
10982   }
10983   configurePlugin(pluginName, configuration) {
10984     if (this.apiVersion.gte(api_default.v314)) {
10985       if (!this.servicePromise)
10986         return;
10987       this.servicePromise.then(() => {
10988         this.executeWithoutWaitingForResponse("configurePlugin", {pluginName, configuration});
10989       });
10990     }
10991   }
10992   interruptGetErr(f) {
10993     return this.bufferSyncSupport.interuptGetErr(f);
10994   }
10995   cancelInflightRequestsForResource(resource) {
10996     if (this.state !== import_coc27.ServiceStat.Running || !this.tsServerProcess) {
10997       return;
10998     }
10999     for (const request of this.tsServerProcess.toCancelOnResourceChange) {
11000       if (request.resource.toString() === resource.toString()) {
11001         request.cancel();
11002       }
11003     }
11004   }
11005 };
11006 var typescriptServiceClient_default = TypeScriptServiceClient;
11007 function getDiagnosticsKind(event) {
11008   switch (event.event) {
11009     case "syntaxDiag":
11010       return DiagnosticKind.Syntax;
11011     case "semanticDiag":
11012       return DiagnosticKind.Semantic;
11013     case "suggestionDiag":
11014       return DiagnosticKind.Suggestion;
11015   }
11016   throw new Error("Unknown dignostics kind");
11017 }
11018 var fenceCommands = new Set(["change", "close", "open"]);
11019 function getQueueingType(command, lowPriority) {
11020   if (fenceCommands.has(command)) {
11021     return RequestQueueingType.Fence;
11022   }
11023   return lowPriority ? RequestQueueingType.LowPriority : RequestQueueingType.Normal;
11024 }
11025
11026 // src/server/utils/languageDescription.ts
11027 var DiagnosticLanguage;
11028 (function(DiagnosticLanguage2) {
11029   DiagnosticLanguage2[DiagnosticLanguage2["JavaScript"] = 0] = "JavaScript";
11030   DiagnosticLanguage2[DiagnosticLanguage2["TypeScript"] = 1] = "TypeScript";
11031 })(DiagnosticLanguage || (DiagnosticLanguage = {}));
11032 var standardLanguageDescriptions = [
11033   {
11034     id: "typescript",
11035     diagnosticSource: "ts",
11036     diagnosticOwner: "typescript",
11037     modeIds: [
11038       typescript,
11039       typescriptreact,
11040       typescripttsx,
11041       typescriptjsx
11042     ],
11043     diagnosticLanguage: 1,
11044     configFile: "tsconfig.json",
11045     configFilePattern: /^tsconfig(\..*)?\.json$/gi
11046   },
11047   {
11048     id: "javascript",
11049     diagnosticSource: "ts",
11050     diagnosticOwner: "typescript",
11051     modeIds: [javascript, javascriptreact, javascriptjsx],
11052     diagnosticLanguage: 0,
11053     configFile: "jsconfig.json",
11054     configFilePattern: /^jsconfig(\..*)?\.json$/gi
11055   }
11056 ];
11057
11058 // src/server/utils/typingsStatus.ts
11059 var import_coc28 = __toModule(require("coc.nvim"));
11060 var import_vscode_languageserver_protocol21 = __toModule(require_main3());
11061 var typingsInstallTimeout = 30 * 1e3;
11062 var TypingsStatus = class {
11063   constructor(client) {
11064     this._acquiringTypings = Object.create({});
11065     this._subscriptions = [];
11066     this._client = client;
11067     this._subscriptions.push(this._client.onDidBeginInstallTypings((event) => this.onBeginInstallTypings(event.eventId)));
11068     this._subscriptions.push(this._client.onDidEndInstallTypings((event) => this.onEndInstallTypings(event.eventId)));
11069   }
11070   dispose() {
11071     this._subscriptions.forEach((x) => x.dispose());
11072     for (const eventId of Object.keys(this._acquiringTypings)) {
11073       clearTimeout(this._acquiringTypings[eventId]);
11074     }
11075   }
11076   get isAcquiringTypings() {
11077     return Object.keys(this._acquiringTypings).length > 0;
11078   }
11079   onBeginInstallTypings(eventId) {
11080     if (this._acquiringTypings[eventId]) {
11081       return;
11082     }
11083     this._acquiringTypings[eventId] = setTimeout(() => {
11084       this.onEndInstallTypings(eventId);
11085     }, typingsInstallTimeout);
11086   }
11087   onEndInstallTypings(eventId) {
11088     const timer = this._acquiringTypings[eventId];
11089     if (timer) {
11090       clearTimeout(timer);
11091     }
11092     delete this._acquiringTypings[eventId];
11093   }
11094 };
11095 var typingsStatus_default = TypingsStatus;
11096 var AtaProgressReporter = class {
11097   constructor(client) {
11098     this._promises = new Map();
11099     this._invalid = false;
11100     this.statusItem = import_coc28.window.createStatusBarItem(10, {progress: true});
11101     const disposables = [];
11102     disposables.push(client.onDidBeginInstallTypings((e) => this._onBegin(e.eventId)));
11103     disposables.push(client.onDidEndInstallTypings((e) => this._onEndOrTimeout(e.eventId)));
11104     disposables.push(client.onTypesInstallerInitializationFailed((_) => this.onTypesInstallerInitializationFailed()));
11105     this._disposable = import_vscode_languageserver_protocol21.Disposable.create(() => {
11106       disposables.forEach((disposable) => {
11107         disposable.dispose();
11108       });
11109     });
11110   }
11111   dispose() {
11112     this._disposable.dispose();
11113     this._promises.forEach((value) => value());
11114   }
11115   _onBegin(eventId) {
11116     const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
11117     new Promise((resolve) => {
11118       this._promises.set(eventId, () => {
11119         clearTimeout(handle);
11120         resolve();
11121       });
11122     });
11123     this.statusItem.text = "Fetching data for better TypeScript IntelliSense";
11124     this.statusItem.show();
11125   }
11126   _onEndOrTimeout(eventId) {
11127     this.statusItem.hide();
11128     const resolve = this._promises.get(eventId);
11129     if (resolve) {
11130       this._promises.delete(eventId);
11131       resolve();
11132     }
11133   }
11134   onTypesInstallerInitializationFailed() {
11135     this.statusItem.hide();
11136     if (!this._invalid) {
11137       import_coc28.window.showMessage("Could not install typings files for JavaScript language features. Please ensure that NPM is installed", "error");
11138     }
11139     this._invalid = true;
11140   }
11141 };
11142
11143 // src/server/typescriptServiceClientHost.ts
11144 var styleCheckDiagnostics = [
11145   6133,
11146   6138,
11147   7027,
11148   7028,
11149   7029,
11150   7030
11151 ];
11152 var TypeScriptServiceClientHost = class {
11153   constructor(descriptions, pluginManager) {
11154     this.languagePerId = new Map();
11155     this.disposables = [];
11156     this.reportStyleCheckAsWarnings = true;
11157     let timer;
11158     const handleProjectChange = () => {
11159       if (timer)
11160         clearTimeout(timer);
11161       timer = setTimeout(() => {
11162         this.triggerAllDiagnostics();
11163       }, 1500);
11164     };
11165     const configFileWatcher = import_coc29.workspace.createFileSystemWatcher("**/[tj]sconfig.json");
11166     this.disposables.push(configFileWatcher);
11167     configFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
11168     configFileWatcher.onDidDelete(this.reloadProjects, this, this.disposables);
11169     configFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
11170     const packageFileWatcher = import_coc29.workspace.createFileSystemWatcher("**/package.json");
11171     packageFileWatcher.onDidCreate(this.reloadProjects, this, this.disposables);
11172     packageFileWatcher.onDidChange(handleProjectChange, this, this.disposables);
11173     const allModeIds = this.getAllModeIds(descriptions, pluginManager);
11174     this.client = new typescriptServiceClient_default(pluginManager, allModeIds);
11175     this.disposables.push(this.client);
11176     this.client.onDiagnosticsReceived(({kind, resource, diagnostics}) => {
11177       this.diagnosticsReceived(kind, resource, diagnostics).catch((e) => {
11178         console.error(e);
11179       });
11180     }, null, this.disposables);
11181     this.disposables.push(new watchBuild_default(this.client));
11182     this.disposables.push(import_coc29.languages.registerWorkspaceSymbolProvider(new workspaceSymbols_default(this.client, allModeIds)));
11183     this.client.onConfigDiagnosticsReceived((diag) => {
11184       let {body} = diag;
11185       if (body) {
11186         let {configFile, diagnostics} = body;
11187         let uri = import_coc29.Uri.file(configFile);
11188         if (diagnostics.length == 0) {
11189           this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), []);
11190         } else {
11191           let diagnosticList = diagnostics.map((o) => {
11192             let {text, code, category, start, end} = o;
11193             let range;
11194             if (!start || !end) {
11195               range = import_vscode_languageserver_protocol22.Range.create(import_vscode_languageserver_protocol22.Position.create(0, 0), import_vscode_languageserver_protocol22.Position.create(0, 1));
11196             } else {
11197               range = import_vscode_languageserver_protocol22.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
11198             }
11199             let severity = category == "error" ? import_vscode_languageserver_protocol22.DiagnosticSeverity.Error : import_vscode_languageserver_protocol22.DiagnosticSeverity.Warning;
11200             return import_vscode_languageserver_protocol22.Diagnostic.create(range, text, severity, code);
11201           });
11202           this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
11203         }
11204       }
11205     }, null, this.disposables);
11206     this.typingsStatus = new typingsStatus_default(this.client);
11207     this.ataProgressReporter = new AtaProgressReporter(this.client);
11208     this.fileConfigurationManager = new fileConfigurationManager_default(this.client);
11209     for (const description of descriptions) {
11210       const manager = new languageProvider_default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
11211       this.languagePerId.set(description.id, manager);
11212     }
11213     const languageIds = new Set();
11214     for (const plugin of pluginManager.plugins) {
11215       if (plugin.configNamespace && plugin.languages.length) {
11216         this.registerExtensionLanguageProvider({
11217           id: plugin.configNamespace,
11218           modeIds: Array.from(plugin.languages),
11219           diagnosticSource: "ts-plugin",
11220           diagnosticLanguage: DiagnosticLanguage.TypeScript,
11221           diagnosticOwner: "typescript",
11222           isExternal: true
11223         });
11224       } else {
11225         for (const language of plugin.languages) {
11226           languageIds.add(language);
11227         }
11228       }
11229     }
11230     if (languageIds.size) {
11231       this.registerExtensionLanguageProvider({
11232         id: "typescript-plugins",
11233         modeIds: Array.from(languageIds.values()),
11234         diagnosticSource: "ts-plugin",
11235         diagnosticLanguage: DiagnosticLanguage.TypeScript,
11236         diagnosticOwner: "typescript",
11237         isExternal: true
11238       });
11239     }
11240     this.client.ensureServiceStarted();
11241     this.client.onTsServerStarted(() => {
11242       this.triggerAllDiagnostics();
11243     });
11244     import_coc29.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
11245     this.configurationChanged();
11246   }
11247   registerExtensionLanguageProvider(description) {
11248     const manager = new languageProvider_default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
11249     this.languagePerId.set(description.id, manager);
11250   }
11251   dispose() {
11252     import_coc29.disposeAll(this.disposables);
11253     for (let language of this.languagePerId.values()) {
11254       language.dispose();
11255     }
11256     this.languagePerId.clear();
11257     this.fileConfigurationManager.dispose();
11258     this.typingsStatus.dispose();
11259     this.ataProgressReporter.dispose();
11260   }
11261   reset() {
11262     this.fileConfigurationManager.reset();
11263   }
11264   get serviceClient() {
11265     return this.client;
11266   }
11267   reloadProjects() {
11268     this.client.diagnosticsManager.reInitialize();
11269     this.client.execute("reloadProjects", null, import_vscode_languageserver_protocol22.CancellationToken.None);
11270     this.triggerAllDiagnostics();
11271   }
11272   getProvider(languageId) {
11273     return this.languagePerId.get(languageId);
11274   }
11275   configurationChanged() {
11276     const config = import_coc29.workspace.getConfiguration("tsserver");
11277     this.reportStyleCheckAsWarnings = config.get("reportStyleChecksAsWarnings", true);
11278   }
11279   async findLanguage(uri) {
11280     try {
11281       let doc = this.client.getDocument(uri);
11282       if (!doc)
11283         return void 0;
11284       let languages4 = Array.from(this.languagePerId.values());
11285       return languages4.find((language) => language.handles(uri, doc.textDocument));
11286     } catch {
11287       return void 0;
11288     }
11289   }
11290   async handles(doc) {
11291     let languages4 = Array.from(this.languagePerId.values());
11292     let idx = languages4.findIndex((language) => language.handles(doc.uri, doc));
11293     if (idx != -1)
11294       return true;
11295     return this.client.bufferSyncSupport.handles(doc.uri);
11296   }
11297   triggerAllDiagnostics() {
11298     for (const language of this.languagePerId.values()) {
11299       language.triggerAllDiagnostics();
11300     }
11301   }
11302   async diagnosticsReceived(kind, resource, diagnostics) {
11303     const language = await this.findLanguage(resource.toString());
11304     if (language) {
11305       language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
11306     }
11307   }
11308   createMarkerDatas(diagnostics) {
11309     return diagnostics.map((tsDiag) => this.tsDiagnosticToLspDiagnostic(tsDiag));
11310   }
11311   tsDiagnosticToLspDiagnostic(diagnostic) {
11312     const {start, end, text} = diagnostic;
11313     const range = {
11314       start: Position.fromLocation(start),
11315       end: Position.fromLocation(end)
11316     };
11317     let relatedInformation;
11318     if (diagnostic.relatedInformation) {
11319       relatedInformation = diagnostic.relatedInformation.map((o) => {
11320         let {span, message} = o;
11321         return {
11322           location: Location2.fromTextSpan(this.client.toResource(span.file), span),
11323           message
11324         };
11325       });
11326     }
11327     return {
11328       range,
11329       message: text,
11330       code: diagnostic.code ? diagnostic.code : null,
11331       severity: this.getDiagnosticSeverity(diagnostic),
11332       reportUnnecessary: diagnostic.reportsUnnecessary,
11333       source: diagnostic.source || "tsserver",
11334       relatedInformation
11335     };
11336   }
11337   getDiagnosticSeverity(diagnostic) {
11338     if (this.reportStyleCheckAsWarnings && this.isStyleCheckDiagnostic(diagnostic.code) && diagnostic.category === DiagnosticCategory.error) {
11339       return import_vscode_languageserver_protocol22.DiagnosticSeverity.Warning;
11340     }
11341     switch (diagnostic.category) {
11342       case DiagnosticCategory.error:
11343         return import_vscode_languageserver_protocol22.DiagnosticSeverity.Error;
11344       case DiagnosticCategory.warning:
11345         return import_vscode_languageserver_protocol22.DiagnosticSeverity.Warning;
11346       case DiagnosticCategory.suggestion:
11347         return import_vscode_languageserver_protocol22.DiagnosticSeverity.Information;
11348       default:
11349         return import_vscode_languageserver_protocol22.DiagnosticSeverity.Error;
11350     }
11351   }
11352   isStyleCheckDiagnostic(code) {
11353     return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
11354   }
11355   getAllModeIds(descriptions, pluginManager) {
11356     const allModeIds = flatten([
11357       ...descriptions.map((x) => x.modeIds),
11358       ...pluginManager.plugins.map((x) => x.languages)
11359     ]);
11360     return allModeIds;
11361   }
11362 };
11363 var typescriptServiceClientHost_default = TypeScriptServiceClientHost;
11364
11365 // src/server/index.ts
11366 var TsserverService = class {
11367   constructor(pluginManager) {
11368     this.pluginManager = pluginManager;
11369     this.id = "tsserver";
11370     this.name = "tsserver";
11371     this.state = import_coc30.ServiceStat.Initial;
11372     this._onDidServiceReady = new import_vscode_languageserver_protocol23.Emitter();
11373     this.onServiceReady = this._onDidServiceReady.event;
11374     this.disposables = [];
11375     this.descriptions = [];
11376     const config = import_coc30.workspace.getConfiguration("tsserver");
11377     const enableJavascript = !!config.get("enableJavascript");
11378     this.enable = config.get("enable");
11379     this.descriptions = standardLanguageDescriptions.filter((o) => {
11380       return enableJavascript ? true : o.id != "javascript";
11381     });
11382     this.selector = this.descriptions.reduce((arr, c) => {
11383       return arr.concat(c.modeIds);
11384     }, []);
11385   }
11386   get config() {
11387     return import_coc30.workspace.getConfiguration("tsserver");
11388   }
11389   getClientHost() {
11390     if (this.state == import_coc30.ServiceStat.Running)
11391       return Promise.resolve(this.clientHost);
11392     this.start();
11393     return new Promise((resolve, reject) => {
11394       let timer = setTimeout(() => {
11395         reject(new Error(`Server not started after 5s`));
11396       }, 5e3);
11397       let disposable = this.onServiceReady(() => {
11398         clearTimeout(timer);
11399         disposable.dispose();
11400         resolve(this.clientHost);
11401       });
11402     });
11403   }
11404   start() {
11405     if (this.clientHost)
11406       return;
11407     this.state = import_coc30.ServiceStat.Starting;
11408     this.clientHost = new typescriptServiceClientHost_default(this.descriptions, this.pluginManager);
11409     this.disposables.push(this.clientHost);
11410     let client = this.clientHost.serviceClient;
11411     return new Promise((resolve) => {
11412       let started = false;
11413       client.onTsServerStarted(() => {
11414         Object.defineProperty(this, "state", {
11415           get: () => {
11416             return this.clientHost.serviceClient.state;
11417           }
11418         });
11419         this._onDidServiceReady.fire(void 0);
11420         if (!started) {
11421           started = true;
11422           resolve();
11423         }
11424       });
11425     });
11426   }
11427   dispose() {
11428     import_coc30.disposeAll(this.disposables);
11429   }
11430   async restart() {
11431     if (!this.clientHost)
11432       return;
11433     let client = this.clientHost.serviceClient;
11434     await client.restartTsServer();
11435   }
11436   async stop() {
11437     if (!this.clientHost)
11438       return;
11439     this.clientHost.reset();
11440     let client = this.clientHost.serviceClient;
11441     await client.stop();
11442     return;
11443   }
11444 };
11445 var server_default = TsserverService;
11446
11447 // src/utils/plugins.ts
11448 var import_coc31 = __toModule(require("coc.nvim"));
11449 var import_vscode_languageserver_protocol24 = __toModule(require_main3());
11450 var TypeScriptServerPlugin;
11451 (function(TypeScriptServerPlugin2) {
11452   function equals2(a, b) {
11453     return a.path === b.path && a.name === b.name && a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions && equals(a.languages, b.languages);
11454   }
11455   TypeScriptServerPlugin2.equals = equals2;
11456 })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
11457 var PluginManager = class {
11458   constructor() {
11459     this._pluginConfigurations = new Map();
11460     this._disposables = [];
11461     this._onDidUpdatePlugins = this._register(new import_vscode_languageserver_protocol24.Emitter());
11462     this.onDidChangePlugins = this._onDidUpdatePlugins.event;
11463     this._onDidUpdateConfig = this._register(new import_vscode_languageserver_protocol24.Emitter());
11464     this.onDidUpdateConfig = this._onDidUpdateConfig.event;
11465     let loadPlugins = () => {
11466       if (!this._plugins) {
11467         return;
11468       }
11469       const newPlugins = this.readPlugins();
11470       if (!equals(flatten(Array.from(this._plugins.values())), flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
11471         this._plugins = newPlugins;
11472         this._onDidUpdatePlugins.fire(this);
11473       }
11474     };
11475     import_coc31.extensions.onDidActiveExtension(loadPlugins, void 0, this._disposables);
11476     import_coc31.extensions.onDidUnloadExtension(loadPlugins, void 0, this._disposables);
11477   }
11478   dispose() {
11479     import_coc31.disposeAll(this._disposables);
11480   }
11481   get plugins() {
11482     if (!this._plugins) {
11483       this._plugins = this.readPlugins();
11484     }
11485     return flatten(Array.from(this._plugins.values()));
11486   }
11487   _register(value) {
11488     this._disposables.push(value);
11489     return value;
11490   }
11491   setConfiguration(pluginId, config) {
11492     this._pluginConfigurations.set(pluginId, config);
11493     this._onDidUpdateConfig.fire({pluginId, config});
11494   }
11495   configurations() {
11496     return this._pluginConfigurations.entries();
11497   }
11498   readPlugins() {
11499     const pluginMap = new Map();
11500     for (const extension of import_coc31.extensions.all) {
11501       const pack = extension.packageJSON;
11502       if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
11503         const plugins = [];
11504         for (const plugin of pack.contributes.typescriptServerPlugins) {
11505           plugins.push({
11506             name: plugin.name,
11507             enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
11508             path: extension.extensionPath,
11509             languages: Array.isArray(plugin.languages) ? plugin.languages : []
11510           });
11511         }
11512         if (plugins.length) {
11513           pluginMap.set(extension.id, plugins);
11514         }
11515       }
11516     }
11517     return pluginMap;
11518   }
11519 };
11520
11521 // src/index.ts
11522 async function activate(context) {
11523   let {subscriptions, logger} = context;
11524   const config = import_coc32.workspace.getConfiguration().get("tsserver", {});
11525   if (!config.enable)
11526     return;
11527   const pluginManager = new PluginManager();
11528   const service = new server_default(pluginManager);
11529   function registCommand2(cmd) {
11530     let {id, execute} = cmd;
11531     subscriptions.push(import_coc32.commands.registerCommand(id, execute, cmd));
11532   }
11533   registCommand2(new ConfigurePluginCommand(pluginManager));
11534   registCommand2(new AutoFixCommand(service));
11535   registCommand2(new ReloadProjectsCommand(service));
11536   registCommand2(new OpenTsServerLogCommand(service));
11537   registCommand2(new TypeScriptGoToProjectConfigCommand(service));
11538   registCommand2(new OrganizeImportsCommand(service));
11539   registCommand2({
11540     id: "tsserver.restart",
11541     execute: () => {
11542       service.stop().then(() => {
11543         setTimeout(() => {
11544           service.restart();
11545         }, 100);
11546       });
11547     }
11548   });
11549   service.start().then(() => {
11550     subscriptions.push(import_coc32.services.regist(service));
11551   }, (e) => {
11552     logger.error(`Error on service start:`, e);
11553   });
11554   return {
11555     configurePlugin: (pluginId, configuration) => {
11556       pluginManager.setConfiguration(pluginId, configuration);
11557     }
11558   };
11559 }
11560 //# sourceMappingURL=index.js.map