neocities/public/js/ace-linters/build/ace-language-client.js
2024-10-13 22:30:24 -05:00

22765 lines
No EOL
818 KiB
JavaScript

(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, () => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 6093:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
/* provided dependency */ var process = __webpack_require__(9907);
/* provided dependency */ var console = __webpack_require__(4364);
// Currently in sync with Node.js lib/assert.js
// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _require = __webpack_require__(1342),
_require$codes = _require.codes,
ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE,
ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS;
var AssertionError = __webpack_require__(9801);
var _require2 = __webpack_require__(6827),
inspect = _require2.inspect;
var _require$types = (__webpack_require__(6827).types),
isPromise = _require$types.isPromise,
isRegExp = _require$types.isRegExp;
var objectAssign = Object.assign ? Object.assign : (__webpack_require__(3046).assign);
var objectIs = Object.is ? Object.is : __webpack_require__(5968);
var errorCache = new Map();
var isDeepEqual;
var isDeepStrictEqual;
var parseExpressionAt;
var findNodeAround;
var decoder;
function lazyLoadComparison() {
var comparison = __webpack_require__(5656);
isDeepEqual = comparison.isDeepEqual;
isDeepStrictEqual = comparison.isDeepStrictEqual;
} // Escape control characters but not \n and \t to keep the line breaks and
// indentation intact.
// eslint-disable-next-line no-control-regex
var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"]));
var escapeFn = function escapeFn(str) {
return meta[str.charCodeAt(0)];
};
var warned = false; // The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
var NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function innerFail(obj) {
if (obj.message instanceof Error) throw obj.message;
throw new AssertionError(obj);
}
function fail(actual, expected, message, operator, stackStartFn) {
var argsLen = arguments.length;
var internalMessage;
if (argsLen === 0) {
internalMessage = 'Failed';
} else if (argsLen === 1) {
message = actual;
actual = undefined;
} else {
if (warned === false) {
warned = true;
var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console);
warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094');
}
if (argsLen === 2) operator = '!=';
}
if (message instanceof Error) throw message;
var errArgs = {
actual: actual,
expected: expected,
operator: operator === undefined ? 'fail' : operator,
stackStartFn: stackStartFn || fail
};
if (message !== undefined) {
errArgs.message = message;
}
var err = new AssertionError(errArgs);
if (internalMessage) {
err.message = internalMessage;
err.generatedMessage = true;
}
throw err;
}
assert.fail = fail; // The AssertionError is defined in internal/error.
assert.AssertionError = AssertionError;
function innerOk(fn, argLen, value, message) {
if (!value) {
var generatedMessage = false;
if (argLen === 0) {
generatedMessage = true;
message = 'No value argument passed to `assert.ok()`';
} else if (message instanceof Error) {
throw message;
}
var err = new AssertionError({
actual: value,
expected: true,
message: message,
operator: '==',
stackStartFn: fn
});
err.generatedMessage = generatedMessage;
throw err;
}
} // Pure assertion tests whether a value is truthy, as determined
// by !!value.
function ok() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
innerOk.apply(void 0, [ok, args.length].concat(args));
}
assert.ok = ok; // The equality assertion tests shallow, coercive equality with ==.
/* eslint-disable no-restricted-properties */
assert.equal = function equal(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
} // eslint-disable-next-line eqeqeq
if (actual != expected) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: '==',
stackStartFn: equal
});
}
}; // The non-equality assertion tests for whether two objects are not
// equal with !=.
assert.notEqual = function notEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
} // eslint-disable-next-line eqeqeq
if (actual == expected) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: '!=',
stackStartFn: notEqual
});
}
}; // The equivalence assertion tests a deep equality relation.
assert.deepEqual = function deepEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (!isDeepEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'deepEqual',
stackStartFn: deepEqual
});
}
}; // The non-equivalence assertion tests for any deep inequality.
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (isDeepEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notDeepEqual',
stackStartFn: notDeepEqual
});
}
};
/* eslint-enable */
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (!isDeepStrictEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'deepStrictEqual',
stackStartFn: deepStrictEqual
});
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (isDeepStrictEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notDeepStrictEqual',
stackStartFn: notDeepStrictEqual
});
}
}
assert.strictEqual = function strictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (!objectIs(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'strictEqual',
stackStartFn: strictEqual
});
}
};
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (objectIs(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notStrictEqual',
stackStartFn: notStrictEqual
});
}
};
var Comparison = function Comparison(obj, keys, actual) {
var _this = this;
_classCallCheck(this, Comparison);
keys.forEach(function (key) {
if (key in obj) {
if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key])) {
_this[key] = actual[key];
} else {
_this[key] = obj[key];
}
}
});
};
function compareExceptionKey(actual, expected, key, message, keys, fn) {
if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) {
if (!message) {
// Create placeholder objects to create a nice output.
var a = new Comparison(actual, keys);
var b = new Comparison(expected, keys, actual);
var err = new AssertionError({
actual: a,
expected: b,
operator: 'deepStrictEqual',
stackStartFn: fn
});
err.actual = actual;
err.expected = expected;
err.operator = fn.name;
throw err;
}
innerFail({
actual: actual,
expected: expected,
message: message,
operator: fn.name,
stackStartFn: fn
});
}
}
function expectedException(actual, expected, msg, fn) {
if (typeof expected !== 'function') {
if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects.
if (arguments.length === 2) {
throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected);
} // Handle primitives properly.
if (_typeof(actual) !== 'object' || actual === null) {
var err = new AssertionError({
actual: actual,
expected: expected,
message: msg,
operator: 'deepStrictEqual',
stackStartFn: fn
});
err.operator = fn.name;
throw err;
}
var keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared
// as well.
if (expected instanceof Error) {
keys.push('name', 'message');
} else if (keys.length === 0) {
throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object');
}
if (isDeepEqual === undefined) lazyLoadComparison();
keys.forEach(function (key) {
if (typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key])) {
return;
}
compareExceptionKey(actual, expected, key, msg, keys, fn);
});
return true;
} // Guard instanceof against arrow functions as they don't have a prototype.
if (expected.prototype !== undefined && actual instanceof expected) {
return true;
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function getActual(fn) {
if (typeof fn !== 'function') {
throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn);
}
try {
fn();
} catch (e) {
return e;
}
return NO_EXCEPTION_SENTINEL;
}
function checkIsPromise(obj) {
// Accept native ES6 promises and promises that are implemented in a similar
// way. Do not accept thenables that use a function as `obj` and that have no
// `catch` handler.
// TODO: thenables are checked up until they have the correct methods,
// but according to documentation, the `then` method should receive
// the `fulfill` and `reject` arguments as well or it may be never resolved.
return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function';
}
function waitForActual(promiseFn) {
return Promise.resolve().then(function () {
var resultPromise;
if (typeof promiseFn === 'function') {
// Return a rejected promise if `promiseFn` throws synchronously.
resultPromise = promiseFn(); // Fail in case no promise is returned.
if (!checkIsPromise(resultPromise)) {
throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise);
}
} else if (checkIsPromise(promiseFn)) {
resultPromise = promiseFn;
} else {
throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn);
}
return Promise.resolve().then(function () {
return resultPromise;
}).then(function () {
return NO_EXCEPTION_SENTINEL;
}).catch(function (e) {
return e;
});
});
}
function expectsError(stackStartFn, actual, error, message) {
if (typeof error === 'string') {
if (arguments.length === 4) {
throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);
}
if (_typeof(actual) === 'object' && actual !== null) {
if (actual.message === error) {
throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message."));
}
} else if (actual === error) {
throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message."));
}
message = error;
error = undefined;
} else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') {
throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);
}
if (actual === NO_EXCEPTION_SENTINEL) {
var details = '';
if (error && error.name) {
details += " (".concat(error.name, ")");
}
details += message ? ": ".concat(message) : '.';
var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception';
innerFail({
actual: undefined,
expected: error,
operator: stackStartFn.name,
message: "Missing expected ".concat(fnType).concat(details),
stackStartFn: stackStartFn
});
}
if (error && !expectedException(actual, error, message, stackStartFn)) {
throw actual;
}
}
function expectsNoError(stackStartFn, actual, error, message) {
if (actual === NO_EXCEPTION_SENTINEL) return;
if (typeof error === 'string') {
message = error;
error = undefined;
}
if (!error || expectedException(actual, error)) {
var details = message ? ": ".concat(message) : '.';
var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception';
innerFail({
actual: actual,
expected: error,
operator: stackStartFn.name,
message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""),
stackStartFn: stackStartFn
});
}
throw actual;
}
assert.throws = function throws(promiseFn) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args));
};
assert.rejects = function rejects(promiseFn) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return waitForActual(promiseFn).then(function (result) {
return expectsError.apply(void 0, [rejects, result].concat(args));
});
};
assert.doesNotThrow = function doesNotThrow(fn) {
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args));
};
assert.doesNotReject = function doesNotReject(fn) {
for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
args[_key5 - 1] = arguments[_key5];
}
return waitForActual(fn).then(function (result) {
return expectsNoError.apply(void 0, [doesNotReject, result].concat(args));
});
};
assert.ifError = function ifError(err) {
if (err !== null && err !== undefined) {
var message = 'ifError got unwanted exception: ';
if (_typeof(err) === 'object' && typeof err.message === 'string') {
if (err.message.length === 0 && err.constructor) {
message += err.constructor.name;
} else {
message += err.message;
}
} else {
message += inspect(err);
}
var newErr = new AssertionError({
actual: err,
expected: null,
operator: 'ifError',
message: message,
stackStartFn: ifError
}); // Make sure we actually have a stack trace!
var origStack = err.stack;
if (typeof origStack === 'string') {
// This will remove any duplicated frames from the error frames taken
// from within `ifError` and add the original error frames to the newly
// created ones.
var tmp2 = origStack.split('\n');
tmp2.shift(); // Filter all frames existing in err.stack.
var tmp1 = newErr.stack.split('\n');
for (var i = 0; i < tmp2.length; i++) {
// Find the first occurrence of the frame.
var pos = tmp1.indexOf(tmp2[i]);
if (pos !== -1) {
// Only keep new frames.
tmp1 = tmp1.slice(0, pos);
break;
}
}
newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n'));
}
throw newErr;
}
}; // Expose a strict only variant of assert
function strict() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
innerOk.apply(void 0, [strict, args.length].concat(args));
}
assert.strict = objectAssign(strict, assert, {
equal: assert.strictEqual,
deepEqual: assert.deepStrictEqual,
notEqual: assert.notStrictEqual,
notDeepEqual: assert.notDeepStrictEqual
});
assert.strict.strict = assert.strict;
/***/ }),
/***/ 9801:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
/* provided dependency */ var process = __webpack_require__(9907);
// Currently in sync with Node.js lib/internal/assert/assertion_error.js
// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _require = __webpack_require__(6827),
inspect = _require.inspect;
var _require2 = __webpack_require__(1342),
ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
function repeat(str, count) {
count = Math.floor(count);
if (str.length == 0 || count == 0) return '';
var maxCount = str.length * count;
count = Math.floor(Math.log(count) / Math.log(2));
while (count) {
str += str;
count--;
}
str += str.substring(0, maxCount - str.length);
return str;
}
var blue = '';
var green = '';
var red = '';
var white = '';
var kReadableOperator = {
deepStrictEqual: 'Expected values to be strictly deep-equal:',
strictEqual: 'Expected values to be strictly equal:',
strictEqualObject: 'Expected "actual" to be reference-equal to "expected":',
deepEqual: 'Expected values to be loosely deep-equal:',
equal: 'Expected values to be loosely equal:',
notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:',
notStrictEqual: 'Expected "actual" to be strictly unequal to:',
notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":',
notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:',
notEqual: 'Expected "actual" to be loosely unequal to:',
notIdentical: 'Values identical but not reference-equal:'
}; // Comparing short primitives should just show === / !== instead of using the
// diff.
var kMaxShortLength = 10;
function copyError(source) {
var keys = Object.keys(source);
var target = Object.create(Object.getPrototypeOf(source));
keys.forEach(function (key) {
target[key] = source[key];
});
Object.defineProperty(target, 'message', {
value: source.message
});
return target;
}
function inspectValue(val) {
// The util.inspect default values could be changed. This makes sure the
// error messages contain the necessary information nevertheless.
return inspect(val, {
compact: false,
customInspect: false,
depth: 1000,
maxArrayLength: Infinity,
// Assert compares only enumerable properties (with a few exceptions).
showHidden: false,
// Having a long line as error is better than wrapping the line for
// comparison for now.
// TODO(BridgeAR): `breakLength` should be limited as soon as soon as we
// have meta information about the inspected properties (i.e., know where
// in what line the property starts and ends).
breakLength: Infinity,
// Assert does not detect proxies currently.
showProxy: false,
sorted: true,
// Inspect getters as we also check them when comparing entries.
getters: true
});
}
function createErrDiff(actual, expected, operator) {
var other = '';
var res = '';
var lastPos = 0;
var end = '';
var skipped = false;
var actualInspected = inspectValue(actual);
var actualLines = actualInspected.split('\n');
var expectedLines = inspectValue(expected).split('\n');
var i = 0;
var indicator = ''; // In case both values are objects explicitly mark them as not reference equal
// for the `strictEqual` operator.
if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) {
operator = 'strictEqualObject';
} // If "actual" and "expected" fit on a single line and they are not strictly
// equal, check further special handling.
if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) {
var inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of "actual" and "expected" together is less than
// kMaxShortLength and if neither is an object and at least one of them is
// not `zero`, use the strict equal comparison to visualize the output.
if (inputLength <= kMaxShortLength) {
if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) {
// -0 === +0
return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n");
}
} else if (operator !== 'strictEqualObject') {
// If the stderr is a tty and the input length is lower than the current
// columns per line, add a mismatch indicator below the output. If it is
// not a tty, use a default value of 80 characters.
var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80;
if (inputLength < maxLength) {
while (actualLines[0][i] === expectedLines[0][i]) {
i++;
} // Ignore the first characters.
if (i > 2) {
// Add position indicator for the first mismatch in case it is a
// single line and the input length is less than the column length.
indicator = "\n ".concat(repeat(' ', i), "^");
i = 0;
}
}
}
} // Remove all ending lines that match (this optimizes the output for
// readability by reducing the number of total changed lines).
var a = actualLines[actualLines.length - 1];
var b = expectedLines[expectedLines.length - 1];
while (a === b) {
if (i++ < 2) {
end = "\n ".concat(a).concat(end);
} else {
other = a;
}
actualLines.pop();
expectedLines.pop();
if (actualLines.length === 0 || expectedLines.length === 0) break;
a = actualLines[actualLines.length - 1];
b = expectedLines[expectedLines.length - 1];
}
var maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference.
// E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() })
if (maxLines === 0) {
// We have to get the result again. The lines were all removed before.
var _actualLines = actualInspected.split('\n'); // Only remove lines in case it makes sense to collapse those.
// TODO: Accept env to always show the full error.
if (_actualLines.length > 30) {
_actualLines[26] = "".concat(blue, "...").concat(white);
while (_actualLines.length > 27) {
_actualLines.pop();
}
}
return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n");
}
if (i > 3) {
end = "\n".concat(blue, "...").concat(white).concat(end);
skipped = true;
}
if (other !== '') {
end = "\n ".concat(other).concat(end);
other = '';
}
var printedLines = 0;
var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white);
var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped");
for (i = 0; i < maxLines; i++) {
// Only extra expected lines exist
var cur = i - lastPos;
if (actualLines.length < i + 1) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(expectedLines[i - 2]);
printedLines++;
}
res += "\n ".concat(expectedLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the expected line to the cache.
other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]);
printedLines++; // Only extra actual lines exist
} else if (expectedLines.length < i + 1) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(actualLines[i - 2]);
printedLines++;
}
res += "\n ".concat(actualLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the actual line to the result.
res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]);
printedLines++; // Lines diverge
} else {
var expectedLine = expectedLines[i];
var actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by
// a trailing comma. In that case it is actually identical and we should
// mark it as such.
var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical,
// add a comma at the end of the actual line. Otherwise the output could
// look weird as in:
//
// [
// 1 // No comma at the end!
// + 2
// ]
//
if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) {
divergingLines = false;
actualLine += ',';
}
if (divergingLines) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(actualLines[i - 2]);
printedLines++;
}
res += "\n ".concat(actualLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the actual line to the result and cache the expected diverging
// line so consecutive diverging lines show up as +++--- and not +-+-+-.
res += "\n".concat(green, "+").concat(white, " ").concat(actualLine);
other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine);
printedLines += 2; // Lines are identical
} else {
// Add all cached information to the result before adding other things
// and reset the cache.
res += other;
other = ''; // If the last diverging line is exactly one line above or if it is the
// very first line, add the line to the result.
if (cur === 1 || i === 0) {
res += "\n ".concat(actualLine);
printedLines++;
}
}
} // Inspected object to big (Show ~20 rows max)
if (printedLines > 20 && i < maxLines - 2) {
return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white);
}
}
return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator);
}
var AssertionError =
/*#__PURE__*/
function (_Error) {
_inherits(AssertionError, _Error);
function AssertionError(options) {
var _this;
_classCallCheck(this, AssertionError);
if (_typeof(options) !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
var message = options.message,
operator = options.operator,
stackStartFn = options.stackStartFn;
var actual = options.actual,
expected = options.expected;
var limit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
if (message != null) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, String(message)));
} else {
if (process.stderr && process.stderr.isTTY) {
// Reset on each call to make sure we handle dynamically set environment
// variables correct.
if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) {
blue = "\x1B[34m";
green = "\x1B[32m";
white = "\x1B[39m";
red = "\x1B[31m";
} else {
blue = '';
green = '';
white = '';
red = '';
}
} // Prevent the error stack from being visible by duplicating the error
// in a very close way to the original in case both sides are actually
// instances of Error.
if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) {
actual = copyError(actual);
expected = copyError(expected);
}
if (operator === 'deepStrictEqual' || operator === 'strictEqual') {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, createErrDiff(actual, expected, operator)));
} else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') {
// In case the objects are equal but the operator requires unequal, show
// the first object and say A equals B
var base = kReadableOperator[operator];
var res = inspectValue(actual).split('\n'); // In case "actual" is an object, it should not be reference equal.
if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) {
base = kReadableOperator.notStrictEqualObject;
} // Only remove lines in case it makes sense to collapse those.
// TODO: Accept env to always show the full error.
if (res.length > 30) {
res[26] = "".concat(blue, "...").concat(white);
while (res.length > 27) {
res.pop();
}
} // Only print a single input.
if (res.length === 1) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, " ").concat(res[0])));
} else {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")));
}
} else {
var _res = inspectValue(actual);
var other = '';
var knownOperators = kReadableOperator[operator];
if (operator === 'notDeepEqual' || operator === 'notEqual') {
_res = "".concat(kReadableOperator[operator], "\n\n").concat(_res);
if (_res.length > 1024) {
_res = "".concat(_res.slice(0, 1021), "...");
}
} else {
other = "".concat(inspectValue(expected));
if (_res.length > 512) {
_res = "".concat(_res.slice(0, 509), "...");
}
if (other.length > 512) {
other = "".concat(other.slice(0, 509), "...");
}
if (operator === 'deepEqual' || operator === 'equal') {
_res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n");
} else {
other = " ".concat(operator, " ").concat(other);
}
}
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(_res).concat(other)));
}
}
Error.stackTraceLimit = limit;
_this.generatedMessage = !message;
Object.defineProperty(_assertThisInitialized(_this), 'name', {
value: 'AssertionError [ERR_ASSERTION]',
enumerable: false,
writable: true,
configurable: true
});
_this.code = 'ERR_ASSERTION';
_this.actual = actual;
_this.expected = expected;
_this.operator = operator;
if (Error.captureStackTrace) {
// eslint-disable-next-line no-restricted-syntax
Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn);
} // Create error message including the error code in the name.
_this.stack; // Reset the name.
_this.name = 'AssertionError';
return _possibleConstructorReturn(_this);
}
_createClass(AssertionError, [{
key: "toString",
value: function toString() {
return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message);
}
}, {
key: inspect.custom,
value: function value(recurseTimes, ctx) {
// This limits the `actual` and `expected` property default inspection to
// the minimum depth. Otherwise those values would be too verbose compared
// to the actual error message which contains a combined view of these two
// input values.
return inspect(this, _objectSpread({}, ctx, {
customInspect: false,
depth: 0
}));
}
}]);
return AssertionError;
}(_wrapNativeSuper(Error));
module.exports = AssertionError;
/***/ }),
/***/ 1342:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
// Currently in sync with Node.js lib/internal/errors.js
// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f
/* eslint node-core/documented-errors: "error" */
/* eslint node-core/alphabetize-errors: "error" */
/* eslint node-core/prefer-util-format-errors: "error" */
// The whole point behind this internal module is to allow Node.js to no
// longer be forced to treat every error message change as a semver-major
// change. The NodeError classes here all expose a `code` property whose
// value statically and permanently identifies the error. While the error
// message may change, the code should not.
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var codes = {}; // Lazy loaded
var assert;
var util;
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error;
}
function getMessage(arg1, arg2, arg3) {
if (typeof message === 'string') {
return message;
} else {
return message(arg1, arg2, arg3);
}
}
var NodeError =
/*#__PURE__*/
function (_Base) {
_inherits(NodeError, _Base);
function NodeError(arg1, arg2, arg3) {
var _this;
_classCallCheck(this, NodeError);
_this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3)));
_this.code = code;
return _this;
}
return NodeError;
}(Base);
codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
var len = expected.length;
expected = expected.map(function (i) {
return String(i);
});
if (len > 2) {
return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
} else if (len === 2) {
return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
} else {
return "of ".concat(thing, " ").concat(expected[0]);
}
} else {
return "of ".concat(thing, " ").concat(String(expected));
}
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
if (assert === undefined) assert = __webpack_require__(6093);
assert(typeof name === 'string', "'name' must be a string"); // determiner: 'must be' or 'must not be'
var determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
var msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} else {
var type = includes(name, '.') ? 'property' : 'argument';
msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} // TODO(BridgeAR): Improve the output by showing `null` and similar.
msg += ". Received type ".concat(_typeof(actual));
return msg;
}, TypeError);
createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) {
var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid';
if (util === undefined) util = __webpack_require__(6827);
var inspected = util.inspect(value);
if (inspected.length > 128) {
inspected = "".concat(inspected.slice(0, 128), "...");
}
return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected);
}, TypeError, RangeError);
createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) {
var type;
if (value && value.constructor && value.constructor.name) {
type = "instance of ".concat(value.constructor.name);
} else {
type = "type ".concat(_typeof(value));
}
return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, ".");
}, TypeError);
createErrorType('ERR_MISSING_ARGS', function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (assert === undefined) assert = __webpack_require__(6093);
assert(args.length > 0, 'At least one arg needs to be specified');
var msg = 'The ';
var len = args.length;
args = args.map(function (a) {
return "\"".concat(a, "\"");
});
switch (len) {
case 1:
msg += "".concat(args[0], " argument");
break;
case 2:
msg += "".concat(args[0], " and ").concat(args[1], " arguments");
break;
default:
msg += args.slice(0, len - 1).join(', ');
msg += ", and ".concat(args[len - 1], " arguments");
break;
}
return "".concat(msg, " must be specified");
}, TypeError);
module.exports.codes = codes;
/***/ }),
/***/ 5656:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
// Currently in sync with Node.js lib/internal/util/comparisons.js
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var regexFlagsSupported = /a/g.flags !== undefined;
var arrayFromSet = function arrayFromSet(set) {
var array = [];
set.forEach(function (value) {
return array.push(value);
});
return array;
};
var arrayFromMap = function arrayFromMap(map) {
var array = [];
map.forEach(function (value, key) {
return array.push([key, value]);
});
return array;
};
var objectIs = Object.is ? Object.is : __webpack_require__(5968);
var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () {
return [];
};
var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(7838);
function uncurryThis(f) {
return f.call.bind(f);
}
var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable);
var objectToString = uncurryThis(Object.prototype.toString);
var _require$types = (__webpack_require__(6827).types),
isAnyArrayBuffer = _require$types.isAnyArrayBuffer,
isArrayBufferView = _require$types.isArrayBufferView,
isDate = _require$types.isDate,
isMap = _require$types.isMap,
isRegExp = _require$types.isRegExp,
isSet = _require$types.isSet,
isNativeError = _require$types.isNativeError,
isBoxedPrimitive = _require$types.isBoxedPrimitive,
isNumberObject = _require$types.isNumberObject,
isStringObject = _require$types.isStringObject,
isBooleanObject = _require$types.isBooleanObject,
isBigIntObject = _require$types.isBigIntObject,
isSymbolObject = _require$types.isSymbolObject,
isFloat32Array = _require$types.isFloat32Array,
isFloat64Array = _require$types.isFloat64Array;
function isNonIndex(key) {
if (key.length === 0 || key.length > 10) return true;
for (var i = 0; i < key.length; i++) {
var code = key.charCodeAt(i);
if (code < 48 || code > 57) return true;
} // The maximum size for an array is 2 ** 32 -1.
return key.length === 10 && key >= Math.pow(2, 32);
}
function getOwnNonIndexProperties(value) {
return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value)));
} // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
var ONLY_ENUMERABLE = undefined;
var kStrict = true;
var kLoose = false;
var kNoIterator = 0;
var kIsArray = 1;
var kIsSet = 2;
var kIsMap = 3; // Check if they have the same source and flags
function areSimilarRegExps(a, b) {
return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b);
}
function areSimilarFloatArrays(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (var offset = 0; offset < a.byteLength; offset++) {
if (a[offset] !== b[offset]) {
return false;
}
}
return true;
}
function areSimilarTypedArrays(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0;
}
function areEqualArrayBuffers(buf1, buf2) {
return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0;
}
function isEqualBoxedPrimitive(val1, val2) {
if (isNumberObject(val1)) {
return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2));
}
if (isStringObject(val1)) {
return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2);
}
if (isBooleanObject(val1)) {
return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2);
}
if (isBigIntObject(val1)) {
return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2);
}
return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2);
} // Notes: Type tags are historical [[Class]] properties that can be set by
// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS
// and retrieved using Object.prototype.toString.call(obj) in JS
// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring
// for a list of tags pre-defined in the spec.
// There are some unspecified tags in the wild too (e.g. typed array tags).
// Since tags can be altered, they only serve fast failures
//
// Typed arrays and buffers are checked by comparing the content in their
// underlying ArrayBuffer. This optimization requires that it's
// reasonable to interpret their underlying memory in the same way,
// which is checked by comparing their type tags.
// (e.g. a Uint8Array and a Uint16Array with the same memory content
// could still be different because they will be interpreted differently).
//
// For strict comparison, objects should have
// a) The same built-in type tags
// b) The same prototypes.
function innerDeepEqual(val1, val2, strict, memos) {
// All identical values are equivalent, as determined by ===.
if (val1 === val2) {
if (val1 !== 0) return true;
return strict ? objectIs(val1, val2) : true;
} // Check more closely if val1 and val2 are equal.
if (strict) {
if (_typeof(val1) !== 'object') {
return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2);
}
if (_typeof(val2) !== 'object' || val1 === null || val2 === null) {
return false;
}
if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) {
return false;
}
} else {
if (val1 === null || _typeof(val1) !== 'object') {
if (val2 === null || _typeof(val2) !== 'object') {
// eslint-disable-next-line eqeqeq
return val1 == val2;
}
return false;
}
if (val2 === null || _typeof(val2) !== 'object') {
return false;
}
}
var val1Tag = objectToString(val1);
var val2Tag = objectToString(val2);
if (val1Tag !== val2Tag) {
return false;
}
if (Array.isArray(val1)) {
// Check for sparse arrays and general fast path
if (val1.length !== val2.length) {
return false;
}
var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
if (keys1.length !== keys2.length) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsArray, keys1);
} // [browserify] This triggers on certain types in IE (Map/Set) so we don't
// wan't to early return out of the rest of the checks. However we can check
// if the second value is one of these values and the first isn't.
if (val1Tag === '[object Object]') {
// return keyCheck(val1, val2, strict, memos, kNoIterator);
if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) {
return false;
}
}
if (isDate(val1)) {
if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) {
return false;
}
} else if (isRegExp(val1)) {
if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) {
return false;
}
} else if (isNativeError(val1) || val1 instanceof Error) {
// Do not compare the stack as it might differ even though the error itself
// is otherwise identical.
if (val1.message !== val2.message || val1.name !== val2.name) {
return false;
}
} else if (isArrayBufferView(val1)) {
if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) {
if (!areSimilarFloatArrays(val1, val2)) {
return false;
}
} else if (!areSimilarTypedArrays(val1, val2)) {
return false;
} // Buffer.compare returns true, so val1.length === val2.length. If they both
// only contain numeric keys, we don't need to exam further than checking
// the symbols.
var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
if (_keys.length !== _keys2.length) {
return false;
}
return keyCheck(val1, val2, strict, memos, kNoIterator, _keys);
} else if (isSet(val1)) {
if (!isSet(val2) || val1.size !== val2.size) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsSet);
} else if (isMap(val1)) {
if (!isMap(val2) || val1.size !== val2.size) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsMap);
} else if (isAnyArrayBuffer(val1)) {
if (!areEqualArrayBuffers(val1, val2)) {
return false;
}
} else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) {
return false;
}
return keyCheck(val1, val2, strict, memos, kNoIterator);
}
function getEnumerables(val, keys) {
return keys.filter(function (k) {
return propertyIsEnumerable(val, k);
});
}
function keyCheck(val1, val2, strict, memos, iterationType, aKeys) {
// For all remaining Object pairs, including Array, objects and Maps,
// equivalence is determined by having:
// a) The same number of owned enumerable properties
// b) The same set of keys/indexes (although not necessarily the same order)
// c) Equivalent values for every corresponding key/index
// d) For Sets and Maps, equal contents
// Note: this accounts for both named and indexed properties on Arrays.
if (arguments.length === 5) {
aKeys = Object.keys(val1);
var bKeys = Object.keys(val2); // The pair must have the same number of owned properties.
if (aKeys.length !== bKeys.length) {
return false;
}
} // Cheap key test
var i = 0;
for (; i < aKeys.length; i++) {
if (!hasOwnProperty(val2, aKeys[i])) {
return false;
}
}
if (strict && arguments.length === 5) {
var symbolKeysA = objectGetOwnPropertySymbols(val1);
if (symbolKeysA.length !== 0) {
var count = 0;
for (i = 0; i < symbolKeysA.length; i++) {
var key = symbolKeysA[i];
if (propertyIsEnumerable(val1, key)) {
if (!propertyIsEnumerable(val2, key)) {
return false;
}
aKeys.push(key);
count++;
} else if (propertyIsEnumerable(val2, key)) {
return false;
}
}
var symbolKeysB = objectGetOwnPropertySymbols(val2);
if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) {
return false;
}
} else {
var _symbolKeysB = objectGetOwnPropertySymbols(val2);
if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) {
return false;
}
}
}
if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) {
return true;
} // Use memos to handle cycles.
if (memos === undefined) {
memos = {
val1: new Map(),
val2: new Map(),
position: 0
};
} else {
// We prevent up to two map.has(x) calls by directly retrieving the value
// and checking for undefined. The map can only contain numbers, so it is
// safe to check for undefined only.
var val2MemoA = memos.val1.get(val1);
if (val2MemoA !== undefined) {
var val2MemoB = memos.val2.get(val2);
if (val2MemoB !== undefined) {
return val2MemoA === val2MemoB;
}
}
memos.position++;
}
memos.val1.set(val1, memos.position);
memos.val2.set(val2, memos.position);
var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType);
memos.val1.delete(val1);
memos.val2.delete(val2);
return areEq;
}
function setHasEqualElement(set, val1, strict, memo) {
// Go looking.
var setValues = arrayFromSet(set);
for (var i = 0; i < setValues.length; i++) {
var val2 = setValues[i];
if (innerDeepEqual(val1, val2, strict, memo)) {
// Remove the matching element to make sure we do not check that again.
set.delete(val2);
return true;
}
}
return false;
} // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using
// Sadly it is not possible to detect corresponding values properly in case the
// type is a string, number, bigint or boolean. The reason is that those values
// can match lots of different string values (e.g., 1n == '+00001').
function findLooseMatchingPrimitives(prim) {
switch (_typeof(prim)) {
case 'undefined':
return null;
case 'object':
// Only pass in null as object!
return undefined;
case 'symbol':
return false;
case 'string':
prim = +prim;
// Loose equal entries exist only if the string is possible to convert to
// a regular number and not NaN.
// Fall through
case 'number':
if (numberIsNaN(prim)) {
return false;
}
}
return true;
}
function setMightHaveLoosePrim(a, b, prim) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) return altValue;
return b.has(altValue) && !a.has(altValue);
}
function mapMightHaveLoosePrim(a, b, prim, item, memo) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
var curB = b.get(altValue);
if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) {
return false;
}
return !a.has(altValue) && innerDeepEqual(item, curB, false, memo);
}
function setEquiv(a, b, strict, memo) {
// This is a lazily initiated Set of entries which have to be compared
// pairwise.
var set = null;
var aValues = arrayFromSet(a);
for (var i = 0; i < aValues.length; i++) {
var val = aValues[i]; // Note: Checking for the objects first improves the performance for object
// heavy sets but it is a minor slow down for primitives. As they are fast
// to check this improves the worst case scenario instead.
if (_typeof(val) === 'object' && val !== null) {
if (set === null) {
set = new Set();
} // If the specified value doesn't exist in the second set its an not null
// object (or non strict only: a not matching primitive) we'll need to go
// hunting for something thats deep-(strict-)equal to it. To make this
// O(n log n) complexity we have to copy these values in a new set first.
set.add(val);
} else if (!b.has(val)) {
if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values.
if (!setMightHaveLoosePrim(a, b, val)) {
return false;
}
if (set === null) {
set = new Set();
}
set.add(val);
}
}
if (set !== null) {
var bValues = arrayFromSet(b);
for (var _i = 0; _i < bValues.length; _i++) {
var _val = bValues[_i]; // We have to check if a primitive value is already
// matching and only if it's not, go hunting for it.
if (_typeof(_val) === 'object' && _val !== null) {
if (!setHasEqualElement(set, _val, strict, memo)) return false;
} else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) {
return false;
}
}
return set.size === 0;
}
return true;
}
function mapHasEqualEntry(set, map, key1, item1, strict, memo) {
// To be able to handle cases like:
// Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']])
// ... we need to consider *all* matching keys, not just the first we find.
var setValues = arrayFromSet(set);
for (var i = 0; i < setValues.length; i++) {
var key2 = setValues[i];
if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) {
set.delete(key2);
return true;
}
}
return false;
}
function mapEquiv(a, b, strict, memo) {
var set = null;
var aEntries = arrayFromMap(a);
for (var i = 0; i < aEntries.length; i++) {
var _aEntries$i = _slicedToArray(aEntries[i], 2),
key = _aEntries$i[0],
item1 = _aEntries$i[1];
if (_typeof(key) === 'object' && key !== null) {
if (set === null) {
set = new Set();
}
set.add(key);
} else {
// By directly retrieving the value we prevent another b.has(key) check in
// almost all possible cases.
var item2 = b.get(key);
if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) {
if (strict) return false; // Fast path to detect missing string, symbol, undefined and null
// keys.
if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false;
if (set === null) {
set = new Set();
}
set.add(key);
}
}
}
if (set !== null) {
var bEntries = arrayFromMap(b);
for (var _i2 = 0; _i2 < bEntries.length; _i2++) {
var _bEntries$_i = _slicedToArray(bEntries[_i2], 2),
key = _bEntries$_i[0],
item = _bEntries$_i[1];
if (_typeof(key) === 'object' && key !== null) {
if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false;
} else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) {
return false;
}
}
return set.size === 0;
}
return true;
}
function objEquiv(a, b, strict, keys, memos, iterationType) {
// Sets and maps don't have their entries accessible via normal object
// properties.
var i = 0;
if (iterationType === kIsSet) {
if (!setEquiv(a, b, strict, memos)) {
return false;
}
} else if (iterationType === kIsMap) {
if (!mapEquiv(a, b, strict, memos)) {
return false;
}
} else if (iterationType === kIsArray) {
for (; i < a.length; i++) {
if (hasOwnProperty(a, i)) {
if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) {
return false;
}
} else if (hasOwnProperty(b, i)) {
return false;
} else {
// Array is sparse.
var keysA = Object.keys(a);
for (; i < keysA.length; i++) {
var key = keysA[i];
if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) {
return false;
}
}
if (keysA.length !== Object.keys(b).length) {
return false;
}
return true;
}
}
} // The pair must have equivalent values for every corresponding key.
// Possibly expensive deep test:
for (i = 0; i < keys.length; i++) {
var _key = keys[i];
if (!innerDeepEqual(a[_key], b[_key], strict, memos)) {
return false;
}
}
return true;
}
function isDeepEqual(val1, val2) {
return innerDeepEqual(val1, val2, kLoose);
}
function isDeepStrictEqual(val1, val2) {
return innerDeepEqual(val1, val2, kStrict);
}
module.exports = {
isDeepEqual: isDeepEqual,
isDeepStrictEqual: isDeepStrictEqual
};
/***/ }),
/***/ 9818:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var GetIntrinsic = __webpack_require__(528);
var callBind = __webpack_require__(8498);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 8498:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var bind = __webpack_require__(9138);
var GetIntrinsic = __webpack_require__(528);
var setFunctionLength = __webpack_require__(6108);
var $TypeError = __webpack_require__(3468);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(4940);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 4364:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/*global window, global*/
var util = __webpack_require__(6827)
var assert = __webpack_require__(6093)
function now() { return new Date().getTime() }
var slice = Array.prototype.slice
var console
var times = {}
if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) {
console = __webpack_require__.g.console
} else if (typeof window !== "undefined" && window.console) {
console = window.console
} else {
console = {}
}
var functions = [
[log, "log"],
[info, "info"],
[warn, "warn"],
[error, "error"],
[time, "time"],
[timeEnd, "timeEnd"],
[trace, "trace"],
[dir, "dir"],
[consoleAssert, "assert"]
]
for (var i = 0; i < functions.length; i++) {
var tuple = functions[i]
var f = tuple[0]
var name = tuple[1]
if (!console[name]) {
console[name] = f
}
}
module.exports = console
function log() {}
function info() {
console.log.apply(console, arguments)
}
function warn() {
console.log.apply(console, arguments)
}
function error() {
console.warn.apply(console, arguments)
}
function time(label) {
times[label] = now()
}
function timeEnd(label) {
var time = times[label]
if (!time) {
throw new Error("No such label: " + label)
}
delete times[label]
var duration = now() - time
console.log(label + ": " + duration + "ms")
}
function trace() {
var err = new Error()
err.name = "Trace"
err.message = util.format.apply(null, arguments)
console.error(err.stack)
}
function dir(object) {
console.log(util.inspect(object) + "\n")
}
function consoleAssert(expression) {
if (!expression) {
var arr = slice.call(arguments, 1)
assert.ok(false, util.format.apply(null, arr))
}
}
/***/ }),
/***/ 686:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var $defineProperty = __webpack_require__(4940);
var $SyntaxError = __webpack_require__(5731);
var $TypeError = __webpack_require__(3468);
var gopd = __webpack_require__(9336);
/** @type {import('.')} */
module.exports = function defineDataProperty(
obj,
property,
value
) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new $TypeError('`obj` must be an object or a function`');
}
if (typeof property !== 'string' && typeof property !== 'symbol') {
throw new $TypeError('`property` must be a string or a symbol`');
}
if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
}
if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
}
if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
}
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
throw new $TypeError('`loose`, if provided, must be a boolean');
}
var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
var nonWritable = arguments.length > 4 ? arguments[4] : null;
var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
var loose = arguments.length > 6 ? arguments[6] : false;
/* @type {false | TypedPropertyDescriptor<unknown>} */
var desc = !!gopd && gopd(obj, property);
if ($defineProperty) {
$defineProperty(obj, property, {
configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
value: value,
writable: nonWritable === null && desc ? desc.writable : !nonWritable
});
} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
obj[property] = value; // eslint-disable-line no-param-reassign
} else {
throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
}
};
/***/ }),
/***/ 1857:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var keys = __webpack_require__(9228);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var hasPropertyDescriptors = __webpack_require__(7239)();
var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
var defineProperty = function (object, name, value, predicate) {
if (name in object) {
if (predicate === true) {
if (object[name] === value) {
return;
}
} else if (!isFunction(predicate) || !predicate()) {
return;
}
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value; // eslint-disable-line no-param-reassign
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/***/ 4940:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var GetIntrinsic = __webpack_require__(528);
/** @type {import('.')} */
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false;
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = false;
}
}
module.exports = $defineProperty;
/***/ }),
/***/ 6729:
/***/ ((module) => {
"use strict";
/** @type {import('./eval')} */
module.exports = EvalError;
/***/ }),
/***/ 9838:
/***/ ((module) => {
"use strict";
/** @type {import('.')} */
module.exports = Error;
/***/ }),
/***/ 1155:
/***/ ((module) => {
"use strict";
/** @type {import('./range')} */
module.exports = RangeError;
/***/ }),
/***/ 4943:
/***/ ((module) => {
"use strict";
/** @type {import('./ref')} */
module.exports = ReferenceError;
/***/ }),
/***/ 5731:
/***/ ((module) => {
"use strict";
/** @type {import('./syntax')} */
module.exports = SyntaxError;
/***/ }),
/***/ 3468:
/***/ ((module) => {
"use strict";
/** @type {import('./type')} */
module.exports = TypeError;
/***/ }),
/***/ 2140:
/***/ ((module) => {
"use strict";
/** @type {import('./uri')} */
module.exports = URIError;
/***/ }),
/***/ 3046:
/***/ ((module) => {
"use strict";
/**
* Code refactored from Mozilla Developer Network:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
*/
function assign(target, firstSource) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
function polyfill() {
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: assign
});
}
}
module.exports = {
assign: assign,
polyfill: polyfill
};
/***/ }),
/***/ 46:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
/* provided dependency */ var console = __webpack_require__(4364);
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
/***/ }),
/***/ 705:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var isCallable = __webpack_require__(9617);
var toStr = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var forEachArray = function forEachArray(array, iterator, receiver) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
if (receiver == null) {
iterator(array[i], i, array);
} else {
iterator.call(receiver, array[i], i, array);
}
}
}
};
var forEachString = function forEachString(string, iterator, receiver) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
if (receiver == null) {
iterator(string.charAt(i), i, string);
} else {
iterator.call(receiver, string.charAt(i), i, string);
}
}
};
var forEachObject = function forEachObject(object, iterator, receiver) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
if (receiver == null) {
iterator(object[k], k, object);
} else {
iterator.call(receiver, object[k], k, object);
}
}
}
};
var forEach = function forEach(list, iterator, thisArg) {
if (!isCallable(iterator)) {
throw new TypeError('iterator must be a function');
}
var receiver;
if (arguments.length >= 3) {
receiver = thisArg;
}
if (toStr.call(list) === '[object Array]') {
forEachArray(list, iterator, receiver);
} else if (typeof list === 'string') {
forEachString(list, iterator, receiver);
} else {
forEachObject(list, iterator, receiver);
}
};
module.exports = forEach;
/***/ }),
/***/ 8794:
/***/ ((module) => {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 9138:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var implementation = __webpack_require__(8794);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 528:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var undefined;
var $Error = __webpack_require__(9838);
var $EvalError = __webpack_require__(6729);
var $RangeError = __webpack_require__(1155);
var $ReferenceError = __webpack_require__(4943);
var $SyntaxError = __webpack_require__(5731);
var $TypeError = __webpack_require__(3468);
var $URIError = __webpack_require__(2140);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(3558)();
var hasProto = __webpack_require__(6869)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(9138);
var hasOwn = __webpack_require__(8554);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 9336:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var GetIntrinsic = __webpack_require__(528);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
if ($gOPD) {
try {
$gOPD([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
$gOPD = null;
}
}
module.exports = $gOPD;
/***/ }),
/***/ 7239:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var $defineProperty = __webpack_require__(4940);
var hasPropertyDescriptors = function hasPropertyDescriptors() {
return !!$defineProperty;
};
hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
// node v0.6 has a bug where array lengths can be Set but not Defined
if (!$defineProperty) {
return null;
}
try {
return $defineProperty([], 'length', { value: 1 }).length !== 1;
} catch (e) {
// In Firefox 4-22, defining length on an array throws an exception.
return true;
}
};
module.exports = hasPropertyDescriptors;
/***/ }),
/***/ 6869:
/***/ ((module) => {
"use strict";
var test = {
foo: {}
};
var $Object = Object;
module.exports = function hasProto() {
return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object);
};
/***/ }),
/***/ 3558:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(2908);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 2908:
/***/ ((module) => {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 1913:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var hasSymbols = __webpack_require__(2908);
module.exports = function hasToStringTagShams() {
return hasSymbols() && !!Symbol.toStringTag;
};
/***/ }),
/***/ 8554:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = __webpack_require__(9138);
/** @type {import('.')} */
module.exports = bind.call(call, $hasOwn);
/***/ }),
/***/ 5615:
/***/ ((module) => {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/***/ 5387:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var hasToStringTag = __webpack_require__(1913)();
var callBound = __webpack_require__(9818);
var $toString = callBound('Object.prototype.toString');
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return $toString(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
$toString(value) !== '[object Array]' &&
$toString(value.callee) === '[object Function]';
};
var supportsStandardArguments = (function () {
return isStandardArguments(arguments);
}());
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
/***/ }),
/***/ 9617:
/***/ ((module) => {
"use strict";
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`
var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
var all = document.all;
if (toStr.call(all) === toStr.call(document.all)) {
isDDA = function isDocumentDotAll(value) {
/* globals document: false */
// in IE 6-8, typeof document.all is "object" and it's truthy
if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
try {
var str = toStr.call(value);
return (
str === ddaClass
|| str === ddaClass2
|| str === ddaClass3 // opera 12.16
|| str === objectClass // IE 6-8
) && value('') == null; // eslint-disable-line eqeqeq
} catch (e) { /**/ }
}
return false;
};
}
}
module.exports = reflectApply
? function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) { return false; }
}
return !isES6ClassFn(value) && tryFunctionObject(value);
}
: function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (hasToStringTag) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr.call(value);
if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
return tryFunctionObject(value);
};
/***/ }),
/***/ 2625:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var toStr = Object.prototype.toString;
var fnToStr = Function.prototype.toString;
var isFnRegex = /^\s*(?:function)?\*/;
var hasToStringTag = __webpack_require__(1913)();
var getProto = Object.getPrototypeOf;
var getGeneratorFunc = function () { // eslint-disable-line consistent-return
if (!hasToStringTag) {
return false;
}
try {
return Function('return function*() {}')();
} catch (e) {
}
};
var GeneratorFunction;
module.exports = function isGeneratorFunction(fn) {
if (typeof fn !== 'function') {
return false;
}
if (isFnRegex.test(fnToStr.call(fn))) {
return true;
}
if (!hasToStringTag) {
var str = toStr.call(fn);
return str === '[object GeneratorFunction]';
}
if (!getProto) {
return false;
}
if (typeof GeneratorFunction === 'undefined') {
var generatorFunc = getGeneratorFunc();
GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;
}
return getProto(fn) === GeneratorFunction;
};
/***/ }),
/***/ 8006:
/***/ ((module) => {
"use strict";
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function isNaN(value) {
return value !== value;
};
/***/ }),
/***/ 7838:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var callBind = __webpack_require__(8498);
var define = __webpack_require__(1857);
var implementation = __webpack_require__(8006);
var getPolyfill = __webpack_require__(1591);
var shim = __webpack_require__(1641);
var polyfill = callBind(getPolyfill(), Number);
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
define(polyfill, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = polyfill;
/***/ }),
/***/ 1591:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var implementation = __webpack_require__(8006);
module.exports = function getPolyfill() {
if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) {
return Number.isNaN;
}
return implementation;
};
/***/ }),
/***/ 1641:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var define = __webpack_require__(1857);
var getPolyfill = __webpack_require__(1591);
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function shimNumberIsNaN() {
var polyfill = getPolyfill();
define(Number, { isNaN: polyfill }, {
isNaN: function testIsNaN() {
return Number.isNaN !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ 5943:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var whichTypedArray = __webpack_require__(2730);
module.exports = function isTypedArray(value) {
return !!whichTypedArray(value);
};
/***/ }),
/***/ 2372:
/***/ ((module) => {
"use strict";
var numberIsNaN = function (value) {
return value !== value;
};
module.exports = function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a === b) {
return true;
}
if (numberIsNaN(a) && numberIsNaN(b)) {
return true;
}
return false;
};
/***/ }),
/***/ 5968:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var define = __webpack_require__(1857);
var callBind = __webpack_require__(8498);
var implementation = __webpack_require__(2372);
var getPolyfill = __webpack_require__(1937);
var shim = __webpack_require__(5087);
var polyfill = callBind(getPolyfill(), Object);
define(polyfill, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = polyfill;
/***/ }),
/***/ 1937:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var implementation = __webpack_require__(2372);
module.exports = function getPolyfill() {
return typeof Object.is === 'function' ? Object.is : implementation;
};
/***/ }),
/***/ 5087:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var getPolyfill = __webpack_require__(1937);
var define = __webpack_require__(1857);
module.exports = function shimObjectIs() {
var polyfill = getPolyfill();
define(Object, { is: polyfill }, {
is: function testObjectIs() {
return Object.is !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ 8160:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArgs = __webpack_require__(968); // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
module.exports = keysShim;
/***/ }),
/***/ 9228:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(968);
var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(8160);
var originalKeys = Object.keys;
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/***/ 968:
/***/ ((module) => {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/***/ 9907:
/***/ ((module) => {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/***/ 6108:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var GetIntrinsic = __webpack_require__(528);
var define = __webpack_require__(686);
var hasDescriptors = __webpack_require__(7239)();
var gOPD = __webpack_require__(9336);
var $TypeError = __webpack_require__(3468);
var $floor = GetIntrinsic('%Math.floor%');
/** @type {import('.')} */
module.exports = function setFunctionLength(fn, length) {
if (typeof fn !== 'function') {
throw new $TypeError('`fn` is not a function');
}
if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
throw new $TypeError('`length` must be a positive 32-bit integer');
}
var loose = arguments.length > 2 && !!arguments[2];
var functionLengthIsConfigurable = true;
var functionLengthIsWritable = true;
if ('length' in fn && gOPD) {
var desc = gOPD(fn, 'length');
if (desc && !desc.configurable) {
functionLengthIsConfigurable = false;
}
if (desc && !desc.writable) {
functionLengthIsWritable = false;
}
}
if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
if (hasDescriptors) {
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
} else {
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
}
}
return fn;
};
/***/ }),
/***/ 8583:
/***/ (function(module, exports, __webpack_require__) {
/* provided dependency */ var console = __webpack_require__(4364);
var __WEBPACK_AMD_DEFINE_RESULT__;;/*! showdown v 2.1.0 - 21-04-2022 */
(function(){
/**
* Created by Tivie on 13-07-2015.
*/
function getDefaultOpts (simple) {
'use strict';
var defaultOptions = {
omitExtraWLInCodeBlocks: {
defaultValue: false,
describe: 'Omit the default extra whiteline added to code blocks',
type: 'boolean'
},
noHeaderId: {
defaultValue: false,
describe: 'Turn on/off generated header id',
type: 'boolean'
},
prefixHeaderId: {
defaultValue: false,
describe: 'Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic \'section-\' prefix',
type: 'string'
},
rawPrefixHeaderId: {
defaultValue: false,
describe: 'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',
type: 'boolean'
},
ghCompatibleHeaderId: {
defaultValue: false,
describe: 'Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)',
type: 'boolean'
},
rawHeaderId: {
defaultValue: false,
describe: 'Remove only spaces, \' and " from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids',
type: 'boolean'
},
headerLevelStart: {
defaultValue: false,
describe: 'The header blocks level start',
type: 'integer'
},
parseImgDimensions: {
defaultValue: false,
describe: 'Turn on/off image dimension parsing',
type: 'boolean'
},
simplifiedAutoLink: {
defaultValue: false,
describe: 'Turn on/off GFM autolink style',
type: 'boolean'
},
excludeTrailingPunctuationFromURLs: {
defaultValue: false,
describe: 'Excludes trailing punctuation from links generated with autoLinking',
type: 'boolean'
},
literalMidWordUnderscores: {
defaultValue: false,
describe: 'Parse midword underscores as literal underscores',
type: 'boolean'
},
literalMidWordAsterisks: {
defaultValue: false,
describe: 'Parse midword asterisks as literal asterisks',
type: 'boolean'
},
strikethrough: {
defaultValue: false,
describe: 'Turn on/off strikethrough support',
type: 'boolean'
},
tables: {
defaultValue: false,
describe: 'Turn on/off tables support',
type: 'boolean'
},
tablesHeaderId: {
defaultValue: false,
describe: 'Add an id to table headers',
type: 'boolean'
},
ghCodeBlocks: {
defaultValue: true,
describe: 'Turn on/off GFM fenced code blocks support',
type: 'boolean'
},
tasklists: {
defaultValue: false,
describe: 'Turn on/off GFM tasklist support',
type: 'boolean'
},
smoothLivePreview: {
defaultValue: false,
describe: 'Prevents weird effects in live previews due to incomplete input',
type: 'boolean'
},
smartIndentationFix: {
defaultValue: false,
describe: 'Tries to smartly fix indentation in es6 strings',
type: 'boolean'
},
disableForced4SpacesIndentedSublists: {
defaultValue: false,
describe: 'Disables the requirement of indenting nested sublists by 4 spaces',
type: 'boolean'
},
simpleLineBreaks: {
defaultValue: false,
describe: 'Parses simple line breaks as <br> (GFM Style)',
type: 'boolean'
},
requireSpaceBeforeHeadingText: {
defaultValue: false,
describe: 'Makes adding a space between `#` and the header text mandatory (GFM Style)',
type: 'boolean'
},
ghMentions: {
defaultValue: false,
describe: 'Enables github @mentions',
type: 'boolean'
},
ghMentionsLink: {
defaultValue: 'https://github.com/{u}',
describe: 'Changes the link generated by @mentions. Only applies if ghMentions option is enabled.',
type: 'string'
},
encodeEmails: {
defaultValue: true,
describe: 'Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities',
type: 'boolean'
},
openLinksInNewWindow: {
defaultValue: false,
describe: 'Open all links in new windows',
type: 'boolean'
},
backslashEscapesHTMLTags: {
defaultValue: false,
describe: 'Support for HTML Tag escaping. ex: \<div>foo\</div>',
type: 'boolean'
},
emoji: {
defaultValue: false,
describe: 'Enable emoji support. Ex: `this is a :smile: emoji`',
type: 'boolean'
},
underline: {
defaultValue: false,
describe: 'Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `<em>` and `<strong>`',
type: 'boolean'
},
ellipsis: {
defaultValue: true,
describe: 'Replaces three dots with the ellipsis unicode character',
type: 'boolean'
},
completeHTMLDocument: {
defaultValue: false,
describe: 'Outputs a complete html document, including `<html>`, `<head>` and `<body>` tags',
type: 'boolean'
},
metadata: {
defaultValue: false,
describe: 'Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).',
type: 'boolean'
},
splitAdjacentBlockquotes: {
defaultValue: false,
describe: 'Split adjacent blockquote blocks',
type: 'boolean'
}
};
if (simple === false) {
return JSON.parse(JSON.stringify(defaultOptions));
}
var ret = {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
ret[opt] = defaultOptions[opt].defaultValue;
}
}
return ret;
}
function allOptionsOn () {
'use strict';
var options = getDefaultOpts(true),
ret = {};
for (var opt in options) {
if (options.hasOwnProperty(opt)) {
ret[opt] = true;
}
}
return ret;
}
/**
* Created by Tivie on 06-01-2015.
*/
// Private properties
var showdown = {},
parsers = {},
extensions = {},
globalOptions = getDefaultOpts(true),
setFlavor = 'vanilla',
flavor = {
github: {
omitExtraWLInCodeBlocks: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
disableForced4SpacesIndentedSublists: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghCompatibleHeaderId: true,
ghMentions: true,
backslashEscapesHTMLTags: true,
emoji: true,
splitAdjacentBlockquotes: true
},
original: {
noHeaderId: true,
ghCodeBlocks: false
},
ghost: {
omitExtraWLInCodeBlocks: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
smoothLivePreview: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghMentions: false,
encodeEmails: true
},
vanilla: getDefaultOpts(true),
allOn: allOptionsOn()
};
/**
* helper namespace
* @type {{}}
*/
showdown.helper = {};
/**
* TODO LEGACY SUPPORT CODE
* @type {{}}
*/
showdown.extensions = {};
/**
* Set a global option
* @static
* @param {string} key
* @param {*} value
* @returns {showdown}
*/
showdown.setOption = function (key, value) {
'use strict';
globalOptions[key] = value;
return this;
};
/**
* Get a global option
* @static
* @param {string} key
* @returns {*}
*/
showdown.getOption = function (key) {
'use strict';
return globalOptions[key];
};
/**
* Get the global options
* @static
* @returns {{}}
*/
showdown.getOptions = function () {
'use strict';
return globalOptions;
};
/**
* Reset global options to the default values
* @static
*/
showdown.resetOptions = function () {
'use strict';
globalOptions = getDefaultOpts(true);
};
/**
* Set the flavor showdown should use as default
* @param {string} name
*/
showdown.setFlavor = function (name) {
'use strict';
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
showdown.resetOptions();
var preset = flavor[name];
setFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
globalOptions[option] = preset[option];
}
}
};
/**
* Get the currently set flavor
* @returns {string}
*/
showdown.getFlavor = function () {
'use strict';
return setFlavor;
};
/**
* Get the options of a specified flavor. Returns undefined if the flavor was not found
* @param {string} name Name of the flavor
* @returns {{}|undefined}
*/
showdown.getFlavorOptions = function (name) {
'use strict';
if (flavor.hasOwnProperty(name)) {
return flavor[name];
}
};
/**
* Get the default options
* @static
* @param {boolean} [simple=true]
* @returns {{}}
*/
showdown.getDefaultOptions = function (simple) {
'use strict';
return getDefaultOpts(simple);
};
/**
* Get or set a subParser
*
* subParser(name) - Get a registered subParser
* subParser(name, func) - Register a subParser
* @static
* @param {string} name
* @param {function} [func]
* @returns {*}
*/
showdown.subParser = function (name, func) {
'use strict';
if (showdown.helper.isString(name)) {
if (typeof func !== 'undefined') {
parsers[name] = func;
} else {
if (parsers.hasOwnProperty(name)) {
return parsers[name];
} else {
throw Error('SubParser named ' + name + ' not registered!');
}
}
}
};
/**
* Gets or registers an extension
* @static
* @param {string} name
* @param {object|object[]|function=} ext
* @returns {*}
*/
showdown.extension = function (name, ext) {
'use strict';
if (!showdown.helper.isString(name)) {
throw Error('Extension \'name\' must be a string');
}
name = showdown.helper.stdExtName(name);
// Getter
if (showdown.helper.isUndefined(ext)) {
if (!extensions.hasOwnProperty(name)) {
throw Error('Extension named ' + name + ' is not registered!');
}
return extensions[name];
// Setter
} else {
// Expand extension if it's wrapped in a function
if (typeof ext === 'function') {
ext = ext();
}
// Ensure extension is an array
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExtension = validate(ext, name);
if (validExtension.valid) {
extensions[name] = ext;
} else {
throw Error(validExtension.error);
}
}
};
/**
* Gets all extensions registered
* @returns {{}}
*/
showdown.getAllExtensions = function () {
'use strict';
return extensions;
};
/**
* Remove an extension
* @param {string} name
*/
showdown.removeExtension = function (name) {
'use strict';
delete extensions[name];
};
/**
* Removes all extensions
*/
showdown.resetExtensions = function () {
'use strict';
extensions = {};
};
/**
* Validate extension
* @param {array} extension
* @param {string} name
* @returns {{valid: boolean, error: string}}
*/
function validate (extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!(ext.regex instanceof RegExp)) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
}
/**
* Validate extension
* @param {object} ext
* @returns {boolean}
*/
showdown.validateExtension = function (ext) {
'use strict';
var validateExtension = validate(ext, null);
if (!validateExtension.valid) {
console.warn(validateExtension.error);
return false;
}
return true;
};
/**
* showdownjs helper functions
*/
if (!showdown.hasOwnProperty('helper')) {
showdown.helper = {};
}
/**
* Check if var is string
* @static
* @param {string} a
* @returns {boolean}
*/
showdown.helper.isString = function (a) {
'use strict';
return (typeof a === 'string' || a instanceof String);
};
/**
* Check if var is a function
* @static
* @param {*} a
* @returns {boolean}
*/
showdown.helper.isFunction = function (a) {
'use strict';
var getType = {};
return a && getType.toString.call(a) === '[object Function]';
};
/**
* isArray helper function
* @static
* @param {*} a
* @returns {boolean}
*/
showdown.helper.isArray = function (a) {
'use strict';
return Array.isArray(a);
};
/**
* Check if value is undefined
* @static
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
*/
showdown.helper.isUndefined = function (value) {
'use strict';
return typeof value === 'undefined';
};
/**
* ForEach helper function
* Iterates over Arrays and Objects (own properties only)
* @static
* @param {*} obj
* @param {function} callback Accepts 3 params: 1. value, 2. key, 3. the original array/object
*/
showdown.helper.forEach = function (obj, callback) {
'use strict';
// check if obj is defined
if (showdown.helper.isUndefined(obj)) {
throw new Error('obj param is required');
}
if (showdown.helper.isUndefined(callback)) {
throw new Error('callback param is required');
}
if (!showdown.helper.isFunction(callback)) {
throw new Error('callback param must be a function/closure');
}
if (typeof obj.forEach === 'function') {
obj.forEach(callback);
} else if (showdown.helper.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
callback(obj[i], i, obj);
}
} else if (typeof (obj) === 'object') {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
callback(obj[prop], prop, obj);
}
}
} else {
throw new Error('obj does not seem to be an array or an iterable object');
}
};
/**
* Standardidize extension name
* @static
* @param {string} s extension name
* @returns {string}
*/
showdown.helper.stdExtName = function (s) {
'use strict';
return s.replace(/[_?*+\/\\.^-]/g, '').replace(/\s/g, '').toLowerCase();
};
function escapeCharactersCallback (wholeMatch, m1) {
'use strict';
var charCodeToEscape = m1.charCodeAt(0);
return '¨E' + charCodeToEscape + 'E';
}
/**
* Callback used to escape characters when passing through String.replace
* @static
* @param {string} wholeMatch
* @param {string} m1
* @returns {string}
*/
showdown.helper.escapeCharactersCallback = escapeCharactersCallback;
/**
* Escape characters in a string
* @static
* @param {string} text
* @param {string} charsToEscape
* @param {boolean} afterBackslash
* @returns {XML|string|void|*}
*/
showdown.helper.escapeCharacters = function (text, charsToEscape, afterBackslash) {
'use strict';
// First we have to escape the escape characters so that
// we can build a character class out of them
var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
if (afterBackslash) {
regexString = '\\\\' + regexString;
}
var regex = new RegExp(regexString, 'g');
text = text.replace(regex, escapeCharactersCallback);
return text;
};
/**
* Unescape HTML entities
* @param txt
* @returns {string}
*/
showdown.helper.unescapeHTMLEntities = function (txt) {
'use strict';
return txt
.replace(/&quot;/g, '"')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
};
var rgxFindMatchPos = function (str, left, right, flags) {
'use strict';
var f = flags || '',
g = f.indexOf('g') > -1,
x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),
l = new RegExp(left, f.replace(/g/g, '')),
pos = [],
t, s, m, start, end;
do {
t = 0;
while ((m = x.exec(str))) {
if (l.test(m[0])) {
if (!(t++)) {
s = x.lastIndex;
start = s - m[0].length;
}
} else if (t) {
if (!--t) {
end = m.index + m[0].length;
var obj = {
left: {start: start, end: s},
match: {start: s, end: m.index},
right: {start: m.index, end: end},
wholeMatch: {start: start, end: end}
};
pos.push(obj);
if (!g) {
return pos;
}
}
}
}
} while (t && (x.lastIndex = s));
return pos;
};
/**
* matchRecursiveRegExp
*
* (c) 2007 Steven Levithan <stevenlevithan.com>
* MIT License
*
* Accepts a string to search, a left and right format delimiter
* as regex patterns, and optional regex flags. Returns an array
* of matches, allowing nested instances of left/right delimiters.
* Use the "g" flag to return all matches, otherwise only the
* first is returned. Be careful to ensure that the left and
* right format delimiters produce mutually exclusive matches.
* Backreferences are not supported within the right delimiter
* due to how it is internally combined with the left delimiter.
* When matching strings whose format delimiters are unbalanced
* to the left or right, the output is intentionally as a
* conventional regex library with recursion support would
* produce, e.g. "<<x>" and "<x>>" both produce ["x"] when using
* "<" and ">" as the delimiters (both strings contain a single,
* balanced instance of "<x>").
*
* examples:
* matchRecursiveRegExp("test", "\\(", "\\)")
* returns: []
* matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
* returns: ["t<<e>><s>", ""]
* matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
* returns: ["test"]
*/
showdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {
'use strict';
var matchPos = rgxFindMatchPos (str, left, right, flags),
results = [];
for (var i = 0; i < matchPos.length; ++i) {
results.push([
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
]);
}
return results;
};
/**
*
* @param {string} str
* @param {string|function} replacement
* @param {string} left
* @param {string} right
* @param {string} flags
* @returns {string}
*/
showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
'use strict';
if (!showdown.helper.isFunction(replacement)) {
var repStr = replacement;
replacement = function () {
return repStr;
};
}
var matchPos = rgxFindMatchPos(str, left, right, flags),
finalStr = str,
lng = matchPos.length;
if (lng > 0) {
var bits = [];
if (matchPos[0].wholeMatch.start !== 0) {
bits.push(str.slice(0, matchPos[0].wholeMatch.start));
}
for (var i = 0; i < lng; ++i) {
bits.push(
replacement(
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
)
);
if (i < lng - 1) {
bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
}
}
if (matchPos[lng - 1].wholeMatch.end < str.length) {
bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
}
finalStr = bits.join('');
}
return finalStr;
};
/**
* Returns the index within the passed String object of the first occurrence of the specified regex,
* starting the search at fromIndex. Returns -1 if the value is not found.
*
* @param {string} str string to search
* @param {RegExp} regex Regular expression to search
* @param {int} [fromIndex = 0] Index to start the search
* @returns {Number}
* @throws InvalidArgumentError
*/
showdown.helper.regexIndexOf = function (str, regex, fromIndex) {
'use strict';
if (!showdown.helper.isString(str)) {
throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';
}
if (regex instanceof RegExp === false) {
throw 'InvalidArgumentError: second parameter of showdown.helper.regexIndexOf function must be an instance of RegExp';
}
var indexOf = str.substring(fromIndex || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (fromIndex || 0)) : indexOf;
};
/**
* Splits the passed string object at the defined index, and returns an array composed of the two substrings
* @param {string} str string to split
* @param {int} index index to split string at
* @returns {[string,string]}
* @throws InvalidArgumentError
*/
showdown.helper.splitAtIndex = function (str, index) {
'use strict';
if (!showdown.helper.isString(str)) {
throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';
}
return [str.substring(0, index), str.substring(index)];
};
/**
* Obfuscate an e-mail address through the use of Character Entities,
* transforming ASCII characters into their equivalent decimal or hex entities.
*
* Since it has a random component, subsequent calls to this function produce different results
*
* @param {string} mail
* @returns {string}
*/
showdown.helper.encodeEmailAddress = function (mail) {
'use strict';
var encode = [
function (ch) {
return '&#' + ch.charCodeAt(0) + ';';
},
function (ch) {
return '&#x' + ch.charCodeAt(0).toString(16) + ';';
},
function (ch) {
return ch;
}
];
mail = mail.replace(/./g, function (ch) {
if (ch === '@') {
// this *must* be encoded. I insist.
ch = encode[Math.floor(Math.random() * 2)](ch);
} else {
var r = Math.random();
// roughly 10% raw, 45% hex, 45% dec
ch = (
r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
);
}
return ch;
});
return mail;
};
/**
*
* @param str
* @param targetLength
* @param padString
* @returns {string}
*/
showdown.helper.padEnd = function padEnd (str, targetLength, padString) {
'use strict';
/*jshint bitwise: false*/
// eslint-disable-next-line space-infix-ops
targetLength = targetLength>>0; //floor if number or convert non-number to 0;
/*jshint bitwise: true*/
padString = String(padString || ' ');
if (str.length > targetLength) {
return String(str);
} else {
targetLength = targetLength - str.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return String(str) + padString.slice(0,targetLength);
}
};
/**
* POLYFILLS
*/
// use this instead of builtin is undefined for IE8 compatibility
if (typeof (console) === 'undefined') {
console = {
warn: function (msg) {
'use strict';
alert(msg);
},
log: function (msg) {
'use strict';
alert(msg);
},
error: function (msg) {
'use strict';
throw msg;
}
};
}
/**
* Common regexes.
* We declare some common regexes to improve performance
*/
showdown.helper.regexes = {
asteriskDashAndColon: /([*_:~])/g
};
/**
* EMOJIS LIST
*/
showdown.helper.emojis = {
'+1':'\ud83d\udc4d',
'-1':'\ud83d\udc4e',
'100':'\ud83d\udcaf',
'1234':'\ud83d\udd22',
'1st_place_medal':'\ud83e\udd47',
'2nd_place_medal':'\ud83e\udd48',
'3rd_place_medal':'\ud83e\udd49',
'8ball':'\ud83c\udfb1',
'a':'\ud83c\udd70\ufe0f',
'ab':'\ud83c\udd8e',
'abc':'\ud83d\udd24',
'abcd':'\ud83d\udd21',
'accept':'\ud83c\ude51',
'aerial_tramway':'\ud83d\udea1',
'airplane':'\u2708\ufe0f',
'alarm_clock':'\u23f0',
'alembic':'\u2697\ufe0f',
'alien':'\ud83d\udc7d',
'ambulance':'\ud83d\ude91',
'amphora':'\ud83c\udffa',
'anchor':'\u2693\ufe0f',
'angel':'\ud83d\udc7c',
'anger':'\ud83d\udca2',
'angry':'\ud83d\ude20',
'anguished':'\ud83d\ude27',
'ant':'\ud83d\udc1c',
'apple':'\ud83c\udf4e',
'aquarius':'\u2652\ufe0f',
'aries':'\u2648\ufe0f',
'arrow_backward':'\u25c0\ufe0f',
'arrow_double_down':'\u23ec',
'arrow_double_up':'\u23eb',
'arrow_down':'\u2b07\ufe0f',
'arrow_down_small':'\ud83d\udd3d',
'arrow_forward':'\u25b6\ufe0f',
'arrow_heading_down':'\u2935\ufe0f',
'arrow_heading_up':'\u2934\ufe0f',
'arrow_left':'\u2b05\ufe0f',
'arrow_lower_left':'\u2199\ufe0f',
'arrow_lower_right':'\u2198\ufe0f',
'arrow_right':'\u27a1\ufe0f',
'arrow_right_hook':'\u21aa\ufe0f',
'arrow_up':'\u2b06\ufe0f',
'arrow_up_down':'\u2195\ufe0f',
'arrow_up_small':'\ud83d\udd3c',
'arrow_upper_left':'\u2196\ufe0f',
'arrow_upper_right':'\u2197\ufe0f',
'arrows_clockwise':'\ud83d\udd03',
'arrows_counterclockwise':'\ud83d\udd04',
'art':'\ud83c\udfa8',
'articulated_lorry':'\ud83d\ude9b',
'artificial_satellite':'\ud83d\udef0',
'astonished':'\ud83d\ude32',
'athletic_shoe':'\ud83d\udc5f',
'atm':'\ud83c\udfe7',
'atom_symbol':'\u269b\ufe0f',
'avocado':'\ud83e\udd51',
'b':'\ud83c\udd71\ufe0f',
'baby':'\ud83d\udc76',
'baby_bottle':'\ud83c\udf7c',
'baby_chick':'\ud83d\udc24',
'baby_symbol':'\ud83d\udebc',
'back':'\ud83d\udd19',
'bacon':'\ud83e\udd53',
'badminton':'\ud83c\udff8',
'baggage_claim':'\ud83d\udec4',
'baguette_bread':'\ud83e\udd56',
'balance_scale':'\u2696\ufe0f',
'balloon':'\ud83c\udf88',
'ballot_box':'\ud83d\uddf3',
'ballot_box_with_check':'\u2611\ufe0f',
'bamboo':'\ud83c\udf8d',
'banana':'\ud83c\udf4c',
'bangbang':'\u203c\ufe0f',
'bank':'\ud83c\udfe6',
'bar_chart':'\ud83d\udcca',
'barber':'\ud83d\udc88',
'baseball':'\u26be\ufe0f',
'basketball':'\ud83c\udfc0',
'basketball_man':'\u26f9\ufe0f',
'basketball_woman':'\u26f9\ufe0f&zwj;\u2640\ufe0f',
'bat':'\ud83e\udd87',
'bath':'\ud83d\udec0',
'bathtub':'\ud83d\udec1',
'battery':'\ud83d\udd0b',
'beach_umbrella':'\ud83c\udfd6',
'bear':'\ud83d\udc3b',
'bed':'\ud83d\udecf',
'bee':'\ud83d\udc1d',
'beer':'\ud83c\udf7a',
'beers':'\ud83c\udf7b',
'beetle':'\ud83d\udc1e',
'beginner':'\ud83d\udd30',
'bell':'\ud83d\udd14',
'bellhop_bell':'\ud83d\udece',
'bento':'\ud83c\udf71',
'biking_man':'\ud83d\udeb4',
'bike':'\ud83d\udeb2',
'biking_woman':'\ud83d\udeb4&zwj;\u2640\ufe0f',
'bikini':'\ud83d\udc59',
'biohazard':'\u2623\ufe0f',
'bird':'\ud83d\udc26',
'birthday':'\ud83c\udf82',
'black_circle':'\u26ab\ufe0f',
'black_flag':'\ud83c\udff4',
'black_heart':'\ud83d\udda4',
'black_joker':'\ud83c\udccf',
'black_large_square':'\u2b1b\ufe0f',
'black_medium_small_square':'\u25fe\ufe0f',
'black_medium_square':'\u25fc\ufe0f',
'black_nib':'\u2712\ufe0f',
'black_small_square':'\u25aa\ufe0f',
'black_square_button':'\ud83d\udd32',
'blonde_man':'\ud83d\udc71',
'blonde_woman':'\ud83d\udc71&zwj;\u2640\ufe0f',
'blossom':'\ud83c\udf3c',
'blowfish':'\ud83d\udc21',
'blue_book':'\ud83d\udcd8',
'blue_car':'\ud83d\ude99',
'blue_heart':'\ud83d\udc99',
'blush':'\ud83d\ude0a',
'boar':'\ud83d\udc17',
'boat':'\u26f5\ufe0f',
'bomb':'\ud83d\udca3',
'book':'\ud83d\udcd6',
'bookmark':'\ud83d\udd16',
'bookmark_tabs':'\ud83d\udcd1',
'books':'\ud83d\udcda',
'boom':'\ud83d\udca5',
'boot':'\ud83d\udc62',
'bouquet':'\ud83d\udc90',
'bowing_man':'\ud83d\ude47',
'bow_and_arrow':'\ud83c\udff9',
'bowing_woman':'\ud83d\ude47&zwj;\u2640\ufe0f',
'bowling':'\ud83c\udfb3',
'boxing_glove':'\ud83e\udd4a',
'boy':'\ud83d\udc66',
'bread':'\ud83c\udf5e',
'bride_with_veil':'\ud83d\udc70',
'bridge_at_night':'\ud83c\udf09',
'briefcase':'\ud83d\udcbc',
'broken_heart':'\ud83d\udc94',
'bug':'\ud83d\udc1b',
'building_construction':'\ud83c\udfd7',
'bulb':'\ud83d\udca1',
'bullettrain_front':'\ud83d\ude85',
'bullettrain_side':'\ud83d\ude84',
'burrito':'\ud83c\udf2f',
'bus':'\ud83d\ude8c',
'business_suit_levitating':'\ud83d\udd74',
'busstop':'\ud83d\ude8f',
'bust_in_silhouette':'\ud83d\udc64',
'busts_in_silhouette':'\ud83d\udc65',
'butterfly':'\ud83e\udd8b',
'cactus':'\ud83c\udf35',
'cake':'\ud83c\udf70',
'calendar':'\ud83d\udcc6',
'call_me_hand':'\ud83e\udd19',
'calling':'\ud83d\udcf2',
'camel':'\ud83d\udc2b',
'camera':'\ud83d\udcf7',
'camera_flash':'\ud83d\udcf8',
'camping':'\ud83c\udfd5',
'cancer':'\u264b\ufe0f',
'candle':'\ud83d\udd6f',
'candy':'\ud83c\udf6c',
'canoe':'\ud83d\udef6',
'capital_abcd':'\ud83d\udd20',
'capricorn':'\u2651\ufe0f',
'car':'\ud83d\ude97',
'card_file_box':'\ud83d\uddc3',
'card_index':'\ud83d\udcc7',
'card_index_dividers':'\ud83d\uddc2',
'carousel_horse':'\ud83c\udfa0',
'carrot':'\ud83e\udd55',
'cat':'\ud83d\udc31',
'cat2':'\ud83d\udc08',
'cd':'\ud83d\udcbf',
'chains':'\u26d3',
'champagne':'\ud83c\udf7e',
'chart':'\ud83d\udcb9',
'chart_with_downwards_trend':'\ud83d\udcc9',
'chart_with_upwards_trend':'\ud83d\udcc8',
'checkered_flag':'\ud83c\udfc1',
'cheese':'\ud83e\uddc0',
'cherries':'\ud83c\udf52',
'cherry_blossom':'\ud83c\udf38',
'chestnut':'\ud83c\udf30',
'chicken':'\ud83d\udc14',
'children_crossing':'\ud83d\udeb8',
'chipmunk':'\ud83d\udc3f',
'chocolate_bar':'\ud83c\udf6b',
'christmas_tree':'\ud83c\udf84',
'church':'\u26ea\ufe0f',
'cinema':'\ud83c\udfa6',
'circus_tent':'\ud83c\udfaa',
'city_sunrise':'\ud83c\udf07',
'city_sunset':'\ud83c\udf06',
'cityscape':'\ud83c\udfd9',
'cl':'\ud83c\udd91',
'clamp':'\ud83d\udddc',
'clap':'\ud83d\udc4f',
'clapper':'\ud83c\udfac',
'classical_building':'\ud83c\udfdb',
'clinking_glasses':'\ud83e\udd42',
'clipboard':'\ud83d\udccb',
'clock1':'\ud83d\udd50',
'clock10':'\ud83d\udd59',
'clock1030':'\ud83d\udd65',
'clock11':'\ud83d\udd5a',
'clock1130':'\ud83d\udd66',
'clock12':'\ud83d\udd5b',
'clock1230':'\ud83d\udd67',
'clock130':'\ud83d\udd5c',
'clock2':'\ud83d\udd51',
'clock230':'\ud83d\udd5d',
'clock3':'\ud83d\udd52',
'clock330':'\ud83d\udd5e',
'clock4':'\ud83d\udd53',
'clock430':'\ud83d\udd5f',
'clock5':'\ud83d\udd54',
'clock530':'\ud83d\udd60',
'clock6':'\ud83d\udd55',
'clock630':'\ud83d\udd61',
'clock7':'\ud83d\udd56',
'clock730':'\ud83d\udd62',
'clock8':'\ud83d\udd57',
'clock830':'\ud83d\udd63',
'clock9':'\ud83d\udd58',
'clock930':'\ud83d\udd64',
'closed_book':'\ud83d\udcd5',
'closed_lock_with_key':'\ud83d\udd10',
'closed_umbrella':'\ud83c\udf02',
'cloud':'\u2601\ufe0f',
'cloud_with_lightning':'\ud83c\udf29',
'cloud_with_lightning_and_rain':'\u26c8',
'cloud_with_rain':'\ud83c\udf27',
'cloud_with_snow':'\ud83c\udf28',
'clown_face':'\ud83e\udd21',
'clubs':'\u2663\ufe0f',
'cocktail':'\ud83c\udf78',
'coffee':'\u2615\ufe0f',
'coffin':'\u26b0\ufe0f',
'cold_sweat':'\ud83d\ude30',
'comet':'\u2604\ufe0f',
'computer':'\ud83d\udcbb',
'computer_mouse':'\ud83d\uddb1',
'confetti_ball':'\ud83c\udf8a',
'confounded':'\ud83d\ude16',
'confused':'\ud83d\ude15',
'congratulations':'\u3297\ufe0f',
'construction':'\ud83d\udea7',
'construction_worker_man':'\ud83d\udc77',
'construction_worker_woman':'\ud83d\udc77&zwj;\u2640\ufe0f',
'control_knobs':'\ud83c\udf9b',
'convenience_store':'\ud83c\udfea',
'cookie':'\ud83c\udf6a',
'cool':'\ud83c\udd92',
'policeman':'\ud83d\udc6e',
'copyright':'\u00a9\ufe0f',
'corn':'\ud83c\udf3d',
'couch_and_lamp':'\ud83d\udecb',
'couple':'\ud83d\udc6b',
'couple_with_heart_woman_man':'\ud83d\udc91',
'couple_with_heart_man_man':'\ud83d\udc68&zwj;\u2764\ufe0f&zwj;\ud83d\udc68',
'couple_with_heart_woman_woman':'\ud83d\udc69&zwj;\u2764\ufe0f&zwj;\ud83d\udc69',
'couplekiss_man_man':'\ud83d\udc68&zwj;\u2764\ufe0f&zwj;\ud83d\udc8b&zwj;\ud83d\udc68',
'couplekiss_man_woman':'\ud83d\udc8f',
'couplekiss_woman_woman':'\ud83d\udc69&zwj;\u2764\ufe0f&zwj;\ud83d\udc8b&zwj;\ud83d\udc69',
'cow':'\ud83d\udc2e',
'cow2':'\ud83d\udc04',
'cowboy_hat_face':'\ud83e\udd20',
'crab':'\ud83e\udd80',
'crayon':'\ud83d\udd8d',
'credit_card':'\ud83d\udcb3',
'crescent_moon':'\ud83c\udf19',
'cricket':'\ud83c\udfcf',
'crocodile':'\ud83d\udc0a',
'croissant':'\ud83e\udd50',
'crossed_fingers':'\ud83e\udd1e',
'crossed_flags':'\ud83c\udf8c',
'crossed_swords':'\u2694\ufe0f',
'crown':'\ud83d\udc51',
'cry':'\ud83d\ude22',
'crying_cat_face':'\ud83d\ude3f',
'crystal_ball':'\ud83d\udd2e',
'cucumber':'\ud83e\udd52',
'cupid':'\ud83d\udc98',
'curly_loop':'\u27b0',
'currency_exchange':'\ud83d\udcb1',
'curry':'\ud83c\udf5b',
'custard':'\ud83c\udf6e',
'customs':'\ud83d\udec3',
'cyclone':'\ud83c\udf00',
'dagger':'\ud83d\udde1',
'dancer':'\ud83d\udc83',
'dancing_women':'\ud83d\udc6f',
'dancing_men':'\ud83d\udc6f&zwj;\u2642\ufe0f',
'dango':'\ud83c\udf61',
'dark_sunglasses':'\ud83d\udd76',
'dart':'\ud83c\udfaf',
'dash':'\ud83d\udca8',
'date':'\ud83d\udcc5',
'deciduous_tree':'\ud83c\udf33',
'deer':'\ud83e\udd8c',
'department_store':'\ud83c\udfec',
'derelict_house':'\ud83c\udfda',
'desert':'\ud83c\udfdc',
'desert_island':'\ud83c\udfdd',
'desktop_computer':'\ud83d\udda5',
'male_detective':'\ud83d\udd75\ufe0f',
'diamond_shape_with_a_dot_inside':'\ud83d\udca0',
'diamonds':'\u2666\ufe0f',
'disappointed':'\ud83d\ude1e',
'disappointed_relieved':'\ud83d\ude25',
'dizzy':'\ud83d\udcab',
'dizzy_face':'\ud83d\ude35',
'do_not_litter':'\ud83d\udeaf',
'dog':'\ud83d\udc36',
'dog2':'\ud83d\udc15',
'dollar':'\ud83d\udcb5',
'dolls':'\ud83c\udf8e',
'dolphin':'\ud83d\udc2c',
'door':'\ud83d\udeaa',
'doughnut':'\ud83c\udf69',
'dove':'\ud83d\udd4a',
'dragon':'\ud83d\udc09',
'dragon_face':'\ud83d\udc32',
'dress':'\ud83d\udc57',
'dromedary_camel':'\ud83d\udc2a',
'drooling_face':'\ud83e\udd24',
'droplet':'\ud83d\udca7',
'drum':'\ud83e\udd41',
'duck':'\ud83e\udd86',
'dvd':'\ud83d\udcc0',
'e-mail':'\ud83d\udce7',
'eagle':'\ud83e\udd85',
'ear':'\ud83d\udc42',
'ear_of_rice':'\ud83c\udf3e',
'earth_africa':'\ud83c\udf0d',
'earth_americas':'\ud83c\udf0e',
'earth_asia':'\ud83c\udf0f',
'egg':'\ud83e\udd5a',
'eggplant':'\ud83c\udf46',
'eight_pointed_black_star':'\u2734\ufe0f',
'eight_spoked_asterisk':'\u2733\ufe0f',
'electric_plug':'\ud83d\udd0c',
'elephant':'\ud83d\udc18',
'email':'\u2709\ufe0f',
'end':'\ud83d\udd1a',
'envelope_with_arrow':'\ud83d\udce9',
'euro':'\ud83d\udcb6',
'european_castle':'\ud83c\udff0',
'european_post_office':'\ud83c\udfe4',
'evergreen_tree':'\ud83c\udf32',
'exclamation':'\u2757\ufe0f',
'expressionless':'\ud83d\ude11',
'eye':'\ud83d\udc41',
'eye_speech_bubble':'\ud83d\udc41&zwj;\ud83d\udde8',
'eyeglasses':'\ud83d\udc53',
'eyes':'\ud83d\udc40',
'face_with_head_bandage':'\ud83e\udd15',
'face_with_thermometer':'\ud83e\udd12',
'fist_oncoming':'\ud83d\udc4a',
'factory':'\ud83c\udfed',
'fallen_leaf':'\ud83c\udf42',
'family_man_woman_boy':'\ud83d\udc6a',
'family_man_boy':'\ud83d\udc68&zwj;\ud83d\udc66',
'family_man_boy_boy':'\ud83d\udc68&zwj;\ud83d\udc66&zwj;\ud83d\udc66',
'family_man_girl':'\ud83d\udc68&zwj;\ud83d\udc67',
'family_man_girl_boy':'\ud83d\udc68&zwj;\ud83d\udc67&zwj;\ud83d\udc66',
'family_man_girl_girl':'\ud83d\udc68&zwj;\ud83d\udc67&zwj;\ud83d\udc67',
'family_man_man_boy':'\ud83d\udc68&zwj;\ud83d\udc68&zwj;\ud83d\udc66',
'family_man_man_boy_boy':'\ud83d\udc68&zwj;\ud83d\udc68&zwj;\ud83d\udc66&zwj;\ud83d\udc66',
'family_man_man_girl':'\ud83d\udc68&zwj;\ud83d\udc68&zwj;\ud83d\udc67',
'family_man_man_girl_boy':'\ud83d\udc68&zwj;\ud83d\udc68&zwj;\ud83d\udc67&zwj;\ud83d\udc66',
'family_man_man_girl_girl':'\ud83d\udc68&zwj;\ud83d\udc68&zwj;\ud83d\udc67&zwj;\ud83d\udc67',
'family_man_woman_boy_boy':'\ud83d\udc68&zwj;\ud83d\udc69&zwj;\ud83d\udc66&zwj;\ud83d\udc66',
'family_man_woman_girl':'\ud83d\udc68&zwj;\ud83d\udc69&zwj;\ud83d\udc67',
'family_man_woman_girl_boy':'\ud83d\udc68&zwj;\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc66',
'family_man_woman_girl_girl':'\ud83d\udc68&zwj;\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc67',
'family_woman_boy':'\ud83d\udc69&zwj;\ud83d\udc66',
'family_woman_boy_boy':'\ud83d\udc69&zwj;\ud83d\udc66&zwj;\ud83d\udc66',
'family_woman_girl':'\ud83d\udc69&zwj;\ud83d\udc67',
'family_woman_girl_boy':'\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc66',
'family_woman_girl_girl':'\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc67',
'family_woman_woman_boy':'\ud83d\udc69&zwj;\ud83d\udc69&zwj;\ud83d\udc66',
'family_woman_woman_boy_boy':'\ud83d\udc69&zwj;\ud83d\udc69&zwj;\ud83d\udc66&zwj;\ud83d\udc66',
'family_woman_woman_girl':'\ud83d\udc69&zwj;\ud83d\udc69&zwj;\ud83d\udc67',
'family_woman_woman_girl_boy':'\ud83d\udc69&zwj;\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc66',
'family_woman_woman_girl_girl':'\ud83d\udc69&zwj;\ud83d\udc69&zwj;\ud83d\udc67&zwj;\ud83d\udc67',
'fast_forward':'\u23e9',
'fax':'\ud83d\udce0',
'fearful':'\ud83d\ude28',
'feet':'\ud83d\udc3e',
'female_detective':'\ud83d\udd75\ufe0f&zwj;\u2640\ufe0f',
'ferris_wheel':'\ud83c\udfa1',
'ferry':'\u26f4',
'field_hockey':'\ud83c\udfd1',
'file_cabinet':'\ud83d\uddc4',
'file_folder':'\ud83d\udcc1',
'film_projector':'\ud83d\udcfd',
'film_strip':'\ud83c\udf9e',
'fire':'\ud83d\udd25',
'fire_engine':'\ud83d\ude92',
'fireworks':'\ud83c\udf86',
'first_quarter_moon':'\ud83c\udf13',
'first_quarter_moon_with_face':'\ud83c\udf1b',
'fish':'\ud83d\udc1f',
'fish_cake':'\ud83c\udf65',
'fishing_pole_and_fish':'\ud83c\udfa3',
'fist_raised':'\u270a',
'fist_left':'\ud83e\udd1b',
'fist_right':'\ud83e\udd1c',
'flags':'\ud83c\udf8f',
'flashlight':'\ud83d\udd26',
'fleur_de_lis':'\u269c\ufe0f',
'flight_arrival':'\ud83d\udeec',
'flight_departure':'\ud83d\udeeb',
'floppy_disk':'\ud83d\udcbe',
'flower_playing_cards':'\ud83c\udfb4',
'flushed':'\ud83d\ude33',
'fog':'\ud83c\udf2b',
'foggy':'\ud83c\udf01',
'football':'\ud83c\udfc8',
'footprints':'\ud83d\udc63',
'fork_and_knife':'\ud83c\udf74',
'fountain':'\u26f2\ufe0f',
'fountain_pen':'\ud83d\udd8b',
'four_leaf_clover':'\ud83c\udf40',
'fox_face':'\ud83e\udd8a',
'framed_picture':'\ud83d\uddbc',
'free':'\ud83c\udd93',
'fried_egg':'\ud83c\udf73',
'fried_shrimp':'\ud83c\udf64',
'fries':'\ud83c\udf5f',
'frog':'\ud83d\udc38',
'frowning':'\ud83d\ude26',
'frowning_face':'\u2639\ufe0f',
'frowning_man':'\ud83d\ude4d&zwj;\u2642\ufe0f',
'frowning_woman':'\ud83d\ude4d',
'middle_finger':'\ud83d\udd95',
'fuelpump':'\u26fd\ufe0f',
'full_moon':'\ud83c\udf15',
'full_moon_with_face':'\ud83c\udf1d',
'funeral_urn':'\u26b1\ufe0f',
'game_die':'\ud83c\udfb2',
'gear':'\u2699\ufe0f',
'gem':'\ud83d\udc8e',
'gemini':'\u264a\ufe0f',
'ghost':'\ud83d\udc7b',
'gift':'\ud83c\udf81',
'gift_heart':'\ud83d\udc9d',
'girl':'\ud83d\udc67',
'globe_with_meridians':'\ud83c\udf10',
'goal_net':'\ud83e\udd45',
'goat':'\ud83d\udc10',
'golf':'\u26f3\ufe0f',
'golfing_man':'\ud83c\udfcc\ufe0f',
'golfing_woman':'\ud83c\udfcc\ufe0f&zwj;\u2640\ufe0f',
'gorilla':'\ud83e\udd8d',
'grapes':'\ud83c\udf47',
'green_apple':'\ud83c\udf4f',
'green_book':'\ud83d\udcd7',
'green_heart':'\ud83d\udc9a',
'green_salad':'\ud83e\udd57',
'grey_exclamation':'\u2755',
'grey_question':'\u2754',
'grimacing':'\ud83d\ude2c',
'grin':'\ud83d\ude01',
'grinning':'\ud83d\ude00',
'guardsman':'\ud83d\udc82',
'guardswoman':'\ud83d\udc82&zwj;\u2640\ufe0f',
'guitar':'\ud83c\udfb8',
'gun':'\ud83d\udd2b',
'haircut_woman':'\ud83d\udc87',
'haircut_man':'\ud83d\udc87&zwj;\u2642\ufe0f',
'hamburger':'\ud83c\udf54',
'hammer':'\ud83d\udd28',
'hammer_and_pick':'\u2692',
'hammer_and_wrench':'\ud83d\udee0',
'hamster':'\ud83d\udc39',
'hand':'\u270b',
'handbag':'\ud83d\udc5c',
'handshake':'\ud83e\udd1d',
'hankey':'\ud83d\udca9',
'hatched_chick':'\ud83d\udc25',
'hatching_chick':'\ud83d\udc23',
'headphones':'\ud83c\udfa7',
'hear_no_evil':'\ud83d\ude49',
'heart':'\u2764\ufe0f',
'heart_decoration':'\ud83d\udc9f',
'heart_eyes':'\ud83d\ude0d',
'heart_eyes_cat':'\ud83d\ude3b',
'heartbeat':'\ud83d\udc93',
'heartpulse':'\ud83d\udc97',
'hearts':'\u2665\ufe0f',
'heavy_check_mark':'\u2714\ufe0f',
'heavy_division_sign':'\u2797',
'heavy_dollar_sign':'\ud83d\udcb2',
'heavy_heart_exclamation':'\u2763\ufe0f',
'heavy_minus_sign':'\u2796',
'heavy_multiplication_x':'\u2716\ufe0f',
'heavy_plus_sign':'\u2795',
'helicopter':'\ud83d\ude81',
'herb':'\ud83c\udf3f',
'hibiscus':'\ud83c\udf3a',
'high_brightness':'\ud83d\udd06',
'high_heel':'\ud83d\udc60',
'hocho':'\ud83d\udd2a',
'hole':'\ud83d\udd73',
'honey_pot':'\ud83c\udf6f',
'horse':'\ud83d\udc34',
'horse_racing':'\ud83c\udfc7',
'hospital':'\ud83c\udfe5',
'hot_pepper':'\ud83c\udf36',
'hotdog':'\ud83c\udf2d',
'hotel':'\ud83c\udfe8',
'hotsprings':'\u2668\ufe0f',
'hourglass':'\u231b\ufe0f',
'hourglass_flowing_sand':'\u23f3',
'house':'\ud83c\udfe0',
'house_with_garden':'\ud83c\udfe1',
'houses':'\ud83c\udfd8',
'hugs':'\ud83e\udd17',
'hushed':'\ud83d\ude2f',
'ice_cream':'\ud83c\udf68',
'ice_hockey':'\ud83c\udfd2',
'ice_skate':'\u26f8',
'icecream':'\ud83c\udf66',
'id':'\ud83c\udd94',
'ideograph_advantage':'\ud83c\ude50',
'imp':'\ud83d\udc7f',
'inbox_tray':'\ud83d\udce5',
'incoming_envelope':'\ud83d\udce8',
'tipping_hand_woman':'\ud83d\udc81',
'information_source':'\u2139\ufe0f',
'innocent':'\ud83d\ude07',
'interrobang':'\u2049\ufe0f',
'iphone':'\ud83d\udcf1',
'izakaya_lantern':'\ud83c\udfee',
'jack_o_lantern':'\ud83c\udf83',
'japan':'\ud83d\uddfe',
'japanese_castle':'\ud83c\udfef',
'japanese_goblin':'\ud83d\udc7a',
'japanese_ogre':'\ud83d\udc79',
'jeans':'\ud83d\udc56',
'joy':'\ud83d\ude02',
'joy_cat':'\ud83d\ude39',
'joystick':'\ud83d\udd79',
'kaaba':'\ud83d\udd4b',
'key':'\ud83d\udd11',
'keyboard':'\u2328\ufe0f',
'keycap_ten':'\ud83d\udd1f',
'kick_scooter':'\ud83d\udef4',
'kimono':'\ud83d\udc58',
'kiss':'\ud83d\udc8b',
'kissing':'\ud83d\ude17',
'kissing_cat':'\ud83d\ude3d',
'kissing_closed_eyes':'\ud83d\ude1a',
'kissing_heart':'\ud83d\ude18',
'kissing_smiling_eyes':'\ud83d\ude19',
'kiwi_fruit':'\ud83e\udd5d',
'koala':'\ud83d\udc28',
'koko':'\ud83c\ude01',
'label':'\ud83c\udff7',
'large_blue_circle':'\ud83d\udd35',
'large_blue_diamond':'\ud83d\udd37',
'large_orange_diamond':'\ud83d\udd36',
'last_quarter_moon':'\ud83c\udf17',
'last_quarter_moon_with_face':'\ud83c\udf1c',
'latin_cross':'\u271d\ufe0f',
'laughing':'\ud83d\ude06',
'leaves':'\ud83c\udf43',
'ledger':'\ud83d\udcd2',
'left_luggage':'\ud83d\udec5',
'left_right_arrow':'\u2194\ufe0f',
'leftwards_arrow_with_hook':'\u21a9\ufe0f',
'lemon':'\ud83c\udf4b',
'leo':'\u264c\ufe0f',
'leopard':'\ud83d\udc06',
'level_slider':'\ud83c\udf9a',
'libra':'\u264e\ufe0f',
'light_rail':'\ud83d\ude88',
'link':'\ud83d\udd17',
'lion':'\ud83e\udd81',
'lips':'\ud83d\udc44',
'lipstick':'\ud83d\udc84',
'lizard':'\ud83e\udd8e',
'lock':'\ud83d\udd12',
'lock_with_ink_pen':'\ud83d\udd0f',
'lollipop':'\ud83c\udf6d',
'loop':'\u27bf',
'loud_sound':'\ud83d\udd0a',
'loudspeaker':'\ud83d\udce2',
'love_hotel':'\ud83c\udfe9',
'love_letter':'\ud83d\udc8c',
'low_brightness':'\ud83d\udd05',
'lying_face':'\ud83e\udd25',
'm':'\u24c2\ufe0f',
'mag':'\ud83d\udd0d',
'mag_right':'\ud83d\udd0e',
'mahjong':'\ud83c\udc04\ufe0f',
'mailbox':'\ud83d\udceb',
'mailbox_closed':'\ud83d\udcea',
'mailbox_with_mail':'\ud83d\udcec',
'mailbox_with_no_mail':'\ud83d\udced',
'man':'\ud83d\udc68',
'man_artist':'\ud83d\udc68&zwj;\ud83c\udfa8',
'man_astronaut':'\ud83d\udc68&zwj;\ud83d\ude80',
'man_cartwheeling':'\ud83e\udd38&zwj;\u2642\ufe0f',
'man_cook':'\ud83d\udc68&zwj;\ud83c\udf73',
'man_dancing':'\ud83d\udd7a',
'man_facepalming':'\ud83e\udd26&zwj;\u2642\ufe0f',
'man_factory_worker':'\ud83d\udc68&zwj;\ud83c\udfed',
'man_farmer':'\ud83d\udc68&zwj;\ud83c\udf3e',
'man_firefighter':'\ud83d\udc68&zwj;\ud83d\ude92',
'man_health_worker':'\ud83d\udc68&zwj;\u2695\ufe0f',
'man_in_tuxedo':'\ud83e\udd35',
'man_judge':'\ud83d\udc68&zwj;\u2696\ufe0f',
'man_juggling':'\ud83e\udd39&zwj;\u2642\ufe0f',
'man_mechanic':'\ud83d\udc68&zwj;\ud83d\udd27',
'man_office_worker':'\ud83d\udc68&zwj;\ud83d\udcbc',
'man_pilot':'\ud83d\udc68&zwj;\u2708\ufe0f',
'man_playing_handball':'\ud83e\udd3e&zwj;\u2642\ufe0f',
'man_playing_water_polo':'\ud83e\udd3d&zwj;\u2642\ufe0f',
'man_scientist':'\ud83d\udc68&zwj;\ud83d\udd2c',
'man_shrugging':'\ud83e\udd37&zwj;\u2642\ufe0f',
'man_singer':'\ud83d\udc68&zwj;\ud83c\udfa4',
'man_student':'\ud83d\udc68&zwj;\ud83c\udf93',
'man_teacher':'\ud83d\udc68&zwj;\ud83c\udfeb',
'man_technologist':'\ud83d\udc68&zwj;\ud83d\udcbb',
'man_with_gua_pi_mao':'\ud83d\udc72',
'man_with_turban':'\ud83d\udc73',
'tangerine':'\ud83c\udf4a',
'mans_shoe':'\ud83d\udc5e',
'mantelpiece_clock':'\ud83d\udd70',
'maple_leaf':'\ud83c\udf41',
'martial_arts_uniform':'\ud83e\udd4b',
'mask':'\ud83d\ude37',
'massage_woman':'\ud83d\udc86',
'massage_man':'\ud83d\udc86&zwj;\u2642\ufe0f',
'meat_on_bone':'\ud83c\udf56',
'medal_military':'\ud83c\udf96',
'medal_sports':'\ud83c\udfc5',
'mega':'\ud83d\udce3',
'melon':'\ud83c\udf48',
'memo':'\ud83d\udcdd',
'men_wrestling':'\ud83e\udd3c&zwj;\u2642\ufe0f',
'menorah':'\ud83d\udd4e',
'mens':'\ud83d\udeb9',
'metal':'\ud83e\udd18',
'metro':'\ud83d\ude87',
'microphone':'\ud83c\udfa4',
'microscope':'\ud83d\udd2c',
'milk_glass':'\ud83e\udd5b',
'milky_way':'\ud83c\udf0c',
'minibus':'\ud83d\ude90',
'minidisc':'\ud83d\udcbd',
'mobile_phone_off':'\ud83d\udcf4',
'money_mouth_face':'\ud83e\udd11',
'money_with_wings':'\ud83d\udcb8',
'moneybag':'\ud83d\udcb0',
'monkey':'\ud83d\udc12',
'monkey_face':'\ud83d\udc35',
'monorail':'\ud83d\ude9d',
'moon':'\ud83c\udf14',
'mortar_board':'\ud83c\udf93',
'mosque':'\ud83d\udd4c',
'motor_boat':'\ud83d\udee5',
'motor_scooter':'\ud83d\udef5',
'motorcycle':'\ud83c\udfcd',
'motorway':'\ud83d\udee3',
'mount_fuji':'\ud83d\uddfb',
'mountain':'\u26f0',
'mountain_biking_man':'\ud83d\udeb5',
'mountain_biking_woman':'\ud83d\udeb5&zwj;\u2640\ufe0f',
'mountain_cableway':'\ud83d\udea0',
'mountain_railway':'\ud83d\ude9e',
'mountain_snow':'\ud83c\udfd4',
'mouse':'\ud83d\udc2d',
'mouse2':'\ud83d\udc01',
'movie_camera':'\ud83c\udfa5',
'moyai':'\ud83d\uddff',
'mrs_claus':'\ud83e\udd36',
'muscle':'\ud83d\udcaa',
'mushroom':'\ud83c\udf44',
'musical_keyboard':'\ud83c\udfb9',
'musical_note':'\ud83c\udfb5',
'musical_score':'\ud83c\udfbc',
'mute':'\ud83d\udd07',
'nail_care':'\ud83d\udc85',
'name_badge':'\ud83d\udcdb',
'national_park':'\ud83c\udfde',
'nauseated_face':'\ud83e\udd22',
'necktie':'\ud83d\udc54',
'negative_squared_cross_mark':'\u274e',
'nerd_face':'\ud83e\udd13',
'neutral_face':'\ud83d\ude10',
'new':'\ud83c\udd95',
'new_moon':'\ud83c\udf11',
'new_moon_with_face':'\ud83c\udf1a',
'newspaper':'\ud83d\udcf0',
'newspaper_roll':'\ud83d\uddde',
'next_track_button':'\u23ed',
'ng':'\ud83c\udd96',
'no_good_man':'\ud83d\ude45&zwj;\u2642\ufe0f',
'no_good_woman':'\ud83d\ude45',
'night_with_stars':'\ud83c\udf03',
'no_bell':'\ud83d\udd15',
'no_bicycles':'\ud83d\udeb3',
'no_entry':'\u26d4\ufe0f',
'no_entry_sign':'\ud83d\udeab',
'no_mobile_phones':'\ud83d\udcf5',
'no_mouth':'\ud83d\ude36',
'no_pedestrians':'\ud83d\udeb7',
'no_smoking':'\ud83d\udead',
'non-potable_water':'\ud83d\udeb1',
'nose':'\ud83d\udc43',
'notebook':'\ud83d\udcd3',
'notebook_with_decorative_cover':'\ud83d\udcd4',
'notes':'\ud83c\udfb6',
'nut_and_bolt':'\ud83d\udd29',
'o':'\u2b55\ufe0f',
'o2':'\ud83c\udd7e\ufe0f',
'ocean':'\ud83c\udf0a',
'octopus':'\ud83d\udc19',
'oden':'\ud83c\udf62',
'office':'\ud83c\udfe2',
'oil_drum':'\ud83d\udee2',
'ok':'\ud83c\udd97',
'ok_hand':'\ud83d\udc4c',
'ok_man':'\ud83d\ude46&zwj;\u2642\ufe0f',
'ok_woman':'\ud83d\ude46',
'old_key':'\ud83d\udddd',
'older_man':'\ud83d\udc74',
'older_woman':'\ud83d\udc75',
'om':'\ud83d\udd49',
'on':'\ud83d\udd1b',
'oncoming_automobile':'\ud83d\ude98',
'oncoming_bus':'\ud83d\ude8d',
'oncoming_police_car':'\ud83d\ude94',
'oncoming_taxi':'\ud83d\ude96',
'open_file_folder':'\ud83d\udcc2',
'open_hands':'\ud83d\udc50',
'open_mouth':'\ud83d\ude2e',
'open_umbrella':'\u2602\ufe0f',
'ophiuchus':'\u26ce',
'orange_book':'\ud83d\udcd9',
'orthodox_cross':'\u2626\ufe0f',
'outbox_tray':'\ud83d\udce4',
'owl':'\ud83e\udd89',
'ox':'\ud83d\udc02',
'package':'\ud83d\udce6',
'page_facing_up':'\ud83d\udcc4',
'page_with_curl':'\ud83d\udcc3',
'pager':'\ud83d\udcdf',
'paintbrush':'\ud83d\udd8c',
'palm_tree':'\ud83c\udf34',
'pancakes':'\ud83e\udd5e',
'panda_face':'\ud83d\udc3c',
'paperclip':'\ud83d\udcce',
'paperclips':'\ud83d\udd87',
'parasol_on_ground':'\u26f1',
'parking':'\ud83c\udd7f\ufe0f',
'part_alternation_mark':'\u303d\ufe0f',
'partly_sunny':'\u26c5\ufe0f',
'passenger_ship':'\ud83d\udef3',
'passport_control':'\ud83d\udec2',
'pause_button':'\u23f8',
'peace_symbol':'\u262e\ufe0f',
'peach':'\ud83c\udf51',
'peanuts':'\ud83e\udd5c',
'pear':'\ud83c\udf50',
'pen':'\ud83d\udd8a',
'pencil2':'\u270f\ufe0f',
'penguin':'\ud83d\udc27',
'pensive':'\ud83d\ude14',
'performing_arts':'\ud83c\udfad',
'persevere':'\ud83d\ude23',
'person_fencing':'\ud83e\udd3a',
'pouting_woman':'\ud83d\ude4e',
'phone':'\u260e\ufe0f',
'pick':'\u26cf',
'pig':'\ud83d\udc37',
'pig2':'\ud83d\udc16',
'pig_nose':'\ud83d\udc3d',
'pill':'\ud83d\udc8a',
'pineapple':'\ud83c\udf4d',
'ping_pong':'\ud83c\udfd3',
'pisces':'\u2653\ufe0f',
'pizza':'\ud83c\udf55',
'place_of_worship':'\ud83d\uded0',
'plate_with_cutlery':'\ud83c\udf7d',
'play_or_pause_button':'\u23ef',
'point_down':'\ud83d\udc47',
'point_left':'\ud83d\udc48',
'point_right':'\ud83d\udc49',
'point_up':'\u261d\ufe0f',
'point_up_2':'\ud83d\udc46',
'police_car':'\ud83d\ude93',
'policewoman':'\ud83d\udc6e&zwj;\u2640\ufe0f',
'poodle':'\ud83d\udc29',
'popcorn':'\ud83c\udf7f',
'post_office':'\ud83c\udfe3',
'postal_horn':'\ud83d\udcef',
'postbox':'\ud83d\udcee',
'potable_water':'\ud83d\udeb0',
'potato':'\ud83e\udd54',
'pouch':'\ud83d\udc5d',
'poultry_leg':'\ud83c\udf57',
'pound':'\ud83d\udcb7',
'rage':'\ud83d\ude21',
'pouting_cat':'\ud83d\ude3e',
'pouting_man':'\ud83d\ude4e&zwj;\u2642\ufe0f',
'pray':'\ud83d\ude4f',
'prayer_beads':'\ud83d\udcff',
'pregnant_woman':'\ud83e\udd30',
'previous_track_button':'\u23ee',
'prince':'\ud83e\udd34',
'princess':'\ud83d\udc78',
'printer':'\ud83d\udda8',
'purple_heart':'\ud83d\udc9c',
'purse':'\ud83d\udc5b',
'pushpin':'\ud83d\udccc',
'put_litter_in_its_place':'\ud83d\udeae',
'question':'\u2753',
'rabbit':'\ud83d\udc30',
'rabbit2':'\ud83d\udc07',
'racehorse':'\ud83d\udc0e',
'racing_car':'\ud83c\udfce',
'radio':'\ud83d\udcfb',
'radio_button':'\ud83d\udd18',
'radioactive':'\u2622\ufe0f',
'railway_car':'\ud83d\ude83',
'railway_track':'\ud83d\udee4',
'rainbow':'\ud83c\udf08',
'rainbow_flag':'\ud83c\udff3\ufe0f&zwj;\ud83c\udf08',
'raised_back_of_hand':'\ud83e\udd1a',
'raised_hand_with_fingers_splayed':'\ud83d\udd90',
'raised_hands':'\ud83d\ude4c',
'raising_hand_woman':'\ud83d\ude4b',
'raising_hand_man':'\ud83d\ude4b&zwj;\u2642\ufe0f',
'ram':'\ud83d\udc0f',
'ramen':'\ud83c\udf5c',
'rat':'\ud83d\udc00',
'record_button':'\u23fa',
'recycle':'\u267b\ufe0f',
'red_circle':'\ud83d\udd34',
'registered':'\u00ae\ufe0f',
'relaxed':'\u263a\ufe0f',
'relieved':'\ud83d\ude0c',
'reminder_ribbon':'\ud83c\udf97',
'repeat':'\ud83d\udd01',
'repeat_one':'\ud83d\udd02',
'rescue_worker_helmet':'\u26d1',
'restroom':'\ud83d\udebb',
'revolving_hearts':'\ud83d\udc9e',
'rewind':'\u23ea',
'rhinoceros':'\ud83e\udd8f',
'ribbon':'\ud83c\udf80',
'rice':'\ud83c\udf5a',
'rice_ball':'\ud83c\udf59',
'rice_cracker':'\ud83c\udf58',
'rice_scene':'\ud83c\udf91',
'right_anger_bubble':'\ud83d\uddef',
'ring':'\ud83d\udc8d',
'robot':'\ud83e\udd16',
'rocket':'\ud83d\ude80',
'rofl':'\ud83e\udd23',
'roll_eyes':'\ud83d\ude44',
'roller_coaster':'\ud83c\udfa2',
'rooster':'\ud83d\udc13',
'rose':'\ud83c\udf39',
'rosette':'\ud83c\udff5',
'rotating_light':'\ud83d\udea8',
'round_pushpin':'\ud83d\udccd',
'rowing_man':'\ud83d\udea3',
'rowing_woman':'\ud83d\udea3&zwj;\u2640\ufe0f',
'rugby_football':'\ud83c\udfc9',
'running_man':'\ud83c\udfc3',
'running_shirt_with_sash':'\ud83c\udfbd',
'running_woman':'\ud83c\udfc3&zwj;\u2640\ufe0f',
'sa':'\ud83c\ude02\ufe0f',
'sagittarius':'\u2650\ufe0f',
'sake':'\ud83c\udf76',
'sandal':'\ud83d\udc61',
'santa':'\ud83c\udf85',
'satellite':'\ud83d\udce1',
'saxophone':'\ud83c\udfb7',
'school':'\ud83c\udfeb',
'school_satchel':'\ud83c\udf92',
'scissors':'\u2702\ufe0f',
'scorpion':'\ud83e\udd82',
'scorpius':'\u264f\ufe0f',
'scream':'\ud83d\ude31',
'scream_cat':'\ud83d\ude40',
'scroll':'\ud83d\udcdc',
'seat':'\ud83d\udcba',
'secret':'\u3299\ufe0f',
'see_no_evil':'\ud83d\ude48',
'seedling':'\ud83c\udf31',
'selfie':'\ud83e\udd33',
'shallow_pan_of_food':'\ud83e\udd58',
'shamrock':'\u2618\ufe0f',
'shark':'\ud83e\udd88',
'shaved_ice':'\ud83c\udf67',
'sheep':'\ud83d\udc11',
'shell':'\ud83d\udc1a',
'shield':'\ud83d\udee1',
'shinto_shrine':'\u26e9',
'ship':'\ud83d\udea2',
'shirt':'\ud83d\udc55',
'shopping':'\ud83d\udecd',
'shopping_cart':'\ud83d\uded2',
'shower':'\ud83d\udebf',
'shrimp':'\ud83e\udd90',
'signal_strength':'\ud83d\udcf6',
'six_pointed_star':'\ud83d\udd2f',
'ski':'\ud83c\udfbf',
'skier':'\u26f7',
'skull':'\ud83d\udc80',
'skull_and_crossbones':'\u2620\ufe0f',
'sleeping':'\ud83d\ude34',
'sleeping_bed':'\ud83d\udecc',
'sleepy':'\ud83d\ude2a',
'slightly_frowning_face':'\ud83d\ude41',
'slightly_smiling_face':'\ud83d\ude42',
'slot_machine':'\ud83c\udfb0',
'small_airplane':'\ud83d\udee9',
'small_blue_diamond':'\ud83d\udd39',
'small_orange_diamond':'\ud83d\udd38',
'small_red_triangle':'\ud83d\udd3a',
'small_red_triangle_down':'\ud83d\udd3b',
'smile':'\ud83d\ude04',
'smile_cat':'\ud83d\ude38',
'smiley':'\ud83d\ude03',
'smiley_cat':'\ud83d\ude3a',
'smiling_imp':'\ud83d\ude08',
'smirk':'\ud83d\ude0f',
'smirk_cat':'\ud83d\ude3c',
'smoking':'\ud83d\udeac',
'snail':'\ud83d\udc0c',
'snake':'\ud83d\udc0d',
'sneezing_face':'\ud83e\udd27',
'snowboarder':'\ud83c\udfc2',
'snowflake':'\u2744\ufe0f',
'snowman':'\u26c4\ufe0f',
'snowman_with_snow':'\u2603\ufe0f',
'sob':'\ud83d\ude2d',
'soccer':'\u26bd\ufe0f',
'soon':'\ud83d\udd1c',
'sos':'\ud83c\udd98',
'sound':'\ud83d\udd09',
'space_invader':'\ud83d\udc7e',
'spades':'\u2660\ufe0f',
'spaghetti':'\ud83c\udf5d',
'sparkle':'\u2747\ufe0f',
'sparkler':'\ud83c\udf87',
'sparkles':'\u2728',
'sparkling_heart':'\ud83d\udc96',
'speak_no_evil':'\ud83d\ude4a',
'speaker':'\ud83d\udd08',
'speaking_head':'\ud83d\udde3',
'speech_balloon':'\ud83d\udcac',
'speedboat':'\ud83d\udea4',
'spider':'\ud83d\udd77',
'spider_web':'\ud83d\udd78',
'spiral_calendar':'\ud83d\uddd3',
'spiral_notepad':'\ud83d\uddd2',
'spoon':'\ud83e\udd44',
'squid':'\ud83e\udd91',
'stadium':'\ud83c\udfdf',
'star':'\u2b50\ufe0f',
'star2':'\ud83c\udf1f',
'star_and_crescent':'\u262a\ufe0f',
'star_of_david':'\u2721\ufe0f',
'stars':'\ud83c\udf20',
'station':'\ud83d\ude89',
'statue_of_liberty':'\ud83d\uddfd',
'steam_locomotive':'\ud83d\ude82',
'stew':'\ud83c\udf72',
'stop_button':'\u23f9',
'stop_sign':'\ud83d\uded1',
'stopwatch':'\u23f1',
'straight_ruler':'\ud83d\udccf',
'strawberry':'\ud83c\udf53',
'stuck_out_tongue':'\ud83d\ude1b',
'stuck_out_tongue_closed_eyes':'\ud83d\ude1d',
'stuck_out_tongue_winking_eye':'\ud83d\ude1c',
'studio_microphone':'\ud83c\udf99',
'stuffed_flatbread':'\ud83e\udd59',
'sun_behind_large_cloud':'\ud83c\udf25',
'sun_behind_rain_cloud':'\ud83c\udf26',
'sun_behind_small_cloud':'\ud83c\udf24',
'sun_with_face':'\ud83c\udf1e',
'sunflower':'\ud83c\udf3b',
'sunglasses':'\ud83d\ude0e',
'sunny':'\u2600\ufe0f',
'sunrise':'\ud83c\udf05',
'sunrise_over_mountains':'\ud83c\udf04',
'surfing_man':'\ud83c\udfc4',
'surfing_woman':'\ud83c\udfc4&zwj;\u2640\ufe0f',
'sushi':'\ud83c\udf63',
'suspension_railway':'\ud83d\ude9f',
'sweat':'\ud83d\ude13',
'sweat_drops':'\ud83d\udca6',
'sweat_smile':'\ud83d\ude05',
'sweet_potato':'\ud83c\udf60',
'swimming_man':'\ud83c\udfca',
'swimming_woman':'\ud83c\udfca&zwj;\u2640\ufe0f',
'symbols':'\ud83d\udd23',
'synagogue':'\ud83d\udd4d',
'syringe':'\ud83d\udc89',
'taco':'\ud83c\udf2e',
'tada':'\ud83c\udf89',
'tanabata_tree':'\ud83c\udf8b',
'taurus':'\u2649\ufe0f',
'taxi':'\ud83d\ude95',
'tea':'\ud83c\udf75',
'telephone_receiver':'\ud83d\udcde',
'telescope':'\ud83d\udd2d',
'tennis':'\ud83c\udfbe',
'tent':'\u26fa\ufe0f',
'thermometer':'\ud83c\udf21',
'thinking':'\ud83e\udd14',
'thought_balloon':'\ud83d\udcad',
'ticket':'\ud83c\udfab',
'tickets':'\ud83c\udf9f',
'tiger':'\ud83d\udc2f',
'tiger2':'\ud83d\udc05',
'timer_clock':'\u23f2',
'tipping_hand_man':'\ud83d\udc81&zwj;\u2642\ufe0f',
'tired_face':'\ud83d\ude2b',
'tm':'\u2122\ufe0f',
'toilet':'\ud83d\udebd',
'tokyo_tower':'\ud83d\uddfc',
'tomato':'\ud83c\udf45',
'tongue':'\ud83d\udc45',
'top':'\ud83d\udd1d',
'tophat':'\ud83c\udfa9',
'tornado':'\ud83c\udf2a',
'trackball':'\ud83d\uddb2',
'tractor':'\ud83d\ude9c',
'traffic_light':'\ud83d\udea5',
'train':'\ud83d\ude8b',
'train2':'\ud83d\ude86',
'tram':'\ud83d\ude8a',
'triangular_flag_on_post':'\ud83d\udea9',
'triangular_ruler':'\ud83d\udcd0',
'trident':'\ud83d\udd31',
'triumph':'\ud83d\ude24',
'trolleybus':'\ud83d\ude8e',
'trophy':'\ud83c\udfc6',
'tropical_drink':'\ud83c\udf79',
'tropical_fish':'\ud83d\udc20',
'truck':'\ud83d\ude9a',
'trumpet':'\ud83c\udfba',
'tulip':'\ud83c\udf37',
'tumbler_glass':'\ud83e\udd43',
'turkey':'\ud83e\udd83',
'turtle':'\ud83d\udc22',
'tv':'\ud83d\udcfa',
'twisted_rightwards_arrows':'\ud83d\udd00',
'two_hearts':'\ud83d\udc95',
'two_men_holding_hands':'\ud83d\udc6c',
'two_women_holding_hands':'\ud83d\udc6d',
'u5272':'\ud83c\ude39',
'u5408':'\ud83c\ude34',
'u55b6':'\ud83c\ude3a',
'u6307':'\ud83c\ude2f\ufe0f',
'u6708':'\ud83c\ude37\ufe0f',
'u6709':'\ud83c\ude36',
'u6e80':'\ud83c\ude35',
'u7121':'\ud83c\ude1a\ufe0f',
'u7533':'\ud83c\ude38',
'u7981':'\ud83c\ude32',
'u7a7a':'\ud83c\ude33',
'umbrella':'\u2614\ufe0f',
'unamused':'\ud83d\ude12',
'underage':'\ud83d\udd1e',
'unicorn':'\ud83e\udd84',
'unlock':'\ud83d\udd13',
'up':'\ud83c\udd99',
'upside_down_face':'\ud83d\ude43',
'v':'\u270c\ufe0f',
'vertical_traffic_light':'\ud83d\udea6',
'vhs':'\ud83d\udcfc',
'vibration_mode':'\ud83d\udcf3',
'video_camera':'\ud83d\udcf9',
'video_game':'\ud83c\udfae',
'violin':'\ud83c\udfbb',
'virgo':'\u264d\ufe0f',
'volcano':'\ud83c\udf0b',
'volleyball':'\ud83c\udfd0',
'vs':'\ud83c\udd9a',
'vulcan_salute':'\ud83d\udd96',
'walking_man':'\ud83d\udeb6',
'walking_woman':'\ud83d\udeb6&zwj;\u2640\ufe0f',
'waning_crescent_moon':'\ud83c\udf18',
'waning_gibbous_moon':'\ud83c\udf16',
'warning':'\u26a0\ufe0f',
'wastebasket':'\ud83d\uddd1',
'watch':'\u231a\ufe0f',
'water_buffalo':'\ud83d\udc03',
'watermelon':'\ud83c\udf49',
'wave':'\ud83d\udc4b',
'wavy_dash':'\u3030\ufe0f',
'waxing_crescent_moon':'\ud83c\udf12',
'wc':'\ud83d\udebe',
'weary':'\ud83d\ude29',
'wedding':'\ud83d\udc92',
'weight_lifting_man':'\ud83c\udfcb\ufe0f',
'weight_lifting_woman':'\ud83c\udfcb\ufe0f&zwj;\u2640\ufe0f',
'whale':'\ud83d\udc33',
'whale2':'\ud83d\udc0b',
'wheel_of_dharma':'\u2638\ufe0f',
'wheelchair':'\u267f\ufe0f',
'white_check_mark':'\u2705',
'white_circle':'\u26aa\ufe0f',
'white_flag':'\ud83c\udff3\ufe0f',
'white_flower':'\ud83d\udcae',
'white_large_square':'\u2b1c\ufe0f',
'white_medium_small_square':'\u25fd\ufe0f',
'white_medium_square':'\u25fb\ufe0f',
'white_small_square':'\u25ab\ufe0f',
'white_square_button':'\ud83d\udd33',
'wilted_flower':'\ud83e\udd40',
'wind_chime':'\ud83c\udf90',
'wind_face':'\ud83c\udf2c',
'wine_glass':'\ud83c\udf77',
'wink':'\ud83d\ude09',
'wolf':'\ud83d\udc3a',
'woman':'\ud83d\udc69',
'woman_artist':'\ud83d\udc69&zwj;\ud83c\udfa8',
'woman_astronaut':'\ud83d\udc69&zwj;\ud83d\ude80',
'woman_cartwheeling':'\ud83e\udd38&zwj;\u2640\ufe0f',
'woman_cook':'\ud83d\udc69&zwj;\ud83c\udf73',
'woman_facepalming':'\ud83e\udd26&zwj;\u2640\ufe0f',
'woman_factory_worker':'\ud83d\udc69&zwj;\ud83c\udfed',
'woman_farmer':'\ud83d\udc69&zwj;\ud83c\udf3e',
'woman_firefighter':'\ud83d\udc69&zwj;\ud83d\ude92',
'woman_health_worker':'\ud83d\udc69&zwj;\u2695\ufe0f',
'woman_judge':'\ud83d\udc69&zwj;\u2696\ufe0f',
'woman_juggling':'\ud83e\udd39&zwj;\u2640\ufe0f',
'woman_mechanic':'\ud83d\udc69&zwj;\ud83d\udd27',
'woman_office_worker':'\ud83d\udc69&zwj;\ud83d\udcbc',
'woman_pilot':'\ud83d\udc69&zwj;\u2708\ufe0f',
'woman_playing_handball':'\ud83e\udd3e&zwj;\u2640\ufe0f',
'woman_playing_water_polo':'\ud83e\udd3d&zwj;\u2640\ufe0f',
'woman_scientist':'\ud83d\udc69&zwj;\ud83d\udd2c',
'woman_shrugging':'\ud83e\udd37&zwj;\u2640\ufe0f',
'woman_singer':'\ud83d\udc69&zwj;\ud83c\udfa4',
'woman_student':'\ud83d\udc69&zwj;\ud83c\udf93',
'woman_teacher':'\ud83d\udc69&zwj;\ud83c\udfeb',
'woman_technologist':'\ud83d\udc69&zwj;\ud83d\udcbb',
'woman_with_turban':'\ud83d\udc73&zwj;\u2640\ufe0f',
'womans_clothes':'\ud83d\udc5a',
'womans_hat':'\ud83d\udc52',
'women_wrestling':'\ud83e\udd3c&zwj;\u2640\ufe0f',
'womens':'\ud83d\udeba',
'world_map':'\ud83d\uddfa',
'worried':'\ud83d\ude1f',
'wrench':'\ud83d\udd27',
'writing_hand':'\u270d\ufe0f',
'x':'\u274c',
'yellow_heart':'\ud83d\udc9b',
'yen':'\ud83d\udcb4',
'yin_yang':'\u262f\ufe0f',
'yum':'\ud83d\ude0b',
'zap':'\u26a1\ufe0f',
'zipper_mouth_face':'\ud83e\udd10',
'zzz':'\ud83d\udca4',
/* special emojis :P */
'octocat': '<img alt=":octocat:" height="20" width="20" align="absmiddle" src="https://assets-cdn.github.com/images/icons/emoji/octocat.png">',
'showdown': '<span style="font-family: \'Anonymous Pro\', monospace; text-decoration: underline; text-decoration-style: dashed; text-decoration-color: #3e8b8a;text-underline-position: under;">S</span>'
};
/**
* Created by Estevao on 31-05-2015.
*/
/**
* Showdown Converter class
* @class
* @param {object} [converterOptions]
* @returns {Converter}
*/
showdown.Converter = function (converterOptions) {
'use strict';
var
/**
* Options used by this converter
* @private
* @type {{}}
*/
options = {},
/**
* Language extensions used by this converter
* @private
* @type {Array}
*/
langExtensions = [],
/**
* Output modifiers extensions used by this converter
* @private
* @type {Array}
*/
outputModifiers = [],
/**
* Event listeners
* @private
* @type {{}}
*/
listeners = {},
/**
* The flavor set in this converter
*/
setConvFlavor = setFlavor,
/**
* Metadata of the document
* @type {{parsed: {}, raw: string, format: string}}
*/
metadata = {
parsed: {},
raw: '',
format: ''
};
_constructor();
/**
* Converter constructor
* @private
*/
function _constructor () {
converterOptions = converterOptions || {};
for (var gOpt in globalOptions) {
if (globalOptions.hasOwnProperty(gOpt)) {
options[gOpt] = globalOptions[gOpt];
}
}
// Merge options
if (typeof converterOptions === 'object') {
for (var opt in converterOptions) {
if (converterOptions.hasOwnProperty(opt)) {
options[opt] = converterOptions[opt];
}
}
} else {
throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
' was passed instead.');
}
if (options.extensions) {
showdown.helper.forEach(options.extensions, _parseExtension);
}
}
/**
* Parse extension
* @param {*} ext
* @param {string} [name='']
* @private
*/
function _parseExtension (ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty('listeners')) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
}
/**
* LEGACY_SUPPORT
* @param {*} ext
* @param {string} name
*/
function legacyExtensionLoading (ext, name) {
if (typeof ext === 'function') {
ext = ext(new showdown.Converter());
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var valid = validate(ext, name);
if (!valid.valid) {
throw Error(valid.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
default:// should never reach here
throw Error('Extension loader error: Type unrecognized!!!');
}
}
}
/**
* Listen to an event
* @param {string} name
* @param {function} callback
*/
function listen (name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
function rTrimInputText (text) {
var rsp = text.match(/^\s*/)[0].length,
rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
return text.replace(rgx, '');
}
/**
* Dispatch an event
* @private
* @param {string} evtName Event name
* @param {string} text Text
* @param {{}} options Converter Options
* @param {{}} globals
* @returns {string}
*/
this._dispatch = function dispatch (evtName, text, options, globals) {
if (listeners.hasOwnProperty(evtName)) {
for (var ei = 0; ei < listeners[evtName].length; ++ei) {
var nText = listeners[evtName][ei](evtName, text, this, options, globals);
if (nText && typeof nText !== 'undefined') {
text = nText;
}
}
}
return text;
};
/**
* Listen to an event
* @param {string} name
* @param {function} callback
* @returns {showdown.Converter}
*/
this.listen = function (name, callback) {
listen(name, callback);
return this;
};
/**
* Converts a markdown string into HTML
* @param {string} text
* @returns {*}
*/
this.makeHtml = function (text) {
//check if text is not falsy
if (!text) {
return text;
}
var globals = {
gHtmlBlocks: [],
gHtmlMdBlocks: [],
gHtmlSpans: [],
gUrls: {},
gTitles: {},
gDimensions: {},
gListLevel: 0,
hashLinkCounts: {},
langExtensions: langExtensions,
outputModifiers: outputModifiers,
converter: this,
ghCodeBlocks: [],
metadata: {
parsed: {},
raw: '',
format: ''
}
};
// This lets us use ¨ trema as an escape char to avoid md5 hashes
// The choice of character is arbitrary; anything that isn't
// magic in Markdown will work.
text = text.replace(/¨/g, '¨T');
// Replace $ with ¨D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\$/g, '¨D');
// Standardize line endings
text = text.replace(/\r\n/g, '\n'); // DOS to Unix
text = text.replace(/\r/g, '\n'); // Mac to Unix
// Stardardize line spaces
text = text.replace(/\u00A0/g, '&nbsp;');
if (options.smartIndentationFix) {
text = rTrimInputText(text);
}
// Make sure text begins and ends with a couple of newlines:
text = '\n\n' + text + '\n\n';
// detab
text = showdown.subParser('detab')(text, options, globals);
/**
* Strip any lines consisting only of spaces and tabs.
* This makes subsequent regexs easier to write, because we can
* match consecutive blank lines with /\n+/ instead of something
* contorted like /[ \t]*\n+/
*/
text = text.replace(/^[ \t]+$/mg, '');
//run languageExtensions
showdown.helper.forEach(langExtensions, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// run the sub parsers
text = showdown.subParser('metadata')(text, options, globals);
text = showdown.subParser('hashPreCodeTags')(text, options, globals);
text = showdown.subParser('githubCodeBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('hashCodeTags')(text, options, globals);
text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
text = showdown.subParser('blockGamut')(text, options, globals);
text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
// attacklab: Restore dollar signs
text = text.replace(/¨D/g, '$$');
// attacklab: Restore tremas
text = text.replace(/¨T/g, '¨');
// render a complete html document instead of a partial if the option is enabled
text = showdown.subParser('completeHTMLDocument')(text, options, globals);
// Run output modifiers
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// update metadata
metadata = globals.metadata;
return text;
};
/**
* Converts an HTML string into a markdown string
* @param src
* @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.
* @returns {string}
*/
this.makeMarkdown = this.makeMd = function (src, HTMLParser) {
// replace \r\n with \n
src = src.replace(/\r\n/g, '\n');
src = src.replace(/\r/g, '\n'); // old macs
// due to an edge case, we need to find this: > <
// to prevent removing of non silent white spaces
// ex: <em>this is</em> <strong>sparta</strong>
src = src.replace(/>[ \t]+</, '>¨NBSP;<');
if (!HTMLParser) {
if (window && window.document) {
HTMLParser = window.document;
} else {
throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');
}
}
var doc = HTMLParser.createElement('div');
doc.innerHTML = src;
var globals = {
preList: substitutePreCodeTags(doc)
};
// remove all newlines and collapse spaces
clean(doc);
// some stuff, like accidental reference links must now be escaped
// TODO
// doc.innerHTML = doc.innerHTML.replace(/\[[\S\t ]]/);
var nodes = doc.childNodes,
mdDoc = '';
for (var i = 0; i < nodes.length; i++) {
mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);
}
function clean (node) {
for (var n = 0; n < node.childNodes.length; ++n) {
var child = node.childNodes[n];
if (child.nodeType === 3) {
if (!/\S/.test(child.nodeValue) && !/^[ ]+$/.test(child.nodeValue)) {
node.removeChild(child);
--n;
} else {
child.nodeValue = child.nodeValue.split('\n').join(' ');
child.nodeValue = child.nodeValue.replace(/(\s)+/g, '$1');
}
} else if (child.nodeType === 1) {
clean(child);
}
}
}
// find all pre tags and replace contents with placeholder
// we need this so that we can remove all indentation from html
// to ease up parsing
function substitutePreCodeTags (doc) {
var pres = doc.querySelectorAll('pre'),
presPH = [];
for (var i = 0; i < pres.length; ++i) {
if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {
var content = pres[i].firstChild.innerHTML.trim(),
language = pres[i].firstChild.getAttribute('data-language') || '';
// if data-language attribute is not defined, then we look for class language-*
if (language === '') {
var classes = pres[i].firstChild.className.split(' ');
for (var c = 0; c < classes.length; ++c) {
var matches = classes[c].match(/^language-(.+)$/);
if (matches !== null) {
language = matches[1];
break;
}
}
}
// unescape html entities in content
content = showdown.helper.unescapeHTMLEntities(content);
presPH.push(content);
pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>';
} else {
presPH.push(pres[i].innerHTML);
pres[i].innerHTML = '';
pres[i].setAttribute('prenum', i.toString());
}
}
return presPH;
}
return mdDoc;
};
/**
* Set an option of this Converter instance
* @param {string} key
* @param {*} value
*/
this.setOption = function (key, value) {
options[key] = value;
};
/**
* Get the option of this Converter instance
* @param {string} key
* @returns {*}
*/
this.getOption = function (key) {
return options[key];
};
/**
* Get the options of this Converter instance
* @returns {{}}
*/
this.getOptions = function () {
return options;
};
/**
* Add extension to THIS converter
* @param {{}} extension
* @param {string} [name=null]
*/
this.addExtension = function (extension, name) {
name = name || null;
_parseExtension(extension, name);
};
/**
* Use a global registered extension with THIS converter
* @param {string} extensionName Name of the previously registered extension
*/
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
};
/**
* Set the flavor THIS converter should use
* @param {string} name
*/
this.setFlavor = function (name) {
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
var preset = flavor[name];
setConvFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
}
}
};
/**
* Get the currently set flavor of this converter
* @returns {string}
*/
this.getFlavor = function () {
return setConvFlavor;
};
/**
* Remove an extension from THIS converter.
* Note: This is a costly operation. It's better to initialize a new converter
* and specify the extensions you wish to use
* @param {Array} extension
*/
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var a = 0; a < extension.length; ++a) {
var ext = extension[a];
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions.splice(i, 1);
}
}
for (var ii = 0; ii < outputModifiers.length; ++ii) {
if (outputModifiers[ii] === ext) {
outputModifiers.splice(ii, 1);
}
}
}
};
/**
* Get all extension of THIS converter
* @returns {{language: Array, output: Array}}
*/
this.getAllExtensions = function () {
return {
language: langExtensions,
output: outputModifiers
};
};
/**
* Get the metadata of the previously parsed document
* @param raw
* @returns {string|{}}
*/
this.getMetadata = function (raw) {
if (raw) {
return metadata.raw;
} else {
return metadata.parsed;
}
};
/**
* Get the metadata format of the previously parsed document
* @returns {string}
*/
this.getMetadataFormat = function () {
return metadata.format;
};
/**
* Private: set a single key, value metadata pair
* @param {string} key
* @param {string} value
*/
this._setMetadataPair = function (key, value) {
metadata.parsed[key] = value;
};
/**
* Private: set metadata format
* @param {string} format
*/
this._setMetadataFormat = function (format) {
metadata.format = format;
};
/**
* Private: set metadata raw text
* @param {string} raw
*/
this._setMetadataRaw = function (raw) {
metadata.raw = raw;
};
};
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('anchors', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('anchors.before', text, options, globals);
var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {
if (showdown.helper.isUndefined(title)) {
title = '';
}
linkId = linkId.toLowerCase();
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (!url) {
if (!linkId) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
}
} else {
return wholeMatch;
}
}
//url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '&quot;');
//title = showdown.helper.escapeCharacters(title, '*_', false); // replaced line to improve performance
title = title.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
// optionLinksInNewWindow only applies
// to external links. Hash links (#) open in same page
if (options.openLinksInNewWindow && !/^#/.test(url)) {
// escaped _
result += ' rel="noopener noreferrer" target="¨E95Eblank"';
}
result += '>' + linkText + '</a>';
return result;
};
// First, handle reference-style links: [link text] [id]
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g, writeAnchorTag);
// Next, inline-style links: [link text](url "optional title")
// cases with crazy urls like ./image/cat1).png
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// normal cases
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
// or [link test](/foo)
text = text.replace(/\[([^\[\]]+)]()()()()()/g, writeAnchorTag);
// Lastly handle GithubMentions if option is enabled
if (options.ghMentions) {
text = text.replace(/(^|\s)(\\)?(@([a-z\d]+(?:[a-z\d.-]+?[a-z\d]+)*))/gmi, function (wm, st, escape, mentions, username) {
if (escape === '\\') {
return st + mentions;
}
//check if options.ghMentionsLink is a string
if (!showdown.helper.isString(options.ghMentionsLink)) {
throw new Error('ghMentionsLink option must be a string');
}
var lnk = options.ghMentionsLink.replace(/\{u}/g, username),
target = '';
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
}
return st + '<a href="' + lnk + '"' + target + '>' + mentions + '</a>';
});
}
text = globals.converter._dispatch('anchors.after', text, options, globals);
return text;
});
// url allowed chars [a-z\d_.~:/?#[]@!$&'()*+,;=-]
var simpleURLRegex = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,
simpleURLRegex2 = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,
delimUrlRegex = /()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,
simpleMailRegex = /(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gmi,
delimMailRegex = /<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
replaceLink = function (options) {
'use strict';
return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {
link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var lnkTxt = link,
append = '',
target = '',
lmc = leadingMagicChars || '',
tmc = trailingMagicChars || '';
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
}
if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
append = trailingPunctuation;
}
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
}
return lmc + '<a href="' + link + '"' + target + '>' + lnkTxt + '</a>' + append + tmc;
};
},
replaceMail = function (options, globals) {
'use strict';
return function (wholeMatch, b, mail) {
var href = 'mailto:';
b = b || '';
mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);
if (options.encodeEmails) {
href = showdown.helper.encodeEmailAddress(href + mail);
mail = showdown.helper.encodeEmailAddress(mail);
} else {
href = href + mail;
}
return b + '<a href="' + href + '">' + mail + '</a>';
};
};
showdown.subParser('autoLinks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('autoLinks.before', text, options, globals);
text = text.replace(delimUrlRegex, replaceLink(options));
text = text.replace(delimMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('autoLinks.after', text, options, globals);
return text;
});
showdown.subParser('simplifiedAutoLinks', function (text, options, globals) {
'use strict';
if (!options.simplifiedAutoLink) {
return text;
}
text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);
if (options.excludeTrailingPunctuationFromURLs) {
text = text.replace(simpleURLRegex2, replaceLink(options));
} else {
text = text.replace(simpleURLRegex, replaceLink(options));
}
text = text.replace(simpleMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);
return text;
});
/**
* These are all the transformations that form block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('blockGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockGamut.before', text, options, globals);
// we parse blockquotes first so that we can have headings and hrs
// inside blockquotes
text = showdown.subParser('blockQuotes')(text, options, globals);
text = showdown.subParser('headers')(text, options, globals);
// Do Horizontal Rules:
text = showdown.subParser('horizontalRule')(text, options, globals);
text = showdown.subParser('lists')(text, options, globals);
text = showdown.subParser('codeBlocks')(text, options, globals);
text = showdown.subParser('tables')(text, options, globals);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('paragraphs')(text, options, globals);
text = globals.converter._dispatch('blockGamut.after', text, options, globals);
return text;
});
showdown.subParser('blockQuotes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
// add a couple extra lines after the text and endtext mark
text = text + '\n\n';
var rgx = /(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;
if (options.splitAdjacentBlockquotes) {
rgx = /^ {0,3}>[\s\S]*?(?:\n\n)/gm;
}
text = text.replace(rgx, function (bq) {
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
bq = bq.replace(/^[ \t]*>[ \t]?/gm, ''); // trim one level of quoting
// attacklab: clean up hack
bq = bq.replace(/¨0/g, '');
bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
bq = bq.replace(/(^|\n)/g, '$1 ');
// These leading spaces screw with <pre> content, so we need to fix that:
bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
pre = pre.replace(/^ /mg, '¨0');
pre = pre.replace(/¨0/g, '');
return pre;
});
return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
});
text = globals.converter._dispatch('blockQuotes.after', text, options, globals);
return text;
});
/**
* Process Markdown `<pre><code>` blocks.
*/
showdown.subParser('codeBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeBlocks.before', text, options, globals);
// sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g;
text = text.replace(pattern, function (wholeMatch, m1, m2) {
var codeblock = m1,
nextChar = m2,
end = '\n';
codeblock = showdown.subParser('outdent')(codeblock, options, globals);
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
if (options.omitExtraWLInCodeBlocks) {
end = '';
}
codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
});
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('codeBlocks.after', text, options, globals);
return text;
});
/**
*
* * Backtick quotes are used for <code></code> spans.
*
* * You can use multiple backticks as the delimiters if you want to
* include literal backticks in the code span. So, this input:
*
* Just type ``foo `bar` baz`` at the prompt.
*
* Will translate to:
*
* <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
*
* There's no arbitrary limit to the number of backticks you
* can use as delimters. If you need three consecutive backticks
* in your code, use four for delimiters, etc.
*
* * You can use spaces to get literal backticks at the edges:
*
* ... type `` `bar` `` ...
*
* Turns to:
*
* ... type <code>`bar`</code> ...
*/
showdown.subParser('codeSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeSpans.before', text, options, globals);
if (typeof (text) === 'undefined') {
text = '';
}
text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
function (wholeMatch, m1, m2, m3) {
var c = m3;
c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
c = showdown.subParser('encodeCode')(c, options, globals);
c = m1 + '<code>' + c + '</code>';
c = showdown.subParser('hashHTMLSpans')(c, options, globals);
return c;
}
);
text = globals.converter._dispatch('codeSpans.after', text, options, globals);
return text;
});
/**
* Create a full HTML document from the processed markdown
*/
showdown.subParser('completeHTMLDocument', function (text, options, globals) {
'use strict';
if (!options.completeHTMLDocument) {
return text;
}
text = globals.converter._dispatch('completeHTMLDocument.before', text, options, globals);
var doctype = 'html',
doctypeParsed = '<!DOCTYPE HTML>\n',
title = '',
charset = '<meta charset="utf-8">\n',
lang = '',
metadata = '';
if (typeof globals.metadata.parsed.doctype !== 'undefined') {
doctypeParsed = '<!DOCTYPE ' + globals.metadata.parsed.doctype + '>\n';
doctype = globals.metadata.parsed.doctype.toString().toLowerCase();
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="utf-8">';
}
}
for (var meta in globals.metadata.parsed) {
if (globals.metadata.parsed.hasOwnProperty(meta)) {
switch (meta.toLowerCase()) {
case 'doctype':
break;
case 'title':
title = '<title>' + globals.metadata.parsed.title + '</title>\n';
break;
case 'charset':
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="' + globals.metadata.parsed.charset + '">\n';
} else {
charset = '<meta name="charset" content="' + globals.metadata.parsed.charset + '">\n';
}
break;
case 'language':
case 'lang':
lang = ' lang="' + globals.metadata.parsed[meta] + '"';
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
break;
default:
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
}
}
}
text = doctypeParsed + '<html' + lang + '>\n<head>\n' + title + charset + metadata + '</head>\n<body>\n' + text.trim() + '\n</body>\n</html>';
text = globals.converter._dispatch('completeHTMLDocument.after', text, options, globals);
return text;
});
/**
* Convert all tabs to spaces
*/
showdown.subParser('detab', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('detab.before', text, options, globals);
// expand first n-1 tabs
text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
// replace the nth with two sentinels
text = text.replace(/\t/g, '¨A¨B');
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {
var leadingText = m1,
numSpaces = 4 - leadingText.length % 4; // g_tab_width
// there *must* be a better way to do this:
for (var i = 0; i < numSpaces; i++) {
leadingText += ' ';
}
return leadingText;
});
// clean up sentinels
text = text.replace(/¨A/g, ' '); // g_tab_width
text = text.replace(/¨B/g, '');
text = globals.converter._dispatch('detab.after', text, options, globals);
return text;
});
showdown.subParser('ellipsis', function (text, options, globals) {
'use strict';
if (!options.ellipsis) {
return text;
}
text = globals.converter._dispatch('ellipsis.before', text, options, globals);
text = text.replace(/\.\.\./g, '…');
text = globals.converter._dispatch('ellipsis.after', text, options, globals);
return text;
});
/**
* Turn emoji codes into emojis
*
* List of supported emojis: https://github.com/showdownjs/showdown/wiki/Emojis
*/
showdown.subParser('emoji', function (text, options, globals) {
'use strict';
if (!options.emoji) {
return text;
}
text = globals.converter._dispatch('emoji.before', text, options, globals);
var emojiRgx = /:([\S]+?):/g;
text = text.replace(emojiRgx, function (wm, emojiCode) {
if (showdown.helper.emojis.hasOwnProperty(emojiCode)) {
return showdown.helper.emojis[emojiCode];
}
return wm;
});
text = globals.converter._dispatch('emoji.after', text, options, globals);
return text;
});
/**
* Smart processing for ampersands and angle brackets that need to be encoded.
*/
showdown.subParser('encodeAmpsAndAngles', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeAmpsAndAngles.before', text, options, globals);
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&amp;');
// Encode naked <'s
text = text.replace(/<(?![a-z\/?$!])/gi, '&lt;');
// Encode <
text = text.replace(/</g, '&lt;');
// Encode >
text = text.replace(/>/g, '&gt;');
text = globals.converter._dispatch('encodeAmpsAndAngles.after', text, options, globals);
return text;
});
/**
* Returns the string, with after processing the following backslash escape sequences.
*
* attacklab: The polite way to do this is with the new escapeCharacters() function:
*
* text = escapeCharacters(text,"\\",true);
* text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
*
* ...but we're sidestepping its use of the (slow) RegExp constructor
* as an optimization for Firefox. This function gets called a LOT.
*/
showdown.subParser('encodeBackslashEscapes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals);
text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
text = text.replace(/\\([`*_{}\[\]()>#+.!~=|:-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals);
return text;
});
/**
* Encode/escape certain characters inside Markdown code runs.
* The point is that in code, these characters are literals,
* and lose their special Markdown meanings.
*/
showdown.subParser('encodeCode', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeCode.before', text, options, globals);
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text
.replace(/&/g, '&amp;')
// Do the angle bracket song and dance:
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
// Now, escape characters that are magic in Markdown:
.replace(/([*_{}\[\]\\=~-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeCode.after', text, options, globals);
return text;
});
/**
* Within tags -- meaning between < and > -- encode [\ ` * _ ~ =] so they
* don't conflict with their use in Markdown for code, italics and strong.
*/
showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals);
// Build a regex to find HTML tags.
var tags = /<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,
comments = /<!(--(?:(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>/gi;
text = text.replace(tags, function (wholeMatch) {
return wholeMatch
.replace(/(.)<\/?code>(?=.)/g, '$1`')
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = text.replace(comments, function (wholeMatch) {
return wholeMatch
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals);
return text;
});
/**
* Handle github codeblocks prior to running HashHTML so that
* HTML contained within the codeblock gets escaped properly
* Example:
* ```ruby
* def hello_world(x)
* puts "Hello, #{x}"
* end
* ```
*/
showdown.subParser('githubCodeBlocks', function (text, options, globals) {
'use strict';
// early exit if option is not enabled
if (!options.ghCodeBlocks) {
return text;
}
text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);
text += '¨0';
text = text.replace(/(?:^|\n)(?: {0,3})(```+|~~~+)(?: *)([^\s`~]*)\n([\s\S]*?)\n(?: {0,3})\1/g, function (wholeMatch, delim, language, codeblock) {
var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
// First parse the github code block
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
// Since GHCodeblocks can be false positives, we need to
// store the primitive text and the parsed text in a global var,
// and then return a token
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
});
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);
});
showdown.subParser('hashBlock', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashBlock.before', text, options, globals);
text = text.replace(/(^\n+|\n+$)/g, '');
text = '\n\n¨K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
text = globals.converter._dispatch('hashBlock.after', text, options, globals);
return text;
});
/**
* Hash and escape <code> elements that should not be parsed as markdown
*/
showdown.subParser('hashCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '¨C' + (globals.gHtmlSpans.push(codeblock) - 1) + 'C';
};
// Hash naked <code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '<code\\b[^>]*>', '</code>', 'gim');
text = globals.converter._dispatch('hashCodeTags.after', text, options, globals);
return text;
});
showdown.subParser('hashElement', function (text, options, globals) {
'use strict';
return function (wholeMatch, m1) {
var blockText = m1;
// Undo double lines
blockText = blockText.replace(/\n\n/g, '\n');
blockText = blockText.replace(/^\n/, '');
// strip trailing blank lines
blockText = blockText.replace(/\n+$/g, '');
// Replace the element text with a marker ("¨KxK" where x is its key)
blockText = '\n\n¨K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
return blockText;
};
});
showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLBlocks.before', text, options, globals);
var blockTags = [
'pre',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'table',
'dl',
'ol',
'ul',
'script',
'noscript',
'form',
'fieldset',
'iframe',
'math',
'style',
'section',
'header',
'footer',
'nav',
'article',
'aside',
'address',
'audio',
'canvas',
'figure',
'hgroup',
'output',
'video',
'p'
],
repFunc = function (wholeMatch, match, left, right) {
var txt = wholeMatch;
// check if this html element is marked as markdown
// if so, it's contents should be parsed as markdown
if (left.search(/\bmarkdown\b/) !== -1) {
txt = left + globals.converter.makeHtml(match) + right;
}
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
};
if (options.backslashEscapesHTMLTags) {
// encode backslash escaped HTML tags
text = text.replace(/\\<(\/?[^>]+?)>/g, function (wm, inside) {
return '&lt;' + inside + '&gt;';
});
}
// hash HTML Blocks
for (var i = 0; i < blockTags.length; ++i) {
var opTagPos,
rgx1 = new RegExp('^ {0,3}(<' + blockTags[i] + '\\b[^>]*>)', 'im'),
patLeft = '<' + blockTags[i] + '\\b[^>]*>',
patRight = '</' + blockTags[i] + '>';
// 1. Look for the first position of the first opening HTML tag in the text
while ((opTagPos = showdown.helper.regexIndexOf(text, rgx1)) !== -1) {
// if the HTML tag is \ escaped, we need to escape it and break
//2. Split the text in that position
var subTexts = showdown.helper.splitAtIndex(text, opTagPos),
//3. Match recursively
newSubText1 = showdown.helper.replaceRecursiveRegExp(subTexts[1], repFunc, patLeft, patRight, 'im');
// prevent an infinite loop
if (newSubText1 === subTexts[1]) {
break;
}
text = subTexts[0].concat(newSubText1);
}
}
// HR SPECIAL CASE
text = text.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
// Special case for standalone HTML comments
text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
}, '^ {0,3}<!--', '-->', 'gm');
// PHP and ASP-style processor instructions (<?...?> and <%...%>)
text = text.replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
text = globals.converter._dispatch('hashHTMLBlocks.after', text, options, globals);
return text;
});
/**
* Hash span elements that should not be parsed as markdown
*/
showdown.subParser('hashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLSpans.before', text, options, globals);
function hashHTMLSpan (html) {
return '¨C' + (globals.gHtmlSpans.push(html) - 1) + 'C';
}
// Hash Self Closing tags
text = text.replace(/<[^>]+?\/>/gi, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags without properties
text = text.replace(/<([^>]+?)>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags with properties
text = text.replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash self closing tags without />
text = text.replace(/<[^>]+?>/gi, function (wm) {
return hashHTMLSpan(wm);
});
/*showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');*/
text = globals.converter._dispatch('hashHTMLSpans.after', text, options, globals);
return text;
});
/**
* Unhash HTML spans
*/
showdown.subParser('unhashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unhashHTMLSpans.before', text, options, globals);
for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
var repText = globals.gHtmlSpans[i],
// limiter to prevent infinite loop (assume 10 as limit for recurse)
limit = 0;
while (/¨C(\d+)C/.test(repText)) {
var num = RegExp.$1;
repText = repText.replace('¨C' + num + 'C', globals.gHtmlSpans[num]);
if (limit === 10) {
console.error('maximum nesting of 10 spans reached!!!');
break;
}
++limit;
}
text = text.replace('¨C' + i + 'C', repText);
}
text = globals.converter._dispatch('unhashHTMLSpans.after', text, options, globals);
return text;
});
/**
* Hash and escape <pre><code> elements that should not be parsed as markdown
*/
showdown.subParser('hashPreCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashPreCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
// encode html entities
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
};
// Hash <pre><code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>', '^ {0,3}</code>\\s*</pre>', 'gim');
text = globals.converter._dispatch('hashPreCodeTags.after', text, options, globals);
return text;
});
showdown.subParser('headers', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('headers.before', text, options, globals);
var headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
// Set text-style headers:
// Header 1
// ========
//
// Header 2
// --------
//
setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
text = text.replace(setextRegexH1, function (wholeMatch, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
text = text.replace(setextRegexH2, function (matchFound, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart + 1,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
var atxStyle = (options.requireSpaceBeforeHeadingText) ? /^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm : /^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;
text = text.replace(atxStyle, function (wholeMatch, m1, m2) {
var hText = m2;
if (options.customizedHeaderId) {
hText = m2.replace(/\s?\{([^{]+?)}\s*$/, '');
}
var span = showdown.subParser('spanGamut')(hText, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
hLevel = headerLevelStart - 1 + m1.length,
header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(header, options, globals);
});
function headerId (m) {
var title,
prefix;
// It is separate from other options to allow combining prefix and customized
if (options.customizedHeaderId) {
var match = m.match(/\{([^{]+?)}\s*$/);
if (match && match[1]) {
m = match[1];
}
}
title = m;
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (showdown.helper.isString(options.prefixHeaderId)) {
prefix = options.prefixHeaderId;
} else if (options.prefixHeaderId === true) {
prefix = 'section-';
} else {
prefix = '';
}
if (!options.rawPrefixHeaderId) {
title = prefix + title;
}
if (options.ghCompatibleHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&amp;/g, '')
.replace(/¨T/g, '')
.replace(/¨D/g, '')
// replace rest of the chars (&~$ are repeated as they might have been escaped)
// borrowed from github's redcarpet (some they should produce similar results)
.replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g, '')
.toLowerCase();
} else if (options.rawHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&amp;/g, '&')
.replace(/¨T/g, '¨')
.replace(/¨D/g, '$')
// replace " and '
.replace(/["']/g, '-')
.toLowerCase();
} else {
title = title
.replace(/[^\w]/g, '')
.toLowerCase();
}
if (options.rawPrefixHeaderId) {
title = prefix + title;
}
if (globals.hashLinkCounts[title]) {
title = title + '-' + (globals.hashLinkCounts[title]++);
} else {
globals.hashLinkCounts[title] = 1;
}
return title;
}
text = globals.converter._dispatch('headers.after', text, options, globals);
return text;
});
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('horizontalRule', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('horizontalRule.before', text, options, globals);
var key = showdown.subParser('hashBlock')('<hr />', options, globals);
text = text.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?_){3,}[ \t]*$/gm, key);
text = globals.converter._dispatch('horizontalRule.after', text, options, globals);
return text;
});
/**
* Turn Markdown image shortcuts into <img> tags.
*/
showdown.subParser('images', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('images.before', text, options, globals);
var inlineRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
crazyRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,
base64RegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
referenceRegExp = /!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,
refShortcutRegExp = /!\[([^\[\]]+)]()()()()()/g;
function writeImageTagBase64 (wholeMatch, altText, linkId, url, width, height, m5, title) {
url = url.replace(/\s/g, '');
return writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title);
}
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
if (!title) {
title = '';
}
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(gUrls[linkId])) {
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
} else {
return wholeMatch;
}
}
altText = altText
.replace(/"/g, '&quot;')
//altText = showdown.helper.escapeCharacters(altText, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
//url = showdown.helper.escapeCharacters(url, '*_', false);
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title && showdown.helper.isString(title)) {
title = title
.replace(/"/g, '&quot;')
//title = showdown.helper.escapeCharacters(title, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
result += ' />';
return result;
}
// First, handle reference-style labeled images: ![alt text][id]
text = text.replace(referenceRegExp, writeImageTag);
// Next, handle inline images: ![alt text](url =<width>x<height> "optional title")
// base64 encoded images
text = text.replace(base64RegExp, writeImageTagBase64);
// cases with crazy urls like ./image/cat1).png
text = text.replace(crazyRegExp, writeImageTag);
// normal cases
text = text.replace(inlineRegExp, writeImageTag);
// handle reference-style shortcuts: ![img text]
text = text.replace(refShortcutRegExp, writeImageTag);
text = globals.converter._dispatch('images.after', text, options, globals);
return text;
});
showdown.subParser('italicsAndBold', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);
// it's faster to have 3 separate regexes for each case than have just one
// because of backtracing, in some cases, it could lead to an exponential effect
// called "catastrophic backtrace". Ominous!
function parseInside (txt, left, right) {
/*
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
*/
return left + txt + right;
}
// Parse underscores
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return parseInside (txt, '<strong><em>', '</em></strong>');
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return parseInside (txt, '<strong>', '</strong>');
});
text = text.replace(/\b_(\S[\s\S]*?)_\b/g, function (wm, txt) {
return parseInside (txt, '<em>', '</em>');
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/_([^\s_][\s\S]*?)_/g, function (wm, m) {
// !/^_[^_]/.test(m) - test if it doesn't start with __ (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
// Now parse asterisks
if (options.literalMidWordAsterisks) {
text = text.replace(/([^*]|^)\B\*\*\*(\S[\s\S]*?)\*\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong><em>', '</em></strong>');
});
text = text.replace(/([^*]|^)\B\*\*(\S[\s\S]*?)\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong>', '</strong>');
});
text = text.replace(/([^*]|^)\B\*(\S[\s\S]*?)\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<em>', '</em>');
});
} else {
text = text.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/\*\*(\S[\s\S]*?)\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/\*([^\s*][\s\S]*?)\*/g, function (wm, m) {
// !/^\*[^*]/.test(m) - test if it doesn't start with ** (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);
return text;
});
/**
* Form HTML ordered (numbered) and unordered (bulleted) lists.
*/
showdown.subParser('lists', function (text, options, globals) {
'use strict';
/**
* Process the contents of a single ordered or unordered list, splitting it
* into individual list items.
* @param {string} listStr
* @param {boolean} trimTrailing
* @returns {string}
*/
function processListItems (listStr, trimTrailing) {
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. "1." or "a.".
globals.gListLevel++;
// trim trailing blank lines:
listStr = listStr.replace(/\n{2,}$/, '\n');
// attacklab: add sentinel to emulate \z
listStr += '¨0';
var rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,
isParagraphed = (/\n[ \t]*\n(?!¨0)/.test(listStr));
// Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,
// which is a syntax breaking change
// activating this option reverts to old behavior
if (options.disableForced4SpacesIndentedSublists) {
rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm;
}
listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
checked = (checked && checked.trim() !== '');
var item = showdown.subParser('outdent')(m4, options, globals),
bulletStyle = '';
// Support for github tasklists
if (taskbtn && options.tasklists) {
bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
if (checked) {
otp += ' checked';
}
otp += '>';
return otp;
});
}
// ISSUE #312
// This input: - - - a
// causes trouble to the parser, since it interprets it as:
// <ul><li><li><li>a</li></li></li></ul>
// instead of:
// <ul><li>- - a</li></ul>
// So, to prevent it, we will put a marker (¨A)in the beginning of the line
// Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser
item = item.replace(/^([-*+]|\d\.)[ \t]+[\S\n ]*/g, function (wm2) {
return '¨A' + wm2;
});
// m1 - Leading line or
// Has a double return (multi paragraph) or
// Has sublist
if (m1 || (item.search(/\n{2,}/) > -1)) {
item = showdown.subParser('githubCodeBlocks')(item, options, globals);
item = showdown.subParser('blockGamut')(item, options, globals);
} else {
// Recursion for sub-lists:
item = showdown.subParser('lists')(item, options, globals);
item = item.replace(/\n$/, ''); // chomp(item)
item = showdown.subParser('hashHTMLBlocks')(item, options, globals);
// Colapse double linebreaks
item = item.replace(/\n\n+/g, '\n\n');
if (isParagraphed) {
item = showdown.subParser('paragraphs')(item, options, globals);
} else {
item = showdown.subParser('spanGamut')(item, options, globals);
}
}
// now we need to remove the marker (¨A)
item = item.replace('¨A', '');
// we can finally wrap the line in list item tags
item = '<li' + bulletStyle + '>' + item + '</li>\n';
return item;
});
// attacklab: strip sentinel
listStr = listStr.replace(/¨0/g, '');
globals.gListLevel--;
if (trimTrailing) {
listStr = listStr.replace(/\s+$/, '');
}
return listStr;
}
function styleStartNumber (list, listType) {
// check if ol and starts by a number different than 1
if (listType === 'ol') {
var res = list.match(/^ *(\d+)\./);
if (res && res[1] !== '1') {
return ' start="' + res[1] + '"';
}
}
return '';
}
/**
* Check and parse consecutive lists (better fix for issue #142)
* @param {string} list
* @param {string} listType
* @param {boolean} trimTrailing
* @returns {string}
*/
function parseConsecutiveLists (list, listType, trimTrailing) {
// check if we caught 2 or more consecutive lists by mistake
// we use the counterRgx, meaning if listType is UL we look for OL and vice versa
var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\d+\.[ \t]/gm : /^ {0,3}\d+\.[ \t]/gm,
ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \t]/gm : /^ {0,3}[*+-][ \t]/gm,
counterRxg = (listType === 'ul') ? olRgx : ulRgx,
result = '';
if (list.search(counterRxg) !== -1) {
(function parseCL (txt) {
var pos = txt.search(counterRxg),
style = styleStartNumber(list, listType);
if (pos !== -1) {
// slice
result += '\n\n<' + listType + style + '>\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n';
// invert counterType and listType
listType = (listType === 'ul') ? 'ol' : 'ul';
counterRxg = (listType === 'ul') ? olRgx : ulRgx;
//recurse
parseCL(txt.slice(pos));
} else {
result += '\n\n<' + listType + style + '>\n' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n';
}
})(list);
} else {
var style = styleStartNumber(list, listType);
result = '\n\n<' + listType + style + '>\n' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n';
}
return result;
}
/** Start of list parsing **/
text = globals.converter._dispatch('lists.before', text, options, globals);
// add sentinel to hack around khtml/safari bug:
// http://bugs.webkit.org/show_bug.cgi?id=11231
text += '¨0';
if (globals.gListLevel) {
text = text.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, list, m2) {
var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, true);
}
);
} else {
text = text.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, m1, list, m3) {
var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, false);
}
);
}
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('lists.after', text, options, globals);
return text;
});
/**
* Parse metadata at the top of the document
*/
showdown.subParser('metadata', function (text, options, globals) {
'use strict';
if (!options.metadata) {
return text;
}
text = globals.converter._dispatch('metadata.before', text, options, globals);
function parseMetadataContents (content) {
// raw is raw so it's not changed in any way
globals.metadata.raw = content;
// escape chars forbidden in html attributes
// double quotes
content = content
// ampersand first
.replace(/&/g, '&amp;')
// double quotes
.replace(/"/g, '&quot;');
content = content.replace(/\n {4}/g, ' ');
content.replace(/^([\S ]+): +([\s\S]+?)$/gm, function (wm, key, value) {
globals.metadata.parsed[key] = value;
return '';
});
}
text = text.replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/, function (wholematch, format, content) {
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/, function (wholematch, format, content) {
if (format) {
globals.metadata.format = format;
}
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/¨M/g, '');
text = globals.converter._dispatch('metadata.after', text, options, globals);
return text;
});
/**
* Remove one level of line-leading tabs or spaces
*/
showdown.subParser('outdent', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('outdent.before', text, options, globals);
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
text = text.replace(/^(\t|[ ]{1,4})/gm, '¨0'); // attacklab: g_tab_width
// attacklab: clean up hack
text = text.replace(/¨0/g, '');
text = globals.converter._dispatch('outdent.after', text, options, globals);
return text;
});
/**
*
*/
showdown.subParser('paragraphs', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('paragraphs.before', text, options, globals);
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
var grafs = text.split(/\n{2,}/g),
grafsOut = [],
end = grafs.length; // Wrap <p> tags
for (var i = 0; i < end; i++) {
var str = grafs[i];
// if this is an HTML marker, copy it
if (str.search(/¨(K|G)(\d+)\1/g) >= 0) {
grafsOut.push(str);
// test for presence of characters to prevent empty lines being parsed
// as paragraphs (resulting in undesired extra empty paragraphs)
} else if (str.search(/\S/) >= 0) {
str = showdown.subParser('spanGamut')(str, options, globals);
str = str.replace(/^([ \t]*)/g, '<p>');
str += '</p>';
grafsOut.push(str);
}
}
/** Unhashify HTML blocks */
end = grafsOut.length;
for (i = 0; i < end; i++) {
var blockText = '',
grafsOutIt = grafsOut[i],
codeFlag = false;
// if this is a marker for an html block...
// use RegExp.test instead of string.search because of QML bug
while (/¨(K|G)(\d+)\1/.test(grafsOutIt)) {
var delim = RegExp.$1,
num = RegExp.$2;
if (delim === 'K') {
blockText = globals.gHtmlBlocks[num];
} else {
// we need to check if ghBlock is a false positive
if (codeFlag) {
// use encoded version of all text
blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text, options, globals);
} else {
blockText = globals.ghCodeBlocks[num].codeblock;
}
}
blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
grafsOutIt = grafsOutIt.replace(/(\n\n)?¨(K|G)\d+\2(\n\n)?/, blockText);
// Check if grafsOutIt is a pre->code
if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
codeFlag = true;
}
}
grafsOut[i] = grafsOutIt;
}
text = grafsOut.join('\n');
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
return globals.converter._dispatch('paragraphs.after', text, options, globals);
});
/**
* Run extension
*/
showdown.subParser('runExtension', function (ext, text, options, globals) {
'use strict';
if (ext.filter) {
text = ext.filter(text, globals.converter, options);
} else if (ext.regex) {
// TODO remove this when old extension loading mechanism is deprecated
var re = ext.regex;
if (!(re instanceof RegExp)) {
re = new RegExp(re, 'g');
}
text = text.replace(re, ext.replace);
}
return text;
});
/**
* These are all the transformations that occur *within* block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('spanGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('spanGamut.before', text, options, globals);
text = showdown.subParser('codeSpans')(text, options, globals);
text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
// Process anchor and image tags. Images must come first,
// because ![foo][f] looks like an anchor.
text = showdown.subParser('images')(text, options, globals);
text = showdown.subParser('anchors')(text, options, globals);
// Make links out of things like `<http://example.com/>`
// Must come after anchors, because you can use < and >
// delimiters in inline links like [this](<url>).
text = showdown.subParser('autoLinks')(text, options, globals);
text = showdown.subParser('simplifiedAutoLinks')(text, options, globals);
text = showdown.subParser('emoji')(text, options, globals);
text = showdown.subParser('underline')(text, options, globals);
text = showdown.subParser('italicsAndBold')(text, options, globals);
text = showdown.subParser('strikethrough')(text, options, globals);
text = showdown.subParser('ellipsis')(text, options, globals);
// we need to hash HTML tags inside spans
text = showdown.subParser('hashHTMLSpans')(text, options, globals);
// now we encode amps and angles
text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
// Do hard breaks
if (options.simpleLineBreaks) {
// GFM style hard breaks
// only add line breaks if the text does not contain a block (special case for lists)
if (!/\n\n¨K/.test(text)) {
text = text.replace(/\n+/g, '<br />\n');
}
} else {
// Vanilla hard breaks
text = text.replace(/ +\n/g, '<br />\n');
}
text = globals.converter._dispatch('spanGamut.after', text, options, globals);
return text;
});
showdown.subParser('strikethrough', function (text, options, globals) {
'use strict';
function parseInside (txt) {
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
return '<del>' + txt + '</del>';
}
if (options.strikethrough) {
text = globals.converter._dispatch('strikethrough.before', text, options, globals);
text = text.replace(/(?:~){2}([\s\S]+?)(?:~){2}/g, function (wm, txt) { return parseInside(txt); });
text = globals.converter._dispatch('strikethrough.after', text, options, globals);
}
return text;
});
/**
* Strips link definitions from text, stores the URLs and titles in
* hash references.
* Link defs are in the form: ^[id]: url "optional title"
*/
showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
'use strict';
var regex = /^ {0,3}\[([^\]]+)]:[ \t]*\n?[ \t]*<?([^>\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,
base64Regex = /^ {0,3}\[([^\]]+)]:[ \t]*\n?[ \t]*<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm;
// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var replaceFunc = function (wholeMatch, linkId, url, width, height, blankLines, title) {
// if there aren't two instances of linkId it must not be a reference link so back out
linkId = linkId.toLowerCase();
if (text.toLowerCase().split(linkId).length - 1 < 2) {
return wholeMatch;
}
if (url.match(/^data:.+?\/.+?;base64,/)) {
// remove newlines
globals.gUrls[linkId] = url.replace(/\s/g, '');
} else {
globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url, options, globals); // Link IDs are case-insensitive
}
if (blankLines) {
// Oops, found blank lines, so it's not a title.
// Put back the parenthetical statement we stole.
return blankLines + title;
} else {
if (title) {
globals.gTitles[linkId] = title.replace(/"|'/g, '&quot;');
}
if (options.parseImgDimensions && width && height) {
globals.gDimensions[linkId] = {
width: width,
height: height
};
}
}
// Completely remove the definition from the text
return '';
};
// first we try to find base64 link references
text = text.replace(base64Regex, replaceFunc);
text = text.replace(regex, replaceFunc);
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return text;
});
showdown.subParser('tables', function (text, options, globals) {
'use strict';
if (!options.tables) {
return text;
}
var tableRgx = /^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,
//singeColTblRgx = /^ {0,3}\|.+\|\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n(?: {0,3}\|.+\|\n)+(?:\n\n|¨0)/gm;
singeColTblRgx = /^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm;
function parseStyles (sLine) {
if (/^:[ \t]*--*$/.test(sLine)) {
return ' style="text-align:left;"';
} else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
return ' style="text-align:right;"';
} else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
return ' style="text-align:center;"';
} else {
return '';
}
}
function parseHeaders (header, style) {
var id = '';
header = header.trim();
// support both tablesHeaderId and tableHeaderId due to error in documentation so we don't break backwards compatibility
if (options.tablesHeaderId || options.tableHeaderId) {
id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
}
header = showdown.subParser('spanGamut')(header, options, globals);
return '<th' + id + style + '>' + header + '</th>\n';
}
function parseCells (cell, style) {
var subText = showdown.subParser('spanGamut')(cell, options, globals);
return '<td' + style + '>' + subText + '</td>\n';
}
function buildTable (headers, cells) {
var tb = '<table>\n<thead>\n<tr>\n',
tblLgn = headers.length;
for (var i = 0; i < tblLgn; ++i) {
tb += headers[i];
}
tb += '</tr>\n</thead>\n<tbody>\n';
for (i = 0; i < cells.length; ++i) {
tb += '<tr>\n';
for (var ii = 0; ii < tblLgn; ++ii) {
tb += cells[i][ii];
}
tb += '</tr>\n';
}
tb += '</tbody>\n</table>\n';
return tb;
}
function parseTable (rawTable) {
var i, tableLines = rawTable.split('\n');
for (i = 0; i < tableLines.length; ++i) {
// strip wrong first and last column if wrapped tables are used
if (/^ {0,3}\|/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/^ {0,3}\|/, '');
}
if (/\|[ \t]*$/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/\|[ \t]*$/, '');
}
// parse code spans first, but we only support one line code spans
tableLines[i] = showdown.subParser('codeSpans')(tableLines[i], options, globals);
}
var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),
rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),
rawCells = [],
headers = [],
styles = [],
cells = [];
tableLines.shift();
tableLines.shift();
for (i = 0; i < tableLines.length; ++i) {
if (tableLines[i].trim() === '') {
continue;
}
rawCells.push(
tableLines[i]
.split('|')
.map(function (s) {
return s.trim();
})
);
}
if (rawHeaders.length < rawStyles.length) {
return rawTable;
}
for (i = 0; i < rawStyles.length; ++i) {
styles.push(parseStyles(rawStyles[i]));
}
for (i = 0; i < rawHeaders.length; ++i) {
if (showdown.helper.isUndefined(styles[i])) {
styles[i] = '';
}
headers.push(parseHeaders(rawHeaders[i], styles[i]));
}
for (i = 0; i < rawCells.length; ++i) {
var row = [];
for (var ii = 0; ii < headers.length; ++ii) {
if (showdown.helper.isUndefined(rawCells[i][ii])) {
}
row.push(parseCells(rawCells[i][ii], styles[ii]));
}
cells.push(row);
}
return buildTable(headers, cells);
}
text = globals.converter._dispatch('tables.before', text, options, globals);
// find escaped pipe characters
text = text.replace(/\\(\|)/g, showdown.helper.escapeCharactersCallback);
// parse multi column tables
text = text.replace(tableRgx, parseTable);
// parse one column tables
text = text.replace(singeColTblRgx, parseTable);
text = globals.converter._dispatch('tables.after', text, options, globals);
return text;
});
showdown.subParser('underline', function (text, options, globals) {
'use strict';
if (!options.underline) {
return text;
}
text = globals.converter._dispatch('underline.before', text, options, globals);
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
}
// escape remaining underscores to prevent them being parsed by italic and bold
text = text.replace(/(_)/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('underline.after', text, options, globals);
return text;
});
/**
* Swap back in all the special characters we've hidden.
*/
showdown.subParser('unescapeSpecialChars', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unescapeSpecialChars.before', text, options, globals);
text = text.replace(/¨E(\d+)E/g, function (wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
});
text = globals.converter._dispatch('unescapeSpecialChars.after', text, options, globals);
return text;
});
showdown.subParser('makeMarkdown.blockquote', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
var innerTxt = showdown.subParser('makeMarkdown.node')(children[i], globals);
if (innerTxt === '') {
continue;
}
txt += innerTxt;
}
}
// cleanup
txt = txt.trim();
txt = '> ' + txt.split('\n').join('\n> ');
return txt;
});
showdown.subParser('makeMarkdown.codeBlock', function (node, globals) {
'use strict';
var lang = node.getAttribute('language'),
num = node.getAttribute('precodenum');
return '```' + lang + '\n' + globals.preList[num] + '\n```';
});
showdown.subParser('makeMarkdown.codeSpan', function (node) {
'use strict';
return '`' + node.innerHTML + '`';
});
showdown.subParser('makeMarkdown.emphasis', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '*';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '*';
}
return txt;
});
showdown.subParser('makeMarkdown.header', function (node, globals, headerLevel) {
'use strict';
var headerMark = new Array(headerLevel + 1).join('#'),
txt = '';
if (node.hasChildNodes()) {
txt = headerMark + ' ';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
return txt;
});
showdown.subParser('makeMarkdown.hr', function () {
'use strict';
return '---';
});
showdown.subParser('makeMarkdown.image', function (node) {
'use strict';
var txt = '';
if (node.hasAttribute('src')) {
txt += '![' + node.getAttribute('alt') + '](';
txt += '<' + node.getAttribute('src') + '>';
if (node.hasAttribute('width') && node.hasAttribute('height')) {
txt += ' =' + node.getAttribute('width') + 'x' + node.getAttribute('height');
}
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});
showdown.subParser('makeMarkdown.links', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes() && node.hasAttribute('href')) {
var children = node.childNodes,
childrenLength = children.length;
txt = '[';
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '](';
txt += '<' + node.getAttribute('href') + '>';
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});
showdown.subParser('makeMarkdown.list', function (node, globals, type) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var listItems = node.childNodes,
listItemsLenght = listItems.length,
listNum = node.getAttribute('start') || 1;
for (var i = 0; i < listItemsLenght; ++i) {
if (typeof listItems[i].tagName === 'undefined' || listItems[i].tagName.toLowerCase() !== 'li') {
continue;
}
// define the bullet to use in list
var bullet = '';
if (type === 'ol') {
bullet = listNum.toString() + '. ';
} else {
bullet = '- ';
}
// parse list item
txt += bullet + showdown.subParser('makeMarkdown.listItem')(listItems[i], globals);
++listNum;
}
// add comment at the end to prevent consecutive lists to be parsed as one
txt += '\n<!-- -->\n';
return txt.trim();
});
showdown.subParser('makeMarkdown.listItem', function (node, globals) {
'use strict';
var listItemTxt = '';
var children = node.childNodes,
childrenLenght = children.length;
for (var i = 0; i < childrenLenght; ++i) {
listItemTxt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
// if it's only one liner, we need to add a newline at the end
if (!/\n$/.test(listItemTxt)) {
listItemTxt += '\n';
} else {
// it's multiparagraph, so we need to indent
listItemTxt = listItemTxt
.split('\n')
.join('\n ')
.replace(/^ {4}$/gm, '')
.replace(/\n\n+/g, '\n\n');
}
return listItemTxt;
});
showdown.subParser('makeMarkdown.node', function (node, globals, spansOnly) {
'use strict';
spansOnly = spansOnly || false;
var txt = '';
// edge case of text without wrapper paragraph
if (node.nodeType === 3) {
return showdown.subParser('makeMarkdown.txt')(node, globals);
}
// HTML comment
if (node.nodeType === 8) {
return '<!--' + node.data + '-->\n\n';
}
// process only node elements
if (node.nodeType !== 1) {
return '';
}
var tagName = node.tagName.toLowerCase();
switch (tagName) {
//
// BLOCKS
//
case 'h1':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 1) + '\n\n'; }
break;
case 'h2':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 2) + '\n\n'; }
break;
case 'h3':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 3) + '\n\n'; }
break;
case 'h4':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 4) + '\n\n'; }
break;
case 'h5':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 5) + '\n\n'; }
break;
case 'h6':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 6) + '\n\n'; }
break;
case 'p':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.paragraph')(node, globals) + '\n\n'; }
break;
case 'blockquote':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.blockquote')(node, globals) + '\n\n'; }
break;
case 'hr':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.hr')(node, globals) + '\n\n'; }
break;
case 'ol':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ol') + '\n\n'; }
break;
case 'ul':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ul') + '\n\n'; }
break;
case 'precode':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.codeBlock')(node, globals) + '\n\n'; }
break;
case 'pre':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.pre')(node, globals) + '\n\n'; }
break;
case 'table':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.table')(node, globals) + '\n\n'; }
break;
//
// SPANS
//
case 'code':
txt = showdown.subParser('makeMarkdown.codeSpan')(node, globals);
break;
case 'em':
case 'i':
txt = showdown.subParser('makeMarkdown.emphasis')(node, globals);
break;
case 'strong':
case 'b':
txt = showdown.subParser('makeMarkdown.strong')(node, globals);
break;
case 'del':
txt = showdown.subParser('makeMarkdown.strikethrough')(node, globals);
break;
case 'a':
txt = showdown.subParser('makeMarkdown.links')(node, globals);
break;
case 'img':
txt = showdown.subParser('makeMarkdown.image')(node, globals);
break;
default:
txt = node.outerHTML + '\n\n';
}
// common normalization
// TODO eventually
return txt;
});
showdown.subParser('makeMarkdown.paragraph', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
// some text normalization
txt = txt.trim();
return txt;
});
showdown.subParser('makeMarkdown.pre', function (node, globals) {
'use strict';
var num = node.getAttribute('prenum');
return '<pre>' + globals.preList[num] + '</pre>';
});
showdown.subParser('makeMarkdown.strikethrough', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '~~';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '~~';
}
return txt;
});
showdown.subParser('makeMarkdown.strong', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '**';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '**';
}
return txt;
});
showdown.subParser('makeMarkdown.table', function (node, globals) {
'use strict';
var txt = '',
tableArray = [[], []],
headings = node.querySelectorAll('thead>tr>th'),
rows = node.querySelectorAll('tbody>tr'),
i, ii;
for (i = 0; i < headings.length; ++i) {
var headContent = showdown.subParser('makeMarkdown.tableCell')(headings[i], globals),
allign = '---';
if (headings[i].hasAttribute('style')) {
var style = headings[i].getAttribute('style').toLowerCase().replace(/\s/g, '');
switch (style) {
case 'text-align:left;':
allign = ':---';
break;
case 'text-align:right;':
allign = '---:';
break;
case 'text-align:center;':
allign = ':---:';
break;
}
}
tableArray[0][i] = headContent.trim();
tableArray[1][i] = allign;
}
for (i = 0; i < rows.length; ++i) {
var r = tableArray.push([]) - 1,
cols = rows[i].getElementsByTagName('td');
for (ii = 0; ii < headings.length; ++ii) {
var cellContent = ' ';
if (typeof cols[ii] !== 'undefined') {
cellContent = showdown.subParser('makeMarkdown.tableCell')(cols[ii], globals);
}
tableArray[r].push(cellContent);
}
}
var cellSpacesCount = 3;
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
var strLen = tableArray[i][ii].length;
if (strLen > cellSpacesCount) {
cellSpacesCount = strLen;
}
}
}
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
if (i === 1) {
if (tableArray[i][ii].slice(-1) === ':') {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii].slice(-1), cellSpacesCount - 1, '-') + ':';
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount, '-');
}
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount);
}
}
txt += '| ' + tableArray[i].join(' | ') + ' |\n';
}
return txt.trim();
});
showdown.subParser('makeMarkdown.tableCell', function (node, globals) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals, true);
}
return txt.trim();
});
showdown.subParser('makeMarkdown.txt', function (node) {
'use strict';
var txt = node.nodeValue;
// multiple spaces are collapsed
txt = txt.replace(/ +/g, ' ');
// replace the custom ¨NBSP; with a space
txt = txt.replace(/¨NBSP;/g, ' ');
// ", <, > and & should replace escaped html entities
txt = showdown.helper.unescapeHTMLEntities(txt);
// escape markdown magic characters
// emphasis, strong and strikethrough - can appear everywhere
// we also escape pipe (|) because of tables
// and escape ` because of code blocks and spans
txt = txt.replace(/([*_~|`])/g, '\\$1');
// escape > because of blockquotes
txt = txt.replace(/^(\s*)>/g, '\\$1>');
// hash character, only troublesome at the beginning of a line because of headers
txt = txt.replace(/^#/gm, '\\#');
// horizontal rules
txt = txt.replace(/^(\s*)([-=]{3,})(\s*)$/, '$1\\$2$3');
// dot, because of ordered lists, only troublesome at the beginning of a line when preceded by an integer
txt = txt.replace(/^( {0,3}\d+)\./gm, '$1\\.');
// +, * and -, at the beginning of a line becomes a list, so we need to escape them also (asterisk was already escaped)
txt = txt.replace(/^( {0,3})([+-])/gm, '$1\\$2');
// images and links, ] followed by ( is problematic, so we escape it
txt = txt.replace(/]([\s]*)\(/g, '\\]$1\\(');
// reference URIs must also be escaped
txt = txt.replace(/^ {0,3}\[([\S \t]*?)]:/gm, '\\[$1]:');
return txt;
});
var root = this;
// AMD Loader
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
'use strict';
return showdown;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// CommonJS/nodeJS Loader
} else {}
}).call(this);
//# sourceMappingURL=showdown.js.map
/***/ }),
/***/ 2032:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ C0: () => (/* binding */ HoverMessage),
/* harmony export */ Go: () => (/* binding */ MessageType),
/* harmony export */ HV: () => (/* binding */ FormatMessage),
/* harmony export */ Hl: () => (/* binding */ ChangeModeMessage),
/* harmony export */ Hx: () => (/* binding */ SignatureHelpMessage),
/* harmony export */ Jk: () => (/* binding */ DeltasMessage),
/* harmony export */ LN: () => (/* binding */ CloseDocumentMessage),
/* harmony export */ N3: () => (/* binding */ DocumentHighlightMessage),
/* harmony export */ PT: () => (/* binding */ ResolveCompletionMessage),
/* harmony export */ RT: () => (/* binding */ ConfigureFeaturesMessage),
/* harmony export */ W_: () => (/* binding */ GetSemanticTokensMessage),
/* harmony export */ X9: () => (/* binding */ AppliedEditMessage),
/* harmony export */ dd: () => (/* binding */ GlobalOptionsMessage),
/* harmony export */ eN: () => (/* binding */ InitMessage),
/* harmony export */ gf: () => (/* binding */ ChangeOptionsMessage),
/* harmony export */ i9: () => (/* binding */ ValidateMessage),
/* harmony export */ kN: () => (/* binding */ GetCodeActionsMessage),
/* harmony export */ lR: () => (/* binding */ SetWorkspaceMessage),
/* harmony export */ m6: () => (/* binding */ ExecuteCommandMessage),
/* harmony export */ qf: () => (/* binding */ CloseConnectionMessage),
/* harmony export */ uO: () => (/* binding */ ChangeMessage),
/* harmony export */ zZ: () => (/* binding */ CompleteMessage)
/* harmony export */ });
/* unused harmony export BaseMessage */
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class BaseMessage {
constructor(documentIdentifier, callbackId){
_define_property(this, "sessionId", void 0);
_define_property(this, "documentUri", void 0);
_define_property(this, "version", void 0);
_define_property(this, "callbackId", void 0);
this.sessionId = documentIdentifier.sessionId;
this.documentUri = documentIdentifier.documentUri;
this.callbackId = callbackId;
}
}
class InitMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, version, mode, options){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.init);
_define_property(this, "mode", void 0);
_define_property(this, "options", void 0);
_define_property(this, "value", void 0);
_define_property(this, "version", void 0);
this.version = version;
this.options = options;
this.mode = mode;
this.value = value;
}
}
class FormatMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, format){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.format);
_define_property(this, "value", void 0);
_define_property(this, "format", void 0);
this.value = value;
this.format = format;
}
}
class CompleteMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.complete);
_define_property(this, "value", void 0);
this.value = value;
}
}
class ResolveCompletionMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.resolveCompletion);
_define_property(this, "value", void 0);
this.value = value;
}
}
class HoverMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.hover);
_define_property(this, "value", void 0);
this.value = value;
}
}
class ValidateMessage extends BaseMessage {
constructor(documentIdentifier, callbackId){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.validate);
}
}
class ChangeMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, version){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.change);
_define_property(this, "value", void 0);
_define_property(this, "version", void 0);
this.value = value;
this.version = version;
}
}
class DeltasMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, version){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.applyDelta);
_define_property(this, "value", void 0);
_define_property(this, "version", void 0);
this.value = value;
this.version = version;
}
}
class ChangeModeMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, version, mode){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.changeMode);
_define_property(this, "mode", void 0);
_define_property(this, "value", void 0);
_define_property(this, "version", void 0);
this.value = value;
this.mode = mode;
this.version = version;
}
}
class ChangeOptionsMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, options, merge = false){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.changeOptions);
_define_property(this, "options", void 0);
_define_property(this, "merge", void 0);
this.options = options;
this.merge = merge;
}
}
class CloseDocumentMessage extends BaseMessage {
constructor(documentIdentifier, callbackId){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.closeDocument);
}
}
class CloseConnectionMessage {
constructor(callbackId){
_define_property(this, "type", MessageType.closeConnection);
_define_property(this, "callbackId", void 0);
this.callbackId = callbackId;
}
}
class GlobalOptionsMessage {
constructor(serviceName, options, merge){
_define_property(this, "type", MessageType.globalOptions);
_define_property(this, "serviceName", void 0);
_define_property(this, "options", void 0);
_define_property(this, "merge", void 0);
this.serviceName = serviceName;
this.options = options;
this.merge = merge;
}
}
class ConfigureFeaturesMessage {
constructor(serviceName, options){
_define_property(this, "type", MessageType.configureFeatures);
_define_property(this, "serviceName", void 0);
_define_property(this, "options", void 0);
this.serviceName = serviceName;
this.options = options;
}
}
class SignatureHelpMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.signatureHelp);
_define_property(this, "value", void 0);
this.value = value;
}
}
class DocumentHighlightMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.documentHighlight);
_define_property(this, "value", void 0);
this.value = value;
}
}
class GetSemanticTokensMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.getSemanticTokens);
_define_property(this, "value", void 0);
this.value = value;
}
}
class GetCodeActionsMessage extends BaseMessage {
constructor(documentIdentifier, callbackId, value, context){
super(documentIdentifier, callbackId);
_define_property(this, "type", MessageType.getCodeActions);
_define_property(this, "value", void 0);
_define_property(this, "context", void 0);
this.value = value;
this.context = context;
}
}
class SetWorkspaceMessage {
constructor(value){
_define_property(this, "type", MessageType.setWorkspace);
_define_property(this, "value", void 0);
this.value = value;
}
}
class ExecuteCommandMessage {
constructor(serviceName, callbackId, command, args){
_define_property(this, "callbackId", void 0);
_define_property(this, "serviceName", void 0);
_define_property(this, "type", MessageType.executeCommand);
_define_property(this, "value", void 0);
_define_property(this, "args", void 0);
this.serviceName = serviceName;
this.callbackId = callbackId;
this.value = command;
this.args = args;
}
}
class AppliedEditMessage {
constructor(value, serviceName, callbackId){
_define_property(this, "callbackId", void 0);
_define_property(this, "serviceName", void 0);
_define_property(this, "type", MessageType.appliedEdit);
_define_property(this, "value", void 0);
this.serviceName = serviceName;
this.callbackId = callbackId;
this.value = value;
}
}
var MessageType;
(function(MessageType) {
MessageType[MessageType["init"] = 0] = "init";
MessageType[MessageType["format"] = 1] = "format";
MessageType[MessageType["complete"] = 2] = "complete";
MessageType[MessageType["resolveCompletion"] = 3] = "resolveCompletion";
MessageType[MessageType["change"] = 4] = "change";
MessageType[MessageType["hover"] = 5] = "hover";
MessageType[MessageType["validate"] = 6] = "validate";
MessageType[MessageType["applyDelta"] = 7] = "applyDelta";
MessageType[MessageType["changeMode"] = 8] = "changeMode";
MessageType[MessageType["changeOptions"] = 9] = "changeOptions";
MessageType[MessageType["closeDocument"] = 10] = "closeDocument";
MessageType[MessageType["globalOptions"] = 11] = "globalOptions";
MessageType[MessageType["configureFeatures"] = 12] = "configureFeatures";
MessageType[MessageType["signatureHelp"] = 13] = "signatureHelp";
MessageType[MessageType["documentHighlight"] = 14] = "documentHighlight";
MessageType[MessageType["closeConnection"] = 15] = "closeConnection";
MessageType[MessageType["capabilitiesChange"] = 16] = "capabilitiesChange";
MessageType[MessageType["getSemanticTokens"] = 17] = "getSemanticTokens";
MessageType[MessageType["getCodeActions"] = 18] = "getCodeActions";
MessageType[MessageType["executeCommand"] = 19] = "executeCommand";
MessageType[MessageType["applyEdit"] = 20] = "applyEdit";
MessageType[MessageType["appliedEdit"] = 21] = "appliedEdit";
MessageType[MessageType["setWorkspace"] = 22] = "setWorkspace";
})(MessageType || (MessageType = {}));
/***/ }),
/***/ 7925:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ServiceManager: () => (/* binding */ ServiceManager)
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7770);
/* harmony import */ var _message_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2032);
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class ServiceManager {
async getServicesCapabilitiesAfterCallback(documentIdentifier, message, callback) {
let services = await callback(documentIdentifier, message.value, message.mode, message.options);
if (services) {
return Object.keys(services).reduce((acc, key)=>{
var _services_key_serviceInstance, _services_key;
acc[key] = ((_services_key = services[key]) === null || _services_key === void 0 ? void 0 : (_services_key_serviceInstance = _services_key.serviceInstance) === null || _services_key_serviceInstance === void 0 ? void 0 : _services_key_serviceInstance.serviceCapabilities) || null;
return acc;
}, {});
}
}
async aggregateFeatureResponses(serviceInstances, feature, methodName, documentIdentifier, attrs) {
return (await Promise.all(this.filterByFeature(serviceInstances, feature).map(async (service)=>{
if (Array.isArray(attrs)) {
return service[methodName](documentIdentifier, ...attrs);
} else {
return service[methodName](documentIdentifier, attrs);
}
}))).filter(_utils__WEBPACK_IMPORTED_MODULE_1__/* .notEmpty */ .z2);
}
applyOptionsToServices(serviceInstances, documentUri, options) {
serviceInstances.forEach((service)=>{
service.setOptions(documentUri, options);
});
}
async closeAllConnections() {
var services = this.$services;
for(let serviceName in services){
var _services_serviceName_serviceInstance, _services_serviceName;
await ((_services_serviceName = services[serviceName]) === null || _services_serviceName === void 0 ? void 0 : (_services_serviceName_serviceInstance = _services_serviceName.serviceInstance) === null || _services_serviceName_serviceInstance === void 0 ? void 0 : _services_serviceName_serviceInstance.closeConnection());
}
}
static async $initServiceInstance(service, ctx, workspaceUri) {
let module;
if ('type' in service) {
if ([
"socket",
"webworker"
].includes(service.type)) {
module = await service.module();
service.serviceInstance = new module["LanguageClient"](service, ctx, workspaceUri);
} else throw "Unknown service type";
} else {
module = await service.module();
service.serviceInstance = new module[service.className](service.modes);
}
if (service.options || service.initializationOptions) {
var _service_options, _ref;
service.serviceInstance.setGlobalOptions((_ref = (_service_options = service.options) !== null && _service_options !== void 0 ? _service_options : service.initializationOptions) !== null && _ref !== void 0 ? _ref : {});
}
service.serviceInstance.serviceData = service;
return service.serviceInstance;
}
async $getServicesInstancesByMode(mode) {
let services = this.findServicesByMode(mode);
if (Object.keys(services).length === 0) {
return [];
}
for(let serviceName in services){
await this.initializeService(serviceName);
}
return services;
}
async initializeService(serviceName) {
let service = this.$services[serviceName];
if (!service.serviceInstance) {
if (!this.serviceInitPromises[service.id]) {
this.serviceInitPromises[service.id] = ServiceManager.$initServiceInstance(service, this.ctx, this.workspaceUri).then((instance)=>{
service.serviceInstance = instance;
service.serviceInstance.serviceName = serviceName;
delete this.serviceInitPromises[service.id]; // Clean up
return instance;
});
}
return this.serviceInitPromises[service.id];
} else {
if (!service.serviceInstance.serviceName) {
service.serviceInstance.serviceName = serviceName;
}
return service.serviceInstance;
}
}
setGlobalOptions(serviceName, options, merge = false) {
let service = this.$services[serviceName];
if (!service) return;
service.options = merge ? (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .mergeObjects */ .rL)(options, service.options) : options;
if (service.serviceInstance) {
service.serviceInstance.setGlobalOptions(service.options);
}
}
setWorkspace(workspaceUri) {
this.workspaceUri = workspaceUri;
Object.values(this.$services).forEach((service)=>{
var _service_serviceInstance;
(_service_serviceInstance = service.serviceInstance) === null || _service_serviceInstance === void 0 ? void 0 : _service_serviceInstance.setWorkspace(this.workspaceUri);
});
}
async addDocument(documentIdentifier, documentValue, mode, options) {
if (!mode || !/^ace\/mode\//.test(mode)) return;
mode = mode.replace("ace/mode/", "");
mode = mode.replace(/golang$/, "go");
let services = await this.$getServicesInstancesByMode(mode);
if (Object.keys(services).length === 0) return;
let documentItem = {
uri: documentIdentifier.uri,
version: documentIdentifier.version,
languageId: mode,
text: documentValue
};
Object.values(services).forEach((el)=>el.serviceInstance.addDocument(documentItem));
this.$sessionIDToMode[documentIdentifier.uri] = mode;
return services;
}
async changeDocumentMode(documentIdentifier, value, mode, options) {
this.removeDocument(documentIdentifier);
return await this.addDocument(documentIdentifier, value, mode, options);
}
removeDocument(document) {
let services = this.getServicesInstances(document.uri);
if (services.length > 0) {
services.forEach((el)=>el.removeDocument(document));
delete this.$sessionIDToMode[document.uri];
}
}
getServicesInstances(documentUri) {
let mode = this.$sessionIDToMode[documentUri];
if (!mode) return []; //TODO:
let services = this.findServicesByMode(mode);
return Object.values(services).map((el)=>el.serviceInstance).filter(_utils__WEBPACK_IMPORTED_MODULE_1__/* .notEmpty */ .z2);
}
filterByFeature(serviceInstances, feature) {
return serviceInstances.filter((el)=>{
if (!el.serviceData.features[feature]) {
return false;
}
const capabilities = el.serviceCapabilities;
switch(feature){
case "hover":
return capabilities.hoverProvider == true;
case "completion":
return capabilities.completionProvider != undefined;
case "completionResolve":
var _capabilities_completionProvider;
return ((_capabilities_completionProvider = capabilities.completionProvider) === null || _capabilities_completionProvider === void 0 ? void 0 : _capabilities_completionProvider.resolveProvider) === true;
case "format":
return capabilities.documentRangeFormattingProvider == true || capabilities.documentFormattingProvider == true;
case "diagnostics":
return capabilities.diagnosticProvider != undefined;
case "signatureHelp":
return capabilities.signatureHelpProvider != undefined;
case "documentHighlight":
return capabilities.documentHighlightProvider == true;
case "semanticTokens":
return capabilities.semanticTokensProvider != undefined;
case "codeAction":
return capabilities.codeActionProvider != undefined;
case "executeCommand":
return capabilities.executeCommandProvider != undefined;
}
});
}
findServicesByMode(mode) {
let servicesWithName = {};
Object.entries(this.$services).forEach(([key, value])=>{
let extensions = value.modes.split('|');
if (extensions.includes(mode)) servicesWithName[key] = this.$services[key];
});
return servicesWithName;
}
registerService(name, service) {
service.id = name;
service.features = this.setDefaultFeaturesState(service.features);
this.$services[name] = service;
}
registerServer(name, clientConfig) {
clientConfig.id = name;
clientConfig.className = "LanguageClient";
clientConfig.features = this.setDefaultFeaturesState(clientConfig.features);
this.$services[name] = clientConfig;
}
configureFeatures(name, features) {
features = this.setDefaultFeaturesState(features);
if (!this.$services[name]) return;
this.$services[name].features = features;
}
setDefaultFeaturesState(serviceFeatures) {
var _features, _features1, _features2, _features3, _features4, _features5, _features6, _features7, _features8, _features9;
let features = serviceFeatures !== null && serviceFeatures !== void 0 ? serviceFeatures : {};
var _hover;
(_hover = (_features = features).hover) !== null && _hover !== void 0 ? _hover : _features.hover = true;
var _completion;
(_completion = (_features1 = features).completion) !== null && _completion !== void 0 ? _completion : _features1.completion = true;
var _completionResolve;
(_completionResolve = (_features2 = features).completionResolve) !== null && _completionResolve !== void 0 ? _completionResolve : _features2.completionResolve = true;
var _format;
(_format = (_features3 = features).format) !== null && _format !== void 0 ? _format : _features3.format = true;
var _diagnostics;
(_diagnostics = (_features4 = features).diagnostics) !== null && _diagnostics !== void 0 ? _diagnostics : _features4.diagnostics = true;
var _signatureHelp;
(_signatureHelp = (_features5 = features).signatureHelp) !== null && _signatureHelp !== void 0 ? _signatureHelp : _features5.signatureHelp = true;
var _documentHighlight;
(_documentHighlight = (_features6 = features).documentHighlight) !== null && _documentHighlight !== void 0 ? _documentHighlight : _features6.documentHighlight = true;
var _semanticTokens;
(_semanticTokens = (_features7 = features).semanticTokens) !== null && _semanticTokens !== void 0 ? _semanticTokens : _features7.semanticTokens = true;
var _codeAction;
(_codeAction = (_features8 = features).codeAction) !== null && _codeAction !== void 0 ? _codeAction : _features8.codeAction = true;
var _executeCommand;
(_executeCommand = (_features9 = features).executeCommand) !== null && _executeCommand !== void 0 ? _executeCommand : _features9.executeCommand = true;
return features;
}
constructor(ctx){
_define_property(this, "$services", {});
_define_property(this, "serviceInitPromises", {});
_define_property(this, "$sessionIDToMode", {});
_define_property(this, "ctx", void 0);
_define_property(this, "workspaceUri", void 0);
this.ctx = ctx;
let doValidation = async (document, servicesInstances)=>{
servicesInstances !== null && servicesInstances !== void 0 ? servicesInstances : servicesInstances = this.getServicesInstances(document.uri);
if (servicesInstances.length === 0) {
return;
}
//this is list of documents linked to services
let documentUrisList = Object.keys(servicesInstances[0].documents);
servicesInstances = this.filterByFeature(servicesInstances, "diagnostics");
servicesInstances = servicesInstances.filter((el)=>{
return el.serviceCapabilities.diagnosticProvider;
});
if (servicesInstances.length === 0) {
return;
}
let postMessage = {
"type": _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.validate
};
for (let documentUri of documentUrisList){
var _ref;
let diagnostics = (_ref = await Promise.all(servicesInstances.map((el)=>{
return el.doValidation({
uri: documentUri
});
}))) !== null && _ref !== void 0 ? _ref : [];
postMessage["documentUri"] = documentUri;
postMessage["value"] = diagnostics.flat();
ctx.postMessage(postMessage);
}
};
let provideValidationForServiceInstance = async (serviceName)=>{
let service = this.$services[serviceName];
if (!service) return;
var serviceInstance = service.serviceInstance;
if (serviceInstance) await doValidation(undefined, [
serviceInstance
]);
};
ctx.addEventListener("message", async (ev)=>{
let message = ev.data;
var _message_sessionId;
let sessionID = (_message_sessionId = message["sessionId"]) !== null && _message_sessionId !== void 0 ? _message_sessionId : "";
var _message_documentUri;
let documentUri = (_message_documentUri = message["documentUri"]) !== null && _message_documentUri !== void 0 ? _message_documentUri : "";
let version = message["version"];
let postMessage = {
"type": message.type,
"sessionId": sessionID,
"callbackId": message["callbackId"]
};
let serviceInstances = this.getServicesInstances(documentUri);
let documentIdentifier = {
uri: documentUri,
version: version
};
switch(message.type){
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.format:
serviceInstances = this.filterByFeature(serviceInstances, "format");
if (serviceInstances.length > 0) {
//we will use only first service to format
postMessage["value"] = await serviceInstances[0].format(documentIdentifier, message.value, message.format);
}
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.complete:
postMessage["value"] = (await Promise.all(this.filterByFeature(serviceInstances, "completion").map(async (service)=>{
return {
completions: await service.doComplete(documentIdentifier, message["value"]),
service: service.serviceData.className
};
}))).filter(_utils__WEBPACK_IMPORTED_MODULE_1__/* .notEmpty */ .z2);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.resolveCompletion:
var _this_filterByFeature_find;
let serviceName = message.value["service"];
postMessage["value"] = await ((_this_filterByFeature_find = this.filterByFeature(serviceInstances, "completionResolve").find((service)=>{
if (service.serviceData.className === serviceName) {
return service;
}
})) === null || _this_filterByFeature_find === void 0 ? void 0 : _this_filterByFeature_find.doResolve(message.value));
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.change:
serviceInstances.forEach((service)=>{
service.setValue(documentIdentifier, message["value"]);
});
await doValidation(documentIdentifier, serviceInstances);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.applyDelta:
serviceInstances.forEach((service)=>{
service.applyDeltas(documentIdentifier, message["value"]);
});
await doValidation(documentIdentifier, serviceInstances);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.hover:
postMessage["value"] = await this.aggregateFeatureResponses(serviceInstances, "hover", "doHover", documentIdentifier, message.value);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.validate:
postMessage["value"] = await doValidation(documentIdentifier, serviceInstances);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.init:
postMessage["value"] = await this.getServicesCapabilitiesAfterCallback(documentIdentifier, message, this.addDocument.bind(this));
await doValidation(documentIdentifier);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.changeMode:
postMessage["value"] = await this.getServicesCapabilitiesAfterCallback(documentIdentifier, message, this.changeDocumentMode.bind(this));
await doValidation(documentIdentifier);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.changeOptions:
this.applyOptionsToServices(serviceInstances, documentUri, message.options);
await doValidation(documentIdentifier, serviceInstances);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.closeDocument:
this.removeDocument(documentIdentifier);
await doValidation(documentIdentifier, serviceInstances);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.closeConnection:
await this.closeAllConnections();
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.globalOptions:
this.setGlobalOptions(message.serviceName, message.options, message.merge);
await provideValidationForServiceInstance(message.serviceName);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.configureFeatures:
this.configureFeatures(message.serviceName, message.options);
await provideValidationForServiceInstance(message.serviceName);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.signatureHelp:
postMessage["value"] = await this.aggregateFeatureResponses(serviceInstances, "signatureHelp", "provideSignatureHelp", documentIdentifier, message.value);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.documentHighlight:
let highlights = await this.aggregateFeatureResponses(serviceInstances, "documentHighlight", "findDocumentHighlights", documentIdentifier, message.value);
postMessage["value"] = highlights.flat();
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.getSemanticTokens:
serviceInstances = this.filterByFeature(serviceInstances, "semanticTokens");
if (serviceInstances.length > 0) {
//we will use only first service
postMessage["value"] = await serviceInstances[0].getSemanticTokens(documentIdentifier, message.value);
}
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.getCodeActions:
let value = message.value;
let context = message.context;
postMessage["value"] = (await Promise.all(this.filterByFeature(serviceInstances, "codeAction").map(async (service)=>{
return {
codeActions: await service.getCodeActions(documentIdentifier, value, context),
service: service.serviceName
};
}))).filter(_utils__WEBPACK_IMPORTED_MODULE_1__/* .notEmpty */ .z2);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.executeCommand:
var _this_$services_message_serviceName_serviceInstance, _this_$services_message_serviceName;
postMessage["value"] = (_this_$services_message_serviceName = this.$services[message.serviceName]) === null || _this_$services_message_serviceName === void 0 ? void 0 : (_this_$services_message_serviceName_serviceInstance = _this_$services_message_serviceName.serviceInstance) === null || _this_$services_message_serviceName_serviceInstance === void 0 ? void 0 : _this_$services_message_serviceName_serviceInstance.executeCommand(message.value, message.args);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.appliedEdit:
var _this_$services_message_serviceName_serviceInstance1, _this_$services_message_serviceName1;
postMessage["value"] = (_this_$services_message_serviceName1 = this.$services[message.serviceName]) === null || _this_$services_message_serviceName1 === void 0 ? void 0 : (_this_$services_message_serviceName_serviceInstance1 = _this_$services_message_serviceName1.serviceInstance) === null || _this_$services_message_serviceName_serviceInstance1 === void 0 ? void 0 : _this_$services_message_serviceName_serviceInstance1.sendAppliedResult(message.value, message.callbackId);
break;
case _message_types__WEBPACK_IMPORTED_MODULE_0__/* .MessageType */ .Go.setWorkspace:
this.setWorkspace(message.value);
break;
}
ctx.postMessage(postMessage);
});
}
}
/***/ }),
/***/ 7770:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ $Z: () => (/* binding */ mergeRanges),
/* harmony export */ Tk: () => (/* binding */ checkValueAgainstRegexpArray),
/* harmony export */ de: () => (/* binding */ convertToUri),
/* harmony export */ rL: () => (/* binding */ mergeObjects),
/* harmony export */ z2: () => (/* binding */ notEmpty)
/* harmony export */ });
/* harmony import */ var vscode_uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2917);
function mergeObjects(obj1, obj2, excludeUndefined = false) {
if (!obj1) return obj2;
if (!obj2) return obj1;
if (excludeUndefined) {
obj1 = excludeUndefinedValues(obj1);
obj2 = excludeUndefinedValues(obj2);
}
const mergedObjects = {
...obj2,
...obj1
}; // Give priority to obj1 values by spreading obj2 first, then obj1
for (const key of Object.keys(mergedObjects)){
if (obj1[key] && obj2[key]) {
if (Array.isArray(obj1[key])) {
mergedObjects[key] = obj1[key].concat(obj2[key]);
} else if (Array.isArray(obj2[key])) {
mergedObjects[key] = obj2[key].concat(obj1[key]);
} else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
mergedObjects[key] = mergeObjects(obj1[key], obj2[key]);
}
}
}
return mergedObjects;
}
function excludeUndefinedValues(obj) {
const filteredEntries = Object.entries(obj).filter(([_, value])=>value !== undefined);
return Object.fromEntries(filteredEntries);
}
function notEmpty(value) {
return value !== null && value !== undefined;
}
//taken with small changes from ace-code
function mergeRanges(ranges) {
var list = ranges;
list = list.sort(function(a, b) {
return comparePoints(a.start, b.start);
});
var next = list[0], range;
for(var i = 1; i < list.length; i++){
range = next;
next = list[i];
var cmp = comparePoints(range.end, next.start);
if (cmp < 0) continue;
if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) continue;
if (comparePoints(range.end, next.end) < 0) {
range.end.row = next.end.row;
range.end.column = next.end.column;
}
list.splice(i, 1);
next = range;
i--;
}
return list;
}
function comparePoints(p1, p2) {
return p1.row - p2.row || p1.column - p2.column;
}
function checkValueAgainstRegexpArray(value, regexpArray) {
if (!regexpArray) {
return false;
}
for(let i = 0; i < regexpArray.length; i++){
if (regexpArray[i].test(value)) {
return true;
}
}
return false;
}
function convertToUri(filePath) {
//already URI
if (filePath.startsWith("file:///")) {
return filePath;
}
return vscode_uri__WEBPACK_IMPORTED_MODULE_0__/* .URI */ .r.file(filePath).toString();
}
/***/ }),
/***/ 5272:
/***/ ((module) => {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/***/ 1531:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
// Currently in sync with Node.js lib/internal/util/types.js
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
var isArgumentsObject = __webpack_require__(5387);
var isGeneratorFunction = __webpack_require__(2625);
var whichTypedArray = __webpack_require__(2730);
var isTypedArray = __webpack_require__(5943);
function uncurryThis(f) {
return f.call.bind(f);
}
var BigIntSupported = typeof BigInt !== 'undefined';
var SymbolSupported = typeof Symbol !== 'undefined';
var ObjectToString = uncurryThis(Object.prototype.toString);
var numberValue = uncurryThis(Number.prototype.valueOf);
var stringValue = uncurryThis(String.prototype.valueOf);
var booleanValue = uncurryThis(Boolean.prototype.valueOf);
if (BigIntSupported) {
var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
}
if (SymbolSupported) {
var symbolValue = uncurryThis(Symbol.prototype.valueOf);
}
function checkBoxedPrimitive(value, prototypeValueOf) {
if (typeof value !== 'object') {
return false;
}
try {
prototypeValueOf(value);
return true;
} catch(e) {
return false;
}
}
exports.isArgumentsObject = isArgumentsObject;
exports.isGeneratorFunction = isGeneratorFunction;
exports.isTypedArray = isTypedArray;
// Taken from here and modified for better browser support
// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
function isPromise(input) {
return (
(
typeof Promise !== 'undefined' &&
input instanceof Promise
) ||
(
input !== null &&
typeof input === 'object' &&
typeof input.then === 'function' &&
typeof input.catch === 'function'
)
);
}
exports.isPromise = isPromise;
function isArrayBufferView(value) {
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
return ArrayBuffer.isView(value);
}
return (
isTypedArray(value) ||
isDataView(value)
);
}
exports.isArrayBufferView = isArrayBufferView;
function isUint8Array(value) {
return whichTypedArray(value) === 'Uint8Array';
}
exports.isUint8Array = isUint8Array;
function isUint8ClampedArray(value) {
return whichTypedArray(value) === 'Uint8ClampedArray';
}
exports.isUint8ClampedArray = isUint8ClampedArray;
function isUint16Array(value) {
return whichTypedArray(value) === 'Uint16Array';
}
exports.isUint16Array = isUint16Array;
function isUint32Array(value) {
return whichTypedArray(value) === 'Uint32Array';
}
exports.isUint32Array = isUint32Array;
function isInt8Array(value) {
return whichTypedArray(value) === 'Int8Array';
}
exports.isInt8Array = isInt8Array;
function isInt16Array(value) {
return whichTypedArray(value) === 'Int16Array';
}
exports.isInt16Array = isInt16Array;
function isInt32Array(value) {
return whichTypedArray(value) === 'Int32Array';
}
exports.isInt32Array = isInt32Array;
function isFloat32Array(value) {
return whichTypedArray(value) === 'Float32Array';
}
exports.isFloat32Array = isFloat32Array;
function isFloat64Array(value) {
return whichTypedArray(value) === 'Float64Array';
}
exports.isFloat64Array = isFloat64Array;
function isBigInt64Array(value) {
return whichTypedArray(value) === 'BigInt64Array';
}
exports.isBigInt64Array = isBigInt64Array;
function isBigUint64Array(value) {
return whichTypedArray(value) === 'BigUint64Array';
}
exports.isBigUint64Array = isBigUint64Array;
function isMapToString(value) {
return ObjectToString(value) === '[object Map]';
}
isMapToString.working = (
typeof Map !== 'undefined' &&
isMapToString(new Map())
);
function isMap(value) {
if (typeof Map === 'undefined') {
return false;
}
return isMapToString.working
? isMapToString(value)
: value instanceof Map;
}
exports.isMap = isMap;
function isSetToString(value) {
return ObjectToString(value) === '[object Set]';
}
isSetToString.working = (
typeof Set !== 'undefined' &&
isSetToString(new Set())
);
function isSet(value) {
if (typeof Set === 'undefined') {
return false;
}
return isSetToString.working
? isSetToString(value)
: value instanceof Set;
}
exports.isSet = isSet;
function isWeakMapToString(value) {
return ObjectToString(value) === '[object WeakMap]';
}
isWeakMapToString.working = (
typeof WeakMap !== 'undefined' &&
isWeakMapToString(new WeakMap())
);
function isWeakMap(value) {
if (typeof WeakMap === 'undefined') {
return false;
}
return isWeakMapToString.working
? isWeakMapToString(value)
: value instanceof WeakMap;
}
exports.isWeakMap = isWeakMap;
function isWeakSetToString(value) {
return ObjectToString(value) === '[object WeakSet]';
}
isWeakSetToString.working = (
typeof WeakSet !== 'undefined' &&
isWeakSetToString(new WeakSet())
);
function isWeakSet(value) {
return isWeakSetToString(value);
}
exports.isWeakSet = isWeakSet;
function isArrayBufferToString(value) {
return ObjectToString(value) === '[object ArrayBuffer]';
}
isArrayBufferToString.working = (
typeof ArrayBuffer !== 'undefined' &&
isArrayBufferToString(new ArrayBuffer())
);
function isArrayBuffer(value) {
if (typeof ArrayBuffer === 'undefined') {
return false;
}
return isArrayBufferToString.working
? isArrayBufferToString(value)
: value instanceof ArrayBuffer;
}
exports.isArrayBuffer = isArrayBuffer;
function isDataViewToString(value) {
return ObjectToString(value) === '[object DataView]';
}
isDataViewToString.working = (
typeof ArrayBuffer !== 'undefined' &&
typeof DataView !== 'undefined' &&
isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
);
function isDataView(value) {
if (typeof DataView === 'undefined') {
return false;
}
return isDataViewToString.working
? isDataViewToString(value)
: value instanceof DataView;
}
exports.isDataView = isDataView;
// Store a copy of SharedArrayBuffer in case it's deleted elsewhere
var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;
function isSharedArrayBufferToString(value) {
return ObjectToString(value) === '[object SharedArrayBuffer]';
}
function isSharedArrayBuffer(value) {
if (typeof SharedArrayBufferCopy === 'undefined') {
return false;
}
if (typeof isSharedArrayBufferToString.working === 'undefined') {
isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
}
return isSharedArrayBufferToString.working
? isSharedArrayBufferToString(value)
: value instanceof SharedArrayBufferCopy;
}
exports.isSharedArrayBuffer = isSharedArrayBuffer;
function isAsyncFunction(value) {
return ObjectToString(value) === '[object AsyncFunction]';
}
exports.isAsyncFunction = isAsyncFunction;
function isMapIterator(value) {
return ObjectToString(value) === '[object Map Iterator]';
}
exports.isMapIterator = isMapIterator;
function isSetIterator(value) {
return ObjectToString(value) === '[object Set Iterator]';
}
exports.isSetIterator = isSetIterator;
function isGeneratorObject(value) {
return ObjectToString(value) === '[object Generator]';
}
exports.isGeneratorObject = isGeneratorObject;
function isWebAssemblyCompiledModule(value) {
return ObjectToString(value) === '[object WebAssembly.Module]';
}
exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
function isNumberObject(value) {
return checkBoxedPrimitive(value, numberValue);
}
exports.isNumberObject = isNumberObject;
function isStringObject(value) {
return checkBoxedPrimitive(value, stringValue);
}
exports.isStringObject = isStringObject;
function isBooleanObject(value) {
return checkBoxedPrimitive(value, booleanValue);
}
exports.isBooleanObject = isBooleanObject;
function isBigIntObject(value) {
return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
}
exports.isBigIntObject = isBigIntObject;
function isSymbolObject(value) {
return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
}
exports.isSymbolObject = isSymbolObject;
function isBoxedPrimitive(value) {
return (
isNumberObject(value) ||
isStringObject(value) ||
isBooleanObject(value) ||
isBigIntObject(value) ||
isSymbolObject(value)
);
}
exports.isBoxedPrimitive = isBoxedPrimitive;
function isAnyArrayBuffer(value) {
return typeof Uint8Array !== 'undefined' && (
isArrayBuffer(value) ||
isSharedArrayBuffer(value)
);
}
exports.isAnyArrayBuffer = isAnyArrayBuffer;
['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
Object.defineProperty(exports, method, {
enumerable: false,
value: function() {
throw new Error(method + ' is not supported in userland');
}
});
});
/***/ }),
/***/ 6827:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
/* provided dependency */ var process = __webpack_require__(9907);
/* provided dependency */ var console = __webpack_require__(4364);
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
function getOwnPropertyDescriptors(obj) {
var keys = Object.keys(obj);
var descriptors = {};
for (var i = 0; i < keys.length; i++) {
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
}
return descriptors;
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
if (typeof process !== 'undefined' && process.noDeprecation === true) {
return fn;
}
// Allow for deprecating things in the process of starting up.
if (typeof process === 'undefined') {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnvRegex = /^$/;
if (process.env.NODE_DEBUG) {
var debugEnv = process.env.NODE_DEBUG;
debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/,/g, '$|^')
.toUpperCase();
debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}
exports.debuglog = function(set) {
set = set.toUpperCase();
if (!debugs[set]) {
if (debugEnvRegex.test(set)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').slice(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.slice(1, -1);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
exports.types = __webpack_require__(1531);
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
exports.types.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
exports.types.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
exports.types.isNativeError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(5272);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(5615);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
exports.promisify = function promisify(original) {
if (typeof original !== 'function')
throw new TypeError('The "original" argument must be of type Function');
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
var fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return fn;
}
function fn() {
var promiseResolve, promiseReject;
var promise = new Promise(function (resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
});
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
args.push(function (err, value) {
if (err) {
promiseReject(err);
} else {
promiseResolve(value);
}
});
try {
original.apply(this, args);
} catch (err) {
promiseReject(err);
}
return promise;
}
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return Object.defineProperties(
fn,
getOwnPropertyDescriptors(original)
);
}
exports.promisify.custom = kCustomPromisifiedSymbol
function callbackifyOnRejected(reason, cb) {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
var newReason = new Error('Promise was rejected with a falsy value');
newReason.reason = reason;
reason = newReason;
}
return cb(reason);
}
function callbackify(original) {
if (typeof original !== 'function') {
throw new TypeError('The "original" argument must be of type Function');
}
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var maybeCb = args.pop();
if (typeof maybeCb !== 'function') {
throw new TypeError('The last argument must be of type Function');
}
var self = this;
var cb = function() {
return maybeCb.apply(self, arguments);
};
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
original.apply(this, args)
.then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },
function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
}
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
Object.defineProperties(callbackified,
getOwnPropertyDescriptors(original));
return callbackified;
}
exports.callbackify = callbackify;
/***/ }),
/***/ 9208:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ----------------------------------------------------------------------------------------- */
module.exports = __webpack_require__(9110);
/***/ }),
/***/ 9110:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createMessageConnection = exports.BrowserMessageWriter = exports.BrowserMessageReader = void 0;
const ril_1 = __webpack_require__(3312);
// Install the browser runtime abstract.
ril_1.default.install();
const api_1 = __webpack_require__(7672);
__exportStar(__webpack_require__(7672), exports);
class BrowserMessageReader extends api_1.AbstractMessageReader {
constructor(port) {
super();
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
this._onData.fire(event.data);
};
port.addEventListener('error', (event) => this.fireError(event));
port.onmessage = this._messageListener;
}
listen(callback) {
return this._onData.event(callback);
}
}
exports.BrowserMessageReader = BrowserMessageReader;
class BrowserMessageWriter extends api_1.AbstractMessageWriter {
constructor(port) {
super();
this.port = port;
this.errorCount = 0;
port.addEventListener('error', (event) => this.fireError(event));
}
write(msg) {
try {
this.port.postMessage(msg);
return Promise.resolve();
}
catch (error) {
this.handleError(error, msg);
return Promise.reject(error);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
end() {
}
}
exports.BrowserMessageWriter = BrowserMessageWriter;
function createMessageConnection(reader, writer, logger, options) {
if (logger === undefined) {
logger = api_1.NullLogger;
}
if (api_1.ConnectionStrategy.is(options)) {
options = { connectionStrategy: options };
}
return (0, api_1.createMessageConnection)(reader, writer, logger, options);
}
exports.createMessageConnection = createMessageConnection;
/***/ }),
/***/ 3312:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* provided dependency */ var console = __webpack_require__(4364);
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
const api_1 = __webpack_require__(7672);
class MessageBuffer extends api_1.AbstractMessageBuffer {
constructor(encoding = 'utf-8') {
super(encoding);
this.asciiDecoder = new TextDecoder('ascii');
}
emptyBuffer() {
return MessageBuffer.emptyBuffer;
}
fromString(value, _encoding) {
return (new TextEncoder()).encode(value);
}
toString(value, encoding) {
if (encoding === 'ascii') {
return this.asciiDecoder.decode(value);
}
else {
return (new TextDecoder(encoding)).decode(value);
}
}
asNative(buffer, length) {
if (length === undefined) {
return buffer;
}
else {
return buffer.slice(0, length);
}
}
allocNative(length) {
return new Uint8Array(length);
}
}
MessageBuffer.emptyBuffer = new Uint8Array(0);
class ReadableStreamWrapper {
constructor(socket) {
this.socket = socket;
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
const blob = event.data;
blob.arrayBuffer().then((buffer) => {
this._onData.fire(new Uint8Array(buffer));
}, () => {
(0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`);
});
};
this.socket.addEventListener('message', this._messageListener);
}
onClose(listener) {
this.socket.addEventListener('close', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
}
onError(listener) {
this.socket.addEventListener('error', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
}
onEnd(listener) {
this.socket.addEventListener('end', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
}
onData(listener) {
return this._onData.event(listener);
}
}
class WritableStreamWrapper {
constructor(socket) {
this.socket = socket;
}
onClose(listener) {
this.socket.addEventListener('close', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener));
}
onError(listener) {
this.socket.addEventListener('error', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener));
}
onEnd(listener) {
this.socket.addEventListener('end', listener);
return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener));
}
write(data, encoding) {
if (typeof data === 'string') {
if (encoding !== undefined && encoding !== 'utf-8') {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);
}
this.socket.send(data);
}
else {
this.socket.send(data);
}
return Promise.resolve();
}
end() {
this.socket.close();
}
}
const _textEncoder = new TextEncoder();
const _ril = Object.freeze({
messageBuffer: Object.freeze({
create: (encoding) => new MessageBuffer(encoding)
}),
applicationJson: Object.freeze({
encoder: Object.freeze({
name: 'application/json',
encode: (msg, options) => {
if (options.charset !== 'utf-8') {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);
}
return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, undefined, 0)));
}
}),
decoder: Object.freeze({
name: 'application/json',
decode: (buffer, options) => {
if (!(buffer instanceof Uint8Array)) {
throw new Error(`In a Browser environments only Uint8Arrays are supported.`);
}
return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)));
}
})
}),
stream: Object.freeze({
asReadableStream: (socket) => new ReadableStreamWrapper(socket),
asWritableStream: (socket) => new WritableStreamWrapper(socket)
}),
console: console,
timer: Object.freeze({
setTimeout(callback, ms, ...args) {
const handle = setTimeout(callback, ms, ...args);
return { dispose: () => clearTimeout(handle) };
},
setImmediate(callback, ...args) {
const handle = setTimeout(callback, 0, ...args);
return { dispose: () => clearTimeout(handle) };
},
setInterval(callback, ms, ...args) {
const handle = setInterval(callback, ms, ...args);
return { dispose: () => clearInterval(handle) };
},
})
});
function RIL() {
return _ril;
}
(function (RIL) {
function install() {
api_1.RAL.install(_ril);
}
RIL.install = install;
})(RIL || (RIL = {}));
exports["default"] = RIL;
/***/ }),
/***/ 7672:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
/// <reference path="../../typings/thenable.d.ts" />
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;
exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;
const messages_1 = __webpack_require__(7162);
Object.defineProperty(exports, "Message", ({ enumerable: true, get: function () { return messages_1.Message; } }));
Object.defineProperty(exports, "RequestType", ({ enumerable: true, get: function () { return messages_1.RequestType; } }));
Object.defineProperty(exports, "RequestType0", ({ enumerable: true, get: function () { return messages_1.RequestType0; } }));
Object.defineProperty(exports, "RequestType1", ({ enumerable: true, get: function () { return messages_1.RequestType1; } }));
Object.defineProperty(exports, "RequestType2", ({ enumerable: true, get: function () { return messages_1.RequestType2; } }));
Object.defineProperty(exports, "RequestType3", ({ enumerable: true, get: function () { return messages_1.RequestType3; } }));
Object.defineProperty(exports, "RequestType4", ({ enumerable: true, get: function () { return messages_1.RequestType4; } }));
Object.defineProperty(exports, "RequestType5", ({ enumerable: true, get: function () { return messages_1.RequestType5; } }));
Object.defineProperty(exports, "RequestType6", ({ enumerable: true, get: function () { return messages_1.RequestType6; } }));
Object.defineProperty(exports, "RequestType7", ({ enumerable: true, get: function () { return messages_1.RequestType7; } }));
Object.defineProperty(exports, "RequestType8", ({ enumerable: true, get: function () { return messages_1.RequestType8; } }));
Object.defineProperty(exports, "RequestType9", ({ enumerable: true, get: function () { return messages_1.RequestType9; } }));
Object.defineProperty(exports, "ResponseError", ({ enumerable: true, get: function () { return messages_1.ResponseError; } }));
Object.defineProperty(exports, "ErrorCodes", ({ enumerable: true, get: function () { return messages_1.ErrorCodes; } }));
Object.defineProperty(exports, "NotificationType", ({ enumerable: true, get: function () { return messages_1.NotificationType; } }));
Object.defineProperty(exports, "NotificationType0", ({ enumerable: true, get: function () { return messages_1.NotificationType0; } }));
Object.defineProperty(exports, "NotificationType1", ({ enumerable: true, get: function () { return messages_1.NotificationType1; } }));
Object.defineProperty(exports, "NotificationType2", ({ enumerable: true, get: function () { return messages_1.NotificationType2; } }));
Object.defineProperty(exports, "NotificationType3", ({ enumerable: true, get: function () { return messages_1.NotificationType3; } }));
Object.defineProperty(exports, "NotificationType4", ({ enumerable: true, get: function () { return messages_1.NotificationType4; } }));
Object.defineProperty(exports, "NotificationType5", ({ enumerable: true, get: function () { return messages_1.NotificationType5; } }));
Object.defineProperty(exports, "NotificationType6", ({ enumerable: true, get: function () { return messages_1.NotificationType6; } }));
Object.defineProperty(exports, "NotificationType7", ({ enumerable: true, get: function () { return messages_1.NotificationType7; } }));
Object.defineProperty(exports, "NotificationType8", ({ enumerable: true, get: function () { return messages_1.NotificationType8; } }));
Object.defineProperty(exports, "NotificationType9", ({ enumerable: true, get: function () { return messages_1.NotificationType9; } }));
Object.defineProperty(exports, "ParameterStructures", ({ enumerable: true, get: function () { return messages_1.ParameterStructures; } }));
const linkedMap_1 = __webpack_require__(1109);
Object.defineProperty(exports, "LinkedMap", ({ enumerable: true, get: function () { return linkedMap_1.LinkedMap; } }));
Object.defineProperty(exports, "LRUCache", ({ enumerable: true, get: function () { return linkedMap_1.LRUCache; } }));
Object.defineProperty(exports, "Touch", ({ enumerable: true, get: function () { return linkedMap_1.Touch; } }));
const disposable_1 = __webpack_require__(8844);
Object.defineProperty(exports, "Disposable", ({ enumerable: true, get: function () { return disposable_1.Disposable; } }));
const events_1 = __webpack_require__(2479);
Object.defineProperty(exports, "Event", ({ enumerable: true, get: function () { return events_1.Event; } }));
Object.defineProperty(exports, "Emitter", ({ enumerable: true, get: function () { return events_1.Emitter; } }));
const cancellation_1 = __webpack_require__(6957);
Object.defineProperty(exports, "CancellationTokenSource", ({ enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } }));
Object.defineProperty(exports, "CancellationToken", ({ enumerable: true, get: function () { return cancellation_1.CancellationToken; } }));
const sharedArrayCancellation_1 = __webpack_require__(3489);
Object.defineProperty(exports, "SharedArraySenderStrategy", ({ enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArraySenderStrategy; } }));
Object.defineProperty(exports, "SharedArrayReceiverStrategy", ({ enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArrayReceiverStrategy; } }));
const messageReader_1 = __webpack_require__(656);
Object.defineProperty(exports, "MessageReader", ({ enumerable: true, get: function () { return messageReader_1.MessageReader; } }));
Object.defineProperty(exports, "AbstractMessageReader", ({ enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } }));
Object.defineProperty(exports, "ReadableStreamMessageReader", ({ enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } }));
const messageWriter_1 = __webpack_require__(9036);
Object.defineProperty(exports, "MessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.MessageWriter; } }));
Object.defineProperty(exports, "AbstractMessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } }));
Object.defineProperty(exports, "WriteableStreamMessageWriter", ({ enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } }));
const messageBuffer_1 = __webpack_require__(9805);
Object.defineProperty(exports, "AbstractMessageBuffer", ({ enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } }));
const connection_1 = __webpack_require__(4054);
Object.defineProperty(exports, "ConnectionStrategy", ({ enumerable: true, get: function () { return connection_1.ConnectionStrategy; } }));
Object.defineProperty(exports, "ConnectionOptions", ({ enumerable: true, get: function () { return connection_1.ConnectionOptions; } }));
Object.defineProperty(exports, "NullLogger", ({ enumerable: true, get: function () { return connection_1.NullLogger; } }));
Object.defineProperty(exports, "createMessageConnection", ({ enumerable: true, get: function () { return connection_1.createMessageConnection; } }));
Object.defineProperty(exports, "ProgressToken", ({ enumerable: true, get: function () { return connection_1.ProgressToken; } }));
Object.defineProperty(exports, "ProgressType", ({ enumerable: true, get: function () { return connection_1.ProgressType; } }));
Object.defineProperty(exports, "Trace", ({ enumerable: true, get: function () { return connection_1.Trace; } }));
Object.defineProperty(exports, "TraceValues", ({ enumerable: true, get: function () { return connection_1.TraceValues; } }));
Object.defineProperty(exports, "TraceFormat", ({ enumerable: true, get: function () { return connection_1.TraceFormat; } }));
Object.defineProperty(exports, "SetTraceNotification", ({ enumerable: true, get: function () { return connection_1.SetTraceNotification; } }));
Object.defineProperty(exports, "LogTraceNotification", ({ enumerable: true, get: function () { return connection_1.LogTraceNotification; } }));
Object.defineProperty(exports, "ConnectionErrors", ({ enumerable: true, get: function () { return connection_1.ConnectionErrors; } }));
Object.defineProperty(exports, "ConnectionError", ({ enumerable: true, get: function () { return connection_1.ConnectionError; } }));
Object.defineProperty(exports, "CancellationReceiverStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } }));
Object.defineProperty(exports, "CancellationSenderStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } }));
Object.defineProperty(exports, "CancellationStrategy", ({ enumerable: true, get: function () { return connection_1.CancellationStrategy; } }));
Object.defineProperty(exports, "MessageStrategy", ({ enumerable: true, get: function () { return connection_1.MessageStrategy; } }));
const ral_1 = __webpack_require__(5091);
exports.RAL = ral_1.default;
/***/ }),
/***/ 6957:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CancellationTokenSource = exports.CancellationToken = void 0;
const ral_1 = __webpack_require__(5091);
const Is = __webpack_require__(6618);
const events_1 = __webpack_require__(2479);
var CancellationToken;
(function (CancellationToken) {
CancellationToken.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: events_1.Event.None
});
CancellationToken.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: events_1.Event.None
});
function is(value) {
const candidate = value;
return candidate && (candidate === CancellationToken.None
|| candidate === CancellationToken.Cancelled
|| (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
}
CancellationToken.is = is;
})(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
const shortcutEvent = Object.freeze(function (callback, context) {
const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
return { dispose() { handle.dispose(); } };
});
class MutableToken {
constructor() {
this._isCancelled = false;
}
cancel() {
if (!this._isCancelled) {
this._isCancelled = true;
if (this._emitter) {
this._emitter.fire(undefined);
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 = undefined;
}
}
}
class CancellationTokenSource {
get token() {
if (!this._token) {
// be lazy and create the token only when
// actually needed
this._token = new MutableToken();
}
return this._token;
}
cancel() {
if (!this._token) {
// save an object by returning the default
// cancelled token when cancellation happens
// before someone asks for the token
this._token = CancellationToken.Cancelled;
}
else {
this._token.cancel();
}
}
dispose() {
if (!this._token) {
// ensure to initialize with an empty token if we had none
this._token = CancellationToken.None;
}
else if (this._token instanceof MutableToken) {
// actually dispose
this._token.dispose();
}
}
}
exports.CancellationTokenSource = CancellationTokenSource;
/***/ }),
/***/ 4054:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;
const ral_1 = __webpack_require__(5091);
const Is = __webpack_require__(6618);
const messages_1 = __webpack_require__(7162);
const linkedMap_1 = __webpack_require__(1109);
const events_1 = __webpack_require__(2479);
const cancellation_1 = __webpack_require__(6957);
var CancelNotification;
(function (CancelNotification) {
CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
})(CancelNotification || (CancelNotification = {}));
var ProgressToken;
(function (ProgressToken) {
function is(value) {
return typeof value === 'string' || typeof value === 'number';
}
ProgressToken.is = is;
})(ProgressToken = exports.ProgressToken || (exports.ProgressToken = {}));
var ProgressNotification;
(function (ProgressNotification) {
ProgressNotification.type = new messages_1.NotificationType('$/progress');
})(ProgressNotification || (ProgressNotification = {}));
class ProgressType {
constructor() {
}
}
exports.ProgressType = ProgressType;
var StarRequestHandler;
(function (StarRequestHandler) {
function is(value) {
return Is.func(value);
}
StarRequestHandler.is = is;
})(StarRequestHandler || (StarRequestHandler = {}));
exports.NullLogger = Object.freeze({
error: () => { },
warn: () => { },
info: () => { },
log: () => { }
});
var Trace;
(function (Trace) {
Trace[Trace["Off"] = 0] = "Off";
Trace[Trace["Messages"] = 1] = "Messages";
Trace[Trace["Compact"] = 2] = "Compact";
Trace[Trace["Verbose"] = 3] = "Verbose";
})(Trace = exports.Trace || (exports.Trace = {}));
var TraceValues;
(function (TraceValues) {
/**
* Turn tracing off.
*/
TraceValues.Off = 'off';
/**
* Trace messages only.
*/
TraceValues.Messages = 'messages';
/**
* Compact message tracing.
*/
TraceValues.Compact = 'compact';
/**
* Verbose message tracing.
*/
TraceValues.Verbose = 'verbose';
})(TraceValues = exports.TraceValues || (exports.TraceValues = {}));
(function (Trace) {
function fromString(value) {
if (!Is.string(value)) {
return Trace.Off;
}
value = value.toLowerCase();
switch (value) {
case 'off':
return Trace.Off;
case 'messages':
return Trace.Messages;
case 'compact':
return Trace.Compact;
case 'verbose':
return Trace.Verbose;
default:
return Trace.Off;
}
}
Trace.fromString = fromString;
function toString(value) {
switch (value) {
case Trace.Off:
return 'off';
case Trace.Messages:
return 'messages';
case Trace.Compact:
return 'compact';
case Trace.Verbose:
return 'verbose';
default:
return 'off';
}
}
Trace.toString = toString;
})(Trace = exports.Trace || (exports.Trace = {}));
var TraceFormat;
(function (TraceFormat) {
TraceFormat["Text"] = "text";
TraceFormat["JSON"] = "json";
})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
(function (TraceFormat) {
function fromString(value) {
if (!Is.string(value)) {
return TraceFormat.Text;
}
value = value.toLowerCase();
if (value === 'json') {
return TraceFormat.JSON;
}
else {
return TraceFormat.Text;
}
}
TraceFormat.fromString = fromString;
})(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
var SetTraceNotification;
(function (SetTraceNotification) {
SetTraceNotification.type = new messages_1.NotificationType('$/setTrace');
})(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
var LogTraceNotification;
(function (LogTraceNotification) {
LogTraceNotification.type = new messages_1.NotificationType('$/logTrace');
})(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
var ConnectionErrors;
(function (ConnectionErrors) {
/**
* The connection is closed.
*/
ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
/**
* The connection got disposed.
*/
ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
/**
* The connection is already in listening mode.
*/
ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
})(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
class ConnectionError extends Error {
constructor(code, message) {
super(message);
this.code = code;
Object.setPrototypeOf(this, ConnectionError.prototype);
}
}
exports.ConnectionError = ConnectionError;
var ConnectionStrategy;
(function (ConnectionStrategy) {
function is(value) {
const candidate = value;
return candidate && Is.func(candidate.cancelUndispatched);
}
ConnectionStrategy.is = is;
})(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
var IdCancellationReceiverStrategy;
(function (IdCancellationReceiverStrategy) {
function is(value) {
const candidate = value;
return candidate && (candidate.kind === undefined || candidate.kind === 'id') && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
}
IdCancellationReceiverStrategy.is = is;
})(IdCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = {}));
var RequestCancellationReceiverStrategy;
(function (RequestCancellationReceiverStrategy) {
function is(value) {
const candidate = value;
return candidate && candidate.kind === 'request' && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
}
RequestCancellationReceiverStrategy.is = is;
})(RequestCancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = {}));
var CancellationReceiverStrategy;
(function (CancellationReceiverStrategy) {
CancellationReceiverStrategy.Message = Object.freeze({
createCancellationTokenSource(_) {
return new cancellation_1.CancellationTokenSource();
}
});
function is(value) {
return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
}
CancellationReceiverStrategy.is = is;
})(CancellationReceiverStrategy = exports.CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = {}));
var CancellationSenderStrategy;
(function (CancellationSenderStrategy) {
CancellationSenderStrategy.Message = Object.freeze({
sendCancellation(conn, id) {
return conn.sendNotification(CancelNotification.type, { id });
},
cleanup(_) { }
});
function is(value) {
const candidate = value;
return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
}
CancellationSenderStrategy.is = is;
})(CancellationSenderStrategy = exports.CancellationSenderStrategy || (exports.CancellationSenderStrategy = {}));
var CancellationStrategy;
(function (CancellationStrategy) {
CancellationStrategy.Message = Object.freeze({
receiver: CancellationReceiverStrategy.Message,
sender: CancellationSenderStrategy.Message
});
function is(value) {
const candidate = value;
return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
}
CancellationStrategy.is = is;
})(CancellationStrategy = exports.CancellationStrategy || (exports.CancellationStrategy = {}));
var MessageStrategy;
(function (MessageStrategy) {
function is(value) {
const candidate = value;
return candidate && Is.func(candidate.handleMessage);
}
MessageStrategy.is = is;
})(MessageStrategy = exports.MessageStrategy || (exports.MessageStrategy = {}));
var ConnectionOptions;
(function (ConnectionOptions) {
function is(value) {
const candidate = value;
return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
}
ConnectionOptions.is = is;
})(ConnectionOptions = exports.ConnectionOptions || (exports.ConnectionOptions = {}));
var ConnectionState;
(function (ConnectionState) {
ConnectionState[ConnectionState["New"] = 1] = "New";
ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
})(ConnectionState || (ConnectionState = {}));
function createMessageConnection(messageReader, messageWriter, _logger, options) {
const logger = _logger !== undefined ? _logger : exports.NullLogger;
let sequenceNumber = 0;
let notificationSequenceNumber = 0;
let unknownResponseSequenceNumber = 0;
const version = '2.0';
let starRequestHandler = undefined;
const requestHandlers = new Map();
let starNotificationHandler = undefined;
const notificationHandlers = new Map();
const progressHandlers = new Map();
let timer;
let messageQueue = new linkedMap_1.LinkedMap();
let responsePromises = new Map();
let knownCanceledRequests = new Set();
let requestTokens = new Map();
let trace = Trace.Off;
let traceFormat = TraceFormat.Text;
let tracer;
let state = ConnectionState.New;
const errorEmitter = new events_1.Emitter();
const closeEmitter = new events_1.Emitter();
const unhandledNotificationEmitter = new events_1.Emitter();
const unhandledProgressEmitter = new events_1.Emitter();
const disposeEmitter = new events_1.Emitter();
const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message;
function createRequestQueueKey(id) {
if (id === null) {
throw new Error(`Can't send requests with id null since the response can't be correlated.`);
}
return 'req-' + id.toString();
}
function createResponseQueueKey(id) {
if (id === null) {
return 'res-unknown-' + (++unknownResponseSequenceNumber).toString();
}
else {
return 'res-' + id.toString();
}
}
function createNotificationQueueKey() {
return 'not-' + (++notificationSequenceNumber).toString();
}
function addMessageToQueue(queue, message) {
if (messages_1.Message.isRequest(message)) {
queue.set(createRequestQueueKey(message.id), message);
}
else if (messages_1.Message.isResponse(message)) {
queue.set(createResponseQueueKey(message.id), message);
}
else {
queue.set(createNotificationQueueKey(), message);
}
}
function cancelUndispatched(_message) {
return undefined;
}
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(undefined);
}
// If the connection is disposed don't sent close events.
}
function readErrorHandler(error) {
errorEmitter.fire([error, undefined, undefined]);
}
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 = (0, ral_1.default)().timer.setImmediate(() => {
timer = undefined;
processMessageQueue();
});
}
function handleMessage(message) {
if (messages_1.Message.isRequest(message)) {
handleRequest(message);
}
else if (messages_1.Message.isNotification(message)) {
handleNotification(message);
}
else if (messages_1.Message.isResponse(message)) {
handleResponse(message);
}
else {
handleInvalidMessage(message);
}
}
function processMessageQueue() {
if (messageQueue.size === 0) {
return;
}
const message = messageQueue.shift();
try {
const messageStrategy = options?.messageStrategy;
if (MessageStrategy.is(messageStrategy)) {
messageStrategy.handleMessage(message, handleMessage);
}
else {
handleMessage(message);
}
}
finally {
triggerMessageQueue();
}
}
const callback = (message) => {
try {
// We have received a cancellation message. Check if the message is still in the queue
// and cancel it if allowed to do so.
if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
const cancelId = message.params.id;
const key = createRequestQueueKey(cancelId);
const toCancel = messageQueue.get(key);
if (messages_1.Message.isRequest(toCancel)) {
const strategy = options?.connectionStrategy;
const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
if (response && (response.error !== undefined || response.result !== undefined)) {
messageQueue.delete(key);
requestTokens.delete(cancelId);
response.id = toCancel.id;
traceSendingResponse(response, message.method, Date.now());
messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
return;
}
}
const cancellationToken = requestTokens.get(cancelId);
// The request is already running. Cancel the token
if (cancellationToken !== undefined) {
cancellationToken.cancel();
traceReceivedNotification(message);
return;
}
else {
// Remember the cancel but still queue the message to
// clean up state in process message.
knownCanceledRequests.add(cancelId);
}
}
addMessageToQueue(messageQueue, message);
}
finally {
triggerMessageQueue();
}
};
function handleRequest(requestMessage) {
if (isDisposed()) {
// we return here silently since we fired an event when the
// connection got disposed.
return;
}
function reply(resultOrError, method, startTime) {
const message = {
jsonrpc: version,
id: requestMessage.id
};
if (resultOrError instanceof messages_1.ResponseError) {
message.error = resultOrError.toJson();
}
else {
message.result = resultOrError === undefined ? null : resultOrError;
}
traceSendingResponse(message, method, startTime);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
function replyError(error, method, startTime) {
const message = {
jsonrpc: version,
id: requestMessage.id,
error: error.toJson()
};
traceSendingResponse(message, method, startTime);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
function replySuccess(result, method, startTime) {
// The JSON RPC defines that a response must either have a result or an error
// So we can't treat undefined as a valid response result.
if (result === undefined) {
result = null;
}
const message = {
jsonrpc: version,
id: requestMessage.id,
result: result
};
traceSendingResponse(message, method, startTime);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
traceReceivedRequest(requestMessage);
const element = requestHandlers.get(requestMessage.method);
let type;
let requestHandler;
if (element) {
type = element.type;
requestHandler = element.handler;
}
const startTime = Date.now();
if (requestHandler || starRequestHandler) {
const tokenKey = requestMessage.id ?? String(Date.now()); //
const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver)
? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey)
: cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
cancellationSource.cancel();
}
if (requestMessage.id !== null) {
requestTokens.set(tokenKey, cancellationSource);
}
try {
let handlerResult;
if (requestHandler) {
if (requestMessage.params === undefined) {
if (type !== undefined && type.numberOfParams !== 0) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(cancellationSource.token);
}
else if (Array.isArray(requestMessage.params)) {
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
}
else {
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
}
}
else if (starRequestHandler) {
handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
}
const promise = handlerResult;
if (!handlerResult) {
requestTokens.delete(tokenKey);
replySuccess(handlerResult, requestMessage.method, startTime);
}
else if (promise.then) {
promise.then((resultOrError) => {
requestTokens.delete(tokenKey);
reply(resultOrError, requestMessage.method, startTime);
}, error => {
requestTokens.delete(tokenKey);
if (error instanceof messages_1.ResponseError) {
replyError(error, requestMessage.method, startTime);
}
else if (error && Is.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 {
requestTokens.delete(tokenKey);
reply(handlerResult, requestMessage.method, startTime);
}
}
catch (error) {
requestTokens.delete(tokenKey);
if (error instanceof messages_1.ResponseError) {
reply(error, requestMessage.method, startTime);
}
else if (error && Is.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()) {
// See handle request.
return;
}
if (responseMessage.id === null) {
if (responseMessage.error) {
logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
}
else {
logger.error(`Received response message without id. No further error information provided.`);
}
}
else {
const key = responseMessage.id;
const responsePromise = responsePromises.get(key);
traceReceivedResponse(responseMessage, responsePromise);
if (responsePromise !== undefined) {
responsePromises.delete(key);
try {
if (responseMessage.error) {
const error = responseMessage.error;
responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
}
else if (responseMessage.result !== undefined) {
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()) {
// See handle request.
return;
}
let type = undefined;
let notificationHandler;
if (message.method === CancelNotification.type.method) {
const cancelId = message.params.id;
knownCanceledRequests.delete(cancelId);
traceReceivedNotification(message);
return;
}
else {
const element = notificationHandlers.get(message.method);
if (element) {
notificationHandler = element.handler;
type = element.type;
}
}
if (notificationHandler || starNotificationHandler) {
try {
traceReceivedNotification(message);
if (notificationHandler) {
if (message.params === undefined) {
if (type !== undefined) {
if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
}
}
notificationHandler();
}
else if (Array.isArray(message.params)) {
// There are JSON-RPC libraries that send progress message as positional params although
// specified as named. So convert them if this is the case.
const params = message.params;
if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
notificationHandler({ token: params[0], value: params[1] });
}
else {
if (type !== undefined) {
if (type.parameterStructures === messages_1.ParameterStructures.byName) {
logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
}
if (type.numberOfParams !== message.params.length) {
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
}
}
notificationHandler(...params);
}
}
else {
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
}
notificationHandler(message.params);
}
}
else if (starNotificationHandler) {
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:\n${JSON.stringify(message, null, 4)}`);
// Test whether we find an id to reject the promise
const responseMessage = message;
if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
const key = responseMessage.id;
const responseHandler = responsePromises.get(key);
if (responseHandler) {
responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
}
}
}
function stringifyTrace(params) {
if (params === undefined || params === null) {
return undefined;
}
switch (trace) {
case Trace.Verbose:
return JSON.stringify(params, null, 4);
case Trace.Compact:
return JSON.stringify(params);
default:
return undefined;
}
}
function traceSendingRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = undefined;
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
data = `Params: ${stringifyTrace(message.params)}\n\n`;
}
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 = undefined;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.params) {
data = `Params: ${stringifyTrace(message.params)}\n\n`;
}
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 = undefined;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.error && message.error.data) {
data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
}
else {
if (message.result) {
data = `Result: ${stringifyTrace(message.result)}\n\n`;
}
else if (message.error === undefined) {
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 = undefined;
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
data = `Params: ${stringifyTrace(message.params)}\n\n`;
}
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 = undefined;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.params) {
data = `Params: ${stringifyTrace(message.params)}\n\n`;
}
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 = undefined;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.error && message.error.data) {
data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
}
else {
if (message.result) {
data = `Result: ${stringifyTrace(message.result)}\n\n`;
}
else if (message.error === undefined) {
data = 'No result returned.\n\n';
}
}
}
if (responsePromise) {
const 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 === undefined) {
return null;
}
else {
return param;
}
}
function nullToUndefined(param) {
if (param === null) {
return undefined;
}
else {
return param;
}
}
function isNamedParam(param) {
return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object';
}
function computeSingleParam(parameterStructures, param) {
switch (parameterStructures) {
case messages_1.ParameterStructures.auto:
if (isNamedParam(param)) {
return nullToUndefined(param);
}
else {
return [undefinedToNull(param)];
}
case messages_1.ParameterStructures.byName:
if (!isNamedParam(param)) {
throw new Error(`Received parameters by name but param is not an object literal.`);
}
return nullToUndefined(param);
case messages_1.ParameterStructures.byPosition:
return [undefinedToNull(param)];
default:
throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
}
}
function computeMessageParams(type, params) {
let result;
const numberOfParams = type.numberOfParams;
switch (numberOfParams) {
case 0:
result = undefined;
break;
case 1:
result = computeSingleParam(type.parameterStructures, 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;
}
const connection = {
sendNotification: (type, ...args) => {
throwIfClosedOrDisposed();
let method;
let messageParams;
if (Is.string(type)) {
method = type;
const first = args[0];
let paramStart = 0;
let parameterStructures = messages_1.ParameterStructures.auto;
if (messages_1.ParameterStructures.is(first)) {
paramStart = 1;
parameterStructures = first;
}
let paramEnd = args.length;
const numberOfParams = paramEnd - paramStart;
switch (numberOfParams) {
case 0:
messageParams = undefined;
break;
case 1:
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
break;
default:
if (parameterStructures === messages_1.ParameterStructures.byName) {
throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
}
messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));
break;
}
}
else {
const params = args;
method = type.method;
messageParams = computeMessageParams(type, params);
}
const notificationMessage = {
jsonrpc: version,
method: method,
params: messageParams
};
traceSendingNotification(notificationMessage);
return messageWriter.write(notificationMessage).catch((error) => {
logger.error(`Sending notification failed.`);
throw error;
});
},
onNotification: (type, handler) => {
throwIfClosedOrDisposed();
let method;
if (Is.func(type)) {
starNotificationHandler = type;
}
else if (handler) {
if (Is.string(type)) {
method = type;
notificationHandlers.set(type, { type: undefined, handler });
}
else {
method = type.method;
notificationHandlers.set(type.method, { type, handler });
}
}
return {
dispose: () => {
if (method !== undefined) {
notificationHandlers.delete(method);
}
else {
starNotificationHandler = undefined;
}
}
};
},
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) => {
// This should not await but simple return to ensure that we don't have another
// async scheduling. Otherwise one send could overtake another send.
return connection.sendNotification(ProgressNotification.type, { token, value });
},
onUnhandledProgress: unhandledProgressEmitter.event,
sendRequest: (type, ...args) => {
throwIfClosedOrDisposed();
throwIfNotListening();
let method;
let messageParams;
let token = undefined;
if (Is.string(type)) {
method = type;
const first = args[0];
const last = args[args.length - 1];
let paramStart = 0;
let parameterStructures = messages_1.ParameterStructures.auto;
if (messages_1.ParameterStructures.is(first)) {
paramStart = 1;
parameterStructures = first;
}
let paramEnd = args.length;
if (cancellation_1.CancellationToken.is(last)) {
paramEnd = paramEnd - 1;
token = last;
}
const numberOfParams = paramEnd - paramStart;
switch (numberOfParams) {
case 0:
messageParams = undefined;
break;
case 1:
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
break;
default:
if (parameterStructures === messages_1.ParameterStructures.byName) {
throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
}
messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value));
break;
}
}
else {
const params = args;
method = type.method;
messageParams = computeMessageParams(type, params);
const numberOfParams = type.numberOfParams;
token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
}
const id = sequenceNumber++;
let disposable;
if (token) {
disposable = token.onCancellationRequested(() => {
const p = cancellationStrategy.sender.sendCancellation(connection, id);
if (p === undefined) {
logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
return Promise.resolve();
}
else {
return p.catch(() => {
logger.log(`Sending cancellation messages for id ${id} failed`);
});
}
});
}
const requestMessage = {
jsonrpc: version,
id: id,
method: method,
params: messageParams
};
traceSendingRequest(requestMessage);
if (typeof cancellationStrategy.sender.enableCancellation === 'function') {
cancellationStrategy.sender.enableCancellation(requestMessage);
}
return new Promise(async (resolve, reject) => {
const resolveWithCleanup = (r) => {
resolve(r);
cancellationStrategy.sender.cleanup(id);
disposable?.dispose();
};
const rejectWithCleanup = (r) => {
reject(r);
cancellationStrategy.sender.cleanup(id);
disposable?.dispose();
};
const responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
try {
await messageWriter.write(requestMessage);
responsePromises.set(id, responsePromise);
}
catch (error) {
logger.error(`Sending request failed.`);
// Writing the message failed. So we need to reject the promise.
responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason'));
throw error;
}
});
},
onRequest: (type, handler) => {
throwIfClosedOrDisposed();
let method = null;
if (StarRequestHandler.is(type)) {
method = undefined;
starRequestHandler = type;
}
else if (Is.string(type)) {
method = null;
if (handler !== undefined) {
method = type;
requestHandlers.set(type, { handler: handler, type: undefined });
}
}
else {
if (handler !== undefined) {
method = type.method;
requestHandlers.set(type.method, { type, handler });
}
}
return {
dispose: () => {
if (method === null) {
return;
}
if (method !== undefined) {
requestHandlers.delete(method);
}
else {
starRequestHandler = undefined;
}
}
};
},
hasPendingResponse: () => {
return responsePromises.size > 0;
},
trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
let _sendNotification = false;
let _traceFormat = TraceFormat.Text;
if (sendNotificationOrTraceOptions !== undefined) {
if (Is.boolean(sendNotificationOrTraceOptions)) {
_sendNotification = sendNotificationOrTraceOptions;
}
else {
_sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
_traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
}
}
trace = _value;
traceFormat = _traceFormat;
if (trace === Trace.Off) {
tracer = undefined;
}
else {
tracer = _tracer;
}
if (_sendNotification && !isClosed() && !isDisposed()) {
await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
}
},
onError: errorEmitter.event,
onClose: closeEmitter.event,
onUnhandledNotification: unhandledNotificationEmitter.event,
onDispose: disposeEmitter.event,
end: () => {
messageWriter.end();
},
dispose: () => {
if (isDisposed()) {
return;
}
state = ConnectionState.Disposed;
disposeEmitter.fire(undefined);
const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, 'Pending response rejected since connection got disposed');
for (const promise of responsePromises.values()) {
promise.reject(error);
}
responsePromises = new Map();
requestTokens = new Map();
knownCanceledRequests = new Set();
messageQueue = new linkedMap_1.LinkedMap();
// Test for backwards compatibility
if (Is.func(messageWriter.dispose)) {
messageWriter.dispose();
}
if (Is.func(messageReader.dispose)) {
messageReader.dispose();
}
},
listen: () => {
throwIfClosedOrDisposed();
throwIfListening();
state = ConnectionState.Listening;
messageReader.listen(callback);
},
inspect: () => {
// eslint-disable-next-line no-console
(0, ral_1.default)().console.log('inspect');
}
};
connection.onNotification(LogTraceNotification.type, (params) => {
if (trace === Trace.Off || !tracer) {
return;
}
const verbose = trace === Trace.Verbose || trace === Trace.Compact;
tracer.log(params.message, verbose ? params.verbose : undefined);
});
connection.onNotification(ProgressNotification.type, (params) => {
const handler = progressHandlers.get(params.token);
if (handler) {
handler(params.value);
}
else {
unhandledProgressEmitter.fire(params);
}
});
return connection;
}
exports.createMessageConnection = createMessageConnection;
/***/ }),
/***/ 8844:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Disposable = void 0;
var Disposable;
(function (Disposable) {
function create(func) {
return {
dispose: func
};
}
Disposable.create = create;
})(Disposable = exports.Disposable || (exports.Disposable = {}));
/***/ }),
/***/ 2479:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Emitter = exports.Event = void 0;
const ral_1 = __webpack_require__(5091);
var Event;
(function (Event) {
const _disposable = { dispose() { } };
Event.None = function () { return _disposable; };
})(Event = exports.Event || (exports.Event = {}));
class CallbackList {
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;
}
let foundCallbackWithDifferentContext = false;
for (let i = 0, len = this._callbacks.length; i < len; i++) {
if (this._callbacks[i] === callback) {
if (this._contexts[i] === context) {
// callback & context match => remove it
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 [];
}
const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
for (let i = 0, len = callbacks.length; i < len; i++) {
try {
ret.push(callbacks[i].apply(contexts[i], args));
}
catch (e) {
// eslint-disable-next-line no-console
(0, ral_1.default)().console.error(e);
}
}
return ret;
}
isEmpty() {
return !this._callbacks || this._callbacks.length === 0;
}
dispose() {
this._callbacks = undefined;
this._contexts = undefined;
}
}
class Emitter {
constructor(_options) {
this._options = _options;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
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);
const result = {
dispose: () => {
if (!this._callbacks) {
// disposable is disposed after emitter is disposed.
return;
}
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;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
if (this._callbacks) {
this._callbacks.invoke.call(this._callbacks, event);
}
}
dispose() {
if (this._callbacks) {
this._callbacks.dispose();
this._callbacks = undefined;
}
}
}
exports.Emitter = Emitter;
Emitter._noop = function () { };
/***/ }),
/***/ 6618:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return typeof value === 'string' || value instanceof String;
}
exports.string = string;
function number(value) {
return typeof value === 'number' || value instanceof Number;
}
exports.number = number;
function error(value) {
return value instanceof Error;
}
exports.error = error;
function func(value) {
return typeof value === 'function';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(elem => string(elem));
}
exports.stringArray = stringArray;
/***/ }),
/***/ 1109:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LRUCache = exports.LinkedMap = exports.Touch = void 0;
var Touch;
(function (Touch) {
Touch.None = 0;
Touch.First = 1;
Touch.AsOld = Touch.First;
Touch.Last = 2;
Touch.AsNew = Touch.Last;
})(Touch = exports.Touch || (exports.Touch = {}));
class LinkedMap {
constructor() {
this[_a] = 'LinkedMap';
this._map = new Map();
this._head = undefined;
this._tail = undefined;
this._size = 0;
this._state = 0;
}
clear() {
this._map.clear();
this._head = undefined;
this._tail = undefined;
this._size = 0;
this._state++;
}
isEmpty() {
return !this._head && !this._tail;
}
get size() {
return this._size;
}
get first() {
return this._head?.value;
}
get last() {
return this._tail?.value;
}
has(key) {
return this._map.has(key);
}
get(key, touch = Touch.None) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
if (touch !== Touch.None) {
this.touch(item, touch);
}
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: undefined, previous: undefined };
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++;
}
return this;
}
delete(key) {
return !!this.remove(key);
}
remove(key) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return item.value;
}
shift() {
if (!this._head && !this._tail) {
return undefined;
}
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) {
const state = this._state;
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
}
else {
callbackfn(current.value, current.key, this);
}
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
current = current.next;
}
}
keys() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.key, done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
values() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.value, done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
entries() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: [current.key, current.value], done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
[(_a = Symbol.toStringTag, Symbol.iterator)]() {
return this.entries();
}
trimOld(newSize) {
if (newSize >= this.size) {
return;
}
if (newSize === 0) {
this.clear();
return;
}
let current = this._head;
let currentSize = this.size;
while (current && currentSize > newSize) {
this._map.delete(current.key);
current = current.next;
currentSize--;
}
this._head = current;
this._size = currentSize;
if (current) {
current.previous = undefined;
}
this._state++;
}
addItemFirst(item) {
// First time Insert
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;
this._state++;
}
addItemLast(item) {
// First time Insert
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;
this._state++;
}
removeItem(item) {
if (item === this._head && item === this._tail) {
this._head = undefined;
this._tail = undefined;
}
else if (item === this._head) {
// This can only happened if size === 1 which is handle
// by the case above.
if (!item.next) {
throw new Error('Invalid list');
}
item.next.previous = undefined;
this._head = item.next;
}
else if (item === this._tail) {
// This can only happened if size === 1 which is handle
// by the case above.
if (!item.previous) {
throw new Error('Invalid list');
}
item.previous.next = undefined;
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;
}
item.next = undefined;
item.previous = undefined;
this._state++;
}
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;
// Unlink the item
if (item === this._tail) {
// previous must be defined since item was not head but is tail
// So there are more than on item in the map
previous.next = undefined;
this._tail = previous;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
// Insert the node at head
item.previous = undefined;
item.next = this._head;
this._head.previous = item;
this._head = item;
this._state++;
}
else if (touch === Touch.Last) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item.
if (item === this._head) {
// next must be defined since item was not tail but is head
// So there are more than on item in the map
next.previous = undefined;
this._head = next;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
item.next = undefined;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
this._state++;
}
}
toJSON() {
const data = [];
this.forEach((value, key) => {
data.push([key, value]);
});
return data;
}
fromJSON(data) {
this.clear();
for (const [key, value] of data) {
this.set(key, value);
}
}
}
exports.LinkedMap = LinkedMap;
class LRUCache extends LinkedMap {
constructor(limit, ratio = 1) {
super();
this._limit = limit;
this._ratio = Math.min(Math.max(0, ratio), 1);
}
get limit() {
return this._limit;
}
set limit(limit) {
this._limit = limit;
this.checkTrim();
}
get ratio() {
return this._ratio;
}
set ratio(ratio) {
this._ratio = Math.min(Math.max(0, ratio), 1);
this.checkTrim();
}
get(key, touch = Touch.AsNew) {
return super.get(key, touch);
}
peek(key) {
return super.get(key, Touch.None);
}
set(key, value) {
super.set(key, value, Touch.Last);
this.checkTrim();
return this;
}
checkTrim() {
if (this.size > this._limit) {
this.trimOld(Math.round(this._limit * this._ratio));
}
}
}
exports.LRUCache = LRUCache;
/***/ }),
/***/ 9805:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AbstractMessageBuffer = void 0;
const CR = 13;
const LF = 10;
const CRLF = '\r\n';
class AbstractMessageBuffer {
constructor(encoding = 'utf-8') {
this._encoding = encoding;
this._chunks = [];
this._totalLength = 0;
}
get encoding() {
return this._encoding;
}
append(chunk) {
const toAppend = typeof chunk === 'string' ? this.fromString(chunk, this._encoding) : chunk;
this._chunks.push(toAppend);
this._totalLength += toAppend.byteLength;
}
tryReadHeaders(lowerCaseKeys = false) {
if (this._chunks.length === 0) {
return undefined;
}
let state = 0;
let chunkIndex = 0;
let offset = 0;
let chunkBytesRead = 0;
row: while (chunkIndex < this._chunks.length) {
const chunk = this._chunks[chunkIndex];
offset = 0;
column: while (offset < chunk.length) {
const value = chunk[offset];
switch (value) {
case CR:
switch (state) {
case 0:
state = 1;
break;
case 2:
state = 3;
break;
default:
state = 0;
}
break;
case LF:
switch (state) {
case 1:
state = 2;
break;
case 3:
state = 4;
offset++;
break row;
default:
state = 0;
}
break;
default:
state = 0;
}
offset++;
}
chunkBytesRead += chunk.byteLength;
chunkIndex++;
}
if (state !== 4) {
return undefined;
}
// The buffer contains the two CRLF at the end. So we will
// have two empty lines after the split at the end as well.
const buffer = this._read(chunkBytesRead + offset);
const result = new Map();
const headers = this.toString(buffer, 'ascii').split(CRLF);
if (headers.length < 2) {
return result;
}
for (let i = 0; i < headers.length - 2; i++) {
const header = headers[i];
const index = header.indexOf(':');
if (index === -1) {
throw new Error('Message header must separate key and value using :');
}
const key = header.substr(0, index);
const value = header.substr(index + 1).trim();
result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
}
return result;
}
tryReadBody(length) {
if (this._totalLength < length) {
return undefined;
}
return this._read(length);
}
get numberOfBytes() {
return this._totalLength;
}
_read(byteCount) {
if (byteCount === 0) {
return this.emptyBuffer();
}
if (byteCount > this._totalLength) {
throw new Error(`Cannot read so many bytes!`);
}
if (this._chunks[0].byteLength === byteCount) {
// super fast path, precisely first chunk must be returned
const chunk = this._chunks[0];
this._chunks.shift();
this._totalLength -= byteCount;
return this.asNative(chunk);
}
if (this._chunks[0].byteLength > byteCount) {
// fast path, the reading is entirely within the first chunk
const chunk = this._chunks[0];
const result = this.asNative(chunk, byteCount);
this._chunks[0] = chunk.slice(byteCount);
this._totalLength -= byteCount;
return result;
}
const result = this.allocNative(byteCount);
let resultOffset = 0;
let chunkIndex = 0;
while (byteCount > 0) {
const chunk = this._chunks[chunkIndex];
if (chunk.byteLength > byteCount) {
// this chunk will survive
const chunkPart = chunk.slice(0, byteCount);
result.set(chunkPart, resultOffset);
resultOffset += byteCount;
this._chunks[chunkIndex] = chunk.slice(byteCount);
this._totalLength -= byteCount;
byteCount -= byteCount;
}
else {
// this chunk will be entirely read
result.set(chunk, resultOffset);
resultOffset += chunk.byteLength;
this._chunks.shift();
this._totalLength -= chunk.byteLength;
byteCount -= chunk.byteLength;
}
}
return result;
}
}
exports.AbstractMessageBuffer = AbstractMessageBuffer;
/***/ }),
/***/ 656:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;
const ral_1 = __webpack_require__(5091);
const Is = __webpack_require__(6618);
const events_1 = __webpack_require__(2479);
const semaphore_1 = __webpack_require__(418);
var MessageReader;
(function (MessageReader) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
}
MessageReader.is = is;
})(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
class AbstractMessageReader {
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(undefined);
}
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: ${Is.string(error.message) ? error.message : 'unknown'}`);
}
}
}
exports.AbstractMessageReader = AbstractMessageReader;
var ResolvedMessageReaderOptions;
(function (ResolvedMessageReaderOptions) {
function fromOptions(options) {
let charset;
let result;
let contentDecoder;
const contentDecoders = new Map();
let contentTypeDecoder;
const contentTypeDecoders = new Map();
if (options === undefined || typeof options === 'string') {
charset = options ?? 'utf-8';
}
else {
charset = options.charset ?? 'utf-8';
if (options.contentDecoder !== undefined) {
contentDecoder = options.contentDecoder;
contentDecoders.set(contentDecoder.name, contentDecoder);
}
if (options.contentDecoders !== undefined) {
for (const decoder of options.contentDecoders) {
contentDecoders.set(decoder.name, decoder);
}
}
if (options.contentTypeDecoder !== undefined) {
contentTypeDecoder = options.contentTypeDecoder;
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
}
if (options.contentTypeDecoders !== undefined) {
for (const decoder of options.contentTypeDecoders) {
contentTypeDecoders.set(decoder.name, decoder);
}
}
}
if (contentTypeDecoder === undefined) {
contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
}
return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
}
ResolvedMessageReaderOptions.fromOptions = fromOptions;
})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
class ReadableStreamMessageReader extends AbstractMessageReader {
constructor(readable, options) {
super();
this.readable = readable;
this.options = ResolvedMessageReaderOptions.fromOptions(options);
this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
this._partialMessageTimeout = 10000;
this.nextMessageLength = -1;
this.messageToken = 0;
this.readSemaphore = new semaphore_1.Semaphore(1);
}
set partialMessageTimeout(timeout) {
this._partialMessageTimeout = timeout;
}
get partialMessageTimeout() {
return this._partialMessageTimeout;
}
listen(callback) {
this.nextMessageLength = -1;
this.messageToken = 0;
this.partialMessageTimer = undefined;
this.callback = callback;
const result = this.readable.onData((data) => {
this.onData(data);
});
this.readable.onError((error) => this.fireError(error));
this.readable.onClose(() => this.fireClose());
return result;
}
onData(data) {
this.buffer.append(data);
while (true) {
if (this.nextMessageLength === -1) {
const headers = this.buffer.tryReadHeaders(true);
if (!headers) {
return;
}
const contentLength = headers.get('content-length');
if (!contentLength) {
this.fireError(new Error('Header must provide a Content-Length property.'));
return;
}
const length = parseInt(contentLength);
if (isNaN(length)) {
this.fireError(new Error('Content-Length value must be a number.'));
return;
}
this.nextMessageLength = length;
}
const body = this.buffer.tryReadBody(this.nextMessageLength);
if (body === undefined) {
/** We haven't received the full message yet. */
this.setPartialMessageTimer();
return;
}
this.clearPartialMessageTimer();
this.nextMessageLength = -1;
// Make sure that we convert one received message after the
// other. Otherwise it could happen that a decoding of a second
// smaller message finished before the decoding of a first larger
// message and then we would deliver the second message first.
this.readSemaphore.lock(async () => {
const bytes = this.options.contentDecoder !== undefined
? await this.options.contentDecoder.decode(body)
: body;
const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
this.callback(message);
}).catch((error) => {
this.fireError(error);
});
}
}
clearPartialMessageTimer() {
if (this.partialMessageTimer) {
this.partialMessageTimer.dispose();
this.partialMessageTimer = undefined;
}
}
setPartialMessageTimer() {
this.clearPartialMessageTimer();
if (this._partialMessageTimeout <= 0) {
return;
}
this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
this.partialMessageTimer = undefined;
if (token === this.messageToken) {
this.firePartialMessage({ messageToken: token, waitingTime: timeout });
this.setPartialMessageTimer();
}
}, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
}
}
exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
/***/ }),
/***/ 9036:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;
const ral_1 = __webpack_require__(5091);
const Is = __webpack_require__(6618);
const semaphore_1 = __webpack_require__(418);
const events_1 = __webpack_require__(2479);
const ContentLength = 'Content-Length: ';
const CRLF = '\r\n';
var MessageWriter;
(function (MessageWriter) {
function is(value) {
let candidate = value;
return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
Is.func(candidate.onError) && Is.func(candidate.write);
}
MessageWriter.is = is;
})(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
class AbstractMessageWriter {
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(undefined);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
}
}
}
exports.AbstractMessageWriter = AbstractMessageWriter;
var ResolvedMessageWriterOptions;
(function (ResolvedMessageWriterOptions) {
function fromOptions(options) {
if (options === undefined || typeof options === 'string') {
return { charset: options ?? 'utf-8', contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
}
else {
return { charset: options.charset ?? 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
}
}
ResolvedMessageWriterOptions.fromOptions = fromOptions;
})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
class WriteableStreamMessageWriter extends AbstractMessageWriter {
constructor(writable, options) {
super();
this.writable = writable;
this.options = ResolvedMessageWriterOptions.fromOptions(options);
this.errorCount = 0;
this.writeSemaphore = new semaphore_1.Semaphore(1);
this.writable.onError((error) => this.fireError(error));
this.writable.onClose(() => this.fireClose());
}
async write(msg) {
return this.writeSemaphore.lock(async () => {
const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
if (this.options.contentEncoder !== undefined) {
return this.options.contentEncoder.encode(buffer);
}
else {
return buffer;
}
});
return payload.then((buffer) => {
const headers = [];
headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
headers.push(CRLF);
return this.doWrite(msg, headers, buffer);
}, (error) => {
this.fireError(error);
throw error;
});
});
}
async doWrite(msg, headers, data) {
try {
await this.writable.write(headers.join(''), 'ascii');
return this.writable.write(data);
}
catch (error) {
this.handleError(error, msg);
return Promise.reject(error);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
end() {
this.writable.end();
}
}
exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
/***/ }),
/***/ 7162:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;
const is = __webpack_require__(6618);
/**
* Predefined error codes.
*/
var ErrorCodes;
(function (ErrorCodes) {
// Defined by JSON RPC
ErrorCodes.ParseError = -32700;
ErrorCodes.InvalidRequest = -32600;
ErrorCodes.MethodNotFound = -32601;
ErrorCodes.InvalidParams = -32602;
ErrorCodes.InternalError = -32603;
/**
* This is the start range of JSON RPC reserved error codes.
* It doesn't denote a real error code. No application error codes should
* be defined between the start and end range. For backwards
* compatibility the `ServerNotInitialized` and the `UnknownErrorCode`
* are left in the range.
*
* @since 3.16.0
*/
ErrorCodes.jsonrpcReservedErrorRangeStart = -32099;
/** @deprecated use jsonrpcReservedErrorRangeStart */
ErrorCodes.serverErrorStart = -32099;
/**
* An error occurred when write a message to the transport layer.
*/
ErrorCodes.MessageWriteError = -32099;
/**
* An error occurred when reading a message from the transport layer.
*/
ErrorCodes.MessageReadError = -32098;
/**
* The connection got disposed or lost and all pending responses got
* rejected.
*/
ErrorCodes.PendingResponseRejected = -32097;
/**
* The connection is inactive and a use of it failed.
*/
ErrorCodes.ConnectionInactive = -32096;
/**
* Error code indicating that a server received a notification or
* request before the server has received the `initialize` request.
*/
ErrorCodes.ServerNotInitialized = -32002;
ErrorCodes.UnknownErrorCode = -32001;
/**
* This is the end range of JSON RPC reserved error codes.
* It doesn't denote a real error code.
*
* @since 3.16.0
*/
ErrorCodes.jsonrpcReservedErrorRangeEnd = -32000;
/** @deprecated use jsonrpcReservedErrorRangeEnd */
ErrorCodes.serverErrorEnd = -32000;
})(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
/**
* An error object return in a response in case a request
* has failed.
*/
class ResponseError 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() {
const result = {
code: this.code,
message: this.message
};
if (this.data !== undefined) {
result.data = this.data;
}
return result;
}
}
exports.ResponseError = ResponseError;
class ParameterStructures {
constructor(kind) {
this.kind = kind;
}
static is(value) {
return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
}
toString() {
return this.kind;
}
}
exports.ParameterStructures = ParameterStructures;
/**
* The parameter structure is automatically inferred on the number of parameters
* and the parameter type in case of a single param.
*/
ParameterStructures.auto = new ParameterStructures('auto');
/**
* Forces `byPosition` parameter structure. This is useful if you have a single
* parameter which has a literal type.
*/
ParameterStructures.byPosition = new ParameterStructures('byPosition');
/**
* Forces `byName` parameter structure. This is only useful when having a single
* parameter. The library will report errors if used with a different number of
* parameters.
*/
ParameterStructures.byName = new ParameterStructures('byName');
/**
* An abstract implementation of a MessageType.
*/
class AbstractMessageSignature {
constructor(method, numberOfParams) {
this.method = method;
this.numberOfParams = numberOfParams;
}
get parameterStructures() {
return ParameterStructures.auto;
}
}
exports.AbstractMessageSignature = AbstractMessageSignature;
/**
* Classes to type request response pairs
*/
class RequestType0 extends AbstractMessageSignature {
constructor(method) {
super(method, 0);
}
}
exports.RequestType0 = RequestType0;
class RequestType extends AbstractMessageSignature {
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
}
exports.RequestType = RequestType;
class RequestType1 extends AbstractMessageSignature {
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
}
exports.RequestType1 = RequestType1;
class RequestType2 extends AbstractMessageSignature {
constructor(method) {
super(method, 2);
}
}
exports.RequestType2 = RequestType2;
class RequestType3 extends AbstractMessageSignature {
constructor(method) {
super(method, 3);
}
}
exports.RequestType3 = RequestType3;
class RequestType4 extends AbstractMessageSignature {
constructor(method) {
super(method, 4);
}
}
exports.RequestType4 = RequestType4;
class RequestType5 extends AbstractMessageSignature {
constructor(method) {
super(method, 5);
}
}
exports.RequestType5 = RequestType5;
class RequestType6 extends AbstractMessageSignature {
constructor(method) {
super(method, 6);
}
}
exports.RequestType6 = RequestType6;
class RequestType7 extends AbstractMessageSignature {
constructor(method) {
super(method, 7);
}
}
exports.RequestType7 = RequestType7;
class RequestType8 extends AbstractMessageSignature {
constructor(method) {
super(method, 8);
}
}
exports.RequestType8 = RequestType8;
class RequestType9 extends AbstractMessageSignature {
constructor(method) {
super(method, 9);
}
}
exports.RequestType9 = RequestType9;
class NotificationType extends AbstractMessageSignature {
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
}
exports.NotificationType = NotificationType;
class NotificationType0 extends AbstractMessageSignature {
constructor(method) {
super(method, 0);
}
}
exports.NotificationType0 = NotificationType0;
class NotificationType1 extends AbstractMessageSignature {
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
}
exports.NotificationType1 = NotificationType1;
class NotificationType2 extends AbstractMessageSignature {
constructor(method) {
super(method, 2);
}
}
exports.NotificationType2 = NotificationType2;
class NotificationType3 extends AbstractMessageSignature {
constructor(method) {
super(method, 3);
}
}
exports.NotificationType3 = NotificationType3;
class NotificationType4 extends AbstractMessageSignature {
constructor(method) {
super(method, 4);
}
}
exports.NotificationType4 = NotificationType4;
class NotificationType5 extends AbstractMessageSignature {
constructor(method) {
super(method, 5);
}
}
exports.NotificationType5 = NotificationType5;
class NotificationType6 extends AbstractMessageSignature {
constructor(method) {
super(method, 6);
}
}
exports.NotificationType6 = NotificationType6;
class NotificationType7 extends AbstractMessageSignature {
constructor(method) {
super(method, 7);
}
}
exports.NotificationType7 = NotificationType7;
class NotificationType8 extends AbstractMessageSignature {
constructor(method) {
super(method, 8);
}
}
exports.NotificationType8 = NotificationType8;
class NotificationType9 extends AbstractMessageSignature {
constructor(method) {
super(method, 9);
}
}
exports.NotificationType9 = NotificationType9;
var Message;
(function (Message) {
/**
* Tests if the given message is a request message
*/
function isRequest(message) {
const candidate = message;
return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
}
Message.isRequest = isRequest;
/**
* Tests if the given message is a notification message
*/
function isNotification(message) {
const candidate = message;
return candidate && is.string(candidate.method) && message.id === void 0;
}
Message.isNotification = isNotification;
/**
* Tests if the given message is a response message
*/
function isResponse(message) {
const candidate = message;
return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
}
Message.isResponse = isResponse;
})(Message = exports.Message || (exports.Message = {}));
/***/ }),
/***/ 5091:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
let _ral;
function RAL() {
if (_ral === undefined) {
throw new Error(`No runtime abstraction layer installed`);
}
return _ral;
}
(function (RAL) {
function install(ral) {
if (ral === undefined) {
throw new Error(`No runtime abstraction layer provided`);
}
_ral = ral;
}
RAL.install = install;
})(RAL || (RAL = {}));
exports["default"] = RAL;
/***/ }),
/***/ 418:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Semaphore = void 0;
const ral_1 = __webpack_require__(5091);
class Semaphore {
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;
}
(0, ral_1.default)().timer.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();
}
}
}
exports.Semaphore = Semaphore;
/***/ }),
/***/ 3489:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;
const cancellation_1 = __webpack_require__(6957);
var CancellationState;
(function (CancellationState) {
CancellationState.Continue = 0;
CancellationState.Cancelled = 1;
})(CancellationState || (CancellationState = {}));
class SharedArraySenderStrategy {
constructor() {
this.buffers = new Map();
}
enableCancellation(request) {
if (request.id === null) {
return;
}
const buffer = new SharedArrayBuffer(4);
const data = new Int32Array(buffer, 0, 1);
data[0] = CancellationState.Continue;
this.buffers.set(request.id, buffer);
request.$cancellationData = buffer;
}
async sendCancellation(_conn, id) {
const buffer = this.buffers.get(id);
if (buffer === undefined) {
return;
}
const data = new Int32Array(buffer, 0, 1);
Atomics.store(data, 0, CancellationState.Cancelled);
}
cleanup(id) {
this.buffers.delete(id);
}
dispose() {
this.buffers.clear();
}
}
exports.SharedArraySenderStrategy = SharedArraySenderStrategy;
class SharedArrayBufferCancellationToken {
constructor(buffer) {
this.data = new Int32Array(buffer, 0, 1);
}
get isCancellationRequested() {
return Atomics.load(this.data, 0) === CancellationState.Cancelled;
}
get onCancellationRequested() {
throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
}
}
class SharedArrayBufferCancellationTokenSource {
constructor(buffer) {
this.token = new SharedArrayBufferCancellationToken(buffer);
}
cancel() {
}
dispose() {
}
}
class SharedArrayReceiverStrategy {
constructor() {
this.kind = 'request';
}
createCancellationTokenSource(request) {
const buffer = request.$cancellationData;
if (buffer === undefined) {
return new cancellation_1.CancellationTokenSource();
}
return new SharedArrayBufferCancellationTokenSource(buffer);
}
}
exports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
/***/ }),
/***/ 5501:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createProtocolConnection = void 0;
const browser_1 = __webpack_require__(9208);
__exportStar(__webpack_require__(9208), exports);
__exportStar(__webpack_require__(3147), exports);
function createProtocolConnection(reader, writer, logger, options) {
return (0, browser_1.createMessageConnection)(reader, writer, logger, options);
}
exports.createProtocolConnection = createProtocolConnection;
/***/ }),
/***/ 3147:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LSPErrorCodes = exports.createProtocolConnection = void 0;
__exportStar(__webpack_require__(9110), exports);
__exportStar(__webpack_require__(7717), exports);
__exportStar(__webpack_require__(8431), exports);
__exportStar(__webpack_require__(1815), exports);
var connection_1 = __webpack_require__(291);
Object.defineProperty(exports, "createProtocolConnection", ({ enumerable: true, get: function () { return connection_1.createProtocolConnection; } }));
var LSPErrorCodes;
(function (LSPErrorCodes) {
/**
* This is the start range of LSP reserved error codes.
* It doesn't denote a real error code.
*
* @since 3.16.0
*/
LSPErrorCodes.lspReservedErrorRangeStart = -32899;
/**
* A request failed but it was syntactically correct, e.g the
* method name was known and the parameters were valid. The error
* message should contain human readable information about why
* the request failed.
*
* @since 3.17.0
*/
LSPErrorCodes.RequestFailed = -32803;
/**
* The server cancelled the request. This error code should
* only be used for requests that explicitly support being
* server cancellable.
*
* @since 3.17.0
*/
LSPErrorCodes.ServerCancelled = -32802;
/**
* The server detected that the content of a document got
* modified outside normal conditions. A server should
* NOT send this error code if it detects a content change
* in it unprocessed messages. The result even computed
* on an older state might still be useful for the client.
*
* If a client decides that a result is not of any use anymore
* the client should cancel the request.
*/
LSPErrorCodes.ContentModified = -32801;
/**
* The client has canceled a request and a server as detected
* the cancel.
*/
LSPErrorCodes.RequestCancelled = -32800;
/**
* This is the end range of LSP reserved error codes.
* It doesn't denote a real error code.
*
* @since 3.16.0
*/
LSPErrorCodes.lspReservedErrorRangeEnd = -32800;
})(LSPErrorCodes = exports.LSPErrorCodes || (exports.LSPErrorCodes = {}));
/***/ }),
/***/ 291:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createProtocolConnection = void 0;
const vscode_jsonrpc_1 = __webpack_require__(9110);
function createProtocolConnection(input, output, logger, options) {
if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
options = { connectionStrategy: options };
}
return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
}
exports.createProtocolConnection = createProtocolConnection;
/***/ }),
/***/ 8431:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProtocolNotificationType = exports.ProtocolNotificationType0 = exports.ProtocolRequestType = exports.ProtocolRequestType0 = exports.RegistrationType = exports.MessageDirection = void 0;
const vscode_jsonrpc_1 = __webpack_require__(9110);
var MessageDirection;
(function (MessageDirection) {
MessageDirection["clientToServer"] = "clientToServer";
MessageDirection["serverToClient"] = "serverToClient";
MessageDirection["both"] = "both";
})(MessageDirection = exports.MessageDirection || (exports.MessageDirection = {}));
class RegistrationType {
constructor(method) {
this.method = method;
}
}
exports.RegistrationType = RegistrationType;
class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
constructor(method) {
super(method);
}
}
exports.ProtocolRequestType0 = ProtocolRequestType0;
class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
constructor(method) {
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
}
}
exports.ProtocolRequestType = ProtocolRequestType;
class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
constructor(method) {
super(method);
}
}
exports.ProtocolNotificationType0 = ProtocolNotificationType0;
class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
constructor(method) {
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
}
}
exports.ProtocolNotificationType = ProtocolNotificationType;
/***/ }),
/***/ 7602:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) TypeFox, Microsoft and others. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.CallHierarchyPrepareRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to result a `CallHierarchyItem` in a document at a given position.
* Can be used as an input to an incoming or outgoing call hierarchy.
*
* @since 3.16.0
*/
var CallHierarchyPrepareRequest;
(function (CallHierarchyPrepareRequest) {
CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
CallHierarchyPrepareRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
})(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
/**
* A request to resolve the incoming calls for a given `CallHierarchyItem`.
*
* @since 3.16.0
*/
var CallHierarchyIncomingCallsRequest;
(function (CallHierarchyIncomingCallsRequest) {
CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
CallHierarchyIncomingCallsRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
})(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
/**
* A request to resolve the outgoing calls for a given `CallHierarchyItem`.
*
* @since 3.16.0
*/
var CallHierarchyOutgoingCallsRequest;
(function (CallHierarchyOutgoingCallsRequest) {
CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
CallHierarchyOutgoingCallsRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
})(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
/***/ }),
/***/ 3747:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ColorPresentationRequest = exports.DocumentColorRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to list all color symbols found in a given text document. The request's
* parameter is of type {@link DocumentColorParams} the
* response is of type {@link ColorInformation ColorInformation[]} or a Thenable
* that resolves to such.
*/
var DocumentColorRequest;
(function (DocumentColorRequest) {
DocumentColorRequest.method = 'textDocument/documentColor';
DocumentColorRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
})(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
/**
* A request to list all presentation for a color. The request's
* parameter is of type {@link ColorPresentationParams} the
* response is of type {@link ColorInformation ColorInformation[]} or a Thenable
* that resolves to such.
*/
var ColorPresentationRequest;
(function (ColorPresentationRequest) {
ColorPresentationRequest.method = 'textDocument/colorPresentation';
ColorPresentationRequest.messageDirection = messages_1.MessageDirection.clientToServer;
ColorPresentationRequest.type = new messages_1.ProtocolRequestType(ColorPresentationRequest.method);
})(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
/***/ }),
/***/ 7639:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConfigurationRequest = void 0;
const messages_1 = __webpack_require__(8431);
//---- Get Configuration request ----
/**
* The 'workspace/configuration' request is sent from the server to the client to fetch a certain
* configuration setting.
*
* This pull model replaces the old push model were the client signaled configuration change via an
* event. If the server still needs to react to configuration changes (since the server caches the
* result of `workspace/configuration` requests) the server should register for an empty configuration
* change event and empty the cache if such an event is received.
*/
var ConfigurationRequest;
(function (ConfigurationRequest) {
ConfigurationRequest.method = 'workspace/configuration';
ConfigurationRequest.messageDirection = messages_1.MessageDirection.serverToClient;
ConfigurationRequest.type = new messages_1.ProtocolRequestType(ConfigurationRequest.method);
})(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
/***/ }),
/***/ 5581:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DeclarationRequest = void 0;
const messages_1 = __webpack_require__(8431);
// @ts-ignore: to avoid inlining LocationLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the type definition locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositionParams]
* (#TextDocumentPositionParams) the response is of type {@link Declaration}
* or a typed array of {@link DeclarationLink} or a Thenable that resolves
* to such.
*/
var DeclarationRequest;
(function (DeclarationRequest) {
DeclarationRequest.method = 'textDocument/declaration';
DeclarationRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
})(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
/***/ }),
/***/ 1494:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = void 0;
const vscode_jsonrpc_1 = __webpack_require__(9110);
const Is = __webpack_require__(8633);
const messages_1 = __webpack_require__(8431);
/**
* @since 3.17.0
*/
var DiagnosticServerCancellationData;
(function (DiagnosticServerCancellationData) {
function is(value) {
const candidate = value;
return candidate && Is.boolean(candidate.retriggerRequest);
}
DiagnosticServerCancellationData.is = is;
})(DiagnosticServerCancellationData = exports.DiagnosticServerCancellationData || (exports.DiagnosticServerCancellationData = {}));
/**
* The document diagnostic report kinds.
*
* @since 3.17.0
*/
var DocumentDiagnosticReportKind;
(function (DocumentDiagnosticReportKind) {
/**
* A diagnostic report with a full
* set of problems.
*/
DocumentDiagnosticReportKind.Full = 'full';
/**
* A report indicating that the last
* returned report is still accurate.
*/
DocumentDiagnosticReportKind.Unchanged = 'unchanged';
})(DocumentDiagnosticReportKind = exports.DocumentDiagnosticReportKind || (exports.DocumentDiagnosticReportKind = {}));
/**
* The document diagnostic request definition.
*
* @since 3.17.0
*/
var DocumentDiagnosticRequest;
(function (DocumentDiagnosticRequest) {
DocumentDiagnosticRequest.method = 'textDocument/diagnostic';
DocumentDiagnosticRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentDiagnosticRequest.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest.method);
DocumentDiagnosticRequest.partialResult = new vscode_jsonrpc_1.ProgressType();
})(DocumentDiagnosticRequest = exports.DocumentDiagnosticRequest || (exports.DocumentDiagnosticRequest = {}));
/**
* The workspace diagnostic request definition.
*
* @since 3.17.0
*/
var WorkspaceDiagnosticRequest;
(function (WorkspaceDiagnosticRequest) {
WorkspaceDiagnosticRequest.method = 'workspace/diagnostic';
WorkspaceDiagnosticRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceDiagnosticRequest.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest.method);
WorkspaceDiagnosticRequest.partialResult = new vscode_jsonrpc_1.ProgressType();
})(WorkspaceDiagnosticRequest = exports.WorkspaceDiagnosticRequest || (exports.WorkspaceDiagnosticRequest = {}));
/**
* The diagnostic refresh request definition.
*
* @since 3.17.0
*/
var DiagnosticRefreshRequest;
(function (DiagnosticRefreshRequest) {
DiagnosticRefreshRequest.method = `workspace/diagnostic/refresh`;
DiagnosticRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
DiagnosticRefreshRequest.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest.method);
})(DiagnosticRefreshRequest = exports.DiagnosticRefreshRequest || (exports.DiagnosticRefreshRequest = {}));
/***/ }),
/***/ 4781:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.DidRenameFilesNotification = exports.WillRenameFilesRequest = exports.DidCreateFilesNotification = exports.WillCreateFilesRequest = exports.FileOperationPatternKind = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A pattern kind describing if a glob pattern matches a file a folder or
* both.
*
* @since 3.16.0
*/
var FileOperationPatternKind;
(function (FileOperationPatternKind) {
/**
* The pattern matches a file only.
*/
FileOperationPatternKind.file = 'file';
/**
* The pattern matches a folder only.
*/
FileOperationPatternKind.folder = 'folder';
})(FileOperationPatternKind = exports.FileOperationPatternKind || (exports.FileOperationPatternKind = {}));
/**
* The will create files request is sent from the client to the server before files are actually
* created as long as the creation is triggered from within the client.
*
* The request can return a `WorkspaceEdit` which will be applied to workspace before the
* files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file
* to be created.
*
* @since 3.16.0
*/
var WillCreateFilesRequest;
(function (WillCreateFilesRequest) {
WillCreateFilesRequest.method = 'workspace/willCreateFiles';
WillCreateFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WillCreateFilesRequest.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest.method);
})(WillCreateFilesRequest = exports.WillCreateFilesRequest || (exports.WillCreateFilesRequest = {}));
/**
* The did create files notification is sent from the client to the server when
* files were created from within the client.
*
* @since 3.16.0
*/
var DidCreateFilesNotification;
(function (DidCreateFilesNotification) {
DidCreateFilesNotification.method = 'workspace/didCreateFiles';
DidCreateFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidCreateFilesNotification.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification.method);
})(DidCreateFilesNotification = exports.DidCreateFilesNotification || (exports.DidCreateFilesNotification = {}));
/**
* The will rename files request is sent from the client to the server before files are actually
* renamed as long as the rename is triggered from within the client.
*
* @since 3.16.0
*/
var WillRenameFilesRequest;
(function (WillRenameFilesRequest) {
WillRenameFilesRequest.method = 'workspace/willRenameFiles';
WillRenameFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WillRenameFilesRequest.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest.method);
})(WillRenameFilesRequest = exports.WillRenameFilesRequest || (exports.WillRenameFilesRequest = {}));
/**
* The did rename files notification is sent from the client to the server when
* files were renamed from within the client.
*
* @since 3.16.0
*/
var DidRenameFilesNotification;
(function (DidRenameFilesNotification) {
DidRenameFilesNotification.method = 'workspace/didRenameFiles';
DidRenameFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidRenameFilesNotification.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification.method);
})(DidRenameFilesNotification = exports.DidRenameFilesNotification || (exports.DidRenameFilesNotification = {}));
/**
* The will delete files request is sent from the client to the server before files are actually
* deleted as long as the deletion is triggered from within the client.
*
* @since 3.16.0
*/
var DidDeleteFilesNotification;
(function (DidDeleteFilesNotification) {
DidDeleteFilesNotification.method = 'workspace/didDeleteFiles';
DidDeleteFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidDeleteFilesNotification.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification.method);
})(DidDeleteFilesNotification = exports.DidDeleteFilesNotification || (exports.DidDeleteFilesNotification = {}));
/**
* The did delete files notification is sent from the client to the server when
* files were deleted from within the client.
*
* @since 3.16.0
*/
var WillDeleteFilesRequest;
(function (WillDeleteFilesRequest) {
WillDeleteFilesRequest.method = 'workspace/willDeleteFiles';
WillDeleteFilesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WillDeleteFilesRequest.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest.method);
})(WillDeleteFilesRequest = exports.WillDeleteFilesRequest || (exports.WillDeleteFilesRequest = {}));
/***/ }),
/***/ 1203:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FoldingRangeRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to provide folding ranges in a document. The request's
* parameter is of type {@link FoldingRangeParams}, the
* response is of type {@link FoldingRangeList} or a Thenable
* that resolves to such.
*/
var FoldingRangeRequest;
(function (FoldingRangeRequest) {
FoldingRangeRequest.method = 'textDocument/foldingRange';
FoldingRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
})(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
/***/ }),
/***/ 7287:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ImplementationRequest = void 0;
const messages_1 = __webpack_require__(8431);
// @ts-ignore: to avoid inlining LocationLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the implementation locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositionParams]
* (#TextDocumentPositionParams) the response is of type {@link Definition} or a
* Thenable that resolves to such.
*/
var ImplementationRequest;
(function (ImplementationRequest) {
ImplementationRequest.method = 'textDocument/implementation';
ImplementationRequest.messageDirection = messages_1.MessageDirection.clientToServer;
ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
})(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
/***/ }),
/***/ 9383:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to provide inlay hints in a document. The request's parameter is of
* type {@link InlayHintsParams}, the response is of type
* {@link InlayHint InlayHint[]} or a Thenable that resolves to such.
*
* @since 3.17.0
*/
var InlayHintRequest;
(function (InlayHintRequest) {
InlayHintRequest.method = 'textDocument/inlayHint';
InlayHintRequest.messageDirection = messages_1.MessageDirection.clientToServer;
InlayHintRequest.type = new messages_1.ProtocolRequestType(InlayHintRequest.method);
})(InlayHintRequest = exports.InlayHintRequest || (exports.InlayHintRequest = {}));
/**
* A request to resolve additional properties for an inlay hint.
* The request's parameter is of type {@link InlayHint}, the response is
* of type {@link InlayHint} or a Thenable that resolves to such.
*
* @since 3.17.0
*/
var InlayHintResolveRequest;
(function (InlayHintResolveRequest) {
InlayHintResolveRequest.method = 'inlayHint/resolve';
InlayHintResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
InlayHintResolveRequest.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest.method);
})(InlayHintResolveRequest = exports.InlayHintResolveRequest || (exports.InlayHintResolveRequest = {}));
/**
* @since 3.17.0
*/
var InlayHintRefreshRequest;
(function (InlayHintRefreshRequest) {
InlayHintRefreshRequest.method = `workspace/inlayHint/refresh`;
InlayHintRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
InlayHintRefreshRequest.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest.method);
})(InlayHintRefreshRequest = exports.InlayHintRefreshRequest || (exports.InlayHintRefreshRequest = {}));
/***/ }),
/***/ 3491:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlineValueRefreshRequest = exports.InlineValueRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to provide inline values in a document. The request's parameter is of
* type {@link InlineValueParams}, the response is of type
* {@link InlineValue InlineValue[]} or a Thenable that resolves to such.
*
* @since 3.17.0
*/
var InlineValueRequest;
(function (InlineValueRequest) {
InlineValueRequest.method = 'textDocument/inlineValue';
InlineValueRequest.messageDirection = messages_1.MessageDirection.clientToServer;
InlineValueRequest.type = new messages_1.ProtocolRequestType(InlineValueRequest.method);
})(InlineValueRequest = exports.InlineValueRequest || (exports.InlineValueRequest = {}));
/**
* @since 3.17.0
*/
var InlineValueRefreshRequest;
(function (InlineValueRefreshRequest) {
InlineValueRefreshRequest.method = `workspace/inlineValue/refresh`;
InlineValueRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
InlineValueRefreshRequest.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest.method);
})(InlineValueRefreshRequest = exports.InlineValueRefreshRequest || (exports.InlineValueRefreshRequest = {}));
/***/ }),
/***/ 1815:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceSymbolRequest = exports.CodeActionResolveRequest = exports.CodeActionRequest = exports.DocumentSymbolRequest = exports.DocumentHighlightRequest = exports.ReferencesRequest = exports.DefinitionRequest = exports.SignatureHelpRequest = exports.SignatureHelpTriggerKind = exports.HoverRequest = exports.CompletionResolveRequest = exports.CompletionRequest = exports.CompletionTriggerKind = exports.PublishDiagnosticsNotification = exports.WatchKind = exports.RelativePattern = exports.FileChangeType = exports.DidChangeWatchedFilesNotification = exports.WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentNotification = exports.TextDocumentSaveReason = exports.DidSaveTextDocumentNotification = exports.DidCloseTextDocumentNotification = exports.DidChangeTextDocumentNotification = exports.TextDocumentContentChangeEvent = exports.DidOpenTextDocumentNotification = exports.TextDocumentSyncKind = exports.TelemetryEventNotification = exports.LogMessageNotification = exports.ShowMessageRequest = exports.ShowMessageNotification = exports.MessageType = exports.DidChangeConfigurationNotification = exports.ExitNotification = exports.ShutdownRequest = exports.InitializedNotification = exports.InitializeErrorCodes = exports.InitializeRequest = exports.WorkDoneProgressOptions = exports.TextDocumentRegistrationOptions = exports.StaticRegistrationOptions = exports.PositionEncodingKind = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.NotebookCellTextDocumentFilter = exports.NotebookDocumentFilter = exports.TextDocumentFilter = void 0;
exports.TypeHierarchySubtypesRequest = exports.TypeHierarchyPrepareRequest = exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.WillRenameFilesRequest = exports.DidRenameFilesNotification = exports.WillCreateFilesRequest = exports.DidCreateFilesNotification = exports.FileOperationPatternKind = exports.LinkedEditingRangeRequest = exports.ShowDocumentRequest = exports.SemanticTokensRegistrationType = exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.TokenFormat = exports.CallHierarchyPrepareRequest = exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = exports.SelectionRangeRequest = exports.DeclarationRequest = exports.FoldingRangeRequest = exports.ColorPresentationRequest = exports.DocumentColorRequest = exports.ConfigurationRequest = exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = exports.TypeDefinitionRequest = exports.ImplementationRequest = exports.ApplyWorkspaceEditRequest = exports.ExecuteCommandRequest = exports.PrepareRenameRequest = exports.RenameRequest = exports.PrepareSupportDefaultBehavior = exports.DocumentOnTypeFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolResolveRequest = void 0;
exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = exports.InlineValueRefreshRequest = exports.InlineValueRequest = exports.TypeHierarchySupertypesRequest = void 0;
const messages_1 = __webpack_require__(8431);
const vscode_languageserver_types_1 = __webpack_require__(7717);
const Is = __webpack_require__(8633);
const protocol_implementation_1 = __webpack_require__(7287);
Object.defineProperty(exports, "ImplementationRequest", ({ enumerable: true, get: function () { return protocol_implementation_1.ImplementationRequest; } }));
const protocol_typeDefinition_1 = __webpack_require__(9264);
Object.defineProperty(exports, "TypeDefinitionRequest", ({ enumerable: true, get: function () { return protocol_typeDefinition_1.TypeDefinitionRequest; } }));
const protocol_workspaceFolder_1 = __webpack_require__(6860);
Object.defineProperty(exports, "WorkspaceFoldersRequest", ({ enumerable: true, get: function () { return protocol_workspaceFolder_1.WorkspaceFoldersRequest; } }));
Object.defineProperty(exports, "DidChangeWorkspaceFoldersNotification", ({ enumerable: true, get: function () { return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification; } }));
const protocol_configuration_1 = __webpack_require__(7639);
Object.defineProperty(exports, "ConfigurationRequest", ({ enumerable: true, get: function () { return protocol_configuration_1.ConfigurationRequest; } }));
const protocol_colorProvider_1 = __webpack_require__(3747);
Object.defineProperty(exports, "DocumentColorRequest", ({ enumerable: true, get: function () { return protocol_colorProvider_1.DocumentColorRequest; } }));
Object.defineProperty(exports, "ColorPresentationRequest", ({ enumerable: true, get: function () { return protocol_colorProvider_1.ColorPresentationRequest; } }));
const protocol_foldingRange_1 = __webpack_require__(1203);
Object.defineProperty(exports, "FoldingRangeRequest", ({ enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRequest; } }));
const protocol_declaration_1 = __webpack_require__(5581);
Object.defineProperty(exports, "DeclarationRequest", ({ enumerable: true, get: function () { return protocol_declaration_1.DeclarationRequest; } }));
const protocol_selectionRange_1 = __webpack_require__(1530);
Object.defineProperty(exports, "SelectionRangeRequest", ({ enumerable: true, get: function () { return protocol_selectionRange_1.SelectionRangeRequest; } }));
const protocol_progress_1 = __webpack_require__(4166);
Object.defineProperty(exports, "WorkDoneProgress", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgress; } }));
Object.defineProperty(exports, "WorkDoneProgressCreateRequest", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCreateRequest; } }));
Object.defineProperty(exports, "WorkDoneProgressCancelNotification", ({ enumerable: true, get: function () { return protocol_progress_1.WorkDoneProgressCancelNotification; } }));
const protocol_callHierarchy_1 = __webpack_require__(7602);
Object.defineProperty(exports, "CallHierarchyIncomingCallsRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest; } }));
Object.defineProperty(exports, "CallHierarchyOutgoingCallsRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest; } }));
Object.defineProperty(exports, "CallHierarchyPrepareRequest", ({ enumerable: true, get: function () { return protocol_callHierarchy_1.CallHierarchyPrepareRequest; } }));
const protocol_semanticTokens_1 = __webpack_require__(2067);
Object.defineProperty(exports, "TokenFormat", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.TokenFormat; } }));
Object.defineProperty(exports, "SemanticTokensRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRequest; } }));
Object.defineProperty(exports, "SemanticTokensDeltaRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensDeltaRequest; } }));
Object.defineProperty(exports, "SemanticTokensRangeRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRangeRequest; } }));
Object.defineProperty(exports, "SemanticTokensRefreshRequest", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRefreshRequest; } }));
Object.defineProperty(exports, "SemanticTokensRegistrationType", ({ enumerable: true, get: function () { return protocol_semanticTokens_1.SemanticTokensRegistrationType; } }));
const protocol_showDocument_1 = __webpack_require__(4333);
Object.defineProperty(exports, "ShowDocumentRequest", ({ enumerable: true, get: function () { return protocol_showDocument_1.ShowDocumentRequest; } }));
const protocol_linkedEditingRange_1 = __webpack_require__(2249);
Object.defineProperty(exports, "LinkedEditingRangeRequest", ({ enumerable: true, get: function () { return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; } }));
const protocol_fileOperations_1 = __webpack_require__(4781);
Object.defineProperty(exports, "FileOperationPatternKind", ({ enumerable: true, get: function () { return protocol_fileOperations_1.FileOperationPatternKind; } }));
Object.defineProperty(exports, "DidCreateFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidCreateFilesNotification; } }));
Object.defineProperty(exports, "WillCreateFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillCreateFilesRequest; } }));
Object.defineProperty(exports, "DidRenameFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidRenameFilesNotification; } }));
Object.defineProperty(exports, "WillRenameFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillRenameFilesRequest; } }));
Object.defineProperty(exports, "DidDeleteFilesNotification", ({ enumerable: true, get: function () { return protocol_fileOperations_1.DidDeleteFilesNotification; } }));
Object.defineProperty(exports, "WillDeleteFilesRequest", ({ enumerable: true, get: function () { return protocol_fileOperations_1.WillDeleteFilesRequest; } }));
const protocol_moniker_1 = __webpack_require__(7684);
Object.defineProperty(exports, "UniquenessLevel", ({ enumerable: true, get: function () { return protocol_moniker_1.UniquenessLevel; } }));
Object.defineProperty(exports, "MonikerKind", ({ enumerable: true, get: function () { return protocol_moniker_1.MonikerKind; } }));
Object.defineProperty(exports, "MonikerRequest", ({ enumerable: true, get: function () { return protocol_moniker_1.MonikerRequest; } }));
const protocol_typeHierarchy_1 = __webpack_require__(7062);
Object.defineProperty(exports, "TypeHierarchyPrepareRequest", ({ enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest; } }));
Object.defineProperty(exports, "TypeHierarchySubtypesRequest", ({ enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest; } }));
Object.defineProperty(exports, "TypeHierarchySupertypesRequest", ({ enumerable: true, get: function () { return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest; } }));
const protocol_inlineValue_1 = __webpack_require__(3491);
Object.defineProperty(exports, "InlineValueRequest", ({ enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRequest; } }));
Object.defineProperty(exports, "InlineValueRefreshRequest", ({ enumerable: true, get: function () { return protocol_inlineValue_1.InlineValueRefreshRequest; } }));
const protocol_inlayHint_1 = __webpack_require__(9383);
Object.defineProperty(exports, "InlayHintRequest", ({ enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRequest; } }));
Object.defineProperty(exports, "InlayHintResolveRequest", ({ enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintResolveRequest; } }));
Object.defineProperty(exports, "InlayHintRefreshRequest", ({ enumerable: true, get: function () { return protocol_inlayHint_1.InlayHintRefreshRequest; } }));
const protocol_diagnostic_1 = __webpack_require__(1494);
Object.defineProperty(exports, "DiagnosticServerCancellationData", ({ enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticServerCancellationData; } }));
Object.defineProperty(exports, "DocumentDiagnosticReportKind", ({ enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticReportKind; } }));
Object.defineProperty(exports, "DocumentDiagnosticRequest", ({ enumerable: true, get: function () { return protocol_diagnostic_1.DocumentDiagnosticRequest; } }));
Object.defineProperty(exports, "WorkspaceDiagnosticRequest", ({ enumerable: true, get: function () { return protocol_diagnostic_1.WorkspaceDiagnosticRequest; } }));
Object.defineProperty(exports, "DiagnosticRefreshRequest", ({ enumerable: true, get: function () { return protocol_diagnostic_1.DiagnosticRefreshRequest; } }));
const protocol_notebook_1 = __webpack_require__(4792);
Object.defineProperty(exports, "NotebookCellKind", ({ enumerable: true, get: function () { return protocol_notebook_1.NotebookCellKind; } }));
Object.defineProperty(exports, "ExecutionSummary", ({ enumerable: true, get: function () { return protocol_notebook_1.ExecutionSummary; } }));
Object.defineProperty(exports, "NotebookCell", ({ enumerable: true, get: function () { return protocol_notebook_1.NotebookCell; } }));
Object.defineProperty(exports, "NotebookDocument", ({ enumerable: true, get: function () { return protocol_notebook_1.NotebookDocument; } }));
Object.defineProperty(exports, "NotebookDocumentSyncRegistrationType", ({ enumerable: true, get: function () { return protocol_notebook_1.NotebookDocumentSyncRegistrationType; } }));
Object.defineProperty(exports, "DidOpenNotebookDocumentNotification", ({ enumerable: true, get: function () { return protocol_notebook_1.DidOpenNotebookDocumentNotification; } }));
Object.defineProperty(exports, "NotebookCellArrayChange", ({ enumerable: true, get: function () { return protocol_notebook_1.NotebookCellArrayChange; } }));
Object.defineProperty(exports, "DidChangeNotebookDocumentNotification", ({ enumerable: true, get: function () { return protocol_notebook_1.DidChangeNotebookDocumentNotification; } }));
Object.defineProperty(exports, "DidSaveNotebookDocumentNotification", ({ enumerable: true, get: function () { return protocol_notebook_1.DidSaveNotebookDocumentNotification; } }));
Object.defineProperty(exports, "DidCloseNotebookDocumentNotification", ({ enumerable: true, get: function () { return protocol_notebook_1.DidCloseNotebookDocumentNotification; } }));
// @ts-ignore: to avoid inlining LocationLink as dynamic import
let __noDynamicImport;
/**
* The TextDocumentFilter namespace provides helper functions to work with
* {@link TextDocumentFilter} literals.
*
* @since 3.17.0
*/
var TextDocumentFilter;
(function (TextDocumentFilter) {
function is(value) {
const candidate = value;
return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
}
TextDocumentFilter.is = is;
})(TextDocumentFilter = exports.TextDocumentFilter || (exports.TextDocumentFilter = {}));
/**
* The NotebookDocumentFilter namespace provides helper functions to work with
* {@link NotebookDocumentFilter} literals.
*
* @since 3.17.0
*/
var NotebookDocumentFilter;
(function (NotebookDocumentFilter) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
}
NotebookDocumentFilter.is = is;
})(NotebookDocumentFilter = exports.NotebookDocumentFilter || (exports.NotebookDocumentFilter = {}));
/**
* The NotebookCellTextDocumentFilter namespace provides helper functions to work with
* {@link NotebookCellTextDocumentFilter} literals.
*
* @since 3.17.0
*/
var NotebookCellTextDocumentFilter;
(function (NotebookCellTextDocumentFilter) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate)
&& (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook))
&& (candidate.language === undefined || Is.string(candidate.language));
}
NotebookCellTextDocumentFilter.is = is;
})(NotebookCellTextDocumentFilter = exports.NotebookCellTextDocumentFilter || (exports.NotebookCellTextDocumentFilter = {}));
/**
* The DocumentSelector namespace provides helper functions to work with
* {@link DocumentSelector}s.
*/
var DocumentSelector;
(function (DocumentSelector) {
function is(value) {
if (!Array.isArray(value)) {
return false;
}
for (let elem of value) {
if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
return false;
}
}
return true;
}
DocumentSelector.is = is;
})(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
/**
* The `client/registerCapability` request is sent from the server to the client to register a new capability
* handler on the client side.
*/
var RegistrationRequest;
(function (RegistrationRequest) {
RegistrationRequest.method = 'client/registerCapability';
RegistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;
RegistrationRequest.type = new messages_1.ProtocolRequestType(RegistrationRequest.method);
})(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
/**
* The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
* handler on the client side.
*/
var UnregistrationRequest;
(function (UnregistrationRequest) {
UnregistrationRequest.method = 'client/unregisterCapability';
UnregistrationRequest.messageDirection = messages_1.MessageDirection.serverToClient;
UnregistrationRequest.type = new messages_1.ProtocolRequestType(UnregistrationRequest.method);
})(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
var ResourceOperationKind;
(function (ResourceOperationKind) {
/**
* Supports creating new files and folders.
*/
ResourceOperationKind.Create = 'create';
/**
* Supports renaming existing files and folders.
*/
ResourceOperationKind.Rename = 'rename';
/**
* Supports deleting existing files and folders.
*/
ResourceOperationKind.Delete = 'delete';
})(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
var FailureHandlingKind;
(function (FailureHandlingKind) {
/**
* Applying the workspace change is simply aborted if one of the changes provided
* fails. All operations executed before the failing operation stay executed.
*/
FailureHandlingKind.Abort = 'abort';
/**
* All operations are executed transactional. That means they either all
* succeed or no changes at all are applied to the workspace.
*/
FailureHandlingKind.Transactional = 'transactional';
/**
* If the workspace edit contains only textual file changes they are executed transactional.
* If resource changes (create, rename or delete file) are part of the change the failure
* handling strategy is abort.
*/
FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
/**
* The client tries to undo the operations already executed. But there is no
* guarantee that this is succeeding.
*/
FailureHandlingKind.Undo = 'undo';
})(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
/**
* A set of predefined position encoding kinds.
*
* @since 3.17.0
*/
var PositionEncodingKind;
(function (PositionEncodingKind) {
/**
* Character offsets count UTF-8 code units (e.g. bytes).
*/
PositionEncodingKind.UTF8 = 'utf-8';
/**
* Character offsets count UTF-16 code units.
*
* This is the default and must always be supported
* by servers
*/
PositionEncodingKind.UTF16 = 'utf-16';
/**
* Character offsets count UTF-32 code units.
*
* Implementation note: these are the same as Unicode codepoints,
* so this `PositionEncodingKind` may also be used for an
* encoding-agnostic representation of character offsets.
*/
PositionEncodingKind.UTF32 = 'utf-32';
})(PositionEncodingKind = exports.PositionEncodingKind || (exports.PositionEncodingKind = {}));
/**
* The StaticRegistrationOptions namespace provides helper functions to work with
* {@link StaticRegistrationOptions} literals.
*/
var StaticRegistrationOptions;
(function (StaticRegistrationOptions) {
function hasId(value) {
const candidate = value;
return candidate && Is.string(candidate.id) && candidate.id.length > 0;
}
StaticRegistrationOptions.hasId = hasId;
})(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
/**
* The TextDocumentRegistrationOptions namespace provides helper functions to work with
* {@link TextDocumentRegistrationOptions} literals.
*/
var TextDocumentRegistrationOptions;
(function (TextDocumentRegistrationOptions) {
function is(value) {
const candidate = value;
return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
}
TextDocumentRegistrationOptions.is = is;
})(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
/**
* The WorkDoneProgressOptions namespace provides helper functions to work with
* {@link WorkDoneProgressOptions} literals.
*/
var WorkDoneProgressOptions;
(function (WorkDoneProgressOptions) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
}
WorkDoneProgressOptions.is = is;
function hasWorkDoneProgress(value) {
const candidate = value;
return candidate && Is.boolean(candidate.workDoneProgress);
}
WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
})(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
/**
* The initialize request is sent from the client to the server.
* It is sent once as the request after starting up the server.
* The requests parameter is of type {@link InitializeParams}
* the response if of type {@link InitializeResult} of a Thenable that
* resolves to such.
*/
var InitializeRequest;
(function (InitializeRequest) {
InitializeRequest.method = 'initialize';
InitializeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
InitializeRequest.type = new messages_1.ProtocolRequestType(InitializeRequest.method);
})(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
/**
* Known error codes for an `InitializeErrorCodes`;
*/
var InitializeErrorCodes;
(function (InitializeErrorCodes) {
/**
* If the protocol version provided by the client can't be handled by the server.
*
* @deprecated This initialize error got replaced by client capabilities. There is
* no version handshake in version 3.0x
*/
InitializeErrorCodes.unknownProtocolVersion = 1;
})(InitializeErrorCodes = exports.InitializeErrorCodes || (exports.InitializeErrorCodes = {}));
/**
* The initialized notification is sent from the client to the
* server after the client is fully initialized and the server
* is allowed to send requests from the server to the client.
*/
var InitializedNotification;
(function (InitializedNotification) {
InitializedNotification.method = 'initialized';
InitializedNotification.messageDirection = messages_1.MessageDirection.clientToServer;
InitializedNotification.type = new messages_1.ProtocolNotificationType(InitializedNotification.method);
})(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
//---- Shutdown Method ----
/**
* A shutdown request is sent from the client to the server.
* It is sent once when the client decides to shutdown the
* server. The only notification that is sent after a shutdown request
* is the exit event.
*/
var ShutdownRequest;
(function (ShutdownRequest) {
ShutdownRequest.method = 'shutdown';
ShutdownRequest.messageDirection = messages_1.MessageDirection.clientToServer;
ShutdownRequest.type = new messages_1.ProtocolRequestType0(ShutdownRequest.method);
})(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
//---- Exit Notification ----
/**
* The exit event is sent from the client to the server to
* ask the server to exit its process.
*/
var ExitNotification;
(function (ExitNotification) {
ExitNotification.method = 'exit';
ExitNotification.messageDirection = messages_1.MessageDirection.clientToServer;
ExitNotification.type = new messages_1.ProtocolNotificationType0(ExitNotification.method);
})(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
/**
* The configuration change notification is sent from the client to the server
* when the client's configuration has changed. The notification contains
* the changed configuration as defined by the language client.
*/
var DidChangeConfigurationNotification;
(function (DidChangeConfigurationNotification) {
DidChangeConfigurationNotification.method = 'workspace/didChangeConfiguration';
DidChangeConfigurationNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification.method);
})(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
//---- Message show and log notifications ----
/**
* The message type
*/
var MessageType;
(function (MessageType) {
/**
* An error message.
*/
MessageType.Error = 1;
/**
* A warning message.
*/
MessageType.Warning = 2;
/**
* An information message.
*/
MessageType.Info = 3;
/**
* A log message.
*/
MessageType.Log = 4;
})(MessageType = exports.MessageType || (exports.MessageType = {}));
/**
* The show message notification is sent from a server to a client to ask
* the client to display a particular message in the user interface.
*/
var ShowMessageNotification;
(function (ShowMessageNotification) {
ShowMessageNotification.method = 'window/showMessage';
ShowMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;
ShowMessageNotification.type = new messages_1.ProtocolNotificationType(ShowMessageNotification.method);
})(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
/**
* The show message request is sent from the server to the client to show a message
* and a set of options actions to the user.
*/
var ShowMessageRequest;
(function (ShowMessageRequest) {
ShowMessageRequest.method = 'window/showMessageRequest';
ShowMessageRequest.messageDirection = messages_1.MessageDirection.serverToClient;
ShowMessageRequest.type = new messages_1.ProtocolRequestType(ShowMessageRequest.method);
})(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
/**
* The log message notification is sent from the server to the client to ask
* the client to log a particular message.
*/
var LogMessageNotification;
(function (LogMessageNotification) {
LogMessageNotification.method = 'window/logMessage';
LogMessageNotification.messageDirection = messages_1.MessageDirection.serverToClient;
LogMessageNotification.type = new messages_1.ProtocolNotificationType(LogMessageNotification.method);
})(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
//---- Telemetry notification
/**
* The telemetry event notification is sent from the server to the client to ask
* the client to log telemetry data.
*/
var TelemetryEventNotification;
(function (TelemetryEventNotification) {
TelemetryEventNotification.method = 'telemetry/event';
TelemetryEventNotification.messageDirection = messages_1.MessageDirection.serverToClient;
TelemetryEventNotification.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification.method);
})(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
/**
* Defines how the host (editor) should sync
* document changes to the language server.
*/
var TextDocumentSyncKind;
(function (TextDocumentSyncKind) {
/**
* Documents should not be synced at all.
*/
TextDocumentSyncKind.None = 0;
/**
* Documents are synced by always sending the full content
* of the document.
*/
TextDocumentSyncKind.Full = 1;
/**
* Documents are synced by sending the full content on open.
* After that only incremental updates to the document are
* send.
*/
TextDocumentSyncKind.Incremental = 2;
})(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
/**
* The document open notification is sent from the client to the server to signal
* newly opened text documents. The document's truth is now managed by the client
* and the server must not try to read the document's truth using the document's
* uri. Open in this sense means it is managed by the client. It doesn't necessarily
* mean that its content is presented in an editor. An open notification must not
* be sent more than once without a corresponding close notification send before.
* This means open and close notification must be balanced and the max open count
* is one.
*/
var DidOpenTextDocumentNotification;
(function (DidOpenTextDocumentNotification) {
DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
DidOpenTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
})(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
var TextDocumentContentChangeEvent;
(function (TextDocumentContentChangeEvent) {
/**
* Checks whether the information describes a delta event.
*/
function isIncremental(event) {
let candidate = event;
return candidate !== undefined && candidate !== null &&
typeof candidate.text === 'string' && candidate.range !== undefined &&
(candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
}
TextDocumentContentChangeEvent.isIncremental = isIncremental;
/**
* Checks whether the information describes a full replacement event.
*/
function isFull(event) {
let candidate = event;
return candidate !== undefined && candidate !== null &&
typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
}
TextDocumentContentChangeEvent.isFull = isFull;
})(TextDocumentContentChangeEvent = exports.TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = {}));
/**
* The document change notification is sent from the client to the server to signal
* changes to a text document.
*/
var DidChangeTextDocumentNotification;
(function (DidChangeTextDocumentNotification) {
DidChangeTextDocumentNotification.method = 'textDocument/didChange';
DidChangeTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
})(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
/**
* The document close notification is sent from the client to the server when
* the document got closed in the client. The document's truth now exists where
* the document's uri points to (e.g. if the document's uri is a file uri the
* truth now exists on disk). As with the open notification the close notification
* is about managing the document's content. Receiving a close notification
* doesn't mean that the document was open in an editor before. A close
* notification requires a previous open notification to be sent.
*/
var DidCloseTextDocumentNotification;
(function (DidCloseTextDocumentNotification) {
DidCloseTextDocumentNotification.method = 'textDocument/didClose';
DidCloseTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
})(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
/**
* The document save notification is sent from the client to the server when
* the document got saved in the client.
*/
var DidSaveTextDocumentNotification;
(function (DidSaveTextDocumentNotification) {
DidSaveTextDocumentNotification.method = 'textDocument/didSave';
DidSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
})(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
/**
* Represents reasons why a text document is saved.
*/
var TextDocumentSaveReason;
(function (TextDocumentSaveReason) {
/**
* Manually triggered, e.g. by the user pressing save, by starting debugging,
* or by an API call.
*/
TextDocumentSaveReason.Manual = 1;
/**
* Automatic after a delay.
*/
TextDocumentSaveReason.AfterDelay = 2;
/**
* When the editor lost focus.
*/
TextDocumentSaveReason.FocusOut = 3;
})(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
/**
* A document will save notification is sent from the client to the server before
* the document is actually saved.
*/
var WillSaveTextDocumentNotification;
(function (WillSaveTextDocumentNotification) {
WillSaveTextDocumentNotification.method = 'textDocument/willSave';
WillSaveTextDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
})(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
/**
* A document will save request is sent from the client to the server before
* the document is actually saved. The request can return an array of TextEdits
* which will be applied to the text document before it is saved. Please note that
* clients might drop results if computing the text edits took too long or if a
* server constantly fails on this request. This is done to keep the save fast and
* reliable.
*/
var WillSaveTextDocumentWaitUntilRequest;
(function (WillSaveTextDocumentWaitUntilRequest) {
WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
WillSaveTextDocumentWaitUntilRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
})(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
/**
* The watched files notification is sent from the client to the server when
* the client detects changes to file watched by the language client.
*/
var DidChangeWatchedFilesNotification;
(function (DidChangeWatchedFilesNotification) {
DidChangeWatchedFilesNotification.method = 'workspace/didChangeWatchedFiles';
DidChangeWatchedFilesNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification.method);
})(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
/**
* The file event type
*/
var FileChangeType;
(function (FileChangeType) {
/**
* The file got created.
*/
FileChangeType.Created = 1;
/**
* The file got changed.
*/
FileChangeType.Changed = 2;
/**
* The file got deleted.
*/
FileChangeType.Deleted = 3;
})(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
var RelativePattern;
(function (RelativePattern) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern);
}
RelativePattern.is = is;
})(RelativePattern = exports.RelativePattern || (exports.RelativePattern = {}));
var WatchKind;
(function (WatchKind) {
/**
* Interested in create events.
*/
WatchKind.Create = 1;
/**
* Interested in change events
*/
WatchKind.Change = 2;
/**
* Interested in delete events
*/
WatchKind.Delete = 4;
})(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
/**
* Diagnostics notification are sent from the server to the client to signal
* results of validation runs.
*/
var PublishDiagnosticsNotification;
(function (PublishDiagnosticsNotification) {
PublishDiagnosticsNotification.method = 'textDocument/publishDiagnostics';
PublishDiagnosticsNotification.messageDirection = messages_1.MessageDirection.serverToClient;
PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification.method);
})(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
/**
* How a completion was triggered
*/
var CompletionTriggerKind;
(function (CompletionTriggerKind) {
/**
* Completion was triggered by typing an identifier (24x7 code
* complete), manual invocation (e.g Ctrl+Space) or via API.
*/
CompletionTriggerKind.Invoked = 1;
/**
* Completion was triggered by a trigger character specified by
* the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
*/
CompletionTriggerKind.TriggerCharacter = 2;
/**
* Completion was re-triggered as current completion list is incomplete
*/
CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
})(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
/**
* Request to request completion at a given text document position. The request's
* parameter is of type {@link TextDocumentPosition} the response
* is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList}
* or a Thenable that resolves to such.
*
* The request can delay the computation of the {@link CompletionItem.detail `detail`}
* and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve`
* request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
* `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
*/
var CompletionRequest;
(function (CompletionRequest) {
CompletionRequest.method = 'textDocument/completion';
CompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
})(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
/**
* Request to resolve additional information for a given completion item.The request's
* parameter is of type {@link CompletionItem} the response
* is of type {@link CompletionItem} or a Thenable that resolves to such.
*/
var CompletionResolveRequest;
(function (CompletionResolveRequest) {
CompletionResolveRequest.method = 'completionItem/resolve';
CompletionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
})(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
/**
* Request to request hover information at a given text document position. The request's
* parameter is of type {@link TextDocumentPosition} the response is of
* type {@link Hover} or a Thenable that resolves to such.
*/
var HoverRequest;
(function (HoverRequest) {
HoverRequest.method = 'textDocument/hover';
HoverRequest.messageDirection = messages_1.MessageDirection.clientToServer;
HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
})(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
/**
* How a signature help was triggered.
*
* @since 3.15.0
*/
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
/**
* Signature help was invoked manually by the user or by a command.
*/
SignatureHelpTriggerKind.Invoked = 1;
/**
* Signature help was triggered by a trigger character.
*/
SignatureHelpTriggerKind.TriggerCharacter = 2;
/**
* Signature help was triggered by the cursor moving or by the document content changing.
*/
SignatureHelpTriggerKind.ContentChange = 3;
})(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
var SignatureHelpRequest;
(function (SignatureHelpRequest) {
SignatureHelpRequest.method = 'textDocument/signatureHelp';
SignatureHelpRequest.messageDirection = messages_1.MessageDirection.clientToServer;
SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
})(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
/**
* A request to resolve the definition location of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPosition]
* (#TextDocumentPosition) the response is of either type {@link Definition}
* or a typed array of {@link DefinitionLink} or a Thenable that resolves
* to such.
*/
var DefinitionRequest;
(function (DefinitionRequest) {
DefinitionRequest.method = 'textDocument/definition';
DefinitionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
})(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
/**
* A request to resolve project-wide references for the symbol denoted
* by the given text document position. The request's parameter is of
* type {@link ReferenceParams} the response is of type
* {@link Location Location[]} or a Thenable that resolves to such.
*/
var ReferencesRequest;
(function (ReferencesRequest) {
ReferencesRequest.method = 'textDocument/references';
ReferencesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
})(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
/**
* Request to resolve a {@link DocumentHighlight} for a given
* text document position. The request's parameter is of type [TextDocumentPosition]
* (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
* (#DocumentHighlight) or a Thenable that resolves to such.
*/
var DocumentHighlightRequest;
(function (DocumentHighlightRequest) {
DocumentHighlightRequest.method = 'textDocument/documentHighlight';
DocumentHighlightRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
})(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
/**
* A request to list all symbols found in a given text document. The request's
* parameter is of type {@link TextDocumentIdentifier} the
* response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable
* that resolves to such.
*/
var DocumentSymbolRequest;
(function (DocumentSymbolRequest) {
DocumentSymbolRequest.method = 'textDocument/documentSymbol';
DocumentSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
})(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
/**
* A request to provide commands for the given text document and range.
*/
var CodeActionRequest;
(function (CodeActionRequest) {
CodeActionRequest.method = 'textDocument/codeAction';
CodeActionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
})(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
/**
* Request to resolve additional information for a given code action.The request's
* parameter is of type {@link CodeAction} the response
* is of type {@link CodeAction} or a Thenable that resolves to such.
*/
var CodeActionResolveRequest;
(function (CodeActionResolveRequest) {
CodeActionResolveRequest.method = 'codeAction/resolve';
CodeActionResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CodeActionResolveRequest.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest.method);
})(CodeActionResolveRequest = exports.CodeActionResolveRequest || (exports.CodeActionResolveRequest = {}));
/**
* A request to list project-wide symbols matching the query string given
* by the {@link WorkspaceSymbolParams}. The response is
* of type {@link SymbolInformation SymbolInformation[]} or a Thenable that
* resolves to such.
*
* @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients
* need to advertise support for WorkspaceSymbols via the client capability
* `workspace.symbol.resolveSupport`.
*
*/
var WorkspaceSymbolRequest;
(function (WorkspaceSymbolRequest) {
WorkspaceSymbolRequest.method = 'workspace/symbol';
WorkspaceSymbolRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
})(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
/**
* A request to resolve the range inside the workspace
* symbol's location.
*
* @since 3.17.0
*/
var WorkspaceSymbolResolveRequest;
(function (WorkspaceSymbolResolveRequest) {
WorkspaceSymbolResolveRequest.method = 'workspaceSymbol/resolve';
WorkspaceSymbolResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceSymbolResolveRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest.method);
})(WorkspaceSymbolResolveRequest = exports.WorkspaceSymbolResolveRequest || (exports.WorkspaceSymbolResolveRequest = {}));
/**
* A request to provide code lens for the given text document.
*/
var CodeLensRequest;
(function (CodeLensRequest) {
CodeLensRequest.method = 'textDocument/codeLens';
CodeLensRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CodeLensRequest.type = new messages_1.ProtocolRequestType(CodeLensRequest.method);
})(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
/**
* A request to resolve a command for a given code lens.
*/
var CodeLensResolveRequest;
(function (CodeLensResolveRequest) {
CodeLensResolveRequest.method = 'codeLens/resolve';
CodeLensResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
CodeLensResolveRequest.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest.method);
})(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
/**
* A request to refresh all code actions
*
* @since 3.16.0
*/
var CodeLensRefreshRequest;
(function (CodeLensRefreshRequest) {
CodeLensRefreshRequest.method = `workspace/codeLens/refresh`;
CodeLensRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
CodeLensRefreshRequest.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest.method);
})(CodeLensRefreshRequest = exports.CodeLensRefreshRequest || (exports.CodeLensRefreshRequest = {}));
/**
* A request to provide document links
*/
var DocumentLinkRequest;
(function (DocumentLinkRequest) {
DocumentLinkRequest.method = 'textDocument/documentLink';
DocumentLinkRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
})(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
/**
* Request to resolve additional information for a given document link. The request's
* parameter is of type {@link DocumentLink} the response
* is of type {@link DocumentLink} or a Thenable that resolves to such.
*/
var DocumentLinkResolveRequest;
(function (DocumentLinkResolveRequest) {
DocumentLinkResolveRequest.method = 'documentLink/resolve';
DocumentLinkResolveRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest.method);
})(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
/**
* A request to to format a whole document.
*/
var DocumentFormattingRequest;
(function (DocumentFormattingRequest) {
DocumentFormattingRequest.method = 'textDocument/formatting';
DocumentFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
})(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
/**
* A request to to format a range in a document.
*/
var DocumentRangeFormattingRequest;
(function (DocumentRangeFormattingRequest) {
DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
DocumentRangeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
})(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
/**
* A request to format a document on type.
*/
var DocumentOnTypeFormattingRequest;
(function (DocumentOnTypeFormattingRequest) {
DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
DocumentOnTypeFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
})(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
//---- Rename ----------------------------------------------
var PrepareSupportDefaultBehavior;
(function (PrepareSupportDefaultBehavior) {
/**
* The client's default behavior is to select the identifier
* according the to language's syntax rule.
*/
PrepareSupportDefaultBehavior.Identifier = 1;
})(PrepareSupportDefaultBehavior = exports.PrepareSupportDefaultBehavior || (exports.PrepareSupportDefaultBehavior = {}));
/**
* A request to rename a symbol.
*/
var RenameRequest;
(function (RenameRequest) {
RenameRequest.method = 'textDocument/rename';
RenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;
RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
})(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
/**
* A request to test and perform the setup necessary for a rename.
*
* @since 3.16 - support for default behavior
*/
var PrepareRenameRequest;
(function (PrepareRenameRequest) {
PrepareRenameRequest.method = 'textDocument/prepareRename';
PrepareRenameRequest.messageDirection = messages_1.MessageDirection.clientToServer;
PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
})(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
/**
* A request send from the client to the server to execute a command. The request might return
* a workspace edit which the client will apply to the workspace.
*/
var ExecuteCommandRequest;
(function (ExecuteCommandRequest) {
ExecuteCommandRequest.method = 'workspace/executeCommand';
ExecuteCommandRequest.messageDirection = messages_1.MessageDirection.clientToServer;
ExecuteCommandRequest.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest.method);
})(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
/**
* A request sent from the server to the client to modified certain resources.
*/
var ApplyWorkspaceEditRequest;
(function (ApplyWorkspaceEditRequest) {
ApplyWorkspaceEditRequest.method = 'workspace/applyEdit';
ApplyWorkspaceEditRequest.messageDirection = messages_1.MessageDirection.serverToClient;
ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
})(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
/***/ }),
/***/ 2249:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LinkedEditingRangeRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to provide ranges that can be edited together.
*
* @since 3.16.0
*/
var LinkedEditingRangeRequest;
(function (LinkedEditingRangeRequest) {
LinkedEditingRangeRequest.method = 'textDocument/linkedEditingRange';
LinkedEditingRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
LinkedEditingRangeRequest.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest.method);
})(LinkedEditingRangeRequest = exports.LinkedEditingRangeRequest || (exports.LinkedEditingRangeRequest = {}));
/***/ }),
/***/ 7684:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = void 0;
const messages_1 = __webpack_require__(8431);
/**
* Moniker uniqueness level to define scope of the moniker.
*
* @since 3.16.0
*/
var UniquenessLevel;
(function (UniquenessLevel) {
/**
* The moniker is only unique inside a document
*/
UniquenessLevel.document = 'document';
/**
* The moniker is unique inside a project for which a dump got created
*/
UniquenessLevel.project = 'project';
/**
* The moniker is unique inside the group to which a project belongs
*/
UniquenessLevel.group = 'group';
/**
* The moniker is unique inside the moniker scheme.
*/
UniquenessLevel.scheme = 'scheme';
/**
* The moniker is globally unique
*/
UniquenessLevel.global = 'global';
})(UniquenessLevel = exports.UniquenessLevel || (exports.UniquenessLevel = {}));
/**
* The moniker kind.
*
* @since 3.16.0
*/
var MonikerKind;
(function (MonikerKind) {
/**
* The moniker represent a symbol that is imported into a project
*/
MonikerKind.$import = 'import';
/**
* The moniker represents a symbol that is exported from a project
*/
MonikerKind.$export = 'export';
/**
* The moniker represents a symbol that is local to a project (e.g. a local
* variable of a function, a class not visible outside the project, ...)
*/
MonikerKind.local = 'local';
})(MonikerKind = exports.MonikerKind || (exports.MonikerKind = {}));
/**
* A request to get the moniker of a symbol at a given text document position.
* The request parameter is of type {@link TextDocumentPositionParams}.
* The response is of type {@link Moniker Moniker[]} or `null`.
*/
var MonikerRequest;
(function (MonikerRequest) {
MonikerRequest.method = 'textDocument/moniker';
MonikerRequest.messageDirection = messages_1.MessageDirection.clientToServer;
MonikerRequest.type = new messages_1.ProtocolRequestType(MonikerRequest.method);
})(MonikerRequest = exports.MonikerRequest || (exports.MonikerRequest = {}));
/***/ }),
/***/ 4792:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = void 0;
const vscode_languageserver_types_1 = __webpack_require__(7717);
const Is = __webpack_require__(8633);
const messages_1 = __webpack_require__(8431);
/**
* A notebook cell kind.
*
* @since 3.17.0
*/
var NotebookCellKind;
(function (NotebookCellKind) {
/**
* A markup-cell is formatted source that is used for display.
*/
NotebookCellKind.Markup = 1;
/**
* A code-cell is source code.
*/
NotebookCellKind.Code = 2;
function is(value) {
return value === 1 || value === 2;
}
NotebookCellKind.is = is;
})(NotebookCellKind = exports.NotebookCellKind || (exports.NotebookCellKind = {}));
var ExecutionSummary;
(function (ExecutionSummary) {
function create(executionOrder, success) {
const result = { executionOrder };
if (success === true || success === false) {
result.success = success;
}
return result;
}
ExecutionSummary.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === undefined || Is.boolean(candidate.success));
}
ExecutionSummary.is = is;
function equals(one, other) {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
return one.executionOrder === other.executionOrder && one.success === other.success;
}
ExecutionSummary.equals = equals;
})(ExecutionSummary = exports.ExecutionSummary || (exports.ExecutionSummary = {}));
var NotebookCell;
(function (NotebookCell) {
function create(kind, document) {
return { kind, document };
}
NotebookCell.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) &&
(candidate.metadata === undefined || Is.objectLiteral(candidate.metadata));
}
NotebookCell.is = is;
function diff(one, two) {
const result = new Set();
if (one.document !== two.document) {
result.add('document');
}
if (one.kind !== two.kind) {
result.add('kind');
}
if (one.executionSummary !== two.executionSummary) {
result.add('executionSummary');
}
if ((one.metadata !== undefined || two.metadata !== undefined) && !equalsMetadata(one.metadata, two.metadata)) {
result.add('metadata');
}
if ((one.executionSummary !== undefined || two.executionSummary !== undefined) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
result.add('executionSummary');
}
return result;
}
NotebookCell.diff = diff;
function equalsMetadata(one, other) {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
const oneArray = Array.isArray(one);
const otherArray = Array.isArray(other);
if (oneArray !== otherArray) {
return false;
}
if (oneArray && otherArray) {
if (one.length !== other.length) {
return false;
}
for (let i = 0; i < one.length; i++) {
if (!equalsMetadata(one[i], other[i])) {
return false;
}
}
}
if (Is.objectLiteral(one) && Is.objectLiteral(other)) {
const oneKeys = Object.keys(one);
const otherKeys = Object.keys(other);
if (oneKeys.length !== otherKeys.length) {
return false;
}
oneKeys.sort();
otherKeys.sort();
if (!equalsMetadata(oneKeys, otherKeys)) {
return false;
}
for (let i = 0; i < oneKeys.length; i++) {
const prop = oneKeys[i];
if (!equalsMetadata(one[prop], other[prop])) {
return false;
}
}
}
return true;
}
})(NotebookCell = exports.NotebookCell || (exports.NotebookCell = {}));
var NotebookDocument;
(function (NotebookDocument) {
function create(uri, notebookType, version, cells) {
return { uri, notebookType, version, cells };
}
NotebookDocument.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is.typedArray(candidate.cells, NotebookCell.is);
}
NotebookDocument.is = is;
})(NotebookDocument = exports.NotebookDocument || (exports.NotebookDocument = {}));
var NotebookDocumentSyncRegistrationType;
(function (NotebookDocumentSyncRegistrationType) {
NotebookDocumentSyncRegistrationType.method = 'notebookDocument/sync';
NotebookDocumentSyncRegistrationType.messageDirection = messages_1.MessageDirection.clientToServer;
NotebookDocumentSyncRegistrationType.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType.method);
})(NotebookDocumentSyncRegistrationType = exports.NotebookDocumentSyncRegistrationType || (exports.NotebookDocumentSyncRegistrationType = {}));
/**
* A notification sent when a notebook opens.
*
* @since 3.17.0
*/
var DidOpenNotebookDocumentNotification;
(function (DidOpenNotebookDocumentNotification) {
DidOpenNotebookDocumentNotification.method = 'notebookDocument/didOpen';
DidOpenNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidOpenNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification.method);
DidOpenNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidOpenNotebookDocumentNotification = exports.DidOpenNotebookDocumentNotification || (exports.DidOpenNotebookDocumentNotification = {}));
var NotebookCellArrayChange;
(function (NotebookCellArrayChange) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === undefined || Is.typedArray(candidate.cells, NotebookCell.is));
}
NotebookCellArrayChange.is = is;
function create(start, deleteCount, cells) {
const result = { start, deleteCount };
if (cells !== undefined) {
result.cells = cells;
}
return result;
}
NotebookCellArrayChange.create = create;
})(NotebookCellArrayChange = exports.NotebookCellArrayChange || (exports.NotebookCellArrayChange = {}));
var DidChangeNotebookDocumentNotification;
(function (DidChangeNotebookDocumentNotification) {
DidChangeNotebookDocumentNotification.method = 'notebookDocument/didChange';
DidChangeNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification.method);
DidChangeNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidChangeNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification || (exports.DidChangeNotebookDocumentNotification = {}));
/**
* A notification sent when a notebook document is saved.
*
* @since 3.17.0
*/
var DidSaveNotebookDocumentNotification;
(function (DidSaveNotebookDocumentNotification) {
DidSaveNotebookDocumentNotification.method = 'notebookDocument/didSave';
DidSaveNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidSaveNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification.method);
DidSaveNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidSaveNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification || (exports.DidSaveNotebookDocumentNotification = {}));
/**
* A notification sent when a notebook closes.
*
* @since 3.17.0
*/
var DidCloseNotebookDocumentNotification;
(function (DidCloseNotebookDocumentNotification) {
DidCloseNotebookDocumentNotification.method = 'notebookDocument/didClose';
DidCloseNotebookDocumentNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidCloseNotebookDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification.method);
DidCloseNotebookDocumentNotification.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidCloseNotebookDocumentNotification = exports.DidCloseNotebookDocumentNotification || (exports.DidCloseNotebookDocumentNotification = {}));
/***/ }),
/***/ 4166:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = void 0;
const vscode_jsonrpc_1 = __webpack_require__(9110);
const messages_1 = __webpack_require__(8431);
var WorkDoneProgress;
(function (WorkDoneProgress) {
WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
function is(value) {
return value === WorkDoneProgress.type;
}
WorkDoneProgress.is = is;
})(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
/**
* The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
* reporting from the server.
*/
var WorkDoneProgressCreateRequest;
(function (WorkDoneProgressCreateRequest) {
WorkDoneProgressCreateRequest.method = 'window/workDoneProgress/create';
WorkDoneProgressCreateRequest.messageDirection = messages_1.MessageDirection.serverToClient;
WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest.method);
})(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
/**
* The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
* initiated on the server side.
*/
var WorkDoneProgressCancelNotification;
(function (WorkDoneProgressCancelNotification) {
WorkDoneProgressCancelNotification.method = 'window/workDoneProgress/cancel';
WorkDoneProgressCancelNotification.messageDirection = messages_1.MessageDirection.clientToServer;
WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification.method);
})(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
/***/ }),
/***/ 1530:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SelectionRangeRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to provide selection ranges in a document. The request's
* parameter is of type {@link SelectionRangeParams}, the
* response is of type {@link SelectionRange SelectionRange[]} or a Thenable
* that resolves to such.
*/
var SelectionRangeRequest;
(function (SelectionRangeRequest) {
SelectionRangeRequest.method = 'textDocument/selectionRange';
SelectionRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
})(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
/***/ }),
/***/ 2067:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.SemanticTokensRegistrationType = exports.TokenFormat = void 0;
const messages_1 = __webpack_require__(8431);
//------- 'textDocument/semanticTokens' -----
var TokenFormat;
(function (TokenFormat) {
TokenFormat.Relative = 'relative';
})(TokenFormat = exports.TokenFormat || (exports.TokenFormat = {}));
var SemanticTokensRegistrationType;
(function (SemanticTokensRegistrationType) {
SemanticTokensRegistrationType.method = 'textDocument/semanticTokens';
SemanticTokensRegistrationType.type = new messages_1.RegistrationType(SemanticTokensRegistrationType.method);
})(SemanticTokensRegistrationType = exports.SemanticTokensRegistrationType || (exports.SemanticTokensRegistrationType = {}));
/**
* @since 3.16.0
*/
var SemanticTokensRequest;
(function (SemanticTokensRequest) {
SemanticTokensRequest.method = 'textDocument/semanticTokens/full';
SemanticTokensRequest.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
SemanticTokensRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
/**
* @since 3.16.0
*/
var SemanticTokensDeltaRequest;
(function (SemanticTokensDeltaRequest) {
SemanticTokensDeltaRequest.method = 'textDocument/semanticTokens/full/delta';
SemanticTokensDeltaRequest.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensDeltaRequest.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest.method);
SemanticTokensDeltaRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensDeltaRequest = exports.SemanticTokensDeltaRequest || (exports.SemanticTokensDeltaRequest = {}));
/**
* @since 3.16.0
*/
var SemanticTokensRangeRequest;
(function (SemanticTokensRangeRequest) {
SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
SemanticTokensRangeRequest.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
SemanticTokensRangeRequest.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
/**
* @since 3.16.0
*/
var SemanticTokensRefreshRequest;
(function (SemanticTokensRefreshRequest) {
SemanticTokensRefreshRequest.method = `workspace/semanticTokens/refresh`;
SemanticTokensRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient;
SemanticTokensRefreshRequest.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest.method);
})(SemanticTokensRefreshRequest = exports.SemanticTokensRefreshRequest || (exports.SemanticTokensRefreshRequest = {}));
/***/ }),
/***/ 4333:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ShowDocumentRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to show a document. This request might open an
* external program depending on the value of the URI to open.
* For example a request to open `https://code.visualstudio.com/`
* will very likely open the URI in a WEB browser.
*
* @since 3.16.0
*/
var ShowDocumentRequest;
(function (ShowDocumentRequest) {
ShowDocumentRequest.method = 'window/showDocument';
ShowDocumentRequest.messageDirection = messages_1.MessageDirection.serverToClient;
ShowDocumentRequest.type = new messages_1.ProtocolRequestType(ShowDocumentRequest.method);
})(ShowDocumentRequest = exports.ShowDocumentRequest || (exports.ShowDocumentRequest = {}));
/***/ }),
/***/ 9264:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeDefinitionRequest = void 0;
const messages_1 = __webpack_require__(8431);
// @ts-ignore: to avoid inlining LocatioLink as dynamic import
let __noDynamicImport;
/**
* A request to resolve the type definition locations of a symbol at a given text
* document position. The request's parameter is of type [TextDocumentPositionParams]
* (#TextDocumentPositionParams) the response is of type {@link Definition} or a
* Thenable that resolves to such.
*/
var TypeDefinitionRequest;
(function (TypeDefinitionRequest) {
TypeDefinitionRequest.method = 'textDocument/typeDefinition';
TypeDefinitionRequest.messageDirection = messages_1.MessageDirection.clientToServer;
TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
})(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
/***/ }),
/***/ 7062:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) TypeFox, Microsoft and others. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeHierarchySubtypesRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchyPrepareRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* A request to result a `TypeHierarchyItem` in a document at a given position.
* Can be used as an input to a subtypes or supertypes type hierarchy.
*
* @since 3.17.0
*/
var TypeHierarchyPrepareRequest;
(function (TypeHierarchyPrepareRequest) {
TypeHierarchyPrepareRequest.method = 'textDocument/prepareTypeHierarchy';
TypeHierarchyPrepareRequest.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest.method);
})(TypeHierarchyPrepareRequest = exports.TypeHierarchyPrepareRequest || (exports.TypeHierarchyPrepareRequest = {}));
/**
* A request to resolve the supertypes for a given `TypeHierarchyItem`.
*
* @since 3.17.0
*/
var TypeHierarchySupertypesRequest;
(function (TypeHierarchySupertypesRequest) {
TypeHierarchySupertypesRequest.method = 'typeHierarchy/supertypes';
TypeHierarchySupertypesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchySupertypesRequest.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest.method);
})(TypeHierarchySupertypesRequest = exports.TypeHierarchySupertypesRequest || (exports.TypeHierarchySupertypesRequest = {}));
/**
* A request to resolve the subtypes for a given `TypeHierarchyItem`.
*
* @since 3.17.0
*/
var TypeHierarchySubtypesRequest;
(function (TypeHierarchySubtypesRequest) {
TypeHierarchySubtypesRequest.method = 'typeHierarchy/subtypes';
TypeHierarchySubtypesRequest.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchySubtypesRequest.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest.method);
})(TypeHierarchySubtypesRequest = exports.TypeHierarchySubtypesRequest || (exports.TypeHierarchySubtypesRequest = {}));
/***/ }),
/***/ 6860:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = void 0;
const messages_1 = __webpack_require__(8431);
/**
* The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
*/
var WorkspaceFoldersRequest;
(function (WorkspaceFoldersRequest) {
WorkspaceFoldersRequest.method = 'workspace/workspaceFolders';
WorkspaceFoldersRequest.messageDirection = messages_1.MessageDirection.serverToClient;
WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest.method);
})(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
/**
* The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
* folder configuration changes.
*/
var DidChangeWorkspaceFoldersNotification;
(function (DidChangeWorkspaceFoldersNotification) {
DidChangeWorkspaceFoldersNotification.method = 'workspace/didChangeWorkspaceFolders';
DidChangeWorkspaceFoldersNotification.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification.method);
})(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
/***/ }),
/***/ 8633:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.objectLiteral = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
return typeof value === 'string' || value instanceof String;
}
exports.string = string;
function number(value) {
return typeof value === 'number' || value instanceof Number;
}
exports.number = number;
function error(value) {
return value instanceof Error;
}
exports.error = error;
function func(value) {
return typeof value === 'function';
}
exports.func = func;
function array(value) {
return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
return array(value) && value.every(elem => string(elem));
}
exports.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function objectLiteral(value) {
// Strictly speaking class instances pass this check as well. Since the LSP
// doesn't use classes we ignore this for now. If we do we need to add something
// like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
return value !== null && typeof value === 'object';
}
exports.objectLiteral = objectLiteral;
/***/ }),
/***/ 7717:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AnnotatedTextEdit: () => (/* binding */ AnnotatedTextEdit),
/* harmony export */ ChangeAnnotation: () => (/* binding */ ChangeAnnotation),
/* harmony export */ ChangeAnnotationIdentifier: () => (/* binding */ ChangeAnnotationIdentifier),
/* harmony export */ CodeAction: () => (/* binding */ CodeAction),
/* harmony export */ CodeActionContext: () => (/* binding */ CodeActionContext),
/* harmony export */ CodeActionKind: () => (/* binding */ CodeActionKind),
/* harmony export */ CodeActionTriggerKind: () => (/* binding */ CodeActionTriggerKind),
/* harmony export */ CodeDescription: () => (/* binding */ CodeDescription),
/* harmony export */ CodeLens: () => (/* binding */ CodeLens),
/* harmony export */ Color: () => (/* binding */ Color),
/* harmony export */ ColorInformation: () => (/* binding */ ColorInformation),
/* harmony export */ ColorPresentation: () => (/* binding */ ColorPresentation),
/* harmony export */ Command: () => (/* binding */ Command),
/* harmony export */ CompletionItem: () => (/* binding */ CompletionItem),
/* harmony export */ CompletionItemKind: () => (/* binding */ CompletionItemKind),
/* harmony export */ CompletionItemLabelDetails: () => (/* binding */ CompletionItemLabelDetails),
/* harmony export */ CompletionItemTag: () => (/* binding */ CompletionItemTag),
/* harmony export */ CompletionList: () => (/* binding */ CompletionList),
/* harmony export */ CreateFile: () => (/* binding */ CreateFile),
/* harmony export */ DeleteFile: () => (/* binding */ DeleteFile),
/* harmony export */ Diagnostic: () => (/* binding */ Diagnostic),
/* harmony export */ DiagnosticRelatedInformation: () => (/* binding */ DiagnosticRelatedInformation),
/* harmony export */ DiagnosticSeverity: () => (/* binding */ DiagnosticSeverity),
/* harmony export */ DiagnosticTag: () => (/* binding */ DiagnosticTag),
/* harmony export */ DocumentHighlight: () => (/* binding */ DocumentHighlight),
/* harmony export */ DocumentHighlightKind: () => (/* binding */ DocumentHighlightKind),
/* harmony export */ DocumentLink: () => (/* binding */ DocumentLink),
/* harmony export */ DocumentSymbol: () => (/* binding */ DocumentSymbol),
/* harmony export */ DocumentUri: () => (/* binding */ DocumentUri),
/* harmony export */ EOL: () => (/* binding */ EOL),
/* harmony export */ FoldingRange: () => (/* binding */ FoldingRange),
/* harmony export */ FoldingRangeKind: () => (/* binding */ FoldingRangeKind),
/* harmony export */ FormattingOptions: () => (/* binding */ FormattingOptions),
/* harmony export */ Hover: () => (/* binding */ Hover),
/* harmony export */ InlayHint: () => (/* binding */ InlayHint),
/* harmony export */ InlayHintKind: () => (/* binding */ InlayHintKind),
/* harmony export */ InlayHintLabelPart: () => (/* binding */ InlayHintLabelPart),
/* harmony export */ InlineValueContext: () => (/* binding */ InlineValueContext),
/* harmony export */ InlineValueEvaluatableExpression: () => (/* binding */ InlineValueEvaluatableExpression),
/* harmony export */ InlineValueText: () => (/* binding */ InlineValueText),
/* harmony export */ InlineValueVariableLookup: () => (/* binding */ InlineValueVariableLookup),
/* harmony export */ InsertReplaceEdit: () => (/* binding */ InsertReplaceEdit),
/* harmony export */ InsertTextFormat: () => (/* binding */ InsertTextFormat),
/* harmony export */ InsertTextMode: () => (/* binding */ InsertTextMode),
/* harmony export */ Location: () => (/* binding */ Location),
/* harmony export */ LocationLink: () => (/* binding */ LocationLink),
/* harmony export */ MarkedString: () => (/* binding */ MarkedString),
/* harmony export */ MarkupContent: () => (/* binding */ MarkupContent),
/* harmony export */ MarkupKind: () => (/* binding */ MarkupKind),
/* harmony export */ OptionalVersionedTextDocumentIdentifier: () => (/* binding */ OptionalVersionedTextDocumentIdentifier),
/* harmony export */ ParameterInformation: () => (/* binding */ ParameterInformation),
/* harmony export */ Position: () => (/* binding */ Position),
/* harmony export */ Range: () => (/* binding */ Range),
/* harmony export */ RenameFile: () => (/* binding */ RenameFile),
/* harmony export */ SelectionRange: () => (/* binding */ SelectionRange),
/* harmony export */ SemanticTokenModifiers: () => (/* binding */ SemanticTokenModifiers),
/* harmony export */ SemanticTokenTypes: () => (/* binding */ SemanticTokenTypes),
/* harmony export */ SemanticTokens: () => (/* binding */ SemanticTokens),
/* harmony export */ SignatureInformation: () => (/* binding */ SignatureInformation),
/* harmony export */ SymbolInformation: () => (/* binding */ SymbolInformation),
/* harmony export */ SymbolKind: () => (/* binding */ SymbolKind),
/* harmony export */ SymbolTag: () => (/* binding */ SymbolTag),
/* harmony export */ TextDocument: () => (/* binding */ TextDocument),
/* harmony export */ TextDocumentEdit: () => (/* binding */ TextDocumentEdit),
/* harmony export */ TextDocumentIdentifier: () => (/* binding */ TextDocumentIdentifier),
/* harmony export */ TextDocumentItem: () => (/* binding */ TextDocumentItem),
/* harmony export */ TextEdit: () => (/* binding */ TextEdit),
/* harmony export */ URI: () => (/* binding */ URI),
/* harmony export */ VersionedTextDocumentIdentifier: () => (/* binding */ VersionedTextDocumentIdentifier),
/* harmony export */ WorkspaceChange: () => (/* binding */ WorkspaceChange),
/* harmony export */ WorkspaceEdit: () => (/* binding */ WorkspaceEdit),
/* harmony export */ WorkspaceFolder: () => (/* binding */ WorkspaceFolder),
/* harmony export */ WorkspaceSymbol: () => (/* binding */ WorkspaceSymbol),
/* harmony export */ integer: () => (/* binding */ integer),
/* harmony export */ uinteger: () => (/* binding */ uinteger)
/* harmony export */ });
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var DocumentUri;
(function (DocumentUri) {
function is(value) {
return typeof value === 'string';
}
DocumentUri.is = is;
})(DocumentUri || (DocumentUri = {}));
var URI;
(function (URI) {
function is(value) {
return typeof value === 'string';
}
URI.is = is;
})(URI || (URI = {}));
var integer;
(function (integer) {
integer.MIN_VALUE = -2147483648;
integer.MAX_VALUE = 2147483647;
function is(value) {
return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE;
}
integer.is = is;
})(integer || (integer = {}));
var uinteger;
(function (uinteger) {
uinteger.MIN_VALUE = 0;
uinteger.MAX_VALUE = 2147483647;
function is(value) {
return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE;
}
uinteger.is = is;
})(uinteger || (uinteger = {}));
/**
* The Position namespace provides helper functions to work with
* {@link Position} literals.
*/
var Position;
(function (Position) {
/**
* Creates a new Position literal from the given line and character.
* @param line The position's line.
* @param character The position's character.
*/
function create(line, character) {
if (line === Number.MAX_VALUE) {
line = uinteger.MAX_VALUE;
}
if (character === Number.MAX_VALUE) {
character = uinteger.MAX_VALUE;
}
return { line: line, character: character };
}
Position.create = create;
/**
* Checks whether the given literal conforms to the {@link Position} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
}
Position.is = is;
})(Position || (Position = {}));
/**
* The Range namespace provides helper functions to work with
* {@link Range} literals.
*/
var Range;
(function (Range) {
function create(one, two, three, four) {
if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
return { start: Position.create(one, two), end: Position.create(three, four) };
}
else if (Position.is(one) && Position.is(two)) {
return { start: one, end: two };
}
else {
throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]"));
}
}
Range.create = create;
/**
* Checks whether the given literal conforms to the {@link Range} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
}
Range.is = is;
})(Range || (Range = {}));
/**
* The Location namespace provides helper functions to work with
* {@link Location} literals.
*/
var Location;
(function (Location) {
/**
* Creates a Location literal.
* @param uri The location's uri.
* @param range The location's range.
*/
function create(uri, range) {
return { uri: uri, range: range };
}
Location.create = create;
/**
* Checks whether the given literal conforms to the {@link Location} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
}
Location.is = is;
})(Location || (Location = {}));
/**
* The LocationLink namespace provides helper functions to work with
* {@link LocationLink} literals.
*/
var LocationLink;
(function (LocationLink) {
/**
* Creates a LocationLink literal.
* @param targetUri The definition's uri.
* @param targetRange The full range of the definition.
* @param targetSelectionRange The span of the symbol definition at the target.
* @param originSelectionRange The span of the symbol being defined in the originating source file.
*/
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
}
LocationLink.create = create;
/**
* Checks whether the given literal conforms to the {@link LocationLink} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
&& Range.is(candidate.targetSelectionRange)
&& (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
}
LocationLink.is = is;
})(LocationLink || (LocationLink = {}));
/**
* The Color namespace provides helper functions to work with
* {@link Color} literals.
*/
var Color;
(function (Color) {
/**
* Creates a new Color literal.
*/
function create(red, green, blue, alpha) {
return {
red: red,
green: green,
blue: blue,
alpha: alpha,
};
}
Color.create = create;
/**
* Checks whether the given literal conforms to the {@link Color} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1)
&& Is.numberRange(candidate.green, 0, 1)
&& Is.numberRange(candidate.blue, 0, 1)
&& Is.numberRange(candidate.alpha, 0, 1);
}
Color.is = is;
})(Color || (Color = {}));
/**
* The ColorInformation namespace provides helper functions to work with
* {@link ColorInformation} literals.
*/
var ColorInformation;
(function (ColorInformation) {
/**
* Creates a new ColorInformation literal.
*/
function create(range, color) {
return {
range: range,
color: color,
};
}
ColorInformation.create = create;
/**
* Checks whether the given literal conforms to the {@link ColorInformation} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
}
ColorInformation.is = is;
})(ColorInformation || (ColorInformation = {}));
/**
* The Color namespace provides helper functions to work with
* {@link ColorPresentation} literals.
*/
var ColorPresentation;
(function (ColorPresentation) {
/**
* Creates a new ColorInformation literal.
*/
function create(label, textEdit, additionalTextEdits) {
return {
label: label,
textEdit: textEdit,
additionalTextEdits: additionalTextEdits,
};
}
ColorPresentation.create = create;
/**
* Checks whether the given literal conforms to the {@link ColorInformation} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.label)
&& (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
&& (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
}
ColorPresentation.is = is;
})(ColorPresentation || (ColorPresentation = {}));
/**
* A set of predefined range kinds.
*/
var FoldingRangeKind;
(function (FoldingRangeKind) {
/**
* Folding range for a comment
*/
FoldingRangeKind.Comment = 'comment';
/**
* Folding range for an import or include
*/
FoldingRangeKind.Imports = 'imports';
/**
* Folding range for a region (e.g. `#region`)
*/
FoldingRangeKind.Region = 'region';
})(FoldingRangeKind || (FoldingRangeKind = {}));
/**
* The folding range namespace provides helper functions to work with
* {@link FoldingRange} literals.
*/
var FoldingRange;
(function (FoldingRange) {
/**
* Creates a new FoldingRange literal.
*/
function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
var result = {
startLine: startLine,
endLine: endLine
};
if (Is.defined(startCharacter)) {
result.startCharacter = startCharacter;
}
if (Is.defined(endCharacter)) {
result.endCharacter = endCharacter;
}
if (Is.defined(kind)) {
result.kind = kind;
}
if (Is.defined(collapsedText)) {
result.collapsedText = collapsedText;
}
return result;
}
FoldingRange.create = create;
/**
* Checks whether the given literal conforms to the {@link FoldingRange} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine)
&& (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter))
&& (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter))
&& (Is.undefined(candidate.kind) || Is.string(candidate.kind));
}
FoldingRange.is = is;
})(FoldingRange || (FoldingRange = {}));
/**
* The DiagnosticRelatedInformation namespace provides helper functions to work with
* {@link DiagnosticRelatedInformation} literals.
*/
var DiagnosticRelatedInformation;
(function (DiagnosticRelatedInformation) {
/**
* Creates a new DiagnosticRelatedInformation literal.
*/
function create(location, message) {
return {
location: location,
message: message
};
}
DiagnosticRelatedInformation.create = create;
/**
* Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
}
DiagnosticRelatedInformation.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
/**
* The diagnostic's severity.
*/
var DiagnosticSeverity;
(function (DiagnosticSeverity) {
/**
* Reports an error.
*/
DiagnosticSeverity.Error = 1;
/**
* Reports a warning.
*/
DiagnosticSeverity.Warning = 2;
/**
* Reports an information.
*/
DiagnosticSeverity.Information = 3;
/**
* Reports a hint.
*/
DiagnosticSeverity.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
/**
* The diagnostic tags.
*
* @since 3.15.0
*/
var DiagnosticTag;
(function (DiagnosticTag) {
/**
* Unused or unnecessary code.
*
* Clients are allowed to render diagnostics with this tag faded out instead of having
* an error squiggle.
*/
DiagnosticTag.Unnecessary = 1;
/**
* Deprecated or obsolete code.
*
* Clients are allowed to rendered diagnostics with this tag strike through.
*/
DiagnosticTag.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
/**
* The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes.
*
* @since 3.16.0
*/
var CodeDescription;
(function (CodeDescription) {
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.href);
}
CodeDescription.is = is;
})(CodeDescription || (CodeDescription = {}));
/**
* The Diagnostic namespace provides helper functions to work with
* {@link Diagnostic} literals.
*/
var Diagnostic;
(function (Diagnostic) {
/**
* Creates a new Diagnostic literal.
*/
function create(range, message, severity, code, source, relatedInformation) {
var result = { range: range, message: message };
if (Is.defined(severity)) {
result.severity = severity;
}
if (Is.defined(code)) {
result.code = code;
}
if (Is.defined(source)) {
result.source = source;
}
if (Is.defined(relatedInformation)) {
result.relatedInformation = relatedInformation;
}
return result;
}
Diagnostic.create = create;
/**
* Checks whether the given literal conforms to the {@link Diagnostic} interface.
*/
function is(value) {
var _a;
var candidate = value;
return Is.defined(candidate)
&& Range.is(candidate.range)
&& Is.string(candidate.message)
&& (Is.number(candidate.severity) || Is.undefined(candidate.severity))
&& (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
&& (Is.undefined(candidate.codeDescription) || (Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)))
&& (Is.string(candidate.source) || Is.undefined(candidate.source))
&& (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
}
Diagnostic.is = is;
})(Diagnostic || (Diagnostic = {}));
/**
* The Command namespace provides helper functions to work with
* {@link Command} literals.
*/
var Command;
(function (Command) {
/**
* Creates a new Command literal.
*/
function create(title, command) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var result = { title: title, command: command };
if (Is.defined(args) && args.length > 0) {
result.arguments = args;
}
return result;
}
Command.create = create;
/**
* Checks whether the given literal conforms to the {@link Command} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
}
Command.is = is;
})(Command || (Command = {}));
/**
* The TextEdit namespace provides helper function to create replace,
* insert and delete edits more easily.
*/
var TextEdit;
(function (TextEdit) {
/**
* Creates a replace text edit.
* @param range The range of text to be replaced.
* @param newText The new text.
*/
function replace(range, newText) {
return { range: range, newText: newText };
}
TextEdit.replace = replace;
/**
* Creates an insert text edit.
* @param position The position to insert the text at.
* @param newText The text to be inserted.
*/
function insert(position, newText) {
return { range: { start: position, end: position }, newText: newText };
}
TextEdit.insert = insert;
/**
* Creates a delete text edit.
* @param range The range of text to be deleted.
*/
function del(range) {
return { range: range, newText: '' };
}
TextEdit.del = del;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate)
&& Is.string(candidate.newText)
&& Range.is(candidate.range);
}
TextEdit.is = is;
})(TextEdit || (TextEdit = {}));
var ChangeAnnotation;
(function (ChangeAnnotation) {
function create(label, needsConfirmation, description) {
var result = { label: label };
if (needsConfirmation !== undefined) {
result.needsConfirmation = needsConfirmation;
}
if (description !== undefined) {
result.description = description;
}
return result;
}
ChangeAnnotation.create = create;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.label) &&
(Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) &&
(Is.string(candidate.description) || candidate.description === undefined);
}
ChangeAnnotation.is = is;
})(ChangeAnnotation || (ChangeAnnotation = {}));
var ChangeAnnotationIdentifier;
(function (ChangeAnnotationIdentifier) {
function is(value) {
var candidate = value;
return Is.string(candidate);
}
ChangeAnnotationIdentifier.is = is;
})(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
var AnnotatedTextEdit;
(function (AnnotatedTextEdit) {
/**
* Creates an annotated replace text edit.
*
* @param range The range of text to be replaced.
* @param newText The new text.
* @param annotation The annotation.
*/
function replace(range, newText, annotation) {
return { range: range, newText: newText, annotationId: annotation };
}
AnnotatedTextEdit.replace = replace;
/**
* Creates an annotated insert text edit.
*
* @param position The position to insert the text at.
* @param newText The text to be inserted.
* @param annotation The annotation.
*/
function insert(position, newText, annotation) {
return { range: { start: position, end: position }, newText: newText, annotationId: annotation };
}
AnnotatedTextEdit.insert = insert;
/**
* Creates an annotated delete text edit.
*
* @param range The range of text to be deleted.
* @param annotation The annotation.
*/
function del(range, annotation) {
return { range: range, newText: '', annotationId: annotation };
}
AnnotatedTextEdit.del = del;
function is(value) {
var candidate = value;
return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
AnnotatedTextEdit.is = is;
})(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
/**
* The TextDocumentEdit namespace provides helper function to create
* an edit that manipulates a text document.
*/
var TextDocumentEdit;
(function (TextDocumentEdit) {
/**
* Creates a new `TextDocumentEdit`
*/
function create(textDocument, edits) {
return { textDocument: textDocument, edits: edits };
}
TextDocumentEdit.create = create;
function is(value) {
var candidate = value;
return Is.defined(candidate)
&& OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)
&& Array.isArray(candidate.edits);
}
TextDocumentEdit.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
var CreateFile;
(function (CreateFile) {
function create(uri, options, annotation) {
var result = {
kind: 'create',
uri: uri
};
if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
result.options = options;
}
if (annotation !== undefined) {
result.annotationId = annotation;
}
return result;
}
CreateFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined ||
((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
CreateFile.is = is;
})(CreateFile || (CreateFile = {}));
var RenameFile;
(function (RenameFile) {
function create(oldUri, newUri, options, annotation) {
var result = {
kind: 'rename',
oldUri: oldUri,
newUri: newUri
};
if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
result.options = options;
}
if (annotation !== undefined) {
result.annotationId = annotation;
}
return result;
}
RenameFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined ||
((candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
RenameFile.is = is;
})(RenameFile || (RenameFile = {}));
var DeleteFile;
(function (DeleteFile) {
function create(uri, options, annotation) {
var result = {
kind: 'delete',
uri: uri
};
if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {
result.options = options;
}
if (annotation !== undefined) {
result.annotationId = annotation;
}
return result;
}
DeleteFile.create = create;
function is(value) {
var candidate = value;
return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined ||
((candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists)))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
DeleteFile.is = is;
})(DeleteFile || (DeleteFile = {}));
var WorkspaceEdit;
(function (WorkspaceEdit) {
function is(value) {
var candidate = value;
return candidate &&
(candidate.changes !== undefined || candidate.documentChanges !== undefined) &&
(candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) {
if (Is.string(change.kind)) {
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
}
else {
return TextDocumentEdit.is(change);
}
}));
}
WorkspaceEdit.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var TextEditChangeImpl = /** @class */ (function () {
function TextEditChangeImpl(edits, changeAnnotations) {
this.edits = edits;
this.changeAnnotations = changeAnnotations;
}
TextEditChangeImpl.prototype.insert = function (position, newText, annotation) {
var edit;
var id;
if (annotation === undefined) {
edit = TextEdit.insert(position, newText);
}
else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.insert(position, newText, annotation);
}
else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.insert(position, newText, id);
}
this.edits.push(edit);
if (id !== undefined) {
return id;
}
};
TextEditChangeImpl.prototype.replace = function (range, newText, annotation) {
var edit;
var id;
if (annotation === undefined) {
edit = TextEdit.replace(range, newText);
}
else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.replace(range, newText, annotation);
}
else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.replace(range, newText, id);
}
this.edits.push(edit);
if (id !== undefined) {
return id;
}
};
TextEditChangeImpl.prototype.delete = function (range, annotation) {
var edit;
var id;
if (annotation === undefined) {
edit = TextEdit.del(range);
}
else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.del(range, annotation);
}
else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.del(range, id);
}
this.edits.push(edit);
if (id !== undefined) {
return id;
}
};
TextEditChangeImpl.prototype.add = function (edit) {
this.edits.push(edit);
};
TextEditChangeImpl.prototype.all = function () {
return this.edits;
};
TextEditChangeImpl.prototype.clear = function () {
this.edits.splice(0, this.edits.length);
};
TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) {
if (value === undefined) {
throw new Error("Text edit change is not configured to manage change annotations.");
}
};
return TextEditChangeImpl;
}());
/**
* A helper class
*/
var ChangeAnnotations = /** @class */ (function () {
function ChangeAnnotations(annotations) {
this._annotations = annotations === undefined ? Object.create(null) : annotations;
this._counter = 0;
this._size = 0;
}
ChangeAnnotations.prototype.all = function () {
return this._annotations;
};
Object.defineProperty(ChangeAnnotations.prototype, "size", {
get: function () {
return this._size;
},
enumerable: false,
configurable: true
});
ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) {
var id;
if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
id = idOrAnnotation;
}
else {
id = this.nextId();
annotation = idOrAnnotation;
}
if (this._annotations[id] !== undefined) {
throw new Error("Id ".concat(id, " is already in use."));
}
if (annotation === undefined) {
throw new Error("No annotation provided for id ".concat(id));
}
this._annotations[id] = annotation;
this._size++;
return id;
};
ChangeAnnotations.prototype.nextId = function () {
this._counter++;
return this._counter.toString();
};
return ChangeAnnotations;
}());
/**
* A workspace change helps constructing changes to a workspace.
*/
var WorkspaceChange = /** @class */ (function () {
function WorkspaceChange(workspaceEdit) {
var _this = this;
this._textEditChanges = Object.create(null);
if (workspaceEdit !== undefined) {
this._workspaceEdit = workspaceEdit;
if (workspaceEdit.documentChanges) {
this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
workspaceEdit.changeAnnotations = this._changeAnnotations.all();
workspaceEdit.documentChanges.forEach(function (change) {
if (TextDocumentEdit.is(change)) {
var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
_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;
});
}
}
else {
this._workspaceEdit = {};
}
}
Object.defineProperty(WorkspaceChange.prototype, "edit", {
/**
* Returns the underlying {@link WorkspaceEdit} literal
* use to be returned from a workspace edit operation like rename.
*/
get: function () {
this.initDocumentChanges();
if (this._changeAnnotations !== undefined) {
if (this._changeAnnotations.size === 0) {
this._workspaceEdit.changeAnnotations = undefined;
}
else {
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
}
}
return this._workspaceEdit;
},
enumerable: false,
configurable: true
});
WorkspaceChange.prototype.getTextEditChange = function (key) {
if (OptionalVersionedTextDocumentIdentifier.is(key)) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === undefined) {
throw new Error('Workspace edit is not configured for document changes.');
}
var textDocument = { uri: key.uri, version: key.version };
var result = this._textEditChanges[textDocument.uri];
if (!result) {
var edits = [];
var textDocumentEdit = {
textDocument: textDocument,
edits: edits
};
this._workspaceEdit.documentChanges.push(textDocumentEdit);
result = new TextEditChangeImpl(edits, this._changeAnnotations);
this._textEditChanges[textDocument.uri] = result;
}
return result;
}
else {
this.initChanges();
if (this._workspaceEdit.changes === undefined) {
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;
}
};
WorkspaceChange.prototype.initDocumentChanges = function () {
if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
this._changeAnnotations = new ChangeAnnotations();
this._workspaceEdit.documentChanges = [];
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
}
};
WorkspaceChange.prototype.initChanges = function () {
if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
this._workspaceEdit.changes = Object.create(null);
}
};
WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === undefined) {
throw new Error('Workspace edit is not configured for document changes.');
}
var annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
}
else {
options = optionsOrAnnotation;
}
var operation;
var id;
if (annotation === undefined) {
operation = CreateFile.create(uri, options);
}
else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = CreateFile.create(uri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== undefined) {
return id;
}
};
WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === undefined) {
throw new Error('Workspace edit is not configured for document changes.');
}
var annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
}
else {
options = optionsOrAnnotation;
}
var operation;
var id;
if (annotation === undefined) {
operation = RenameFile.create(oldUri, newUri, options);
}
else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = RenameFile.create(oldUri, newUri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== undefined) {
return id;
}
};
WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === undefined) {
throw new Error('Workspace edit is not configured for document changes.');
}
var annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
}
else {
options = optionsOrAnnotation;
}
var operation;
var id;
if (annotation === undefined) {
operation = DeleteFile.create(uri, options);
}
else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = DeleteFile.create(uri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== undefined) {
return id;
}
};
return WorkspaceChange;
}());
/**
* The TextDocumentIdentifier namespace provides helper functions to work with
* {@link TextDocumentIdentifier} literals.
*/
var TextDocumentIdentifier;
(function (TextDocumentIdentifier) {
/**
* Creates a new TextDocumentIdentifier literal.
* @param uri The document's uri.
*/
function create(uri) {
return { uri: uri };
}
TextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri);
}
TextDocumentIdentifier.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
/**
* The VersionedTextDocumentIdentifier namespace provides helper functions to work with
* {@link VersionedTextDocumentIdentifier} literals.
*/
var VersionedTextDocumentIdentifier;
(function (VersionedTextDocumentIdentifier) {
/**
* Creates a new VersionedTextDocumentIdentifier literal.
* @param uri The document's uri.
* @param version The document's version.
*/
function create(uri, version) {
return { uri: uri, version: version };
}
VersionedTextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
}
VersionedTextDocumentIdentifier.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
/**
* The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with
* {@link OptionalVersionedTextDocumentIdentifier} literals.
*/
var OptionalVersionedTextDocumentIdentifier;
(function (OptionalVersionedTextDocumentIdentifier) {
/**
* Creates a new OptionalVersionedTextDocumentIdentifier literal.
* @param uri The document's uri.
* @param version The document's version.
*/
function create(uri, version) {
return { uri: uri, version: version };
}
OptionalVersionedTextDocumentIdentifier.create = create;
/**
* Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
}
OptionalVersionedTextDocumentIdentifier.is = is;
})(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
/**
* The TextDocumentItem namespace provides helper functions to work with
* {@link TextDocumentItem} literals.
*/
var TextDocumentItem;
(function (TextDocumentItem) {
/**
* Creates a new TextDocumentItem literal.
* @param uri The document's uri.
* @param languageId The document's language identifier.
* @param version The document's version number.
* @param text The document's text.
*/
function create(uri, languageId, version, text) {
return { uri: uri, languageId: languageId, version: version, text: text };
}
TextDocumentItem.create = create;
/**
* Checks whether the given literal conforms to the {@link TextDocumentItem} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
}
TextDocumentItem.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
/**
* Describes the content type that a client supports in various
* result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
*
* Please note that `MarkupKinds` must not start with a `$`. This kinds
* are reserved for internal usage.
*/
var MarkupKind;
(function (MarkupKind) {
/**
* Plain text is supported as a content format
*/
MarkupKind.PlainText = 'plaintext';
/**
* Markdown is supported as a content format
*/
MarkupKind.Markdown = 'markdown';
/**
* Checks whether the given value is a value of the {@link MarkupKind} type.
*/
function is(value) {
var candidate = value;
return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
}
MarkupKind.is = is;
})(MarkupKind || (MarkupKind = {}));
var MarkupContent;
(function (MarkupContent) {
/**
* Checks whether the given value conforms to the {@link MarkupContent} interface.
*/
function is(value) {
var candidate = value;
return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
}
MarkupContent.is = is;
})(MarkupContent || (MarkupContent = {}));
/**
* The kind of a completion entry.
*/
var CompletionItemKind;
(function (CompletionItemKind) {
CompletionItemKind.Text = 1;
CompletionItemKind.Method = 2;
CompletionItemKind.Function = 3;
CompletionItemKind.Constructor = 4;
CompletionItemKind.Field = 5;
CompletionItemKind.Variable = 6;
CompletionItemKind.Class = 7;
CompletionItemKind.Interface = 8;
CompletionItemKind.Module = 9;
CompletionItemKind.Property = 10;
CompletionItemKind.Unit = 11;
CompletionItemKind.Value = 12;
CompletionItemKind.Enum = 13;
CompletionItemKind.Keyword = 14;
CompletionItemKind.Snippet = 15;
CompletionItemKind.Color = 16;
CompletionItemKind.File = 17;
CompletionItemKind.Reference = 18;
CompletionItemKind.Folder = 19;
CompletionItemKind.EnumMember = 20;
CompletionItemKind.Constant = 21;
CompletionItemKind.Struct = 22;
CompletionItemKind.Event = 23;
CompletionItemKind.Operator = 24;
CompletionItemKind.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
/**
* Defines whether the insert text in a completion item should be interpreted as
* plain text or a snippet.
*/
var InsertTextFormat;
(function (InsertTextFormat) {
/**
* The primary text to be inserted is treated as a plain string.
*/
InsertTextFormat.PlainText = 1;
/**
* The primary text to be inserted is treated as a snippet.
*
* A snippet can define tab stops and placeholders with `$1`, `$2`
* and `${3:foo}`. `$0` defines the final tab stop, it defaults to
* the end of the snippet. Placeholders with equal identifiers are linked,
* that is typing in one will update others too.
*
* See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax
*/
InsertTextFormat.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
/**
* Completion item tags are extra annotations that tweak the rendering of a completion
* item.
*
* @since 3.15.0
*/
var CompletionItemTag;
(function (CompletionItemTag) {
/**
* Render a completion as obsolete, usually using a strike-out.
*/
CompletionItemTag.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
/**
* The InsertReplaceEdit namespace provides functions to deal with insert / replace edits.
*
* @since 3.16.0
*/
var InsertReplaceEdit;
(function (InsertReplaceEdit) {
/**
* Creates a new insert / replace edit
*/
function create(newText, insert, replace) {
return { newText: newText, insert: insert, replace: replace };
}
InsertReplaceEdit.create = create;
/**
* Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface.
*/
function is(value) {
var candidate = value;
return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
}
InsertReplaceEdit.is = is;
})(InsertReplaceEdit || (InsertReplaceEdit = {}));
/**
* How whitespace and indentation is handled during completion
* item insertion.
*
* @since 3.16.0
*/
var InsertTextMode;
(function (InsertTextMode) {
/**
* The insertion or replace strings is taken as it is. If the
* value is multi line the lines below the cursor will be
* inserted using the indentation defined in the string value.
* The client will not apply any kind of adjustments to the
* string.
*/
InsertTextMode.asIs = 1;
/**
* The editor adjusts leading whitespace of new lines so that
* they match the indentation up to the cursor of the line for
* which the item is accepted.
*
* Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a
* multi line completion item is indented using 2 tabs and all
* following lines inserted will be indented using 2 tabs as well.
*/
InsertTextMode.adjustIndentation = 2;
})(InsertTextMode || (InsertTextMode = {}));
var CompletionItemLabelDetails;
(function (CompletionItemLabelDetails) {
function is(value) {
var candidate = value;
return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) &&
(Is.string(candidate.description) || candidate.description === undefined);
}
CompletionItemLabelDetails.is = is;
})(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));
/**
* The CompletionItem namespace provides functions to deal with
* completion items.
*/
var CompletionItem;
(function (CompletionItem) {
/**
* Create a completion item and seed it with a label.
* @param label The completion item's label
*/
function create(label) {
return { label: label };
}
CompletionItem.create = create;
})(CompletionItem || (CompletionItem = {}));
/**
* The CompletionList namespace provides functions to deal with
* completion lists.
*/
var CompletionList;
(function (CompletionList) {
/**
* Creates a new completion list.
*
* @param items The completion items.
* @param isIncomplete The list is not complete.
*/
function create(items, isIncomplete) {
return { items: items ? items : [], isIncomplete: !!isIncomplete };
}
CompletionList.create = create;
})(CompletionList || (CompletionList = {}));
var MarkedString;
(function (MarkedString) {
/**
* Creates a marked string from plain text.
*
* @param plainText The plain text.
*/
function fromPlainText(plainText) {
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
}
MarkedString.fromPlainText = fromPlainText;
/**
* Checks whether the given value conforms to the {@link MarkedString} type.
*/
function is(value) {
var candidate = value;
return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
}
MarkedString.is = is;
})(MarkedString || (MarkedString = {}));
var Hover;
(function (Hover) {
/**
* Checks whether the given value conforms to the {@link Hover} interface.
*/
function is(value) {
var candidate = value;
return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
MarkedString.is(candidate.contents) ||
Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));
}
Hover.is = is;
})(Hover || (Hover = {}));
/**
* The ParameterInformation namespace provides helper functions to work with
* {@link ParameterInformation} literals.
*/
var ParameterInformation;
(function (ParameterInformation) {
/**
* Creates a new parameter information literal.
*
* @param label A label string.
* @param documentation A doc string.
*/
function create(label, documentation) {
return documentation ? { label: label, documentation: documentation } : { label: label };
}
ParameterInformation.create = create;
})(ParameterInformation || (ParameterInformation = {}));
/**
* The SignatureInformation namespace provides helper functions to work with
* {@link SignatureInformation} literals.
*/
var SignatureInformation;
(function (SignatureInformation) {
function create(label, documentation) {
var parameters = [];
for (var _i = 2; _i < arguments.length; _i++) {
parameters[_i - 2] = arguments[_i];
}
var result = { label: label };
if (Is.defined(documentation)) {
result.documentation = documentation;
}
if (Is.defined(parameters)) {
result.parameters = parameters;
}
else {
result.parameters = [];
}
return result;
}
SignatureInformation.create = create;
})(SignatureInformation || (SignatureInformation = {}));
/**
* A document highlight kind.
*/
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
/**
* A textual occurrence.
*/
DocumentHighlightKind.Text = 1;
/**
* Read-access of a symbol, like reading a variable.
*/
DocumentHighlightKind.Read = 2;
/**
* Write-access of a symbol, like writing to a variable.
*/
DocumentHighlightKind.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
/**
* DocumentHighlight namespace to provide helper functions to work with
* {@link DocumentHighlight} literals.
*/
var DocumentHighlight;
(function (DocumentHighlight) {
/**
* Create a DocumentHighlight object.
* @param range The range the highlight applies to.
* @param kind The highlight kind
*/
function create(range, kind) {
var result = { range: range };
if (Is.number(kind)) {
result.kind = kind;
}
return result;
}
DocumentHighlight.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
/**
* A symbol kind.
*/
var SymbolKind;
(function (SymbolKind) {
SymbolKind.File = 1;
SymbolKind.Module = 2;
SymbolKind.Namespace = 3;
SymbolKind.Package = 4;
SymbolKind.Class = 5;
SymbolKind.Method = 6;
SymbolKind.Property = 7;
SymbolKind.Field = 8;
SymbolKind.Constructor = 9;
SymbolKind.Enum = 10;
SymbolKind.Interface = 11;
SymbolKind.Function = 12;
SymbolKind.Variable = 13;
SymbolKind.Constant = 14;
SymbolKind.String = 15;
SymbolKind.Number = 16;
SymbolKind.Boolean = 17;
SymbolKind.Array = 18;
SymbolKind.Object = 19;
SymbolKind.Key = 20;
SymbolKind.Null = 21;
SymbolKind.EnumMember = 22;
SymbolKind.Struct = 23;
SymbolKind.Event = 24;
SymbolKind.Operator = 25;
SymbolKind.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
/**
* Symbol tags are extra annotations that tweak the rendering of a symbol.
*
* @since 3.16
*/
var SymbolTag;
(function (SymbolTag) {
/**
* Render a symbol as obsolete, usually using a strike-out.
*/
SymbolTag.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
var SymbolInformation;
(function (SymbolInformation) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the location of the symbol.
* @param uri The resource of the location of symbol.
* @param containerName The name of the symbol containing the symbol.
*/
function create(name, kind, range, uri, containerName) {
var result = {
name: name,
kind: kind,
location: { uri: uri, range: range }
};
if (containerName) {
result.containerName = containerName;
}
return result;
}
SymbolInformation.create = create;
})(SymbolInformation || (SymbolInformation = {}));
var WorkspaceSymbol;
(function (WorkspaceSymbol) {
/**
* Create a new workspace symbol.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param uri The resource of the location of the symbol.
* @param range An options range of the location.
* @returns A WorkspaceSymbol.
*/
function create(name, kind, uri, range) {
return range !== undefined
? { name: name, kind: kind, location: { uri: uri, range: range } }
: { name: name, kind: kind, location: { uri: uri } };
}
WorkspaceSymbol.create = create;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
var DocumentSymbol;
(function (DocumentSymbol) {
/**
* Creates a new symbol information literal.
*
* @param name The name of the symbol.
* @param detail The detail of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the symbol.
* @param selectionRange The selectionRange of the symbol.
* @param children Children of the symbol.
*/
function create(name, detail, kind, range, selectionRange, children) {
var result = {
name: name,
detail: detail,
kind: kind,
range: range,
selectionRange: selectionRange
};
if (children !== undefined) {
result.children = children;
}
return result;
}
DocumentSymbol.create = create;
/**
* Checks whether the given literal conforms to the {@link DocumentSymbol} interface.
*/
function is(value) {
var candidate = value;
return candidate &&
Is.string(candidate.name) && Is.number(candidate.kind) &&
Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
(candidate.detail === undefined || Is.string(candidate.detail)) &&
(candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) &&
(candidate.children === undefined || Array.isArray(candidate.children)) &&
(candidate.tags === undefined || Array.isArray(candidate.tags));
}
DocumentSymbol.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
/**
* A set of predefined code action kinds
*/
var CodeActionKind;
(function (CodeActionKind) {
/**
* Empty kind.
*/
CodeActionKind.Empty = '';
/**
* Base kind for quickfix actions: 'quickfix'
*/
CodeActionKind.QuickFix = 'quickfix';
/**
* Base kind for refactoring actions: 'refactor'
*/
CodeActionKind.Refactor = 'refactor';
/**
* Base kind for refactoring extraction actions: 'refactor.extract'
*
* Example extract actions:
*
* - Extract method
* - Extract function
* - Extract variable
* - Extract interface from class
* - ...
*/
CodeActionKind.RefactorExtract = 'refactor.extract';
/**
* Base kind for refactoring inline actions: 'refactor.inline'
*
* Example inline actions:
*
* - Inline function
* - Inline variable
* - Inline constant
* - ...
*/
CodeActionKind.RefactorInline = 'refactor.inline';
/**
* Base kind for refactoring rewrite actions: 'refactor.rewrite'
*
* Example rewrite actions:
*
* - Convert JavaScript function to class
* - Add or remove parameter
* - Encapsulate field
* - Make method static
* - Move method to base class
* - ...
*/
CodeActionKind.RefactorRewrite = 'refactor.rewrite';
/**
* Base kind for source actions: `source`
*
* Source code actions apply to the entire file.
*/
CodeActionKind.Source = 'source';
/**
* Base kind for an organize imports source action: `source.organizeImports`
*/
CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
/**
* Base kind for auto-fix source actions: `source.fixAll`.
*
* Fix all actions automatically fix errors that have a clear fix that do not require user input.
* They should not suppress errors or perform unsafe fixes such as generating new types or classes.
*
* @since 3.15.0
*/
CodeActionKind.SourceFixAll = 'source.fixAll';
})(CodeActionKind || (CodeActionKind = {}));
/**
* The reason why code actions were requested.
*
* @since 3.17.0
*/
var CodeActionTriggerKind;
(function (CodeActionTriggerKind) {
/**
* Code actions were explicitly requested by the user or by an extension.
*/
CodeActionTriggerKind.Invoked = 1;
/**
* Code actions were requested automatically.
*
* This typically happens when current selection in a file changes, but can
* also be triggered when file content changes.
*/
CodeActionTriggerKind.Automatic = 2;
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
/**
* The CodeActionContext namespace provides helper functions to work with
* {@link CodeActionContext} literals.
*/
var CodeActionContext;
(function (CodeActionContext) {
/**
* Creates a new CodeActionContext literal.
*/
function create(diagnostics, only, triggerKind) {
var result = { diagnostics: diagnostics };
if (only !== undefined && only !== null) {
result.only = only;
}
if (triggerKind !== undefined && triggerKind !== null) {
result.triggerKind = triggerKind;
}
return result;
}
CodeActionContext.create = create;
/**
* Checks whether the given literal conforms to the {@link CodeActionContext} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is)
&& (candidate.only === undefined || Is.typedArray(candidate.only, Is.string))
&& (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
}
CodeActionContext.is = is;
})(CodeActionContext || (CodeActionContext = {}));
var CodeAction;
(function (CodeAction) {
function create(title, kindOrCommandOrEdit, kind) {
var result = { title: title };
var checkKind = true;
if (typeof kindOrCommandOrEdit === 'string') {
checkKind = false;
result.kind = kindOrCommandOrEdit;
}
else if (Command.is(kindOrCommandOrEdit)) {
result.command = kindOrCommandOrEdit;
}
else {
result.edit = kindOrCommandOrEdit;
}
if (checkKind && kind !== undefined) {
result.kind = kind;
}
return result;
}
CodeAction.create = create;
function is(value) {
var candidate = value;
return candidate && Is.string(candidate.title) &&
(candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
(candidate.kind === undefined || Is.string(candidate.kind)) &&
(candidate.edit !== undefined || candidate.command !== undefined) &&
(candidate.command === undefined || Command.is(candidate.command)) &&
(candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) &&
(candidate.edit === undefined || WorkspaceEdit.is(candidate.edit));
}
CodeAction.is = is;
})(CodeAction || (CodeAction = {}));
/**
* The CodeLens namespace provides helper functions to work with
* {@link CodeLens} literals.
*/
var CodeLens;
(function (CodeLens) {
/**
* Creates a new CodeLens literal.
*/
function create(range, data) {
var result = { range: range };
if (Is.defined(data)) {
result.data = data;
}
return result;
}
CodeLens.create = create;
/**
* Checks whether the given literal conforms to the {@link CodeLens} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
}
CodeLens.is = is;
})(CodeLens || (CodeLens = {}));
/**
* The FormattingOptions namespace provides helper functions to work with
* {@link FormattingOptions} literals.
*/
var FormattingOptions;
(function (FormattingOptions) {
/**
* Creates a new FormattingOptions literal.
*/
function create(tabSize, insertSpaces) {
return { tabSize: tabSize, insertSpaces: insertSpaces };
}
FormattingOptions.create = create;
/**
* Checks whether the given literal conforms to the {@link FormattingOptions} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
}
FormattingOptions.is = is;
})(FormattingOptions || (FormattingOptions = {}));
/**
* The DocumentLink namespace provides helper functions to work with
* {@link DocumentLink} literals.
*/
var DocumentLink;
(function (DocumentLink) {
/**
* Creates a new DocumentLink literal.
*/
function create(range, target, data) {
return { range: range, target: target, data: data };
}
DocumentLink.create = create;
/**
* Checks whether the given literal conforms to the {@link DocumentLink} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
}
DocumentLink.is = is;
})(DocumentLink || (DocumentLink = {}));
/**
* The SelectionRange namespace provides helper function to work with
* SelectionRange literals.
*/
var SelectionRange;
(function (SelectionRange) {
/**
* Creates a new SelectionRange
* @param range the range.
* @param parent an optional parent.
*/
function create(range, parent) {
return { range: range, parent: parent };
}
SelectionRange.create = create;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
}
SelectionRange.is = is;
})(SelectionRange || (SelectionRange = {}));
/**
* A set of predefined token types. This set is not fixed
* an clients can specify additional token types via the
* corresponding client capabilities.
*
* @since 3.16.0
*/
var SemanticTokenTypes;
(function (SemanticTokenTypes) {
SemanticTokenTypes["namespace"] = "namespace";
/**
* Represents a generic type. Acts as a fallback for types which can't be mapped to
* a specific type like class or enum.
*/
SemanticTokenTypes["type"] = "type";
SemanticTokenTypes["class"] = "class";
SemanticTokenTypes["enum"] = "enum";
SemanticTokenTypes["interface"] = "interface";
SemanticTokenTypes["struct"] = "struct";
SemanticTokenTypes["typeParameter"] = "typeParameter";
SemanticTokenTypes["parameter"] = "parameter";
SemanticTokenTypes["variable"] = "variable";
SemanticTokenTypes["property"] = "property";
SemanticTokenTypes["enumMember"] = "enumMember";
SemanticTokenTypes["event"] = "event";
SemanticTokenTypes["function"] = "function";
SemanticTokenTypes["method"] = "method";
SemanticTokenTypes["macro"] = "macro";
SemanticTokenTypes["keyword"] = "keyword";
SemanticTokenTypes["modifier"] = "modifier";
SemanticTokenTypes["comment"] = "comment";
SemanticTokenTypes["string"] = "string";
SemanticTokenTypes["number"] = "number";
SemanticTokenTypes["regexp"] = "regexp";
SemanticTokenTypes["operator"] = "operator";
/**
* @since 3.17.0
*/
SemanticTokenTypes["decorator"] = "decorator";
})(SemanticTokenTypes || (SemanticTokenTypes = {}));
/**
* A set of predefined token modifiers. This set is not fixed
* an clients can specify additional token types via the
* corresponding client capabilities.
*
* @since 3.16.0
*/
var SemanticTokenModifiers;
(function (SemanticTokenModifiers) {
SemanticTokenModifiers["declaration"] = "declaration";
SemanticTokenModifiers["definition"] = "definition";
SemanticTokenModifiers["readonly"] = "readonly";
SemanticTokenModifiers["static"] = "static";
SemanticTokenModifiers["deprecated"] = "deprecated";
SemanticTokenModifiers["abstract"] = "abstract";
SemanticTokenModifiers["async"] = "async";
SemanticTokenModifiers["modification"] = "modification";
SemanticTokenModifiers["documentation"] = "documentation";
SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary";
})(SemanticTokenModifiers || (SemanticTokenModifiers = {}));
/**
* @since 3.16.0
*/
var SemanticTokens;
(function (SemanticTokens) {
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
}
SemanticTokens.is = is;
})(SemanticTokens || (SemanticTokens = {}));
/**
* The InlineValueText namespace provides functions to deal with InlineValueTexts.
*
* @since 3.17.0
*/
var InlineValueText;
(function (InlineValueText) {
/**
* Creates a new InlineValueText literal.
*/
function create(range, text) {
return { range: range, text: text };
}
InlineValueText.create = create;
function is(value) {
var candidate = value;
return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);
}
InlineValueText.is = is;
})(InlineValueText || (InlineValueText = {}));
/**
* The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups.
*
* @since 3.17.0
*/
var InlineValueVariableLookup;
(function (InlineValueVariableLookup) {
/**
* Creates a new InlineValueText literal.
*/
function create(range, variableName, caseSensitiveLookup) {
return { range: range, variableName: variableName, caseSensitiveLookup: caseSensitiveLookup };
}
InlineValueVariableLookup.create = create;
function is(value) {
var candidate = value;
return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup)
&& (Is.string(candidate.variableName) || candidate.variableName === undefined);
}
InlineValueVariableLookup.is = is;
})(InlineValueVariableLookup || (InlineValueVariableLookup = {}));
/**
* The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression.
*
* @since 3.17.0
*/
var InlineValueEvaluatableExpression;
(function (InlineValueEvaluatableExpression) {
/**
* Creates a new InlineValueEvaluatableExpression literal.
*/
function create(range, expression) {
return { range: range, expression: expression };
}
InlineValueEvaluatableExpression.create = create;
function is(value) {
var candidate = value;
return candidate !== undefined && candidate !== null && Range.is(candidate.range)
&& (Is.string(candidate.expression) || candidate.expression === undefined);
}
InlineValueEvaluatableExpression.is = is;
})(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));
/**
* The InlineValueContext namespace provides helper functions to work with
* {@link InlineValueContext} literals.
*
* @since 3.17.0
*/
var InlineValueContext;
(function (InlineValueContext) {
/**
* Creates a new InlineValueContext literal.
*/
function create(frameId, stoppedLocation) {
return { frameId: frameId, stoppedLocation: stoppedLocation };
}
InlineValueContext.create = create;
/**
* Checks whether the given literal conforms to the {@link InlineValueContext} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Range.is(value.stoppedLocation);
}
InlineValueContext.is = is;
})(InlineValueContext || (InlineValueContext = {}));
/**
* Inlay hint kinds.
*
* @since 3.17.0
*/
var InlayHintKind;
(function (InlayHintKind) {
/**
* An inlay hint that for a type annotation.
*/
InlayHintKind.Type = 1;
/**
* An inlay hint that is for a parameter.
*/
InlayHintKind.Parameter = 2;
function is(value) {
return value === 1 || value === 2;
}
InlayHintKind.is = is;
})(InlayHintKind || (InlayHintKind = {}));
var InlayHintLabelPart;
(function (InlayHintLabelPart) {
function create(value) {
return { value: value };
}
InlayHintLabelPart.create = create;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate)
&& (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))
&& (candidate.location === undefined || Location.is(candidate.location))
&& (candidate.command === undefined || Command.is(candidate.command));
}
InlayHintLabelPart.is = is;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
var InlayHint;
(function (InlayHint) {
function create(position, label, kind) {
var result = { position: position, label: label };
if (kind !== undefined) {
result.kind = kind;
}
return result;
}
InlayHint.create = create;
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.position)
&& (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is))
&& (candidate.kind === undefined || InlayHintKind.is(candidate.kind))
&& (candidate.textEdits === undefined) || Is.typedArray(candidate.textEdits, TextEdit.is)
&& (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip))
&& (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft))
&& (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight));
}
InlayHint.is = is;
})(InlayHint || (InlayHint = {}));
var WorkspaceFolder;
(function (WorkspaceFolder) {
function is(value) {
var candidate = value;
return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);
}
WorkspaceFolder.is = is;
})(WorkspaceFolder || (WorkspaceFolder = {}));
var EOL = ['\n', '\r\n', '\r'];
/**
* @deprecated Use the text document from the new vscode-languageserver-textdocument package.
*/
var TextDocument;
(function (TextDocument) {
/**
* Creates a new ITextDocument literal from the given uri and content.
* @param uri The document's uri.
* @param languageId The document's language Id.
* @param version The document's version.
* @param content The document's content.
*/
function create(uri, languageId, version, content) {
return new FullTextDocument(uri, languageId, version, content);
}
TextDocument.create = create;
/**
* Checks whether the given literal conforms to the {@link ITextDocument} interface.
*/
function is(value) {
var candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount)
&& Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
}
TextDocument.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;
}
TextDocument.applyEdits = applyEdits;
function mergeSort(data, compare) {
if (data.length <= 1) {
// sorted
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) {
// smaller_equal -> take left to preserve order
data[i++] = left[leftIdx++];
}
else {
// greater -> take right
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
})(TextDocument || (TextDocument = {}));
/**
* @deprecated Use the text document from the new vscode-languageserver-textdocument package.
*/
var FullTextDocument = /** @class */ (function () {
function FullTextDocument(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = undefined;
}
Object.defineProperty(FullTextDocument.prototype, "uri", {
get: function () {
return this._uri;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "languageId", {
get: function () {
return this._languageId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FullTextDocument.prototype, "version", {
get: function () {
return this._version;
},
enumerable: false,
configurable: true
});
FullTextDocument.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;
};
FullTextDocument.prototype.update = function (event, version) {
this._content = event.text;
this._version = version;
this._lineOffsets = undefined;
};
FullTextDocument.prototype.getLineOffsets = function () {
if (this._lineOffsets === undefined) {
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;
};
FullTextDocument.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 Position.create(0, offset);
}
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
}
else {
low = mid + 1;
}
}
// low is the least x for which the line offset is larger than the current offset
// or array.length if no line offset is larger than the current offset
var line = low - 1;
return Position.create(line, offset - lineOffsets[line]);
};
FullTextDocument.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(FullTextDocument.prototype, "lineCount", {
get: function () {
return this.getLineOffsets().length;
},
enumerable: false,
configurable: true
});
return FullTextDocument;
}());
var Is;
(function (Is) {
var toString = Object.prototype.toString;
function defined(value) {
return typeof value !== 'undefined';
}
Is.defined = defined;
function undefined(value) {
return typeof value === 'undefined';
}
Is.undefined = undefined;
function boolean(value) {
return value === true || value === false;
}
Is.boolean = boolean;
function string(value) {
return toString.call(value) === '[object String]';
}
Is.string = string;
function number(value) {
return toString.call(value) === '[object Number]';
}
Is.number = number;
function numberRange(value, min, max) {
return toString.call(value) === '[object Number]' && min <= value && value <= max;
}
Is.numberRange = numberRange;
function integer(value) {
return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647;
}
Is.integer = integer;
function uinteger(value) {
return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647;
}
Is.uinteger = uinteger;
function func(value) {
return toString.call(value) === '[object Function]';
}
Is.func = func;
function objectLiteral(value) {
// Strictly speaking class instances pass this check as well. Since the LSP
// doesn't use classes we ignore this for now. If we do we need to add something
// like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
return value !== null && typeof value === 'object';
}
Is.objectLiteral = objectLiteral;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
Is.typedArray = typedArray;
})(Is || (Is = {}));
/***/ }),
/***/ 2730:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var forEach = __webpack_require__(705);
var availableTypedArrays = __webpack_require__(4834);
var callBind = __webpack_require__(8498);
var callBound = __webpack_require__(9818);
var gOPD = __webpack_require__(9336);
var $toString = callBound('Object.prototype.toString');
var hasToStringTag = __webpack_require__(1913)();
var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis;
var typedArrays = availableTypedArrays();
var $slice = callBound('String.prototype.slice');
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
var cache = { __proto__: null };
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
descriptor = gOPD(superProto, Symbol.toStringTag);
}
cache['$' + typedArray] = callBind(descriptor.get);
}
});
} else {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
cache['$' + typedArray] = callBind(arr.slice);
});
}
var tryTypedArrays = function tryAllTypedArrays(value) {
var found = false;
forEach(cache, function (getter, typedArray) {
if (!found) {
try {
if ('$' + getter(value) === typedArray) {
found = $slice(typedArray, 1);
}
} catch (e) { /**/ }
}
});
return found;
};
var trySlices = function tryAllSlices(value) {
var found = false;
forEach(cache, function (getter, name) {
if (!found) {
try {
getter(value);
found = $slice(name, 1);
} catch (e) { /**/ }
}
});
return found;
};
module.exports = function whichTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag) {
var tag = $slice($toString(value), 8, -1);
if ($indexOf(typedArrays, tag) > -1) {
return tag;
}
if (tag !== 'Object') {
return false;
}
// node < 0.6 hits here on real Typed Arrays
return trySlices(value);
}
if (!gOPD) { return null; } // unknown engine
return tryTypedArrays(value);
};
/***/ }),
/***/ 4834:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var possibleNames = [
'BigInt64Array',
'BigUint64Array',
'Float32Array',
'Float64Array',
'Int16Array',
'Int32Array',
'Int8Array',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray'
];
var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis;
module.exports = function availableTypedArrays() {
var out = [];
for (var i = 0; i < possibleNames.length; i++) {
if (typeof g[possibleNames[i]] === 'function') {
out[out.length] = possibleNames[i];
}
}
return out;
};
/***/ }),
/***/ 2917:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ r: () => (/* binding */ URI)
/* harmony export */ });
/* unused harmony export Utils */
/* provided dependency */ var process = __webpack_require__(9907);
var LIB;(()=>{"use strict";var t={470:t=>{function e(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function r(t,e){for(var r,n="",i=0,o=-1,s=0,h=0;h<=t.length;++h){if(h<t.length)r=t.charCodeAt(h);else{if(47===r)break;r=47}if(47===r){if(o===h-1||1===s);else if(o!==h-1&&2===s){if(n.length<2||2!==i||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var a=n.lastIndexOf("/");if(a!==n.length-1){-1===a?(n="",i=0):i=(n=n.slice(0,a)).length-1-n.lastIndexOf("/"),o=h,s=0;continue}}else if(2===n.length||1===n.length){n="",i=0,o=h,s=0;continue}e&&(n.length>0?n+="/..":n="..",i=2)}else n.length>0?n+="/"+t.slice(o+1,h):n=t.slice(o+1,h),i=h-o-1;o=h,s=0}else 46===r&&-1!==s?++s:s=-1}return n}var n={resolve:function(){for(var t,n="",i=!1,o=arguments.length-1;o>=-1&&!i;o--){var s;o>=0?s=arguments[o]:(void 0===t&&(t=process.cwd()),s=t),e(s),0!==s.length&&(n=s+"/"+n,i=47===s.charCodeAt(0))}return n=r(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(t){if(e(t),0===t.length)return".";var n=47===t.charCodeAt(0),i=47===t.charCodeAt(t.length-1);return 0!==(t=r(t,!n)).length||n||(t="."),t.length>0&&i&&(t+="/"),n?"/"+t:t},isAbsolute:function(t){return e(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,r=0;r<arguments.length;++r){var i=arguments[r];e(i),i.length>0&&(void 0===t?t=i:t+="/"+i)}return void 0===t?".":n.normalize(t)},relative:function(t,r){if(e(t),e(r),t===r)return"";if((t=n.resolve(t))===(r=n.resolve(r)))return"";for(var i=1;i<t.length&&47===t.charCodeAt(i);++i);for(var o=t.length,s=o-i,h=1;h<r.length&&47===r.charCodeAt(h);++h);for(var a=r.length-h,c=s<a?s:a,f=-1,u=0;u<=c;++u){if(u===c){if(a>c){if(47===r.charCodeAt(h+u))return r.slice(h+u+1);if(0===u)return r.slice(h+u)}else s>c&&(47===t.charCodeAt(i+u)?f=u:0===u&&(f=0));break}var l=t.charCodeAt(i+u);if(l!==r.charCodeAt(h+u))break;47===l&&(f=u)}var g="";for(u=i+f+1;u<=o;++u)u!==o&&47!==t.charCodeAt(u)||(0===g.length?g+="..":g+="/..");return g.length>0?g+r.slice(h+f):(h+=f,47===r.charCodeAt(h)&&++h,r.slice(h))},_makeLong:function(t){return t},dirname:function(t){if(e(t),0===t.length)return".";for(var r=t.charCodeAt(0),n=47===r,i=-1,o=!0,s=t.length-1;s>=1;--s)if(47===(r=t.charCodeAt(s))){if(!o){i=s;break}}else o=!1;return-1===i?n?"/":".":n&&1===i?"//":t.slice(0,i)},basename:function(t,r){if(void 0!==r&&"string"!=typeof r)throw new TypeError('"ext" argument must be a string');e(t);var n,i=0,o=-1,s=!0;if(void 0!==r&&r.length>0&&r.length<=t.length){if(r.length===t.length&&r===t)return"";var h=r.length-1,a=-1;for(n=t.length-1;n>=0;--n){var c=t.charCodeAt(n);if(47===c){if(!s){i=n+1;break}}else-1===a&&(s=!1,a=n+1),h>=0&&(c===r.charCodeAt(h)?-1==--h&&(o=n):(h=-1,o=a))}return i===o?o=a:-1===o&&(o=t.length),t.slice(i,o)}for(n=t.length-1;n>=0;--n)if(47===t.charCodeAt(n)){if(!s){i=n+1;break}}else-1===o&&(s=!1,o=n+1);return-1===o?"":t.slice(i,o)},extname:function(t){e(t);for(var r=-1,n=0,i=-1,o=!0,s=0,h=t.length-1;h>=0;--h){var a=t.charCodeAt(h);if(47!==a)-1===i&&(o=!1,i=h+1),46===a?-1===r?r=h:1!==s&&(s=1):-1!==r&&(s=-1);else if(!o){n=h+1;break}}return-1===r||-1===i||0===s||1===s&&r===i-1&&r===n+1?"":t.slice(r,i)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return function(t,e){var r=e.dir||e.root,n=e.base||(e.name||"")+(e.ext||"");return r?r===e.root?r+n:r+"/"+n:n}(0,t)},parse:function(t){e(t);var r={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return r;var n,i=t.charCodeAt(0),o=47===i;o?(r.root="/",n=1):n=0;for(var s=-1,h=0,a=-1,c=!0,f=t.length-1,u=0;f>=n;--f)if(47!==(i=t.charCodeAt(f)))-1===a&&(c=!1,a=f+1),46===i?-1===s?s=f:1!==u&&(u=1):-1!==s&&(u=-1);else if(!c){h=f+1;break}return-1===s||-1===a||0===u||1===u&&s===a-1&&s===h+1?-1!==a&&(r.base=r.name=0===h&&o?t.slice(1,a):t.slice(h,a)):(0===h&&o?(r.name=t.slice(1,s),r.base=t.slice(1,a)):(r.name=t.slice(h,s),r.base=t.slice(h,a)),r.ext=t.slice(s,a)),h>0?r.dir=t.slice(0,h-1):o&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,t.exports=n}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var n={};(()=>{let t;if(r.r(n),r.d(n,{URI:()=>f,Utils:()=>P}),"object"==typeof process)t="win32"===process.platform;else if("object"==typeof navigator){let e=navigator.userAgent;t=e.indexOf("Windows")>=0}const e=/^\w[\w\d+.-]*$/,i=/^\//,o=/^\/\//;function s(t,r){if(!t.scheme&&r)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t.authority}", path: "${t.path}", query: "${t.query}", fragment: "${t.fragment}"}`);if(t.scheme&&!e.test(t.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(t.path)if(t.authority){if(!i.test(t.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(o.test(t.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}const h="",a="/",c=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class f{static isUri(t){return t instanceof f||!!t&&"string"==typeof t.authority&&"string"==typeof t.fragment&&"string"==typeof t.path&&"string"==typeof t.query&&"string"==typeof t.scheme&&"string"==typeof t.fsPath&&"function"==typeof t.with&&"function"==typeof t.toString}scheme;authority;path;query;fragment;constructor(t,e,r,n,i,o=!1){"object"==typeof t?(this.scheme=t.scheme||h,this.authority=t.authority||h,this.path=t.path||h,this.query=t.query||h,this.fragment=t.fragment||h):(this.scheme=function(t,e){return t||e?t:"file"}(t,o),this.authority=e||h,this.path=function(t,e){switch(t){case"https":case"http":case"file":e?e[0]!==a&&(e=a+e):e=a}return e}(this.scheme,r||h),this.query=n||h,this.fragment=i||h,s(this,o))}get fsPath(){return m(this,!1)}with(t){if(!t)return this;let{scheme:e,authority:r,path:n,query:i,fragment:o}=t;return void 0===e?e=this.scheme:null===e&&(e=h),void 0===r?r=this.authority:null===r&&(r=h),void 0===n?n=this.path:null===n&&(n=h),void 0===i?i=this.query:null===i&&(i=h),void 0===o?o=this.fragment:null===o&&(o=h),e===this.scheme&&r===this.authority&&n===this.path&&i===this.query&&o===this.fragment?this:new l(e,r,n,i,o)}static parse(t,e=!1){const r=c.exec(t);return r?new l(r[2]||h,C(r[4]||h),C(r[5]||h),C(r[7]||h),C(r[9]||h),e):new l(h,h,h,h,h)}static file(e){let r=h;if(t&&(e=e.replace(/\\/g,a)),e[0]===a&&e[1]===a){const t=e.indexOf(a,2);-1===t?(r=e.substring(2),e=a):(r=e.substring(2,t),e=e.substring(t)||a)}return new l("file",r,e,h,h)}static from(t){const e=new l(t.scheme,t.authority,t.path,t.query,t.fragment);return s(e,!0),e}toString(t=!1){return y(this,t)}toJSON(){return this}static revive(t){if(t){if(t instanceof f)return t;{const e=new l(t);return e._formatted=t.external,e._fsPath=t._sep===u?t.fsPath:null,e}}return t}}const u=t?1:void 0;class l extends f{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=m(this,!1)),this._fsPath}toString(t=!1){return t?y(this,!0):(this._formatted||(this._formatted=y(this,!1)),this._formatted)}toJSON(){const t={$mid:1};return this._fsPath&&(t.fsPath=this._fsPath,t._sep=u),this._formatted&&(t.external=this._formatted),this.path&&(t.path=this.path),this.scheme&&(t.scheme=this.scheme),this.authority&&(t.authority=this.authority),this.query&&(t.query=this.query),this.fragment&&(t.fragment=this.fragment),t}}const g={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function d(t,e,r){let n,i=-1;for(let o=0;o<t.length;o++){const s=t.charCodeAt(o);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||e&&47===s||r&&91===s||r&&93===s||r&&58===s)-1!==i&&(n+=encodeURIComponent(t.substring(i,o)),i=-1),void 0!==n&&(n+=t.charAt(o));else{void 0===n&&(n=t.substr(0,o));const e=g[s];void 0!==e?(-1!==i&&(n+=encodeURIComponent(t.substring(i,o)),i=-1),n+=e):-1===i&&(i=o)}}return-1!==i&&(n+=encodeURIComponent(t.substring(i))),void 0!==n?n:t}function p(t){let e;for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);35===n||63===n?(void 0===e&&(e=t.substr(0,r)),e+=g[n]):void 0!==e&&(e+=t[r])}return void 0!==e?e:t}function m(e,r){let n;return n=e.authority&&e.path.length>1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?r?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,t&&(n=n.replace(/\//g,"\\")),n}function y(t,e){const r=e?p:d;let n="",{scheme:i,authority:o,path:s,query:h,fragment:c}=t;if(i&&(n+=i,n+=":"),(o||"file"===i)&&(n+=a,n+=a),o){let t=o.indexOf("@");if(-1!==t){const e=o.substr(0,t);o=o.substr(t+1),t=e.lastIndexOf(":"),-1===t?n+=r(e,!1,!1):(n+=r(e.substr(0,t),!1,!1),n+=":",n+=r(e.substr(t+1),!1,!0)),n+="@"}o=o.toLowerCase(),t=o.lastIndexOf(":"),-1===t?n+=r(o,!1,!0):(n+=r(o.substr(0,t),!1,!0),n+=o.substr(t))}if(s){if(s.length>=3&&47===s.charCodeAt(0)&&58===s.charCodeAt(2)){const t=s.charCodeAt(1);t>=65&&t<=90&&(s=`/${String.fromCharCode(t+32)}:${s.substr(3)}`)}else if(s.length>=2&&58===s.charCodeAt(1)){const t=s.charCodeAt(0);t>=65&&t<=90&&(s=`${String.fromCharCode(t+32)}:${s.substr(2)}`)}n+=r(s,!0,!1)}return h&&(n+="?",n+=r(h,!1,!1)),c&&(n+="#",n+=e?c:d(c,!1,!1)),n}function v(t){try{return decodeURIComponent(t)}catch{return t.length>3?t.substr(0,3)+v(t.substr(3)):t}}const b=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function C(t){return t.match(b)?t.replace(b,(t=>v(t))):t}var A=r(470);const w=A.posix||A,x="/";var P;!function(t){t.joinPath=function(t,...e){return t.with({path:w.join(t.path,...e)})},t.resolvePath=function(t,...e){let r=t.path,n=!1;r[0]!==x&&(r=x+r,n=!0);let i=w.resolve(r,...e);return n&&i[0]===x&&!t.authority&&(i=i.substring(1)),t.with({path:i})},t.dirname=function(t){if(0===t.path.length||t.path===x)return t;let e=w.dirname(t.path);return 1===e.length&&46===e.charCodeAt(0)&&(e=""),t.with({path:e})},t.basename=function(t){return w.basename(t.path)},t.extname=function(t){return w.extname(t.path)}}(P||(P={}))})(),LIB=n})();const{URI,Utils}=LIB;
//# sourceMappingURL=index.mjs.map
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
AceLanguageClient: () => (/* binding */ AceLanguageClient)
});
// EXTERNAL MODULE: ../../node_modules/vscode-languageserver-protocol/lib/browser/main.js
var main = __webpack_require__(5501);
// EXTERNAL MODULE: ./src/utils.ts
var utils = __webpack_require__(7770);
;// CONCATENATED MODULE: ./src/ace/range-singleton.ts
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class AceRange {
static getConstructor(editor) {
if (!AceRange._instance && editor) {
AceRange._instance = editor.getSelectionRange().constructor;
}
return AceRange._instance;
}
}
_define_property(AceRange, "_instance", void 0);
;// CONCATENATED MODULE: ./src/type-converters/common-converters.ts
var common_converters_CommonConverter;
(function(CommonConverter) {
function normalizeRanges(completions) {
return completions && completions.map((el)=>{
if (el["range"]) {
el["range"] = toRange(el["range"]);
}
return el;
});
}
CommonConverter.normalizeRanges = normalizeRanges;
function cleanHtml(html) {
return html.replace(/<a\s/, "<a target='_blank' ");
}
CommonConverter.cleanHtml = cleanHtml;
function toRange(range) {
if (!range || !range.start || !range.end) {
return;
}
let Range = AceRange.getConstructor();
// @ts-ignore
return Range.fromPoints(range.start, range.end);
}
CommonConverter.toRange = toRange;
function convertKind(kind) {
switch(kind){
case "primitiveType":
case "keyword":
return main.CompletionItemKind.Keyword;
case "variable":
case "localVariable":
return main.CompletionItemKind.Variable;
case "memberVariable":
case "memberGetAccessor":
case "memberSetAccessor":
return main.CompletionItemKind.Field;
case "function":
case "memberFunction":
case "constructSignature":
case "callSignature":
case "indexSignature":
return main.CompletionItemKind.Function;
case "enum":
return main.CompletionItemKind.Enum;
case "module":
return main.CompletionItemKind.Module;
case "class":
return main.CompletionItemKind.Class;
case "interface":
return main.CompletionItemKind.Interface;
case "warning":
return main.CompletionItemKind.File;
}
return main.CompletionItemKind.Property;
}
CommonConverter.convertKind = convertKind;
function excludeByErrorMessage(diagnostics, errorMessagesToIgnore, fieldName = "message") {
if (!errorMessagesToIgnore) return diagnostics;
return diagnostics.filter((el)=>!(0,utils/* checkValueAgainstRegexpArray */.Tk)(el[fieldName], errorMessagesToIgnore));
}
CommonConverter.excludeByErrorMessage = excludeByErrorMessage;
})(common_converters_CommonConverter || (common_converters_CommonConverter = {}));
// EXTERNAL MODULE: ./src/message-types.ts
var message_types = __webpack_require__(2032);
// EXTERNAL MODULE: ../../node_modules/vscode-uri/lib/esm/index.mjs
var esm = __webpack_require__(2917);
;// CONCATENATED MODULE: ./src/message-controller.ts
function message_controller_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class MessageController {
getSessionIdByUri(documentUri) {
if (!documentUri) {
return;
}
return this.provider.$urisToSessionsIds[documentUri] || this.provider.$urisToSessionsIds[esm/* URI */.r.parse(documentUri).toString()];
}
init(documentIdentifier, document, mode, options, initCallback) {
this.postMessage(new message_types/* InitMessage */.eN(documentIdentifier, this.callbackId++, document.getValue(), document["version"], mode, options), initCallback);
}
doValidation(documentIdentifier, callback) {
this.postMessage(new message_types/* ValidateMessage */.i9(documentIdentifier, this.callbackId++), callback);
}
doComplete(documentIdentifier, position, callback) {
this.postMessage(new message_types/* CompleteMessage */.zZ(documentIdentifier, this.callbackId++, position), callback);
}
doResolve(documentIdentifier, completion, callback) {
this.postMessage(new message_types/* ResolveCompletionMessage */.PT(documentIdentifier, this.callbackId++, completion), callback);
}
format(documentIdentifier, range, format, callback) {
this.postMessage(new message_types/* FormatMessage */.HV(documentIdentifier, this.callbackId++, range, format), callback);
}
doHover(documentIdentifier, position, callback) {
this.postMessage(new message_types/* HoverMessage */.C0(documentIdentifier, this.callbackId++, position), callback);
}
change(documentIdentifier, deltas, document, callback) {
let message;
if (deltas.length > 50 && deltas.length > document.getLength() >> 1) {
message = new message_types/* ChangeMessage */.uO(documentIdentifier, this.callbackId++, document.getValue(), document["version"]);
} else {
message = new message_types/* DeltasMessage */.Jk(documentIdentifier, this.callbackId++, deltas, document["version"]);
}
this.postMessage(message, callback);
}
changeMode(documentIdentifier, value, version, mode, callback) {
this.postMessage(new message_types/* ChangeModeMessage */.Hl(documentIdentifier, this.callbackId++, value, version, mode), callback);
}
changeOptions(documentIdentifier, options, callback, merge = false) {
this.postMessage(new message_types/* ChangeOptionsMessage */.gf(documentIdentifier, this.callbackId++, options, merge), callback);
}
closeDocument(documentIdentifier, callback) {
this.postMessage(new message_types/* CloseDocumentMessage */.LN(documentIdentifier, this.callbackId++), callback);
}
closeConnection(callback) {
this.postMessage(new message_types/* CloseConnectionMessage */.qf(this.callbackId++), callback);
}
setGlobalOptions(serviceName, options, merge = false) {
// @ts-ignore
this.$worker.postMessage(new message_types/* GlobalOptionsMessage */.dd(serviceName, options, merge));
}
provideSignatureHelp(documentIdentifier, position, callback) {
this.postMessage(new message_types/* SignatureHelpMessage */.Hx(documentIdentifier, this.callbackId++, position), callback);
}
findDocumentHighlights(documentIdentifier, position, callback) {
this.postMessage(new message_types/* DocumentHighlightMessage */.N3(documentIdentifier, this.callbackId++, position), callback);
}
configureFeatures(serviceName, features) {
this.$worker.postMessage(new message_types/* ConfigureFeaturesMessage */.RT(serviceName, features));
}
getSemanticTokens(documentIdentifier, range, callback) {
this.postMessage(new message_types/* GetSemanticTokensMessage */.W_(documentIdentifier, this.callbackId++, range), callback);
}
getCodeActions(documentIdentifier, range, context, callback) {
this.postMessage(new message_types/* GetCodeActionsMessage */.kN(documentIdentifier, this.callbackId++, range, context), callback);
}
executeCommand(serviceName, command, args, callback) {
this.postMessage(new message_types/* ExecuteCommandMessage */.m6(serviceName, this.callbackId++, command, args), callback);
}
setWorkspace(workspaceUri, callback) {
this.$worker.postMessage(new message_types/* SetWorkspaceMessage */.lR(workspaceUri));
}
postMessage(message, callback) {
if (callback) {
this.callbacks[message.callbackId] = callback;
}
this.$worker.postMessage(message);
}
constructor(worker, provider){
message_controller_define_property(this, "$worker", void 0);
message_controller_define_property(this, "callbacks", {});
message_controller_define_property(this, "callbackId", 1);
message_controller_define_property(this, "provider", void 0);
this.$worker = worker;
this.provider = provider;
this.$worker.addEventListener("message", (e)=>{
const message = e.data;
const callbackId = message.callbackId;
if (message.type === message_types/* MessageType */.Go.validate || message.type === message_types/* MessageType */.Go.capabilitiesChange) {
const sessionId = this.getSessionIdByUri(message.documentUri);
if (!sessionId) {
return;
}
if (message.type === message_types/* MessageType */.Go.validate) {
var _this_provider_$sessionLanguageProviders_sessionId;
(_this_provider_$sessionLanguageProviders_sessionId = this.provider.$sessionLanguageProviders[sessionId]) === null || _this_provider_$sessionLanguageProviders_sessionId === void 0 ? void 0 : _this_provider_$sessionLanguageProviders_sessionId.$showAnnotations(message.value);
} else {
var _this_provider_$sessionLanguageProviders_sessionId1;
(_this_provider_$sessionLanguageProviders_sessionId1 = this.provider.$sessionLanguageProviders[sessionId]) === null || _this_provider_$sessionLanguageProviders_sessionId1 === void 0 ? void 0 : _this_provider_$sessionLanguageProviders_sessionId1.setServerCapabilities(message.value);
}
} else if (message.type === message_types/* MessageType */.Go.applyEdit) {
const applied = (result, serviceName)=>{
this.$worker.postMessage(new message_types/* AppliedEditMessage */.X9(result, serviceName, message.callbackId));
};
this.provider.applyEdit(message.value, message.serviceName, applied);
} else {
if (this.callbacks[callbackId]) {
this.callbacks[callbackId](message.value);
delete this.callbacks[callbackId];
}
}
});
}
}
;// CONCATENATED MODULE: ./src/type-converters/lsp/lsp-converters.ts
function fromRange(range) {
return {
start: {
line: range.start.row,
character: range.start.column
},
end: {
line: range.end.row,
character: range.end.column
}
};
}
function rangeFromPositions(start, end) {
return {
start: start,
end: end
};
}
function toRange(range) {
return {
start: {
row: range.start.line,
column: range.start.character
},
end: {
row: range.end.line,
column: range.end.character
}
};
}
function fromPoint(point) {
return {
line: point.row,
character: point.column
};
}
function toPoint(position) {
return {
row: position.line,
column: position.character
};
}
function toAnnotations(diagnostics) {
var _diagnostics;
return (_diagnostics = diagnostics) === null || _diagnostics === void 0 ? void 0 : _diagnostics.map((el)=>{
return {
row: el.range.start.line,
column: el.range.start.character,
text: el.message,
type: el.severity === 1 ? "error" : el.severity === 2 ? "warning" : "info",
code: el.code
};
});
}
function fromAnnotations(annotations) {
var _annotations;
return (_annotations = annotations) === null || _annotations === void 0 ? void 0 : _annotations.map((el)=>{
return {
range: {
start: {
line: el.row,
character: el.column
},
end: {
line: el.row,
character: el.column
}
},
message: el.text,
severity: el.type === "error" ? 1 : el.type === "warning" ? 2 : 3,
code: el["code"]
};
});
}
function toCompletion(item) {
var _item_textEdit, _item_command;
let itemKind = item.kind;
let kind = itemKind ? Object.keys(main.CompletionItemKind)[Object.values(main.CompletionItemKind).indexOf(itemKind)] : undefined;
var _item_textEdit_newText, _ref;
let text = (_ref = (_item_textEdit_newText = (_item_textEdit = item.textEdit) === null || _item_textEdit === void 0 ? void 0 : _item_textEdit.newText) !== null && _item_textEdit_newText !== void 0 ? _item_textEdit_newText : item.insertText) !== null && _ref !== void 0 ? _ref : item.label;
let filterText;
// filtering would happen on ace editor side
//TODO: if filtering and sorting are on server side, we should disable FilteredList in ace completer
if (item.filterText) {
const firstWordMatch = item.filterText.match(/\w+/);
const firstWord = firstWordMatch ? firstWordMatch[0] : null;
if (firstWord) {
const wordRegex = new RegExp(`\\b${firstWord}\\b`, 'i');
if (!wordRegex.test(text)) {
text = `${item.filterText} ${text}`;
filterText = item.filterText;
}
} else {
if (!text.includes(item.filterText)) {
text = `${item.filterText} ${text}`;
filterText = item.filterText;
}
}
}
let command = ((_item_command = item.command) === null || _item_command === void 0 ? void 0 : _item_command.command) == "editor.action.triggerSuggest" ? "startAutocomplete" : undefined;
let range = item.textEdit ? getTextEditRange(item.textEdit, filterText) : undefined;
let completion = {
meta: kind,
caption: item.label,
score: undefined
};
completion["command"] = command;
completion["range"] = range;
completion["item"] = item;
if (item.insertTextFormat == main.InsertTextFormat.Snippet) {
completion["snippet"] = text;
} else {
completion["value"] = text !== null && text !== void 0 ? text : "";
}
completion["documentation"] = item.documentation; //TODO: this is workaround for services with instant completion
completion["position"] = item["position"];
completion["service"] = item["service"]; //TODO: since we have multiple servers, we need to determine which
// server to use for resolving
return completion;
}
function toCompletions(completions) {
if (completions.length > 0) {
let combinedCompletions = completions.map((el)=>{
if (!el.completions) {
return [];
}
let allCompletions;
if (Array.isArray(el.completions)) {
allCompletions = el.completions;
} else {
allCompletions = el.completions.items;
}
return allCompletions.map((item)=>{
item["service"] = el.service;
return item;
});
}).flat();
return combinedCompletions.map((item)=>toCompletion(item));
}
return [];
}
function toResolvedCompletion(completion, item) {
completion["docMarkdown"] = fromMarkupContent(item.documentation);
return completion;
}
function toCompletionItem(completion) {
let command;
if (completion["command"]) {
command = {
title: "triggerSuggest",
command: completion["command"]
};
}
var _completion_caption;
let completionItem = {
label: (_completion_caption = completion.caption) !== null && _completion_caption !== void 0 ? _completion_caption : "",
kind: common_converters_CommonConverter.convertKind(completion.meta),
command: command,
insertTextFormat: completion["snippet"] ? main.InsertTextFormat.Snippet : main.InsertTextFormat.PlainText,
documentation: completion["documentation"]
};
if (completion["range"]) {
var _completion_snippet;
completionItem.textEdit = {
range: fromRange(completion["range"]),
newText: (_completion_snippet = completion["snippet"]) !== null && _completion_snippet !== void 0 ? _completion_snippet : completion["value"]
};
} else {
var _completion_snippet1;
completionItem.insertText = (_completion_snippet1 = completion["snippet"]) !== null && _completion_snippet1 !== void 0 ? _completion_snippet1 : completion["value"];
}
completionItem["fileName"] = completion["fileName"];
completionItem["position"] = completion["position"];
completionItem["item"] = completion["item"];
completionItem["service"] = completion["service"]; //TODO:
return completionItem;
}
function getTextEditRange(textEdit, filterText) {
const filterLength = filterText ? filterText.length : 0;
if ("insert" in textEdit && "replace" in textEdit) {
let mergedRanges = (0,utils/* mergeRanges */.$Z)([
toRange(textEdit.insert),
toRange(textEdit.replace)
]);
return mergedRanges[0];
} else {
textEdit.range.start.character -= filterLength;
return toRange(textEdit.range);
}
}
function toTooltip(hover) {
var _hover_find;
if (!hover) return;
let content = hover.map((el)=>{
if (!el || !el.contents) return;
if (main.MarkupContent.is(el.contents)) {
return fromMarkupContent(el.contents);
} else if (main.MarkedString.is(el.contents)) {
if (typeof el.contents === "string") {
return el.contents;
}
return "```" + el.contents.value + "```";
} else {
let contents = el.contents.map((el)=>{
if (typeof el !== "string") {
return `\`\`\`${el.value}\`\`\``;
} else {
return el;
}
});
return contents.join("\n\n");
}
}).filter(utils/* notEmpty */.z2);
if (content.length === 0) return;
//TODO: it could be merged within all ranges in future
let lspRange = (_hover_find = hover.find((el)=>{
var _el;
return (_el = el) === null || _el === void 0 ? void 0 : _el.range;
})) === null || _hover_find === void 0 ? void 0 : _hover_find.range;
let range;
if (lspRange) range = toRange(lspRange);
return {
content: {
type: "markdown",
text: content.join("\n\n")
},
range: range
};
}
function fromSignatureHelp(signatureHelp) {
if (!signatureHelp) return;
let content = signatureHelp.map((el)=>{
var _el, _el1;
if (!el) return;
let signatureIndex = ((_el = el) === null || _el === void 0 ? void 0 : _el.activeSignature) || 0;
let activeSignature = el.signatures[signatureIndex];
if (!activeSignature) return;
let activeParam = (_el1 = el) === null || _el1 === void 0 ? void 0 : _el1.activeParameter;
let contents = activeSignature.label;
if (activeParam != undefined && activeSignature.parameters && activeSignature.parameters[activeParam]) {
let param = activeSignature.parameters[activeParam].label;
if (typeof param == "string") {
contents = contents.replace(param, `**${param}**`);
}
}
if (activeSignature.documentation) {
if (main.MarkupContent.is(activeSignature.documentation)) {
return contents + "\n\n" + fromMarkupContent(activeSignature.documentation);
} else {
contents += "\n\n" + activeSignature.documentation;
return contents;
}
} else {
return contents;
}
}).filter(utils/* notEmpty */.z2);
if (content.length === 0) return;
return {
content: {
type: "markdown",
text: content.join("\n\n")
}
};
}
function fromMarkupContent(content) {
if (!content) return;
if (typeof content === "string") {
return content;
} else {
return content.value;
}
}
function fromAceDelta(delta, eol) {
const text = delta.lines.length > 1 ? delta.lines.join(eol) : delta.lines[0];
return {
range: delta.action === "insert" ? rangeFromPositions(fromPoint(delta.start), fromPoint(delta.start)) : rangeFromPositions(fromPoint(delta.start), fromPoint(delta.end)),
text: delta.action === "insert" ? text : ""
};
}
function filterDiagnostics(diagnostics, filterErrors) {
return CommonConverter.excludeByErrorMessage(diagnostics, filterErrors.errorMessagesToIgnore).map((el)=>{
if (checkValueAgainstRegexpArray(el.message, filterErrors.errorMessagesToTreatAsWarning)) {
el.severity = DiagnosticSeverity.Warning;
} else if (checkValueAgainstRegexpArray(el.message, filterErrors.errorMessagesToTreatAsInfo)) {
el.severity = DiagnosticSeverity.Information;
}
return el;
});
}
function fromDocumentHighlights(documentHighlights) {
return documentHighlights.map(function(el) {
let className = el.kind == 2 ? "language_highlight_read" : el.kind == 3 ? "language_highlight_write" : "language_highlight_text";
return toMarkerGroupItem(common_converters_CommonConverter.toRange(toRange(el.range)), className);
});
}
function toMarkerGroupItem(range, className, tooltipText) {
let markerGroupItem = {
range: range,
className: className
};
if (tooltipText) {
markerGroupItem["tooltipText"] = tooltipText;
}
return markerGroupItem;
}
// EXTERNAL MODULE: ../../node_modules/showdown/dist/showdown.js
var showdown = __webpack_require__(8583);
var showdown_default = /*#__PURE__*/__webpack_require__.n(showdown);
;// CONCATENATED MODULE: ./src/cdn-worker.ts
function createWorkerBlob(cdnUrl, services) {
var _service_cdnUrl;
return new Blob([
`
importScripts("${cdnUrl}/service-manager.js");
const manager = new ServiceManager(self);
${services.map((service)=>`
manager.registerService("${service.name}", {
module: () => {
importScripts("${(_service_cdnUrl = service.cdnUrl) !== null && _service_cdnUrl !== void 0 ? _service_cdnUrl : cdnUrl}/${service.script}");
return {${service.className}};
},
className: "${service.className}",
modes: "${service.modes}"
});
`).join('\n')}
`
], {
type: "application/javascript"
});
}
function createWorker(source, includeLinters) {
if (includeLinters === undefined) {
includeLinters = true;
}
if (typeof Worker == "undefined") return {
postMessage: function() {},
terminate: function() {}
};
let blob;
if (typeof source === "string") {
const allServices = getServices(includeLinters);
blob = createWorkerBlob(source, allServices);
} else {
const allServices = [
...source.services,
...getServices(includeLinters)
];
const cdnUrl = source.serviceManagerCdn;
blob = createWorkerBlob(cdnUrl, allServices);
}
var URL = window.URL || window.webkitURL;
var blobURL = URL.createObjectURL(blob);
// calling URL.revokeObjectURL before worker is terminated breaks it on IE Edge
return new Worker(blobURL);
}
function getServices(includeLinters) {
const allServices = [
{
name: "json",
script: "json-service.js",
className: "JsonService",
modes: "json|json5"
},
{
name: "html",
script: "html-service.js",
className: "HtmlService",
modes: "html"
},
{
name: "css",
script: "css-service.js",
className: "CssService",
modes: "css"
},
{
name: "less",
script: "css-service.js",
className: "CssService",
modes: "less"
},
{
name: "scss",
script: "css-service.js",
className: "CssService",
modes: "scss"
},
{
name: "typescript",
script: "typescript-service.js",
className: "TypescriptService",
modes: "typescript|tsx|javascript|jsx"
},
{
name: "lua",
script: "lua-service.js",
className: "LuaService",
modes: "lua"
},
{
name: "yaml",
script: "yaml-service.js",
className: "YamlService",
modes: "yaml"
},
{
name: "xml",
script: "xml-service.js",
className: "XmlService",
modes: "xml"
},
{
name: "php",
script: "php-service.js",
className: "PhpService",
modes: "php"
},
{
name: "eslint",
script: "javascript-service.js",
className: "JavascriptService",
modes: "javascript"
},
{
name: "python",
script: "python-service.js",
className: "PythonService",
modes: "python"
}
];
if (includeLinters === true || includeLinters === undefined) {
return allServices;
} else if (includeLinters === false) {
return [];
}
if (includeLinters.javascript) {
includeLinters.eslint = includeLinters.javascript;
delete includeLinters.javascript;
}
return allServices.filter((service)=>{
return includeLinters[service.name];
});
}
;// CONCATENATED MODULE: ./src/ace/tooltip.ts
function tooltip_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var CLASSNAME = "ace_tooltip";
//taken from ace-code with small changes
class Tooltip {
$init() {
this.$element = document.createElement("div");
this.$element.className = CLASSNAME;
this.$element.style.display = "none";
this.$parentNode.appendChild(this.$element);
return this.$element;
}
/**
* @returns {HTMLElement}
**/ getElement() {
return this.$element || this.$init();
}
/**
* @param {String} text
**/ setText(text) {
this.getElement().textContent = text;
}
/**
* @param {String} html
**/ setHtml(html) {
this.getElement().innerHTML = html;
}
/**
* @param {Number} x
* @param {Number} y
**/ setPosition(x, y) {
this.getElement().style.left = x + "px";
this.getElement().style.top = y + "px";
}
/**
* @param {String} className
**/ setClassName(className) {
this.getElement().className += " " + className;
}
setTheme(theme) {
this.getElement().className = CLASSNAME + " " + (theme.isDark ? "ace_dark " : "") + (theme.cssClass || "");
}
/**
* @param {String} text
* @param {Number} x
* @param {Number} y
**/ show(text, x, y) {
if (text != null) this.setText(text);
if (x != null && y != null) this.setPosition(x, y);
if (!this.isOpen) {
this.getElement().style.display = "block";
this.isOpen = true;
}
}
hide() {
if (this.isOpen) {
this.getElement().style.display = "none";
this.getElement().className = CLASSNAME;
this.isOpen = false;
}
}
/**
* @returns {Number}
**/ getHeight() {
return this.getElement().offsetHeight;
}
/**
* @returns {Number}
**/ getWidth() {
return this.getElement().offsetWidth;
}
destroy() {
this.isOpen = false;
if (this.$element && this.$element.parentNode) {
this.$element.parentNode.removeChild(this.$element);
}
}
/**
* @param {Element} parentNode
**/ constructor(parentNode){
tooltip_define_property(this, "$element", void 0);
tooltip_define_property(this, "isOpen", void 0);
tooltip_define_property(this, "$parentNode", void 0);
this.isOpen = false;
this.$element = null;
this.$parentNode = parentNode;
}
}
;// CONCATENATED MODULE: ./src/components/base-tooltip.ts
function base_tooltip_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class BaseTooltip extends Tooltip {
$show() {
if (!this.$activeEditor) return;
let renderer = this.$activeEditor.renderer;
let position = renderer.textToScreenCoordinates(this.row, this.column);
let cursorPos = this.$activeEditor.getCursorPosition();
this.show(null, position.pageX, position.pageY);
let labelHeight = this.getElement().getBoundingClientRect().height;
let rect = renderer.scroller.getBoundingClientRect();
let isTopdown = true;
if (this.row > cursorPos.row) // don't obscure cursor
isTopdown = true;
else if (this.row < cursorPos.row) // don't obscure cursor
isTopdown = false;
if (position.pageY - labelHeight + renderer.lineHeight < rect.top) // not enough space above us
isTopdown = true;
else if (position.pageY + labelHeight > rect.bottom) isTopdown = false;
if (!isTopdown) position.pageY -= labelHeight;
else position.pageY += renderer.lineHeight;
this.getElement().style.maxWidth = rect.width - (position.pageX - rect.left) + "px";
this.show(null, position.pageX, position.pageY);
}
getElement() {
return super.getElement();
}
hide() {
super.hide();
}
show(param, pageX, pageY) {
super.show(param, pageX, pageY);
this.$registerEditorEvents();
}
setHtml(descriptionText) {
super.setHtml(descriptionText);
}
destroy() {
this.$hide();
this.getElement().removeEventListener("mouseout", this.onMouseOut);
}
$registerEditorEvents() {
this.$activeEditor.on("change", this.$hide);
this.$activeEditor.on("mousewheel", this.$hide);
//@ts-ignore
this.$activeEditor.on("mousedown", this.$hide);
}
$removeEditorEvents() {
this.$activeEditor.off("change", this.$hide);
this.$activeEditor.off("mousewheel", this.$hide);
//@ts-ignore
this.$activeEditor.off("mousedown", this.$hide);
}
$inactivateEditor() {
var _this_$activeEditor;
(_this_$activeEditor = this.$activeEditor) === null || _this_$activeEditor === void 0 ? void 0 : _this_$activeEditor.container.removeEventListener("mouseout", this.onMouseOut);
this.$activeEditor = undefined;
}
$activateEditor(editor) {
if (this.$activeEditor == editor) return;
this.$inactivateEditor();
this.$activeEditor = editor;
this.$activeEditor.container.addEventListener("mouseout", this.onMouseOut);
}
constructor(provider){
super(document.body);
base_tooltip_define_property(this, "provider", void 0);
base_tooltip_define_property(this, "$activeEditor", void 0);
base_tooltip_define_property(this, "descriptionText", void 0);
base_tooltip_define_property(this, "x", void 0);
base_tooltip_define_property(this, "y", void 0);
base_tooltip_define_property(this, "$mouseMoveTimer", void 0);
base_tooltip_define_property(this, "$showTimer", void 0);
base_tooltip_define_property(this, "row", void 0);
base_tooltip_define_property(this, "column", void 0);
base_tooltip_define_property(this, "$hide", ()=>{
clearTimeout(this.$mouseMoveTimer);
clearTimeout(this.$showTimer);
if (this.isOpen) {
this.$removeEditorEvents();
this.hide();
}
this.$inactivateEditor();
});
base_tooltip_define_property(this, "onMouseOut", (e)=>{
clearTimeout(this.$mouseMoveTimer);
clearTimeout(this.$showTimer);
if (!e.relatedTarget || e.relatedTarget == this.getElement()) return;
//@ts-ignore
if (e && e.currentTarget.contains(e.relatedTarget)) return;
//@ts-ignore
if (!e.relatedTarget.classList.contains("ace_content")) this.$hide();
});
this.provider = provider;
//this is for ace-code version < 1.16.0
try {
Tooltip.call(this, document.body);
} catch (e) {}
this.getElement().style.pointerEvents = "auto";
this.getElement().style.whiteSpace = "pre-wrap";
this.getElement().addEventListener("mouseout", this.onMouseOut);
}
}
;// CONCATENATED MODULE: ./src/components/signature-tooltip.ts
function signature_tooltip_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class SignatureTooltip extends BaseTooltip {
registerEditor(editor) {
// @ts-ignore
editor.on("changeSelection", ()=>this.onChangeSelection(editor));
}
update(editor) {
clearTimeout(this.$mouseMoveTimer);
clearTimeout(this.$showTimer);
if (this.isOpen) {
this.provideSignatureHelp();
} else {
this.$mouseMoveTimer = setTimeout(()=>{
this.$activateEditor(editor);
this.provideSignatureHelp();
this.$mouseMoveTimer = undefined;
}, 500);
}
}
constructor(...args){
super(...args);
signature_tooltip_define_property(this, "provideSignatureHelp", ()=>{
if (!this.provider.options.functionality.signatureHelp) return;
let cursor = this.$activeEditor.getCursorPosition();
let session = this.$activeEditor.session;
let docPos = session.screenToDocumentPosition(cursor.row, cursor.column);
this.provider.provideSignatureHelp(session, docPos, (tooltip)=>{
var _tooltip_range, _tooltip_range1, _token;
let descriptionText = tooltip ? this.provider.getTooltipText(tooltip) : null;
if (!tooltip || !descriptionText) {
this.hide();
return;
}
let token = session.getTokenAt(docPos.row, docPos.column);
var _tooltip_range_start_row;
let row = (_tooltip_range_start_row = (_tooltip_range = tooltip.range) === null || _tooltip_range === void 0 ? void 0 : _tooltip_range.start.row) !== null && _tooltip_range_start_row !== void 0 ? _tooltip_range_start_row : docPos.row;
var _tooltip_range_start_column, _ref;
let column = (_ref = (_tooltip_range_start_column = (_tooltip_range1 = tooltip.range) === null || _tooltip_range1 === void 0 ? void 0 : _tooltip_range1.start.column) !== null && _tooltip_range_start_column !== void 0 ? _tooltip_range_start_column : (_token = token) === null || _token === void 0 ? void 0 : _token.start) !== null && _ref !== void 0 ? _ref : 0;
if (this.descriptionText != descriptionText) {
this.hide();
this.setHtml(descriptionText);
this.descriptionText = descriptionText;
} else if (this.row == row && this.column == column && this.isOpen) {
return;
}
this.row = row;
this.column = column;
if (this.$mouseMoveTimer) {
this.$show();
} else {
this.$showTimer = setTimeout(()=>{
this.$show();
this.$showTimer = undefined;
}, 500);
}
});
});
signature_tooltip_define_property(this, "onChangeSelection", (editor)=>{
this.update(editor);
});
}
}
;// CONCATENATED MODULE: ./src/ace/marker_group.ts
function marker_group_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/*
Potential improvements:
- use binary search when looking for hover match
*/ //taken from ace-code with small changes
class MarkerGroup {
/**
* Finds the first marker containing pos
* @param {Position} pos
* @returns Ace.MarkerGroupItem
*/ getMarkerAtPosition(pos) {
return this.markers.find(function(marker) {
return marker.range.contains(pos.row, pos.column);
});
}
/**
* Finds all markers that contain the given position.
* @param {Position} pos - The position to search for.
* @returns {Ace.MarkerGroupItem[]} - An array of all markers that contain the given position.
*/ getMarkersAtPosition(pos) {
return this.markers.filter(function(marker) {
return marker.range.contains(pos.row, pos.column);
});
}
/**
* Comparator for Array.sort function, which sorts marker definitions by their positions
*
* @param {Ace.MarkerGroupItem} a first marker.
* @param {Ace.MarkerGroupItem} b second marker.
* @returns {number} negative number if a should be before b, positive number if b should be before a, 0 otherwise.
*/ markersComparator(a, b) {
return a.range.start.row - b.range.start.row;
}
/**
* Sets marker definitions to be rendered. Limits the number of markers at MAX_MARKERS.
* @param {Ace.MarkerGroupItem[]} markers an array of marker definitions.
*/ setMarkers(markers) {
this.markers = markers.sort(this.markersComparator).slice(0, this.MAX_MARKERS);
this.session._signal("changeBackMarker");
}
update(html, markerLayer, session, config) {
if (!this.markers || !this.markers.length) return;
var visibleRangeStartRow = config.firstRow, visibleRangeEndRow = config.lastRow;
var foldLine;
var markersOnOneLine = 0;
var lastRow = 0;
for(var i = 0; i < this.markers.length; i++){
var marker = this.markers[i];
if (marker.range.end.row < visibleRangeStartRow) continue;
if (marker.range.start.row > visibleRangeEndRow) continue;
if (marker.range.start.row === lastRow) {
markersOnOneLine++;
} else {
lastRow = marker.range.start.row;
markersOnOneLine = 0;
}
// do not render too many markers on one line
// because we do not have virtual scroll for horizontal direction
if (markersOnOneLine > 200) {
continue;
}
var markerVisibleRange = marker.range.clipRows(visibleRangeStartRow, visibleRangeEndRow);
if (markerVisibleRange.start.row === markerVisibleRange.end.row && markerVisibleRange.start.column === markerVisibleRange.end.column) {
continue; // visible range is empty
}
var screenRange = markerVisibleRange.toScreenRange(session);
if (screenRange.isEmpty()) {
// we are inside a fold
foldLine = session.getNextFoldLine(markerVisibleRange.end.row, foldLine);
if (foldLine && foldLine.end.row > markerVisibleRange.end.row) {
visibleRangeStartRow = foldLine.end.row;
}
continue;
}
if (screenRange.isMultiLine()) {
markerLayer.drawTextMarker(html, screenRange, marker.className, config);
} else {
markerLayer.drawSingleLineMarker(html, screenRange, marker.className, config);
}
}
}
constructor(session){
marker_group_define_property(this, "markers", void 0);
marker_group_define_property(this, "session", void 0);
// this caps total amount of markers at 10K
marker_group_define_property(this, "MAX_MARKERS", 10000);
this.markers = [];
this.session = session;
session.addDynamicMarker(this);
}
}
;// CONCATENATED MODULE: ./src/ace/popupManager.ts
//taken from ace-code with small changes
function popupManager_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class PopupManager {
addPopup(popup) {
this.popups.push(popup);
this.updatePopups();
}
removePopup(popup) {
const index = this.popups.indexOf(popup);
if (index !== -1) {
this.popups.splice(index, 1);
this.updatePopups();
}
}
updatePopups() {
this.popups.sort((a, b)=>b.priority - a.priority);
let visiblepopups = [];
for (let popup of this.popups){
let shouldDisplay = true;
for (let visiblePopup of visiblepopups){
if (this.doPopupsOverlap(visiblePopup, popup)) {
shouldDisplay = false;
break;
}
}
if (shouldDisplay) {
visiblepopups.push(popup);
} else {
popup.hide();
}
}
}
doPopupsOverlap(popupA, popupB) {
const rectA = popupA.getElement().getBoundingClientRect();
const rectB = popupB.getElement().getBoundingClientRect();
return rectA.left < rectB.right && rectA.right > rectB.left && rectA.top < rectB.bottom && rectA.bottom > rectB.top;
}
constructor(){
popupManager_define_property(this, "popups", void 0);
this.popups = [];
}
}
;// CONCATENATED MODULE: ./src/ace/hover-tooltip.ts
function hover_tooltip_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
let popupManager = new PopupManager();
//taken from ace-code with small changes
class HoverTooltip extends Tooltip {
addToEditor(editor) {
editor.on("mousemove", this.onMouseMove);
editor.on("mousedown", this.hide);
editor.renderer.getMouseEventTarget().addEventListener("mouseout", this.onMouseOut, true);
}
removeFromEditor(editor) {
editor.off("mousemove", this.onMouseMove);
editor.off("mousedown", this.hide);
editor.renderer.getMouseEventTarget().removeEventListener("mouseout", this.onMouseOut, true);
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
onMouseMove(e, editor) {
this.lastEvent = e;
this.lastT = Date.now();
var isMousePressed = editor.$mouseHandler.isMousePressed;
if (this.isOpen) {
var pos = this.lastEvent && this.lastEvent.getDocumentPosition();
if (!this.range || !this.range.contains(pos.row, pos.column) || isMousePressed || this.isOutsideOfText(this.lastEvent)) {
this.hide();
}
}
if (this.timeout || isMousePressed) return;
this.lastEvent = e;
this.timeout = setTimeout(this.waitForHover, this.idleTime);
}
waitForHover() {
if (this.timeout) clearTimeout(this.timeout);
var dt = Date.now() - this.lastT;
if (this.idleTime - dt > 10) {
this.timeout = setTimeout(this.waitForHover, this.idleTime - dt);
return;
}
this.timeout = null;
if (this.lastEvent && !this.isOutsideOfText(this.lastEvent)) {
this.$gatherData(this.lastEvent, this.lastEvent.editor);
}
}
isOutsideOfText(e) {
var editor = e.editor;
var docPos = e.getDocumentPosition();
var line = editor.session.getLine(docPos.row);
if (docPos.column == line.length) {
var screenPos = editor.renderer.pixelToScreenCoordinates(e.clientX, e.clientY);
var clippedPos = editor.session.documentToScreenPosition(docPos.row, docPos.column);
if (clippedPos.column != screenPos.column || clippedPos.row != screenPos.row) {
return true;
}
}
return false;
}
setDataProvider(value) {
this.$gatherData = value;
}
showForRange(editor, range, domNode, startingEvent) {
if (startingEvent && startingEvent != this.lastEvent) return;
if (this.isOpen && document.activeElement == this.getElement()) return;
var renderer = editor.renderer;
if (!this.isOpen) {
popupManager.addPopup(this);
this.$registerCloseEvents();
this.setTheme(renderer.theme);
}
this.isOpen = true;
this.addMarker(range, editor.session);
const Range = editor.getSelectionRange().constructor;
this.range = Range.fromPoints(range.start, range.end);
var element = this.getElement();
element.innerHTML = "";
element.appendChild(domNode);
element.style.display = "block";
var position = renderer.textToScreenCoordinates(range.start.row, range.start.column);
var cursorPos = editor.getCursorPosition();
var labelHeight = element.clientHeight;
var rect = renderer.scroller.getBoundingClientRect();
var isTopdown = true;
if (this.row > cursorPos.row) {
// don't obscure cursor
isTopdown = true;
} else if (this.row < cursorPos.row) {
// don't obscure cursor
isTopdown = false;
}
if (position.pageY - labelHeight + renderer.lineHeight < rect.top) {
// not enough space above us
isTopdown = true;
} else if (position.pageY + labelHeight > rect.bottom) {
isTopdown = false;
}
if (!isTopdown) {
position.pageY -= labelHeight;
} else {
position.pageY += renderer.lineHeight;
}
element.style.maxWidth = rect.width - (position.pageX - rect.left) + "px";
this.setPosition(position.pageX, position.pageY);
}
addMarker(range, session) {
if (this.marker) {
this.$markerSession.removeMarker(this.marker);
}
this.$markerSession = session;
this.marker = session && session.addMarker(range, "ace_highlight-marker", "text");
}
hide(e) {
if (!e && document.activeElement == this.getElement()) return;
if (e && e.target && (e.type != "keydown" || e.ctrlKey || e.metaKey) && this.$element && this.$element.contains(e.target)) return;
this.lastEvent = null;
if (this.timeout) clearTimeout(this.timeout);
this.timeout = null;
this.addMarker(null);
if (this.isOpen) {
this.$removeCloseEvents();
this.getElement().style.display = "none";
this.isOpen = false;
popupManager.removePopup(this);
}
}
$registerCloseEvents() {
window.addEventListener("keydown", this.hide, true);
window.addEventListener("mousewheel", this.hide, true);
window.addEventListener("mousedown", this.hide, true);
}
$removeCloseEvents() {
window.removeEventListener("keydown", this.hide, true);
window.removeEventListener("mousewheel", this.hide, true);
window.removeEventListener("mousedown", this.hide, true);
}
onMouseOut(e) {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.lastEvent = null;
if (!this.isOpen) return;
if (!e.relatedTarget || e.relatedTarget == this.getElement()) return;
if (e && e.currentTarget.contains(e.relatedTarget)) return;
if (!e.relatedTarget.classList.contains("ace_content")) this.hide();
}
constructor(parentNode = document.body){
super(parentNode);
hover_tooltip_define_property(this, "$gatherData", void 0);
hover_tooltip_define_property(this, "timeout", void 0);
hover_tooltip_define_property(this, "idleTime", void 0);
hover_tooltip_define_property(this, "lastT", void 0);
hover_tooltip_define_property(this, "lastEvent", void 0);
hover_tooltip_define_property(this, "range", void 0);
hover_tooltip_define_property(this, "row", void 0);
hover_tooltip_define_property(this, "marker", void 0);
hover_tooltip_define_property(this, "$markerSession", void 0);
this.timeout = undefined;
this.lastT = 0;
this.idleTime = 350;
this.lastEvent = undefined;
this.onMouseOut = this.onMouseOut.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.waitForHover = this.waitForHover.bind(this);
this.hide = this.hide.bind(this);
var el = this.getElement();
el.style.whiteSpace = "pre-wrap";
el.style.pointerEvents = "auto";
el.addEventListener("mouseout", this.onMouseOut);
el.tabIndex = -1;
el.addEventListener("blur", (function() {
if (!el.contains(document.activeElement)) this.hide();
}).bind(this));
}
}
;// CONCATENATED MODULE: ./src/type-converters/lsp/semantic-tokens.ts
function semantic_tokens_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function decodeModifiers(modifierFlag, tokenModifiersLegend) {
const modifiers = [];
for(let i = 0; i < tokenModifiersLegend.length; i++){
if (modifierFlag & 1 << i) {
modifiers.push(tokenModifiersLegend[i]);
}
}
return modifiers;
}
function parseSemanticTokens(tokens, tokenTypes, tokenModifiersLegend) {
if (tokens.length % 5 !== 0) {
return;
}
const decodedTokens = [];
let line = 0;
let startColumn = 0;
for(let i = 0; i < tokens.length; i += 5){
line += tokens[i];
if (tokens[i] === 0) {
startColumn += tokens[i + 1];
} else {
startColumn = tokens[i + 1];
}
const length = tokens[i + 2];
const tokenTypeIndex = tokens[i + 3];
const tokenModifierFlag = tokens[i + 4];
const tokenType = tokenTypes[tokenTypeIndex];
const tokenModifiers = decodeModifiers(tokenModifierFlag, tokenModifiersLegend);
decodedTokens.push({
row: line,
startColumn: startColumn,
length,
type: toAceTokenType(tokenType, tokenModifiers)
});
}
return new DecodedSemanticTokens(decodedTokens);
}
function toAceTokenType(tokenType, tokenModifiers) {
let modifiers = "";
let type = tokenType;
if (tokenModifiers.length > 0) {
modifiers = "." + tokenModifiers.join(".");
}
switch(tokenType){
case "class":
type = "entity.name.type.class";
break;
case "struct":
type = "storage.type.struct";
break;
case "enum":
type = "entity.name.type.enum";
break;
case "interface":
type = "entity.name.type.interface";
break;
case "namespace":
type = "entity.name.namespace";
break;
case "typeParameter":
break;
case "type":
type = "entity.name.type";
break;
case "parameter":
type = "variable.parameter";
break;
case "variable":
type = "entity.name.variable";
break;
case "enumMember":
type = "variable.other.enummember";
break;
case "property":
type = "variable.other.property";
break;
case "function":
type = "entity.name.function";
break;
case "method":
type = "entity.name.function.member";
break;
case "event":
type = "variable.other.event";
break;
}
return type + modifiers;
}
function mergeTokens(aceTokens, decodedTokens) {
let mergedTokens = [];
let currentCharIndex = 0; // Keeps track of the character index across Ace tokens
let aceTokenIndex = 0; // Index within the aceTokens array
decodedTokens.forEach((semanticToken)=>{
let semanticStart = semanticToken.startColumn;
let semanticEnd = semanticStart + semanticToken.length;
// Process leading Ace tokens that don't overlap with the semantic token
while(aceTokenIndex < aceTokens.length && currentCharIndex + aceTokens[aceTokenIndex].value.length <= semanticStart){
mergedTokens.push(aceTokens[aceTokenIndex]);
currentCharIndex += aceTokens[aceTokenIndex].value.length;
aceTokenIndex++;
}
// Process overlapping Ace tokens
while(aceTokenIndex < aceTokens.length && currentCharIndex < semanticEnd){
let aceToken = aceTokens[aceTokenIndex];
let aceTokenEnd = currentCharIndex + aceToken.value.length;
let overlapStart = Math.max(currentCharIndex, semanticStart);
let overlapEnd = Math.min(aceTokenEnd, semanticEnd);
if (currentCharIndex < semanticStart) {
// Part of Ace token is before semantic token; add this part to mergedTokens
let beforeSemantic = {
...aceToken,
value: aceToken.value.substring(0, semanticStart - currentCharIndex)
};
mergedTokens.push(beforeSemantic);
}
// Middle part (overlapped by semantic token)
let middle = {
type: semanticToken.type,
value: aceToken.value.substring(overlapStart - currentCharIndex, overlapEnd - currentCharIndex)
};
mergedTokens.push(middle);
if (aceTokenEnd > semanticEnd) {
// If Ace token extends beyond the semantic token, prepare the remaining part for future processing
let afterSemantic = {
...aceToken,
value: aceToken.value.substring(semanticEnd - currentCharIndex)
};
// Add the afterSemantic as a new token to process in subsequent iterations
currentCharIndex = semanticEnd; // Update currentCharIndex to reflect the start of afterSemantic
aceTokens.splice(aceTokenIndex, 1, afterSemantic); // Replace the current token with afterSemantic for correct processing in the next iteration
break; // Move to the next semantic token without incrementing aceTokenIndex
}
// If the entire Ace token is covered by the semantic token, proceed to the next Ace token
currentCharIndex = aceTokenEnd;
aceTokenIndex++;
}
});
// Add remaining Ace tokens that were not overlapped by any semantic tokens
while(aceTokenIndex < aceTokens.length){
mergedTokens.push(aceTokens[aceTokenIndex]);
aceTokenIndex++;
}
return mergedTokens;
}
class DecodedSemanticTokens {
getByRow(row) {
return this.tokens.filter((token)=>token.row === row);
}
sortTokens(tokens) {
return tokens.sort((a, b)=>{
if (a.row === b.row) {
return a.startColumn - b.startColumn;
}
return a.row - b.row;
});
}
constructor(tokens){
semantic_tokens_define_property(this, "tokens", void 0);
this.tokens = this.sortTokens(tokens);
}
}
//vscode-languageserver
class SemanticTokensBuilder {
initialize() {
this._id = Date.now();
this._prevLine = 0;
this._prevChar = 0;
this._data = [];
this._dataLen = 0;
}
push(line, char, length, tokenType, tokenModifiers) {
let pushLine = line;
let pushChar = char;
if (this._dataLen > 0) {
pushLine -= this._prevLine;
if (pushLine === 0) {
pushChar -= this._prevChar;
}
}
this._data[this._dataLen++] = pushLine;
this._data[this._dataLen++] = pushChar;
this._data[this._dataLen++] = length;
this._data[this._dataLen++] = tokenType;
this._data[this._dataLen++] = tokenModifiers;
this._prevLine = line;
this._prevChar = char;
}
get id() {
return this._id.toString();
}
previousResult(id) {
if (this.id === id) {
this._prevData = this._data;
}
this.initialize();
}
build() {
this._prevData = undefined;
return {
resultId: this.id,
data: this._data
};
}
canBuildEdits() {
return this._prevData !== undefined;
}
constructor(){
semantic_tokens_define_property(this, "_id", void 0);
semantic_tokens_define_property(this, "_prevLine", void 0);
semantic_tokens_define_property(this, "_prevChar", void 0);
semantic_tokens_define_property(this, "_data", void 0);
semantic_tokens_define_property(this, "_dataLen", void 0);
semantic_tokens_define_property(this, "_prevData", void 0);
this._prevData = undefined;
this.initialize();
}
}
;// CONCATENATED MODULE: ./src/ace/renderer-singleton.ts
function renderer_singleton_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class AceVirtualRenderer {
static getConstructor(editor) {
if (!AceVirtualRenderer._instance && editor) {
AceVirtualRenderer._instance = editor.renderer.constructor;
}
return AceVirtualRenderer._instance;
}
}
renderer_singleton_define_property(AceVirtualRenderer, "_instance", void 0);
;// CONCATENATED MODULE: ./src/ace/editor-singleton.ts
function editor_singleton_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class AceEditor {
static getConstructor(editor) {
if (!AceEditor._instance && editor) {
AceEditor._instance = editor.constructor;
}
return AceEditor._instance;
}
}
editor_singleton_define_property(AceEditor, "_instance", void 0);
;// CONCATENATED MODULE: ./src/ace/acePopup.ts
var getAriaId = function(index) {
return `suggest-aria-id:${index}`;
};
var _navigator = typeof navigator == "object" ? navigator : {
userAgent: ""
};
var ua = _navigator.userAgent || "";
var isSafari = parseFloat(ua.split(" Safari/")[1]) || undefined;
// Safari requires different ARIA A11Y attributes compared to other browsers
var popupAriaRole = isSafari ? "menu" : "listbox";
var optionAriaRole = isSafari ? "menuitem" : "option";
var ariaActiveState = isSafari ? "aria-current" : "aria-selected";
/**
*
* @param {HTMLElement} [el]
* @return {Editor}
*/ var $singleLineEditor = function(el) {
var Renderer = AceVirtualRenderer.getConstructor();
var Editor = AceEditor.getConstructor();
var renderer = new Renderer(el);
renderer.$maxLines = 4;
var editor = new Editor(renderer);
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(false);
editor.renderer.setHighlightGutterLine(false);
editor.$mouseHandler.$focusTimeout = 0;
editor.$highlightTagPending = true;
return editor;
};
/**
* This object is used in some places where needed to show popups - like prompt; autocomplete etc.
*/ class AcePopup {
/**
* Creates and renders single line editor in popup window. If `parentNode` param is isset, then attaching it to this element.
* @param {Element} [parentNode]
*/ constructor(parentNode){
var el = document.createElement("div");
var popup = $singleLineEditor(el);
var Range = AceRange.getConstructor();
if (parentNode) {
parentNode.appendChild(el);
}
el.style.display = "none";
popup.renderer.content.style.cursor = "default";
popup.renderer.setStyle("ace_autocomplete");
// Set aria attributes for the popup
popup.renderer["$textLayer"].element.setAttribute("role", popupAriaRole);
// popup.renderer.$textLayer.element.setAttribute("aria-roledescription", nls("autocomplete.popup.aria-roledescription", "Autocomplete suggestions"));
// popup.renderer.$textLayer.element.setAttribute("aria-label", nls("autocomplete.popup.aria-label", "Autocomplete suggestions"));
popup.renderer["textarea"].setAttribute("aria-hidden", "true");
popup.setOption("displayIndentGuides", false);
popup.setOption("dragDelay", 150);
var noop = function() {};
popup.focus = noop;
popup.$isFocused = true;
popup.renderer["$cursorLayer"].restartTimer = noop;
popup.renderer["$cursorLayer"].element.style.opacity = "0";
popup.renderer["$maxLines"] = 8;
popup.renderer["$keepTextAreaAtCursor"] = false;
popup.setHighlightActiveLine(false);
// set default highlight color
// @ts-ignore
popup.session.highlight("");
popup.session["$searchHighlight"].clazz = "ace_highlight-marker";
// @ts-ignore
popup.on("mousedown", function(e) {
var pos = e.getDocumentPosition();
// @ts-ignore
popup.selection.moveToPosition(pos);
selectionMarker.start.row = selectionMarker.end.row = pos.row;
e.stop();
});
var lastMouseEvent;
var hoverMarker = new Range(-1, 0, -1, Infinity);
var selectionMarker = new Range(-1, 0, -1, Infinity);
selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
popup.setSelectOnHover = function(val) {
if (!val) {
hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
} else if (hoverMarker.id) {
popup.session.removeMarker(hoverMarker.id);
hoverMarker.id = null;
}
};
popup.setSelectOnHover(false);
popup.on("mousemove", function(e) {
if (!lastMouseEvent) {
lastMouseEvent = e;
return;
}
if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
return;
}
lastMouseEvent = e;
lastMouseEvent.scrollTop = popup.renderer.scrollTop;
popup.isMouseOver = true;
var row = lastMouseEvent.getDocumentPosition().row;
if (hoverMarker.start.row != row) {
if (!hoverMarker.id) popup.setRow(row);
setHoverMarker(row);
}
});
popup.renderer.on("beforeRender", function() {
if (lastMouseEvent && hoverMarker.start.row != -1) {
lastMouseEvent.$pos = null;
var row = lastMouseEvent.getDocumentPosition().row;
if (!hoverMarker.id) popup.setRow(row);
setHoverMarker(row, true);
}
});
popup.renderer.on("afterRender", function() {
var row = popup.getRow();
var t = popup.renderer["$textLayer"];
var selected = /** @type {HTMLElement|null} */ t.element.childNodes[row - t.config.firstRow];
var el = document.activeElement; // Active element is textarea of main editor
if (selected !== popup.selectedNode && popup.selectedNode) {
var _el;
popup.renderer["$textLayer"].dom.removeCssClass(popup.selectedNode, "ace_selected");
(_el = el) === null || _el === void 0 ? void 0 : _el.removeAttribute("aria-activedescendant");
popup.selectedNode.removeAttribute(ariaActiveState);
popup.selectedNode.removeAttribute("id");
}
popup.selectedNode = selected;
if (selected) {
var _el1;
popup.renderer["$textLayer"].dom.addCssClass(selected, "ace_selected");
var ariaId = getAriaId(row);
selected.id = ariaId;
t.element.setAttribute("aria-activedescendant", ariaId);
(_el1 = el) === null || _el1 === void 0 ? void 0 : _el1.setAttribute("aria-activedescendant", ariaId);
selected.setAttribute("role", optionAriaRole);
// selected.setAttribute("aria-roledescription", nls("autocomplete.popup.item.aria-roledescription", "item"));
selected.setAttribute("aria-label", popup.getData(row).caption || popup.getData(row).value);
selected.setAttribute("aria-setsize", popup.data.length);
selected.setAttribute("aria-posinset", row + 1);
selected.setAttribute("aria-describedby", "doc-tooltip");
selected.setAttribute(ariaActiveState, "true");
}
});
var hideHoverMarker = function() {
setHoverMarker(-1);
};
var setHoverMarker = function(row, suppressRedraw) {
if (row !== hoverMarker.start.row) {
hoverMarker.start.row = hoverMarker.end.row = row;
if (!suppressRedraw) {
// @ts-ignore
popup.session._emit("changeBackMarker");
}
popup._emit("changeHoverMarker");
}
};
popup.getHoveredRow = function() {
return hoverMarker.start.row;
};
popup.container.addEventListener("mouseout", function() {
popup.isMouseOver = false;
hideHoverMarker();
});
// @ts-ignore
popup.on("hide", hideHoverMarker);
// @ts-ignore
popup.on("changeSelection", hideHoverMarker);
popup.session.doc.getLength = function() {
return popup.data.length;
};
popup.session.doc.getLine = function(i) {
var data = popup.data[i];
if (typeof data == "string") return data;
return data && data.value || "";
};
var bgTokenizer = popup.session.bgTokenizer;
bgTokenizer.$tokenizeRow = function(row) {
/**@type {import("../../ace-internal").Ace.Completion &{name?, className?, matchMask?, message?}}*/ var data = popup.data[row];
var tokens = [];
if (!data) return tokens;
if (typeof data == "string") data = {
value: data
};
var caption = data.caption || data.value || data.name;
function addToken(value, className) {
value && tokens.push({
type: (data.className || "") + (className || ""),
value: value
});
}
var lower = caption.toLowerCase();
var filterText = (popup.filterText || "").toLowerCase();
var lastIndex = 0;
var lastI = 0;
for(var i = 0; i <= filterText.length; i++){
if (i != lastI && (data.matchMask & 1 << i || i == filterText.length)) {
var sub = filterText.slice(lastI, i);
lastI = i;
var index = lower.indexOf(sub, lastIndex);
if (index == -1) continue;
addToken(caption.slice(lastIndex, index), "");
lastIndex = index + sub.length;
addToken(caption.slice(index, lastIndex), "completion-highlight");
}
}
addToken(caption.slice(lastIndex, caption.length), "");
tokens.push({
type: "completion-spacer",
value: " "
});
if (data.meta) tokens.push({
type: "completion-meta",
value: data.meta
});
if (data.message) tokens.push({
type: "completion-message",
value: data.message
});
return tokens;
};
bgTokenizer.$updateOnChange = noop;
bgTokenizer.start = noop;
popup.session["$computeWidth"] = function() {
return this.screenWidth = 0;
};
// public
popup.isOpen = false;
popup.isTopdown = false;
popup.autoSelect = true;
popup.filterText = "";
popup.isMouseOver = false;
popup.data = [];
popup.setData = function(list, filterText) {
popup.filterText = filterText || "";
popup.setValue("\n".repeat(list.length), -1);
popup.data = list || [];
popup.setRow(0);
};
popup.getData = function(row) {
return popup.data[row];
};
popup.getRow = function() {
return selectionMarker.start.row;
};
popup.setRow = function(line) {
line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length - 1, line));
if (selectionMarker.start.row != line) {
popup.selection.clearSelection();
selectionMarker.start.row = selectionMarker.end.row = line || 0;
// @ts-ignore
popup.session._emit("changeBackMarker");
popup.moveCursorTo(line || 0, 0);
if (popup.isOpen) popup._signal("select");
}
};
// @ts-ignore
popup.on("changeSelection", function() {
if (popup.isOpen) {
popup.setRow(popup.selection.lead.row);
}
// @ts-ignore
popup.renderer.scrollCursorIntoView();
});
popup.hide = function() {
this.container.style.display = "none";
popup.anchorPos = null;
popup.anchor = null;
if (popup.isOpen) {
popup.isOpen = false;
this._signal("hide");
}
};
/**
* Tries to show the popup anchored to the given position and anchors.
* If the anchor is not specified it tries to align to bottom and right as much as possible.
* If the popup does not have enough space to be rendered with the given anchors, it returns false without rendering the popup.
* The forceShow flag can be used to render the popup in these cases, which slides the popup so it entirely fits on the screen.
* @param {{top: number, left: number}} pos
* @param {number} lineHeight
* @param {"top" | "bottom" | undefined} anchor
* @param {boolean} forceShow
* @returns {boolean}
*/ popup.tryShow = function(pos, lineHeight, anchor, forceShow) {
if (!forceShow && popup.isOpen && popup.anchorPos && popup.anchor && popup.anchorPos.top === pos.top && popup.anchorPos.left === pos.left && popup.anchor === anchor) {
return true;
}
var el = this.container;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var renderer = this.renderer;
// var maxLines = Math.min(renderer.$maxLines, this.session.getLength());
var maxH = renderer.$maxLines * lineHeight * 1.4;
var dims = {
top: 0,
bottom: 0,
left: 0
};
var spaceBelow = screenHeight - pos.top - 3 * this.$borderSize - lineHeight;
var spaceAbove = pos.top - 3 * this.$borderSize;
if (!anchor) {
if (spaceAbove <= spaceBelow || spaceBelow >= maxH) {
anchor = "bottom";
} else {
anchor = "top";
}
}
if (anchor === "top") {
dims.bottom = pos.top - this.$borderSize;
dims.top = dims.bottom - maxH;
} else if (anchor === "bottom") {
dims.top = pos.top + lineHeight + this.$borderSize;
dims.bottom = dims.top + maxH;
}
var fitsX = dims.top >= 0 && dims.bottom <= screenHeight;
if (!forceShow && !fitsX) {
return false;
}
if (!fitsX) {
if (anchor === "top") {
renderer.$maxPixelHeight = spaceAbove;
} else {
renderer.$maxPixelHeight = spaceBelow;
}
} else {
renderer.$maxPixelHeight = null;
}
if (anchor === "top") {
el.style.top = "";
el.style.bottom = screenHeight - dims.bottom + "px";
popup.isTopdown = false;
} else {
el.style.top = dims.top + "px";
el.style.bottom = "";
popup.isTopdown = true;
}
el.style.display = "";
var left = pos.left;
if (left + el.offsetWidth > screenWidth) left = screenWidth - el.offsetWidth;
el.style.left = left + "px";
el.style.right = "";
if (!popup.isOpen) {
popup.isOpen = true;
this._signal("show");
lastMouseEvent = null;
}
popup.anchorPos = pos;
popup.anchor = anchor;
return true;
};
popup.show = function(pos, lineHeight, topdownOnly) {
this.tryShow(pos, lineHeight, topdownOnly ? "bottom" : undefined, true);
};
popup.goTo = function(where) {
var row = this.getRow();
var max = this.session.getLength() - 1;
switch(where){
case "up":
row = row <= 0 ? max : row - 1;
break;
case "down":
row = row >= max ? -1 : row + 1;
break;
case "start":
row = 0;
break;
case "end":
row = max;
break;
}
this.setRow(row);
};
popup.getTextLeftOffset = function() {
return this.$borderSize + this.renderer.$padding + this.$imageSize;
};
popup.$imageSize = 0;
popup.$borderSize = 1;
return popup;
}
}
;// CONCATENATED MODULE: ./src/components/lightbulb.ts
function lightbulb_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class LightbulbWidget {
setEditorListeners(editor) {
//@ts-expect-error
editor.on("changeSelection", this.hideAll);
editor.on("focus", this.hideAll);
editor.renderer.on("afterRender", this.setPosition);
}
removeListeners() {
this.editor.off("changeSelection", this.hideAll);
this.editor.off("focus", this.hideAll);
this.editor.session.off("changeScrollTop", this.setPosition);
this.editor.session.off("changeScrollLeft", this.setPosition);
}
setExecuteActionCallback(callback) {
this.executeActionCallback = callback;
}
createLightbulb() {
this.lightbulb = document.createElement("div");
this.lightbulb.id = "lightbulb";
this.lightbulb.style.display = 'none';
this.lightbulb.style.position = 'absolute';
this.lightbulb.style.width = this.lightBulbWidth + 'px';
this.lightbulb.style.height = this.lightBulbHeight + 'px';
this.lightbulb.style.zIndex = "999";
this.lightbulb.style.background = 'url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxzdmcgdmlld0JveD0iNi4yMTM2IDIuMjk4MSAxMi42OTI0IDE4LjYzMjgiIHdpZHRoPSIxMCIgaGVpZ2h0PSIxNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCiAgPHBhdGggZD0iTSAxNi43ODEgNC4wOCBDIDE1LjQzMyAyLjc1MiAxMy42MiAyLjA5OCAxMS44MSAyLjM1MiBDIDguOTUyIDIuNzU0IDYuNjY4IDUuMjE0IDYuMjc4IDguMzA4IEMgNS45ODYgMTAuNjE2IDYuNjk2IDEyLjg0NSA4LjIyNyAxNC40MjQgQyA5LjE4NyAxNS40MTUgOS43MzkgMTYuNzgzIDkuNzM5IDE4LjE3NSBMIDE1LjM5NiAxOC4xODkgQyAxNS4zOTYgMTYuODc2IDE1LjkxMSAxNS40MTggMTYuODc1IDE0LjQzNSBDIDE4LjE2NSAxMy4xMTYgMTguOTA2IDExLjI0OSAxOC45MDYgOS4zMTQgQyAxOC45MDYgNy4zMTcgMTguMTMzIDUuNDEgMTYuNzgxIDQuMDggWiIgc3R5bGU9ImZpbGw6IHJnYigyNTIsIDE5NSwgODcpOyIgdHJhbnNmb3JtPSJtYXRyaXgoMSwgMCwgMCwgMSwgMCwgLTEuNDIxMDg1NDcxNTIwMjAwNGUtMTQpIi8+DQogIDxyZWN0IHg9IjguMzgiIHk9IjIzMy42NzkiIHdpZHRoPSI0LjMxMyIgaGVpZ2h0PSIwLjAxMSIgc3R5bGU9ImZpbGw6IHJnYigyMTYsIDIxNiwgMjE2KTsgc3Ryb2tlOiByZ2IoMCwgMCwgMCk7IiB0cmFuc2Zvcm09Im1hdHJpeCgxLCAwLCAwLCAtMSwgMi4wNzg5ODQxMDcxNjIxODUsIDI1Mi45MzUzNDM1OTU5NDE5NikiLz4NCiAgPHJlY3QgeD0iLTExLjY2NSIgeT0iLTIzLjU5NSIgd2lkdGg9IjMuMDk4IiBzdHlsZT0iZmlsbDogcmdiKDIxNiwgMjE2LCAyMTYpOyBzdHJva2U6IHJnYigwLCAwLCAwKTsiIHRyYW5zZm9ybT0ibWF0cml4KDAuOTk5OTgxOTk5Mzk3Mjc3OSwgLTAuMDA2MDUyOTk5NzU3MjMwMjgxLCAwLCAxLjAwMDAxODAwMDYwMjcyMjIsIDIyLjcyOTA4NDk0NDQxNjMwNywgNDQuNDQ0NjczNDQ4NDU5MDg1KSIgaGVpZ2h0PSIwLjAxMSIvPg0KPC9zdmc+) no-repeat center center';
this.lightbulb.style.cursor = 'pointer';
this.lightbulb.setAttribute('role', 'button');
this.lightbulb.setAttribute('aria-label', 'Show code actions');
this.editor.container.appendChild(this.lightbulb);
this.lightbulb.addEventListener('click', (event)=>{
this.showMenu(event.clientX, event.clientY);
});
}
setCodeActions(actions) {
this.codeActions = actions;
}
showMenu(x, y) {
if (this.codeActions.length === 0) {
return;
}
this.setDataToPopup();
//@ts-expect-error wrong public API
this.popup.show({
top: y,
left: x
}, 12, false);
}
isEmpty() {
if (this.codeActions.length === 0) {
return true;
}
for (let actionsByService of this.codeActions){
if (actionsByService.codeActions && actionsByService.codeActions.length > 0) {
return false;
}
}
return true;
}
setDataToPopup() {
let codeActions = [];
this.codeActions.forEach((codeActionsByService)=>{
var _codeActionsByService_codeActions;
(_codeActionsByService_codeActions = codeActionsByService.codeActions) === null || _codeActionsByService_codeActions === void 0 ? void 0 : _codeActionsByService_codeActions.forEach((action)=>{
codeActions.push({
value: action.title,
//@ts-expect-error
serviceName: codeActionsByService.service,
action: action
});
});
});
this.popup.setData(codeActions, "");
}
executeAction(action, serviceName) {
this.executeActionCallback && this.executeActionCallback(action, serviceName);
this.hideLightbulb();
}
showLightbulb() {
if (this.isEmpty()) {
return;
}
this.setPosition();
this.lightbulb.style.display = 'block';
}
hideLightbulb() {
this.lightbulb.style.display = 'none';
}
calculatePosition() {
const gutterCenter = Math.round(this.editor.renderer["gutterWidth"] / 2 - this.lightBulbWidth);
const firstRow = this.editor.renderer.getFirstVisibleRow();
const cursor = this.editor.getCursorPosition();
const lineHeight = this.editor.renderer.lineHeight;
return {
x: gutterCenter,
y: (cursor.row - firstRow) * lineHeight
};
}
dispose() {
this.removeListeners();
document.body.removeChild(this.lightbulb);
}
constructor(editor, executeActionCallback){
lightbulb_define_property(this, "codeActions", void 0);
lightbulb_define_property(this, "lightbulb", void 0);
lightbulb_define_property(this, "popup", void 0);
lightbulb_define_property(this, "executeActionCallback", void 0);
lightbulb_define_property(this, "editor", void 0);
lightbulb_define_property(this, "lightBulbWidth", 10);
lightbulb_define_property(this, "lightBulbHeight", 16);
lightbulb_define_property(this, "hideAll", ()=>{
this.hideLightbulb();
this.popup.hide();
});
lightbulb_define_property(this, "setPosition", ()=>{
const position = this.calculatePosition();
this.lightbulb.style.left = `${position.x}px`;
this.lightbulb.style.top = `${position.y}px`;
});
this.editor = editor;
this.codeActions = [];
this.executeActionCallback = executeActionCallback;
// @ts-ignore
this.popup = new AcePopup(editor.container || document.body || document.documentElement);
//@ts-expect-error
this.popup.on("click", (e)=>{
const selectedRow = this.popup.getData(this.popup.getRow());
// @ts-ignore
this.executeAction(selectedRow.action, selectedRow.serviceName);
this.popup.hide();
e.stop();
});
this.setEditorListeners(editor);
this.createLightbulb();
}
}
;// CONCATENATED MODULE: ./src/misc/styles.ts
function setStyles(editor) {
editor.renderer["$textLayer"].dom.importCssString(`.ace_tooltip * {
margin: 0;
font-size: 12px;
}
.ace_tooltip code {
font-style: italic;
font-size: 11px;
}
.language_highlight_error {
position: absolute;
border-bottom: dotted 1px #e00404;
z-index: 2000;
border-radius: 0;
}
.language_highlight_warning {
position: absolute;
border-bottom: solid 1px #DDC50F;
z-index: 2000;
border-radius: 0;
}
.language_highlight_info {
position: absolute;
border-bottom: dotted 1px #999;
z-index: 2000;
border-radius: 0;
}
.language_highlight_text, .language_highlight_read, .language_highlight_write {
position: absolute;
box-sizing: border-box;
border: solid 1px #888;
z-index: 2000;
}
.language_highlight_write {
border: solid 1px #F88;
}`, "linters.css");
editor.renderer["$textLayer"].dom.importCssString(`
.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {
background-color: #CAD6FA;
z-index: 1;
}
.ace_dark.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {
background-color: #3a674e;
}
.ace_editor.ace_autocomplete .ace_line-hover {
border: 1px solid #abbffe;
margin-top: -1px;
background: rgba(233,233,253,0.4);
position: absolute;
z-index: 2;
}
.ace_dark.ace_editor.ace_autocomplete .ace_line-hover {
border: 1px solid rgba(109, 150, 13, 0.8);
background: rgba(58, 103, 78, 0.62);
}
.ace_completion-meta {
opacity: 0.5;
margin-left: 0.9em;
}
.ace_completion-message {
margin-left: 0.9em;
color: blue;
}
.ace_editor.ace_autocomplete .ace_completion-highlight{
color: #2d69c7;
}
.ace_dark.ace_editor.ace_autocomplete .ace_completion-highlight{
color: #93ca12;
}
.ace_editor.ace_autocomplete {
width: 300px;
z-index: 200000;
border: 1px lightgray solid;
position: fixed;
box-shadow: 2px 3px 5px rgba(0,0,0,.2);
line-height: 1.4;
background: #fefefe;
color: #111;
}
.ace_dark.ace_editor.ace_autocomplete {
border: 1px #484747 solid;
box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.51);
line-height: 1.4;
background: #25282c;
color: #c1c1c1;
}
.ace_autocomplete .ace_text-layer {
width: calc(100% - 8px);
}
.ace_autocomplete .ace_line {
display: flex;
align-items: center;
}
.ace_autocomplete .ace_line > * {
min-width: 0;
flex: 0 0 auto;
}
.ace_autocomplete .ace_line .ace_ {
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
}
.ace_autocomplete .ace_completion-spacer {
flex: 1;
}
.ace_autocomplete.ace_loading:after {
content: "";
position: absolute;
top: 0px;
height: 2px;
width: 8%;
background: blue;
z-index: 100;
animation: ace_progress 3s infinite linear;
animation-delay: 300ms;
transform: translateX(-100%) scaleX(1);
}
@keyframes ace_progress {
0% { transform: translateX(-100%) scaleX(1) }
50% { transform: translateX(625%) scaleX(2) }
100% { transform: translateX(1500%) scaleX(3) }
}
@media (prefers-reduced-motion) {
.ace_autocomplete.ace_loading:after {
transform: translateX(625%) scaleX(2);
animation: none;
}
}
`, "autocompletion.css", false);
}
;// CONCATENATED MODULE: ./src/language-provider.ts
function language_provider_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class LanguageProvider {
/**
* Creates LanguageProvider using our transport protocol with ability to register different services on same
* webworker
* @param {Worker} worker
* @param {ProviderOptions} options
*/ static create(worker, options) {
return new LanguageProvider(worker, options);
}
static fromCdn(source, options, includeDefaultLinters) {
let worker;
if (typeof source === "string") {
if (source == "" || !/^http(s)?:/.test(source)) {
throw "Url is not valid";
}
if (source[source.length - 1] == "/") {
source = source.substring(0, source.length - 1);
}
worker = createWorker(source, includeDefaultLinters);
} else {
if (source.includeDefaultLinters == undefined) {
source.includeDefaultLinters = true;
}
var _source_includeDefaultLinters;
worker = createWorker({
services: source.services,
serviceManagerCdn: source.serviceManagerCdn
}, (_source_includeDefaultLinters = source.includeDefaultLinters) !== null && _source_includeDefaultLinters !== void 0 ? _source_includeDefaultLinters : includeDefaultLinters);
}
return new LanguageProvider(worker, options);
}
setProviderOptions(options) {
var _options;
var _this_options;
const defaultFunctionalities = {
hover: true,
completion: {
overwriteCompleters: true
},
completionResolve: true,
format: true,
documentHighlights: true,
signatureHelp: true,
semanticTokens: false,
codeActions: true
};
this.options = options !== null && options !== void 0 ? options : {};
this.options.functionality = typeof this.options.functionality === 'object' ? this.options.functionality : {};
Object.entries(defaultFunctionalities).forEach(([key, value])=>{
// Check if the functionality has not been defined in the provided options
if (this.options.functionality[key] === undefined) {
// If not, set it to its default value
this.options.functionality[key] = value;
}
});
(_this_options = this.options).markdownConverter || (_this_options.markdownConverter = new (showdown_default()).Converter());
var _this_options_requireFilePath;
this.requireFilePath = (_this_options_requireFilePath = this.options.requireFilePath) !== null && _this_options_requireFilePath !== void 0 ? _this_options_requireFilePath : false;
if ((_options = options) === null || _options === void 0 ? void 0 : _options.workspacePath) {
this.workspaceUri = (0,utils/* convertToUri */.de)(options.workspacePath);
}
}
/**
* @param session
* @param filePath - The full file path associated with the editor.
*/ setSessionFilePath(session, filePath) {
var _this_$getSessionLanguageProvider;
(_this_$getSessionLanguageProvider = this.$getSessionLanguageProvider(session)) === null || _this_$getSessionLanguageProvider === void 0 ? void 0 : _this_$getSessionLanguageProvider.setFilePath(filePath);
}
$getSessionLanguageProvider(session) {
return this.$sessionLanguageProviders[session["id"]];
}
$getFileName(session) {
let sessionLanguageProvider = this.$getSessionLanguageProvider(session);
return sessionLanguageProvider.comboDocumentIdentifier;
}
/**
* Registers an Ace editor instance with the language provider.
* @param editor - The Ace editor instance to register.
*/ registerEditor(editor) {
if (!this.editors.includes(editor)) this.$registerEditor(editor);
this.$registerSession(editor.session, editor);
}
setCodeActionCallback(callback) {
this.codeActionCallback = callback;
}
executeCommand(command, serviceName, args, callback) {
this.$messageController.executeCommand(serviceName, command, args, callback); //TODO:
}
applyEdit(workspaceEdit, serviceName, callback) {
if (workspaceEdit.changes) {
for(let uri in workspaceEdit.changes){
if (!this.$urisToSessionsIds[uri]) {
callback && callback({
applied: false,
failureReason: "No session found for uri " + uri
}, serviceName);
return;
}
}
for(let uri in workspaceEdit.changes){
let sessionId = this.$urisToSessionsIds[uri];
let sessionLanguageProvider = this.$sessionLanguageProviders[sessionId];
sessionLanguageProvider.applyEdits(workspaceEdit.changes[uri]);
}
callback && callback({
applied: true
}, serviceName);
}
// some servers doesn't respect missing capability
if (workspaceEdit.documentChanges) {
for (let change of workspaceEdit.documentChanges){
if ("kind" in change) {
// we don't support create/rename/remove stuff
return;
}
if ("textDocument" in change) {
let uri = change.textDocument.uri;
if (!this.$urisToSessionsIds[uri]) {
callback && callback({
applied: false,
failureReason: "No session found for uri " + uri
}, serviceName);
return;
}
}
}
for (let change of workspaceEdit.documentChanges){
if ("textDocument" in change) {
let sessionId = this.$urisToSessionsIds[change.textDocument.uri];
let sessionLanguageProvider = this.$sessionLanguageProviders[sessionId];
sessionLanguageProvider.applyEdits(change.edits);
}
}
callback && callback({
applied: true
}, serviceName);
}
}
$registerEditor(editor) {
this.editors.push(editor);
//init singletons
AceRange.getConstructor(editor);
AceVirtualRenderer.getConstructor(editor);
AceEditor.getConstructor(editor);
editor.setOption("useWorker", false);
editor.on("changeSession", ({ session })=>this.$registerSession(session, editor));
if (this.options.functionality.completion) {
this.$registerCompleters(editor);
}
var _this_activeEditor;
(_this_activeEditor = this.activeEditor) !== null && _this_activeEditor !== void 0 ? _this_activeEditor : this.activeEditor = editor;
editor.on("focus", ()=>{
this.activeEditor = editor;
});
if (this.options.functionality.documentHighlights) {
var $timer;
// @ts-ignore
editor.on("changeSelection", ()=>{
if (!$timer) $timer = setTimeout(()=>{
let cursor = editor.getCursorPosition();
let sessionLanguageProvider = this.$getSessionLanguageProvider(editor.session);
this.$messageController.findDocumentHighlights(this.$getFileName(editor.session), fromPoint(cursor), sessionLanguageProvider.$applyDocumentHighlight);
$timer = undefined;
}, 50);
});
}
if (this.options.functionality.codeActions) {
this.$provideCodeActions(editor);
}
if (this.options.functionality.hover) {
if (!this.$hoverTooltip) {
this.$hoverTooltip = new HoverTooltip();
}
this.$initHoverTooltip(editor);
}
if (this.options.functionality.signatureHelp) {
this.$signatureTooltip.registerEditor(editor);
}
this.setStyles(editor);
}
$provideCodeActions(editor) {
const lightBulb = new LightbulbWidget(editor);
this.$lightBulbWidgets[editor.id] = lightBulb;
lightBulb.setExecuteActionCallback((action, serviceName)=>{
for(let id in this.$lightBulbWidgets){
this.$lightBulbWidgets[id].hideAll();
}
if (typeof action.command === "string") {
this.executeCommand(action.command, serviceName, action["arguments"]);
} else {
if (action.command) {
this.executeCommand(action.command.command, serviceName, action.command.arguments);
} else if ("edit" in action) {
this.applyEdit(action.edit, serviceName);
}
}
});
var actionTimer;
// @ts-ignore
editor.on("changeSelection", ()=>{
if (!actionTimer) actionTimer = setTimeout(()=>{
//TODO: no need to send request on empty
let selection = editor.getSelection().getRange();
let cursor = editor.getCursorPosition();
let diagnostics = fromAnnotations(editor.session.getAnnotations().filter((el)=>el.row === cursor.row));
this.$messageController.getCodeActions(this.$getFileName(editor.session), fromRange(selection), {
diagnostics
}, (codeActions)=>{
lightBulb.setCodeActions(codeActions);
lightBulb.showLightbulb();
});
actionTimer = undefined;
}, 500);
});
}
$initHoverTooltip(editor) {
const Range = editor.getSelectionRange().constructor;
this.$hoverTooltip.setDataProvider((e, editor)=>{
const session = editor.session;
const docPos = e.getDocumentPosition();
this.doHover(session, docPos, (hover)=>{
var _this_$getSessionLanguageProvider_state_diagnosticMarkers, _this_$getSessionLanguageProvider_state, _hover, _hover1, _errorMarkers_;
var _this_$getSessionLanguageProvider_state_diagnosticMarkers_getMarkersAtPosition;
const errorMarkers = (_this_$getSessionLanguageProvider_state_diagnosticMarkers_getMarkersAtPosition = (_this_$getSessionLanguageProvider_state = this.$getSessionLanguageProvider(session).state) === null || _this_$getSessionLanguageProvider_state === void 0 ? void 0 : (_this_$getSessionLanguageProvider_state_diagnosticMarkers = _this_$getSessionLanguageProvider_state.diagnosticMarkers) === null || _this_$getSessionLanguageProvider_state_diagnosticMarkers === void 0 ? void 0 : _this_$getSessionLanguageProvider_state_diagnosticMarkers.getMarkersAtPosition(docPos)) !== null && _this_$getSessionLanguageProvider_state_diagnosticMarkers_getMarkersAtPosition !== void 0 ? _this_$getSessionLanguageProvider_state_diagnosticMarkers_getMarkersAtPosition : [];
const hasHoverContent = (_hover = hover) === null || _hover === void 0 ? void 0 : _hover.content;
if (errorMarkers.length === 0 && !hasHoverContent) return;
var _hover_range;
var range = (_hover_range = (_hover1 = hover) === null || _hover1 === void 0 ? void 0 : _hover1.range) !== null && _hover_range !== void 0 ? _hover_range : (_errorMarkers_ = errorMarkers[0]) === null || _errorMarkers_ === void 0 ? void 0 : _errorMarkers_.range;
range = range ? Range.fromPoints(range.start, range.end) : session.getWordRange(docPos.row, docPos.column);
const hoverNode = hasHoverContent ? this.createHoverNode(hover) : null;
const errorNode = errorMarkers.length > 0 ? this.createErrorNode(errorMarkers) : null;
const domNode = document.createElement('div');
if (errorNode) domNode.appendChild(errorNode);
if (hoverNode) domNode.appendChild(hoverNode);
this.$hoverTooltip.showForRange(editor, range, domNode, e);
});
});
this.$hoverTooltip.addToEditor(editor);
}
createHoverNode(hover) {
const hoverNode = document.createElement("div");
hoverNode.innerHTML = this.getTooltipText(hover);
return hoverNode;
}
createErrorNode(errorMarkers) {
const errorDiv = document.createElement('div');
errorDiv.textContent = errorMarkers.map((el)=>el.tooltipText.trim()).join("\n");
return errorDiv;
}
setStyles(editor) {
if (!this.stylesEmbedded) {
setStyles(editor);
this.stylesEmbedded = true;
}
}
setGlobalOptions(serviceName, options, merge = false) {
this.$messageController.setGlobalOptions(serviceName, options, merge);
}
/**
* Sets the workspace URI for the language provider.
*
* If the provided URI is the same as the current workspace URI, no action is taken.
* Otherwise, the workspace URI is updated and the message controller is notified.
*
* Not all servers support changing of workspace URI.
*
* @param workspaceUri - The new workspace URI. Could be simple path, not URI itself.
*/ changeWorkspaceFolder(workspaceUri) {
if (workspaceUri === this.workspaceUri) return;
this.workspaceUri = (0,utils/* convertToUri */.de)(workspaceUri);
this.$messageController.setWorkspace(workspaceUri);
}
setSessionOptions(session, options) {
let sessionLanguageProvider = this.$getSessionLanguageProvider(session);
sessionLanguageProvider.setOptions(options);
}
configureServiceFeatures(serviceName, features) {
this.$messageController.configureFeatures(serviceName, features);
}
doHover(session, position, callback) {
this.$messageController.doHover(this.$getFileName(session), fromPoint(position), (hover)=>callback && callback(toTooltip(hover)));
}
provideSignatureHelp(session, position, callback) {
this.$messageController.provideSignatureHelp(this.$getFileName(session), fromPoint(position), (signatureHelp)=>callback && callback(fromSignatureHelp(signatureHelp)));
}
getTooltipText(hover) {
return hover.content.type === "markdown" ? common_converters_CommonConverter.cleanHtml(this.options.markdownConverter.makeHtml(hover.content.text)) : hover.content.text;
}
getSemanticTokens() {
if (!this.options.functionality.semanticTokens) return;
let sessionLanguageProvider = this.$getSessionLanguageProvider(this.activeEditor.session);
sessionLanguageProvider.getSemanticTokens();
}
doComplete(editor, session, callback) {
let cursor = editor.getCursorPosition();
this.$messageController.doComplete(this.$getFileName(session), fromPoint(cursor), (completions)=>completions && callback(toCompletions(completions)));
}
doResolve(item, callback) {
this.$messageController.doResolve(item["fileName"], toCompletionItem(item), callback);
}
$registerCompleters(editor) {
let completer = {
getCompletions: async (editor, session, pos, prefix, callback)=>{
this.$getSessionLanguageProvider(session).$sendDeltaQueue(()=>{
this.doComplete(editor, session, (completions)=>{
let fileName = this.$getFileName(session);
if (!completions) return;
completions.forEach((item)=>{
item.completerId = completer.id;
item["fileName"] = fileName;
});
callback(null, common_converters_CommonConverter.normalizeRanges(completions));
});
});
},
getDocTooltip: (item)=>{
if (this.options.functionality.completionResolve && !item["isResolved"] && item.completerId === completer.id) {
this.doResolve(item, (completionItem)=>{
item["isResolved"] = true;
if (!completionItem) return;
let completion = toResolvedCompletion(item, completionItem);
item.docText = completion.docText;
if (completion.docHTML) {
item.docHTML = completion.docHTML;
} else if (completion["docMarkdown"]) {
item.docHTML = common_converters_CommonConverter.cleanHtml(this.options.markdownConverter.makeHtml(completion["docMarkdown"]));
}
if (editor["completer"]) {
editor["completer"].updateDocTooltip();
}
});
}
return item;
},
id: "lspCompleters"
};
if (this.options.functionality.completion && this.options.functionality.completion.overwriteCompleters) {
editor.completers = [
completer
];
} else {
if (!editor.completers) {
editor.completers = [];
}
editor.completers.push(completer);
}
}
closeConnection() {
this.$messageController.closeConnection(()=>{
this.$messageController.$worker.terminate();
});
}
/**
* Removes document from all linked services by session id
* @param session
* @param [callback]
*/ closeDocument(session, callback) {
let sessionProvider = this.$getSessionLanguageProvider(session);
if (sessionProvider) {
sessionProvider.closeDocument(callback);
delete this.$sessionLanguageProviders[session["id"]];
}
}
constructor(worker, options){
language_provider_define_property(this, "activeEditor", void 0);
language_provider_define_property(this, "$messageController", void 0);
language_provider_define_property(this, "$signatureTooltip", void 0);
language_provider_define_property(this, "$sessionLanguageProviders", {});
language_provider_define_property(this, "editors", []);
language_provider_define_property(this, "options", void 0);
language_provider_define_property(this, "$hoverTooltip", void 0);
language_provider_define_property(this, "$urisToSessionsIds", {});
language_provider_define_property(this, "workspaceUri", void 0);
language_provider_define_property(this, "requireFilePath", false);
language_provider_define_property(this, "$lightBulbWidgets", {});
language_provider_define_property(this, "stylesEmbedded", void 0);
language_provider_define_property(this, "$registerSession", (session, editor)=>{
var _this_$sessionLanguageProviders, _session_id;
var _;
(_ = (_this_$sessionLanguageProviders = this.$sessionLanguageProviders)[_session_id = session["id"]]) !== null && _ !== void 0 ? _ : _this_$sessionLanguageProviders[_session_id] = new SessionLanguageProvider(this, session, editor, this.$messageController);
});
language_provider_define_property(this, "codeActionCallback", void 0);
language_provider_define_property(this, "format", ()=>{
if (!this.options.functionality.format) return;
let sessionLanguageProvider = this.$getSessionLanguageProvider(this.activeEditor.session);
sessionLanguageProvider.$sendDeltaQueue(sessionLanguageProvider.format);
});
this.$messageController = new MessageController(worker, this);
this.setProviderOptions(options);
this.$signatureTooltip = new SignatureTooltip(this);
}
}
class SessionLanguageProvider {
get comboDocumentIdentifier() {
return {
documentUri: this.documentUri,
sessionId: this.session["id"]
};
}
/**
* @param filePath
*/ setFilePath(filePath) {
if (this.$filePath !== undefined) return;
this.$filePath = filePath;
this.$init();
}
$init() {
if (this.$isFilePathRequired && this.$filePath === undefined) return;
this.initDocumentUri();
this.$messageController.init(this.comboDocumentIdentifier, this.session.doc, this.$mode, this.$options, this.$connected);
}
addSemanticTokenSupport(session) {
let bgTokenizer = session.bgTokenizer;
session.setSemanticTokens = (tokens)=>{
bgTokenizer.semanticTokens = tokens;
};
bgTokenizer.$tokenizeRow = (row)=>{
var line = bgTokenizer.doc.getLine(row);
var state = bgTokenizer.states[row - 1];
var data = bgTokenizer.tokenizer.getLineTokens(line, state, row);
if (bgTokenizer.states[row] + "" !== data.state + "") {
bgTokenizer.states[row] = data.state;
bgTokenizer.lines[row + 1] = null;
if (bgTokenizer.currentLine > row + 1) bgTokenizer.currentLine = row + 1;
} else if (bgTokenizer.currentLine == row) {
bgTokenizer.currentLine = row + 1;
}
if (bgTokenizer.semanticTokens) {
let decodedTokens = bgTokenizer.semanticTokens.getByRow(row);
if (decodedTokens) {
data.tokens = mergeTokens(data.tokens, decodedTokens);
}
}
return bgTokenizer.lines[row] = data.tokens;
};
}
initDocumentUri() {
var _this_$filePath;
let filePath = (_this_$filePath = this.$filePath) !== null && _this_$filePath !== void 0 ? _this_$filePath : this.session["id"] + "." + this.$extension;
this.documentUri = (0,utils/* convertToUri */.de)(filePath);
this.$provider.$urisToSessionsIds[this.documentUri] = this.session["id"];
}
get $extension() {
let mode = this.$mode.replace("ace/mode/", "");
var _this_extensions_mode;
return (_this_extensions_mode = this.extensions[mode]) !== null && _this_extensions_mode !== void 0 ? _this_extensions_mode : mode;
}
get $mode() {
return this.session["$modeId"];
}
get $format() {
return {
tabSize: this.session.getTabSize(),
insertSpaces: this.session.getUseSoftTabs()
};
}
setOptions(options) {
if (!this.$isConnected) {
this.$options = options;
return;
}
this.$messageController.changeOptions(this.comboDocumentIdentifier, options);
}
getSemanticTokens() {
if (!this.$provider.options.functionality.semanticTokens) return;
//TODO: improve this
let lastRow = this.editor.renderer.getLastVisibleRow();
let visibleRange = {
start: {
row: this.editor.renderer.getFirstVisibleRow(),
column: 0
},
end: {
row: lastRow + 1,
column: this.session.getLine(lastRow).length
}
};
this.$messageController.getSemanticTokens(this.comboDocumentIdentifier, fromRange(visibleRange), (tokens)=>{
if (!tokens) {
return;
}
let decodedTokens = parseSemanticTokens(tokens.data, this.semanticTokensLegend.tokenTypes, this.semanticTokensLegend.tokenModifiers);
this.session.setSemanticTokens(decodedTokens);
let bgTokenizer = this.session.bgTokenizer;
bgTokenizer.running = setTimeout(()=>{
var _bgTokenizer_semanticTokens, _bgTokenizer, _bgTokenizer_semanticTokens1, _bgTokenizer1;
if (((_bgTokenizer = bgTokenizer) === null || _bgTokenizer === void 0 ? void 0 : (_bgTokenizer_semanticTokens = _bgTokenizer.semanticTokens) === null || _bgTokenizer_semanticTokens === void 0 ? void 0 : _bgTokenizer_semanticTokens.tokens) && ((_bgTokenizer1 = bgTokenizer) === null || _bgTokenizer1 === void 0 ? void 0 : (_bgTokenizer_semanticTokens1 = _bgTokenizer1.semanticTokens) === null || _bgTokenizer_semanticTokens1 === void 0 ? void 0 : _bgTokenizer_semanticTokens1.tokens.length) > 0) {
var _bgTokenizer_semanticTokens2, _bgTokenizer2;
let startRow = (_bgTokenizer2 = bgTokenizer) === null || _bgTokenizer2 === void 0 ? void 0 : (_bgTokenizer_semanticTokens2 = _bgTokenizer2.semanticTokens) === null || _bgTokenizer_semanticTokens2 === void 0 ? void 0 : _bgTokenizer_semanticTokens2.tokens[0].row;
bgTokenizer.currentLine = startRow;
bgTokenizer.lines = bgTokenizer.lines.slice(0, startRow - 1);
} else {
bgTokenizer.currentLine = 0;
bgTokenizer.lines = [];
}
bgTokenizer.$worker();
}, 20);
});
}
closeDocument(callback) {
this.$messageController.closeDocument(this.comboDocumentIdentifier, callback);
}
/**
* Constructs a new instance of the `SessionLanguageProvider` class.
*
* @param provider - The `LanguageProvider` instance.
* @param session - The Ace editor session.
* @param editor - The Ace editor instance.
* @param messageController - The `IMessageController` instance for handling messages.
*/ constructor(provider, session, editor, messageController){
language_provider_define_property(this, "session", void 0);
language_provider_define_property(this, "documentUri", void 0);
language_provider_define_property(this, "$messageController", void 0);
language_provider_define_property(this, "$deltaQueue", void 0);
language_provider_define_property(this, "$isConnected", false);
language_provider_define_property(this, "$modeIsChanged", false);
language_provider_define_property(this, "$options", void 0);
language_provider_define_property(this, "$filePath", void 0);
language_provider_define_property(this, "$isFilePathRequired", false);
language_provider_define_property(this, "$servicesCapabilities", void 0);
language_provider_define_property(this, "state", {
occurrenceMarkers: null,
diagnosticMarkers: null
});
language_provider_define_property(this, "extensions", {
"typescript": "ts",
"javascript": "js"
});
language_provider_define_property(this, "editor", void 0);
language_provider_define_property(this, "semanticTokensLegend", void 0);
language_provider_define_property(this, "$provider", void 0);
language_provider_define_property(this, "$connected", (capabilities)=>{
this.$isConnected = true;
// @ts-ignore
this.setServerCapabilities(capabilities);
if (this.$modeIsChanged) this.$changeMode();
if (this.$deltaQueue) this.$sendDeltaQueue();
if (this.$options) this.setOptions(this.$options);
});
language_provider_define_property(this, "$changeMode", ()=>{
if (!this.$isConnected) {
this.$modeIsChanged = true;
return;
}
this.$deltaQueue = [];
this.session.clearAnnotations();
if (this.state.diagnosticMarkers) {
this.state.diagnosticMarkers.setMarkers([]);
}
this.session.setSemanticTokens(undefined); //clear all semantic tokens
let newVersion = this.session.doc["version"]++;
this.$messageController.changeMode(this.comboDocumentIdentifier, this.session.getValue(), newVersion, this.$mode, this.setServerCapabilities);
});
language_provider_define_property(this, "setServerCapabilities", (capabilities)=>{
if (!capabilities) return;
this.$servicesCapabilities = {
...capabilities
};
let hasTriggerChars = Object.values(capabilities).some((capability)=>{
var _capability_completionProvider, _capability;
return (_capability = capability) === null || _capability === void 0 ? void 0 : (_capability_completionProvider = _capability.completionProvider) === null || _capability_completionProvider === void 0 ? void 0 : _capability_completionProvider.triggerCharacters;
});
if (hasTriggerChars) {
let completer = this.editor.completers.find((completer)=>completer.id === "lspCompleters");
if (completer) {
let allTriggerCharacters = [];
Object.values(capabilities).forEach((capability)=>{
var _capability_completionProvider, _capability;
if ((_capability = capability) === null || _capability === void 0 ? void 0 : (_capability_completionProvider = _capability.completionProvider) === null || _capability_completionProvider === void 0 ? void 0 : _capability_completionProvider.triggerCharacters) {
allTriggerCharacters.push(...capability.completionProvider.triggerCharacters);
}
});
allTriggerCharacters = [
...new Set(allTriggerCharacters)
];
completer.triggerCharacters = allTriggerCharacters;
}
}
let hasSemanticTokensProvider = Object.values(capabilities).some((capability)=>{
var _capability;
if ((_capability = capability) === null || _capability === void 0 ? void 0 : _capability.semanticTokensProvider) {
this.semanticTokensLegend = capability.semanticTokensProvider.legend;
return true;
}
});
if (hasSemanticTokensProvider) {
this.getSemanticTokens();
}
});
language_provider_define_property(this, "$changeListener", (delta)=>{
this.session.doc["version"]++;
if (!this.$deltaQueue) {
this.$deltaQueue = [];
setTimeout(()=>this.$sendDeltaQueue(()=>{
this.getSemanticTokens();
}), 0);
}
this.$deltaQueue.push(delta);
});
language_provider_define_property(this, "$sendDeltaQueue", (callback)=>{
let deltas = this.$deltaQueue;
if (!deltas) return callback && callback();
this.$deltaQueue = null;
if (deltas.length) this.$messageController.change(this.comboDocumentIdentifier, deltas.map((delta)=>fromAceDelta(delta, this.session.doc.getNewLineCharacter())), this.session.doc, callback);
});
language_provider_define_property(this, "$showAnnotations", (diagnostics)=>{
var _diagnostics;
if (!diagnostics) {
return;
}
this.session.clearAnnotations();
let annotations = toAnnotations(diagnostics);
if (annotations && annotations.length > 0) {
this.session.setAnnotations(annotations);
}
if (!this.state.diagnosticMarkers) {
this.state.diagnosticMarkers = new MarkerGroup(this.session);
}
this.state.diagnosticMarkers.setMarkers((_diagnostics = diagnostics) === null || _diagnostics === void 0 ? void 0 : _diagnostics.map((el)=>toMarkerGroupItem(common_converters_CommonConverter.toRange(toRange(el.range)), "language_highlight_error", el.message)));
});
language_provider_define_property(this, "validate", ()=>{
this.$messageController.doValidation(this.comboDocumentIdentifier, this.$showAnnotations);
});
language_provider_define_property(this, "format", ()=>{
let selectionRanges = this.session.getSelection().getAllRanges();
let $format = this.$format;
let aceRangeDatas = selectionRanges;
if (!selectionRanges || selectionRanges[0].isEmpty()) {
let row = this.session.getLength();
let column = this.session.getLine(row).length - 1;
aceRangeDatas = [
{
start: {
row: 0,
column: 0
},
end: {
row: row,
column: column
}
}
];
}
for (let range of aceRangeDatas){
this.$messageController.format(this.comboDocumentIdentifier, fromRange(range), $format, this.applyEdits);
}
});
language_provider_define_property(this, "applyEdits", (edits)=>{
edits !== null && edits !== void 0 ? edits : edits = [];
for (let edit of edits.reverse()){
this.session.replace(toRange(edit.range), edit.newText);
}
});
language_provider_define_property(this, "$applyDocumentHighlight", (documentHighlights)=>{
if (!this.state.occurrenceMarkers) {
this.state.occurrenceMarkers = new MarkerGroup(this.session);
}
if (documentHighlights) {
this.state.occurrenceMarkers.setMarkers(fromDocumentHighlights(documentHighlights));
}
});
this.$provider = provider;
this.$messageController = messageController;
this.session = session;
this.editor = editor;
this.$isFilePathRequired = provider.requireFilePath;
session.doc["version"] = 1;
session.doc.on("change", this.$changeListener, true);
this.addSemanticTokenSupport(session); //TODO: ?
// @ts-ignore
session.on("changeMode", this.$changeMode);
if (this.$provider.options.functionality.semanticTokens) {
session.on("changeScrollTop", ()=>this.getSemanticTokens());
}
this.$init();
}
}
// EXTERNAL MODULE: ./src/services/service-manager.ts
var service_manager = __webpack_require__(7925);
// EXTERNAL MODULE: ../../node_modules/events/events.js
var events = __webpack_require__(46);
var events_default = /*#__PURE__*/__webpack_require__.n(events);
;// CONCATENATED MODULE: ./src/misc/mock-worker.ts
function mock_worker_define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class MockWorker extends (events_default()) {
onerror(ev) {}
onmessage(ev) {}
onmessageerror(ev) {}
addEventListener(type, listener, options) {
this.addListener(type, listener);
}
dispatchEvent(event) {
return false;
}
postMessage(data, transfer) {
if (this.isProduction) {
this.$emitter.emit("message", {
data: data
});
} else {
setTimeout(()=>{
this.$emitter.emit("message", {
data: data
});
}, 0);
}
}
removeEventListener(type, listener, options) {
this.removeListener(type, listener);
}
terminate() {}
setEmitter(emitter) {
this.$emitter = emitter;
}
constructor(isProduction){
super();
mock_worker_define_property(this, "$emitter", void 0);
mock_worker_define_property(this, "isProduction", void 0);
this.isProduction = isProduction;
}
}
;// CONCATENATED MODULE: ./src/ace-language-client.ts
let serviceManager, client;
class AceLanguageClient {
/**
* Creates LanguageProvider for any Language Server to connect with JSON-RPC (webworker, websocket)
* @param {LanguageClientConfig | LanguageClientConfig[]} servers
* @param {ProviderOptions} options
*/ static for(servers, options) {
if (!serviceManager) {
client = new MockWorker(true);
let ctx = new MockWorker(true);
client.setEmitter(ctx);
ctx.setEmitter(client);
serviceManager = new service_manager.ServiceManager(ctx);
}
if (servers instanceof Array) {
servers.forEach((serverData, index)=>{
serviceManager.registerServer("server" + index, serverData);
});
} else {
serviceManager.registerServer("server", servers);
}
return LanguageProvider.create(client, options);
}
}
})();
/******/ return __webpack_exports__;
/******/ })()
;
});