/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 5697: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/main.ts var main_exports = {}; __export(main_exports, { config: () => config, t: () => t }); module.exports = __toCommonJS(main_exports); // src/node/reader.ts var import_fs = __nccwpck_require__(7147); var import_promises = __nccwpck_require__(3292); async function readFileFromUri(uri) { if (uri.protocol === "file:") { return await (0, import_promises.readFile)(uri, "utf8"); } if (uri.protocol === "http:" || uri.protocol === "https:") { const res = await fetch(uri.toString(), { headers: { "Accept-Encoding": "gzip, deflate", "Accept": "application/json" }, redirect: "follow" }); if (!res.ok) { let error = `Unexpected ${res.status} response while trying to read ${uri}`; try { error += `: ${await res.text()}`; } catch { } throw new Error(error); } const decoded = await res.text(); return decoded; } throw new Error("Unsupported protocol"); } function readFileFromFsPath(fsPath) { return (0, import_fs.readFileSync)(fsPath, "utf8"); } // src/main.ts var bundle; function config(config2) { if ("contents" in config2) { if (typeof config2.contents === "string") { bundle = JSON.parse(config2.contents); } else { bundle = config2.contents; } return; } if ("fsPath" in config2) { const fileContent = readFileFromFsPath(config2.fsPath); const content = JSON.parse(fileContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; return; } if (config2.uri) { let uri = config2.uri; if (typeof config2.uri === "string") { uri = new URL(config2.uri); } return new Promise((resolve, reject) => { readFileFromUri(uri).then((uriContent) => { try { const content = JSON.parse(uriContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; resolve(); } catch (err) { reject(err); } }).catch((err) => { reject(err); }); }); } } function t(...args) { const firstArg = args[0]; let key; let message; let formatArgs; if (typeof firstArg === "string") { key = firstArg; message = firstArg; args.splice(0, 1); formatArgs = !args || typeof args[0] !== "object" ? args : args[0]; } else if (firstArg instanceof Array) { const replacements = args.slice(1); if (firstArg.length !== replacements.length + 1) { throw new Error("expected a string as the first argument to l10n.t"); } let str = firstArg[0]; for (let i = 1; i < firstArg.length; i++) { str += `{${i - 1}}` + firstArg[i]; } return t(str, ...replacements); } else { message = firstArg.message; key = message; if (firstArg.comment && firstArg.comment.length > 0) { key += `/${Array.isArray(firstArg.comment) ? firstArg.comment.join("") : firstArg.comment}`; } formatArgs = firstArg.args ?? {}; } const messageFromBundle = bundle?.[key]; if (!messageFromBundle) { return format(message, formatArgs); } if (typeof messageFromBundle === "string") { return format(messageFromBundle, formatArgs); } if (messageFromBundle.comment) { return format(messageFromBundle.message, formatArgs); } return format(message, formatArgs); } var _format2Regexp = /{([^}]+)}/g; function format(template, values) { if (Object.keys(values).length === 0) { return template; } return template.replace(_format2Regexp, (match, group) => values[group] ?? match); } function isBuiltinExtension(json) { return !!(typeof json?.contents?.bundle === "object" && typeof json?.version === "string"); } // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 7017: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { (()=>{var e={46:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,{signal:r}={}){return new Promise(((o,n)=>{function s(){null==r||r.removeEventListener("abort",s),e.removeListener(t,a),e.removeListener("error",u)}function a(...e){s(),o(e)}function u(e){s(),n(e)}null==r||r.addEventListener("abort",s),e.on(t,a),e.on("error",u)}))}},54:function(e,t,r){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const n=r(361),s=o(r(374)),a=o(r(304)),u=s.default("agent-base");function i(){const{stack:e}=new Error;return"string"==typeof e&&e.split("\n").some((e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:")))}function c(e,t){return new c.Agent(e,t)}!function(e){class t extends n.EventEmitter{constructor(e,t){super();let r=t;"function"==typeof e?this.callback=e:e&&(r=e),this.timeout=null,r&&"number"==typeof r.timeout&&(this.timeout=r.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return"number"==typeof this.explicitDefaultPort?this.explicitDefaultPort:i()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){return"string"==typeof this.explicitProtocol?this.explicitProtocol:i()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,r){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const r=Object.assign({},t);"boolean"!=typeof r.secureEndpoint&&(r.secureEndpoint=i()),null==r.host&&(r.host="localhost"),null==r.port&&(r.port=r.secureEndpoint?443:80),null==r.protocol&&(r.protocol=r.secureEndpoint?"https:":"http:"),r.host&&r.path&&delete r.path,delete r.agent,delete r.hostname,delete r._defaultAgent,delete r.defaultPort,delete r.createConnection,e._last=!0,e.shouldKeepAlive=!1;let o=!1,n=null;const s=r.timeout||this.timeout,c=t=>{e._hadError||(e.emit("error",t),e._hadError=!0)},l=()=>{n=null,o=!0;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT",c(e)},d=e=>{o||(null!==n&&(clearTimeout(n),n=null),c(e))},f=t=>{if(o)return;if(null!=n&&(clearTimeout(n),n=null),s=t,Boolean(s)&&"function"==typeof s.addRequest)return u("Callback returned another Agent instance %o",t.constructor.name),void t.addRequest(e,r);var s;if(t)return t.once("free",(()=>{this.freeSocket(t,r)})),void e.onSocket(t);const a=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);c(a)};if("function"==typeof this.callback){this.promisifiedCallback||(this.callback.length>=3?(u("Converting legacy callback function to promise"),this.promisifiedCallback=a.default(this.callback)):this.promisifiedCallback=this.callback),"number"==typeof s&&s>0&&(n=setTimeout(l,s)),"port"in r&&"number"!=typeof r.port&&(r.port=Number(r.port));try{u("Resolving socket for %o request: %o",r.protocol,`${e.method} ${e.path}`),Promise.resolve(this.promisifiedCallback(e,r)).then(f,d)}catch(e){Promise.reject(e).catch(d)}}else c(new Error("`callback` is not defined"))}freeSocket(e,t){u("Freeing socket %o %o",e.constructor.name,t),e.destroy()}destroy(){u("Destroying agent %o",this.constructor.name)}}e.Agent=t,e.prototype=e.Agent.prototype}(c||(c={})),e.exports=c},304:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(t,r){return new Promise(((o,n)=>{e.call(this,t,r,((e,t)=>{e?n(e):o(t)}))}))}}},370:function(e,t,r){"use strict";var o=this&&this.__awaiter||function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{i(o.next(e))}catch(e){s(e)}}function u(e){try{i(o.throw(e))}catch(e){s(e)}}function i(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,u)}i((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(r(808)),a=n(r(404)),u=n(r(310)),i=n(r(374)),c=n(r(46)),l=r(54),d=(0,i.default)("http-proxy-agent");class f extends l.Agent{constructor(e){let t;if(t="string"==typeof e?u.default.parse(e):e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");d("Creating new HttpProxyAgent instance: %o",t),super(t);const r=Object.assign({},t);var o;this.secureProxy=t.secureProxy||"string"==typeof(o=r.protocol)&&/^https:?$/i.test(o),r.host=r.hostname||r.host,"string"==typeof r.port&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,t){return o(this,void 0,void 0,(function*(){const{proxy:r,secureProxy:o}=this,n=u.default.parse(e.path);let i;if(n.protocol||(n.protocol="http:"),n.hostname||(n.hostname=t.hostname||t.host||null),null==n.port&&(t.port,1)&&(n.port=String(t.port)),"80"===n.port&&(n.port=""),e.path=u.default.format(n),r.auth&&e.setHeader("Proxy-Authorization",`Basic ${Buffer.from(r.auth).toString("base64")}`),o?(d("Creating `tls.Socket`: %o",r),i=a.default.connect(r)):(d("Creating `net.Socket`: %o",r),i=s.default.connect(r)),e._header){let t,r;d("Regenerating stored HTTP header string for request"),e._header=null,e._implicitHeader(),e.output&&e.output.length>0?(d("Patching connection write() output buffer with updated header"),t=e.output[0],r=t.indexOf("\r\n\r\n")+4,e.output[0]=e._header+t.substring(r),d("Output buffer: %o",e.output)):e.outputData&&e.outputData.length>0&&(d("Patching connection write() output buffer with updated header"),t=e.outputData[0].data,r=t.indexOf("\r\n\r\n")+4,e.outputData[0].data=e._header+t.substring(r),d("Output buffer: %o",e.outputData[0].data))}return yield(0,c.default)(i,"connect"),i}))}}t.default=f},201:function(e,t,r){"use strict";const o=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(370));function n(e){return new o.default(e)}!function(e){e.HttpProxyAgent=o.default,e.prototype=o.default.prototype}(n||(n={})),e.exports=n},146:function(e,t,r){"use strict";var o=this&&this.__awaiter||function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function a(e){try{i(o.next(e))}catch(e){s(e)}}function u(e){try{i(o.throw(e))}catch(e){s(e)}}function i(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,u)}i((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=n(r(808)),a=n(r(404)),u=n(r(310)),i=n(r(491)),c=n(r(374)),l=r(54),d=n(r(829)),f=c.default("https-proxy-agent:agent");class p extends l.Agent{constructor(e){let t;if(t="string"==typeof e?u.default.parse(e):e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");f("creating new HttpsProxyAgent instance: %o",t),super(t);const r=Object.assign({},t);var o;this.secureProxy=t.secureProxy||"string"==typeof(o=r.protocol)&&/^https:?$/i.test(o),r.host=r.hostname||r.host,"string"==typeof r.port&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,t){return o(this,void 0,void 0,(function*(){const{proxy:r,secureProxy:o}=this;let n;o?(f("Creating `tls.Socket`: %o",r),n=a.default.connect(r)):(f("Creating `net.Socket`: %o",r),n=s.default.connect(r));const u=Object.assign({},r.headers);let c=`CONNECT ${t.host}:${t.port} HTTP/1.1\r\n`;r.auth&&(u["Proxy-Authorization"]=`Basic ${Buffer.from(r.auth).toString("base64")}`);let{host:l,port:p,secureEndpoint:g}=t;(function(e,t){return Boolean(!t&&80===e||t&&443===e)})(p,g)||(l+=`:${p}`),u.Host=l,u.Connection="close";for(const e of Object.keys(u))c+=`${e}: ${u[e]}\r\n`;const v=d.default(n);n.write(`${c}\r\n`);const{statusCode:m,buffered:y}=yield v;if(200===m){if(e.once("socket",h),t.secureEndpoint){f("Upgrading socket connection to TLS");const e=t.servername||t.host;return a.default.connect(Object.assign(Object.assign({},function(e,...t){const r={};let o;for(o in e)t.includes(o)||(r[o]=e[o]);return r}(t,"host","hostname","path","port")),{socket:n,servername:e}))}return n}n.destroy();const b=new s.default.Socket({writable:!1});return b.readable=!0,e.once("socket",(e=>{f("replaying proxy buffer for failed request"),i.default(e.listenerCount("data")>0),e.push(y),e.push(null)})),b}))}}function h(e){e.resume()}t.default=p},18:function(e,t,r){"use strict";const o=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(r(146));function n(e){return new o.default(e)}!function(e){e.HttpsProxyAgent=o.default,e.prototype=o.default.prototype}(n||(n={})),e.exports=n},829:function(e,t,r){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=o(r(374)).default("https-proxy-agent:parse-proxy-response");t.default=function(e){return new Promise(((t,r)=>{let o=0;const s=[];function a(){const r=e.read();r?function(e){s.push(e),o+=e.length;const r=Buffer.concat(s,o);if(-1===r.indexOf("\r\n\r\n"))return n("have not received end of HTTP headers yet..."),void a();const u=r.toString("ascii",0,r.indexOf("\r\n")),i=+u.split(" ")[1];n("got proxy server response: %o",u),t({statusCode:i,buffered:r})}(r):e.once("readable",a)}function u(e){n("onclose had error %o",e)}function i(){n("onend")}e.on("error",(function t(o){e.removeListener("end",i),e.removeListener("error",t),e.removeListener("close",u),e.removeListener("readable",a),n("onerror %o",o),r(o)})),e.on("close",u),e.on("end",i),a()}))}},539:function(e,t,r){"use strict";var o,n=this&&this.__extends||(o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},o(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),s=this&&this.__assign||function(){return s=Object.assign||function(e){for(var t,r=1,o=arguments.length;r=300&&o.statusCode<400&&e.followRedirects&&e.followRedirects>0&&o.headers.location){var s=o.headers.location;s.startsWith("/")&&(s=(0,i.format)({protocol:n.protocol,hostname:n.hostname,port:n.port,pathname:s})),r(m(function(e){for(var t=[],r=1;r=100&&a<200||204===a||304===a))){var p={flush:l.constants.Z_SYNC_FLUSH,finishFlush:l.constants.Z_SYNC_FLUSH};if("gzip"===f){var g=l.createGunzip(p);u.pipe(g),c=g}else if("deflate"===f){var v=l.createInflate(p);u.pipe(v),c=v}}var m=[];c.on("data",(function(e){return m.push(e)})),c.on("end",(function(){if(!d){if(d=!0,e.followRedirects>0&&(u.statusCode>=300&&u.statusCode<=303||307===u.statusCode)){var r=u.headers.location;if(r.startsWith("/")){var s=(0,i.parse)(e.url);r=(0,i.format)({protocol:s.protocol,hostname:s.hostname,port:s.port,pathname:r})}if(r){var a={type:e.type,url:r,user:e.user,password:e.password,headers:e.headers,timeout:e.timeout,followRedirects:e.followRedirects-1,data:e.data,token:e.token};return void(0,t.xhr)(a).then(o,n)}}var c=Buffer.concat(m),l={responseText:c.toString(),body:c,status:u.statusCode,headers:u.headers||{}};u.statusCode>=200&&u.statusCode<300||1223===u.statusCode?o(l):n(l)}})),c.on("error",(function(t){var r;r=y.is(t)?t:{responseText:h("error","Unable to access {0}. Error: {1}",e.url,t.message),body:Buffer.concat(m),status:500,headers:{}},d=!0,n(r)})),e.token&&(e.token.isCancellationRequested&&c.destroy(new y),e.token.onCancellationRequested((function(){c.destroy(new y)})))}))}),(function(t){var r;return r=y.is(t)?t:{responseText:e.agent?h("error.cannot.connect.proxy","Unable to connect to {0} through a proxy. Error: {1}",e.url,t.message):h("error.cannot.connect","Unable to connect to {0}. Error: {1}",e.url,t.message),body:Buffer.concat([]),status:404,headers:{}},Promise.reject(r)}))},t.getErrorStatusDescription=function(e){if(!(e<400))switch(e){case 400:return h("status.400","Bad request. The request cannot be fulfilled due to bad syntax.");case 401:return h("status.401","Unauthorized. The server is refusing to respond.");case 403:return h("status.403","Forbidden. The server is refusing to respond.");case 404:return h("status.404","Not Found. The requested location could not be found.");case 405:return h("status.405","Method not allowed. A request was made using a request method not supported by that location.");case 406:return h("status.406","Not Acceptable. The server can only generate a response that is not accepted by the client.");case 407:return h("status.407","Proxy Authentication Required. The client must first authenticate itself with the proxy.");case 408:return h("status.408","Request Timeout. The server timed out waiting for the request.");case 409:return h("status.409","Conflict. The request could not be completed because of a conflict in the request.");case 410:return h("status.410","Gone. The requested page is no longer available.");case 411:return h("status.411",'Length Required. The "Content-Length" is not defined.');case 412:return h("status.412","Precondition Failed. The precondition given in the request evaluated to false by the server.");case 413:return h("status.413","Request Entity Too Large. The server will not accept the request, because the request entity is too large.");case 414:return h("status.414","Request-URI Too Long. The server will not accept the request, because the URL is too long.");case 415:return h("status.415","Unsupported Media Type. The server will not accept the request, because the media type is not supported.");case 500:return h("status.500","Internal Server Error.");case 501:return h("status.501","Not Implemented. The server either does not recognize the request method, or it lacks the ability to fulfill the request.");case 502:return h("status.502","Bad Gateway. The upstream server did not respond.");case 503:return h("status.503","Service Unavailable. The server is currently unavailable (overloaded or down).");default:return h("status.416","HTTP status code {0}",e)}};var y=function(e){function t(){var r=e.call(this,"The user aborted a request")||this;return r.name="AbortError",Object.setPrototypeOf(r,t.prototype),r}return n(t,e),t.is=function(e){return e instanceof t},t}(Error)},800:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.config=t.loadMessageBundle=t.localize=t.format=t.setPseudo=t.isPseudo=t.isDefined=t.BundleFormat=t.MessageFormat=void 0;var o,n,s,a=r(926);function u(e){return void 0!==e}function i(e,r){return t.isPseudo&&(e="["+e.replace(/[aouei]/g,"$&$&")+"]"),0===r.length?e:e.replace(/\{(\d+)\}/g,(function(e,t){var o=t[0],n=r[o],s=e;return"string"==typeof n?s=n:"number"!=typeof n&&"boolean"!=typeof n&&null!=n||(s=String(n)),s}))}(s=t.MessageFormat||(t.MessageFormat={})).file="file",s.bundle="bundle",s.both="both",(n=t.BundleFormat||(t.BundleFormat={})).standalone="standalone",n.languagePack="languagePack",function(e){e.is=function(e){var t=e;return t&&u(t.key)&&u(t.comment)}}(o||(o={})),t.isDefined=u,t.isPseudo=!1,t.setPseudo=function(e){t.isPseudo=e},t.format=i,t.localize=function(e,t){for(var r=[],o=2;o{"use strict";var r;function o(){if(void 0===r)throw new Error("No runtime abstraction layer installed");return r}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.install=function(e){if(void 0===e)throw new Error("No runtime abstraction layer provided");r=e}}(o||(o={})),t.default=o},472:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.config=t.loadMessageBundle=t.BundleFormat=t.MessageFormat=void 0;var o=r(17),n=r(147),s=r(926),a=r(800),u=r(800);Object.defineProperty(t,"MessageFormat",{enumerable:!0,get:function(){return u.MessageFormat}}),Object.defineProperty(t,"BundleFormat",{enumerable:!0,get:function(){return u.BundleFormat}});var i,c,l=Object.prototype.toString;function d(e){return"[object Number]"===l.call(e)}function f(e){return"[object String]"===l.call(e)}function p(e){return JSON.parse(n.readFileSync(e,"utf8"))}function h(e){return function(t,r){for(var o=[],n=2;n=e.length?void console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: ".concat(new Error("").stack)):(0,a.format)(e[t],o):f(r)?(console.warn("Message ".concat(r," didn't get externalized correctly.")),(0,a.format)(r,o)):void console.error("Broken localize call found. Stacktrace is\n: ".concat(new Error("").stack))}}function g(e,t){return i[e]=t,t}function v(e){try{return function(e){var t=p(o.join(e,"nls.metadata.json")),r=Object.create(null);for(var n in t){var s=t[n];r[n]=s.messages}return r}(e)}catch(e){return void console.log("Generating default bundle from meta data failed.",e)}}function m(e,t){var r;if(!0===c.languagePackSupport&&void 0!==c.cacheRoot&&void 0!==c.languagePackId&&void 0!==c.translationsConfigFile&&void 0!==c.translationsConfig)try{r=function(e,t){var r,s,a,u=o.join(c.cacheRoot,"".concat(e.id,"-").concat(e.hash,".json")),i=!1,l=!1;try{return r=JSON.parse(n.readFileSync(u,{encoding:"utf8",flag:"r"})),s=u,a=new Date,n.utimes(s,a,a,(function(){})),r}catch(e){if("ENOENT"===e.code)l=!0;else{if(!(e instanceof SyntaxError))throw e;console.log("Syntax error parsing message bundle: ".concat(e.message,".")),n.unlink(u,(function(e){e&&console.error("Deleting corrupted bundle ".concat(u," failed."))})),i=!0}}if(r=function(e,t){var r=c.translationsConfig[e.id];if(r){var n=p(r).contents,s=p(o.join(t,"nls.metadata.json")),a=Object.create(null);for(var u in s){var i=s[u],l=n["".concat(e.outDir,"/").concat(u)];if(l){for(var d=[],h=0;h0?t.substring(0,s):void 0}if(void 0===t&&(r=o.join(e,"nls.bundle.json"),n.existsSync(r)))return r}(t);if(s)try{return p(s)}catch(e){console.log("Loading in the box message bundle failed.",e)}r=v(t)}return r}function y(e){if(!e)return a.localize;var t=o.extname(e);if(t&&(e=e.substr(0,e.length-t.length)),c.messageFormat===a.MessageFormat.both||c.messageFormat===a.MessageFormat.bundle){var r=function(e){for(var t,r=o.dirname(e);t=o.join(r,"nls.metadata.header.json"),!n.existsSync(t);){var s=o.dirname(r);if(s===r){t=void 0;break}r=s}return t}(e);if(r){var s=o.dirname(r),u=i[s];if(void 0===u)try{var l=JSON.parse(n.readFileSync(r,"utf8"));try{var d=m(l,s);u=g(s,d?{header:l,nlsBundle:d}:null)}catch(e){console.error("Failed to load nls bundle",e),u=g(s,null)}}catch(e){console.error("Failed to read header file",e),u=g(s,null)}if(u){var f=e.substr(s.length+1).replace(/\\/g,"/"),v=u.nlsBundle[f];return void 0===v?(console.error("Messages for file ".concat(e," not found. See console for details.")),function(){return"Messages not found."}):h(v)}}}if(c.messageFormat===a.MessageFormat.both||c.messageFormat===a.MessageFormat.file)try{var y=p(function(e){var t;if(c.cacheLanguageResolution&&t);else{if(a.isPseudo||!c.language)t=".nls.json";else for(var r=c.language;r;){var o=".nls."+r+".json";if(n.existsSync(e+o)){t=o;break}var s=r.lastIndexOf("-");s>0?r=r.substring(0,s):(t=".nls.json",r=null)}c.cacheLanguageResolution}return e+t}(e));return Array.isArray(y)?h(y):(0,a.isDefined)(y.messages)&&(0,a.isDefined)(y.keys)?h(y.messages):(console.error("String bundle '".concat(e,"' uses an unsupported format.")),function(){return"File bundle has unsupported format. See console for details"})}catch(e){"ENOENT"!==e.code&&console.error("Failed to load single file bundle",e)}return console.error("Failed to load message bundle for file ".concat(e)),function(){return"Failed to load message bundle. See console for details."}}function b(e){return e&&(f(e.locale)&&(c.locale=e.locale.toLowerCase(),c.language=c.locale,i=Object.create(null)),void 0!==e.messageFormat&&(c.messageFormat=e.messageFormat),e.bundleFormat===a.BundleFormat.standalone&&!0===c.languagePackSupport&&(c.languagePackSupport=!1)),(0,a.setPseudo)("pseudo"===c.locale),y}!function(){if(c={locale:void 0,language:void 0,languagePackSupport:!1,cacheLanguageResolution:!0,messageFormat:a.MessageFormat.bundle},f(process.env.VSCODE_NLS_CONFIG))try{var e=JSON.parse(process.env.VSCODE_NLS_CONFIG),t=void 0;if(e.availableLanguages){var r=e.availableLanguages["*"];f(r)&&(t=r)}if(f(e.locale)&&(c.locale=e.locale.toLowerCase()),void 0===t?c.language=c.locale:"en"!==t&&(c.language=t),function(e){return!0===e||!1===e}(e._languagePackSupport)&&(c.languagePackSupport=e._languagePackSupport),f(e._cacheRoot)&&(c.cacheRoot=e._cacheRoot),f(e._languagePackId)&&(c.languagePackId=e._languagePackId),f(e._translationsConfigFile)){c.translationsConfigFile=e._translationsConfigFile;try{c.translationsConfig=p(c.translationsConfigFile)}catch(t){if(e._corruptedFile){var s=o.dirname(e._corruptedFile);n.exists(s,(function(t){t&&n.writeFile(e._corruptedFile,"corrupted","utf8",(function(e){console.error(e)}))}))}}}}catch(e){}(0,a.setPseudo)("pseudo"===c.locale),i=Object.create(null)}(),t.loadMessageBundle=y,t.config=b,s.default.install(Object.freeze({loadMessageBundle:y,config:b}))},374:(e,t)=>{function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return r}},491:e=>{"use strict";e.exports=__nccwpck_require__(9491)},361:e=>{"use strict";e.exports=__nccwpck_require__(2361)},147:e=>{"use strict";e.exports=__nccwpck_require__(7147)},685:e=>{"use strict";e.exports=__nccwpck_require__(3685)},687:e=>{"use strict";e.exports=__nccwpck_require__(5687)},808:e=>{"use strict";e.exports=__nccwpck_require__(1808)},17:e=>{"use strict";e.exports=__nccwpck_require__(1017)},404:e=>{"use strict";e.exports=__nccwpck_require__(4404)},310:e=>{"use strict";e.exports=__nccwpck_require__(7310)},796:e=>{"use strict";e.exports=__nccwpck_require__(9796)}},t={},r=function r(o){var n=t[o];if(void 0!==n)return n.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,r),s.exports}(539),o=exports;for(var n in r)o[n]=r[n];r.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})(); /***/ }), /***/ 447: /***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => { "use strict"; // ESM COMPAT FLAG __nccwpck_require__.r(__webpack_exports__); // EXPORTS __nccwpck_require__.d(__webpack_exports__, { "ClientCapabilities": () => (/* reexport */ ClientCapabilities), "CodeAction": () => (/* reexport */ CodeAction), "CodeActionContext": () => (/* reexport */ CodeActionContext), "CodeActionKind": () => (/* reexport */ CodeActionKind), "Color": () => (/* reexport */ Color), "ColorInformation": () => (/* reexport */ ColorInformation), "ColorPresentation": () => (/* reexport */ ColorPresentation), "Command": () => (/* reexport */ Command), "CompletionItem": () => (/* reexport */ CompletionItem), "CompletionItemKind": () => (/* reexport */ CompletionItemKind), "CompletionItemTag": () => (/* reexport */ CompletionItemTag), "CompletionList": () => (/* reexport */ CompletionList), "Diagnostic": () => (/* reexport */ Diagnostic), "DiagnosticSeverity": () => (/* reexport */ DiagnosticSeverity), "DocumentHighlight": () => (/* reexport */ DocumentHighlight), "DocumentHighlightKind": () => (/* reexport */ DocumentHighlightKind), "DocumentLink": () => (/* reexport */ DocumentLink), "DocumentSymbol": () => (/* reexport */ DocumentSymbol), "DocumentUri": () => (/* reexport */ DocumentUri), "ErrorCode": () => (/* reexport */ ErrorCode), "FoldingRange": () => (/* reexport */ FoldingRange), "FoldingRangeKind": () => (/* reexport */ FoldingRangeKind), "Hover": () => (/* reexport */ Hover), "InsertTextFormat": () => (/* reexport */ InsertTextFormat), "Location": () => (/* reexport */ Location), "MarkedString": () => (/* reexport */ MarkedString), "MarkupContent": () => (/* reexport */ MarkupContent), "MarkupKind": () => (/* reexport */ MarkupKind), "Position": () => (/* reexport */ Position), "Range": () => (/* reexport */ Range), "SchemaDraft": () => (/* reexport */ SchemaDraft), "SelectionRange": () => (/* reexport */ SelectionRange), "SymbolInformation": () => (/* reexport */ SymbolInformation), "SymbolKind": () => (/* reexport */ SymbolKind), "TextDocument": () => (/* reexport */ main_TextDocument), "TextDocumentEdit": () => (/* reexport */ TextDocumentEdit), "TextEdit": () => (/* reexport */ TextEdit), "VersionedTextDocumentIdentifier": () => (/* reexport */ VersionedTextDocumentIdentifier), "WorkspaceEdit": () => (/* reexport */ WorkspaceEdit), "getLanguageService": () => (/* binding */ getLanguageService) }); ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/impl/scanner.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */ function createScanner(text, ignoreTrivia = false) { const len = text.length; let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; function scanHexDigits(count, exact) { let digits = 0; let value = 0; while (digits < count || !exact) { let ch = text.charCodeAt(pos); if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { value = value * 16 + ch - 48 /* CharacterCodes._0 */; } else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; } else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; } else { break; } pos++; digits++; } if (digits < count) { value = -1; } return value; } function setPosition(newPosition) { pos = newPosition; value = ''; tokenOffset = 0; token = 16 /* SyntaxKind.Unknown */; scanError = 0 /* ScanError.None */; } function scanNumber() { let start = pos; if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { pos++; } else { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { pos++; if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; return text.substring(start, pos); } } let end = pos; if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { pos++; if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { pos++; } if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } end = pos; } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; } } return text.substring(start, end); } function scanString() { let result = '', start = pos; while (true) { if (pos >= len) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch = text.charCodeAt(pos); if (ch === 34 /* CharacterCodes.doubleQuote */) { result += text.substring(start, pos); pos++; break; } if (ch === 92 /* CharacterCodes.backslash */) { result += text.substring(start, pos); pos++; if (pos >= len) { scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch2 = text.charCodeAt(pos++); switch (ch2) { case 34 /* CharacterCodes.doubleQuote */: result += '\"'; break; case 92 /* CharacterCodes.backslash */: result += '\\'; break; case 47 /* CharacterCodes.slash */: result += '/'; break; case 98 /* CharacterCodes.b */: result += '\b'; break; case 102 /* CharacterCodes.f */: result += '\f'; break; case 110 /* CharacterCodes.n */: result += '\n'; break; case 114 /* CharacterCodes.r */: result += '\r'; break; case 116 /* CharacterCodes.t */: result += '\t'; break; case 117 /* CharacterCodes.u */: const ch3 = scanHexDigits(4, true); if (ch3 >= 0) { result += String.fromCharCode(ch3); } else { scanError = 4 /* ScanError.InvalidUnicode */; } break; default: scanError = 5 /* ScanError.InvalidEscapeCharacter */; } start = pos; continue; } if (ch >= 0 && ch <= 0x1f) { if (isLineBreak(ch)) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } else { scanError = 6 /* ScanError.InvalidCharacter */; // mark as error but continue with string } } pos++; } return result; } function scanNext() { value = ''; scanError = 0 /* ScanError.None */; tokenOffset = pos; lineStartOffset = lineNumber; prevTokenLineStartOffset = tokenLineStartOffset; if (pos >= len) { // at the end tokenOffset = len; return token = 17 /* SyntaxKind.EOF */; } let code = text.charCodeAt(pos); // trivia: whitespace if (isWhiteSpace(code)) { do { pos++; value += String.fromCharCode(code); code = text.charCodeAt(pos); } while (isWhiteSpace(code)); return token = 15 /* SyntaxKind.Trivia */; } // trivia: newlines if (isLineBreak(code)) { pos++; value += String.fromCharCode(code); if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; value += '\n'; } lineNumber++; tokenLineStartOffset = pos; return token = 14 /* SyntaxKind.LineBreakTrivia */; } switch (code) { // tokens: []{}:, case 123 /* CharacterCodes.openBrace */: pos++; return token = 1 /* SyntaxKind.OpenBraceToken */; case 125 /* CharacterCodes.closeBrace */: pos++; return token = 2 /* SyntaxKind.CloseBraceToken */; case 91 /* CharacterCodes.openBracket */: pos++; return token = 3 /* SyntaxKind.OpenBracketToken */; case 93 /* CharacterCodes.closeBracket */: pos++; return token = 4 /* SyntaxKind.CloseBracketToken */; case 58 /* CharacterCodes.colon */: pos++; return token = 6 /* SyntaxKind.ColonToken */; case 44 /* CharacterCodes.comma */: pos++; return token = 5 /* SyntaxKind.CommaToken */; // strings case 34 /* CharacterCodes.doubleQuote */: pos++; value = scanString(); return token = 10 /* SyntaxKind.StringLiteral */; // comments case 47 /* CharacterCodes.slash */: const start = pos - 1; // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; while (pos < len) { if (isLineBreak(text.charCodeAt(pos))) { break; } pos++; } value = text.substring(start, pos); return token = 12 /* SyntaxKind.LineCommentTrivia */; } // Multi-line comment if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { pos += 2; const safeLength = len - 1; // For lookahead. let commentClosed = false; while (pos < safeLength) { const ch = text.charCodeAt(pos); if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; commentClosed = true; break; } pos++; if (isLineBreak(ch)) { if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; } lineNumber++; tokenLineStartOffset = pos; } } if (!commentClosed) { pos++; scanError = 1 /* ScanError.UnexpectedEndOfComment */; } value = text.substring(start, pos); return token = 13 /* SyntaxKind.BlockCommentTrivia */; } // just a single slash value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; // numbers case 45 /* CharacterCodes.minus */: value += String.fromCharCode(code); pos++; if (pos === len || !isDigit(text.charCodeAt(pos))) { return token = 16 /* SyntaxKind.Unknown */; } // found a minus, followed by a number so // we fall through to proceed with scanning // numbers case 48 /* CharacterCodes._0 */: case 49 /* CharacterCodes._1 */: case 50 /* CharacterCodes._2 */: case 51 /* CharacterCodes._3 */: case 52 /* CharacterCodes._4 */: case 53 /* CharacterCodes._5 */: case 54 /* CharacterCodes._6 */: case 55 /* CharacterCodes._7 */: case 56 /* CharacterCodes._8 */: case 57 /* CharacterCodes._9 */: value += scanNumber(); return token = 11 /* SyntaxKind.NumericLiteral */; // literals and unknown symbols default: // is a literal? Read the full word. while (pos < len && isUnknownContentCharacter(code)) { pos++; code = text.charCodeAt(pos); } if (tokenOffset !== pos) { value = text.substring(tokenOffset, pos); // keywords: true, false, null switch (value) { case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; case 'null': return token = 7 /* SyntaxKind.NullKeyword */; } return token = 16 /* SyntaxKind.Unknown */; } // some value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; } } function isUnknownContentCharacter(code) { if (isWhiteSpace(code) || isLineBreak(code)) { return false; } switch (code) { case 125 /* CharacterCodes.closeBrace */: case 93 /* CharacterCodes.closeBracket */: case 123 /* CharacterCodes.openBrace */: case 91 /* CharacterCodes.openBracket */: case 34 /* CharacterCodes.doubleQuote */: case 58 /* CharacterCodes.colon */: case 44 /* CharacterCodes.comma */: case 47 /* CharacterCodes.slash */: return false; } return true; } function scanNextNonTrivia() { let result; do { result = scanNext(); } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); return result; } return { setPosition: setPosition, getPosition: () => pos, scan: ignoreTrivia ? scanNextNonTrivia : scanNext, getToken: () => token, getTokenValue: () => value, getTokenOffset: () => tokenOffset, getTokenLength: () => pos - tokenOffset, getTokenStartLine: () => lineStartOffset, getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, getTokenError: () => scanError, }; } function isWhiteSpace(ch) { return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */; } function isLineBreak(ch) { return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */; } function isDigit(ch) { return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */; } var CharacterCodes; (function (CharacterCodes) { CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; CharacterCodes[CharacterCodes["space"] = 32] = "space"; CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; CharacterCodes[CharacterCodes["a"] = 97] = "a"; CharacterCodes[CharacterCodes["b"] = 98] = "b"; CharacterCodes[CharacterCodes["c"] = 99] = "c"; CharacterCodes[CharacterCodes["d"] = 100] = "d"; CharacterCodes[CharacterCodes["e"] = 101] = "e"; CharacterCodes[CharacterCodes["f"] = 102] = "f"; CharacterCodes[CharacterCodes["g"] = 103] = "g"; CharacterCodes[CharacterCodes["h"] = 104] = "h"; CharacterCodes[CharacterCodes["i"] = 105] = "i"; CharacterCodes[CharacterCodes["j"] = 106] = "j"; CharacterCodes[CharacterCodes["k"] = 107] = "k"; CharacterCodes[CharacterCodes["l"] = 108] = "l"; CharacterCodes[CharacterCodes["m"] = 109] = "m"; CharacterCodes[CharacterCodes["n"] = 110] = "n"; CharacterCodes[CharacterCodes["o"] = 111] = "o"; CharacterCodes[CharacterCodes["p"] = 112] = "p"; CharacterCodes[CharacterCodes["q"] = 113] = "q"; CharacterCodes[CharacterCodes["r"] = 114] = "r"; CharacterCodes[CharacterCodes["s"] = 115] = "s"; CharacterCodes[CharacterCodes["t"] = 116] = "t"; CharacterCodes[CharacterCodes["u"] = 117] = "u"; CharacterCodes[CharacterCodes["v"] = 118] = "v"; CharacterCodes[CharacterCodes["w"] = 119] = "w"; CharacterCodes[CharacterCodes["x"] = 120] = "x"; CharacterCodes[CharacterCodes["y"] = 121] = "y"; CharacterCodes[CharacterCodes["z"] = 122] = "z"; CharacterCodes[CharacterCodes["A"] = 65] = "A"; CharacterCodes[CharacterCodes["B"] = 66] = "B"; CharacterCodes[CharacterCodes["C"] = 67] = "C"; CharacterCodes[CharacterCodes["D"] = 68] = "D"; CharacterCodes[CharacterCodes["E"] = 69] = "E"; CharacterCodes[CharacterCodes["F"] = 70] = "F"; CharacterCodes[CharacterCodes["G"] = 71] = "G"; CharacterCodes[CharacterCodes["H"] = 72] = "H"; CharacterCodes[CharacterCodes["I"] = 73] = "I"; CharacterCodes[CharacterCodes["J"] = 74] = "J"; CharacterCodes[CharacterCodes["K"] = 75] = "K"; CharacterCodes[CharacterCodes["L"] = 76] = "L"; CharacterCodes[CharacterCodes["M"] = 77] = "M"; CharacterCodes[CharacterCodes["N"] = 78] = "N"; CharacterCodes[CharacterCodes["O"] = 79] = "O"; CharacterCodes[CharacterCodes["P"] = 80] = "P"; CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; CharacterCodes[CharacterCodes["R"] = 82] = "R"; CharacterCodes[CharacterCodes["S"] = 83] = "S"; CharacterCodes[CharacterCodes["T"] = 84] = "T"; CharacterCodes[CharacterCodes["U"] = 85] = "U"; CharacterCodes[CharacterCodes["V"] = 86] = "V"; CharacterCodes[CharacterCodes["W"] = 87] = "W"; CharacterCodes[CharacterCodes["X"] = 88] = "X"; CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; })(CharacterCodes || (CharacterCodes = {})); ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/impl/string-intern.js const cachedSpaces = new Array(20).fill(0).map((_, index) => { return ' '.repeat(index); }); const maxCachedValues = 200; const cachedBreakLinesWithSpaces = { ' ': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + ' '.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + ' '.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + ' '.repeat(index); }), }, '\t': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + '\t'.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + '\t'.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + '\t'.repeat(index); }), } }; const supportedEols = ['\n', '\r', '\r\n']; ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/impl/format.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function format_format(documentText, range, options) { let initialIndentLevel; let formatText; let formatTextStart; let rangeStart; let rangeEnd; if (range) { rangeStart = range.offset; rangeEnd = rangeStart + range.length; formatTextStart = rangeStart; while (formatTextStart > 0 && !format_isEOL(documentText, formatTextStart - 1)) { formatTextStart--; } let endOffset = rangeEnd; while (endOffset < documentText.length && !format_isEOL(documentText, endOffset)) { endOffset++; } formatText = documentText.substring(formatTextStart, endOffset); initialIndentLevel = computeIndentLevel(formatText, options); } else { formatText = documentText; initialIndentLevel = 0; formatTextStart = 0; rangeStart = 0; rangeEnd = documentText.length; } const eol = getEOL(options, documentText); const eolFastPathSupported = supportedEols.includes(eol); let numberLineBreaks = 0; let indentLevel = 0; let indentValue; if (options.insertSpaces) { indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4); } else { indentValue = '\t'; } const indentType = indentValue === '\t' ? '\t' : ' '; let scanner = createScanner(formatText, false); let hasError = false; function newLinesAndIndent() { if (numberLineBreaks > 1) { return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); } const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) { return eol + repeat(indentValue, initialIndentLevel + indentLevel); } if (amountOfSpaces <= 0) { return eol; } return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; } function scanNext() { let token = scanner.scan(); numberLineBreaks = 0; while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { numberLineBreaks += 1; } else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { numberLineBreaks = 1; } token = scanner.scan(); } hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; return token; } const editOperations = []; function addEdit(text, startOffset, endOffset) { if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); } } let firstToken = scanNext(); if (options.keepLines && numberLineBreaks > 0) { addEdit(repeat(eol, numberLineBreaks), 0, 0); } if (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenStart = scanner.getTokenOffset() + formatTextStart; let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel); addEdit(initialIndent, formatTextStart, firstTokenStart); } while (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; let secondToken = scanNext(); let replaceContent = ''; let needsLineBreak = false; while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { let commentTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart); firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; replaceContent = needsLineBreak ? newLinesAndIndent() : ''; secondToken = scanNext(); } if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = cachedSpaces[1]; } } else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = cachedSpaces[1]; } } else { switch (firstToken) { case 3 /* SyntaxKind.OpenBracketToken */: case 1 /* SyntaxKind.OpenBraceToken */: indentLevel++; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = cachedSpaces[1]; } break; case 5 /* SyntaxKind.CommaToken */: if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = cachedSpaces[1]; } break; case 12 /* SyntaxKind.LineCommentTrivia */: replaceContent = newLinesAndIndent(); break; case 13 /* SyntaxKind.BlockCommentTrivia */: if (numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = cachedSpaces[1]; } break; case 6 /* SyntaxKind.ColonToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = cachedSpaces[1]; } break; case 10 /* SyntaxKind.StringLiteral */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { replaceContent = ''; } break; case 7 /* SyntaxKind.NullKeyword */: case 8 /* SyntaxKind.TrueKeyword */: case 9 /* SyntaxKind.FalseKeyword */: case 11 /* SyntaxKind.NumericLiteral */: case 2 /* SyntaxKind.CloseBraceToken */: case 4 /* SyntaxKind.CloseBracketToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { replaceContent = cachedSpaces[1]; } else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { hasError = true; } } break; case 16 /* SyntaxKind.Unknown */: hasError = true; break; } if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { replaceContent = newLinesAndIndent(); } } if (secondToken === 17 /* SyntaxKind.EOF */) { if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { replaceContent = options.insertFinalNewline ? eol : ''; } } const secondTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(replaceContent, firstTokenEnd, secondTokenStart); firstToken = secondToken; } return editOperations; } function repeat(s, count) { let result = ''; for (let i = 0; i < count; i++) { result += s; } return result; } function computeIndentLevel(content, options) { let i = 0; let nChars = 0; const tabSize = options.tabSize || 4; while (i < content.length) { let ch = content.charAt(i); if (ch === cachedSpaces[1]) { nChars++; } else if (ch === '\t') { nChars += tabSize; } else { break; } i++; } return Math.floor(nChars / tabSize); } function getEOL(options, text) { for (let i = 0; i < text.length; i++) { const ch = text.charAt(i); if (ch === '\r') { if (i + 1 < text.length && text.charAt(i + 1) === '\n') { return '\r\n'; } return '\r'; } else if (ch === '\n') { return '\n'; } } return (options && options.eol) || '\n'; } function format_isEOL(text, offset) { return '\r\n'.indexOf(text.charAt(offset)) !== -1; } ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/impl/parser.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var ParseOptions; (function (ParseOptions) { ParseOptions.DEFAULT = { allowTrailingComma: false }; })(ParseOptions || (ParseOptions = {})); /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ function getLocation(text, position) { const segments = []; // strings or numbers const earlyReturnException = new Object(); let previousNode = undefined; const previousNodeInst = { value: {}, offset: 0, length: 0, type: 'object', parent: undefined }; let isAtPropertyKey = false; function setPreviousNode(value, offset, length, type) { previousNodeInst.value = value; previousNodeInst.offset = offset; previousNodeInst.length = length; previousNodeInst.type = type; previousNodeInst.colonOffset = undefined; previousNode = previousNodeInst; } try { visit(text, { onObjectBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; isAtPropertyKey = position > offset; segments.push(''); // push a placeholder (will be replaced) }, onObjectProperty: (name, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(name, offset, length, 'property'); segments[segments.length - 1] = name; if (position <= offset + length) { throw earlyReturnException; } }, onObjectEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onArrayBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.push(0); }, onArrayEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onLiteralValue: (value, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(value, offset, length, getNodeType(value)); if (position <= offset + length) { throw earlyReturnException; } }, onSeparator: (sep, offset, length) => { if (position <= offset) { throw earlyReturnException; } if (sep === ':' && previousNode && previousNode.type === 'property') { previousNode.colonOffset = offset; isAtPropertyKey = false; previousNode = undefined; } else if (sep === ',') { const last = segments[segments.length - 1]; if (typeof last === 'number') { segments[segments.length - 1] = last + 1; } else { isAtPropertyKey = true; segments[segments.length - 1] = ''; } previousNode = undefined; } } }); } catch (e) { if (e !== earlyReturnException) { throw e; } } return { path: segments, previousNode, isAtPropertyKey, matches: (pattern) => { let k = 0; for (let i = 0; k < pattern.length && i < segments.length; i++) { if (pattern[k] === segments[i] || pattern[k] === '*') { k++; } else if (pattern[k] !== '**') { return false; } } return k === pattern.length; } }; } /** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore always check the errors list to find out if the input was valid. */ function parse(text, errors = [], options = ParseOptions.DEFAULT) { let currentProperty = null; let currentParent = []; const previousParents = []; function onValue(value) { if (Array.isArray(currentParent)) { currentParent.push(value); } else if (currentProperty !== null) { currentParent[currentProperty] = value; } } const visitor = { onObjectBegin: () => { const object = {}; onValue(object); previousParents.push(currentParent); currentParent = object; currentProperty = null; }, onObjectProperty: (name) => { currentProperty = name; }, onObjectEnd: () => { currentParent = previousParents.pop(); }, onArrayBegin: () => { const array = []; onValue(array); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, onArrayEnd: () => { currentParent = previousParents.pop(); }, onLiteralValue: onValue, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); return currentParent[0]; } /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ function parser_parseTree(text, errors = [], options = ParseOptions.DEFAULT) { let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root function ensurePropertyComplete(endOffset) { if (currentParent.type === 'property') { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent; } } function onValue(valueNode) { currentParent.children.push(valueNode); return valueNode; } const visitor = { onObjectBegin: (offset) => { currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); }, onObjectProperty: (name, offset, length) => { currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); }, onObjectEnd: (offset, length) => { ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onArrayBegin: (offset, length) => { currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); }, onArrayEnd: (offset, length) => { currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onLiteralValue: (value, offset, length) => { onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); ensurePropertyComplete(offset + length); }, onSeparator: (sep, offset, length) => { if (currentParent.type === 'property') { if (sep === ':') { currentParent.colonOffset = offset; } else if (sep === ',') { ensurePropertyComplete(offset); } } }, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); const result = currentParent.children[0]; if (result) { delete result.parent; } return result; } /** * Finds the node at the given path in a JSON DOM. */ function parser_findNodeAtLocation(root, path) { if (!root) { return undefined; } let node = root; for (let segment of path) { if (typeof segment === 'string') { if (node.type !== 'object' || !Array.isArray(node.children)) { return undefined; } let found = false; for (const propertyNode of node.children) { if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { node = propertyNode.children[1]; found = true; break; } } if (!found) { return undefined; } } else { const index = segment; if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { return undefined; } node = node.children[index]; } } return node; } /** * Gets the JSON path of the given JSON DOM node */ function getNodePath(node) { if (!node.parent || !node.parent.children) { return []; } const path = getNodePath(node.parent); if (node.parent.type === 'property') { const key = node.parent.children[0].value; path.push(key); } else if (node.parent.type === 'array') { const index = node.parent.children.indexOf(node); if (index !== -1) { path.push(index); } } return path; } /** * Evaluates the JavaScript object of the given JSON DOM node */ function getNodeValue(node) { switch (node.type) { case 'array': return node.children.map(getNodeValue); case 'object': const obj = Object.create(null); for (let prop of node.children) { const valueNode = prop.children[1]; if (valueNode) { obj[prop.children[0].value] = getNodeValue(valueNode); } } return obj; case 'null': case 'string': case 'number': case 'boolean': return node.value; default: return undefined; } } function contains(node, offset, includeRightBound = false) { return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); } /** * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */ function findNodeAtOffset(node, offset, includeRightBound = false) { if (contains(node, offset, includeRightBound)) { const children = node.children; if (Array.isArray(children)) { for (let i = 0; i < children.length && children[i].offset <= offset; i++) { const item = findNodeAtOffset(children[i], offset, includeRightBound); if (item) { return item; } } } return node; } return undefined; } /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ function visit(text, visitor, options = ParseOptions.DEFAULT) { const _scanner = createScanner(text, false); // Important: Only pass copies of this to visitor functions to prevent accidental modification, and // to not affect visitor functions which stored a reference to a previous JSONPath const _jsonPath = []; // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already. // Callbacks are only called when this value is 0. let suppressedCallbacks = 0; function toNoArgVisit(visitFunction) { return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toOneArgVisit(visitFunction) { return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toOneArgVisitWithPath(visitFunction) { return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } function toBeginVisit(visitFunction) { return visitFunction ? () => { if (suppressedCallbacks > 0) { suppressedCallbacks++; } else { let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()); if (cbReturn === false) { suppressedCallbacks = 1; } } } : () => true; } function toEndVisit(visitFunction) { return visitFunction ? () => { if (suppressedCallbacks > 0) { suppressedCallbacks--; } if (suppressedCallbacks === 0) { visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } } : () => true; } const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); const disallowComments = options && options.disallowComments; const allowTrailingComma = options && options.allowTrailingComma; function scanNext() { while (true) { const token = _scanner.scan(); switch (_scanner.getTokenError()) { case 4 /* ScanError.InvalidUnicode */: handleError(14 /* ParseErrorCode.InvalidUnicode */); break; case 5 /* ScanError.InvalidEscapeCharacter */: handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); break; case 3 /* ScanError.UnexpectedEndOfNumber */: handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); break; case 1 /* ScanError.UnexpectedEndOfComment */: if (!disallowComments) { handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); } break; case 2 /* ScanError.UnexpectedEndOfString */: handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); break; case 6 /* ScanError.InvalidCharacter */: handleError(16 /* ParseErrorCode.InvalidCharacter */); break; } switch (token) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: if (disallowComments) { handleError(10 /* ParseErrorCode.InvalidCommentToken */); } else { onComment(); } break; case 16 /* SyntaxKind.Unknown */: handleError(1 /* ParseErrorCode.InvalidSymbol */); break; case 15 /* SyntaxKind.Trivia */: case 14 /* SyntaxKind.LineBreakTrivia */: break; default: return token; } } } function handleError(error, skipUntilAfter = [], skipUntil = []) { onError(error); if (skipUntilAfter.length + skipUntil.length > 0) { let token = _scanner.getToken(); while (token !== 17 /* SyntaxKind.EOF */) { if (skipUntilAfter.indexOf(token) !== -1) { scanNext(); break; } else if (skipUntil.indexOf(token) !== -1) { break; } token = scanNext(); } } } function parseString(isValue) { const value = _scanner.getTokenValue(); if (isValue) { onLiteralValue(value); } else { onObjectProperty(value); // add property name afterwards _jsonPath.push(value); } scanNext(); return true; } function parseLiteral() { switch (_scanner.getToken()) { case 11 /* SyntaxKind.NumericLiteral */: const tokenValue = _scanner.getTokenValue(); let value = Number(tokenValue); if (isNaN(value)) { handleError(2 /* ParseErrorCode.InvalidNumberFormat */); value = 0; } onLiteralValue(value); break; case 7 /* SyntaxKind.NullKeyword */: onLiteralValue(null); break; case 8 /* SyntaxKind.TrueKeyword */: onLiteralValue(true); break; case 9 /* SyntaxKind.FalseKeyword */: onLiteralValue(false); break; default: return false; } scanNext(); return true; } function parseProperty() { if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); return false; } parseString(false); if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { onSeparator(':'); scanNext(); // consume colon if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } } else { handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } _jsonPath.pop(); // remove processed property name return true; } function parseObject() { onObjectBegin(); scanNext(); // consume open brace let needsComma = false; while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (!parseProperty()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onObjectEnd(); if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); } else { scanNext(); // consume close brace } return true; } function parseArray() { onArrayBegin(); scanNext(); // consume open bracket let isFirstElement = true; let needsComma = false; while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (isFirstElement) { _jsonPath.push(0); isFirstElement = false; } else { _jsonPath[_jsonPath.length - 1]++; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onArrayEnd(); if (!isFirstElement) { _jsonPath.pop(); // remove array index } if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); } else { scanNext(); // consume close bracket } return true; } function parseValue() { switch (_scanner.getToken()) { case 3 /* SyntaxKind.OpenBracketToken */: return parseArray(); case 1 /* SyntaxKind.OpenBraceToken */: return parseObject(); case 10 /* SyntaxKind.StringLiteral */: return parseString(true); default: return parseLiteral(); } } scanNext(); if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { if (options.allowEmptyContent) { return true; } handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); } return true; } /** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ function stripComments(text, replaceCh) { let _scanner = createScanner(text), parts = [], kind, offset = 0, pos; do { pos = _scanner.getPosition(); kind = _scanner.scan(); switch (kind) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: case 17 /* SyntaxKind.EOF */: if (offset !== pos) { parts.push(text.substring(offset, pos)); } if (replaceCh !== undefined) { parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); } offset = _scanner.getPosition(); break; } } while (kind !== 17 /* SyntaxKind.EOF */); return parts.join(''); } function getNodeType(value) { switch (typeof value) { case 'boolean': return 'boolean'; case 'number': return 'number'; case 'string': return 'string'; case 'object': { if (!value) { return 'null'; } else if (Array.isArray(value)) { return 'array'; } return 'object'; } default: return 'null'; } } ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/impl/edit.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function removeProperty(text, path, options) { return setProperty(text, path, void 0, options); } function setProperty(text, originalPath, value, options) { const path = originalPath.slice(); const errors = []; const root = parseTree(text, errors); let parent = void 0; let lastSegment = void 0; while (path.length > 0) { lastSegment = path.pop(); parent = findNodeAtLocation(root, path); if (parent === void 0 && value !== void 0) { if (typeof lastSegment === 'string') { value = { [lastSegment]: value }; } else { value = [value]; } } else { break; } } if (!parent) { // empty document if (value === void 0) { // delete throw new Error('Can not delete in empty document'); } return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); } else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { const existing = findNodeAtLocation(parent, [lastSegment]); if (existing !== void 0) { if (value === void 0) { // delete if (!existing.parent) { throw new Error('Malformed AST'); } const propertyIndex = parent.children.indexOf(existing.parent); let removeBegin; let removeEnd = existing.parent.offset + existing.parent.length; if (propertyIndex > 0) { // remove the comma of the previous node let previous = parent.children[propertyIndex - 1]; removeBegin = previous.offset + previous.length; } else { removeBegin = parent.offset + 1; if (parent.children.length > 1) { // remove the comma of the next node let next = parent.children[1]; removeEnd = next.offset; } } return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); } else { // set value of existing property return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); } } else { if (value === void 0) { // delete return []; // property does not exist, nothing to do } const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; let edit; if (index > 0) { let previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } else if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; } return withFormatting(text, edit, options); } } else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { const insertIndex = lastSegment; if (insertIndex === -1) { // Insert const newProperty = `${JSON.stringify(value)}`; let edit; if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { const previous = parent.children[parent.children.length - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else if (value === void 0 && parent.children.length >= 0) { // Removal const removalIndex = lastSegment; const toRemove = parent.children[removalIndex]; let edit; if (parent.children.length === 1) { // only item edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; } else if (parent.children.length - 1 === removalIndex) { // last item let previous = parent.children[removalIndex - 1]; let offset = previous.offset + previous.length; let parentEndOffset = parent.offset + parent.length; edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; } else { edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; } return withFormatting(text, edit, options); } else if (value !== void 0) { let edit; const newProperty = `${JSON.stringify(value)}`; if (!options.isArrayInsertion && parent.children.length > lastSegment) { const toModify = parent.children[lastSegment]; edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; } else if (parent.children.length === 0 || lastSegment === 0) { edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; } else { const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; const previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else { throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); } } else { throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); } } function withFormatting(text, edit, options) { if (!options.formattingOptions) { return [edit]; } // apply the edit let newText = applyEdit(text, edit); // format the new text let begin = edit.offset; let end = edit.offset + edit.content.length; if (edit.length === 0 || edit.content.length === 0) { // insert or remove while (begin > 0 && !isEOL(newText, begin - 1)) { begin--; } while (end < newText.length && !isEOL(newText, end)) { end++; } } const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); // apply the formatting edits and track the begin and end offsets of the changes for (let i = edits.length - 1; i >= 0; i--) { const edit = edits[i]; newText = applyEdit(newText, edit); begin = Math.min(begin, edit.offset); end = Math.max(end, edit.offset + edit.length); end += edit.content.length - edit.length; } // create a single edit with all changes const editLength = text.length - (newText.length - end) - begin; return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; } function applyEdit(text, edit) { return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); } function isWS(text, offset) { return '\r\n \t'.indexOf(text.charAt(offset)) !== -1; } ;// CONCATENATED MODULE: ./node_modules/jsonc-parser/lib/esm/main.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */ const main_createScanner = createScanner; var ScanError; (function (ScanError) { ScanError[ScanError["None"] = 0] = "None"; ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; })(ScanError || (ScanError = {})); var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; })(SyntaxKind || (SyntaxKind = {})); /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ const main_getLocation = getLocation; /** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore, always check the errors list to find out if the input was valid. */ const main_parse = parse; /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ const main_parseTree = parser_parseTree; /** * Finds the node at the given path in a JSON DOM. */ const main_findNodeAtLocation = parser_findNodeAtLocation; /** * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */ const main_findNodeAtOffset = findNodeAtOffset; /** * Gets the JSON path of the given JSON DOM node */ const main_getNodePath = getNodePath; /** * Evaluates the JavaScript object of the given JSON DOM node */ const main_getNodeValue = getNodeValue; /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ const main_visit = visit; /** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ const main_stripComments = stripComments; var ParseErrorCode; (function (ParseErrorCode) { ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; })(ParseErrorCode || (ParseErrorCode = {})); function printParseErrorCode(code) { switch (code) { case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; } return ''; } /** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */ function main_format(documentText, range, options) { return format_format(documentText, range, options); } /** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */ function modify(text, path, value, options) { return edit.setProperty(text, path, value, options); } /** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */ function applyEdits(text, edits) { let sortedEdits = edits.slice(0).sort((a, b) => { const diff = a.offset - b.offset; if (diff === 0) { return a.length - b.length; } return diff; }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { let e = sortedEdits[i]; if (e.offset + e.length <= lastModifiedOffset) { text = edit.applyEdit(text, e); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = e.offset; } return text; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/objects.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function equals(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; } if ((Array.isArray(one)) !== (Array.isArray(other))) { return false; } let i, key; if (Array.isArray(one)) { if (one.length !== other.length) { return false; } for (i = 0; i < one.length; i++) { if (!equals(one[i], other[i])) { return false; } } } else { const oneKeys = []; for (key in one) { oneKeys.push(key); } oneKeys.sort(); const otherKeys = []; for (key in other) { otherKeys.push(key); } otherKeys.sort(); if (!equals(oneKeys, otherKeys)) { return false; } for (i = 0; i < oneKeys.length; i++) { if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { return false; } } } return true; } function isNumber(val) { return typeof val === 'number'; } function isDefined(val) { return typeof val !== 'undefined'; } function isBoolean(val) { return typeof val === 'boolean'; } function isString(val) { return typeof val === 'string'; } function isObject(val) { return typeof val === 'object' && val !== null && !Array.isArray(val); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/strings.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function startsWith(haystack, needle) { if (haystack.length < needle.length) { return false; } for (let i = 0; i < needle.length; i++) { if (haystack[i] !== needle[i]) { return false; } } return true; } /** * Determines if haystack ends with needle. */ function endsWith(haystack, needle) { const diff = haystack.length - needle.length; if (diff > 0) { return haystack.lastIndexOf(needle) === diff; } else if (diff === 0) { return haystack === needle; } else { return false; } } function convertSimple2RegExpPattern(pattern) { return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*'); } function strings_repeat(value, count) { let s = ''; while (count > 0) { if ((count & 1) === 1) { s += value; } value += value; count = count >>> 1; } return s; } function extendedRegExp(pattern) { let flags = ''; if (startsWith(pattern, '(?i)')) { pattern = pattern.substring(4); flags = 'i'; } try { return new RegExp(pattern, flags + 'u'); } catch (e) { // could be an exception due to the 'u ' flag try { return new RegExp(pattern, flags); } catch (e) { // invalid pattern return undefined; } } } // from https://tanishiking.github.io/posts/count-unicode-codepoint/#work-hard-with-for-statements function stringLength(str) { let count = 0; for (let i = 0; i < str.length; i++) { count++; // obtain the i-th 16-bit const code = str.charCodeAt(i); if (0xD800 <= code && code <= 0xDBFF) { // if the i-th 16bit is an upper surrogate // skip the next 16 bits (lower surrogate) i++; } } return count; } ;// CONCATENATED MODULE: ./node_modules/vscode-languageserver-types/lib/esm/main.js /* -------------------------------------------------------------------------------------------- * 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, character }; } Position.create = create; /** * Checks whether the given literal conforms to the {@link Position} interface. */ function is(value) { let 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[${one}, ${two}, ${three}, ${four}]`); } } Range.create = create; /** * Checks whether the given literal conforms to the {@link Range} interface. */ function is(value) { let 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, range }; } Location.create = create; /** * Checks whether the given literal conforms to the {@link Location} interface. */ function is(value) { let 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, targetRange, targetSelectionRange, originSelectionRange }; } LocationLink.create = create; /** * Checks whether the given literal conforms to the {@link LocationLink} interface. */ function is(value) { let 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, green, blue, alpha, }; } Color.create = create; /** * Checks whether the given literal conforms to the {@link Color} interface. */ function is(value) { const 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, color, }; } ColorInformation.create = create; /** * Checks whether the given literal conforms to the {@link ColorInformation} interface. */ function is(value) { const 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, textEdit, additionalTextEdits, }; } ColorPresentation.create = create; /** * Checks whether the given literal conforms to the {@link ColorInformation} interface. */ function is(value) { const 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) { const result = { startLine, 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) { const 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, message }; } DiagnosticRelatedInformation.create = create; /** * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. */ function is(value) { let 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) { const 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) { let result = { range, 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; let 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, ...args) { let result = { title, 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) { let 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, 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 }; } TextEdit.insert = insert; /** * Creates a delete text edit. * @param range The range of text to be deleted. */ function del(range) { return { range, newText: '' }; } TextEdit.del = del; function is(value) { const 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) { const result = { label }; if (needsConfirmation !== undefined) { result.needsConfirmation = needsConfirmation; } if (description !== undefined) { result.description = description; } return result; } ChangeAnnotation.create = create; function is(value) { const 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) { const 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, 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, 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, newText: '', annotationId: annotation }; } AnnotatedTextEdit.del = del; function is(value) { const 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, edits }; } TextDocumentEdit.create = create; function is(value) { let 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) { let result = { kind: 'create', 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) { let 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) { let result = { kind: 'rename', oldUri, 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) { let 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) { let result = { kind: 'delete', 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) { let 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) { let candidate = value; return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every((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 = {})); class TextEditChangeImpl { constructor(edits, changeAnnotations) { this.edits = edits; this.changeAnnotations = changeAnnotations; } insert(position, newText, annotation) { let edit; let 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; } } replace(range, newText, annotation) { let edit; let 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; } } delete(range, annotation) { let edit; let 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; } } add(edit) { this.edits.push(edit); } all() { return this.edits; } clear() { this.edits.splice(0, this.edits.length); } assertChangeAnnotations(value) { if (value === undefined) { throw new Error(`Text edit change is not configured to manage change annotations.`); } } } /** * A helper class */ class ChangeAnnotations { constructor(annotations) { this._annotations = annotations === undefined ? Object.create(null) : annotations; this._counter = 0; this._size = 0; } all() { return this._annotations; } get size() { return this._size; } manage(idOrAnnotation, annotation) { let id; if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { id = idOrAnnotation; } else { id = this.nextId(); annotation = idOrAnnotation; } if (this._annotations[id] !== undefined) { throw new Error(`Id ${id} is already in use.`); } if (annotation === undefined) { throw new Error(`No annotation provided for id ${id}`); } this._annotations[id] = annotation; this._size++; return id; } nextId() { this._counter++; return this._counter.toString(); } } /** * A workspace change helps constructing changes to a workspace. */ class WorkspaceChange { constructor(workspaceEdit) { 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((change) => { if (TextDocumentEdit.is(change)) { const textEditChange = new TextEditChangeImpl(change.edits, this._changeAnnotations); this._textEditChanges[change.textDocument.uri] = textEditChange; } }); } else if (workspaceEdit.changes) { Object.keys(workspaceEdit.changes).forEach((key) => { const textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); this._textEditChanges[key] = textEditChange; }); } } else { this._workspaceEdit = {}; } } /** * Returns the underlying {@link WorkspaceEdit} literal * use to be returned from a workspace edit operation like rename. */ get edit() { 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; } getTextEditChange(key) { if (OptionalVersionedTextDocumentIdentifier.is(key)) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } const textDocument = { uri: key.uri, version: key.version }; let result = this._textEditChanges[textDocument.uri]; if (!result) { const edits = []; const textDocumentEdit = { textDocument, 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.'); } let result = this._textEditChanges[key]; if (!result) { let edits = []; this._workspaceEdit.changes[key] = edits; result = new TextEditChangeImpl(edits); this._textEditChanges[key] = result; } return result; } } initDocumentChanges() { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._changeAnnotations = new ChangeAnnotations(); this._workspaceEdit.documentChanges = []; this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); } } initChanges() { if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { this._workspaceEdit.changes = Object.create(null); } } createFile(uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } let annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } let operation; let 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; } } renameFile(oldUri, newUri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } let annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } let operation; let 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; } } deleteFile(uri, optionsOrAnnotation, options) { this.initDocumentChanges(); if (this._workspaceEdit.documentChanges === undefined) { throw new Error('Workspace edit is not configured for document changes.'); } let annotation; if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { annotation = optionsOrAnnotation; } else { options = optionsOrAnnotation; } let operation; let 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; } } } /** * 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 }; } TextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. */ function is(value) { let 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, version }; } VersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. */ function is(value) { let 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, version }; } OptionalVersionedTextDocumentIdentifier.create = create; /** * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. */ function is(value) { let 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, languageId, version, text }; } TextDocumentItem.create = create; /** * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. */ function is(value) { let 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) { const 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) { const 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, insert, replace }; } InsertReplaceEdit.create = create; /** * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. */ function is(value) { const 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><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) { const 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 }; } 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) { const 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) { let 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, documentation } : { 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, ...parameters) { let result = { 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) { let result = { 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) { let result = { name, kind, location: { uri, 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, kind, location: { uri, range } } : { name, kind, location: { 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) { let result = { name, detail, kind, range, 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) { let 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) { let result = { 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) { let 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) { let result = { title }; let 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) { let 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) { let result = { 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) { let 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, insertSpaces }; } FormattingOptions.create = create; /** * Checks whether the given literal conforms to the {@link FormattingOptions} interface. */ function is(value) { let 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, target, data }; } DocumentLink.create = create; /** * Checks whether the given literal conforms to the {@link DocumentLink} interface. */ function is(value) { let 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, parent }; } SelectionRange.create = create; function is(value) { let 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) { const 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, text }; } InlineValueText.create = create; function is(value) { const 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, variableName, caseSensitiveLookup }; } InlineValueVariableLookup.create = create; function is(value) { const 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, expression }; } InlineValueEvaluatableExpression.create = create; function is(value) { const 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, stoppedLocation }; } InlineValueContext.create = create; /** * Checks whether the given literal conforms to the {@link InlineValueContext} interface. */ function is(value) { const 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 }; } InlayHintLabelPart.create = create; function is(value) { const 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) { const result = { position, label }; if (kind !== undefined) { result.kind = kind; } return result; } InlayHint.create = create; function is(value) { const 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 StringValue; (function (StringValue) { function createSnippet(value) { return { kind: 'snippet', value }; } StringValue.createSnippet = createSnippet; })(StringValue || (StringValue = {})); var InlineCompletionItem; (function (InlineCompletionItem) { function create(insertText, filterText, range, command) { return { insertText, filterText, range, command }; } InlineCompletionItem.create = create; })(InlineCompletionItem || (InlineCompletionItem = {})); var InlineCompletionList; (function (InlineCompletionList) { function create(items) { return { items }; } InlineCompletionList.create = create; })(InlineCompletionList || (InlineCompletionList = {})); /** * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. * * @since 3.18.0 * @proposed */ var InlineCompletionTriggerKind; (function (InlineCompletionTriggerKind) { /** * Completion was triggered explicitly by a user gesture. */ InlineCompletionTriggerKind.Invoked = 0; /** * Completion was triggered automatically while editing. */ InlineCompletionTriggerKind.Automatic = 1; })(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {})); var SelectedCompletionInfo; (function (SelectedCompletionInfo) { function create(range, text) { return { range, text }; } SelectedCompletionInfo.create = create; })(SelectedCompletionInfo || (SelectedCompletionInfo = {})); var InlineCompletionContext; (function (InlineCompletionContext) { function create(triggerKind, selectedCompletionInfo) { return { triggerKind, selectedCompletionInfo }; } InlineCompletionContext.create = create; })(InlineCompletionContext || (InlineCompletionContext = {})); var WorkspaceFolder; (function (WorkspaceFolder) { function is(value) { const candidate = value; return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); } WorkspaceFolder.is = is; })(WorkspaceFolder || (WorkspaceFolder = {})); const EOL = (/* unused pure expression or super */ null && (['\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) { let 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) { let text = document.getText(); let sortedEdits = mergeSort(edits, (a, b) => { let diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { let e = sortedEdits[i]; let startOffset = document.offsetAt(e.range.start); let 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; } const p = (data.length / 2) | 0; const left = data.slice(0, p); const right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); let leftIdx = 0; let rightIdx = 0; let i = 0; while (leftIdx < left.length && rightIdx < right.length) { let 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. */ class FullTextDocument { constructor(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } get uri() { return this._uri; } get languageId() { return this._languageId; } get version() { return this._version; } getText(range) { if (range) { let start = this.offsetAt(range.start); let end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; } update(event, version) { this._content = event.text; this._version = version; this._lineOffsets = undefined; } getLineOffsets() { if (this._lineOffsets === undefined) { let lineOffsets = []; let text = this._content; let isLineStart = true; for (let i = 0; i < text.length; i++) { if (isLineStart) { lineOffsets.push(i); isLineStart = false; } let 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; } positionAt(offset) { offset = Math.max(Math.min(offset, this._content.length), 0); let lineOffsets = this.getLineOffsets(); let low = 0, high = lineOffsets.length; if (high === 0) { return Position.create(0, offset); } while (low < high) { let 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 let line = low - 1; return Position.create(line, offset - lineOffsets[line]); } offsetAt(position) { let lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } let lineOffset = lineOffsets[position.line]; let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); } get lineCount() { return this.getLineOffsets().length; } } var Is; (function (Is) { const 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 = {})); ;// CONCATENATED MODULE: ./node_modules/vscode-languageserver-textdocument/lib/esm/main.js /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ class main_FullTextDocument { constructor(uri, languageId, version, content) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } get uri() { return this._uri; } get languageId() { return this._languageId; } get version() { return this._version; } getText(range) { if (range) { const start = this.offsetAt(range.start); const end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; } update(changes, version) { for (let change of changes) { if (main_FullTextDocument.isIncremental(change)) { // makes sure start is before end const range = getWellformedRange(change.range); // update content const startOffset = this.offsetAt(range.start); const endOffset = this.offsetAt(range.end); this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length); // update the offsets const startLine = Math.max(range.start.line, 0); const endLine = Math.max(range.end.line, 0); let lineOffsets = this._lineOffsets; const addedLineOffsets = computeLineOffsets(change.text, false, startOffset); if (endLine - startLine === addedLineOffsets.length) { for (let i = 0, len = addedLineOffsets.length; i < len; i++) { lineOffsets[i + startLine + 1] = addedLineOffsets[i]; } } else { if (addedLineOffsets.length < 10000) { lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets); } else { // avoid too many arguments for splice this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1)); } } const diff = change.text.length - (endOffset - startOffset); if (diff !== 0) { for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) { lineOffsets[i] = lineOffsets[i] + diff; } } } else if (main_FullTextDocument.isFull(change)) { this._content = change.text; this._lineOffsets = undefined; } else { throw new Error('Unknown change event received'); } } this._version = version; } getLineOffsets() { if (this._lineOffsets === undefined) { this._lineOffsets = computeLineOffsets(this._content, true); } return this._lineOffsets; } positionAt(offset) { offset = Math.max(Math.min(offset, this._content.length), 0); let lineOffsets = this.getLineOffsets(); let low = 0, high = lineOffsets.length; if (high === 0) { return { line: 0, character: offset }; } while (low < high) { let 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 let line = low - 1; return { line, character: offset - lineOffsets[line] }; } offsetAt(position) { let lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } let lineOffset = lineOffsets[position.line]; let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); } get lineCount() { return this.getLineOffsets().length; } static isIncremental(event) { let candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); } static isFull(event) { let candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } } var main_TextDocument; (function (TextDocument) { /** * Creates a new text document. * * @param uri The document's uri. * @param languageId The document's language Id. * @param version The document's initial version number. * @param content The document's content. */ function create(uri, languageId, version, content) { return new main_FullTextDocument(uri, languageId, version, content); } TextDocument.create = create; /** * Updates a TextDocument by modifying its content. * * @param document the document to update. Only documents created by TextDocument.create are valid inputs. * @param changes the changes to apply to the document. * @param version the changes version for the document. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter. * */ function update(document, changes, version) { if (document instanceof main_FullTextDocument) { document.update(changes, version); return document; } else { throw new Error('TextDocument.update: document must be created by TextDocument.create'); } } TextDocument.update = update; function applyEdits(document, edits) { let text = document.getText(); let sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => { let diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); let lastModifiedOffset = 0; const spans = []; for (const e of sortedEdits) { let startOffset = document.offsetAt(e.range.start); if (startOffset < lastModifiedOffset) { throw new Error('Overlapping edit'); } else if (startOffset > lastModifiedOffset) { spans.push(text.substring(lastModifiedOffset, startOffset)); } if (e.newText.length) { spans.push(e.newText); } lastModifiedOffset = document.offsetAt(e.range.end); } spans.push(text.substr(lastModifiedOffset)); return spans.join(''); } TextDocument.applyEdits = applyEdits; })(main_TextDocument || (main_TextDocument = {})); function mergeSort(data, compare) { if (data.length <= 1) { // sorted return data; } const p = (data.length / 2) | 0; const left = data.slice(0, p); const right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); let leftIdx = 0; let rightIdx = 0; let i = 0; while (leftIdx < left.length && rightIdx < right.length) { let 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; } function computeLineOffsets(text, isAtLineStart, textOffset = 0) { const result = isAtLineStart ? [textOffset] : []; for (let i = 0; i < text.length; i++) { let ch = text.charCodeAt(i); if (ch === 13 /* CharCode.CarriageReturn */ || ch === 10 /* CharCode.LineFeed */) { if (ch === 13 /* CharCode.CarriageReturn */ && i + 1 < text.length && text.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) { i++; } result.push(textOffset + i + 1); } } return result; } function getWellformedRange(range) { const start = range.start; const end = range.end; if (start.line > end.line || (start.line === end.line && start.character > end.character)) { return { start: end, end: start }; } return range; } function getWellformedEdit(textEdit) { const range = getWellformedRange(textEdit.range); if (range !== textEdit.range) { return { newText: textEdit.newText, range }; } return textEdit; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/jsonLanguageTypes.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * Error codes used by diagnostics */ var ErrorCode; (function (ErrorCode) { ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined"; ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch"; ErrorCode[ErrorCode["Deprecated"] = 2] = "Deprecated"; ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment"; ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString"; ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber"; ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode"; ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter"; ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter"; ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected"; ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected"; ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected"; ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected"; ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected"; ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected"; ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma"; ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey"; ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted"; ErrorCode[ErrorCode["PropertyKeysMustBeDoublequoted"] = 528] = "PropertyKeysMustBeDoublequoted"; ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError"; ErrorCode[ErrorCode["SchemaUnsupportedFeature"] = 769] = "SchemaUnsupportedFeature"; })(ErrorCode || (ErrorCode = {})); var SchemaDraft; (function (SchemaDraft) { SchemaDraft[SchemaDraft["v3"] = 3] = "v3"; SchemaDraft[SchemaDraft["v4"] = 4] = "v4"; SchemaDraft[SchemaDraft["v6"] = 6] = "v6"; SchemaDraft[SchemaDraft["v7"] = 7] = "v7"; SchemaDraft[SchemaDraft["v2019_09"] = 19] = "v2019_09"; SchemaDraft[SchemaDraft["v2020_12"] = 20] = "v2020_12"; })(SchemaDraft || (SchemaDraft = {})); var ClientCapabilities; (function (ClientCapabilities) { ClientCapabilities.LATEST = { textDocument: { completion: { completionItem: { documentationFormat: [MarkupKind.Markdown, MarkupKind.PlainText], commitCharactersSupport: true, labelDetailsSupport: true } } } }; })(ClientCapabilities || (ClientCapabilities = {})); // EXTERNAL MODULE: ./node_modules/@vscode/l10n/dist/main.js var main = __nccwpck_require__(5697); ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/parser/jsonParser.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const formats = { 'color-hex': { errorMessage: main.t('Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ }, 'date-time': { errorMessage: main.t('String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i }, 'date': { errorMessage: main.t('String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i }, 'time': { errorMessage: main.t('String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i }, 'email': { errorMessage: main.t('String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))$/ }, 'hostname': { errorMessage: main.t('String is not a hostname.'), pattern: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i }, 'ipv4': { errorMessage: main.t('String is not an IPv4 address.'), pattern: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/ }, 'ipv6': { errorMessage: main.t('String is not an IPv6 address.'), pattern: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i }, }; class ASTNodeImpl { constructor(parent, offset, length = 0) { this.offset = offset; this.length = length; this.parent = parent; } get children() { return []; } toString() { return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : ''); } } class NullASTNodeImpl extends ASTNodeImpl { constructor(parent, offset) { super(parent, offset); this.type = 'null'; this.value = null; } } class BooleanASTNodeImpl extends ASTNodeImpl { constructor(parent, boolValue, offset) { super(parent, offset); this.type = 'boolean'; this.value = boolValue; } } class ArrayASTNodeImpl extends ASTNodeImpl { constructor(parent, offset) { super(parent, offset); this.type = 'array'; this.items = []; } get children() { return this.items; } } class NumberASTNodeImpl extends ASTNodeImpl { constructor(parent, offset) { super(parent, offset); this.type = 'number'; this.isInteger = true; this.value = Number.NaN; } } class StringASTNodeImpl extends ASTNodeImpl { constructor(parent, offset, length) { super(parent, offset, length); this.type = 'string'; this.value = ''; } } class PropertyASTNodeImpl extends ASTNodeImpl { constructor(parent, offset, keyNode) { super(parent, offset); this.type = 'property'; this.colonOffset = -1; this.keyNode = keyNode; } get children() { return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode]; } } class ObjectASTNodeImpl extends ASTNodeImpl { constructor(parent, offset) { super(parent, offset); this.type = 'object'; this.properties = []; } get children() { return this.properties; } } function asSchema(schema) { if (isBoolean(schema)) { return schema ? {} : { "not": {} }; } return schema; } var EnumMatch; (function (EnumMatch) { EnumMatch[EnumMatch["Key"] = 0] = "Key"; EnumMatch[EnumMatch["Enum"] = 1] = "Enum"; })(EnumMatch || (EnumMatch = {})); const schemaDraftFromId = { 'http://json-schema.org/draft-03/schema#': SchemaDraft.v3, 'http://json-schema.org/draft-04/schema#': SchemaDraft.v4, 'http://json-schema.org/draft-06/schema#': SchemaDraft.v6, 'http://json-schema.org/draft-07/schema#': SchemaDraft.v7, 'https://json-schema.org/draft/2019-09/schema': SchemaDraft.v2019_09, 'https://json-schema.org/draft/2020-12/schema': SchemaDraft.v2020_12 }; class EvaluationContext { constructor(schemaDraft) { this.schemaDraft = schemaDraft; } } class SchemaCollector { constructor(focusOffset = -1, exclude) { this.focusOffset = focusOffset; this.exclude = exclude; this.schemas = []; } add(schema) { this.schemas.push(schema); } merge(other) { Array.prototype.push.apply(this.schemas, other.schemas); } include(node) { return (this.focusOffset === -1 || jsonParser_contains(node, this.focusOffset)) && (node !== this.exclude); } newSub() { return new SchemaCollector(-1, this.exclude); } } class NoOpSchemaCollector { constructor() { } get schemas() { return []; } add(_schema) { } merge(_other) { } include(_node) { return true; } newSub() { return this; } } NoOpSchemaCollector.instance = new NoOpSchemaCollector(); class ValidationResult { constructor() { this.problems = []; this.propertiesMatches = 0; this.processedProperties = new Set(); this.propertiesValueMatches = 0; this.primaryValueMatches = 0; this.enumValueMatch = false; this.enumValues = undefined; } hasProblems() { return !!this.problems.length; } merge(validationResult) { this.problems = this.problems.concat(validationResult.problems); this.propertiesMatches += validationResult.propertiesMatches; this.propertiesValueMatches += validationResult.propertiesValueMatches; this.mergeProcessedProperties(validationResult); } mergeEnumValues(validationResult) { if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) { this.enumValues = this.enumValues.concat(validationResult.enumValues); for (const error of this.problems) { if (error.code === ErrorCode.EnumValueMismatch) { error.message = main.t('Value is not accepted. Valid values: {0}.', this.enumValues.map(v => JSON.stringify(v)).join(', ')); } } } } mergePropertyMatch(propertyValidationResult) { this.problems = this.problems.concat(propertyValidationResult.problems); this.propertiesMatches++; if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) { this.propertiesValueMatches++; } if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) { this.primaryValueMatches++; } } mergeProcessedProperties(validationResult) { validationResult.processedProperties.forEach(p => this.processedProperties.add(p)); } compare(other) { const hasProblems = this.hasProblems(); if (hasProblems !== other.hasProblems()) { return hasProblems ? -1 : 1; } if (this.enumValueMatch !== other.enumValueMatch) { return other.enumValueMatch ? -1 : 1; } if (this.primaryValueMatches !== other.primaryValueMatches) { return this.primaryValueMatches - other.primaryValueMatches; } if (this.propertiesValueMatches !== other.propertiesValueMatches) { return this.propertiesValueMatches - other.propertiesValueMatches; } return this.propertiesMatches - other.propertiesMatches; } } function newJSONDocument(root, diagnostics = []) { return new JSONDocument(root, diagnostics, []); } function jsonParser_getNodeValue(node) { return main_getNodeValue(node); } function jsonParser_getNodePath(node) { return main_getNodePath(node); } function jsonParser_contains(node, offset, includeRightBound = false) { return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length); } class JSONDocument { constructor(root, syntaxErrors = [], comments = []) { this.root = root; this.syntaxErrors = syntaxErrors; this.comments = comments; } getNodeFromOffset(offset, includeRightBound = false) { if (this.root) { return main_findNodeAtOffset(this.root, offset, includeRightBound); } return undefined; } visit(visitor) { if (this.root) { const doVisit = (node) => { let ctn = visitor(node); const children = node.children; if (Array.isArray(children)) { for (let i = 0; i < children.length && ctn; i++) { ctn = doVisit(children[i]); } } return ctn; }; doVisit(this.root); } } validate(textDocument, schema, severity = DiagnosticSeverity.Warning, schemaDraft) { if (this.root && schema) { const validationResult = new ValidationResult(); validate(this.root, schema, validationResult, NoOpSchemaCollector.instance, new EvaluationContext(schemaDraft ?? getSchemaDraft(schema))); return validationResult.problems.map(p => { const range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length)); return Diagnostic.create(range, p.message, p.severity ?? severity, p.code); }); } return undefined; } getMatchingSchemas(schema, focusOffset = -1, exclude) { if (this.root && schema) { const matchingSchemas = new SchemaCollector(focusOffset, exclude); const schemaDraft = getSchemaDraft(schema); const context = new EvaluationContext(schemaDraft); validate(this.root, schema, new ValidationResult(), matchingSchemas, context); return matchingSchemas.schemas; } return []; } } function getSchemaDraft(schema, fallBack = SchemaDraft.v2020_12) { let schemaId = schema.$schema; if (schemaId) { return schemaDraftFromId[schemaId] ?? fallBack; } return fallBack; } function validate(n, schema, validationResult, matchingSchemas, context) { if (!n || !matchingSchemas.include(n)) { return; } if (n.type === 'property') { return validate(n.valueNode, schema, validationResult, matchingSchemas, context); } const node = n; _validateNode(); switch (node.type) { case 'object': _validateObjectNode(node); break; case 'array': _validateArrayNode(node); break; case 'string': _validateStringNode(node); break; case 'number': _validateNumberNode(node); break; } matchingSchemas.add({ node: node, schema: schema }); function _validateNode() { function matchesType(type) { return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger); } if (Array.isArray(schema.type)) { if (!schema.type.some(matchesType)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t('Incorrect type. Expected one of {0}.', schema.type.join(', ')) }); } } else if (schema.type) { if (!matchesType(schema.type)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t('Incorrect type. Expected "{0}".', schema.type) }); } } if (Array.isArray(schema.allOf)) { for (const subSchemaRef of schema.allOf) { const subValidationResult = new ValidationResult(); const subMatchingSchemas = matchingSchemas.newSub(); validate(node, asSchema(subSchemaRef), subValidationResult, subMatchingSchemas, context); validationResult.merge(subValidationResult); matchingSchemas.merge(subMatchingSchemas); } } const notSchema = asSchema(schema.not); if (notSchema) { const subValidationResult = new ValidationResult(); const subMatchingSchemas = matchingSchemas.newSub(); validate(node, notSchema, subValidationResult, subMatchingSchemas, context); if (!subValidationResult.hasProblems()) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t("Matches a schema that is not allowed.") }); } for (const ms of subMatchingSchemas.schemas) { ms.inverted = !ms.inverted; matchingSchemas.add(ms); } } const testAlternatives = (alternatives, maxOneMatch) => { const matches = []; // remember the best match that is used for error messages let bestMatch = undefined; for (const subSchemaRef of alternatives) { const subSchema = asSchema(subSchemaRef); const subValidationResult = new ValidationResult(); const subMatchingSchemas = matchingSchemas.newSub(); validate(node, subSchema, subValidationResult, subMatchingSchemas, context); if (!subValidationResult.hasProblems()) { matches.push(subSchema); } if (!bestMatch) { bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas }; } else { if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) { // no errors, both are equally good matches bestMatch.matchingSchemas.merge(subMatchingSchemas); bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches; bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches; bestMatch.validationResult.mergeProcessedProperties(subValidationResult); } else { const compareResult = subValidationResult.compare(bestMatch.validationResult); if (compareResult > 0) { // our node is the best matching so far bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas }; } else if (compareResult === 0) { // there's already a best matching but we are as good bestMatch.matchingSchemas.merge(subMatchingSchemas); bestMatch.validationResult.mergeEnumValues(subValidationResult); } } } } if (matches.length > 1 && maxOneMatch) { validationResult.problems.push({ location: { offset: node.offset, length: 1 }, message: main.t("Matches multiple schemas when only one must validate.") }); } if (bestMatch) { validationResult.merge(bestMatch.validationResult); matchingSchemas.merge(bestMatch.matchingSchemas); } return matches.length; }; if (Array.isArray(schema.anyOf)) { testAlternatives(schema.anyOf, false); } if (Array.isArray(schema.oneOf)) { testAlternatives(schema.oneOf, true); } const testBranch = (schema) => { const subValidationResult = new ValidationResult(); const subMatchingSchemas = matchingSchemas.newSub(); validate(node, asSchema(schema), subValidationResult, subMatchingSchemas, context); validationResult.merge(subValidationResult); matchingSchemas.merge(subMatchingSchemas); }; const testCondition = (ifSchema, thenSchema, elseSchema) => { const subSchema = asSchema(ifSchema); const subValidationResult = new ValidationResult(); const subMatchingSchemas = matchingSchemas.newSub(); validate(node, subSchema, subValidationResult, subMatchingSchemas, context); matchingSchemas.merge(subMatchingSchemas); validationResult.mergeProcessedProperties(subValidationResult); if (!subValidationResult.hasProblems()) { if (thenSchema) { testBranch(thenSchema); } } else if (elseSchema) { testBranch(elseSchema); } }; const ifSchema = asSchema(schema.if); if (ifSchema) { testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else)); } if (Array.isArray(schema.enum)) { const val = jsonParser_getNodeValue(node); let enumValueMatch = false; for (const e of schema.enum) { if (equals(val, e)) { enumValueMatch = true; break; } } validationResult.enumValues = schema.enum; validationResult.enumValueMatch = enumValueMatch; if (!enumValueMatch) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, code: ErrorCode.EnumValueMismatch, message: schema.errorMessage || main.t('Value is not accepted. Valid values: {0}.', schema.enum.map(v => JSON.stringify(v)).join(', ')) }); } } if (isDefined(schema.const)) { const val = jsonParser_getNodeValue(node); if (!equals(val, schema.const)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, code: ErrorCode.EnumValueMismatch, message: schema.errorMessage || main.t('Value must be {0}.', JSON.stringify(schema.const)) }); validationResult.enumValueMatch = false; } else { validationResult.enumValueMatch = true; } validationResult.enumValues = [schema.const]; } let deprecationMessage = schema.deprecationMessage; if (deprecationMessage || schema.deprecated) { deprecationMessage = deprecationMessage || main.t('Value is deprecated'); let targetNode = node.parent?.type === 'property' ? node.parent : node; validationResult.problems.push({ location: { offset: targetNode.offset, length: targetNode.length }, severity: DiagnosticSeverity.Warning, message: deprecationMessage, code: ErrorCode.Deprecated }); } } function _validateNumberNode(node) { const val = node.value; function normalizeFloats(float) { const parts = /^(-?\d+)(?:\.(\d+))?(?:e([-+]\d+))?$/.exec(float.toString()); return parts && { value: Number(parts[1] + (parts[2] || '')), multiplier: (parts[2]?.length || 0) - (parseInt(parts[3]) || 0) }; } ; if (isNumber(schema.multipleOf)) { let remainder = -1; if (Number.isInteger(schema.multipleOf)) { remainder = val % schema.multipleOf; } else { let normMultipleOf = normalizeFloats(schema.multipleOf); let normValue = normalizeFloats(val); if (normMultipleOf && normValue) { const multiplier = 10 ** Math.abs(normValue.multiplier - normMultipleOf.multiplier); if (normValue.multiplier < normMultipleOf.multiplier) { normValue.value *= multiplier; } else { normMultipleOf.value *= multiplier; } remainder = normValue.value % normMultipleOf.value; } } if (remainder !== 0) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Value is not divisible by {0}.', schema.multipleOf) }); } } function getExclusiveLimit(limit, exclusive) { if (isNumber(exclusive)) { return exclusive; } if (isBoolean(exclusive) && exclusive) { return limit; } return undefined; } function getLimit(limit, exclusive) { if (!isBoolean(exclusive) || !exclusive) { return limit; } return undefined; } const exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum); if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Value is below the exclusive minimum of {0}.', exclusiveMinimum) }); } const exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum); if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Value is above the exclusive maximum of {0}.', exclusiveMaximum) }); } const minimum = getLimit(schema.minimum, schema.exclusiveMinimum); if (isNumber(minimum) && val < minimum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Value is below the minimum of {0}.', minimum) }); } const maximum = getLimit(schema.maximum, schema.exclusiveMaximum); if (isNumber(maximum) && val > maximum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Value is above the maximum of {0}.', maximum) }); } } function _validateStringNode(node) { if (isNumber(schema.minLength) && stringLength(node.value) < schema.minLength) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('String is shorter than the minimum length of {0}.', schema.minLength) }); } if (isNumber(schema.maxLength) && stringLength(node.value) > schema.maxLength) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('String is longer than the maximum length of {0}.', schema.maxLength) }); } if (isString(schema.pattern)) { const regex = extendedRegExp(schema.pattern); if (!(regex?.test(node.value))) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.patternErrorMessage || schema.errorMessage || main.t('String does not match the pattern of "{0}".', schema.pattern) }); } } if (schema.format) { switch (schema.format) { case 'uri': case 'uri-reference': { let errorMessage; if (!node.value) { errorMessage = main.t('URI expected.'); } else { const match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value); if (!match) { errorMessage = main.t('URI is expected.'); } else if (!match[2] && schema.format === 'uri') { errorMessage = main.t('URI with a scheme is expected.'); } } if (errorMessage) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.patternErrorMessage || schema.errorMessage || main.t('String is not a URI: {0}', errorMessage) }); } } break; case 'color-hex': case 'date-time': case 'date': case 'time': case 'email': case 'hostname': case 'ipv4': case 'ipv6': const format = formats[schema.format]; if (!node.value || !format.pattern.exec(node.value)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage }); } default: } } } function _validateArrayNode(node) { let prefixItemsSchemas; let additionalItemSchema; if (context.schemaDraft >= SchemaDraft.v2020_12) { prefixItemsSchemas = schema.prefixItems; additionalItemSchema = !Array.isArray(schema.items) ? schema.items : undefined; } else { prefixItemsSchemas = Array.isArray(schema.items) ? schema.items : undefined; additionalItemSchema = !Array.isArray(schema.items) ? schema.items : schema.additionalItems; } let index = 0; if (prefixItemsSchemas !== undefined) { const max = Math.min(prefixItemsSchemas.length, node.items.length); for (; index < max; index++) { const subSchemaRef = prefixItemsSchemas[index]; const subSchema = asSchema(subSchemaRef); const itemValidationResult = new ValidationResult(); const item = node.items[index]; if (item) { validate(item, subSchema, itemValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(itemValidationResult); } validationResult.processedProperties.add(String(index)); } } if (additionalItemSchema !== undefined && index < node.items.length) { if (typeof additionalItemSchema === 'boolean') { if (additionalItemSchema === false) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Array has too many items according to schema. Expected {0} or fewer.', index) }); } for (; index < node.items.length; index++) { validationResult.processedProperties.add(String(index)); validationResult.propertiesValueMatches++; } } else { for (; index < node.items.length; index++) { const itemValidationResult = new ValidationResult(); validate(node.items[index], additionalItemSchema, itemValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(itemValidationResult); validationResult.processedProperties.add(String(index)); } } } const containsSchema = asSchema(schema.contains); if (containsSchema) { let containsCount = 0; for (let index = 0; index < node.items.length; index++) { const item = node.items[index]; const itemValidationResult = new ValidationResult(); validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance, context); if (!itemValidationResult.hasProblems()) { containsCount++; if (context.schemaDraft >= SchemaDraft.v2020_12) { validationResult.processedProperties.add(String(index)); } } } if (containsCount === 0 && !isNumber(schema.minContains)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t('Array does not contain required item.') }); } if (isNumber(schema.minContains) && containsCount < schema.minContains) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t('Array has too few items that match the contains contraint. Expected {0} or more.', schema.minContains) }); } if (isNumber(schema.maxContains) && containsCount > schema.maxContains) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: schema.errorMessage || main.t('Array has too many items that match the contains contraint. Expected {0} or less.', schema.maxContains) }); } } const unevaluatedItems = schema.unevaluatedItems; if (unevaluatedItems !== undefined) { for (let i = 0; i < node.items.length; i++) { if (!validationResult.processedProperties.has(String(i))) { if (unevaluatedItems === false) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Item does not match any validation rule from the array.') }); } else { const itemValidationResult = new ValidationResult(); validate(node.items[i], schema.unevaluatedItems, itemValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(itemValidationResult); } } validationResult.processedProperties.add(String(i)); validationResult.propertiesValueMatches++; } } if (isNumber(schema.minItems) && node.items.length < schema.minItems) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Array has too few items. Expected {0} or more.', schema.minItems) }); } if (isNumber(schema.maxItems) && node.items.length > schema.maxItems) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Array has too many items. Expected {0} or fewer.', schema.maxItems) }); } if (schema.uniqueItems === true) { const values = jsonParser_getNodeValue(node); function hasDuplicates() { for (let i = 0; i < values.length - 1; i++) { const value = values[i]; for (let j = i + 1; j < values.length; j++) { if (equals(value, values[j])) { return true; } } } return false; } if (hasDuplicates()) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Array has duplicate items.') }); } } } function _validateObjectNode(node) { const seenKeys = Object.create(null); const unprocessedProperties = new Set(); for (const propertyNode of node.properties) { const key = propertyNode.keyNode.value; seenKeys[key] = propertyNode.valueNode; unprocessedProperties.add(key); } if (Array.isArray(schema.required)) { for (const propertyName of schema.required) { if (!seenKeys[propertyName]) { const keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode; const location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 }; validationResult.problems.push({ location: location, message: main.t('Missing property "{0}".', propertyName) }); } } } const propertyProcessed = (prop) => { unprocessedProperties.delete(prop); validationResult.processedProperties.add(prop); }; if (schema.properties) { for (const propertyName of Object.keys(schema.properties)) { propertyProcessed(propertyName); const propertySchema = schema.properties[propertyName]; const child = seenKeys[propertyName]; if (child) { if (isBoolean(propertySchema)) { if (!propertySchema) { const propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, message: schema.errorMessage || main.t('Property {0} is not allowed.', propertyName) }); } else { validationResult.propertiesMatches++; validationResult.propertiesValueMatches++; } } else { const propertyValidationResult = new ValidationResult(); validate(child, propertySchema, propertyValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(propertyValidationResult); } } } } if (schema.patternProperties) { for (const propertyPattern of Object.keys(schema.patternProperties)) { const regex = extendedRegExp(propertyPattern); if (regex) { const processed = []; for (const propertyName of unprocessedProperties) { if (regex.test(propertyName)) { processed.push(propertyName); const child = seenKeys[propertyName]; if (child) { const propertySchema = schema.patternProperties[propertyPattern]; if (isBoolean(propertySchema)) { if (!propertySchema) { const propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, message: schema.errorMessage || main.t('Property {0} is not allowed.', propertyName) }); } else { validationResult.propertiesMatches++; validationResult.propertiesValueMatches++; } } else { const propertyValidationResult = new ValidationResult(); validate(child, propertySchema, propertyValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(propertyValidationResult); } } } } processed.forEach(propertyProcessed); } } } const additionalProperties = schema.additionalProperties; if (additionalProperties !== undefined) { for (const propertyName of unprocessedProperties) { propertyProcessed(propertyName); const child = seenKeys[propertyName]; if (child) { if (additionalProperties === false) { const propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, message: schema.errorMessage || main.t('Property {0} is not allowed.', propertyName) }); } else if (additionalProperties !== true) { const propertyValidationResult = new ValidationResult(); validate(child, additionalProperties, propertyValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(propertyValidationResult); } } } } const unevaluatedProperties = schema.unevaluatedProperties; if (unevaluatedProperties !== undefined) { const processed = []; for (const propertyName of unprocessedProperties) { if (!validationResult.processedProperties.has(propertyName)) { processed.push(propertyName); const child = seenKeys[propertyName]; if (child) { if (unevaluatedProperties === false) { const propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, message: schema.errorMessage || main.t('Property {0} is not allowed.', propertyName) }); } else if (unevaluatedProperties !== true) { const propertyValidationResult = new ValidationResult(); validate(child, unevaluatedProperties, propertyValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(propertyValidationResult); } } } } processed.forEach(propertyProcessed); } if (isNumber(schema.maxProperties)) { if (node.properties.length > schema.maxProperties) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Object has more properties than limit of {0}.', schema.maxProperties) }); } } if (isNumber(schema.minProperties)) { if (node.properties.length < schema.minProperties) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Object has fewer properties than the required number of {0}', schema.minProperties) }); } } if (schema.dependentRequired) { for (const key in schema.dependentRequired) { const prop = seenKeys[key]; const propertyDeps = schema.dependentRequired[key]; if (prop && Array.isArray(propertyDeps)) { _validatePropertyDependencies(key, propertyDeps); } } } if (schema.dependentSchemas) { for (const key in schema.dependentSchemas) { const prop = seenKeys[key]; const propertyDeps = schema.dependentSchemas[key]; if (prop && isObject(propertyDeps)) { _validatePropertyDependencies(key, propertyDeps); } } } if (schema.dependencies) { for (const key in schema.dependencies) { const prop = seenKeys[key]; if (prop) { _validatePropertyDependencies(key, schema.dependencies[key]); } } } const propertyNames = asSchema(schema.propertyNames); if (propertyNames) { for (const f of node.properties) { const key = f.keyNode; if (key) { validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance, context); } } } function _validatePropertyDependencies(key, propertyDep) { if (Array.isArray(propertyDep)) { for (const requiredProp of propertyDep) { if (!seenKeys[requiredProp]) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, message: main.t('Object is missing property {0} required by property {1}.', requiredProp, key) }); } else { validationResult.propertiesValueMatches++; } } } else { const propertySchema = asSchema(propertyDep); if (propertySchema) { const propertyValidationResult = new ValidationResult(); validate(node, propertySchema, propertyValidationResult, matchingSchemas, context); validationResult.mergePropertyMatch(propertyValidationResult); } } } } } function jsonParser_parse(textDocument, config) { const problems = []; let lastProblemOffset = -1; const text = textDocument.getText(); const scanner = main_createScanner(text, false); const commentRanges = config && config.collectComments ? [] : undefined; function _scanNext() { while (true) { const token = scanner.scan(); _checkScanError(); switch (token) { case 12 /* Json.SyntaxKind.LineCommentTrivia */: case 13 /* Json.SyntaxKind.BlockCommentTrivia */: if (Array.isArray(commentRanges)) { commentRanges.push(Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()))); } break; case 15 /* Json.SyntaxKind.Trivia */: case 14 /* Json.SyntaxKind.LineBreakTrivia */: break; default: return token; } } } function _accept(token) { if (scanner.getToken() === token) { _scanNext(); return true; } return false; } function _errorAtRange(message, code, startOffset, endOffset, severity = DiagnosticSeverity.Error) { if (problems.length === 0 || startOffset !== lastProblemOffset) { const range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset)); problems.push(Diagnostic.create(range, message, severity, code, textDocument.languageId)); lastProblemOffset = startOffset; } } function _error(message, code, node = undefined, skipUntilAfter = [], skipUntil = []) { let start = scanner.getTokenOffset(); let end = scanner.getTokenOffset() + scanner.getTokenLength(); if (start === end && start > 0) { start--; while (start > 0 && /\s/.test(text.charAt(start))) { start--; } end = start + 1; } _errorAtRange(message, code, start, end); if (node) { _finalize(node, false); } if (skipUntilAfter.length + skipUntil.length > 0) { let token = scanner.getToken(); while (token !== 17 /* Json.SyntaxKind.EOF */) { if (skipUntilAfter.indexOf(token) !== -1) { _scanNext(); break; } else if (skipUntil.indexOf(token) !== -1) { break; } token = _scanNext(); } } return node; } function _checkScanError() { switch (scanner.getTokenError()) { case 4 /* Json.ScanError.InvalidUnicode */: _error(main.t('Invalid unicode sequence in string.'), ErrorCode.InvalidUnicode); return true; case 5 /* Json.ScanError.InvalidEscapeCharacter */: _error(main.t('Invalid escape character in string.'), ErrorCode.InvalidEscapeCharacter); return true; case 3 /* Json.ScanError.UnexpectedEndOfNumber */: _error(main.t('Unexpected end of number.'), ErrorCode.UnexpectedEndOfNumber); return true; case 1 /* Json.ScanError.UnexpectedEndOfComment */: _error(main.t('Unexpected end of comment.'), ErrorCode.UnexpectedEndOfComment); return true; case 2 /* Json.ScanError.UnexpectedEndOfString */: _error(main.t('Unexpected end of string.'), ErrorCode.UnexpectedEndOfString); return true; case 6 /* Json.ScanError.InvalidCharacter */: _error(main.t('Invalid characters in string. Control characters must be escaped.'), ErrorCode.InvalidCharacter); return true; } return false; } function _finalize(node, scanNext) { node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset; if (scanNext) { _scanNext(); } return node; } function _parseArray(parent) { if (scanner.getToken() !== 3 /* Json.SyntaxKind.OpenBracketToken */) { return undefined; } const node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset()); _scanNext(); // consume OpenBracketToken const count = 0; let needsComma = false; while (scanner.getToken() !== 4 /* Json.SyntaxKind.CloseBracketToken */ && scanner.getToken() !== 17 /* Json.SyntaxKind.EOF */) { if (scanner.getToken() === 5 /* Json.SyntaxKind.CommaToken */) { if (!needsComma) { _error(main.t('Value expected'), ErrorCode.ValueExpected); } const commaOffset = scanner.getTokenOffset(); _scanNext(); // consume comma if (scanner.getToken() === 4 /* Json.SyntaxKind.CloseBracketToken */) { if (needsComma) { _errorAtRange(main.t('Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1); } continue; } } else if (needsComma) { _error(main.t('Expected comma'), ErrorCode.CommaExpected); } const item = _parseValue(node); if (!item) { _error(main.t('Value expected'), ErrorCode.ValueExpected, undefined, [], [4 /* Json.SyntaxKind.CloseBracketToken */, 5 /* Json.SyntaxKind.CommaToken */]); } else { node.items.push(item); } needsComma = true; } if (scanner.getToken() !== 4 /* Json.SyntaxKind.CloseBracketToken */) { return _error(main.t('Expected comma or closing bracket'), ErrorCode.CommaOrCloseBacketExpected, node); } return _finalize(node, true); } const keyPlaceholder = new StringASTNodeImpl(undefined, 0, 0); function _parseProperty(parent, keysSeen) { const node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset(), keyPlaceholder); let key = _parseString(node); if (!key) { if (scanner.getToken() === 16 /* Json.SyntaxKind.Unknown */) { // give a more helpful error message _error(main.t('Property keys must be doublequoted'), ErrorCode.PropertyKeysMustBeDoublequoted); const keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength()); keyNode.value = scanner.getTokenValue(); key = keyNode; _scanNext(); // consume Unknown } else { return undefined; } } node.keyNode = key; // For JSON files that forbid code comments, there is a convention to use the key name "//" to add comments. // Multiple instances of "//" are okay. if (key.value !== "//") { const seen = keysSeen[key.value]; if (seen) { _errorAtRange(main.t("Duplicate object key"), ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, DiagnosticSeverity.Warning); if (isObject(seen)) { _errorAtRange(main.t("Duplicate object key"), ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, DiagnosticSeverity.Warning); } keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting } else { keysSeen[key.value] = node; } } if (scanner.getToken() === 6 /* Json.SyntaxKind.ColonToken */) { node.colonOffset = scanner.getTokenOffset(); _scanNext(); // consume ColonToken } else { _error(main.t('Colon expected'), ErrorCode.ColonExpected); if (scanner.getToken() === 10 /* Json.SyntaxKind.StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) { node.length = key.length; return node; } } const value = _parseValue(node); if (!value) { return _error(main.t('Value expected'), ErrorCode.ValueExpected, node, [], [2 /* Json.SyntaxKind.CloseBraceToken */, 5 /* Json.SyntaxKind.CommaToken */]); } node.valueNode = value; node.length = value.offset + value.length - node.offset; return node; } function _parseObject(parent) { if (scanner.getToken() !== 1 /* Json.SyntaxKind.OpenBraceToken */) { return undefined; } const node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset()); const keysSeen = Object.create(null); _scanNext(); // consume OpenBraceToken let needsComma = false; while (scanner.getToken() !== 2 /* Json.SyntaxKind.CloseBraceToken */ && scanner.getToken() !== 17 /* Json.SyntaxKind.EOF */) { if (scanner.getToken() === 5 /* Json.SyntaxKind.CommaToken */) { if (!needsComma) { _error(main.t('Property expected'), ErrorCode.PropertyExpected); } const commaOffset = scanner.getTokenOffset(); _scanNext(); // consume comma if (scanner.getToken() === 2 /* Json.SyntaxKind.CloseBraceToken */) { if (needsComma) { _errorAtRange(main.t('Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1); } continue; } } else if (needsComma) { _error(main.t('Expected comma'), ErrorCode.CommaExpected); } const property = _parseProperty(node, keysSeen); if (!property) { _error(main.t('Property expected'), ErrorCode.PropertyExpected, undefined, [], [2 /* Json.SyntaxKind.CloseBraceToken */, 5 /* Json.SyntaxKind.CommaToken */]); } else { node.properties.push(property); } needsComma = true; } if (scanner.getToken() !== 2 /* Json.SyntaxKind.CloseBraceToken */) { return _error(main.t('Expected comma or closing brace'), ErrorCode.CommaOrCloseBraceExpected, node); } return _finalize(node, true); } function _parseString(parent) { if (scanner.getToken() !== 10 /* Json.SyntaxKind.StringLiteral */) { return undefined; } const node = new StringASTNodeImpl(parent, scanner.getTokenOffset()); node.value = scanner.getTokenValue(); return _finalize(node, true); } function _parseNumber(parent) { if (scanner.getToken() !== 11 /* Json.SyntaxKind.NumericLiteral */) { return undefined; } const node = new NumberASTNodeImpl(parent, scanner.getTokenOffset()); if (scanner.getTokenError() === 0 /* Json.ScanError.None */) { const tokenValue = scanner.getTokenValue(); try { const numberValue = JSON.parse(tokenValue); if (!isNumber(numberValue)) { return _error(main.t('Invalid number format.'), ErrorCode.Undefined, node); } node.value = numberValue; } catch (e) { return _error(main.t('Invalid number format.'), ErrorCode.Undefined, node); } node.isInteger = tokenValue.indexOf('.') === -1; } return _finalize(node, true); } function _parseLiteral(parent) { let node; switch (scanner.getToken()) { case 7 /* Json.SyntaxKind.NullKeyword */: return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true); case 8 /* Json.SyntaxKind.TrueKeyword */: return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true); case 9 /* Json.SyntaxKind.FalseKeyword */: return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true); default: return undefined; } } function _parseValue(parent) { return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent); } let _root = undefined; const token = _scanNext(); if (token !== 17 /* Json.SyntaxKind.EOF */) { _root = _parseValue(_root); if (!_root) { _error(main.t('Expected a JSON object, array or literal.'), ErrorCode.Undefined); } else if (scanner.getToken() !== 17 /* Json.SyntaxKind.EOF */) { _error(main.t('End of file expected.'), ErrorCode.Undefined); } } return new JSONDocument(_root, problems, commentRanges); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/json.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function stringifyObject(obj, indent, stringifyLiteral) { if (obj !== null && typeof obj === 'object') { const newIndent = indent + '\t'; if (Array.isArray(obj)) { if (obj.length === 0) { return '[]'; } let result = '[\n'; for (let i = 0; i < obj.length; i++) { result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral); if (i < obj.length - 1) { result += ','; } result += '\n'; } result += indent + ']'; return result; } else { const keys = Object.keys(obj); if (keys.length === 0) { return '{}'; } let result = '{\n'; for (let i = 0; i < keys.length; i++) { const key = keys[i]; result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral); if (i < keys.length - 1) { result += ','; } result += '\n'; } result += indent + '}'; return result; } } return stringifyLiteral(obj); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonCompletion.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const valueCommitCharacters = [',', '}', ']']; const propertyCommitCharacters = [':']; class JSONCompletion { constructor(schemaService, contributions = [], promiseConstructor = Promise, clientCapabilities = {}) { this.schemaService = schemaService; this.contributions = contributions; this.promiseConstructor = promiseConstructor; this.clientCapabilities = clientCapabilities; } doResolve(item) { for (let i = this.contributions.length - 1; i >= 0; i--) { const resolveCompletion = this.contributions[i].resolveCompletion; if (resolveCompletion) { const resolver = resolveCompletion(item); if (resolver) { return resolver; } } } return this.promiseConstructor.resolve(item); } doComplete(document, position, doc) { const result = { items: [], isIncomplete: false }; const text = document.getText(); const offset = document.offsetAt(position); let node = doc.getNodeFromOffset(offset, true); if (this.isInComment(document, node ? node.offset : 0, offset)) { return Promise.resolve(result); } if (node && (offset === node.offset + node.length) && offset > 0) { const ch = text[offset - 1]; if (node.type === 'object' && ch === '}' || node.type === 'array' && ch === ']') { // after ] or } node = node.parent; } } const currentWord = this.getCurrentWord(document, offset); let overwriteRange; if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { overwriteRange = Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length)); } else { let overwriteStart = offset - currentWord.length; if (overwriteStart > 0 && text[overwriteStart - 1] === '"') { overwriteStart--; } overwriteRange = Range.create(document.positionAt(overwriteStart), position); } const supportsCommitCharacters = false; //this.doesSupportsCommitCharacters(); disabled for now, waiting for new API: https://github.com/microsoft/vscode/issues/42544 const proposed = new Map(); const collector = { add: (suggestion) => { let label = suggestion.label; const existing = proposed.get(label); if (!existing) { label = label.replace(/[\n]/g, '↵'); if (label.length > 60) { const shortendedLabel = label.substr(0, 57).trim() + '...'; if (!proposed.has(shortendedLabel)) { label = shortendedLabel; } } suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText); if (supportsCommitCharacters) { suggestion.commitCharacters = suggestion.kind === CompletionItemKind.Property ? propertyCommitCharacters : valueCommitCharacters; } suggestion.label = label; proposed.set(label, suggestion); result.items.push(suggestion); } else { if (!existing.documentation) { existing.documentation = suggestion.documentation; } if (!existing.detail) { existing.detail = suggestion.detail; } if (!existing.labelDetails) { existing.labelDetails = suggestion.labelDetails; } } }, setAsIncomplete: () => { result.isIncomplete = true; }, error: (message) => { console.error(message); }, getNumberOfProposals: () => { return result.items.length; } }; return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => { const collectionPromises = []; let addValue = true; let currentKey = ''; let currentProperty = undefined; if (node) { if (node.type === 'string') { const parent = node.parent; if (parent && parent.type === 'property' && parent.keyNode === node) { addValue = !parent.valueNode; currentProperty = parent; currentKey = text.substr(node.offset + 1, node.length - 2); if (parent) { node = parent.parent; } } } } // proposals for properties if (node && node.type === 'object') { // don't suggest keys when the cursor is just before the opening curly brace if (node.offset === offset) { return result; } // don't suggest properties that are already present const properties = node.properties; properties.forEach(p => { if (!currentProperty || currentProperty !== p) { proposed.set(p.keyNode.value, CompletionItem.create('__')); } }); let separatorAfter = ''; if (addValue) { separatorAfter = this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end)); } if (schema) { // property proposals with schema this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector); } else { // property proposals without schema this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector); } const location = jsonParser_getNodePath(node); this.contributions.forEach((contribution) => { const collectPromise = contribution.collectPropertyCompletions(document.uri, location, currentWord, addValue, separatorAfter === '', collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); if ((!schema && currentWord.length > 0 && text.charAt(offset - currentWord.length - 1) !== '"')) { collector.add({ kind: CompletionItemKind.Property, label: this.getLabelForValue(currentWord), insertText: this.getInsertTextForProperty(currentWord, undefined, false, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation: '', }); collector.setAsIncomplete(); } } // proposals for values const types = {}; if (schema) { // value proposals with schema this.getValueCompletions(schema, doc, node, offset, document, collector, types); } else { // value proposals without schema this.getSchemaLessValueCompletions(doc, node, offset, document, collector); } if (this.contributions.length > 0) { this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises); } return this.promiseConstructor.all(collectionPromises).then(() => { if (collector.getNumberOfProposals() === 0) { let offsetForSeparator = offset; if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { offsetForSeparator = node.offset + node.length; } const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator); this.addFillerValueCompletions(types, separatorAfter, collector); } return result; }); }); } getPropertyCompletions(schema, doc, node, addValue, separatorAfter, collector) { const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset); matchingSchemas.forEach((s) => { if (s.node === node && !s.inverted) { const schemaProperties = s.schema.properties; if (schemaProperties) { Object.keys(schemaProperties).forEach((key) => { const propertySchema = schemaProperties[key]; if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) { const proposal = { kind: CompletionItemKind.Property, label: key, insertText: this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, filterText: this.getFilterTextForValue(key), documentation: this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '', }; if (propertySchema.suggestSortText !== undefined) { proposal.sortText = propertySchema.suggestSortText; } if (proposal.insertText && endsWith(proposal.insertText, `$1${separatorAfter}`)) { proposal.command = { title: 'Suggest', command: 'editor.action.triggerSuggest' }; } collector.add(proposal); } }); } const schemaPropertyNames = s.schema.propertyNames; if (typeof schemaPropertyNames === 'object' && !schemaPropertyNames.deprecationMessage && !schemaPropertyNames.doNotSuggest) { const propertyNameCompletionItem = (name, enumDescription = undefined) => { const proposal = { kind: CompletionItemKind.Property, label: name, insertText: this.getInsertTextForProperty(name, undefined, addValue, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, filterText: this.getFilterTextForValue(name), documentation: enumDescription || this.fromMarkup(schemaPropertyNames.markdownDescription) || schemaPropertyNames.description || '', }; if (schemaPropertyNames.suggestSortText !== undefined) { proposal.sortText = schemaPropertyNames.suggestSortText; } if (proposal.insertText && endsWith(proposal.insertText, `$1${separatorAfter}`)) { proposal.command = { title: 'Suggest', command: 'editor.action.triggerSuggest' }; } collector.add(proposal); }; if (schemaPropertyNames.enum) { for (let i = 0; i < schemaPropertyNames.enum.length; i++) { let enumDescription = undefined; if (schemaPropertyNames.markdownEnumDescriptions && i < schemaPropertyNames.markdownEnumDescriptions.length) { enumDescription = this.fromMarkup(schemaPropertyNames.markdownEnumDescriptions[i]); } else if (schemaPropertyNames.enumDescriptions && i < schemaPropertyNames.enumDescriptions.length) { enumDescription = schemaPropertyNames.enumDescriptions[i]; } propertyNameCompletionItem(schemaPropertyNames.enum[i], enumDescription); } } if (schemaPropertyNames.const) { propertyNameCompletionItem(schemaPropertyNames.const); } } } }); } getSchemaLessPropertyCompletions(doc, node, currentKey, collector) { const collectCompletionsForSimilarObject = (obj) => { obj.properties.forEach((p) => { const key = p.keyNode.value; collector.add({ kind: CompletionItemKind.Property, label: key, insertText: this.getInsertTextForValue(key, ''), insertTextFormat: InsertTextFormat.Snippet, filterText: this.getFilterTextForValue(key), documentation: '' }); }); }; if (node.parent) { if (node.parent.type === 'property') { // if the object is a property value, check the tree for other objects that hang under a property of the same name const parentKey = node.parent.keyNode.value; doc.visit(n => { if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'object') { collectCompletionsForSimilarObject(n.valueNode); } return true; }); } else if (node.parent.type === 'array') { // if the object is in an array, use all other array elements as similar objects node.parent.items.forEach(n => { if (n.type === 'object' && n !== node) { collectCompletionsForSimilarObject(n); } }); } } else if (node.type === 'object') { collector.add({ kind: CompletionItemKind.Property, label: '$schema', insertText: this.getInsertTextForProperty('$schema', undefined, true, ''), insertTextFormat: InsertTextFormat.Snippet, documentation: '', filterText: this.getFilterTextForValue("$schema") }); } } getSchemaLessValueCompletions(doc, node, offset, document, collector) { let offsetForSeparator = offset; if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { offsetForSeparator = node.offset + node.length; node = node.parent; } if (!node) { collector.add({ kind: this.getSuggestionKind('object'), label: 'Empty object', insertText: this.getInsertTextForValue({}, ''), insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); collector.add({ kind: this.getSuggestionKind('array'), label: 'Empty array', insertText: this.getInsertTextForValue([], ''), insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); return; } const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator); const collectSuggestionsForValues = (value) => { if (value.parent && !jsonParser_contains(value.parent, offset, true)) { collector.add({ kind: this.getSuggestionKind(value.type), label: this.getLabelTextForMatchingNode(value, document), insertText: this.getInsertTextForMatchingNode(value, document, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); } if (value.type === 'boolean') { this.addBooleanValueCompletion(!value.value, separatorAfter, collector); } }; if (node.type === 'property') { if (offset > (node.colonOffset || 0)) { const valueNode = node.valueNode; if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) { return; } // suggest values at the same key const parentKey = node.keyNode.value; doc.visit(n => { if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode) { collectSuggestionsForValues(n.valueNode); } return true; }); if (parentKey === '$schema' && node.parent && !node.parent.parent) { this.addDollarSchemaCompletions(separatorAfter, collector); } } } if (node.type === 'array') { if (node.parent && node.parent.type === 'property') { // suggest items of an array at the same key const parentKey = node.parent.keyNode.value; doc.visit((n) => { if (n.type === 'property' && n.keyNode.value === parentKey && n.valueNode && n.valueNode.type === 'array') { n.valueNode.items.forEach(collectSuggestionsForValues); } return true; }); } else { // suggest items in the same array node.items.forEach(collectSuggestionsForValues); } } } getValueCompletions(schema, doc, node, offset, document, collector, types) { let offsetForSeparator = offset; let parentKey = undefined; let valueNode = undefined; if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) { offsetForSeparator = node.offset + node.length; valueNode = node; node = node.parent; } if (!node) { this.addSchemaValueCompletions(schema.schema, '', collector, types); return; } if ((node.type === 'property') && offset > (node.colonOffset || 0)) { const valueNode = node.valueNode; if (valueNode && offset > (valueNode.offset + valueNode.length)) { return; // we are past the value node } parentKey = node.keyNode.value; node = node.parent; } if (node && (parentKey !== undefined || node.type === 'array')) { const separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator); const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode); for (const s of matchingSchemas) { if (s.node === node && !s.inverted && s.schema) { if (node.type === 'array' && s.schema.items) { let c = collector; if (s.schema.uniqueItems) { const existingValues = new Set(); node.children.forEach(n => { if (n.type !== 'array' && n.type !== 'object') { existingValues.add(this.getLabelForValue(jsonParser_getNodeValue(n))); } }); c = { ...collector, add(suggestion) { if (!existingValues.has(suggestion.label)) { collector.add(suggestion); } } }; } if (Array.isArray(s.schema.items)) { const index = this.findItemAtOffset(node, document, offset); if (index < s.schema.items.length) { this.addSchemaValueCompletions(s.schema.items[index], separatorAfter, c, types); } } else { this.addSchemaValueCompletions(s.schema.items, separatorAfter, c, types); } } if (parentKey !== undefined) { let propertyMatched = false; if (s.schema.properties) { const propertySchema = s.schema.properties[parentKey]; if (propertySchema) { propertyMatched = true; this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types); } } if (s.schema.patternProperties && !propertyMatched) { for (const pattern of Object.keys(s.schema.patternProperties)) { const regex = extendedRegExp(pattern); if (regex?.test(parentKey)) { propertyMatched = true; const propertySchema = s.schema.patternProperties[pattern]; this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types); } } } if (s.schema.additionalProperties && !propertyMatched) { const propertySchema = s.schema.additionalProperties; this.addSchemaValueCompletions(propertySchema, separatorAfter, collector, types); } } } } if (parentKey === '$schema' && !node.parent) { this.addDollarSchemaCompletions(separatorAfter, collector); } if (types['boolean']) { this.addBooleanValueCompletion(true, separatorAfter, collector); this.addBooleanValueCompletion(false, separatorAfter, collector); } if (types['null']) { this.addNullValueCompletion(separatorAfter, collector); } } } getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises) { if (!node) { this.contributions.forEach((contribution) => { const collectPromise = contribution.collectDefaultCompletions(document.uri, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } else { if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') { node = node.parent; } if (node && (node.type === 'property') && offset > (node.colonOffset || 0)) { const parentKey = node.keyNode.value; const valueNode = node.valueNode; if ((!valueNode || offset <= (valueNode.offset + valueNode.length)) && node.parent) { const location = jsonParser_getNodePath(node.parent); this.contributions.forEach((contribution) => { const collectPromise = contribution.collectValueCompletions(document.uri, location, parentKey, collector); if (collectPromise) { collectionPromises.push(collectPromise); } }); } } } } addSchemaValueCompletions(schema, separatorAfter, collector, types) { if (typeof schema === 'object') { this.addEnumValueCompletions(schema, separatorAfter, collector); this.addDefaultValueCompletions(schema, separatorAfter, collector); this.collectTypes(schema, types); if (Array.isArray(schema.allOf)) { schema.allOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types)); } if (Array.isArray(schema.anyOf)) { schema.anyOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types)); } if (Array.isArray(schema.oneOf)) { schema.oneOf.forEach(s => this.addSchemaValueCompletions(s, separatorAfter, collector, types)); } } } addDefaultValueCompletions(schema, separatorAfter, collector, arrayDepth = 0) { let hasProposals = false; if (isDefined(schema.default)) { let type = schema.type; let value = schema.default; for (let i = arrayDepth; i > 0; i--) { value = [value]; type = 'array'; } const completionItem = { kind: this.getSuggestionKind(type), label: this.getLabelForValue(value), insertText: this.getInsertTextForValue(value, separatorAfter), insertTextFormat: InsertTextFormat.Snippet }; if (this.doesSupportsLabelDetails()) { completionItem.labelDetails = { description: main.t('Default value') }; } else { completionItem.detail = main.t('Default value'); } collector.add(completionItem); hasProposals = true; } if (Array.isArray(schema.examples)) { schema.examples.forEach(example => { let type = schema.type; let value = example; for (let i = arrayDepth; i > 0; i--) { value = [value]; type = 'array'; } collector.add({ kind: this.getSuggestionKind(type), label: this.getLabelForValue(value), insertText: this.getInsertTextForValue(value, separatorAfter), insertTextFormat: InsertTextFormat.Snippet }); hasProposals = true; }); } if (Array.isArray(schema.defaultSnippets)) { schema.defaultSnippets.forEach(s => { let type = schema.type; let value = s.body; let label = s.label; let insertText; let filterText; if (isDefined(value)) { let type = schema.type; for (let i = arrayDepth; i > 0; i--) { value = [value]; type = 'array'; } insertText = this.getInsertTextForSnippetValue(value, separatorAfter); filterText = this.getFilterTextForSnippetValue(value); label = label || this.getLabelForSnippetValue(value); } else if (typeof s.bodyText === 'string') { let prefix = '', suffix = '', indent = ''; for (let i = arrayDepth; i > 0; i--) { prefix = prefix + indent + '[\n'; suffix = suffix + '\n' + indent + ']'; indent += '\t'; type = 'array'; } insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter; label = label || insertText, filterText = insertText.replace(/[\n]/g, ''); // remove new lines } else { return; } collector.add({ kind: this.getSuggestionKind(type), label, documentation: this.fromMarkup(s.markdownDescription) || s.description, insertText, insertTextFormat: InsertTextFormat.Snippet, filterText }); hasProposals = true; }); } if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items) && arrayDepth < 5 /* beware of recursion */) { this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1); } } addEnumValueCompletions(schema, separatorAfter, collector) { if (isDefined(schema.const)) { collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(schema.const), insertText: this.getInsertTextForValue(schema.const, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation: this.fromMarkup(schema.markdownDescription) || schema.description }); } if (Array.isArray(schema.enum)) { for (let i = 0, length = schema.enum.length; i < length; i++) { const enm = schema.enum[i]; let documentation = this.fromMarkup(schema.markdownDescription) || schema.description; if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) { documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]); } else if (schema.enumDescriptions && i < schema.enumDescriptions.length) { documentation = schema.enumDescriptions[i]; } collector.add({ kind: this.getSuggestionKind(schema.type), label: this.getLabelForValue(enm), insertText: this.getInsertTextForValue(enm, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation }); } } } collectTypes(schema, types) { if (Array.isArray(schema.enum) || isDefined(schema.const)) { return; } const type = schema.type; if (Array.isArray(type)) { type.forEach(t => types[t] = true); } else if (type) { types[type] = true; } } addFillerValueCompletions(types, separatorAfter, collector) { if (types['object']) { collector.add({ kind: this.getSuggestionKind('object'), label: '{}', insertText: this.getInsertTextForGuessedValue({}, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, detail: main.t('New object'), documentation: '' }); } if (types['array']) { collector.add({ kind: this.getSuggestionKind('array'), label: '[]', insertText: this.getInsertTextForGuessedValue([], separatorAfter), insertTextFormat: InsertTextFormat.Snippet, detail: main.t('New array'), documentation: '' }); } } addBooleanValueCompletion(value, separatorAfter, collector) { collector.add({ kind: this.getSuggestionKind('boolean'), label: value ? 'true' : 'false', insertText: this.getInsertTextForValue(value, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); } addNullValueCompletion(separatorAfter, collector) { collector.add({ kind: this.getSuggestionKind('null'), label: 'null', insertText: 'null' + separatorAfter, insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); } addDollarSchemaCompletions(separatorAfter, collector) { const schemaIds = this.schemaService.getRegisteredSchemaIds(schema => schema === 'http' || schema === 'https'); schemaIds.forEach(schemaId => { if (schemaId.startsWith('http://json-schema.org/draft-')) { schemaId = schemaId + '#'; } collector.add({ kind: CompletionItemKind.Module, label: this.getLabelForValue(schemaId), filterText: this.getFilterTextForValue(schemaId), insertText: this.getInsertTextForValue(schemaId, separatorAfter), insertTextFormat: InsertTextFormat.Snippet, documentation: '' }); }); } getLabelForValue(value) { return JSON.stringify(value); } getValueFromLabel(value) { return JSON.parse(value); } getFilterTextForValue(value) { return JSON.stringify(value); } getFilterTextForSnippetValue(value) { return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1'); } getLabelForSnippetValue(value) { const label = JSON.stringify(value); return label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1'); } getInsertTextForPlainText(text) { return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and } } getInsertTextForValue(value, separatorAfter) { const text = JSON.stringify(value, null, '\t'); if (text === '{}') { return '{$1}' + separatorAfter; } else if (text === '[]') { return '[$1]' + separatorAfter; } return this.getInsertTextForPlainText(text + separatorAfter); } getInsertTextForSnippetValue(value, separatorAfter) { const replacer = (value) => { if (typeof value === 'string') { if (value[0] === '^') { return value.substr(1); } } return JSON.stringify(value); }; return stringifyObject(value, '', replacer) + separatorAfter; } getInsertTextForGuessedValue(value, separatorAfter) { switch (typeof value) { case 'object': if (value === null) { return '${1:null}' + separatorAfter; } return this.getInsertTextForValue(value, separatorAfter); case 'string': let snippetValue = JSON.stringify(value); snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and } return '"${1:' + snippetValue + '}"' + separatorAfter; case 'number': case 'boolean': return '${1:' + JSON.stringify(value) + '}' + separatorAfter; } return this.getInsertTextForValue(value, separatorAfter); } getSuggestionKind(type) { if (Array.isArray(type)) { const array = type; type = array.length > 0 ? array[0] : undefined; } if (!type) { return CompletionItemKind.Value; } switch (type) { case 'string': return CompletionItemKind.Value; case 'object': return CompletionItemKind.Module; case 'property': return CompletionItemKind.Property; default: return CompletionItemKind.Value; } } getLabelTextForMatchingNode(node, document) { switch (node.type) { case 'array': return '[]'; case 'object': return '{}'; default: const content = document.getText().substr(node.offset, node.length); return content; } } getInsertTextForMatchingNode(node, document, separatorAfter) { switch (node.type) { case 'array': return this.getInsertTextForValue([], separatorAfter); case 'object': return this.getInsertTextForValue({}, separatorAfter); default: const content = document.getText().substr(node.offset, node.length) + separatorAfter; return this.getInsertTextForPlainText(content); } } getInsertTextForProperty(key, propertySchema, addValue, separatorAfter) { const propertyText = this.getInsertTextForValue(key, ''); if (!addValue) { return propertyText; } const resultText = propertyText + ': '; let value; let nValueProposals = 0; if (propertySchema) { if (Array.isArray(propertySchema.defaultSnippets)) { if (propertySchema.defaultSnippets.length === 1) { const body = propertySchema.defaultSnippets[0].body; if (isDefined(body)) { value = this.getInsertTextForSnippetValue(body, ''); } } nValueProposals += propertySchema.defaultSnippets.length; } if (propertySchema.enum) { if (!value && propertySchema.enum.length === 1) { value = this.getInsertTextForGuessedValue(propertySchema.enum[0], ''); } nValueProposals += propertySchema.enum.length; } if (isDefined(propertySchema.const)) { if (!value) { value = this.getInsertTextForGuessedValue(propertySchema.const, ''); } nValueProposals++; } if (isDefined(propertySchema.default)) { if (!value) { value = this.getInsertTextForGuessedValue(propertySchema.default, ''); } nValueProposals++; } if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) { if (!value) { value = this.getInsertTextForGuessedValue(propertySchema.examples[0], ''); } nValueProposals += propertySchema.examples.length; } if (nValueProposals === 0) { let type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type; if (!type) { if (propertySchema.properties) { type = 'object'; } else if (propertySchema.items) { type = 'array'; } } switch (type) { case 'boolean': value = '$1'; break; case 'string': value = '"$1"'; break; case 'object': value = '{$1}'; break; case 'array': value = '[$1]'; break; case 'number': case 'integer': value = '${1:0}'; break; case 'null': value = '${1:null}'; break; default: return propertyText; } } } if (!value || nValueProposals > 1) { value = '$1'; } return resultText + value + separatorAfter; } getCurrentWord(document, offset) { let i = offset - 1; const text = document.getText(); while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) { i--; } return text.substring(i + 1, offset); } evaluateSeparatorAfter(document, offset) { const scanner = main_createScanner(document.getText(), true); scanner.setPosition(offset); const token = scanner.scan(); switch (token) { case 5 /* Json.SyntaxKind.CommaToken */: case 2 /* Json.SyntaxKind.CloseBraceToken */: case 4 /* Json.SyntaxKind.CloseBracketToken */: case 17 /* Json.SyntaxKind.EOF */: return ''; default: return ','; } } findItemAtOffset(node, document, offset) { const scanner = main_createScanner(document.getText(), true); const children = node.items; for (let i = children.length - 1; i >= 0; i--) { const child = children[i]; if (offset > child.offset + child.length) { scanner.setPosition(child.offset + child.length); const token = scanner.scan(); if (token === 5 /* Json.SyntaxKind.CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) { return i + 1; } return i; } else if (offset >= child.offset) { return i; } } return 0; } isInComment(document, start, offset) { const scanner = main_createScanner(document.getText(), false); scanner.setPosition(start); let token = scanner.scan(); while (token !== 17 /* Json.SyntaxKind.EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) { token = scanner.scan(); } return (token === 12 /* Json.SyntaxKind.LineCommentTrivia */ || token === 13 /* Json.SyntaxKind.BlockCommentTrivia */) && scanner.getTokenOffset() <= offset; } fromMarkup(markupString) { if (markupString && this.doesSupportMarkdown()) { return { kind: MarkupKind.Markdown, value: markupString }; } return undefined; } doesSupportMarkdown() { if (!isDefined(this.supportsMarkdown)) { const documentationFormat = this.clientCapabilities.textDocument?.completion?.completionItem?.documentationFormat; this.supportsMarkdown = Array.isArray(documentationFormat) && documentationFormat.indexOf(MarkupKind.Markdown) !== -1; } return this.supportsMarkdown; } doesSupportsCommitCharacters() { if (!isDefined(this.supportsCommitCharacters)) { this.labelDetailsSupport = this.clientCapabilities.textDocument?.completion?.completionItem?.commitCharactersSupport; } return this.supportsCommitCharacters; } doesSupportsLabelDetails() { if (!isDefined(this.labelDetailsSupport)) { this.labelDetailsSupport = this.clientCapabilities.textDocument?.completion?.completionItem?.labelDetailsSupport; } return this.labelDetailsSupport; } } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonHover.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ class JSONHover { constructor(schemaService, contributions = [], promiseConstructor) { this.schemaService = schemaService; this.contributions = contributions; this.promise = promiseConstructor || Promise; } doHover(document, position, doc) { const offset = document.offsetAt(position); let node = doc.getNodeFromOffset(offset); if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) { return this.promise.resolve(null); } const hoverRangeNode = node; // use the property description when hovering over an object key if (node.type === 'string') { const parent = node.parent; if (parent && parent.type === 'property' && parent.keyNode === node) { node = parent.valueNode; if (!node) { return this.promise.resolve(null); } } } const hoverRange = Range.create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length)); const createHover = (contents) => { const result = { contents: contents, range: hoverRange }; return result; }; const location = jsonParser_getNodePath(node); for (let i = this.contributions.length - 1; i >= 0; i--) { const contribution = this.contributions[i]; const promise = contribution.getInfoContribution(document.uri, location); if (promise) { return promise.then(htmlContent => createHover(htmlContent)); } } return this.schemaService.getSchemaForResource(document.uri, doc).then((schema) => { if (schema && node) { const matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset); let title = undefined; let markdownDescription = undefined; let markdownEnumValueDescription = undefined, enumValue = undefined; matchingSchemas.every((s) => { if (s.node === node && !s.inverted && s.schema) { title = title || s.schema.title; markdownDescription = markdownDescription || s.schema.markdownDescription || toMarkdown(s.schema.description); if (s.schema.enum) { const idx = s.schema.enum.indexOf(jsonParser_getNodeValue(node)); if (s.schema.markdownEnumDescriptions) { markdownEnumValueDescription = s.schema.markdownEnumDescriptions[idx]; } else if (s.schema.enumDescriptions) { markdownEnumValueDescription = toMarkdown(s.schema.enumDescriptions[idx]); } if (markdownEnumValueDescription) { enumValue = s.schema.enum[idx]; if (typeof enumValue !== 'string') { enumValue = JSON.stringify(enumValue); } } } } return true; }); let result = ''; if (title) { result = toMarkdown(title); } if (markdownDescription) { if (result.length > 0) { result += "\n\n"; } result += markdownDescription; } if (markdownEnumValueDescription) { if (result.length > 0) { result += "\n\n"; } result += `\`${toMarkdownCodeBlock(enumValue)}\`: ${markdownEnumValueDescription}`; } return createHover([result]); } return null; }); } } function toMarkdown(plain) { if (plain) { const res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph) return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } return undefined; } function toMarkdownCodeBlock(content) { // see https://daringfireball.net/projects/markdown/syntax#precode if (content.indexOf('`') !== -1) { return '`` ' + content + ' ``'; } return content; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonValidation.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ class JSONValidation { constructor(jsonSchemaService, promiseConstructor) { this.jsonSchemaService = jsonSchemaService; this.promise = promiseConstructor; this.validationEnabled = true; } configure(raw) { if (raw) { this.validationEnabled = raw.validate !== false; this.commentSeverity = raw.allowComments ? undefined : DiagnosticSeverity.Error; } } doValidation(textDocument, jsonDocument, documentSettings, schema) { if (!this.validationEnabled) { return this.promise.resolve([]); } const diagnostics = []; const added = {}; const addProblem = (problem) => { // remove duplicated messages const signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message; if (!added[signature]) { added[signature] = true; diagnostics.push(problem); } }; const getDiagnostics = (schema) => { let trailingCommaSeverity = documentSettings?.trailingCommas ? toDiagnosticSeverity(documentSettings.trailingCommas) : DiagnosticSeverity.Error; let commentSeverity = documentSettings?.comments ? toDiagnosticSeverity(documentSettings.comments) : this.commentSeverity; let schemaValidation = documentSettings?.schemaValidation ? toDiagnosticSeverity(documentSettings.schemaValidation) : DiagnosticSeverity.Warning; let schemaRequest = documentSettings?.schemaRequest ? toDiagnosticSeverity(documentSettings.schemaRequest) : DiagnosticSeverity.Warning; if (schema) { const addSchemaProblem = (errorMessage, errorCode) => { if (jsonDocument.root && schemaRequest) { const astRoot = jsonDocument.root; const property = astRoot.type === 'object' ? astRoot.properties[0] : undefined; if (property && property.keyNode.value === '$schema') { const node = property.valueNode || property; const range = Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length)); addProblem(Diagnostic.create(range, errorMessage, schemaRequest, errorCode)); } else { const range = Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1)); addProblem(Diagnostic.create(range, errorMessage, schemaRequest, errorCode)); } } }; if (schema.errors.length) { addSchemaProblem(schema.errors[0], ErrorCode.SchemaResolveError); } else if (schemaValidation) { for (const warning of schema.warnings) { addSchemaProblem(warning, ErrorCode.SchemaUnsupportedFeature); } const semanticErrors = jsonDocument.validate(textDocument, schema.schema, schemaValidation, documentSettings?.schemaDraft); if (semanticErrors) { semanticErrors.forEach(addProblem); } } if (schemaAllowsComments(schema.schema)) { commentSeverity = undefined; } if (schemaAllowsTrailingCommas(schema.schema)) { trailingCommaSeverity = undefined; } } for (const p of jsonDocument.syntaxErrors) { if (p.code === ErrorCode.TrailingComma) { if (typeof trailingCommaSeverity !== 'number') { continue; } p.severity = trailingCommaSeverity; } addProblem(p); } if (typeof commentSeverity === 'number') { const message = main.t('Comments are not permitted in JSON.'); jsonDocument.comments.forEach(c => { addProblem(Diagnostic.create(c, message, commentSeverity, ErrorCode.CommentNotPermitted)); }); } return diagnostics; }; if (schema) { const uri = schema.id || ('schemaservice://untitled/' + idCounter++); const handle = this.jsonSchemaService.registerExternalSchema({ uri, schema }); return handle.getResolvedSchema().then(resolvedSchema => { return getDiagnostics(resolvedSchema); }); } return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(schema => { return getDiagnostics(schema); }); } getLanguageStatus(textDocument, jsonDocument) { return { schemas: this.jsonSchemaService.getSchemaURIsForResource(textDocument.uri, jsonDocument) }; } } let idCounter = 0; function schemaAllowsComments(schemaRef) { if (schemaRef && typeof schemaRef === 'object') { if (isBoolean(schemaRef.allowComments)) { return schemaRef.allowComments; } if (schemaRef.allOf) { for (const schema of schemaRef.allOf) { const allow = schemaAllowsComments(schema); if (isBoolean(allow)) { return allow; } } } } return undefined; } function schemaAllowsTrailingCommas(schemaRef) { if (schemaRef && typeof schemaRef === 'object') { if (isBoolean(schemaRef.allowTrailingCommas)) { return schemaRef.allowTrailingCommas; } const deprSchemaRef = schemaRef; if (isBoolean(deprSchemaRef['allowsTrailingCommas'])) { // deprecated return deprSchemaRef['allowsTrailingCommas']; } if (schemaRef.allOf) { for (const schema of schemaRef.allOf) { const allow = schemaAllowsTrailingCommas(schema); if (isBoolean(allow)) { return allow; } } } } return undefined; } function toDiagnosticSeverity(severityLevel) { switch (severityLevel) { case 'error': return DiagnosticSeverity.Error; case 'warning': return DiagnosticSeverity.Warning; case 'ignore': return undefined; } return undefined; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/colors.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const Digit0 = 48; const Digit9 = 57; const A = 65; const a = 97; const f = 102; function hexDigit(charCode) { if (charCode < Digit0) { return 0; } if (charCode <= Digit9) { return charCode - Digit0; } if (charCode < a) { charCode += (a - A); } if (charCode >= a && charCode <= f) { return charCode - a + 10; } return 0; } function colorFromHex(text) { if (text[0] !== '#') { return undefined; } switch (text.length) { case 4: return { red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0, green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0, blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0, alpha: 1 }; case 5: return { red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0, green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0, blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0, alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0, }; case 7: return { red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0, green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0, blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0, alpha: 1 }; case 9: return { red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0, green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0, blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0, alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0 }; } return undefined; } function colorFrom256RGB(red, green, blue, alpha = 1.0) { return { red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha }; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonDocumentSymbols.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ class JSONDocumentSymbols { constructor(schemaService) { this.schemaService = schemaService; } findDocumentSymbols(document, doc, context = { resultLimit: Number.MAX_VALUE }) { const root = doc.root; if (!root) { return []; } let limit = context.resultLimit || Number.MAX_VALUE; // special handling for key bindings const resourceString = document.uri; if ((resourceString === 'vscode://defaultsettings/keybindings.json') || endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) { if (root.type === 'array') { const result = []; for (const item of root.items) { if (item.type === 'object') { for (const property of item.properties) { if (property.keyNode.value === 'key' && property.valueNode) { const location = Location.create(document.uri, getRange(document, item)); result.push({ name: getName(property.valueNode), kind: SymbolKind.Function, location: location }); limit--; if (limit <= 0) { if (context && context.onResultLimitExceeded) { context.onResultLimitExceeded(resourceString); } return result; } } } } } return result; } } const toVisit = [ { node: root, containerName: '' } ]; let nextToVisit = 0; let limitExceeded = false; const result = []; const collectOutlineEntries = (node, containerName) => { if (node.type === 'array') { node.items.forEach(node => { if (node) { toVisit.push({ node, containerName }); } }); } else if (node.type === 'object') { node.properties.forEach((property) => { const valueNode = property.valueNode; if (valueNode) { if (limit > 0) { limit--; const location = Location.create(document.uri, getRange(document, property)); const childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value; result.push({ name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), location: location, containerName: containerName }); toVisit.push({ node: valueNode, containerName: childContainerName }); } else { limitExceeded = true; } } }); } }; // breath first traversal while (nextToVisit < toVisit.length) { const next = toVisit[nextToVisit++]; collectOutlineEntries(next.node, next.containerName); } if (limitExceeded && context && context.onResultLimitExceeded) { context.onResultLimitExceeded(resourceString); } return result; } findDocumentSymbols2(document, doc, context = { resultLimit: Number.MAX_VALUE }) { const root = doc.root; if (!root) { return []; } let limit = context.resultLimit || Number.MAX_VALUE; // special handling for key bindings const resourceString = document.uri; if ((resourceString === 'vscode://defaultsettings/keybindings.json') || endsWith(resourceString.toLowerCase(), '/user/keybindings.json')) { if (root.type === 'array') { const result = []; for (const item of root.items) { if (item.type === 'object') { for (const property of item.properties) { if (property.keyNode.value === 'key' && property.valueNode) { const range = getRange(document, item); const selectionRange = getRange(document, property.keyNode); result.push({ name: getName(property.valueNode), kind: SymbolKind.Function, range, selectionRange }); limit--; if (limit <= 0) { if (context && context.onResultLimitExceeded) { context.onResultLimitExceeded(resourceString); } return result; } } } } } return result; } } const result = []; const toVisit = [ { node: root, result } ]; let nextToVisit = 0; let limitExceeded = false; const collectOutlineEntries = (node, result) => { if (node.type === 'array') { node.items.forEach((node, index) => { if (node) { if (limit > 0) { limit--; const range = getRange(document, node); const selectionRange = range; const name = String(index); const symbol = { name, kind: this.getSymbolKind(node.type), range, selectionRange, children: [] }; result.push(symbol); toVisit.push({ result: symbol.children, node }); } else { limitExceeded = true; } } }); } else if (node.type === 'object') { node.properties.forEach((property) => { const valueNode = property.valueNode; if (valueNode) { if (limit > 0) { limit--; const range = getRange(document, property); const selectionRange = getRange(document, property.keyNode); const children = []; const symbol = { name: this.getKeyLabel(property), kind: this.getSymbolKind(valueNode.type), range, selectionRange, children, detail: this.getDetail(valueNode) }; result.push(symbol); toVisit.push({ result: children, node: valueNode }); } else { limitExceeded = true; } } }); } }; // breath first traversal while (nextToVisit < toVisit.length) { const next = toVisit[nextToVisit++]; collectOutlineEntries(next.node, next.result); } if (limitExceeded && context && context.onResultLimitExceeded) { context.onResultLimitExceeded(resourceString); } return result; } getSymbolKind(nodeType) { switch (nodeType) { case 'object': return SymbolKind.Module; case 'string': return SymbolKind.String; case 'number': return SymbolKind.Number; case 'array': return SymbolKind.Array; case 'boolean': return SymbolKind.Boolean; default: // 'null' return SymbolKind.Variable; } } getKeyLabel(property) { let name = property.keyNode.value; if (name) { name = name.replace(/[\n]/g, '↵'); } if (name && name.trim()) { return name; } return `"${name}"`; } getDetail(node) { if (!node) { return undefined; } if (node.type === 'boolean' || node.type === 'number' || node.type === 'null' || node.type === 'string') { return String(node.value); } else { if (node.type === 'array') { return node.children.length ? undefined : '[]'; } else if (node.type === 'object') { return node.children.length ? undefined : '{}'; } } return undefined; } findDocumentColors(document, doc, context) { return this.schemaService.getSchemaForResource(document.uri, doc).then(schema => { const result = []; if (schema) { let limit = context && typeof context.resultLimit === 'number' ? context.resultLimit : Number.MAX_VALUE; const matchingSchemas = doc.getMatchingSchemas(schema.schema); const visitedNode = {}; for (const s of matchingSchemas) { if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') { const nodeId = String(s.node.offset); if (!visitedNode[nodeId]) { const color = colorFromHex(jsonParser_getNodeValue(s.node)); if (color) { const range = getRange(document, s.node); result.push({ color, range }); } visitedNode[nodeId] = true; limit--; if (limit <= 0) { if (context && context.onResultLimitExceeded) { context.onResultLimitExceeded(document.uri); } return result; } } } } } return result; }); } getColorPresentations(document, doc, color, range) { const result = []; const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255); function toTwoDigitHex(n) { const r = n.toString(16); return r.length !== 2 ? '0' + r : r; } let label; if (color.alpha === 1) { label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`; } else { label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`; } result.push({ label: label, textEdit: TextEdit.replace(range, JSON.stringify(label)) }); return result; } } function getRange(document, node) { return Range.create(document.positionAt(node.offset), document.positionAt(node.offset + node.length)); } function getName(node) { return jsonParser_getNodeValue(node) || main.t(''); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/configuration.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const schemaContributions = { schemaAssociations: [], schemas: { // bundle the schema-schema to include (localized) descriptions 'http://json-schema.org/draft-04/schema#': { '$schema': 'http://json-schema.org/draft-04/schema#', 'definitions': { 'schemaArray': { 'type': 'array', 'minItems': 1, 'items': { '$ref': '#' } }, 'positiveInteger': { 'type': 'integer', 'minimum': 0 }, 'positiveIntegerDefault0': { 'allOf': [ { '$ref': '#/definitions/positiveInteger' }, { 'default': 0 } ] }, 'simpleTypes': { 'type': 'string', 'enum': [ 'array', 'boolean', 'integer', 'null', 'number', 'object', 'string' ] }, 'stringArray': { 'type': 'array', 'items': { 'type': 'string' }, 'minItems': 1, 'uniqueItems': true } }, 'type': 'object', 'properties': { 'id': { 'type': 'string', 'format': 'uri' }, '$schema': { 'type': 'string', 'format': 'uri' }, 'title': { 'type': 'string' }, 'description': { 'type': 'string' }, 'default': {}, 'multipleOf': { 'type': 'number', 'minimum': 0, 'exclusiveMinimum': true }, 'maximum': { 'type': 'number' }, 'exclusiveMaximum': { 'type': 'boolean', 'default': false }, 'minimum': { 'type': 'number' }, 'exclusiveMinimum': { 'type': 'boolean', 'default': false }, 'maxLength': { 'allOf': [ { '$ref': '#/definitions/positiveInteger' } ] }, 'minLength': { 'allOf': [ { '$ref': '#/definitions/positiveIntegerDefault0' } ] }, 'pattern': { 'type': 'string', 'format': 'regex' }, 'additionalItems': { 'anyOf': [ { 'type': 'boolean' }, { '$ref': '#' } ], 'default': {} }, 'items': { 'anyOf': [ { '$ref': '#' }, { '$ref': '#/definitions/schemaArray' } ], 'default': {} }, 'maxItems': { 'allOf': [ { '$ref': '#/definitions/positiveInteger' } ] }, 'minItems': { 'allOf': [ { '$ref': '#/definitions/positiveIntegerDefault0' } ] }, 'uniqueItems': { 'type': 'boolean', 'default': false }, 'maxProperties': { 'allOf': [ { '$ref': '#/definitions/positiveInteger' } ] }, 'minProperties': { 'allOf': [ { '$ref': '#/definitions/positiveIntegerDefault0' } ] }, 'required': { 'allOf': [ { '$ref': '#/definitions/stringArray' } ] }, 'additionalProperties': { 'anyOf': [ { 'type': 'boolean' }, { '$ref': '#' } ], 'default': {} }, 'definitions': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'default': {} }, 'properties': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'default': {} }, 'patternProperties': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'default': {} }, 'dependencies': { 'type': 'object', 'additionalProperties': { 'anyOf': [ { '$ref': '#' }, { '$ref': '#/definitions/stringArray' } ] } }, 'enum': { 'type': 'array', 'minItems': 1, 'uniqueItems': true }, 'type': { 'anyOf': [ { '$ref': '#/definitions/simpleTypes' }, { 'type': 'array', 'items': { '$ref': '#/definitions/simpleTypes' }, 'minItems': 1, 'uniqueItems': true } ] }, 'format': { 'anyOf': [ { 'type': 'string', 'enum': [ 'date-time', 'uri', 'email', 'hostname', 'ipv4', 'ipv6', 'regex' ] }, { 'type': 'string' } ] }, 'allOf': { 'allOf': [ { '$ref': '#/definitions/schemaArray' } ] }, 'anyOf': { 'allOf': [ { '$ref': '#/definitions/schemaArray' } ] }, 'oneOf': { 'allOf': [ { '$ref': '#/definitions/schemaArray' } ] }, 'not': { 'allOf': [ { '$ref': '#' } ] } }, 'dependencies': { 'exclusiveMaximum': [ 'maximum' ], 'exclusiveMinimum': [ 'minimum' ] }, 'default': {} }, 'http://json-schema.org/draft-07/schema#': { 'definitions': { 'schemaArray': { 'type': 'array', 'minItems': 1, 'items': { '$ref': '#' } }, 'nonNegativeInteger': { 'type': 'integer', 'minimum': 0 }, 'nonNegativeIntegerDefault0': { 'allOf': [ { '$ref': '#/definitions/nonNegativeInteger' }, { 'default': 0 } ] }, 'simpleTypes': { 'enum': [ 'array', 'boolean', 'integer', 'null', 'number', 'object', 'string' ] }, 'stringArray': { 'type': 'array', 'items': { 'type': 'string' }, 'uniqueItems': true, 'default': [] } }, 'type': ['object', 'boolean'], 'properties': { '$id': { 'type': 'string', 'format': 'uri-reference' }, '$schema': { 'type': 'string', 'format': 'uri' }, '$ref': { 'type': 'string', 'format': 'uri-reference' }, '$comment': { 'type': 'string' }, 'title': { 'type': 'string' }, 'description': { 'type': 'string' }, 'default': true, 'readOnly': { 'type': 'boolean', 'default': false }, 'examples': { 'type': 'array', 'items': true }, 'multipleOf': { 'type': 'number', 'exclusiveMinimum': 0 }, 'maximum': { 'type': 'number' }, 'exclusiveMaximum': { 'type': 'number' }, 'minimum': { 'type': 'number' }, 'exclusiveMinimum': { 'type': 'number' }, 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' }, 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' }, 'pattern': { 'type': 'string', 'format': 'regex' }, 'additionalItems': { '$ref': '#' }, 'items': { 'anyOf': [ { '$ref': '#' }, { '$ref': '#/definitions/schemaArray' } ], 'default': true }, 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' }, 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' }, 'uniqueItems': { 'type': 'boolean', 'default': false }, 'contains': { '$ref': '#' }, 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' }, 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' }, 'required': { '$ref': '#/definitions/stringArray' }, 'additionalProperties': { '$ref': '#' }, 'definitions': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'default': {} }, 'properties': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'default': {} }, 'patternProperties': { 'type': 'object', 'additionalProperties': { '$ref': '#' }, 'propertyNames': { 'format': 'regex' }, 'default': {} }, 'dependencies': { 'type': 'object', 'additionalProperties': { 'anyOf': [ { '$ref': '#' }, { '$ref': '#/definitions/stringArray' } ] } }, 'propertyNames': { '$ref': '#' }, 'const': true, 'enum': { 'type': 'array', 'items': true, 'minItems': 1, 'uniqueItems': true }, 'type': { 'anyOf': [ { '$ref': '#/definitions/simpleTypes' }, { 'type': 'array', 'items': { '$ref': '#/definitions/simpleTypes' }, 'minItems': 1, 'uniqueItems': true } ] }, 'format': { 'type': 'string' }, 'contentMediaType': { 'type': 'string' }, 'contentEncoding': { 'type': 'string' }, 'if': { '$ref': '#' }, 'then': { '$ref': '#' }, 'else': { '$ref': '#' }, 'allOf': { '$ref': '#/definitions/schemaArray' }, 'anyOf': { '$ref': '#/definitions/schemaArray' }, 'oneOf': { '$ref': '#/definitions/schemaArray' }, 'not': { '$ref': '#' } }, 'default': true } } }; const descriptions = { id: main.t("A unique identifier for the schema."), $schema: main.t("The schema to verify this document against."), title: main.t("A descriptive title of the element."), description: main.t("A long description of the element. Used in hover menus and suggestions."), default: main.t("A default value. Used by suggestions."), multipleOf: main.t("A number that should cleanly divide the current value (i.e. have no remainder)."), maximum: main.t("The maximum numerical value, inclusive by default."), exclusiveMaximum: main.t("Makes the maximum property exclusive."), minimum: main.t("The minimum numerical value, inclusive by default."), exclusiveMinimum: main.t("Makes the minimum property exclusive."), maxLength: main.t("The maximum length of a string."), minLength: main.t("The minimum length of a string."), pattern: main.t("A regular expression to match the string against. It is not implicitly anchored."), additionalItems: main.t("For arrays, only when items is set as an array. If it is a schema, then this schema validates items after the ones specified by the items array. If it is false, then additional items will cause validation to fail."), items: main.t("For arrays. Can either be a schema to validate every element against or an array of schemas to validate each item against in order (the first schema will validate the first element, the second schema will validate the second element, and so on."), maxItems: main.t("The maximum number of items that can be inside an array. Inclusive."), minItems: main.t("The minimum number of items that can be inside an array. Inclusive."), uniqueItems: main.t("If all of the items in the array must be unique. Defaults to false."), maxProperties: main.t("The maximum number of properties an object can have. Inclusive."), minProperties: main.t("The minimum number of properties an object can have. Inclusive."), required: main.t("An array of strings that lists the names of all properties required on this object."), additionalProperties: main.t("Either a schema or a boolean. If a schema, then used to validate all properties not matched by 'properties' or 'patternProperties'. If false, then any properties not matched by either will cause this schema to fail."), definitions: main.t("Not used for validation. Place subschemas here that you wish to reference inline with $ref."), properties: main.t("A map of property names to schemas for each property."), patternProperties: main.t("A map of regular expressions on property names to schemas for matching properties."), dependencies: main.t("A map of property names to either an array of property names or a schema. An array of property names means the property named in the key depends on the properties in the array being present in the object in order to be valid. If the value is a schema, then the schema is only applied to the object if the property in the key exists on the object."), enum: main.t("The set of literal values that are valid."), type: main.t("Either a string of one of the basic schema types (number, integer, null, array, object, boolean, string) or an array of strings specifying a subset of those types."), format: main.t("Describes the format expected for the value."), allOf: main.t("An array of schemas, all of which must match."), anyOf: main.t("An array of schemas, where at least one must match."), oneOf: main.t("An array of schemas, exactly one of which must match."), not: main.t("A schema which must not match."), $id: main.t("A unique identifier for the schema."), $ref: main.t("Reference a definition hosted on any location."), $comment: main.t("Comments from schema authors to readers or maintainers of the schema."), readOnly: main.t("Indicates that the value of the instance is managed exclusively by the owning authority."), examples: main.t("Sample JSON values associated with a particular schema, for the purpose of illustrating usage."), contains: main.t("An array instance is valid against \"contains\" if at least one of its elements is valid against the given schema."), propertyNames: main.t("If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema."), const: main.t("An instance validates successfully against this keyword if its value is equal to the value of the keyword."), contentMediaType: main.t("Describes the media type of a string property."), contentEncoding: main.t("Describes the content encoding of a string property."), if: main.t("The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."), then: main.t("The \"if\" subschema is used for validation when the \"if\" subschema succeeds."), else: main.t("The \"else\" subschema is used for validation when the \"if\" subschema fails.") }; for (const schemaName in schemaContributions.schemas) { const schema = schemaContributions.schemas[schemaName]; for (const property in schema.properties) { let propertyObject = schema.properties[property]; if (typeof propertyObject === 'boolean') { propertyObject = schema.properties[property] = {}; } const description = descriptions[property]; if (description) { propertyObject['description'] = description; } } } ;// CONCATENATED MODULE: ./node_modules/vscode-uri/lib/esm/index.mjs 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(h2){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;r0&&(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;ic){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=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;r1&&"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: esm_URI,Utils}=LIB; //# sourceMappingURL=index.mjs.map ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/glob.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) 2013, Nick Fitzgerald * Licensed under the MIT License. See LICENCE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ function createRegex(glob, opts) { if (typeof glob !== 'string') { throw new TypeError('Expected a string'); } const str = String(glob); // The regexp we are building, as a string. let reStr = ""; // Whether we are matching so called "extended" globs (like bash) and should // support single character matching, matching ranges of characters, group // matching, etc. const extended = opts ? !!opts.extended : false; // When globstar is _false_ (default), '/foo/*' is translated a regexp like // '^\/foo\/.*$' which will match any string beginning with '/foo/' // When globstar is _true_, '/foo/*' is translated to regexp like // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT // which does not have a '/' to the right of it. // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but // these will not '/foo/bar/baz', '/foo/bar/baz.txt' // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when // globstar is _false_ const globstar = opts ? !!opts.globstar : false; // If we are doing extended matching, this boolean is true when we are inside // a group (eg {*.html,*.js}), and false otherwise. let inGroup = false; // RegExp flags (eg "i" ) to pass in to RegExp constructor. const flags = opts && typeof (opts.flags) === "string" ? opts.flags : ""; let c; for (let i = 0, len = str.length; i < len; i++) { c = str[i]; switch (c) { case "/": case "$": case "^": case "+": case ".": case "(": case ")": case "=": case "!": case "|": reStr += "\\" + c; break; case "?": if (extended) { reStr += "."; break; } case "[": case "]": if (extended) { reStr += c; break; } case "{": if (extended) { inGroup = true; reStr += "("; break; } case "}": if (extended) { inGroup = false; reStr += ")"; break; } case ",": if (inGroup) { reStr += "|"; break; } reStr += "\\" + c; break; case "*": // Move over all consecutive "*"'s. // Also store the previous and next characters const prevChar = str[i - 1]; let starCount = 1; while (str[i + 1] === "*") { starCount++; i++; } const nextChar = str[i + 1]; if (!globstar) { // globstar is disabled, so treat any number of "*" as one reStr += ".*"; } else { // globstar is enabled, so determine if this is a globstar segment const isGlobstar = starCount > 1 // multiple "*"'s && (prevChar === "/" || prevChar === undefined || prevChar === '{' || prevChar === ',') // from the start of the segment && (nextChar === "/" || nextChar === undefined || nextChar === ',' || nextChar === '}'); // to the end of the segment if (isGlobstar) { if (nextChar === "/") { i++; // move over the "/" } else if (prevChar === '/' && reStr.endsWith('\\/')) { reStr = reStr.substr(0, reStr.length - 2); } // it's a globstar, so match zero or more path segments reStr += "((?:[^/]*(?:\/|$))*)"; } else { // it's not a globstar, so only match one path segment reStr += "([^/]*)"; } } break; default: reStr += c; } } // When regexp 'g' flag is specified don't // constrain the regular expression with ^ & $ if (!flags || !~flags.indexOf('g')) { reStr = "^" + reStr + "$"; } return new RegExp(reStr, flags); } ; ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonSchemaService.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const BANG = '!'; const PATH_SEP = '/'; class FilePatternAssociation { constructor(pattern, folderUri, uris) { this.folderUri = folderUri; this.uris = uris; this.globWrappers = []; try { for (let patternString of pattern) { const include = patternString[0] !== BANG; if (!include) { patternString = patternString.substring(1); } if (patternString.length > 0) { if (patternString[0] === PATH_SEP) { patternString = patternString.substring(1); } this.globWrappers.push({ regexp: createRegex('**/' + patternString, { extended: true, globstar: true }), include: include, }); } } ; if (folderUri) { folderUri = normalizeResourceForMatching(folderUri); if (!folderUri.endsWith('/')) { folderUri = folderUri + '/'; } this.folderUri = folderUri; } } catch (e) { this.globWrappers.length = 0; this.uris = []; } } matchesPattern(fileName) { if (this.folderUri && !fileName.startsWith(this.folderUri)) { return false; } let match = false; for (const { regexp, include } of this.globWrappers) { if (regexp.test(fileName)) { match = include; } } return match; } getURIs() { return this.uris; } } class SchemaHandle { constructor(service, uri, unresolvedSchemaContent) { this.service = service; this.uri = uri; this.dependencies = new Set(); this.anchors = undefined; if (unresolvedSchemaContent) { this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent)); } } getUnresolvedSchema() { if (!this.unresolvedSchema) { this.unresolvedSchema = this.service.loadSchema(this.uri); } return this.unresolvedSchema; } getResolvedSchema() { if (!this.resolvedSchema) { this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => { return this.service.resolveSchemaContent(unresolved, this); }); } return this.resolvedSchema; } clearSchema() { const hasChanges = !!this.unresolvedSchema; this.resolvedSchema = undefined; this.unresolvedSchema = undefined; this.dependencies.clear(); this.anchors = undefined; return hasChanges; } } class UnresolvedSchema { constructor(schema, errors = []) { this.schema = schema; this.errors = errors; } } class ResolvedSchema { constructor(schema, errors = [], warnings = [], schemaDraft) { this.schema = schema; this.errors = errors; this.warnings = warnings; this.schemaDraft = schemaDraft; } getSection(path) { const schemaRef = this.getSectionRecursive(path, this.schema); if (schemaRef) { return asSchema(schemaRef); } return undefined; } getSectionRecursive(path, schema) { if (!schema || typeof schema === 'boolean' || path.length === 0) { return schema; } const next = path.shift(); if (schema.properties && typeof schema.properties[next]) { return this.getSectionRecursive(path, schema.properties[next]); } else if (schema.patternProperties) { for (const pattern of Object.keys(schema.patternProperties)) { const regex = extendedRegExp(pattern); if (regex?.test(next)) { return this.getSectionRecursive(path, schema.patternProperties[pattern]); } } } else if (typeof schema.additionalProperties === 'object') { return this.getSectionRecursive(path, schema.additionalProperties); } else if (next.match('[0-9]+')) { if (Array.isArray(schema.items)) { const index = parseInt(next, 10); if (!isNaN(index) && schema.items[index]) { return this.getSectionRecursive(path, schema.items[index]); } } else if (schema.items) { return this.getSectionRecursive(path, schema.items); } } return undefined; } } class JSONSchemaService { constructor(requestService, contextService, promiseConstructor) { this.contextService = contextService; this.requestService = requestService; this.promiseConstructor = promiseConstructor || Promise; this.callOnDispose = []; this.contributionSchemas = {}; this.contributionAssociations = []; this.schemasById = {}; this.filePatternAssociations = []; this.registeredSchemasIds = {}; } getRegisteredSchemaIds(filter) { return Object.keys(this.registeredSchemasIds).filter(id => { const scheme = esm_URI.parse(id).scheme; return scheme !== 'schemaservice' && (!filter || filter(scheme)); }); } get promise() { return this.promiseConstructor; } dispose() { while (this.callOnDispose.length > 0) { this.callOnDispose.pop()(); } } onResourceChange(uri) { // always clear this local cache when a resource changes this.cachedSchemaForResource = undefined; let hasChanges = false; uri = normalizeId(uri); const toWalk = [uri]; const all = Object.keys(this.schemasById).map(key => this.schemasById[key]); while (toWalk.length) { const curr = toWalk.pop(); for (let i = 0; i < all.length; i++) { const handle = all[i]; if (handle && (handle.uri === curr || handle.dependencies.has(curr))) { if (handle.uri !== curr) { toWalk.push(handle.uri); } if (handle.clearSchema()) { hasChanges = true; } all[i] = undefined; } } } return hasChanges; } setSchemaContributions(schemaContributions) { if (schemaContributions.schemas) { const schemas = schemaContributions.schemas; for (const id in schemas) { const normalizedId = normalizeId(id); this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]); } } if (Array.isArray(schemaContributions.schemaAssociations)) { const schemaAssociations = schemaContributions.schemaAssociations; for (let schemaAssociation of schemaAssociations) { const uris = schemaAssociation.uris.map(normalizeId); const association = this.addFilePatternAssociation(schemaAssociation.pattern, schemaAssociation.folderUri, uris); this.contributionAssociations.push(association); } } } addSchemaHandle(id, unresolvedSchemaContent) { const schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent); this.schemasById[id] = schemaHandle; return schemaHandle; } getOrAddSchemaHandle(id, unresolvedSchemaContent) { return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent); } addFilePatternAssociation(pattern, folderUri, uris) { const fpa = new FilePatternAssociation(pattern, folderUri, uris); this.filePatternAssociations.push(fpa); return fpa; } registerExternalSchema(config) { const id = normalizeId(config.uri); this.registeredSchemasIds[id] = true; this.cachedSchemaForResource = undefined; if (config.fileMatch && config.fileMatch.length) { this.addFilePatternAssociation(config.fileMatch, config.folderUri, [id]); } return config.schema ? this.addSchemaHandle(id, config.schema) : this.getOrAddSchemaHandle(id); } clearExternalSchemas() { this.schemasById = {}; this.filePatternAssociations = []; this.registeredSchemasIds = {}; this.cachedSchemaForResource = undefined; for (const id in this.contributionSchemas) { this.schemasById[id] = this.contributionSchemas[id]; this.registeredSchemasIds[id] = true; } for (const contributionAssociation of this.contributionAssociations) { this.filePatternAssociations.push(contributionAssociation); } } getResolvedSchema(schemaId) { const id = normalizeId(schemaId); const schemaHandle = this.schemasById[id]; if (schemaHandle) { return schemaHandle.getResolvedSchema(); } return this.promise.resolve(undefined); } loadSchema(url) { if (!this.requestService) { const errorMessage = main.t('Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url)); return this.promise.resolve(new UnresolvedSchema({}, [errorMessage])); } if (url.startsWith('http://json-schema.org/')) { url = 'https' + url.substring(4); // always access json-schema.org with https. See https://github.com/microsoft/vscode/issues/195189 } return this.requestService(url).then(content => { if (!content) { const errorMessage = main.t('Unable to load schema from \'{0}\': No content.', toDisplayString(url)); return new UnresolvedSchema({}, [errorMessage]); } const errors = []; if (content.charCodeAt(0) === 65279) { errors.push(main.t('Problem reading content from \'{0}\': UTF-8 with BOM detected, only UTF 8 is allowed.', toDisplayString(url))); content = content.trimStart(); } let schemaContent = {}; const jsonErrors = []; schemaContent = main_parse(content, jsonErrors); if (jsonErrors.length) { errors.push(main.t('Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)); } return new UnresolvedSchema(schemaContent, errors); }, (error) => { let errorMessage = error.toString(); const errorSplit = error.toString().split('Error: '); if (errorSplit.length > 1) { // more concise error message, URL and context are attached by caller anyways errorMessage = errorSplit[1]; } if (endsWith(errorMessage, '.')) { errorMessage = errorMessage.substr(0, errorMessage.length - 1); } return new UnresolvedSchema({}, [main.t('Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]); }); } resolveSchemaContent(schemaToResolve, handle) { const resolveErrors = schemaToResolve.errors.slice(0); const schema = schemaToResolve.schema; let schemaDraft = schema.$schema ? normalizeId(schema.$schema) : undefined; if (schemaDraft === 'http://json-schema.org/draft-03/schema') { return this.promise.resolve(new ResolvedSchema({}, [main.t("Draft-03 schemas are not supported.")], [], schemaDraft)); } let usesUnsupportedFeatures = new Set(); const contextService = this.contextService; const findSectionByJSONPointer = (schema, path) => { path = decodeURIComponent(path); let current = schema; if (path[0] === '/') { path = path.substring(1); } path.split('/').some((part) => { part = part.replace(/~1/g, '/').replace(/~0/g, '~'); current = current[part]; return !current; }); return current; }; const findSchemaById = (schema, handle, id) => { if (!handle.anchors) { handle.anchors = collectAnchors(schema); } return handle.anchors.get(id); }; const merge = (target, section) => { for (const key in section) { if (section.hasOwnProperty(key) && key !== 'id' && key !== '$id') { target[key] = section[key]; } } }; const mergeRef = (target, sourceRoot, sourceHandle, refSegment) => { let section; if (refSegment === undefined || refSegment.length === 0) { section = sourceRoot; } else if (refSegment.charAt(0) === '/') { // A $ref to a JSON Pointer (i.e #/definitions/foo) section = findSectionByJSONPointer(sourceRoot, refSegment); } else { // A $ref to a sub-schema with an $id (i.e #hello) section = findSchemaById(sourceRoot, sourceHandle, refSegment); } if (section) { merge(target, section); } else { resolveErrors.push(main.t('$ref \'{0}\' in \'{1}\' can not be resolved.', refSegment || '', sourceHandle.uri)); } }; const resolveExternalLink = (node, uri, refSegment, parentHandle) => { if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/\/.*/.test(uri)) { uri = contextService.resolveRelativePath(uri, parentHandle.uri); } uri = normalizeId(uri); const referencedHandle = this.getOrAddSchemaHandle(uri); return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => { parentHandle.dependencies.add(uri); if (unresolvedSchema.errors.length) { const loc = refSegment ? uri + '#' + refSegment : uri; resolveErrors.push(main.t('Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0])); } mergeRef(node, unresolvedSchema.schema, referencedHandle, refSegment); return resolveRefs(node, unresolvedSchema.schema, referencedHandle); }); }; const resolveRefs = (node, parentSchema, parentHandle) => { const openPromises = []; this.traverseNodes(node, next => { const seenRefs = new Set(); while (next.$ref) { const ref = next.$ref; const segments = ref.split('#', 2); delete next.$ref; if (segments[0].length > 0) { // This is a reference to an external schema openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentHandle)); return; } else { // This is a reference inside the current schema if (!seenRefs.has(ref)) { const id = segments[1]; mergeRef(next, parentSchema, parentHandle, id); seenRefs.add(ref); } } } if (next.$recursiveRef) { usesUnsupportedFeatures.add('$recursiveRef'); } if (next.$dynamicRef) { usesUnsupportedFeatures.add('$dynamicRef'); } }); return this.promise.all(openPromises); }; const collectAnchors = (root) => { const result = new Map(); this.traverseNodes(root, next => { const id = next.$id || next.id; const anchor = isString(id) && id.charAt(0) === '#' ? id.substring(1) : next.$anchor; if (anchor) { if (result.has(anchor)) { resolveErrors.push(main.t('Duplicate anchor declaration: \'{0}\'', anchor)); } else { result.set(anchor, next); } } if (next.$recursiveAnchor) { usesUnsupportedFeatures.add('$recursiveAnchor'); } if (next.$dynamicAnchor) { usesUnsupportedFeatures.add('$dynamicAnchor'); } }); return result; }; return resolveRefs(schema, schema, handle).then(_ => { let resolveWarnings = []; if (usesUnsupportedFeatures.size) { resolveWarnings.push(main.t('The schema uses meta-schema features ({0}) that are not yet supported by the validator.', Array.from(usesUnsupportedFeatures.keys()).join(', '))); } return new ResolvedSchema(schema, resolveErrors, resolveWarnings, schemaDraft); }); } traverseNodes(root, handle) { if (!root || typeof root !== 'object') { return Promise.resolve(null); } const seen = new Set(); const collectEntries = (...entries) => { for (const entry of entries) { if (isObject(entry)) { toWalk.push(entry); } } }; const collectMapEntries = (...maps) => { for (const map of maps) { if (isObject(map)) { for (const k in map) { const key = k; const entry = map[key]; if (isObject(entry)) { toWalk.push(entry); } } } } }; const collectArrayEntries = (...arrays) => { for (const array of arrays) { if (Array.isArray(array)) { for (const entry of array) { if (isObject(entry)) { toWalk.push(entry); } } } } }; const collectEntryOrArrayEntries = (items) => { if (Array.isArray(items)) { for (const entry of items) { if (isObject(entry)) { toWalk.push(entry); } } } else if (isObject(items)) { toWalk.push(items); } }; const toWalk = [root]; let next = toWalk.pop(); while (next) { if (!seen.has(next)) { seen.add(next); handle(next); collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties); collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, next.dependencies, next.dependentSchemas); collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems); collectEntryOrArrayEntries(next.items); } next = toWalk.pop(); } } ; getSchemaFromProperty(resource, document) { if (document.root?.type === 'object') { for (const p of document.root.properties) { if (p.keyNode.value === '$schema' && p.valueNode?.type === 'string') { let schemaId = p.valueNode.value; if (this.contextService && !/^\w[\w\d+.-]*:/.test(schemaId)) { // has scheme schemaId = this.contextService.resolveRelativePath(schemaId, resource); } return schemaId; } } } return undefined; } getAssociatedSchemas(resource) { const seen = Object.create(null); const schemas = []; const normalizedResource = normalizeResourceForMatching(resource); for (const entry of this.filePatternAssociations) { if (entry.matchesPattern(normalizedResource)) { for (const schemaId of entry.getURIs()) { if (!seen[schemaId]) { schemas.push(schemaId); seen[schemaId] = true; } } } } return schemas; } getSchemaURIsForResource(resource, document) { let schemeId = document && this.getSchemaFromProperty(resource, document); if (schemeId) { return [schemeId]; } return this.getAssociatedSchemas(resource); } getSchemaForResource(resource, document) { if (document) { // first use $schema if present let schemeId = this.getSchemaFromProperty(resource, document); if (schemeId) { const id = normalizeId(schemeId); return this.getOrAddSchemaHandle(id).getResolvedSchema(); } } if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) { return this.cachedSchemaForResource.resolvedSchema; } const schemas = this.getAssociatedSchemas(resource); const resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined); this.cachedSchemaForResource = { resource, resolvedSchema }; return resolvedSchema; } createCombinedSchema(resource, schemaIds) { if (schemaIds.length === 1) { return this.getOrAddSchemaHandle(schemaIds[0]); } else { const combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource); const combinedSchema = { allOf: schemaIds.map(schemaId => ({ $ref: schemaId })) }; return this.addSchemaHandle(combinedSchemaId, combinedSchema); } } getMatchingSchemas(document, jsonDocument, schema) { if (schema) { const id = schema.id || ('schemaservice://untitled/matchingSchemas/' + jsonSchemaService_idCounter++); const handle = this.addSchemaHandle(id, schema); return handle.getResolvedSchema().then(resolvedSchema => { return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(s => !s.inverted); }); } return this.getSchemaForResource(document.uri, jsonDocument).then(schema => { if (schema) { return jsonDocument.getMatchingSchemas(schema.schema).filter(s => !s.inverted); } return []; }); } } let jsonSchemaService_idCounter = 0; function normalizeId(id) { // remove trailing '#', normalize drive capitalization try { return esm_URI.parse(id).toString(true); } catch (e) { return id; } } function normalizeResourceForMatching(resource) { // remove queries and fragments, normalize drive capitalization try { return esm_URI.parse(resource).with({ fragment: null, query: null }).toString(true); } catch (e) { return resource; } } function toDisplayString(url) { try { const uri = esm_URI.parse(url); if (uri.scheme === 'file') { return uri.fsPath; } } catch (e) { // ignore } return url; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonFolding.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function getFoldingRanges(document, context) { const ranges = []; const nestingLevels = []; const stack = []; let prevStart = -1; const scanner = main_createScanner(document.getText(), false); let token = scanner.scan(); function addRange(range) { ranges.push(range); nestingLevels.push(stack.length); } while (token !== 17 /* SyntaxKind.EOF */) { switch (token) { case 1 /* SyntaxKind.OpenBraceToken */: case 3 /* SyntaxKind.OpenBracketToken */: { const startLine = document.positionAt(scanner.getTokenOffset()).line; const range = { startLine, endLine: startLine, kind: token === 1 /* SyntaxKind.OpenBraceToken */ ? 'object' : 'array' }; stack.push(range); break; } case 2 /* SyntaxKind.CloseBraceToken */: case 4 /* SyntaxKind.CloseBracketToken */: { const kind = token === 2 /* SyntaxKind.CloseBraceToken */ ? 'object' : 'array'; if (stack.length > 0 && stack[stack.length - 1].kind === kind) { const range = stack.pop(); const line = document.positionAt(scanner.getTokenOffset()).line; if (range && line > range.startLine + 1 && prevStart !== range.startLine) { range.endLine = line - 1; addRange(range); prevStart = range.startLine; } } break; } case 13 /* SyntaxKind.BlockCommentTrivia */: { const startLine = document.positionAt(scanner.getTokenOffset()).line; const endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line; if (scanner.getTokenError() === 1 /* ScanError.UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) { scanner.setPosition(document.offsetAt(Position.create(startLine + 1, 0))); } else { if (startLine < endLine) { addRange({ startLine, endLine, kind: FoldingRangeKind.Comment }); prevStart = startLine; } } break; } case 12 /* SyntaxKind.LineCommentTrivia */: { const text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength()); const m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/); if (m) { const line = document.positionAt(scanner.getTokenOffset()).line; if (m[1]) { // start pattern match const range = { startLine: line, endLine: line, kind: FoldingRangeKind.Region }; stack.push(range); } else { let i = stack.length - 1; while (i >= 0 && stack[i].kind !== FoldingRangeKind.Region) { i--; } if (i >= 0) { const range = stack[i]; stack.length = i; if (line > range.startLine && prevStart !== range.startLine) { range.endLine = line; addRange(range); prevStart = range.startLine; } } } } break; } } token = scanner.scan(); } const rangeLimit = context && context.rangeLimit; if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) { return ranges; } if (context && context.onRangeLimitExceeded) { context.onRangeLimitExceeded(document.uri); } const counts = []; for (let level of nestingLevels) { if (level < 30) { counts[level] = (counts[level] || 0) + 1; } } let entries = 0; let maxLevel = 0; for (let i = 0; i < counts.length; i++) { const n = counts[i]; if (n) { if (n + entries > rangeLimit) { maxLevel = i; break; } entries += n; } } const result = []; for (let i = 0; i < ranges.length; i++) { const level = nestingLevels[i]; if (typeof level === 'number') { if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) { result.push(ranges[i]); } } } return result; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonSelectionRanges.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function getSelectionRanges(document, positions, doc) { function getSelectionRange(position) { let offset = document.offsetAt(position); let node = doc.getNodeFromOffset(offset, true); const result = []; while (node) { switch (node.type) { case 'string': case 'object': case 'array': // range without ", [ or { const cStart = node.offset + 1, cEnd = node.offset + node.length - 1; if (cStart < cEnd && offset >= cStart && offset <= cEnd) { result.push(newRange(cStart, cEnd)); } result.push(newRange(node.offset, node.offset + node.length)); break; case 'number': case 'boolean': case 'null': case 'property': result.push(newRange(node.offset, node.offset + node.length)); break; } if (node.type === 'property' || node.parent && node.parent.type === 'array') { const afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* SyntaxKind.CommaToken */); if (afterCommaOffset !== -1) { result.push(newRange(node.offset, afterCommaOffset)); } } node = node.parent; } let current = undefined; for (let index = result.length - 1; index >= 0; index--) { current = SelectionRange.create(result[index], current); } if (!current) { current = SelectionRange.create(Range.create(position, position)); } return current; } function newRange(start, end) { return Range.create(document.positionAt(start), document.positionAt(end)); } const scanner = main_createScanner(document.getText(), true); function getOffsetAfterNextToken(offset, expectedToken) { scanner.setPosition(offset); let token = scanner.scan(); if (token === expectedToken) { return scanner.getTokenOffset() + scanner.getTokenLength(); } return -1; } return positions.map(getSelectionRange); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/format.js function utils_format_format(documentToFormat, formattingOptions, formattingRange) { let range = undefined; if (formattingRange) { const offset = documentToFormat.offsetAt(formattingRange.start); const length = documentToFormat.offsetAt(formattingRange.end) - offset; range = { offset, length }; } const options = { tabSize: formattingOptions ? formattingOptions.tabSize : 4, insertSpaces: formattingOptions?.insertSpaces === true, insertFinalNewline: formattingOptions?.insertFinalNewline === true, eol: '\n', keepLines: formattingOptions?.keepLines === true }; return main_format(documentToFormat.getText(), range, options).map(edit => { return TextEdit.replace(Range.create(documentToFormat.positionAt(edit.offset), documentToFormat.positionAt(edit.offset + edit.length)), edit.content); }); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/propertyTree.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var Container; (function (Container) { Container[Container["Object"] = 0] = "Object"; Container[Container["Array"] = 1] = "Array"; })(Container || (Container = {})); class PropertyTree { constructor(propertyName, beginningLineNumber) { this.propertyName = propertyName ?? ''; this.beginningLineNumber = beginningLineNumber; this.childrenProperties = []; this.lastProperty = false; this.noKeyName = false; } addChildProperty(childProperty) { childProperty.parent = this; if (this.childrenProperties.length > 0) { let insertionIndex = 0; if (childProperty.noKeyName) { insertionIndex = this.childrenProperties.length; } else { insertionIndex = binarySearchOnPropertyArray(this.childrenProperties, childProperty, compareProperties); } if (insertionIndex < 0) { insertionIndex = (insertionIndex * -1) - 1; } this.childrenProperties.splice(insertionIndex, 0, childProperty); } else { this.childrenProperties.push(childProperty); } return childProperty; } } function compareProperties(propertyTree1, propertyTree2) { const propertyName1 = propertyTree1.propertyName.toLowerCase(); const propertyName2 = propertyTree2.propertyName.toLowerCase(); if (propertyName1 < propertyName2) { return -1; } else if (propertyName1 > propertyName2) { return 1; } return 0; } function binarySearchOnPropertyArray(propertyTreeArray, propertyTree, compare_fn) { const propertyName = propertyTree.propertyName.toLowerCase(); const firstPropertyInArrayName = propertyTreeArray[0].propertyName.toLowerCase(); const lastPropertyInArrayName = propertyTreeArray[propertyTreeArray.length - 1].propertyName.toLowerCase(); if (propertyName < firstPropertyInArrayName) { return 0; } if (propertyName > lastPropertyInArrayName) { return propertyTreeArray.length; } let m = 0; let n = propertyTreeArray.length - 1; while (m <= n) { let k = (n + m) >> 1; let cmp = compare_fn(propertyTree, propertyTreeArray[k]); if (cmp > 0) { m = k + 1; } else if (cmp < 0) { n = k - 1; } else { return k; } } return -m - 1; } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/utils/sort.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // import { TextEdit} from 'vscode-languageserver-textdocument'; function sort(documentToSort, formattingOptions) { const options = { ...formattingOptions, keepLines: false, // keepLines must be false so that the properties are on separate lines for the sorting }; const formattedJsonString = main_TextDocument.applyEdits(documentToSort, utils_format_format(documentToSort, options, undefined)); const formattedJsonDocument = main_TextDocument.create('test://test.json', 'json', 0, formattedJsonString); const jsonPropertyTree = findJsoncPropertyTree(formattedJsonDocument); const sortedJsonDocument = sortJsoncDocument(formattedJsonDocument, jsonPropertyTree); const edits = utils_format_format(sortedJsonDocument, options, undefined); const sortedAndFormattedJsonDocument = main_TextDocument.applyEdits(sortedJsonDocument, edits); return [TextEdit.replace(Range.create(Position.create(0, 0), documentToSort.positionAt(documentToSort.getText().length)), sortedAndFormattedJsonDocument)]; } function findJsoncPropertyTree(formattedDocument) { const formattedString = formattedDocument.getText(); const scanner = main_createScanner(formattedString, false); // The tree that will be returned let rootTree = new PropertyTree(); // The tree where the current properties can be added as children let currentTree = rootTree; // The tree representing the current property analyzed let currentProperty = rootTree; // The tree representing the previous property analyzed let lastProperty = rootTree; // The current scanned token let token = undefined; // Line number of the last token found let lastTokenLine = 0; // Total number of characters on the lines prior to current line let numberOfCharactersOnPreviousLines = 0; // The last token scanned that is not trivial, nor a comment let lastNonTriviaNonCommentToken = undefined; // The second to last token scanned that is not trivial, nor a comment let secondToLastNonTriviaNonCommentToken = undefined; // Line number of last token that is not trivial, nor a comment let lineOfLastNonTriviaNonCommentToken = -1; // End index on its line of last token that is not trivial, nor a comment let endIndexOfLastNonTriviaNonCommentToken = -1; // Line number of the start of the range of current/next property let beginningLineNumber = 0; // Line number of the end of the range of current/next property let endLineNumber = 0; // Stack indicating whether we are inside of an object or an array let currentContainerStack = []; // Boolean indicating that the current property end line number needs to be updated. Used only when block comments are encountered. let updateLastPropertyEndLineNumber = false; // Boolean indicating that the beginning line number should be updated. Used only when block comments are encountered. let updateBeginningLineNumber = false; while ((token = scanner.scan()) !== 17 /* SyntaxKind.EOF */) { // In the case when a block comment has been encountered that starts on the same line as the comma ending a property, update the end line of that // property so that it covers the block comment. For example, if we have: // 1. "key" : {}, /* some block // 2. comment */ // Then, the end line of the property "key" should be line 2 not line 1 if (updateLastPropertyEndLineNumber === true && token !== 14 /* SyntaxKind.LineBreakTrivia */ && token !== 15 /* SyntaxKind.Trivia */ && token !== 12 /* SyntaxKind.LineCommentTrivia */ && token !== 13 /* SyntaxKind.BlockCommentTrivia */ && currentProperty.endLineNumber === undefined) { let endLineNumber = scanner.getTokenStartLine(); // Update the end line number in the case when the last property visited is a container (object or array) if (secondToLastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || secondToLastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */) { lastProperty.endLineNumber = endLineNumber - 1; } // Update the end line number in the case when the last property visited is a simple property else { currentProperty.endLineNumber = endLineNumber - 1; } beginningLineNumber = endLineNumber; updateLastPropertyEndLineNumber = false; } // When a block comment follows an open brace or an open bracket, that block comment should be associated to that brace or bracket, not the property below it. For example, for: // 1. { /* // 2. ... */ // 3. "key" : {} // 4. } // Instead of associating the block comment to the property on line 3, it is associate to the property on line 1 if (updateBeginningLineNumber === true && token !== 14 /* SyntaxKind.LineBreakTrivia */ && token !== 15 /* SyntaxKind.Trivia */ && token !== 12 /* SyntaxKind.LineCommentTrivia */ && token !== 13 /* SyntaxKind.BlockCommentTrivia */) { beginningLineNumber = scanner.getTokenStartLine(); updateBeginningLineNumber = false; } // Update the number of characters on all the previous lines each time the new token is on a different line to the previous token if (scanner.getTokenStartLine() !== lastTokenLine) { for (let i = lastTokenLine; i < scanner.getTokenStartLine(); i++) { const lengthOfLine = formattedDocument.getText(Range.create(Position.create(i, 0), Position.create(i + 1, 0))).length; numberOfCharactersOnPreviousLines = numberOfCharactersOnPreviousLines + lengthOfLine; } lastTokenLine = scanner.getTokenStartLine(); } switch (token) { // When a string is found, if it follows an open brace or a comma token and it is within an object, then it corresponds to a key name, not a simple string case 10 /* SyntaxKind.StringLiteral */: { if ((lastNonTriviaNonCommentToken === undefined || lastNonTriviaNonCommentToken === 1 /* SyntaxKind.OpenBraceToken */ || (lastNonTriviaNonCommentToken === 5 /* SyntaxKind.CommaToken */ && currentContainerStack[currentContainerStack.length - 1] === Container.Object))) { // In that case create the child property which starts at beginningLineNumber, add it to the current tree const childProperty = new PropertyTree(scanner.getTokenValue(), beginningLineNumber); lastProperty = currentProperty; currentProperty = currentTree.addChildProperty(childProperty); } break; } // When the token is an open bracket, then we enter into an array case 3 /* SyntaxKind.OpenBracketToken */: { // If the root tree beginning line number is not defined, then this open bracket is the first open bracket in the document if (rootTree.beginningLineNumber === undefined) { rootTree.beginningLineNumber = scanner.getTokenStartLine(); } // Suppose we are inside of an object, then the current array is associated to a key, and has already been created // We have the following configuration: {"a": "val", "array": [...], "b": "val"} // In that case navigate down to the child property if (currentContainerStack[currentContainerStack.length - 1] === Container.Object) { currentTree = currentProperty; } // Suppose we are inside of an array, then since the current array is not associated to a key, it has not been created yet // We have the following configuration: ["a", [...], "b"] // In that case create the property and navigate down else if (currentContainerStack[currentContainerStack.length - 1] === Container.Array) { const childProperty = new PropertyTree(scanner.getTokenValue(), beginningLineNumber); childProperty.noKeyName = true; lastProperty = currentProperty; currentProperty = currentTree.addChildProperty(childProperty); currentTree = currentProperty; } currentContainerStack.push(Container.Array); currentProperty.type = Container.Array; beginningLineNumber = scanner.getTokenStartLine(); beginningLineNumber++; break; } // When the token is an open brace, then we enter into an object case 1 /* SyntaxKind.OpenBraceToken */: { // If the root tree beginning line number is not defined, then this open brace is the first open brace in the document if (rootTree.beginningLineNumber === undefined) { rootTree.beginningLineNumber = scanner.getTokenStartLine(); } // 1. If we are inside of an objet, the current object is associated to a key and has already been created // We have the following configuration: {"a": "val", "object": {...}, "b": "val"} // 2. Otherwise the current object property is inside of an array, not associated to a key name and the property has not yet been created // We have the following configuration: ["a", {...}, "b"] else if (currentContainerStack[currentContainerStack.length - 1] === Container.Array) { const childProperty = new PropertyTree(scanner.getTokenValue(), beginningLineNumber); childProperty.noKeyName = true; lastProperty = currentProperty; currentProperty = currentTree.addChildProperty(childProperty); } currentProperty.type = Container.Object; currentContainerStack.push(Container.Object); currentTree = currentProperty; beginningLineNumber = scanner.getTokenStartLine(); beginningLineNumber++; break; } case 4 /* SyntaxKind.CloseBracketToken */: { endLineNumber = scanner.getTokenStartLine(); currentContainerStack.pop(); // If the last non-trivial non-comment token is a closing brace or bracket, then the currentProperty end line number has not been set yet so set it // The configuration considered is: [..., {}] or [..., []] if (currentProperty.endLineNumber === undefined && (lastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || lastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */)) { currentProperty.endLineNumber = endLineNumber - 1; currentProperty.lastProperty = true; currentProperty.lineWhereToAddComma = lineOfLastNonTriviaNonCommentToken; currentProperty.indexWhereToAddComa = endIndexOfLastNonTriviaNonCommentToken; lastProperty = currentProperty; currentProperty = currentProperty ? currentProperty.parent : undefined; currentTree = currentProperty; } rootTree.endLineNumber = endLineNumber; beginningLineNumber = endLineNumber + 1; break; } case 2 /* SyntaxKind.CloseBraceToken */: { endLineNumber = scanner.getTokenStartLine(); currentContainerStack.pop(); // If we are not inside of an empty object if (lastNonTriviaNonCommentToken !== 1 /* SyntaxKind.OpenBraceToken */) { // If current property end line number has not yet been defined, define it if (currentProperty.endLineNumber === undefined) { currentProperty.endLineNumber = endLineNumber - 1; // The current property is also the last property currentProperty.lastProperty = true; // The last property of an object is associated with the line and index of where to add the comma, in case after sorting, it is no longer the last property currentProperty.lineWhereToAddComma = lineOfLastNonTriviaNonCommentToken; currentProperty.indexWhereToAddComa = endIndexOfLastNonTriviaNonCommentToken; } lastProperty = currentProperty; currentProperty = currentProperty ? currentProperty.parent : undefined; currentTree = currentProperty; } rootTree.endLineNumber = scanner.getTokenStartLine(); beginningLineNumber = endLineNumber + 1; break; } case 5 /* SyntaxKind.CommaToken */: { endLineNumber = scanner.getTokenStartLine(); // If the current container is an object or the current container is an array and the last non-trivia non-comment token is a closing brace or a closing bracket // Then update the end line number of the current property if (currentProperty.endLineNumber === undefined && (currentContainerStack[currentContainerStack.length - 1] === Container.Object || (currentContainerStack[currentContainerStack.length - 1] === Container.Array && (lastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || lastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */)))) { currentProperty.endLineNumber = endLineNumber; // Store the line and the index of the comma in case it needs to be removed during the sorting currentProperty.commaIndex = scanner.getTokenOffset() - numberOfCharactersOnPreviousLines; currentProperty.commaLine = endLineNumber; } if (lastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || lastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */) { lastProperty = currentProperty; currentProperty = currentProperty ? currentProperty.parent : undefined; currentTree = currentProperty; } beginningLineNumber = endLineNumber + 1; break; } case 13 /* SyntaxKind.BlockCommentTrivia */: { // If the last non trivia non-comment token is a comma and the block comment starts on the same line as the comma, then update the end line number of the current property. For example if: // 1. {}, /* ... // 2. ..*/ // The the property on line 1 shoud end on line 2, not line 1 // In the case we are in an array we update the end line number only if the second to last non-trivia non-comment token is a closing brace or bracket if (lastNonTriviaNonCommentToken === 5 /* SyntaxKind.CommaToken */ && lineOfLastNonTriviaNonCommentToken === scanner.getTokenStartLine() && (currentContainerStack[currentContainerStack.length - 1] === Container.Array && (secondToLastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || secondToLastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */) || currentContainerStack[currentContainerStack.length - 1] === Container.Object)) { if (currentContainerStack[currentContainerStack.length - 1] === Container.Array && (secondToLastNonTriviaNonCommentToken === 2 /* SyntaxKind.CloseBraceToken */ || secondToLastNonTriviaNonCommentToken === 4 /* SyntaxKind.CloseBracketToken */) || currentContainerStack[currentContainerStack.length - 1] === Container.Object) { currentProperty.endLineNumber = undefined; updateLastPropertyEndLineNumber = true; } } // When the block comment follows an open brace or an open token, we have the following scenario: // { /** // ../ // } // The block comment should be assigned to the open brace not the first property below it if ((lastNonTriviaNonCommentToken === 1 /* SyntaxKind.OpenBraceToken */ || lastNonTriviaNonCommentToken === 3 /* SyntaxKind.OpenBracketToken */) && lineOfLastNonTriviaNonCommentToken === scanner.getTokenStartLine()) { updateBeginningLineNumber = true; } break; } } // Update the last and second to last non-trivia non-comment tokens if (token !== 14 /* SyntaxKind.LineBreakTrivia */ && token !== 13 /* SyntaxKind.BlockCommentTrivia */ && token !== 12 /* SyntaxKind.LineCommentTrivia */ && token !== 15 /* SyntaxKind.Trivia */) { secondToLastNonTriviaNonCommentToken = lastNonTriviaNonCommentToken; lastNonTriviaNonCommentToken = token; lineOfLastNonTriviaNonCommentToken = scanner.getTokenStartLine(); endIndexOfLastNonTriviaNonCommentToken = scanner.getTokenOffset() + scanner.getTokenLength() - numberOfCharactersOnPreviousLines; } } return rootTree; } function sortJsoncDocument(jsonDocument, propertyTree) { if (propertyTree.childrenProperties.length === 0) { return jsonDocument; } const sortedJsonDocument = main_TextDocument.create('test://test.json', 'json', 0, jsonDocument.getText()); const queueToSort = []; updateSortingQueue(queueToSort, propertyTree, propertyTree.beginningLineNumber); while (queueToSort.length > 0) { const dataToSort = queueToSort.shift(); const propertyTreeArray = dataToSort.propertyTreeArray; let beginningLineNumber = dataToSort.beginningLineNumber; for (let i = 0; i < propertyTreeArray.length; i++) { const propertyTree = propertyTreeArray[i]; const range = Range.create(Position.create(propertyTree.beginningLineNumber, 0), Position.create(propertyTree.endLineNumber + 1, 0)); const jsonContentToReplace = jsonDocument.getText(range); const jsonDocumentToReplace = main_TextDocument.create('test://test.json', 'json', 0, jsonContentToReplace); if (propertyTree.lastProperty === true && i !== propertyTreeArray.length - 1) { const lineWhereToAddComma = propertyTree.lineWhereToAddComma - propertyTree.beginningLineNumber; const indexWhereToAddComma = propertyTree.indexWhereToAddComa; const edit = { range: Range.create(Position.create(lineWhereToAddComma, indexWhereToAddComma), Position.create(lineWhereToAddComma, indexWhereToAddComma)), text: ',' }; main_TextDocument.update(jsonDocumentToReplace, [edit], 1); } else if (propertyTree.lastProperty === false && i === propertyTreeArray.length - 1) { const commaIndex = propertyTree.commaIndex; const commaLine = propertyTree.commaLine; const lineWhereToRemoveComma = commaLine - propertyTree.beginningLineNumber; const edit = { range: Range.create(Position.create(lineWhereToRemoveComma, commaIndex), Position.create(lineWhereToRemoveComma, commaIndex + 1)), text: '' }; main_TextDocument.update(jsonDocumentToReplace, [edit], 1); } const length = propertyTree.endLineNumber - propertyTree.beginningLineNumber + 1; const edit = { range: Range.create(Position.create(beginningLineNumber, 0), Position.create(beginningLineNumber + length, 0)), text: jsonDocumentToReplace.getText() }; main_TextDocument.update(sortedJsonDocument, [edit], 1); updateSortingQueue(queueToSort, propertyTree, beginningLineNumber); beginningLineNumber = beginningLineNumber + length; } } return sortedJsonDocument; } function updateSortingQueue(queue, propertyTree, beginningLineNumber) { if (propertyTree.childrenProperties.length === 0) { return; } if (propertyTree.type === Container.Object) { let minimumBeginningLineNumber = Infinity; for (const childProperty of propertyTree.childrenProperties) { if (childProperty.beginningLineNumber < minimumBeginningLineNumber) { minimumBeginningLineNumber = childProperty.beginningLineNumber; } } const diff = minimumBeginningLineNumber - propertyTree.beginningLineNumber; beginningLineNumber = beginningLineNumber + diff; queue.push(new SortingRange(beginningLineNumber, propertyTree.childrenProperties)); } else if (propertyTree.type === Container.Array) { updateSortingQueueForArrayProperties(queue, propertyTree, beginningLineNumber); } } function updateSortingQueueForArrayProperties(queue, propertyTree, beginningLineNumber) { for (const subObject of propertyTree.childrenProperties) { // If the child property of the array is an object, then you can sort the properties within this object if (subObject.type === Container.Object) { let minimumBeginningLineNumber = Infinity; for (const childProperty of subObject.childrenProperties) { if (childProperty.beginningLineNumber < minimumBeginningLineNumber) { minimumBeginningLineNumber = childProperty.beginningLineNumber; } } const diff = minimumBeginningLineNumber - subObject.beginningLineNumber; queue.push(new SortingRange(beginningLineNumber + subObject.beginningLineNumber - propertyTree.beginningLineNumber + diff, subObject.childrenProperties)); } // If the child property of the array is an array, then you need to recurse on the children properties, until you find an object to sort if (subObject.type === Container.Array) { updateSortingQueueForArrayProperties(queue, subObject, beginningLineNumber + subObject.beginningLineNumber - propertyTree.beginningLineNumber); } } } class SortingRange { constructor(beginningLineNumber, propertyTreeArray) { this.beginningLineNumber = beginningLineNumber; this.propertyTreeArray = propertyTreeArray; } } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/services/jsonLinks.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function findLinks(document, doc) { const links = []; doc.visit(node => { if (node.type === "property" && node.keyNode.value === "$ref" && node.valueNode?.type === 'string') { const path = node.valueNode.value; const targetNode = findTargetNode(doc, path); if (targetNode) { const targetPos = document.positionAt(targetNode.offset); links.push({ target: `${document.uri}#${targetPos.line + 1},${targetPos.character + 1}`, range: createRange(document, node.valueNode) }); } } return true; }); return Promise.resolve(links); } function createRange(document, node) { return Range.create(document.positionAt(node.offset + 1), document.positionAt(node.offset + node.length - 1)); } function findTargetNode(doc, path) { const tokens = parseJSONPointer(path); if (!tokens) { return null; } return findNode(tokens, doc.root); } function findNode(pointer, node) { if (!node) { return null; } if (pointer.length === 0) { return node; } const token = pointer.shift(); if (node && node.type === 'object') { const propertyNode = node.properties.find((propertyNode) => propertyNode.keyNode.value === token); if (!propertyNode) { return null; } return findNode(pointer, propertyNode.valueNode); } else if (node && node.type === 'array') { if (token.match(/^(0|[1-9][0-9]*)$/)) { const index = Number.parseInt(token); const arrayItem = node.items[index]; if (!arrayItem) { return null; } return findNode(pointer, arrayItem); } } return null; } function parseJSONPointer(path) { if (path === "#") { return []; } if (path[0] !== '#' || path[1] !== '/') { return null; } return path.substring(2).split(/\//).map(jsonLinks_unescape); } function jsonLinks_unescape(str) { return str.replace(/~1/g, '/').replace(/~0/g, '~'); } ;// CONCATENATED MODULE: ./node_modules/vscode-json-languageservice/lib/esm/jsonLanguageService.js /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ function getLanguageService(params) { const promise = params.promiseConstructor || Promise; const jsonSchemaService = new JSONSchemaService(params.schemaRequestService, params.workspaceContext, promise); jsonSchemaService.setSchemaContributions(schemaContributions); const jsonCompletion = new JSONCompletion(jsonSchemaService, params.contributions, promise, params.clientCapabilities); const jsonHover = new JSONHover(jsonSchemaService, params.contributions, promise); const jsonDocumentSymbols = new JSONDocumentSymbols(jsonSchemaService); const jsonValidation = new JSONValidation(jsonSchemaService, promise); return { configure: (settings) => { jsonSchemaService.clearExternalSchemas(); settings.schemas?.forEach(jsonSchemaService.registerExternalSchema.bind(jsonSchemaService)); jsonValidation.configure(settings); }, resetSchema: (uri) => jsonSchemaService.onResourceChange(uri), doValidation: jsonValidation.doValidation.bind(jsonValidation), getLanguageStatus: jsonValidation.getLanguageStatus.bind(jsonValidation), parseJSONDocument: (document) => jsonParser_parse(document, { collectComments: true }), newJSONDocument: (root, diagnostics) => newJSONDocument(root, diagnostics), getMatchingSchemas: jsonSchemaService.getMatchingSchemas.bind(jsonSchemaService), doResolve: jsonCompletion.doResolve.bind(jsonCompletion), doComplete: jsonCompletion.doComplete.bind(jsonCompletion), findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols), findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols), findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols), getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols), doHover: jsonHover.doHover.bind(jsonHover), getFoldingRanges: getFoldingRanges, getSelectionRanges: getSelectionRanges, findDefinition: () => Promise.resolve([]), findLinks: findLinks, format: (document, range, options) => utils_format_format(document, options, range), sort: (document, options) => sort(document, options) }; } /***/ }), /***/ 3757: /***/ ((__unused_webpack_module, exports, __nccwpck_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.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.TraceValue = exports.Trace = void 0; const messages_1 = __nccwpck_require__(4341); 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 = __nccwpck_require__(3816); 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 = __nccwpck_require__(8400); Object.defineProperty(exports, "Disposable", ({ enumerable: true, get: function () { return disposable_1.Disposable; } })); const events_1 = __nccwpck_require__(9145); 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 = __nccwpck_require__(8823); 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 = __nccwpck_require__(8636); 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 = __nccwpck_require__(1002); 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 = __nccwpck_require__(487); 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 = __nccwpck_require__(6367); Object.defineProperty(exports, "AbstractMessageBuffer", ({ enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } })); const connection_1 = __nccwpck_require__(7624); 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, "TraceValue", ({ enumerable: true, get: function () { return connection_1.TraceValue; } })); 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; } })); Object.defineProperty(exports, "TraceValues", ({ enumerable: true, get: function () { return connection_1.TraceValues; } })); const ral_1 = __nccwpck_require__(8514); exports.RAL = ral_1.default; /***/ }), /***/ 8823: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8514); const Is = __nccwpck_require__(1216); const events_1 = __nccwpck_require__(9145); 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 = 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; /***/ }), /***/ 7624: /***/ ((__unused_webpack_module, exports, __nccwpck_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.TraceValue = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0; const ral_1 = __nccwpck_require__(8514); const Is = __nccwpck_require__(1216); const messages_1 = __nccwpck_require__(4341); const linkedMap_1 = __nccwpck_require__(3816); const events_1 = __nccwpck_require__(9145); const cancellation_1 = __nccwpck_require__(8823); 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 = 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 = Trace = {})); var TraceValue; (function (TraceValue) { /** * Turn tracing off. */ TraceValue.Off = 'off'; /** * Trace messages only. */ TraceValue.Messages = 'messages'; /** * Compact message tracing. */ TraceValue.Compact = 'compact'; /** * Verbose message tracing. */ TraceValue.Verbose = 'verbose'; })(TraceValue || (exports.TraceValue = TraceValue = {})); /** * @deprecated Use TraceValue instead */ exports.TraceValues = TraceValue; (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 = Trace = {})); var TraceFormat; (function (TraceFormat) { TraceFormat["Text"] = "text"; TraceFormat["JSON"] = "json"; })(TraceFormat || (exports.TraceFormat = 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 = TraceFormat = {})); var SetTraceNotification; (function (SetTraceNotification) { SetTraceNotification.type = new messages_1.NotificationType('$/setTrace'); })(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {})); var LogTraceNotification; (function (LogTraceNotification) { LogTraceNotification.type = new messages_1.NotificationType('$/logTrace'); })(LogTraceNotification || (exports.LogTraceNotification = 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 = 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 = 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 = 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 = 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 = 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 = 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 = CancellationStrategy = {})); var MessageStrategy; (function (MessageStrategy) { function is(value) { const candidate = value; return candidate && Is.func(candidate.handleMessage); } MessageStrategy.is = is; })(MessageStrategy || (exports.MessageStrategy = 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) || Is.number(candidate.maxParallelism)); } ConnectionOptions.is = is; })(ConnectionOptions || (exports.ConnectionOptions = 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'; const maxParallelism = options?.maxParallelism ?? -1; let inFlight = 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 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 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)) { // If we have unlimited parallelism we queue the response to keep // the previous semantics. if (maxParallelism === -1) { queue.set(createResponseQueueKey(message.id), message); } else { // If we have limited parallelism we resolve responses to avoid // dead locks. handleResponse(message); } } else { queue.set(createNotificationQueueKey(), message); } } function triggerMessageQueue() { if (timer || messageQueue.size === 0) { return; } if (maxParallelism !== -1 && inFlight >= maxParallelism) { return; } timer = (0, ral_1.default)().timer.setImmediate(async () => { timer = undefined; if (messageQueue.size === 0) { return; } if (maxParallelism !== -1 && inFlight >= maxParallelism) { return; } const message = messageQueue.shift(); let result; try { inFlight++; const messageStrategy = options?.messageStrategy; if (MessageStrategy.is(messageStrategy)) { result = messageStrategy.handleMessage(message, handleMessage); } else { result = handleMessage(message); } } catch (error) { logger.error(`Processing message queue failed: ${error.toString()}`); } finally { if (result instanceof Promise) { result.then(() => { inFlight--; triggerMessageQueue(); }).catch((error) => { logger.error(`Processing message queue failed: ${error.toString()}`); }); } else { inFlight--; } triggerMessageQueue(); } }); } async function handleMessage(message) { if (messages_1.Message.isRequest(message)) { return handleRequest(message); } else if (messages_1.Message.isNotification(message)) { return handleNotification(message); } else if (messages_1.Message.isResponse(message)) { return handleResponse(message); } else { return handleInvalidMessage(message); } } 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(); } }; async function handleRequest(requestMessage) { if (isDisposed()) { // we return here silently since we fired an event when the // connection got disposed. return Promise.resolve(); } 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); return messageWriter.write(message); } function replyError(error, method, startTime) { const message = { jsonrpc: version, id: requestMessage.id, error: error.toJson() }; traceSendingResponse(message, method, startTime); return messageWriter.write(message); } 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) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime); } handlerResult = requestHandler(cancellationSource.token); } else if (Array.isArray(requestMessage.params)) { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime); } handlerResult = requestHandler(...requestMessage.params, cancellationSource.token); } else { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime); } handlerResult = requestHandler(requestMessage.params, cancellationSource.token); } } else if (starRequestHandler) { handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); } const resultOrError = await handlerResult; await reply(resultOrError, requestMessage.method, startTime); } catch (error) { if (error instanceof messages_1.ResponseError) { await reply(error, requestMessage.method, startTime); } else if (error && Is.string(error.message)) { await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); } else { await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); } } finally { requestTokens.delete(tokenKey); } } else { await 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.`); } } } } } async 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.`); } } await 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])) { await 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`); } } await 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`); } await notificationHandler(message.params); } } else if (starNotificationHandler) { await 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; } const 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(); function sendCancellation(connection, id) { const p = cancellationStrategy.sender.sendCancellation(connection, id); if (p === undefined) { logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`); } else { p.catch(() => { logger.log(`Sending cancellation messages for id ${id} failed.`); }); } } 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; let tokenWasCancelled = false; if (token !== undefined) { if (token.isCancellationRequested) { tokenWasCancelled = true; } else { disposable = token.onCancellationRequested(() => { sendCancellation(connection, id); }); } } const requestMessage = { jsonrpc: version, id: id, method: method, params: messageParams }; traceSendingRequest(requestMessage); if (typeof cancellationStrategy.sender.enableCancellation === 'function') { cancellationStrategy.sender.enableCancellation(requestMessage); } // eslint-disable-next-line no-async-promise-executor 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 { responsePromises.set(id, responsePromise); await messageWriter.write(requestMessage); if (tokenWasCancelled) { sendCancellation(connection, id); } } catch (error) { // Writing the message failed. So we need to delete it from the response promises and // reject it. responsePromises.delete(id); responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason')); logger.error(`Sending request failed.`); 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, async (params) => { const handler = progressHandlers.get(params.token); if (handler) { await handler(params.value); } else { unhandledProgressEmitter.fire(params); } }); return connection; } exports.createMessageConnection = createMessageConnection; /***/ }), /***/ 8400: /***/ ((__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 = Disposable = {})); /***/ }), /***/ 9145: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8514); var Event; (function (Event) { const _disposable = { dispose() { } }; Event.None = function () { return _disposable; }; })(Event || (exports.Event = 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 () { }; /***/ }), /***/ 1216: /***/ ((__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; /***/ }), /***/ 3816: /***/ ((__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 = 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; } before(key) { const item = this._map.get(key); return item ? item.previous?.value : undefined; } after(key) { const item = this._map.get(key); return item ? item.next?.value : undefined; } 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; /***/ }), /***/ 6367: /***/ ((__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; 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 ':'\n${header}`); } 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; const 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; /***/ }), /***/ 1002: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8514); const Is = __nccwpck_require__(1216); const events_1 = __nccwpck_require__(9145); const semaphore_1 = __nccwpck_require__(9848); var MessageReader; (function (MessageReader) { function is(value) { const 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 = 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) { try { 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.\n${JSON.stringify(Object.fromEntries(headers))}`)); return; } const length = parseInt(contentLength); if (isNaN(length)) { this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`)); 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); }); } } 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; /***/ }), /***/ 487: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8514); const Is = __nccwpck_require__(1216); const semaphore_1 = __nccwpck_require__(9848); const events_1 = __nccwpck_require__(9145); const ContentLength = 'Content-Length: '; const CRLF = '\r\n'; var MessageWriter; (function (MessageWriter) { function is(value) { const 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 = 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; /***/ }), /***/ 4341: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(1216); /** * 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 = 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 = Message = {})); /***/ }), /***/ 8514: /***/ ((__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; /***/ }), /***/ 9848: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8514); 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; /***/ }), /***/ 8636: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(8823); 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; /***/ }), /***/ 5918: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0; /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */ const ril_1 = __nccwpck_require__(3932); // Install the node runtime abstract. ril_1.default.install(); const path = __nccwpck_require__(1017); const os = __nccwpck_require__(2037); const fs = __nccwpck_require__(7147); const crypto_1 = __nccwpck_require__(6113); const net_1 = __nccwpck_require__(1808); const api_1 = __nccwpck_require__(3757); __exportStar(__nccwpck_require__(3757), exports); class IPCMessageReader extends api_1.AbstractMessageReader { constructor(process) { super(); this.process = process; const eventEmitter = this.process; eventEmitter.on('error', (error) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose()); } listen(callback) { this.process.on('message', callback); return api_1.Disposable.create(() => this.process.off('message', callback)); } } exports.IPCMessageReader = IPCMessageReader; class IPCMessageWriter extends api_1.AbstractMessageWriter { constructor(process) { super(); this.process = process; this.errorCount = 0; const eventEmitter = this.process; eventEmitter.on('error', (error) => this.fireError(error)); eventEmitter.on('close', () => this.fireClose); } write(msg) { try { if (typeof this.process.send === 'function') { this.process.send(msg, undefined, undefined, (error) => { if (error) { this.errorCount++; this.handleError(error, msg); } else { this.errorCount = 0; } }); } 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.IPCMessageWriter = IPCMessageWriter; class PortMessageReader extends api_1.AbstractMessageReader { constructor(port) { super(); this.onData = new api_1.Emitter; port.on('close', () => this.fireClose); port.on('error', (error) => this.fireError(error)); port.on('message', (message) => { this.onData.fire(message); }); } listen(callback) { return this.onData.event(callback); } } exports.PortMessageReader = PortMessageReader; class PortMessageWriter extends api_1.AbstractMessageWriter { constructor(port) { super(); this.port = port; this.errorCount = 0; port.on('close', () => this.fireClose()); port.on('error', (error) => this.fireError(error)); } 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.PortMessageWriter = PortMessageWriter; class SocketMessageReader extends api_1.ReadableStreamMessageReader { constructor(socket, encoding = 'utf-8') { super((0, ril_1.default)().stream.asReadableStream(socket), encoding); } } exports.SocketMessageReader = SocketMessageReader; class SocketMessageWriter extends api_1.WriteableStreamMessageWriter { constructor(socket, options) { super((0, ril_1.default)().stream.asWritableStream(socket), options); this.socket = socket; } dispose() { super.dispose(); this.socket.destroy(); } } exports.SocketMessageWriter = SocketMessageWriter; class StreamMessageReader extends api_1.ReadableStreamMessageReader { constructor(readable, encoding) { super((0, ril_1.default)().stream.asReadableStream(readable), encoding); } } exports.StreamMessageReader = StreamMessageReader; class StreamMessageWriter extends api_1.WriteableStreamMessageWriter { constructor(writable, options) { super((0, ril_1.default)().stream.asWritableStream(writable), options); } } exports.StreamMessageWriter = StreamMessageWriter; const XDG_RUNTIME_DIR = process.env['XDG_RUNTIME_DIR']; const safeIpcPathLengths = new Map([ ['linux', 107], ['darwin', 103] ]); function generateRandomPipeName() { if (process.platform === 'win32') { return `\\\\.\\pipe\\lsp-${(0, crypto_1.randomBytes)(16).toString('hex')}-sock`; } let randomLength = 32; const fixedLength = 'lsp-.sock'.length; const tmpDir = fs.realpathSync(XDG_RUNTIME_DIR ?? os.tmpdir()); const limit = safeIpcPathLengths.get(process.platform); if (limit !== undefined) { randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength); } if (randomLength < 16) { throw new Error(`Unable to generate a random pipe name with ${randomLength} characters.`); } const randomSuffix = (0, crypto_1.randomBytes)(Math.floor(randomLength / 2)).toString('hex'); return path.join(tmpDir, `lsp-${randomSuffix}.sock`); } exports.generateRandomPipeName = generateRandomPipeName; function createClientPipeTransport(pipeName, encoding = 'utf-8') { let connectResolve; const connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { const server = (0, net_1.createServer)((socket) => { server.close(); connectResolve([ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]); }); server.on('error', reject); server.listen(pipeName, () => { server.removeListener('error', reject); resolve({ onConnected: () => { return connected; } }); }); }); } exports.createClientPipeTransport = createClientPipeTransport; function createServerPipeTransport(pipeName, encoding = 'utf-8') { const socket = (0, net_1.createConnection)(pipeName); return [ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]; } exports.createServerPipeTransport = createServerPipeTransport; function createClientSocketTransport(port, encoding = 'utf-8') { let connectResolve; const connected = new Promise((resolve, _reject) => { connectResolve = resolve; }); return new Promise((resolve, reject) => { const server = (0, net_1.createServer)((socket) => { server.close(); connectResolve([ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]); }); server.on('error', reject); server.listen(port, '127.0.0.1', () => { server.removeListener('error', reject); resolve({ onConnected: () => { return connected; } }); }); }); } exports.createClientSocketTransport = createClientSocketTransport; function createServerSocketTransport(port, encoding = 'utf-8') { const socket = (0, net_1.createConnection)(port, '127.0.0.1'); return [ new SocketMessageReader(socket, encoding), new SocketMessageWriter(socket, encoding) ]; } exports.createServerSocketTransport = createServerSocketTransport; function isReadableStream(value) { const candidate = value; return candidate.read !== undefined && candidate.addListener !== undefined; } function isWritableStream(value) { const candidate = value; return candidate.write !== undefined && candidate.addListener !== undefined; } function createMessageConnection(input, output, logger, options) { if (!logger) { logger = api_1.NullLogger; } const reader = isReadableStream(input) ? new StreamMessageReader(input) : input; const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output; if (api_1.ConnectionStrategy.is(options)) { options = { connectionStrategy: options }; } return (0, api_1.createMessageConnection)(reader, writer, logger, options); } exports.createMessageConnection = createMessageConnection; /***/ }), /***/ 3932: /***/ ((__unused_webpack_module, exports, __nccwpck_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 })); const util_1 = __nccwpck_require__(3837); const api_1 = __nccwpck_require__(3757); class MessageBuffer extends api_1.AbstractMessageBuffer { constructor(encoding = 'utf-8') { super(encoding); } emptyBuffer() { return MessageBuffer.emptyBuffer; } fromString(value, encoding) { return Buffer.from(value, encoding); } toString(value, encoding) { if (value instanceof Buffer) { return value.toString(encoding); } else { return new util_1.TextDecoder(encoding).decode(value); } } asNative(buffer, length) { if (length === undefined) { return buffer instanceof Buffer ? buffer : Buffer.from(buffer); } else { return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length); } } allocNative(length) { return Buffer.allocUnsafe(length); } } MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0); class ReadableStreamWrapper { constructor(stream) { this.stream = stream; } onClose(listener) { this.stream.on('close', listener); return api_1.Disposable.create(() => this.stream.off('close', listener)); } onError(listener) { this.stream.on('error', listener); return api_1.Disposable.create(() => this.stream.off('error', listener)); } onEnd(listener) { this.stream.on('end', listener); return api_1.Disposable.create(() => this.stream.off('end', listener)); } onData(listener) { this.stream.on('data', listener); return api_1.Disposable.create(() => this.stream.off('data', listener)); } } class WritableStreamWrapper { constructor(stream) { this.stream = stream; } onClose(listener) { this.stream.on('close', listener); return api_1.Disposable.create(() => this.stream.off('close', listener)); } onError(listener) { this.stream.on('error', listener); return api_1.Disposable.create(() => this.stream.off('error', listener)); } onEnd(listener) { this.stream.on('end', listener); return api_1.Disposable.create(() => this.stream.off('end', listener)); } write(data, encoding) { return new Promise((resolve, reject) => { const callback = (error) => { if (error === undefined || error === null) { resolve(); } else { reject(error); } }; if (typeof data === 'string') { this.stream.write(data, encoding, callback); } else { this.stream.write(data, callback); } }); } end() { this.stream.end(); } } const _ril = Object.freeze({ messageBuffer: Object.freeze({ create: (encoding) => new MessageBuffer(encoding) }), applicationJson: Object.freeze({ encoder: Object.freeze({ name: 'application/json', encode: (msg, options) => { try { return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset)); } catch (err) { return Promise.reject(err); } } }), decoder: Object.freeze({ name: 'application/json', decode: (buffer, options) => { try { if (buffer instanceof Buffer) { return Promise.resolve(JSON.parse(buffer.toString(options.charset))); } else { return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer))); } } catch (err) { return Promise.reject(err); } } }) }), stream: Object.freeze({ asReadableStream: (stream) => new ReadableStreamWrapper(stream), asWritableStream: (stream) => new WritableStreamWrapper(stream) }), console: console, timer: Object.freeze({ setTimeout(callback, ms, ...args) { const handle = setTimeout(callback, ms, ...args); return { dispose: () => clearTimeout(handle) }; }, setImmediate(callback, ...args) { const handle = setImmediate(callback, ...args); return { dispose: () => clearImmediate(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; /***/ }), /***/ 9827: /***/ ((module, __unused_webpack_exports, __nccwpck_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 = __nccwpck_require__(5918); /***/ }), /***/ 7601: /***/ (function(__unused_webpack_module, exports, __nccwpck_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(__nccwpck_require__(5918), exports); __exportStar(__nccwpck_require__(2742), exports); __exportStar(__nccwpck_require__(7819), exports); __exportStar(__nccwpck_require__(695), exports); var connection_1 = __nccwpck_require__(3147); 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 has 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 = LSPErrorCodes = {})); /***/ }), /***/ 3147: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(5918); 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; /***/ }), /***/ 7819: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(5918); var MessageDirection; (function (MessageDirection) { MessageDirection["clientToServer"] = "clientToServer"; MessageDirection["serverToClient"] = "serverToClient"; MessageDirection["both"] = "both"; })(MessageDirection || (exports.MessageDirection = 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; /***/ }), /***/ 2452: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = CallHierarchyOutgoingCallsRequest = {})); /***/ }), /***/ 7155: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = ColorPresentationRequest = {})); /***/ }), /***/ 7774: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); //---- 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 = ConfigurationRequest = {})); /***/ }), /***/ 7190: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); // @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 {@link 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 = DeclarationRequest = {})); /***/ }), /***/ 7730: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(5918); const Is = __nccwpck_require__(8680); const messages_1 = __nccwpck_require__(7819); /** * @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 = 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 = 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 = 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 = 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 = DiagnosticRefreshRequest = {})); /***/ }), /***/ 4636: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = 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 = 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 = 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 = 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 = WillDeleteFilesRequest = {})); /***/ }), /***/ 8564: /***/ ((__unused_webpack_module, exports, __nccwpck_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.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = void 0; const messages_1 = __nccwpck_require__(7819); /** * 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 = FoldingRangeRequest = {})); /** * @since 3.18.0 * @proposed */ var FoldingRangeRefreshRequest; (function (FoldingRangeRefreshRequest) { FoldingRangeRefreshRequest.method = `workspace/foldingRange/refresh`; FoldingRangeRefreshRequest.messageDirection = messages_1.MessageDirection.serverToClient; FoldingRangeRefreshRequest.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest.method); })(FoldingRangeRefreshRequest || (exports.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {})); /***/ }), /***/ 3592: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); // @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 {@link 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 = ImplementationRequest = {})); /***/ }), /***/ 9414: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = InlayHintRefreshRequest = {})); /***/ }), /***/ 9647: /***/ ((__unused_webpack_module, exports, __nccwpck_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.InlineCompletionRequest = void 0; const messages_1 = __nccwpck_require__(7819); /** * A request to provide inline completions in a document. The request's parameter is of * type {@link InlineCompletionParams}, the response is of type * {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. * * @since 3.18.0 * @proposed */ var InlineCompletionRequest; (function (InlineCompletionRequest) { InlineCompletionRequest.method = 'textDocument/inlineCompletion'; InlineCompletionRequest.messageDirection = messages_1.MessageDirection.clientToServer; InlineCompletionRequest.type = new messages_1.ProtocolRequestType(InlineCompletionRequest.method); })(InlineCompletionRequest || (exports.InlineCompletionRequest = InlineCompletionRequest = {})); /***/ }), /***/ 2326: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = InlineValueRefreshRequest = {})); /***/ }), /***/ 695: /***/ ((__unused_webpack_module, exports, __nccwpck_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.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.RegularExpressionEngineKind = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.NotebookCellTextDocumentFilter = exports.NotebookDocumentFilter = exports.TextDocumentFilter = void 0; 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.FoldingRangeRefreshRequest = 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.DocumentRangesFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolResolveRequest = exports.WorkspaceSymbolRequest = void 0; exports.InlineCompletionRequest = 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 = exports.TypeHierarchySubtypesRequest = exports.TypeHierarchyPrepareRequest = exports.MonikerRequest = void 0; const messages_1 = __nccwpck_require__(7819); const vscode_languageserver_types_1 = __nccwpck_require__(2742); const Is = __nccwpck_require__(8680); const protocol_implementation_1 = __nccwpck_require__(3592); Object.defineProperty(exports, "ImplementationRequest", ({ enumerable: true, get: function () { return protocol_implementation_1.ImplementationRequest; } })); const protocol_typeDefinition_1 = __nccwpck_require__(6061); Object.defineProperty(exports, "TypeDefinitionRequest", ({ enumerable: true, get: function () { return protocol_typeDefinition_1.TypeDefinitionRequest; } })); const protocol_workspaceFolder_1 = __nccwpck_require__(3965); 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 = __nccwpck_require__(7774); Object.defineProperty(exports, "ConfigurationRequest", ({ enumerable: true, get: function () { return protocol_configuration_1.ConfigurationRequest; } })); const protocol_colorProvider_1 = __nccwpck_require__(7155); 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 = __nccwpck_require__(8564); Object.defineProperty(exports, "FoldingRangeRequest", ({ enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRequest; } })); Object.defineProperty(exports, "FoldingRangeRefreshRequest", ({ enumerable: true, get: function () { return protocol_foldingRange_1.FoldingRangeRefreshRequest; } })); const protocol_declaration_1 = __nccwpck_require__(7190); Object.defineProperty(exports, "DeclarationRequest", ({ enumerable: true, get: function () { return protocol_declaration_1.DeclarationRequest; } })); const protocol_selectionRange_1 = __nccwpck_require__(3613); Object.defineProperty(exports, "SelectionRangeRequest", ({ enumerable: true, get: function () { return protocol_selectionRange_1.SelectionRangeRequest; } })); const protocol_progress_1 = __nccwpck_require__(3551); 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 = __nccwpck_require__(2452); 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 = __nccwpck_require__(8507); 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 = __nccwpck_require__(7614); Object.defineProperty(exports, "ShowDocumentRequest", ({ enumerable: true, get: function () { return protocol_showDocument_1.ShowDocumentRequest; } })); const protocol_linkedEditingRange_1 = __nccwpck_require__(6107); Object.defineProperty(exports, "LinkedEditingRangeRequest", ({ enumerable: true, get: function () { return protocol_linkedEditingRange_1.LinkedEditingRangeRequest; } })); const protocol_fileOperations_1 = __nccwpck_require__(4636); 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 = __nccwpck_require__(2737); 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 = __nccwpck_require__(2193); 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 = __nccwpck_require__(2326); 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 = __nccwpck_require__(9414); 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 = __nccwpck_require__(7730); 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 = __nccwpck_require__(9668); 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; } })); const protocol_inlineCompletion_1 = __nccwpck_require__(9647); Object.defineProperty(exports, "InlineCompletionRequest", ({ enumerable: true, get: function () { return protocol_inlineCompletion_1.InlineCompletionRequest; } })); // @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) || (Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern)); } TextDocumentFilter.is = is; })(TextDocumentFilter || (exports.TextDocumentFilter = 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 = 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 = 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 (const elem of value) { if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) { return false; } } return true; } DocumentSelector.is = is; })(DocumentSelector || (exports.DocumentSelector = 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 = 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 = 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 = 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 = FailureHandlingKind = {})); /** * Regular Expression Engines * * @since 3.18.0 * @proposed */ var RegularExpressionEngineKind; (function (RegularExpressionEngineKind) { RegularExpressionEngineKind.ES2020 = 'ES2020'; })(RegularExpressionEngineKind || (exports.RegularExpressionEngineKind = RegularExpressionEngineKind = {})); /** * 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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; /** * A debug message. * * @since 3.18.0 * @proposed */ MessageType.Debug = 5; })(MessageType || (exports.MessageType = 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 = 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 = 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 = 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 = 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 = 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 = DidOpenTextDocumentNotification = {})); var TextDocumentContentChangeEvent; (function (TextDocumentContentChangeEvent) { /** * Checks whether the information describes a delta event. */ function isIncremental(event) { const 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) { const candidate = event; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } TextDocumentContentChangeEvent.isFull = isFull; })(TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = SignatureHelpRequest = {})); /** * A request to resolve the definition location of a symbol at a given text * document position. The request's parameter is of type {@link 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 = 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 = ReferencesRequest = {})); /** * Request to resolve a {@link DocumentHighlight} for a given * text document position. The request's parameter is of type {@link TextDocumentPosition} * the request response is an array of type {@link 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = DocumentLinkResolveRequest = {})); /** * A request 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 = DocumentFormattingRequest = {})); /** * A request 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 = DocumentRangeFormattingRequest = {})); /** * A request to format ranges in a document. * * @since 3.18.0 * @proposed */ var DocumentRangesFormattingRequest; (function (DocumentRangesFormattingRequest) { DocumentRangesFormattingRequest.method = 'textDocument/rangesFormatting'; DocumentRangesFormattingRequest.messageDirection = messages_1.MessageDirection.clientToServer; DocumentRangesFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest.method); })(DocumentRangesFormattingRequest || (exports.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {})); /** * 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 = 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 = 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 = 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 = 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 = 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 = ApplyWorkspaceEditRequest = {})); /***/ }), /***/ 6107: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = LinkedEditingRangeRequest = {})); /***/ }), /***/ 2737: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = MonikerRequest = {})); /***/ }), /***/ 9668: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(2742); const Is = __nccwpck_require__(8680); const messages_1 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = DidCloseNotebookDocumentNotification = {})); /***/ }), /***/ 3551: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(5918); const messages_1 = __nccwpck_require__(7819); var WorkDoneProgress; (function (WorkDoneProgress) { WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType(); function is(value) { return value === WorkDoneProgress.type; } WorkDoneProgress.is = is; })(WorkDoneProgress || (exports.WorkDoneProgress = 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 = 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 = WorkDoneProgressCancelNotification = {})); /***/ }), /***/ 3613: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = SelectionRangeRequest = {})); /***/ }), /***/ 8507: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); //------- 'textDocument/semanticTokens' ----- var TokenFormat; (function (TokenFormat) { TokenFormat.Relative = 'relative'; })(TokenFormat || (exports.TokenFormat = TokenFormat = {})); var SemanticTokensRegistrationType; (function (SemanticTokensRegistrationType) { SemanticTokensRegistrationType.method = 'textDocument/semanticTokens'; SemanticTokensRegistrationType.type = new messages_1.RegistrationType(SemanticTokensRegistrationType.method); })(SemanticTokensRegistrationType || (exports.SemanticTokensRegistrationType = 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 = 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 = 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 = 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 = SemanticTokensRefreshRequest = {})); /***/ }), /***/ 7614: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = ShowDocumentRequest = {})); /***/ }), /***/ 6061: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); // @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 {@link 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 = TypeDefinitionRequest = {})); /***/ }), /***/ 2193: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = 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 = TypeHierarchySubtypesRequest = {})); /***/ }), /***/ 3965: /***/ ((__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7819); /** * 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 = 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 = DidChangeWorkspaceFoldersNotification = {})); /***/ }), /***/ 8680: /***/ ((__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; /***/ }), /***/ 3135: /***/ (function(__unused_webpack_module, exports, __nccwpck_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 node_1 = __nccwpck_require__(9827); __exportStar(__nccwpck_require__(9827), exports); __exportStar(__nccwpck_require__(7601), exports); function createProtocolConnection(input, output, logger, options) { return (0, node_1.createMessageConnection)(input, output, logger, options); } exports.createProtocolConnection = createProtocolConnection; /***/ }), /***/ 4121: /***/ ((module, __unused_webpack_exports, __nccwpck_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 = __nccwpck_require__(3135); /***/ }), /***/ 2742: /***/ ((module, exports) => { (function (factory) { if ( true && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); } })(function () { /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TextDocument = exports.EOL = exports.WorkspaceFolder = exports.InlineCompletionContext = exports.SelectedCompletionInfo = exports.InlineCompletionTriggerKind = exports.InlineCompletionList = exports.InlineCompletionItem = exports.StringValue = exports.InlayHint = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlineValueContext = exports.InlineValueEvaluatableExpression = exports.InlineValueVariableLookup = exports.InlineValueText = exports.SemanticTokens = exports.SemanticTokenModifiers = exports.SemanticTokenTypes = exports.SelectionRange = exports.DocumentLink = exports.FormattingOptions = exports.CodeLens = exports.CodeAction = exports.CodeActionContext = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.DocumentSymbol = exports.WorkspaceSymbol = exports.SymbolInformation = exports.SymbolTag = exports.SymbolKind = exports.DocumentHighlight = exports.DocumentHighlightKind = exports.SignatureInformation = exports.ParameterInformation = exports.Hover = exports.MarkedString = exports.CompletionList = exports.CompletionItem = exports.CompletionItemLabelDetails = exports.InsertTextMode = exports.InsertReplaceEdit = exports.CompletionItemTag = exports.InsertTextFormat = exports.CompletionItemKind = exports.MarkupContent = exports.MarkupKind = exports.TextDocumentItem = exports.LanguageKind = exports.OptionalVersionedTextDocumentIdentifier = exports.VersionedTextDocumentIdentifier = exports.TextDocumentIdentifier = exports.WorkspaceChange = exports.SnippetTextEdit = exports.WorkspaceEdit = exports.DeleteFile = exports.RenameFile = exports.CreateFile = exports.TextDocumentEdit = exports.AnnotatedTextEdit = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.TextEdit = exports.Command = exports.Diagnostic = exports.CodeDescription = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.FoldingRange = exports.FoldingRangeKind = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.LocationLink = exports.Location = exports.Range = exports.Position = exports.uinteger = exports.integer = exports.URI = exports.DocumentUri = void 0; var DocumentUri; (function (DocumentUri) { function is(value) { return typeof value === 'string'; } DocumentUri.is = is; })(DocumentUri || (exports.DocumentUri = DocumentUri = {})); var URI; (function (URI) { function is(value) { return typeof value === 'string'; } URI.is = is; })(URI || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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) && (candidate.tooltip === undefined || Is.string(candidate.tooltip)) && Is.string(candidate.command); } Command.is = is; })(Command || (exports.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 || (exports.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 || (exports.ChangeAnnotation = ChangeAnnotation = {})); var ChangeAnnotationIdentifier; (function (ChangeAnnotationIdentifier) { function is(value) { var candidate = value; return Is.string(candidate); } ChangeAnnotationIdentifier.is = is; })(ChangeAnnotationIdentifier || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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; }()); var SnippetTextEdit; (function (SnippetTextEdit) { function is(value) { var candidate = value; return Is.objectLiteral(candidate) && Range.is(candidate.range) && StringValue.isSnippet(candidate.snippet) && (candidate.annotationId === undefined || (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId))); } SnippetTextEdit.is = is; })(SnippetTextEdit || (exports.SnippetTextEdit = SnippetTextEdit = {})); /** * 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; }()); exports.WorkspaceChange = 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 || (exports.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 || (exports.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 || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); /** * Predefined Language kinds * @since 3.18.0 * @proposed */ var LanguageKind; (function (LanguageKind) { LanguageKind.ABAP = 'abap'; LanguageKind.WindowsBat = 'bat'; LanguageKind.BibTeX = 'bibtex'; LanguageKind.Clojure = 'clojure'; LanguageKind.Coffeescript = 'coffeescript'; LanguageKind.C = 'c'; LanguageKind.CPP = 'cpp'; LanguageKind.CSharp = 'csharp'; LanguageKind.CSS = 'css'; /** * @since 3.18.0 * @proposed */ LanguageKind.D = 'd'; /** * @since 3.18.0 * @proposed */ LanguageKind.Delphi = 'pascal'; LanguageKind.Diff = 'diff'; LanguageKind.Dart = 'dart'; LanguageKind.Dockerfile = 'dockerfile'; LanguageKind.Elixir = 'elixir'; LanguageKind.Erlang = 'erlang'; LanguageKind.FSharp = 'fsharp'; LanguageKind.GitCommit = 'git-commit'; LanguageKind.GitRebase = 'rebase'; LanguageKind.Go = 'go'; LanguageKind.Groovy = 'groovy'; LanguageKind.Handlebars = 'handlebars'; LanguageKind.Haskell = 'haskell'; LanguageKind.HTML = 'html'; LanguageKind.Ini = 'ini'; LanguageKind.Java = 'java'; LanguageKind.JavaScript = 'javascript'; LanguageKind.JavaScriptReact = 'javascriptreact'; LanguageKind.JSON = 'json'; LanguageKind.LaTeX = 'latex'; LanguageKind.Less = 'less'; LanguageKind.Lua = 'lua'; LanguageKind.Makefile = 'makefile'; LanguageKind.Markdown = 'markdown'; LanguageKind.ObjectiveC = 'objective-c'; LanguageKind.ObjectiveCPP = 'objective-cpp'; /** * @since 3.18.0 * @proposed */ LanguageKind.Pascal = 'pascal'; LanguageKind.Perl = 'perl'; LanguageKind.Perl6 = 'perl6'; LanguageKind.PHP = 'php'; LanguageKind.Powershell = 'powershell'; LanguageKind.Pug = 'jade'; LanguageKind.Python = 'python'; LanguageKind.R = 'r'; LanguageKind.Razor = 'razor'; LanguageKind.Ruby = 'ruby'; LanguageKind.Rust = 'rust'; LanguageKind.SCSS = 'scss'; LanguageKind.SASS = 'sass'; LanguageKind.Scala = 'scala'; LanguageKind.ShaderLab = 'shaderlab'; LanguageKind.ShellScript = 'shellscript'; LanguageKind.SQL = 'sql'; LanguageKind.Swift = 'swift'; LanguageKind.TypeScript = 'typescript'; LanguageKind.TypeScriptReact = 'typescriptreact'; LanguageKind.TeX = 'tex'; LanguageKind.VisualBasic = 'vb'; LanguageKind.XML = 'xml'; LanguageKind.XSL = 'xsl'; LanguageKind.YAML = 'yaml'; })(LanguageKind || (exports.LanguageKind = LanguageKind = {})); /** * 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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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><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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 move actions: `refactor.move` * * Example move actions: * * - Move a function to a new file * - Move a property between classes * - Move method to base class * - ... * * @since 3.18.0 * @proposed */ CodeActionKind.RefactorMove = 'refactor.move'; /** * 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'; /** * Base kind for all code actions applying to the entire notebook's scope. CodeActionKinds using * this should always begin with `notebook.` * * @since 3.18.0 */ CodeActionKind.Notebook = 'notebook'; })(CodeActionKind || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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"; /** * @since 3.18.0 */ SemanticTokenTypes["label"] = "label"; })(SemanticTokenTypes || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.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 || (exports.InlayHint = InlayHint = {})); var StringValue; (function (StringValue) { function createSnippet(value) { return { kind: 'snippet', value: value }; } StringValue.createSnippet = createSnippet; function isSnippet(value) { var candidate = value; return Is.objectLiteral(candidate) && candidate.kind === 'snippet' && Is.string(candidate.value); } StringValue.isSnippet = isSnippet; })(StringValue || (exports.StringValue = StringValue = {})); var InlineCompletionItem; (function (InlineCompletionItem) { function create(insertText, filterText, range, command) { return { insertText: insertText, filterText: filterText, range: range, command: command }; } InlineCompletionItem.create = create; })(InlineCompletionItem || (exports.InlineCompletionItem = InlineCompletionItem = {})); var InlineCompletionList; (function (InlineCompletionList) { function create(items) { return { items: items }; } InlineCompletionList.create = create; })(InlineCompletionList || (exports.InlineCompletionList = InlineCompletionList = {})); /** * Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. * * @since 3.18.0 * @proposed */ var InlineCompletionTriggerKind; (function (InlineCompletionTriggerKind) { /** * Completion was triggered explicitly by a user gesture. */ InlineCompletionTriggerKind.Invoked = 1; /** * Completion was triggered automatically while editing. */ InlineCompletionTriggerKind.Automatic = 2; })(InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {})); var SelectedCompletionInfo; (function (SelectedCompletionInfo) { function create(range, text) { return { range: range, text: text }; } SelectedCompletionInfo.create = create; })(SelectedCompletionInfo || (exports.SelectedCompletionInfo = SelectedCompletionInfo = {})); var InlineCompletionContext; (function (InlineCompletionContext) { function create(triggerKind, selectedCompletionInfo) { return { triggerKind: triggerKind, selectedCompletionInfo: selectedCompletionInfo }; } InlineCompletionContext.create = create; })(InlineCompletionContext || (exports.InlineCompletionContext = InlineCompletionContext = {})); 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 || (exports.WorkspaceFolder = WorkspaceFolder = {})); exports.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 || (exports.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 = {})); }); /***/ }), /***/ 6487: /***/ (function(__unused_webpack_module, exports, __nccwpck_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.ProposedFeatures = exports.NotebookDocuments = exports.TextDocuments = exports.SemanticTokensBuilder = void 0; const semanticTokens_1 = __nccwpck_require__(698); Object.defineProperty(exports, "SemanticTokensBuilder", ({ enumerable: true, get: function () { return semanticTokens_1.SemanticTokensBuilder; } })); const ic = __nccwpck_require__(9203); __exportStar(__nccwpck_require__(3135), exports); const textDocuments_1 = __nccwpck_require__(892); Object.defineProperty(exports, "TextDocuments", ({ enumerable: true, get: function () { return textDocuments_1.TextDocuments; } })); const notebook_1 = __nccwpck_require__(7301); Object.defineProperty(exports, "NotebookDocuments", ({ enumerable: true, get: function () { return notebook_1.NotebookDocuments; } })); __exportStar(__nccwpck_require__(8511), exports); var ProposedFeatures; (function (ProposedFeatures) { ProposedFeatures.all = { __brand: 'features', languages: ic.InlineCompletionFeature }; })(ProposedFeatures || (exports.ProposedFeatures = ProposedFeatures = {})); /***/ }), /***/ 4181: /***/ ((__unused_webpack_module, exports, __nccwpck_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.CallHierarchyFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const CallHierarchyFeature = (Base) => { return class extends Base { get callHierarchy() { return { onPrepare: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), undefined); }); }, onIncomingCalls: (handler) => { const type = vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); }, onOutgoingCalls: (handler) => { const type = vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); } }; } }; }; exports.CallHierarchyFeature = CallHierarchyFeature; /***/ }), /***/ 2378: /***/ ((__unused_webpack_module, exports, __nccwpck_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.ConfigurationFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const Is = __nccwpck_require__(2472); const ConfigurationFeature = (Base) => { return class extends Base { getConfiguration(arg) { if (!arg) { return this._getConfiguration({}); } else if (Is.string(arg)) { return this._getConfiguration({ section: arg }); } else { return this._getConfiguration(arg); } } _getConfiguration(arg) { const params = { items: Array.isArray(arg) ? arg : [arg] }; return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => { if (Array.isArray(result)) { return Array.isArray(arg) ? result : result[0]; } else { return Array.isArray(arg) ? [] : null; } }); } }; }; exports.ConfigurationFeature = ConfigurationFeature; /***/ }), /***/ 2594: /***/ ((__unused_webpack_module, exports, __nccwpck_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.DiagnosticFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const DiagnosticFeature = (Base) => { return class extends Base { get diagnostics() { return { refresh: () => { return this.connection.sendRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type); }, on: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.partialResult, params)); }); }, onWorkspace: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, params)); }); } }; } }; }; exports.DiagnosticFeature = DiagnosticFeature; /***/ }), /***/ 4068: /***/ ((__unused_webpack_module, exports, __nccwpck_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.FileOperationsFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const FileOperationsFeature = (Base) => { return class extends Base { onDidCreateFiles(handler) { return this.connection.onNotification(vscode_languageserver_protocol_1.DidCreateFilesNotification.type, (params) => { return handler(params); }); } onDidRenameFiles(handler) { return this.connection.onNotification(vscode_languageserver_protocol_1.DidRenameFilesNotification.type, (params) => { return handler(params); }); } onDidDeleteFiles(handler) { return this.connection.onNotification(vscode_languageserver_protocol_1.DidDeleteFilesNotification.type, (params) => { return handler(params); }); } onWillCreateFiles(handler) { return this.connection.onRequest(vscode_languageserver_protocol_1.WillCreateFilesRequest.type, (params, cancel) => { return handler(params, cancel); }); } onWillRenameFiles(handler) { return this.connection.onRequest(vscode_languageserver_protocol_1.WillRenameFilesRequest.type, (params, cancel) => { return handler(params, cancel); }); } onWillDeleteFiles(handler) { return this.connection.onRequest(vscode_languageserver_protocol_1.WillDeleteFilesRequest.type, (params, cancel) => { return handler(params, cancel); }); } }; }; exports.FileOperationsFeature = FileOperationsFeature; /***/ }), /***/ 9610: /***/ ((__unused_webpack_module, exports, __nccwpck_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.FoldingRangeFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const FoldingRangeFeature = (Base) => { return class extends Base { get foldingRange() { return { refresh: () => { return this.connection.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type); }, on: (handler) => { const type = vscode_languageserver_protocol_1.FoldingRangeRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); } }; } }; }; exports.FoldingRangeFeature = FoldingRangeFeature; /***/ }), /***/ 9809: /***/ ((__unused_webpack_module, exports, __nccwpck_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.InlayHintFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const InlayHintFeature = (Base) => { return class extends Base { get inlayHint() { return { refresh: () => { return this.connection.sendRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type); }, on: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params)); }); }, resolve: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, (params, cancel) => { return handler(params, cancel); }); } }; } }; }; exports.InlayHintFeature = InlayHintFeature; /***/ }), /***/ 9203: /***/ ((__unused_webpack_module, exports, __nccwpck_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.InlineCompletionFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const InlineCompletionFeature = (Base) => { return class extends Base { get inlineCompletion() { return { on: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params)); }); } }; } }; }; exports.InlineCompletionFeature = InlineCompletionFeature; /***/ }), /***/ 5170: /***/ ((__unused_webpack_module, exports, __nccwpck_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.InlineValueFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const InlineValueFeature = (Base) => { return class extends Base { get inlineValue() { return { refresh: () => { return this.connection.sendRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type); }, on: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params)); }); } }; } }; }; exports.InlineValueFeature = InlineValueFeature; /***/ }), /***/ 5342: /***/ ((__unused_webpack_module, exports, __nccwpck_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.LinkedEditingRangeFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const LinkedEditingRangeFeature = (Base) => { return class extends Base { onLinkedEditingRange(handler) { return this.connection.onRequest(vscode_languageserver_protocol_1.LinkedEditingRangeRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), undefined); }); } }; }; exports.LinkedEditingRangeFeature = LinkedEditingRangeFeature; /***/ }), /***/ 6532: /***/ ((__unused_webpack_module, exports, __nccwpck_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.MonikerFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const MonikerFeature = (Base) => { return class extends Base { get moniker() { return { on: (handler) => { const type = vscode_languageserver_protocol_1.MonikerRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); }, }; } }; }; exports.MonikerFeature = MonikerFeature; /***/ }), /***/ 7301: /***/ ((__unused_webpack_module, exports, __nccwpck_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.NotebookDocuments = exports.NotebookSyncFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const textDocuments_1 = __nccwpck_require__(892); const NotebookSyncFeature = (Base) => { return class extends Base { get synchronization() { return { onDidOpenNotebookDocument: (handler) => { return this.connection.onNotification(vscode_languageserver_protocol_1.DidOpenNotebookDocumentNotification.type, (params) => { return handler(params); }); }, onDidChangeNotebookDocument: (handler) => { return this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeNotebookDocumentNotification.type, (params) => { return handler(params); }); }, onDidSaveNotebookDocument: (handler) => { return this.connection.onNotification(vscode_languageserver_protocol_1.DidSaveNotebookDocumentNotification.type, (params) => { return handler(params); }); }, onDidCloseNotebookDocument: (handler) => { return this.connection.onNotification(vscode_languageserver_protocol_1.DidCloseNotebookDocumentNotification.type, (params) => { return handler(params); }); } }; } }; }; exports.NotebookSyncFeature = NotebookSyncFeature; class CellTextDocumentConnection { onDidOpenTextDocument(handler) { this.openHandler = handler; return vscode_languageserver_protocol_1.Disposable.create(() => { this.openHandler = undefined; }); } openTextDocument(params) { return this.openHandler && this.openHandler(params); } onDidChangeTextDocument(handler) { this.changeHandler = handler; return vscode_languageserver_protocol_1.Disposable.create(() => { this.changeHandler = handler; }); } changeTextDocument(params) { return this.changeHandler && this.changeHandler(params); } onDidCloseTextDocument(handler) { this.closeHandler = handler; return vscode_languageserver_protocol_1.Disposable.create(() => { this.closeHandler = undefined; }); } closeTextDocument(params) { return this.closeHandler && this.closeHandler(params); } onWillSaveTextDocument() { return CellTextDocumentConnection.NULL_DISPOSE; } onWillSaveTextDocumentWaitUntil() { return CellTextDocumentConnection.NULL_DISPOSE; } onDidSaveTextDocument() { return CellTextDocumentConnection.NULL_DISPOSE; } } CellTextDocumentConnection.NULL_DISPOSE = Object.freeze({ dispose: () => { } }); class NotebookDocuments { constructor(configurationOrTextDocuments) { if (configurationOrTextDocuments instanceof textDocuments_1.TextDocuments) { this._cellTextDocuments = configurationOrTextDocuments; } else { this._cellTextDocuments = new textDocuments_1.TextDocuments(configurationOrTextDocuments); } this.notebookDocuments = new Map(); this.notebookCellMap = new Map(); this._onDidOpen = new vscode_languageserver_protocol_1.Emitter(); this._onDidChange = new vscode_languageserver_protocol_1.Emitter(); this._onDidSave = new vscode_languageserver_protocol_1.Emitter(); this._onDidClose = new vscode_languageserver_protocol_1.Emitter(); } get cellTextDocuments() { return this._cellTextDocuments; } getCellTextDocument(cell) { return this._cellTextDocuments.get(cell.document); } getNotebookDocument(uri) { return this.notebookDocuments.get(uri); } getNotebookCell(uri) { const value = this.notebookCellMap.get(uri); return value && value[0]; } findNotebookDocumentForCell(cell) { const key = typeof cell === 'string' ? cell : cell.document; const value = this.notebookCellMap.get(key); return value && value[1]; } get onDidOpen() { return this._onDidOpen.event; } get onDidSave() { return this._onDidSave.event; } get onDidChange() { return this._onDidChange.event; } get onDidClose() { return this._onDidClose.event; } /** * Listens for `low level` notification on the given connection to * update the notebook documents managed by this instance. * * Please note that the connection only provides handlers not an event model. Therefore * listening on a connection will overwrite the following handlers on a connection: * `onDidOpenNotebookDocument`, `onDidChangeNotebookDocument`, `onDidSaveNotebookDocument`, * and `onDidCloseNotebookDocument`. * * @param connection The connection to listen on. */ listen(connection) { const cellTextDocumentConnection = new CellTextDocumentConnection(); const disposables = []; disposables.push(this.cellTextDocuments.listen(cellTextDocumentConnection)); disposables.push(connection.notebooks.synchronization.onDidOpenNotebookDocument(async (params) => { this.notebookDocuments.set(params.notebookDocument.uri, params.notebookDocument); for (const cellTextDocument of params.cellTextDocuments) { await cellTextDocumentConnection.openTextDocument({ textDocument: cellTextDocument }); } this.updateCellMap(params.notebookDocument); this._onDidOpen.fire(params.notebookDocument); })); disposables.push(connection.notebooks.synchronization.onDidChangeNotebookDocument(async (params) => { const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri); if (notebookDocument === undefined) { return; } notebookDocument.version = params.notebookDocument.version; const oldMetadata = notebookDocument.metadata; let metadataChanged = false; const change = params.change; if (change.metadata !== undefined) { metadataChanged = true; notebookDocument.metadata = change.metadata; } const opened = []; const closed = []; const data = []; const text = []; if (change.cells !== undefined) { const changedCells = change.cells; if (changedCells.structure !== undefined) { const array = changedCells.structure.array; notebookDocument.cells.splice(array.start, array.deleteCount, ...(array.cells !== undefined ? array.cells : [])); // Additional open cell text documents. if (changedCells.structure.didOpen !== undefined) { for (const open of changedCells.structure.didOpen) { await cellTextDocumentConnection.openTextDocument({ textDocument: open }); opened.push(open.uri); } } // Additional closed cell test documents. if (changedCells.structure.didClose) { for (const close of changedCells.structure.didClose) { await cellTextDocumentConnection.closeTextDocument({ textDocument: close }); closed.push(close.uri); } } } if (changedCells.data !== undefined) { const cellUpdates = new Map(changedCells.data.map(cell => [cell.document, cell])); for (let i = 0; i <= notebookDocument.cells.length; i++) { const change = cellUpdates.get(notebookDocument.cells[i].document); if (change !== undefined) { const old = notebookDocument.cells.splice(i, 1, change); data.push({ old: old[0], new: change }); cellUpdates.delete(change.document); if (cellUpdates.size === 0) { break; } } } } if (changedCells.textContent !== undefined) { for (const cellTextDocument of changedCells.textContent) { await cellTextDocumentConnection.changeTextDocument({ textDocument: cellTextDocument.document, contentChanges: cellTextDocument.changes }); text.push(cellTextDocument.document.uri); } } } // Update internal data structure. this.updateCellMap(notebookDocument); const changeEvent = { notebookDocument }; if (metadataChanged) { changeEvent.metadata = { old: oldMetadata, new: notebookDocument.metadata }; } const added = []; for (const open of opened) { added.push(this.getNotebookCell(open)); } const removed = []; for (const close of closed) { removed.push(this.getNotebookCell(close)); } const textContent = []; for (const change of text) { textContent.push(this.getNotebookCell(change)); } if (added.length > 0 || removed.length > 0 || data.length > 0 || textContent.length > 0) { changeEvent.cells = { added, removed, changed: { data, textContent } }; } if (changeEvent.metadata !== undefined || changeEvent.cells !== undefined) { this._onDidChange.fire(changeEvent); } })); disposables.push(connection.notebooks.synchronization.onDidSaveNotebookDocument((params) => { const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri); if (notebookDocument === undefined) { return; } this._onDidSave.fire(notebookDocument); })); disposables.push(connection.notebooks.synchronization.onDidCloseNotebookDocument(async (params) => { const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri); if (notebookDocument === undefined) { return; } this._onDidClose.fire(notebookDocument); for (const cellTextDocument of params.cellTextDocuments) { await cellTextDocumentConnection.closeTextDocument({ textDocument: cellTextDocument }); } this.notebookDocuments.delete(params.notebookDocument.uri); for (const cell of notebookDocument.cells) { this.notebookCellMap.delete(cell.document); } })); return vscode_languageserver_protocol_1.Disposable.create(() => { disposables.forEach(disposable => disposable.dispose()); }); } updateCellMap(notebookDocument) { for (const cell of notebookDocument.cells) { this.notebookCellMap.set(cell.document, [cell, notebookDocument]); } } } exports.NotebookDocuments = NotebookDocuments; /***/ }), /***/ 5643: /***/ ((__unused_webpack_module, exports, __nccwpck_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.attachPartialResult = exports.ProgressFeature = exports.attachWorkDone = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const uuid_1 = __nccwpck_require__(6402); class WorkDoneProgressReporterImpl { constructor(_connection, _token) { this._connection = _connection; this._token = _token; WorkDoneProgressReporterImpl.Instances.set(this._token, this); } begin(title, percentage, message, cancellable) { const param = { kind: 'begin', title, message, cancellable }; if (typeof percentage === 'number') { // Round to the nearest integer, because the percentage // is a uinteger according to the specification param.percentage = Math.round(percentage); } this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param); } report(arg0, arg1) { const param = { kind: 'report' }; if (typeof arg0 === 'number') { // Round to the nearest integer, because the percentage // is a uinteger according to the specification param.percentage = Math.round(arg0); if (arg1 !== undefined) { param.message = arg1; } } else { param.message = arg0; } this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param); } done() { WorkDoneProgressReporterImpl.Instances.delete(this._token); this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, { kind: 'end' }); } } WorkDoneProgressReporterImpl.Instances = new Map(); class WorkDoneProgressServerReporterImpl extends WorkDoneProgressReporterImpl { constructor(connection, token) { super(connection, token); this._source = new vscode_languageserver_protocol_1.CancellationTokenSource(); } get token() { return this._source.token; } done() { this._source.dispose(); super.done(); } cancel() { this._source.cancel(); } } class NullProgressReporter { constructor() { } begin() { } report() { } done() { } } class NullProgressServerReporter extends NullProgressReporter { constructor() { super(); this._source = new vscode_languageserver_protocol_1.CancellationTokenSource(); } get token() { return this._source.token; } done() { this._source.dispose(); } cancel() { this._source.cancel(); } } function attachWorkDone(connection, params) { if (params === undefined || params.workDoneToken === undefined) { return new NullProgressReporter(); } const token = params.workDoneToken; delete params.workDoneToken; return new WorkDoneProgressReporterImpl(connection, token); } exports.attachWorkDone = attachWorkDone; const ProgressFeature = (Base) => { return class extends Base { constructor() { super(); this._progressSupported = false; } initialize(capabilities) { super.initialize(capabilities); if (capabilities?.window?.workDoneProgress === true) { this._progressSupported = true; this.connection.onNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, (params) => { const progress = WorkDoneProgressReporterImpl.Instances.get(params.token); if (progress instanceof WorkDoneProgressServerReporterImpl || progress instanceof NullProgressServerReporter) { progress.cancel(); } }); } } attachWorkDoneProgress(token) { if (token === undefined) { return new NullProgressReporter(); } else { return new WorkDoneProgressReporterImpl(this.connection, token); } } createWorkDoneProgress() { if (this._progressSupported) { const token = (0, uuid_1.generateUuid)(); return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, { token }).then(() => { const result = new WorkDoneProgressServerReporterImpl(this.connection, token); return result; }); } else { return Promise.resolve(new NullProgressServerReporter()); } } }; }; exports.ProgressFeature = ProgressFeature; var ResultProgress; (function (ResultProgress) { ResultProgress.type = new vscode_languageserver_protocol_1.ProgressType(); })(ResultProgress || (ResultProgress = {})); class ResultProgressReporterImpl { constructor(_connection, _token) { this._connection = _connection; this._token = _token; } report(data) { this._connection.sendProgress(ResultProgress.type, this._token, data); } } function attachPartialResult(connection, params) { if (params === undefined || params.partialResultToken === undefined) { return undefined; } const token = params.partialResultToken; delete params.partialResultToken; return new ResultProgressReporterImpl(connection, token); } exports.attachPartialResult = attachPartialResult; /***/ }), /***/ 698: /***/ ((__unused_webpack_module, exports, __nccwpck_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.SemanticTokensBuilder = exports.SemanticTokensDiff = exports.SemanticTokensFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const SemanticTokensFeature = (Base) => { return class extends Base { get semanticTokens() { return { refresh: () => { return this.connection.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type); }, on: (handler) => { const type = vscode_languageserver_protocol_1.SemanticTokensRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); }, onDelta: (handler) => { const type = vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); }, onRange: (handler) => { const type = vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); } }; } }; }; exports.SemanticTokensFeature = SemanticTokensFeature; class SemanticTokensDiff { constructor(originalSequence, modifiedSequence) { this.originalSequence = originalSequence; this.modifiedSequence = modifiedSequence; } computeDiff() { const originalLength = this.originalSequence.length; const modifiedLength = this.modifiedSequence.length; let startIndex = 0; while (startIndex < modifiedLength && startIndex < originalLength && this.originalSequence[startIndex] === this.modifiedSequence[startIndex]) { startIndex++; } if (startIndex < modifiedLength && startIndex < originalLength) { let originalEndIndex = originalLength - 1; let modifiedEndIndex = modifiedLength - 1; while (originalEndIndex >= startIndex && modifiedEndIndex >= startIndex && this.originalSequence[originalEndIndex] === this.modifiedSequence[modifiedEndIndex]) { originalEndIndex--; modifiedEndIndex--; } // if one moved behind the start index move them forward again if (originalEndIndex < startIndex || modifiedEndIndex < startIndex) { originalEndIndex++; modifiedEndIndex++; } const deleteCount = originalEndIndex - startIndex + 1; const newData = this.modifiedSequence.slice(startIndex, modifiedEndIndex + 1); // If we moved behind the start index we could have missed a simple delete. if (newData.length === 1 && newData[0] === this.originalSequence[originalEndIndex]) { return [ { start: startIndex, deleteCount: deleteCount - 1 } ]; } else { return [ { start: startIndex, deleteCount, data: newData } ]; } } else if (startIndex < modifiedLength) { return [ { start: startIndex, deleteCount: 0, data: this.modifiedSequence.slice(startIndex) } ]; } else if (startIndex < originalLength) { return [ { start: startIndex, deleteCount: originalLength - startIndex } ]; } else { // The two arrays are the same. return []; } } } exports.SemanticTokensDiff = SemanticTokensDiff; class SemanticTokensBuilder { constructor() { this._prevData = undefined; this.initialize(); } initialize() { this._id = Date.now(); this._prevLine = 0; this._prevChar = 0; this._data = []; this._dataNonDelta = []; this._dataLen = 0; this._dataIsSortedAndDeltaEncoded = true; } push(line, char, length, tokenType, tokenModifiers) { if (this._dataIsSortedAndDeltaEncoded && (line < this._prevLine || (line === this._prevLine && char < this._prevChar))) { // push calls were ordered and are no longer ordered this._dataIsSortedAndDeltaEncoded = false; this._dataNonDelta = SemanticTokensBuilder._deltaDecode(this._data); } let pushLine = line; let pushChar = char; if (this._dataIsSortedAndDeltaEncoded && this._dataLen > 0) { pushLine -= this._prevLine; if (pushLine === 0) { pushChar -= this._prevChar; } } const dataSource = this._dataIsSortedAndDeltaEncoded ? this._data : this._dataNonDelta; dataSource[this._dataLen++] = pushLine; dataSource[this._dataLen++] = pushChar; dataSource[this._dataLen++] = length; dataSource[this._dataLen++] = tokenType; dataSource[this._dataLen++] = tokenModifiers; this._prevLine = line; this._prevChar = char; } get id() { return this._id.toString(); } static _deltaDecode(data) { // Remove delta encoding from data const tokenCount = (data.length / 5) | 0; let prevLine = 0; let prevChar = 0; const result = []; for (let i = 0; i < tokenCount; i++) { const dstOffset = 5 * i; let line = data[dstOffset]; let char = data[dstOffset + 1]; if (line === 0) { // on the same line as previous token line = prevLine; char += prevChar; } else { // on a different line than previous token line += prevLine; } const length = data[dstOffset + 2]; const tokenType = data[dstOffset + 3]; const tokenModifiers = data[dstOffset + 4]; result[dstOffset + 0] = line; result[dstOffset + 1] = char; result[dstOffset + 2] = length; result[dstOffset + 3] = tokenType; result[dstOffset + 4] = tokenModifiers; prevLine = line; prevChar = char; } return result; } static _sortAndDeltaEncode(data) { const pos = []; const tokenCount = (data.length / 5) | 0; for (let i = 0; i < tokenCount; i++) { pos[i] = i; } pos.sort((a, b) => { const aLine = data[5 * a]; const bLine = data[5 * b]; if (aLine === bLine) { const aChar = data[5 * a + 1]; const bChar = data[5 * b + 1]; return aChar - bChar; } return aLine - bLine; }); const result = []; let prevLine = 0; let prevChar = 0; for (let i = 0; i < tokenCount; i++) { const srcOffset = 5 * pos[i]; const line = data[srcOffset + 0]; const char = data[srcOffset + 1]; const length = data[srcOffset + 2]; const tokenType = data[srcOffset + 3]; const tokenModifiers = data[srcOffset + 4]; const pushLine = line - prevLine; const pushChar = (pushLine === 0 ? char - prevChar : char); const dstOffset = 5 * i; result[dstOffset + 0] = pushLine; result[dstOffset + 1] = pushChar; result[dstOffset + 2] = length; result[dstOffset + 3] = tokenType; result[dstOffset + 4] = tokenModifiers; prevLine = line; prevChar = char; } return result; } getFinalDataDelta() { if (this._dataIsSortedAndDeltaEncoded) { return this._data; } else { return SemanticTokensBuilder._sortAndDeltaEncode(this._dataNonDelta); } } previousResult(id) { if (this.id === id) { this._prevData = this.getFinalDataDelta(); } this.initialize(); } build() { this._prevData = undefined; return { resultId: this.id, data: this.getFinalDataDelta() }; } canBuildEdits() { return this._prevData !== undefined; } buildEdits() { if (this._prevData !== undefined) { return { resultId: this.id, edits: (new SemanticTokensDiff(this._prevData, this.getFinalDataDelta())).computeDiff() }; } else { return this.build(); } } } exports.SemanticTokensBuilder = SemanticTokensBuilder; /***/ }), /***/ 8511: /***/ ((__unused_webpack_module, exports, __nccwpck_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.createConnection = exports.combineFeatures = exports.combineNotebooksFeatures = exports.combineLanguagesFeatures = exports.combineWorkspaceFeatures = exports.combineWindowFeatures = exports.combineClientFeatures = exports.combineTracerFeatures = exports.combineTelemetryFeatures = exports.combineConsoleFeatures = exports._NotebooksImpl = exports._LanguagesImpl = exports.BulkUnregistration = exports.BulkRegistration = exports.ErrorMessageTracker = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const Is = __nccwpck_require__(2472); const UUID = __nccwpck_require__(6402); const progress_1 = __nccwpck_require__(5643); const configuration_1 = __nccwpck_require__(2378); const workspaceFolder_1 = __nccwpck_require__(1224); const callHierarchy_1 = __nccwpck_require__(4181); const semanticTokens_1 = __nccwpck_require__(698); const showDocument_1 = __nccwpck_require__(6746); const fileOperations_1 = __nccwpck_require__(4068); const linkedEditingRange_1 = __nccwpck_require__(5342); const typeHierarchy_1 = __nccwpck_require__(3562); const inlineValue_1 = __nccwpck_require__(5170); const foldingRange_1 = __nccwpck_require__(9610); // import { InlineCompletionFeatureShape, InlineCompletionFeature } from './inlineCompletion.proposed'; const inlayHint_1 = __nccwpck_require__(9809); const diagnostic_1 = __nccwpck_require__(2594); const notebook_1 = __nccwpck_require__(7301); const moniker_1 = __nccwpck_require__(6532); function null2Undefined(value) { if (value === null) { return undefined; } return value; } /** * Helps tracking error message. Equal occurrences of the same * message are only stored once. This class is for example * useful if text documents are validated in a loop and equal * error message should be folded into one. */ class ErrorMessageTracker { constructor() { this._messages = Object.create(null); } /** * Add a message to the tracker. * * @param message The message to add. */ add(message) { let count = this._messages[message]; if (!count) { count = 0; } count++; this._messages[message] = count; } /** * Send all tracked messages to the connection's window. * * @param connection The connection established between client and server. */ sendErrors(connection) { Object.keys(this._messages).forEach(message => { connection.window.showErrorMessage(message); }); } } exports.ErrorMessageTracker = ErrorMessageTracker; class RemoteConsoleImpl { constructor() { } rawAttach(connection) { this._rawConnection = connection; } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } fillServerCapabilities(_capabilities) { } initialize(_capabilities) { } error(message) { this.send(vscode_languageserver_protocol_1.MessageType.Error, message); } warn(message) { this.send(vscode_languageserver_protocol_1.MessageType.Warning, message); } info(message) { this.send(vscode_languageserver_protocol_1.MessageType.Info, message); } log(message) { this.send(vscode_languageserver_protocol_1.MessageType.Log, message); } debug(message) { this.send(vscode_languageserver_protocol_1.MessageType.Debug, message); } send(type, message) { if (this._rawConnection) { this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message }).catch(() => { (0, vscode_languageserver_protocol_1.RAL)().console.error(`Sending log message failed`); }); } } } class _RemoteWindowImpl { constructor() { } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } showErrorMessage(message, ...actions) { const params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions }; return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined); } showWarningMessage(message, ...actions) { const params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions }; return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined); } showInformationMessage(message, ...actions) { const params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions }; return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined); } } const RemoteWindowImpl = (0, showDocument_1.ShowDocumentFeature)((0, progress_1.ProgressFeature)(_RemoteWindowImpl)); var BulkRegistration; (function (BulkRegistration) { /** * Creates a new bulk registration. * @return an empty bulk registration. */ function create() { return new BulkRegistrationImpl(); } BulkRegistration.create = create; })(BulkRegistration || (exports.BulkRegistration = BulkRegistration = {})); class BulkRegistrationImpl { constructor() { this._registrations = []; this._registered = new Set(); } add(type, registerOptions) { const method = Is.string(type) ? type : type.method; if (this._registered.has(method)) { throw new Error(`${method} is already added to this registration`); } const id = UUID.generateUuid(); this._registrations.push({ id: id, method: method, registerOptions: registerOptions || {} }); this._registered.add(method); } asRegistrationParams() { return { registrations: this._registrations }; } } var BulkUnregistration; (function (BulkUnregistration) { function create() { return new BulkUnregistrationImpl(undefined, []); } BulkUnregistration.create = create; })(BulkUnregistration || (exports.BulkUnregistration = BulkUnregistration = {})); class BulkUnregistrationImpl { constructor(_connection, unregistrations) { this._connection = _connection; this._unregistrations = new Map(); unregistrations.forEach(unregistration => { this._unregistrations.set(unregistration.method, unregistration); }); } get isAttached() { return !!this._connection; } attach(connection) { this._connection = connection; } add(unregistration) { this._unregistrations.set(unregistration.method, unregistration); } dispose() { const unregistrations = []; for (const unregistration of this._unregistrations.values()) { unregistrations.push(unregistration); } const params = { unregisterations: unregistrations }; this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => { this._connection.console.info(`Bulk unregistration failed.`); }); } disposeSingle(arg) { const method = Is.string(arg) ? arg : arg.method; const unregistration = this._unregistrations.get(method); if (!unregistration) { return false; } const params = { unregisterations: [unregistration] }; this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => { this._unregistrations.delete(method); }, (_error) => { this._connection.console.info(`Un-registering request handler for ${unregistration.id} failed.`); }); return true; } } class RemoteClientImpl { attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } register(typeOrRegistrations, registerOptionsOrType, registerOptions) { if (typeOrRegistrations instanceof BulkRegistrationImpl) { return this.registerMany(typeOrRegistrations); } else if (typeOrRegistrations instanceof BulkUnregistrationImpl) { return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions); } else { return this.registerSingle2(typeOrRegistrations, registerOptionsOrType); } } registerSingle1(unregistration, type, registerOptions) { const method = Is.string(type) ? type : type.method; const id = UUID.generateUuid(); const params = { registrations: [{ id, method, registerOptions: registerOptions || {} }] }; if (!unregistration.isAttached) { unregistration.attach(this.connection); } return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => { unregistration.add({ id: id, method: method }); return unregistration; }, (_error) => { this.connection.console.info(`Registering request handler for ${method} failed.`); return Promise.reject(_error); }); } registerSingle2(type, registerOptions) { const method = Is.string(type) ? type : type.method; const id = UUID.generateUuid(); const params = { registrations: [{ id, method, registerOptions: registerOptions || {} }] }; return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => { return vscode_languageserver_protocol_1.Disposable.create(() => { this.unregisterSingle(id, method).catch(() => { this.connection.console.info(`Un-registering capability with id ${id} failed.`); }); }); }, (_error) => { this.connection.console.info(`Registering request handler for ${method} failed.`); return Promise.reject(_error); }); } unregisterSingle(id, method) { const params = { unregisterations: [{ id, method }] }; return this.connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => { this.connection.console.info(`Un-registering request handler for ${id} failed.`); }); } registerMany(registrations) { const params = registrations.asRegistrationParams(); return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => { return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; })); }, (_error) => { this.connection.console.info(`Bulk registration failed.`); return Promise.reject(_error); }); } } class _RemoteWorkspaceImpl { constructor() { } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } applyEdit(paramOrEdit) { function isApplyWorkspaceEditParams(value) { return value && !!value.edit; } const params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit }; return this.connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params); } } const RemoteWorkspaceImpl = (0, fileOperations_1.FileOperationsFeature)((0, workspaceFolder_1.WorkspaceFoldersFeature)((0, configuration_1.ConfigurationFeature)(_RemoteWorkspaceImpl))); class TracerImpl { constructor() { this._trace = vscode_languageserver_protocol_1.Trace.Off; } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } set trace(value) { this._trace = value; } log(message, verbose) { if (this._trace === vscode_languageserver_protocol_1.Trace.Off) { return; } this.connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, { message: message, verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined }).catch(() => { // Very hard to decide what to do. We tried to send a log // message which failed so we can't simply send another :-(. }); } } class TelemetryImpl { constructor() { } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } logEvent(data) { this.connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data).catch(() => { this.connection.console.log(`Sending TelemetryEventNotification failed`); }); } } class _LanguagesImpl { constructor() { } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } attachWorkDoneProgress(params) { return (0, progress_1.attachWorkDone)(this.connection, params); } attachPartialResultProgress(_type, params) { return (0, progress_1.attachPartialResult)(this.connection, params); } } exports._LanguagesImpl = _LanguagesImpl; const LanguagesImpl = (0, foldingRange_1.FoldingRangeFeature)((0, moniker_1.MonikerFeature)((0, diagnostic_1.DiagnosticFeature)((0, inlayHint_1.InlayHintFeature)((0, inlineValue_1.InlineValueFeature)((0, typeHierarchy_1.TypeHierarchyFeature)((0, linkedEditingRange_1.LinkedEditingRangeFeature)((0, semanticTokens_1.SemanticTokensFeature)((0, callHierarchy_1.CallHierarchyFeature)(_LanguagesImpl))))))))); class _NotebooksImpl { constructor() { } attach(connection) { this._connection = connection; } get connection() { if (!this._connection) { throw new Error('Remote is not attached to a connection yet.'); } return this._connection; } initialize(_capabilities) { } fillServerCapabilities(_capabilities) { } attachWorkDoneProgress(params) { return (0, progress_1.attachWorkDone)(this.connection, params); } attachPartialResultProgress(_type, params) { return (0, progress_1.attachPartialResult)(this.connection, params); } } exports._NotebooksImpl = _NotebooksImpl; const NotebooksImpl = (0, notebook_1.NotebookSyncFeature)(_NotebooksImpl); function combineConsoleFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineConsoleFeatures = combineConsoleFeatures; function combineTelemetryFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineTelemetryFeatures = combineTelemetryFeatures; function combineTracerFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineTracerFeatures = combineTracerFeatures; function combineClientFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineClientFeatures = combineClientFeatures; function combineWindowFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineWindowFeatures = combineWindowFeatures; function combineWorkspaceFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineWorkspaceFeatures = combineWorkspaceFeatures; function combineLanguagesFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineLanguagesFeatures = combineLanguagesFeatures; function combineNotebooksFeatures(one, two) { return function (Base) { return two(one(Base)); }; } exports.combineNotebooksFeatures = combineNotebooksFeatures; function combineFeatures(one, two) { function combine(one, two, func) { if (one && two) { return func(one, two); } else if (one) { return one; } else { return two; } } const result = { __brand: 'features', console: combine(one.console, two.console, combineConsoleFeatures), tracer: combine(one.tracer, two.tracer, combineTracerFeatures), telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures), client: combine(one.client, two.client, combineClientFeatures), window: combine(one.window, two.window, combineWindowFeatures), workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures), languages: combine(one.languages, two.languages, combineLanguagesFeatures), notebooks: combine(one.notebooks, two.notebooks, combineNotebooksFeatures) }; return result; } exports.combineFeatures = combineFeatures; function createConnection(connectionFactory, watchDog, factories) { const logger = (factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl()); const connection = connectionFactory(logger); logger.rawAttach(connection); const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl()); const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl()); const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl()); const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl()); const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl()); const languages = (factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl()); const notebooks = (factories && factories.notebooks ? new (factories.notebooks(NotebooksImpl))() : new NotebooksImpl()); const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages, notebooks]; function asPromise(value) { if (value instanceof Promise) { return value; } else if (Is.thenable(value)) { return new Promise((resolve, reject) => { value.then((resolved) => resolve(resolved), (error) => reject(error)); }); } else { return Promise.resolve(value); } } let shutdownHandler = undefined; let initializeHandler = undefined; let exitHandler = undefined; const protocolConnection = { listen: () => connection.listen(), sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params), onRequest: (type, handler) => connection.onRequest(type, handler), sendNotification: (type, param) => { const method = Is.string(type) ? type : type.method; return connection.sendNotification(method, param); }, onNotification: (type, handler) => connection.onNotification(type, handler), onProgress: connection.onProgress, sendProgress: connection.sendProgress, onInitialize: (handler) => { initializeHandler = handler; return { dispose: () => { initializeHandler = undefined; } }; }, onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler), onShutdown: (handler) => { shutdownHandler = handler; return { dispose: () => { shutdownHandler = undefined; } }; }, onExit: (handler) => { exitHandler = handler; return { dispose: () => { exitHandler = undefined; } }; }, get console() { return logger; }, get telemetry() { return telemetry; }, get tracer() { return tracer; }, get client() { return client; }, get window() { return remoteWindow; }, get workspace() { return workspace; }, get languages() { return languages; }, get notebooks() { return notebooks; }, onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler), onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler), __textDocumentSync: undefined, onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler), onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler), onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler), onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler), onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler), onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler), sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params), onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler), onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onWorkspaceSymbolResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, handler), onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onCodeActionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, (params, cancel) => { return handler(params, cancel); }), onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => { return handler(params, cancel); }), onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => { return handler(params, cancel); }), onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => { return handler(params, cancel); }), onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => { return handler(params, cancel); }), onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onSelectionRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params)); }), onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => { return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), undefined); }), dispose: () => connection.dispose() }; for (const remote of allRemotes) { remote.attach(protocolConnection); } connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => { watchDog.initialize(params); if (Is.string(params.trace)) { tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace); } for (const remote of allRemotes) { remote.initialize(params.capabilities); } if (initializeHandler) { const result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, (0, progress_1.attachWorkDone)(connection, params), undefined); return asPromise(result).then((value) => { if (value instanceof vscode_languageserver_protocol_1.ResponseError) { return value; } let result = value; if (!result) { result = { capabilities: {} }; } let capabilities = result.capabilities; if (!capabilities) { capabilities = {}; result.capabilities = capabilities; } if (capabilities.textDocumentSync === undefined || capabilities.textDocumentSync === null) { capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None; } else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) { capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None; } for (const remote of allRemotes) { remote.fillServerCapabilities(capabilities); } return result; }); } else { const result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } }; for (const remote of allRemotes) { remote.fillServerCapabilities(result.capabilities); } return result; } }); connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => { watchDog.shutdownReceived = true; if (shutdownHandler) { return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token); } else { return undefined; } }); connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => { try { if (exitHandler) { return exitHandler(); } } finally { if (watchDog.shutdownReceived) { watchDog.exit(0); } else { watchDog.exit(1); } } }); connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => { tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value); }); return protocolConnection; } exports.createConnection = createConnection; /***/ }), /***/ 6746: /***/ ((__unused_webpack_module, exports, __nccwpck_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.ShowDocumentFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const ShowDocumentFeature = (Base) => { return class extends Base { showDocument(params) { return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, params); } }; }; exports.ShowDocumentFeature = ShowDocumentFeature; /***/ }), /***/ 892: /***/ ((__unused_webpack_module, exports, __nccwpck_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.TextDocuments = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); /** * A manager for simple text documents. The manager requires at a minimum that * the server registered for the following text document sync events in the * initialize handler or via dynamic registration: * * - open and close events. * - change events. * * Registering for save and will save events is optional. */ class TextDocuments { /** * Create a new text document manager. */ constructor(configuration) { this._configuration = configuration; this._syncedDocuments = new Map(); this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter(); this._onDidOpen = new vscode_languageserver_protocol_1.Emitter(); this._onDidClose = new vscode_languageserver_protocol_1.Emitter(); this._onDidSave = new vscode_languageserver_protocol_1.Emitter(); this._onWillSave = new vscode_languageserver_protocol_1.Emitter(); } /** * An event that fires when a text document managed by this manager * has been opened. */ get onDidOpen() { return this._onDidOpen.event; } /** * An event that fires when a text document managed by this manager * has been opened or the content changes. */ get onDidChangeContent() { return this._onDidChangeContent.event; } /** * An event that fires when a text document managed by this manager * will be saved. */ get onWillSave() { return this._onWillSave.event; } /** * Sets a handler that will be called if a participant wants to provide * edits during a text document save. */ onWillSaveWaitUntil(handler) { this._willSaveWaitUntil = handler; } /** * An event that fires when a text document managed by this manager * has been saved. */ get onDidSave() { return this._onDidSave.event; } /** * An event that fires when a text document managed by this manager * has been closed. */ get onDidClose() { return this._onDidClose.event; } /** * Returns the document for the given URI. Returns undefined if * the document is not managed by this instance. * * @param uri The text document's URI to retrieve. * @return the text document or `undefined`. */ get(uri) { return this._syncedDocuments.get(uri); } /** * Returns all text documents managed by this instance. * * @return all text documents. */ all() { return Array.from(this._syncedDocuments.values()); } /** * Returns the URIs of all text documents managed by this instance. * * @return the URI's of all text documents. */ keys() { return Array.from(this._syncedDocuments.keys()); } /** * Listens for `low level` notification on the given connection to * update the text documents managed by this instance. * * Please note that the connection only provides handlers not an event model. Therefore * listening on a connection will overwrite the following handlers on a connection: * `onDidOpenTextDocument`, `onDidChangeTextDocument`, `onDidCloseTextDocument`, * `onWillSaveTextDocument`, `onWillSaveTextDocumentWaitUntil` and `onDidSaveTextDocument`. * * Use the corresponding events on the TextDocuments instance instead. * * @param connection The connection to listen on. */ listen(connection) { connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental; const disposables = []; disposables.push(connection.onDidOpenTextDocument((event) => { const td = event.textDocument; const document = this._configuration.create(td.uri, td.languageId, td.version, td.text); this._syncedDocuments.set(td.uri, document); const toFire = Object.freeze({ document }); this._onDidOpen.fire(toFire); this._onDidChangeContent.fire(toFire); })); disposables.push(connection.onDidChangeTextDocument((event) => { const td = event.textDocument; const changes = event.contentChanges; if (changes.length === 0) { return; } const { version } = td; if (version === null || version === undefined) { throw new Error(`Received document change event for ${td.uri} without valid version identifier`); } let syncedDocument = this._syncedDocuments.get(td.uri); if (syncedDocument !== undefined) { syncedDocument = this._configuration.update(syncedDocument, changes, version); this._syncedDocuments.set(td.uri, syncedDocument); this._onDidChangeContent.fire(Object.freeze({ document: syncedDocument })); } })); disposables.push(connection.onDidCloseTextDocument((event) => { const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._syncedDocuments.delete(event.textDocument.uri); this._onDidClose.fire(Object.freeze({ document: syncedDocument })); } })); disposables.push(connection.onWillSaveTextDocument((event) => { const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason })); } })); disposables.push(connection.onWillSaveTextDocumentWaitUntil((event, token) => { const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined && this._willSaveWaitUntil) { return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token); } else { return []; } })); disposables.push(connection.onDidSaveTextDocument((event) => { const syncedDocument = this._syncedDocuments.get(event.textDocument.uri); if (syncedDocument !== undefined) { this._onDidSave.fire(Object.freeze({ document: syncedDocument })); } })); return vscode_languageserver_protocol_1.Disposable.create(() => { disposables.forEach(disposable => disposable.dispose()); }); } } exports.TextDocuments = TextDocuments; /***/ }), /***/ 3562: /***/ ((__unused_webpack_module, exports, __nccwpck_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.TypeHierarchyFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const TypeHierarchyFeature = (Base) => { return class extends Base { get typeHierarchy() { return { onPrepare: (handler) => { return this.connection.onRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), undefined); }); }, onSupertypes: (handler) => { const type = vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); }, onSubtypes: (handler) => { const type = vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type; return this.connection.onRequest(type, (params, cancel) => { return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params)); }); } }; } }; }; exports.TypeHierarchyFeature = TypeHierarchyFeature; /***/ }), /***/ 2472: /***/ ((__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.thenable = 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 thenable(value) { return value && func(value.then); } exports.thenable = thenable; /***/ }), /***/ 6402: /***/ ((__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.generateUuid = exports.parse = exports.isUUID = exports.v4 = exports.empty = void 0; class ValueUUID { constructor(_value) { this._value = _value; // empty } asHex() { return this._value; } equals(other) { return this.asHex() === other.asHex(); } } class V4UUID extends ValueUUID { static _oneOf(array) { return array[Math.floor(array.length * Math.random())]; } static _randomHex() { return V4UUID._oneOf(V4UUID._chars); } constructor() { super([ V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', '4', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._oneOf(V4UUID._timeHighBits), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), '-', V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), V4UUID._randomHex(), ].join('')); } } V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; V4UUID._timeHighBits = ['8', '9', 'a', 'b']; /** * An empty UUID that contains only zeros. */ exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000'); function v4() { return new V4UUID(); } exports.v4 = v4; const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; function isUUID(value) { return _UUIDPattern.test(value); } exports.isUUID = isUUID; /** * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. * @param value A uuid string. */ function parse(value) { if (!isUUID(value)) { throw new Error('invalid uuid'); } return new ValueUUID(value); } exports.parse = parse; function generateUuid() { return v4().asHex(); } exports.generateUuid = generateUuid; /***/ }), /***/ 1224: /***/ ((__unused_webpack_module, exports, __nccwpck_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.WorkspaceFoldersFeature = void 0; const vscode_languageserver_protocol_1 = __nccwpck_require__(3135); const WorkspaceFoldersFeature = (Base) => { return class extends Base { constructor() { super(); this._notificationIsAutoRegistered = false; } initialize(capabilities) { super.initialize(capabilities); const workspaceCapabilities = capabilities.workspace; if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) { this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter(); this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => { this._onDidChangeWorkspaceFolders.fire(params.event); }); } } fillServerCapabilities(capabilities) { super.fillServerCapabilities(capabilities); const changeNotifications = capabilities.workspace?.workspaceFolders?.changeNotifications; this._notificationIsAutoRegistered = changeNotifications === true || typeof changeNotifications === 'string'; } getWorkspaceFolders() { return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type); } get onDidChangeWorkspaceFolders() { if (!this._onDidChangeWorkspaceFolders) { throw new Error('Client doesn\'t support sending workspace folder change events.'); } if (!this._notificationIsAutoRegistered && !this._unregistration) { this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type); } return this._onDidChangeWorkspaceFolders.event; } }; }; exports.WorkspaceFoldersFeature = WorkspaceFoldersFeature; /***/ }), /***/ 7910: /***/ ((__unused_webpack_module, exports, __nccwpck_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.resolveModulePath = exports.FileSystem = exports.resolveGlobalYarnPath = exports.resolveGlobalNodePath = exports.resolve = exports.uriToFilePath = void 0; const url = __nccwpck_require__(7310); const path = __nccwpck_require__(1017); const fs = __nccwpck_require__(7147); const child_process_1 = __nccwpck_require__(2081); /** * @deprecated Use the `vscode-uri` npm module which provides a more * complete implementation of handling VS Code URIs. */ function uriToFilePath(uri) { const parsed = url.parse(uri); if (parsed.protocol !== 'file:' || !parsed.path) { return undefined; } const segments = parsed.path.split('/'); for (let i = 0, len = segments.length; i < len; i++) { segments[i] = decodeURIComponent(segments[i]); } if (process.platform === 'win32' && segments.length > 1) { const first = segments[0]; const second = segments[1]; // Do we have a drive letter and we started with a / which is the // case if the first segement is empty (see split above) if (first.length === 0 && second.length > 1 && second[1] === ':') { // Remove first slash segments.shift(); } } return path.normalize(segments.join('/')); } exports.uriToFilePath = uriToFilePath; function isWindows() { return process.platform === 'win32'; } function resolve(moduleName, nodePath, cwd, tracer) { const nodePathKey = 'NODE_PATH'; const app = [ 'var p = process;', 'p.on(\'message\',function(m){', 'if(m.c===\'e\'){', 'p.exit(0);', '}', 'else if(m.c===\'rs\'){', 'try{', 'var r=require.resolve(m.a);', 'p.send({c:\'r\',s:true,r:r});', '}', 'catch(err){', 'p.send({c:\'r\',s:false});', '}', '}', '});' ].join(''); return new Promise((resolve, reject) => { const env = process.env; const newEnv = Object.create(null); Object.keys(env).forEach(key => newEnv[key] = env[key]); if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) { if (newEnv[nodePathKey]) { newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey]; } else { newEnv[nodePathKey] = nodePath; } if (tracer) { tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`); } } newEnv['ELECTRON_RUN_AS_NODE'] = '1'; try { const cp = (0, child_process_1.fork)('', [], { cwd: cwd, env: newEnv, execArgv: ['-e', app] }); if (cp.pid === void 0) { reject(new Error(`Starting process to resolve node module ${moduleName} failed`)); return; } cp.on('error', (error) => { reject(error); }); cp.on('message', (message) => { if (message.c === 'r') { cp.send({ c: 'e' }); if (message.s) { resolve(message.r); } else { reject(new Error(`Failed to resolve module: ${moduleName}`)); } } }); const message = { c: 'rs', a: moduleName }; cp.send(message); } catch (error) { reject(error); } }); } exports.resolve = resolve; /** * Resolve the global npm package path. * @deprecated Since this depends on the used package manager and their version the best is that servers * implement this themselves since they know best what kind of package managers to support. * @param tracer the tracer to use */ function resolveGlobalNodePath(tracer) { let npmCommand = 'npm'; const env = Object.create(null); Object.keys(process.env).forEach(key => env[key] = process.env[key]); env['NO_UPDATE_NOTIFIER'] = 'true'; const options = { encoding: 'utf8', env }; if (isWindows()) { npmCommand = 'npm.cmd'; options.shell = true; } const handler = () => { }; try { process.on('SIGPIPE', handler); const stdout = (0, child_process_1.spawnSync)(npmCommand, ['config', 'get', 'prefix'], options).stdout; if (!stdout) { if (tracer) { tracer(`'npm config get prefix' didn't return a value.`); } return undefined; } const prefix = stdout.trim(); if (tracer) { tracer(`'npm config get prefix' value is: ${prefix}`); } if (prefix.length > 0) { if (isWindows()) { return path.join(prefix, 'node_modules'); } else { return path.join(prefix, 'lib', 'node_modules'); } } return undefined; } catch (err) { return undefined; } finally { process.removeListener('SIGPIPE', handler); } } exports.resolveGlobalNodePath = resolveGlobalNodePath; /* * Resolve the global yarn pakage path. * @deprecated Since this depends on the used package manager and their version the best is that servers * implement this themselves since they know best what kind of package managers to support. * @param tracer the tracer to use */ function resolveGlobalYarnPath(tracer) { let yarnCommand = 'yarn'; const options = { encoding: 'utf8' }; if (isWindows()) { yarnCommand = 'yarn.cmd'; options.shell = true; } const handler = () => { }; try { process.on('SIGPIPE', handler); const results = (0, child_process_1.spawnSync)(yarnCommand, ['global', 'dir', '--json'], options); const stdout = results.stdout; if (!stdout) { if (tracer) { tracer(`'yarn global dir' didn't return a value.`); if (results.stderr) { tracer(results.stderr); } } return undefined; } const lines = stdout.trim().split(/\r?\n/); for (const line of lines) { try { const yarn = JSON.parse(line); if (yarn.type === 'log') { return path.join(yarn.data, 'node_modules'); } } catch (e) { // Do nothing. Ignore the line } } return undefined; } catch (err) { return undefined; } finally { process.removeListener('SIGPIPE', handler); } } exports.resolveGlobalYarnPath = resolveGlobalYarnPath; var FileSystem; (function (FileSystem) { let _isCaseSensitive = undefined; function isCaseSensitive() { if (_isCaseSensitive !== void 0) { return _isCaseSensitive; } if (process.platform === 'win32') { _isCaseSensitive = false; } else { // convert current file name to upper case / lower case and check if file exists // (guards against cases when name is already all uppercase or lowercase) _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase()); } return _isCaseSensitive; } FileSystem.isCaseSensitive = isCaseSensitive; function isParent(parent, child) { if (isCaseSensitive()) { return path.normalize(child).indexOf(path.normalize(parent)) === 0; } else { return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) === 0; } } FileSystem.isParent = isParent; })(FileSystem || (exports.FileSystem = FileSystem = {})); function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) { if (nodePath) { if (!path.isAbsolute(nodePath)) { nodePath = path.join(workspaceRoot, nodePath); } return resolve(moduleName, nodePath, nodePath, tracer).then((value) => { if (FileSystem.isParent(nodePath, value)) { return value; } else { return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`)); } }).then(undefined, (_error) => { return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer); }); } else { return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer); } } exports.resolveModulePath = resolveModulePath; /***/ }), /***/ 4681: /***/ (function(__unused_webpack_module, exports, __nccwpck_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.createConnection = exports.Files = void 0; const node_util_1 = __nccwpck_require__(7261); const Is = __nccwpck_require__(2472); const server_1 = __nccwpck_require__(8511); const fm = __nccwpck_require__(7910); const node_1 = __nccwpck_require__(4121); __exportStar(__nccwpck_require__(4121), exports); __exportStar(__nccwpck_require__(6487), exports); var Files; (function (Files) { Files.uriToFilePath = fm.uriToFilePath; Files.resolveGlobalNodePath = fm.resolveGlobalNodePath; Files.resolveGlobalYarnPath = fm.resolveGlobalYarnPath; Files.resolve = fm.resolve; Files.resolveModulePath = fm.resolveModulePath; })(Files || (exports.Files = Files = {})); let _protocolConnection; function endProtocolConnection() { if (_protocolConnection === undefined) { return; } try { _protocolConnection.end(); } catch (_err) { // Ignore. The client process could have already // did and we can't send an end into the connection. } } let _shutdownReceived = false; let exitTimer = undefined; function setupExitTimer() { const argName = '--clientProcessId'; function runTimer(value) { try { const processId = parseInt(value); if (!isNaN(processId)) { exitTimer = setInterval(() => { try { process.kill(processId, 0); } catch (ex) { // Parent process doesn't exist anymore. Exit the server. endProtocolConnection(); process.exit(_shutdownReceived ? 0 : 1); } }, 3000); } } catch (e) { // Ignore errors; } } for (let i = 2; i < process.argv.length; i++) { const arg = process.argv[i]; if (arg === argName && i + 1 < process.argv.length) { runTimer(process.argv[i + 1]); return; } else { const args = arg.split('='); if (args[0] === argName) { runTimer(args[1]); } } } } setupExitTimer(); const watchDog = { initialize: (params) => { const processId = params.processId; if (Is.number(processId) && exitTimer === undefined) { // We received a parent process id. Set up a timer to periodically check // if the parent is still alive. setInterval(() => { try { process.kill(processId, 0); } catch (ex) { // Parent process doesn't exist anymore. Exit the server. process.exit(_shutdownReceived ? 0 : 1); } }, 3000); } }, get shutdownReceived() { return _shutdownReceived; }, set shutdownReceived(value) { _shutdownReceived = value; }, exit: (code) => { endProtocolConnection(); process.exit(code); } }; function createConnection(arg1, arg2, arg3, arg4) { let factories; let input; let output; let options; if (arg1 !== undefined && arg1.__brand === 'features') { factories = arg1; arg1 = arg2; arg2 = arg3; arg3 = arg4; } if (node_1.ConnectionStrategy.is(arg1) || node_1.ConnectionOptions.is(arg1)) { options = arg1; } else { input = arg1; output = arg2; options = arg3; } return _createConnection(input, output, options, factories); } exports.createConnection = createConnection; function _createConnection(input, output, options, factories) { let stdio = false; if (!input && !output && process.argv.length > 2) { let port = undefined; let pipeName = undefined; const argv = process.argv.slice(2); for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === '--node-ipc') { input = new node_1.IPCMessageReader(process); output = new node_1.IPCMessageWriter(process); break; } else if (arg === '--stdio') { stdio = true; input = process.stdin; output = process.stdout; break; } else if (arg === '--socket') { port = parseInt(argv[i + 1]); break; } else if (arg === '--pipe') { pipeName = argv[i + 1]; break; } else { const args = arg.split('='); if (args[0] === '--socket') { port = parseInt(args[1]); break; } else if (args[0] === '--pipe') { pipeName = args[1]; break; } } } if (port) { const transport = (0, node_1.createServerSocketTransport)(port); input = transport[0]; output = transport[1]; } else if (pipeName) { const transport = (0, node_1.createServerPipeTransport)(pipeName); input = transport[0]; output = transport[1]; } } const commandLineMessage = 'Use arguments of createConnection or set command line parameters: \'--node-ipc\', \'--stdio\' or \'--socket={number}\''; if (!input) { throw new Error('Connection input stream is not set. ' + commandLineMessage); } if (!output) { throw new Error('Connection output stream is not set. ' + commandLineMessage); } // Backwards compatibility if (Is.func(input.read) && Is.func(input.on)) { const inputStream = input; inputStream.on('end', () => { endProtocolConnection(); process.exit(_shutdownReceived ? 0 : 1); }); inputStream.on('close', () => { endProtocolConnection(); process.exit(_shutdownReceived ? 0 : 1); }); } const connectionFactory = (logger) => { const result = (0, node_1.createProtocolConnection)(input, output, logger, options); if (stdio) { patchConsole(logger); } return result; }; return (0, server_1.createConnection)(connectionFactory, watchDog, factories); } function patchConsole(logger) { function serialize(args) { return args.map(arg => typeof arg === 'string' ? arg : (0, node_util_1.inspect)(arg)).join(' '); } const counters = new Map(); console.assert = function assert(assertion, ...args) { if (assertion) { return; } if (args.length === 0) { logger.error('Assertion failed'); } else { const [message, ...rest] = args; logger.error(`Assertion failed: ${message} ${serialize(rest)}`); } }; console.count = function count(label = 'default') { const message = String(label); let counter = counters.get(message) ?? 0; counter += 1; counters.set(message, counter); logger.log(`${message}: ${message}`); }; console.countReset = function countReset(label) { if (label === undefined) { counters.clear(); } else { counters.delete(String(label)); } }; console.debug = function debug(...args) { logger.log(serialize(args)); }; console.dir = function dir(arg, options) { // @ts-expect-error https://github.com/DefinitelyTyped/DefinitelyTyped/pull/66626 logger.log((0, node_util_1.inspect)(arg, options)); }; console.log = function log(...args) { logger.log(serialize(args)); }; console.error = function error(...args) { logger.error(serialize(args)); }; console.trace = function trace(...args) { const stack = new Error().stack.replace(/(.+\n){2}/, ''); let message = 'Trace'; if (args.length !== 0) { message += `: ${serialize(args)}`; } logger.log(`${message}\n${stack}`); }; console.warn = function warn(...args) { logger.warn(serialize(args)); }; } /***/ }), /***/ 9284: /***/ ((module, __unused_webpack_exports, __nccwpck_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 = __nccwpck_require__(4681); /***/ }), /***/ 2699: /***/ (function(module) { !function(t,e){if(true)module.exports=e();else { var n, r; }}(this,(()=>(()=>{"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,a=0;a<=t.length;++a){if(a2){var h=n.lastIndexOf("/");if(h!==n.length-1){-1===h?(n="",i=0):i=(n=n.slice(0,h)).length-1-n.lastIndexOf("/"),o=a,s=0;continue}}else if(2===n.length||1===n.length){n="",i=0,o=a,s=0;continue}e&&(n.length>0?n+="/..":n="..",i=2)}else n.length>0?n+="/"+t.slice(o+1,a):n=t.slice(o+1,a),i=a-o-1;o=a,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;r0&&(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;ic){if(47===r.charCodeAt(a+u))return r.slice(a+u+1);if(0===u)return r.slice(a+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(a+u))break;47===l&&(f=u)}var d="";for(u=i+f+1;u<=o;++u)u!==o&&47!==t.charCodeAt(u)||(0===d.length?d+="..":d+="/..");return d.length>0?d+r.slice(a+f):(a+=f,47===r.charCodeAt(a)&&++a,r.slice(a))},_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 a=r.length-1,h=-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===h&&(s=!1,h=n+1),a>=0&&(c===r.charCodeAt(a)?-1==--a&&(o=n):(a=-1,o=h))}return i===o?o=h:-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,a=t.length-1;a>=0;--a){var h=t.charCodeAt(a);if(47!==h)-1===i&&(o=!1,i=a+1),46===h?-1===r?r=a:1!==s&&(s=1):-1!==r&&(s=-1);else if(!o){n=a+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,a=0,h=-1,c=!0,f=t.length-1,u=0;f>=n;--f)if(47!==(i=t.charCodeAt(f)))-1===h&&(c=!1,h=f+1),46===i?-1===s?s=f:1!==u&&(u=1):-1!==s&&(u=-1);else if(!c){a=f+1;break}return-1===s||-1===h||0===u||1===u&&s===h-1&&s===a+1?-1!==h&&(r.base=r.name=0===a&&o?t.slice(1,h):t.slice(a,h)):(0===a&&o?(r.name=t.slice(1,s),r.base=t.slice(1,h)):(r.name=t.slice(a,s),r.base=t.slice(a,h)),r.ext=t.slice(s,h)),a>0?r.dir=t.slice(0,a-1):o&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};n.posix=n,t.exports=n},674:(t,e)=>{if(Object.defineProperty(e,"__esModule",{value:!0}),e.isWindows=void 0,"object"==typeof process)e.isWindows="win32"===process.platform;else if("object"==typeof navigator){let t=navigator.userAgent;e.isWindows=t.indexOf("Windows")>=0}},796:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.uriToFsPath=e.URI=void 0;const n=r(674),i=/^\w[\w\d+.-]*$/,o=/^\//,s=/^\/\//;function a(t,e){if(!t.scheme&&e)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t.authority}", path: "${t.path}", query: "${t.query}", fragment: "${t.fragment}"}`);if(t.scheme&&!i.test(t.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(t.path)if(t.authority){if(!o.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(s.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="",c="/",f=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class u{static isUri(t){return t instanceof u||!!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]!==c&&(e=c+e):e=c}return e}(this.scheme,r||h),this.query=n||h,this.fragment=i||h,a(this,o))}get fsPath(){return v(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 d(e,r,n,i,o)}static parse(t,e=!1){const r=f.exec(t);return r?new d(r[2]||h,w(r[4]||h),w(r[5]||h),w(r[7]||h),w(r[9]||h),e):new d(h,h,h,h,h)}static file(t){let e=h;if(n.isWindows&&(t=t.replace(/\\/g,c)),t[0]===c&&t[1]===c){const r=t.indexOf(c,2);-1===r?(e=t.substring(2),t=c):(e=t.substring(2,r),t=t.substring(r)||c)}return new d("file",e,t,h,h)}static from(t){const e=new d(t.scheme,t.authority,t.path,t.query,t.fragment);return a(e,!0),e}toString(t=!1){return y(this,t)}toJSON(){return this}static revive(t){if(t){if(t instanceof u)return t;{const e=new d(t);return e._formatted=t.external,e._fsPath=t._sep===l?t.fsPath:null,e}}return t}}e.URI=u;const l=n.isWindows?1:void 0;class d extends u{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=v(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=l),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 p={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 g(t,e,r){let n,i=-1;for(let o=0;o=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=p[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 m(t){let e;for(let r=0;r1&&"file"===t.scheme?`//${t.authority}${t.path}`:47===t.path.charCodeAt(0)&&(t.path.charCodeAt(1)>=65&&t.path.charCodeAt(1)<=90||t.path.charCodeAt(1)>=97&&t.path.charCodeAt(1)<=122)&&58===t.path.charCodeAt(2)?e?t.path.substr(1):t.path[1].toLowerCase()+t.path.substr(2):t.path,n.isWindows&&(r=r.replace(/\//g,"\\")),r}function y(t,e){const r=e?m:g;let n="",{scheme:i,authority:o,path:s,query:a,fragment:h}=t;if(i&&(n+=i,n+=":"),(o||"file"===i)&&(n+=c,n+=c),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 a&&(n+="?",n+=r(a,!1,!1)),h&&(n+="#",n+=e?h:g(h,!1,!1)),n}function b(t){try{return decodeURIComponent(t)}catch{return t.length>3?t.substr(0,3)+b(t.substr(3)):t}}e.uriToFsPath=v;const C=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function w(t){return t.match(C)?t.replace(C,(t=>b(t))):t}},679:function(t,e,r){var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.prototype.hasOwnProperty.call(t,r)&&n(e,t,r);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.Utils=void 0;const s=o(r(470)),a=s.posix||s,h="/";var c;!function(t){t.joinPath=function(t,...e){return t.with({path:a.join(t.path,...e)})},t.resolvePath=function(t,...e){let r=t.path,n=!1;r[0]!==h&&(r=h+r,n=!0);let i=a.resolve(r,...e);return n&&i[0]===h&&!t.authority&&(i=i.substring(1)),t.with({path:i})},t.dirname=function(t){if(0===t.path.length||t.path===h)return t;let e=a.dirname(t.path);return 1===e.length&&46===e.charCodeAt(0)&&(e=""),t.with({path:e})},t.basename=function(t){return a.basename(t.path)},t.extname=function(t){return a.extname(t.path)}}(c||(e.Utils=c={}))}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}var n={};return(()=>{var t=n;Object.defineProperty(t,"__esModule",{value:!0}),t.Utils=t.URI=void 0;const e=r(796);Object.defineProperty(t,"URI",{enumerable:!0,get:function(){return e.URI}});const i=r(679);Object.defineProperty(t,"Utils",{enumerable:!0,get:function(){return i.Utils}})})(),n})())); //# sourceMappingURL=index.js.map /***/ }), /***/ 5711: /***/ ((__unused_webpack_module, exports, __nccwpck_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.startServer = startServer; const vscode_languageserver_1 = __nccwpck_require__(4681); const runner_1 = __nccwpck_require__(8605); const validation_1 = __nccwpck_require__(3711); const vscode_json_languageservice_1 = __nccwpck_require__(447); const languageModelCache_1 = __nccwpck_require__(5387); const vscode_uri_1 = __nccwpck_require__(2699); const l10n = __nccwpck_require__(5697); const request_light_1 = __nccwpck_require__(7017); var SchemaAssociationNotification; (function (SchemaAssociationNotification) { SchemaAssociationNotification.type = new vscode_languageserver_1.NotificationType('json/schemaAssociations'); })(SchemaAssociationNotification || (SchemaAssociationNotification = {})); var VSCodeContentRequest; (function (VSCodeContentRequest) { VSCodeContentRequest.type = new vscode_languageserver_1.RequestType('vscode/content'); })(VSCodeContentRequest || (VSCodeContentRequest = {})); var SchemaContentChangeNotification; (function (SchemaContentChangeNotification) { SchemaContentChangeNotification.type = new vscode_languageserver_1.NotificationType('json/schemaContent'); })(SchemaContentChangeNotification || (SchemaContentChangeNotification = {})); var ForceValidateRequest; (function (ForceValidateRequest) { ForceValidateRequest.type = new vscode_languageserver_1.RequestType('json/validate'); })(ForceValidateRequest || (ForceValidateRequest = {})); var LanguageStatusRequest; (function (LanguageStatusRequest) { LanguageStatusRequest.type = new vscode_languageserver_1.RequestType('json/languageStatus'); })(LanguageStatusRequest || (LanguageStatusRequest = {})); var DocumentSortingRequest; (function (DocumentSortingRequest) { DocumentSortingRequest.type = new vscode_languageserver_1.RequestType('json/sort'); })(DocumentSortingRequest || (DocumentSortingRequest = {})); const workspaceContext = { resolveRelativePath: (relativePath, resource) => { const base = resource.substring(0, resource.lastIndexOf('/') + 1); return vscode_uri_1.Utils.resolvePath(vscode_uri_1.URI.parse(base), relativePath).toString(); } }; function startServer(connection, runtime) { function getSchemaRequestService(handledSchemas = ['https', 'http', 'file']) { const builtInHandlers = {}; for (const protocol of handledSchemas) { if (protocol === 'file') { builtInHandlers[protocol] = runtime.file; } else if (protocol === 'http' || protocol === 'https') { builtInHandlers[protocol] = runtime.http; } } return (uri) => { const protocol = uri.substr(0, uri.indexOf(':')); const builtInHandler = builtInHandlers[protocol]; if (builtInHandler) { return builtInHandler.getContent(uri); } return connection.sendRequest(VSCodeContentRequest.type, uri).then(responseText => { return responseText; }, error => { return Promise.reject(error.message); }); }; } // create the JSON language service let languageService = (0, vscode_json_languageservice_1.getLanguageService)({ workspaceContext, contributions: [], clientCapabilities: vscode_json_languageservice_1.ClientCapabilities.LATEST }); // Create a text document manager. const documents = new vscode_languageserver_1.TextDocuments(vscode_json_languageservice_1.TextDocument); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); let clientSnippetSupport = false; let dynamicFormatterRegistration = false; let hierarchicalDocumentSymbolSupport = false; let foldingRangeLimitDefault = Number.MAX_VALUE; let resultLimit = Number.MAX_VALUE; let jsonFoldingRangeLimit = Number.MAX_VALUE; let jsoncFoldingRangeLimit = Number.MAX_VALUE; let jsonColorDecoratorLimit = Number.MAX_VALUE; let jsoncColorDecoratorLimit = Number.MAX_VALUE; let formatterMaxNumberOfEdits = Number.MAX_VALUE; let diagnosticsSupport; // After the server has started the client sends an initialize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. connection.onInitialize((params) => { setSchemaStoreSettingsIfNotSet(); const initializationOptions = params.initializationOptions || {}; const handledProtocols = initializationOptions?.handledSchemaProtocols; languageService = (0, vscode_json_languageservice_1.getLanguageService)({ schemaRequestService: getSchemaRequestService(handledProtocols), workspaceContext, contributions: [], clientCapabilities: params.capabilities }); function getClientCapability(name, def) { const keys = name.split('.'); let c = params.capabilities; for (let i = 0; c && i < keys.length; i++) { if (!c.hasOwnProperty(keys[i])) { return def; } c = c[keys[i]]; } return c; } clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false); dynamicFormatterRegistration = getClientCapability('textDocument.rangeFormatting.dynamicRegistration', false) && (typeof initializationOptions.provideFormatter !== 'boolean'); foldingRangeLimitDefault = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE); hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false); formatterMaxNumberOfEdits = initializationOptions.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE; const supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined); if (supportsDiagnosticPull === undefined) { diagnosticsSupport = (0, validation_1.registerDiagnosticsPushSupport)(documents, connection, runtime, validateTextDocument); } else { diagnosticsSupport = (0, validation_1.registerDiagnosticsPullSupport)(documents, connection, runtime, validateTextDocument); } const capabilities = { textDocumentSync: vscode_languageserver_1.TextDocumentSyncKind.Incremental, completionProvider: clientSnippetSupport ? { resolveProvider: false, // turn off resolving as the current language service doesn't do anything on resolve. Also fixes #91747 triggerCharacters: ['"', ':'] } : undefined, hoverProvider: true, documentSymbolProvider: true, documentRangeFormattingProvider: initializationOptions.provideFormatter === true, documentFormattingProvider: initializationOptions.provideFormatter === true, colorProvider: {}, foldingRangeProvider: true, selectionRangeProvider: true, documentLinkProvider: {}, diagnosticProvider: { documentSelector: null, interFileDependencies: false, workspaceDiagnostics: false }, codeActionProvider: true }; return { capabilities }; }); let schemaStoreSettings = []; let jsonConfigurationSettings = undefined; let schemaAssociations = undefined; let formatterRegistrations = null; let validateEnabled = true; let keepLinesEnabled = false; // The settings have changed. Is sent on server activation as well. connection.onDidChangeConfiguration((change) => { const settings = change.settings; runtime.configureHttpRequests?.(settings?.http?.proxy, !!settings.http?.proxyStrictSSL); jsonConfigurationSettings = settings.json?.schemas; validateEnabled = !!settings.json?.validate?.enable; keepLinesEnabled = settings.json?.keepLines?.enable || false; updateConfiguration(); const sanitizeLimitSetting = (settingValue) => Math.trunc(Math.max(settingValue, 0)); resultLimit = sanitizeLimitSetting(settings.json?.resultLimit || Number.MAX_VALUE); jsonFoldingRangeLimit = sanitizeLimitSetting(settings.json?.jsonFoldingLimit || foldingRangeLimitDefault); jsoncFoldingRangeLimit = sanitizeLimitSetting(settings.json?.jsoncFoldingLimit || foldingRangeLimitDefault); jsonColorDecoratorLimit = sanitizeLimitSetting(settings.json?.jsonColorDecoratorLimit || Number.MAX_VALUE); jsoncColorDecoratorLimit = sanitizeLimitSetting(settings.json?.jsoncColorDecoratorLimit || Number.MAX_VALUE); // dynamically enable & disable the formatter if (dynamicFormatterRegistration) { const enableFormatter = settings.json?.format?.enable; if (enableFormatter) { if (!formatterRegistrations) { const documentSelector = [{ language: 'json' }, { language: 'jsonc' }]; formatterRegistrations = [ connection.client.register(vscode_languageserver_1.DocumentRangeFormattingRequest.type, { documentSelector }), connection.client.register(vscode_languageserver_1.DocumentFormattingRequest.type, { documentSelector }) ]; } } else if (formatterRegistrations) { formatterRegistrations.forEach(p => p.then(r => r.dispose())); formatterRegistrations = null; } } }); function setSchemaStoreSettingsIfNotSet() { if (schemaStoreSettings.length === 0) { getSchemaStoreMatchingSchemas().then(schemaStore => { schemaStoreSettings = schemaStore.schemas; updateConfiguration(); }); } } function getSchemaStoreMatchingSchemas() { return (0, request_light_1.xhr)({ url: "http://schemastore.org/api/json/catalog.json" }).then(response => { let languageSettings = { schemas: new Array() }; let schemas = JSON.parse(response.responseText); for (let schemaIndex in schemas.schemas) { let schema = schemas.schemas[schemaIndex]; languageSettings.schemas.push({ uri: schema.url, fileMatch: schema.fileMatch || [] }); } return languageSettings; }, (error) => { throw error; }); } // The jsonValidation extension configuration has changed connection.onNotification(SchemaAssociationNotification.type, associations => { schemaAssociations = associations; updateConfiguration(); }); // A schema has changed connection.onNotification(SchemaContentChangeNotification.type, uriOrUris => { let needsRevalidation = false; if (Array.isArray(uriOrUris)) { for (const uri of uriOrUris) { if (languageService.resetSchema(uri)) { needsRevalidation = true; } } } else { needsRevalidation = languageService.resetSchema(uriOrUris); } if (needsRevalidation) { diagnosticsSupport?.requestRefresh(); } }); // Retry schema validation on all open documents connection.onRequest(ForceValidateRequest.type, async (uri) => { const document = documents.get(uri); if (document) { updateConfiguration(); return await validateTextDocument(document); } return []; }); connection.onRequest(LanguageStatusRequest.type, async (uri) => { const document = documents.get(uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.getLanguageStatus(document, jsonDocument); } else { return { schemas: [] }; } }); connection.onRequest(DocumentSortingRequest.type, async (params) => { const uri = params.uri; const options = params.options; const document = documents.get(uri); if (document) { return languageService.sort(document, options); } return []; }); function updateConfiguration() { const languageSettings = { validate: validateEnabled, allowComments: true, schemas: new Array() }; if (schemaAssociations) { if (Array.isArray(schemaAssociations)) { Array.prototype.push.apply(languageSettings.schemas, schemaAssociations); } else { for (const pattern in schemaAssociations) { const association = schemaAssociations[pattern]; if (Array.isArray(association)) { association.forEach(uri => { languageSettings.schemas.push({ uri, fileMatch: [pattern] }); }); } } } } if (jsonConfigurationSettings) { jsonConfigurationSettings.forEach((schema, index) => { let uri = schema.url; if (!uri && schema.schema) { uri = schema.schema.id || `vscode://schemas/custom/${index}`; } if (uri) { languageSettings.schemas.push({ uri, fileMatch: schema.fileMatch, schema: schema.schema, folderUri: schema.folderUri }); } }); } if (schemaStoreSettings) { languageSettings.schemas = languageSettings.schemas.concat(schemaStoreSettings); } languageService.configure(languageSettings); diagnosticsSupport?.requestRefresh(); } async function validateTextDocument(textDocument) { if (textDocument.getText().length === 0) { return []; // ignore empty documents } const jsonDocument = getJSONDocument(textDocument); const documentSettings = textDocument.languageId === 'jsonc' ? { comments: 'ignore', trailingCommas: 'warning' } : { comments: 'error', trailingCommas: 'error' }; return await languageService.doValidation(textDocument, jsonDocument, documentSettings); } connection.onDidChangeWatchedFiles((change) => { // Monitored files have changed in VSCode let hasChanges = false; change.changes.forEach(c => { if (languageService.resetSchema(c.uri)) { hasChanges = true; } }); if (hasChanges) { diagnosticsSupport?.requestRefresh(); } }); const jsonDocuments = (0, languageModelCache_1.getLanguageModelCache)(10, 60, document => languageService.parseJSONDocument(document)); documents.onDidClose(e => { jsonDocuments.onDocumentRemoved(e.document); }); connection.onShutdown(() => { jsonDocuments.dispose(); }); function getJSONDocument(document) { return jsonDocuments.get(document); } connection.onCompletion((textDocumentPosition, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.doComplete(document, textDocumentPosition.position, jsonDocument); } return null; }, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onHover((textDocumentPositionParams, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(textDocumentPositionParams.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.doHover(document, textDocumentPositionParams.position, jsonDocument); } return null; }, null, `Error while computing hover for ${textDocumentPositionParams.textDocument.uri}`, token); }); connection.onDocumentSymbol((documentSymbolParams, token) => { return (0, runner_1.runSafe)(runtime, () => { const document = documents.get(documentSymbolParams.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); if (hierarchicalDocumentSymbolSupport) { return languageService.findDocumentSymbols2(document, jsonDocument, { resultLimit }); } else { return languageService.findDocumentSymbols(document, jsonDocument, { resultLimit }); } } return []; }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token); }); connection.onCodeAction((codeActionParams, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(codeActionParams.textDocument.uri); if (document) { const sortCodeAction = vscode_languageserver_1.CodeAction.create('Sort JSON', vscode_languageserver_1.CodeActionKind.Source.concat('.sort', '.json')); sortCodeAction.command = { command: 'json.sort', title: l10n.t('Sort JSON') }; return [sortCodeAction]; } return []; }, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token); }); function onFormat(textDocument, range, options) { options.keepLines = keepLinesEnabled; const document = documents.get(textDocument.uri); if (document) { const edits = languageService.format(document, range ?? getFullRange(document), options); if (edits.length > formatterMaxNumberOfEdits) { const newText = vscode_json_languageservice_1.TextDocument.applyEdits(document, edits); return [vscode_languageserver_1.TextEdit.replace(getFullRange(document), newText)]; } return edits; } return []; } connection.onDocumentRangeFormatting((formatParams, token) => { return (0, runner_1.runSafe)(runtime, () => onFormat(formatParams.textDocument, formatParams.range, formatParams.options), [], `Error while formatting range for ${formatParams.textDocument.uri}`, token); }); connection.onDocumentFormatting((formatParams, token) => { return (0, runner_1.runSafe)(runtime, () => onFormat(formatParams.textDocument, undefined, formatParams.options), [], `Error while formatting ${formatParams.textDocument.uri}`, token); }); connection.onDocumentColor((params, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); const resultLimit = document.languageId === 'jsonc' ? jsoncColorDecoratorLimit : jsonColorDecoratorLimit; return languageService.findDocumentColors(document, jsonDocument, { resultLimit }); } return []; }, [], `Error while computing document colors for ${params.textDocument.uri}`, token); }); connection.onColorPresentation((params, token) => { return (0, runner_1.runSafe)(runtime, () => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.getColorPresentations(document, jsonDocument, params.color, params.range); } return []; }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token); }); connection.onFoldingRanges((params, token) => { return (0, runner_1.runSafe)(runtime, () => { const document = documents.get(params.textDocument.uri); if (document) { const rangeLimit = document.languageId === 'jsonc' ? jsoncFoldingRangeLimit : jsonFoldingRangeLimit; return languageService.getFoldingRanges(document, { rangeLimit }); } return null; }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token); }); connection.onSelectionRanges((params, token) => { return (0, runner_1.runSafe)(runtime, () => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.getSelectionRanges(document, params.positions, jsonDocument); } return []; }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token); }); connection.onDocumentLinks((params, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { const jsonDocument = getJSONDocument(document); return languageService.findLinks(document, jsonDocument); } return []; }, [], `Error while computing links for ${params.textDocument.uri}`, token); }); // Listen on the connection connection.listen(); } function getFullRange(document) { return vscode_json_languageservice_1.Range.create(vscode_json_languageservice_1.Position.create(0, 0), document.positionAt(document.getText().length)); } /***/ }), /***/ 5387: /***/ ((__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.getLanguageModelCache = getLanguageModelCache; function getLanguageModelCache(maxEntries, cleanupIntervalTimeInSec, parse) { let languageModels = {}; let nModels = 0; let cleanupInterval = undefined; if (cleanupIntervalTimeInSec > 0) { cleanupInterval = setInterval(() => { const cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000; const uris = Object.keys(languageModels); for (const uri of uris) { const languageModelInfo = languageModels[uri]; if (languageModelInfo.cTime < cutoffTime) { delete languageModels[uri]; nModels--; } } }, cleanupIntervalTimeInSec * 1000); } return { get(document) { const version = document.version; const languageId = document.languageId; const languageModelInfo = languageModels[document.uri]; if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) { languageModelInfo.cTime = Date.now(); return languageModelInfo.languageModel; } const languageModel = parse(document); languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() }; if (!languageModelInfo) { nModels++; } if (nModels === maxEntries) { let oldestTime = Number.MAX_VALUE; let oldestUri = null; for (const uri in languageModels) { const languageModelInfo = languageModels[uri]; if (languageModelInfo.cTime < oldestTime) { oldestUri = uri; oldestTime = languageModelInfo.cTime; } } if (oldestUri) { delete languageModels[oldestUri]; nModels--; } } return languageModel; }, onDocumentRemoved(document) { const uri = document.uri; if (languageModels[uri]) { delete languageModels[uri]; nModels--; } }, dispose() { if (typeof cleanupInterval !== 'undefined') { clearInterval(cleanupInterval); cleanupInterval = undefined; languageModels = {}; nModels = 0; } } }; } /***/ }), /***/ 6092: /***/ ((__unused_webpack_module, exports, __nccwpck_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 })); const node_1 = __nccwpck_require__(9284); const runner_1 = __nccwpck_require__(8605); const jsonServer_1 = __nccwpck_require__(5711); const request_light_1 = __nccwpck_require__(7017); const vscode_uri_1 = __nccwpck_require__(2699); const fs = __nccwpck_require__(7147); // Create a connection for the server. const connection = (0, node_1.createConnection)(); console.log = connection.console.log.bind(connection.console); console.error = connection.console.error.bind(connection.console); process.on('unhandledRejection', (e) => { connection.console.error((0, runner_1.formatError)(`Unhandled exception`, e)); }); function getHTTPRequestService() { return { getContent(uri, _encoding) { const headers = { 'Accept-Encoding': 'gzip, deflate' }; return (0, request_light_1.xhr)({ url: uri, followRedirects: 5, headers }).then(response => { return response.responseText; }, (error) => { return Promise.reject(error.responseText || (0, request_light_1.getErrorStatusDescription)(error.status) || error.toString()); }); } }; } function getFileRequestService() { return { getContent(location, encoding) { return new Promise((c, e) => { const uri = vscode_uri_1.URI.parse(location); fs.readFile(uri.fsPath, encoding, (err, buf) => { if (err) { return e(err); } c(buf.toString()); }); }); } }; } const runtime = { timer: { setImmediate(callback, ...args) { const handle = setImmediate(callback, ...args); return { dispose: () => clearImmediate(handle) }; }, setTimeout(callback, ms, ...args) { const handle = setTimeout(callback, ms, ...args); return { dispose: () => clearTimeout(handle) }; } }, file: getFileRequestService(), http: getHTTPRequestService(), configureHttpRequests: request_light_1.configure }; (0, jsonServer_1.startServer)(connection, runtime); /***/ }), /***/ 8605: /***/ ((__unused_webpack_module, exports, __nccwpck_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.formatError = formatError; exports.runSafeAsync = runSafeAsync; exports.runSafe = runSafe; const vscode_languageserver_1 = __nccwpck_require__(4681); function formatError(message, err) { if (err instanceof Error) { const error = err; return `${message}: ${error.message}\n${error.stack}`; } else if (typeof err === 'string') { return `${message}: ${err}`; } else if (err) { return `${message}: ${err.toString()}`; } return message; } function runSafeAsync(runtime, func, errorVal, errorMessage, token) { return new Promise((resolve) => { runtime.timer.setImmediate(() => { if (token.isCancellationRequested) { resolve(cancelValue()); return; } return func().then(result => { if (token.isCancellationRequested) { resolve(cancelValue()); return; } else { resolve(result); } }, e => { console.error(formatError(errorMessage, e)); resolve(errorVal); }); }); }); } function runSafe(runtime, func, errorVal, errorMessage, token) { return new Promise((resolve) => { runtime.timer.setImmediate(() => { if (token.isCancellationRequested) { resolve(cancelValue()); } else { try { const result = func(); if (token.isCancellationRequested) { resolve(cancelValue()); return; } else { resolve(result); } } catch (e) { console.error(formatError(errorMessage, e)); resolve(errorVal); } } }); }); } function cancelValue() { console.log('cancelled'); return new vscode_languageserver_1.ResponseError(vscode_languageserver_1.LSPErrorCodes.RequestCancelled, 'Request cancelled'); } /***/ }), /***/ 3711: /***/ ((__unused_webpack_module, exports, __nccwpck_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.registerDiagnosticsPushSupport = registerDiagnosticsPushSupport; exports.registerDiagnosticsPullSupport = registerDiagnosticsPullSupport; const vscode_languageserver_1 = __nccwpck_require__(4681); const runner_1 = __nccwpck_require__(8605); function registerDiagnosticsPushSupport(documents, connection, runtime, validate) { const pendingValidationRequests = {}; const validationDelayMs = 500; const disposables = []; // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent(change => { triggerValidation(change.document); }, undefined, disposables); // a document has closed: clear all diagnostics documents.onDidClose(event => { cleanPendingValidation(event.document); connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] }); }, undefined, disposables); function cleanPendingValidation(textDocument) { const request = pendingValidationRequests[textDocument.uri]; if (request) { request.dispose(); delete pendingValidationRequests[textDocument.uri]; } } function triggerValidation(textDocument) { cleanPendingValidation(textDocument); const request = pendingValidationRequests[textDocument.uri] = runtime.timer.setTimeout(async () => { if (request === pendingValidationRequests[textDocument.uri]) { try { const diagnostics = await validate(textDocument); if (request === pendingValidationRequests[textDocument.uri]) { connection.sendDiagnostics({ uri: textDocument.uri, diagnostics }); } delete pendingValidationRequests[textDocument.uri]; } catch (e) { connection.console.error((0, runner_1.formatError)(`Error while validating ${textDocument.uri}`, e)); } } }, validationDelayMs); } return { requestRefresh: () => { documents.all().forEach(triggerValidation); }, dispose: () => { disposables.forEach(d => d.dispose()); disposables.length = 0; const keys = Object.keys(pendingValidationRequests); for (const key of keys) { pendingValidationRequests[key].dispose(); delete pendingValidationRequests[key]; } } }; } function registerDiagnosticsPullSupport(documents, connection, runtime, validate) { function newDocumentDiagnosticReport(diagnostics) { return { kind: vscode_languageserver_1.DocumentDiagnosticReportKind.Full, items: diagnostics }; } const registration = connection.languages.diagnostics.on(async (params, token) => { return (0, runner_1.runSafeAsync)(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { return newDocumentDiagnosticReport(await validate(document)); } return newDocumentDiagnosticReport([]); }, newDocumentDiagnosticReport([]), `Error while computing diagnostics for ${params.textDocument.uri}`, token); }); function requestRefresh() { connection.languages.diagnostics.refresh(); } return { requestRefresh, dispose: () => { registration.dispose(); } }; } /***/ }), /***/ 9491: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 2081: /***/ ((module) => { "use strict"; module.exports = require("child_process"); /***/ }), /***/ 6113: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 2361: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 7147: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 3292: /***/ ((module) => { "use strict"; module.exports = require("fs/promises"); /***/ }), /***/ 3685: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 5687: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 1808: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 7261: /***/ ((module) => { "use strict"; module.exports = require("node:util"); /***/ }), /***/ 2037: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 1017: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 4404: /***/ ((module) => { "use strict"; module.exports = require("tls"); /***/ }), /***/ 7310: /***/ ((module) => { "use strict"; module.exports = require("url"); /***/ }), /***/ 3837: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 9796: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_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 /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __nccwpck_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __nccwpck_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be in strict mode. (() => { "use strict"; var exports = __webpack_exports__; Object.defineProperty(exports, "__esModule", ({ value: true })); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const l10n = __nccwpck_require__(5697); async function setupMain() { const l10nLog = []; const i10lLocation = process.env['VSCODE_L10N_BUNDLE_LOCATION']; if (i10lLocation) { try { await l10n.config({ uri: i10lLocation }); l10nLog.push(`l10n: Configured to ${i10lLocation.toString()}`); } catch (e) { l10nLog.push(`l10n: Problems loading ${i10lLocation.toString()} : ${e}`); } } await Promise.resolve().then(() => __nccwpck_require__(6092)); l10nLog.forEach(console.log); } setupMain(); })(); module.exports = __webpack_exports__; /******/ })() ;