notes/coc/extensions/node_modules/coc-eslint/lib/index.js

5461 lines
205 KiB
JavaScript

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
var __commonJS = (callback, module2) => () => {
if (!module2) {
module2 = {exports: {}};
callback(module2.exports, module2);
}
return module2.exports;
};
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, {get: all[name], enumerable: true});
};
var __exportStar = (target, module2, desc) => {
__markAsModule(target);
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
}
return target;
};
var __toModule = (module2) => {
if (module2 && module2.__esModule)
return module2;
return __exportStar(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", {value: module2, enumerable: true}), module2);
};
// node_modules/vscode-jsonrpc/lib/is.js
var require_is = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
function boolean(value) {
return value === true || value === false;
}
exports2.boolean = boolean;
function string(value) {
return typeof value === "string" || value instanceof String;
}
exports2.string = string;
function number(value) {
return typeof value === "number" || value instanceof Number;
}
exports2.number = number;
function error(value) {
return value instanceof Error;
}
exports2.error = error;
function func(value) {
return typeof value === "function";
}
exports2.func = func;
function array(value) {
return Array.isArray(value);
}
exports2.array = array;
function stringArray(value) {
return array(value) && value.every((elem) => string(elem));
}
exports2.stringArray = stringArray;
});
// node_modules/vscode-jsonrpc/lib/messages.js
var require_messages = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var is = require_is();
var ErrorCodes;
(function(ErrorCodes2) {
ErrorCodes2.ParseError = -32700;
ErrorCodes2.InvalidRequest = -32600;
ErrorCodes2.MethodNotFound = -32601;
ErrorCodes2.InvalidParams = -32602;
ErrorCodes2.InternalError = -32603;
ErrorCodes2.serverErrorStart = -32099;
ErrorCodes2.serverErrorEnd = -32e3;
ErrorCodes2.ServerNotInitialized = -32002;
ErrorCodes2.UnknownErrorCode = -32001;
ErrorCodes2.RequestCancelled = -32800;
ErrorCodes2.ContentModified = -32801;
ErrorCodes2.MessageWriteError = 1;
ErrorCodes2.MessageReadError = 2;
})(ErrorCodes = exports2.ErrorCodes || (exports2.ErrorCodes = {}));
var ResponseError = class extends Error {
constructor(code, message, data) {
super(message);
this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
this.data = data;
Object.setPrototypeOf(this, ResponseError.prototype);
}
toJson() {
return {
code: this.code,
message: this.message,
data: this.data
};
}
};
exports2.ResponseError = ResponseError;
var AbstractMessageType = class {
constructor(_method, _numberOfParams) {
this._method = _method;
this._numberOfParams = _numberOfParams;
}
get method() {
return this._method;
}
get numberOfParams() {
return this._numberOfParams;
}
};
exports2.AbstractMessageType = AbstractMessageType;
var RequestType0 = class extends AbstractMessageType {
constructor(method) {
super(method, 0);
}
};
exports2.RequestType0 = RequestType0;
var RequestType2 = class extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
};
exports2.RequestType = RequestType2;
var RequestType1 = class extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
};
exports2.RequestType1 = RequestType1;
var RequestType22 = class extends AbstractMessageType {
constructor(method) {
super(method, 2);
}
};
exports2.RequestType2 = RequestType22;
var RequestType3 = class extends AbstractMessageType {
constructor(method) {
super(method, 3);
}
};
exports2.RequestType3 = RequestType3;
var RequestType4 = class extends AbstractMessageType {
constructor(method) {
super(method, 4);
}
};
exports2.RequestType4 = RequestType4;
var RequestType5 = class extends AbstractMessageType {
constructor(method) {
super(method, 5);
}
};
exports2.RequestType5 = RequestType5;
var RequestType6 = class extends AbstractMessageType {
constructor(method) {
super(method, 6);
}
};
exports2.RequestType6 = RequestType6;
var RequestType7 = class extends AbstractMessageType {
constructor(method) {
super(method, 7);
}
};
exports2.RequestType7 = RequestType7;
var RequestType8 = class extends AbstractMessageType {
constructor(method) {
super(method, 8);
}
};
exports2.RequestType8 = RequestType8;
var RequestType9 = class extends AbstractMessageType {
constructor(method) {
super(method, 9);
}
};
exports2.RequestType9 = RequestType9;
var NotificationType2 = class extends AbstractMessageType {
constructor(method) {
super(method, 1);
this._ = void 0;
}
};
exports2.NotificationType = NotificationType2;
var NotificationType02 = class extends AbstractMessageType {
constructor(method) {
super(method, 0);
}
};
exports2.NotificationType0 = NotificationType02;
var NotificationType1 = class extends AbstractMessageType {
constructor(method) {
super(method, 1);
}
};
exports2.NotificationType1 = NotificationType1;
var NotificationType22 = class extends AbstractMessageType {
constructor(method) {
super(method, 2);
}
};
exports2.NotificationType2 = NotificationType22;
var NotificationType3 = class extends AbstractMessageType {
constructor(method) {
super(method, 3);
}
};
exports2.NotificationType3 = NotificationType3;
var NotificationType4 = class extends AbstractMessageType {
constructor(method) {
super(method, 4);
}
};
exports2.NotificationType4 = NotificationType4;
var NotificationType5 = class extends AbstractMessageType {
constructor(method) {
super(method, 5);
}
};
exports2.NotificationType5 = NotificationType5;
var NotificationType6 = class extends AbstractMessageType {
constructor(method) {
super(method, 6);
}
};
exports2.NotificationType6 = NotificationType6;
var NotificationType7 = class extends AbstractMessageType {
constructor(method) {
super(method, 7);
}
};
exports2.NotificationType7 = NotificationType7;
var NotificationType8 = class extends AbstractMessageType {
constructor(method) {
super(method, 8);
}
};
exports2.NotificationType8 = NotificationType8;
var NotificationType9 = class extends AbstractMessageType {
constructor(method) {
super(method, 9);
}
};
exports2.NotificationType9 = NotificationType9;
function isRequestMessage(message) {
let candidate = message;
return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
}
exports2.isRequestMessage = isRequestMessage;
function isNotificationMessage(message) {
let candidate = message;
return candidate && is.string(candidate.method) && message.id === void 0;
}
exports2.isNotificationMessage = isNotificationMessage;
function isResponseMessage(message) {
let candidate = message;
return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
}
exports2.isResponseMessage = isResponseMessage;
});
// node_modules/vscode-jsonrpc/lib/events.js
var require_events = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var Disposable3;
(function(Disposable4) {
function create(func) {
return {
dispose: func
};
}
Disposable4.create = create;
})(Disposable3 = exports2.Disposable || (exports2.Disposable = {}));
var Event;
(function(Event2) {
const _disposable = {dispose() {
}};
Event2.None = function() {
return _disposable;
};
})(Event = exports2.Event || (exports2.Event = {}));
var CallbackList = class {
add(callback, context = null, bucket) {
if (!this._callbacks) {
this._callbacks = [];
this._contexts = [];
}
this._callbacks.push(callback);
this._contexts.push(context);
if (Array.isArray(bucket)) {
bucket.push({dispose: () => this.remove(callback, context)});
}
}
remove(callback, context = null) {
if (!this._callbacks) {
return;
}
var foundCallbackWithDifferentContext = false;
for (var i = 0, len = this._callbacks.length; i < len; i++) {
if (this._callbacks[i] === callback) {
if (this._contexts[i] === context) {
this._callbacks.splice(i, 1);
this._contexts.splice(i, 1);
return;
} else {
foundCallbackWithDifferentContext = true;
}
}
}
if (foundCallbackWithDifferentContext) {
throw new Error("When adding a listener with a context, you should remove it with the same context");
}
}
invoke(...args) {
if (!this._callbacks) {
return [];
}
var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
for (var i = 0, len = callbacks.length; i < len; i++) {
try {
ret.push(callbacks[i].apply(contexts[i], args));
} catch (e) {
console.error(e);
}
}
return ret;
}
isEmpty() {
return !this._callbacks || this._callbacks.length === 0;
}
dispose() {
this._callbacks = void 0;
this._contexts = void 0;
}
};
var Emitter = class {
constructor(_options) {
this._options = _options;
}
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
if (!this._callbacks) {
this._callbacks = new CallbackList();
}
if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
this._options.onFirstListenerAdd(this);
}
this._callbacks.add(listener, thisArgs);
let result;
result = {
dispose: () => {
this._callbacks.remove(listener, thisArgs);
result.dispose = Emitter._noop;
if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
this._options.onLastListenerRemove(this);
}
}
};
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
fire(event) {
if (this._callbacks) {
this._callbacks.invoke.call(this._callbacks, event);
}
}
dispose() {
if (this._callbacks) {
this._callbacks.dispose();
this._callbacks = void 0;
}
}
};
exports2.Emitter = Emitter;
Emitter._noop = function() {
};
});
// node_modules/vscode-jsonrpc/lib/messageReader.js
var require_messageReader = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var events_1 = require_events();
var Is2 = require_is();
var DefaultSize = 8192;
var CR = Buffer.from("\r", "ascii")[0];
var LF = Buffer.from("\n", "ascii")[0];
var CRLF = "\r\n";
var MessageBuffer = class {
constructor(encoding = "utf8") {
this.encoding = encoding;
this.index = 0;
this.buffer = Buffer.allocUnsafe(DefaultSize);
}
append(chunk) {
var toAppend = chunk;
if (typeof chunk === "string") {
var str = chunk;
var bufferLen = Buffer.byteLength(str, this.encoding);
toAppend = Buffer.allocUnsafe(bufferLen);
toAppend.write(str, 0, bufferLen, this.encoding);
}
if (this.buffer.length - this.index >= toAppend.length) {
toAppend.copy(this.buffer, this.index, 0, toAppend.length);
} else {
var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
if (this.index === 0) {
this.buffer = Buffer.allocUnsafe(newSize);
toAppend.copy(this.buffer, 0, 0, toAppend.length);
} else {
this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
}
}
this.index += toAppend.length;
}
tryReadHeaders() {
let result = void 0;
let current = 0;
while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
current++;
}
if (current + 3 >= this.index) {
return result;
}
result = Object.create(null);
let headers = this.buffer.toString("ascii", 0, current).split(CRLF);
headers.forEach((header) => {
let index = header.indexOf(":");
if (index === -1) {
throw new Error("Message header must separate key and value using :");
}
let key = header.substr(0, index);
let value = header.substr(index + 1).trim();
result[key] = value;
});
let nextStart = current + 4;
this.buffer = this.buffer.slice(nextStart);
this.index = this.index - nextStart;
return result;
}
tryReadContent(length) {
if (this.index < length) {
return null;
}
let result = this.buffer.toString(this.encoding, 0, length);
let nextStart = length;
this.buffer.copy(this.buffer, 0, nextStart);
this.index = this.index - nextStart;
return result;
}
get numberOfBytes() {
return this.index;
}
};
var MessageReader;
(function(MessageReader2) {
function is(value) {
let candidate = value;
return candidate && Is2.func(candidate.listen) && Is2.func(candidate.dispose) && Is2.func(candidate.onError) && Is2.func(candidate.onClose) && Is2.func(candidate.onPartialMessage);
}
MessageReader2.is = is;
})(MessageReader = exports2.MessageReader || (exports2.MessageReader = {}));
var AbstractMessageReader = class {
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
this.partialMessageEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error) {
this.errorEmitter.fire(this.asError(error));
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(void 0);
}
get onPartialMessage() {
return this.partialMessageEmitter.event;
}
firePartialMessage(info) {
this.partialMessageEmitter.fire(info);
}
asError(error) {
if (error instanceof Error) {
return error;
} else {
return new Error(`Reader received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
}
}
};
exports2.AbstractMessageReader = AbstractMessageReader;
var StreamMessageReader = class extends AbstractMessageReader {
constructor(readable, encoding = "utf8") {
super();
this.readable = readable;
this.buffer = new MessageBuffer(encoding);
this._partialMessageTimeout = 1e4;
}
set partialMessageTimeout(timeout) {
this._partialMessageTimeout = timeout;
}
get partialMessageTimeout() {
return this._partialMessageTimeout;
}
listen(callback) {
this.nextMessageLength = -1;
this.messageToken = 0;
this.partialMessageTimer = void 0;
this.callback = callback;
this.readable.on("data", (data) => {
this.onData(data);
});
this.readable.on("error", (error) => this.fireError(error));
this.readable.on("close", () => this.fireClose());
}
onData(data) {
this.buffer.append(data);
while (true) {
if (this.nextMessageLength === -1) {
let headers = this.buffer.tryReadHeaders();
if (!headers) {
return;
}
let contentLength = headers["Content-Length"];
if (!contentLength) {
throw new Error("Header must provide a Content-Length property.");
}
let length = parseInt(contentLength);
if (isNaN(length)) {
throw new Error("Content-Length value must be a number.");
}
this.nextMessageLength = length;
}
var msg = this.buffer.tryReadContent(this.nextMessageLength);
if (msg === null) {
this.setPartialMessageTimer();
return;
}
this.clearPartialMessageTimer();
this.nextMessageLength = -1;
this.messageToken++;
var json = JSON.parse(msg);
this.callback(json);
}
}
clearPartialMessageTimer() {
if (this.partialMessageTimer) {
clearTimeout(this.partialMessageTimer);
this.partialMessageTimer = void 0;
}
}
setPartialMessageTimer() {
this.clearPartialMessageTimer();
if (this._partialMessageTimeout <= 0) {
return;
}
this.partialMessageTimer = setTimeout((token, timeout) => {
this.partialMessageTimer = void 0;
if (token === this.messageToken) {
this.firePartialMessage({messageToken: token, waitingTime: timeout});
this.setPartialMessageTimer();
}
}, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
}
};
exports2.StreamMessageReader = StreamMessageReader;
var IPCMessageReader = class extends AbstractMessageReader {
constructor(process2) {
super();
this.process = process2;
let eventEmitter = this.process;
eventEmitter.on("error", (error) => this.fireError(error));
eventEmitter.on("close", () => this.fireClose());
}
listen(callback) {
this.process.on("message", callback);
}
};
exports2.IPCMessageReader = IPCMessageReader;
var SocketMessageReader = class extends StreamMessageReader {
constructor(socket, encoding = "utf-8") {
super(socket, encoding);
}
};
exports2.SocketMessageReader = SocketMessageReader;
});
// node_modules/vscode-jsonrpc/lib/messageWriter.js
var require_messageWriter = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var events_1 = require_events();
var Is2 = require_is();
var ContentLength = "Content-Length: ";
var CRLF = "\r\n";
var MessageWriter;
(function(MessageWriter2) {
function is(value) {
let candidate = value;
return candidate && Is2.func(candidate.dispose) && Is2.func(candidate.onClose) && Is2.func(candidate.onError) && Is2.func(candidate.write);
}
MessageWriter2.is = is;
})(MessageWriter = exports2.MessageWriter || (exports2.MessageWriter = {}));
var AbstractMessageWriter = class {
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error, message, count) {
this.errorEmitter.fire([this.asError(error), message, count]);
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(void 0);
}
asError(error) {
if (error instanceof Error) {
return error;
} else {
return new Error(`Writer received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
}
}
};
exports2.AbstractMessageWriter = AbstractMessageWriter;
var StreamMessageWriter = class extends AbstractMessageWriter {
constructor(writable, encoding = "utf8") {
super();
this.writable = writable;
this.encoding = encoding;
this.errorCount = 0;
this.writable.on("error", (error) => this.fireError(error));
this.writable.on("close", () => this.fireClose());
}
write(msg) {
let json = JSON.stringify(msg);
let contentLength = Buffer.byteLength(json, this.encoding);
let headers = [
ContentLength,
contentLength.toString(),
CRLF,
CRLF
];
try {
this.writable.write(headers.join(""), "ascii");
this.writable.write(json, this.encoding);
this.errorCount = 0;
} catch (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
}
};
exports2.StreamMessageWriter = StreamMessageWriter;
var IPCMessageWriter = class extends AbstractMessageWriter {
constructor(process2) {
super();
this.process = process2;
this.errorCount = 0;
this.queue = [];
this.sending = false;
let eventEmitter = this.process;
eventEmitter.on("error", (error) => this.fireError(error));
eventEmitter.on("close", () => this.fireClose);
}
write(msg) {
if (!this.sending && this.queue.length === 0) {
this.doWriteMessage(msg);
} else {
this.queue.push(msg);
}
}
doWriteMessage(msg) {
try {
if (this.process.send) {
this.sending = true;
this.process.send(msg, void 0, void 0, (error) => {
this.sending = false;
if (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
} else {
this.errorCount = 0;
}
if (this.queue.length > 0) {
this.doWriteMessage(this.queue.shift());
}
});
}
} catch (error) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
}
};
exports2.IPCMessageWriter = IPCMessageWriter;
var SocketMessageWriter = class extends AbstractMessageWriter {
constructor(socket, encoding = "utf8") {
super();
this.socket = socket;
this.queue = [];
this.sending = false;
this.encoding = encoding;
this.errorCount = 0;
this.socket.on("error", (error) => this.fireError(error));
this.socket.on("close", () => this.fireClose());
}
dispose() {
super.dispose();
this.socket.destroy();
}
write(msg) {
if (!this.sending && this.queue.length === 0) {
this.doWriteMessage(msg);
} else {
this.queue.push(msg);
}
}
doWriteMessage(msg) {
let json = JSON.stringify(msg);
let contentLength = Buffer.byteLength(json, this.encoding);
let headers = [
ContentLength,
contentLength.toString(),
CRLF,
CRLF
];
try {
this.sending = true;
this.socket.write(headers.join(""), "ascii", (error) => {
if (error) {
this.handleError(error, msg);
}
try {
this.socket.write(json, this.encoding, (error2) => {
this.sending = false;
if (error2) {
this.handleError(error2, msg);
} else {
this.errorCount = 0;
}
if (this.queue.length > 0) {
this.doWriteMessage(this.queue.shift());
}
});
} catch (error2) {
this.handleError(error2, msg);
}
});
} catch (error) {
this.handleError(error, msg);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
};
exports2.SocketMessageWriter = SocketMessageWriter;
});
// node_modules/vscode-jsonrpc/lib/cancellation.js
var require_cancellation = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var events_1 = require_events();
var Is2 = require_is();
var CancellationToken;
(function(CancellationToken2) {
CancellationToken2.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: events_1.Event.None
});
CancellationToken2.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: events_1.Event.None
});
function is(value) {
let candidate = value;
return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is2.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
}
CancellationToken2.is = is;
})(CancellationToken = exports2.CancellationToken || (exports2.CancellationToken = {}));
var shortcutEvent = Object.freeze(function(callback, context) {
let handle = setTimeout(callback.bind(context), 0);
return {dispose() {
clearTimeout(handle);
}};
});
var MutableToken = class {
constructor() {
this._isCancelled = false;
}
cancel() {
if (!this._isCancelled) {
this._isCancelled = true;
if (this._emitter) {
this._emitter.fire(void 0);
this.dispose();
}
}
}
get isCancellationRequested() {
return this._isCancelled;
}
get onCancellationRequested() {
if (this._isCancelled) {
return shortcutEvent;
}
if (!this._emitter) {
this._emitter = new events_1.Emitter();
}
return this._emitter.event;
}
dispose() {
if (this._emitter) {
this._emitter.dispose();
this._emitter = void 0;
}
}
};
var CancellationTokenSource = class {
get token() {
if (!this._token) {
this._token = new MutableToken();
}
return this._token;
}
cancel() {
if (!this._token) {
this._token = CancellationToken.Cancelled;
} else {
this._token.cancel();
}
}
dispose() {
if (!this._token) {
this._token = CancellationToken.None;
} else if (this._token instanceof MutableToken) {
this._token.dispose();
}
}
};
exports2.CancellationTokenSource = CancellationTokenSource;
});
// node_modules/vscode-jsonrpc/lib/linkedMap.js
var require_linkedMap = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var Touch;
(function(Touch2) {
Touch2.None = 0;
Touch2.First = 1;
Touch2.Last = 2;
})(Touch = exports2.Touch || (exports2.Touch = {}));
var LinkedMap = class {
constructor() {
this._map = new Map();
this._head = void 0;
this._tail = void 0;
this._size = 0;
}
clear() {
this._map.clear();
this._head = void 0;
this._tail = void 0;
this._size = 0;
}
isEmpty() {
return !this._head && !this._tail;
}
get size() {
return this._size;
}
has(key) {
return this._map.has(key);
}
get(key) {
const item = this._map.get(key);
if (!item) {
return void 0;
}
return item.value;
}
set(key, value, touch = Touch.None) {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== Touch.None) {
this.touch(item, touch);
}
} else {
item = {key, value, next: void 0, previous: void 0};
switch (touch) {
case Touch.None:
this.addItemLast(item);
break;
case Touch.First:
this.addItemFirst(item);
break;
case Touch.Last:
this.addItemLast(item);
break;
default:
this.addItemLast(item);
break;
}
this._map.set(key, item);
this._size++;
}
}
delete(key) {
const item = this._map.get(key);
if (!item) {
return false;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return true;
}
shift() {
if (!this._head && !this._tail) {
return void 0;
}
if (!this._head || !this._tail) {
throw new Error("Invalid list");
}
const item = this._head;
this._map.delete(item.key);
this.removeItem(item);
this._size--;
return item.value;
}
forEach(callbackfn, thisArg) {
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
} else {
callbackfn(current.value, current.key, this);
}
current = current.next;
}
}
forEachReverse(callbackfn, thisArg) {
let current = this._tail;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
} else {
callbackfn(current.value, current.key, this);
}
current = current.previous;
}
}
values() {
let result = [];
let current = this._head;
while (current) {
result.push(current.value);
current = current.next;
}
return result;
}
keys() {
let result = [];
let current = this._head;
while (current) {
result.push(current.key);
current = current.next;
}
return result;
}
addItemFirst(item) {
if (!this._head && !this._tail) {
this._tail = item;
} else if (!this._head) {
throw new Error("Invalid list");
} else {
item.next = this._head;
this._head.previous = item;
}
this._head = item;
}
addItemLast(item) {
if (!this._head && !this._tail) {
this._head = item;
} else if (!this._tail) {
throw new Error("Invalid list");
} else {
item.previous = this._tail;
this._tail.next = item;
}
this._tail = item;
}
removeItem(item) {
if (item === this._head && item === this._tail) {
this._head = void 0;
this._tail = void 0;
} else if (item === this._head) {
this._head = item.next;
} else if (item === this._tail) {
this._tail = item.previous;
} else {
const next = item.next;
const previous = item.previous;
if (!next || !previous) {
throw new Error("Invalid list");
}
next.previous = previous;
previous.next = next;
}
}
touch(item, touch) {
if (!this._head || !this._tail) {
throw new Error("Invalid list");
}
if (touch !== Touch.First && touch !== Touch.Last) {
return;
}
if (touch === Touch.First) {
if (item === this._head) {
return;
}
const next = item.next;
const previous = item.previous;
if (item === this._tail) {
previous.next = void 0;
this._tail = previous;
} else {
next.previous = previous;
previous.next = next;
}
item.previous = void 0;
item.next = this._head;
this._head.previous = item;
this._head = item;
} else if (touch === Touch.Last) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
if (item === this._head) {
next.previous = void 0;
this._head = next;
} else {
next.previous = previous;
previous.next = next;
}
item.next = void 0;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
}
}
};
exports2.LinkedMap = LinkedMap;
});
// node_modules/vscode-jsonrpc/lib/pipeSupport.js
var require_pipeSupport = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var path_1 = require("path");
var os_1 = require("os");
var crypto_1 = require("crypto");
var net_1 = require("net");
var messageReader_1 = require_messageReader();
var messageWriter_1 = require_messageWriter();
function generateRandomPipeName() {
const randomSuffix = crypto_1.randomBytes(21).toString("hex");
if (process.platform === "win32") {
return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
} else {
return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
}
}
exports2.generateRandomPipeName = generateRandomPipeName;
function createClientPipeTransport(pipeName, encoding = "utf-8") {
let connectResolve;
let connected = new Promise((resolve, _reject) => {
connectResolve = resolve;
});
return new Promise((resolve, reject) => {
let server = net_1.createServer((socket) => {
server.close();
connectResolve([
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
]);
});
server.on("error", reject);
server.listen(pipeName, () => {
server.removeListener("error", reject);
resolve({
onConnected: () => {
return connected;
}
});
});
});
}
exports2.createClientPipeTransport = createClientPipeTransport;
function createServerPipeTransport(pipeName, encoding = "utf-8") {
const socket = net_1.createConnection(pipeName);
return [
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
];
}
exports2.createServerPipeTransport = createServerPipeTransport;
});
// node_modules/vscode-jsonrpc/lib/socketSupport.js
var require_socketSupport = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var net_1 = require("net");
var messageReader_1 = require_messageReader();
var messageWriter_1 = require_messageWriter();
function createClientSocketTransport(port, encoding = "utf-8") {
let connectResolve;
let connected = new Promise((resolve, _reject) => {
connectResolve = resolve;
});
return new Promise((resolve, reject) => {
let server = net_1.createServer((socket) => {
server.close();
connectResolve([
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
]);
});
server.on("error", reject);
server.listen(port, "127.0.0.1", () => {
server.removeListener("error", reject);
resolve({
onConnected: () => {
return connected;
}
});
});
});
}
exports2.createClientSocketTransport = createClientSocketTransport;
function createServerSocketTransport(port, encoding = "utf-8") {
const socket = net_1.createConnection(port, "127.0.0.1");
return [
new messageReader_1.SocketMessageReader(socket, encoding),
new messageWriter_1.SocketMessageWriter(socket, encoding)
];
}
exports2.createServerSocketTransport = createServerSocketTransport;
});
// node_modules/vscode-jsonrpc/lib/main.js
var require_main = __commonJS((exports2) => {
"use strict";
function __export2(m) {
for (var p in m)
if (!exports2.hasOwnProperty(p))
exports2[p] = m[p];
}
Object.defineProperty(exports2, "__esModule", {value: true});
var Is2 = require_is();
var messages_1 = require_messages();
exports2.RequestType = messages_1.RequestType;
exports2.RequestType0 = messages_1.RequestType0;
exports2.RequestType1 = messages_1.RequestType1;
exports2.RequestType2 = messages_1.RequestType2;
exports2.RequestType3 = messages_1.RequestType3;
exports2.RequestType4 = messages_1.RequestType4;
exports2.RequestType5 = messages_1.RequestType5;
exports2.RequestType6 = messages_1.RequestType6;
exports2.RequestType7 = messages_1.RequestType7;
exports2.RequestType8 = messages_1.RequestType8;
exports2.RequestType9 = messages_1.RequestType9;
exports2.ResponseError = messages_1.ResponseError;
exports2.ErrorCodes = messages_1.ErrorCodes;
exports2.NotificationType = messages_1.NotificationType;
exports2.NotificationType0 = messages_1.NotificationType0;
exports2.NotificationType1 = messages_1.NotificationType1;
exports2.NotificationType2 = messages_1.NotificationType2;
exports2.NotificationType3 = messages_1.NotificationType3;
exports2.NotificationType4 = messages_1.NotificationType4;
exports2.NotificationType5 = messages_1.NotificationType5;
exports2.NotificationType6 = messages_1.NotificationType6;
exports2.NotificationType7 = messages_1.NotificationType7;
exports2.NotificationType8 = messages_1.NotificationType8;
exports2.NotificationType9 = messages_1.NotificationType9;
var messageReader_1 = require_messageReader();
exports2.MessageReader = messageReader_1.MessageReader;
exports2.StreamMessageReader = messageReader_1.StreamMessageReader;
exports2.IPCMessageReader = messageReader_1.IPCMessageReader;
exports2.SocketMessageReader = messageReader_1.SocketMessageReader;
var messageWriter_1 = require_messageWriter();
exports2.MessageWriter = messageWriter_1.MessageWriter;
exports2.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
exports2.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
exports2.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
var events_1 = require_events();
exports2.Disposable = events_1.Disposable;
exports2.Event = events_1.Event;
exports2.Emitter = events_1.Emitter;
var cancellation_1 = require_cancellation();
exports2.CancellationTokenSource = cancellation_1.CancellationTokenSource;
exports2.CancellationToken = cancellation_1.CancellationToken;
var linkedMap_1 = require_linkedMap();
__export2(require_pipeSupport());
__export2(require_socketSupport());
var CancelNotification;
(function(CancelNotification2) {
CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
})(CancelNotification || (CancelNotification = {}));
var ProgressNotification;
(function(ProgressNotification2) {
ProgressNotification2.type = new messages_1.NotificationType("$/progress");
})(ProgressNotification || (ProgressNotification = {}));
var ProgressType = class {
constructor() {
}
};
exports2.ProgressType = ProgressType;
exports2.NullLogger = Object.freeze({
error: () => {
},
warn: () => {
},
info: () => {
},
log: () => {
}
});
var Trace;
(function(Trace2) {
Trace2[Trace2["Off"] = 0] = "Off";
Trace2[Trace2["Messages"] = 1] = "Messages";
Trace2[Trace2["Verbose"] = 2] = "Verbose";
})(Trace = exports2.Trace || (exports2.Trace = {}));
(function(Trace2) {
function fromString(value) {
if (!Is2.string(value)) {
return Trace2.Off;
}
value = value.toLowerCase();
switch (value) {
case "off":
return Trace2.Off;
case "messages":
return Trace2.Messages;
case "verbose":
return Trace2.Verbose;
default:
return Trace2.Off;
}
}
Trace2.fromString = fromString;
function toString(value) {
switch (value) {
case Trace2.Off:
return "off";
case Trace2.Messages:
return "messages";
case Trace2.Verbose:
return "verbose";
default:
return "off";
}
}
Trace2.toString = toString;
})(Trace = exports2.Trace || (exports2.Trace = {}));
var TraceFormat;
(function(TraceFormat2) {
TraceFormat2["Text"] = "text";
TraceFormat2["JSON"] = "json";
})(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
(function(TraceFormat2) {
function fromString(value) {
value = value.toLowerCase();
if (value === "json") {
return TraceFormat2.JSON;
} else {
return TraceFormat2.Text;
}
}
TraceFormat2.fromString = fromString;
})(TraceFormat = exports2.TraceFormat || (exports2.TraceFormat = {}));
var SetTraceNotification;
(function(SetTraceNotification2) {
SetTraceNotification2.type = new messages_1.NotificationType("$/setTraceNotification");
})(SetTraceNotification = exports2.SetTraceNotification || (exports2.SetTraceNotification = {}));
var LogTraceNotification;
(function(LogTraceNotification2) {
LogTraceNotification2.type = new messages_1.NotificationType("$/logTraceNotification");
})(LogTraceNotification = exports2.LogTraceNotification || (exports2.LogTraceNotification = {}));
var ConnectionErrors;
(function(ConnectionErrors2) {
ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
})(ConnectionErrors = exports2.ConnectionErrors || (exports2.ConnectionErrors = {}));
var ConnectionError = class extends Error {
constructor(code, message) {
super(message);
this.code = code;
Object.setPrototypeOf(this, ConnectionError.prototype);
}
};
exports2.ConnectionError = ConnectionError;
var ConnectionStrategy;
(function(ConnectionStrategy2) {
function is(value) {
let candidate = value;
return candidate && Is2.func(candidate.cancelUndispatched);
}
ConnectionStrategy2.is = is;
})(ConnectionStrategy = exports2.ConnectionStrategy || (exports2.ConnectionStrategy = {}));
var ConnectionState;
(function(ConnectionState2) {
ConnectionState2[ConnectionState2["New"] = 1] = "New";
ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
})(ConnectionState || (ConnectionState = {}));
function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
let sequenceNumber = 0;
let notificationSquenceNumber = 0;
let unknownResponseSquenceNumber = 0;
const version = "2.0";
let starRequestHandler = void 0;
let requestHandlers = Object.create(null);
let starNotificationHandler = void 0;
let notificationHandlers = Object.create(null);
let progressHandlers = new Map();
let timer;
let messageQueue = new linkedMap_1.LinkedMap();
let responsePromises = Object.create(null);
let requestTokens = Object.create(null);
let trace = Trace.Off;
let traceFormat = TraceFormat.Text;
let tracer;
let state = ConnectionState.New;
let errorEmitter = new events_1.Emitter();
let closeEmitter = new events_1.Emitter();
let unhandledNotificationEmitter = new events_1.Emitter();
let unhandledProgressEmitter = new events_1.Emitter();
let disposeEmitter = new events_1.Emitter();
function createRequestQueueKey(id) {
return "req-" + id.toString();
}
function createResponseQueueKey(id) {
if (id === null) {
return "res-unknown-" + (++unknownResponseSquenceNumber).toString();
} else {
return "res-" + id.toString();
}
}
function createNotificationQueueKey() {
return "not-" + (++notificationSquenceNumber).toString();
}
function addMessageToQueue(queue, message) {
if (messages_1.isRequestMessage(message)) {
queue.set(createRequestQueueKey(message.id), message);
} else if (messages_1.isResponseMessage(message)) {
queue.set(createResponseQueueKey(message.id), message);
} else {
queue.set(createNotificationQueueKey(), message);
}
}
function cancelUndispatched(_message) {
return void 0;
}
function isListening() {
return state === ConnectionState.Listening;
}
function isClosed() {
return state === ConnectionState.Closed;
}
function isDisposed() {
return state === ConnectionState.Disposed;
}
function closeHandler() {
if (state === ConnectionState.New || state === ConnectionState.Listening) {
state = ConnectionState.Closed;
closeEmitter.fire(void 0);
}
}
function readErrorHandler(error) {
errorEmitter.fire([error, void 0, void 0]);
}
function writeErrorHandler(data) {
errorEmitter.fire(data);
}
messageReader.onClose(closeHandler);
messageReader.onError(readErrorHandler);
messageWriter.onClose(closeHandler);
messageWriter.onError(writeErrorHandler);
function triggerMessageQueue() {
if (timer || messageQueue.size === 0) {
return;
}
timer = setImmediate(() => {
timer = void 0;
processMessageQueue();
});
}
function processMessageQueue() {
if (messageQueue.size === 0) {
return;
}
let message = messageQueue.shift();
try {
if (messages_1.isRequestMessage(message)) {
handleRequest(message);
} else if (messages_1.isNotificationMessage(message)) {
handleNotification(message);
} else if (messages_1.isResponseMessage(message)) {
handleResponse(message);
} else {
handleInvalidMessage(message);
}
} finally {
triggerMessageQueue();
}
}
let callback = (message) => {
try {
if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
let key = createRequestQueueKey(message.params.id);
let toCancel = messageQueue.get(key);
if (messages_1.isRequestMessage(toCancel)) {
let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
if (response && (response.error !== void 0 || response.result !== void 0)) {
messageQueue.delete(key);
response.id = toCancel.id;
traceSendingResponse(response, message.method, Date.now());
messageWriter.write(response);
return;
}
}
}
addMessageToQueue(messageQueue, message);
} finally {
triggerMessageQueue();
}
};
function handleRequest(requestMessage) {
if (isDisposed()) {
return;
}
function reply(resultOrError, method, startTime2) {
let message = {
jsonrpc: version,
id: requestMessage.id
};
if (resultOrError instanceof messages_1.ResponseError) {
message.error = resultOrError.toJson();
} else {
message.result = resultOrError === void 0 ? null : resultOrError;
}
traceSendingResponse(message, method, startTime2);
messageWriter.write(message);
}
function replyError(error, method, startTime2) {
let message = {
jsonrpc: version,
id: requestMessage.id,
error: error.toJson()
};
traceSendingResponse(message, method, startTime2);
messageWriter.write(message);
}
function replySuccess(result, method, startTime2) {
if (result === void 0) {
result = null;
}
let message = {
jsonrpc: version,
id: requestMessage.id,
result
};
traceSendingResponse(message, method, startTime2);
messageWriter.write(message);
}
traceReceivedRequest(requestMessage);
let element = requestHandlers[requestMessage.method];
let type;
let requestHandler;
if (element) {
type = element.type;
requestHandler = element.handler;
}
let startTime = Date.now();
if (requestHandler || starRequestHandler) {
let cancellationSource = new cancellation_1.CancellationTokenSource();
let tokenKey = String(requestMessage.id);
requestTokens[tokenKey] = cancellationSource;
try {
let handlerResult;
if (requestMessage.params === void 0 || type !== void 0 && type.numberOfParams === 0) {
handlerResult = requestHandler ? requestHandler(cancellationSource.token) : starRequestHandler(requestMessage.method, cancellationSource.token);
} else if (Is2.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
handlerResult = requestHandler ? requestHandler(...requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
} else {
handlerResult = requestHandler ? requestHandler(requestMessage.params, cancellationSource.token) : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
}
let promise = handlerResult;
if (!handlerResult) {
delete requestTokens[tokenKey];
replySuccess(handlerResult, requestMessage.method, startTime);
} else if (promise.then) {
promise.then((resultOrError) => {
delete requestTokens[tokenKey];
reply(resultOrError, requestMessage.method, startTime);
}, (error) => {
delete requestTokens[tokenKey];
if (error instanceof messages_1.ResponseError) {
replyError(error, requestMessage.method, startTime);
} else if (error && Is2.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
});
} else {
delete requestTokens[tokenKey];
reply(handlerResult, requestMessage.method, startTime);
}
} catch (error) {
delete requestTokens[tokenKey];
if (error instanceof messages_1.ResponseError) {
reply(error, requestMessage.method, startTime);
} else if (error && Is2.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
}
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
}
}
function handleResponse(responseMessage) {
if (isDisposed()) {
return;
}
if (responseMessage.id === null) {
if (responseMessage.error) {
logger.error(`Received response message without id: Error is:
${JSON.stringify(responseMessage.error, void 0, 4)}`);
} else {
logger.error(`Received response message without id. No further error information provided.`);
}
} else {
let key = String(responseMessage.id);
let responsePromise = responsePromises[key];
traceReceivedResponse(responseMessage, responsePromise);
if (responsePromise) {
delete responsePromises[key];
try {
if (responseMessage.error) {
let error = responseMessage.error;
responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
} else if (responseMessage.result !== void 0) {
responsePromise.resolve(responseMessage.result);
} else {
throw new Error("Should never happen.");
}
} catch (error) {
if (error.message) {
logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
} else {
logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
}
}
}
}
}
function handleNotification(message) {
if (isDisposed()) {
return;
}
let type = void 0;
let notificationHandler;
if (message.method === CancelNotification.type.method) {
notificationHandler = (params) => {
let id = params.id;
let source = requestTokens[String(id)];
if (source) {
source.cancel();
}
};
} else {
let element = notificationHandlers[message.method];
if (element) {
notificationHandler = element.handler;
type = element.type;
}
}
if (notificationHandler || starNotificationHandler) {
try {
traceReceivedNotification(message);
if (message.params === void 0 || type !== void 0 && type.numberOfParams === 0) {
notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
} else if (Is2.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
} else {
notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
}
} catch (error) {
if (error.message) {
logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
} else {
logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
}
}
} else {
unhandledNotificationEmitter.fire(message);
}
}
function handleInvalidMessage(message) {
if (!message) {
logger.error("Received empty message.");
return;
}
logger.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(message, null, 4)}`);
let responseMessage = message;
if (Is2.string(responseMessage.id) || Is2.number(responseMessage.id)) {
let key = String(responseMessage.id);
let responseHandler = responsePromises[key];
if (responseHandler) {
responseHandler.reject(new Error("The received response has neither a result nor an error property."));
}
}
}
function traceSendingRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose && message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}
`;
}
tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
} else {
logLSPMessage("send-request", message);
}
}
function traceSendingNotification(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose) {
if (message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}
`;
} else {
data = "No parameters provided.\n\n";
}
}
tracer.log(`Sending notification '${message.method}'.`, data);
} else {
logLSPMessage("send-notification", message);
}
}
function traceSendingResponse(message, method, startTime) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose) {
if (message.error && message.error.data) {
data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
`;
} else {
if (message.result) {
data = `Result: ${JSON.stringify(message.result, null, 4)}
`;
} else if (message.error === void 0) {
data = "No result returned.\n\n";
}
}
}
tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
} else {
logLSPMessage("send-response", message);
}
}
function traceReceivedRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose && message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}
`;
}
tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
} else {
logLSPMessage("receive-request", message);
}
}
function traceReceivedNotification(message) {
if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose) {
if (message.params) {
data = `Params: ${JSON.stringify(message.params, null, 4)}
`;
} else {
data = "No parameters provided.\n\n";
}
}
tracer.log(`Received notification '${message.method}'.`, data);
} else {
logLSPMessage("receive-notification", message);
}
}
function traceReceivedResponse(message, responsePromise) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose) {
if (message.error && message.error.data) {
data = `Error data: ${JSON.stringify(message.error.data, null, 4)}
`;
} else {
if (message.result) {
data = `Result: ${JSON.stringify(message.result, null, 4)}
`;
} else if (message.error === void 0) {
data = "No result returned.\n\n";
}
}
}
if (responsePromise) {
let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
} else {
tracer.log(`Received response ${message.id} without active response promise.`, data);
}
} else {
logLSPMessage("receive-response", message);
}
}
function logLSPMessage(type, message) {
if (!tracer || trace === Trace.Off) {
return;
}
const lspMessage = {
isLSPMessage: true,
type,
message,
timestamp: Date.now()
};
tracer.log(lspMessage);
}
function throwIfClosedOrDisposed() {
if (isClosed()) {
throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
}
if (isDisposed()) {
throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
}
}
function throwIfListening() {
if (isListening()) {
throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
}
}
function throwIfNotListening() {
if (!isListening()) {
throw new Error("Call listen() first.");
}
}
function undefinedToNull(param) {
if (param === void 0) {
return null;
} else {
return param;
}
}
function computeMessageParams(type, params) {
let result;
let numberOfParams = type.numberOfParams;
switch (numberOfParams) {
case 0:
result = null;
break;
case 1:
result = undefinedToNull(params[0]);
break;
default:
result = [];
for (let i = 0; i < params.length && i < numberOfParams; i++) {
result.push(undefinedToNull(params[i]));
}
if (params.length < numberOfParams) {
for (let i = params.length; i < numberOfParams; i++) {
result.push(null);
}
}
break;
}
return result;
}
let connection = {
sendNotification: (type, ...params) => {
throwIfClosedOrDisposed();
let method;
let messageParams;
if (Is2.string(type)) {
method = type;
switch (params.length) {
case 0:
messageParams = null;
break;
case 1:
messageParams = params[0];
break;
default:
messageParams = params;
break;
}
} else {
method = type.method;
messageParams = computeMessageParams(type, params);
}
let notificationMessage = {
jsonrpc: version,
method,
params: messageParams
};
traceSendingNotification(notificationMessage);
messageWriter.write(notificationMessage);
},
onNotification: (type, handler) => {
throwIfClosedOrDisposed();
if (Is2.func(type)) {
starNotificationHandler = type;
} else if (handler) {
if (Is2.string(type)) {
notificationHandlers[type] = {type: void 0, handler};
} else {
notificationHandlers[type.method] = {type, handler};
}
}
},
onProgress: (_type, token, handler) => {
if (progressHandlers.has(token)) {
throw new Error(`Progress handler for token ${token} already registered`);
}
progressHandlers.set(token, handler);
return {
dispose: () => {
progressHandlers.delete(token);
}
};
},
sendProgress: (_type, token, value) => {
connection.sendNotification(ProgressNotification.type, {token, value});
},
onUnhandledProgress: unhandledProgressEmitter.event,
sendRequest: (type, ...params) => {
throwIfClosedOrDisposed();
throwIfNotListening();
let method;
let messageParams;
let token = void 0;
if (Is2.string(type)) {
method = type;
switch (params.length) {
case 0:
messageParams = null;
break;
case 1:
if (cancellation_1.CancellationToken.is(params[0])) {
messageParams = null;
token = params[0];
} else {
messageParams = undefinedToNull(params[0]);
}
break;
default:
const last = params.length - 1;
if (cancellation_1.CancellationToken.is(params[last])) {
token = params[last];
if (params.length === 2) {
messageParams = undefinedToNull(params[0]);
} else {
messageParams = params.slice(0, last).map((value) => undefinedToNull(value));
}
} else {
messageParams = params.map((value) => undefinedToNull(value));
}
break;
}
} else {
method = type.method;
messageParams = computeMessageParams(type, params);
let numberOfParams = type.numberOfParams;
token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
}
let id = sequenceNumber++;
let result = new Promise((resolve, reject) => {
let requestMessage = {
jsonrpc: version,
id,
method,
params: messageParams
};
let responsePromise = {method, timerStart: Date.now(), resolve, reject};
traceSendingRequest(requestMessage);
try {
messageWriter.write(requestMessage);
} catch (e) {
responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : "Unknown reason"));
responsePromise = null;
}
if (responsePromise) {
responsePromises[String(id)] = responsePromise;
}
});
if (token) {
token.onCancellationRequested(() => {
connection.sendNotification(CancelNotification.type, {id});
});
}
return result;
},
onRequest: (type, handler) => {
throwIfClosedOrDisposed();
if (Is2.func(type)) {
starRequestHandler = type;
} else if (handler) {
if (Is2.string(type)) {
requestHandlers[type] = {type: void 0, handler};
} else {
requestHandlers[type.method] = {type, handler};
}
}
},
trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
let _sendNotification = false;
let _traceFormat = TraceFormat.Text;
if (sendNotificationOrTraceOptions !== void 0) {
if (Is2.boolean(sendNotificationOrTraceOptions)) {
_sendNotification = sendNotificationOrTraceOptions;
} else {
_sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
_traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
}
}
trace = _value;
traceFormat = _traceFormat;
if (trace === Trace.Off) {
tracer = void 0;
} else {
tracer = _tracer;
}
if (_sendNotification && !isClosed() && !isDisposed()) {
connection.sendNotification(SetTraceNotification.type, {value: Trace.toString(_value)});
}
},
onError: errorEmitter.event,
onClose: closeEmitter.event,
onUnhandledNotification: unhandledNotificationEmitter.event,
onDispose: disposeEmitter.event,
dispose: () => {
if (isDisposed()) {
return;
}
state = ConnectionState.Disposed;
disposeEmitter.fire(void 0);
let error = new Error("Connection got disposed.");
Object.keys(responsePromises).forEach((key) => {
responsePromises[key].reject(error);
});
responsePromises = Object.create(null);
requestTokens = Object.create(null);
messageQueue = new linkedMap_1.LinkedMap();
if (Is2.func(messageWriter.dispose)) {
messageWriter.dispose();
}
if (Is2.func(messageReader.dispose)) {
messageReader.dispose();
}
},
listen: () => {
throwIfClosedOrDisposed();
throwIfListening();
state = ConnectionState.Listening;
messageReader.listen(callback);
},
inspect: () => {
console.log("inspect");
}
};
connection.onNotification(LogTraceNotification.type, (params) => {
if (trace === Trace.Off || !tracer) {
return;
}
tracer.log(params.message, trace === Trace.Verbose ? params.verbose : void 0);
});
connection.onNotification(ProgressNotification.type, (params) => {
const handler = progressHandlers.get(params.token);
if (handler) {
handler(params.value);
} else {
unhandledProgressEmitter.fire(params);
}
});
return connection;
}
function isMessageReader(value) {
return value.listen !== void 0 && value.read === void 0;
}
function isMessageWriter(value) {
return value.write !== void 0 && value.end === void 0;
}
function createMessageConnection(input, output, logger, strategy) {
if (!logger) {
logger = exports2.NullLogger;
}
let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
return _createMessageConnection(reader, writer, logger, strategy);
}
exports2.createMessageConnection = createMessageConnection;
});
// node_modules/vscode-languageserver-types/lib/esm/main.js
var require_main2 = __commonJS((exports2) => {
__export(exports2, {
CodeAction: () => CodeAction2,
CodeActionContext: () => CodeActionContext2,
CodeActionKind: () => CodeActionKind2,
CodeLens: () => CodeLens,
Color: () => Color,
ColorInformation: () => ColorInformation,
ColorPresentation: () => ColorPresentation,
Command: () => Command2,
CompletionItem: () => CompletionItem,
CompletionItemKind: () => CompletionItemKind,
CompletionItemTag: () => CompletionItemTag,
CompletionList: () => CompletionList,
CreateFile: () => CreateFile,
DeleteFile: () => DeleteFile,
Diagnostic: () => Diagnostic2,
DiagnosticRelatedInformation: () => DiagnosticRelatedInformation,
DiagnosticSeverity: () => DiagnosticSeverity,
DiagnosticTag: () => DiagnosticTag,
DocumentHighlight: () => DocumentHighlight,
DocumentHighlightKind: () => DocumentHighlightKind,
DocumentLink: () => DocumentLink,
DocumentSymbol: () => DocumentSymbol,
EOL: () => EOL,
FoldingRange: () => FoldingRange,
FoldingRangeKind: () => FoldingRangeKind,
FormattingOptions: () => FormattingOptions,
Hover: () => Hover,
InsertTextFormat: () => InsertTextFormat,
Location: () => Location2,
LocationLink: () => LocationLink,
MarkedString: () => MarkedString,
MarkupContent: () => MarkupContent,
MarkupKind: () => MarkupKind,
ParameterInformation: () => ParameterInformation,
Position: () => Position2,
Range: () => Range2,
RenameFile: () => RenameFile,
SelectionRange: () => SelectionRange,
SignatureInformation: () => SignatureInformation,
SymbolInformation: () => SymbolInformation,
SymbolKind: () => SymbolKind,
SymbolTag: () => SymbolTag,
TextDocument: () => TextDocument2,
TextDocumentEdit: () => TextDocumentEdit,
TextDocumentIdentifier: () => TextDocumentIdentifier2,
TextDocumentItem: () => TextDocumentItem,
TextEdit: () => TextEdit,
VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier2,
WorkspaceChange: () => WorkspaceChange,
WorkspaceEdit: () => WorkspaceEdit
});
"use strict";
var Position2;
(function(Position3) {
function create(line, character) {
return {line, character};
}
Position3.create = create;
function is(value) {
var candidate = value;
return Is2.objectLiteral(candidate) && Is2.number(candidate.line) && Is2.number(candidate.character);
}
Position3.is = is;
})(Position2 || (Position2 = {}));
var Range2;
(function(Range3) {
function create(one, two, three, four) {
if (Is2.number(one) && Is2.number(two) && Is2.number(three) && Is2.number(four)) {
return {start: Position2.create(one, two), end: Position2.create(three, four)};
} else if (Position2.is(one) && Position2.is(two)) {
return {start: one, end: two};
} else {
throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
}
}
Range3.create = create;
function is(value) {
var candidate = value;
return Is2.objectLiteral(candidate) && Position2.is(candidate.start) && Position2.is(candidate.end);
}
Range3.is = is;
})(Range2 || (Range2 = {}));
var Location2;
(function(Location3) {
function create(uri, range) {
return {uri, range};
}
Location3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Range2.is(candidate.range) && (Is2.string(candidate.uri) || Is2.undefined(candidate.uri));
}
Location3.is = is;
})(Location2 || (Location2 = {}));
var LocationLink;
(function(LocationLink2) {
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
return {targetUri, targetRange, targetSelectionRange, originSelectionRange};
}
LocationLink2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Range2.is(candidate.targetRange) && Is2.string(candidate.targetUri) && (Range2.is(candidate.targetSelectionRange) || Is2.undefined(candidate.targetSelectionRange)) && (Range2.is(candidate.originSelectionRange) || Is2.undefined(candidate.originSelectionRange));
}
LocationLink2.is = is;
})(LocationLink || (LocationLink = {}));
var Color;
(function(Color2) {
function create(red, green, blue, alpha) {
return {
red,
green,
blue,
alpha
};
}
Color2.create = create;
function is(value) {
var candidate = value;
return Is2.number(candidate.red) && Is2.number(candidate.green) && Is2.number(candidate.blue) && Is2.number(candidate.alpha);
}
Color2.is = is;
})(Color || (Color = {}));
var ColorInformation;
(function(ColorInformation2) {
function create(range, color) {
return {
range,
color
};
}
ColorInformation2.create = create;
function is(value) {
var candidate = value;
return Range2.is(candidate.range) && Color.is(candidate.color);
}
ColorInformation2.is = is;
})(ColorInformation || (ColorInformation = {}));
var ColorPresentation;
(function(ColorPresentation2) {
function create(label, textEdit, additionalTextEdits) {
return {
label,
textEdit,
additionalTextEdits
};
}
ColorPresentation2.create = create;
function is(value) {
var candidate = value;
return Is2.string(candidate.label) && (Is2.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is2.undefined(candidate.additionalTextEdits) || Is2.typedArray(candidate.additionalTextEdits, TextEdit.is));
}
ColorPresentation2.is = is;
})(ColorPresentation || (ColorPresentation = {}));
var FoldingRangeKind;
(function(FoldingRangeKind2) {
FoldingRangeKind2["Comment"] = "comment";
FoldingRangeKind2["Imports"] = "imports";
FoldingRangeKind2["Region"] = "region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
var FoldingRange;
(function(FoldingRange2) {
function create(startLine, endLine, startCharacter, endCharacter, kind) {
var result = {
startLine,
endLine
};
if (Is2.defined(startCharacter)) {
result.startCharacter = startCharacter;
}
if (Is2.defined(endCharacter)) {
result.endCharacter = endCharacter;
}
if (Is2.defined(kind)) {
result.kind = kind;
}
return result;
}
FoldingRange2.create = create;
function is(value) {
var candidate = value;
return Is2.number(candidate.startLine) && Is2.number(candidate.startLine) && (Is2.undefined(candidate.startCharacter) || Is2.number(candidate.startCharacter)) && (Is2.undefined(candidate.endCharacter) || Is2.number(candidate.endCharacter)) && (Is2.undefined(candidate.kind) || Is2.string(candidate.kind));
}
FoldingRange2.is = is;
})(FoldingRange || (FoldingRange = {}));
var DiagnosticRelatedInformation;
(function(DiagnosticRelatedInformation2) {
function create(location, message) {
return {
location,
message
};
}
DiagnosticRelatedInformation2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Location2.is(candidate.location) && Is2.string(candidate.message);
}
DiagnosticRelatedInformation2.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
var DiagnosticSeverity;
(function(DiagnosticSeverity2) {
DiagnosticSeverity2.Error = 1;
DiagnosticSeverity2.Warning = 2;
DiagnosticSeverity2.Information = 3;
DiagnosticSeverity2.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
var DiagnosticTag;
(function(DiagnosticTag2) {
DiagnosticTag2.Unnecessary = 1;
DiagnosticTag2.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
var Diagnostic2;
(function(Diagnostic3) {
function create(range, message, severity, code, source, relatedInformation) {
var result = {range, message};
if (Is2.defined(severity)) {
result.severity = severity;
}
if (Is2.defined(code)) {
result.code = code;
}
if (Is2.defined(source)) {
result.source = source;
}
if (Is2.defined(relatedInformation)) {
result.relatedInformation = relatedInformation;
}
return result;
}
Diagnostic3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Range2.is(candidate.range) && Is2.string(candidate.message) && (Is2.number(candidate.severity) || Is2.undefined(candidate.severity)) && (Is2.number(candidate.code) || Is2.string(candidate.code) || Is2.undefined(candidate.code)) && (Is2.string(candidate.source) || Is2.undefined(candidate.source)) && (Is2.undefined(candidate.relatedInformation) || Is2.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
}
Diagnostic3.is = is;
})(Diagnostic2 || (Diagnostic2 = {}));
var Command2;
(function(Command3) {
function create(title, command) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = {title, command};
if (Is2.defined(args) && args.length > 0) {
result.arguments = args;
}
return result;
}
Command3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.string(candidate.title) && Is2.string(candidate.command);
}
Command3.is = is;
})(Command2 || (Command2 = {}));
var TextEdit;
(function(TextEdit2) {
function replace(range, newText) {
return {range, newText};
}
TextEdit2.replace = replace;
function insert(position, newText) {
return {range: {start: position, end: position}, newText};
}
TextEdit2.insert = insert;
function del(range) {
return {range, newText: ""};
}
TextEdit2.del = del;
function is(value) {
var candidate = value;
return Is2.objectLiteral(candidate) && Is2.string(candidate.newText) && Range2.is(candidate.range);
}
TextEdit2.is = is;
})(TextEdit || (TextEdit = {}));
var TextDocumentEdit;
(function(TextDocumentEdit2) {
function create(textDocument, edits) {
return {textDocument, edits};
}
TextDocumentEdit2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && VersionedTextDocumentIdentifier2.is(candidate.textDocument) && Array.isArray(candidate.edits);
}
TextDocumentEdit2.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
var CreateFile;
(function(CreateFile2) {
function create(uri, options) {
var result = {
kind: "create",
uri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
CreateFile2.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === "create" && Is2.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is2.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is2.boolean(candidate.options.ignoreIfExists)));
}
CreateFile2.is = is;
})(CreateFile || (CreateFile = {}));
var RenameFile;
(function(RenameFile2) {
function create(oldUri, newUri, options) {
var result = {
kind: "rename",
oldUri,
newUri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
return result;
}
RenameFile2.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === "rename" && Is2.string(candidate.oldUri) && Is2.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is2.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is2.boolean(candidate.options.ignoreIfExists)));
}
RenameFile2.is = is;
})(RenameFile || (RenameFile = {}));
var DeleteFile;
(function(DeleteFile2) {
function create(uri, options) {
var result = {
kind: "delete",
uri
};
if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
result.options = options;
}
return result;
}
DeleteFile2.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === "delete" && Is2.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is2.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is2.boolean(candidate.options.ignoreIfNotExists)));
}
DeleteFile2.is = is;
})(DeleteFile || (DeleteFile = {}));
var WorkspaceEdit;
(function(WorkspaceEdit2) {
function is(value) {
var candidate = value;
return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) {
if (Is2.string(change.kind)) {
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
} else {
return TextDocumentEdit.is(change);
}
}));
}
WorkspaceEdit2.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var TextEditChangeImpl = function() {
function TextEditChangeImpl2(edits) {
this.edits = edits;
}
TextEditChangeImpl2.prototype.insert = function(position, newText) {
this.edits.push(TextEdit.insert(position, newText));
};
TextEditChangeImpl2.prototype.replace = function(range, newText) {
this.edits.push(TextEdit.replace(range, newText));
};
TextEditChangeImpl2.prototype.delete = function(range) {
this.edits.push(TextEdit.del(range));
};
TextEditChangeImpl2.prototype.add = function(edit) {
this.edits.push(edit);
};
TextEditChangeImpl2.prototype.all = function() {
return this.edits;
};
TextEditChangeImpl2.prototype.clear = function() {
this.edits.splice(0, this.edits.length);
};
return TextEditChangeImpl2;
}();
var WorkspaceChange = function() {
function WorkspaceChange2(workspaceEdit) {
var _this = this;
this._textEditChanges = Object.create(null);
if (workspaceEdit) {
this._workspaceEdit = workspaceEdit;
if (workspaceEdit.documentChanges) {
workspaceEdit.documentChanges.forEach(function(change) {
if (TextDocumentEdit.is(change)) {
var textEditChange = new TextEditChangeImpl(change.edits);
_this._textEditChanges[change.textDocument.uri] = textEditChange;
}
});
} else if (workspaceEdit.changes) {
Object.keys(workspaceEdit.changes).forEach(function(key) {
var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
_this._textEditChanges[key] = textEditChange;
});
}
}
}
Object.defineProperty(WorkspaceChange2.prototype, "edit", {
get: function() {
return this._workspaceEdit;
},
enumerable: true,
configurable: true
});
WorkspaceChange2.prototype.getTextEditChange = function(key) {
if (VersionedTextDocumentIdentifier2.is(key)) {
if (!this._workspaceEdit) {
this._workspaceEdit = {
documentChanges: []
};
}
if (!this._workspaceEdit.documentChanges) {
throw new Error("Workspace edit is not configured for document changes.");
}
var textDocument = key;
var result = this._textEditChanges[textDocument.uri];
if (!result) {
var edits = [];
var textDocumentEdit = {
textDocument,
edits
};
this._workspaceEdit.documentChanges.push(textDocumentEdit);
result = new TextEditChangeImpl(edits);
this._textEditChanges[textDocument.uri] = result;
}
return result;
} else {
if (!this._workspaceEdit) {
this._workspaceEdit = {
changes: Object.create(null)
};
}
if (!this._workspaceEdit.changes) {
throw new Error("Workspace edit is not configured for normal text edit changes.");
}
var result = this._textEditChanges[key];
if (!result) {
var edits = [];
this._workspaceEdit.changes[key] = edits;
result = new TextEditChangeImpl(edits);
this._textEditChanges[key] = result;
}
return result;
}
};
WorkspaceChange2.prototype.createFile = function(uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
};
WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
};
WorkspaceChange2.prototype.deleteFile = function(uri, options) {
this.checkDocumentChanges();
this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
};
WorkspaceChange2.prototype.checkDocumentChanges = function() {
if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
throw new Error("Workspace edit is not configured for document changes.");
}
};
return WorkspaceChange2;
}();
var TextDocumentIdentifier2;
(function(TextDocumentIdentifier3) {
function create(uri) {
return {uri};
}
TextDocumentIdentifier3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.string(candidate.uri);
}
TextDocumentIdentifier3.is = is;
})(TextDocumentIdentifier2 || (TextDocumentIdentifier2 = {}));
var VersionedTextDocumentIdentifier2;
(function(VersionedTextDocumentIdentifier3) {
function create(uri, version) {
return {uri, version};
}
VersionedTextDocumentIdentifier3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.string(candidate.uri) && (candidate.version === null || Is2.number(candidate.version));
}
VersionedTextDocumentIdentifier3.is = is;
})(VersionedTextDocumentIdentifier2 || (VersionedTextDocumentIdentifier2 = {}));
var TextDocumentItem;
(function(TextDocumentItem2) {
function create(uri, languageId, version, text) {
return {uri, languageId, version, text};
}
TextDocumentItem2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.string(candidate.uri) && Is2.string(candidate.languageId) && Is2.number(candidate.version) && Is2.string(candidate.text);
}
TextDocumentItem2.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
var MarkupKind;
(function(MarkupKind2) {
MarkupKind2.PlainText = "plaintext";
MarkupKind2.Markdown = "markdown";
})(MarkupKind || (MarkupKind = {}));
(function(MarkupKind2) {
function is(value) {
var candidate = value;
return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown;
}
MarkupKind2.is = is;
})(MarkupKind || (MarkupKind = {}));
var MarkupContent;
(function(MarkupContent2) {
function is(value) {
var candidate = value;
return Is2.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is2.string(candidate.value);
}
MarkupContent2.is = is;
})(MarkupContent || (MarkupContent = {}));
var CompletionItemKind;
(function(CompletionItemKind2) {
CompletionItemKind2.Text = 1;
CompletionItemKind2.Method = 2;
CompletionItemKind2.Function = 3;
CompletionItemKind2.Constructor = 4;
CompletionItemKind2.Field = 5;
CompletionItemKind2.Variable = 6;
CompletionItemKind2.Class = 7;
CompletionItemKind2.Interface = 8;
CompletionItemKind2.Module = 9;
CompletionItemKind2.Property = 10;
CompletionItemKind2.Unit = 11;
CompletionItemKind2.Value = 12;
CompletionItemKind2.Enum = 13;
CompletionItemKind2.Keyword = 14;
CompletionItemKind2.Snippet = 15;
CompletionItemKind2.Color = 16;
CompletionItemKind2.File = 17;
CompletionItemKind2.Reference = 18;
CompletionItemKind2.Folder = 19;
CompletionItemKind2.EnumMember = 20;
CompletionItemKind2.Constant = 21;
CompletionItemKind2.Struct = 22;
CompletionItemKind2.Event = 23;
CompletionItemKind2.Operator = 24;
CompletionItemKind2.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
var InsertTextFormat;
(function(InsertTextFormat2) {
InsertTextFormat2.PlainText = 1;
InsertTextFormat2.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
var CompletionItemTag;
(function(CompletionItemTag2) {
CompletionItemTag2.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
var CompletionItem;
(function(CompletionItem2) {
function create(label) {
return {label};
}
CompletionItem2.create = create;
})(CompletionItem || (CompletionItem = {}));
var CompletionList;
(function(CompletionList2) {
function create(items, isIncomplete) {
return {items: items ? items : [], isIncomplete: !!isIncomplete};
}
CompletionList2.create = create;
})(CompletionList || (CompletionList = {}));
var MarkedString;
(function(MarkedString2) {
function fromPlainText(plainText) {
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
}
MarkedString2.fromPlainText = fromPlainText;
function is(value) {
var candidate = value;
return Is2.string(candidate) || Is2.objectLiteral(candidate) && Is2.string(candidate.language) && Is2.string(candidate.value);
}
MarkedString2.is = is;
})(MarkedString || (MarkedString = {}));
var Hover;
(function(Hover2) {
function is(value) {
var candidate = value;
return !!candidate && Is2.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is2.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range2.is(value.range));
}
Hover2.is = is;
})(Hover || (Hover = {}));
var ParameterInformation;
(function(ParameterInformation2) {
function create(label, documentation) {
return documentation ? {label, documentation} : {label};
}
ParameterInformation2.create = create;
})(ParameterInformation || (ParameterInformation = {}));
var SignatureInformation;
(function(SignatureInformation2) {
function create(label, documentation) {
var parameters = [];
for (var _i = 2; _i < arguments.length; _i++) {
parameters[_i - 2] = arguments[_i];
}
var result = {label};
if (Is2.defined(documentation)) {
result.documentation = documentation;
}
if (Is2.defined(parameters)) {
result.parameters = parameters;
} else {
result.parameters = [];
}
return result;
}
SignatureInformation2.create = create;
})(SignatureInformation || (SignatureInformation = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind2) {
DocumentHighlightKind2.Text = 1;
DocumentHighlightKind2.Read = 2;
DocumentHighlightKind2.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
var DocumentHighlight;
(function(DocumentHighlight2) {
function create(range, kind) {
var result = {range};
if (Is2.number(kind)) {
result.kind = kind;
}
return result;
}
DocumentHighlight2.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
var SymbolKind;
(function(SymbolKind2) {
SymbolKind2.File = 1;
SymbolKind2.Module = 2;
SymbolKind2.Namespace = 3;
SymbolKind2.Package = 4;
SymbolKind2.Class = 5;
SymbolKind2.Method = 6;
SymbolKind2.Property = 7;
SymbolKind2.Field = 8;
SymbolKind2.Constructor = 9;
SymbolKind2.Enum = 10;
SymbolKind2.Interface = 11;
SymbolKind2.Function = 12;
SymbolKind2.Variable = 13;
SymbolKind2.Constant = 14;
SymbolKind2.String = 15;
SymbolKind2.Number = 16;
SymbolKind2.Boolean = 17;
SymbolKind2.Array = 18;
SymbolKind2.Object = 19;
SymbolKind2.Key = 20;
SymbolKind2.Null = 21;
SymbolKind2.EnumMember = 22;
SymbolKind2.Struct = 23;
SymbolKind2.Event = 24;
SymbolKind2.Operator = 25;
SymbolKind2.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
var SymbolTag;
(function(SymbolTag2) {
SymbolTag2.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
var SymbolInformation;
(function(SymbolInformation2) {
function create(name, kind, range, uri, containerName) {
var result = {
name,
kind,
location: {uri, range}
};
if (containerName) {
result.containerName = containerName;
}
return result;
}
SymbolInformation2.create = create;
})(SymbolInformation || (SymbolInformation = {}));
var DocumentSymbol;
(function(DocumentSymbol2) {
function create(name, detail, kind, range, selectionRange, children) {
var result = {
name,
detail,
kind,
range,
selectionRange
};
if (children !== void 0) {
result.children = children;
}
return result;
}
DocumentSymbol2.create = create;
function is(value) {
var candidate = value;
return candidate && Is2.string(candidate.name) && Is2.number(candidate.kind) && Range2.is(candidate.range) && Range2.is(candidate.selectionRange) && (candidate.detail === void 0 || Is2.string(candidate.detail)) && (candidate.deprecated === void 0 || Is2.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children));
}
DocumentSymbol2.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
var CodeActionKind2;
(function(CodeActionKind3) {
CodeActionKind3.Empty = "";
CodeActionKind3.QuickFix = "quickfix";
CodeActionKind3.Refactor = "refactor";
CodeActionKind3.RefactorExtract = "refactor.extract";
CodeActionKind3.RefactorInline = "refactor.inline";
CodeActionKind3.RefactorRewrite = "refactor.rewrite";
CodeActionKind3.Source = "source";
CodeActionKind3.SourceOrganizeImports = "source.organizeImports";
CodeActionKind3.SourceFixAll = "source.fixAll";
})(CodeActionKind2 || (CodeActionKind2 = {}));
var CodeActionContext2;
(function(CodeActionContext3) {
function create(diagnostics, only) {
var result = {diagnostics};
if (only !== void 0 && only !== null) {
result.only = only;
}
return result;
}
CodeActionContext3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.typedArray(candidate.diagnostics, Diagnostic2.is) && (candidate.only === void 0 || Is2.typedArray(candidate.only, Is2.string));
}
CodeActionContext3.is = is;
})(CodeActionContext2 || (CodeActionContext2 = {}));
var CodeAction2;
(function(CodeAction3) {
function create(title, commandOrEdit, kind) {
var result = {title};
if (Command2.is(commandOrEdit)) {
result.command = commandOrEdit;
} else {
result.edit = commandOrEdit;
}
if (kind !== void 0) {
result.kind = kind;
}
return result;
}
CodeAction3.create = create;
function is(value) {
var candidate = value;
return candidate && Is2.string(candidate.title) && (candidate.diagnostics === void 0 || Is2.typedArray(candidate.diagnostics, Diagnostic2.is)) && (candidate.kind === void 0 || Is2.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command2.is(candidate.command)) && (candidate.isPreferred === void 0 || Is2.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
}
CodeAction3.is = is;
})(CodeAction2 || (CodeAction2 = {}));
var CodeLens;
(function(CodeLens2) {
function create(range, data) {
var result = {range};
if (Is2.defined(data)) {
result.data = data;
}
return result;
}
CodeLens2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Range2.is(candidate.range) && (Is2.undefined(candidate.command) || Command2.is(candidate.command));
}
CodeLens2.is = is;
})(CodeLens || (CodeLens = {}));
var FormattingOptions;
(function(FormattingOptions2) {
function create(tabSize, insertSpaces) {
return {tabSize, insertSpaces};
}
FormattingOptions2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.number(candidate.tabSize) && Is2.boolean(candidate.insertSpaces);
}
FormattingOptions2.is = is;
})(FormattingOptions || (FormattingOptions = {}));
var DocumentLink;
(function(DocumentLink2) {
function create(range, target, data) {
return {range, target, data};
}
DocumentLink2.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Range2.is(candidate.range) && (Is2.undefined(candidate.target) || Is2.string(candidate.target));
}
DocumentLink2.is = is;
})(DocumentLink || (DocumentLink = {}));
var SelectionRange;
(function(SelectionRange2) {
function create(range, parent) {
return {range, parent};
}
SelectionRange2.create = create;
function is(value) {
var candidate = value;
return candidate !== void 0 && Range2.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
}
SelectionRange2.is = is;
})(SelectionRange || (SelectionRange = {}));
var EOL = ["\n", "\r\n", "\r"];
var TextDocument2;
(function(TextDocument3) {
function create(uri, languageId, version, content) {
return new FullTextDocument(uri, languageId, version, content);
}
TextDocument3.create = create;
function is(value) {
var candidate = value;
return Is2.defined(candidate) && Is2.string(candidate.uri) && (Is2.undefined(candidate.languageId) || Is2.string(candidate.languageId)) && Is2.number(candidate.lineCount) && Is2.func(candidate.getText) && Is2.func(candidate.positionAt) && Is2.func(candidate.offsetAt) ? true : false;
}
TextDocument3.is = is;
function applyEdits(document, edits) {
var text = document.getText();
var sortedEdits = mergeSort(edits, function(a, b) {
var diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
var lastModifiedOffset = text.length;
for (var i = sortedEdits.length - 1; i >= 0; i--) {
var e = sortedEdits[i];
var startOffset = document.offsetAt(e.range.start);
var endOffset = document.offsetAt(e.range.end);
if (endOffset <= lastModifiedOffset) {
text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
} else {
throw new Error("Overlapping edit");
}
lastModifiedOffset = startOffset;
}
return text;
}
TextDocument3.applyEdits = applyEdits;
function mergeSort(data, compare) {
if (data.length <= 1) {
return data;
}
var p = data.length / 2 | 0;
var left = data.slice(0, p);
var right = data.slice(p);
mergeSort(left, compare);
mergeSort(right, compare);
var leftIdx = 0;
var rightIdx = 0;
var i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
var ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
data[i++] = left[leftIdx++];
} else {
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
})(TextDocument2 || (TextDocument2 = {}));
var FullTextDocument = function() {
function FullTextDocument2(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = void 0;
}
Object.defineProperty(FullTextDocument2.prototype, "uri", {
get: function() {
return this._uri;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument2.prototype, "languageId", {
get: function() {
return this._languageId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FullTextDocument2.prototype, "version", {
get: function() {
return this._version;
},
enumerable: true,
configurable: true
});
FullTextDocument2.prototype.getText = function(range) {
if (range) {
var start = this.offsetAt(range.start);
var end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
};
FullTextDocument2.prototype.update = function(event, version) {
this._content = event.text;
this._version = version;
this._lineOffsets = void 0;
};
FullTextDocument2.prototype.getLineOffsets = function() {
if (this._lineOffsets === void 0) {
var lineOffsets = [];
var text = this._content;
var isLineStart = true;
for (var i = 0; i < text.length; i++) {
if (isLineStart) {
lineOffsets.push(i);
isLineStart = false;
}
var ch = text.charAt(i);
isLineStart = ch === "\r" || ch === "\n";
if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
i++;
}
}
if (isLineStart && text.length > 0) {
lineOffsets.push(text.length);
}
this._lineOffsets = lineOffsets;
}
return this._lineOffsets;
};
FullTextDocument2.prototype.positionAt = function(offset) {
offset = Math.max(Math.min(offset, this._content.length), 0);
var lineOffsets = this.getLineOffsets();
var low = 0, high = lineOffsets.length;
if (high === 0) {
return Position2.create(0, offset);
}
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
} else {
low = mid + 1;
}
}
var line = low - 1;
return Position2.create(line, offset - lineOffsets[line]);
};
FullTextDocument2.prototype.offsetAt = function(position) {
var lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
} else if (position.line < 0) {
return 0;
}
var lineOffset = lineOffsets[position.line];
var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
};
Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
get: function() {
return this.getLineOffsets().length;
},
enumerable: true,
configurable: true
});
return FullTextDocument2;
}();
var Is2;
(function(Is3) {
var toString = Object.prototype.toString;
function defined(value) {
return typeof value !== "undefined";
}
Is3.defined = defined;
function undefined2(value) {
return typeof value === "undefined";
}
Is3.undefined = undefined2;
function boolean(value) {
return value === true || value === false;
}
Is3.boolean = boolean;
function string(value) {
return toString.call(value) === "[object String]";
}
Is3.string = string;
function number(value) {
return toString.call(value) === "[object Number]";
}
Is3.number = number;
function func(value) {
return toString.call(value) === "[object Function]";
}
Is3.func = func;
function objectLiteral(value) {
return value !== null && typeof value === "object";
}
Is3.objectLiteral = objectLiteral;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
Is3.typedArray = typedArray;
})(Is2 || (Is2 = {}));
});
// node_modules/vscode-languageserver-protocol/lib/utils/is.js
var require_is2 = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
function boolean(value) {
return value === true || value === false;
}
exports2.boolean = boolean;
function string(value) {
return typeof value === "string" || value instanceof String;
}
exports2.string = string;
function number(value) {
return typeof value === "number" || value instanceof Number;
}
exports2.number = number;
function error(value) {
return value instanceof Error;
}
exports2.error = error;
function func(value) {
return typeof value === "function";
}
exports2.func = func;
function array(value) {
return Array.isArray(value);
}
exports2.array = array;
function stringArray(value) {
return array(value) && value.every((elem) => string(elem));
}
exports2.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
exports2.typedArray = typedArray;
function objectLiteral(value) {
return value !== null && typeof value === "object";
}
exports2.objectLiteral = objectLiteral;
});
// node_modules/vscode-languageserver-protocol/lib/messages.js
var require_messages2 = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var ProtocolRequestType0 = class extends vscode_jsonrpc_1.RequestType0 {
constructor(method) {
super(method);
}
};
exports2.ProtocolRequestType0 = ProtocolRequestType0;
var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType {
constructor(method) {
super(method);
}
};
exports2.ProtocolRequestType = ProtocolRequestType;
var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType {
constructor(method) {
super(method);
}
};
exports2.ProtocolNotificationType = ProtocolNotificationType;
var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 {
constructor(method) {
super(method);
}
};
exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
});
// node_modules/vscode-languageserver-protocol/lib/protocol.implementation.js
var require_protocol_implementation = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var ImplementationRequest;
(function(ImplementationRequest2) {
ImplementationRequest2.method = "textDocument/implementation";
ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
ImplementationRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(ImplementationRequest = exports2.ImplementationRequest || (exports2.ImplementationRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.typeDefinition.js
var require_protocol_typeDefinition = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var TypeDefinitionRequest;
(function(TypeDefinitionRequest2) {
TypeDefinitionRequest2.method = "textDocument/typeDefinition";
TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
TypeDefinitionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(TypeDefinitionRequest = exports2.TypeDefinitionRequest || (exports2.TypeDefinitionRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.workspaceFolders.js
var require_protocol_workspaceFolders = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var messages_1 = require_messages2();
var WorkspaceFoldersRequest;
(function(WorkspaceFoldersRequest2) {
WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0("workspace/workspaceFolders");
})(WorkspaceFoldersRequest = exports2.WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = {}));
var DidChangeWorkspaceFoldersNotification;
(function(DidChangeWorkspaceFoldersNotification2) {
DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWorkspaceFolders");
})(DidChangeWorkspaceFoldersNotification = exports2.DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.configuration.js
var require_protocol_configuration = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var messages_1 = require_messages2();
var ConfigurationRequest;
(function(ConfigurationRequest2) {
ConfigurationRequest2.type = new messages_1.ProtocolRequestType("workspace/configuration");
})(ConfigurationRequest = exports2.ConfigurationRequest || (exports2.ConfigurationRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.colorProvider.js
var require_protocol_colorProvider = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var DocumentColorRequest;
(function(DocumentColorRequest2) {
DocumentColorRequest2.method = "textDocument/documentColor";
DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
DocumentColorRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentColorRequest = exports2.DocumentColorRequest || (exports2.DocumentColorRequest = {}));
var ColorPresentationRequest;
(function(ColorPresentationRequest2) {
ColorPresentationRequest2.type = new messages_1.ProtocolRequestType("textDocument/colorPresentation");
})(ColorPresentationRequest = exports2.ColorPresentationRequest || (exports2.ColorPresentationRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.foldingRange.js
var require_protocol_foldingRange = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var FoldingRangeKind;
(function(FoldingRangeKind2) {
FoldingRangeKind2["Comment"] = "comment";
FoldingRangeKind2["Imports"] = "imports";
FoldingRangeKind2["Region"] = "region";
})(FoldingRangeKind = exports2.FoldingRangeKind || (exports2.FoldingRangeKind = {}));
var FoldingRangeRequest;
(function(FoldingRangeRequest2) {
FoldingRangeRequest2.method = "textDocument/foldingRange";
FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
FoldingRangeRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(FoldingRangeRequest = exports2.FoldingRangeRequest || (exports2.FoldingRangeRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.declaration.js
var require_protocol_declaration = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var DeclarationRequest;
(function(DeclarationRequest2) {
DeclarationRequest2.method = "textDocument/declaration";
DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
DeclarationRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DeclarationRequest = exports2.DeclarationRequest || (exports2.DeclarationRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.selectionRange.js
var require_protocol_selectionRange = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var SelectionRangeRequest;
(function(SelectionRangeRequest2) {
SelectionRangeRequest2.method = "textDocument/selectionRange";
SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
SelectionRangeRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(SelectionRangeRequest = exports2.SelectionRangeRequest || (exports2.SelectionRangeRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.progress.js
var require_protocol_progress = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var WorkDoneProgress;
(function(WorkDoneProgress2) {
WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
})(WorkDoneProgress = exports2.WorkDoneProgress || (exports2.WorkDoneProgress = {}));
var WorkDoneProgressCreateRequest;
(function(WorkDoneProgressCreateRequest2) {
WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType("window/workDoneProgress/create");
})(WorkDoneProgressCreateRequest = exports2.WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = {}));
var WorkDoneProgressCancelNotification;
(function(WorkDoneProgressCancelNotification2) {
WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType("window/workDoneProgress/cancel");
})(WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.js
var require_protocol = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var Is2 = require_is2();
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var protocol_implementation_1 = require_protocol_implementation();
exports2.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
var protocol_typeDefinition_1 = require_protocol_typeDefinition();
exports2.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
var protocol_workspaceFolders_1 = require_protocol_workspaceFolders();
exports2.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
exports2.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
var protocol_configuration_1 = require_protocol_configuration();
exports2.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
var protocol_colorProvider_1 = require_protocol_colorProvider();
exports2.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
exports2.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
var protocol_foldingRange_1 = require_protocol_foldingRange();
exports2.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
var protocol_declaration_1 = require_protocol_declaration();
exports2.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
var protocol_selectionRange_1 = require_protocol_selectionRange();
exports2.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
var protocol_progress_1 = require_protocol_progress();
exports2.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
exports2.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
exports2.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
var DocumentFilter2;
(function(DocumentFilter3) {
function is(value) {
const candidate = value;
return Is2.string(candidate.language) || Is2.string(candidate.scheme) || Is2.string(candidate.pattern);
}
DocumentFilter3.is = is;
})(DocumentFilter2 = exports2.DocumentFilter || (exports2.DocumentFilter = {}));
var DocumentSelector;
(function(DocumentSelector2) {
function is(value) {
if (!Array.isArray(value)) {
return false;
}
for (let elem of value) {
if (!Is2.string(elem) && !DocumentFilter2.is(elem)) {
return false;
}
}
return true;
}
DocumentSelector2.is = is;
})(DocumentSelector = exports2.DocumentSelector || (exports2.DocumentSelector = {}));
var RegistrationRequest;
(function(RegistrationRequest2) {
RegistrationRequest2.type = new messages_1.ProtocolRequestType("client/registerCapability");
})(RegistrationRequest = exports2.RegistrationRequest || (exports2.RegistrationRequest = {}));
var UnregistrationRequest;
(function(UnregistrationRequest2) {
UnregistrationRequest2.type = new messages_1.ProtocolRequestType("client/unregisterCapability");
})(UnregistrationRequest = exports2.UnregistrationRequest || (exports2.UnregistrationRequest = {}));
var ResourceOperationKind;
(function(ResourceOperationKind2) {
ResourceOperationKind2.Create = "create";
ResourceOperationKind2.Rename = "rename";
ResourceOperationKind2.Delete = "delete";
})(ResourceOperationKind = exports2.ResourceOperationKind || (exports2.ResourceOperationKind = {}));
var FailureHandlingKind;
(function(FailureHandlingKind2) {
FailureHandlingKind2.Abort = "abort";
FailureHandlingKind2.Transactional = "transactional";
FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
FailureHandlingKind2.Undo = "undo";
})(FailureHandlingKind = exports2.FailureHandlingKind || (exports2.FailureHandlingKind = {}));
var StaticRegistrationOptions;
(function(StaticRegistrationOptions2) {
function hasId(value) {
const candidate = value;
return candidate && Is2.string(candidate.id) && candidate.id.length > 0;
}
StaticRegistrationOptions2.hasId = hasId;
})(StaticRegistrationOptions = exports2.StaticRegistrationOptions || (exports2.StaticRegistrationOptions = {}));
var TextDocumentRegistrationOptions;
(function(TextDocumentRegistrationOptions2) {
function is(value) {
const candidate = value;
return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
}
TextDocumentRegistrationOptions2.is = is;
})(TextDocumentRegistrationOptions = exports2.TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = {}));
var WorkDoneProgressOptions;
(function(WorkDoneProgressOptions2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is2.boolean(candidate.workDoneProgress));
}
WorkDoneProgressOptions2.is = is;
function hasWorkDoneProgress(value) {
const candidate = value;
return candidate && Is2.boolean(candidate.workDoneProgress);
}
WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
})(WorkDoneProgressOptions = exports2.WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = {}));
var InitializeRequest;
(function(InitializeRequest2) {
InitializeRequest2.type = new messages_1.ProtocolRequestType("initialize");
})(InitializeRequest = exports2.InitializeRequest || (exports2.InitializeRequest = {}));
var InitializeError;
(function(InitializeError2) {
InitializeError2.unknownProtocolVersion = 1;
})(InitializeError = exports2.InitializeError || (exports2.InitializeError = {}));
var InitializedNotification;
(function(InitializedNotification2) {
InitializedNotification2.type = new messages_1.ProtocolNotificationType("initialized");
})(InitializedNotification = exports2.InitializedNotification || (exports2.InitializedNotification = {}));
var ShutdownRequest;
(function(ShutdownRequest2) {
ShutdownRequest2.type = new messages_1.ProtocolRequestType0("shutdown");
})(ShutdownRequest = exports2.ShutdownRequest || (exports2.ShutdownRequest = {}));
var ExitNotification;
(function(ExitNotification2) {
ExitNotification2.type = new messages_1.ProtocolNotificationType0("exit");
})(ExitNotification = exports2.ExitNotification || (exports2.ExitNotification = {}));
var DidChangeConfigurationNotification2;
(function(DidChangeConfigurationNotification3) {
DidChangeConfigurationNotification3.type = new messages_1.ProtocolNotificationType("workspace/didChangeConfiguration");
})(DidChangeConfigurationNotification2 = exports2.DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = {}));
var MessageType;
(function(MessageType2) {
MessageType2.Error = 1;
MessageType2.Warning = 2;
MessageType2.Info = 3;
MessageType2.Log = 4;
})(MessageType = exports2.MessageType || (exports2.MessageType = {}));
var ShowMessageNotification;
(function(ShowMessageNotification2) {
ShowMessageNotification2.type = new messages_1.ProtocolNotificationType("window/showMessage");
})(ShowMessageNotification = exports2.ShowMessageNotification || (exports2.ShowMessageNotification = {}));
var ShowMessageRequest;
(function(ShowMessageRequest2) {
ShowMessageRequest2.type = new messages_1.ProtocolRequestType("window/showMessageRequest");
})(ShowMessageRequest = exports2.ShowMessageRequest || (exports2.ShowMessageRequest = {}));
var LogMessageNotification;
(function(LogMessageNotification2) {
LogMessageNotification2.type = new messages_1.ProtocolNotificationType("window/logMessage");
})(LogMessageNotification = exports2.LogMessageNotification || (exports2.LogMessageNotification = {}));
var TelemetryEventNotification;
(function(TelemetryEventNotification2) {
TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType("telemetry/event");
})(TelemetryEventNotification = exports2.TelemetryEventNotification || (exports2.TelemetryEventNotification = {}));
var TextDocumentSyncKind;
(function(TextDocumentSyncKind2) {
TextDocumentSyncKind2.None = 0;
TextDocumentSyncKind2.Full = 1;
TextDocumentSyncKind2.Incremental = 2;
})(TextDocumentSyncKind = exports2.TextDocumentSyncKind || (exports2.TextDocumentSyncKind = {}));
var DidOpenTextDocumentNotification2;
(function(DidOpenTextDocumentNotification3) {
DidOpenTextDocumentNotification3.method = "textDocument/didOpen";
DidOpenTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification3.method);
})(DidOpenTextDocumentNotification2 = exports2.DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = {}));
var DidChangeTextDocumentNotification;
(function(DidChangeTextDocumentNotification2) {
DidChangeTextDocumentNotification2.method = "textDocument/didChange";
DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
})(DidChangeTextDocumentNotification = exports2.DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = {}));
var DidCloseTextDocumentNotification2;
(function(DidCloseTextDocumentNotification3) {
DidCloseTextDocumentNotification3.method = "textDocument/didClose";
DidCloseTextDocumentNotification3.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification3.method);
})(DidCloseTextDocumentNotification2 = exports2.DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = {}));
var DidSaveTextDocumentNotification;
(function(DidSaveTextDocumentNotification2) {
DidSaveTextDocumentNotification2.method = "textDocument/didSave";
DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
})(DidSaveTextDocumentNotification = exports2.DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = {}));
var TextDocumentSaveReason;
(function(TextDocumentSaveReason2) {
TextDocumentSaveReason2.Manual = 1;
TextDocumentSaveReason2.AfterDelay = 2;
TextDocumentSaveReason2.FocusOut = 3;
})(TextDocumentSaveReason = exports2.TextDocumentSaveReason || (exports2.TextDocumentSaveReason = {}));
var WillSaveTextDocumentNotification;
(function(WillSaveTextDocumentNotification2) {
WillSaveTextDocumentNotification2.method = "textDocument/willSave";
WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
})(WillSaveTextDocumentNotification = exports2.WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = {}));
var WillSaveTextDocumentWaitUntilRequest;
(function(WillSaveTextDocumentWaitUntilRequest2) {
WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
})(WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = {}));
var DidChangeWatchedFilesNotification;
(function(DidChangeWatchedFilesNotification2) {
DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType("workspace/didChangeWatchedFiles");
})(DidChangeWatchedFilesNotification = exports2.DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = {}));
var FileChangeType;
(function(FileChangeType2) {
FileChangeType2.Created = 1;
FileChangeType2.Changed = 2;
FileChangeType2.Deleted = 3;
})(FileChangeType = exports2.FileChangeType || (exports2.FileChangeType = {}));
var WatchKind;
(function(WatchKind2) {
WatchKind2.Create = 1;
WatchKind2.Change = 2;
WatchKind2.Delete = 4;
})(WatchKind = exports2.WatchKind || (exports2.WatchKind = {}));
var PublishDiagnosticsNotification;
(function(PublishDiagnosticsNotification2) {
PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType("textDocument/publishDiagnostics");
})(PublishDiagnosticsNotification = exports2.PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind2) {
CompletionTriggerKind2.Invoked = 1;
CompletionTriggerKind2.TriggerCharacter = 2;
CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
})(CompletionTriggerKind = exports2.CompletionTriggerKind || (exports2.CompletionTriggerKind = {}));
var CompletionRequest;
(function(CompletionRequest2) {
CompletionRequest2.method = "textDocument/completion";
CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
CompletionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(CompletionRequest = exports2.CompletionRequest || (exports2.CompletionRequest = {}));
var CompletionResolveRequest;
(function(CompletionResolveRequest2) {
CompletionResolveRequest2.method = "completionItem/resolve";
CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
})(CompletionResolveRequest = exports2.CompletionResolveRequest || (exports2.CompletionResolveRequest = {}));
var HoverRequest;
(function(HoverRequest2) {
HoverRequest2.method = "textDocument/hover";
HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
})(HoverRequest = exports2.HoverRequest || (exports2.HoverRequest = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind2) {
SignatureHelpTriggerKind2.Invoked = 1;
SignatureHelpTriggerKind2.TriggerCharacter = 2;
SignatureHelpTriggerKind2.ContentChange = 3;
})(SignatureHelpTriggerKind = exports2.SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = {}));
var SignatureHelpRequest;
(function(SignatureHelpRequest2) {
SignatureHelpRequest2.method = "textDocument/signatureHelp";
SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
})(SignatureHelpRequest = exports2.SignatureHelpRequest || (exports2.SignatureHelpRequest = {}));
var DefinitionRequest;
(function(DefinitionRequest2) {
DefinitionRequest2.method = "textDocument/definition";
DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
DefinitionRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DefinitionRequest = exports2.DefinitionRequest || (exports2.DefinitionRequest = {}));
var ReferencesRequest;
(function(ReferencesRequest2) {
ReferencesRequest2.method = "textDocument/references";
ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
ReferencesRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(ReferencesRequest = exports2.ReferencesRequest || (exports2.ReferencesRequest = {}));
var DocumentHighlightRequest;
(function(DocumentHighlightRequest2) {
DocumentHighlightRequest2.method = "textDocument/documentHighlight";
DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
DocumentHighlightRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentHighlightRequest = exports2.DocumentHighlightRequest || (exports2.DocumentHighlightRequest = {}));
var DocumentSymbolRequest;
(function(DocumentSymbolRequest2) {
DocumentSymbolRequest2.method = "textDocument/documentSymbol";
DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
DocumentSymbolRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentSymbolRequest = exports2.DocumentSymbolRequest || (exports2.DocumentSymbolRequest = {}));
var CodeActionRequest2;
(function(CodeActionRequest3) {
CodeActionRequest3.method = "textDocument/codeAction";
CodeActionRequest3.type = new messages_1.ProtocolRequestType(CodeActionRequest3.method);
CodeActionRequest3.resultType = new vscode_jsonrpc_1.ProgressType();
})(CodeActionRequest2 = exports2.CodeActionRequest || (exports2.CodeActionRequest = {}));
var WorkspaceSymbolRequest;
(function(WorkspaceSymbolRequest2) {
WorkspaceSymbolRequest2.method = "workspace/symbol";
WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
WorkspaceSymbolRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(WorkspaceSymbolRequest = exports2.WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = {}));
var CodeLensRequest;
(function(CodeLensRequest2) {
CodeLensRequest2.type = new messages_1.ProtocolRequestType("textDocument/codeLens");
CodeLensRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(CodeLensRequest = exports2.CodeLensRequest || (exports2.CodeLensRequest = {}));
var CodeLensResolveRequest;
(function(CodeLensResolveRequest2) {
CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType("codeLens/resolve");
})(CodeLensResolveRequest = exports2.CodeLensResolveRequest || (exports2.CodeLensResolveRequest = {}));
var DocumentLinkRequest;
(function(DocumentLinkRequest2) {
DocumentLinkRequest2.method = "textDocument/documentLink";
DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
DocumentLinkRequest2.resultType = new vscode_jsonrpc_1.ProgressType();
})(DocumentLinkRequest = exports2.DocumentLinkRequest || (exports2.DocumentLinkRequest = {}));
var DocumentLinkResolveRequest;
(function(DocumentLinkResolveRequest2) {
DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType("documentLink/resolve");
})(DocumentLinkResolveRequest = exports2.DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = {}));
var DocumentFormattingRequest;
(function(DocumentFormattingRequest2) {
DocumentFormattingRequest2.method = "textDocument/formatting";
DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
})(DocumentFormattingRequest = exports2.DocumentFormattingRequest || (exports2.DocumentFormattingRequest = {}));
var DocumentRangeFormattingRequest;
(function(DocumentRangeFormattingRequest2) {
DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
})(DocumentRangeFormattingRequest = exports2.DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = {}));
var DocumentOnTypeFormattingRequest;
(function(DocumentOnTypeFormattingRequest2) {
DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
})(DocumentOnTypeFormattingRequest = exports2.DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = {}));
var RenameRequest;
(function(RenameRequest2) {
RenameRequest2.method = "textDocument/rename";
RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
})(RenameRequest = exports2.RenameRequest || (exports2.RenameRequest = {}));
var PrepareRenameRequest;
(function(PrepareRenameRequest2) {
PrepareRenameRequest2.method = "textDocument/prepareRename";
PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
})(PrepareRenameRequest = exports2.PrepareRenameRequest || (exports2.PrepareRenameRequest = {}));
var ExecuteCommandRequest2;
(function(ExecuteCommandRequest3) {
ExecuteCommandRequest3.type = new messages_1.ProtocolRequestType("workspace/executeCommand");
})(ExecuteCommandRequest2 = exports2.ExecuteCommandRequest || (exports2.ExecuteCommandRequest = {}));
var ApplyWorkspaceEditRequest;
(function(ApplyWorkspaceEditRequest2) {
ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
})(ApplyWorkspaceEditRequest = exports2.ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.callHierarchy.proposed.js
var require_protocol_callHierarchy_proposed = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var messages_1 = require_messages2();
var CallHierarchyPrepareRequest;
(function(CallHierarchyPrepareRequest2) {
CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
})(CallHierarchyPrepareRequest = exports2.CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = {}));
var CallHierarchyIncomingCallsRequest;
(function(CallHierarchyIncomingCallsRequest2) {
CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
})(CallHierarchyIncomingCallsRequest = exports2.CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = {}));
var CallHierarchyOutgoingCallsRequest;
(function(CallHierarchyOutgoingCallsRequest2) {
CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
})(CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/protocol.sematicTokens.proposed.js
var require_protocol_sematicTokens_proposed = __commonJS((exports2) => {
"use strict";
Object.defineProperty(exports2, "__esModule", {value: true});
var messages_1 = require_messages2();
var SemanticTokenTypes;
(function(SemanticTokenTypes2) {
SemanticTokenTypes2["comment"] = "comment";
SemanticTokenTypes2["keyword"] = "keyword";
SemanticTokenTypes2["string"] = "string";
SemanticTokenTypes2["number"] = "number";
SemanticTokenTypes2["regexp"] = "regexp";
SemanticTokenTypes2["operator"] = "operator";
SemanticTokenTypes2["namespace"] = "namespace";
SemanticTokenTypes2["type"] = "type";
SemanticTokenTypes2["struct"] = "struct";
SemanticTokenTypes2["class"] = "class";
SemanticTokenTypes2["interface"] = "interface";
SemanticTokenTypes2["enum"] = "enum";
SemanticTokenTypes2["typeParameter"] = "typeParameter";
SemanticTokenTypes2["function"] = "function";
SemanticTokenTypes2["member"] = "member";
SemanticTokenTypes2["property"] = "property";
SemanticTokenTypes2["macro"] = "macro";
SemanticTokenTypes2["variable"] = "variable";
SemanticTokenTypes2["parameter"] = "parameter";
SemanticTokenTypes2["label"] = "label";
})(SemanticTokenTypes = exports2.SemanticTokenTypes || (exports2.SemanticTokenTypes = {}));
var SemanticTokenModifiers;
(function(SemanticTokenModifiers2) {
SemanticTokenModifiers2["documentation"] = "documentation";
SemanticTokenModifiers2["declaration"] = "declaration";
SemanticTokenModifiers2["definition"] = "definition";
SemanticTokenModifiers2["reference"] = "reference";
SemanticTokenModifiers2["static"] = "static";
SemanticTokenModifiers2["abstract"] = "abstract";
SemanticTokenModifiers2["deprecated"] = "deprecated";
SemanticTokenModifiers2["async"] = "async";
SemanticTokenModifiers2["volatile"] = "volatile";
SemanticTokenModifiers2["readonly"] = "readonly";
})(SemanticTokenModifiers = exports2.SemanticTokenModifiers || (exports2.SemanticTokenModifiers = {}));
var SemanticTokens;
(function(SemanticTokens2) {
function is(value) {
const candidate = value;
return candidate !== void 0 && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
}
SemanticTokens2.is = is;
})(SemanticTokens = exports2.SemanticTokens || (exports2.SemanticTokens = {}));
var SemanticTokensRequest;
(function(SemanticTokensRequest2) {
SemanticTokensRequest2.method = "textDocument/semanticTokens";
SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
})(SemanticTokensRequest = exports2.SemanticTokensRequest || (exports2.SemanticTokensRequest = {}));
var SemanticTokensEditsRequest;
(function(SemanticTokensEditsRequest2) {
SemanticTokensEditsRequest2.method = "textDocument/semanticTokens/edits";
SemanticTokensEditsRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest2.method);
})(SemanticTokensEditsRequest = exports2.SemanticTokensEditsRequest || (exports2.SemanticTokensEditsRequest = {}));
var SemanticTokensRangeRequest;
(function(SemanticTokensRangeRequest2) {
SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
})(SemanticTokensRangeRequest = exports2.SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = {}));
});
// node_modules/vscode-languageserver-protocol/lib/main.js
var require_main3 = __commonJS((exports2) => {
"use strict";
function __export2(m) {
for (var p in m)
if (!exports2.hasOwnProperty(p))
exports2[p] = m[p];
}
Object.defineProperty(exports2, "__esModule", {value: true});
var vscode_jsonrpc_1 = require_main();
exports2.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
exports2.ResponseError = vscode_jsonrpc_1.ResponseError;
exports2.CancellationToken = vscode_jsonrpc_1.CancellationToken;
exports2.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
exports2.Disposable = vscode_jsonrpc_1.Disposable;
exports2.Event = vscode_jsonrpc_1.Event;
exports2.Emitter = vscode_jsonrpc_1.Emitter;
exports2.Trace = vscode_jsonrpc_1.Trace;
exports2.TraceFormat = vscode_jsonrpc_1.TraceFormat;
exports2.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
exports2.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
exports2.RequestType = vscode_jsonrpc_1.RequestType;
exports2.RequestType0 = vscode_jsonrpc_1.RequestType0;
exports2.NotificationType = vscode_jsonrpc_1.NotificationType;
exports2.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
exports2.MessageReader = vscode_jsonrpc_1.MessageReader;
exports2.MessageWriter = vscode_jsonrpc_1.MessageWriter;
exports2.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
exports2.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
exports2.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
exports2.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
exports2.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
exports2.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
exports2.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
exports2.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
exports2.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
exports2.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
exports2.ProgressType = vscode_jsonrpc_1.ProgressType;
__export2(require_main2());
__export2(require_protocol());
var callHierarchy = require_protocol_callHierarchy_proposed();
var st = require_protocol_sematicTokens_proposed();
var Proposed;
(function(Proposed2) {
let CallHierarchyPrepareRequest;
(function(CallHierarchyPrepareRequest2) {
CallHierarchyPrepareRequest2.method = callHierarchy.CallHierarchyPrepareRequest.method;
CallHierarchyPrepareRequest2.type = callHierarchy.CallHierarchyPrepareRequest.type;
})(CallHierarchyPrepareRequest = Proposed2.CallHierarchyPrepareRequest || (Proposed2.CallHierarchyPrepareRequest = {}));
let CallHierarchyIncomingCallsRequest;
(function(CallHierarchyIncomingCallsRequest2) {
CallHierarchyIncomingCallsRequest2.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
CallHierarchyIncomingCallsRequest2.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
})(CallHierarchyIncomingCallsRequest = Proposed2.CallHierarchyIncomingCallsRequest || (Proposed2.CallHierarchyIncomingCallsRequest = {}));
let CallHierarchyOutgoingCallsRequest;
(function(CallHierarchyOutgoingCallsRequest2) {
CallHierarchyOutgoingCallsRequest2.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
CallHierarchyOutgoingCallsRequest2.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
})(CallHierarchyOutgoingCallsRequest = Proposed2.CallHierarchyOutgoingCallsRequest || (Proposed2.CallHierarchyOutgoingCallsRequest = {}));
Proposed2.SemanticTokenTypes = st.SemanticTokenTypes;
Proposed2.SemanticTokenModifiers = st.SemanticTokenModifiers;
Proposed2.SemanticTokens = st.SemanticTokens;
let SemanticTokensRequest;
(function(SemanticTokensRequest2) {
SemanticTokensRequest2.method = st.SemanticTokensRequest.method;
SemanticTokensRequest2.type = st.SemanticTokensRequest.type;
})(SemanticTokensRequest = Proposed2.SemanticTokensRequest || (Proposed2.SemanticTokensRequest = {}));
let SemanticTokensEditsRequest;
(function(SemanticTokensEditsRequest2) {
SemanticTokensEditsRequest2.method = st.SemanticTokensEditsRequest.method;
SemanticTokensEditsRequest2.type = st.SemanticTokensEditsRequest.type;
})(SemanticTokensEditsRequest = Proposed2.SemanticTokensEditsRequest || (Proposed2.SemanticTokensEditsRequest = {}));
let SemanticTokensRangeRequest;
(function(SemanticTokensRangeRequest2) {
SemanticTokensRangeRequest2.method = st.SemanticTokensRangeRequest.method;
SemanticTokensRangeRequest2.type = st.SemanticTokensRangeRequest.type;
})(SemanticTokensRangeRequest = Proposed2.SemanticTokensRangeRequest || (Proposed2.SemanticTokensRangeRequest = {}));
})(Proposed = exports2.Proposed || (exports2.Proposed = {}));
function createProtocolConnection(reader, writer, logger, strategy) {
return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
}
exports2.createProtocolConnection = createProtocolConnection;
});
// entry-ns:index.ts
__export(exports, {
activate: () => activate,
deactivate: () => deactivate
});
// src/index.ts
var import_path2 = __toModule(require("path"));
var import_fs2 = __toModule(require("fs"));
var import_coc3 = __toModule(require("coc.nvim"));
var import_vscode_languageserver_protocol = __toModule(require_main3());
// src/utils.ts
var import_fs = __toModule(require("fs"));
var import_path = __toModule(require("path"));
"use strict";
function exists(file) {
return new Promise((resolve, _reject) => {
import_fs.default.exists(file, (value) => {
resolve(value);
});
});
}
async function findEslint(rootPath) {
const platform = process.platform;
if (platform === "win32" && await exists(import_path.default.join(rootPath, "node_modules", ".bin", "eslint.cmd"))) {
return import_path.default.join(".", "node_modules", ".bin", "eslint.cmd");
} else if ((platform === "linux" || platform === "darwin") && await exists(import_path.default.join(rootPath, "node_modules", ".bin", "eslint"))) {
return import_path.default.join(".", "node_modules", ".bin", "eslint");
} else {
return "eslint";
}
}
var NodeType;
(function(NodeType2) {
NodeType2["text"] = "text";
NodeType2["separator"] = "separator";
NodeType2["brace"] = "brace";
NodeType2["bracket"] = "bracket";
NodeType2["questionMark"] = "questionMark";
NodeType2["star"] = "star";
NodeType2["globStar"] = "globStar";
})(NodeType || (NodeType = {}));
function escapeRegExpCharacters(value) {
return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
var PatternParser = class {
constructor(value, mode = "pattern") {
this.value = value;
this.index = 0;
this.mode = mode;
this.stopChar = mode === "pattern" ? void 0 : "}";
}
makeTextNode(start) {
return {type: NodeType.text, value: escapeRegExpCharacters(this.value.substring(start, this.index))};
}
next() {
let start = this.index;
let ch;
while ((ch = this.value[this.index]) !== this.stopChar) {
switch (ch) {
case "/":
if (start < this.index) {
return this.makeTextNode(start);
} else {
this.index++;
return {type: NodeType.separator};
}
case "?":
this.index++;
return {type: NodeType.questionMark};
case "*":
if (this.value[this.index + 1] === "*") {
this.index += 2;
return {type: NodeType.globStar};
} else {
this.index++;
return {type: NodeType.star};
}
case "{":
if (start < this.index) {
return this.makeTextNode(start);
} else {
const bracketParser = new PatternParser(this.value.substring(this.index + 1), "brace");
const alternatives = [];
let node;
while ((node = bracketParser.next()) !== void 0) {
if (node.type === NodeType.globStar || node.type === NodeType.separator) {
throw new Error(`Invalid glob pattern ${this.index}. Stopped at ${this.index}`);
}
alternatives.push(node);
}
this.index = this.index + bracketParser.index + 2;
return {type: NodeType.brace, alternatives};
}
case ",":
if (this.mode === "brace") {
if (start < this.index) {
let result = this.makeTextNode(start);
this.index++;
return result;
}
}
this.index++;
break;
case "[":
const buffer = [];
this.index++;
const firstIndex = this.index;
while (this.index < this.value.length) {
const ch2 = this.value[this.index];
if (this.index === firstIndex) {
switch (ch2) {
case "]":
buffer.push(ch2);
break;
case "!":
case "^":
buffer.push("^");
break;
default:
buffer.push(escapeRegExpCharacters(ch2));
break;
}
} else if (ch2 === "-") {
buffer.push(ch2);
} else if (ch2 === "]") {
this.index++;
return {type: NodeType.bracket, value: buffer.join("")};
} else {
buffer.push(escapeRegExpCharacters(ch2));
}
this.index++;
}
throw new Error(`Invalid glob pattern ${this.index}. Stopped at ${this.index}`);
default:
this.index++;
}
}
return start === this.index ? void 0 : this.makeTextNode(start);
}
};
function convert2RegExp(pattern) {
const separator = process.platform === "win32" ? "\\\\" : "\\/";
const fileChar = `[^${separator}]`;
function convertNode(node) {
switch (node.type) {
case NodeType.separator:
return separator;
case NodeType.text:
return node.value;
case NodeType.questionMark:
return fileChar;
case NodeType.star:
return `${fileChar}*?`;
case NodeType.globStar:
return `(?:${fileChar}|(?:(?:${fileChar}${separator})+${fileChar}))*?`;
case NodeType.bracket:
return `[${node.value}]`;
case NodeType.brace: {
let buffer = [];
for (const child of node.alternatives) {
buffer.push(convertNode(child));
}
return `(?:${buffer.join("|")})`;
}
}
}
try {
const buffer = ["^"];
let parser = new PatternParser(pattern);
let node;
while ((node = parser.next()) !== void 0) {
buffer.push(convertNode(node));
}
return buffer.length > 0 ? new RegExp(buffer.join("")) : void 0;
} catch (err) {
console.error(err);
return void 0;
}
}
function toOSPath(path3) {
if (process.platform === "win32") {
path3 = path3.replace(/^\/(\w)\//, "$1:\\");
return path3.replace(/\//g, "\\");
} else {
return path3;
}
}
function toPosixPath(path3) {
if (process.platform !== "win32") {
return path3;
}
return path3.replace(/\\/g, "/");
}
var Semaphore = class {
constructor(capacity = 1) {
if (capacity <= 0) {
throw new Error("Capacity must be greater than 0");
}
this._capacity = capacity;
this._active = 0;
this._waiting = [];
}
lock(thunk) {
return new Promise((resolve, reject) => {
this._waiting.push({thunk, resolve, reject});
this.runNext();
});
}
get active() {
return this._active;
}
runNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
setImmediate(() => this.doRunNext());
}
doRunNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
const next = this._waiting.shift();
this._active++;
if (this._active > this._capacity) {
throw new Error(`To many thunks active`);
}
try {
const result = next.thunk();
if (result instanceof Promise) {
result.then((value) => {
this._active--;
next.resolve(value);
this.runNext();
}, (err) => {
this._active--;
next.reject(err);
this.runNext();
});
} else {
this._active--;
next.resolve(result);
this.runNext();
}
} catch (err) {
this._active--;
next.reject(err);
this.runNext();
}
}
};
// src/task.ts
var import_coc = __toModule(require("coc.nvim"));
var import_coc2 = __toModule(require("coc.nvim"));
var errorRegex = /^(.+):(\d+):(\d+):\s*(.+?)\s\[(\w+)\/(.*)\]/;
var EslintTask2 = class {
constructor() {
this.disposables = [];
this.statusItem = import_coc.window.createStatusBarItem(1, {progress: true});
let task = this.task = import_coc.workspace.createTask("ESLINT");
this.disposables.push(import_coc.commands.registerCommand(EslintTask2.id, async () => {
let opts = await this.getOptions();
let started = await this.start(opts);
if (started) {
this.statusItem.text = "compiling";
this.statusItem.isProgress = true;
this.statusItem.show();
import_coc.workspace.nvim.call("setqflist", [[]], true);
}
}));
task.onExit((code) => {
if (code != 0) {
import_coc.window.showMessage(`Eslint found issues`, "warning");
}
this.onStop();
});
task.onStdout((lines) => {
for (let line of lines) {
this.onLine(line);
}
});
task.onStderr((lines) => {
import_coc.window.showMessage(`TSC error: ` + lines.join("\n"), "error");
});
this.disposables.push(import_coc2.Disposable.create(() => {
task.dispose();
}));
}
async start(options) {
return await this.task.start(options);
}
onStop() {
this.statusItem.hide();
}
onLine(line) {
let ms = line.match(errorRegex);
if (!ms)
return;
let fullpath = ms[1];
let uri = import_coc.Uri.file(fullpath).toString();
let doc = import_coc.workspace.getDocument(uri);
let bufnr = doc ? doc.bufnr : null;
let item = {
filename: fullpath,
lnum: Number(ms[2]),
col: Number(ms[3]),
text: `${ms[4]} [${ms[6]}]`,
type: /error/i.test(ms[5]) ? "E" : "W"
};
if (bufnr)
item.bufnr = bufnr;
import_coc.workspace.nvim.call("setqflist", [[item], "a"]);
}
async getOptions() {
let root = import_coc.Uri.parse(import_coc.workspace.workspaceFolder.uri).fsPath;
let cmd = await findEslint(root);
let config = import_coc.workspace.getConfiguration("eslint");
let args = config.get("lintTask.options", ["."]);
return {
cmd,
args: args.concat(["-f", "unix", "--no-color"]),
cwd: root
};
}
dispose() {
import_coc.disposeAll(this.disposables);
}
};
var EslintTask = EslintTask2;
EslintTask.id = "eslint.lintProject";
EslintTask.startTexts = ["Starting compilation in watch mode", "Starting incremental compilation"];
var task_default = EslintTask;
// src/index.ts
"use strict";
var ConfigurationTarget;
(function(ConfigurationTarget2) {
ConfigurationTarget2[ConfigurationTarget2["Global"] = 0] = "Global";
ConfigurationTarget2[ConfigurationTarget2["User"] = 1] = "User";
ConfigurationTarget2[ConfigurationTarget2["Workspace"] = 2] = "Workspace";
})(ConfigurationTarget || (ConfigurationTarget = {}));
var Is;
(function(Is2) {
const toString = Object.prototype.toString;
function boolean(value) {
return value === true || value === false;
}
Is2.boolean = boolean;
function string(value) {
return toString.call(value) === "[object String]";
}
Is2.string = string;
function objectLiteral(value) {
return value !== null && value !== void 0 && !Array.isArray(value) && typeof value === "object";
}
Is2.objectLiteral = objectLiteral;
})(Is || (Is = {}));
var ValidateItem;
(function(ValidateItem2) {
function is(item) {
const candidate = item;
return candidate && Is.string(candidate.language) && (Is.boolean(candidate.autoFix) || candidate.autoFix === void 0);
}
ValidateItem2.is = is;
})(ValidateItem || (ValidateItem = {}));
var LegacyDirectoryItem;
(function(LegacyDirectoryItem2) {
function is(item) {
const candidate = item;
return candidate && Is.string(candidate.directory) && Is.boolean(candidate.changeProcessCWD);
}
LegacyDirectoryItem2.is = is;
})(LegacyDirectoryItem || (LegacyDirectoryItem = {}));
var ModeEnum;
(function(ModeEnum2) {
ModeEnum2["auto"] = "auto";
ModeEnum2["location"] = "location";
})(ModeEnum || (ModeEnum = {}));
(function(ModeEnum2) {
function is(value) {
return value === ModeEnum2.auto || value === ModeEnum2.location;
}
ModeEnum2.is = is;
})(ModeEnum || (ModeEnum = {}));
var ModeItem;
(function(ModeItem2) {
function is(item) {
const candidate = item;
return candidate && ModeEnum.is(candidate.mode);
}
ModeItem2.is = is;
})(ModeItem || (ModeItem = {}));
var DirectoryItem;
(function(DirectoryItem2) {
function is(item) {
const candidate = item;
return candidate && Is.string(candidate.directory) && (Is.boolean(candidate["!cwd"]) || candidate["!cwd"] === void 0);
}
DirectoryItem2.is = is;
})(DirectoryItem || (DirectoryItem = {}));
var PatternItem;
(function(PatternItem2) {
function is(item) {
const candidate = item;
return candidate && Is.string(candidate.pattern) && (Is.boolean(candidate["!cwd"]) || candidate["!cwd"] === void 0);
}
PatternItem2.is = is;
})(PatternItem || (PatternItem = {}));
var CodeActionsOnSaveMode;
(function(CodeActionsOnSaveMode2) {
CodeActionsOnSaveMode2["all"] = "all";
CodeActionsOnSaveMode2["problems"] = "problems";
})(CodeActionsOnSaveMode || (CodeActionsOnSaveMode = {}));
(function(CodeActionsOnSaveMode2) {
function from(value) {
if (value === void 0 || value === null) {
return CodeActionsOnSaveMode2.all;
}
switch (value.toLowerCase()) {
case CodeActionsOnSaveMode2.problems:
return CodeActionsOnSaveMode2.problems;
default:
return CodeActionsOnSaveMode2.all;
}
}
CodeActionsOnSaveMode2.from = from;
})(CodeActionsOnSaveMode || (CodeActionsOnSaveMode = {}));
var Validate;
(function(Validate2) {
Validate2["on"] = "on";
Validate2["off"] = "off";
Validate2["probe"] = "probe";
})(Validate || (Validate = {}));
var ESLintSeverity;
(function(ESLintSeverity2) {
ESLintSeverity2["off"] = "off";
ESLintSeverity2["warn"] = "warn";
ESLintSeverity2["error"] = "error";
})(ESLintSeverity || (ESLintSeverity = {}));
(function(ESLintSeverity2) {
function from(value) {
if (value === void 0 || value === null) {
return ESLintSeverity2.off;
}
switch (value.toLowerCase()) {
case ESLintSeverity2.off:
return ESLintSeverity2.off;
case ESLintSeverity2.warn:
return ESLintSeverity2.warn;
case ESLintSeverity2.error:
return ESLintSeverity2.error;
default:
return ESLintSeverity2.off;
}
}
ESLintSeverity2.from = from;
})(ESLintSeverity || (ESLintSeverity = {}));
var ConfirmationSelection;
(function(ConfirmationSelection2) {
ConfirmationSelection2[ConfirmationSelection2["deny"] = 1] = "deny";
ConfirmationSelection2[ConfirmationSelection2["disable"] = 2] = "disable";
ConfirmationSelection2[ConfirmationSelection2["allow"] = 3] = "allow";
ConfirmationSelection2[ConfirmationSelection2["alwaysAllow"] = 4] = "alwaysAllow";
})(ConfirmationSelection || (ConfirmationSelection = {}));
var Status;
(function(Status2) {
Status2[Status2["ok"] = 1] = "ok";
Status2[Status2["warn"] = 2] = "warn";
Status2[Status2["error"] = 3] = "error";
Status2[Status2["confirmationPending"] = 4] = "confirmationPending";
Status2[Status2["executionDisabled"] = 5] = "executionDisabled";
Status2[Status2["executionDenied"] = 6] = "executionDenied";
})(Status || (Status = {}));
var StatusNotification;
(function(StatusNotification2) {
StatusNotification2.type = new import_coc3.NotificationType("eslint/status");
})(StatusNotification || (StatusNotification = {}));
var NoConfigRequest;
(function(NoConfigRequest2) {
NoConfigRequest2.type = new import_coc3.RequestType("eslint/noConfig");
})(NoConfigRequest || (NoConfigRequest = {}));
var NoESLintLibraryRequest;
(function(NoESLintLibraryRequest2) {
NoESLintLibraryRequest2.type = new import_coc3.RequestType("eslint/noLibrary");
})(NoESLintLibraryRequest || (NoESLintLibraryRequest = {}));
var OpenESLintDocRequest;
(function(OpenESLintDocRequest2) {
OpenESLintDocRequest2.type = new import_coc3.RequestType("eslint/openDoc");
})(OpenESLintDocRequest || (OpenESLintDocRequest = {}));
var ProbeFailedRequest;
(function(ProbeFailedRequest2) {
ProbeFailedRequest2.type = new import_coc3.RequestType("eslint/probeFailed");
})(ProbeFailedRequest || (ProbeFailedRequest = {}));
var ConfirmExecutionResult;
(function(ConfirmExecutionResult2) {
ConfirmExecutionResult2[ConfirmExecutionResult2["denied"] = 1] = "denied";
ConfirmExecutionResult2[ConfirmExecutionResult2["confirmationPending"] = 2] = "confirmationPending";
ConfirmExecutionResult2[ConfirmExecutionResult2["disabled"] = 3] = "disabled";
ConfirmExecutionResult2[ConfirmExecutionResult2["approved"] = 4] = "approved";
})(ConfirmExecutionResult || (ConfirmExecutionResult = {}));
(function(ConfirmExecutionResult2) {
function toStatus(value) {
switch (value) {
case ConfirmExecutionResult2.denied:
return 6;
case ConfirmExecutionResult2.confirmationPending:
return 4;
case ConfirmExecutionResult2.disabled:
return 5;
case ConfirmExecutionResult2.approved:
return 1;
}
}
ConfirmExecutionResult2.toStatus = toStatus;
})(ConfirmExecutionResult || (ConfirmExecutionResult = {}));
var ConfirmExecution;
(function(ConfirmExecution2) {
ConfirmExecution2.type = new import_coc3.RequestType("eslint/confirmESLintExecution");
})(ConfirmExecution || (ConfirmExecution = {}));
var ShowOutputChannel;
(function(ShowOutputChannel2) {
ShowOutputChannel2.type = new import_coc3.NotificationType0("eslint/showOutputChannel");
})(ShowOutputChannel || (ShowOutputChannel = {}));
var exitCalled = new import_coc3.NotificationType("eslint/exitCalled");
async function pickFolder(folders, placeHolder) {
if (folders.length === 1) {
return Promise.resolve(folders[0]);
}
const selected = await import_coc3.window.showQuickpick(folders.map((folder) => {
return folder.name;
}), placeHolder);
if (selected === -1) {
return void 0;
}
return folders[selected];
}
function createDefaultConfiguration() {
const folders = import_coc3.workspace.workspaceFolders;
if (!folders) {
import_coc3.window.showErrorMessage("An ESLint configuration can only be generated if VS Code is opened on a workspace folder.");
return;
}
const noConfigFolders = folders.filter((folder) => {
const configFiles = [".eslintrc.js", ".eslintrc.yaml", ".eslintrc.yml", ".eslintrc", ".eslintrc.json"];
for (const configFile of configFiles) {
if (import_fs2.default.existsSync(import_path2.default.join(import_coc3.Uri.parse(folder.uri).fsPath, configFile))) {
return false;
}
}
return true;
});
if (noConfigFolders.length === 0) {
if (folders.length === 1) {
import_coc3.window.showInformationMessage("The workspace already contains an ESLint configuration file.");
} else {
import_coc3.window.showInformationMessage("All workspace folders already contain an ESLint configuration file.");
}
return;
}
pickFolder(noConfigFolders, "Select a workspace folder to generate a ESLint configuration for").then(async (folder) => {
if (!folder) {
return;
}
const folderRootPath = import_coc3.Uri.parse(folder.uri).fsPath;
const terminal = await import_coc3.workspace.createTerminal({
name: `ESLint init`,
cwd: folderRootPath
});
const eslintCommand = await findEslint(folderRootPath);
terminal.sendText(`${eslintCommand} --init`);
terminal.show();
});
}
var onActivateCommands;
var probeFailed = new Set();
function computeValidate(textDocument) {
const config = import_coc3.workspace.getConfiguration("eslint", textDocument.uri);
if (!config.get("enable", true)) {
return Validate.off;
}
const languageId = textDocument.languageId;
const validate = config.get("validate");
if (Array.isArray(validate)) {
for (const item of validate) {
if (Is.string(item) && item === languageId) {
return Validate.on;
} else if (ValidateItem.is(item) && item.language === languageId) {
return Validate.on;
}
}
}
const uri = textDocument.uri.toString();
if (probeFailed.has(uri)) {
return Validate.off;
}
const probe = config.get("probe");
if (Array.isArray(probe)) {
for (const item of probe) {
if (item === languageId) {
return Validate.probe;
}
}
}
return Validate.off;
}
var eslintExecutionKey = "eslintLibraries";
var eslintExecutionState;
var eslintAlwaysAllowExecutionKey = "eslintAlwaysAllowExecution";
var eslintAlwaysAllowExecutionState = false;
var sessionState = new Map();
var disabledLibraries = new Set();
var resource2ResourceInfo = new Map();
var globalStatus;
var lastExecutionInfo;
var libraryPath2ExecutionInfo = new Map();
var workspaceFolder2ExecutionInfos = new Map();
function updateExecutionInfo(params, result) {
let value = libraryPath2ExecutionInfo.get(params.libraryPath);
if (value === void 0) {
value = {
params: {libraryPath: params.libraryPath, scope: params.scope},
result,
editorErrorUri: void 0,
codeActionProvider: void 0,
diagnostics: import_coc3.languages.createDiagnosticCollection()
};
libraryPath2ExecutionInfo.set(params.libraryPath, value);
} else {
value.result = result;
}
}
function updateStatusInfo(param) {
globalStatus = param.state;
let info = resource2ResourceInfo.get(param.uri);
if (info === void 0) {
info = {
executionInfo: void 0,
status: param.state
};
resource2ResourceInfo.set(param.uri, info);
} else {
info.status = param.state;
}
}
function getExecutionInfo(doc, strict) {
if (doc == void 0) {
return void 0;
}
const info = resource2ResourceInfo.get(doc.uri);
if (info !== void 0) {
return info.executionInfo;
}
if (!strict) {
const folder = import_coc3.workspace.getWorkspaceFolder(doc.uri);
if (folder !== void 0) {
const values = workspaceFolder2ExecutionInfos.get(folder.uri.toString());
return values && values[0];
}
}
return void 0;
}
function clearInfo(info) {
info.diagnostics.clear();
if (info.codeActionProvider !== void 0) {
info.codeActionProvider.dispose();
}
}
function clearDiagnosticState(params) {
const info = libraryPath2ExecutionInfo.get(params.libraryPath);
if (info === void 0) {
return;
}
clearInfo(info);
}
function clearAllDiagnosticState() {
for (const info of Array.from(libraryPath2ExecutionInfo.values())) {
clearInfo(info);
}
}
async function askForLibraryConfirmation(client, context, params, update) {
sessionState.set(params.libraryPath, params);
const libraryUri = import_coc3.Uri.file(params.libraryPath);
const folder = import_coc3.workspace.getWorkspaceFolder(libraryUri.toString());
let message;
if (folder !== void 0) {
let relativePath = libraryUri.toString().substr(folder.uri.toString().length + 1);
const mainPath = "/lib/api.js";
if (relativePath.endsWith(mainPath)) {
relativePath = relativePath.substr(0, relativePath.length - mainPath.length);
}
message = `The ESLint extension will use '${relativePath}' for validation, which is installed locally in folder '${folder.name}'. Do you allow the execution of this ESLint version including all plugins and configuration files it will load on your behalf?
Press 'Allow Everywhere' to remember the choice for all workspaces. Use 'Disable' to disable ESLint for this session.`;
} else {
message = params.scope === "global" ? `The ESLint extension will use a globally installed ESLint library for validation. Do you allow the execution of this ESLint version including all plugins and configuration files it will load on your behalf?
Press 'Always Allow' to remember the choice for all workspaces. Use 'Cancel' to disable ESLint for this session.` : `The ESLint extension will use a locally installed ESLint library for validation. Do you allow the execution of this ESLint version including all plugins and configuration files it will load on your behalf?
Press 'Always Allow' to remember the choice for all workspaces. Use 'Cancel' to disable ESLint for this session.`;
}
const messageItems = [
{title: "Allow Everywhere", value: 4},
{title: "Allow", value: 3},
{title: "Deny", value: 1},
{title: "Disable", value: 2}
];
const item = await import_coc3.window.showInformationMessage(message, ...messageItems);
if (item === void 0) {
return;
}
if (item.value === 2) {
disabledLibraries.add(params.libraryPath);
updateExecutionInfo(params, 3);
clearDiagnosticState(params);
} else {
disabledLibraries.delete(params.libraryPath);
if (item.value === 3 || item.value === 1) {
const value = item.value === 3 ? true : false;
eslintExecutionState.libs[params.libraryPath] = value;
context.globalState.update(eslintExecutionKey, eslintExecutionState);
updateExecutionInfo(params, value ? 4 : 1);
clearDiagnosticState(params);
} else if (item.value === 4) {
eslintAlwaysAllowExecutionState = true;
context.globalState.update(eslintAlwaysAllowExecutionKey, eslintAlwaysAllowExecutionState);
updateExecutionInfo(params, 4);
clearAllDiagnosticState();
}
}
update && update();
client && client.sendNotification(import_vscode_languageserver_protocol.DidChangeConfigurationNotification.type, {settings: {}});
}
async function resetLibraryConfirmations(client, context, update) {
const items = [
{label: "Reset ESLint library decisions for this workspace", kind: "session"},
{label: "Reset all ESLint library decisions", kind: "all"}
];
if (eslintAlwaysAllowExecutionState) {
items.splice(1, 0, {label: "Reset Always Allow all ESlint libraries decision", kind: "alwaysAllow"});
}
const selectedIdx = await import_coc3.window.showQuickpick(items.map((o) => o.label), "Clear library confirmations");
if (selectedIdx == -1) {
return;
}
let selected = items[selectedIdx];
switch (selected.kind) {
case "all":
eslintExecutionState.libs = {};
eslintAlwaysAllowExecutionState = false;
break;
case "alwaysAllow":
eslintAlwaysAllowExecutionState = false;
break;
case "session":
if (sessionState.size === 1) {
const param = sessionState.values().next().value;
await askForLibraryConfirmation(client, context, param, update);
return;
} else {
for (const lib of sessionState.keys()) {
delete eslintExecutionState.libs[lib];
}
}
break;
}
context.globalState.update(eslintExecutionKey, eslintExecutionState);
context.globalState.update(eslintAlwaysAllowExecutionKey, eslintAlwaysAllowExecutionState);
disabledLibraries.clear();
libraryPath2ExecutionInfo.clear();
resource2ResourceInfo.clear();
workspaceFolder2ExecutionInfos.clear();
update && update();
client && client.sendNotification(import_vscode_languageserver_protocol.DidChangeConfigurationNotification.type, {settings: {}});
}
function activate(context) {
eslintExecutionState = context.globalState.get(eslintExecutionKey, {libs: {}});
eslintAlwaysAllowExecutionState = context.globalState.get(eslintAlwaysAllowExecutionKey, false);
function didOpenTextDocument(textDocument) {
if (activated) {
return;
}
if (computeValidate(textDocument) !== Validate.off) {
openListener.dispose();
configurationListener.dispose();
activated = true;
realActivate(context);
}
}
function configurationChanged() {
if (activated) {
return;
}
for (const textDocument of import_coc3.workspace.textDocuments) {
if (computeValidate(textDocument) !== Validate.off) {
openListener.dispose();
configurationListener.dispose();
activated = true;
realActivate(context);
return;
}
}
}
let activated = false;
const openListener = import_coc3.workspace.onDidOpenTextDocument(didOpenTextDocument);
const configurationListener = import_coc3.workspace.onDidChangeConfiguration(configurationChanged);
const notValidating = async () => {
let bufnr = await import_coc3.workspace.nvim.call("bufnr", ["%"]);
let doc = import_coc3.workspace.getDocument(bufnr);
const enabled = import_coc3.workspace.getConfiguration("eslint", doc ? doc.uri : void 0).get("enable", true);
if (!enabled) {
import_coc3.window.showInformationMessage(`ESLint is not running because the deprecated setting 'eslint.enable' is set to false. Remove the setting and use the extension disablement feature.`);
} else {
import_coc3.window.showInformationMessage("ESLint is not running. By default only TypeScript and JavaScript files are validated. If you want to validate other file types please specify them in the 'eslint.probe' setting.");
}
};
onActivateCommands = [
import_coc3.commands.registerCommand("eslint.executeAutofix", notValidating),
import_coc3.commands.registerCommand("eslint.showOutputChannel", notValidating),
import_coc3.commands.registerCommand("eslint.manageLibraryExecution", notValidating),
import_coc3.commands.registerCommand("eslint.resetLibraryExecution", () => {
resetLibraryConfirmations(void 0, context, void 0);
})
];
context.subscriptions.push(import_coc3.commands.registerCommand("eslint.createConfig", createDefaultConfiguration));
context.subscriptions.push(new task_default());
configurationChanged();
}
var CodeActionsOnSave;
(function(CodeActionsOnSave2) {
function isExplicitlyDisabled(setting) {
if (setting === void 0 || setting === null || Array.isArray(setting)) {
return false;
}
return setting["source.fixAll.eslint"] === false;
}
CodeActionsOnSave2.isExplicitlyDisabled = isExplicitlyDisabled;
function getSourceFixAll(setting) {
if (setting === null) {
return void 0;
}
if (Array.isArray(setting)) {
return setting.includes("source.fixAll") ? true : void 0;
} else {
return setting["source.fixAll"];
}
}
CodeActionsOnSave2.getSourceFixAll = getSourceFixAll;
function getSourceFixAllESLint(setting) {
if (setting === null) {
return void 0;
} else if (Array.isArray(setting)) {
return setting.includes("source.fixAll.eslint") ? true : void 0;
} else {
return setting["source.fixAll.eslint"];
}
}
CodeActionsOnSave2.getSourceFixAllESLint = getSourceFixAllESLint;
function setSourceFixAllESLint(setting, value) {
if (setting === null) {
return;
} else if (Array.isArray(setting)) {
const index = setting.indexOf("source.fixAll.eslint");
if (value === true) {
if (index === -1) {
setting.push("source.fixAll.eslint");
}
} else {
if (index >= 0) {
setting.splice(index, 1);
}
}
} else {
setting["source.fixAll.eslint"] = value;
}
}
CodeActionsOnSave2.setSourceFixAllESLint = setSourceFixAllESLint;
})(CodeActionsOnSave || (CodeActionsOnSave = {}));
function realActivate(context) {
const statusBarItem = import_coc3.window.createStatusBarItem(0);
context.subscriptions.push(statusBarItem);
let serverRunning;
const starting = "ESLint server is starting.";
const running = "ESLint server is running.";
const stopped = "ESLint server stopped.";
statusBarItem.text = "ESLint";
function updateStatusBar(status, isValidated) {
let text = "ESLint";
switch (status) {
case 1:
text = "";
break;
case 2:
text = "Eslint warning";
break;
case 3:
text = "Eslint error";
break;
case 6:
text = "Eslint denied";
break;
case 5:
text = "Eslint disabled";
break;
case 4:
text = "ESLint not approved or denied yet.";
break;
default:
text = "";
}
statusBarItem.text = serverRunning === void 0 ? starting : text;
const alwaysShow = import_coc3.workspace.getConfiguration("eslint").get("alwaysShowStatus", false);
if (alwaysShow || eslintAlwaysAllowExecutionState === true || status !== 1 || status === 1 && isValidated) {
statusBarItem.show();
} else {
statusBarItem.hide();
}
}
const flaggedLanguages = new Set(["javascript", "javascriptreact", "typescript", "typescriptreact"]);
async function updateStatusBarAndDiagnostics() {
let doc = await import_coc3.workspace.document;
function clearLastExecutionInfo() {
if (lastExecutionInfo === void 0) {
return;
}
if (lastExecutionInfo.codeActionProvider !== void 0) {
lastExecutionInfo.codeActionProvider.dispose();
lastExecutionInfo.codeActionProvider = void 0;
}
if (lastExecutionInfo.editorErrorUri !== void 0) {
lastExecutionInfo.diagnostics.delete(lastExecutionInfo.editorErrorUri.toString());
lastExecutionInfo.editorErrorUri = void 0;
}
lastExecutionInfo = void 0;
}
function handleEditor(doc2) {
var _a, _b;
const uri = doc2.uri;
const resourceInfo = resource2ResourceInfo.get(uri);
if (resourceInfo === void 0) {
return;
}
const info = resourceInfo.executionInfo;
if (info === void 0) {
return;
}
if (info.result === 2 && ((_a = info.editorErrorUri) == null ? void 0 : _a.toString()) !== uri.toString()) {
const range = (_b = doc2.getWordRangeAtPosition(import_coc3.Position.create(0, 0))) != null ? _b : import_coc3.Range.create(0, 0, 0, 0);
const diagnostic = import_coc3.Diagnostic.create(range, "ESLint is disabled since its execution has not been approved or denied yet. Use :CocCommand eslint.showOutputChannel to open the approval dialog.", import_coc3.DiagnosticSeverity.Warning);
diagnostic.source = "eslint";
const errorUri = doc2.uri;
info.diagnostics.set(errorUri, [diagnostic]);
if (info.editorErrorUri !== void 0) {
info.diagnostics.delete(info.editorErrorUri.toString());
}
info.editorErrorUri = import_coc3.Uri.parse(errorUri);
if (info.codeActionProvider !== void 0) {
info.codeActionProvider.dispose();
}
info.codeActionProvider = import_coc3.languages.registerCodeActionProvider([{pattern: import_coc3.Uri.parse(errorUri).fsPath}], {
provideCodeActions: (_document, _range, context2) => {
for (const diag of context2.diagnostics) {
if (diag === diagnostic) {
const result = {
title: "ESLint: Manage Library Execution",
kind: import_vscode_languageserver_protocol.CodeActionKind.QuickFix
};
result.isPreferred = true;
result.command = {
title: "Manage Library Execution",
command: "eslint.manageLibraryExecution",
arguments: [info.params]
};
return [result];
}
}
return [];
}
}, "eslint-library");
}
lastExecutionInfo = info;
}
function findApplicableStatus(editor) {
let candidates;
if (editor !== void 0) {
const resourceInfo = resource2ResourceInfo.get(editor.uri);
if (resourceInfo !== void 0) {
return [resourceInfo.status, true];
}
const workspaceFolder = import_coc3.workspace.getWorkspaceFolder(editor.uri);
if (workspaceFolder !== void 0) {
candidates = workspaceFolder2ExecutionInfos.get(workspaceFolder.uri.toString());
}
}
if (candidates === void 0) {
candidates = libraryPath2ExecutionInfo.values();
}
let result;
for (const info of candidates) {
if (result === void 0) {
result = info.result;
} else {
if (info.result === 2) {
result = info.result;
break;
} else if (info.result === 1 || info.result === 3) {
result = info.result;
}
}
}
return [result !== void 0 ? ConfirmExecutionResult.toStatus(result) : 1, false];
}
const executionInfo = getExecutionInfo(doc, true);
if (lastExecutionInfo !== executionInfo) {
clearLastExecutionInfo();
}
if (doc && doc.attached && flaggedLanguages.has(doc.filetype)) {
handleEditor(doc);
} else {
clearLastExecutionInfo();
}
const [status, isValidated] = findApplicableStatus(doc);
updateStatusBar(status, isValidated);
}
const serverModule = context.asAbsolutePath("lib/server.js");
const eslintConfig = import_coc3.workspace.getConfiguration("eslint");
const runtime = eslintConfig.get("runtime", void 0);
const debug = eslintConfig.get("debug");
const argv = eslintConfig.get("execArgv", []);
const nodeEnv = eslintConfig.get("nodeEnv", null);
let env;
if (debug) {
env = env || {};
env.DEBUG = "eslint:*,-eslint:code-path";
}
if (nodeEnv) {
env = env || {};
env.NODE_ENV = nodeEnv;
}
const serverOptions = {
run: {module: serverModule, transport: import_coc3.TransportKind.ipc, runtime, options: {cwd: import_coc3.workspace.cwd, env, execArgv: argv}},
debug: {module: serverModule, transport: import_coc3.TransportKind.ipc, runtime, options: {execArgv: argv.concat(["--nolazy", "--inspect=6011"]), cwd: process.cwd(), env}}
};
let defaultErrorHandler;
let serverCalledProcessExit = false;
const packageJsonFilter = {scheme: "file", pattern: "**/package.json"};
const configFileFilter = {scheme: "file", pattern: "**/.eslintr{c.js,c.yaml,c.yml,c,c.json}"};
const syncedDocuments = new Map();
const confirmationSemaphore = new Semaphore(1);
const supportedQuickFixKinds = new Set([import_vscode_languageserver_protocol.CodeActionKind.Source, import_vscode_languageserver_protocol.CodeActionKind.SourceFixAll, `${import_vscode_languageserver_protocol.CodeActionKind.SourceFixAll}.eslint`, import_vscode_languageserver_protocol.CodeActionKind.QuickFix]);
const clientOptions = {
documentSelector: [{scheme: "file"}, {scheme: "untitled"}],
diagnosticCollectionName: "eslint",
revealOutputChannelOn: import_coc3.RevealOutputChannelOn.Never,
initializationOptions: {},
progressOnInitialization: true,
synchronize: {
fileEvents: [
import_coc3.workspace.createFileSystemWatcher("**/.eslintr{c.js,c.yaml,c.yml,c,c.json}"),
import_coc3.workspace.createFileSystemWatcher("**/.eslintignore"),
import_coc3.workspace.createFileSystemWatcher("**/package.json")
]
},
initializationFailedHandler: (error) => {
client.error("Server initialization failed.", error);
client.outputChannel.show(true);
return false;
},
errorHandler: {
error: (error, message, count) => {
return defaultErrorHandler.error(error, message, count);
},
closed: () => {
if (serverCalledProcessExit) {
return import_coc3.CloseAction.DoNotRestart;
}
return defaultErrorHandler.closed();
}
},
middleware: {
didOpen: (document, next) => {
if (import_coc3.workspace.match([packageJsonFilter], document) || import_coc3.workspace.match([configFileFilter], document) || computeValidate(document) !== Validate.off) {
next(document);
syncedDocuments.set(document.uri, document);
return;
}
},
didChange: (event, next) => {
if (syncedDocuments.has(event.textDocument.uri)) {
next(event);
}
},
willSave: (event, next) => {
if (syncedDocuments.has(event.document.uri)) {
next(event);
}
},
willSaveWaitUntil: (event, next) => {
if (syncedDocuments.has(event.document.uri)) {
return next(event);
} else {
return Promise.resolve([]);
}
},
didSave: (document, next) => {
if (syncedDocuments.has(document.uri)) {
next(document);
}
},
didClose: (document, next) => {
const uri = document.uri;
if (syncedDocuments.has(uri)) {
syncedDocuments.delete(uri);
next(document);
}
},
provideCodeActions: (document, range, context2, token, next) => {
if (!syncedDocuments.has(document.uri.toString())) {
return [];
}
if (context2.only !== void 0 && !supportedQuickFixKinds.has(context2.only[0])) {
return [];
}
if (context2.only === void 0 && (!context2.diagnostics || context2.diagnostics.length === 0)) {
return [];
}
const eslintDiagnostics = [];
for (const diagnostic of context2.diagnostics) {
if (diagnostic.source === "eslint") {
eslintDiagnostics.push(diagnostic);
}
}
if (context2.only === void 0 && eslintDiagnostics.length === 0) {
return [];
}
const newContext = Object.assign({}, context2, {diagnostics: eslintDiagnostics});
return next(document, range, newContext, token);
},
workspace: {
didChangeWatchedFile: (event, next) => {
probeFailed.clear();
next(event);
},
didChangeConfiguration: (sections, next) => {
next(sections);
},
configuration: async (params, _token, _next) => {
if (params.items === void 0) {
return [];
}
const result = [];
for (const item of params.items) {
if (item.section || !item.scopeUri) {
result.push(null);
continue;
}
const resource = item.scopeUri;
const config = import_coc3.workspace.getConfiguration("eslint", resource);
const workspaceFolder = import_coc3.workspace.getWorkspaceFolder(resource);
const settings = {
validate: Validate.off,
packageManager: config.get("packageManager", "npm"),
codeActionOnSave: {
enable: false,
mode: CodeActionsOnSaveMode.all
},
format: false,
quiet: config.get("quiet", false),
onIgnoredFiles: ESLintSeverity.from(config.get("onIgnoredFiles", ESLintSeverity.off)),
options: config.get("options", {}),
run: config.get("run", "onType"),
nodePath: config.get("nodePath", null),
workingDirectory: void 0,
workspaceFolder: void 0,
codeAction: {
disableRuleComment: config.get("codeAction.disableRuleComment", {enable: true, location: "separateLine"}),
showDocumentation: config.get("codeAction.showDocumentation", {enable: true})
}
};
const document = syncedDocuments.get(item.scopeUri);
if (document === void 0) {
result.push(settings);
continue;
}
if (config.get("enabled", true)) {
settings.validate = computeValidate(document);
}
if (settings.validate !== Validate.off) {
settings.format = !!config.get("format.enable", false);
settings.codeActionOnSave.enable = !!config.get("autoFixOnSave", false);
settings.codeActionOnSave.mode = CodeActionsOnSaveMode.from(config.get("codeActionsOnSave.mode", CodeActionsOnSaveMode.all));
}
if (workspaceFolder !== void 0) {
settings.workspaceFolder = {
name: workspaceFolder.name,
uri: workspaceFolder.uri
};
}
const workingDirectories = config.get("workingDirectories", void 0);
if (Array.isArray(workingDirectories)) {
let workingDirectory = void 0;
const workspaceFolderPath = workspaceFolder && import_coc3.Uri.parse(workspaceFolder.uri).scheme === "file" ? import_coc3.Uri.parse(workspaceFolder.uri).fsPath : void 0;
for (const entry of workingDirectories) {
let directory;
let pattern;
let noCWD = false;
if (Is.string(entry)) {
directory = entry;
} else if (LegacyDirectoryItem.is(entry)) {
directory = entry.directory;
noCWD = !entry.changeProcessCWD;
} else if (DirectoryItem.is(entry)) {
directory = entry.directory;
if (entry["!cwd"] !== void 0) {
noCWD = entry["!cwd"];
}
} else if (PatternItem.is(entry)) {
pattern = entry.pattern;
if (entry["!cwd"] !== void 0) {
noCWD = entry["!cwd"];
}
} else if (ModeItem.is(entry)) {
workingDirectory = entry;
continue;
}
let itemValue;
if (directory !== void 0 || pattern !== void 0) {
const uri = import_coc3.Uri.parse(document.uri);
const filePath = uri.scheme === "file" ? uri.fsPath : void 0;
if (filePath !== void 0) {
if (directory !== void 0) {
directory = toOSPath(directory);
if (!import_path2.default.isAbsolute(directory) && workspaceFolderPath !== void 0) {
directory = import_path2.default.join(workspaceFolderPath, directory);
}
if (directory.charAt(directory.length - 1) !== import_path2.default.sep) {
directory = directory + import_path2.default.sep;
}
if (filePath.startsWith(directory)) {
itemValue = directory;
}
} else if (pattern !== void 0 && pattern.length > 0) {
if (!import_path2.default.posix.isAbsolute(pattern) && workspaceFolderPath !== void 0) {
pattern = import_path2.default.posix.join(toPosixPath(workspaceFolderPath), pattern);
}
if (pattern.charAt(pattern.length - 1) !== import_path2.default.posix.sep) {
pattern = pattern + import_path2.default.posix.sep;
}
const regExp = convert2RegExp(pattern);
if (regExp !== void 0) {
const match = regExp.exec(filePath);
if (match !== null && match.length > 0) {
itemValue = match[0];
}
}
}
}
}
if (itemValue !== void 0) {
if (workingDirectory === void 0 || ModeItem.is(workingDirectory)) {
workingDirectory = {directory: itemValue, "!cwd": noCWD};
} else {
if (workingDirectory.directory.length < itemValue.length) {
workingDirectory.directory = itemValue;
workingDirectory["!cwd"] = noCWD;
}
}
}
}
settings.workingDirectory = workingDirectory;
}
result.push(settings);
}
return result;
}
}
}
};
let client;
try {
client = new import_coc3.LanguageClient("ESLint", serverOptions, clientOptions);
} catch (err) {
import_coc3.window.showErrorMessage(`The ESLint extension couldn't be started. See the ESLint output channel for details.`);
return;
}
import_coc3.workspace.registerAutocmd({
request: true,
event: "BufWritePre",
arglist: [`+expand('<abuf>')`],
callback: async (bufnr) => {
let doc = import_coc3.workspace.getDocument(bufnr);
if (!doc || !doc.attached)
return;
if (computeValidate(doc.textDocument) == Validate.off)
return;
const config = import_coc3.workspace.getConfiguration("eslint", doc.uri);
if (config.get("autoFixOnSave", false)) {
const params = {
textDocument: {
uri: doc.uri
},
range: import_coc3.Range.create(0, 0, doc.textDocument.lineCount, 0),
context: {
only: [`${import_vscode_languageserver_protocol.CodeActionKind.SourceFixAll}.eslint`],
diagnostics: []
}
};
let res = await Promise.resolve(client.sendRequest(import_vscode_languageserver_protocol.CodeActionRequest.type, params));
if (res && Array.isArray(res)) {
if (import_vscode_languageserver_protocol.CodeAction.is(res[0])) {
await import_coc3.workspace.applyEdit(res[0].edit);
}
}
}
}
});
import_coc3.workspace.onDidChangeConfiguration(() => {
probeFailed.clear();
for (const textDocument of syncedDocuments.values()) {
if (computeValidate(textDocument) === Validate.off) {
try {
const provider = client.getFeature(import_vscode_languageserver_protocol.DidCloseTextDocumentNotification.method).getProvider(textDocument);
provider == null ? void 0 : provider.send(textDocument);
} catch (err) {
}
}
}
for (const textDocument of import_coc3.workspace.textDocuments) {
if (!syncedDocuments.has(textDocument.uri.toString()) && computeValidate(textDocument) !== Validate.off) {
try {
const provider = client.getFeature(import_vscode_languageserver_protocol.DidOpenTextDocumentNotification.method).getProvider(textDocument);
provider == null ? void 0 : provider.send(textDocument);
} catch (err) {
}
}
}
});
defaultErrorHandler = client.createDefaultErrorHandler();
client.onDidChangeState((event) => {
if (event.newState === import_coc3.State.Starting) {
client.info("ESLint server is starting");
serverRunning = void 0;
} else if (event.newState === import_coc3.State.Running) {
client.info(running);
serverRunning = true;
} else {
client.info(stopped);
serverRunning = false;
}
updateStatusBar((globalStatus != null ? globalStatus : serverRunning === false) ? 3 : 1, true);
});
client.onReady().then(() => {
client.onNotification(ShowOutputChannel.type, () => {
client.outputChannel.show();
});
client.onNotification(StatusNotification.type, (params) => {
updateStatusInfo(params);
updateStatusBarAndDiagnostics();
});
client.onNotification(exitCalled, (params) => {
serverCalledProcessExit = true;
client.error(`Server process exited with code ${params[0]}. This usually indicates a misconfigured ESLint setup.`, params[1]);
import_coc3.window.showErrorMessage(`ESLint server shut down itself. See 'ESLint' output channel for details.`, {title: "Open Output", id: 1}).then((value) => {
if (value !== void 0 && value.id === 1) {
client.outputChannel.show();
}
});
});
client.onRequest(NoConfigRequest.type, (params) => {
const uri = import_coc3.Uri.parse(params.document.uri);
const workspaceFolder = import_coc3.workspace.getWorkspaceFolder(params.document.uri);
const fileLocation = uri.fsPath;
if (workspaceFolder) {
client.warn([
"",
`No ESLint configuration (e.g .eslintrc) found for file: ${fileLocation}`,
`File will not be validated. Consider running 'eslint --init' in the workspace folder ${workspaceFolder.name}`,
`Alternatively you can disable ESLint by executing the 'Disable ESLint' command.`
].join("\n"));
} else {
client.warn([
"",
`No ESLint configuration (e.g .eslintrc) found for file: ${fileLocation}`,
`File will not be validated. Alternatively you can disable ESLint by executing the 'Disable ESLint' command.`
].join("\n"));
}
let resourceInfo = resource2ResourceInfo.get(params.document.uri);
if (resourceInfo === void 0) {
resourceInfo = {
status: 2,
executionInfo: void 0
};
resource2ResourceInfo.set(params.document.uri, resourceInfo);
} else {
resourceInfo.status = 2;
}
updateStatusBarAndDiagnostics();
return {};
});
client.onRequest(NoESLintLibraryRequest.type, (params) => {
const key = "noESLintMessageShown";
const state = context.globalState.get(key, {});
const uri = import_coc3.Uri.parse(params.source.uri);
const workspaceFolder = import_coc3.workspace.getWorkspaceFolder(uri.toString());
const packageManager = import_coc3.workspace.getConfiguration("eslint", uri.toString()).get("packageManager", "npm");
const localInstall = {
npm: "npm install eslint",
pnpm: "pnpm install eslint",
yarn: "yarn add eslint"
};
const globalInstall = {
npm: "npm install -g eslint",
pnpm: "pnpm install -g eslint",
yarn: "yarn global add eslint"
};
const isPackageManagerNpm = packageManager === "npm";
const outputItem = {
title: "Go to output",
id: 1
};
if (workspaceFolder) {
client.info([
"",
`Failed to load the ESLint library for the document ${uri.fsPath}`,
"",
`To use ESLint please install eslint by running ${localInstall[packageManager]} in the workspace folder ${workspaceFolder.name}`,
`or globally using '${globalInstall[packageManager]}'. You need to reopen the workspace after installing eslint.`,
"",
isPackageManagerNpm ? "If you are using yarn or pnpm instead of npm set the setting `eslint.packageManager` to either `yarn` or `pnpm`" : null,
`Alternatively you can disable ESLint for the workspace folder ${workspaceFolder.name} by executing the 'Disable ESLint' command.`
].filter((str) => str !== null).join("\n"));
if (state.workspaces === void 0) {
state.workspaces = {};
}
if (!state.workspaces[workspaceFolder.uri.toString()]) {
state.workspaces[workspaceFolder.uri.toString()] = true;
context.globalState.update(key, state);
import_coc3.window.showInformationMessage(`Failed to load the ESLint library for the document ${uri.fsPath}. See the output for more information.`, outputItem).then((item) => {
if (item && item.id === 1) {
client.outputChannel.show(true);
}
});
}
} else {
client.info([
`Failed to load the ESLint library for the document ${uri.fsPath}`,
`To use ESLint for single JavaScript file install eslint globally using '${globalInstall[packageManager]}'.`,
isPackageManagerNpm ? "If you are using yarn or pnpm instead of npm set the setting `eslint.packageManager` to either `yarn` or `pnpm`" : null,
"You need to reopen VS Code after installing eslint."
].filter((str) => str !== null).join("\n"));
if (!state.global) {
state.global = true;
context.globalState.update(key, state);
import_coc3.window.showInformationMessage(`Failed to load the ESLint library for the document ${uri.fsPath}. See the output for more information.`, outputItem).then((item) => {
if (item && item.id === 1) {
client.outputChannel.show(true);
}
});
}
}
return {};
});
client.onRequest(OpenESLintDocRequest.type, (params) => {
import_coc3.commands.executeCommand("vscode.open", import_coc3.Uri.parse(params.url));
return {};
});
client.onRequest(ProbeFailedRequest.type, (params) => {
var _a;
probeFailed.add(params.textDocument.uri);
const closeFeature = client.getFeature(import_vscode_languageserver_protocol.DidCloseTextDocumentNotification.method);
for (const document of import_coc3.workspace.textDocuments) {
if (document.uri.toString() === params.textDocument.uri) {
(_a = closeFeature.getProvider(document)) == null ? void 0 : _a.send(document);
}
}
});
client.onRequest(ConfirmExecution.type, async (params) => {
return confirmationSemaphore.lock(async () => {
try {
sessionState.set(params.libraryPath, params);
let result;
if (disabledLibraries.has(params.libraryPath)) {
result = 3;
} else {
const state = eslintExecutionState.libs[params.libraryPath];
if (state === true || state === false) {
clearDiagnosticState(params);
result = state ? 4 : 1;
} else if (eslintAlwaysAllowExecutionState === true) {
clearDiagnosticState(params);
result = 4;
}
}
result = result != null ? result : 2;
let executionInfo = libraryPath2ExecutionInfo.get(params.libraryPath);
if (executionInfo === void 0) {
executionInfo = {
params,
result,
codeActionProvider: void 0,
diagnostics: import_coc3.languages.createDiagnosticCollection(),
editorErrorUri: void 0
};
libraryPath2ExecutionInfo.set(params.libraryPath, executionInfo);
const workspaceFolder = import_coc3.workspace.getWorkspaceFolder(params.uri);
if (workspaceFolder !== void 0) {
const key = workspaceFolder.uri.toString();
let infos = workspaceFolder2ExecutionInfos.get(key);
if (infos === void 0) {
infos = [];
workspaceFolder2ExecutionInfos.set(key, infos);
}
infos.push(executionInfo);
}
} else {
executionInfo.result = result;
}
let resourceInfo = resource2ResourceInfo.get(params.uri);
if (resourceInfo === void 0) {
resourceInfo = {
status: ConfirmExecutionResult.toStatus(result),
executionInfo
};
resource2ResourceInfo.set(params.uri, resourceInfo);
} else {
resourceInfo.status = ConfirmExecutionResult.toStatus(result);
}
updateStatusBarAndDiagnostics();
return result;
} catch (err) {
return 1;
}
});
});
});
if (onActivateCommands) {
onActivateCommands.forEach((command) => command.dispose());
onActivateCommands = void 0;
}
context.subscriptions.push(client.start(), import_coc3.events.on("BufEnter", () => {
updateStatusBarAndDiagnostics();
}), import_coc3.workspace.registerTextDocumentContentProvider("eslint-error", {
provideTextDocumentContent: () => {
return [
"ESLint is disabled since its execution has not been approved or rejected yet.",
"",
"When validating a file using ESLint, the ESLint NPM library will load customization files and code from your workspace",
"and will execute it. If you do not trust the content in your workspace you should answer accordingly on the corresponding",
"approval dialog."
].join("\n");
}
}), import_coc3.workspace.onDidCloseTextDocument((document) => {
const uri = document.uri.toString();
resource2ResourceInfo.delete(uri);
}), import_coc3.commands.registerCommand("eslint.executeAutofix", async () => {
const doc = await import_coc3.workspace.document;
if (!doc || !doc.attached) {
return;
}
doc.forceSync();
const textDocument = {
uri: doc.uri,
version: doc.version
};
const params = {
command: "eslint.applyAllFixes",
arguments: [textDocument]
};
await client.onReady();
client.sendRequest(import_vscode_languageserver_protocol.ExecuteCommandRequest.type, params).then(void 0, () => {
import_coc3.window.showErrorMessage("Failed to apply ESLint fixes to the document. Please consider opening an issue with steps to reproduce.");
});
}), import_coc3.commands.registerCommand("eslint.showOutputChannel", async () => {
let doc = await import_coc3.workspace.document;
const executionInfo = getExecutionInfo(doc, false);
if (executionInfo !== void 0 && (executionInfo.result === 2 || executionInfo.result === 3)) {
await askForLibraryConfirmation(client, context, executionInfo.params, updateStatusBarAndDiagnostics);
return;
}
if (globalStatus === 1 || globalStatus === 2 || globalStatus === 3) {
client.outputChannel.show();
return;
}
if (globalStatus === 6) {
await resetLibraryConfirmations(client, context, updateStatusBarAndDiagnostics);
return;
}
let candidate;
let toRemove;
if (globalStatus === 4) {
if (libraryPath2ExecutionInfo.size === 1) {
candidate = libraryPath2ExecutionInfo.keys().next().value;
}
}
if (globalStatus === 5) {
if (disabledLibraries.size === 1) {
candidate = disabledLibraries.keys().next().value;
toRemove = disabledLibraries;
}
}
if (candidate !== void 0) {
if (sessionState.has(candidate)) {
if (toRemove !== void 0) {
toRemove.delete(candidate);
}
await askForLibraryConfirmation(client, context, sessionState.get(candidate), updateStatusBarAndDiagnostics);
return;
}
}
client.outputChannel.show();
}), import_coc3.commands.registerCommand("eslint.resetLibraryExecution", () => {
resetLibraryConfirmations(client, context, updateStatusBarAndDiagnostics);
}), import_coc3.commands.registerCommand("eslint.manageLibraryExecution", async (params) => {
if (params !== void 0) {
await askForLibraryConfirmation(client, context, params, updateStatusBarAndDiagnostics);
} else {
let doc = await import_coc3.workspace.document;
const info = getExecutionInfo(doc, false);
if (info !== void 0) {
await askForLibraryConfirmation(client, context, info.params, updateStatusBarAndDiagnostics);
} else {
import_coc3.window.showInformationMessage(doc && doc.attached ? "No ESLint library execution information found for current buffer." : "No ESLint library execution information found.");
}
}
}));
}
function deactivate() {
if (onActivateCommands) {
onActivateCommands.forEach((command) => command.dispose());
}
}
//# sourceMappingURL=index.js.map