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) => () => {
10 module2 = {exports: {}};
11 callback(module2.exports, module2);
13 return module2.exports;
15 var __export = (target, all) => {
16 __markAsModule(target);
18 __defProp(target, name, {get: all[name], enumerable: true});
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});
29 var __toModule = (module2) => {
30 if (module2 && module2.__esModule)
32 return __exportStar(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", {value: module2, enumerable: true}), module2);
35 // node_modules/vscode-jsonrpc/lib/is.js
36 var require_is = __commonJS((exports2) => {
38 Object.defineProperty(exports2, "__esModule", {value: true});
39 function boolean2(value) {
40 return value === true || value === false;
42 exports2.boolean = boolean2;
43 function string2(value) {
44 return typeof value === "string" || value instanceof String;
46 exports2.string = string2;
47 function number(value) {
48 return typeof value === "number" || value instanceof Number;
50 exports2.number = number;
51 function error(value) {
52 return value instanceof Error;
54 exports2.error = error;
55 function func(value) {
56 return typeof value === "function";
59 function array(value) {
60 return Array.isArray(value);
62 exports2.array = array;
63 function stringArray(value) {
64 return array(value) && value.every((elem) => string2(elem));
66 exports2.stringArray = stringArray;
69 // node_modules/vscode-jsonrpc/lib/messages.js
70 var require_messages = __commonJS((exports2) => {
72 Object.defineProperty(exports2, "__esModule", {value: true});
73 var is2 = require_is();
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) {
93 this.code = is2.number(code) ? code : ErrorCodes.UnknownErrorCode;
95 Object.setPrototypeOf(this, ResponseError.prototype);
100 message: this.message,
105 exports2.ResponseError = ResponseError;
106 var AbstractMessageType = class {
107 constructor(_method, _numberOfParams) {
108 this._method = _method;
109 this._numberOfParams = _numberOfParams;
114 get numberOfParams() {
115 return this._numberOfParams;
118 exports2.AbstractMessageType = AbstractMessageType;
119 var RequestType0 = class extends AbstractMessageType {
120 constructor(method) {
124 exports2.RequestType0 = RequestType0;
125 var RequestType = class extends AbstractMessageType {
126 constructor(method) {
130 exports2.RequestType = RequestType;
131 var RequestType1 = class extends AbstractMessageType {
132 constructor(method) {
136 exports2.RequestType1 = RequestType1;
137 var RequestType2 = class extends AbstractMessageType {
138 constructor(method) {
142 exports2.RequestType2 = RequestType2;
143 var RequestType3 = class extends AbstractMessageType {
144 constructor(method) {
148 exports2.RequestType3 = RequestType3;
149 var RequestType4 = class extends AbstractMessageType {
150 constructor(method) {
154 exports2.RequestType4 = RequestType4;
155 var RequestType5 = class extends AbstractMessageType {
156 constructor(method) {
160 exports2.RequestType5 = RequestType5;
161 var RequestType6 = class extends AbstractMessageType {
162 constructor(method) {
166 exports2.RequestType6 = RequestType6;
167 var RequestType7 = class extends AbstractMessageType {
168 constructor(method) {
172 exports2.RequestType7 = RequestType7;
173 var RequestType8 = class extends AbstractMessageType {
174 constructor(method) {
178 exports2.RequestType8 = RequestType8;
179 var RequestType9 = class extends AbstractMessageType {
180 constructor(method) {
184 exports2.RequestType9 = RequestType9;
185 var NotificationType = class extends AbstractMessageType {
186 constructor(method) {
191 exports2.NotificationType = NotificationType;
192 var NotificationType0 = class extends AbstractMessageType {
193 constructor(method) {
197 exports2.NotificationType0 = NotificationType0;
198 var NotificationType1 = class extends AbstractMessageType {
199 constructor(method) {
203 exports2.NotificationType1 = NotificationType1;
204 var NotificationType2 = class extends AbstractMessageType {
205 constructor(method) {
209 exports2.NotificationType2 = NotificationType2;
210 var NotificationType3 = class extends AbstractMessageType {
211 constructor(method) {
215 exports2.NotificationType3 = NotificationType3;
216 var NotificationType4 = class extends AbstractMessageType {
217 constructor(method) {
221 exports2.NotificationType4 = NotificationType4;
222 var NotificationType5 = class extends AbstractMessageType {
223 constructor(method) {
227 exports2.NotificationType5 = NotificationType5;
228 var NotificationType6 = class extends AbstractMessageType {
229 constructor(method) {
233 exports2.NotificationType6 = NotificationType6;
234 var NotificationType7 = class extends AbstractMessageType {
235 constructor(method) {
239 exports2.NotificationType7 = NotificationType7;
240 var NotificationType8 = class extends AbstractMessageType {
241 constructor(method) {
245 exports2.NotificationType8 = NotificationType8;
246 var NotificationType9 = class extends AbstractMessageType {
247 constructor(method) {
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));
256 exports2.isRequestMessage = isRequestMessage;
257 function isNotificationMessage(message) {
258 let candidate = message;
259 return candidate && is2.string(candidate.method) && message.id === void 0;
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);
266 exports2.isResponseMessage = isResponseMessage;
269 // node_modules/vscode-jsonrpc/lib/events.js
270 var require_events = __commonJS((exports2) => {
272 Object.defineProperty(exports2, "__esModule", {value: true});
274 (function(Disposable13) {
275 function create(func) {
280 Disposable13.create = create;
281 })(Disposable12 = exports2.Disposable || (exports2.Disposable = {}));
284 const _disposable = {dispose() {
286 Event6.None = function() {
289 })(Event5 = exports2.Event || (exports2.Event = {}));
290 var CallbackList = class {
291 add(callback, context = null, bucket) {
292 if (!this._callbacks) {
293 this._callbacks = [];
296 this._callbacks.push(callback);
297 this._contexts.push(context);
298 if (Array.isArray(bucket)) {
299 bucket.push({dispose: () => this.remove(callback, context)});
302 remove(callback, context = null) {
303 if (!this._callbacks) {
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);
314 foundCallbackWithDifferentContext = true;
318 if (foundCallbackWithDifferentContext) {
319 throw new Error("When adding a listener with a context, you should remove it with the same context");
323 if (!this._callbacks) {
326 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
327 for (var i = 0, len = callbacks.length; i < len; i++) {
329 ret.push(callbacks[i].apply(contexts[i], args));
337 return !this._callbacks || this._callbacks.length === 0;
340 this._callbacks = void 0;
341 this._contexts = void 0;
344 var Emitter6 = class {
345 constructor(_options) {
346 this._options = _options;
350 this._event = (listener, thisArgs, disposables) => {
351 if (!this._callbacks) {
352 this._callbacks = new CallbackList();
354 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
355 this._options.onFirstListenerAdd(this);
357 this._callbacks.add(listener, thisArgs);
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);
368 if (Array.isArray(disposables)) {
369 disposables.push(result);
377 if (this._callbacks) {
378 this._callbacks.invoke.call(this._callbacks, event);
382 if (this._callbacks) {
383 this._callbacks.dispose();
384 this._callbacks = void 0;
388 exports2.Emitter = Emitter6;
389 Emitter6._noop = function() {
393 // node_modules/vscode-jsonrpc/lib/messageReader.js
394 var require_messageReader = __commonJS((exports2) => {
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];
403 var MessageBuffer = class {
404 constructor(encoding = "utf8") {
405 this.encoding = encoding;
407 this.buffer = Buffer.allocUnsafe(DefaultSize2);
410 var toAppend = chunk;
411 if (typeof chunk === "string") {
413 var bufferLen = Buffer.byteLength(str, this.encoding);
414 toAppend = Buffer.allocUnsafe(bufferLen);
415 toAppend.write(str, 0, bufferLen, this.encoding);
417 if (this.buffer.length - this.index >= toAppend.length) {
418 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
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);
425 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
428 this.index += toAppend.length;
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)) {
436 if (current + 3 >= this.index) {
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(":");
444 throw new Error("Message header must separate key and value using :");
446 let key = header.substr(0, index);
447 let value = header.substr(index + 1).trim();
450 let nextStart = current + 4;
451 this.buffer = this.buffer.slice(nextStart);
452 this.index = this.index - nextStart;
455 tryReadContent(length) {
456 if (this.index < length) {
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;
465 get numberOfBytes() {
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);
475 MessageReader2.is = is2;
476 })(MessageReader = exports2.MessageReader || (exports2.MessageReader = {}));
477 var AbstractMessageReader = class {
479 this.errorEmitter = new events_1.Emitter();
480 this.closeEmitter = new events_1.Emitter();
481 this.partialMessageEmitter = new events_1.Emitter();
484 this.errorEmitter.dispose();
485 this.closeEmitter.dispose();
488 return this.errorEmitter.event;
491 this.errorEmitter.fire(this.asError(error));
494 return this.closeEmitter.event;
497 this.closeEmitter.fire(void 0);
499 get onPartialMessage() {
500 return this.partialMessageEmitter.event;
502 firePartialMessage(info) {
503 this.partialMessageEmitter.fire(info);
506 if (error instanceof Error) {
509 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
513 exports2.AbstractMessageReader = AbstractMessageReader;
514 var StreamMessageReader = class extends AbstractMessageReader {
515 constructor(readable, encoding = "utf8") {
517 this.readable = readable;
518 this.buffer = new MessageBuffer(encoding);
519 this._partialMessageTimeout = 1e4;
521 set partialMessageTimeout(timeout) {
522 this._partialMessageTimeout = timeout;
524 get partialMessageTimeout() {
525 return this._partialMessageTimeout;
528 this.nextMessageLength = -1;
529 this.messageToken = 0;
530 this.partialMessageTimer = void 0;
531 this.callback = callback;
532 this.readable.on("data", (data) => {
535 this.readable.on("error", (error) => this.fireError(error));
536 this.readable.on("close", () => this.fireClose());
539 this.buffer.append(data);
541 if (this.nextMessageLength === -1) {
542 let headers = this.buffer.tryReadHeaders();
546 let contentLength = headers["Content-Length"];
547 if (!contentLength) {
548 throw new Error("Header must provide a Content-Length property.");
550 let length = parseInt(contentLength);
552 throw new Error("Content-Length value must be a number.");
554 this.nextMessageLength = length;
556 var msg = this.buffer.tryReadContent(this.nextMessageLength);
558 this.setPartialMessageTimer();
561 this.clearPartialMessageTimer();
562 this.nextMessageLength = -1;
564 var json = JSON.parse(msg);
568 clearPartialMessageTimer() {
569 if (this.partialMessageTimer) {
570 clearTimeout(this.partialMessageTimer);
571 this.partialMessageTimer = void 0;
574 setPartialMessageTimer() {
575 this.clearPartialMessageTimer();
576 if (this._partialMessageTimeout <= 0) {
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();
585 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
588 exports2.StreamMessageReader = StreamMessageReader;
589 var IPCMessageReader = class extends AbstractMessageReader {
590 constructor(process2) {
592 this.process = process2;
593 let eventEmitter = this.process;
594 eventEmitter.on("error", (error) => this.fireError(error));
595 eventEmitter.on("close", () => this.fireClose());
598 this.process.on("message", callback);
601 exports2.IPCMessageReader = IPCMessageReader;
602 var SocketMessageReader = class extends StreamMessageReader {
603 constructor(socket, encoding = "utf-8") {
604 super(socket, encoding);
607 exports2.SocketMessageReader = SocketMessageReader;
610 // node_modules/vscode-jsonrpc/lib/messageWriter.js
611 var require_messageWriter = __commonJS((exports2) => {
613 Object.defineProperty(exports2, "__esModule", {value: true});
614 var events_1 = require_events();
615 var Is = require_is();
616 var ContentLength2 = "Content-Length: ";
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);
624 MessageWriter2.is = is2;
625 })(MessageWriter = exports2.MessageWriter || (exports2.MessageWriter = {}));
626 var AbstractMessageWriter = class {
628 this.errorEmitter = new events_1.Emitter();
629 this.closeEmitter = new events_1.Emitter();
632 this.errorEmitter.dispose();
633 this.closeEmitter.dispose();
636 return this.errorEmitter.event;
638 fireError(error, message, count) {
639 this.errorEmitter.fire([this.asError(error), message, count]);
642 return this.closeEmitter.event;
645 this.closeEmitter.fire(void 0);
648 if (error instanceof Error) {
651 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
655 exports2.AbstractMessageWriter = AbstractMessageWriter;
656 var StreamMessageWriter = class extends AbstractMessageWriter {
657 constructor(writable, encoding = "utf8") {
659 this.writable = writable;
660 this.encoding = encoding;
662 this.writable.on("error", (error) => this.fireError(error));
663 this.writable.on("close", () => this.fireClose());
666 let json = JSON.stringify(msg);
667 let contentLength = Buffer.byteLength(json, this.encoding);
670 contentLength.toString(),
675 this.writable.write(headers.join(""), "ascii");
676 this.writable.write(json, this.encoding);
680 this.fireError(error, msg, this.errorCount);
684 exports2.StreamMessageWriter = StreamMessageWriter;
685 var IPCMessageWriter = class extends AbstractMessageWriter {
686 constructor(process2) {
688 this.process = process2;
691 this.sending = false;
692 let eventEmitter = this.process;
693 eventEmitter.on("error", (error) => this.fireError(error));
694 eventEmitter.on("close", () => this.fireClose);
697 if (!this.sending && this.queue.length === 0) {
698 this.doWriteMessage(msg);
700 this.queue.push(msg);
703 doWriteMessage(msg) {
705 if (this.process.send) {
707 this.process.send(msg, void 0, void 0, (error) => {
708 this.sending = false;
711 this.fireError(error, msg, this.errorCount);
715 if (this.queue.length > 0) {
716 this.doWriteMessage(this.queue.shift());
722 this.fireError(error, msg, this.errorCount);
726 exports2.IPCMessageWriter = IPCMessageWriter;
727 var SocketMessageWriter = class extends AbstractMessageWriter {
728 constructor(socket, encoding = "utf8") {
730 this.socket = socket;
732 this.sending = false;
733 this.encoding = encoding;
735 this.socket.on("error", (error) => this.fireError(error));
736 this.socket.on("close", () => this.fireClose());
740 this.socket.destroy();
743 if (!this.sending && this.queue.length === 0) {
744 this.doWriteMessage(msg);
746 this.queue.push(msg);
749 doWriteMessage(msg) {
750 let json = JSON.stringify(msg);
751 let contentLength = Buffer.byteLength(json, this.encoding);
754 contentLength.toString(),
760 this.socket.write(headers.join(""), "ascii", (error) => {
762 this.handleError(error, msg);
765 this.socket.write(json, this.encoding, (error2) => {
766 this.sending = false;
768 this.handleError(error2, msg);
772 if (this.queue.length > 0) {
773 this.doWriteMessage(this.queue.shift());
777 this.handleError(error2, msg);
781 this.handleError(error, msg);
784 handleError(error, msg) {
786 this.fireError(error, msg, this.errorCount);
789 exports2.SocketMessageWriter = SocketMessageWriter;
792 // node_modules/vscode-jsonrpc/lib/cancellation.js
793 var require_cancellation = __commonJS((exports2) => {
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
804 CancellationToken20.Cancelled = Object.freeze({
805 isCancellationRequested: true,
806 onCancellationRequested: events_1.Event.None
808 function is2(value) {
809 let candidate = value;
810 return candidate && (candidate === CancellationToken20.None || candidate === CancellationToken20.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
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);
817 clearTimeout(handle);
820 var MutableToken = class {
822 this._isCancelled = false;
825 if (!this._isCancelled) {
826 this._isCancelled = true;
828 this._emitter.fire(void 0);
833 get isCancellationRequested() {
834 return this._isCancelled;
836 get onCancellationRequested() {
837 if (this._isCancelled) {
838 return shortcutEvent;
840 if (!this._emitter) {
841 this._emitter = new events_1.Emitter();
843 return this._emitter.event;
847 this._emitter.dispose();
848 this._emitter = void 0;
852 var CancellationTokenSource3 = class {
855 this._token = new MutableToken();
861 this._token = CancellationToken19.Cancelled;
863 this._token.cancel();
868 this._token = CancellationToken19.None;
869 } else if (this._token instanceof MutableToken) {
870 this._token.dispose();
874 exports2.CancellationTokenSource = CancellationTokenSource3;
877 // node_modules/vscode-jsonrpc/lib/linkedMap.js
878 var require_linkedMap = __commonJS((exports2) => {
880 Object.defineProperty(exports2, "__esModule", {value: true});
886 })(Touch = exports2.Touch || (exports2.Touch = {}));
887 var LinkedMap = class {
889 this._map = new Map();
901 return !this._head && !this._tail;
907 return this._map.has(key);
910 const item = this._map.get(key);
916 set(key, value, touch = Touch.None) {
917 let item = this._map.get(key);
920 if (touch !== Touch.None) {
921 this.touch(item, touch);
924 item = {key, value, next: void 0, previous: void 0};
927 this.addItemLast(item);
930 this.addItemFirst(item);
933 this.addItemLast(item);
936 this.addItemLast(item);
939 this._map.set(key, item);
944 const item = this._map.get(key);
948 this._map.delete(key);
949 this.removeItem(item);
954 if (!this._head && !this._tail) {
957 if (!this._head || !this._tail) {
958 throw new Error("Invalid list");
960 const item = this._head;
961 this._map.delete(item.key);
962 this.removeItem(item);
966 forEach(callbackfn, thisArg) {
967 let current = this._head;
970 callbackfn.bind(thisArg)(current.value, current.key, this);
972 callbackfn(current.value, current.key, this);
974 current = current.next;
977 forEachReverse(callbackfn, thisArg) {
978 let current = this._tail;
981 callbackfn.bind(thisArg)(current.value, current.key, this);
983 callbackfn(current.value, current.key, this);
985 current = current.previous;
990 let current = this._head;
992 result.push(current.value);
993 current = current.next;
999 let current = this._head;
1001 result.push(current.key);
1002 current = current.next;
1006 addItemFirst(item) {
1007 if (!this._head && !this._tail) {
1009 } else if (!this._head) {
1010 throw new Error("Invalid list");
1012 item.next = this._head;
1013 this._head.previous = item;
1018 if (!this._head && !this._tail) {
1020 } else if (!this._tail) {
1021 throw new Error("Invalid list");
1023 item.previous = this._tail;
1024 this._tail.next = 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;
1037 const next = item.next;
1038 const previous = item.previous;
1039 if (!next || !previous) {
1040 throw new Error("Invalid list");
1042 next.previous = previous;
1043 previous.next = next;
1046 touch(item, touch) {
1047 if (!this._head || !this._tail) {
1048 throw new Error("Invalid list");
1050 if (touch !== Touch.First && touch !== Touch.Last) {
1053 if (touch === Touch.First) {
1054 if (item === this._head) {
1057 const next = item.next;
1058 const previous = item.previous;
1059 if (item === this._tail) {
1060 previous.next = void 0;
1061 this._tail = previous;
1063 next.previous = previous;
1064 previous.next = next;
1066 item.previous = void 0;
1067 item.next = this._head;
1068 this._head.previous = item;
1070 } else if (touch === Touch.Last) {
1071 if (item === this._tail) {
1074 const next = item.next;
1075 const previous = item.previous;
1076 if (item === this._head) {
1077 next.previous = void 0;
1080 next.previous = previous;
1081 previous.next = next;
1084 item.previous = this._tail;
1085 this._tail.next = item;
1090 exports2.LinkedMap = LinkedMap;
1093 // node_modules/vscode-jsonrpc/lib/pipeSupport.js
1094 var require_pipeSupport = __commonJS((exports2) => {
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`;
1108 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
1111 exports2.generateRandomPipeName = generateRandomPipeName;
1112 function createClientPipeTransport(pipeName, encoding = "utf-8") {
1114 let connected = new Promise((resolve, _reject) => {
1115 connectResolve = resolve;
1117 return new Promise((resolve, reject) => {
1118 let server = net_1.createServer((socket) => {
1121 new messageReader_1.SocketMessageReader(socket, encoding),
1122 new messageWriter_1.SocketMessageWriter(socket, encoding)
1125 server.on("error", reject);
1126 server.listen(pipeName, () => {
1127 server.removeListener("error", reject);
1129 onConnected: () => {
1136 exports2.createClientPipeTransport = createClientPipeTransport;
1137 function createServerPipeTransport(pipeName, encoding = "utf-8") {
1138 const socket = net_1.createConnection(pipeName);
1140 new messageReader_1.SocketMessageReader(socket, encoding),
1141 new messageWriter_1.SocketMessageWriter(socket, encoding)
1144 exports2.createServerPipeTransport = createServerPipeTransport;
1147 // node_modules/vscode-jsonrpc/lib/socketSupport.js
1148 var require_socketSupport = __commonJS((exports2) => {
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") {
1156 let connected = new Promise((resolve, _reject) => {
1157 connectResolve = resolve;
1159 return new Promise((resolve, reject) => {
1160 let server = net_1.createServer((socket) => {
1163 new messageReader_1.SocketMessageReader(socket, encoding),
1164 new messageWriter_1.SocketMessageWriter(socket, encoding)
1167 server.on("error", reject);
1168 server.listen(port, "127.0.0.1", () => {
1169 server.removeListener("error", reject);
1171 onConnected: () => {
1178 exports2.createClientSocketTransport = createClientSocketTransport;
1179 function createServerSocketTransport(port, encoding = "utf-8") {
1180 const socket = net_1.createConnection(port, "127.0.0.1");
1182 new messageReader_1.SocketMessageReader(socket, encoding),
1183 new messageWriter_1.SocketMessageWriter(socket, encoding)
1186 exports2.createServerSocketTransport = createServerSocketTransport;
1189 // node_modules/vscode-jsonrpc/lib/main.js
1190 var require_main = __commonJS((exports2) => {
1192 function __export2(m) {
1194 if (!exports2.hasOwnProperty(p))
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 {
1256 exports2.ProgressType = ProgressType;
1257 exports2.NullLogger = Object.freeze({
1269 Trace3[Trace3["Off"] = 0] = "Off";
1270 Trace3[Trace3["Messages"] = 1] = "Messages";
1271 Trace3[Trace3["Verbose"] = 2] = "Verbose";
1272 })(Trace2 = exports2.Trace || (exports2.Trace = {}));
1274 function fromString(value) {
1275 if (!Is.string(value)) {
1278 value = value.toLowerCase();
1283 return Trace3.Messages;
1285 return Trace3.Verbose;
1290 Trace3.fromString = fromString;
1291 function toString2(value) {
1295 case Trace3.Messages:
1297 case Trace3.Verbose:
1303 Trace3.toString = toString2;
1304 })(Trace2 = exports2.Trace || (exports2.Trace = {}));
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;
1316 return TraceFormat2.Text;
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) {
1339 Object.setPrototypeOf(this, ConnectionError.prototype);
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);
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();
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;
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();
1384 function createResponseQueueKey(id) {
1386 return "res-unknown-" + (++unknownResponseSquenceNumber).toString();
1388 return "res-" + id.toString();
1391 function createNotificationQueueKey() {
1392 return "not-" + (++notificationSquenceNumber).toString();
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);
1400 queue.set(createNotificationQueueKey(), message);
1403 function cancelUndispatched(_message) {
1406 function isListening() {
1407 return state === ConnectionState.Listening;
1409 function isClosed() {
1410 return state === ConnectionState.Closed;
1412 function isDisposed() {
1413 return state === ConnectionState.Disposed;
1415 function closeHandler() {
1416 if (state === ConnectionState.New || state === ConnectionState.Listening) {
1417 state = ConnectionState.Closed;
1418 closeEmitter.fire(void 0);
1421 function readErrorHandler(error) {
1422 errorEmitter.fire([error, void 0, void 0]);
1424 function writeErrorHandler(data) {
1425 errorEmitter.fire(data);
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) {
1435 timer = setImmediate(() => {
1437 processMessageQueue();
1440 function processMessageQueue() {
1441 if (messageQueue.size === 0) {
1444 let message = messageQueue.shift();
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);
1453 handleInvalidMessage(message);
1456 triggerMessageQueue();
1459 let callback = (message) => {
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);
1475 addMessageToQueue(messageQueue, message);
1477 triggerMessageQueue();
1480 function handleRequest(requestMessage) {
1484 function reply(resultOrError, method, startTime2) {
1487 id: requestMessage.id
1489 if (resultOrError instanceof messages_1.ResponseError) {
1490 message.error = resultOrError.toJson();
1492 message.result = resultOrError === void 0 ? null : resultOrError;
1494 traceSendingResponse(message, method, startTime2);
1495 messageWriter.write(message);
1497 function replyError(error, method, startTime2) {
1500 id: requestMessage.id,
1501 error: error.toJson()
1503 traceSendingResponse(message, method, startTime2);
1504 messageWriter.write(message);
1506 function replySuccess(result, method, startTime2) {
1507 if (result === void 0) {
1512 id: requestMessage.id,
1515 traceSendingResponse(message, method, startTime2);
1516 messageWriter.write(message);
1518 traceReceivedRequest(requestMessage);
1519 let element = requestHandlers[requestMessage.method];
1523 type = element.type;
1524 requestHandler = element.handler;
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;
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);
1538 handlerResult = requestHandler ? requestHandler(requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
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);
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);
1555 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1559 delete requestTokens[tokenKey];
1560 reply(handlerResult, requestMessage.method, startTime);
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);
1569 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1573 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
1576 function handleResponse(responseMessage) {
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)}`);
1585 logger.error(`Received response message without id. No further error information provided.`);
1588 let key = String(responseMessage.id);
1589 let responsePromise = responsePromises[key];
1590 traceReceivedResponse(responseMessage, responsePromise);
1591 if (responsePromise) {
1592 delete responsePromises[key];
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);
1600 throw new Error("Should never happen.");
1603 if (error.message) {
1604 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
1606 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
1612 function handleNotification(message) {
1617 let notificationHandler;
1618 if (message.method === CancelNotification.type.method) {
1619 notificationHandler = (params) => {
1621 let source = requestTokens[String(id)];
1627 let element = notificationHandlers[message.method];
1629 notificationHandler = element.handler;
1630 type = element.type;
1633 if (notificationHandler || starNotificationHandler) {
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);
1641 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
1644 if (error.message) {
1645 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
1647 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
1651 unhandledNotificationEmitter.fire(message);
1654 function handleInvalidMessage(message) {
1656 logger.error("Received empty message.");
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."));
1670 function traceSendingRequest(message) {
1671 if (trace === Trace2.Off || !tracer) {
1674 if (traceFormat === TraceFormat.Text) {
1676 if (trace === Trace2.Verbose && message.params) {
1677 data = `Params: ${JSON.stringify(message.params, null, 4)}
1681 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
1683 logLSPMessage("send-request", message);
1686 function traceSendingNotification(message) {
1687 if (trace === Trace2.Off || !tracer) {
1690 if (traceFormat === TraceFormat.Text) {
1692 if (trace === Trace2.Verbose) {
1693 if (message.params) {
1694 data = `Params: ${JSON.stringify(message.params, null, 4)}
1698 data = "No parameters provided.\n\n";
1701 tracer.log(`Sending notification '${message.method}'.`, data);
1703 logLSPMessage("send-notification", message);
1706 function traceSendingResponse(message, method, startTime) {
1707 if (trace === Trace2.Off || !tracer) {
1710 if (traceFormat === TraceFormat.Text) {
1712 if (trace === Trace2.Verbose) {
1713 if (message.error && message.error.data) {
1714 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
1718 if (message.result) {
1719 data = `Result: ${JSON.stringify(message.result, null, 4)}
1722 } else if (message.error === void 0) {
1723 data = "No result returned.\n\n";
1727 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
1729 logLSPMessage("send-response", message);
1732 function traceReceivedRequest(message) {
1733 if (trace === Trace2.Off || !tracer) {
1736 if (traceFormat === TraceFormat.Text) {
1738 if (trace === Trace2.Verbose && message.params) {
1739 data = `Params: ${JSON.stringify(message.params, null, 4)}
1743 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
1745 logLSPMessage("receive-request", message);
1748 function traceReceivedNotification(message) {
1749 if (trace === Trace2.Off || !tracer || message.method === LogTraceNotification.type.method) {
1752 if (traceFormat === TraceFormat.Text) {
1754 if (trace === Trace2.Verbose) {
1755 if (message.params) {
1756 data = `Params: ${JSON.stringify(message.params, null, 4)}
1760 data = "No parameters provided.\n\n";
1763 tracer.log(`Received notification '${message.method}'.`, data);
1765 logLSPMessage("receive-notification", message);
1768 function traceReceivedResponse(message, responsePromise) {
1769 if (trace === Trace2.Off || !tracer) {
1772 if (traceFormat === TraceFormat.Text) {
1774 if (trace === Trace2.Verbose) {
1775 if (message.error && message.error.data) {
1776 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
1780 if (message.result) {
1781 data = `Result: ${JSON.stringify(message.result, null, 4)}
1784 } else if (message.error === void 0) {
1785 data = "No result returned.\n\n";
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);
1793 tracer.log(`Received response ${message.id} without active response promise.`, data);
1796 logLSPMessage("receive-response", message);
1799 function logLSPMessage(type, message) {
1800 if (!tracer || trace === Trace2.Off) {
1803 const lspMessage = {
1807 timestamp: Date.now()
1809 tracer.log(lspMessage);
1811 function throwIfClosedOrDisposed() {
1813 throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
1816 throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
1819 function throwIfListening() {
1820 if (isListening()) {
1821 throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
1824 function throwIfNotListening() {
1825 if (!isListening()) {
1826 throw new Error("Call listen() first.");
1829 function undefinedToNull(param) {
1830 if (param === void 0) {
1836 function computeMessageParams(type, params) {
1838 let numberOfParams = type.numberOfParams;
1839 switch (numberOfParams) {
1844 result = undefinedToNull(params[0]);
1848 for (let i = 0; i < params.length && i < numberOfParams; i++) {
1849 result.push(undefinedToNull(params[i]));
1851 if (params.length < numberOfParams) {
1852 for (let i = params.length; i < numberOfParams; i++) {
1861 sendNotification: (type, ...params) => {
1862 throwIfClosedOrDisposed();
1865 if (Is.string(type)) {
1867 switch (params.length) {
1869 messageParams = null;
1872 messageParams = params[0];
1875 messageParams = params;
1879 method = type.method;
1880 messageParams = computeMessageParams(type, params);
1882 let notificationMessage = {
1885 params: messageParams
1887 traceSendingNotification(notificationMessage);
1888 messageWriter.write(notificationMessage);
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};
1898 notificationHandlers[type.method] = {type, handler};
1902 onProgress: (_type, token, handler) => {
1903 if (progressHandlers.has(token)) {
1904 throw new Error(`Progress handler for token ${token} already registered`);
1906 progressHandlers.set(token, handler);
1909 progressHandlers.delete(token);
1913 sendProgress: (_type, token, value) => {
1914 connection.sendNotification(ProgressNotification.type, {token, value});
1916 onUnhandledProgress: unhandledProgressEmitter.event,
1917 sendRequest: (type, ...params) => {
1918 throwIfClosedOrDisposed();
1919 throwIfNotListening();
1923 if (Is.string(type)) {
1925 switch (params.length) {
1927 messageParams = null;
1930 if (cancellation_1.CancellationToken.is(params[0])) {
1931 messageParams = null;
1934 messageParams = undefinedToNull(params[0]);
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]);
1944 messageParams = params.slice(0, last).map((value) => undefinedToNull(value));
1947 messageParams = params.map((value) => undefinedToNull(value));
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;
1957 let id = sequenceNumber++;
1958 let result = new Promise((resolve, reject) => {
1959 let requestMessage = {
1963 params: messageParams
1965 let responsePromise = {method, timerStart: Date.now(), resolve, reject};
1966 traceSendingRequest(requestMessage);
1968 messageWriter.write(requestMessage);
1970 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : "Unknown reason"));
1971 responsePromise = null;
1973 if (responsePromise) {
1974 responsePromises[String(id)] = responsePromise;
1978 token.onCancellationRequested(() => {
1979 connection.sendNotification(CancelNotification.type, {id});
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};
1992 requestHandlers[type.method] = {type, handler};
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;
2003 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
2004 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
2008 traceFormat = _traceFormat;
2009 if (trace === Trace2.Off) {
2014 if (_sendNotification && !isClosed() && !isDisposed()) {
2015 connection.sendNotification(SetTraceNotification.type, {value: Trace2.toString(_value)});
2018 onError: errorEmitter.event,
2019 onClose: closeEmitter.event,
2020 onUnhandledNotification: unhandledNotificationEmitter.event,
2021 onDispose: disposeEmitter.event,
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);
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();
2038 if (Is.func(messageReader.dispose)) {
2039 messageReader.dispose();
2043 throwIfClosedOrDisposed();
2045 state = ConnectionState.Listening;
2046 messageReader.listen(callback);
2049 console.log("inspect");
2052 connection.onNotification(LogTraceNotification.type, (params) => {
2053 if (trace === Trace2.Off || !tracer) {
2056 tracer.log(params.message, trace === Trace2.Verbose ? params.verbose : void 0);
2058 connection.onNotification(ProgressNotification.type, (params) => {
2059 const handler = progressHandlers.get(params.token);
2061 handler(params.value);
2063 unhandledProgressEmitter.fire(params);
2068 function isMessageReader(value) {
2069 return value.listen !== void 0 && value.read === void 0;
2071 function isMessageWriter(value) {
2072 return value.write !== void 0 && value.end === void 0;
2074 function createMessageConnection(input, output, logger, strategy) {
2076 logger = exports2.NullLogger;
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);
2082 exports2.createMessageConnection = createMessageConnection;
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,
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,
2111 FoldingRange: () => FoldingRange2,
2112 FoldingRangeKind: () => FoldingRangeKind,
2113 FormattingOptions: () => FormattingOptions,
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
2141 (function(Position8) {
2142 function create(line, character) {
2143 return {line, character};
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);
2151 })(Position7 || (Position7 = {}));
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};
2160 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
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);
2169 })(Range15 || (Range15 = {}));
2171 (function(Location4) {
2172 function create(uri, range) {
2173 return {uri, range};
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));
2181 })(Location3 || (Location3 = {}));
2183 (function(LocationLink2) {
2184 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
2185 return {targetUri, targetRange, targetSelectionRange, originSelectionRange};
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));
2192 LocationLink2.is = is2;
2193 })(LocationLink || (LocationLink = {}));
2196 function create(red, green, blue, alpha) {
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);
2210 })(Color || (Color = {}));
2211 var ColorInformation;
2212 (function(ColorInformation2) {
2213 function create(range, color) {
2219 ColorInformation2.create = create;
2220 function is2(value) {
2221 var candidate = value;
2222 return Range15.is(candidate.range) && Color.is(candidate.color);
2224 ColorInformation2.is = is2;
2225 })(ColorInformation || (ColorInformation = {}));
2226 var ColorPresentation;
2227 (function(ColorPresentation2) {
2228 function create(label, textEdit, additionalTextEdits) {
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));
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 = {}));
2249 (function(FoldingRange3) {
2250 function create(startLine, endLine, startCharacter, endCharacter, kind) {
2255 if (Is.defined(startCharacter)) {
2256 result.startCharacter = startCharacter;
2258 if (Is.defined(endCharacter)) {
2259 result.endCharacter = endCharacter;
2261 if (Is.defined(kind)) {
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));
2271 FoldingRange3.is = is2;
2272 })(FoldingRange2 || (FoldingRange2 = {}));
2273 var DiagnosticRelatedInformation2;
2274 (function(DiagnosticRelatedInformation3) {
2275 function create(location, message) {
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);
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 = {}));
2296 (function(DiagnosticTag2) {
2297 DiagnosticTag2.Unnecessary = 1;
2298 DiagnosticTag2.Deprecated = 2;
2299 })(DiagnosticTag || (DiagnosticTag = {}));
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;
2307 if (Is.defined(code)) {
2310 if (Is.defined(source)) {
2311 result.source = source;
2313 if (Is.defined(relatedInformation)) {
2314 result.relatedInformation = relatedInformation;
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));
2323 Diagnostic6.is = is2;
2324 })(Diagnostic5 || (Diagnostic5 = {}));
2326 (function(Command6) {
2327 function create(title, command) {
2329 for (var _i = 2; _i < arguments.length; _i++) {
2330 args[_i - 2] = arguments[_i];
2332 var result = {title, command};
2333 if (Is.defined(args) && args.length > 0) {
2334 result.arguments = args;
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);
2344 })(Command5 || (Command5 = {}));
2346 (function(TextEdit7) {
2347 function replace(range, newText) {
2348 return {range, newText};
2350 TextEdit7.replace = replace;
2351 function insert(position, newText) {
2352 return {range: {start: position, end: position}, newText};
2354 TextEdit7.insert = insert;
2355 function del(range) {
2356 return {range, newText: ""};
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);
2364 })(TextEdit6 || (TextEdit6 = {}));
2365 var TextDocumentEdit;
2366 (function(TextDocumentEdit2) {
2367 function create(textDocument, edits) {
2368 return {textDocument, edits};
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);
2375 TextDocumentEdit2.is = is2;
2376 })(TextDocumentEdit || (TextDocumentEdit = {}));
2378 (function(CreateFile2) {
2379 function create(uri, options) {
2384 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
2385 result.options = options;
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)));
2394 CreateFile2.is = is2;
2395 })(CreateFile || (CreateFile = {}));
2397 (function(RenameFile2) {
2398 function create(oldUri, newUri, options) {
2404 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
2405 result.options = options;
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)));
2414 RenameFile2.is = is2;
2415 })(RenameFile || (RenameFile = {}));
2417 (function(DeleteFile2) {
2418 function create(uri, options) {
2423 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
2424 result.options = options;
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)));
2433 DeleteFile2.is = is2;
2434 })(DeleteFile || (DeleteFile = {}));
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);
2443 return TextDocumentEdit.is(change);
2447 WorkspaceEdit7.is = is2;
2448 })(WorkspaceEdit6 || (WorkspaceEdit6 = {}));
2449 var TextEditChangeImpl = function() {
2450 function TextEditChangeImpl2(edits) {
2453 TextEditChangeImpl2.prototype.insert = function(position, newText) {
2454 this.edits.push(TextEdit6.insert(position, newText));
2456 TextEditChangeImpl2.prototype.replace = function(range, newText) {
2457 this.edits.push(TextEdit6.replace(range, newText));
2459 TextEditChangeImpl2.prototype.delete = function(range) {
2460 this.edits.push(TextEdit6.del(range));
2462 TextEditChangeImpl2.prototype.add = function(edit) {
2463 this.edits.push(edit);
2465 TextEditChangeImpl2.prototype.all = function() {
2468 TextEditChangeImpl2.prototype.clear = function() {
2469 this.edits.splice(0, this.edits.length);
2471 return TextEditChangeImpl2;
2473 var WorkspaceChange = function() {
2474 function WorkspaceChange2(workspaceEdit) {
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;
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;
2494 Object.defineProperty(WorkspaceChange2.prototype, "edit", {
2496 return this._workspaceEdit;
2501 WorkspaceChange2.prototype.getTextEditChange = function(key) {
2502 if (VersionedTextDocumentIdentifier.is(key)) {
2503 if (!this._workspaceEdit) {
2504 this._workspaceEdit = {
2508 if (!this._workspaceEdit.documentChanges) {
2509 throw new Error("Workspace edit is not configured for document changes.");
2511 var textDocument = key;
2512 var result = this._textEditChanges[textDocument.uri];
2515 var textDocumentEdit = {
2519 this._workspaceEdit.documentChanges.push(textDocumentEdit);
2520 result = new TextEditChangeImpl(edits);
2521 this._textEditChanges[textDocument.uri] = result;
2525 if (!this._workspaceEdit) {
2526 this._workspaceEdit = {
2527 changes: Object.create(null)
2530 if (!this._workspaceEdit.changes) {
2531 throw new Error("Workspace edit is not configured for normal text edit changes.");
2533 var result = this._textEditChanges[key];
2536 this._workspaceEdit.changes[key] = edits;
2537 result = new TextEditChangeImpl(edits);
2538 this._textEditChanges[key] = result;
2543 WorkspaceChange2.prototype.createFile = function(uri, options) {
2544 this.checkDocumentChanges();
2545 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
2547 WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, options) {
2548 this.checkDocumentChanges();
2549 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
2551 WorkspaceChange2.prototype.deleteFile = function(uri, options) {
2552 this.checkDocumentChanges();
2553 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
2555 WorkspaceChange2.prototype.checkDocumentChanges = function() {
2556 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
2557 throw new Error("Workspace edit is not configured for document changes.");
2560 return WorkspaceChange2;
2562 var TextDocumentIdentifier;
2563 (function(TextDocumentIdentifier2) {
2564 function create(uri) {
2567 TextDocumentIdentifier2.create = create;
2568 function is2(value) {
2569 var candidate = value;
2570 return Is.defined(candidate) && Is.string(candidate.uri);
2572 TextDocumentIdentifier2.is = is2;
2573 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
2574 var VersionedTextDocumentIdentifier;
2575 (function(VersionedTextDocumentIdentifier2) {
2576 function create(uri, version) {
2577 return {uri, version};
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));
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};
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);
2596 TextDocumentItem2.is = is2;
2597 })(TextDocumentItem || (TextDocumentItem = {}));
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;
2608 MarkupKind4.is = is2;
2609 })(MarkupKind3 || (MarkupKind3 = {}));
2611 (function(MarkupContent4) {
2612 function is2(value) {
2613 var candidate = value;
2614 return Is.objectLiteral(value) && MarkupKind3.is(candidate.kind) && Is.string(candidate.value);
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) {
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};
2667 CompletionList4.create = create;
2668 })(CompletionList3 || (CompletionList3 = {}));
2670 (function(MarkedString2) {
2671 function fromPlainText(plainText) {
2672 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
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);
2679 MarkedString2.is = is2;
2680 })(MarkedString || (MarkedString = {}));
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));
2688 })(Hover || (Hover = {}));
2689 var ParameterInformation;
2690 (function(ParameterInformation2) {
2691 function create(label, documentation) {
2692 return documentation ? {label, documentation} : {label};
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];
2703 var result = {label};
2704 if (Is.defined(documentation)) {
2705 result.documentation = documentation;
2707 if (Is.defined(parameters)) {
2708 result.parameters = parameters;
2710 result.parameters = [];
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)) {
2731 DocumentHighlight3.create = create;
2732 })(DocumentHighlight2 || (DocumentHighlight2 = {}));
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 = {}));
2763 (function(SymbolTag2) {
2764 SymbolTag2.Deprecated = 1;
2765 })(SymbolTag || (SymbolTag = {}));
2766 var SymbolInformation2;
2767 (function(SymbolInformation3) {
2768 function create(name, kind, range, uri, containerName) {
2772 location: {uri, range}
2774 if (containerName) {
2775 result.containerName = containerName;
2779 SymbolInformation3.create = create;
2780 })(SymbolInformation2 || (SymbolInformation2 = {}));
2781 var DocumentSymbol2;
2782 (function(DocumentSymbol3) {
2783 function create(name, detail, kind, range, selectionRange, children) {
2791 if (children !== void 0) {
2792 result.children = children;
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));
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) {
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));
2829 CodeActionContext7.is = is2;
2830 })(CodeActionContext6 || (CodeActionContext6 = {}));
2832 (function(CodeAction7) {
2833 function create(title, commandOrEdit, kind) {
2834 var result = {title};
2835 if (Command5.is(commandOrEdit)) {
2836 result.command = commandOrEdit;
2838 result.edit = commandOrEdit;
2840 if (kind !== void 0) {
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));
2850 CodeAction7.is = is2;
2851 })(CodeAction6 || (CodeAction6 = {}));
2853 (function(CodeLens3) {
2854 function create(range, data) {
2855 var result = {range};
2856 if (Is.defined(data)) {
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));
2867 })(CodeLens2 || (CodeLens2 = {}));
2868 var FormattingOptions;
2869 (function(FormattingOptions2) {
2870 function create(tabSize, insertSpaces) {
2871 return {tabSize, insertSpaces};
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);
2878 FormattingOptions2.is = is2;
2879 })(FormattingOptions || (FormattingOptions = {}));
2881 (function(DocumentLink2) {
2882 function create(range, target, data) {
2883 return {range, target, data};
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));
2890 DocumentLink2.is = is2;
2891 })(DocumentLink || (DocumentLink = {}));
2893 (function(SelectionRange2) {
2894 function create(range, parent) {
2895 return {range, parent};
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));
2902 SelectionRange2.is = is2;
2903 })(SelectionRange || (SelectionRange = {}));
2904 var EOL = ["\n", "\r\n", "\r"];
2906 (function(TextDocument12) {
2907 function create(uri, languageId, version, content) {
2908 return new FullTextDocument(uri, languageId, version, content);
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;
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;
2921 return a.range.start.character - b.range.start.character;
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);
2933 throw new Error("Overlapping edit");
2935 lastModifiedOffset = startOffset;
2939 TextDocument12.applyEdits = applyEdits;
2940 function mergeSort(data, compare) {
2941 if (data.length <= 1) {
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);
2952 while (leftIdx < left.length && rightIdx < right.length) {
2953 var ret = compare(left[leftIdx], right[rightIdx]);
2955 data[i++] = left[leftIdx++];
2957 data[i++] = right[rightIdx++];
2960 while (leftIdx < left.length) {
2961 data[i++] = left[leftIdx++];
2963 while (rightIdx < right.length) {
2964 data[i++] = right[rightIdx++];
2968 })(TextDocument11 || (TextDocument11 = {}));
2969 var FullTextDocument = function() {
2970 function FullTextDocument2(uri, languageId, version, content) {
2972 this._languageId = languageId;
2973 this._version = version;
2974 this._content = content;
2975 this._lineOffsets = void 0;
2977 Object.defineProperty(FullTextDocument2.prototype, "uri", {
2984 Object.defineProperty(FullTextDocument2.prototype, "languageId", {
2986 return this._languageId;
2991 Object.defineProperty(FullTextDocument2.prototype, "version", {
2993 return this._version;
2998 FullTextDocument2.prototype.getText = function(range) {
3000 var start = this.offsetAt(range.start);
3001 var end = this.offsetAt(range.end);
3002 return this._content.substring(start, end);
3004 return this._content;
3006 FullTextDocument2.prototype.update = function(event, version) {
3007 this._content = event.text;
3008 this._version = version;
3009 this._lineOffsets = void 0;
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++) {
3018 lineOffsets.push(i);
3019 isLineStart = false;
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") {
3027 if (isLineStart && text.length > 0) {
3028 lineOffsets.push(text.length);
3030 this._lineOffsets = lineOffsets;
3032 return this._lineOffsets;
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;
3039 return Position7.create(0, offset);
3041 while (low < high) {
3042 var mid = Math.floor((low + high) / 2);
3043 if (lineOffsets[mid] > offset) {
3050 return Position7.create(line, offset - lineOffsets[line]);
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) {
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);
3063 Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
3065 return this.getLineOffsets().length;
3070 return FullTextDocument2;
3074 var toString2 = Object.prototype.toString;
3075 function defined(value) {
3076 return typeof value !== "undefined";
3078 Is2.defined = defined;
3079 function undefined2(value) {
3080 return typeof value === "undefined";
3082 Is2.undefined = undefined2;
3083 function boolean2(value) {
3084 return value === true || value === false;
3086 Is2.boolean = boolean2;
3087 function string2(value) {
3088 return toString2.call(value) === "[object String]";
3090 Is2.string = string2;
3091 function number(value) {
3092 return toString2.call(value) === "[object Number]";
3094 Is2.number = number;
3095 function func(value) {
3096 return toString2.call(value) === "[object Function]";
3099 function objectLiteral(value) {
3100 return value !== null && typeof value === "object";
3102 Is2.objectLiteral = objectLiteral;
3103 function typedArray(value, check) {
3104 return Array.isArray(value) && value.every(check);
3106 Is2.typedArray = typedArray;
3107 })(Is || (Is = {}));
3110 // node_modules/vscode-languageserver-protocol/lib/utils/is.js
3111 var require_is2 = __commonJS((exports2) => {
3113 Object.defineProperty(exports2, "__esModule", {value: true});
3114 function boolean2(value) {
3115 return value === true || value === false;
3117 exports2.boolean = boolean2;
3118 function string2(value) {
3119 return typeof value === "string" || value instanceof String;
3121 exports2.string = string2;
3122 function number(value) {
3123 return typeof value === "number" || value instanceof Number;
3125 exports2.number = number;
3126 function error(value) {
3127 return value instanceof Error;
3129 exports2.error = error;
3130 function func(value) {
3131 return typeof value === "function";
3133 exports2.func = func;
3134 function array(value) {
3135 return Array.isArray(value);
3137 exports2.array = array;
3138 function stringArray(value) {
3139 return array(value) && value.every((elem) => string2(elem));
3141 exports2.stringArray = stringArray;
3142 function typedArray(value, check) {
3143 return Array.isArray(value) && value.every(check);
3145 exports2.typedArray = typedArray;
3146 function objectLiteral(value) {
3147 return value !== null && typeof value === "object";
3149 exports2.objectLiteral = objectLiteral;
3152 // node_modules/vscode-languageserver-protocol/lib/messages.js
3153 var require_messages2 = __commonJS((exports2) => {
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) {
3162 exports2.ProtocolRequestType0 = ProtocolRequestType0;
3163 var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType {
3164 constructor(method) {
3168 exports2.ProtocolRequestType = ProtocolRequestType;
3169 var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType {
3170 constructor(method) {
3174 exports2.ProtocolNotificationType = ProtocolNotificationType;
3175 var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 {
3176 constructor(method) {
3180 exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
3183 // node_modules/vscode-languageserver-protocol/lib/protocol.implementation.js
3184 var require_protocol_implementation = __commonJS((exports2) => {
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 = {}));
3197 // node_modules/vscode-languageserver-protocol/lib/protocol.typeDefinition.js
3198 var require_protocol_typeDefinition = __commonJS((exports2) => {
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 = {}));
3211 // node_modules/vscode-languageserver-protocol/lib/protocol.workspaceFolders.js
3212 var require_protocol_workspaceFolders = __commonJS((exports2) => {
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 = {}));
3226 // node_modules/vscode-languageserver-protocol/lib/protocol.configuration.js
3227 var require_protocol_configuration = __commonJS((exports2) => {
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 = {}));
3237 // node_modules/vscode-languageserver-protocol/lib/protocol.colorProvider.js
3238 var require_protocol_colorProvider = __commonJS((exports2) => {
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 = {}));
3255 // node_modules/vscode-languageserver-protocol/lib/protocol.foldingRange.js
3256 var require_protocol_foldingRange = __commonJS((exports2) => {
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 = {}));
3275 // node_modules/vscode-languageserver-protocol/lib/protocol.declaration.js
3276 var require_protocol_declaration = __commonJS((exports2) => {
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 = {}));
3289 // node_modules/vscode-languageserver-protocol/lib/protocol.selectionRange.js
3290 var require_protocol_selectionRange = __commonJS((exports2) => {
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 = {}));
3303 // node_modules/vscode-languageserver-protocol/lib/protocol.progress.js
3304 var require_protocol_progress = __commonJS((exports2) => {
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 = {}));
3323 // node_modules/vscode-languageserver-protocol/lib/protocol.js
3324 var require_protocol = __commonJS((exports2) => {
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;
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);
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)) {
3366 for (let elem of value) {
3367 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
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;
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));
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));
3418 WorkDoneProgressOptions2.is = is2;
3419 function hasWorkDoneProgress(value) {
3420 const candidate = value;
3421 return candidate && Is.boolean(candidate.workDoneProgress);
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 = {}));
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 = {}));
3519 (function(FileChangeType2) {
3520 FileChangeType2.Created = 1;
3521 FileChangeType2.Changed = 2;
3522 FileChangeType2.Deleted = 3;
3523 })(FileChangeType = exports2.FileChangeType || (exports2.FileChangeType = {}));
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 = {}));
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 = {}));
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 = {}));
3657 // node_modules/vscode-languageserver-protocol/lib/protocol.callHierarchy.proposed.js
3658 var require_protocol_callHierarchy_proposed = __commonJS((exports2) => {
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 = {}));
3679 // node_modules/vscode-languageserver-protocol/lib/protocol.sematicTokens.proposed.js
3680 var require_protocol_sematicTokens_proposed = __commonJS((exports2) => {
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 = {}));
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");
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 = {}));
3745 // node_modules/vscode-languageserver-protocol/lib/main.js
3746 var require_main3 = __commonJS((exports2) => {
3748 function __export2(m) {
3750 if (!exports2.hasOwnProperty(p))
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();
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);
3826 exports2.createProtocolConnection = createProtocolConnection;
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;
3836 SEMVER_SPEC_VERSION,
3839 MAX_SAFE_COMPONENT_LENGTH
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) : () => {
3847 module2.exports = debug;
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 = {};
3859 var createToken = (name, value, isGlobal) => {
3861 debug(index, value);
3864 re[index] = new RegExp(value, isGlobal ? "g" : void 0);
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*$");
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);
3921 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
3923 var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
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") {
3941 includePrerelease: false
3944 if (version instanceof SemVer) {
3945 if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
3948 version = version.version;
3950 } else if (typeof version !== "string") {
3951 throw new TypeError(`Invalid Version: ${version}`);
3953 if (version.length > MAX_LENGTH) {
3954 throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
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]);
3962 throw new TypeError(`Invalid Version: ${version}`);
3968 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
3969 throw new TypeError("Invalid major version");
3971 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
3972 throw new TypeError("Invalid minor version");
3974 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
3975 throw new TypeError("Invalid patch version");
3978 this.prerelease = [];
3980 this.prerelease = m[4].split(".").map((id) => {
3981 if (/^[0-9]+$/.test(id)) {
3983 if (num >= 0 && num < MAX_SAFE_INTEGER) {
3990 this.build = m[5] ? m[5].split(".") : [];
3994 this.version = `${this.major}.${this.minor}.${this.patch}`;
3995 if (this.prerelease.length) {
3996 this.version += `-${this.prerelease.join(".")}`;
3998 return this.version;
4001 return this.version;
4004 debug("SemVer.compare", this.version, this.options, other);
4005 if (!(other instanceof SemVer)) {
4006 if (typeof other === "string" && other === this.version) {
4009 other = new SemVer(other, this.options);
4011 if (other.version === this.version) {
4014 return this.compareMain(other) || this.comparePre(other);
4016 compareMain(other) {
4017 if (!(other instanceof SemVer)) {
4018 other = new SemVer(other, this.options);
4020 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
4023 if (!(other instanceof SemVer)) {
4024 other = new SemVer(other, this.options);
4026 if (this.prerelease.length && !other.prerelease.length) {
4028 } else if (!this.prerelease.length && other.prerelease.length) {
4030 } else if (!this.prerelease.length && !other.prerelease.length) {
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) {
4040 } else if (b === void 0) {
4042 } else if (a === void 0) {
4044 } else if (a === b) {
4047 return compareIdentifiers(a, b);
4051 compareBuild(other) {
4052 if (!(other instanceof SemVer)) {
4053 other = new SemVer(other, this.options);
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) {
4062 } else if (b === void 0) {
4064 } else if (a === void 0) {
4066 } else if (a === b) {
4069 return compareIdentifiers(a, b);
4073 inc(release, identifier) {
4076 this.prerelease.length = 0;
4080 this.inc("pre", identifier);
4083 this.prerelease.length = 0;
4086 this.inc("pre", identifier);
4089 this.prerelease.length = 0;
4090 this.inc("patch", identifier);
4091 this.inc("pre", identifier);
4094 if (this.prerelease.length === 0) {
4095 this.inc("patch", identifier);
4097 this.inc("pre", identifier);
4100 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
4105 this.prerelease = [];
4108 if (this.patch !== 0 || this.prerelease.length === 0) {
4112 this.prerelease = [];
4115 if (this.prerelease.length === 0) {
4118 this.prerelease = [];
4121 if (this.prerelease.length === 0) {
4122 this.prerelease = [0];
4124 let i = this.prerelease.length;
4126 if (typeof this.prerelease[i] === "number") {
4127 this.prerelease[i]++;
4132 this.prerelease.push(0);
4136 if (this.prerelease[0] === identifier) {
4137 if (isNaN(this.prerelease[1])) {
4138 this.prerelease = [identifier, 0];
4141 this.prerelease = [identifier, 0];
4146 throw new Error(`invalid increment argument: ${release}`);
4149 this.raw = this.version;
4153 module2.exports = SemVer;
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") {
4165 includePrerelease: false
4168 if (version instanceof SemVer) {
4171 if (typeof version !== "string") {
4174 if (version.length > MAX_LENGTH) {
4177 const r = options.loose ? re[t.LOOSE] : re[t.FULL];
4178 if (!r.test(version)) {
4182 return new SemVer(version, options);
4187 module2.exports = parse;
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;
4197 module2.exports = valid2;
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;
4207 module2.exports = clean;
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;
4219 return new SemVer(version, options).inc(release, identifier).version;
4224 module2.exports = inc;
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;
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;
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)) {
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;
4261 return defaultResult;
4264 module2.exports = diff;
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;
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;
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;
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;
4295 module2.exports = prerelease;
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;
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;
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);
4320 module2.exports = compareBuild;
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;
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;
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;
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;
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;
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;
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;
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) => {
4383 if (typeof a === "object")
4385 if (typeof b === "object")
4389 if (typeof a === "object")
4391 if (typeof b === "object")
4397 return eq(a, b, loose);
4399 return neq(a, b, loose);
4401 return gt(a, b, loose);
4403 return gte2(a, b, loose);
4405 return lt(a, b, loose);
4407 return lte(a, b, loose);
4409 throw new TypeError(`Invalid operator: ${op}`);
4412 module2.exports = cmp;
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) {
4424 if (typeof version === "number") {
4425 version = String(version);
4427 if (typeof version !== "string") {
4430 options = options || {};
4433 match = version.match(re[t.COERCE]);
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) {
4440 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
4442 re[t.COERCERTL].lastIndex = -1;
4446 return parse(`${match[2]}.${match[3] || "0"}.${match[4] || "0"}`, options);
4448 module2.exports = coerce;
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") {
4458 includePrerelease: false
4461 if (range instanceof Range15) {
4462 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
4465 return new Range15(range.raw, options);
4468 if (range instanceof Comparator) {
4469 this.raw = range.value;
4470 this.set = [[range]];
4474 this.options = options;
4475 this.loose = !!options.loose;
4476 this.includePrerelease = !!options.includePrerelease;
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}`);
4485 this.range = this.set.map((comps) => {
4486 return comps.join(" ").trim();
4487 }).join("||").trim();
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));
4507 intersects(range, options) {
4508 if (!(range instanceof Range15)) {
4509 throw new TypeError("a Range is required");
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);
4525 if (typeof version === "string") {
4527 version = new SemVer(version, this.options);
4532 for (let i = 0; i < this.set.length; i++) {
4533 if (testSet(this.set[i], version, this.options)) {
4540 module2.exports = Range15;
4541 var Comparator = require_comparator();
4542 var debug = require_debug();
4543 var SemVer = require_semver();
4547 comparatorTrimReplace,
4551 var isSatisfiable = (comparators, options) => {
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);
4559 testComparator = remainingComparators.pop();
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);
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);
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);
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`;
4591 debug("replaceTilde pr", pr);
4592 ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
4594 ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
4596 debug("tilde return", ret);
4600 var replaceCarets = (comp, options) => comp.trim().split(/\s+/).map((comp2) => {
4601 return replaceCaret(comp2, options);
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);
4612 } else if (isX(m)) {
4613 ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
4614 } else if (isX(p)) {
4616 ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
4618 ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
4621 debug("replaceCaret pr", pr);
4624 ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
4626 ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
4629 ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
4635 ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
4637 ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
4640 ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
4643 debug("caret return", ret);
4647 var replaceXRanges = (comp, options) => {
4648 debug("replaceXRanges", comp, options);
4649 return comp.split(/\s+/).map((comp2) => {
4650 return replaceXRange(comp2, options);
4653 var replaceXRange = (comp, options) => {
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);
4659 const xm = xM || isX(m);
4660 const xp = xm || isX(p);
4662 if (gtlt === "=" && anyX) {
4665 pr = options.includePrerelease ? "-0" : "";
4667 if (gtlt === ">" || gtlt === "<") {
4672 } else if (gtlt && anyX) {
4687 } else if (gtlt === "<=") {
4697 ret = `${gtlt + M}.${m}.${p}${pr}`;
4699 ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
4701 ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
4703 debug("xRange return", ret);
4707 var replaceStars = (comp, options) => {
4708 debug("replaceStars", comp, options);
4709 return comp.trim().replace(re[t.STAR], "");
4711 var replaceGTE0 = (comp, options) => {
4712 debug("replaceGTE0", comp, options);
4713 return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
4715 var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => {
4718 } else if (isX(fm)) {
4719 from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
4720 } else if (isX(fp)) {
4721 from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
4725 from = `>=${from}${incPr ? "-0" : ""}`;
4729 } else if (isX(tm)) {
4730 to = `<${+tM + 1}.0.0-0`;
4731 } else if (isX(tp)) {
4732 to = `<${tM}.${+tm + 1}.0-0`;
4734 to = `<=${tM}.${tm}.${tp}-${tpr}`;
4736 to = `<${tM}.${tm}.${+tp + 1}-0`;
4740 return `${from} ${to}`.trim();
4742 var testSet = (set, version, options) => {
4743 for (let i = 0; i < set.length; i++) {
4744 if (!set[i].test(version)) {
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) {
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) {
4767 // node_modules/semver/classes/comparator.js
4768 var require_comparator = __commonJS((exports2, module2) => {
4769 var ANY = Symbol("SemVer ANY");
4770 var Comparator = class {
4774 constructor(comp, options) {
4775 if (!options || typeof options !== "object") {
4778 includePrerelease: false
4781 if (comp instanceof Comparator) {
4782 if (comp.loose === !!options.loose) {
4788 debug("comparator", comp, options);
4789 this.options = options;
4790 this.loose = !!options.loose;
4792 if (this.semver === ANY) {
4795 this.value = this.operator + this.semver.version;
4797 debug("comp", this);
4800 const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
4801 const m = comp.match(r);
4803 throw new TypeError(`Invalid comparator: ${comp}`);
4805 this.operator = m[1] !== void 0 ? m[1] : "";
4806 if (this.operator === "=") {
4812 this.semver = new SemVer(m[2], this.options.loose);
4819 debug("Comparator.test", version, this.options.loose);
4820 if (this.semver === ANY || version === ANY) {
4823 if (typeof version === "string") {
4825 version = new SemVer(version, this.options);
4830 return cmp(version, this.operator, this.semver, this.options);
4832 intersects(comp, options) {
4833 if (!(comp instanceof Comparator)) {
4834 throw new TypeError("a Comparator is required");
4836 if (!options || typeof options !== "object") {
4839 includePrerelease: false
4842 if (this.operator === "") {
4843 if (this.value === "") {
4846 return new Range15(comp.value, options).test(this.value);
4847 } else if (comp.operator === "") {
4848 if (comp.value === "") {
4851 return new Range15(this.value, options).test(comp.semver);
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;
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();
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) => {
4875 range = new Range15(range, options);
4879 return range.test(version);
4881 module2.exports = satisfies;
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;
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) => {
4898 let rangeObj = null;
4900 rangeObj = new Range15(range, options);
4904 versions.forEach((v) => {
4905 if (rangeObj.test(v)) {
4906 if (!max || maxSV.compare(v) === -1) {
4908 maxSV = new SemVer(max, options);
4914 module2.exports = maxSatisfying;
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) => {
4924 let rangeObj = null;
4926 rangeObj = new Range15(range, options);
4930 versions.forEach((v) => {
4931 if (rangeObj.test(v)) {
4932 if (!min || minSV.compare(v) === 1) {
4934 minSV = new SemVer(min, options);
4940 module2.exports = minSatisfying;
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)) {
4954 minver = new SemVer("0.0.0-0");
4955 if (range.test(minver)) {
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) {
4965 if (compver.prerelease.length === 0) {
4968 compver.prerelease.push(0);
4970 compver.raw = compver.format();
4973 if (!minver || gt(minver, compver)) {
4981 throw new Error(`Unexpected operation: ${comparator.operator}`);
4985 if (minver && range.test(minver)) {
4990 module2.exports = minVersion;
4993 // node_modules/semver/ranges/valid.js
4994 var require_valid2 = __commonJS((exports2, module2) => {
4995 var Range15 = require_range();
4996 var validRange = (range, options) => {
4998 return new Range15(range, options).range || "*";
5003 module2.exports = validRange;
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;
5037 throw new TypeError('Must provide a hilo val of "<" or ">"');
5039 if (satisfies(version, range, options)) {
5042 for (let i = 0; i < range.set.length; ++i) {
5043 const comparators = range.set[i];
5046 comparators.forEach((comparator) => {
5047 if (comparator.semver === ANY) {
5048 comparator = new Comparator(">=0.0.0");
5050 high = high || comparator;
5051 low = low || comparator;
5052 if (gtfn(comparator.semver, high.semver, options)) {
5054 } else if (ltfn(comparator.semver, low.semver, options)) {
5058 if (high.operator === comp || high.operator === ecomp) {
5061 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
5063 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
5069 module2.exports = outside;
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;
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;
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);
5094 module2.exports = intersects;
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) => {
5105 const v = versions.sort((a, b) => compare(a, b, options));
5106 for (const version of v) {
5107 const included = satisfies(version, range, options);
5114 set.push([min, prev]);
5121 set.push([min, null]);
5123 for (const [min2, max] of set) {
5126 else if (!max && min2 === v[0])
5129 ranges.push(`>=${min2}`);
5130 else if (min2 === v[0])
5131 ranges.push(`<=${max}`);
5133 ranges.push(`${min2} - ${max}`);
5135 const simplified = ranges.join(" || ");
5136 const original = typeof range.raw === "string" ? range.raw : String(range);
5137 return simplified.length < original.length ? simplified : range;
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;
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;
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();
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);
5175 eqSet.add(c.semver);
5181 gtltComp = compare(gt.semver, lt.semver, options);
5184 else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<="))
5187 for (const eq of eqSet) {
5188 if (gt && !satisfies(eq, String(gt), options))
5190 if (lt && !satisfies(eq, String(lt), options))
5192 for (const c of dom) {
5193 if (!satisfies(eq, String(c), options))
5199 let hasDomLT, hasDomGT;
5200 for (const c of dom) {
5201 hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
5202 hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
5204 if (c.operator === ">" || c.operator === ">=") {
5205 higher = higherGT(gt, c, options);
5208 } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options))
5212 if (c.operator === "<" || c.operator === "<=") {
5213 lower = lowerLT(lt, c, options);
5216 } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options))
5219 if (!c.operator && (lt || gt) && gtltComp !== 0)
5222 if (gt && hasDomLT && !lt && gtltComp !== 0)
5224 if (lt && hasDomGT && !gt && gtltComp !== 0)
5228 var higherGT = (a, b, options) => {
5231 const comp = compare(a.semver, b.semver, options);
5232 return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
5234 var lowerLT = (a, b, options) => {
5237 const comp = compare(a.semver, b.semver, options);
5238 return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
5240 module2.exports = subset;
5243 // node_modules/semver/index.js
5244 var require_semver2 = __commonJS((exports2, module2) => {
5245 var internalRe = require_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(),
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(),
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(),
5288 intersects: require_intersects(),
5289 simplifyRange: require_simplify(),
5290 subset: require_subset()
5294 // node_modules/isexe/windows.js
5295 var require_windows = __commonJS((exports2, module2) => {
5296 module2.exports = isexe;
5298 var fs5 = require("fs");
5299 function checkPathExt(path8, options) {
5300 var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
5304 pathext = pathext.split(";");
5305 if (pathext.indexOf("") !== -1) {
5308 for (var i = 0; i < pathext.length; i++) {
5309 var p = pathext[i].toLowerCase();
5310 if (p && path8.substr(-p.length).toLowerCase() === p) {
5316 function checkStat(stat, path8, options) {
5317 if (!stat.isSymbolicLink() && !stat.isFile()) {
5320 return checkPathExt(path8, options);
5322 function isexe(path8, options, cb) {
5323 fs5.stat(path8, function(er, stat) {
5324 cb(er, er ? false : checkStat(stat, path8, options));
5327 function sync(path8, options) {
5328 return checkStat(fs5.statSync(path8), path8, options);
5332 // node_modules/isexe/mode.js
5333 var require_mode = __commonJS((exports2, module2) => {
5334 module2.exports = isexe;
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));
5342 function sync(path8, options) {
5343 return checkStat(fs5.statSync(path8), options);
5345 function checkStat(stat, options) {
5346 return stat.isFile() && checkMode(stat, options);
5348 function checkMode(stat, options) {
5349 var mod = stat.mode;
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);
5358 var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
5363 // node_modules/isexe/index.js
5364 var require_isexe = __commonJS((exports2, module2) => {
5365 var fs5 = require("fs");
5367 if (process.platform === "win32" || global.TESTING_WINDOWS) {
5368 core = require_windows();
5370 core = require_mode();
5372 module2.exports = isexe;
5374 function isexe(path8, options, cb) {
5375 if (typeof options === "function") {
5380 if (typeof Promise !== "function") {
5381 throw new TypeError("callback not provided");
5383 return new Promise(function(resolve, reject) {
5384 isexe(path8, options || {}, function(er, is2) {
5393 core(path8, options || {}, function(er, is2) {
5395 if (er.code === "EACCES" || options && options.ignoreErrors) {
5403 function sync(path8, options) {
5405 return core.sync(path8, options || {});
5407 if (options && options.ignoreErrors || er.code === "EACCES") {
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)
5429 const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
5430 const pathExt = isWindows ? pathExtExe.split(colon) : [""];
5432 if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
5433 pathExt.unshift("");
5441 var which2 = (cmd, opt, cb) => {
5442 if (typeof opt === "function") {
5448 const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
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));
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) => {
5466 found.push(p + ext);
5468 return resolve(p + ext);
5470 return resolve(subStep(p, i, ii + 1));
5473 return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
5475 var whichSync = (cmd, opt) => {
5477 const {pathEnv, pathExt, pathExtExe} = getPathInfo(cmd, opt);
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];
5487 const is2 = isexe.sync(cur, {pathExt: pathExtExe});
5498 if (opt.all && found.length)
5502 throw getNotFoundError(cmd);
5504 module2.exports = which2;
5505 which2.sync = whichSync;
5510 activate: () => activate
5512 var import_coc32 = __toModule(require("coc.nvim"));
5514 // src/server/index.ts
5515 var import_coc30 = __toModule(require("coc.nvim"));
5516 var import_vscode_languageserver_protocol23 = __toModule(require_main3());
5518 // src/server/typescriptServiceClientHost.ts
5519 var import_coc29 = __toModule(require("coc.nvim"));
5520 var import_vscode_languageserver_protocol22 = __toModule(require_main3());
5522 // src/utils/arrays.ts
5523 function equals(one, other, itemEquals = (a, b) => a === b) {
5524 if (one.length !== other.length) {
5527 for (let i = 0, len = one.length; i < len; i++) {
5528 if (!itemEquals(one[i], other[i])) {
5534 function flatten(arr) {
5535 return [].concat.apply([], arr);
5538 // src/server/features/fileConfigurationManager.ts
5539 var import_coc = __toModule(require("coc.nvim"));
5540 var import_vscode_languageserver_protocol = __toModule(require_main3());
5542 // src/server/utils/api.ts
5543 var semver = __toModule(require_semver2());
5545 constructor(versionString, version) {
5546 this.versionString = versionString;
5547 this.version = version;
5549 static fromSimpleString(value) {
5550 return new API2(value, value);
5552 static fromVersionString(versionString) {
5553 let version = semver.valid(versionString);
5555 return new API2("invalid version", "1.0.0");
5557 const index = versionString.indexOf("-");
5559 version = version.substr(0, index);
5561 return new API2(versionString, version);
5564 return semver.gte(this.version, other.version);
5567 return !this.gte(other);
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;
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++) {
5609 if (a[key] !== b[key]) {
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);
5624 async ensureConfigurationOptions(document, insertSpaces, tabSize, token) {
5625 const file2 = this.client.toPath(document.uri);
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))
5634 this.cachedMap.set(document.uri, currentOptions);
5639 await this.client.execute("configure", args, import_vscode_languageserver_protocol.CancellationToken.None);
5641 const response = await this.client.execute("configure", args, token);
5642 if (response.type !== "response") {
5643 this.cachedMap.delete(document.uri);
5646 this.cachedMap.delete(document.uri);
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);
5654 this.cachedMap.clear();
5656 getLanguageConfiguration(languageId) {
5657 return import_coc.workspace.getConfiguration(languageId);
5659 isTypeScriptDocument(languageId) {
5660 return languageId.startsWith("typescript");
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");
5668 enableJavascript() {
5669 const config = import_coc.workspace.getConfiguration("tsserver");
5670 return !!config.get("enableJavascript");
5672 getFileOptions(options, document) {
5673 const lang = this.isTypeScriptDocument(document.languageId) ? "typescript" : "javascript";
5675 formatOptions: this.getFormatOptions(options, lang, document.uri),
5676 preferences: this.getPreferences(lang, document.uri)
5679 getFormatOptions(options, language, uri) {
5680 const config = import_coc.workspace.getConfiguration(`${language}.format`, uri);
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)
5705 getCompleteOptions(languageId) {
5706 const lang = this.isTypeScriptDocument(languageId) ? "typescript" : "javascript";
5707 const config = import_coc.workspace.getConfiguration(`${lang}.suggest`);
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)
5717 getPreferences(language, uri) {
5718 if (this.client.apiVersion.lt(api_default.v290)) {
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)
5732 getQuoteStyle(config) {
5733 let quoteStyle = config.get("quoteStyle", "auto");
5734 if (this.client.apiVersion.gte(api_default.v333) || quoteStyle != "auto")
5739 import_coc.disposeAll(this.disposables);
5742 var fileConfigurationManager_default = FileConfigurationManager;
5743 function getImportModuleSpecifier(config) {
5744 let val = config.get("importModuleSpecifier");
5748 case "non-relative":
5749 return "non-relative";
5754 function getImportModuleSpecifierEndingPreference(config) {
5755 switch (config.get("importModuleSpecifierEnding")) {
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*(.+)$/;
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);
5790 task.onExit((code) => {
5792 import_coc2.window.showMessage(`TSC exit with code ${code}`, "warning");
5796 task.onStdout((lines) => {
5797 for (let line of lines) {
5801 task.onStderr((lines) => {
5802 import_coc2.window.showMessage(`TSC error: ` + lines.join("\n"), "error");
5804 this.disposables.push(import_vscode_languageserver_protocol2.Disposable.create(() => {
5807 this.check().catch((_e) => {
5811 let running = await this.task.running;
5813 this.options = await this.getOptions();
5814 this.statusItem.isProgress = false;
5815 this.statusItem.text = "?";
5816 this.statusItem.show();
5821 async start(options) {
5822 await this.task.start(options);
5825 this.statusItem.hide();
5828 this.statusItem.text = "compiling";
5829 this.statusItem.isProgress = true;
5830 this.statusItem.show();
5831 import_coc2.workspace.nvim.call("setqflist", [[]], true);
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) {
5841 let ms = line.match(errorRegex);
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;
5850 lnum: Number(ms[2]),
5852 text: `[tsc ${ms[5]}] ${ms[6]}`,
5853 type: /error/i.test(ms[4]) ? "E" : "W"
5857 import_coc2.workspace.nvim.call("setqflist", [[item], "a"]);
5860 async getOptions() {
5861 let {tscPath} = this.client;
5863 import_coc2.window.showMessage(`Local & global tsc not found`, "error");
5866 let find = await import_coc2.workspace.findUp(["tsconfig.json"]);
5868 import_coc2.window.showMessage("tsconfig.json not found!", "error");
5871 let root = import_path.default.dirname(find);
5874 args: ["-p", "tsconfig.json", "--watch", "true", "--pretty", "false"],
5879 import_coc2.disposeAll(this.disposables);
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;
5887 // src/server/features/workspaceSymbols.ts
5888 var import_coc3 = __toModule(require("coc.nvim"));
5889 var import_vscode_languageserver_protocol3 = __toModule(require_main3());
5891 // src/server/utils/typeConverters.ts
5893 (function(Range15) {
5894 Range15.fromTextSpan = (span) => {
5897 line: span.start.line - 1,
5898 character: span.start.offset - 1
5901 line: span.end.line - 1,
5902 character: span.end.offset - 1
5906 Range15.toFormattingRequestArgs = (file2, range) => ({
5908 line: range.start.line + 1,
5909 offset: range.start.character + 1,
5910 endLine: range.end.line + 1,
5911 endOffset: range.end.character + 1
5913 Range15.toFileRangeRequestArgs = (file2, range) => ({
5915 startLine: range.start.line + 1,
5916 startOffset: range.start.character + 1,
5917 endLine: range.end.line + 1,
5918 endOffset: range.end.character + 1
5920 })(Range || (Range = {}));
5922 (function(Position7) {
5923 Position7.fromLocation = (tslocation) => {
5925 line: tslocation.line - 1,
5926 character: tslocation.offset - 1
5929 Position7.toLocation = (position) => ({
5930 line: position.line + 1,
5931 offset: position.character + 1
5933 Position7.toFileLocationRequestArgs = (file2, position) => ({
5935 line: position.line + 1,
5936 offset: position.character + 1
5938 })(Position || (Position = {}));
5940 (function(Location3) {
5941 Location3.fromTextSpan = (uri, tsTextSpan) => {
5944 range: Range.fromTextSpan(tsTextSpan)
5947 })(Location2 || (Location2 = {}));
5949 (function(TextEdit6) {
5950 TextEdit6.fromCodeEdit = (edit) => {
5952 range: Range.fromTextSpan(edit),
5953 newText: edit.newText
5956 })(TextEdit || (TextEdit = {}));
5958 (function(WorkspaceEdit6) {
5959 function fromFileCodeEdits(client, edits) {
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);
5969 WorkspaceEdit6.fromFileCodeEdits = fromFileCodeEdits;
5970 })(WorkspaceEdit || (WorkspaceEdit = {}));
5972 // src/server/features/workspaceSymbols.ts
5973 function getSymbolKind(item) {
5974 switch (item.kind) {
5976 return import_vscode_languageserver_protocol3.SymbolKind.Method;
5978 return import_vscode_languageserver_protocol3.SymbolKind.Enum;
5980 return import_vscode_languageserver_protocol3.SymbolKind.Function;
5982 return import_vscode_languageserver_protocol3.SymbolKind.Class;
5984 return import_vscode_languageserver_protocol3.SymbolKind.Interface;
5986 return import_vscode_languageserver_protocol3.SymbolKind.Variable;
5988 return import_vscode_languageserver_protocol3.SymbolKind.Variable;
5991 var TypeScriptWorkspaceSymbolProvider = class {
5992 constructor(client, languageIds) {
5993 this.client = client;
5994 this.languageIds = languageIds;
5996 async provideWorkspaceSymbols(search, token) {
5998 if (this.searchAllOpenProjects) {
6001 let uri = this.getUri();
6002 filepath = uri ? this.client.toPath(uri) : void 0;
6003 if (!filepath && this.client.apiVersion.lt(api_default.v390)) {
6009 searchValue: search,
6012 const response = await this.client.execute("navto", args, token);
6013 if (response.type !== "response" || response.body == null)
6016 for (const item of response.body) {
6017 if (!item.containerName && item.kind === "alias") {
6020 const label = TypeScriptWorkspaceSymbolProvider.getLabel(item);
6022 start: Position.fromLocation(item.start),
6023 end: Position.fromLocation(item.end)
6025 const symbolInfo = import_vscode_languageserver_protocol3.SymbolInformation.create(label, getSymbolKind(item), range, this.client.toResource(item.file));
6026 result.push(symbolInfo);
6030 static getLabel(item) {
6031 let label = item.name;
6032 if (item.kind === "method" || item.kind === "function") {
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;
6046 get searchAllOpenProjects() {
6047 return this.client.apiVersion.gte(api_default.v390) && import_coc3.workspace.getConfiguration("typescript").get("workspaceSymbols.scope", "allOpenProjects") === "allOpenProjects";
6050 var workspaceSymbols_default = TypeScriptWorkspaceSymbolProvider;
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());
6057 // src/server/features/baseCodeLensProvider.ts
6058 var import_vscode_languageserver_protocol4 = __toModule(require_main3());
6060 // src/server/utils/regexp.ts
6061 function escapeRegExp(text) {
6062 return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
6065 // src/server/features/baseCodeLensProvider.ts
6066 var CachedNavTreeResponse = class {
6071 execute(document, f) {
6072 if (this.matches(document)) {
6073 return this.response;
6075 return this.update(document, f());
6078 return this.version === document.version && this.document === document.uri.toString();
6080 update(document, response) {
6081 this.response = response;
6082 this.version = document.version;
6083 this.document = document.uri.toString();
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();
6093 get onDidChangeCodeLenses() {
6094 return this.onDidChangeCodeLensesEmitter.event;
6096 async provideCodeLenses(document, token) {
6097 const filepath = this.client.toPath(document.uri);
6102 const response = await this.cachedResponse.execute(document, () => this.client.execute("navtree", {file: filepath}, token));
6106 const tree = response.body;
6107 const referenceableSpans = [];
6108 if (tree && tree.childItems) {
6109 tree.childItems.forEach((item) => this.walkNavTree(document, item, null, referenceableSpans));
6111 return referenceableSpans.map((range) => {
6114 data: {uri: document.uri}
6121 walkNavTree(document, item, parent, results) {
6125 const range = this.extractSymbol(document, item, parent);
6127 results.push(range);
6129 if (item.childItems) {
6130 item.childItems.forEach((child) => this.walkNavTree(document, child, item, results));
6133 getSymbolRange(document, item) {
6137 if (item.nameSpan) {
6138 return Range.fromTextSpan(item.nameSpan);
6140 const span = item.spans && item.spans[0];
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;
6151 start: document.positionAt(startOffset),
6152 end: document.positionAt(startOffset + item.text.length)
6157 // src/server/features/completionItemProvider.ts
6158 var import_coc5 = __toModule(require("coc.nvim"));
6159 var import_vscode_languageserver_protocol8 = __toModule(require_main3());
6161 // src/server/protocol.const.ts
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";
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";
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";
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 {
6196 DiagnosticCategory.error = "error";
6197 DiagnosticCategory.warning = "warning";
6198 DiagnosticCategory.suggestion = "suggestion";
6199 var KindModifiers2 = class {
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
6218 var DisplayPartKind = class {
6220 DisplayPartKind.functionName = "functionName";
6221 DisplayPartKind.methodName = "methodName";
6222 DisplayPartKind.parameterName = "parameterName";
6223 DisplayPartKind.propertyName = "propertyName";
6224 DisplayPartKind.punctuation = "punctuation";
6225 DisplayPartKind.text = "text";
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;
6233 async function applyCodeAction(client, action) {
6234 const workspaceEdit = getEditForCodeAction(client, action);
6235 if (workspaceEdit) {
6236 if (!await import_coc4.workspace.applyEdit(workspaceEdit)) {
6240 return applyCodeActionCommands(client, action);
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) {
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;
6261 if (tsEntry.isRecommended) {
6264 if (tsEntry.source) {
6265 sortText = "\uFFFF" + sortText;
6267 sortText = tsEntry.sortText;
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) {
6278 range: import_vscode_languageserver_protocol6.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1),
6279 newText: insertText || label
6283 if (tsEntry.kindModifiers) {
6284 const kindModifiers = new Set(tsEntry.kindModifiers.split(/,|\s+/g));
6285 if (kindModifiers.has(KindModifiers.optional)) {
6289 if (kindModifiers.has(KindModifiers.color)) {
6290 kind = import_vscode_languageserver_protocol6.CompletionItemKind.Color;
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;
6298 detail = tsEntry.name + extModifier;
6319 source: tsEntry.source || ""
6323 function convertKind(kind) {
6325 case Kind.primitiveType:
6327 return import_vscode_languageserver_protocol6.CompletionItemKind.Keyword;
6329 return import_vscode_languageserver_protocol6.CompletionItemKind.Constant;
6332 case Kind.localVariable:
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;
6340 return import_vscode_languageserver_protocol6.CompletionItemKind.Function;
6342 case Kind.constructSignature:
6343 case Kind.callSignature:
6344 case Kind.indexSignature:
6345 return import_vscode_languageserver_protocol6.CompletionItemKind.Method;
6347 return import_vscode_languageserver_protocol6.CompletionItemKind.Enum;
6349 case Kind.externalModuleName:
6350 return import_vscode_languageserver_protocol6.CompletionItemKind.Module;
6353 return import_vscode_languageserver_protocol6.CompletionItemKind.Class;
6354 case Kind.interface:
6355 return import_vscode_languageserver_protocol6.CompletionItemKind.Interface;
6358 return import_vscode_languageserver_protocol6.CompletionItemKind.File;
6359 case Kind.directory:
6360 return import_vscode_languageserver_protocol6.CompletionItemKind.Folder;
6362 return import_vscode_languageserver_protocol6.CompletionItemKind.Variable;
6364 function getCommitCharacters(tsEntry, context) {
6365 if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) {
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:
6376 case Kind.interface:
6377 commitCharacters.push(".", ";");
6384 case Kind.localVariable:
6385 case Kind.memberVariable:
6390 case Kind.parameter:
6391 commitCharacters.push(".", ",", ";");
6392 if (context.enableCallCompletions) {
6393 commitCharacters.push("(");
6397 return commitCharacters.length === 0 ? void 0 : commitCharacters;
6399 function getParameterListParts(displayParts) {
6401 let isInMethod = false;
6402 let hasOptionalParameters = false;
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) {
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) {
6425 hasOptionalParameters = hasOptionalParameters || nameIsFollowedByOptionalIndicator;
6428 case DisplayPartKind.punctuation:
6429 if (part.text === "(") {
6431 } else if (part.text === ")") {
6433 if (parenCount <= 0 && isInMethod) {
6436 } else if (part.text === "..." && parenCount === 1) {
6437 hasOptionalParameters = true;
6439 } else if (part.text === "{") {
6441 } else if (part.text === "}") {
6447 return {hasOptionalParameters, parts};
6450 // src/server/utils/previewer.ts
6451 var import_vscode_languageserver_protocol7 = __toModule(require_main3());
6452 function getTagBodyText(tag) {
6459 if (tag.text.match(/^\s*[~`]{3}/g)) {
6462 return "```\n" + tag.text + "\n```";
6466 function getTagDocumentation(tag) {
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}\``;
6477 return label2 + (doc.match(/\r\n|\n/g) ? "\n" + doc : ` \u2014 ${doc}`);
6480 const label = `*@${tag.name}*`;
6481 const text = getTagBodyText(tag);
6485 return label + (text.match(/\r\n|\n/g) ? "\n" + text : ` \u2014 ${text}`);
6487 function plain(parts) {
6488 if (!parts || !parts.length)
6490 return parts.map((part) => part.text).join("");
6492 function tagsMarkdownPreview(tags) {
6493 return (tags || []).map(getTagDocumentation).join(" \n\n");
6495 function markdownDocumentation(documentation, tags) {
6496 let out = plain(documentation);
6497 const tagsPreview = tagsMarkdownPreview(tags);
6499 out = out + ("\n\n" + tagsPreview);
6502 kind: import_vscode_languageserver_protocol7.MarkupKind.Markdown,
6507 // src/server/utils/SnippetString.ts
6508 var SnippetString = class {
6509 constructor(value) {
6511 this.value = value || "";
6513 static isSnippetString(thing) {
6514 if (thing instanceof SnippetString) {
6520 return typeof thing.value === "string";
6522 static _escape(value) {
6523 return value.replace(/\$|}|\\/g, "\\$&");
6526 this.value += SnippetString._escape(str);
6529 appendTabstop(n = this._tabstop++) {
6534 appendPlaceholder(value, n = this._tabstop++) {
6535 if (typeof value === "function") {
6536 const nested = new SnippetString();
6537 nested._tabstop = this._tabstop;
6539 this._tabstop = nested._tabstop;
6540 value = nested.value;
6542 value = SnippetString._escape(value);
6547 this.value += value;
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, "\\$&");
6565 this.value += defaultValue;
6571 var SnippetString_default = SnippetString;
6573 // src/server/features/completionItemProvider.ts
6574 var ApplyCompletionCodeActionCommand2 = class {
6575 constructor(client) {
6576 this.client = client;
6577 this.id = ApplyCompletionCodeActionCommand2.ID;
6579 async execute(codeActions) {
6580 if (codeActions.length === 0) {
6583 if (codeActions.length === 1) {
6584 await applyCodeAction(this.client, codeActions[0]);
6587 const idx = await import_coc5.window.showQuickpick(codeActions.map((o) => o.description), "Select code action to apply");
6590 const action = codeActions[idx];
6591 await applyCodeAction(this.client, action);
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);
6607 import_coc5.workspace.onDidChangeConfiguration((_e) => {
6608 this.setCompleteOption(languageId);
6611 setCompleteOption(languageId) {
6612 this.completeOption = this.fileConfigurationManager.getCompleteOptions(languageId);
6614 async provideCompletionItems(document, position, token, context) {
6615 if (this.typingsStatus.isAcquiringTypings) {
6616 return Promise.resolve({
6619 label: "Acquiring typings...",
6620 detail: "Acquiring typings definitions for IntelliSense."
6624 let {uri} = document;
6625 const file2 = this.client.toPath(document.uri);
6628 let preText = document.getText({
6629 start: {line: position.line, character: 0},
6632 let {triggerCharacter, option} = context;
6633 if (!this.shouldTrigger(triggerCharacter, preText, option)) {
6636 await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token));
6637 const {completeOption} = this;
6639 ...Position.toFileLocationRequestArgs(file2, position),
6640 includeExternalModuleExports: completeOption.autoImports,
6641 includeInsertTextCompletions: true,
6642 triggerCharacter: this.getTsTriggerCharacter(context),
6643 includeAutomaticOptionalChainCompletions: completeOption.includeAutomaticOptionalChainCompletions
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)) {
6653 const response = await this.client.interruptGetErr(() => this.client.execute("completionInfo", args, token));
6654 if (response.type !== "response" || !response.body) {
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;
6662 const range = import_vscode_languageserver_protocol8.Range.create({
6663 line: position.line,
6664 character: position.character - dotMatch.length
6666 const text = document.getText(range);
6667 dotAccessorContext = {range, text};
6670 isIncomplete = response.metadata && response.metadata.isIncomplete;
6671 entries = response.body.entries;
6673 if (e.message == "No content available.") {
6679 const response = await this.client.interruptGetErr(() => this.client.execute("completions", args, token));
6680 if (response.type !== "response" || !response.body) {
6683 entries = response.body;
6685 const completionItems = [];
6686 for (const element of entries) {
6687 if (shouldExcludeCompletionEntry(element, completeOption)) {
6690 const item = convertCompletionEntry(element, uri, position, {
6691 isNewIdentifierLocation,
6693 enableCallCompletions: completeOption.completeFunctionCalls,
6694 isInValidCommitCharacterContext,
6697 completionItems.push(item);
6699 return {isIncomplete, items: completionItems};
6701 getTsTriggerCharacter(context) {
6702 switch (context.triggerCharacter) {
6704 return this.client.apiVersion.gte(api_default.v310) && this.client.apiVersion.lt(api_default.v320) ? void 0 : "@";
6706 return this.client.apiVersion.lt(api_default.v381) ? void 0 : "#";
6713 return context.triggerCharacter;
6717 async resolveCompletionItem(item, token) {
6720 let {uri, position, source, name} = item.data;
6721 const filepath = this.client.toPath(uri);
6724 let document = import_coc5.workspace.getDocument(uri);
6728 ...Position.toFileLocationRequestArgs(filepath, position),
6729 entryNames: [source ? {name, source} : name]
6733 response = await this.client.interruptGetErr(() => this.client.execute("completionEntryDetails", args, token));
6737 if (response.type !== "response" || !response.body || !response.body.length) {
6740 const details = response.body;
6741 if (!details || !details.length || !details[0]) {
6744 const detail = details[0];
6745 if (!item.detail && detail.displayParts.length) {
6746 item.detail = plain(detail.displayParts);
6748 item.documentation = this.getDocumentation(detail);
6749 const {command, additionalTextEdits} = this.getCodeActions(detail, filepath);
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);
6761 getCodeActions(detail, filepath) {
6762 if (!detail.codeActions || !detail.codeActions.length) {
6765 const additionalTextEdits = [];
6766 let hasRemainingCommandsOrEdits = false;
6767 for (const tsAction of detail.codeActions) {
6768 if (tsAction.commands) {
6769 hasRemainingCommandsOrEdits = true;
6771 if (tsAction.changes) {
6772 for (const change of tsAction.changes) {
6773 if (change.fileName === filepath) {
6774 additionalTextEdits.push(...change.textChanges.map(TextEdit.fromCodeEdit));
6776 hasRemainingCommandsOrEdits = true;
6782 if (hasRemainingCommandsOrEdits) {
6785 command: ApplyCompletionCodeActionCommand.ID,
6787 detail.codeActions.map((x) => ({
6788 commands: x.commands,
6789 description: x.description,
6790 changes: x.changes.filter((x2) => x2.fileName !== filepath)
6797 additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : void 0
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)) {
6806 if (!pre.match(/^\s*\*[ ]?@/) && !pre.match(/\/\*\*+[ ]?@/)) {
6809 } else if (triggerCharacter === "<") {
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}
6824 plain(detail.documentation),
6825 tagsMarkdownPreview(detail.tags)
6827 parts = parts.filter((s) => s && s.trim() != "");
6828 documentation += parts.join("\n\n");
6829 if (documentation.length) {
6831 kind: import_vscode_languageserver_protocol8.MarkupKind.Markdown,
6832 value: documentation
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();
6846 snippet.appendText(")");
6847 snippet.appendTabstop(0);
6848 item.insertText = snippet.value;
6850 async isValidFunctionCompletionContext(filepath, position, token) {
6852 const args = Position.toFileLocationRequestArgs(filepath, position);
6853 const response = await this.client.execute("quickinfo", args, token);
6854 if (response.type !== "response") {
6857 const {body} = response;
6858 switch (body && body.kind) {
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;
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;
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);
6896 // src/server/features/definitionProvider.ts
6897 var TypeScriptDefinitionProvider = class {
6898 constructor(client) {
6899 this.client = client;
6901 async getSymbolLocations(definitionType, document, position, token) {
6902 const filepath = this.client.toPath(document.uri);
6906 const args = Position.toFileLocationRequestArgs(filepath, position);
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));
6915 provideDefinition(document, position, token) {
6916 return this.getSymbolLocations("definition", document, position, token);
6918 provideTypeDefinition(document, position, token) {
6919 return this.getSymbolLocations("typeDefinition", document, position, token);
6921 provideImplementation(document, position, token) {
6922 return this.getSymbolLocations("implementation", document, position, token);
6925 var definitionProvider_default = TypeScriptDefinitionProvider;
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 = [
6933 description: "Enables semantic checking in a JavaScript file. Must be at the top of a file."
6936 value: "@ts-nocheck",
6937 description: "Disables semantic checking in a JavaScript file. Must be at the top of a file."
6940 value: "@ts-ignore",
6941 description: "Suppresses @ts-check errors on the next line of a file."
6944 var tsDirectives390 = [
6947 value: "@ts-expect-error",
6948 description: "Suppresses @ts-check errors on the next line of a file, expecting at least one to exist."
6951 var DirectiveCommentCompletionProvider = class {
6952 constructor(client) {
6953 this.client = client;
6955 provideCompletionItems(document, position, _token, context) {
6956 if (context.triggerCharacter != "@") {
6959 const file2 = this.client.toPath(document.uri);
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\-]*)?$/);
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;
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
6980 isIncomplete: false,
6983 res.startcol = doc.fixStartcol(position, ["@"]);
6989 var directiveCommentCompletions_default = DirectiveCommentCompletionProvider;
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;
6997 async provideDocumentHighlights(resource, position, token) {
6998 const file2 = this.client.toPath(resource.uri);
7002 ...Position.toFileLocationRequestArgs(file2, position),
7003 filesToSearch: [file2]
7006 const response = await this.client.execute("documentHighlights", args, token);
7007 if (response.type !== "response" || !response.body) {
7010 return flatten(response.body.filter((highlight) => highlight.file === file2).map(convertDocumentHighlight));
7016 var documentHighlight_default = TypeScriptDocumentHighlightProvider;
7017 function convertDocumentHighlight(highlight) {
7018 return highlight.highlightSpans.map((span) => {
7020 range: Range.fromTextSpan(span),
7021 kind: span.kind === "writtenReference" ? import_vscode_languageserver_protocol10.DocumentHighlightKind.Write : import_vscode_languageserver_protocol10.DocumentHighlightKind.Read
7026 // src/server/features/documentSymbol.ts
7027 var import_vscode_languageserver_protocol11 = __toModule(require_main3());
7028 var getSymbolKind2 = (kind) => {
7031 return import_vscode_languageserver_protocol11.SymbolKind.Module;
7033 return import_vscode_languageserver_protocol11.SymbolKind.Class;
7035 return import_vscode_languageserver_protocol11.SymbolKind.Enum;
7036 case Kind.interface:
7037 return import_vscode_languageserver_protocol11.SymbolKind.Interface;
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;
7047 return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7049 return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7050 case Kind.localVariable:
7051 return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7053 return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7054 case Kind.constructSignature:
7055 case Kind.constructorImplementation:
7057 case Kind.localFunction:
7058 return import_vscode_languageserver_protocol11.SymbolKind.Function;
7060 return import_vscode_languageserver_protocol11.SymbolKind.Variable;
7062 var TypeScriptDocumentSymbolProvider = class {
7063 constructor(client) {
7064 this.client = client;
7066 async provideDocumentSymbols(resource, token) {
7067 const filepath = this.client.toPath(resource.uri);
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));
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);
7102 if (shouldInclude) {
7103 bucket.push(symbolInfo);
7106 return shouldInclude;
7108 static shouldInclueEntry(item) {
7109 if (item.kind === Kind.alias) {
7112 return !!(item.text && item.text !== "<function>" && item.text !== "<class>");
7115 var documentSymbol_default = TypeScriptDocumentSymbolProvider;
7116 function containsRange(range, otherRange) {
7117 if (otherRange.start.line < range.start.line || otherRange.end.line < range.start.line) {
7120 if (otherRange.start.line > range.end.line || otherRange.end.line > range.end.line) {
7123 if (otherRange.start.line === range.start.line && otherRange.start.character < range.start.character) {
7126 if (otherRange.end.line === range.end.line && otherRange.end.character > range.end.character) {
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;
7139 async provideFoldingRanges(document, _context, token) {
7140 const file2 = this.client.toPath(document.uri);
7144 const args = {file: file2};
7145 const res = await this.client.execute("getOutliningSpans", args, token);
7146 if (res.type != "response") {
7153 return body.map((span) => this.convertOutliningSpan(span, document)).filter((foldingRange) => !!foldingRange);
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)) {
7165 let {start, end} = range;
7166 return import_vscode_languageserver_types.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
7168 static getFoldingRangeKind(span) {
7169 switch (span.kind) {
7180 var folding_default = TypeScriptFoldingProvider;
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;
7190 return this.formattingOptionsManager.formatEnabled(document);
7192 async doFormat(document, options, args, token) {
7193 if (!this.enabled(document))
7195 await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
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);
7206 async provideDocumentRangeFormattingEdits(document, range, options, token) {
7207 if (!this.enabled(document))
7209 const filepath = this.client.toPath(document.uri);
7214 line: range.start.line + 1,
7215 offset: range.start.character + 1,
7216 endLine: range.end.line + 1,
7217 endOffset: range.end.character + 1
7219 return this.doFormat(document, options, args, token);
7221 async provideDocumentFormattingEdits(document, options, token) {
7222 if (!this.enabled(document))
7224 const filepath = this.client.toPath(document.uri);
7231 endLine: document.lineCount + 1,
7234 return this.doFormat(document, options, args, token);
7236 async provideOnTypeFormattingEdits(document, position, ch, options, token) {
7237 if (!this.enabled(document))
7239 if (!this.client.configuration.formatOnType)
7241 const file2 = this.client.toPath(document.uri);
7244 await this.formattingOptionsManager.ensureConfigurationOptions(document, options.insertSpaces, options.tabSize, token);
7245 const doc = import_coc8.workspace.getDocument(document.uri);
7247 ...Position.toFileLocationRequestArgs(file2, position),
7251 const res = await this.client.execute("formatonkey", args, token);
7252 if (res.type != "response") {
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);
7270 result.push(textEdit);
7279 var formatting_default = TypeScriptFormattingProvider;
7281 // src/server/features/hover.ts
7282 var TypeScriptHoverProvider = class {
7283 constructor(client) {
7284 this.client = client;
7286 async provideHover(document, position, token) {
7287 const filepath = this.client.toPath(document.uri);
7291 const args = Position.toFileLocationRequestArgs(filepath, position);
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;
7297 contents: TypeScriptHoverProvider.getContents(data),
7298 range: Range.fromTextSpan(data)
7305 static getContents(data) {
7307 if (data.displayString) {
7308 parts.push({language: "typescript", value: data.displayString});
7310 const tags = tagsMarkdownPreview(data.tags);
7311 parts.push(data.documentation + (tags ? "\n\n" + tags : ""));
7315 var hover_default = TypeScriptHoverProvider;
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);
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) => {
7328 uri: this.client.toResource(reference.file),
7330 start: Position.fromLocation(reference.start),
7332 line: reference.start.line,
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);
7343 codeLens.command = {
7344 title: "0 implementations",
7349 getCommand(locations, codeLens) {
7350 let {uri} = codeLens.data;
7352 title: this.getTitle(locations),
7353 command: locations.length ? "editor.action.showReferences" : "",
7354 arguments: [uri, codeLens.range.start, locations]
7357 getTitle(locations) {
7358 return locations.length === 1 ? "1 implementation" : `${locations.length} implementations`;
7360 extractSymbol(document, item, _parent) {
7361 switch (item.kind) {
7362 case Kind.interface:
7363 return super.getSymbolRange(document, item);
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);
7377 var implementationsCodeLens_default = TypeScriptImplementationsCodeLensProvider;
7379 // src/server/features/importFix.ts
7380 var import_coc9 = __toModule(require("coc.nvim"));
7381 var import_vscode_languageserver_protocol12 = __toModule(require_main3());
7383 // src/server/utils/helper.ts
7415 // src/server/features/importFix.ts
7416 var ImportFixProvider = class {
7417 constructor(bufferSyncSupport) {
7418 this.bufferSyncSupport = bufferSyncSupport;
7420 async provideCodeActions(document, _range, context, _token) {
7421 if (this.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
7424 let diagnostics = context.diagnostics.filter((d) => d.code == 2304);
7425 if (!diagnostics.length)
7429 let doc = import_coc9.workspace.getDocument(document.uri);
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)
7437 if (nodeModules.indexOf(name) !== -1) {
7440 range: import_vscode_languageserver_protocol12.Range.create(0, 0, 0, 0),
7441 newText: `import ${name} from '${name}'
7444 command = "tsserver.organizeImports";
7449 [document.uri]: edits
7455 title: `fix import`,
7456 command: "tsserver.organizeImports"
7459 title: `Add import ${names.join(", ")}`,
7465 var importFix_default = ImportFixProvider;
7467 // src/server/features/moduleInstall.ts
7468 var import_coc11 = __toModule(require("coc.nvim"));
7469 var import_vscode_languageserver_protocol13 = __toModule(require_main3());
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) => {
7480 timer = setTimeout(() => {
7481 reject(new Error(`timeout after ${timeout}s`));
7484 import_child_process.exec(cmd, {cwd}, (err, stdout) => {
7486 clearTimeout(timer);
7488 reject(new Error(`exited with ${err.code}`));
7495 async function getManager() {
7496 let res = await import_coc10.workspace.findUp(["yarn.lock", "package-lock.json"]);
7499 return res.endsWith("yarn.lock") ? "yarn" : "npm";
7501 async function moduleExists(name) {
7503 let content = await runCommand(`npm info ${name} --json`, process.cwd());
7506 let obj = JSON.parse(content);
7507 if (obj.error != null)
7515 function distinct(array, keyFn) {
7517 return array.filter((element, position) => {
7518 return array.indexOf(element) === position;
7521 const seen = Object.create(null);
7522 return array.filter((elem) => {
7523 const key = keyFn(elem);
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");
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(" ")}`;
7543 let exists = await Promise.all(arr.map((name) => {
7544 return moduleExists(name).then((exists2) => {
7545 return exists2 ? name : null;
7548 let manager = await getManager();
7549 exists = exists.filter((s) => s != null);
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(" ")}`;
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);
7561 statusItem.dispose();
7562 import_coc10.window.showMessage(`Install error ${e.message}`, "error");
7565 statusItem.dispose();
7566 import_coc10.window.showMessage(`Installed: ${exists.join(" ")}`, "more");
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]);
7577 async provideCodeActions(document, _range, context, _token) {
7578 const uri = import_coc11.Uri.parse(document.uri);
7579 if (uri.scheme != "file")
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;
7587 names = names.filter((s) => s != null);
7591 for (let name of names) {
7592 let title = `install ${name}`;
7594 title: `install ${name}`,
7595 command: "_tsserver.installModule",
7596 arguments: [document.uri, name]
7598 let codeAction = import_vscode_languageserver_protocol13.CodeAction.create(title, command, import_vscode_languageserver_protocol13.CodeActionKind.QuickFix);
7599 actions.push(codeAction);
7604 var moduleInstall_default = InstallModuleProvider;
7606 // src/server/features/quickfix.ts
7607 var import_coc13 = __toModule(require("coc.nvim"));
7608 var import_vscode_languageserver_protocol14 = __toModule(require_main3());
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";
7619 let client = await this.service.getClientHost();
7620 client.reloadProjects();
7621 import_coc12.window.showMessage("projects reloaded");
7624 var OpenTsServerLogCommand = class {
7625 constructor(service) {
7626 this.service = service;
7627 this.id = "tsserver.openTsServerLog";
7630 let client = await this.service.getClientHost();
7631 client.serviceClient.openTsServerLogFile();
7634 var TypeScriptGoToProjectConfigCommand = class {
7635 constructor(service) {
7636 this.service = service;
7637 this.id = "tsserver.goToProjectConfig";
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}`);
7647 await goToProjectConfig(client, doc.uri);
7650 async function goToProjectConfig(clientHost, uri) {
7651 const client = clientHost.serviceClient;
7652 const file2 = client.toPath(uri);
7655 res = await client.execute("projectInfo", {file: file2, needFileNameList: false}, import_coc12.CancellationToken.None);
7658 if (!res || !res.body) {
7659 import_coc12.window.showMessage("Could not determine TypeScript or JavaScript project.", "warning");
7662 const {configFileName} = res.body;
7663 if (configFileName && !isImplicitProjectConfigFile(configFileName)) {
7664 await import_coc12.workspace.openResource(import_coc12.Uri.file(configFileName).toString());
7667 import_coc12.window.showMessage("Config file not found", "warning");
7669 function isImplicitProjectConfigFile(configFileName) {
7670 return configFileName.indexOf("/dev/null/") === 0;
7672 var autoFixableDiagnosticCodes = new Set([
7677 var AutoFixCommand = class {
7678 constructor(service) {
7679 this.service = service;
7680 this.id = "tsserver.executeAutofix";
7683 if (this.service.state != import_coc12.ServiceStat.Running) {
7684 throw new Error("service not running");
7687 let client = await this.service.getClientHost();
7688 let document = await import_coc12.workspace.document;
7689 let handles = await client.handles(document.textDocument);
7691 throw new Error(`Document ${document.uri} is not handled by tsserver.`);
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;
7702 names2 = names2.filter((s) => s != null);
7703 if (names2.length) {
7704 installModules(document.uri, names2).catch((e) => {
7705 console.error(e.message);
7709 diagnostics = diagnostics.filter((x) => autoFixableDiagnosticCodes.has(x.code));
7710 if (diagnostics.length == 0)
7712 diagnostics = diagnostics.reduce((arr, curr) => {
7713 if (curr.code == 2304 && arr.findIndex((o) => o.message == curr.message) != -1)
7721 for (let diagnostic of diagnostics) {
7723 ...Range.toFileRangeRequestArgs(file2, diagnostic.range),
7724 errorCodes: [+diagnostic.code]
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) {
7735 range: import_vscode_languageserver_types2.Range.create(0, 0, 0, 0),
7736 newText: `import ${name} from '${name}'
7739 command = "tsserver.organizeImports";
7744 const fix = response.body[0];
7745 for (let change of fix.changes) {
7746 if (change.fileName != file2)
7748 for (let ch of change.textChanges) {
7750 range: Range.fromTextSpan(ch),
7757 await document.applyEdits(edits);
7759 import_coc12.commands.executeCommand(command);
7762 var ConfigurePluginCommand = class {
7763 constructor(pluginManager) {
7764 this.pluginManager = pluginManager;
7765 this.id = "_typescript.configurePlugin";
7767 execute(pluginId, configuration) {
7768 this.pluginManager.setConfiguration(pluginId, configuration);
7771 function registCommand(cmd) {
7772 let {id, execute} = cmd;
7773 return import_coc12.commands.registerCommand(id, execute, cmd);
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;
7783 async execute(action) {
7784 return applyCodeActionCommands(this.client, action);
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;
7795 async execute(document, file2, tsAction) {
7796 if (!tsAction.fixId) {
7799 await this.formattingConfigurationManager.ensureConfigurationForDocument(document, import_vscode_languageserver_protocol14.CancellationToken.None);
7805 fixId: tsAction.fixId
7808 const res = await this.client.execute("getCombinedCodeFix", args, import_vscode_languageserver_protocol14.CancellationToken.None);
7809 if (res.type != "response") {
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);
7826 var ApplyFixAllCodeAction = ApplyFixAllCodeAction2;
7827 ApplyFixAllCodeAction.ID = "_typescript.applyFixAllCodeAction";
7828 var DiagnosticsSet = class {
7829 constructor(_values) {
7830 this._values = _values;
7832 static from(diagnostics) {
7833 const values = new Map();
7834 for (const diagnostic of diagnostics) {
7835 values.set(DiagnosticsSet.key(diagnostic), diagnostic);
7837 return new DiagnosticsSet(values);
7839 static key(diagnostic) {
7840 const {start, end} = diagnostic.range;
7841 return `${diagnostic.code}-${start.line},${start.character}-${end.line},${end.character}`;
7844 return this._values.values();
7847 var SupportedCodeActionProvider = class {
7848 constructor(client) {
7849 this.client = client;
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);
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") {
7864 let codes = res.body.map((code) => +code).filter((code) => !isNaN(code));
7865 resolve(new Set(codes));
7869 return Promise.resolve(this._supportedCodeActions);
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);
7880 async provideCodeActions(document, _range, context, token) {
7881 const file2 = this.client.toPath(document.uri);
7885 await this.formattingConfigurationManager.ensureConfigurationForDocument(document, token);
7886 const fixableDiagnostics = await this.supportedCodeActionProvider.getFixableDiagnosticsForContext(context);
7887 if (!fixableDiagnostics.length) {
7890 if (this.client.bufferSyncSupport.hasPendingDiagnostics(document.uri)) {
7894 for (const diagnostic of fixableDiagnostics) {
7895 results.push(...await this.getFixesForDiagnostic(document, file2, diagnostic, token));
7899 async getFixesForDiagnostic(document, file2, diagnostic, token) {
7901 ...Range.toFileRangeRequestArgs(file2, diagnostic.range),
7902 errorCodes: [+diagnostic.code]
7904 const codeFixesResponse = await this.client.execute("getCodeFixes", args, token);
7905 if (codeFixesResponse.type != "response") {
7908 if (codeFixesResponse.body) {
7910 for (const tsCodeFix of codeFixesResponse.body) {
7911 results.push(...await this.getAllFixesForTsCodeAction(document, file2, diagnostic, tsCodeFix));
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];
7922 getSingleFixForTsCodeAction(diagnostic, tsAction) {
7923 const codeAction = {
7924 title: tsAction.description,
7925 kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
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
7939 async getFixAllForTsCodeAction(document, file2, diagnostic, tsAction) {
7940 if (!tsAction.fixId || !this.client.apiVersion.gte(api_default.v270)) {
7943 if (!this.client.diagnosticsManager.getDiagnostics(document.uri).some((x) => x.code === diagnostic.code && x !== diagnostic)) {
7947 title: tsAction.fixAllDescription || "Fix all in file",
7948 kind: import_vscode_languageserver_protocol14.CodeActionKind.QuickFix
7950 action.diagnostics = [diagnostic];
7952 command: ApplyFixAllCodeAction.ID,
7953 arguments: [document, file2, tsAction],
7959 var quickfix_default = TypeScriptQuickFixProvider;
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;
7969 async execute(document, file2, refactor, action, range) {
7971 ...Range.toFileRangeRequestArgs(file2, range),
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) {
7980 const workspaceEdit = await this.toWorkspaceEdit(body);
7981 if (!await import_coc14.workspace.applyEdit(workspaceEdit)) {
7984 const renameLocation = body.renameLocation;
7985 if (renameLocation) {
7986 import_coc14.commands.executeCommand("editor.action.rename", document.uri, Position.fromLocation(renameLocation));
7990 async toWorkspaceEdit(body) {
7991 for (const edit of body.edits) {
7992 await import_coc14.workspace.createFile(edit.fileName, {ignoreIfExists: true});
7994 let workspaceEdit = WorkspaceEdit.fromFileCodeEdits(this.client, body.edits);
7995 return workspaceEdit;
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;
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));
8010 let label = info.actions[idx].name;
8013 return this.doRefactoring.execute(document, file2, info.name, label, range);
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));
8026 async provideCodeActions(document, range, context, token) {
8027 if (!this.shouldTrigger(context)) {
8030 const file2 = this.client.toPath(document.uri);
8033 await this.formattingOptionsManager.ensureConfigurationForDocument(document, token);
8034 const args = Range.toFileRangeRequestArgs(file2, range);
8037 response = await this.client.interruptGetErr(() => {
8038 return this.client.execute("getApplicableRefactors", args, token);
8040 if (!response || !response.body) {
8046 return this.convertApplicableRefactors(response.body, document, file2, range, context.only && context.only.some((v) => v.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor)));
8048 convertApplicableRefactors(body, document, file2, rangeOrSelection, setPrefrred) {
8050 for (const info of body) {
8051 if (info.notApplicableReason)
8053 if (!info.inlineable) {
8054 const codeAction = {
8055 title: info.description,
8056 kind: import_vscode_languageserver_protocol15.CodeActionKind.Refactor
8058 codeAction.command = {
8059 title: info.description,
8060 command: SelectRefactorCommand.ID,
8061 arguments: [document, file2, info, rangeOrSelection]
8063 actions.push(codeAction);
8065 for (const action of info.actions) {
8066 let codeAction = this.refactorActionToCodeAction(action, document, file2, info, rangeOrSelection);
8068 codeAction.isPreferred = TypeScriptRefactorProvider2.isPreferred(action, info.actions);
8070 actions.push(codeAction);
8076 refactorActionToCodeAction(action, document, file2, info, rangeOrSelection) {
8077 const codeAction = {
8078 title: action.description,
8079 kind: TypeScriptRefactorProvider2.getKind(action)
8081 codeAction.command = {
8082 title: action.description,
8083 command: ApplyRefactoringCommand.ID,
8084 arguments: [document, file2, info.name, action.name, rangeOrSelection]
8088 shouldTrigger(context) {
8089 if (context.only && context.only.every((o) => !o.includes(import_vscode_languageserver_protocol15.CodeActionKind.Refactor))) {
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;
8102 return import_vscode_languageserver_protocol15.CodeActionKind.Refactor;
8104 static isPreferred(action, allActions) {
8105 let kind = TypeScriptRefactorProvider2.getKind(action);
8106 if (TypeScriptRefactorProvider2.extractConstantKind == kind) {
8107 const getScope = (name2) => {
8109 const scope2 = (_a = name2.match(/scope_(\d)/)) == null ? void 0 : _a[1];
8110 return scope2 ? +scope2 : void 0;
8112 const scope = getScope(action.name);
8113 if (typeof scope !== "number") {
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;
8121 let {name} = action;
8122 if (name.startsWith("Extract to type alias") || name.startsWith("Extract to interface")) {
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]
8135 var refactor_default = TypeScriptRefactorProvider;
8137 // src/server/features/references.ts
8138 var TypeScriptReferences = class {
8139 constructor(client) {
8140 this.client = client;
8142 async provideReferences(document, position, context, token) {
8143 const filepath = this.client.toPath(document.uri);
8146 const args = Position.toFileLocationRequestArgs(filepath, position);
8148 const msg = await this.client.execute("references", args, token);
8149 if (!msg || msg.type != "response" || !msg.body) {
8153 for (const ref of msg.body.refs) {
8154 if (!context.includeDeclaration && ref.isDefinition) {
8157 const url = this.client.toResource(ref.file);
8158 const location = Location2.fromTextSpan(url, ref);
8159 result.push(location);
8167 var references_default = TypeScriptReferences;
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, {
8177 }).then((response) => {
8178 if (!response || response.type != "response" || !response.body) {
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]
8189 codeLens.command = {
8190 title: "0 references",
8196 extractSymbol(document, item, parent) {
8197 if (parent && parent.kind === Kind.enum) {
8198 return super.getSymbolRange(document, item);
8200 switch (item.kind) {
8205 if (!item.kindModifiers.match(/\bexport\b/)) {
8209 if (item.text === "<class>") {
8213 case Kind.memberVariable:
8214 case Kind.memberGetAccessor:
8215 case Kind.memberSetAccessor:
8216 case Kind.constructorImplementation:
8217 case Kind.interface:
8220 return super.getSymbolRange(document, item);
8225 var referencesCodeLens_default = TypeScriptReferencesCodeLensProvider;
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;
8235 async prepareRename(document, position, token) {
8236 const response = await this.execRename(document, position, token);
8237 if (!response || response.type !== "response" || !response.body) {
8240 const renameInfo = response.body.info;
8241 if (!renameInfo.canRename) {
8242 return Promise.reject(new Error("Invalid location for rename."));
8244 if (this.client.apiVersion.gte(api_default.v310)) {
8245 const triggerSpan = renameInfo.triggerSpan;
8247 const range = Range.fromTextSpan(triggerSpan);
8253 async provideRenameEdits(document, position, newName, token) {
8254 const response = await this.execRename(document, position, token);
8255 if (!response || response.type !== "response" || !response.body) {
8258 const renameInfo = response.body.info;
8259 if (!renameInfo.canRename) {
8260 return Promise.reject(new Error("Invalid location for rename."));
8262 if (this.client.apiVersion.gte(api_default.v310)) {
8263 if (renameInfo.fileToRename) {
8264 const edits = await this.renameFile(renameInfo.fileToRename, newName, token);
8268 return Promise.reject(new Error("An error occurred while renaming file"));
8272 return this.toWorkspaceEdit(response.body.locs, newName);
8274 async execRename(document, position, token) {
8275 const file2 = this.client.toPath(document.uri);
8279 ...Position.toFileLocationRequestArgs(file2, position),
8280 findInStrings: false,
8281 findInComments: false
8283 await this.fileConfigurationManager.ensureConfigurationForDocument(document, token);
8284 return this.client.interruptGetErr(() => {
8285 return this.client.execute("rename", args, token);
8288 toWorkspaceEdit(locations, newName) {
8290 for (const spanGroup of locations) {
8291 const uri = this.client.toResource(spanGroup.file);
8294 for (const textSpan of spanGroup.locs) {
8296 range: Range.fromTextSpan(textSpan),
8297 newText: (textSpan.prefixText || "") + newName + (textSpan.suffixText || "")
8304 async renameFile(fileToRename, newName, token) {
8305 if (!import_path3.default.extname(newName)) {
8306 newName += import_path3.default.extname(fileToRename);
8308 const dirname = import_path3.default.dirname(fileToRename);
8309 const newFilePath = import_path3.default.join(dirname, newName);
8312 oldFilePath: fileToRename,
8315 const response = await this.client.execute("getEditsForFileRename", args, token);
8316 if (response.type !== "response" || !response.body) {
8319 const edits = WorkspaceEdit.fromFileCodeEdits(this.client, response.body);
8320 edits.documentChanges = edits.documentChanges || [];
8321 edits.documentChanges.push({
8323 oldUri: import_coc15.Uri.file(fileToRename).toString(),
8324 newUri: import_coc15.Uri.file(newFilePath).toString(),
8327 ignoreIfExists: true
8333 var rename_default = TypeScriptRenameProvider;
8335 // src/server/features/signatureHelp.ts
8336 var TypeScriptSignatureHelpProvider = class {
8337 constructor(client) {
8338 this.client = client;
8340 async provideSignatureHelp(document, position, token) {
8341 const filepath = this.client.toPath(document.uri);
8345 const args = Position.toFileLocationRequestArgs(filepath, position);
8348 response = await this.client.interruptGetErr(() => this.client.execute("signatureHelp", args, token));
8352 if (response.type !== "response" || !response.body) {
8355 let info = response.body;
8357 activeSignature: info.selectedItemIndex,
8358 activeParameter: this.getActiveParmeter(info),
8359 signatures: info.items.map((signature) => {
8360 return this.convertSignature(signature);
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);
8370 return info.argumentIndex;
8372 convertSignature(item) {
8374 let parameters = item.parameters.map((p) => {
8376 label: plain(p.displayParts),
8377 documentation: markdownDocumentation(p.documentation, [])
8380 let label = plain(item.prefixDisplayParts);
8381 label += parameters.map((parameter) => parameter.label).join(plain(item.separatorDisplayParts));
8382 label += plain(item.suffixDisplayParts);
8385 documentation: markdownDocumentation(item.documentation, (_a = item.tags) == null ? void 0 : _a.filter((x) => x.name !== "param")),
8390 TypeScriptSignatureHelpProvider.triggerCharacters = ["(", ",", "<"];
8391 var signatureHelp_default = TypeScriptSignatureHelpProvider;
8393 // src/server/features/smartSelect.ts
8394 var SmartSelection = class {
8395 constructor(client) {
8396 this.client = client;
8398 async provideSelectionRanges(document, positions, token) {
8399 const file2 = this.client.toPath(document.uri);
8405 locations: positions.map(Position.toLocation)
8407 const response = await this.client.execute("selectionRange", args, token);
8408 if (response.type !== "response" || !response.body) {
8411 return response.body.map(SmartSelection.convertSelectionRange);
8413 static convertSelectionRange(selectionRange) {
8415 range: Range.fromTextSpan(selectionRange.textSpan),
8416 parent: selectionRange.parent ? SmartSelection.convertSelectionRange(selectionRange.parent) : void 0
8420 var smartSelect_default = SmartSelection;
8422 // src/server/features/updatePathOnRename.ts
8423 var import_coc16 = __toModule(require("coc.nvim"));
8424 var import_vscode_languageserver_protocol16 = __toModule(require_main3());
8426 // src/server/utils/mutex.ts
8433 if (this.count > 0 && this.tasks.length > 0) {
8435 let next = this.tasks.shift();
8440 return this.count == 0;
8443 return new Promise((res) => {
8445 let released = false;
8454 this.tasks.push(task);
8455 process.nextTick(this.sched.bind(this));
8459 return this.acquire().then((release) => {
8460 return f().then((res) => {
8471 // src/server/features/updatePathOnRename.ts
8473 return new Promise((resolve) => {
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();
8491 await this.doRename(e.oldUri, e.newUri);
8494 this.client.logger.error("Error on rename:", e2);
8497 }, null, this.disposables);
8500 import_coc16.disposeAll(this.disposables);
8502 async doRename(oldResource, newResource) {
8503 if (oldResource.scheme !== "file" || newResource.scheme !== "file") {
8506 const targetFile = newResource.fsPath;
8507 const oldFile = oldResource.fsPath;
8508 const newUri = newResource.toString();
8509 let oldDocument = import_coc16.workspace.getDocument(oldResource.toString());
8511 await import_coc16.workspace.nvim.command(`silent ${oldDocument.bufnr}bwipeout!`);
8513 let document = import_coc16.workspace.getDocument(newUri);
8515 await import_coc16.workspace.nvim.command(`silent ${document.bufnr}bwipeout!`);
8518 document = await import_coc16.workspace.loadFile(newUri);
8522 const edits = await this.getEditsForFileRename(document.textDocument, oldFile, targetFile);
8525 if (await this.promptUser(newResource)) {
8526 await import_coc16.workspace.applyEdit(edits);
8529 async promptUser(newResource) {
8530 return await import_coc16.window.showPrompt(`Update imports for moved file: ${newResource.fsPath}?`);
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(() => {
8536 oldFilePath: oldFile,
8537 newFilePath: newFile
8539 return this.client.execute("getEditsForFileRename", args, import_vscode_languageserver_protocol16.CancellationToken.None);
8541 if (!response || response.type != "response" || !response.body) {
8545 for (const edit of response.body) {
8546 if (edit.fileName.match(/[\/\\]node_modules[\/\\]/gi)) {
8549 for (const change of edit.textChanges) {
8550 if (change.newText.match(/\/node_modules\//gi)) {
8556 return WorkspaceEdit.fromFileCodeEdits(this.client, edits);
8559 var updatePathOnRename_default = UpdateImportsOnFileRenameHandler;
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";
8569 async _execute(client, document) {
8570 let file2 = client.toPath(document.uri);
8579 const response = await client.interruptGetErr(() => client.execute("organizeImports", args, import_vscode_languageserver_protocol17.CancellationToken.None));
8580 if (!response || response.type != "response" || !response.success) {
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]);
8588 await doc.applyEdits(edit.changes[keys[0]]);
8593 await import_coc17.workspace.applyEdit(edit);
8595 async execute(document) {
8596 let client = await this.service.getClientHost();
8598 let doc = await import_coc17.workspace.document;
8599 if (!doc.attached) {
8600 throw new Error(`Document not attached.`);
8602 if (client.serviceClient.modeIds.indexOf(doc.filetype) == -1) {
8603 throw new Error(`filetype "${doc.filetype}" not supported by tsserver.`);
8605 document = doc.textDocument;
8607 await this._execute(client.serviceClient, document);
8610 var OrganizeImportsCodeActionProvider = class {
8611 constructor(client, fileConfigManager) {
8612 this.client = client;
8613 this.fileConfigManager = fileConfigManager;
8615 providedCodeActionKinds: [import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports]
8618 async provideCodeActions(document, _range, context, token) {
8619 if (this.client.modeIds.indexOf(document.languageId) == -1)
8621 if (!context.only || !context.only.includes(import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports)) {
8624 await this.fileConfigManager.ensureConfigurationForDocument(document, token);
8625 const action = import_vscode_languageserver_protocol17.CodeAction.create("Organize Imports", {
8627 command: "tsserver.organizeImports",
8628 arguments: [document]
8629 }, import_vscode_languageserver_protocol17.CodeActionKind.SourceOrganizeImports);
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 () => {
8649 this.registerProviders(client, typingsStatus);
8653 configurationChanged() {
8654 const config = import_coc18.workspace.getConfiguration(this.id, null);
8655 this.client.diagnosticsManager.setEnableSuggestions(this.id, config.get(suggestionSetting, true));
8658 import_coc18.disposeAll(this.disposables);
8660 _register(disposable) {
8661 this.disposables.push(disposable);
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), ["@"]));
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));
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]));
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]));
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)));
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)));
8708 if (this.client.apiVersion.gte(api_default.v350)) {
8709 this._register(import_coc18.languages.registerSelectionRangeProvider(languageIds, new smartSelect_default(this.client)));
8712 handles(resource, doc) {
8713 if (doc && this.description.modeIds.indexOf(doc.languageId) >= 0) {
8716 const base = import_path4.default.basename(import_coc18.Uri.parse(resource).fsPath);
8717 return !!base && (!!this.description.configFilePattern && this.description.configFilePattern.test(base));
8720 return this.description.id;
8722 get diagnosticSource() {
8723 return this.description.diagnosticSource;
8725 triggerAllDiagnostics() {
8726 this.client.bufferSyncSupport.requestAllDiagnostics();
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) {
8734 if (diag.reportUnnecessary && diag.severity === import_vscode_languageserver_protocol18.DiagnosticSeverity.Information) {
8742 var languageProvider_default = LanguageProvider;
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());
8751 // src/utils/fileSchemess.ts
8755 var disabledSchemes = new Set([
8760 // src/server/typescriptService.ts
8762 (function(ServerResponse2) {
8764 constructor(reason) {
8765 this.reason = reason;
8766 this.type = "cancelled";
8769 ServerResponse2.Cancelled = Cancelled;
8770 ServerResponse2.NoContent = new class {
8772 this.type = "noContent";
8775 })(ServerResponse || (ServerResponse = {}));
8776 var ExectuionTarget;
8777 (function(ExectuionTarget2) {
8778 ExectuionTarget2[ExectuionTarget2["Semantic"] = 0] = "Semantic";
8779 ExectuionTarget2[ExectuionTarget2["Syntax"] = 1] = "Syntax";
8780 })(ExectuionTarget || (ExectuionTarget = {}));
8782 // src/server/callbackMap.ts
8783 var CallbackMap = class {
8785 this._callbacks = new Map();
8786 this._asyncCallbacks = new Map();
8789 const cancellation = new ServerResponse.Cancelled(cause);
8790 for (const callback of this._callbacks.values()) {
8791 callback.onSuccess(cancellation);
8793 this._callbacks.clear();
8794 for (const callback of this._asyncCallbacks.values()) {
8795 callback.onSuccess(cancellation);
8797 this._asyncCallbacks.clear();
8799 add(seq, callback, isAsync) {
8801 this._asyncCallbacks.set(seq, callback);
8803 this._callbacks.set(seq, callback);
8807 const callback = this._callbacks.get(seq) || this._asyncCallbacks.get(seq);
8812 if (!this._callbacks.delete(seq)) {
8813 this._asyncCallbacks.delete(seq);
8818 // src/server/features/bufferSyncSupport.ts
8819 var import_coc20 = __toModule(require("coc.nvim"));
8820 var import_vscode_languageserver_protocol19 = __toModule(require_main3());
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;
8831 trigger(task, delay = this.defaultDelay) {
8834 this.cancelTimeout();
8836 if (!this.completionPromise) {
8837 this.completionPromise = new Promise((resolve) => {
8838 this.onSuccess = resolve;
8840 this.completionPromise = null;
8841 this.onSuccess = null;
8842 let result = this.task && this.task();
8847 if (delay >= 0 || this.timeout === null) {
8848 this.timeout = setTimeout(() => {
8849 this.timeout = null;
8850 if (this.onSuccess) {
8851 this.onSuccess(void 0);
8853 }, delay >= 0 ? delay : this.defaultDelay);
8855 return this.completionPromise;
8858 if (this.timeout !== null) {
8859 clearTimeout(this.timeout);
8860 this.timeout = null;
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) {
8881 case typescriptreact:
8885 case javascriptreact:
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") {
8898 return resource.toString();
8900 var ResourceMap = class {
8901 constructor(_normalizePath = defaultPathNormalizer) {
8902 this._normalizePath = _normalizePath;
8903 this._map = new Map();
8906 return this._map.size;
8909 return this._map.values();
8912 const file2 = this.toKey(uri);
8913 return !!file2 && this._map.has(file2);
8916 const file2 = this.toKey(uri);
8919 let entry = this._map.get(file2);
8920 return entry ? entry.value : void 0;
8923 const file2 = this.toKey(uri);
8925 this._map.set(file2, {uri, value});
8929 const file2 = this.toKey(uri);
8931 this._map.delete(file2);
8935 return Array.from(this._map.values()).map((x) => x.value);
8938 return Array.from(this._map.values()).map((x) => x.uri);
8944 const key = this._normalizePath ? this._normalizePath(uri) : uri;
8948 return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
8950 isCaseInsensitivePath(path8) {
8951 if (isWindowsPath(path8)) {
8954 return path8[0] === "/" && this.onIsCaseInsenitiveFileSystem;
8956 get onIsCaseInsenitiveFileSystem() {
8957 if (process.platform === "win32") {
8960 if (process.platform === "darwin") {
8966 function isWindowsPath(path8) {
8967 return /^[a-zA-Z]:\\/.test(path8);
8970 // src/server/features/bufferSyncSupport.ts
8972 (function(BufferKind2) {
8973 BufferKind2[BufferKind2["TypeScript"] = 1] = "TypeScript";
8974 BufferKind2[BufferKind2["JavaScript"] = 2] = "JavaScript";
8975 })(BufferKind || (BufferKind = {}));
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 {
8994 var OpenOperation = class {
9000 var ChangeOperation = class {
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;
9016 file: this.filepath,
9017 fileContent: this.document.getText(),
9018 projectRootPath: this.client.getProjectRootPath(this.document.uri)
9020 const scriptKind = mode2ScriptKind(this.document.languageId);
9022 args.scriptKindName = scriptKind;
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);
9030 this.synchronizer.open(this.resource, args);
9034 return this.document.uri;
9037 return this.document.lineCount;
9040 if (this.document.languageId.startsWith("javascript")) {
9046 if (this.state !== 2) {
9051 return this.synchronizer.close(this.resource, this.filepath);
9053 onContentChanged(events2) {
9054 if (this.state !== 2) {
9055 console.error(`Unexpected buffer state: ${this.state}`);
9057 this.synchronizer.change(this.resource, this.filepath, events2);
9060 var SyncedBufferMap = class extends ResourceMap {
9061 getForPath(filePath) {
9062 return this.get(import_coc20.Uri.file(filePath).toString());
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);
9078 var BufferSynchronizer = class {
9079 constructor(client, pathNormalizer) {
9080 this.client = client;
9081 this._pending = new ResourceMap(pathNormalizer);
9083 open(resource, args) {
9084 if (this.supportsBatching) {
9085 this.updatePending(resource, new OpenOperation(args));
9087 this.client.executeWithoutWaitingForResponse("open", args);
9090 close(resource, filepath) {
9091 if (this.supportsBatching) {
9092 return this.updatePending(resource, new CloseOperation(filepath));
9094 const args = {file: filepath};
9095 this.client.executeWithoutWaitingForResponse("close", args);
9099 change(resource, filepath, events2) {
9100 if (!events2.length) {
9103 if (this.supportsBatching) {
9104 this.updatePending(resource, new ChangeOperation({
9106 textChanges: events2.map((change) => ({
9107 newText: change.text,
9108 start: Position.toLocation(change.range.start),
9109 end: Position.toLocation(change.range.end)
9113 for (const {range, text} of events2) {
9116 ...Range.toFormattingRequestArgs(filepath, range)
9118 this.client.executeWithoutWaitingForResponse("change", args);
9123 this._pending.clear();
9125 beforeCommand(command) {
9126 if (command === "updateOpen") {
9132 if (!this.supportsBatching) {
9133 this._pending.clear();
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) {
9143 changedFiles.push(change.args);
9146 openFiles.push(change.args);
9149 closedFiles.push(change.args);
9153 this.client.execute("updateOpen", {changedFiles, closedFiles, openFiles}, import_vscode_languageserver_protocol19.CancellationToken.None, {nonRecoverable: true});
9154 this._pending.clear();
9157 get supportsBatching() {
9158 return this.client.apiVersion.gte(api_default.v340);
9160 updatePending(resource, op) {
9163 const existing = this._pending.get(resource);
9164 switch (existing == null ? void 0 : existing.type) {
9166 this._pending.delete(resource);
9171 if (this._pending.has(resource)) {
9174 this._pending.set(resource, op);
9178 var GetErrRequest = class {
9179 constructor(client, uris, _token, onDone) {
9181 this._token = _token;
9183 let files = uris.map((uri) => client.normalizePath(uri));
9188 const done = () => {
9195 client.executeAsync("geterr", args, _token.token).then(done, done);
9197 static executeGetErrRequest(client, uris, onDone) {
9198 const token = new import_vscode_languageserver_protocol19.CancellationTokenSource();
9199 return new GetErrRequest(client, uris, token, onDone);
9203 this._token.cancel();
9205 this._token.dispose();
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);
9229 if (this.listening) {
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);
9239 return this.syncedBuffers.has(resource);
9242 this.pendingDiagnostics.clear();
9243 import_coc20.disposeAll(this.disposables);
9244 this._onWillChange.dispose();
9245 this._onDelete.dispose();
9247 ensureHasBuffer(resource) {
9248 if (this.syncedBuffers.has(resource)) {
9251 const existingDocument = import_coc20.workspace.textDocuments.find((doc) => doc.uri.toString() === resource);
9252 if (existingDocument) {
9253 return this.openTextDocument(existingDocument);
9257 toResource(filePath) {
9258 const buffer = this.syncedBuffers.getForPath(filePath);
9260 return buffer.resource;
9261 return import_coc20.Uri.file(filePath).toString();
9265 (_a = this.pendingGetErr) == null ? void 0 : _a.cancel();
9266 this.pendingDiagnostics.clear();
9267 this.synchronizer.reset();
9271 for (const buffer of this.syncedBuffers.allBuffers) {
9275 openTextDocument(document) {
9276 if (!this.modeIds.has(document.languageId)) {
9279 const resource = document.uri;
9280 const filepath = this.client.normalizePath(import_coc20.Uri.parse(resource));
9284 if (this.syncedBuffers.has(resource)) {
9287 const syncedBuffer = new SyncedBuffer(document, filepath, this.client, this.synchronizer);
9288 this.syncedBuffers.set(resource, syncedBuffer);
9289 syncedBuffer.open();
9290 this.requestDiagnostic(syncedBuffer);
9293 closeResource(resource) {
9294 const syncedBuffer = this.syncedBuffers.get(resource);
9295 if (!syncedBuffer) {
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();
9306 onDidCloseTextDocument(document) {
9307 this.closeResource(document.uri);
9309 onDidChangeTextDocument(e) {
9310 const syncedBuffer = this.syncedBuffers.get(e.textDocument.uri);
9311 if (!syncedBuffer) {
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();
9323 beforeCommand(command) {
9324 this.synchronizer.beforeCommand(command);
9327 if (!this.pendingGetErr) {
9330 this.pendingGetErr.cancel();
9331 this.pendingGetErr = void 0;
9333 this.triggerDiagnostics();
9337 const handledResources = resources.filter((resource) => {
9338 let syncedBuffer = this.syncedBuffers.get(resource.toString());
9339 return syncedBuffer && this.shouldValidate(syncedBuffer);
9341 if (!handledResources.length) {
9344 for (const resource of handledResources) {
9345 this.pendingDiagnostics.set(resource.toString(), Date.now());
9347 this.triggerDiagnostics();
9349 triggerDiagnostics(delay = 200) {
9350 this.diagnosticDelayer.trigger(() => {
9351 this.sendPendingDiagnostics();
9354 requestAllDiagnostics() {
9355 for (const buffer of this.syncedBuffers.allBuffers) {
9356 if (this.shouldValidate(buffer)) {
9357 this.pendingDiagnostics.set(buffer.resource, Date.now());
9360 this.triggerDiagnostics();
9362 requestDiagnostic(buffer) {
9363 if (!this.shouldValidate(buffer)) {
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);
9371 hasPendingDiagnostics(uri) {
9372 return this.pendingDiagnostics.has(uri);
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);
9384 orderedFileSet.delete(resource);
9387 this.pendingGetErr = void 0;
9389 for (const buffer of this.syncedBuffers.values) {
9390 if (this.shouldValidate(buffer)) {
9391 orderedFileSet.set(buffer.resource, void 0);
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;
9402 this.pendingDiagnostics.clear();
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);
9410 shouldValidate(buffer) {
9411 switch (buffer.kind) {
9413 return this._validateJavaScript;
9416 return this._validateTypeScript;
9420 var bufferSyncSupport_default = BufferSyncSupport;
9422 // src/server/features/diagnostics.ts
9423 var import_coc21 = __toModule(require("coc.nvim"));
9424 var DiagnosticSet = class {
9426 this._map = new ResourceMap();
9428 set(uri, diagnostics) {
9429 this._map.set(uri, diagnostics);
9432 return this._map.get(uri) || [];
9435 this._map = new ResourceMap();
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 = [
9449 var DiagnosticsManager = class {
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());
9459 this._currentDiagnostics = import_coc21.languages.createDiagnosticCollection("tsserver");
9462 this._currentDiagnostics.dispose();
9463 for (const value of this._pendingUpdates.values) {
9464 clearTimeout(value);
9466 this._pendingUpdates = new ResourceMap();
9469 this._currentDiagnostics.clear();
9470 for (const diagnosticSet of this._diagnostics.values()) {
9471 diagnosticSet.clear();
9474 setEnableSuggestions(languageId, value) {
9475 let curr = languageId == "javascript" ? this._enableJavascriptSuggestions : this._enableTypescriptSuggestions;
9476 if (curr == value) {
9479 if (languageId == "javascript") {
9480 this._enableJavascriptSuggestions = value;
9482 this._enableTypescriptSuggestions = value;
9485 diagnosticsReceived(kind, uri, diagnostics) {
9486 const collection = this._diagnostics.get(kind);
9489 let doc = import_coc21.workspace.getDocument(uri);
9492 if (diagnostics.length === 0) {
9493 const existing = collection.get(uri);
9494 if (existing.length === 0) {
9498 collection.set(uri, diagnostics);
9499 this.scheduleDiagnosticsUpdate(uri);
9501 configFileDiagnosticsReceived(uri, diagnostics) {
9502 this._currentDiagnostics.set(uri, diagnostics);
9505 this._currentDiagnostics.delete(uri);
9507 getDiagnostics(uri) {
9508 return this._currentDiagnostics.get(uri) || [];
9511 scheduleDiagnosticsUpdate(uri) {
9512 if (!this._pendingUpdates.has(uri)) {
9513 this._pendingUpdates.set(uri, setTimeout(() => this.updateCurrentDiagnostics(uri), this.updateDelay));
9516 updateCurrentDiagnostics(uri) {
9517 if (this._pendingUpdates.has(uri)) {
9518 clearTimeout(this._pendingUpdates.get(uri));
9519 this._pendingUpdates.delete(uri);
9521 const allDiagnostics = [
9522 ...this._diagnostics.get(0).get(uri),
9523 ...this._diagnostics.get(1).get(uri),
9524 ...this.getSuggestionDiagnostics(uri)
9526 this._currentDiagnostics.set(uri, allDiagnostics);
9528 getSuggestionDiagnostics(uri) {
9529 const enabled = this.suggestionsEnabled(uri);
9530 return this._diagnostics.get(2).get(uri).filter((x) => {
9532 return x.code == 6133;
9537 suggestionsEnabled(uri) {
9538 let doc = import_coc21.workspace.getDocument(uri);
9541 if (doc.filetype.startsWith("javascript")) {
9542 return this._enableJavascriptSuggestions;
9544 if (doc.filetype.startsWith("typescript")) {
9545 return this._enableTypescriptSuggestions;
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 {
9561 this.sequenceNumber = 0;
9564 return this.queue.length;
9567 if (item.queueingType === 1) {
9568 let index = this.queue.length - 1;
9569 while (index >= 0) {
9570 if (this.queue[index].queueingType !== 2) {
9575 this.queue.splice(index + 1, 0, item);
9577 this.queue.push(item);
9581 return this.queue.shift();
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);
9592 createRequest(command, args) {
9594 seq: this.sequenceNumber++,
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()) {
9616 return TsServerLogLevel2.Normal;
9618 return TsServerLogLevel2.Terse;
9620 return TsServerLogLevel2.Verbose;
9623 return TsServerLogLevel2.Off;
9626 TsServerLogLevel2.fromString = fromString;
9627 function toString2(value) {
9629 case TsServerLogLevel2.Normal:
9631 case TsServerLogLevel2.Terse:
9633 case TsServerLogLevel2.Verbose:
9635 case TsServerLogLevel2.Off:
9640 TsServerLogLevel2.toString = toString2;
9641 })(TsServerLogLevel || (TsServerLogLevel = {}));
9642 var TypeScriptServiceConfiguration = class {
9644 this._configuration = import_coc22.workspace.getConfiguration("tsserver");
9645 import_coc22.workspace.onDidChangeConfiguration(() => {
9646 this._configuration = import_coc22.workspace.getConfiguration("tsserver");
9650 return this._configuration.get("locale", null);
9653 return this._configuration.get("tsdk", null);
9655 get ignoreLocalTsserver() {
9656 return this._configuration.get("ignoreLocalTsserver", false);
9658 get tsServerLogLevel() {
9659 return TsServerLogLevel.fromString(this._configuration.get("log", null));
9661 get watchOptions() {
9662 return this._configuration.get("watchOptions");
9664 get typingsCacheLocation() {
9665 return this._configuration.get("typingsCacheLocation", "");
9667 get tsServerPluginPaths() {
9668 return this._configuration.get("pluginPaths", []);
9671 return this._configuration.get("implicitProjectConfig.checkJs", false);
9673 get experimentalDecorators() {
9674 return this._configuration.get("implicitProjectConfig.experimentalDecorators", false);
9676 get disableAutomaticTypeAcquisition() {
9677 return this._configuration.get("disableAutomaticTypeAcquisition", false);
9679 get formatOnType() {
9680 return this._configuration.get("formatOnType", false);
9682 get maxTsServerMemory() {
9683 return this._configuration.get("maxTsServerMemory", 0);
9686 return this._configuration.get("debugPort", parseInt(process.env["TSS_DEBUG"], 10));
9689 let path8 = this._configuration.get("npm", "");
9691 return import_coc22.workspace.expand(path8);
9693 path8 = import_which.default.sync("npm");
9699 static loadFromWorkspace() {
9700 return new TypeScriptServiceConfiguration();
9704 // src/server/utils/logger.ts
9705 var import_coc23 = __toModule(require("coc.nvim"));
9707 // src/server/utils/is.ts
9708 var toString = Object.prototype.toString;
9709 function boolean(value) {
9710 return value === true || value === false;
9712 function string(value) {
9713 return toString.call(value) === "[object String]";
9716 // src/server/utils/logger.ts
9717 var Logger = class {
9719 if (this._channel) {
9720 return this._channel;
9722 this._channel = import_coc23.window.createOutputChannel("tsserver");
9723 return this._channel;
9726 if (this._channel) {
9727 this._channel.dispose();
9731 if (data instanceof Error) {
9732 if (string(data.stack)) {
9735 return data.message;
9737 if (boolean(data.success) && !data.success && string(data.message)) {
9738 return data.message;
9743 return data.toString();
9745 info(message, data) {
9746 this.logLevel("Info", message, data);
9748 warn(message, data) {
9749 this.logLevel("Warn", message, data);
9751 error(message, data) {
9752 if (data && data.message === "No content available.") {
9755 this.logLevel("Error", message, data);
9757 logLevel(level, message, data) {
9758 this.output.appendLine(`[${level} - ${new Date().toLocaleTimeString()}] ${message}`);
9760 this.output.appendLine(this.data2String(data));
9764 var logger_default = Logger;
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"];
9775 for (let i = 0; i < length; i++) {
9776 const idx = Math.floor(chars.length * Math.random());
9777 result += chars[idx];
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);
9788 function generatePipeName() {
9789 return getPipeName(makeRandomHexString(40));
9791 function getPipeName(name) {
9792 const fullName = "coc-tsc-" + name;
9793 if (process.platform === "win32") {
9794 return "\\\\.\\pipe\\" + fullName + "-sock";
9796 const tmpdir = getTempDirectory();
9797 return import_path5.default.join(tmpdir, fullName + ".sock");
9799 function getTempFile(name) {
9800 const fullName = "coc-nvim-" + name;
9801 return import_path5.default.join(getTempDirectory(), fullName + ".sock");
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;
9812 function fork(modulePath, args, options, logger, callback) {
9813 let callbackCalled = false;
9814 const resolve = (result) => {
9815 if (callbackCalled) {
9818 callbackCalled = true;
9819 callback(null, result);
9821 const reject = (err) => {
9822 if (callbackCalled) {
9825 callbackCalled = true;
9826 callback(err, null);
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, "..", "..", "..");
9834 let stdErrServer = import_net.default.createServer((stdErrStream) => {
9835 childProcess.stderr = stdErrStream;
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);
9845 stdOutServer.listen(stdOutPipeName);
9846 let serverClosed = false;
9847 const closeServer = () => {
9851 serverClosed = true;
9852 stdOutServer.close();
9853 stdErrServer.close();
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), {
9860 execArgv: options.execArgv
9862 childProcess.once("error", (err) => {
9866 childProcess.once("exit", (err) => {
9872 // src/server/utils/tracer.ts
9873 var import_coc24 = __toModule(require("coc.nvim"));
9876 Trace2[Trace2["Off"] = 0] = "Off";
9877 Trace2[Trace2["Messages"] = 1] = "Messages";
9878 Trace2[Trace2["Verbose"] = 2] = "Verbose";
9879 })(Trace || (Trace = {}));
9881 function fromString(value) {
9882 value = value || "";
9883 value = value.toLowerCase();
9888 return Trace2.Messages;
9890 return Trace2.Verbose;
9895 Trace2.fromString = fromString;
9896 })(Trace || (Trace = {}));
9897 var Tracer = class {
9898 constructor(logger) {
9899 this.logger = logger;
9900 this.trace = Tracer.readTrace();
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) {
9909 traceRequest(request, responseExpected, queueLength) {
9910 if (this.trace === 0)
9913 if (this.trace === 2 && request.arguments) {
9914 data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;
9916 this.logTrace(`Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? "yes" : "no"}. Current queue length: ${queueLength}`, data);
9918 traceResponse(response, startTime) {
9919 if (this.trace === 0) {
9923 if (this.trace === 2 && response.body) {
9924 data = `Result: ${JSON.stringify(response.body, null, 4)}`;
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);
9929 if (this.trace === 0) {
9933 if (this.trace === 2 && event.body) {
9934 data = `Data: ${JSON.stringify(event.body, null, 4)}`;
9936 this.logTrace(`Event received: ${event.event} (${event.seq}).`, data);
9938 logTrace(message, data) {
9939 if (this.trace !== 0) {
9940 this.logger.logLevel("Trace", message, data);
9943 traceRequestCompleted(command, request_seq, startTime) {
9944 if (this.trace === 0) {
9947 this.logTrace(`Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);
9950 var tracer_default = Tracer;
9952 // src/server/utils/tsconfig.ts
9953 function inferredProjectConfig(config) {
9959 if (config.checkJs) {
9960 base.checkJs = true;
9962 if (config.experimentalDecorators) {
9963 base.experimentalDecorators = true;
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) {
9975 this._pathLabel = _pathLabel;
9979 return import_path6.default.resolve(this.path, "../bin/tsc");
9981 get tsServerPath() {
9982 return import_path6.default.resolve(this.path, "tsserver.js");
9985 return typeof this._pathLabel === "undefined" ? this.path : this._pathLabel;
9988 return this.version != null;
9993 let api = this._api = this.getTypeScriptVersion(this.tsServerPath);
9996 get versionString() {
9997 const version = this.version;
9998 return version ? version.versionString : null;
10000 getTypeScriptVersion(serverPath) {
10001 if (!import_fs3.default.existsSync(serverPath)) {
10004 const p = serverPath.split(import_path6.default.sep);
10005 if (p.length <= 2) {
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");
10016 if (!import_fs3.default.existsSync(fileName)) {
10019 const contents = import_fs3.default.readFileSync(fileName).toString();
10022 desc = JSON.parse(contents);
10026 if (!desc || !desc.version) {
10029 return desc.version ? api_default.fromVersionString(desc.version) : void 0;
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;
10037 updateConfiguration(configuration) {
10038 this.configuration = configuration;
10040 getDefaultVersion() {
10041 let {globalTsdk} = this.configuration;
10043 return new TypeScriptVersion(globalTsdk);
10044 return this.bundledVersion;
10046 get globalVersion() {
10047 let {globalTsdk} = this.configuration;
10049 return new TypeScriptVersion(import_coc25.workspace.expand(globalTsdk));
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)
10066 get bundledVersion() {
10068 const file2 = require.resolve("typescript");
10069 const bundledVersion = new TypeScriptVersion(import_path6.default.dirname(file2), "");
10070 return bundledVersion;
10072 import_coc25.window.showMessage("Bundled typescript module not found", "error");
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();
10090 this._versionBarEntry.dispose();
10091 this._onChangeEditorSub.dispose();
10093 onDidChangeTypeScriptVersion(version) {
10094 this._versionString = version.versionString;
10096 set loading(isLoading) {
10098 this._versionBarEntry.text = `Initialing tsserver ${this._versionString}`;
10100 this._versionBarEntry.text = `TSC ${this._versionString}`;
10102 this._versionBarEntry.isProgress = isLoading;
10104 checkFiletype(filetype) {
10105 if (filetype.startsWith("javascript") && this.enableJavascript) {
10108 return filetype.startsWith("typescript");
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();
10115 this._versionBarEntry.hide();
10119 var versionStatus_default = VersionStatus;
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 {
10131 this.buffer = Buffer.allocUnsafe(DefaultSize);
10134 let toAppend = null;
10135 if (Buffer.isBuffer(data)) {
10138 toAppend = Buffer.from(data, "utf8");
10140 if (this.buffer.length - this.index >= toAppend.length) {
10141 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
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);
10148 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
10151 this.index += toAppend.length;
10153 tryReadContentLength() {
10156 while (current < this.index && (this.buffer[current] === Blank || this.buffer[current] === BackslashR || this.buffer[current] === BackslashN)) {
10159 if (this.index < current + ContentLengthSize) {
10162 current += ContentLengthSize;
10163 let start = current;
10164 while (current < this.index && this.buffer[current] !== BackslashR) {
10167 if (current + 3 >= this.index || this.buffer[current + 1] !== BackslashN || this.buffer[current + 2] !== BackslashR || this.buffer[current + 3] !== BackslashN) {
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);
10176 tryReadContent(length) {
10177 if (this.index < length) {
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)) {
10185 this.buffer.copy(this.buffer, 0, sourceStart);
10186 this.index = this.index - sourceStart;
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);
10201 onLengthData(data) {
10203 this.buffer.append(data);
10205 if (this.nextMessageLength === -1) {
10206 this.nextMessageLength = this.buffer.tryReadContentLength();
10207 if (this.nextMessageLength === -1) {
10211 const msg = this.buffer.tryReadContent(this.nextMessageLength);
10212 if (msg === null) {
10215 this.nextMessageLength = -1;
10216 const json = JSON.parse(msg);
10217 this.callback(json);
10225 // src/server/typescriptServiceClient.ts
10226 var ForkedTsServerProcess = class {
10227 constructor(childProcess) {
10228 this.childProcess = childProcess;
10229 this.toCancelOnResourceChange = new Set();
10232 this.childProcess.on("error", cb);
10235 this.childProcess.on("exit", cb);
10237 write(serverRequest) {
10238 this.childProcess.stdin.write(JSON.stringify(serverRequest) + "\r\n", "utf8");
10240 createReader(callback, onError) {
10241 new Reader(this.childProcess.stdout, callback, onError);
10244 this.childProcess.kill();
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();
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);
10298 get onDiagnosticsReceived() {
10299 return this._onDiagnosticsReceived.event;
10301 get onConfigDiagnosticsReceived() {
10302 return this._onConfigDiagnosticsReceived.event;
10304 get onResendModelsRequested() {
10305 return this._onResendModelsRequested.event;
10307 get configuration() {
10308 return this._configuration;
10311 if (this.servicePromise) {
10312 this.servicePromise.then((childProcess) => {
10313 childProcess.kill();
10314 }).then(void 0, () => void 0);
10316 this.bufferSyncSupport.dispose();
10317 this.logger.dispose();
10318 this._onTsServerStarted.dispose();
10319 this._onResendModelsRequested.dispose();
10320 this.versionStatus.dispose();
10322 info(message, data) {
10323 this.logger.info(message, data);
10325 error(message, data) {
10326 this.logger.error(message, data);
10328 restartTsServer() {
10329 const start = () => {
10330 this.servicePromise = this.startService(true);
10331 return this.servicePromise;
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;
10342 return Promise.resolve(start());
10346 if (!this.servicePromise)
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(() => {
10355 childProcess.kill();
10356 this.servicePromise = null;
10363 get onTsServerStarted() {
10364 return this._onTsServerStarted.event;
10366 get onProjectLanguageServiceStateChanged() {
10367 return this._onProjectLanguageServiceStateChanged.event;
10369 get onDidBeginInstallTypings() {
10370 return this._onDidBeginInstallTypings.event;
10372 get onDidEndInstallTypings() {
10373 return this._onDidEndInstallTypings.event;
10375 get onTypesInstallerInitializationFailed() {
10376 return this._onTypesInstallerInitializationFailed.event;
10379 return this._apiVersion;
10382 return this._tscPath;
10385 if (this.servicePromise) {
10386 return this.servicePromise;
10388 if (this.lastError) {
10389 return Promise.reject(this.lastError);
10391 return this.startService().then(() => {
10392 if (this.servicePromise) {
10393 return this.servicePromise;
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}`);
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();
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");
10417 import_coc27.window.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, "error");
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;
10430 ...debugPort ? [`--inspect=${debugPort}`] : [],
10431 ...maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []
10433 cwd: import_coc27.workspace.root
10435 this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels);
10436 return this.servicePromise;
10438 startProcess(currentVersion, args, options, resendModels) {
10439 this.state = import_coc27.ServiceStat.Starting;
10440 return new Promise((resolve, reject) => {
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);
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);
10461 handle.onExit((code) => {
10462 if (code == null) {
10463 this.info("TSServer normal exit");
10465 this.error(`TSServer exited with code: ${code}`);
10467 this.info(`TSServer log file: ${this.tsServerLogFile || ""}`);
10468 this.serviceExited(!this.isRestarting);
10469 this.isRestarting = false;
10471 handle.createReader((msg) => {
10472 this.dispatchMessage(msg);
10474 this.error("ReaderError", error);
10477 this.serviceStarted(resendModels);
10478 this._onTsServerStarted.fire(currentVersion.version);
10485 async openTsServerLogFile() {
10486 const isRoot = process.getuid && process.getuid() == 0;
10487 let echoErr = (msg) => {
10488 import_coc27.window.showMessage(msg, "error");
10491 echoErr("Log disabled for root user.");
10494 if (!this.apiVersion.gte(api_default.v222)) {
10495 echoErr("TS Server logging requires TS 2.2.2+");
10498 if (this._configuration.tsServerLogLevel === TsServerLogLevel.Off) {
10499 echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`);
10502 if (!this.tsServerLogFile) {
10503 echoErr("TS Server has not started logging.");
10507 await import_coc27.workspace.nvim.command(`edit ${this.tsServerLogFile}`);
10510 echoErr("Could not open TS Server log file");
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",
10520 providePrefixAndSuffixTextForRename: true,
10521 allowRenameOfImportPath: true
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();
10533 for (const [config, pluginName] of this.pluginManager.configurations()) {
10534 this.configurePlugin(config, pluginName);
10537 setCompilerOptionsForInferredProjects(configuration) {
10538 if (!this.apiVersion.gte(api_default.v206))
10541 options: this.getCompilerOptionsForInferredProjects(configuration)
10543 this.executeWithoutWaitingForResponse("compilerOptionsForInferredProjects", args);
10545 getCompilerOptionsForInferredProjects(configuration) {
10547 ...inferredProjectConfig(configuration),
10549 allowSyntheticDefaultImports: true,
10550 allowNonTsExtensions: true
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();
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");
10576 if (startService) {
10577 this.startService(true);
10582 return this.normalizePath(import_coc27.Uri.parse(uri));
10584 toOpenedFilePath(uri, options = {}) {
10585 if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
10586 if (!options.suppressAlertOnFailure) {
10587 console.error(`Unexpected resource ${uri}`);
10591 return this.toPath(uri);
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))});
10604 return resource.toString();
10607 return import_coc27.Uri.file(filepath).toString();
10609 normalizePath(resource) {
10610 if (disabledSchemes.has(resource.scheme)) {
10613 switch (resource.scheme) {
10615 let result = resource.fsPath;
10618 result = import_path7.default.normalize(result);
10619 return result.replace(new RegExp("\\" + this.pathSeparator, "g"), "/");
10622 return this.inMemoryResourcePrefix + resource.toString(true);
10626 getDocument(resource) {
10627 if (resource.startsWith("untitled:")) {
10628 let bufnr = parseInt(resource.split(":", 2)[1], 10);
10629 return import_coc27.workspace.getDocument(bufnr);
10631 return import_coc27.workspace.getDocument(resource);
10633 get inMemoryResourcePrefix() {
10634 return this._apiVersion.gte(api_default.v270) ? "^" : "";
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))
10652 return import_coc27.Uri.file(filepath);
10654 execute(command, args, token, config) {
10657 if (config == null ? void 0 : config.cancelOnResourceChange) {
10658 const source = new import_vscode_languageserver_protocol20.CancellationTokenSource();
10659 token.onCancellationRequested(() => source.cancel());
10661 resource: config.cancelOnResourceChange,
10662 cancel: () => source.cancel()
10664 (_a = this.tsServerProcess) == null ? void 0 : _a.toCancelOnResourceChange.add(inFlight);
10665 execution = this.executeImpl(command, args, {
10667 token: source.token,
10668 expectsResult: true,
10672 (_a2 = this.tsServerProcess) == null ? void 0 : _a2.toCancelOnResourceChange.delete(inFlight);
10676 execution = this.executeImpl(command, args, {
10679 expectsResult: true,
10683 if (config == null ? void 0 : config.nonRecoverable) {
10684 execution.catch((err) => this.fatalError(command, err));
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) => {
10697 executeAsync(command, args, token) {
10698 return this.executeImpl(command, args, {
10701 expectsResult: true
10704 executeWithoutWaitingForResponse(command, args) {
10705 this.executeImpl(command, args, {
10708 expectsResult: false
10711 executeImpl(command, args, executeInfo) {
10712 if (this.servicePromise == null) {
10713 return Promise.resolve(void 0);
10715 this.bufferSyncSupport.beforeCommand(command);
10716 const request = this._requestQueue.createRequest(command, args);
10717 const requestInfo = {
10719 expectsResponse: executeInfo.expectsResult,
10720 isAsync: executeInfo.isAsync,
10721 queueingType: getQueueingType(command, executeInfo.lowPriority)
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);
10732 }).catch((err) => {
10736 this._requestQueue.enqueue(requestInfo);
10737 this.sendNextRequests();
10740 sendNextRequests() {
10741 while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
10742 const item = this._requestQueue.dequeue();
10744 this.sendRequest(item);
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);
10754 this.service().then((childProcess) => {
10756 childProcess.write(serverRequest);
10758 const callback = this.fetchCallback(serverRequest.seq);
10760 callback.onError(err);
10765 tryCancelRequest(seq, command) {
10767 if (this._requestQueue.tryDeletePendingRequest(seq)) {
10768 this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`);
10771 if (this.cancellationPipeName) {
10772 this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`);
10774 import_fs4.default.writeFileSync(this.cancellationPipeName + seq, "");
10779 this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`);
10782 const callback = this.fetchCallback(seq);
10784 callback.onSuccess(new ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`));
10788 fetchCallback(seq) {
10789 const callback = this._callbacks.fetch(seq);
10793 this._pendingResponses.delete(seq);
10796 dispatchMessage(message) {
10798 switch (message.type) {
10800 this.dispatchResponse(message);
10803 const event = message;
10804 if (event.event === "requestCompleted") {
10805 const seq = event.body.request_seq;
10806 const p = this._callbacks.fetch(seq);
10808 this.tracer.traceRequestCompleted("requestCompleted", seq, p.startTime);
10809 p.onSuccess(void 0);
10812 this.tracer.traceEvent(event);
10813 this.dispatchEvent(event);
10817 throw new Error(`Unknown message type ${message.type} received`);
10820 this.sendNextRequests();
10823 dispatchResponse(response) {
10824 const callback = this.fetchCallback(response.request_seq);
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);
10834 callback.onError(new Error(response.message));
10837 dispatchEvent(event) {
10838 switch (event.event) {
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
10851 case "configFileDiag":
10852 this._onConfigDiagnosticsReceived.fire(event);
10854 case "projectLanguageServiceState":
10856 this._onProjectLanguageServiceStateChanged.fire(event.body);
10859 case "beginInstallTypes":
10861 this._onDidBeginInstallTypings.fire(event.body);
10864 case "endInstallTypes":
10866 this._onDidEndInstallTypings.fire(event.body);
10869 case "projectsUpdatedInBackground":
10870 const body = event.body;
10871 const resources = body.openFiles.map(import_coc27.Uri.file);
10872 this.bufferSyncSupport.getErr(resources);
10874 case "typesInstallerInitializationFailed":
10876 this._onTypesInstallerInitializationFailed.fire(event.body);
10879 case "projectLoadingStart":
10880 this.versionStatus.loading = true;
10882 case "projectLoadingFinish":
10883 this.versionStatus.loading = false;
10887 async getTsServerArgs(currentVersion) {
10889 args.push("--allowLocalPluginLoads");
10890 if (this.apiVersion.gte(api_default.v250)) {
10891 args.push("--useInferredProjectPerProjectRoot");
10893 args.push("--useSingleInferredProject");
10895 if (this.apiVersion.gte(api_default.v206) && this._configuration.disableAutomaticTypeAcquisition) {
10896 args.push("--disableAutomaticTypingAcquisition");
10898 if (this.apiVersion.gte(api_default.v222)) {
10899 this.cancellationPipeName = getTempFile(`tscancellation-${makeRandomHexString(20)}`);
10900 args.push("--cancellationPipeName", this.cancellationPipeName + "*");
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();
10907 this.tsServerLogFile = import_path7.default.join(logDir, `tsserver.log`);
10908 this.info("TSServer log file :", this.tsServerLogFile);
10910 this.tsServerLogFile = null;
10911 this.error("Could not create TSServer log directory");
10913 if (this.tsServerLogFile) {
10914 args.push("--logVerbosity", TsServerLogLevel.toString(this._configuration.tsServerLogLevel));
10915 args.push("--logFile", this.tsServerLogFile);
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)) {
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)));
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);
10940 if (pluginPaths.length) {
10941 args.push("--pluginProbeLocations", pluginPaths.join(","));
10944 if (this._configuration.locale) {
10945 args.push("--locale", this._configuration.locale);
10947 if (this._configuration.typingsCacheLocation) {
10948 args.push("--globalTypingsCacheLocation", `"${this._configuration.typingsCacheLocation}"`);
10950 if (this.apiVersion.gte(api_default.v234)) {
10951 let {npmLocation} = this._configuration;
10953 this.logger.info(`using npm from ${npmLocation}`);
10954 args.push("--npmLocation", `"${npmLocation}"`);
10957 if (this.apiVersion.gte(api_default.v291)) {
10958 args.push("--noGetErrOnBackgroundUpdate");
10960 if (this.apiVersion.gte(api_default.v345)) {
10961 args.push("--validateDefaultNpmLocation");
10965 getProjectRootPath(uri) {
10966 let root = import_coc27.workspace.cwd;
10967 let u = import_coc27.Uri.parse(uri);
10968 if (u.scheme !== "file")
10970 let folder = import_coc27.workspace.getWorkspaceFolder(uri);
10972 root = import_coc27.Uri.parse(folder.uri).fsPath;
10974 let filepath = import_coc27.Uri.parse(uri).fsPath;
10975 if (!filepath.startsWith(root)) {
10976 root = import_path7.default.dirname(filepath);
10979 if (root == import_os2.default.homedir())
10983 configurePlugin(pluginName, configuration) {
10984 if (this.apiVersion.gte(api_default.v314)) {
10985 if (!this.servicePromise)
10987 this.servicePromise.then(() => {
10988 this.executeWithoutWaitingForResponse("configurePlugin", {pluginName, configuration});
10992 interruptGetErr(f) {
10993 return this.bufferSyncSupport.interuptGetErr(f);
10995 cancelInflightRequestsForResource(resource) {
10996 if (this.state !== import_coc27.ServiceStat.Running || !this.tsServerProcess) {
10999 for (const request of this.tsServerProcess.toCancelOnResourceChange) {
11000 if (request.resource.toString() === resource.toString()) {
11006 var typescriptServiceClient_default = TypeScriptServiceClient;
11007 function getDiagnosticsKind(event) {
11008 switch (event.event) {
11010 return DiagnosticKind.Syntax;
11011 case "semanticDiag":
11012 return DiagnosticKind.Semantic;
11013 case "suggestionDiag":
11014 return DiagnosticKind.Suggestion;
11016 throw new Error("Unknown dignostics kind");
11018 var fenceCommands = new Set(["change", "close", "open"]);
11019 function getQueueingType(command, lowPriority) {
11020 if (fenceCommands.has(command)) {
11021 return RequestQueueingType.Fence;
11023 return lowPriority ? RequestQueueingType.LowPriority : RequestQueueingType.Normal;
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 = [
11035 diagnosticSource: "ts",
11036 diagnosticOwner: "typescript",
11043 diagnosticLanguage: 1,
11044 configFile: "tsconfig.json",
11045 configFilePattern: /^tsconfig(\..*)?\.json$/gi
11049 diagnosticSource: "ts",
11050 diagnosticOwner: "typescript",
11051 modeIds: [javascript, javascriptreact, javascriptjsx],
11052 diagnosticLanguage: 0,
11053 configFile: "jsconfig.json",
11054 configFilePattern: /^jsconfig(\..*)?\.json$/gi
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)));
11071 this._subscriptions.forEach((x) => x.dispose());
11072 for (const eventId of Object.keys(this._acquiringTypings)) {
11073 clearTimeout(this._acquiringTypings[eventId]);
11076 get isAcquiringTypings() {
11077 return Object.keys(this._acquiringTypings).length > 0;
11079 onBeginInstallTypings(eventId) {
11080 if (this._acquiringTypings[eventId]) {
11083 this._acquiringTypings[eventId] = setTimeout(() => {
11084 this.onEndInstallTypings(eventId);
11085 }, typingsInstallTimeout);
11087 onEndInstallTypings(eventId) {
11088 const timer = this._acquiringTypings[eventId];
11090 clearTimeout(timer);
11092 delete this._acquiringTypings[eventId];
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();
11112 this._disposable.dispose();
11113 this._promises.forEach((value) => value());
11115 _onBegin(eventId) {
11116 const handle = setTimeout(() => this._onEndOrTimeout(eventId), typingsInstallTimeout);
11117 new Promise((resolve) => {
11118 this._promises.set(eventId, () => {
11119 clearTimeout(handle);
11123 this.statusItem.text = "Fetching data for better TypeScript IntelliSense";
11124 this.statusItem.show();
11126 _onEndOrTimeout(eventId) {
11127 this.statusItem.hide();
11128 const resolve = this._promises.get(eventId);
11130 this._promises.delete(eventId);
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");
11139 this._invalid = true;
11143 // src/server/typescriptServiceClientHost.ts
11144 var styleCheckDiagnostics = [
11152 var TypeScriptServiceClientHost = class {
11153 constructor(descriptions, pluginManager) {
11154 this.languagePerId = new Map();
11155 this.disposables = [];
11156 this.reportStyleCheckAsWarnings = true;
11158 const handleProjectChange = () => {
11160 clearTimeout(timer);
11161 timer = setTimeout(() => {
11162 this.triggerAllDiagnostics();
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) => {
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) => {
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(), []);
11191 let diagnosticList = diagnostics.map((o) => {
11192 let {text, code, category, start, end} = o;
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));
11197 range = import_vscode_languageserver_protocol22.Range.create(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
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);
11202 this.client.diagnosticsManager.configFileDiagnosticsReceived(uri.toString(), diagnosticList);
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);
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",
11225 for (const language of plugin.languages) {
11226 languageIds.add(language);
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",
11240 this.client.ensureServiceStarted();
11241 this.client.onTsServerStarted(() => {
11242 this.triggerAllDiagnostics();
11244 import_coc29.workspace.onDidChangeConfiguration(this.configurationChanged, this, this.disposables);
11245 this.configurationChanged();
11247 registerExtensionLanguageProvider(description) {
11248 const manager = new languageProvider_default(this.client, this.fileConfigurationManager, description, this.typingsStatus);
11249 this.languagePerId.set(description.id, manager);
11252 import_coc29.disposeAll(this.disposables);
11253 for (let language of this.languagePerId.values()) {
11254 language.dispose();
11256 this.languagePerId.clear();
11257 this.fileConfigurationManager.dispose();
11258 this.typingsStatus.dispose();
11259 this.ataProgressReporter.dispose();
11262 this.fileConfigurationManager.reset();
11264 get serviceClient() {
11265 return this.client;
11268 this.client.diagnosticsManager.reInitialize();
11269 this.client.execute("reloadProjects", null, import_vscode_languageserver_protocol22.CancellationToken.None);
11270 this.triggerAllDiagnostics();
11272 getProvider(languageId) {
11273 return this.languagePerId.get(languageId);
11275 configurationChanged() {
11276 const config = import_coc29.workspace.getConfiguration("tsserver");
11277 this.reportStyleCheckAsWarnings = config.get("reportStyleChecksAsWarnings", true);
11279 async findLanguage(uri) {
11281 let doc = this.client.getDocument(uri);
11284 let languages4 = Array.from(this.languagePerId.values());
11285 return languages4.find((language) => language.handles(uri, doc.textDocument));
11290 async handles(doc) {
11291 let languages4 = Array.from(this.languagePerId.values());
11292 let idx = languages4.findIndex((language) => language.handles(doc.uri, doc));
11295 return this.client.bufferSyncSupport.handles(doc.uri);
11297 triggerAllDiagnostics() {
11298 for (const language of this.languagePerId.values()) {
11299 language.triggerAllDiagnostics();
11302 async diagnosticsReceived(kind, resource, diagnostics) {
11303 const language = await this.findLanguage(resource.toString());
11305 language.diagnosticsReceived(kind, resource, this.createMarkerDatas(diagnostics));
11308 createMarkerDatas(diagnostics) {
11309 return diagnostics.map((tsDiag) => this.tsDiagnosticToLspDiagnostic(tsDiag));
11311 tsDiagnosticToLspDiagnostic(diagnostic) {
11312 const {start, end, text} = diagnostic;
11314 start: Position.fromLocation(start),
11315 end: Position.fromLocation(end)
11317 let relatedInformation;
11318 if (diagnostic.relatedInformation) {
11319 relatedInformation = diagnostic.relatedInformation.map((o) => {
11320 let {span, message} = o;
11322 location: Location2.fromTextSpan(this.client.toResource(span.file), span),
11330 code: diagnostic.code ? diagnostic.code : null,
11331 severity: this.getDiagnosticSeverity(diagnostic),
11332 reportUnnecessary: diagnostic.reportsUnnecessary,
11333 source: diagnostic.source || "tsserver",
11337 getDiagnosticSeverity(diagnostic) {
11338 if (this.reportStyleCheckAsWarnings && this.isStyleCheckDiagnostic(diagnostic.code) && diagnostic.category === DiagnosticCategory.error) {
11339 return import_vscode_languageserver_protocol22.DiagnosticSeverity.Warning;
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;
11349 return import_vscode_languageserver_protocol22.DiagnosticSeverity.Error;
11352 isStyleCheckDiagnostic(code) {
11353 return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
11355 getAllModeIds(descriptions, pluginManager) {
11356 const allModeIds = flatten([
11357 ...descriptions.map((x) => x.modeIds),
11358 ...pluginManager.plugins.map((x) => x.languages)
11363 var typescriptServiceClientHost_default = TypeScriptServiceClientHost;
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";
11382 this.selector = this.descriptions.reduce((arr, c) => {
11383 return arr.concat(c.modeIds);
11387 return import_coc30.workspace.getConfiguration("tsserver");
11390 if (this.state == import_coc30.ServiceStat.Running)
11391 return Promise.resolve(this.clientHost);
11393 return new Promise((resolve, reject) => {
11394 let timer = setTimeout(() => {
11395 reject(new Error(`Server not started after 5s`));
11397 let disposable = this.onServiceReady(() => {
11398 clearTimeout(timer);
11399 disposable.dispose();
11400 resolve(this.clientHost);
11405 if (this.clientHost)
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", {
11416 return this.clientHost.serviceClient.state;
11419 this._onDidServiceReady.fire(void 0);
11428 import_coc30.disposeAll(this.disposables);
11431 if (!this.clientHost)
11433 let client = this.clientHost.serviceClient;
11434 await client.restartTsServer();
11437 if (!this.clientHost)
11439 this.clientHost.reset();
11440 let client = this.clientHost.serviceClient;
11441 await client.stop();
11445 var server_default = TsserverService;
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);
11455 TypeScriptServerPlugin2.equals = equals2;
11456 })(TypeScriptServerPlugin || (TypeScriptServerPlugin = {}));
11457 var PluginManager = class {
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) {
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);
11475 import_coc31.extensions.onDidActiveExtension(loadPlugins, void 0, this._disposables);
11476 import_coc31.extensions.onDidUnloadExtension(loadPlugins, void 0, this._disposables);
11479 import_coc31.disposeAll(this._disposables);
11482 if (!this._plugins) {
11483 this._plugins = this.readPlugins();
11485 return flatten(Array.from(this._plugins.values()));
11488 this._disposables.push(value);
11491 setConfiguration(pluginId, config) {
11492 this._pluginConfigurations.set(pluginId, config);
11493 this._onDidUpdateConfig.fire({pluginId, config});
11496 return this._pluginConfigurations.entries();
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) {
11507 enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
11508 path: extension.extensionPath,
11509 languages: Array.isArray(plugin.languages) ? plugin.languages : []
11512 if (plugins.length) {
11513 pluginMap.set(extension.id, plugins);
11522 async function activate(context) {
11523 let {subscriptions, logger} = context;
11524 const config = import_coc32.workspace.getConfiguration().get("tsserver", {});
11525 if (!config.enable)
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));
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));
11540 id: "tsserver.restart",
11542 service.stop().then(() => {
11549 service.start().then(() => {
11550 subscriptions.push(import_coc32.services.regist(service));
11552 logger.error(`Error on service start:`, e);
11555 configurePlugin: (pluginId, configuration) => {
11556 pluginManager.setConfiguration(pluginId, configuration);
11560 //# sourceMappingURL=index.js.map