My dotfiles
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

9455 рядки
367 KiB

  1. (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
  2. /******/ // The module cache
  3. /******/ var installedModules = {};
  4. /******/
  5. /******/ // The require function
  6. /******/ function __webpack_require__(moduleId) {
  7. /******/
  8. /******/ // Check if module is in cache
  9. /******/ if(installedModules[moduleId]) {
  10. /******/ return installedModules[moduleId].exports;
  11. /******/ }
  12. /******/ // Create a new module (and put it into the cache)
  13. /******/ var module = installedModules[moduleId] = {
  14. /******/ i: moduleId,
  15. /******/ l: false,
  16. /******/ exports: {}
  17. /******/ };
  18. /******/
  19. /******/ // Execute the module function
  20. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  21. /******/
  22. /******/ // Flag the module as loaded
  23. /******/ module.l = true;
  24. /******/
  25. /******/ // Return the exports of the module
  26. /******/ return module.exports;
  27. /******/ }
  28. /******/
  29. /******/
  30. /******/ // expose the modules object (__webpack_modules__)
  31. /******/ __webpack_require__.m = modules;
  32. /******/
  33. /******/ // expose the module cache
  34. /******/ __webpack_require__.c = installedModules;
  35. /******/
  36. /******/ // define getter function for harmony exports
  37. /******/ __webpack_require__.d = function(exports, name, getter) {
  38. /******/ if(!__webpack_require__.o(exports, name)) {
  39. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  40. /******/ }
  41. /******/ };
  42. /******/
  43. /******/ // define __esModule on exports
  44. /******/ __webpack_require__.r = function(exports) {
  45. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  46. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  47. /******/ }
  48. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  49. /******/ };
  50. /******/
  51. /******/ // create a fake namespace object
  52. /******/ // mode & 1: value is a module id, require it
  53. /******/ // mode & 2: merge all properties of value into the ns
  54. /******/ // mode & 4: return value when already ns object
  55. /******/ // mode & 8|1: behave like require
  56. /******/ __webpack_require__.t = function(value, mode) {
  57. /******/ if(mode & 1) value = __webpack_require__(value);
  58. /******/ if(mode & 8) return value;
  59. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  60. /******/ var ns = Object.create(null);
  61. /******/ __webpack_require__.r(ns);
  62. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  63. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  64. /******/ return ns;
  65. /******/ };
  66. /******/
  67. /******/ // getDefaultExport function for compatibility with non-harmony modules
  68. /******/ __webpack_require__.n = function(module) {
  69. /******/ var getter = module && module.__esModule ?
  70. /******/ function getDefault() { return module['default']; } :
  71. /******/ function getModuleExports() { return module; };
  72. /******/ __webpack_require__.d(getter, 'a', getter);
  73. /******/ return getter;
  74. /******/ };
  75. /******/
  76. /******/ // Object.prototype.hasOwnProperty.call
  77. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  78. /******/
  79. /******/ // __webpack_public_path__
  80. /******/ __webpack_require__.p = "";
  81. /******/
  82. /******/
  83. /******/ // Load entry module and return exports
  84. /******/ return __webpack_require__(__webpack_require__.s = 0);
  85. /******/ })
  86. /************************************************************************/
  87. /******/ ([
  88. /* 0 */
  89. /***/ (function(module, exports, __webpack_require__) {
  90. "use strict";
  91. var __importDefault = (this && this.__importDefault) || function (mod) {
  92. return (mod && mod.__esModule) ? mod : { "default": mod };
  93. };
  94. Object.defineProperty(exports, "__esModule", { value: true });
  95. /******************************************************************
  96. MIT License http://www.opensource.org/licenses/mit-license.php
  97. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  98. *******************************************************************/
  99. const coc_nvim_1 = __webpack_require__(1);
  100. const os_1 = __importDefault(__webpack_require__(2));
  101. const fs_1 = __importDefault(__webpack_require__(3));
  102. const path_1 = __importDefault(__webpack_require__(4));
  103. const util_1 = __importDefault(__webpack_require__(5));
  104. const vscode_languageserver_types_1 = __webpack_require__(6);
  105. const snippet_1 = __importDefault(__webpack_require__(7));
  106. const provider_1 = __webpack_require__(35);
  107. const snipmateProvider_1 = __webpack_require__(39);
  108. const textmateProvider_1 = __webpack_require__(43);
  109. const ultisnipsProvider_1 = __webpack_require__(49);
  110. const debounce_1 = __importDefault(__webpack_require__(52));
  111. const languages_1 = __importDefault(__webpack_require__(53));
  112. const documentation = `# A valid snippet should starts with:
  113. #
  114. # snippet trigger_word [ "description" [ options ] ]
  115. #
  116. # and end with:
  117. #
  118. # endsnippet
  119. #
  120. # Snippet options:
  121. #
  122. # b - Beginning of line.
  123. # i - In-word expansion.
  124. # w - Word boundary.
  125. # r - Regular expression
  126. # e - Custom context snippet
  127. # A - Snippet will be triggered automatically, when condition matches.
  128. #
  129. # Basic example:
  130. #
  131. # snippet emitter "emitter properties" b
  132. # private readonly $\{1} = new Emitter<$2>()
  133. # public readonly $\{1/^_(.*)/$1/}: Event<$2> = this.$1.event
  134. # endsnippet
  135. #
  136. # Online reference: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt
  137. `;
  138. async function activate(context) {
  139. let { subscriptions } = context;
  140. const { nvim } = coc_nvim_1.workspace;
  141. const configuration = coc_nvim_1.workspace.getConfiguration('snippets');
  142. const filetypeExtends = configuration.get('extends', {});
  143. const manager = new provider_1.ProviderManager();
  144. const trace = configuration.get('trace', 'error');
  145. let mru = coc_nvim_1.workspace.createMru('snippets-mru');
  146. const channel = coc_nvim_1.workspace.createOutputChannel('snippets');
  147. let snippetsDir = configuration.get('userSnippetsDirectory');
  148. if (snippetsDir) {
  149. snippetsDir = snippetsDir.replace(/^~/, os_1.default.homedir());
  150. if (snippetsDir.indexOf('$') !== -1) {
  151. snippetsDir = snippetsDir.replace(/\$(\w+)/g, (match, p1) => {
  152. var _a;
  153. return (_a = process.env[p1]) !== null && _a !== void 0 ? _a : match;
  154. });
  155. }
  156. if (!path_1.default.isAbsolute(snippetsDir)) {
  157. coc_nvim_1.workspace.showMessage(`snippets.userSnippetsDirectory => ${snippetsDir} should be absolute path`, 'warning');
  158. snippetsDir = null;
  159. }
  160. }
  161. if (!snippetsDir)
  162. snippetsDir = path_1.default.join(path_1.default.dirname(coc_nvim_1.workspace.env.extensionRoot), 'ultisnips');
  163. if (!fs_1.default.existsSync(snippetsDir)) {
  164. await util_1.default.promisify(fs_1.default.mkdir)(snippetsDir);
  165. }
  166. coc_nvim_1.events.on('CompleteDone', async (item) => {
  167. if (item.user_data && item.user_data.indexOf('snippets') !== -1) {
  168. await mru.add(item.word);
  169. }
  170. }, null, subscriptions);
  171. coc_nvim_1.workspace.onDidOpenTextDocument(async (document) => {
  172. if (document.uri.endsWith('.snippets')) {
  173. let doc = coc_nvim_1.workspace.getDocument(document.uri);
  174. if (!doc)
  175. return;
  176. let { buffer } = doc;
  177. await buffer.setOption('filetype', 'snippets');
  178. }
  179. }, null, subscriptions);
  180. if (configuration.get('ultisnips.enable', true)) {
  181. let config = configuration.get('ultisnips', {});
  182. let c = Object.assign({}, config, {
  183. extends: Object.assign({}, filetypeExtends)
  184. });
  185. c.directories = c.directories ? c.directories.slice() : [];
  186. if (c.directories.indexOf(snippetsDir) == -1) {
  187. c.directories.push(snippetsDir);
  188. }
  189. let provider = new ultisnipsProvider_1.UltiSnippetsProvider(channel, trace, c, context);
  190. manager.regist(provider, 'ultisnips');
  191. subscriptions.push(provider);
  192. // add rtp if ultisnips not found
  193. nvim.getOption('runtimepath').then(async (rtp) => {
  194. let paths = rtp.split(',');
  195. let idx = paths.findIndex(s => /^ultisnips$/i.test(path_1.default.basename(s)));
  196. if (idx !== -1)
  197. return;
  198. let directory = path_1.default.resolve(__dirname, '..');
  199. nvim.command('autocmd BufNewFile,BufRead *.snippets setf snippets', true);
  200. nvim.command(`execute 'noa set rtp+='.fnameescape('${directory.replace(/'/g, "''")}')`, true);
  201. coc_nvim_1.workspace.documents.forEach(doc => {
  202. if (doc.uri.endsWith('.snippets')) {
  203. doc.buffer.setOption('filetype', 'snippets', true);
  204. }
  205. });
  206. }, _e => {
  207. // noop
  208. });
  209. }
  210. let config = {
  211. loadFromExtensions: configuration.get('loadFromExtensions', true),
  212. snippetsRoots: configuration.get('textmateSnippetsRoots', []),
  213. extends: Object.assign({}, filetypeExtends)
  214. };
  215. let provider = new textmateProvider_1.TextmateProvider(channel, trace, config);
  216. manager.regist(provider, 'snippets');
  217. if (configuration.get('snipmate.enable', true)) {
  218. let config = {
  219. author: configuration.get('snipmate.author', ''),
  220. extends: Object.assign({}, filetypeExtends)
  221. };
  222. let provider = new snipmateProvider_1.SnipmateProvider(channel, trace, config);
  223. manager.regist(provider, 'snipmate');
  224. }
  225. if (configuration.get('autoTrigger', true)) {
  226. let insertTs;
  227. coc_nvim_1.events.on('InsertCharPre', () => {
  228. insertTs = Date.now();
  229. }, null, subscriptions);
  230. coc_nvim_1.events.on(['TextChanged', 'TextChangedP', 'TextChangedI'], debounce_1.default(async () => {
  231. if (!coc_nvim_1.workspace.insertMode)
  232. return;
  233. if (!insertTs || Date.now() - insertTs > 200)
  234. return;
  235. let curr = insertTs;
  236. let edits = await manager.getTriggerSnippets(true);
  237. if (insertTs != curr || edits.length == 0)
  238. return;
  239. if (edits.length > 1) {
  240. channel.appendLine(`Multiple snippet found for auto trigger: ${edits.map(s => s.prefix).join(', ')}`);
  241. coc_nvim_1.workspace.showMessage('Multiple snippet found for auto trigger, check output by :CocCommand workspace.showOutput', 'warning');
  242. }
  243. await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
  244. await mru.add(edits[0].prefix);
  245. }, 100), null, subscriptions);
  246. }
  247. let statusItem;
  248. if (configuration.get('enableStatusItem', true)) {
  249. statusItem = coc_nvim_1.workspace.createStatusBarItem(90, { progress: true });
  250. statusItem.text = 'loading snippets';
  251. statusItem.show();
  252. }
  253. manager.init().then(() => {
  254. statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
  255. }, e => {
  256. statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
  257. coc_nvim_1.workspace.showMessage(`Error on load snippets: ${e.message}`, 'error');
  258. });
  259. if (manager.hasProvider) {
  260. let disposable = coc_nvim_1.languages.registerCompletionItemProvider('snippets', 'S', null, manager, configuration.get('triggerCharacters', []), configuration.get('priority', 90));
  261. subscriptions.push(disposable);
  262. }
  263. async function fallback() {
  264. await nvim.call('coc#start', [{ source: 'snippets' }]);
  265. }
  266. async function doExpand() {
  267. let edits = await manager.getTriggerSnippets();
  268. if (edits.length == 0)
  269. return false;
  270. if (edits.length == 1) {
  271. await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
  272. await mru.add(edits[0].prefix);
  273. }
  274. else {
  275. let idx = await coc_nvim_1.workspace.showQuickpick(edits.map(e => e.description || e.prefix), 'choose snippet:');
  276. if (idx == -1)
  277. return;
  278. await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[idx]);
  279. await mru.add(edits[idx].prefix);
  280. }
  281. return true;
  282. }
  283. if (configuration.get("convertToSnippetsAction")) {
  284. subscriptions.push(coc_nvim_1.languages.registerCodeActionProvider([{ scheme: 'file' }, { scheme: 'untitled' }], {
  285. provideCodeActions: async (document, range, context) => {
  286. if (context.only && !context.only.includes(vscode_languageserver_types_1.CodeActionKind.Source))
  287. return;
  288. let text = document.getText(range);
  289. if (text.endsWith('\n'))
  290. text = text.replace(/\n$/, '');
  291. let action = vscode_languageserver_types_1.CodeAction.create('Convert to snippet', {
  292. command: 'snippets.editSnippets',
  293. title: 'Convert to snippet',
  294. arguments: [text]
  295. });
  296. return [action];
  297. }
  298. }, 'snippets', [vscode_languageserver_types_1.CodeActionKind.Source]));
  299. }
  300. subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.editSnippets', async (text) => {
  301. let buf = await nvim.buffer;
  302. let doc = coc_nvim_1.workspace.getDocument(buf.id);
  303. if (!doc) {
  304. coc_nvim_1.workspace.showMessage('Document not found', 'error');
  305. return;
  306. }
  307. let file = path_1.default.join(snippetsDir, `${doc.filetype}.snippets`);
  308. if (!fs_1.default.existsSync(file)) {
  309. await util_1.default.promisify(fs_1.default.writeFile)(file, documentation, 'utf8');
  310. }
  311. let uri = coc_nvim_1.Uri.file(file).toString();
  312. await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
  313. if (text) {
  314. await nvim.command('normal! G');
  315. await nvim.command('normal! 2o');
  316. let position = await coc_nvim_1.workspace.getCursorPosition();
  317. let indent = text.match(/^\s*/)[0];
  318. text = text.split(/\r?\n/).map(s => s.startsWith(indent) ? s.slice(indent.length) : s).join('\n');
  319. let escaped = text.replace(/([$}\]])/g, '\\$1');
  320. // tslint:disable-next-line: no-invalid-template-strings
  321. let snippet = 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n' + escaped + '\nendsnippet';
  322. let edit = vscode_languageserver_types_1.TextEdit.insert(position, snippet);
  323. await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edit);
  324. }
  325. }));
  326. subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.openSnippetFiles', async () => {
  327. let buf = await nvim.buffer;
  328. let doc = coc_nvim_1.workspace.getDocument(buf.id);
  329. if (!doc) {
  330. coc_nvim_1.workspace.showMessage('Document not found', 'error');
  331. return;
  332. }
  333. let files = await manager.getSnippetFiles(doc.filetype);
  334. if (!files.length) {
  335. coc_nvim_1.workspace.showMessage('No related snippet file found', 'warning');
  336. return;
  337. }
  338. let idx = await coc_nvim_1.workspace.showQuickpick(files, 'choose snippet file:');
  339. if (idx == -1)
  340. return;
  341. let uri = coc_nvim_1.Uri.file(files[idx]).toString();
  342. await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
  343. }));
  344. subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand', async () => {
  345. let expanded = await doExpand();
  346. if (!expanded)
  347. await fallback();
  348. }, { silent: true, sync: true, cancel: true }));
  349. subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand-jump', async () => {
  350. let expanded = await doExpand();
  351. if (!expanded) {
  352. let bufnr = await nvim.call('bufnr', '%');
  353. let session = coc_nvim_1.snippetManager.getSession(bufnr);
  354. if (session && session.isActive) {
  355. await nvim.call('coc#_cancel', []);
  356. await coc_nvim_1.snippetManager.nextPlaceholder();
  357. return;
  358. }
  359. await fallback();
  360. }
  361. }, { silent: true, sync: true, cancel: true }));
  362. subscriptions.push(coc_nvim_1.workspace.registerKeymap(['v'], 'snippets-select', async () => {
  363. let doc = await coc_nvim_1.workspace.document;
  364. if (!doc)
  365. return;
  366. let mode = await nvim.call('visualmode');
  367. if (['v', 'V'].indexOf(mode) == -1) {
  368. coc_nvim_1.workspace.showMessage(`visual mode ${mode} not supported`, 'warning');
  369. return;
  370. }
  371. await nvim.command('normal! `<');
  372. let start = await coc_nvim_1.workspace.getCursorPosition();
  373. await nvim.command('normal! `>');
  374. let end = await coc_nvim_1.workspace.getCursorPosition();
  375. end = vscode_languageserver_types_1.Position.create(end.line, end.character + 1);
  376. let range = vscode_languageserver_types_1.Range.create(start, end);
  377. let text = doc.textDocument.getText(range);
  378. await nvim.call('feedkeys', ['i', 'in']);
  379. if (mode == 'v') {
  380. await doc.applyEdits(coc_nvim_1.workspace.nvim, [{ range, newText: '' }]);
  381. }
  382. else {
  383. // keep indent
  384. let currline = doc.getline(start.line);
  385. let indent = currline.match(/^\s*/)[0];
  386. let lines = text.split(/\r?\n/);
  387. lines = lines.map(s => s.startsWith(indent) ? s.slice(indent.length) : s);
  388. text = lines.join('\n');
  389. range = vscode_languageserver_types_1.Range.create(vscode_languageserver_types_1.Position.create(start.line, indent.length), end);
  390. await doc.applyEdits(coc_nvim_1.workspace.nvim, [{ range, newText: '' }]);
  391. }
  392. await nvim.setVar('coc_selected_text', text);
  393. await coc_nvim_1.workspace.moveTo(range.start);
  394. }, { silent: true, sync: false, cancel: true }));
  395. let languageProvider = new languages_1.default(channel, trace);
  396. subscriptions.push(coc_nvim_1.languages.registerCompletionItemProvider('snippets-source', 'S', ['snippets'], languageProvider, ['$'], configuration.get('priority', 90)));
  397. subscriptions.push(statusItem);
  398. subscriptions.push(channel);
  399. subscriptions.push(coc_nvim_1.listManager.registerList(new snippet_1.default(coc_nvim_1.workspace.nvim, manager, mru)));
  400. return {
  401. expandable: async () => {
  402. let edits;
  403. try {
  404. edits = await manager.getTriggerSnippets();
  405. }
  406. catch (e) {
  407. channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on getTriggerSnippets: ${e}`);
  408. }
  409. return edits && edits.length > 0;
  410. }
  411. };
  412. }
  413. exports.activate = activate;
  414. /***/ }),
  415. /* 1 */
  416. /***/ (function(module, exports) {
  417. module.exports = require("coc.nvim");
  418. /***/ }),
  419. /* 2 */
  420. /***/ (function(module, exports) {
  421. module.exports = require("os");
  422. /***/ }),
  423. /* 3 */
  424. /***/ (function(module, exports) {
  425. module.exports = require("fs");
  426. /***/ }),
  427. /* 4 */
  428. /***/ (function(module, exports) {
  429. module.exports = require("path");
  430. /***/ }),
  431. /* 5 */
  432. /***/ (function(module, exports) {
  433. module.exports = require("util");
  434. /***/ }),
  435. /* 6 */
  436. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  437. "use strict";
  438. __webpack_require__.r(__webpack_exports__);
  439. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
  440. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
  441. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
  442. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
  443. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
  444. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
  445. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
  446. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
  447. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
  448. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
  449. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
  450. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
  451. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
  452. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
  453. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
  454. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
  455. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
  456. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
  457. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
  458. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
  459. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
  460. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
  461. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
  462. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
  463. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
  464. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
  465. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
  466. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
  467. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
  468. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
  469. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
  470. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
  471. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
  472. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
  473. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
  474. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
  475. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
  476. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
  477. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
  478. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
  479. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
  480. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
  481. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
  482. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
  483. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
  484. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
  485. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
  486. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
  487. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
  488. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
  489. /* --------------------------------------------------------------------------------------------
  490. * Copyright (c) Microsoft Corporation. All rights reserved.
  491. * Licensed under the MIT License. See License.txt in the project root for license information.
  492. * ------------------------------------------------------------------------------------------ */
  493. /**
  494. * The Position namespace provides helper functions to work with
  495. * [Position](#Position) literals.
  496. */
  497. var Position;
  498. (function (Position) {
  499. /**
  500. * Creates a new Position literal from the given line and character.
  501. * @param line The position's line.
  502. * @param character The position's character.
  503. */
  504. function create(line, character) {
  505. return { line: line, character: character };
  506. }
  507. Position.create = create;
  508. /**
  509. * Checks whether the given liternal conforms to the [Position](#Position) interface.
  510. */
  511. function is(value) {
  512. var candidate = value;
  513. return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
  514. }
  515. Position.is = is;
  516. })(Position || (Position = {}));
  517. /**
  518. * The Range namespace provides helper functions to work with
  519. * [Range](#Range) literals.
  520. */
  521. var Range;
  522. (function (Range) {
  523. function create(one, two, three, four) {
  524. if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
  525. return { start: Position.create(one, two), end: Position.create(three, four) };
  526. }
  527. else if (Position.is(one) && Position.is(two)) {
  528. return { start: one, end: two };
  529. }
  530. else {
  531. throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
  532. }
  533. }
  534. Range.create = create;
  535. /**
  536. * Checks whether the given literal conforms to the [Range](#Range) interface.
  537. */
  538. function is(value) {
  539. var candidate = value;
  540. return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  541. }
  542. Range.is = is;
  543. })(Range || (Range = {}));
  544. /**
  545. * The Location namespace provides helper functions to work with
  546. * [Location](#Location) literals.
  547. */
  548. var Location;
  549. (function (Location) {
  550. /**
  551. * Creates a Location literal.
  552. * @param uri The location's uri.
  553. * @param range The location's range.
  554. */
  555. function create(uri, range) {
  556. return { uri: uri, range: range };
  557. }
  558. Location.create = create;
  559. /**
  560. * Checks whether the given literal conforms to the [Location](#Location) interface.
  561. */
  562. function is(value) {
  563. var candidate = value;
  564. return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  565. }
  566. Location.is = is;
  567. })(Location || (Location = {}));
  568. /**
  569. * The LocationLink namespace provides helper functions to work with
  570. * [LocationLink](#LocationLink) literals.
  571. */
  572. var LocationLink;
  573. (function (LocationLink) {
  574. /**
  575. * Creates a LocationLink literal.
  576. * @param targetUri The definition's uri.
  577. * @param targetRange The full range of the definition.
  578. * @param targetSelectionRange The span of the symbol definition at the target.
  579. * @param originSelectionRange The span of the symbol being defined in the originating source file.
  580. */
  581. function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
  582. return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
  583. }
  584. LocationLink.create = create;
  585. /**
  586. * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
  587. */
  588. function is(value) {
  589. var candidate = value;
  590. return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
  591. && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
  592. && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  593. }
  594. LocationLink.is = is;
  595. })(LocationLink || (LocationLink = {}));
  596. /**
  597. * The Color namespace provides helper functions to work with
  598. * [Color](#Color) literals.
  599. */
  600. var Color;
  601. (function (Color) {
  602. /**
  603. * Creates a new Color literal.
  604. */
  605. function create(red, green, blue, alpha) {
  606. return {
  607. red: red,
  608. green: green,
  609. blue: blue,
  610. alpha: alpha,
  611. };
  612. }
  613. Color.create = create;
  614. /**
  615. * Checks whether the given literal conforms to the [Color](#Color) interface.
  616. */
  617. function is(value) {
  618. var candidate = value;
  619. return Is.number(candidate.red)
  620. && Is.number(candidate.green)
  621. && Is.number(candidate.blue)
  622. && Is.number(candidate.alpha);
  623. }
  624. Color.is = is;
  625. })(Color || (Color = {}));
  626. /**
  627. * The ColorInformation namespace provides helper functions to work with
  628. * [ColorInformation](#ColorInformation) literals.
  629. */
  630. var ColorInformation;
  631. (function (ColorInformation) {
  632. /**
  633. * Creates a new ColorInformation literal.
  634. */
  635. function create(range, color) {
  636. return {
  637. range: range,
  638. color: color,
  639. };
  640. }
  641. ColorInformation.create = create;
  642. /**
  643. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  644. */
  645. function is(value) {
  646. var candidate = value;
  647. return Range.is(candidate.range) && Color.is(candidate.color);
  648. }
  649. ColorInformation.is = is;
  650. })(ColorInformation || (ColorInformation = {}));
  651. /**
  652. * The Color namespace provides helper functions to work with
  653. * [ColorPresentation](#ColorPresentation) literals.
  654. */
  655. var ColorPresentation;
  656. (function (ColorPresentation) {
  657. /**
  658. * Creates a new ColorInformation literal.
  659. */
  660. function create(label, textEdit, additionalTextEdits) {
  661. return {
  662. label: label,
  663. textEdit: textEdit,
  664. additionalTextEdits: additionalTextEdits,
  665. };
  666. }
  667. ColorPresentation.create = create;
  668. /**
  669. * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
  670. */
  671. function is(value) {
  672. var candidate = value;
  673. return Is.string(candidate.label)
  674. && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
  675. && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  676. }
  677. ColorPresentation.is = is;
  678. })(ColorPresentation || (ColorPresentation = {}));
  679. /**
  680. * Enum of known range kinds
  681. */
  682. var FoldingRangeKind;
  683. (function (FoldingRangeKind) {
  684. /**
  685. * Folding range for a comment
  686. */
  687. FoldingRangeKind["Comment"] = "comment";
  688. /**
  689. * Folding range for a imports or includes
  690. */
  691. FoldingRangeKind["Imports"] = "imports";
  692. /**
  693. * Folding range for a region (e.g. `#region`)
  694. */
  695. FoldingRangeKind["Region"] = "region";
  696. })(FoldingRangeKind || (FoldingRangeKind = {}));
  697. /**
  698. * The folding range namespace provides helper functions to work with
  699. * [FoldingRange](#FoldingRange) literals.
  700. */
  701. var FoldingRange;
  702. (function (FoldingRange) {
  703. /**
  704. * Creates a new FoldingRange literal.
  705. */
  706. function create(startLine, endLine, startCharacter, endCharacter, kind) {
  707. var result = {
  708. startLine: startLine,
  709. endLine: endLine
  710. };
  711. if (Is.defined(startCharacter)) {
  712. result.startCharacter = startCharacter;
  713. }
  714. if (Is.defined(endCharacter)) {
  715. result.endCharacter = endCharacter;
  716. }
  717. if (Is.defined(kind)) {
  718. result.kind = kind;
  719. }
  720. return result;
  721. }
  722. FoldingRange.create = create;
  723. /**
  724. * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
  725. */
  726. function is(value) {
  727. var candidate = value;
  728. return Is.number(candidate.startLine) && Is.number(candidate.startLine)
  729. && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
  730. && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
  731. && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  732. }
  733. FoldingRange.is = is;
  734. })(FoldingRange || (FoldingRange = {}));
  735. /**
  736. * The DiagnosticRelatedInformation namespace provides helper functions to work with
  737. * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
  738. */
  739. var DiagnosticRelatedInformation;
  740. (function (DiagnosticRelatedInformation) {
  741. /**
  742. * Creates a new DiagnosticRelatedInformation literal.
  743. */
  744. function create(location, message) {
  745. return {
  746. location: location,
  747. message: message
  748. };
  749. }
  750. DiagnosticRelatedInformation.create = create;
  751. /**
  752. * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
  753. */
  754. function is(value) {
  755. var candidate = value;
  756. return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  757. }
  758. DiagnosticRelatedInformation.is = is;
  759. })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
  760. /**
  761. * The diagnostic's severity.
  762. */
  763. var DiagnosticSeverity;
  764. (function (DiagnosticSeverity) {
  765. /**
  766. * Reports an error.
  767. */
  768. DiagnosticSeverity.Error = 1;
  769. /**
  770. * Reports a warning.
  771. */
  772. DiagnosticSeverity.Warning = 2;
  773. /**
  774. * Reports an information.
  775. */
  776. DiagnosticSeverity.Information = 3;
  777. /**
  778. * Reports a hint.
  779. */
  780. DiagnosticSeverity.Hint = 4;
  781. })(DiagnosticSeverity || (DiagnosticSeverity = {}));
  782. /**
  783. * The diagnostic tags.
  784. *
  785. * @since 3.15.0
  786. */
  787. var DiagnosticTag;
  788. (function (DiagnosticTag) {
  789. /**
  790. * Unused or unnecessary code.
  791. *
  792. * Clients are allowed to render diagnostics with this tag faded out instead of having
  793. * an error squiggle.
  794. */
  795. DiagnosticTag.Unnecessary = 1;
  796. /**
  797. * Deprecated or obsolete code.
  798. *
  799. * Clients are allowed to rendered diagnostics with this tag strike through.
  800. */
  801. DiagnosticTag.Deprecated = 2;
  802. })(DiagnosticTag || (DiagnosticTag = {}));
  803. /**
  804. * The Diagnostic namespace provides helper functions to work with
  805. * [Diagnostic](#Diagnostic) literals.
  806. */
  807. var Diagnostic;
  808. (function (Diagnostic) {
  809. /**
  810. * Creates a new Diagnostic literal.
  811. */
  812. function create(range, message, severity, code, source, relatedInformation) {
  813. var result = { range: range, message: message };
  814. if (Is.defined(severity)) {
  815. result.severity = severity;
  816. }
  817. if (Is.defined(code)) {
  818. result.code = code;
  819. }
  820. if (Is.defined(source)) {
  821. result.source = source;
  822. }
  823. if (Is.defined(relatedInformation)) {
  824. result.relatedInformation = relatedInformation;
  825. }
  826. return result;
  827. }
  828. Diagnostic.create = create;
  829. /**
  830. * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
  831. */
  832. function is(value) {
  833. var candidate = value;
  834. return Is.defined(candidate)
  835. && Range.is(candidate.range)
  836. && Is.string(candidate.message)
  837. && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
  838. && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
  839. && (Is.string(candidate.source) || Is.undefined(candidate.source))
  840. && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  841. }
  842. Diagnostic.is = is;
  843. })(Diagnostic || (Diagnostic = {}));
  844. /**
  845. * The Command namespace provides helper functions to work with
  846. * [Command](#Command) literals.
  847. */
  848. var Command;
  849. (function (Command) {
  850. /**
  851. * Creates a new Command literal.
  852. */
  853. function create(title, command) {
  854. var args = [];
  855. for (var _i = 2; _i < arguments.length; _i++) {
  856. args[_i - 2] = arguments[_i];
  857. }
  858. var result = { title: title, command: command };
  859. if (Is.defined(args) && args.length > 0) {
  860. result.arguments = args;
  861. }
  862. return result;
  863. }
  864. Command.create = create;
  865. /**
  866. * Checks whether the given literal conforms to the [Command](#Command) interface.
  867. */
  868. function is(value) {
  869. var candidate = value;
  870. return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
  871. }
  872. Command.is = is;
  873. })(Command || (Command = {}));
  874. /**
  875. * The TextEdit namespace provides helper function to create replace,
  876. * insert and delete edits more easily.
  877. */
  878. var TextEdit;
  879. (function (TextEdit) {
  880. /**
  881. * Creates a replace text edit.
  882. * @param range The range of text to be replaced.
  883. * @param newText The new text.
  884. */
  885. function replace(range, newText) {
  886. return { range: range, newText: newText };
  887. }
  888. TextEdit.replace = replace;
  889. /**
  890. * Creates a insert text edit.
  891. * @param position The position to insert the text at.
  892. * @param newText The text to be inserted.
  893. */
  894. function insert(position, newText) {
  895. return { range: { start: position, end: position }, newText: newText };
  896. }
  897. TextEdit.insert = insert;
  898. /**
  899. * Creates a delete text edit.
  900. * @param range The range of text to be deleted.
  901. */
  902. function del(range) {
  903. return { range: range, newText: '' };
  904. }
  905. TextEdit.del = del;
  906. function is(value) {
  907. var candidate = value;
  908. return Is.objectLiteral(candidate)
  909. && Is.string(candidate.newText)
  910. && Range.is(candidate.range);
  911. }
  912. TextEdit.is = is;
  913. })(TextEdit || (TextEdit = {}));
  914. /**
  915. * The TextDocumentEdit namespace provides helper function to create
  916. * an edit that manipulates a text document.
  917. */
  918. var TextDocumentEdit;
  919. (function (TextDocumentEdit) {
  920. /**
  921. * Creates a new `TextDocumentEdit`
  922. */
  923. function create(textDocument, edits) {
  924. return { textDocument: textDocument, edits: edits };
  925. }
  926. TextDocumentEdit.create = create;
  927. function is(value) {
  928. var candidate = value;
  929. return Is.defined(candidate)
  930. && VersionedTextDocumentIdentifier.is(candidate.textDocument)
  931. && Array.isArray(candidate.edits);
  932. }
  933. TextDocumentEdit.is = is;
  934. })(TextDocumentEdit || (TextDocumentEdit = {}));
  935. var CreateFile;
  936. (function (CreateFile) {
  937. function create(uri, options) {
  938. var result = {
  939. kind: 'create',
  940. uri: uri
  941. };
  942. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  943. result.options = options;
  944. }
  945. return result;
  946. }
  947. CreateFile.create = create;
  948. function is(value) {
  949. var candidate = value;
  950. return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
  951. (candidate.options === void 0 ||
  952. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  953. }
  954. CreateFile.is = is;
  955. })(CreateFile || (CreateFile = {}));
  956. var RenameFile;
  957. (function (RenameFile) {
  958. function create(oldUri, newUri, options) {
  959. var result = {
  960. kind: 'rename',
  961. oldUri: oldUri,
  962. newUri: newUri
  963. };
  964. if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
  965. result.options = options;
  966. }
  967. return result;
  968. }
  969. RenameFile.create = create;
  970. function is(value) {
  971. var candidate = value;
  972. return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
  973. (candidate.options === void 0 ||
  974. ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
  975. }
  976. RenameFile.is = is;
  977. })(RenameFile || (RenameFile = {}));
  978. var DeleteFile;
  979. (function (DeleteFile) {
  980. function create(uri, options) {
  981. var result = {
  982. kind: 'delete',
  983. uri: uri
  984. };
  985. if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
  986. result.options = options;
  987. }
  988. return result;
  989. }
  990. DeleteFile.create = create;
  991. function is(value) {
  992. var candidate = value;
  993. return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
  994. (candidate.options === void 0 ||
  995. ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
  996. }
  997. DeleteFile.is = is;
  998. })(DeleteFile || (DeleteFile = {}));
  999. var WorkspaceEdit;
  1000. (function (WorkspaceEdit) {
  1001. function is(value) {
  1002. var candidate = value;
  1003. return candidate &&
  1004. (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
  1005. (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
  1006. if (Is.string(change.kind)) {
  1007. return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
  1008. }
  1009. else {
  1010. return TextDocumentEdit.is(change);
  1011. }
  1012. }));
  1013. }
  1014. WorkspaceEdit.is = is;
  1015. })(WorkspaceEdit || (WorkspaceEdit = {}));
  1016. var TextEditChangeImpl = /** @class */ (function () {
  1017. function TextEditChangeImpl(edits) {
  1018. this.edits = edits;
  1019. }
  1020. TextEditChangeImpl.prototype.insert = function (position, newText) {
  1021. this.edits.push(TextEdit.insert(position, newText));
  1022. };
  1023. TextEditChangeImpl.prototype.replace = function (range, newText) {
  1024. this.edits.push(TextEdit.replace(range, newText));
  1025. };
  1026. TextEditChangeImpl.prototype.delete = function (range) {
  1027. this.edits.push(TextEdit.del(range));
  1028. };
  1029. TextEditChangeImpl.prototype.add = function (edit) {
  1030. this.edits.push(edit);
  1031. };
  1032. TextEditChangeImpl.prototype.all = function () {
  1033. return this.edits;
  1034. };
  1035. TextEditChangeImpl.prototype.clear = function () {
  1036. this.edits.splice(0, this.edits.length);
  1037. };
  1038. return TextEditChangeImpl;
  1039. }());
  1040. /**
  1041. * A workspace change helps constructing changes to a workspace.
  1042. */
  1043. var WorkspaceChange = /** @class */ (function () {
  1044. function WorkspaceChange(workspaceEdit) {
  1045. var _this = this;
  1046. this._textEditChanges = Object.create(null);
  1047. if (workspaceEdit) {
  1048. this._workspaceEdit = workspaceEdit;
  1049. if (workspaceEdit.documentChanges) {
  1050. workspaceEdit.documentChanges.forEach(function (change) {
  1051. if (TextDocumentEdit.is(change)) {
  1052. var textEditChange = new TextEditChangeImpl(change.edits);
  1053. _this._textEditChanges[change.textDocument.uri] = textEditChange;
  1054. }
  1055. });
  1056. }
  1057. else if (workspaceEdit.changes) {
  1058. Object.keys(workspaceEdit.changes).forEach(function (key) {
  1059. var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
  1060. _this._textEditChanges[key] = textEditChange;
  1061. });
  1062. }
  1063. }
  1064. }
  1065. Object.defineProperty(WorkspaceChange.prototype, "edit", {
  1066. /**
  1067. * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
  1068. * use to be returned from a workspace edit operation like rename.
  1069. */
  1070. get: function () {
  1071. return this._workspaceEdit;
  1072. },
  1073. enumerable: true,
  1074. configurable: true
  1075. });
  1076. WorkspaceChange.prototype.getTextEditChange = function (key) {
  1077. if (VersionedTextDocumentIdentifier.is(key)) {
  1078. if (!this._workspaceEdit) {
  1079. this._workspaceEdit = {
  1080. documentChanges: []
  1081. };
  1082. }
  1083. if (!this._workspaceEdit.documentChanges) {
  1084. throw new Error('Workspace edit is not configured for document changes.');
  1085. }
  1086. var textDocument = key;
  1087. var result = this._textEditChanges[textDocument.uri];
  1088. if (!result) {
  1089. var edits = [];
  1090. var textDocumentEdit = {
  1091. textDocument: textDocument,
  1092. edits: edits
  1093. };
  1094. this._workspaceEdit.documentChanges.push(textDocumentEdit);
  1095. result = new TextEditChangeImpl(edits);
  1096. this._textEditChanges[textDocument.uri] = result;
  1097. }
  1098. return result;
  1099. }
  1100. else {
  1101. if (!this._workspaceEdit) {
  1102. this._workspaceEdit = {
  1103. changes: Object.create(null)
  1104. };
  1105. }
  1106. if (!this._workspaceEdit.changes) {
  1107. throw new Error('Workspace edit is not configured for normal text edit changes.');
  1108. }
  1109. var result = this._textEditChanges[key];
  1110. if (!result) {
  1111. var edits = [];
  1112. this._workspaceEdit.changes[key] = edits;
  1113. result = new TextEditChangeImpl(edits);
  1114. this._textEditChanges[key] = result;
  1115. }
  1116. return result;
  1117. }
  1118. };
  1119. WorkspaceChange.prototype.createFile = function (uri, options) {
  1120. this.checkDocumentChanges();
  1121. this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
  1122. };
  1123. WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
  1124. this.checkDocumentChanges();
  1125. this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
  1126. };
  1127. WorkspaceChange.prototype.deleteFile = function (uri, options) {
  1128. this.checkDocumentChanges();
  1129. this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
  1130. };
  1131. WorkspaceChange.prototype.checkDocumentChanges = function () {
  1132. if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
  1133. throw new Error('Workspace edit is not configured for document changes.');
  1134. }
  1135. };
  1136. return WorkspaceChange;
  1137. }());
  1138. /**
  1139. * The TextDocumentIdentifier namespace provides helper functions to work with
  1140. * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
  1141. */
  1142. var TextDocumentIdentifier;
  1143. (function (TextDocumentIdentifier) {
  1144. /**
  1145. * Creates a new TextDocumentIdentifier literal.
  1146. * @param uri The document's uri.
  1147. */
  1148. function create(uri) {
  1149. return { uri: uri };
  1150. }
  1151. TextDocumentIdentifier.create = create;
  1152. /**
  1153. * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
  1154. */
  1155. function is(value) {
  1156. var candidate = value;
  1157. return Is.defined(candidate) && Is.string(candidate.uri);
  1158. }
  1159. TextDocumentIdentifier.is = is;
  1160. })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
  1161. /**
  1162. * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
  1163. * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
  1164. */
  1165. var VersionedTextDocumentIdentifier;
  1166. (function (VersionedTextDocumentIdentifier) {
  1167. /**
  1168. * Creates a new VersionedTextDocumentIdentifier literal.
  1169. * @param uri The document's uri.
  1170. * @param uri The document's text.
  1171. */
  1172. function create(uri, version) {
  1173. return { uri: uri, version: version };
  1174. }
  1175. VersionedTextDocumentIdentifier.create = create;
  1176. /**
  1177. * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
  1178. */
  1179. function is(value) {
  1180. var candidate = value;
  1181. return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
  1182. }
  1183. VersionedTextDocumentIdentifier.is = is;
  1184. })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
  1185. /**
  1186. * The TextDocumentItem namespace provides helper functions to work with
  1187. * [TextDocumentItem](#TextDocumentItem) literals.
  1188. */
  1189. var TextDocumentItem;
  1190. (function (TextDocumentItem) {
  1191. /**
  1192. * Creates a new TextDocumentItem literal.
  1193. * @param uri The document's uri.
  1194. * @param languageId The document's language identifier.
  1195. * @param version The document's version number.
  1196. * @param text The document's text.
  1197. */
  1198. function create(uri, languageId, version, text) {
  1199. return { uri: uri, languageId: languageId, version: version, text: text };
  1200. }
  1201. TextDocumentItem.create = create;
  1202. /**
  1203. * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
  1204. */
  1205. function is(value) {
  1206. var candidate = value;
  1207. return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
  1208. }
  1209. TextDocumentItem.is = is;
  1210. })(TextDocumentItem || (TextDocumentItem = {}));
  1211. /**
  1212. * Describes the content type that a client supports in various
  1213. * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
  1214. *
  1215. * Please note that `MarkupKinds` must not start with a `$`. This kinds
  1216. * are reserved for internal usage.
  1217. */
  1218. var MarkupKind;
  1219. (function (MarkupKind) {
  1220. /**
  1221. * Plain text is supported as a content format
  1222. */
  1223. MarkupKind.PlainText = 'plaintext';
  1224. /**
  1225. * Markdown is supported as a content format
  1226. */
  1227. MarkupKind.Markdown = 'markdown';
  1228. })(MarkupKind || (MarkupKind = {}));
  1229. (function (MarkupKind) {
  1230. /**
  1231. * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
  1232. */
  1233. function is(value) {
  1234. var candidate = value;
  1235. return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
  1236. }
  1237. MarkupKind.is = is;
  1238. })(MarkupKind || (MarkupKind = {}));
  1239. var MarkupContent;
  1240. (function (MarkupContent) {
  1241. /**
  1242. * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
  1243. */
  1244. function is(value) {
  1245. var candidate = value;
  1246. return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  1247. }
  1248. MarkupContent.is = is;
  1249. })(MarkupContent || (MarkupContent = {}));
  1250. /**
  1251. * The kind of a completion entry.
  1252. */
  1253. var CompletionItemKind;
  1254. (function (CompletionItemKind) {
  1255. CompletionItemKind.Text = 1;
  1256. CompletionItemKind.Method = 2;
  1257. CompletionItemKind.Function = 3;
  1258. CompletionItemKind.Constructor = 4;
  1259. CompletionItemKind.Field = 5;
  1260. CompletionItemKind.Variable = 6;
  1261. CompletionItemKind.Class = 7;
  1262. CompletionItemKind.Interface = 8;
  1263. CompletionItemKind.Module = 9;
  1264. CompletionItemKind.Property = 10;
  1265. CompletionItemKind.Unit = 11;
  1266. CompletionItemKind.Value = 12;
  1267. CompletionItemKind.Enum = 13;
  1268. CompletionItemKind.Keyword = 14;
  1269. CompletionItemKind.Snippet = 15;
  1270. CompletionItemKind.Color = 16;
  1271. CompletionItemKind.File = 17;
  1272. CompletionItemKind.Reference = 18;
  1273. CompletionItemKind.Folder = 19;
  1274. CompletionItemKind.EnumMember = 20;
  1275. CompletionItemKind.Constant = 21;
  1276. CompletionItemKind.Struct = 22;
  1277. CompletionItemKind.Event = 23;
  1278. CompletionItemKind.Operator = 24;
  1279. CompletionItemKind.TypeParameter = 25;
  1280. })(CompletionItemKind || (CompletionItemKind = {}));
  1281. /**
  1282. * Defines whether the insert text in a completion item should be interpreted as
  1283. * plain text or a snippet.
  1284. */
  1285. var InsertTextFormat;
  1286. (function (InsertTextFormat) {
  1287. /**
  1288. * The primary text to be inserted is treated as a plain string.
  1289. */
  1290. InsertTextFormat.PlainText = 1;
  1291. /**
  1292. * The primary text to be inserted is treated as a snippet.
  1293. *
  1294. * A snippet can define tab stops and placeholders with `$1`, `$2`
  1295. * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
  1296. * the end of the snippet. Placeholders with equal identifiers are linked,
  1297. * that is typing in one will update others too.
  1298. *
  1299. * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
  1300. */
  1301. InsertTextFormat.Snippet = 2;
  1302. })(InsertTextFormat || (InsertTextFormat = {}));
  1303. /**
  1304. * Completion item tags are extra annotations that tweak the rendering of a completion
  1305. * item.
  1306. *
  1307. * @since 3.15.0
  1308. */
  1309. var CompletionItemTag;
  1310. (function (CompletionItemTag) {
  1311. /**
  1312. * Render a completion as obsolete, usually using a strike-out.
  1313. */
  1314. CompletionItemTag.Deprecated = 1;
  1315. })(CompletionItemTag || (CompletionItemTag = {}));
  1316. /**
  1317. * The CompletionItem namespace provides functions to deal with
  1318. * completion items.
  1319. */
  1320. var CompletionItem;
  1321. (function (CompletionItem) {
  1322. /**
  1323. * Create a completion item and seed it with a label.
  1324. * @param label The completion item's label
  1325. */
  1326. function create(label) {
  1327. return { label: label };
  1328. }
  1329. CompletionItem.create = create;
  1330. })(CompletionItem || (CompletionItem = {}));
  1331. /**
  1332. * The CompletionList namespace provides functions to deal with
  1333. * completion lists.
  1334. */
  1335. var CompletionList;
  1336. (function (CompletionList) {
  1337. /**
  1338. * Creates a new completion list.
  1339. *
  1340. * @param items The completion items.
  1341. * @param isIncomplete The list is not complete.
  1342. */
  1343. function create(items, isIncomplete) {
  1344. return { items: items ? items : [], isIncomplete: !!isIncomplete };
  1345. }
  1346. CompletionList.create = create;
  1347. })(CompletionList || (CompletionList = {}));
  1348. var MarkedString;
  1349. (function (MarkedString) {
  1350. /**
  1351. * Creates a marked string from plain text.
  1352. *
  1353. * @param plainText The plain text.
  1354. */
  1355. function fromPlainText(plainText) {
  1356. return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
  1357. }
  1358. MarkedString.fromPlainText = fromPlainText;
  1359. /**
  1360. * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
  1361. */
  1362. function is(value) {
  1363. var candidate = value;
  1364. return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
  1365. }
  1366. MarkedString.is = is;
  1367. })(MarkedString || (MarkedString = {}));
  1368. var Hover;
  1369. (function (Hover) {
  1370. /**
  1371. * Checks whether the given value conforms to the [Hover](#Hover) interface.
  1372. */
  1373. function is(value) {
  1374. var candidate = value;
  1375. return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
  1376. MarkedString.is(candidate.contents) ||
  1377. Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  1378. }
  1379. Hover.is = is;
  1380. })(Hover || (Hover = {}));
  1381. /**
  1382. * The ParameterInformation namespace provides helper functions to work with
  1383. * [ParameterInformation](#ParameterInformation) literals.
  1384. */
  1385. var ParameterInformation;
  1386. (function (ParameterInformation) {
  1387. /**
  1388. * Creates a new parameter information literal.
  1389. *
  1390. * @param label A label string.
  1391. * @param documentation A doc string.
  1392. */
  1393. function create(label, documentation) {
  1394. return documentation ? { label: label, documentation: documentation } : { label: label };
  1395. }
  1396. ParameterInformation.create = create;
  1397. })(ParameterInformation || (ParameterInformation = {}));
  1398. /**
  1399. * The SignatureInformation namespace provides helper functions to work with
  1400. * [SignatureInformation](#SignatureInformation) literals.
  1401. */
  1402. var SignatureInformation;
  1403. (function (SignatureInformation) {
  1404. function create(label, documentation) {
  1405. var parameters = [];
  1406. for (var _i = 2; _i < arguments.length; _i++) {
  1407. parameters[_i - 2] = arguments[_i];
  1408. }
  1409. var result = { label: label };
  1410. if (Is.defined(documentation)) {
  1411. result.documentation = documentation;
  1412. }
  1413. if (Is.defined(parameters)) {
  1414. result.parameters = parameters;
  1415. }
  1416. else {
  1417. result.parameters = [];
  1418. }
  1419. return result;
  1420. }
  1421. SignatureInformation.create = create;
  1422. })(SignatureInformation || (SignatureInformation = {}));
  1423. /**
  1424. * A document highlight kind.
  1425. */
  1426. var DocumentHighlightKind;
  1427. (function (DocumentHighlightKind) {
  1428. /**
  1429. * A textual occurrence.
  1430. */
  1431. DocumentHighlightKind.Text = 1;
  1432. /**
  1433. * Read-access of a symbol, like reading a variable.
  1434. */
  1435. DocumentHighlightKind.Read = 2;
  1436. /**
  1437. * Write-access of a symbol, like writing to a variable.
  1438. */
  1439. DocumentHighlightKind.Write = 3;
  1440. })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  1441. /**
  1442. * DocumentHighlight namespace to provide helper functions to work with
  1443. * [DocumentHighlight](#DocumentHighlight) literals.
  1444. */
  1445. var DocumentHighlight;
  1446. (function (DocumentHighlight) {
  1447. /**
  1448. * Create a DocumentHighlight object.
  1449. * @param range The range the highlight applies to.
  1450. */
  1451. function create(range, kind) {
  1452. var result = { range: range };
  1453. if (Is.number(kind)) {
  1454. result.kind = kind;
  1455. }
  1456. return result;
  1457. }
  1458. DocumentHighlight.create = create;
  1459. })(DocumentHighlight || (DocumentHighlight = {}));
  1460. /**
  1461. * A symbol kind.
  1462. */
  1463. var SymbolKind;
  1464. (function (SymbolKind) {
  1465. SymbolKind.File = 1;
  1466. SymbolKind.Module = 2;
  1467. SymbolKind.Namespace = 3;
  1468. SymbolKind.Package = 4;
  1469. SymbolKind.Class = 5;
  1470. SymbolKind.Method = 6;
  1471. SymbolKind.Property = 7;
  1472. SymbolKind.Field = 8;
  1473. SymbolKind.Constructor = 9;
  1474. SymbolKind.Enum = 10;
  1475. SymbolKind.Interface = 11;
  1476. SymbolKind.Function = 12;
  1477. SymbolKind.Variable = 13;
  1478. SymbolKind.Constant = 14;
  1479. SymbolKind.String = 15;
  1480. SymbolKind.Number = 16;
  1481. SymbolKind.Boolean = 17;
  1482. SymbolKind.Array = 18;
  1483. SymbolKind.Object = 19;
  1484. SymbolKind.Key = 20;
  1485. SymbolKind.Null = 21;
  1486. SymbolKind.EnumMember = 22;
  1487. SymbolKind.Struct = 23;
  1488. SymbolKind.Event = 24;
  1489. SymbolKind.Operator = 25;
  1490. SymbolKind.TypeParameter = 26;
  1491. })(SymbolKind || (SymbolKind = {}));
  1492. /**
  1493. * Symbol tags are extra annotations that tweak the rendering of a symbol.
  1494. * @since 3.15
  1495. */
  1496. var SymbolTag;
  1497. (function (SymbolTag) {
  1498. /**
  1499. * Render a symbol as obsolete, usually using a strike-out.
  1500. */
  1501. SymbolTag.Deprecated = 1;
  1502. })(SymbolTag || (SymbolTag = {}));
  1503. var SymbolInformation;
  1504. (function (SymbolInformation) {
  1505. /**
  1506. * Creates a new symbol information literal.
  1507. *
  1508. * @param name The name of the symbol.
  1509. * @param kind The kind of the symbol.
  1510. * @param range The range of the location of the symbol.
  1511. * @param uri The resource of the location of symbol, defaults to the current document.
  1512. * @param containerName The name of the symbol containing the symbol.
  1513. */
  1514. function create(name, kind, range, uri, containerName) {
  1515. var result = {
  1516. name: name,
  1517. kind: kind,
  1518. location: { uri: uri, range: range }
  1519. };
  1520. if (containerName) {
  1521. result.containerName = containerName;
  1522. }
  1523. return result;
  1524. }
  1525. SymbolInformation.create = create;
  1526. })(SymbolInformation || (SymbolInformation = {}));
  1527. var DocumentSymbol;
  1528. (function (DocumentSymbol) {
  1529. /**
  1530. * Creates a new symbol information literal.
  1531. *
  1532. * @param name The name of the symbol.
  1533. * @param detail The detail of the symbol.
  1534. * @param kind The kind of the symbol.
  1535. * @param range The range of the symbol.
  1536. * @param selectionRange The selectionRange of the symbol.
  1537. * @param children Children of the symbol.
  1538. */
  1539. function create(name, detail, kind, range, selectionRange, children) {
  1540. var result = {
  1541. name: name,
  1542. detail: detail,
  1543. kind: kind,
  1544. range: range,
  1545. selectionRange: selectionRange
  1546. };
  1547. if (children !== void 0) {
  1548. result.children = children;
  1549. }
  1550. return result;
  1551. }
  1552. DocumentSymbol.create = create;
  1553. /**
  1554. * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
  1555. */
  1556. function is(value) {
  1557. var candidate = value;
  1558. return candidate &&
  1559. Is.string(candidate.name) && Is.number(candidate.kind) &&
  1560. Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
  1561. (candidate.detail === void 0 || Is.string(candidate.detail)) &&
  1562. (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
  1563. (candidate.children === void 0 || Array.isArray(candidate.children));
  1564. }
  1565. DocumentSymbol.is = is;
  1566. })(DocumentSymbol || (DocumentSymbol = {}));
  1567. /**
  1568. * A set of predefined code action kinds
  1569. */
  1570. var CodeActionKind;
  1571. (function (CodeActionKind) {
  1572. /**
  1573. * Empty kind.
  1574. */
  1575. CodeActionKind.Empty = '';
  1576. /**
  1577. * Base kind for quickfix actions: 'quickfix'
  1578. */
  1579. CodeActionKind.QuickFix = 'quickfix';
  1580. /**
  1581. * Base kind for refactoring actions: 'refactor'
  1582. */
  1583. CodeActionKind.Refactor = 'refactor';
  1584. /**
  1585. * Base kind for refactoring extraction actions: 'refactor.extract'
  1586. *
  1587. * Example extract actions:
  1588. *
  1589. * - Extract method
  1590. * - Extract function
  1591. * - Extract variable
  1592. * - Extract interface from class
  1593. * - ...
  1594. */
  1595. CodeActionKind.RefactorExtract = 'refactor.extract';
  1596. /**
  1597. * Base kind for refactoring inline actions: 'refactor.inline'
  1598. *
  1599. * Example inline actions:
  1600. *
  1601. * - Inline function
  1602. * - Inline variable
  1603. * - Inline constant
  1604. * - ...
  1605. */
  1606. CodeActionKind.RefactorInline = 'refactor.inline';
  1607. /**
  1608. * Base kind for refactoring rewrite actions: 'refactor.rewrite'
  1609. *
  1610. * Example rewrite actions:
  1611. *
  1612. * - Convert JavaScript function to class
  1613. * - Add or remove parameter
  1614. * - Encapsulate field
  1615. * - Make method static
  1616. * - Move method to base class
  1617. * - ...
  1618. */
  1619. CodeActionKind.RefactorRewrite = 'refactor.rewrite';
  1620. /**
  1621. * Base kind for source actions: `source`
  1622. *
  1623. * Source code actions apply to the entire file.
  1624. */
  1625. CodeActionKind.Source = 'source';
  1626. /**
  1627. * Base kind for an organize imports source action: `source.organizeImports`
  1628. */
  1629. CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
  1630. /**
  1631. * Base kind for auto-fix source actions: `source.fixAll`.
  1632. *
  1633. * Fix all actions automatically fix errors that have a clear fix that do not require user input.
  1634. * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
  1635. *
  1636. * @since 3.15.0
  1637. */
  1638. CodeActionKind.SourceFixAll = 'source.fixAll';
  1639. })(CodeActionKind || (CodeActionKind = {}));
  1640. /**
  1641. * The CodeActionContext namespace provides helper functions to work with
  1642. * [CodeActionContext](#CodeActionContext) literals.
  1643. */
  1644. var CodeActionContext;
  1645. (function (CodeActionContext) {
  1646. /**
  1647. * Creates a new CodeActionContext literal.
  1648. */
  1649. function create(diagnostics, only) {
  1650. var result = { diagnostics: diagnostics };
  1651. if (only !== void 0 && only !== null) {
  1652. result.only = only;
  1653. }
  1654. return result;
  1655. }
  1656. CodeActionContext.create = create;
  1657. /**
  1658. * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
  1659. */
  1660. function is(value) {
  1661. var candidate = value;
  1662. return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
  1663. }
  1664. CodeActionContext.is = is;
  1665. })(CodeActionContext || (CodeActionContext = {}));
  1666. var CodeAction;
  1667. (function (CodeAction) {
  1668. function create(title, commandOrEdit, kind) {
  1669. var result = { title: title };
  1670. if (Command.is(commandOrEdit)) {
  1671. result.command = commandOrEdit;
  1672. }
  1673. else {
  1674. result.edit = commandOrEdit;
  1675. }
  1676. if (kind !== void 0) {
  1677. result.kind = kind;
  1678. }
  1679. return result;
  1680. }
  1681. CodeAction.create = create;
  1682. function is(value) {
  1683. var candidate = value;
  1684. return candidate && Is.string(candidate.title) &&
  1685. (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
  1686. (candidate.kind === void 0 || Is.string(candidate.kind)) &&
  1687. (candidate.edit !== void 0 || candidate.command !== void 0) &&
  1688. (candidate.command === void 0 || Command.is(candidate.command)) &&
  1689. (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
  1690. (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  1691. }
  1692. CodeAction.is = is;
  1693. })(CodeAction || (CodeAction = {}));
  1694. /**
  1695. * The CodeLens namespace provides helper functions to work with
  1696. * [CodeLens](#CodeLens) literals.
  1697. */
  1698. var CodeLens;
  1699. (function (CodeLens) {
  1700. /**
  1701. * Creates a new CodeLens literal.
  1702. */
  1703. function create(range, data) {
  1704. var result = { range: range };
  1705. if (Is.defined(data)) {
  1706. result.data = data;
  1707. }
  1708. return result;
  1709. }
  1710. CodeLens.create = create;
  1711. /**
  1712. * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
  1713. */
  1714. function is(value) {
  1715. var candidate = value;
  1716. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  1717. }
  1718. CodeLens.is = is;
  1719. })(CodeLens || (CodeLens = {}));
  1720. /**
  1721. * The FormattingOptions namespace provides helper functions to work with
  1722. * [FormattingOptions](#FormattingOptions) literals.
  1723. */
  1724. var FormattingOptions;
  1725. (function (FormattingOptions) {
  1726. /**
  1727. * Creates a new FormattingOptions literal.
  1728. */
  1729. function create(tabSize, insertSpaces) {
  1730. return { tabSize: tabSize, insertSpaces: insertSpaces };
  1731. }
  1732. FormattingOptions.create = create;
  1733. /**
  1734. * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
  1735. */
  1736. function is(value) {
  1737. var candidate = value;
  1738. return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  1739. }
  1740. FormattingOptions.is = is;
  1741. })(FormattingOptions || (FormattingOptions = {}));
  1742. /**
  1743. * The DocumentLink namespace provides helper functions to work with
  1744. * [DocumentLink](#DocumentLink) literals.
  1745. */
  1746. var DocumentLink;
  1747. (function (DocumentLink) {
  1748. /**
  1749. * Creates a new DocumentLink literal.
  1750. */
  1751. function create(range, target, data) {
  1752. return { range: range, target: target, data: data };
  1753. }
  1754. DocumentLink.create = create;
  1755. /**
  1756. * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
  1757. */
  1758. function is(value) {
  1759. var candidate = value;
  1760. return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  1761. }
  1762. DocumentLink.is = is;
  1763. })(DocumentLink || (DocumentLink = {}));
  1764. /**
  1765. * The SelectionRange namespace provides helper function to work with
  1766. * SelectionRange literals.
  1767. */
  1768. var SelectionRange;
  1769. (function (SelectionRange) {
  1770. /**
  1771. * Creates a new SelectionRange
  1772. * @param range the range.
  1773. * @param parent an optional parent.
  1774. */
  1775. function create(range, parent) {
  1776. return { range: range, parent: parent };
  1777. }
  1778. SelectionRange.create = create;
  1779. function is(value) {
  1780. var candidate = value;
  1781. return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
  1782. }
  1783. SelectionRange.is = is;
  1784. })(SelectionRange || (SelectionRange = {}));
  1785. var EOL = ['\n', '\r\n', '\r'];
  1786. /**
  1787. * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
  1788. */
  1789. var TextDocument;
  1790. (function (TextDocument) {
  1791. /**
  1792. * Creates a new ITextDocument literal from the given uri and content.
  1793. * @param uri The document's uri.
  1794. * @param languageId The document's language Id.
  1795. * @param content The document's content.
  1796. */
  1797. function create(uri, languageId, version, content) {
  1798. return new FullTextDocument(uri, languageId, version, content);
  1799. }
  1800. TextDocument.create = create;
  1801. /**
  1802. * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
  1803. */
  1804. function is(value) {
  1805. var candidate = value;
  1806. return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
  1807. && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  1808. }
  1809. TextDocument.is = is;
  1810. function applyEdits(document, edits) {
  1811. var text = document.getText();
  1812. var sortedEdits = mergeSort(edits, function (a, b) {
  1813. var diff = a.range.start.line - b.range.start.line;
  1814. if (diff === 0) {
  1815. return a.range.start.character - b.range.start.character;
  1816. }
  1817. return diff;
  1818. });
  1819. var lastModifiedOffset = text.length;
  1820. for (var i = sortedEdits.length - 1; i >= 0; i--) {
  1821. var e = sortedEdits[i];
  1822. var startOffset = document.offsetAt(e.range.start);
  1823. var endOffset = document.offsetAt(e.range.end);
  1824. if (endOffset <= lastModifiedOffset) {
  1825. text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
  1826. }
  1827. else {
  1828. throw new Error('Overlapping edit');
  1829. }
  1830. lastModifiedOffset = startOffset;
  1831. }
  1832. return text;
  1833. }
  1834. TextDocument.applyEdits = applyEdits;
  1835. function mergeSort(data, compare) {
  1836. if (data.length <= 1) {
  1837. // sorted
  1838. return data;
  1839. }
  1840. var p = (data.length / 2) | 0;
  1841. var left = data.slice(0, p);
  1842. var right = data.slice(p);
  1843. mergeSort(left, compare);
  1844. mergeSort(right, compare);
  1845. var leftIdx = 0;
  1846. var rightIdx = 0;
  1847. var i = 0;
  1848. while (leftIdx < left.length && rightIdx < right.length) {
  1849. var ret = compare(left[leftIdx], right[rightIdx]);
  1850. if (ret <= 0) {
  1851. // smaller_equal -> take left to preserve order
  1852. data[i++] = left[leftIdx++];
  1853. }
  1854. else {
  1855. // greater -> take right
  1856. data[i++] = right[rightIdx++];
  1857. }
  1858. }
  1859. while (leftIdx < left.length) {
  1860. data[i++] = left[leftIdx++];
  1861. }
  1862. while (rightIdx < right.length) {
  1863. data[i++] = right[rightIdx++];
  1864. }
  1865. return data;
  1866. }
  1867. })(TextDocument || (TextDocument = {}));
  1868. var FullTextDocument = /** @class */ (function () {
  1869. function FullTextDocument(uri, languageId, version, content) {
  1870. this._uri = uri;
  1871. this._languageId = languageId;
  1872. this._version = version;
  1873. this._content = content;
  1874. this._lineOffsets = undefined;
  1875. }
  1876. Object.defineProperty(FullTextDocument.prototype, "uri", {
  1877. get: function () {
  1878. return this._uri;
  1879. },
  1880. enumerable: true,
  1881. configurable: true
  1882. });
  1883. Object.defineProperty(FullTextDocument.prototype, "languageId", {
  1884. get: function () {
  1885. return this._languageId;
  1886. },
  1887. enumerable: true,
  1888. configurable: true
  1889. });
  1890. Object.defineProperty(FullTextDocument.prototype, "version", {
  1891. get: function () {
  1892. return this._version;
  1893. },
  1894. enumerable: true,
  1895. configurable: true
  1896. });
  1897. FullTextDocument.prototype.getText = function (range) {
  1898. if (range) {
  1899. var start = this.offsetAt(range.start);
  1900. var end = this.offsetAt(range.end);
  1901. return this._content.substring(start, end);
  1902. }
  1903. return this._content;
  1904. };
  1905. FullTextDocument.prototype.update = function (event, version) {
  1906. this._content = event.text;
  1907. this._version = version;
  1908. this._lineOffsets = undefined;
  1909. };
  1910. FullTextDocument.prototype.getLineOffsets = function () {
  1911. if (this._lineOffsets === undefined) {
  1912. var lineOffsets = [];
  1913. var text = this._content;
  1914. var isLineStart = true;
  1915. for (var i = 0; i < text.length; i++) {
  1916. if (isLineStart) {
  1917. lineOffsets.push(i);
  1918. isLineStart = false;
  1919. }
  1920. var ch = text.charAt(i);
  1921. isLineStart = (ch === '\r' || ch === '\n');
  1922. if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
  1923. i++;
  1924. }
  1925. }
  1926. if (isLineStart && text.length > 0) {
  1927. lineOffsets.push(text.length);
  1928. }
  1929. this._lineOffsets = lineOffsets;
  1930. }
  1931. return this._lineOffsets;
  1932. };
  1933. FullTextDocument.prototype.positionAt = function (offset) {
  1934. offset = Math.max(Math.min(offset, this._content.length), 0);
  1935. var lineOffsets = this.getLineOffsets();
  1936. var low = 0, high = lineOffsets.length;
  1937. if (high === 0) {
  1938. return Position.create(0, offset);
  1939. }
  1940. while (low < high) {
  1941. var mid = Math.floor((low + high) / 2);
  1942. if (lineOffsets[mid] > offset) {
  1943. high = mid;
  1944. }
  1945. else {
  1946. low = mid + 1;
  1947. }
  1948. }
  1949. // low is the least x for which the line offset is larger than the current offset
  1950. // or array.length if no line offset is larger than the current offset
  1951. var line = low - 1;
  1952. return Position.create(line, offset - lineOffsets[line]);
  1953. };
  1954. FullTextDocument.prototype.offsetAt = function (position) {
  1955. var lineOffsets = this.getLineOffsets();
  1956. if (position.line >= lineOffsets.length) {
  1957. return this._content.length;
  1958. }
  1959. else if (position.line < 0) {
  1960. return 0;
  1961. }
  1962. var lineOffset = lineOffsets[position.line];
  1963. var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
  1964. return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  1965. };
  1966. Object.defineProperty(FullTextDocument.prototype, "lineCount", {
  1967. get: function () {
  1968. return this.getLineOffsets().length;
  1969. },
  1970. enumerable: true,
  1971. configurable: true
  1972. });
  1973. return FullTextDocument;
  1974. }());
  1975. var Is;
  1976. (function (Is) {
  1977. var toString = Object.prototype.toString;
  1978. function defined(value) {
  1979. return typeof value !== 'undefined';
  1980. }
  1981. Is.defined = defined;
  1982. function undefined(value) {
  1983. return typeof value === 'undefined';
  1984. }
  1985. Is.undefined = undefined;
  1986. function boolean(value) {
  1987. return value === true || value === false;
  1988. }
  1989. Is.boolean = boolean;
  1990. function string(value) {
  1991. return toString.call(value) === '[object String]';
  1992. }
  1993. Is.string = string;
  1994. function number(value) {
  1995. return toString.call(value) === '[object Number]';
  1996. }
  1997. Is.number = number;
  1998. function func(value) {
  1999. return toString.call(value) === '[object Function]';
  2000. }
  2001. Is.func = func;
  2002. function objectLiteral(value) {
  2003. // Strictly speaking class instances pass this check as well. Since the LSP
  2004. // doesn't use classes we ignore this for now. If we do we need to add something
  2005. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  2006. return value !== null && typeof value === 'object';
  2007. }
  2008. Is.objectLiteral = objectLiteral;
  2009. function typedArray(value, check) {
  2010. return Array.isArray(value) && value.every(check);
  2011. }
  2012. Is.typedArray = typedArray;
  2013. })(Is || (Is = {}));
  2014. /***/ }),
  2015. /* 7 */
  2016. /***/ (function(module, exports, __webpack_require__) {
  2017. "use strict";
  2018. var __importDefault = (this && this.__importDefault) || function (mod) {
  2019. return (mod && mod.__esModule) ? mod : { "default": mod };
  2020. };
  2021. Object.defineProperty(exports, "__esModule", { value: true });
  2022. /******************************************************************
  2023. MIT License http://www.opensource.org/licenses/mit-license.php
  2024. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  2025. *******************************************************************/
  2026. const coc_nvim_1 = __webpack_require__(1);
  2027. const vscode_languageserver_protocol_1 = __webpack_require__(8);
  2028. const os_1 = __importDefault(__webpack_require__(2));
  2029. class SnippetsList extends coc_nvim_1.BasicList {
  2030. constructor(nvim, manager, mru) {
  2031. super(nvim);
  2032. this.manager = manager;
  2033. this.mru = mru;
  2034. this.name = 'snippets';
  2035. this.description = 'snippets list';
  2036. this.addLocationActions();
  2037. }
  2038. async loadItems(context) {
  2039. let { window } = context;
  2040. let valid = await window.valid;
  2041. if (!valid)
  2042. return;
  2043. let buf = await window.buffer;
  2044. let doc = coc_nvim_1.workspace.getDocument(buf.id);
  2045. if (!doc)
  2046. return [];
  2047. let snippets = await this.manager.getSnippets(doc.filetype);
  2048. let res = [];
  2049. let recents = await this.mru.load();
  2050. for (let snip of snippets) {
  2051. let pos = vscode_languageserver_protocol_1.Position.create(snip.lnum, 0);
  2052. let location = vscode_languageserver_protocol_1.Location.create(coc_nvim_1.Uri.file(snip.filepath).toString(), vscode_languageserver_protocol_1.Range.create(pos, pos));
  2053. let prefix = snip.prefix;
  2054. if (prefix.length < 20) {
  2055. prefix = `${prefix}${' '.repeat(20 - prefix.length)}`;
  2056. }
  2057. let idx = recents.indexOf(snip.prefix);
  2058. res.push({
  2059. label: `${prefix}\t${snip.description}\t${snip.filepath.replace(os_1.default.homedir(), '~')}`,
  2060. filterText: `${snip.prefix} ${snip.description}`,
  2061. location,
  2062. recentScore: idx == -1 ? -1 : recents.length - idx
  2063. });
  2064. }
  2065. return res;
  2066. }
  2067. async doHighlight() {
  2068. let { nvim } = coc_nvim_1.workspace;
  2069. nvim.pauseNotification();
  2070. nvim.command('syntax match CocSnippetsPrefix /\\v^\\S+/ contained containedin=CocSnippetsLine', true);
  2071. nvim.command('syntax match CocSnippetsFile /\\v\\t\\S+$/ contained containedin=CocSnippetsLine', true);
  2072. nvim.command('highlight default link CocSnippetsPrefix Identifier', true);
  2073. nvim.command('highlight default link CocSnippetsFile Comment', true);
  2074. await nvim.resumeNotification();
  2075. }
  2076. }
  2077. exports.default = SnippetsList;
  2078. /***/ }),
  2079. /* 8 */
  2080. /***/ (function(module, exports, __webpack_require__) {
  2081. "use strict";
  2082. /* --------------------------------------------------------------------------------------------
  2083. * Copyright (c) Microsoft Corporation. All rights reserved.
  2084. * Licensed under the MIT License. See License.txt in the project root for license information.
  2085. * ------------------------------------------------------------------------------------------ */
  2086. function __export(m) {
  2087. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2088. }
  2089. Object.defineProperty(exports, "__esModule", { value: true });
  2090. const vscode_jsonrpc_1 = __webpack_require__(9);
  2091. exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
  2092. exports.ResponseError = vscode_jsonrpc_1.ResponseError;
  2093. exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
  2094. exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
  2095. exports.Disposable = vscode_jsonrpc_1.Disposable;
  2096. exports.Event = vscode_jsonrpc_1.Event;
  2097. exports.Emitter = vscode_jsonrpc_1.Emitter;
  2098. exports.Trace = vscode_jsonrpc_1.Trace;
  2099. exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
  2100. exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
  2101. exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
  2102. exports.RequestType = vscode_jsonrpc_1.RequestType;
  2103. exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
  2104. exports.NotificationType = vscode_jsonrpc_1.NotificationType;
  2105. exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
  2106. exports.MessageReader = vscode_jsonrpc_1.MessageReader;
  2107. exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
  2108. exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
  2109. exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
  2110. exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
  2111. exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
  2112. exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
  2113. exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
  2114. exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
  2115. exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
  2116. exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
  2117. exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
  2118. exports.ProgressType = vscode_jsonrpc_1.ProgressType;
  2119. __export(__webpack_require__(6));
  2120. __export(__webpack_require__(21));
  2121. const callHierarchy = __webpack_require__(33);
  2122. const st = __webpack_require__(34);
  2123. var Proposed;
  2124. (function (Proposed) {
  2125. let CallHierarchyPrepareRequest;
  2126. (function (CallHierarchyPrepareRequest) {
  2127. CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
  2128. CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
  2129. })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
  2130. let CallHierarchyIncomingCallsRequest;
  2131. (function (CallHierarchyIncomingCallsRequest) {
  2132. CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
  2133. CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
  2134. })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
  2135. let CallHierarchyOutgoingCallsRequest;
  2136. (function (CallHierarchyOutgoingCallsRequest) {
  2137. CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
  2138. CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
  2139. })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
  2140. Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
  2141. Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
  2142. Proposed.SemanticTokens = st.SemanticTokens;
  2143. let SemanticTokensRequest;
  2144. (function (SemanticTokensRequest) {
  2145. SemanticTokensRequest.method = st.SemanticTokensRequest.method;
  2146. SemanticTokensRequest.type = st.SemanticTokensRequest.type;
  2147. })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
  2148. let SemanticTokensEditsRequest;
  2149. (function (SemanticTokensEditsRequest) {
  2150. SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
  2151. SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
  2152. })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
  2153. let SemanticTokensRangeRequest;
  2154. (function (SemanticTokensRangeRequest) {
  2155. SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
  2156. SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
  2157. })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
  2158. })(Proposed = exports.Proposed || (exports.Proposed = {}));
  2159. function createProtocolConnection(reader, writer, logger, strategy) {
  2160. return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
  2161. }
  2162. exports.createProtocolConnection = createProtocolConnection;
  2163. /***/ }),
  2164. /* 9 */
  2165. /***/ (function(module, exports, __webpack_require__) {
  2166. "use strict";
  2167. /* --------------------------------------------------------------------------------------------
  2168. * Copyright (c) Microsoft Corporation. All rights reserved.
  2169. * Licensed under the MIT License. See License.txt in the project root for license information.
  2170. * ------------------------------------------------------------------------------------------ */
  2171. /// <reference path="../typings/thenable.d.ts" />
  2172. function __export(m) {
  2173. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2174. }
  2175. Object.defineProperty(exports, "__esModule", { value: true });
  2176. const Is = __webpack_require__(10);
  2177. const messages_1 = __webpack_require__(11);
  2178. exports.RequestType = messages_1.RequestType;
  2179. exports.RequestType0 = messages_1.RequestType0;
  2180. exports.RequestType1 = messages_1.RequestType1;
  2181. exports.RequestType2 = messages_1.RequestType2;
  2182. exports.RequestType3 = messages_1.RequestType3;
  2183. exports.RequestType4 = messages_1.RequestType4;
  2184. exports.RequestType5 = messages_1.RequestType5;
  2185. exports.RequestType6 = messages_1.RequestType6;
  2186. exports.RequestType7 = messages_1.RequestType7;
  2187. exports.RequestType8 = messages_1.RequestType8;
  2188. exports.RequestType9 = messages_1.RequestType9;
  2189. exports.ResponseError = messages_1.ResponseError;
  2190. exports.ErrorCodes = messages_1.ErrorCodes;
  2191. exports.NotificationType = messages_1.NotificationType;
  2192. exports.NotificationType0 = messages_1.NotificationType0;
  2193. exports.NotificationType1 = messages_1.NotificationType1;
  2194. exports.NotificationType2 = messages_1.NotificationType2;
  2195. exports.NotificationType3 = messages_1.NotificationType3;
  2196. exports.NotificationType4 = messages_1.NotificationType4;
  2197. exports.NotificationType5 = messages_1.NotificationType5;
  2198. exports.NotificationType6 = messages_1.NotificationType6;
  2199. exports.NotificationType7 = messages_1.NotificationType7;
  2200. exports.NotificationType8 = messages_1.NotificationType8;
  2201. exports.NotificationType9 = messages_1.NotificationType9;
  2202. const messageReader_1 = __webpack_require__(12);
  2203. exports.MessageReader = messageReader_1.MessageReader;
  2204. exports.StreamMessageReader = messageReader_1.StreamMessageReader;
  2205. exports.IPCMessageReader = messageReader_1.IPCMessageReader;
  2206. exports.SocketMessageReader = messageReader_1.SocketMessageReader;
  2207. const messageWriter_1 = __webpack_require__(14);
  2208. exports.MessageWriter = messageWriter_1.MessageWriter;
  2209. exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
  2210. exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
  2211. exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
  2212. const events_1 = __webpack_require__(13);
  2213. exports.Disposable = events_1.Disposable;
  2214. exports.Event = events_1.Event;
  2215. exports.Emitter = events_1.Emitter;
  2216. const cancellation_1 = __webpack_require__(15);
  2217. exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
  2218. exports.CancellationToken = cancellation_1.CancellationToken;
  2219. const linkedMap_1 = __webpack_require__(16);
  2220. __export(__webpack_require__(17));
  2221. __export(__webpack_require__(20));
  2222. var CancelNotification;
  2223. (function (CancelNotification) {
  2224. CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
  2225. })(CancelNotification || (CancelNotification = {}));
  2226. var ProgressNotification;
  2227. (function (ProgressNotification) {
  2228. ProgressNotification.type = new messages_1.NotificationType('$/progress');
  2229. })(ProgressNotification || (ProgressNotification = {}));
  2230. class ProgressType {
  2231. constructor() {
  2232. }
  2233. }
  2234. exports.ProgressType = ProgressType;
  2235. exports.NullLogger = Object.freeze({
  2236. error: () => { },
  2237. warn: () => { },
  2238. info: () => { },
  2239. log: () => { }
  2240. });
  2241. var Trace;
  2242. (function (Trace) {
  2243. Trace[Trace["Off"] = 0] = "Off";
  2244. Trace[Trace["Messages"] = 1] = "Messages";
  2245. Trace[Trace["Verbose"] = 2] = "Verbose";
  2246. })(Trace = exports.Trace || (exports.Trace = {}));
  2247. (function (Trace) {
  2248. function fromString(value) {
  2249. if (!Is.string(value)) {
  2250. return Trace.Off;
  2251. }
  2252. value = value.toLowerCase();
  2253. switch (value) {
  2254. case 'off':
  2255. return Trace.Off;
  2256. case 'messages':
  2257. return Trace.Messages;
  2258. case 'verbose':
  2259. return Trace.Verbose;
  2260. default:
  2261. return Trace.Off;
  2262. }
  2263. }
  2264. Trace.fromString = fromString;
  2265. function toString(value) {
  2266. switch (value) {
  2267. case Trace.Off:
  2268. return 'off';
  2269. case Trace.Messages:
  2270. return 'messages';
  2271. case Trace.Verbose:
  2272. return 'verbose';
  2273. default:
  2274. return 'off';
  2275. }
  2276. }
  2277. Trace.toString = toString;
  2278. })(Trace = exports.Trace || (exports.Trace = {}));
  2279. var TraceFormat;
  2280. (function (TraceFormat) {
  2281. TraceFormat["Text"] = "text";
  2282. TraceFormat["JSON"] = "json";
  2283. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  2284. (function (TraceFormat) {
  2285. function fromString(value) {
  2286. value = value.toLowerCase();
  2287. if (value === 'json') {
  2288. return TraceFormat.JSON;
  2289. }
  2290. else {
  2291. return TraceFormat.Text;
  2292. }
  2293. }
  2294. TraceFormat.fromString = fromString;
  2295. })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
  2296. var SetTraceNotification;
  2297. (function (SetTraceNotification) {
  2298. SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
  2299. })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
  2300. var LogTraceNotification;
  2301. (function (LogTraceNotification) {
  2302. LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
  2303. })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
  2304. var ConnectionErrors;
  2305. (function (ConnectionErrors) {
  2306. /**
  2307. * The connection is closed.
  2308. */
  2309. ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
  2310. /**
  2311. * The connection got disposed.
  2312. */
  2313. ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
  2314. /**
  2315. * The connection is already in listening mode.
  2316. */
  2317. ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
  2318. })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
  2319. class ConnectionError extends Error {
  2320. constructor(code, message) {
  2321. super(message);
  2322. this.code = code;
  2323. Object.setPrototypeOf(this, ConnectionError.prototype);
  2324. }
  2325. }
  2326. exports.ConnectionError = ConnectionError;
  2327. var ConnectionStrategy;
  2328. (function (ConnectionStrategy) {
  2329. function is(value) {
  2330. let candidate = value;
  2331. return candidate && Is.func(candidate.cancelUndispatched);
  2332. }
  2333. ConnectionStrategy.is = is;
  2334. })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
  2335. var ConnectionState;
  2336. (function (ConnectionState) {
  2337. ConnectionState[ConnectionState["New"] = 1] = "New";
  2338. ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
  2339. ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
  2340. ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
  2341. })(ConnectionState || (ConnectionState = {}));
  2342. function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
  2343. let sequenceNumber = 0;
  2344. let notificationSquenceNumber = 0;
  2345. let unknownResponseSquenceNumber = 0;
  2346. const version = '2.0';
  2347. let starRequestHandler = undefined;
  2348. let requestHandlers = Object.create(null);
  2349. let starNotificationHandler = undefined;
  2350. let notificationHandlers = Object.create(null);
  2351. let progressHandlers = new Map();
  2352. let timer;
  2353. let messageQueue = new linkedMap_1.LinkedMap();
  2354. let responsePromises = Object.create(null);
  2355. let requestTokens = Object.create(null);
  2356. let trace = Trace.Off;
  2357. let traceFormat = TraceFormat.Text;
  2358. let tracer;
  2359. let state = ConnectionState.New;
  2360. let errorEmitter = new events_1.Emitter();
  2361. let closeEmitter = new events_1.Emitter();
  2362. let unhandledNotificationEmitter = new events_1.Emitter();
  2363. let unhandledProgressEmitter = new events_1.Emitter();
  2364. let disposeEmitter = new events_1.Emitter();
  2365. function createRequestQueueKey(id) {
  2366. return 'req-' + id.toString();
  2367. }
  2368. function createResponseQueueKey(id) {
  2369. if (id === null) {
  2370. return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
  2371. }
  2372. else {
  2373. return 'res-' + id.toString();
  2374. }
  2375. }
  2376. function createNotificationQueueKey() {
  2377. return 'not-' + (++notificationSquenceNumber).toString();
  2378. }
  2379. function addMessageToQueue(queue, message) {
  2380. if (messages_1.isRequestMessage(message)) {
  2381. queue.set(createRequestQueueKey(message.id), message);
  2382. }
  2383. else if (messages_1.isResponseMessage(message)) {
  2384. queue.set(createResponseQueueKey(message.id), message);
  2385. }
  2386. else {
  2387. queue.set(createNotificationQueueKey(), message);
  2388. }
  2389. }
  2390. function cancelUndispatched(_message) {
  2391. return undefined;
  2392. }
  2393. function isListening() {
  2394. return state === ConnectionState.Listening;
  2395. }
  2396. function isClosed() {
  2397. return state === ConnectionState.Closed;
  2398. }
  2399. function isDisposed() {
  2400. return state === ConnectionState.Disposed;
  2401. }
  2402. function closeHandler() {
  2403. if (state === ConnectionState.New || state === ConnectionState.Listening) {
  2404. state = ConnectionState.Closed;
  2405. closeEmitter.fire(undefined);
  2406. }
  2407. // If the connection is disposed don't sent close events.
  2408. }
  2409. function readErrorHandler(error) {
  2410. errorEmitter.fire([error, undefined, undefined]);
  2411. }
  2412. function writeErrorHandler(data) {
  2413. errorEmitter.fire(data);
  2414. }
  2415. messageReader.onClose(closeHandler);
  2416. messageReader.onError(readErrorHandler);
  2417. messageWriter.onClose(closeHandler);
  2418. messageWriter.onError(writeErrorHandler);
  2419. function triggerMessageQueue() {
  2420. if (timer || messageQueue.size === 0) {
  2421. return;
  2422. }
  2423. timer = setImmediate(() => {
  2424. timer = undefined;
  2425. processMessageQueue();
  2426. });
  2427. }
  2428. function processMessageQueue() {
  2429. if (messageQueue.size === 0) {
  2430. return;
  2431. }
  2432. let message = messageQueue.shift();
  2433. try {
  2434. if (messages_1.isRequestMessage(message)) {
  2435. handleRequest(message);
  2436. }
  2437. else if (messages_1.isNotificationMessage(message)) {
  2438. handleNotification(message);
  2439. }
  2440. else if (messages_1.isResponseMessage(message)) {
  2441. handleResponse(message);
  2442. }
  2443. else {
  2444. handleInvalidMessage(message);
  2445. }
  2446. }
  2447. finally {
  2448. triggerMessageQueue();
  2449. }
  2450. }
  2451. let callback = (message) => {
  2452. try {
  2453. // We have received a cancellation message. Check if the message is still in the queue
  2454. // and cancel it if allowed to do so.
  2455. if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
  2456. let key = createRequestQueueKey(message.params.id);
  2457. let toCancel = messageQueue.get(key);
  2458. if (messages_1.isRequestMessage(toCancel)) {
  2459. let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
  2460. if (response && (response.error !== void 0 || response.result !== void 0)) {
  2461. messageQueue.delete(key);
  2462. response.id = toCancel.id;
  2463. traceSendingResponse(response, message.method, Date.now());
  2464. messageWriter.write(response);
  2465. return;
  2466. }
  2467. }
  2468. }
  2469. addMessageToQueue(messageQueue, message);
  2470. }
  2471. finally {
  2472. triggerMessageQueue();
  2473. }
  2474. };
  2475. function handleRequest(requestMessage) {
  2476. if (isDisposed()) {
  2477. // we return here silently since we fired an event when the
  2478. // connection got disposed.
  2479. return;
  2480. }
  2481. function reply(resultOrError, method, startTime) {
  2482. let message = {
  2483. jsonrpc: version,
  2484. id: requestMessage.id
  2485. };
  2486. if (resultOrError instanceof messages_1.ResponseError) {
  2487. message.error = resultOrError.toJson();
  2488. }
  2489. else {
  2490. message.result = resultOrError === void 0 ? null : resultOrError;
  2491. }
  2492. traceSendingResponse(message, method, startTime);
  2493. messageWriter.write(message);
  2494. }
  2495. function replyError(error, method, startTime) {
  2496. let message = {
  2497. jsonrpc: version,
  2498. id: requestMessage.id,
  2499. error: error.toJson()
  2500. };
  2501. traceSendingResponse(message, method, startTime);
  2502. messageWriter.write(message);
  2503. }
  2504. function replySuccess(result, method, startTime) {
  2505. // The JSON RPC defines that a response must either have a result or an error
  2506. // So we can't treat undefined as a valid response result.
  2507. if (result === void 0) {
  2508. result = null;
  2509. }
  2510. let message = {
  2511. jsonrpc: version,
  2512. id: requestMessage.id,
  2513. result: result
  2514. };
  2515. traceSendingResponse(message, method, startTime);
  2516. messageWriter.write(message);
  2517. }
  2518. traceReceivedRequest(requestMessage);
  2519. let element = requestHandlers[requestMessage.method];
  2520. let type;
  2521. let requestHandler;
  2522. if (element) {
  2523. type = element.type;
  2524. requestHandler = element.handler;
  2525. }
  2526. let startTime = Date.now();
  2527. if (requestHandler || starRequestHandler) {
  2528. let cancellationSource = new cancellation_1.CancellationTokenSource();
  2529. let tokenKey = String(requestMessage.id);
  2530. requestTokens[tokenKey] = cancellationSource;
  2531. try {
  2532. let handlerResult;
  2533. if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  2534. handlerResult = requestHandler
  2535. ? requestHandler(cancellationSource.token)
  2536. : starRequestHandler(requestMessage.method, cancellationSource.token);
  2537. }
  2538. else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
  2539. handlerResult = requestHandler
  2540. ? requestHandler(...requestMessage.params, cancellationSource.token)
  2541. : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
  2542. }
  2543. else {
  2544. handlerResult = requestHandler
  2545. ? requestHandler(requestMessage.params, cancellationSource.token)
  2546. : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
  2547. }
  2548. let promise = handlerResult;
  2549. if (!handlerResult) {
  2550. delete requestTokens[tokenKey];
  2551. replySuccess(handlerResult, requestMessage.method, startTime);
  2552. }
  2553. else if (promise.then) {
  2554. promise.then((resultOrError) => {
  2555. delete requestTokens[tokenKey];
  2556. reply(resultOrError, requestMessage.method, startTime);
  2557. }, error => {
  2558. delete requestTokens[tokenKey];
  2559. if (error instanceof messages_1.ResponseError) {
  2560. replyError(error, requestMessage.method, startTime);
  2561. }
  2562. else if (error && Is.string(error.message)) {
  2563. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  2564. }
  2565. else {
  2566. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  2567. }
  2568. });
  2569. }
  2570. else {
  2571. delete requestTokens[tokenKey];
  2572. reply(handlerResult, requestMessage.method, startTime);
  2573. }
  2574. }
  2575. catch (error) {
  2576. delete requestTokens[tokenKey];
  2577. if (error instanceof messages_1.ResponseError) {
  2578. reply(error, requestMessage.method, startTime);
  2579. }
  2580. else if (error && Is.string(error.message)) {
  2581. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
  2582. }
  2583. else {
  2584. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
  2585. }
  2586. }
  2587. }
  2588. else {
  2589. replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
  2590. }
  2591. }
  2592. function handleResponse(responseMessage) {
  2593. if (isDisposed()) {
  2594. // See handle request.
  2595. return;
  2596. }
  2597. if (responseMessage.id === null) {
  2598. if (responseMessage.error) {
  2599. logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
  2600. }
  2601. else {
  2602. logger.error(`Received response message without id. No further error information provided.`);
  2603. }
  2604. }
  2605. else {
  2606. let key = String(responseMessage.id);
  2607. let responsePromise = responsePromises[key];
  2608. traceReceivedResponse(responseMessage, responsePromise);
  2609. if (responsePromise) {
  2610. delete responsePromises[key];
  2611. try {
  2612. if (responseMessage.error) {
  2613. let error = responseMessage.error;
  2614. responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
  2615. }
  2616. else if (responseMessage.result !== void 0) {
  2617. responsePromise.resolve(responseMessage.result);
  2618. }
  2619. else {
  2620. throw new Error('Should never happen.');
  2621. }
  2622. }
  2623. catch (error) {
  2624. if (error.message) {
  2625. logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
  2626. }
  2627. else {
  2628. logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. function handleNotification(message) {
  2635. if (isDisposed()) {
  2636. // See handle request.
  2637. return;
  2638. }
  2639. let type = undefined;
  2640. let notificationHandler;
  2641. if (message.method === CancelNotification.type.method) {
  2642. notificationHandler = (params) => {
  2643. let id = params.id;
  2644. let source = requestTokens[String(id)];
  2645. if (source) {
  2646. source.cancel();
  2647. }
  2648. };
  2649. }
  2650. else {
  2651. let element = notificationHandlers[message.method];
  2652. if (element) {
  2653. notificationHandler = element.handler;
  2654. type = element.type;
  2655. }
  2656. }
  2657. if (notificationHandler || starNotificationHandler) {
  2658. try {
  2659. traceReceivedNotification(message);
  2660. if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
  2661. notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
  2662. }
  2663. else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
  2664. notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
  2665. }
  2666. else {
  2667. notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
  2668. }
  2669. }
  2670. catch (error) {
  2671. if (error.message) {
  2672. logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
  2673. }
  2674. else {
  2675. logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
  2676. }
  2677. }
  2678. }
  2679. else {
  2680. unhandledNotificationEmitter.fire(message);
  2681. }
  2682. }
  2683. function handleInvalidMessage(message) {
  2684. if (!message) {
  2685. logger.error('Received empty message.');
  2686. return;
  2687. }
  2688. logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
  2689. // Test whether we find an id to reject the promise
  2690. let responseMessage = message;
  2691. if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
  2692. let key = String(responseMessage.id);
  2693. let responseHandler = responsePromises[key];
  2694. if (responseHandler) {
  2695. responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
  2696. }
  2697. }
  2698. }
  2699. function traceSendingRequest(message) {
  2700. if (trace === Trace.Off || !tracer) {
  2701. return;
  2702. }
  2703. if (traceFormat === TraceFormat.Text) {
  2704. let data = undefined;
  2705. if (trace === Trace.Verbose && message.params) {
  2706. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  2707. }
  2708. tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
  2709. }
  2710. else {
  2711. logLSPMessage('send-request', message);
  2712. }
  2713. }
  2714. function traceSendingNotification(message) {
  2715. if (trace === Trace.Off || !tracer) {
  2716. return;
  2717. }
  2718. if (traceFormat === TraceFormat.Text) {
  2719. let data = undefined;
  2720. if (trace === Trace.Verbose) {
  2721. if (message.params) {
  2722. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  2723. }
  2724. else {
  2725. data = 'No parameters provided.\n\n';
  2726. }
  2727. }
  2728. tracer.log(`Sending notification '${message.method}'.`, data);
  2729. }
  2730. else {
  2731. logLSPMessage('send-notification', message);
  2732. }
  2733. }
  2734. function traceSendingResponse(message, method, startTime) {
  2735. if (trace === Trace.Off || !tracer) {
  2736. return;
  2737. }
  2738. if (traceFormat === TraceFormat.Text) {
  2739. let data = undefined;
  2740. if (trace === Trace.Verbose) {
  2741. if (message.error && message.error.data) {
  2742. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  2743. }
  2744. else {
  2745. if (message.result) {
  2746. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  2747. }
  2748. else if (message.error === void 0) {
  2749. data = 'No result returned.\n\n';
  2750. }
  2751. }
  2752. }
  2753. tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
  2754. }
  2755. else {
  2756. logLSPMessage('send-response', message);
  2757. }
  2758. }
  2759. function traceReceivedRequest(message) {
  2760. if (trace === Trace.Off || !tracer) {
  2761. return;
  2762. }
  2763. if (traceFormat === TraceFormat.Text) {
  2764. let data = undefined;
  2765. if (trace === Trace.Verbose && message.params) {
  2766. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  2767. }
  2768. tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
  2769. }
  2770. else {
  2771. logLSPMessage('receive-request', message);
  2772. }
  2773. }
  2774. function traceReceivedNotification(message) {
  2775. if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
  2776. return;
  2777. }
  2778. if (traceFormat === TraceFormat.Text) {
  2779. let data = undefined;
  2780. if (trace === Trace.Verbose) {
  2781. if (message.params) {
  2782. data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
  2783. }
  2784. else {
  2785. data = 'No parameters provided.\n\n';
  2786. }
  2787. }
  2788. tracer.log(`Received notification '${message.method}'.`, data);
  2789. }
  2790. else {
  2791. logLSPMessage('receive-notification', message);
  2792. }
  2793. }
  2794. function traceReceivedResponse(message, responsePromise) {
  2795. if (trace === Trace.Off || !tracer) {
  2796. return;
  2797. }
  2798. if (traceFormat === TraceFormat.Text) {
  2799. let data = undefined;
  2800. if (trace === Trace.Verbose) {
  2801. if (message.error && message.error.data) {
  2802. data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
  2803. }
  2804. else {
  2805. if (message.result) {
  2806. data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
  2807. }
  2808. else if (message.error === void 0) {
  2809. data = 'No result returned.\n\n';
  2810. }
  2811. }
  2812. }
  2813. if (responsePromise) {
  2814. let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
  2815. tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
  2816. }
  2817. else {
  2818. tracer.log(`Received response ${message.id} without active response promise.`, data);
  2819. }
  2820. }
  2821. else {
  2822. logLSPMessage('receive-response', message);
  2823. }
  2824. }
  2825. function logLSPMessage(type, message) {
  2826. if (!tracer || trace === Trace.Off) {
  2827. return;
  2828. }
  2829. const lspMessage = {
  2830. isLSPMessage: true,
  2831. type,
  2832. message,
  2833. timestamp: Date.now()
  2834. };
  2835. tracer.log(lspMessage);
  2836. }
  2837. function throwIfClosedOrDisposed() {
  2838. if (isClosed()) {
  2839. throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
  2840. }
  2841. if (isDisposed()) {
  2842. throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
  2843. }
  2844. }
  2845. function throwIfListening() {
  2846. if (isListening()) {
  2847. throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
  2848. }
  2849. }
  2850. function throwIfNotListening() {
  2851. if (!isListening()) {
  2852. throw new Error('Call listen() first.');
  2853. }
  2854. }
  2855. function undefinedToNull(param) {
  2856. if (param === void 0) {
  2857. return null;
  2858. }
  2859. else {
  2860. return param;
  2861. }
  2862. }
  2863. function computeMessageParams(type, params) {
  2864. let result;
  2865. let numberOfParams = type.numberOfParams;
  2866. switch (numberOfParams) {
  2867. case 0:
  2868. result = null;
  2869. break;
  2870. case 1:
  2871. result = undefinedToNull(params[0]);
  2872. break;
  2873. default:
  2874. result = [];
  2875. for (let i = 0; i < params.length && i < numberOfParams; i++) {
  2876. result.push(undefinedToNull(params[i]));
  2877. }
  2878. if (params.length < numberOfParams) {
  2879. for (let i = params.length; i < numberOfParams; i++) {
  2880. result.push(null);
  2881. }
  2882. }
  2883. break;
  2884. }
  2885. return result;
  2886. }
  2887. let connection = {
  2888. sendNotification: (type, ...params) => {
  2889. throwIfClosedOrDisposed();
  2890. let method;
  2891. let messageParams;
  2892. if (Is.string(type)) {
  2893. method = type;
  2894. switch (params.length) {
  2895. case 0:
  2896. messageParams = null;
  2897. break;
  2898. case 1:
  2899. messageParams = params[0];
  2900. break;
  2901. default:
  2902. messageParams = params;
  2903. break;
  2904. }
  2905. }
  2906. else {
  2907. method = type.method;
  2908. messageParams = computeMessageParams(type, params);
  2909. }
  2910. let notificationMessage = {
  2911. jsonrpc: version,
  2912. method: method,
  2913. params: messageParams
  2914. };
  2915. traceSendingNotification(notificationMessage);
  2916. messageWriter.write(notificationMessage);
  2917. },
  2918. onNotification: (type, handler) => {
  2919. throwIfClosedOrDisposed();
  2920. if (Is.func(type)) {
  2921. starNotificationHandler = type;
  2922. }
  2923. else if (handler) {
  2924. if (Is.string(type)) {
  2925. notificationHandlers[type] = { type: undefined, handler };
  2926. }
  2927. else {
  2928. notificationHandlers[type.method] = { type, handler };
  2929. }
  2930. }
  2931. },
  2932. onProgress: (_type, token, handler) => {
  2933. if (progressHandlers.has(token)) {
  2934. throw new Error(`Progress handler for token ${token} already registered`);
  2935. }
  2936. progressHandlers.set(token, handler);
  2937. return {
  2938. dispose: () => {
  2939. progressHandlers.delete(token);
  2940. }
  2941. };
  2942. },
  2943. sendProgress: (_type, token, value) => {
  2944. connection.sendNotification(ProgressNotification.type, { token, value });
  2945. },
  2946. onUnhandledProgress: unhandledProgressEmitter.event,
  2947. sendRequest: (type, ...params) => {
  2948. throwIfClosedOrDisposed();
  2949. throwIfNotListening();
  2950. let method;
  2951. let messageParams;
  2952. let token = undefined;
  2953. if (Is.string(type)) {
  2954. method = type;
  2955. switch (params.length) {
  2956. case 0:
  2957. messageParams = null;
  2958. break;
  2959. case 1:
  2960. // The cancellation token is optional so it can also be undefined.
  2961. if (cancellation_1.CancellationToken.is(params[0])) {
  2962. messageParams = null;
  2963. token = params[0];
  2964. }
  2965. else {
  2966. messageParams = undefinedToNull(params[0]);
  2967. }
  2968. break;
  2969. default:
  2970. const last = params.length - 1;
  2971. if (cancellation_1.CancellationToken.is(params[last])) {
  2972. token = params[last];
  2973. if (params.length === 2) {
  2974. messageParams = undefinedToNull(params[0]);
  2975. }
  2976. else {
  2977. messageParams = params.slice(0, last).map(value => undefinedToNull(value));
  2978. }
  2979. }
  2980. else {
  2981. messageParams = params.map(value => undefinedToNull(value));
  2982. }
  2983. break;
  2984. }
  2985. }
  2986. else {
  2987. method = type.method;
  2988. messageParams = computeMessageParams(type, params);
  2989. let numberOfParams = type.numberOfParams;
  2990. token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
  2991. }
  2992. let id = sequenceNumber++;
  2993. let result = new Promise((resolve, reject) => {
  2994. let requestMessage = {
  2995. jsonrpc: version,
  2996. id: id,
  2997. method: method,
  2998. params: messageParams
  2999. };
  3000. let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
  3001. traceSendingRequest(requestMessage);
  3002. try {
  3003. messageWriter.write(requestMessage);
  3004. }
  3005. catch (e) {
  3006. // Writing the message failed. So we need to reject the promise.
  3007. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
  3008. responsePromise = null;
  3009. }
  3010. if (responsePromise) {
  3011. responsePromises[String(id)] = responsePromise;
  3012. }
  3013. });
  3014. if (token) {
  3015. token.onCancellationRequested(() => {
  3016. connection.sendNotification(CancelNotification.type, { id });
  3017. });
  3018. }
  3019. return result;
  3020. },
  3021. onRequest: (type, handler) => {
  3022. throwIfClosedOrDisposed();
  3023. if (Is.func(type)) {
  3024. starRequestHandler = type;
  3025. }
  3026. else if (handler) {
  3027. if (Is.string(type)) {
  3028. requestHandlers[type] = { type: undefined, handler };
  3029. }
  3030. else {
  3031. requestHandlers[type.method] = { type, handler };
  3032. }
  3033. }
  3034. },
  3035. trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
  3036. let _sendNotification = false;
  3037. let _traceFormat = TraceFormat.Text;
  3038. if (sendNotificationOrTraceOptions !== void 0) {
  3039. if (Is.boolean(sendNotificationOrTraceOptions)) {
  3040. _sendNotification = sendNotificationOrTraceOptions;
  3041. }
  3042. else {
  3043. _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
  3044. _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
  3045. }
  3046. }
  3047. trace = _value;
  3048. traceFormat = _traceFormat;
  3049. if (trace === Trace.Off) {
  3050. tracer = undefined;
  3051. }
  3052. else {
  3053. tracer = _tracer;
  3054. }
  3055. if (_sendNotification && !isClosed() && !isDisposed()) {
  3056. connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
  3057. }
  3058. },
  3059. onError: errorEmitter.event,
  3060. onClose: closeEmitter.event,
  3061. onUnhandledNotification: unhandledNotificationEmitter.event,
  3062. onDispose: disposeEmitter.event,
  3063. dispose: () => {
  3064. if (isDisposed()) {
  3065. return;
  3066. }
  3067. state = ConnectionState.Disposed;
  3068. disposeEmitter.fire(undefined);
  3069. let error = new Error('Connection got disposed.');
  3070. Object.keys(responsePromises).forEach((key) => {
  3071. responsePromises[key].reject(error);
  3072. });
  3073. responsePromises = Object.create(null);
  3074. requestTokens = Object.create(null);
  3075. messageQueue = new linkedMap_1.LinkedMap();
  3076. // Test for backwards compatibility
  3077. if (Is.func(messageWriter.dispose)) {
  3078. messageWriter.dispose();
  3079. }
  3080. if (Is.func(messageReader.dispose)) {
  3081. messageReader.dispose();
  3082. }
  3083. },
  3084. listen: () => {
  3085. throwIfClosedOrDisposed();
  3086. throwIfListening();
  3087. state = ConnectionState.Listening;
  3088. messageReader.listen(callback);
  3089. },
  3090. inspect: () => {
  3091. // eslint-disable-next-line no-console
  3092. console.log('inspect');
  3093. }
  3094. };
  3095. connection.onNotification(LogTraceNotification.type, (params) => {
  3096. if (trace === Trace.Off || !tracer) {
  3097. return;
  3098. }
  3099. tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
  3100. });
  3101. connection.onNotification(ProgressNotification.type, (params) => {
  3102. const handler = progressHandlers.get(params.token);
  3103. if (handler) {
  3104. handler(params.value);
  3105. }
  3106. else {
  3107. unhandledProgressEmitter.fire(params);
  3108. }
  3109. });
  3110. return connection;
  3111. }
  3112. function isMessageReader(value) {
  3113. return value.listen !== void 0 && value.read === void 0;
  3114. }
  3115. function isMessageWriter(value) {
  3116. return value.write !== void 0 && value.end === void 0;
  3117. }
  3118. function createMessageConnection(input, output, logger, strategy) {
  3119. if (!logger) {
  3120. logger = exports.NullLogger;
  3121. }
  3122. let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
  3123. let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
  3124. return _createMessageConnection(reader, writer, logger, strategy);
  3125. }
  3126. exports.createMessageConnection = createMessageConnection;
  3127. /***/ }),
  3128. /* 10 */
  3129. /***/ (function(module, exports, __webpack_require__) {
  3130. "use strict";
  3131. /* --------------------------------------------------------------------------------------------
  3132. * Copyright (c) Microsoft Corporation. All rights reserved.
  3133. * Licensed under the MIT License. See License.txt in the project root for license information.
  3134. * ------------------------------------------------------------------------------------------ */
  3135. Object.defineProperty(exports, "__esModule", { value: true });
  3136. function boolean(value) {
  3137. return value === true || value === false;
  3138. }
  3139. exports.boolean = boolean;
  3140. function string(value) {
  3141. return typeof value === 'string' || value instanceof String;
  3142. }
  3143. exports.string = string;
  3144. function number(value) {
  3145. return typeof value === 'number' || value instanceof Number;
  3146. }
  3147. exports.number = number;
  3148. function error(value) {
  3149. return value instanceof Error;
  3150. }
  3151. exports.error = error;
  3152. function func(value) {
  3153. return typeof value === 'function';
  3154. }
  3155. exports.func = func;
  3156. function array(value) {
  3157. return Array.isArray(value);
  3158. }
  3159. exports.array = array;
  3160. function stringArray(value) {
  3161. return array(value) && value.every(elem => string(elem));
  3162. }
  3163. exports.stringArray = stringArray;
  3164. /***/ }),
  3165. /* 11 */
  3166. /***/ (function(module, exports, __webpack_require__) {
  3167. "use strict";
  3168. /* --------------------------------------------------------------------------------------------
  3169. * Copyright (c) Microsoft Corporation. All rights reserved.
  3170. * Licensed under the MIT License. See License.txt in the project root for license information.
  3171. * ------------------------------------------------------------------------------------------ */
  3172. Object.defineProperty(exports, "__esModule", { value: true });
  3173. const is = __webpack_require__(10);
  3174. /**
  3175. * Predefined error codes.
  3176. */
  3177. var ErrorCodes;
  3178. (function (ErrorCodes) {
  3179. // Defined by JSON RPC
  3180. ErrorCodes.ParseError = -32700;
  3181. ErrorCodes.InvalidRequest = -32600;
  3182. ErrorCodes.MethodNotFound = -32601;
  3183. ErrorCodes.InvalidParams = -32602;
  3184. ErrorCodes.InternalError = -32603;
  3185. ErrorCodes.serverErrorStart = -32099;
  3186. ErrorCodes.serverErrorEnd = -32000;
  3187. ErrorCodes.ServerNotInitialized = -32002;
  3188. ErrorCodes.UnknownErrorCode = -32001;
  3189. // Defined by the protocol.
  3190. ErrorCodes.RequestCancelled = -32800;
  3191. ErrorCodes.ContentModified = -32801;
  3192. // Defined by VSCode library.
  3193. ErrorCodes.MessageWriteError = 1;
  3194. ErrorCodes.MessageReadError = 2;
  3195. })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
  3196. /**
  3197. * An error object return in a response in case a request
  3198. * has failed.
  3199. */
  3200. class ResponseError extends Error {
  3201. constructor(code, message, data) {
  3202. super(message);
  3203. this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
  3204. this.data = data;
  3205. Object.setPrototypeOf(this, ResponseError.prototype);
  3206. }
  3207. toJson() {
  3208. return {
  3209. code: this.code,
  3210. message: this.message,
  3211. data: this.data,
  3212. };
  3213. }
  3214. }
  3215. exports.ResponseError = ResponseError;
  3216. /**
  3217. * An abstract implementation of a MessageType.
  3218. */
  3219. class AbstractMessageType {
  3220. constructor(_method, _numberOfParams) {
  3221. this._method = _method;
  3222. this._numberOfParams = _numberOfParams;
  3223. }
  3224. get method() {
  3225. return this._method;
  3226. }
  3227. get numberOfParams() {
  3228. return this._numberOfParams;
  3229. }
  3230. }
  3231. exports.AbstractMessageType = AbstractMessageType;
  3232. /**
  3233. * Classes to type request response pairs
  3234. *
  3235. * The type parameter RO will be removed in the next major version
  3236. * of the JSON RPC library since it is a LSP concept and doesn't
  3237. * belong here. For now it is tagged as default never.
  3238. */
  3239. class RequestType0 extends AbstractMessageType {
  3240. constructor(method) {
  3241. super(method, 0);
  3242. }
  3243. }
  3244. exports.RequestType0 = RequestType0;
  3245. class RequestType extends AbstractMessageType {
  3246. constructor(method) {
  3247. super(method, 1);
  3248. }
  3249. }
  3250. exports.RequestType = RequestType;
  3251. class RequestType1 extends AbstractMessageType {
  3252. constructor(method) {
  3253. super(method, 1);
  3254. }
  3255. }
  3256. exports.RequestType1 = RequestType1;
  3257. class RequestType2 extends AbstractMessageType {
  3258. constructor(method) {
  3259. super(method, 2);
  3260. }
  3261. }
  3262. exports.RequestType2 = RequestType2;
  3263. class RequestType3 extends AbstractMessageType {
  3264. constructor(method) {
  3265. super(method, 3);
  3266. }
  3267. }
  3268. exports.RequestType3 = RequestType3;
  3269. class RequestType4 extends AbstractMessageType {
  3270. constructor(method) {
  3271. super(method, 4);
  3272. }
  3273. }
  3274. exports.RequestType4 = RequestType4;
  3275. class RequestType5 extends AbstractMessageType {
  3276. constructor(method) {
  3277. super(method, 5);
  3278. }
  3279. }
  3280. exports.RequestType5 = RequestType5;
  3281. class RequestType6 extends AbstractMessageType {
  3282. constructor(method) {
  3283. super(method, 6);
  3284. }
  3285. }
  3286. exports.RequestType6 = RequestType6;
  3287. class RequestType7 extends AbstractMessageType {
  3288. constructor(method) {
  3289. super(method, 7);
  3290. }
  3291. }
  3292. exports.RequestType7 = RequestType7;
  3293. class RequestType8 extends AbstractMessageType {
  3294. constructor(method) {
  3295. super(method, 8);
  3296. }
  3297. }
  3298. exports.RequestType8 = RequestType8;
  3299. class RequestType9 extends AbstractMessageType {
  3300. constructor(method) {
  3301. super(method, 9);
  3302. }
  3303. }
  3304. exports.RequestType9 = RequestType9;
  3305. /**
  3306. * The type parameter RO will be removed in the next major version
  3307. * of the JSON RPC library since it is a LSP concept and doesn't
  3308. * belong here. For now it is tagged as default never.
  3309. */
  3310. class NotificationType extends AbstractMessageType {
  3311. constructor(method) {
  3312. super(method, 1);
  3313. this._ = undefined;
  3314. }
  3315. }
  3316. exports.NotificationType = NotificationType;
  3317. class NotificationType0 extends AbstractMessageType {
  3318. constructor(method) {
  3319. super(method, 0);
  3320. }
  3321. }
  3322. exports.NotificationType0 = NotificationType0;
  3323. class NotificationType1 extends AbstractMessageType {
  3324. constructor(method) {
  3325. super(method, 1);
  3326. }
  3327. }
  3328. exports.NotificationType1 = NotificationType1;
  3329. class NotificationType2 extends AbstractMessageType {
  3330. constructor(method) {
  3331. super(method, 2);
  3332. }
  3333. }
  3334. exports.NotificationType2 = NotificationType2;
  3335. class NotificationType3 extends AbstractMessageType {
  3336. constructor(method) {
  3337. super(method, 3);
  3338. }
  3339. }
  3340. exports.NotificationType3 = NotificationType3;
  3341. class NotificationType4 extends AbstractMessageType {
  3342. constructor(method) {
  3343. super(method, 4);
  3344. }
  3345. }
  3346. exports.NotificationType4 = NotificationType4;
  3347. class NotificationType5 extends AbstractMessageType {
  3348. constructor(method) {
  3349. super(method, 5);
  3350. }
  3351. }
  3352. exports.NotificationType5 = NotificationType5;
  3353. class NotificationType6 extends AbstractMessageType {
  3354. constructor(method) {
  3355. super(method, 6);
  3356. }
  3357. }
  3358. exports.NotificationType6 = NotificationType6;
  3359. class NotificationType7 extends AbstractMessageType {
  3360. constructor(method) {
  3361. super(method, 7);
  3362. }
  3363. }
  3364. exports.NotificationType7 = NotificationType7;
  3365. class NotificationType8 extends AbstractMessageType {
  3366. constructor(method) {
  3367. super(method, 8);
  3368. }
  3369. }
  3370. exports.NotificationType8 = NotificationType8;
  3371. class NotificationType9 extends AbstractMessageType {
  3372. constructor(method) {
  3373. super(method, 9);
  3374. }
  3375. }
  3376. exports.NotificationType9 = NotificationType9;
  3377. /**
  3378. * Tests if the given message is a request message
  3379. */
  3380. function isRequestMessage(message) {
  3381. let candidate = message;
  3382. return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
  3383. }
  3384. exports.isRequestMessage = isRequestMessage;
  3385. /**
  3386. * Tests if the given message is a notification message
  3387. */
  3388. function isNotificationMessage(message) {
  3389. let candidate = message;
  3390. return candidate && is.string(candidate.method) && message.id === void 0;
  3391. }
  3392. exports.isNotificationMessage = isNotificationMessage;
  3393. /**
  3394. * Tests if the given message is a response message
  3395. */
  3396. function isResponseMessage(message) {
  3397. let candidate = message;
  3398. return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
  3399. }
  3400. exports.isResponseMessage = isResponseMessage;
  3401. /***/ }),
  3402. /* 12 */
  3403. /***/ (function(module, exports, __webpack_require__) {
  3404. "use strict";
  3405. /* --------------------------------------------------------------------------------------------
  3406. * Copyright (c) Microsoft Corporation. All rights reserved.
  3407. * Licensed under the MIT License. See License.txt in the project root for license information.
  3408. * ------------------------------------------------------------------------------------------ */
  3409. Object.defineProperty(exports, "__esModule", { value: true });
  3410. const events_1 = __webpack_require__(13);
  3411. const Is = __webpack_require__(10);
  3412. let DefaultSize = 8192;
  3413. let CR = Buffer.from('\r', 'ascii')[0];
  3414. let LF = Buffer.from('\n', 'ascii')[0];
  3415. let CRLF = '\r\n';
  3416. class MessageBuffer {
  3417. constructor(encoding = 'utf8') {
  3418. this.encoding = encoding;
  3419. this.index = 0;
  3420. this.buffer = Buffer.allocUnsafe(DefaultSize);
  3421. }
  3422. append(chunk) {
  3423. var toAppend = chunk;
  3424. if (typeof (chunk) === 'string') {
  3425. var str = chunk;
  3426. var bufferLen = Buffer.byteLength(str, this.encoding);
  3427. toAppend = Buffer.allocUnsafe(bufferLen);
  3428. toAppend.write(str, 0, bufferLen, this.encoding);
  3429. }
  3430. if (this.buffer.length - this.index >= toAppend.length) {
  3431. toAppend.copy(this.buffer, this.index, 0, toAppend.length);
  3432. }
  3433. else {
  3434. var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
  3435. if (this.index === 0) {
  3436. this.buffer = Buffer.allocUnsafe(newSize);
  3437. toAppend.copy(this.buffer, 0, 0, toAppend.length);
  3438. }
  3439. else {
  3440. this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
  3441. }
  3442. }
  3443. this.index += toAppend.length;
  3444. }
  3445. tryReadHeaders() {
  3446. let result = undefined;
  3447. let current = 0;
  3448. while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
  3449. current++;
  3450. }
  3451. // No header / body separator found (e.g CRLFCRLF)
  3452. if (current + 3 >= this.index) {
  3453. return result;
  3454. }
  3455. result = Object.create(null);
  3456. let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
  3457. headers.forEach((header) => {
  3458. let index = header.indexOf(':');
  3459. if (index === -1) {
  3460. throw new Error('Message header must separate key and value using :');
  3461. }
  3462. let key = header.substr(0, index);
  3463. let value = header.substr(index + 1).trim();
  3464. result[key] = value;
  3465. });
  3466. let nextStart = current + 4;
  3467. this.buffer = this.buffer.slice(nextStart);
  3468. this.index = this.index - nextStart;
  3469. return result;
  3470. }
  3471. tryReadContent(length) {
  3472. if (this.index < length) {
  3473. return null;
  3474. }
  3475. let result = this.buffer.toString(this.encoding, 0, length);
  3476. let nextStart = length;
  3477. this.buffer.copy(this.buffer, 0, nextStart);
  3478. this.index = this.index - nextStart;
  3479. return result;
  3480. }
  3481. get numberOfBytes() {
  3482. return this.index;
  3483. }
  3484. }
  3485. var MessageReader;
  3486. (function (MessageReader) {
  3487. function is(value) {
  3488. let candidate = value;
  3489. return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
  3490. Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
  3491. }
  3492. MessageReader.is = is;
  3493. })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
  3494. class AbstractMessageReader {
  3495. constructor() {
  3496. this.errorEmitter = new events_1.Emitter();
  3497. this.closeEmitter = new events_1.Emitter();
  3498. this.partialMessageEmitter = new events_1.Emitter();
  3499. }
  3500. dispose() {
  3501. this.errorEmitter.dispose();
  3502. this.closeEmitter.dispose();
  3503. }
  3504. get onError() {
  3505. return this.errorEmitter.event;
  3506. }
  3507. fireError(error) {
  3508. this.errorEmitter.fire(this.asError(error));
  3509. }
  3510. get onClose() {
  3511. return this.closeEmitter.event;
  3512. }
  3513. fireClose() {
  3514. this.closeEmitter.fire(undefined);
  3515. }
  3516. get onPartialMessage() {
  3517. return this.partialMessageEmitter.event;
  3518. }
  3519. firePartialMessage(info) {
  3520. this.partialMessageEmitter.fire(info);
  3521. }
  3522. asError(error) {
  3523. if (error instanceof Error) {
  3524. return error;
  3525. }
  3526. else {
  3527. return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  3528. }
  3529. }
  3530. }
  3531. exports.AbstractMessageReader = AbstractMessageReader;
  3532. class StreamMessageReader extends AbstractMessageReader {
  3533. constructor(readable, encoding = 'utf8') {
  3534. super();
  3535. this.readable = readable;
  3536. this.buffer = new MessageBuffer(encoding);
  3537. this._partialMessageTimeout = 10000;
  3538. }
  3539. set partialMessageTimeout(timeout) {
  3540. this._partialMessageTimeout = timeout;
  3541. }
  3542. get partialMessageTimeout() {
  3543. return this._partialMessageTimeout;
  3544. }
  3545. listen(callback) {
  3546. this.nextMessageLength = -1;
  3547. this.messageToken = 0;
  3548. this.partialMessageTimer = undefined;
  3549. this.callback = callback;
  3550. this.readable.on('data', (data) => {
  3551. this.onData(data);
  3552. });
  3553. this.readable.on('error', (error) => this.fireError(error));
  3554. this.readable.on('close', () => this.fireClose());
  3555. }
  3556. onData(data) {
  3557. this.buffer.append(data);
  3558. while (true) {
  3559. if (this.nextMessageLength === -1) {
  3560. let headers = this.buffer.tryReadHeaders();
  3561. if (!headers) {
  3562. return;
  3563. }
  3564. let contentLength = headers['Content-Length'];
  3565. if (!contentLength) {
  3566. throw new Error('Header must provide a Content-Length property.');
  3567. }
  3568. let length = parseInt(contentLength);
  3569. if (isNaN(length)) {
  3570. throw new Error('Content-Length value must be a number.');
  3571. }
  3572. this.nextMessageLength = length;
  3573. // Take the encoding form the header. For compatibility
  3574. // treat both utf-8 and utf8 as node utf8
  3575. }
  3576. var msg = this.buffer.tryReadContent(this.nextMessageLength);
  3577. if (msg === null) {
  3578. /** We haven't received the full message yet. */
  3579. this.setPartialMessageTimer();
  3580. return;
  3581. }
  3582. this.clearPartialMessageTimer();
  3583. this.nextMessageLength = -1;
  3584. this.messageToken++;
  3585. var json = JSON.parse(msg);
  3586. this.callback(json);
  3587. }
  3588. }
  3589. clearPartialMessageTimer() {
  3590. if (this.partialMessageTimer) {
  3591. clearTimeout(this.partialMessageTimer);
  3592. this.partialMessageTimer = undefined;
  3593. }
  3594. }
  3595. setPartialMessageTimer() {
  3596. this.clearPartialMessageTimer();
  3597. if (this._partialMessageTimeout <= 0) {
  3598. return;
  3599. }
  3600. this.partialMessageTimer = setTimeout((token, timeout) => {
  3601. this.partialMessageTimer = undefined;
  3602. if (token === this.messageToken) {
  3603. this.firePartialMessage({ messageToken: token, waitingTime: timeout });
  3604. this.setPartialMessageTimer();
  3605. }
  3606. }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
  3607. }
  3608. }
  3609. exports.StreamMessageReader = StreamMessageReader;
  3610. class IPCMessageReader extends AbstractMessageReader {
  3611. constructor(process) {
  3612. super();
  3613. this.process = process;
  3614. let eventEmitter = this.process;
  3615. eventEmitter.on('error', (error) => this.fireError(error));
  3616. eventEmitter.on('close', () => this.fireClose());
  3617. }
  3618. listen(callback) {
  3619. this.process.on('message', callback);
  3620. }
  3621. }
  3622. exports.IPCMessageReader = IPCMessageReader;
  3623. class SocketMessageReader extends StreamMessageReader {
  3624. constructor(socket, encoding = 'utf-8') {
  3625. super(socket, encoding);
  3626. }
  3627. }
  3628. exports.SocketMessageReader = SocketMessageReader;
  3629. /***/ }),
  3630. /* 13 */
  3631. /***/ (function(module, exports, __webpack_require__) {
  3632. "use strict";
  3633. /* --------------------------------------------------------------------------------------------
  3634. * Copyright (c) Microsoft Corporation. All rights reserved.
  3635. * Licensed under the MIT License. See License.txt in the project root for license information.
  3636. * ------------------------------------------------------------------------------------------ */
  3637. Object.defineProperty(exports, "__esModule", { value: true });
  3638. var Disposable;
  3639. (function (Disposable) {
  3640. function create(func) {
  3641. return {
  3642. dispose: func
  3643. };
  3644. }
  3645. Disposable.create = create;
  3646. })(Disposable = exports.Disposable || (exports.Disposable = {}));
  3647. var Event;
  3648. (function (Event) {
  3649. const _disposable = { dispose() { } };
  3650. Event.None = function () { return _disposable; };
  3651. })(Event = exports.Event || (exports.Event = {}));
  3652. class CallbackList {
  3653. add(callback, context = null, bucket) {
  3654. if (!this._callbacks) {
  3655. this._callbacks = [];
  3656. this._contexts = [];
  3657. }
  3658. this._callbacks.push(callback);
  3659. this._contexts.push(context);
  3660. if (Array.isArray(bucket)) {
  3661. bucket.push({ dispose: () => this.remove(callback, context) });
  3662. }
  3663. }
  3664. remove(callback, context = null) {
  3665. if (!this._callbacks) {
  3666. return;
  3667. }
  3668. var foundCallbackWithDifferentContext = false;
  3669. for (var i = 0, len = this._callbacks.length; i < len; i++) {
  3670. if (this._callbacks[i] === callback) {
  3671. if (this._contexts[i] === context) {
  3672. // callback & context match => remove it
  3673. this._callbacks.splice(i, 1);
  3674. this._contexts.splice(i, 1);
  3675. return;
  3676. }
  3677. else {
  3678. foundCallbackWithDifferentContext = true;
  3679. }
  3680. }
  3681. }
  3682. if (foundCallbackWithDifferentContext) {
  3683. throw new Error('When adding a listener with a context, you should remove it with the same context');
  3684. }
  3685. }
  3686. invoke(...args) {
  3687. if (!this._callbacks) {
  3688. return [];
  3689. }
  3690. var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
  3691. for (var i = 0, len = callbacks.length; i < len; i++) {
  3692. try {
  3693. ret.push(callbacks[i].apply(contexts[i], args));
  3694. }
  3695. catch (e) {
  3696. // eslint-disable-next-line no-console
  3697. console.error(e);
  3698. }
  3699. }
  3700. return ret;
  3701. }
  3702. isEmpty() {
  3703. return !this._callbacks || this._callbacks.length === 0;
  3704. }
  3705. dispose() {
  3706. this._callbacks = undefined;
  3707. this._contexts = undefined;
  3708. }
  3709. }
  3710. class Emitter {
  3711. constructor(_options) {
  3712. this._options = _options;
  3713. }
  3714. /**
  3715. * For the public to allow to subscribe
  3716. * to events from this Emitter
  3717. */
  3718. get event() {
  3719. if (!this._event) {
  3720. this._event = (listener, thisArgs, disposables) => {
  3721. if (!this._callbacks) {
  3722. this._callbacks = new CallbackList();
  3723. }
  3724. if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
  3725. this._options.onFirstListenerAdd(this);
  3726. }
  3727. this._callbacks.add(listener, thisArgs);
  3728. let result;
  3729. result = {
  3730. dispose: () => {
  3731. this._callbacks.remove(listener, thisArgs);
  3732. result.dispose = Emitter._noop;
  3733. if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
  3734. this._options.onLastListenerRemove(this);
  3735. }
  3736. }
  3737. };
  3738. if (Array.isArray(disposables)) {
  3739. disposables.push(result);
  3740. }
  3741. return result;
  3742. };
  3743. }
  3744. return this._event;
  3745. }
  3746. /**
  3747. * To be kept private to fire an event to
  3748. * subscribers
  3749. */
  3750. fire(event) {
  3751. if (this._callbacks) {
  3752. this._callbacks.invoke.call(this._callbacks, event);
  3753. }
  3754. }
  3755. dispose() {
  3756. if (this._callbacks) {
  3757. this._callbacks.dispose();
  3758. this._callbacks = undefined;
  3759. }
  3760. }
  3761. }
  3762. exports.Emitter = Emitter;
  3763. Emitter._noop = function () { };
  3764. /***/ }),
  3765. /* 14 */
  3766. /***/ (function(module, exports, __webpack_require__) {
  3767. "use strict";
  3768. /* --------------------------------------------------------------------------------------------
  3769. * Copyright (c) Microsoft Corporation. All rights reserved.
  3770. * Licensed under the MIT License. See License.txt in the project root for license information.
  3771. * ------------------------------------------------------------------------------------------ */
  3772. Object.defineProperty(exports, "__esModule", { value: true });
  3773. const events_1 = __webpack_require__(13);
  3774. const Is = __webpack_require__(10);
  3775. let ContentLength = 'Content-Length: ';
  3776. let CRLF = '\r\n';
  3777. var MessageWriter;
  3778. (function (MessageWriter) {
  3779. function is(value) {
  3780. let candidate = value;
  3781. return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
  3782. Is.func(candidate.onError) && Is.func(candidate.write);
  3783. }
  3784. MessageWriter.is = is;
  3785. })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
  3786. class AbstractMessageWriter {
  3787. constructor() {
  3788. this.errorEmitter = new events_1.Emitter();
  3789. this.closeEmitter = new events_1.Emitter();
  3790. }
  3791. dispose() {
  3792. this.errorEmitter.dispose();
  3793. this.closeEmitter.dispose();
  3794. }
  3795. get onError() {
  3796. return this.errorEmitter.event;
  3797. }
  3798. fireError(error, message, count) {
  3799. this.errorEmitter.fire([this.asError(error), message, count]);
  3800. }
  3801. get onClose() {
  3802. return this.closeEmitter.event;
  3803. }
  3804. fireClose() {
  3805. this.closeEmitter.fire(undefined);
  3806. }
  3807. asError(error) {
  3808. if (error instanceof Error) {
  3809. return error;
  3810. }
  3811. else {
  3812. return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
  3813. }
  3814. }
  3815. }
  3816. exports.AbstractMessageWriter = AbstractMessageWriter;
  3817. class StreamMessageWriter extends AbstractMessageWriter {
  3818. constructor(writable, encoding = 'utf8') {
  3819. super();
  3820. this.writable = writable;
  3821. this.encoding = encoding;
  3822. this.errorCount = 0;
  3823. this.writable.on('error', (error) => this.fireError(error));
  3824. this.writable.on('close', () => this.fireClose());
  3825. }
  3826. write(msg) {
  3827. let json = JSON.stringify(msg);
  3828. let contentLength = Buffer.byteLength(json, this.encoding);
  3829. let headers = [
  3830. ContentLength, contentLength.toString(), CRLF,
  3831. CRLF
  3832. ];
  3833. try {
  3834. // Header must be written in ASCII encoding
  3835. this.writable.write(headers.join(''), 'ascii');
  3836. // Now write the content. This can be written in any encoding
  3837. this.writable.write(json, this.encoding);
  3838. this.errorCount = 0;
  3839. }
  3840. catch (error) {
  3841. this.errorCount++;
  3842. this.fireError(error, msg, this.errorCount);
  3843. }
  3844. }
  3845. }
  3846. exports.StreamMessageWriter = StreamMessageWriter;
  3847. class IPCMessageWriter extends AbstractMessageWriter {
  3848. constructor(process) {
  3849. super();
  3850. this.process = process;
  3851. this.errorCount = 0;
  3852. this.queue = [];
  3853. this.sending = false;
  3854. let eventEmitter = this.process;
  3855. eventEmitter.on('error', (error) => this.fireError(error));
  3856. eventEmitter.on('close', () => this.fireClose);
  3857. }
  3858. write(msg) {
  3859. if (!this.sending && this.queue.length === 0) {
  3860. // See https://github.com/nodejs/node/issues/7657
  3861. this.doWriteMessage(msg);
  3862. }
  3863. else {
  3864. this.queue.push(msg);
  3865. }
  3866. }
  3867. doWriteMessage(msg) {
  3868. try {
  3869. if (this.process.send) {
  3870. this.sending = true;
  3871. this.process.send(msg, undefined, undefined, (error) => {
  3872. this.sending = false;
  3873. if (error) {
  3874. this.errorCount++;
  3875. this.fireError(error, msg, this.errorCount);
  3876. }
  3877. else {
  3878. this.errorCount = 0;
  3879. }
  3880. if (this.queue.length > 0) {
  3881. this.doWriteMessage(this.queue.shift());
  3882. }
  3883. });
  3884. }
  3885. }
  3886. catch (error) {
  3887. this.errorCount++;
  3888. this.fireError(error, msg, this.errorCount);
  3889. }
  3890. }
  3891. }
  3892. exports.IPCMessageWriter = IPCMessageWriter;
  3893. class SocketMessageWriter extends AbstractMessageWriter {
  3894. constructor(socket, encoding = 'utf8') {
  3895. super();
  3896. this.socket = socket;
  3897. this.queue = [];
  3898. this.sending = false;
  3899. this.encoding = encoding;
  3900. this.errorCount = 0;
  3901. this.socket.on('error', (error) => this.fireError(error));
  3902. this.socket.on('close', () => this.fireClose());
  3903. }
  3904. dispose() {
  3905. super.dispose();
  3906. this.socket.destroy();
  3907. }
  3908. write(msg) {
  3909. if (!this.sending && this.queue.length === 0) {
  3910. // See https://github.com/nodejs/node/issues/7657
  3911. this.doWriteMessage(msg);
  3912. }
  3913. else {
  3914. this.queue.push(msg);
  3915. }
  3916. }
  3917. doWriteMessage(msg) {
  3918. let json = JSON.stringify(msg);
  3919. let contentLength = Buffer.byteLength(json, this.encoding);
  3920. let headers = [
  3921. ContentLength, contentLength.toString(), CRLF,
  3922. CRLF
  3923. ];
  3924. try {
  3925. // Header must be written in ASCII encoding
  3926. this.sending = true;
  3927. this.socket.write(headers.join(''), 'ascii', (error) => {
  3928. if (error) {
  3929. this.handleError(error, msg);
  3930. }
  3931. try {
  3932. // Now write the content. This can be written in any encoding
  3933. this.socket.write(json, this.encoding, (error) => {
  3934. this.sending = false;
  3935. if (error) {
  3936. this.handleError(error, msg);
  3937. }
  3938. else {
  3939. this.errorCount = 0;
  3940. }
  3941. if (this.queue.length > 0) {
  3942. this.doWriteMessage(this.queue.shift());
  3943. }
  3944. });
  3945. }
  3946. catch (error) {
  3947. this.handleError(error, msg);
  3948. }
  3949. });
  3950. }
  3951. catch (error) {
  3952. this.handleError(error, msg);
  3953. }
  3954. }
  3955. handleError(error, msg) {
  3956. this.errorCount++;
  3957. this.fireError(error, msg, this.errorCount);
  3958. }
  3959. }
  3960. exports.SocketMessageWriter = SocketMessageWriter;
  3961. /***/ }),
  3962. /* 15 */
  3963. /***/ (function(module, exports, __webpack_require__) {
  3964. "use strict";
  3965. /*---------------------------------------------------------------------------------------------
  3966. * Copyright (c) Microsoft Corporation. All rights reserved.
  3967. * Licensed under the MIT License. See License.txt in the project root for license information.
  3968. *--------------------------------------------------------------------------------------------*/
  3969. Object.defineProperty(exports, "__esModule", { value: true });
  3970. const events_1 = __webpack_require__(13);
  3971. const Is = __webpack_require__(10);
  3972. var CancellationToken;
  3973. (function (CancellationToken) {
  3974. CancellationToken.None = Object.freeze({
  3975. isCancellationRequested: false,
  3976. onCancellationRequested: events_1.Event.None
  3977. });
  3978. CancellationToken.Cancelled = Object.freeze({
  3979. isCancellationRequested: true,
  3980. onCancellationRequested: events_1.Event.None
  3981. });
  3982. function is(value) {
  3983. let candidate = value;
  3984. return candidate && (candidate === CancellationToken.None
  3985. || candidate === CancellationToken.Cancelled
  3986. || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
  3987. }
  3988. CancellationToken.is = is;
  3989. })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
  3990. const shortcutEvent = Object.freeze(function (callback, context) {
  3991. let handle = setTimeout(callback.bind(context), 0);
  3992. return { dispose() { clearTimeout(handle); } };
  3993. });
  3994. class MutableToken {
  3995. constructor() {
  3996. this._isCancelled = false;
  3997. }
  3998. cancel() {
  3999. if (!this._isCancelled) {
  4000. this._isCancelled = true;
  4001. if (this._emitter) {
  4002. this._emitter.fire(undefined);
  4003. this.dispose();
  4004. }
  4005. }
  4006. }
  4007. get isCancellationRequested() {
  4008. return this._isCancelled;
  4009. }
  4010. get onCancellationRequested() {
  4011. if (this._isCancelled) {
  4012. return shortcutEvent;
  4013. }
  4014. if (!this._emitter) {
  4015. this._emitter = new events_1.Emitter();
  4016. }
  4017. return this._emitter.event;
  4018. }
  4019. dispose() {
  4020. if (this._emitter) {
  4021. this._emitter.dispose();
  4022. this._emitter = undefined;
  4023. }
  4024. }
  4025. }
  4026. class CancellationTokenSource {
  4027. get token() {
  4028. if (!this._token) {
  4029. // be lazy and create the token only when
  4030. // actually needed
  4031. this._token = new MutableToken();
  4032. }
  4033. return this._token;
  4034. }
  4035. cancel() {
  4036. if (!this._token) {
  4037. // save an object by returning the default
  4038. // cancelled token when cancellation happens
  4039. // before someone asks for the token
  4040. this._token = CancellationToken.Cancelled;
  4041. }
  4042. else {
  4043. this._token.cancel();
  4044. }
  4045. }
  4046. dispose() {
  4047. if (!this._token) {
  4048. // ensure to initialize with an empty token if we had none
  4049. this._token = CancellationToken.None;
  4050. }
  4051. else if (this._token instanceof MutableToken) {
  4052. // actually dispose
  4053. this._token.dispose();
  4054. }
  4055. }
  4056. }
  4057. exports.CancellationTokenSource = CancellationTokenSource;
  4058. /***/ }),
  4059. /* 16 */
  4060. /***/ (function(module, exports, __webpack_require__) {
  4061. "use strict";
  4062. /*---------------------------------------------------------------------------------------------
  4063. * Copyright (c) Microsoft Corporation. All rights reserved.
  4064. * Licensed under the MIT License. See License.txt in the project root for license information.
  4065. *--------------------------------------------------------------------------------------------*/
  4066. Object.defineProperty(exports, "__esModule", { value: true });
  4067. var Touch;
  4068. (function (Touch) {
  4069. Touch.None = 0;
  4070. Touch.First = 1;
  4071. Touch.Last = 2;
  4072. })(Touch = exports.Touch || (exports.Touch = {}));
  4073. class LinkedMap {
  4074. constructor() {
  4075. this._map = new Map();
  4076. this._head = undefined;
  4077. this._tail = undefined;
  4078. this._size = 0;
  4079. }
  4080. clear() {
  4081. this._map.clear();
  4082. this._head = undefined;
  4083. this._tail = undefined;
  4084. this._size = 0;
  4085. }
  4086. isEmpty() {
  4087. return !this._head && !this._tail;
  4088. }
  4089. get size() {
  4090. return this._size;
  4091. }
  4092. has(key) {
  4093. return this._map.has(key);
  4094. }
  4095. get(key) {
  4096. const item = this._map.get(key);
  4097. if (!item) {
  4098. return undefined;
  4099. }
  4100. return item.value;
  4101. }
  4102. set(key, value, touch = Touch.None) {
  4103. let item = this._map.get(key);
  4104. if (item) {
  4105. item.value = value;
  4106. if (touch !== Touch.None) {
  4107. this.touch(item, touch);
  4108. }
  4109. }
  4110. else {
  4111. item = { key, value, next: undefined, previous: undefined };
  4112. switch (touch) {
  4113. case Touch.None:
  4114. this.addItemLast(item);
  4115. break;
  4116. case Touch.First:
  4117. this.addItemFirst(item);
  4118. break;
  4119. case Touch.Last:
  4120. this.addItemLast(item);
  4121. break;
  4122. default:
  4123. this.addItemLast(item);
  4124. break;
  4125. }
  4126. this._map.set(key, item);
  4127. this._size++;
  4128. }
  4129. }
  4130. delete(key) {
  4131. const item = this._map.get(key);
  4132. if (!item) {
  4133. return false;
  4134. }
  4135. this._map.delete(key);
  4136. this.removeItem(item);
  4137. this._size--;
  4138. return true;
  4139. }
  4140. shift() {
  4141. if (!this._head && !this._tail) {
  4142. return undefined;
  4143. }
  4144. if (!this._head || !this._tail) {
  4145. throw new Error('Invalid list');
  4146. }
  4147. const item = this._head;
  4148. this._map.delete(item.key);
  4149. this.removeItem(item);
  4150. this._size--;
  4151. return item.value;
  4152. }
  4153. forEach(callbackfn, thisArg) {
  4154. let current = this._head;
  4155. while (current) {
  4156. if (thisArg) {
  4157. callbackfn.bind(thisArg)(current.value, current.key, this);
  4158. }
  4159. else {
  4160. callbackfn(current.value, current.key, this);
  4161. }
  4162. current = current.next;
  4163. }
  4164. }
  4165. forEachReverse(callbackfn, thisArg) {
  4166. let current = this._tail;
  4167. while (current) {
  4168. if (thisArg) {
  4169. callbackfn.bind(thisArg)(current.value, current.key, this);
  4170. }
  4171. else {
  4172. callbackfn(current.value, current.key, this);
  4173. }
  4174. current = current.previous;
  4175. }
  4176. }
  4177. values() {
  4178. let result = [];
  4179. let current = this._head;
  4180. while (current) {
  4181. result.push(current.value);
  4182. current = current.next;
  4183. }
  4184. return result;
  4185. }
  4186. keys() {
  4187. let result = [];
  4188. let current = this._head;
  4189. while (current) {
  4190. result.push(current.key);
  4191. current = current.next;
  4192. }
  4193. return result;
  4194. }
  4195. /* JSON RPC run on es5 which has no Symbol.iterator
  4196. public keys(): IterableIterator<K> {
  4197. let current = this._head;
  4198. let iterator: IterableIterator<K> = {
  4199. [Symbol.iterator]() {
  4200. return iterator;
  4201. },
  4202. next():IteratorResult<K> {
  4203. if (current) {
  4204. let result = { value: current.key, done: false };
  4205. current = current.next;
  4206. return result;
  4207. } else {
  4208. return { value: undefined, done: true };
  4209. }
  4210. }
  4211. };
  4212. return iterator;
  4213. }
  4214. public values(): IterableIterator<V> {
  4215. let current = this._head;
  4216. let iterator: IterableIterator<V> = {
  4217. [Symbol.iterator]() {
  4218. return iterator;
  4219. },
  4220. next():IteratorResult<V> {
  4221. if (current) {
  4222. let result = { value: current.value, done: false };
  4223. current = current.next;
  4224. return result;
  4225. } else {
  4226. return { value: undefined, done: true };
  4227. }
  4228. }
  4229. };
  4230. return iterator;
  4231. }
  4232. */
  4233. addItemFirst(item) {
  4234. // First time Insert
  4235. if (!this._head && !this._tail) {
  4236. this._tail = item;
  4237. }
  4238. else if (!this._head) {
  4239. throw new Error('Invalid list');
  4240. }
  4241. else {
  4242. item.next = this._head;
  4243. this._head.previous = item;
  4244. }
  4245. this._head = item;
  4246. }
  4247. addItemLast(item) {
  4248. // First time Insert
  4249. if (!this._head && !this._tail) {
  4250. this._head = item;
  4251. }
  4252. else if (!this._tail) {
  4253. throw new Error('Invalid list');
  4254. }
  4255. else {
  4256. item.previous = this._tail;
  4257. this._tail.next = item;
  4258. }
  4259. this._tail = item;
  4260. }
  4261. removeItem(item) {
  4262. if (item === this._head && item === this._tail) {
  4263. this._head = undefined;
  4264. this._tail = undefined;
  4265. }
  4266. else if (item === this._head) {
  4267. this._head = item.next;
  4268. }
  4269. else if (item === this._tail) {
  4270. this._tail = item.previous;
  4271. }
  4272. else {
  4273. const next = item.next;
  4274. const previous = item.previous;
  4275. if (!next || !previous) {
  4276. throw new Error('Invalid list');
  4277. }
  4278. next.previous = previous;
  4279. previous.next = next;
  4280. }
  4281. }
  4282. touch(item, touch) {
  4283. if (!this._head || !this._tail) {
  4284. throw new Error('Invalid list');
  4285. }
  4286. if ((touch !== Touch.First && touch !== Touch.Last)) {
  4287. return;
  4288. }
  4289. if (touch === Touch.First) {
  4290. if (item === this._head) {
  4291. return;
  4292. }
  4293. const next = item.next;
  4294. const previous = item.previous;
  4295. // Unlink the item
  4296. if (item === this._tail) {
  4297. // previous must be defined since item was not head but is tail
  4298. // So there are more than on item in the map
  4299. previous.next = undefined;
  4300. this._tail = previous;
  4301. }
  4302. else {
  4303. // Both next and previous are not undefined since item was neither head nor tail.
  4304. next.previous = previous;
  4305. previous.next = next;
  4306. }
  4307. // Insert the node at head
  4308. item.previous = undefined;
  4309. item.next = this._head;
  4310. this._head.previous = item;
  4311. this._head = item;
  4312. }
  4313. else if (touch === Touch.Last) {
  4314. if (item === this._tail) {
  4315. return;
  4316. }
  4317. const next = item.next;
  4318. const previous = item.previous;
  4319. // Unlink the item.
  4320. if (item === this._head) {
  4321. // next must be defined since item was not tail but is head
  4322. // So there are more than on item in the map
  4323. next.previous = undefined;
  4324. this._head = next;
  4325. }
  4326. else {
  4327. // Both next and previous are not undefined since item was neither head nor tail.
  4328. next.previous = previous;
  4329. previous.next = next;
  4330. }
  4331. item.next = undefined;
  4332. item.previous = this._tail;
  4333. this._tail.next = item;
  4334. this._tail = item;
  4335. }
  4336. }
  4337. }
  4338. exports.LinkedMap = LinkedMap;
  4339. /***/ }),
  4340. /* 17 */
  4341. /***/ (function(module, exports, __webpack_require__) {
  4342. "use strict";
  4343. /* --------------------------------------------------------------------------------------------
  4344. * Copyright (c) Microsoft Corporation. All rights reserved.
  4345. * Licensed under the MIT License. See License.txt in the project root for license information.
  4346. * ------------------------------------------------------------------------------------------ */
  4347. Object.defineProperty(exports, "__esModule", { value: true });
  4348. const path_1 = __webpack_require__(4);
  4349. const os_1 = __webpack_require__(2);
  4350. const crypto_1 = __webpack_require__(18);
  4351. const net_1 = __webpack_require__(19);
  4352. const messageReader_1 = __webpack_require__(12);
  4353. const messageWriter_1 = __webpack_require__(14);
  4354. function generateRandomPipeName() {
  4355. const randomSuffix = crypto_1.randomBytes(21).toString('hex');
  4356. if (process.platform === 'win32') {
  4357. return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
  4358. }
  4359. else {
  4360. // Mac/Unix: use socket file
  4361. return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
  4362. }
  4363. }
  4364. exports.generateRandomPipeName = generateRandomPipeName;
  4365. function createClientPipeTransport(pipeName, encoding = 'utf-8') {
  4366. let connectResolve;
  4367. let connected = new Promise((resolve, _reject) => {
  4368. connectResolve = resolve;
  4369. });
  4370. return new Promise((resolve, reject) => {
  4371. let server = net_1.createServer((socket) => {
  4372. server.close();
  4373. connectResolve([
  4374. new messageReader_1.SocketMessageReader(socket, encoding),
  4375. new messageWriter_1.SocketMessageWriter(socket, encoding)
  4376. ]);
  4377. });
  4378. server.on('error', reject);
  4379. server.listen(pipeName, () => {
  4380. server.removeListener('error', reject);
  4381. resolve({
  4382. onConnected: () => { return connected; }
  4383. });
  4384. });
  4385. });
  4386. }
  4387. exports.createClientPipeTransport = createClientPipeTransport;
  4388. function createServerPipeTransport(pipeName, encoding = 'utf-8') {
  4389. const socket = net_1.createConnection(pipeName);
  4390. return [
  4391. new messageReader_1.SocketMessageReader(socket, encoding),
  4392. new messageWriter_1.SocketMessageWriter(socket, encoding)
  4393. ];
  4394. }
  4395. exports.createServerPipeTransport = createServerPipeTransport;
  4396. /***/ }),
  4397. /* 18 */
  4398. /***/ (function(module, exports) {
  4399. module.exports = require("crypto");
  4400. /***/ }),
  4401. /* 19 */
  4402. /***/ (function(module, exports) {
  4403. module.exports = require("net");
  4404. /***/ }),
  4405. /* 20 */
  4406. /***/ (function(module, exports, __webpack_require__) {
  4407. "use strict";
  4408. /* --------------------------------------------------------------------------------------------
  4409. * Copyright (c) Microsoft Corporation. All rights reserved.
  4410. * Licensed under the MIT License. See License.txt in the project root for license information.
  4411. * ------------------------------------------------------------------------------------------ */
  4412. Object.defineProperty(exports, "__esModule", { value: true });
  4413. const net_1 = __webpack_require__(19);
  4414. const messageReader_1 = __webpack_require__(12);
  4415. const messageWriter_1 = __webpack_require__(14);
  4416. function createClientSocketTransport(port, encoding = 'utf-8') {
  4417. let connectResolve;
  4418. let connected = new Promise((resolve, _reject) => {
  4419. connectResolve = resolve;
  4420. });
  4421. return new Promise((resolve, reject) => {
  4422. let server = net_1.createServer((socket) => {
  4423. server.close();
  4424. connectResolve([
  4425. new messageReader_1.SocketMessageReader(socket, encoding),
  4426. new messageWriter_1.SocketMessageWriter(socket, encoding)
  4427. ]);
  4428. });
  4429. server.on('error', reject);
  4430. server.listen(port, '127.0.0.1', () => {
  4431. server.removeListener('error', reject);
  4432. resolve({
  4433. onConnected: () => { return connected; }
  4434. });
  4435. });
  4436. });
  4437. }
  4438. exports.createClientSocketTransport = createClientSocketTransport;
  4439. function createServerSocketTransport(port, encoding = 'utf-8') {
  4440. const socket = net_1.createConnection(port, '127.0.0.1');
  4441. return [
  4442. new messageReader_1.SocketMessageReader(socket, encoding),
  4443. new messageWriter_1.SocketMessageWriter(socket, encoding)
  4444. ];
  4445. }
  4446. exports.createServerSocketTransport = createServerSocketTransport;
  4447. /***/ }),
  4448. /* 21 */
  4449. /***/ (function(module, exports, __webpack_require__) {
  4450. "use strict";
  4451. /* --------------------------------------------------------------------------------------------
  4452. * Copyright (c) Microsoft Corporation. All rights reserved.
  4453. * Licensed under the MIT License. See License.txt in the project root for license information.
  4454. * ------------------------------------------------------------------------------------------ */
  4455. Object.defineProperty(exports, "__esModule", { value: true });
  4456. const Is = __webpack_require__(22);
  4457. const vscode_jsonrpc_1 = __webpack_require__(9);
  4458. const messages_1 = __webpack_require__(23);
  4459. const protocol_implementation_1 = __webpack_require__(24);
  4460. exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
  4461. const protocol_typeDefinition_1 = __webpack_require__(25);
  4462. exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
  4463. const protocol_workspaceFolders_1 = __webpack_require__(26);
  4464. exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
  4465. exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
  4466. const protocol_configuration_1 = __webpack_require__(27);
  4467. exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
  4468. const protocol_colorProvider_1 = __webpack_require__(28);
  4469. exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
  4470. exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
  4471. const protocol_foldingRange_1 = __webpack_require__(29);
  4472. exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
  4473. const protocol_declaration_1 = __webpack_require__(30);
  4474. exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
  4475. const protocol_selectionRange_1 = __webpack_require__(31);
  4476. exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
  4477. const protocol_progress_1 = __webpack_require__(32);
  4478. exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
  4479. exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
  4480. exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
  4481. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  4482. let __noDynamicImport;
  4483. /**
  4484. * The DocumentFilter namespace provides helper functions to work with
  4485. * [DocumentFilter](#DocumentFilter) literals.
  4486. */
  4487. var DocumentFilter;
  4488. (function (DocumentFilter) {
  4489. function is(value) {
  4490. const candidate = value;
  4491. return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
  4492. }
  4493. DocumentFilter.is = is;
  4494. })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
  4495. /**
  4496. * The DocumentSelector namespace provides helper functions to work with
  4497. * [DocumentSelector](#DocumentSelector)s.
  4498. */
  4499. var DocumentSelector;
  4500. (function (DocumentSelector) {
  4501. function is(value) {
  4502. if (!Array.isArray(value)) {
  4503. return false;
  4504. }
  4505. for (let elem of value) {
  4506. if (!Is.string(elem) && !DocumentFilter.is(elem)) {
  4507. return false;
  4508. }
  4509. }
  4510. return true;
  4511. }
  4512. DocumentSelector.is = is;
  4513. })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
  4514. /**
  4515. * The `client/registerCapability` request is sent from the server to the client to register a new capability
  4516. * handler on the client side.
  4517. */
  4518. var RegistrationRequest;
  4519. (function (RegistrationRequest) {
  4520. RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
  4521. })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
  4522. /**
  4523. * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
  4524. * handler on the client side.
  4525. */
  4526. var UnregistrationRequest;
  4527. (function (UnregistrationRequest) {
  4528. UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
  4529. })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
  4530. var ResourceOperationKind;
  4531. (function (ResourceOperationKind) {
  4532. /**
  4533. * Supports creating new files and folders.
  4534. */
  4535. ResourceOperationKind.Create = 'create';
  4536. /**
  4537. * Supports renaming existing files and folders.
  4538. */
  4539. ResourceOperationKind.Rename = 'rename';
  4540. /**
  4541. * Supports deleting existing files and folders.
  4542. */
  4543. ResourceOperationKind.Delete = 'delete';
  4544. })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
  4545. var FailureHandlingKind;
  4546. (function (FailureHandlingKind) {
  4547. /**
  4548. * Applying the workspace change is simply aborted if one of the changes provided
  4549. * fails. All operations executed before the failing operation stay executed.
  4550. */
  4551. FailureHandlingKind.Abort = 'abort';
  4552. /**
  4553. * All operations are executed transactional. That means they either all
  4554. * succeed or no changes at all are applied to the workspace.
  4555. */
  4556. FailureHandlingKind.Transactional = 'transactional';
  4557. /**
  4558. * If the workspace edit contains only textual file changes they are executed transactional.
  4559. * If resource changes (create, rename or delete file) are part of the change the failure
  4560. * handling startegy is abort.
  4561. */
  4562. FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
  4563. /**
  4564. * The client tries to undo the operations already executed. But there is no
  4565. * guarantee that this is succeeding.
  4566. */
  4567. FailureHandlingKind.Undo = 'undo';
  4568. })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
  4569. /**
  4570. * The StaticRegistrationOptions namespace provides helper functions to work with
  4571. * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
  4572. */
  4573. var StaticRegistrationOptions;
  4574. (function (StaticRegistrationOptions) {
  4575. function hasId(value) {
  4576. const candidate = value;
  4577. return candidate && Is.string(candidate.id) && candidate.id.length > 0;
  4578. }
  4579. StaticRegistrationOptions.hasId = hasId;
  4580. })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
  4581. /**
  4582. * The TextDocumentRegistrationOptions namespace provides helper functions to work with
  4583. * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
  4584. */
  4585. var TextDocumentRegistrationOptions;
  4586. (function (TextDocumentRegistrationOptions) {
  4587. function is(value) {
  4588. const candidate = value;
  4589. return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
  4590. }
  4591. TextDocumentRegistrationOptions.is = is;
  4592. })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
  4593. /**
  4594. * The WorkDoneProgressOptions namespace provides helper functions to work with
  4595. * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
  4596. */
  4597. var WorkDoneProgressOptions;
  4598. (function (WorkDoneProgressOptions) {
  4599. function is(value) {
  4600. const candidate = value;
  4601. return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
  4602. }
  4603. WorkDoneProgressOptions.is = is;
  4604. function hasWorkDoneProgress(value) {
  4605. const candidate = value;
  4606. return candidate && Is.boolean(candidate.workDoneProgress);
  4607. }
  4608. WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
  4609. })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
  4610. /**
  4611. * The initialize request is sent from the client to the server.
  4612. * It is sent once as the request after starting up the server.
  4613. * The requests parameter is of type [InitializeParams](#InitializeParams)
  4614. * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
  4615. * resolves to such.
  4616. */
  4617. var InitializeRequest;
  4618. (function (InitializeRequest) {
  4619. InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
  4620. })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
  4621. /**
  4622. * Known error codes for an `InitializeError`;
  4623. */
  4624. var InitializeError;
  4625. (function (InitializeError) {
  4626. /**
  4627. * If the protocol version provided by the client can't be handled by the server.
  4628. * @deprecated This initialize error got replaced by client capabilities. There is
  4629. * no version handshake in version 3.0x
  4630. */
  4631. InitializeError.unknownProtocolVersion = 1;
  4632. })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
  4633. /**
  4634. * The intialized notification is sent from the client to the
  4635. * server after the client is fully initialized and the server
  4636. * is allowed to send requests from the server to the client.
  4637. */
  4638. var InitializedNotification;
  4639. (function (InitializedNotification) {
  4640. InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
  4641. })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
  4642. //---- Shutdown Method ----
  4643. /**
  4644. * A shutdown request is sent from the client to the server.
  4645. * It is sent once when the client decides to shutdown the
  4646. * server. The only notification that is sent after a shutdown request
  4647. * is the exit event.
  4648. */
  4649. var ShutdownRequest;
  4650. (function (ShutdownRequest) {
  4651. ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
  4652. })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
  4653. //---- Exit Notification ----
  4654. /**
  4655. * The exit event is sent from the client to the server to
  4656. * ask the server to exit its process.
  4657. */
  4658. var ExitNotification;
  4659. (function (ExitNotification) {
  4660. ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
  4661. })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
  4662. /**
  4663. * The configuration change notification is sent from the client to the server
  4664. * when the client's configuration has changed. The notification contains
  4665. * the changed configuration as defined by the language client.
  4666. */
  4667. var DidChangeConfigurationNotification;
  4668. (function (DidChangeConfigurationNotification) {
  4669. DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
  4670. })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
  4671. //---- Message show and log notifications ----
  4672. /**
  4673. * The message type
  4674. */
  4675. var MessageType;
  4676. (function (MessageType) {
  4677. /**
  4678. * An error message.
  4679. */
  4680. MessageType.Error = 1;
  4681. /**
  4682. * A warning message.
  4683. */
  4684. MessageType.Warning = 2;
  4685. /**
  4686. * An information message.
  4687. */
  4688. MessageType.Info = 3;
  4689. /**
  4690. * A log message.
  4691. */
  4692. MessageType.Log = 4;
  4693. })(MessageType = exports.MessageType || (exports.MessageType = {}));
  4694. /**
  4695. * The show message notification is sent from a server to a client to ask
  4696. * the client to display a particular message in the user interface.
  4697. */
  4698. var ShowMessageNotification;
  4699. (function (ShowMessageNotification) {
  4700. ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
  4701. })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
  4702. /**
  4703. * The show message request is sent from the server to the client to show a message
  4704. * and a set of options actions to the user.
  4705. */
  4706. var ShowMessageRequest;
  4707. (function (ShowMessageRequest) {
  4708. ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
  4709. })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
  4710. /**
  4711. * The log message notification is sent from the server to the client to ask
  4712. * the client to log a particular message.
  4713. */
  4714. var LogMessageNotification;
  4715. (function (LogMessageNotification) {
  4716. LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
  4717. })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
  4718. //---- Telemetry notification
  4719. /**
  4720. * The telemetry event notification is sent from the server to the client to ask
  4721. * the client to log telemetry data.
  4722. */
  4723. var TelemetryEventNotification;
  4724. (function (TelemetryEventNotification) {
  4725. TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
  4726. })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
  4727. /**
  4728. * Defines how the host (editor) should sync
  4729. * document changes to the language server.
  4730. */
  4731. var TextDocumentSyncKind;
  4732. (function (TextDocumentSyncKind) {
  4733. /**
  4734. * Documents should not be synced at all.
  4735. */
  4736. TextDocumentSyncKind.None = 0;
  4737. /**
  4738. * Documents are synced by always sending the full content
  4739. * of the document.
  4740. */
  4741. TextDocumentSyncKind.Full = 1;
  4742. /**
  4743. * Documents are synced by sending the full content on open.
  4744. * After that only incremental updates to the document are
  4745. * send.
  4746. */
  4747. TextDocumentSyncKind.Incremental = 2;
  4748. })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
  4749. /**
  4750. * The document open notification is sent from the client to the server to signal
  4751. * newly opened text documents. The document's truth is now managed by the client
  4752. * and the server must not try to read the document's truth using the document's
  4753. * uri. Open in this sense means it is managed by the client. It doesn't necessarily
  4754. * mean that its content is presented in an editor. An open notification must not
  4755. * be sent more than once without a corresponding close notification send before.
  4756. * This means open and close notification must be balanced and the max open count
  4757. * is one.
  4758. */
  4759. var DidOpenTextDocumentNotification;
  4760. (function (DidOpenTextDocumentNotification) {
  4761. DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
  4762. DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
  4763. })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
  4764. /**
  4765. * The document change notification is sent from the client to the server to signal
  4766. * changes to a text document.
  4767. */
  4768. var DidChangeTextDocumentNotification;
  4769. (function (DidChangeTextDocumentNotification) {
  4770. DidChangeTextDocumentNotification.method = 'textDocument/didChange';
  4771. DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
  4772. })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
  4773. /**
  4774. * The document close notification is sent from the client to the server when
  4775. * the document got closed in the client. The document's truth now exists where
  4776. * the document's uri points to (e.g. if the document's uri is a file uri the
  4777. * truth now exists on disk). As with the open notification the close notification
  4778. * is about managing the document's content. Receiving a close notification
  4779. * doesn't mean that the document was open in an editor before. A close
  4780. * notification requires a previous open notification to be sent.
  4781. */
  4782. var DidCloseTextDocumentNotification;
  4783. (function (DidCloseTextDocumentNotification) {
  4784. DidCloseTextDocumentNotification.method = 'textDocument/didClose';
  4785. DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
  4786. })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
  4787. /**
  4788. * The document save notification is sent from the client to the server when
  4789. * the document got saved in the client.
  4790. */
  4791. var DidSaveTextDocumentNotification;
  4792. (function (DidSaveTextDocumentNotification) {
  4793. DidSaveTextDocumentNotification.method = 'textDocument/didSave';
  4794. DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
  4795. })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
  4796. /**
  4797. * Represents reasons why a text document is saved.
  4798. */
  4799. var TextDocumentSaveReason;
  4800. (function (TextDocumentSaveReason) {
  4801. /**
  4802. * Manually triggered, e.g. by the user pressing save, by starting debugging,
  4803. * or by an API call.
  4804. */
  4805. TextDocumentSaveReason.Manual = 1;
  4806. /**
  4807. * Automatic after a delay.
  4808. */
  4809. TextDocumentSaveReason.AfterDelay = 2;
  4810. /**
  4811. * When the editor lost focus.
  4812. */
  4813. TextDocumentSaveReason.FocusOut = 3;
  4814. })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
  4815. /**
  4816. * A document will save notification is sent from the client to the server before
  4817. * the document is actually saved.
  4818. */
  4819. var WillSaveTextDocumentNotification;
  4820. (function (WillSaveTextDocumentNotification) {
  4821. WillSaveTextDocumentNotification.method = 'textDocument/willSave';
  4822. WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
  4823. })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
  4824. /**
  4825. * A document will save request is sent from the client to the server before
  4826. * the document is actually saved. The request can return an array of TextEdits
  4827. * which will be applied to the text document before it is saved. Please note that
  4828. * clients might drop results if computing the text edits took too long or if a
  4829. * server constantly fails on this request. This is done to keep the save fast and
  4830. * reliable.
  4831. */
  4832. var WillSaveTextDocumentWaitUntilRequest;
  4833. (function (WillSaveTextDocumentWaitUntilRequest) {
  4834. WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
  4835. WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
  4836. })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
  4837. /**
  4838. * The watched files notification is sent from the client to the server when
  4839. * the client detects changes to file watched by the language client.
  4840. */
  4841. var DidChangeWatchedFilesNotification;
  4842. (function (DidChangeWatchedFilesNotification) {
  4843. DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
  4844. })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
  4845. /**
  4846. * The file event type
  4847. */
  4848. var FileChangeType;
  4849. (function (FileChangeType) {
  4850. /**
  4851. * The file got created.
  4852. */
  4853. FileChangeType.Created = 1;
  4854. /**
  4855. * The file got changed.
  4856. */
  4857. FileChangeType.Changed = 2;
  4858. /**
  4859. * The file got deleted.
  4860. */
  4861. FileChangeType.Deleted = 3;
  4862. })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
  4863. var WatchKind;
  4864. (function (WatchKind) {
  4865. /**
  4866. * Interested in create events.
  4867. */
  4868. WatchKind.Create = 1;
  4869. /**
  4870. * Interested in change events
  4871. */
  4872. WatchKind.Change = 2;
  4873. /**
  4874. * Interested in delete events
  4875. */
  4876. WatchKind.Delete = 4;
  4877. })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
  4878. /**
  4879. * Diagnostics notification are sent from the server to the client to signal
  4880. * results of validation runs.
  4881. */
  4882. var PublishDiagnosticsNotification;
  4883. (function (PublishDiagnosticsNotification) {
  4884. PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
  4885. })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
  4886. /**
  4887. * How a completion was triggered
  4888. */
  4889. var CompletionTriggerKind;
  4890. (function (CompletionTriggerKind) {
  4891. /**
  4892. * Completion was triggered by typing an identifier (24x7 code
  4893. * complete), manual invocation (e.g Ctrl+Space) or via API.
  4894. */
  4895. CompletionTriggerKind.Invoked = 1;
  4896. /**
  4897. * Completion was triggered by a trigger character specified by
  4898. * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
  4899. */
  4900. CompletionTriggerKind.TriggerCharacter = 2;
  4901. /**
  4902. * Completion was re-triggered as current completion list is incomplete
  4903. */
  4904. CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
  4905. })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
  4906. /**
  4907. * Request to request completion at a given text document position. The request's
  4908. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
  4909. * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
  4910. * or a Thenable that resolves to such.
  4911. *
  4912. * The request can delay the computation of the [`detail`](#CompletionItem.detail)
  4913. * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
  4914. * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
  4915. * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
  4916. */
  4917. var CompletionRequest;
  4918. (function (CompletionRequest) {
  4919. CompletionRequest.method = 'textDocument/completion';
  4920. CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
  4921. /** @deprecated Use CompletionRequest.type */
  4922. CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4923. })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
  4924. /**
  4925. * Request to resolve additional information for a given completion item.The request's
  4926. * parameter is of type [CompletionItem](#CompletionItem) the response
  4927. * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
  4928. */
  4929. var CompletionResolveRequest;
  4930. (function (CompletionResolveRequest) {
  4931. CompletionResolveRequest.method = 'completionItem/resolve';
  4932. CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
  4933. })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
  4934. /**
  4935. * Request to request hover information at a given text document position. The request's
  4936. * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
  4937. * type [Hover](#Hover) or a Thenable that resolves to such.
  4938. */
  4939. var HoverRequest;
  4940. (function (HoverRequest) {
  4941. HoverRequest.method = 'textDocument/hover';
  4942. HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
  4943. })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
  4944. /**
  4945. * How a signature help was triggered.
  4946. *
  4947. * @since 3.15.0
  4948. */
  4949. var SignatureHelpTriggerKind;
  4950. (function (SignatureHelpTriggerKind) {
  4951. /**
  4952. * Signature help was invoked manually by the user or by a command.
  4953. */
  4954. SignatureHelpTriggerKind.Invoked = 1;
  4955. /**
  4956. * Signature help was triggered by a trigger character.
  4957. */
  4958. SignatureHelpTriggerKind.TriggerCharacter = 2;
  4959. /**
  4960. * Signature help was triggered by the cursor moving or by the document content changing.
  4961. */
  4962. SignatureHelpTriggerKind.ContentChange = 3;
  4963. })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
  4964. var SignatureHelpRequest;
  4965. (function (SignatureHelpRequest) {
  4966. SignatureHelpRequest.method = 'textDocument/signatureHelp';
  4967. SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
  4968. })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
  4969. /**
  4970. * A request to resolve the definition location of a symbol at a given text
  4971. * document position. The request's parameter is of type [TextDocumentPosition]
  4972. * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
  4973. * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
  4974. * to such.
  4975. */
  4976. var DefinitionRequest;
  4977. (function (DefinitionRequest) {
  4978. DefinitionRequest.method = 'textDocument/definition';
  4979. DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
  4980. /** @deprecated Use DefinitionRequest.type */
  4981. DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4982. })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
  4983. /**
  4984. * A request to resolve project-wide references for the symbol denoted
  4985. * by the given text document position. The request's parameter is of
  4986. * type [ReferenceParams](#ReferenceParams) the response is of type
  4987. * [Location[]](#Location) or a Thenable that resolves to such.
  4988. */
  4989. var ReferencesRequest;
  4990. (function (ReferencesRequest) {
  4991. ReferencesRequest.method = 'textDocument/references';
  4992. ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
  4993. /** @deprecated Use ReferencesRequest.type */
  4994. ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  4995. })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
  4996. /**
  4997. * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
  4998. * text document position. The request's parameter is of type [TextDocumentPosition]
  4999. * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
  5000. * (#DocumentHighlight) or a Thenable that resolves to such.
  5001. */
  5002. var DocumentHighlightRequest;
  5003. (function (DocumentHighlightRequest) {
  5004. DocumentHighlightRequest.method = 'textDocument/documentHighlight';
  5005. DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
  5006. /** @deprecated Use DocumentHighlightRequest.type */
  5007. DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5008. })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
  5009. /**
  5010. * A request to list all symbols found in a given text document. The request's
  5011. * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
  5012. * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
  5013. * that resolves to such.
  5014. */
  5015. var DocumentSymbolRequest;
  5016. (function (DocumentSymbolRequest) {
  5017. DocumentSymbolRequest.method = 'textDocument/documentSymbol';
  5018. DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
  5019. /** @deprecated Use DocumentSymbolRequest.type */
  5020. DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5021. })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
  5022. /**
  5023. * A request to provide commands for the given text document and range.
  5024. */
  5025. var CodeActionRequest;
  5026. (function (CodeActionRequest) {
  5027. CodeActionRequest.method = 'textDocument/codeAction';
  5028. CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
  5029. /** @deprecated Use CodeActionRequest.type */
  5030. CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5031. })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
  5032. /**
  5033. * A request to list project-wide symbols matching the query string given
  5034. * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
  5035. * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
  5036. * resolves to such.
  5037. */
  5038. var WorkspaceSymbolRequest;
  5039. (function (WorkspaceSymbolRequest) {
  5040. WorkspaceSymbolRequest.method = 'workspace/symbol';
  5041. WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
  5042. /** @deprecated Use WorkspaceSymbolRequest.type */
  5043. WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5044. })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
  5045. /**
  5046. * A request to provide code lens for the given text document.
  5047. */
  5048. var CodeLensRequest;
  5049. (function (CodeLensRequest) {
  5050. CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
  5051. /** @deprecated Use CodeLensRequest.type */
  5052. CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5053. })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
  5054. /**
  5055. * A request to resolve a command for a given code lens.
  5056. */
  5057. var CodeLensResolveRequest;
  5058. (function (CodeLensResolveRequest) {
  5059. CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
  5060. })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
  5061. /**
  5062. * A request to provide document links
  5063. */
  5064. var DocumentLinkRequest;
  5065. (function (DocumentLinkRequest) {
  5066. DocumentLinkRequest.method = 'textDocument/documentLink';
  5067. DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
  5068. /** @deprecated Use DocumentLinkRequest.type */
  5069. DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5070. })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
  5071. /**
  5072. * Request to resolve additional information for a given document link. The request's
  5073. * parameter is of type [DocumentLink](#DocumentLink) the response
  5074. * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
  5075. */
  5076. var DocumentLinkResolveRequest;
  5077. (function (DocumentLinkResolveRequest) {
  5078. DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
  5079. })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
  5080. /**
  5081. * A request to to format a whole document.
  5082. */
  5083. var DocumentFormattingRequest;
  5084. (function (DocumentFormattingRequest) {
  5085. DocumentFormattingRequest.method = 'textDocument/formatting';
  5086. DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
  5087. })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
  5088. /**
  5089. * A request to to format a range in a document.
  5090. */
  5091. var DocumentRangeFormattingRequest;
  5092. (function (DocumentRangeFormattingRequest) {
  5093. DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
  5094. DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
  5095. })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
  5096. /**
  5097. * A request to format a document on type.
  5098. */
  5099. var DocumentOnTypeFormattingRequest;
  5100. (function (DocumentOnTypeFormattingRequest) {
  5101. DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
  5102. DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
  5103. })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
  5104. /**
  5105. * A request to rename a symbol.
  5106. */
  5107. var RenameRequest;
  5108. (function (RenameRequest) {
  5109. RenameRequest.method = 'textDocument/rename';
  5110. RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
  5111. })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
  5112. /**
  5113. * A request to test and perform the setup necessary for a rename.
  5114. */
  5115. var PrepareRenameRequest;
  5116. (function (PrepareRenameRequest) {
  5117. PrepareRenameRequest.method = 'textDocument/prepareRename';
  5118. PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
  5119. })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
  5120. /**
  5121. * A request send from the client to the server to execute a command. The request might return
  5122. * a workspace edit which the client will apply to the workspace.
  5123. */
  5124. var ExecuteCommandRequest;
  5125. (function (ExecuteCommandRequest) {
  5126. ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
  5127. })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
  5128. /**
  5129. * A request sent from the server to the client to modified certain resources.
  5130. */
  5131. var ApplyWorkspaceEditRequest;
  5132. (function (ApplyWorkspaceEditRequest) {
  5133. ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
  5134. })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
  5135. /***/ }),
  5136. /* 22 */
  5137. /***/ (function(module, exports, __webpack_require__) {
  5138. "use strict";
  5139. /* --------------------------------------------------------------------------------------------
  5140. * Copyright (c) Microsoft Corporation. All rights reserved.
  5141. * Licensed under the MIT License. See License.txt in the project root for license information.
  5142. * ------------------------------------------------------------------------------------------ */
  5143. Object.defineProperty(exports, "__esModule", { value: true });
  5144. function boolean(value) {
  5145. return value === true || value === false;
  5146. }
  5147. exports.boolean = boolean;
  5148. function string(value) {
  5149. return typeof value === 'string' || value instanceof String;
  5150. }
  5151. exports.string = string;
  5152. function number(value) {
  5153. return typeof value === 'number' || value instanceof Number;
  5154. }
  5155. exports.number = number;
  5156. function error(value) {
  5157. return value instanceof Error;
  5158. }
  5159. exports.error = error;
  5160. function func(value) {
  5161. return typeof value === 'function';
  5162. }
  5163. exports.func = func;
  5164. function array(value) {
  5165. return Array.isArray(value);
  5166. }
  5167. exports.array = array;
  5168. function stringArray(value) {
  5169. return array(value) && value.every(elem => string(elem));
  5170. }
  5171. exports.stringArray = stringArray;
  5172. function typedArray(value, check) {
  5173. return Array.isArray(value) && value.every(check);
  5174. }
  5175. exports.typedArray = typedArray;
  5176. function objectLiteral(value) {
  5177. // Strictly speaking class instances pass this check as well. Since the LSP
  5178. // doesn't use classes we ignore this for now. If we do we need to add something
  5179. // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
  5180. return value !== null && typeof value === 'object';
  5181. }
  5182. exports.objectLiteral = objectLiteral;
  5183. /***/ }),
  5184. /* 23 */
  5185. /***/ (function(module, exports, __webpack_require__) {
  5186. "use strict";
  5187. /* --------------------------------------------------------------------------------------------
  5188. * Copyright (c) Microsoft Corporation. All rights reserved.
  5189. * Licensed under the MIT License. See License.txt in the project root for license information.
  5190. * ------------------------------------------------------------------------------------------ */
  5191. Object.defineProperty(exports, "__esModule", { value: true });
  5192. const vscode_jsonrpc_1 = __webpack_require__(9);
  5193. class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
  5194. constructor(method) {
  5195. super(method);
  5196. }
  5197. }
  5198. exports.ProtocolRequestType0 = ProtocolRequestType0;
  5199. class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
  5200. constructor(method) {
  5201. super(method);
  5202. }
  5203. }
  5204. exports.ProtocolRequestType = ProtocolRequestType;
  5205. class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
  5206. constructor(method) {
  5207. super(method);
  5208. }
  5209. }
  5210. exports.ProtocolNotificationType = ProtocolNotificationType;
  5211. class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
  5212. constructor(method) {
  5213. super(method);
  5214. }
  5215. }
  5216. exports.ProtocolNotificationType0 = ProtocolNotificationType0;
  5217. /***/ }),
  5218. /* 24 */
  5219. /***/ (function(module, exports, __webpack_require__) {
  5220. "use strict";
  5221. /* --------------------------------------------------------------------------------------------
  5222. * Copyright (c) Microsoft Corporation. All rights reserved.
  5223. * Licensed under the MIT License. See License.txt in the project root for license information.
  5224. * ------------------------------------------------------------------------------------------ */
  5225. Object.defineProperty(exports, "__esModule", { value: true });
  5226. const vscode_jsonrpc_1 = __webpack_require__(9);
  5227. const messages_1 = __webpack_require__(23);
  5228. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5229. let __noDynamicImport;
  5230. /**
  5231. * A request to resolve the implementation locations of a symbol at a given text
  5232. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5233. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  5234. * Thenable that resolves to such.
  5235. */
  5236. var ImplementationRequest;
  5237. (function (ImplementationRequest) {
  5238. ImplementationRequest.method = 'textDocument/implementation';
  5239. ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
  5240. /** @deprecated Use ImplementationRequest.type */
  5241. ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5242. })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
  5243. /***/ }),
  5244. /* 25 */
  5245. /***/ (function(module, exports, __webpack_require__) {
  5246. "use strict";
  5247. /* --------------------------------------------------------------------------------------------
  5248. * Copyright (c) Microsoft Corporation. All rights reserved.
  5249. * Licensed under the MIT License. See License.txt in the project root for license information.
  5250. * ------------------------------------------------------------------------------------------ */
  5251. Object.defineProperty(exports, "__esModule", { value: true });
  5252. const vscode_jsonrpc_1 = __webpack_require__(9);
  5253. const messages_1 = __webpack_require__(23);
  5254. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5255. let __noDynamicImport;
  5256. /**
  5257. * A request to resolve the type definition locations of a symbol at a given text
  5258. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5259. * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
  5260. * Thenable that resolves to such.
  5261. */
  5262. var TypeDefinitionRequest;
  5263. (function (TypeDefinitionRequest) {
  5264. TypeDefinitionRequest.method = 'textDocument/typeDefinition';
  5265. TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
  5266. /** @deprecated Use TypeDefinitionRequest.type */
  5267. TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5268. })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
  5269. /***/ }),
  5270. /* 26 */
  5271. /***/ (function(module, exports, __webpack_require__) {
  5272. "use strict";
  5273. /* --------------------------------------------------------------------------------------------
  5274. * Copyright (c) Microsoft Corporation. All rights reserved.
  5275. * Licensed under the MIT License. See License.txt in the project root for license information.
  5276. * ------------------------------------------------------------------------------------------ */
  5277. Object.defineProperty(exports, "__esModule", { value: true });
  5278. const messages_1 = __webpack_require__(23);
  5279. /**
  5280. * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
  5281. */
  5282. var WorkspaceFoldersRequest;
  5283. (function (WorkspaceFoldersRequest) {
  5284. WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
  5285. })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
  5286. /**
  5287. * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
  5288. * folder configuration changes.
  5289. */
  5290. var DidChangeWorkspaceFoldersNotification;
  5291. (function (DidChangeWorkspaceFoldersNotification) {
  5292. DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
  5293. })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
  5294. /***/ }),
  5295. /* 27 */
  5296. /***/ (function(module, exports, __webpack_require__) {
  5297. "use strict";
  5298. /* --------------------------------------------------------------------------------------------
  5299. * Copyright (c) Microsoft Corporation. All rights reserved.
  5300. * Licensed under the MIT License. See License.txt in the project root for license information.
  5301. * ------------------------------------------------------------------------------------------ */
  5302. Object.defineProperty(exports, "__esModule", { value: true });
  5303. const messages_1 = __webpack_require__(23);
  5304. /**
  5305. * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
  5306. * configuration setting.
  5307. *
  5308. * This pull model replaces the old push model were the client signaled configuration change via an
  5309. * event. If the server still needs to react to configuration changes (since the server caches the
  5310. * result of `workspace/configuration` requests) the server should register for an empty configuration
  5311. * change event and empty the cache if such an event is received.
  5312. */
  5313. var ConfigurationRequest;
  5314. (function (ConfigurationRequest) {
  5315. ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
  5316. })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
  5317. /***/ }),
  5318. /* 28 */
  5319. /***/ (function(module, exports, __webpack_require__) {
  5320. "use strict";
  5321. /* --------------------------------------------------------------------------------------------
  5322. * Copyright (c) Microsoft Corporation. All rights reserved.
  5323. * Licensed under the MIT License. See License.txt in the project root for license information.
  5324. * ------------------------------------------------------------------------------------------ */
  5325. Object.defineProperty(exports, "__esModule", { value: true });
  5326. const vscode_jsonrpc_1 = __webpack_require__(9);
  5327. const messages_1 = __webpack_require__(23);
  5328. /**
  5329. * A request to list all color symbols found in a given text document. The request's
  5330. * parameter is of type [DocumentColorParams](#DocumentColorParams) the
  5331. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  5332. * that resolves to such.
  5333. */
  5334. var DocumentColorRequest;
  5335. (function (DocumentColorRequest) {
  5336. DocumentColorRequest.method = 'textDocument/documentColor';
  5337. DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
  5338. /** @deprecated Use DocumentColorRequest.type */
  5339. DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5340. })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
  5341. /**
  5342. * A request to list all presentation for a color. The request's
  5343. * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
  5344. * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
  5345. * that resolves to such.
  5346. */
  5347. var ColorPresentationRequest;
  5348. (function (ColorPresentationRequest) {
  5349. ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
  5350. })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
  5351. /***/ }),
  5352. /* 29 */
  5353. /***/ (function(module, exports, __webpack_require__) {
  5354. "use strict";
  5355. /*---------------------------------------------------------------------------------------------
  5356. * Copyright (c) Microsoft Corporation. All rights reserved.
  5357. * Licensed under the MIT License. See License.txt in the project root for license information.
  5358. *--------------------------------------------------------------------------------------------*/
  5359. Object.defineProperty(exports, "__esModule", { value: true });
  5360. const vscode_jsonrpc_1 = __webpack_require__(9);
  5361. const messages_1 = __webpack_require__(23);
  5362. /**
  5363. * Enum of known range kinds
  5364. */
  5365. var FoldingRangeKind;
  5366. (function (FoldingRangeKind) {
  5367. /**
  5368. * Folding range for a comment
  5369. */
  5370. FoldingRangeKind["Comment"] = "comment";
  5371. /**
  5372. * Folding range for a imports or includes
  5373. */
  5374. FoldingRangeKind["Imports"] = "imports";
  5375. /**
  5376. * Folding range for a region (e.g. `#region`)
  5377. */
  5378. FoldingRangeKind["Region"] = "region";
  5379. })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
  5380. /**
  5381. * A request to provide folding ranges in a document. The request's
  5382. * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
  5383. * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
  5384. * that resolves to such.
  5385. */
  5386. var FoldingRangeRequest;
  5387. (function (FoldingRangeRequest) {
  5388. FoldingRangeRequest.method = 'textDocument/foldingRange';
  5389. FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
  5390. /** @deprecated Use FoldingRangeRequest.type */
  5391. FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5392. })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
  5393. /***/ }),
  5394. /* 30 */
  5395. /***/ (function(module, exports, __webpack_require__) {
  5396. "use strict";
  5397. /* --------------------------------------------------------------------------------------------
  5398. * Copyright (c) Microsoft Corporation. All rights reserved.
  5399. * Licensed under the MIT License. See License.txt in the project root for license information.
  5400. * ------------------------------------------------------------------------------------------ */
  5401. Object.defineProperty(exports, "__esModule", { value: true });
  5402. const vscode_jsonrpc_1 = __webpack_require__(9);
  5403. const messages_1 = __webpack_require__(23);
  5404. // @ts-ignore: to avoid inlining LocatioLink as dynamic import
  5405. let __noDynamicImport;
  5406. /**
  5407. * A request to resolve the type definition locations of a symbol at a given text
  5408. * document position. The request's parameter is of type [TextDocumentPositioParams]
  5409. * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
  5410. * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
  5411. * to such.
  5412. */
  5413. var DeclarationRequest;
  5414. (function (DeclarationRequest) {
  5415. DeclarationRequest.method = 'textDocument/declaration';
  5416. DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
  5417. /** @deprecated Use DeclarationRequest.type */
  5418. DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5419. })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
  5420. /***/ }),
  5421. /* 31 */
  5422. /***/ (function(module, exports, __webpack_require__) {
  5423. "use strict";
  5424. /*---------------------------------------------------------------------------------------------
  5425. * Copyright (c) Microsoft Corporation. All rights reserved.
  5426. * Licensed under the MIT License. See License.txt in the project root for license information.
  5427. *--------------------------------------------------------------------------------------------*/
  5428. Object.defineProperty(exports, "__esModule", { value: true });
  5429. const vscode_jsonrpc_1 = __webpack_require__(9);
  5430. const messages_1 = __webpack_require__(23);
  5431. /**
  5432. * A request to provide selection ranges in a document. The request's
  5433. * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
  5434. * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
  5435. * that resolves to such.
  5436. */
  5437. var SelectionRangeRequest;
  5438. (function (SelectionRangeRequest) {
  5439. SelectionRangeRequest.method = 'textDocument/selectionRange';
  5440. SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
  5441. /** @deprecated Use SelectionRangeRequest.type */
  5442. SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
  5443. })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
  5444. /***/ }),
  5445. /* 32 */
  5446. /***/ (function(module, exports, __webpack_require__) {
  5447. "use strict";
  5448. /* --------------------------------------------------------------------------------------------
  5449. * Copyright (c) Microsoft Corporation. All rights reserved.
  5450. * Licensed under the MIT License. See License.txt in the project root for license information.
  5451. * ------------------------------------------------------------------------------------------ */
  5452. Object.defineProperty(exports, "__esModule", { value: true });
  5453. const vscode_jsonrpc_1 = __webpack_require__(9);
  5454. const messages_1 = __webpack_require__(23);
  5455. var WorkDoneProgress;
  5456. (function (WorkDoneProgress) {
  5457. WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
  5458. })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
  5459. /**
  5460. * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
  5461. * reporting from the server.
  5462. */
  5463. var WorkDoneProgressCreateRequest;
  5464. (function (WorkDoneProgressCreateRequest) {
  5465. WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
  5466. })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
  5467. /**
  5468. * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
  5469. * initiated on the server side.
  5470. */
  5471. var WorkDoneProgressCancelNotification;
  5472. (function (WorkDoneProgressCancelNotification) {
  5473. WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
  5474. })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
  5475. /***/ }),
  5476. /* 33 */
  5477. /***/ (function(module, exports, __webpack_require__) {
  5478. "use strict";
  5479. /* --------------------------------------------------------------------------------------------
  5480. * Copyright (c) TypeFox and others. All rights reserved.
  5481. * Licensed under the MIT License. See License.txt in the project root for license information.
  5482. * ------------------------------------------------------------------------------------------ */
  5483. Object.defineProperty(exports, "__esModule", { value: true });
  5484. const messages_1 = __webpack_require__(23);
  5485. /**
  5486. * A request to result a `CallHierarchyItem` in a document at a given position.
  5487. * Can be used as an input to a incoming or outgoing call hierarchy.
  5488. *
  5489. * @since 3.16.0 - Proposed state
  5490. */
  5491. var CallHierarchyPrepareRequest;
  5492. (function (CallHierarchyPrepareRequest) {
  5493. CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
  5494. CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
  5495. })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
  5496. /**
  5497. * A request to resolve the incoming calls for a given `CallHierarchyItem`.
  5498. *
  5499. * @since 3.16.0 - Proposed state
  5500. */
  5501. var CallHierarchyIncomingCallsRequest;
  5502. (function (CallHierarchyIncomingCallsRequest) {
  5503. CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
  5504. CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
  5505. })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
  5506. /**
  5507. * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
  5508. *
  5509. * @since 3.16.0 - Proposed state
  5510. */
  5511. var CallHierarchyOutgoingCallsRequest;
  5512. (function (CallHierarchyOutgoingCallsRequest) {
  5513. CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
  5514. CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
  5515. })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
  5516. /***/ }),
  5517. /* 34 */
  5518. /***/ (function(module, exports, __webpack_require__) {
  5519. "use strict";
  5520. /* --------------------------------------------------------------------------------------------
  5521. * Copyright (c) Microsoft Corporation. All rights reserved.
  5522. * Licensed under the MIT License. See License.txt in the project root for license information.
  5523. * ------------------------------------------------------------------------------------------ */
  5524. Object.defineProperty(exports, "__esModule", { value: true });
  5525. const messages_1 = __webpack_require__(23);
  5526. /**
  5527. * A set of predefined token types. This set is not fixed
  5528. * an clients can specify additional token types via the
  5529. * corresponding client capabilities.
  5530. *
  5531. * @since 3.16.0 - Proposed state
  5532. */
  5533. var SemanticTokenTypes;
  5534. (function (SemanticTokenTypes) {
  5535. SemanticTokenTypes["comment"] = "comment";
  5536. SemanticTokenTypes["keyword"] = "keyword";
  5537. SemanticTokenTypes["string"] = "string";
  5538. SemanticTokenTypes["number"] = "number";
  5539. SemanticTokenTypes["regexp"] = "regexp";
  5540. SemanticTokenTypes["operator"] = "operator";
  5541. SemanticTokenTypes["namespace"] = "namespace";
  5542. SemanticTokenTypes["type"] = "type";
  5543. SemanticTokenTypes["struct"] = "struct";
  5544. SemanticTokenTypes["class"] = "class";
  5545. SemanticTokenTypes["interface"] = "interface";
  5546. SemanticTokenTypes["enum"] = "enum";
  5547. SemanticTokenTypes["typeParameter"] = "typeParameter";
  5548. SemanticTokenTypes["function"] = "function";
  5549. SemanticTokenTypes["member"] = "member";
  5550. SemanticTokenTypes["property"] = "property";
  5551. SemanticTokenTypes["macro"] = "macro";
  5552. SemanticTokenTypes["variable"] = "variable";
  5553. SemanticTokenTypes["parameter"] = "parameter";
  5554. SemanticTokenTypes["label"] = "label";
  5555. })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
  5556. /**
  5557. * A set of predefined token modifiers. This set is not fixed
  5558. * an clients can specify additional token types via the
  5559. * corresponding client capabilities.
  5560. *
  5561. * @since 3.16.0 - Proposed state
  5562. */
  5563. var SemanticTokenModifiers;
  5564. (function (SemanticTokenModifiers) {
  5565. SemanticTokenModifiers["documentation"] = "documentation";
  5566. SemanticTokenModifiers["declaration"] = "declaration";
  5567. SemanticTokenModifiers["definition"] = "definition";
  5568. SemanticTokenModifiers["reference"] = "reference";
  5569. SemanticTokenModifiers["static"] = "static";
  5570. SemanticTokenModifiers["abstract"] = "abstract";
  5571. SemanticTokenModifiers["deprecated"] = "deprecated";
  5572. SemanticTokenModifiers["async"] = "async";
  5573. SemanticTokenModifiers["volatile"] = "volatile";
  5574. SemanticTokenModifiers["readonly"] = "readonly";
  5575. })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
  5576. /**
  5577. * @since 3.16.0 - Proposed state
  5578. */
  5579. var SemanticTokens;
  5580. (function (SemanticTokens) {
  5581. function is(value) {
  5582. const candidate = value;
  5583. return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
  5584. Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
  5585. }
  5586. SemanticTokens.is = is;
  5587. })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
  5588. /**
  5589. * @since 3.16.0 - Proposed state
  5590. */
  5591. var SemanticTokensRequest;
  5592. (function (SemanticTokensRequest) {
  5593. SemanticTokensRequest.method = 'textDocument/semanticTokens';
  5594. SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
  5595. })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
  5596. /**
  5597. * @since 3.16.0 - Proposed state
  5598. */
  5599. var SemanticTokensEditsRequest;
  5600. (function (SemanticTokensEditsRequest) {
  5601. SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
  5602. SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
  5603. })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
  5604. /**
  5605. * @since 3.16.0 - Proposed state
  5606. */
  5607. var SemanticTokensRangeRequest;
  5608. (function (SemanticTokensRangeRequest) {
  5609. SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
  5610. SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
  5611. })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
  5612. /***/ }),
  5613. /* 35 */
  5614. /***/ (function(module, exports, __webpack_require__) {
  5615. "use strict";
  5616. var __importDefault = (this && this.__importDefault) || function (mod) {
  5617. return (mod && mod.__esModule) ? mod : { "default": mod };
  5618. };
  5619. Object.defineProperty(exports, "__esModule", { value: true });
  5620. /******************************************************************
  5621. MIT License http://www.opensource.org/licenses/mit-license.php
  5622. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  5623. *******************************************************************/
  5624. const coc_nvim_1 = __webpack_require__(1);
  5625. const path_1 = __importDefault(__webpack_require__(4));
  5626. const vscode_languageserver_protocol_1 = __webpack_require__(8);
  5627. const types_1 = __webpack_require__(36);
  5628. const util_1 = __webpack_require__(37);
  5629. class ProviderManager {
  5630. constructor() {
  5631. this.providers = new Map();
  5632. }
  5633. regist(provider, name) {
  5634. this.providers.set(name, provider);
  5635. return vscode_languageserver_protocol_1.Disposable.create(() => {
  5636. this.providers.delete(name);
  5637. });
  5638. }
  5639. get hasProvider() {
  5640. return this.providers.size > 0;
  5641. }
  5642. async init() {
  5643. let providers = Array.from(this.providers.values());
  5644. await Promise.all(providers.map(provider => {
  5645. return provider.init();
  5646. }));
  5647. }
  5648. async getSnippets(filetype) {
  5649. let names = Array.from(this.providers.keys());
  5650. let list = [];
  5651. for (let name of names) {
  5652. let provider = this.providers.get(name);
  5653. let snippets = await provider.getSnippets(filetype);
  5654. snippets.map(s => s.provider = name);
  5655. list.push(...snippets);
  5656. }
  5657. return list;
  5658. }
  5659. async getSnippetFiles(filetype) {
  5660. let files = [];
  5661. for (let provider of this.providers.values()) {
  5662. let res = await provider.getSnippetFiles(filetype);
  5663. files = files.concat(res);
  5664. }
  5665. return files;
  5666. }
  5667. async getTriggerSnippets(autoTrigger = false) {
  5668. let bufnr = await coc_nvim_1.workspace.nvim.call('bufnr', '%');
  5669. let doc = coc_nvim_1.workspace.getDocument(bufnr);
  5670. if (!doc)
  5671. return [];
  5672. await doc.patchChange();
  5673. let position = await coc_nvim_1.workspace.getCursorPosition();
  5674. let names = Array.from(this.providers.keys());
  5675. let list = [];
  5676. for (let name of names) {
  5677. let provider = this.providers.get(name);
  5678. let items = await provider.getTriggerSnippets(doc, position, autoTrigger);
  5679. for (let item of items) {
  5680. if (list.findIndex(o => o.prefix == item.prefix) == -1) {
  5681. list.push(item);
  5682. }
  5683. }
  5684. }
  5685. list.sort((a, b) => b.priority - a.priority);
  5686. if (list.length > 1 && list[0].priority > 0) {
  5687. list = list.filter(o => o.priority > 0);
  5688. }
  5689. return list;
  5690. }
  5691. async provideCompletionItems(document, position, _token, context) {
  5692. let doc = coc_nvim_1.workspace.getDocument(document.uri);
  5693. if (!doc)
  5694. return [];
  5695. let snippets = await this.getSnippets(doc.filetype);
  5696. let currline = doc.getline(position.line, true);
  5697. let { input, col } = context.option;
  5698. let character = characterIndex(currline, col);
  5699. let before_content = currline.slice(0, character);
  5700. let res = [];
  5701. let contextPrefixes = [];
  5702. for (let snip of snippets) {
  5703. let contentBehind = before_content;
  5704. if (contextPrefixes.indexOf(snip.prefix) !== -1)
  5705. continue;
  5706. if (snip.regex != null && snip.prefix == '')
  5707. continue;
  5708. if (snip.context) {
  5709. let provider = this.providers.get(snip.provider);
  5710. let valid = await provider.checkContext(snip.context);
  5711. if (!valid)
  5712. continue;
  5713. contextPrefixes.push(snip.prefix);
  5714. }
  5715. let head = this.getPrefixHead(doc, snip.prefix);
  5716. if (input.length == 0 && !before_content.endsWith(snip.prefix))
  5717. continue;
  5718. let item = {
  5719. label: snip.prefix,
  5720. kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
  5721. filterText: snip.prefix,
  5722. detail: snip.description,
  5723. insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet
  5724. };
  5725. item.data = {
  5726. snip,
  5727. provider: snip.provider,
  5728. filepath: `${path_1.default.basename(snip.filepath)}:${snip.lnum}`
  5729. };
  5730. if (snip.regex) {
  5731. if (!input.length || snip.prefix && input[0] != snip.prefix[0])
  5732. continue;
  5733. let content = before_content + snip.prefix;
  5734. let ms = content.match(snip.regex);
  5735. if (!ms)
  5736. continue;
  5737. }
  5738. else if (head && before_content.endsWith(head)) {
  5739. contentBehind = before_content.slice(0, -head.length);
  5740. let prefix = snip.prefix.slice(head.length);
  5741. Object.assign(item, {
  5742. textEdit: {
  5743. range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - head.length }, position),
  5744. newText: prefix
  5745. }
  5746. });
  5747. }
  5748. else if (input.length == 0) {
  5749. let { prefix } = snip;
  5750. contentBehind = before_content.slice(0, -prefix.length);
  5751. Object.assign(item, {
  5752. preselect: true,
  5753. textEdit: {
  5754. range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - prefix.length }, position),
  5755. newText: prefix
  5756. }
  5757. });
  5758. }
  5759. if (snip.triggerKind == types_1.TriggerKind.LineBegin && contentBehind.trim().length)
  5760. continue;
  5761. if (snip.triggerKind == types_1.TriggerKind.SpaceBefore) {
  5762. if (contentBehind.length && !/\s/.test(contentBehind[contentBehind.length - 1])) {
  5763. continue;
  5764. }
  5765. }
  5766. if (!item.textEdit) {
  5767. item.textEdit = {
  5768. range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character }, position),
  5769. newText: item.label
  5770. };
  5771. }
  5772. item.data.location = `${snip.filepath}:${snip.lnum}`;
  5773. item.data.line = contentBehind + snip.prefix;
  5774. res.push(item);
  5775. }
  5776. return res;
  5777. }
  5778. async resolveCompletionItem(item) {
  5779. let provider = this.providers.get(item.data.provider);
  5780. if (provider) {
  5781. let filetype = await coc_nvim_1.workspace.nvim.eval('&filetype');
  5782. let insertSnippet = await provider.resolveSnippetBody(item.data.snip, item.textEdit.range, item.data.line);
  5783. item.textEdit.newText = insertSnippet;
  5784. if (coc_nvim_1.snippetManager) {
  5785. let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(insertSnippet));
  5786. item.documentation = {
  5787. kind: 'markdown',
  5788. value: util_1.markdownBlock(snip.toString(), filetype)
  5789. };
  5790. }
  5791. }
  5792. return item;
  5793. }
  5794. getPrefixHead(doc, prefix) {
  5795. let res = 0;
  5796. for (let idx = prefix.length - 1; idx >= 0; idx--) {
  5797. if (!doc.isWord(prefix[idx])) {
  5798. res = idx;
  5799. break;
  5800. }
  5801. }
  5802. return res == 0 ? '' : prefix.slice(0, res + 1);
  5803. }
  5804. }
  5805. exports.ProviderManager = ProviderManager;
  5806. function characterIndex(content, byteIndex) {
  5807. let buf = Buffer.from(content, 'utf8');
  5808. return buf.slice(0, byteIndex).toString('utf8').length;
  5809. }
  5810. exports.characterIndex = characterIndex;
  5811. /***/ }),
  5812. /* 36 */
  5813. /***/ (function(module, exports, __webpack_require__) {
  5814. "use strict";
  5815. Object.defineProperty(exports, "__esModule", { value: true });
  5816. var TriggerKind;
  5817. (function (TriggerKind) {
  5818. TriggerKind[TriggerKind["SpaceBefore"] = 0] = "SpaceBefore";
  5819. TriggerKind[TriggerKind["LineBegin"] = 1] = "LineBegin";
  5820. TriggerKind[TriggerKind["WordBoundary"] = 2] = "WordBoundary";
  5821. TriggerKind[TriggerKind["InWord"] = 3] = "InWord";
  5822. })(TriggerKind = exports.TriggerKind || (exports.TriggerKind = {}));
  5823. /***/ }),
  5824. /* 37 */
  5825. /***/ (function(module, exports, __webpack_require__) {
  5826. "use strict";
  5827. var __importDefault = (this && this.__importDefault) || function (mod) {
  5828. return (mod && mod.__esModule) ? mod : { "default": mod };
  5829. };
  5830. Object.defineProperty(exports, "__esModule", { value: true });
  5831. /******************************************************************
  5832. MIT License http://www.opensource.org/licenses/mit-license.php
  5833. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  5834. *******************************************************************/
  5835. const pify_1 = __importDefault(__webpack_require__(38));
  5836. const fs_1 = __importDefault(__webpack_require__(3));
  5837. const crypto_1 = __importDefault(__webpack_require__(18));
  5838. const BASE64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
  5839. function tostr(bytes) {
  5840. let r = [];
  5841. let i;
  5842. for (i = 0; i < bytes.length; i++) {
  5843. r.push(BASE64[bytes[i] % 64]);
  5844. }
  5845. return r.join('');
  5846. }
  5847. function uid() {
  5848. return tostr(crypto_1.default.randomBytes(10));
  5849. }
  5850. exports.uid = uid;
  5851. function replaceText(content, items) {
  5852. let res = '';
  5853. items.sort((a, b) => a.index - b.index);
  5854. let item = items.shift();
  5855. for (let i = 0; i < content.length; i++) {
  5856. let idx = item ? item.index : null;
  5857. if (idx == null || i != idx) {
  5858. res = res + content[i];
  5859. continue;
  5860. }
  5861. res = res + item.newText;
  5862. i = i + item.length;
  5863. }
  5864. return res;
  5865. }
  5866. exports.replaceText = replaceText;
  5867. function flatten(arr) {
  5868. return arr.reduce((p, curr) => p.concat(curr), []);
  5869. }
  5870. exports.flatten = flatten;
  5871. async function statAsync(filepath) {
  5872. try {
  5873. return await pify_1.default(fs_1.default.stat)(filepath);
  5874. }
  5875. catch (e) {
  5876. return null;
  5877. }
  5878. }
  5879. exports.statAsync = statAsync;
  5880. async function writeFileAsync(fullpath, content) {
  5881. await pify_1.default(fs_1.default.writeFile)(fullpath, content, 'utf8');
  5882. }
  5883. exports.writeFileAsync = writeFileAsync;
  5884. async function readFileAsync(fullpath, encoding = 'utf8') {
  5885. return await pify_1.default(fs_1.default.readFile)(fullpath, encoding);
  5886. }
  5887. exports.readFileAsync = readFileAsync;
  5888. async function readdirAsync(filepath) {
  5889. try {
  5890. return await pify_1.default(fs_1.default.readdir)(filepath);
  5891. }
  5892. catch (e) {
  5893. return null;
  5894. }
  5895. }
  5896. exports.readdirAsync = readdirAsync;
  5897. function headTail(line) {
  5898. line = line.trim();
  5899. let ms = line.match(/^(\S+)\s+(.*)/);
  5900. if (!ms)
  5901. return [line, ''];
  5902. return [ms[1], ms[2]];
  5903. }
  5904. exports.headTail = headTail;
  5905. function memorize(_target, key, descriptor) {
  5906. let fn = descriptor.get;
  5907. if (typeof fn !== 'function')
  5908. return;
  5909. let memoKey = '$' + key;
  5910. descriptor.get = function (...args) {
  5911. if (this.hasOwnProperty(memoKey))
  5912. return Promise.resolve(this[memoKey]);
  5913. return new Promise((resolve, reject) => {
  5914. Promise.resolve(fn.apply(this, args)).then(res => {
  5915. this[memoKey] = res;
  5916. resolve(res);
  5917. }, e => {
  5918. reject(e);
  5919. });
  5920. });
  5921. };
  5922. }
  5923. exports.memorize = memorize;
  5924. function trimQuote(str) {
  5925. if (str.startsWith('"') || str.startsWith("'"))
  5926. return str.slice(1, -1);
  5927. return str;
  5928. }
  5929. exports.trimQuote = trimQuote;
  5930. function distinct(array, keyFn) {
  5931. if (!keyFn) {
  5932. return array.filter((element, position) => {
  5933. return array.indexOf(element) === position;
  5934. });
  5935. }
  5936. const seen = Object.create(null);
  5937. return array.filter(elem => {
  5938. const key = keyFn(elem);
  5939. if (seen[key]) {
  5940. return false;
  5941. }
  5942. seen[key] = true;
  5943. return true;
  5944. });
  5945. }
  5946. exports.distinct = distinct;
  5947. const conditionRe = /\(\?\(\?:\w+\).+\|/;
  5948. const bellRe = /\\a/;
  5949. const commentRe = /\(\?#.*?\)/;
  5950. const stringStartRe = /\\A/;
  5951. const namedCaptureRe = /\(\?P<\w+>.*?\)/;
  5952. const namedReferenceRe = /\(\?P=(\w+)\)/;
  5953. const braceRe = /\^\]/;
  5954. const regex = new RegExp(`${bellRe.source}|${commentRe.source}|${stringStartRe.source}|${namedCaptureRe.source}|${namedReferenceRe.source}|${braceRe}`, 'g');
  5955. /**
  5956. * Convert python regex to javascript regex,
  5957. * throw error when unsupported pattern found
  5958. *
  5959. * @public
  5960. * @param {string} str
  5961. * @returns {string}
  5962. */
  5963. function convertRegex(str) {
  5964. if (str.indexOf('\\z') !== -1) {
  5965. throw new Error('pattern \\z not supported');
  5966. }
  5967. if (str.indexOf('(?s)') !== -1) {
  5968. throw new Error('pattern (?s) not supported');
  5969. }
  5970. if (str.indexOf('(?x)') !== -1) {
  5971. throw new Error('pattern (?x) not supported');
  5972. }
  5973. if (str.indexOf('\n') !== -1) {
  5974. throw new Error('multiple line pattern not supported');
  5975. }
  5976. if (conditionRe.test(str)) {
  5977. throw new Error('condition pattern not supported');
  5978. }
  5979. return str.replace(regex, (match, p1) => {
  5980. if (match == '^]')
  5981. return '^\\]';
  5982. if (match == '\\a')
  5983. return '';
  5984. if (match.startsWith('(?#'))
  5985. return '';
  5986. if (match == '\\A')
  5987. return '^';
  5988. if (match.startsWith('(?P<'))
  5989. return '(?' + match.slice(3);
  5990. if (match.startsWith('(?P='))
  5991. return `\\k<${p1}>`;
  5992. return '';
  5993. });
  5994. }
  5995. exports.convertRegex = convertRegex;
  5996. function wait(ms) {
  5997. return new Promise(resolve => {
  5998. setTimeout(() => {
  5999. resolve();
  6000. }, ms);
  6001. });
  6002. }
  6003. exports.wait = wait;
  6004. function getRegexText(prefix) {
  6005. if (prefix.startsWith('^'))
  6006. prefix = prefix.slice(1);
  6007. if (prefix.endsWith('$'))
  6008. prefix = prefix.slice(0, -1);
  6009. let content = prefix.replace(/\(.*\)\??/g, '');
  6010. content = content.replace(/\\/g, '');
  6011. return content;
  6012. }
  6013. exports.getRegexText = getRegexText;
  6014. function markdownBlock(code, filetype) {
  6015. filetype = filetype == 'javascriptreact' ? 'javascript' : filetype;
  6016. filetype = filetype == 'typescriptreact' ? 'typescript' : filetype;
  6017. return '``` ' + filetype + '\n' + code + '\n```';
  6018. }
  6019. exports.markdownBlock = markdownBlock;
  6020. /***/ }),
  6021. /* 38 */
  6022. /***/ (function(module, exports, __webpack_require__) {
  6023. "use strict";
  6024. const processFn = (fn, options, proxy, unwrapped) => function (...arguments_) {
  6025. const P = options.promiseModule;
  6026. return new P((resolve, reject) => {
  6027. if (options.multiArgs) {
  6028. arguments_.push((...result) => {
  6029. if (options.errorFirst) {
  6030. if (result[0]) {
  6031. reject(result);
  6032. } else {
  6033. result.shift();
  6034. resolve(result);
  6035. }
  6036. } else {
  6037. resolve(result);
  6038. }
  6039. });
  6040. } else if (options.errorFirst) {
  6041. arguments_.push((error, result) => {
  6042. if (error) {
  6043. reject(error);
  6044. } else {
  6045. resolve(result);
  6046. }
  6047. });
  6048. } else {
  6049. arguments_.push(resolve);
  6050. }
  6051. const self = this === proxy ? unwrapped : this;
  6052. Reflect.apply(fn, self, arguments_);
  6053. });
  6054. };
  6055. const filterCache = new WeakMap();
  6056. module.exports = (input, options) => {
  6057. options = {
  6058. exclude: [/.+(?:Sync|Stream)$/],
  6059. errorFirst: true,
  6060. promiseModule: Promise,
  6061. ...options
  6062. };
  6063. const objectType = typeof input;
  6064. if (!(input !== null && (objectType === 'object' || objectType === 'function'))) {
  6065. throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objectType}\``);
  6066. }
  6067. const filter = (target, key) => {
  6068. let cached = filterCache.get(target);
  6069. if (!cached) {
  6070. cached = {};
  6071. filterCache.set(target, cached);
  6072. }
  6073. if (key in cached) {
  6074. return cached[key];
  6075. }
  6076. const match = pattern => (typeof pattern === 'string' || typeof key === 'symbol') ? key === pattern : pattern.test(key);
  6077. const desc = Reflect.getOwnPropertyDescriptor(target, key);
  6078. const writableOrConfigurableOwn = (desc === undefined || desc.writable || desc.configurable);
  6079. const included = options.include ? options.include.some(match) : !options.exclude.some(match);
  6080. const shouldFilter = included && writableOrConfigurableOwn;
  6081. cached[key] = shouldFilter;
  6082. return shouldFilter;
  6083. };
  6084. const cache = new WeakMap();
  6085. const proxy = new Proxy(input, {
  6086. apply(target, thisArg, args) {
  6087. const cached = cache.get(target);
  6088. if (cached) {
  6089. return Reflect.apply(cached, thisArg, args);
  6090. }
  6091. const pified = options.excludeMain ? target : processFn(target, options, proxy, target);
  6092. cache.set(target, pified);
  6093. return Reflect.apply(pified, thisArg, args);
  6094. },
  6095. get(target, key) {
  6096. const property = target[key];
  6097. // eslint-disable-next-line no-use-extend-native/no-use-extend-native
  6098. if (!filter(target, key) || property === Function.prototype[key]) {
  6099. return property;
  6100. }
  6101. const cached = cache.get(property);
  6102. if (cached) {
  6103. return cached;
  6104. }
  6105. if (typeof property === 'function') {
  6106. const pified = processFn(property, options, proxy, target);
  6107. cache.set(property, pified);
  6108. return pified;
  6109. }
  6110. return property;
  6111. }
  6112. });
  6113. return proxy;
  6114. };
  6115. /***/ }),
  6116. /* 39 */
  6117. /***/ (function(module, exports, __webpack_require__) {
  6118. "use strict";
  6119. var __importDefault = (this && this.__importDefault) || function (mod) {
  6120. return (mod && mod.__esModule) ? mod : { "default": mod };
  6121. };
  6122. Object.defineProperty(exports, "__esModule", { value: true });
  6123. /******************************************************************
  6124. MIT License http://www.opensource.org/licenses/mit-license.php
  6125. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  6126. *******************************************************************/
  6127. const coc_nvim_1 = __webpack_require__(1);
  6128. const fs_1 = __importDefault(__webpack_require__(3));
  6129. const path_1 = __importDefault(__webpack_require__(4));
  6130. const readline_1 = __importDefault(__webpack_require__(40));
  6131. const vscode_languageserver_types_1 = __webpack_require__(6);
  6132. const baseProvider_1 = __importDefault(__webpack_require__(41));
  6133. const types_1 = __webpack_require__(36);
  6134. const util_1 = __webpack_require__(37);
  6135. const parser_1 = __importDefault(__webpack_require__(42));
  6136. class SnipmateProvider extends baseProvider_1.default {
  6137. constructor(channel, trace, config) {
  6138. super(config);
  6139. this.channel = channel;
  6140. this.trace = trace;
  6141. this.snippetFiles = [];
  6142. this.disposables = [];
  6143. coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
  6144. let uri = coc_nvim_1.Uri.parse(doc.uri);
  6145. if (uri.scheme != 'file')
  6146. return;
  6147. let filepath = uri.fsPath;
  6148. if (!fs_1.default.existsSync(filepath))
  6149. return;
  6150. let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
  6151. if (snippetFile)
  6152. await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
  6153. }, null, this.disposables);
  6154. }
  6155. async init() {
  6156. let arr = await this.getAllSnippetFiles();
  6157. let { nvim } = coc_nvim_1.workspace;
  6158. let author = await nvim.getVar('snips_author');
  6159. if (!author)
  6160. await nvim.setVar('snips_author', this.config.author);
  6161. await Promise.all(arr.map(({ filepath, directory, filetype }) => {
  6162. return this.loadSnippetsFromFile(filetype, directory, filepath);
  6163. }));
  6164. }
  6165. async loadSnippetsFromFile(filetype, directory, filepath) {
  6166. let snippets = await this.parseSnippetsFile(filepath);
  6167. let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
  6168. if (idx !== -1)
  6169. this.snippetFiles.splice(idx, 1);
  6170. this.snippetFiles.push({
  6171. directory,
  6172. filepath,
  6173. filetype,
  6174. snippets
  6175. });
  6176. if (this.trace == 'verbose') {
  6177. this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Loaded ${snippets.length} snippets from: ${filepath}`);
  6178. }
  6179. }
  6180. /**
  6181. * Resolve snippet body to inserted text.
  6182. *
  6183. * @public
  6184. * @param {Snippet} snippet
  6185. * @param {Range} _range
  6186. * @param {string} _line
  6187. * @returns {Promise<string>}
  6188. */
  6189. async resolveSnippetBody(snippet, _range, _line) {
  6190. let parser = new parser_1.default(snippet.body);
  6191. let resolved = '';
  6192. let { nvim } = coc_nvim_1.workspace;
  6193. while (!parser.eof()) {
  6194. if (parser.curr == '`') {
  6195. let idx = parser.nextIndex('`', true, false);
  6196. if (idx == -1) {
  6197. resolved = resolved + parser.eatTo(parser.len);
  6198. break;
  6199. }
  6200. let code = parser.eatTo(idx + 1);
  6201. code = code.slice(1, -1);
  6202. if (code.startsWith('Filename')) {
  6203. resolved = resolved + await nvim.call('expand', '%:p:t');
  6204. }
  6205. else {
  6206. try {
  6207. resolved = resolved + await nvim.eval(code);
  6208. }
  6209. catch (e) {
  6210. this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on eval: ${code}`);
  6211. }
  6212. }
  6213. continue;
  6214. }
  6215. parser.iterate(ch => {
  6216. if (ch == '`') {
  6217. return false;
  6218. }
  6219. else {
  6220. resolved = resolved + ch;
  6221. }
  6222. return true;
  6223. });
  6224. }
  6225. return resolved;
  6226. }
  6227. /**
  6228. * Parse snippets from snippets file.
  6229. *
  6230. * @public
  6231. * @param {string} filepath
  6232. * @returns {Promise<Snippet[]>}
  6233. */
  6234. parseSnippetsFile(filepath) {
  6235. let res = [];
  6236. const rl = readline_1.default.createInterface({
  6237. input: fs_1.default.createReadStream(filepath, 'utf8'),
  6238. crlfDelay: Infinity
  6239. });
  6240. let lnum = 0;
  6241. let lines = [];
  6242. let prefix = '';
  6243. let description = '';
  6244. rl.on('line', line => {
  6245. lnum += 1;
  6246. if (line.startsWith('#'))
  6247. return;
  6248. if (line.startsWith('snippet')) {
  6249. line = line.replace(/\s*$/, '');
  6250. if (lines.length && prefix) {
  6251. res.push({
  6252. filepath,
  6253. lnum: lnum - lines.length - 1,
  6254. body: lines.join('\n').replace(/\s+$/, ''),
  6255. prefix,
  6256. description,
  6257. triggerKind: types_1.TriggerKind.SpaceBefore
  6258. });
  6259. lines = [];
  6260. }
  6261. let ms = line.match(/^snippet\s+(\S+)(?:\s(.+))?$/);
  6262. if (!ms) {
  6263. prefix = '';
  6264. this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Broken line on ${filepath}:${lnum}`);
  6265. return;
  6266. }
  6267. prefix = ms[1];
  6268. description = ms[2] || '';
  6269. return;
  6270. }
  6271. if (prefix) {
  6272. if (line.indexOf('VISUAL') !== -1) {
  6273. line = line.replace(/\$(\{?)VISUAL\b(:[^\}])?(\}?)/g, '$$$1TM_SELECTED_TEXT$2$3');
  6274. }
  6275. if (line.startsWith('\t')) {
  6276. lines.push(line.slice(1));
  6277. }
  6278. else {
  6279. lines.push(line);
  6280. }
  6281. }
  6282. });
  6283. return new Promise(resolve => {
  6284. rl.on('close', async () => {
  6285. if (lines.length) {
  6286. res.push({
  6287. filepath,
  6288. lnum: lnum - lines.length - 1,
  6289. body: lines.join('\n'),
  6290. prefix,
  6291. description,
  6292. triggerKind: types_1.TriggerKind.SpaceBefore
  6293. });
  6294. }
  6295. resolve(res);
  6296. });
  6297. });
  6298. }
  6299. async getTriggerSnippets(document, position, autoTrigger) {
  6300. if (autoTrigger)
  6301. return [];
  6302. let snippets = await this.getSnippets(document.filetype);
  6303. let line = document.getline(position.line);
  6304. line = line.slice(0, position.character);
  6305. if (!line || line[line.length - 1] == ' ')
  6306. return [];
  6307. snippets = snippets.filter(s => {
  6308. let { prefix } = s;
  6309. if (!line.endsWith(prefix))
  6310. return false;
  6311. let pre = line.slice(0, line.length - prefix.length);
  6312. return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
  6313. });
  6314. let edits = [];
  6315. for (let s of snippets) {
  6316. let character = position.character - s.prefix.length;
  6317. let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
  6318. let newText = await this.resolveSnippetBody(s, range, line);
  6319. edits.push({
  6320. prefix: s.prefix,
  6321. description: s.description,
  6322. location: s.filepath,
  6323. range,
  6324. newText,
  6325. priority: -1
  6326. });
  6327. }
  6328. return edits;
  6329. }
  6330. async getSnippetFiles(filetype) {
  6331. let filetypes = this.getFiletypes(filetype);
  6332. let res = [];
  6333. for (let s of this.snippetFiles) {
  6334. if (filetypes.indexOf(s.filetype) !== -1) {
  6335. res.push(s.filepath);
  6336. }
  6337. }
  6338. return res;
  6339. }
  6340. async getSnippets(filetype) {
  6341. let filetypes = this.getFiletypes(filetype);
  6342. filetypes.push('_');
  6343. let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
  6344. let result = [];
  6345. snippetFiles.sort((a, b) => {
  6346. if (a.filetype == b.filetype)
  6347. return 1;
  6348. if (a.filetype == filetype)
  6349. return -1;
  6350. return 1;
  6351. });
  6352. for (let file of snippetFiles) {
  6353. let { snippets } = file;
  6354. for (let snip of snippets) {
  6355. result.push(snip);
  6356. }
  6357. }
  6358. return result;
  6359. }
  6360. async getAllSnippetFiles() {
  6361. let { nvim } = coc_nvim_1.workspace;
  6362. let opt = await nvim.eval('&rtp');
  6363. let rtps = opt.split(',');
  6364. let res = [];
  6365. for (let rtp of rtps) {
  6366. let items = await this.getSnippetFileItems(path_1.default.join(rtp, 'snippets'));
  6367. res.push(...items);
  6368. }
  6369. return res;
  6370. }
  6371. async getSnippetFileItems(directory) {
  6372. let res = [];
  6373. let stat = await util_1.statAsync(directory);
  6374. if (stat && stat.isDirectory()) {
  6375. let files = await util_1.readdirAsync(directory);
  6376. if (files.length) {
  6377. for (let f of files) {
  6378. let file = path_1.default.join(directory, f);
  6379. if (file.endsWith('.snippets')) {
  6380. let basename = path_1.default.basename(f, '.snippets');
  6381. let filetype = basename.split('-', 2)[0];
  6382. res.push({ filepath: file, directory, filetype });
  6383. }
  6384. else {
  6385. let stat = await util_1.statAsync(file);
  6386. if (stat && stat.isDirectory()) {
  6387. let files = await util_1.readdirAsync(file);
  6388. for (let filename of files) {
  6389. if (filename.endsWith('.snippets')) {
  6390. res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
  6391. }
  6392. }
  6393. }
  6394. }
  6395. }
  6396. }
  6397. }
  6398. return res;
  6399. }
  6400. }
  6401. exports.SnipmateProvider = SnipmateProvider;
  6402. /***/ }),
  6403. /* 40 */
  6404. /***/ (function(module, exports) {
  6405. module.exports = require("readline");
  6406. /***/ }),
  6407. /* 41 */
  6408. /***/ (function(module, exports, __webpack_require__) {
  6409. "use strict";
  6410. Object.defineProperty(exports, "__esModule", { value: true });
  6411. const coc_nvim_1 = __webpack_require__(1);
  6412. const util_1 = __webpack_require__(37);
  6413. class BaseProvider {
  6414. constructor(config) {
  6415. this.config = config;
  6416. }
  6417. async checkContext(_context) {
  6418. return true;
  6419. }
  6420. getExtendsFiletypes(filetype, exists = new Set()) {
  6421. if (exists.has(filetype))
  6422. return [];
  6423. let extend = this.config.extends ? this.config.extends[filetype] : null;
  6424. exists.add(filetype);
  6425. if (!extend || extend.length == 0)
  6426. return [];
  6427. return extend.reduce((arr, curr) => {
  6428. return arr.concat([curr], this.getExtendsFiletypes(curr, exists));
  6429. }, []);
  6430. }
  6431. getFiletypes(filetype) {
  6432. let filetypes = [filetype];
  6433. if (filetype.indexOf('.') !== -1) {
  6434. filetypes.push(...filetype.split('.'));
  6435. }
  6436. if (filetype == 'javascript.jsx')
  6437. filetypes.push('javascriptreact');
  6438. if (filetype == 'typescript.jsx' || filetype == 'typescript.tsx')
  6439. filetypes.push('typescriptreact');
  6440. let map = coc_nvim_1.workspace.env.filetypeMap;
  6441. if (map && map[filetype]) {
  6442. filetypes.push(map[filetype]);
  6443. }
  6444. let extendFiletypes = filetypes.reduce((arr, curr) => {
  6445. return arr.concat(this.getExtendsFiletypes(curr));
  6446. }, []);
  6447. filetypes.push(...extendFiletypes);
  6448. filetypes.reverse();
  6449. return util_1.distinct(filetypes);
  6450. }
  6451. }
  6452. exports.default = BaseProvider;
  6453. /***/ }),
  6454. /* 42 */
  6455. /***/ (function(module, exports, __webpack_require__) {
  6456. "use strict";
  6457. /******************************************************************
  6458. MIT License http://www.opensource.org/licenses/mit-license.php
  6459. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  6460. *******************************************************************/
  6461. Object.defineProperty(exports, "__esModule", { value: true });
  6462. /**
  6463. * A very basic parser
  6464. *
  6465. * @public
  6466. */
  6467. class Parser {
  6468. constructor(_content) {
  6469. this._content = _content;
  6470. this._curr = 0;
  6471. }
  6472. eof() {
  6473. return this._curr >= this._content.length;
  6474. }
  6475. skipSpaces() {
  6476. for (let i = this._curr; i <= this._content.length; i++) {
  6477. let ch = this._content[i];
  6478. if (!ch || /\S/.test(ch)) {
  6479. this._curr = i;
  6480. break;
  6481. }
  6482. }
  6483. }
  6484. get index() {
  6485. return this._curr;
  6486. }
  6487. get curr() {
  6488. return this._content[this._curr] || '';
  6489. }
  6490. get len() {
  6491. return this._content.length;
  6492. }
  6493. next(count = 1) {
  6494. return this._content.slice(this._curr + 1, this._curr + 1 + count);
  6495. }
  6496. nextIndex(character, checkEscape = true, allowEnd = true) {
  6497. if (this._curr >= this.len - 1)
  6498. return allowEnd ? this.len - 1 : -1;
  6499. let i = this._curr + 1;
  6500. let pre = this.curr || '';
  6501. while (i != this.len - 1) {
  6502. let ch = this._content[i];
  6503. if (ch == character && (!checkEscape || pre !== '\\')) {
  6504. break;
  6505. }
  6506. pre = ch;
  6507. i = i + 1;
  6508. }
  6509. if (!allowEnd && i == this.len - 1 && character != this._content[i]) {
  6510. return -1;
  6511. }
  6512. return i;
  6513. }
  6514. prev() {
  6515. return this._content[this._curr - 1] || '';
  6516. }
  6517. iterate(fn) {
  6518. while (this._curr < this._content.length) {
  6519. let fine = fn(this.curr, this._curr);
  6520. if (fine === false) {
  6521. break;
  6522. }
  6523. this._curr = this._curr + 1;
  6524. }
  6525. }
  6526. eat(count) {
  6527. let end = this._curr + count;
  6528. end = Math.min(end, this.len);
  6529. let str = this._content.slice(this._curr, end);
  6530. this._curr = end;
  6531. return str;
  6532. }
  6533. // make curr to index, return contnet between curr (inclusive) and index (exclusive)
  6534. eatTo(index) {
  6535. if (index == this._curr)
  6536. return '';
  6537. let str = this._content.slice(this._curr, index);
  6538. this._curr = index;
  6539. return str;
  6540. }
  6541. }
  6542. exports.default = Parser;
  6543. /***/ }),
  6544. /* 43 */
  6545. /***/ (function(module, exports, __webpack_require__) {
  6546. "use strict";
  6547. var __importDefault = (this && this.__importDefault) || function (mod) {
  6548. return (mod && mod.__esModule) ? mod : { "default": mod };
  6549. };
  6550. Object.defineProperty(exports, "__esModule", { value: true });
  6551. const coc_nvim_1 = __webpack_require__(1);
  6552. const fs_1 = __importDefault(__webpack_require__(3));
  6553. const jsonc_parser_1 = __webpack_require__(44);
  6554. const os_1 = __importDefault(__webpack_require__(2));
  6555. const path_1 = __importDefault(__webpack_require__(4));
  6556. const util_1 = __importDefault(__webpack_require__(5));
  6557. const vscode_languageserver_types_1 = __webpack_require__(6);
  6558. const baseProvider_1 = __importDefault(__webpack_require__(41));
  6559. const types_1 = __webpack_require__(36);
  6560. const util_2 = __webpack_require__(37);
  6561. class TextmateProvider extends baseProvider_1.default {
  6562. constructor(channel, trace, config) {
  6563. super(config);
  6564. this.channel = channel;
  6565. this.trace = trace;
  6566. this._snippetCache = {};
  6567. this._userSnippets = {};
  6568. if (config.loadFromExtensions) {
  6569. coc_nvim_1.extensions.onDidLoadExtension(extension => {
  6570. this.loadSnippetsFromExtension(extension).catch(e => {
  6571. channel.appendLine(`[Error] ${e.message}`);
  6572. });
  6573. });
  6574. coc_nvim_1.extensions.onDidUnloadExtension(id => {
  6575. delete this._snippetCache[id];
  6576. });
  6577. }
  6578. }
  6579. async init() {
  6580. if (this.config.loadFromExtensions) {
  6581. for (let extension of coc_nvim_1.extensions.all) {
  6582. await this.loadSnippetsFromExtension(extension);
  6583. }
  6584. }
  6585. let paths = this.config.snippetsRoots;
  6586. if (paths && paths.length) {
  6587. for (let dir of paths) {
  6588. await this.loadSnippetsFromRoot(dir);
  6589. }
  6590. }
  6591. }
  6592. async getSnippetFiles(filetype) {
  6593. let filetypes = this.getFiletypes(filetype);
  6594. let filepaths = [];
  6595. if (this.config.loadFromExtensions) {
  6596. for (let key of Object.keys(this._snippetCache)) {
  6597. let cache = this._snippetCache[key];
  6598. for (let filetype of filetypes) {
  6599. let snippets = cache[filetype];
  6600. if (snippets && snippets.length) {
  6601. filepaths.push(snippets[0].filepath);
  6602. }
  6603. }
  6604. }
  6605. }
  6606. for (let filetype of filetypes) {
  6607. let snippets = this._userSnippets[filetype];
  6608. if (snippets && snippets.length) {
  6609. for (let snip of snippets) {
  6610. let { filepath } = snip;
  6611. if (filepaths.indexOf(filepath) == -1) {
  6612. filepaths.push(filepath);
  6613. }
  6614. }
  6615. }
  6616. }
  6617. return util_2.distinct(filepaths);
  6618. }
  6619. async getTriggerSnippets(document, position, autoTrigger) {
  6620. if (autoTrigger)
  6621. return [];
  6622. let line = document.getline(position.line);
  6623. line = line.slice(0, position.character);
  6624. let snippets = await this.getSnippets(document.filetype);
  6625. if (!snippets || !snippets.length)
  6626. return [];
  6627. let edits = [];
  6628. for (let snip of snippets) {
  6629. let { prefix } = snip;
  6630. if (!line.endsWith(prefix))
  6631. continue;
  6632. let pre = line.slice(0, line.length - prefix.length);
  6633. // not allowed after word
  6634. if (pre.length && /\w/.test(pre[pre.length - 1]))
  6635. continue;
  6636. edits.push({
  6637. prefix,
  6638. range: vscode_languageserver_types_1.Range.create(position.line, position.character - prefix.length, position.line, position.character),
  6639. newText: snip.body,
  6640. location: snip.filepath,
  6641. description: snip.description,
  6642. priority: -1
  6643. });
  6644. }
  6645. return edits;
  6646. }
  6647. async getSnippets(filetype) {
  6648. let res = [];
  6649. let filetypes = this.getFiletypes(filetype);
  6650. let added = new Set();
  6651. for (let key of Object.keys(this._snippetCache)) {
  6652. let cache = this._snippetCache[key];
  6653. for (let filetype of filetypes) {
  6654. let snippets = cache[filetype];
  6655. if (snippets) {
  6656. for (let snip of snippets) {
  6657. if (!added.has(snip.prefix)) {
  6658. added.add(snip.prefix);
  6659. res.push(snip);
  6660. }
  6661. }
  6662. }
  6663. }
  6664. }
  6665. for (let filetype of filetypes) {
  6666. let snippets = this._userSnippets[filetype];
  6667. if (snippets && snippets.length) {
  6668. for (let snip of snippets) {
  6669. if (!added.has(snip.prefix)) {
  6670. added.add(snip.prefix);
  6671. res.push(snip);
  6672. }
  6673. }
  6674. }
  6675. }
  6676. return res;
  6677. }
  6678. async resolveSnippetBody(snip, _range) {
  6679. return snip.body;
  6680. }
  6681. async loadSnippetsFromExtension(extension) {
  6682. let { packageJSON } = extension;
  6683. if (packageJSON.contributes && packageJSON.contributes.snippets) {
  6684. let { snippets } = packageJSON.contributes;
  6685. let def = {
  6686. extensionId: extension.id,
  6687. snippets: []
  6688. };
  6689. for (let item of snippets) {
  6690. let p = path_1.default.join(extension.extensionPath, item.path);
  6691. let { language } = item;
  6692. def.snippets.push({
  6693. languageId: language,
  6694. filepath: p
  6695. });
  6696. }
  6697. if (snippets && snippets.length) {
  6698. await this.loadSnippetsFromDefinition(def);
  6699. }
  6700. }
  6701. }
  6702. async loadSnippetsFromRoot(root) {
  6703. let { _userSnippets } = this;
  6704. if (root.startsWith('~'))
  6705. root = root.replace(/^~/, os_1.default.homedir());
  6706. let files = await util_1.default.promisify(fs_1.default.readdir)(root, 'utf8');
  6707. files = files.filter(f => f.endsWith('.json') || f.endsWith('.code-snippets'));
  6708. await Promise.all(files.map(file => {
  6709. file = path_1.default.join(root, file);
  6710. let basename = path_1.default.basename(file, '.json');
  6711. basename = basename.replace(/\.code-snippets$/, '');
  6712. return this.loadSnippetsFromFile(file).then(snippets => {
  6713. _userSnippets[basename] = snippets;
  6714. });
  6715. }));
  6716. }
  6717. async loadSnippetsFromDefinition(def) {
  6718. let { extensionId, snippets } = def;
  6719. let cache = this._snippetCache[extensionId] = {};
  6720. for (let item of snippets) {
  6721. let { languageId } = item;
  6722. if (!fs_1.default.existsSync(item.filepath))
  6723. continue;
  6724. let arr = await this.loadSnippetsFromFile(item.filepath);
  6725. let exists = cache[languageId] || [];
  6726. cache[languageId] = [...exists, ...arr];
  6727. }
  6728. }
  6729. async loadSnippetsFromFile(snippetFilePath) {
  6730. const contents = await new Promise((resolve, reject) => {
  6731. fs_1.default.readFile(snippetFilePath, "utf8", (err, data) => {
  6732. if (err)
  6733. return reject(err);
  6734. resolve(data);
  6735. });
  6736. });
  6737. const snippets = this.loadSnippetsFromText(snippetFilePath, contents);
  6738. if (this.trace == 'verbose') {
  6739. this.channel.appendLine(`[Info ${(new Date()).toLocaleDateString()}] Loaded ${snippets.length} snippets from ${snippetFilePath}`);
  6740. }
  6741. return snippets;
  6742. }
  6743. loadSnippetsFromText(filepath, contents) {
  6744. let snippets = [];
  6745. try {
  6746. let errors = [];
  6747. let snippetObject = jsonc_parser_1.parse(contents, errors, { allowTrailingComma: true });
  6748. if (errors.length) {
  6749. this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] parser error: ${errors[0].error}`);
  6750. }
  6751. if (snippetObject) {
  6752. for (let key of Object.keys(snippetObject)) {
  6753. snippets.push(snippetObject[key]);
  6754. }
  6755. }
  6756. }
  6757. catch (ex) {
  6758. this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] ${ex.stack}`);
  6759. snippets = [];
  6760. }
  6761. const normalizedSnippets = snippets.map((snip) => {
  6762. let prefix = Array.isArray(snip.prefix) ? snip.prefix[0] : snip.prefix;
  6763. return {
  6764. filepath,
  6765. lnum: 0,
  6766. body: typeof snip.body === 'string' ? snip.body : snip.body.join('\n'),
  6767. prefix,
  6768. description: typeof snip.description === 'string' ? snip.description : typeof snip.description !== 'undefined' ? snip.description.join('\n') : '',
  6769. triggerKind: types_1.TriggerKind.WordBoundary
  6770. };
  6771. });
  6772. return normalizedSnippets;
  6773. }
  6774. }
  6775. exports.TextmateProvider = TextmateProvider;
  6776. /***/ }),
  6777. /* 44 */
  6778. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  6779. "use strict";
  6780. __webpack_require__.r(__webpack_exports__);
  6781. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
  6782. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
  6783. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
  6784. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
  6785. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
  6786. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
  6787. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
  6788. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
  6789. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
  6790. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
  6791. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; });
  6792. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
  6793. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; });
  6794. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; });
  6795. /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45);
  6796. /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47);
  6797. /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46);
  6798. /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48);
  6799. /*---------------------------------------------------------------------------------------------
  6800. * Copyright (c) Microsoft Corporation. All rights reserved.
  6801. * Licensed under the MIT License. See License.txt in the project root for license information.
  6802. *--------------------------------------------------------------------------------------------*/
  6803. /**
  6804. * Creates a JSON scanner on the given text.
  6805. * If ignoreTrivia is set, whitespaces or comments are ignored.
  6806. */
  6807. var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"];
  6808. /**
  6809. * 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.
  6810. */
  6811. var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"];
  6812. /**
  6813. * 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.
  6814. * Therefore, always check the errors list to find out if the input was valid.
  6815. */
  6816. var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"];
  6817. /**
  6818. * 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.
  6819. */
  6820. var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"];
  6821. /**
  6822. * Finds the node at the given path in a JSON DOM.
  6823. */
  6824. var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"];
  6825. /**
  6826. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  6827. */
  6828. var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"];
  6829. /**
  6830. * Gets the JSON path of the given JSON DOM node
  6831. */
  6832. var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"];
  6833. /**
  6834. * Evaluates the JavaScript object of the given JSON DOM node
  6835. */
  6836. var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"];
  6837. /**
  6838. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  6839. */
  6840. var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"];
  6841. /**
  6842. * Takes JSON with JavaScript-style comments and remove
  6843. * them. Optionally replaces every none-newline character
  6844. * of comments with a replaceCharacter
  6845. */
  6846. var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"];
  6847. function printParseErrorCode(code) {
  6848. switch (code) {
  6849. case 1 /* InvalidSymbol */: return 'InvalidSymbol';
  6850. case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
  6851. case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
  6852. case 4 /* ValueExpected */: return 'ValueExpected';
  6853. case 5 /* ColonExpected */: return 'ColonExpected';
  6854. case 6 /* CommaExpected */: return 'CommaExpected';
  6855. case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
  6856. case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
  6857. case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
  6858. case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
  6859. case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
  6860. case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
  6861. case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
  6862. case 14 /* InvalidUnicode */: return 'InvalidUnicode';
  6863. case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
  6864. case 16 /* InvalidCharacter */: return 'InvalidCharacter';
  6865. }
  6866. return '<unknown ParseErrorCode>';
  6867. }
  6868. /**
  6869. * Computes the edits needed to format a JSON document.
  6870. *
  6871. * @param documentText The input text
  6872. * @param range The range to format or `undefined` to format the full content
  6873. * @param options The formatting options
  6874. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  6875. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  6876. * text in the original document. However, multiple edits can have
  6877. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  6878. * To apply edits to an input, you can use `applyEdits`.
  6879. */
  6880. function format(documentText, range, options) {
  6881. return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options);
  6882. }
  6883. /**
  6884. * Computes the edits needed to modify a value in the JSON document.
  6885. *
  6886. * @param documentText The input text
  6887. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  6888. * If the path points to an non-existing property or item, it will be created.
  6889. * @param value The new value for the specified property or item. If the value is undefined,
  6890. * the property or item will be removed.
  6891. * @param options Options
  6892. * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
  6893. * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
  6894. * text in the original document. However, multiple edits can have
  6895. * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
  6896. * To apply edits to an input, you can use `applyEdits`.
  6897. */
  6898. function modify(text, path, value, options) {
  6899. return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options.formattingOptions, options.getInsertionIndex);
  6900. }
  6901. /**
  6902. * Applies edits to a input string.
  6903. */
  6904. function applyEdits(text, edits) {
  6905. for (var i = edits.length - 1; i >= 0; i--) {
  6906. text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]);
  6907. }
  6908. return text;
  6909. }
  6910. /***/ }),
  6911. /* 45 */
  6912. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  6913. "use strict";
  6914. __webpack_require__.r(__webpack_exports__);
  6915. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
  6916. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; });
  6917. /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
  6918. /*---------------------------------------------------------------------------------------------
  6919. * Copyright (c) Microsoft Corporation. All rights reserved.
  6920. * Licensed under the MIT License. See License.txt in the project root for license information.
  6921. *--------------------------------------------------------------------------------------------*/
  6922. function format(documentText, range, options) {
  6923. var initialIndentLevel;
  6924. var formatText;
  6925. var formatTextStart;
  6926. var rangeStart;
  6927. var rangeEnd;
  6928. if (range) {
  6929. rangeStart = range.offset;
  6930. rangeEnd = rangeStart + range.length;
  6931. formatTextStart = rangeStart;
  6932. while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
  6933. formatTextStart--;
  6934. }
  6935. var endOffset = rangeEnd;
  6936. while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
  6937. endOffset++;
  6938. }
  6939. formatText = documentText.substring(formatTextStart, endOffset);
  6940. initialIndentLevel = computeIndentLevel(formatText, options);
  6941. }
  6942. else {
  6943. formatText = documentText;
  6944. initialIndentLevel = 0;
  6945. formatTextStart = 0;
  6946. rangeStart = 0;
  6947. rangeEnd = documentText.length;
  6948. }
  6949. var eol = getEOL(options, documentText);
  6950. var lineBreak = false;
  6951. var indentLevel = 0;
  6952. var indentValue;
  6953. if (options.insertSpaces) {
  6954. indentValue = repeat(' ', options.tabSize || 4);
  6955. }
  6956. else {
  6957. indentValue = '\t';
  6958. }
  6959. var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false);
  6960. var hasError = false;
  6961. function newLineAndIndent() {
  6962. return eol + repeat(indentValue, initialIndentLevel + indentLevel);
  6963. }
  6964. function scanNext() {
  6965. var token = scanner.scan();
  6966. lineBreak = false;
  6967. while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
  6968. lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
  6969. token = scanner.scan();
  6970. }
  6971. hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
  6972. return token;
  6973. }
  6974. var editOperations = [];
  6975. function addEdit(text, startOffset, endOffset) {
  6976. if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
  6977. editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
  6978. }
  6979. }
  6980. var firstToken = scanNext();
  6981. if (firstToken !== 17 /* EOF */) {
  6982. var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
  6983. var initialIndent = repeat(indentValue, initialIndentLevel);
  6984. addEdit(initialIndent, formatTextStart, firstTokenStart);
  6985. }
  6986. while (firstToken !== 17 /* EOF */) {
  6987. var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  6988. var secondToken = scanNext();
  6989. var replaceContent = '';
  6990. while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  6991. // comments on the same line: keep them on the same line, but ignore them otherwise
  6992. var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
  6993. addEdit(' ', firstTokenEnd, commentTokenStart);
  6994. firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
  6995. replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
  6996. secondToken = scanNext();
  6997. }
  6998. if (secondToken === 2 /* CloseBraceToken */) {
  6999. if (firstToken !== 1 /* OpenBraceToken */) {
  7000. indentLevel--;
  7001. replaceContent = newLineAndIndent();
  7002. }
  7003. }
  7004. else if (secondToken === 4 /* CloseBracketToken */) {
  7005. if (firstToken !== 3 /* OpenBracketToken */) {
  7006. indentLevel--;
  7007. replaceContent = newLineAndIndent();
  7008. }
  7009. }
  7010. else {
  7011. switch (firstToken) {
  7012. case 3 /* OpenBracketToken */:
  7013. case 1 /* OpenBraceToken */:
  7014. indentLevel++;
  7015. replaceContent = newLineAndIndent();
  7016. break;
  7017. case 5 /* CommaToken */:
  7018. case 12 /* LineCommentTrivia */:
  7019. replaceContent = newLineAndIndent();
  7020. break;
  7021. case 13 /* BlockCommentTrivia */:
  7022. if (lineBreak) {
  7023. replaceContent = newLineAndIndent();
  7024. }
  7025. else {
  7026. // symbol following comment on the same line: keep on same line, separate with ' '
  7027. replaceContent = ' ';
  7028. }
  7029. break;
  7030. case 6 /* ColonToken */:
  7031. replaceContent = ' ';
  7032. break;
  7033. case 10 /* StringLiteral */:
  7034. if (secondToken === 6 /* ColonToken */) {
  7035. replaceContent = '';
  7036. break;
  7037. }
  7038. // fall through
  7039. case 7 /* NullKeyword */:
  7040. case 8 /* TrueKeyword */:
  7041. case 9 /* FalseKeyword */:
  7042. case 11 /* NumericLiteral */:
  7043. case 2 /* CloseBraceToken */:
  7044. case 4 /* CloseBracketToken */:
  7045. if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
  7046. replaceContent = ' ';
  7047. }
  7048. else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
  7049. hasError = true;
  7050. }
  7051. break;
  7052. case 16 /* Unknown */:
  7053. hasError = true;
  7054. break;
  7055. }
  7056. if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
  7057. replaceContent = newLineAndIndent();
  7058. }
  7059. }
  7060. var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
  7061. addEdit(replaceContent, firstTokenEnd, secondTokenStart);
  7062. firstToken = secondToken;
  7063. }
  7064. return editOperations;
  7065. }
  7066. function repeat(s, count) {
  7067. var result = '';
  7068. for (var i = 0; i < count; i++) {
  7069. result += s;
  7070. }
  7071. return result;
  7072. }
  7073. function computeIndentLevel(content, options) {
  7074. var i = 0;
  7075. var nChars = 0;
  7076. var tabSize = options.tabSize || 4;
  7077. while (i < content.length) {
  7078. var ch = content.charAt(i);
  7079. if (ch === ' ') {
  7080. nChars++;
  7081. }
  7082. else if (ch === '\t') {
  7083. nChars += tabSize;
  7084. }
  7085. else {
  7086. break;
  7087. }
  7088. i++;
  7089. }
  7090. return Math.floor(nChars / tabSize);
  7091. }
  7092. function getEOL(options, text) {
  7093. for (var i = 0; i < text.length; i++) {
  7094. var ch = text.charAt(i);
  7095. if (ch === '\r') {
  7096. if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
  7097. return '\r\n';
  7098. }
  7099. return '\r';
  7100. }
  7101. else if (ch === '\n') {
  7102. return '\n';
  7103. }
  7104. }
  7105. return (options && options.eol) || '\n';
  7106. }
  7107. function isEOL(text, offset) {
  7108. return '\r\n'.indexOf(text.charAt(offset)) !== -1;
  7109. }
  7110. /***/ }),
  7111. /* 46 */
  7112. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  7113. "use strict";
  7114. __webpack_require__.r(__webpack_exports__);
  7115. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
  7116. /*---------------------------------------------------------------------------------------------
  7117. * Copyright (c) Microsoft Corporation. All rights reserved.
  7118. * Licensed under the MIT License. See License.txt in the project root for license information.
  7119. *--------------------------------------------------------------------------------------------*/
  7120. /**
  7121. * Creates a JSON scanner on the given text.
  7122. * If ignoreTrivia is set, whitespaces or comments are ignored.
  7123. */
  7124. function createScanner(text, ignoreTrivia) {
  7125. if (ignoreTrivia === void 0) { ignoreTrivia = false; }
  7126. var len = text.length;
  7127. var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
  7128. function scanHexDigits(count, exact) {
  7129. var digits = 0;
  7130. var value = 0;
  7131. while (digits < count || !exact) {
  7132. var ch = text.charCodeAt(pos);
  7133. if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
  7134. value = value * 16 + ch - 48 /* _0 */;
  7135. }
  7136. else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
  7137. value = value * 16 + ch - 65 /* A */ + 10;
  7138. }
  7139. else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
  7140. value = value * 16 + ch - 97 /* a */ + 10;
  7141. }
  7142. else {
  7143. break;
  7144. }
  7145. pos++;
  7146. digits++;
  7147. }
  7148. if (digits < count) {
  7149. value = -1;
  7150. }
  7151. return value;
  7152. }
  7153. function setPosition(newPosition) {
  7154. pos = newPosition;
  7155. value = '';
  7156. tokenOffset = 0;
  7157. token = 16 /* Unknown */;
  7158. scanError = 0 /* None */;
  7159. }
  7160. function scanNumber() {
  7161. var start = pos;
  7162. if (text.charCodeAt(pos) === 48 /* _0 */) {
  7163. pos++;
  7164. }
  7165. else {
  7166. pos++;
  7167. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  7168. pos++;
  7169. }
  7170. }
  7171. if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
  7172. pos++;
  7173. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  7174. pos++;
  7175. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  7176. pos++;
  7177. }
  7178. }
  7179. else {
  7180. scanError = 3 /* UnexpectedEndOfNumber */;
  7181. return text.substring(start, pos);
  7182. }
  7183. }
  7184. var end = pos;
  7185. if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
  7186. pos++;
  7187. if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
  7188. pos++;
  7189. }
  7190. if (pos < text.length && isDigit(text.charCodeAt(pos))) {
  7191. pos++;
  7192. while (pos < text.length && isDigit(text.charCodeAt(pos))) {
  7193. pos++;
  7194. }
  7195. end = pos;
  7196. }
  7197. else {
  7198. scanError = 3 /* UnexpectedEndOfNumber */;
  7199. }
  7200. }
  7201. return text.substring(start, end);
  7202. }
  7203. function scanString() {
  7204. var result = '', start = pos;
  7205. while (true) {
  7206. if (pos >= len) {
  7207. result += text.substring(start, pos);
  7208. scanError = 2 /* UnexpectedEndOfString */;
  7209. break;
  7210. }
  7211. var ch = text.charCodeAt(pos);
  7212. if (ch === 34 /* doubleQuote */) {
  7213. result += text.substring(start, pos);
  7214. pos++;
  7215. break;
  7216. }
  7217. if (ch === 92 /* backslash */) {
  7218. result += text.substring(start, pos);
  7219. pos++;
  7220. if (pos >= len) {
  7221. scanError = 2 /* UnexpectedEndOfString */;
  7222. break;
  7223. }
  7224. var ch2 = text.charCodeAt(pos++);
  7225. switch (ch2) {
  7226. case 34 /* doubleQuote */:
  7227. result += '\"';
  7228. break;
  7229. case 92 /* backslash */:
  7230. result += '\\';
  7231. break;
  7232. case 47 /* slash */:
  7233. result += '/';
  7234. break;
  7235. case 98 /* b */:
  7236. result += '\b';
  7237. break;
  7238. case 102 /* f */:
  7239. result += '\f';
  7240. break;
  7241. case 110 /* n */:
  7242. result += '\n';
  7243. break;
  7244. case 114 /* r */:
  7245. result += '\r';
  7246. break;
  7247. case 116 /* t */:
  7248. result += '\t';
  7249. break;
  7250. case 117 /* u */:
  7251. var ch3 = scanHexDigits(4, true);
  7252. if (ch3 >= 0) {
  7253. result += String.fromCharCode(ch3);
  7254. }
  7255. else {
  7256. scanError = 4 /* InvalidUnicode */;
  7257. }
  7258. break;
  7259. default:
  7260. scanError = 5 /* InvalidEscapeCharacter */;
  7261. }
  7262. start = pos;
  7263. continue;
  7264. }
  7265. if (ch >= 0 && ch <= 0x1f) {
  7266. if (isLineBreak(ch)) {
  7267. result += text.substring(start, pos);
  7268. scanError = 2 /* UnexpectedEndOfString */;
  7269. break;
  7270. }
  7271. else {
  7272. scanError = 6 /* InvalidCharacter */;
  7273. // mark as error but continue with string
  7274. }
  7275. }
  7276. pos++;
  7277. }
  7278. return result;
  7279. }
  7280. function scanNext() {
  7281. value = '';
  7282. scanError = 0 /* None */;
  7283. tokenOffset = pos;
  7284. lineStartOffset = lineNumber;
  7285. prevTokenLineStartOffset = tokenLineStartOffset;
  7286. if (pos >= len) {
  7287. // at the end
  7288. tokenOffset = len;
  7289. return token = 17 /* EOF */;
  7290. }
  7291. var code = text.charCodeAt(pos);
  7292. // trivia: whitespace
  7293. if (isWhiteSpace(code)) {
  7294. do {
  7295. pos++;
  7296. value += String.fromCharCode(code);
  7297. code = text.charCodeAt(pos);
  7298. } while (isWhiteSpace(code));
  7299. return token = 15 /* Trivia */;
  7300. }
  7301. // trivia: newlines
  7302. if (isLineBreak(code)) {
  7303. pos++;
  7304. value += String.fromCharCode(code);
  7305. if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  7306. pos++;
  7307. value += '\n';
  7308. }
  7309. lineNumber++;
  7310. tokenLineStartOffset = pos;
  7311. return token = 14 /* LineBreakTrivia */;
  7312. }
  7313. switch (code) {
  7314. // tokens: []{}:,
  7315. case 123 /* openBrace */:
  7316. pos++;
  7317. return token = 1 /* OpenBraceToken */;
  7318. case 125 /* closeBrace */:
  7319. pos++;
  7320. return token = 2 /* CloseBraceToken */;
  7321. case 91 /* openBracket */:
  7322. pos++;
  7323. return token = 3 /* OpenBracketToken */;
  7324. case 93 /* closeBracket */:
  7325. pos++;
  7326. return token = 4 /* CloseBracketToken */;
  7327. case 58 /* colon */:
  7328. pos++;
  7329. return token = 6 /* ColonToken */;
  7330. case 44 /* comma */:
  7331. pos++;
  7332. return token = 5 /* CommaToken */;
  7333. // strings
  7334. case 34 /* doubleQuote */:
  7335. pos++;
  7336. value = scanString();
  7337. return token = 10 /* StringLiteral */;
  7338. // comments
  7339. case 47 /* slash */:
  7340. var start = pos - 1;
  7341. // Single-line comment
  7342. if (text.charCodeAt(pos + 1) === 47 /* slash */) {
  7343. pos += 2;
  7344. while (pos < len) {
  7345. if (isLineBreak(text.charCodeAt(pos))) {
  7346. break;
  7347. }
  7348. pos++;
  7349. }
  7350. value = text.substring(start, pos);
  7351. return token = 12 /* LineCommentTrivia */;
  7352. }
  7353. // Multi-line comment
  7354. if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
  7355. pos += 2;
  7356. var safeLength = len - 1; // For lookahead.
  7357. var commentClosed = false;
  7358. while (pos < safeLength) {
  7359. var ch = text.charCodeAt(pos);
  7360. if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
  7361. pos += 2;
  7362. commentClosed = true;
  7363. break;
  7364. }
  7365. pos++;
  7366. if (isLineBreak(ch)) {
  7367. if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
  7368. pos++;
  7369. }
  7370. lineNumber++;
  7371. tokenLineStartOffset = pos;
  7372. }
  7373. }
  7374. if (!commentClosed) {
  7375. pos++;
  7376. scanError = 1 /* UnexpectedEndOfComment */;
  7377. }
  7378. value = text.substring(start, pos);
  7379. return token = 13 /* BlockCommentTrivia */;
  7380. }
  7381. // just a single slash
  7382. value += String.fromCharCode(code);
  7383. pos++;
  7384. return token = 16 /* Unknown */;
  7385. // numbers
  7386. case 45 /* minus */:
  7387. value += String.fromCharCode(code);
  7388. pos++;
  7389. if (pos === len || !isDigit(text.charCodeAt(pos))) {
  7390. return token = 16 /* Unknown */;
  7391. }
  7392. // found a minus, followed by a number so
  7393. // we fall through to proceed with scanning
  7394. // numbers
  7395. case 48 /* _0 */:
  7396. case 49 /* _1 */:
  7397. case 50 /* _2 */:
  7398. case 51 /* _3 */:
  7399. case 52 /* _4 */:
  7400. case 53 /* _5 */:
  7401. case 54 /* _6 */:
  7402. case 55 /* _7 */:
  7403. case 56 /* _8 */:
  7404. case 57 /* _9 */:
  7405. value += scanNumber();
  7406. return token = 11 /* NumericLiteral */;
  7407. // literals and unknown symbols
  7408. default:
  7409. // is a literal? Read the full word.
  7410. while (pos < len && isUnknownContentCharacter(code)) {
  7411. pos++;
  7412. code = text.charCodeAt(pos);
  7413. }
  7414. if (tokenOffset !== pos) {
  7415. value = text.substring(tokenOffset, pos);
  7416. // keywords: true, false, null
  7417. switch (value) {
  7418. case 'true': return token = 8 /* TrueKeyword */;
  7419. case 'false': return token = 9 /* FalseKeyword */;
  7420. case 'null': return token = 7 /* NullKeyword */;
  7421. }
  7422. return token = 16 /* Unknown */;
  7423. }
  7424. // some
  7425. value += String.fromCharCode(code);
  7426. pos++;
  7427. return token = 16 /* Unknown */;
  7428. }
  7429. }
  7430. function isUnknownContentCharacter(code) {
  7431. if (isWhiteSpace(code) || isLineBreak(code)) {
  7432. return false;
  7433. }
  7434. switch (code) {
  7435. case 125 /* closeBrace */:
  7436. case 93 /* closeBracket */:
  7437. case 123 /* openBrace */:
  7438. case 91 /* openBracket */:
  7439. case 34 /* doubleQuote */:
  7440. case 58 /* colon */:
  7441. case 44 /* comma */:
  7442. case 47 /* slash */:
  7443. return false;
  7444. }
  7445. return true;
  7446. }
  7447. function scanNextNonTrivia() {
  7448. var result;
  7449. do {
  7450. result = scanNext();
  7451. } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
  7452. return result;
  7453. }
  7454. return {
  7455. setPosition: setPosition,
  7456. getPosition: function () { return pos; },
  7457. scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
  7458. getToken: function () { return token; },
  7459. getTokenValue: function () { return value; },
  7460. getTokenOffset: function () { return tokenOffset; },
  7461. getTokenLength: function () { return pos - tokenOffset; },
  7462. getTokenStartLine: function () { return lineStartOffset; },
  7463. getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
  7464. getTokenError: function () { return scanError; },
  7465. };
  7466. }
  7467. function isWhiteSpace(ch) {
  7468. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
  7469. ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
  7470. ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
  7471. }
  7472. function isLineBreak(ch) {
  7473. return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
  7474. }
  7475. function isDigit(ch) {
  7476. return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
  7477. }
  7478. /***/ }),
  7479. /* 47 */
  7480. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  7481. "use strict";
  7482. __webpack_require__.r(__webpack_exports__);
  7483. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; });
  7484. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; });
  7485. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; });
  7486. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; });
  7487. /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45);
  7488. /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48);
  7489. /*---------------------------------------------------------------------------------------------
  7490. * Copyright (c) Microsoft Corporation. All rights reserved.
  7491. * Licensed under the MIT License. See License.txt in the project root for license information.
  7492. *--------------------------------------------------------------------------------------------*/
  7493. function removeProperty(text, path, formattingOptions) {
  7494. return setProperty(text, path, void 0, formattingOptions);
  7495. }
  7496. function setProperty(text, originalPath, value, formattingOptions, getInsertionIndex) {
  7497. var _a;
  7498. var path = originalPath.slice();
  7499. var errors = [];
  7500. var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors);
  7501. var parent = void 0;
  7502. var lastSegment = void 0;
  7503. while (path.length > 0) {
  7504. lastSegment = path.pop();
  7505. parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path);
  7506. if (parent === void 0 && value !== void 0) {
  7507. if (typeof lastSegment === 'string') {
  7508. value = (_a = {}, _a[lastSegment] = value, _a);
  7509. }
  7510. else {
  7511. value = [value];
  7512. }
  7513. }
  7514. else {
  7515. break;
  7516. }
  7517. }
  7518. if (!parent) {
  7519. // empty document
  7520. if (value === void 0) { // delete
  7521. throw new Error('Can not delete in empty document');
  7522. }
  7523. return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
  7524. }
  7525. else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
  7526. var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]);
  7527. if (existing !== void 0) {
  7528. if (value === void 0) { // delete
  7529. if (!existing.parent) {
  7530. throw new Error('Malformed AST');
  7531. }
  7532. var propertyIndex = parent.children.indexOf(existing.parent);
  7533. var removeBegin = void 0;
  7534. var removeEnd = existing.parent.offset + existing.parent.length;
  7535. if (propertyIndex > 0) {
  7536. // remove the comma of the previous node
  7537. var previous = parent.children[propertyIndex - 1];
  7538. removeBegin = previous.offset + previous.length;
  7539. }
  7540. else {
  7541. removeBegin = parent.offset + 1;
  7542. if (parent.children.length > 1) {
  7543. // remove the comma of the next node
  7544. var next = parent.children[1];
  7545. removeEnd = next.offset;
  7546. }
  7547. }
  7548. return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
  7549. }
  7550. else {
  7551. // set value of existing property
  7552. return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
  7553. }
  7554. }
  7555. else {
  7556. if (value === void 0) { // delete
  7557. return []; // property does not exist, nothing to do
  7558. }
  7559. var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
  7560. var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
  7561. var edit = void 0;
  7562. if (index > 0) {
  7563. var previous = parent.children[index - 1];
  7564. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  7565. }
  7566. else if (parent.children.length === 0) {
  7567. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  7568. }
  7569. else {
  7570. edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
  7571. }
  7572. return withFormatting(text, edit, formattingOptions);
  7573. }
  7574. }
  7575. else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
  7576. var insertIndex = lastSegment;
  7577. if (insertIndex === -1) {
  7578. // Insert
  7579. var newProperty = "" + JSON.stringify(value);
  7580. var edit = void 0;
  7581. if (parent.children.length === 0) {
  7582. edit = { offset: parent.offset + 1, length: 0, content: newProperty };
  7583. }
  7584. else {
  7585. var previous = parent.children[parent.children.length - 1];
  7586. edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
  7587. }
  7588. return withFormatting(text, edit, formattingOptions);
  7589. }
  7590. else {
  7591. if (value === void 0 && parent.children.length >= 0) {
  7592. //Removal
  7593. var removalIndex = lastSegment;
  7594. var toRemove = parent.children[removalIndex];
  7595. var edit = void 0;
  7596. if (parent.children.length === 1) {
  7597. // only item
  7598. edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
  7599. }
  7600. else if (parent.children.length - 1 === removalIndex) {
  7601. // last item
  7602. var previous = parent.children[removalIndex - 1];
  7603. var offset = previous.offset + previous.length;
  7604. var parentEndOffset = parent.offset + parent.length;
  7605. edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
  7606. }
  7607. else {
  7608. edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
  7609. }
  7610. return withFormatting(text, edit, formattingOptions);
  7611. }
  7612. else {
  7613. throw new Error('Array modification not supported yet');
  7614. }
  7615. }
  7616. }
  7617. else {
  7618. throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
  7619. }
  7620. }
  7621. function withFormatting(text, edit, formattingOptions) {
  7622. // apply the edit
  7623. var newText = applyEdit(text, edit);
  7624. // format the new text
  7625. var begin = edit.offset;
  7626. var end = edit.offset + edit.content.length;
  7627. if (edit.length === 0 || edit.content.length === 0) { // insert or remove
  7628. while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) {
  7629. begin--;
  7630. }
  7631. while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) {
  7632. end++;
  7633. }
  7634. }
  7635. var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, formattingOptions);
  7636. // apply the formatting edits and track the begin and end offsets of the changes
  7637. for (var i = edits.length - 1; i >= 0; i--) {
  7638. var edit_1 = edits[i];
  7639. newText = applyEdit(newText, edit_1);
  7640. begin = Math.min(begin, edit_1.offset);
  7641. end = Math.max(end, edit_1.offset + edit_1.length);
  7642. end += edit_1.content.length - edit_1.length;
  7643. }
  7644. // create a single edit with all changes
  7645. var editLength = text.length - (newText.length - end) - begin;
  7646. return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
  7647. }
  7648. function applyEdit(text, edit) {
  7649. return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
  7650. }
  7651. function isWS(text, offset) {
  7652. return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
  7653. }
  7654. /***/ }),
  7655. /* 48 */
  7656. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  7657. "use strict";
  7658. __webpack_require__.r(__webpack_exports__);
  7659. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
  7660. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
  7661. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
  7662. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
  7663. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
  7664. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
  7665. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
  7666. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
  7667. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
  7668. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
  7669. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeType", function() { return getNodeType; });
  7670. /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
  7671. /*---------------------------------------------------------------------------------------------
  7672. * Copyright (c) Microsoft Corporation. All rights reserved.
  7673. * Licensed under the MIT License. See License.txt in the project root for license information.
  7674. *--------------------------------------------------------------------------------------------*/
  7675. var ParseOptions;
  7676. (function (ParseOptions) {
  7677. ParseOptions.DEFAULT = {
  7678. allowTrailingComma: false
  7679. };
  7680. })(ParseOptions || (ParseOptions = {}));
  7681. /**
  7682. * 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.
  7683. */
  7684. function getLocation(text, position) {
  7685. var segments = []; // strings or numbers
  7686. var earlyReturnException = new Object();
  7687. var previousNode = undefined;
  7688. var previousNodeInst = {
  7689. value: {},
  7690. offset: 0,
  7691. length: 0,
  7692. type: 'object',
  7693. parent: undefined
  7694. };
  7695. var isAtPropertyKey = false;
  7696. function setPreviousNode(value, offset, length, type) {
  7697. previousNodeInst.value = value;
  7698. previousNodeInst.offset = offset;
  7699. previousNodeInst.length = length;
  7700. previousNodeInst.type = type;
  7701. previousNodeInst.colonOffset = undefined;
  7702. previousNode = previousNodeInst;
  7703. }
  7704. try {
  7705. visit(text, {
  7706. onObjectBegin: function (offset, length) {
  7707. if (position <= offset) {
  7708. throw earlyReturnException;
  7709. }
  7710. previousNode = undefined;
  7711. isAtPropertyKey = position > offset;
  7712. segments.push(''); // push a placeholder (will be replaced)
  7713. },
  7714. onObjectProperty: function (name, offset, length) {
  7715. if (position < offset) {
  7716. throw earlyReturnException;
  7717. }
  7718. setPreviousNode(name, offset, length, 'property');
  7719. segments[segments.length - 1] = name;
  7720. if (position <= offset + length) {
  7721. throw earlyReturnException;
  7722. }
  7723. },
  7724. onObjectEnd: function (offset, length) {
  7725. if (position <= offset) {
  7726. throw earlyReturnException;
  7727. }
  7728. previousNode = undefined;
  7729. segments.pop();
  7730. },
  7731. onArrayBegin: function (offset, length) {
  7732. if (position <= offset) {
  7733. throw earlyReturnException;
  7734. }
  7735. previousNode = undefined;
  7736. segments.push(0);
  7737. },
  7738. onArrayEnd: function (offset, length) {
  7739. if (position <= offset) {
  7740. throw earlyReturnException;
  7741. }
  7742. previousNode = undefined;
  7743. segments.pop();
  7744. },
  7745. onLiteralValue: function (value, offset, length) {
  7746. if (position < offset) {
  7747. throw earlyReturnException;
  7748. }
  7749. setPreviousNode(value, offset, length, getNodeType(value));
  7750. if (position <= offset + length) {
  7751. throw earlyReturnException;
  7752. }
  7753. },
  7754. onSeparator: function (sep, offset, length) {
  7755. if (position <= offset) {
  7756. throw earlyReturnException;
  7757. }
  7758. if (sep === ':' && previousNode && previousNode.type === 'property') {
  7759. previousNode.colonOffset = offset;
  7760. isAtPropertyKey = false;
  7761. previousNode = undefined;
  7762. }
  7763. else if (sep === ',') {
  7764. var last = segments[segments.length - 1];
  7765. if (typeof last === 'number') {
  7766. segments[segments.length - 1] = last + 1;
  7767. }
  7768. else {
  7769. isAtPropertyKey = true;
  7770. segments[segments.length - 1] = '';
  7771. }
  7772. previousNode = undefined;
  7773. }
  7774. }
  7775. });
  7776. }
  7777. catch (e) {
  7778. if (e !== earlyReturnException) {
  7779. throw e;
  7780. }
  7781. }
  7782. return {
  7783. path: segments,
  7784. previousNode: previousNode,
  7785. isAtPropertyKey: isAtPropertyKey,
  7786. matches: function (pattern) {
  7787. var k = 0;
  7788. for (var i = 0; k < pattern.length && i < segments.length; i++) {
  7789. if (pattern[k] === segments[i] || pattern[k] === '*') {
  7790. k++;
  7791. }
  7792. else if (pattern[k] !== '**') {
  7793. return false;
  7794. }
  7795. }
  7796. return k === pattern.length;
  7797. }
  7798. };
  7799. }
  7800. /**
  7801. * 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.
  7802. * Therefore always check the errors list to find out if the input was valid.
  7803. */
  7804. function parse(text, errors, options) {
  7805. if (errors === void 0) { errors = []; }
  7806. if (options === void 0) { options = ParseOptions.DEFAULT; }
  7807. var currentProperty = null;
  7808. var currentParent = [];
  7809. var previousParents = [];
  7810. function onValue(value) {
  7811. if (Array.isArray(currentParent)) {
  7812. currentParent.push(value);
  7813. }
  7814. else if (currentProperty !== null) {
  7815. currentParent[currentProperty] = value;
  7816. }
  7817. }
  7818. var visitor = {
  7819. onObjectBegin: function () {
  7820. var object = {};
  7821. onValue(object);
  7822. previousParents.push(currentParent);
  7823. currentParent = object;
  7824. currentProperty = null;
  7825. },
  7826. onObjectProperty: function (name) {
  7827. currentProperty = name;
  7828. },
  7829. onObjectEnd: function () {
  7830. currentParent = previousParents.pop();
  7831. },
  7832. onArrayBegin: function () {
  7833. var array = [];
  7834. onValue(array);
  7835. previousParents.push(currentParent);
  7836. currentParent = array;
  7837. currentProperty = null;
  7838. },
  7839. onArrayEnd: function () {
  7840. currentParent = previousParents.pop();
  7841. },
  7842. onLiteralValue: onValue,
  7843. onError: function (error, offset, length) {
  7844. errors.push({ error: error, offset: offset, length: length });
  7845. }
  7846. };
  7847. visit(text, visitor, options);
  7848. return currentParent[0];
  7849. }
  7850. /**
  7851. * 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.
  7852. */
  7853. function parseTree(text, errors, options) {
  7854. if (errors === void 0) { errors = []; }
  7855. if (options === void 0) { options = ParseOptions.DEFAULT; }
  7856. var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
  7857. function ensurePropertyComplete(endOffset) {
  7858. if (currentParent.type === 'property') {
  7859. currentParent.length = endOffset - currentParent.offset;
  7860. currentParent = currentParent.parent;
  7861. }
  7862. }
  7863. function onValue(valueNode) {
  7864. currentParent.children.push(valueNode);
  7865. return valueNode;
  7866. }
  7867. var visitor = {
  7868. onObjectBegin: function (offset) {
  7869. currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
  7870. },
  7871. onObjectProperty: function (name, offset, length) {
  7872. currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
  7873. currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
  7874. },
  7875. onObjectEnd: function (offset, length) {
  7876. ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
  7877. currentParent.length = offset + length - currentParent.offset;
  7878. currentParent = currentParent.parent;
  7879. ensurePropertyComplete(offset + length);
  7880. },
  7881. onArrayBegin: function (offset, length) {
  7882. currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
  7883. },
  7884. onArrayEnd: function (offset, length) {
  7885. currentParent.length = offset + length - currentParent.offset;
  7886. currentParent = currentParent.parent;
  7887. ensurePropertyComplete(offset + length);
  7888. },
  7889. onLiteralValue: function (value, offset, length) {
  7890. onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
  7891. ensurePropertyComplete(offset + length);
  7892. },
  7893. onSeparator: function (sep, offset, length) {
  7894. if (currentParent.type === 'property') {
  7895. if (sep === ':') {
  7896. currentParent.colonOffset = offset;
  7897. }
  7898. else if (sep === ',') {
  7899. ensurePropertyComplete(offset);
  7900. }
  7901. }
  7902. },
  7903. onError: function (error, offset, length) {
  7904. errors.push({ error: error, offset: offset, length: length });
  7905. }
  7906. };
  7907. visit(text, visitor, options);
  7908. var result = currentParent.children[0];
  7909. if (result) {
  7910. delete result.parent;
  7911. }
  7912. return result;
  7913. }
  7914. /**
  7915. * Finds the node at the given path in a JSON DOM.
  7916. */
  7917. function findNodeAtLocation(root, path) {
  7918. if (!root) {
  7919. return undefined;
  7920. }
  7921. var node = root;
  7922. for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
  7923. var segment = path_1[_i];
  7924. if (typeof segment === 'string') {
  7925. if (node.type !== 'object' || !Array.isArray(node.children)) {
  7926. return undefined;
  7927. }
  7928. var found = false;
  7929. for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
  7930. var propertyNode = _b[_a];
  7931. if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
  7932. node = propertyNode.children[1];
  7933. found = true;
  7934. break;
  7935. }
  7936. }
  7937. if (!found) {
  7938. return undefined;
  7939. }
  7940. }
  7941. else {
  7942. var index = segment;
  7943. if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
  7944. return undefined;
  7945. }
  7946. node = node.children[index];
  7947. }
  7948. }
  7949. return node;
  7950. }
  7951. /**
  7952. * Gets the JSON path of the given JSON DOM node
  7953. */
  7954. function getNodePath(node) {
  7955. if (!node.parent || !node.parent.children) {
  7956. return [];
  7957. }
  7958. var path = getNodePath(node.parent);
  7959. if (node.parent.type === 'property') {
  7960. var key = node.parent.children[0].value;
  7961. path.push(key);
  7962. }
  7963. else if (node.parent.type === 'array') {
  7964. var index = node.parent.children.indexOf(node);
  7965. if (index !== -1) {
  7966. path.push(index);
  7967. }
  7968. }
  7969. return path;
  7970. }
  7971. /**
  7972. * Evaluates the JavaScript object of the given JSON DOM node
  7973. */
  7974. function getNodeValue(node) {
  7975. switch (node.type) {
  7976. case 'array':
  7977. return node.children.map(getNodeValue);
  7978. case 'object':
  7979. var obj = Object.create(null);
  7980. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  7981. var prop = _a[_i];
  7982. var valueNode = prop.children[1];
  7983. if (valueNode) {
  7984. obj[prop.children[0].value] = getNodeValue(valueNode);
  7985. }
  7986. }
  7987. return obj;
  7988. case 'null':
  7989. case 'string':
  7990. case 'number':
  7991. case 'boolean':
  7992. return node.value;
  7993. default:
  7994. return undefined;
  7995. }
  7996. }
  7997. function contains(node, offset, includeRightBound) {
  7998. if (includeRightBound === void 0) { includeRightBound = false; }
  7999. return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
  8000. }
  8001. /**
  8002. * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  8003. */
  8004. function findNodeAtOffset(node, offset, includeRightBound) {
  8005. if (includeRightBound === void 0) { includeRightBound = false; }
  8006. if (contains(node, offset, includeRightBound)) {
  8007. var children = node.children;
  8008. if (Array.isArray(children)) {
  8009. for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
  8010. var item = findNodeAtOffset(children[i], offset, includeRightBound);
  8011. if (item) {
  8012. return item;
  8013. }
  8014. }
  8015. }
  8016. return node;
  8017. }
  8018. return undefined;
  8019. }
  8020. /**
  8021. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  8022. */
  8023. function visit(text, visitor, options) {
  8024. if (options === void 0) { options = ParseOptions.DEFAULT; }
  8025. var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false);
  8026. function toNoArgVisit(visitFunction) {
  8027. return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  8028. }
  8029. function toOneArgVisit(visitFunction) {
  8030. return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
  8031. }
  8032. var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  8033. var disallowComments = options && options.disallowComments;
  8034. var allowTrailingComma = options && options.allowTrailingComma;
  8035. function scanNext() {
  8036. while (true) {
  8037. var token = _scanner.scan();
  8038. switch (_scanner.getTokenError()) {
  8039. case 4 /* InvalidUnicode */:
  8040. handleError(14 /* InvalidUnicode */);
  8041. break;
  8042. case 5 /* InvalidEscapeCharacter */:
  8043. handleError(15 /* InvalidEscapeCharacter */);
  8044. break;
  8045. case 3 /* UnexpectedEndOfNumber */:
  8046. handleError(13 /* UnexpectedEndOfNumber */);
  8047. break;
  8048. case 1 /* UnexpectedEndOfComment */:
  8049. if (!disallowComments) {
  8050. handleError(11 /* UnexpectedEndOfComment */);
  8051. }
  8052. break;
  8053. case 2 /* UnexpectedEndOfString */:
  8054. handleError(12 /* UnexpectedEndOfString */);
  8055. break;
  8056. case 6 /* InvalidCharacter */:
  8057. handleError(16 /* InvalidCharacter */);
  8058. break;
  8059. }
  8060. switch (token) {
  8061. case 12 /* LineCommentTrivia */:
  8062. case 13 /* BlockCommentTrivia */:
  8063. if (disallowComments) {
  8064. handleError(10 /* InvalidCommentToken */);
  8065. }
  8066. else {
  8067. onComment();
  8068. }
  8069. break;
  8070. case 16 /* Unknown */:
  8071. handleError(1 /* InvalidSymbol */);
  8072. break;
  8073. case 15 /* Trivia */:
  8074. case 14 /* LineBreakTrivia */:
  8075. break;
  8076. default:
  8077. return token;
  8078. }
  8079. }
  8080. }
  8081. function handleError(error, skipUntilAfter, skipUntil) {
  8082. if (skipUntilAfter === void 0) { skipUntilAfter = []; }
  8083. if (skipUntil === void 0) { skipUntil = []; }
  8084. onError(error);
  8085. if (skipUntilAfter.length + skipUntil.length > 0) {
  8086. var token = _scanner.getToken();
  8087. while (token !== 17 /* EOF */) {
  8088. if (skipUntilAfter.indexOf(token) !== -1) {
  8089. scanNext();
  8090. break;
  8091. }
  8092. else if (skipUntil.indexOf(token) !== -1) {
  8093. break;
  8094. }
  8095. token = scanNext();
  8096. }
  8097. }
  8098. }
  8099. function parseString(isValue) {
  8100. var value = _scanner.getTokenValue();
  8101. if (isValue) {
  8102. onLiteralValue(value);
  8103. }
  8104. else {
  8105. onObjectProperty(value);
  8106. }
  8107. scanNext();
  8108. return true;
  8109. }
  8110. function parseLiteral() {
  8111. switch (_scanner.getToken()) {
  8112. case 11 /* NumericLiteral */:
  8113. var value = 0;
  8114. try {
  8115. value = JSON.parse(_scanner.getTokenValue());
  8116. if (typeof value !== 'number') {
  8117. handleError(2 /* InvalidNumberFormat */);
  8118. value = 0;
  8119. }
  8120. }
  8121. catch (e) {
  8122. handleError(2 /* InvalidNumberFormat */);
  8123. }
  8124. onLiteralValue(value);
  8125. break;
  8126. case 7 /* NullKeyword */:
  8127. onLiteralValue(null);
  8128. break;
  8129. case 8 /* TrueKeyword */:
  8130. onLiteralValue(true);
  8131. break;
  8132. case 9 /* FalseKeyword */:
  8133. onLiteralValue(false);
  8134. break;
  8135. default:
  8136. return false;
  8137. }
  8138. scanNext();
  8139. return true;
  8140. }
  8141. function parseProperty() {
  8142. if (_scanner.getToken() !== 10 /* StringLiteral */) {
  8143. handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  8144. return false;
  8145. }
  8146. parseString(false);
  8147. if (_scanner.getToken() === 6 /* ColonToken */) {
  8148. onSeparator(':');
  8149. scanNext(); // consume colon
  8150. if (!parseValue()) {
  8151. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  8152. }
  8153. }
  8154. else {
  8155. handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  8156. }
  8157. return true;
  8158. }
  8159. function parseObject() {
  8160. onObjectBegin();
  8161. scanNext(); // consume open brace
  8162. var needsComma = false;
  8163. while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
  8164. if (_scanner.getToken() === 5 /* CommaToken */) {
  8165. if (!needsComma) {
  8166. handleError(4 /* ValueExpected */, [], []);
  8167. }
  8168. onSeparator(',');
  8169. scanNext(); // consume comma
  8170. if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
  8171. break;
  8172. }
  8173. }
  8174. else if (needsComma) {
  8175. handleError(6 /* CommaExpected */, [], []);
  8176. }
  8177. if (!parseProperty()) {
  8178. handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
  8179. }
  8180. needsComma = true;
  8181. }
  8182. onObjectEnd();
  8183. if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
  8184. handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
  8185. }
  8186. else {
  8187. scanNext(); // consume close brace
  8188. }
  8189. return true;
  8190. }
  8191. function parseArray() {
  8192. onArrayBegin();
  8193. scanNext(); // consume open bracket
  8194. var needsComma = false;
  8195. while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
  8196. if (_scanner.getToken() === 5 /* CommaToken */) {
  8197. if (!needsComma) {
  8198. handleError(4 /* ValueExpected */, [], []);
  8199. }
  8200. onSeparator(',');
  8201. scanNext(); // consume comma
  8202. if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
  8203. break;
  8204. }
  8205. }
  8206. else if (needsComma) {
  8207. handleError(6 /* CommaExpected */, [], []);
  8208. }
  8209. if (!parseValue()) {
  8210. handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
  8211. }
  8212. needsComma = true;
  8213. }
  8214. onArrayEnd();
  8215. if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
  8216. handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
  8217. }
  8218. else {
  8219. scanNext(); // consume close bracket
  8220. }
  8221. return true;
  8222. }
  8223. function parseValue() {
  8224. switch (_scanner.getToken()) {
  8225. case 3 /* OpenBracketToken */:
  8226. return parseArray();
  8227. case 1 /* OpenBraceToken */:
  8228. return parseObject();
  8229. case 10 /* StringLiteral */:
  8230. return parseString(true);
  8231. default:
  8232. return parseLiteral();
  8233. }
  8234. }
  8235. scanNext();
  8236. if (_scanner.getToken() === 17 /* EOF */) {
  8237. if (options.allowEmptyContent) {
  8238. return true;
  8239. }
  8240. handleError(4 /* ValueExpected */, [], []);
  8241. return false;
  8242. }
  8243. if (!parseValue()) {
  8244. handleError(4 /* ValueExpected */, [], []);
  8245. return false;
  8246. }
  8247. if (_scanner.getToken() !== 17 /* EOF */) {
  8248. handleError(9 /* EndOfFileExpected */, [], []);
  8249. }
  8250. return true;
  8251. }
  8252. /**
  8253. * Takes JSON with JavaScript-style comments and remove
  8254. * them. Optionally replaces every none-newline character
  8255. * of comments with a replaceCharacter
  8256. */
  8257. function stripComments(text, replaceCh) {
  8258. var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos;
  8259. do {
  8260. pos = _scanner.getPosition();
  8261. kind = _scanner.scan();
  8262. switch (kind) {
  8263. case 12 /* LineCommentTrivia */:
  8264. case 13 /* BlockCommentTrivia */:
  8265. case 17 /* EOF */:
  8266. if (offset !== pos) {
  8267. parts.push(text.substring(offset, pos));
  8268. }
  8269. if (replaceCh !== undefined) {
  8270. parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
  8271. }
  8272. offset = _scanner.getPosition();
  8273. break;
  8274. }
  8275. } while (kind !== 17 /* EOF */);
  8276. return parts.join('');
  8277. }
  8278. function getNodeType(value) {
  8279. switch (typeof value) {
  8280. case 'boolean': return 'boolean';
  8281. case 'number': return 'number';
  8282. case 'string': return 'string';
  8283. case 'object': {
  8284. if (!value) {
  8285. return 'null';
  8286. }
  8287. else if (Array.isArray(value)) {
  8288. return 'array';
  8289. }
  8290. return 'object';
  8291. }
  8292. default: return 'null';
  8293. }
  8294. }
  8295. /***/ }),
  8296. /* 49 */
  8297. /***/ (function(module, exports, __webpack_require__) {
  8298. "use strict";
  8299. var __importDefault = (this && this.__importDefault) || function (mod) {
  8300. return (mod && mod.__esModule) ? mod : { "default": mod };
  8301. };
  8302. Object.defineProperty(exports, "__esModule", { value: true });
  8303. /******************************************************************
  8304. MIT License http://www.opensource.org/licenses/mit-license.php
  8305. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  8306. *******************************************************************/
  8307. const coc_nvim_1 = __webpack_require__(1);
  8308. const fs_1 = __importDefault(__webpack_require__(3));
  8309. const os_1 = __importDefault(__webpack_require__(2));
  8310. const path_1 = __importDefault(__webpack_require__(4));
  8311. const vscode_languageserver_types_1 = __webpack_require__(6);
  8312. const baseProvider_1 = __importDefault(__webpack_require__(41));
  8313. const types_1 = __webpack_require__(36);
  8314. const ultisnipsParser_1 = __importDefault(__webpack_require__(50));
  8315. const util_1 = __webpack_require__(37);
  8316. const pythonCodes = new Map();
  8317. class UltiSnippetsProvider extends baseProvider_1.default {
  8318. constructor(channel, trace, config, context) {
  8319. super(config);
  8320. this.channel = channel;
  8321. this.trace = trace;
  8322. this.config = config;
  8323. this.context = context;
  8324. this.snippetFiles = [];
  8325. this.disposables = [];
  8326. this.directories = [];
  8327. this.runtimeDirs = [];
  8328. this.runtimeDirs = coc_nvim_1.workspace.env.runtimepath.split(',');
  8329. coc_nvim_1.workspace.watchOption('runtimepath', async (_, newValue) => {
  8330. let parts = newValue.split(',');
  8331. let subFolders = await this.getSubFolders();
  8332. let items = [];
  8333. for (let dir of parts) {
  8334. if (this.runtimeDirs.indexOf(dir) == -1) {
  8335. this.runtimeDirs.push(dir);
  8336. let res = await this.getSnippetsFromPlugin(dir, subFolders);
  8337. items.push(...res);
  8338. }
  8339. }
  8340. if (items.length) {
  8341. await Promise.all(items.map(({ filepath, directory, filetype }) => {
  8342. return this.loadSnippetsFromFile(filetype, directory, filepath);
  8343. }));
  8344. let files = items.map(o => o.filepath);
  8345. let pythonCode = '';
  8346. for (let file of files) {
  8347. let code = pythonCodes.get(file);
  8348. if (code) {
  8349. pythonCode += `# ${file}\n` + code + '\n';
  8350. }
  8351. }
  8352. if (pythonCode) {
  8353. pythonCodes.clear();
  8354. await this.executePythonCode(pythonCode);
  8355. }
  8356. }
  8357. }, this.disposables);
  8358. }
  8359. checkLoaded(filepath) {
  8360. return this.snippetFiles.findIndex(o => o.filepath == filepath) !== -1;
  8361. }
  8362. async init() {
  8363. let { nvim, env } = coc_nvim_1.workspace;
  8364. let { runtimepath } = env;
  8365. let { config } = this;
  8366. for (let dir of config.directories) {
  8367. if (dir.startsWith('~') || dir.indexOf('$') !== -1) {
  8368. let res = await coc_nvim_1.workspace.nvim.call('expand', [dir]);
  8369. this.directories.push(res);
  8370. }
  8371. else {
  8372. this.directories.push(dir);
  8373. }
  8374. }
  8375. this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Using ultisnips directories: ${this.directories.join(' ')}`);
  8376. let hasPythonx = await nvim.call('has', ['pythonx']);
  8377. let pythonCode = await util_1.readFileAsync(this.context.asAbsolutePath('python/ultisnips.py'), 'utf8');
  8378. if (hasPythonx && config.usePythonx) {
  8379. this.pyMethod = 'pyx';
  8380. }
  8381. else {
  8382. this.pyMethod = config.pythonVersion == 3 ? 'py3' : 'py';
  8383. }
  8384. this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Using ultisnips python command: ${this.pyMethod}`);
  8385. this.parser = new ultisnipsParser_1.default(this.pyMethod, this.channel, this.trace);
  8386. let arr = await this.getAllSnippetFiles(runtimepath);
  8387. let files = arr.map(o => o.filepath);
  8388. await Promise.all(arr.map(({ filepath, directory, filetype }) => {
  8389. return this.loadSnippetsFromFile(filetype, directory, filepath);
  8390. }));
  8391. for (let file of files) {
  8392. let code = pythonCodes.get(file);
  8393. if (code) {
  8394. pythonCode += `\n# ${file}\n` + code + '\n';
  8395. }
  8396. }
  8397. await this.executePythonCode(pythonCode);
  8398. coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
  8399. let uri = coc_nvim_1.Uri.parse(doc.uri);
  8400. if (uri.scheme != 'file' || !doc.uri.endsWith('.snippets'))
  8401. return;
  8402. let filepath = uri.fsPath;
  8403. if (!fs_1.default.existsSync(filepath))
  8404. return;
  8405. let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
  8406. if (snippetFile) {
  8407. await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
  8408. }
  8409. else {
  8410. let filetype = path_1.default.basename(filepath, '.snippets');
  8411. await this.loadSnippetsFromFile(filetype, path_1.default.dirname(filepath), filepath);
  8412. }
  8413. }, null, this.disposables);
  8414. }
  8415. async loadSnippetsFromFile(filetype, directory, filepath) {
  8416. let { snippets, pythonCode, extendFiletypes, clearsnippets } = await this.parser.parseUltisnipsFile(filepath);
  8417. let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
  8418. if (idx !== -1)
  8419. this.snippetFiles.splice(idx, 1);
  8420. this.snippetFiles.push({
  8421. extendFiletypes,
  8422. clearsnippets,
  8423. directory,
  8424. filepath,
  8425. filetype,
  8426. snippets
  8427. });
  8428. if (extendFiletypes) {
  8429. let filetypes = this.config.extends[filetype] || [];
  8430. filetypes = filetypes.concat(extendFiletypes);
  8431. this.config.extends[filetype] = util_1.distinct(filetypes);
  8432. }
  8433. if (this.trace == 'verbose') {
  8434. this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Loaded ${snippets.length} snippets from: ${filepath}`);
  8435. }
  8436. pythonCodes.set(filepath, pythonCode);
  8437. }
  8438. async resolveSnippetBody(snippet, range, line) {
  8439. let { nvim } = coc_nvim_1.workspace;
  8440. let { body, context, originRegex } = snippet;
  8441. let buf = await nvim.buffer;
  8442. let filepath = await buf.name;
  8443. let indentCount = await nvim.call('indent', '.');
  8444. let ind = ' '.repeat(indentCount);
  8445. if (body.indexOf('`!p') !== -1) {
  8446. let values = new Map();
  8447. let re = /\$\{(\d+)(?::([^}]+))?\}/g;
  8448. let r;
  8449. // tslint:disable-next-line: no-conditional-assignment
  8450. while (r = re.exec(body)) {
  8451. let idx = parseInt(r[1], 10);
  8452. let val = r[2] || '';
  8453. let exists = values.get(idx);
  8454. if (exists == null || (val && exists == "''")) {
  8455. if (/^`!\w/.test(val) && val.endsWith('`')) {
  8456. let code = val.slice(1).slice(0, -1);
  8457. val = await this.parser.execute(code, this.pyMethod, ind);
  8458. }
  8459. val = val.replace(/'/g, "\\'").replace(/\n/g, '\\n');
  8460. values.set(idx, "'" + val + "'");
  8461. }
  8462. }
  8463. re = /\$(\d+)/g;
  8464. // tslint:disable-next-line: no-conditional-assignment
  8465. while (r = re.exec(body)) {
  8466. let idx = parseInt(r[1], 10);
  8467. if (!values.has(idx)) {
  8468. values.set(idx, "''");
  8469. }
  8470. }
  8471. let len = values.size == 0 ? 0 : Math.max.apply(null, Array.from(values.keys()));
  8472. let vals = (new Array(len)).fill('""');
  8473. for (let [idx, val] of values.entries()) {
  8474. vals[idx] = val;
  8475. }
  8476. let pyCodes = [];
  8477. pyCodes.push('import re, os, vim, string, random');
  8478. pyCodes.push(`t = ('', ${vals.join(',')})`);
  8479. pyCodes.push(`fn = '${path_1.default.basename(filepath)}'`);
  8480. pyCodes.push(`path = '${filepath}'`);
  8481. if (context) {
  8482. pyCodes.push(`snip = ContextSnippet()`);
  8483. pyCodes.push(`context = ${context}`);
  8484. }
  8485. else {
  8486. pyCodes.push(`context = {}`);
  8487. }
  8488. let start = `(${range.start.line},${Buffer.byteLength(line.slice(0, range.start.character))})`;
  8489. let end = `(${range.end.line},${Buffer.byteLength(line.slice(0, range.end.character))})`;
  8490. pyCodes.push(`snip = SnippetUtil('${ind}', ${start}, ${end}, context)`);
  8491. if (originRegex) {
  8492. pyCodes.push(`pattern = re.compile(r"${originRegex.replace(/"/g, '\\"')}")`);
  8493. pyCodes.push(`match = pattern.search("${line.replace(/"/g, '\\"')}")`);
  8494. }
  8495. try {
  8496. await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
  8497. }
  8498. catch (e) {
  8499. this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
  8500. this.channel.appendLine(`code: ${pyCodes.join('\n')}`);
  8501. }
  8502. }
  8503. return this.parser.resolveUltisnipsBody(body);
  8504. }
  8505. async checkContext(context) {
  8506. let { nvim } = coc_nvim_1.workspace;
  8507. let pyCodes = [];
  8508. pyCodes.push('import re, os, vim, string, random');
  8509. pyCodes.push(`snip = ContextSnippet()`);
  8510. pyCodes.push(`context = ${context}`);
  8511. await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
  8512. let res = await nvim.call(`${this.pyMethod}eval`, 'True if context else False');
  8513. return res;
  8514. }
  8515. async getTriggerSnippets(document, position, autoTrigger) {
  8516. let snippets = await this.getSnippets(document.filetype);
  8517. let line = document.getline(position.line);
  8518. line = line.slice(0, position.character);
  8519. if (!line || line[line.length - 1] == ' ')
  8520. return [];
  8521. snippets = snippets.filter(s => {
  8522. let { prefix, regex } = s;
  8523. if (autoTrigger && !s.autoTrigger)
  8524. return false;
  8525. if (regex) {
  8526. let ms = line.match(regex);
  8527. if (!ms)
  8528. return false;
  8529. prefix = ms[0];
  8530. }
  8531. if (!line.endsWith(prefix))
  8532. return false;
  8533. if (s.triggerKind == types_1.TriggerKind.InWord)
  8534. return true;
  8535. let pre = line.slice(0, line.length - prefix.length);
  8536. if (s.triggerKind == types_1.TriggerKind.LineBegin)
  8537. return pre.trim() == '';
  8538. if (s.triggerKind == types_1.TriggerKind.SpaceBefore)
  8539. return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
  8540. if (s.triggerKind == types_1.TriggerKind.WordBoundary)
  8541. return pre.length == 0 || !document.isWord(pre[pre.length - 1]);
  8542. return false;
  8543. });
  8544. snippets.sort((a, b) => {
  8545. if (a.context && !b.context)
  8546. return -1;
  8547. if (b.context && !a.context)
  8548. return 1;
  8549. return 0;
  8550. });
  8551. let edits = [];
  8552. let contextPrefixes = [];
  8553. for (let s of snippets) {
  8554. let character;
  8555. if (s.context) {
  8556. let valid = await this.checkContext(s.context);
  8557. if (!valid)
  8558. continue;
  8559. contextPrefixes.push(s.context);
  8560. }
  8561. else if (contextPrefixes.indexOf(s.prefix) !== -1) {
  8562. continue;
  8563. }
  8564. if (s.regex == null) {
  8565. character = position.character - s.prefix.length;
  8566. }
  8567. else {
  8568. let len = line.match(s.regex)[0].length;
  8569. character = position.character - len;
  8570. }
  8571. let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
  8572. let newText = await this.resolveSnippetBody(s, range, line);
  8573. edits.push({
  8574. prefix: s.prefix,
  8575. description: s.description,
  8576. location: s.filepath,
  8577. priority: s.priority,
  8578. range,
  8579. newText,
  8580. });
  8581. }
  8582. return edits;
  8583. }
  8584. async getSnippetFiles(filetype) {
  8585. let filetypes = this.getFiletypes(filetype);
  8586. let res = [];
  8587. for (let s of this.snippetFiles) {
  8588. if (filetypes.indexOf(s.filetype) !== -1) {
  8589. res.push(s.filepath);
  8590. }
  8591. }
  8592. return res;
  8593. }
  8594. async getSnippets(filetype) {
  8595. let filetypes = this.getFiletypes(filetype);
  8596. filetypes.push('all');
  8597. let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
  8598. let min = null;
  8599. let result = [];
  8600. snippetFiles.sort((a, b) => {
  8601. if (a.filetype == b.filetype)
  8602. return 1;
  8603. if (a.filetype == filetype)
  8604. return -1;
  8605. return 1;
  8606. });
  8607. for (let file of snippetFiles) {
  8608. let { snippets, clearsnippets } = file;
  8609. if (typeof clearsnippets == 'number') {
  8610. min = min ? Math.max(min, clearsnippets) : clearsnippets;
  8611. }
  8612. for (let snip of snippets) {
  8613. if (snip.regex || snip.context) {
  8614. result.push(snip);
  8615. }
  8616. else {
  8617. let idx = result.findIndex(o => o.prefix == snip.prefix && o.triggerKind == snip.triggerKind);
  8618. if (idx == -1) {
  8619. result.push(snip);
  8620. }
  8621. else {
  8622. let item = result[idx];
  8623. if (snip.priority > item.priority) {
  8624. result[idx] = item;
  8625. }
  8626. }
  8627. }
  8628. }
  8629. }
  8630. if (min != null)
  8631. result = result.filter(o => o.priority >= min);
  8632. result.sort((a, b) => {
  8633. if (a.context && !b.context)
  8634. return -1;
  8635. if (b.context && !a.context)
  8636. return 1;
  8637. return 0;
  8638. });
  8639. return result;
  8640. }
  8641. async getAllSnippetFiles(runtimepath) {
  8642. let { directories } = this;
  8643. let res = [];
  8644. for (let directory of directories) {
  8645. if (path_1.default.isAbsolute(directory)) {
  8646. let items = await this.getSnippetFileItems(directory);
  8647. res.push(...items);
  8648. }
  8649. }
  8650. let subFolders = await this.getSubFolders();
  8651. let rtps = runtimepath.split(',');
  8652. this.runtimeDirs = rtps;
  8653. for (let rtp of rtps) {
  8654. let items = await this.getSnippetsFromPlugin(rtp, subFolders);
  8655. res.push(...items);
  8656. }
  8657. return res;
  8658. }
  8659. async getSubFolders() {
  8660. let { directories } = this;
  8661. directories = directories.filter(s => !path_1.default.isAbsolute(s));
  8662. // use UltiSnipsSnippetDirectories
  8663. let dirs = await coc_nvim_1.workspace.nvim.eval('get(g:, "UltiSnipsSnippetDirectories", [])');
  8664. for (let dir of dirs) {
  8665. if (directories.indexOf(dir) == -1) {
  8666. directories.push(dir);
  8667. }
  8668. }
  8669. return directories;
  8670. }
  8671. async getSnippetsFromPlugin(directory, subFolders) {
  8672. let res = [];
  8673. for (let folder of subFolders) {
  8674. let items = await this.getSnippetFileItems(path_1.default.join(directory, folder));
  8675. res.push(...items);
  8676. }
  8677. return res;
  8678. }
  8679. async getSnippetFileItems(directory) {
  8680. let res = [];
  8681. let stat = await util_1.statAsync(directory);
  8682. if (stat && stat.isDirectory()) {
  8683. let files = await util_1.readdirAsync(directory);
  8684. if (files.length) {
  8685. for (let f of files) {
  8686. let file = path_1.default.join(directory, f);
  8687. if (file.endsWith('.snippets')) {
  8688. let basename = path_1.default.basename(f, '.snippets');
  8689. let filetype = basename.split('_', 2)[0];
  8690. res.push({ filepath: file, directory, filetype });
  8691. }
  8692. else {
  8693. let stat = await util_1.statAsync(file);
  8694. if (stat && stat.isDirectory()) {
  8695. let files = await util_1.readdirAsync(file);
  8696. for (let filename of files) {
  8697. if (filename.endsWith('.snippets')) {
  8698. res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
  8699. }
  8700. }
  8701. }
  8702. }
  8703. }
  8704. }
  8705. }
  8706. return res;
  8707. }
  8708. async executePythonCode(pythonCode) {
  8709. try {
  8710. let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
  8711. if (!fs_1.default.existsSync(dir))
  8712. fs_1.default.mkdirSync(dir);
  8713. let tmpfile = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`, `coc-ultisnips-${util_1.uid()}.py`);
  8714. fs_1.default.writeFileSync(tmpfile, '# -*- coding: utf-8 -*-\n' + pythonCode, 'utf8');
  8715. await coc_nvim_1.workspace.nvim.command(`exe '${this.pyMethod}file '.fnameescape('${tmpfile}')`);
  8716. pythonCodes.clear();
  8717. }
  8718. catch (e) {
  8719. this.channel.appendLine(`Error on execute python script:`);
  8720. this.channel.append(e.message);
  8721. coc_nvim_1.workspace.showMessage(`Error on execute python script: ${e.message}`, 'error');
  8722. }
  8723. }
  8724. dispose() {
  8725. coc_nvim_1.disposeAll(this.disposables);
  8726. }
  8727. }
  8728. exports.UltiSnippetsProvider = UltiSnippetsProvider;
  8729. /***/ }),
  8730. /* 50 */
  8731. /***/ (function(module, exports, __webpack_require__) {
  8732. "use strict";
  8733. var __importDefault = (this && this.__importDefault) || function (mod) {
  8734. return (mod && mod.__esModule) ? mod : { "default": mod };
  8735. };
  8736. Object.defineProperty(exports, "__esModule", { value: true });
  8737. /******************************************************************
  8738. MIT License http://www.opensource.org/licenses/mit-license.php
  8739. Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
  8740. *******************************************************************/
  8741. const child_process_1 = __webpack_require__(51);
  8742. const coc_nvim_1 = __webpack_require__(1);
  8743. const fs_1 = __importDefault(__webpack_require__(3));
  8744. const pify_1 = __importDefault(__webpack_require__(38));
  8745. const readline_1 = __importDefault(__webpack_require__(40));
  8746. const parser_1 = __importDefault(__webpack_require__(42));
  8747. const types_1 = __webpack_require__(36);
  8748. const util_1 = __webpack_require__(37);
  8749. class UltiSnipsParser {
  8750. constructor(pyMethod, channel, trace = 'error') {
  8751. this.pyMethod = pyMethod;
  8752. this.channel = channel;
  8753. this.trace = trace;
  8754. }
  8755. parseUltisnipsFile(filepath) {
  8756. const rl = readline_1.default.createInterface({
  8757. input: fs_1.default.createReadStream(filepath, 'utf8'),
  8758. crlfDelay: Infinity
  8759. });
  8760. let pycodes = [];
  8761. let snippets = [];
  8762. let block;
  8763. let preLines = [];
  8764. let first;
  8765. let priority = 0;
  8766. let lnum = 0;
  8767. let clearsnippets = null;
  8768. let parsedContext = null;
  8769. let extendFiletypes = [];
  8770. rl.on('line', line => {
  8771. lnum += 1;
  8772. if (!block && (line.startsWith('#') || line.length == 0))
  8773. return;
  8774. const [head, tail] = util_1.headTail(line);
  8775. if (!block) {
  8776. switch (head) {
  8777. case 'priority':
  8778. let n = parseInt(tail.trim(), 10);
  8779. if (!isNaN(n))
  8780. priority = n;
  8781. break;
  8782. case 'extends':
  8783. let fts = tail.trim().split(/,\s+/);
  8784. for (let ft of fts) {
  8785. if (extendFiletypes.indexOf(ft) == -1) {
  8786. extendFiletypes.push(ft);
  8787. }
  8788. }
  8789. break;
  8790. case 'clearsnippets':
  8791. clearsnippets = priority;
  8792. break;
  8793. case 'context':
  8794. parsedContext = tail.replace(/^"(.+)"$/, '$1');
  8795. break;
  8796. case 'snippet':
  8797. case 'global':
  8798. block = head;
  8799. first = tail;
  8800. break;
  8801. }
  8802. return;
  8803. }
  8804. if (head == 'endglobal' && block == 'global') {
  8805. block = null;
  8806. pycodes.push(...preLines);
  8807. preLines = [];
  8808. return;
  8809. }
  8810. if (head == 'endsnippet' && block == 'snippet') {
  8811. block = null;
  8812. try {
  8813. let originRegex;
  8814. let body = preLines.join('\n');
  8815. // convert placeholder regex to javascript regex
  8816. body = body.replace(/((?:[^\\]?\$\{\w+?)\/)([^\n]*?[^\\])(?=\/)/g, (_match, p1, p2) => {
  8817. return p1 + util_1.convertRegex(p2);
  8818. });
  8819. let ms = first.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?\s*$/);
  8820. let prefix = ms[1];
  8821. let description = ms[2] || '';
  8822. let context = ms[3];
  8823. let option = ms[4] || '';
  8824. if (prefix.length > 2 && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
  8825. prefix = prefix.slice(1, prefix.length - 1);
  8826. }
  8827. let isExpression = option.indexOf('r') !== -1;
  8828. let regex = null;
  8829. if (isExpression) {
  8830. originRegex = prefix;
  8831. prefix = util_1.convertRegex(prefix);
  8832. prefix = prefix.endsWith('$') ? prefix : prefix + '$';
  8833. try {
  8834. regex = new RegExp(prefix);
  8835. // get the real text
  8836. prefix = util_1.getRegexText(prefix);
  8837. }
  8838. catch (e) {
  8839. this.error(`Convert regex error for: ${prefix}`);
  8840. }
  8841. }
  8842. if (parsedContext) {
  8843. context = parsedContext;
  8844. }
  8845. else if (option.indexOf('e') == -1) {
  8846. context = null;
  8847. }
  8848. let snippet = {
  8849. filepath,
  8850. context,
  8851. originRegex,
  8852. autoTrigger: option.indexOf('A') !== -1,
  8853. lnum: lnum - preLines.length - 2,
  8854. triggerKind: getTriggerKind(option),
  8855. prefix,
  8856. description,
  8857. regex,
  8858. body,
  8859. priority
  8860. };
  8861. snippets.push(snippet);
  8862. }
  8863. catch (e) {
  8864. this.error(`Create snippet error on: ${filepath}:${lnum - preLines.length - 1} ${e.message}`);
  8865. }
  8866. finally {
  8867. parsedContext = null;
  8868. preLines = [];
  8869. }
  8870. }
  8871. if (block == 'snippet' || block == 'global') {
  8872. preLines.push(line);
  8873. return;
  8874. }
  8875. });
  8876. return new Promise(resolve => {
  8877. rl.on('close', async () => {
  8878. resolve({ snippets, clearsnippets, pythonCode: pycodes.join('\n'), extendFiletypes });
  8879. });
  8880. });
  8881. }
  8882. async resolveUltisnipsBody(body) {
  8883. let { pyMethod } = this;
  8884. let parser = new parser_1.default(body);
  8885. let resolved = '';
  8886. while (!parser.eof()) {
  8887. let p = parser.prev();
  8888. if (parser.curr == '`' && (!p || p != '\\')) {
  8889. let idx = parser.nextIndex('`', true, false);
  8890. if (idx == -1) {
  8891. resolved = resolved + parser.eatTo(parser.len);
  8892. break;
  8893. }
  8894. let code = parser.eatTo(idx + 1);
  8895. code = code.slice(1, -1);
  8896. let indent = resolved.split(/\n/).slice(-1)[0].match(/^\s*/)[0];
  8897. resolved = resolved + await this.execute(code, pyMethod, indent);
  8898. continue;
  8899. }
  8900. else if (parser.curr == '$') {
  8901. let text = parser.next(7);
  8902. if (text.startsWith('VISUAL') || text.startsWith('{VISUAL')) {
  8903. parser.eat(8);
  8904. resolved += '$' + text.replace('VISUAL', 'TM_SELECTED_TEXT');
  8905. }
  8906. else if (!/^\d/.test(text) && !text.startsWith('{') && p != '\\') {
  8907. // escape $ if it's not escaped and not a placeholder, ultisnips sucks
  8908. resolved += '\\' + parser.eat(1);
  8909. }
  8910. else {
  8911. // skip current
  8912. resolved += parser.eat(1);
  8913. }
  8914. }
  8915. let prev = parser.prev() || '';
  8916. parser.iterate(ch => {
  8917. if (prev !== '\\' && (ch == '`' || ch == '$')) {
  8918. return false;
  8919. }
  8920. else {
  8921. resolved = resolved + ch;
  8922. }
  8923. prev = ch;
  8924. return true;
  8925. });
  8926. }
  8927. resolved = decode(resolved);
  8928. this.debug(`resolved: ${resolved}`);
  8929. return resolved;
  8930. }
  8931. async execute(code, pyMethod, indent) {
  8932. let { nvim } = coc_nvim_1.workspace;
  8933. let res = '';
  8934. if (code.startsWith('!')) {
  8935. code = code.trim().slice(1);
  8936. if (code.startsWith('p')) {
  8937. code = code.slice(1).trim();
  8938. let lines = code.split('\n');
  8939. lines = lines.map(line => line.replace(/\t/g, ' '));
  8940. lines = lines.map(line => ` ${line}`);
  8941. lines.unshift('try:');
  8942. lines.unshift('import traceback');
  8943. lines.push('except Exception as e:');
  8944. lines.push(' snip.rv = traceback.format_exc()');
  8945. await nvim.command(`${pyMethod} ${lines.join('\n')}`);
  8946. res = await nvim.call(`${pyMethod}eval`, 'snip.rv');
  8947. }
  8948. else if (code.startsWith('v')) {
  8949. code = code.replace(/^v\s*/, '');
  8950. try {
  8951. res = await nvim.eval(code);
  8952. }
  8953. catch (e) {
  8954. res = `Error: ${e.message}`;
  8955. this.error(e.stack);
  8956. }
  8957. }
  8958. }
  8959. else {
  8960. try {
  8961. res = await pify_1.default(child_process_1.exec)(code);
  8962. }
  8963. catch (e) {
  8964. res = `Error: ${e.message}`;
  8965. this.error(`Error on eval ${code}: ` + e.stack);
  8966. }
  8967. }
  8968. res = res.toString();
  8969. res = res.replace(/\r?\n$/, '');
  8970. let parts = res.split(/\r?\n/);
  8971. if (parts.length > 1) {
  8972. res = parts.map((s, idx) => {
  8973. if (idx == 0 || s.length == 0)
  8974. return s;
  8975. return `${indent}${s}`;
  8976. }).join('\n');
  8977. }
  8978. return res;
  8979. }
  8980. error(str) {
  8981. if (!this.channel)
  8982. return;
  8983. this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] ${str}`);
  8984. }
  8985. debug(str) {
  8986. if (!this.channel || this.trace == 'error')
  8987. return;
  8988. this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] ${str}`);
  8989. }
  8990. }
  8991. exports.default = UltiSnipsParser;
  8992. function decode(str) {
  8993. return str.replace(/\\`/g, '`').replace(/\\{/g, '{');
  8994. }
  8995. function getTriggerKind(option) {
  8996. if (option.indexOf('w') !== -1) {
  8997. return types_1.TriggerKind.WordBoundary;
  8998. }
  8999. if (option.indexOf('b') !== -1) {
  9000. return types_1.TriggerKind.LineBegin;
  9001. }
  9002. if (option.indexOf('i') !== -1) {
  9003. return types_1.TriggerKind.InWord;
  9004. }
  9005. return types_1.TriggerKind.SpaceBefore;
  9006. }
  9007. /***/ }),
  9008. /* 51 */
  9009. /***/ (function(module, exports) {
  9010. module.exports = require("child_process");
  9011. /***/ }),
  9012. /* 52 */
  9013. /***/ (function(module, exports) {
  9014. /**
  9015. * Returns a function, that, as long as it continues to be invoked, will not
  9016. * be triggered. The function will be called after it stops being called for
  9017. * N milliseconds. If `immediate` is passed, trigger the function on the
  9018. * leading edge, instead of the trailing. The function also has a property 'clear'
  9019. * that is a function which will clear the timer to prevent previously scheduled executions.
  9020. *
  9021. * @source underscore.js
  9022. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  9023. * @param {Function} function to wrap
  9024. * @param {Number} timeout in ms (`100`)
  9025. * @param {Boolean} whether to execute at the beginning (`false`)
  9026. * @api public
  9027. */
  9028. function debounce(func, wait, immediate){
  9029. var timeout, args, context, timestamp, result;
  9030. if (null == wait) wait = 100;
  9031. function later() {
  9032. var last = Date.now() - timestamp;
  9033. if (last < wait && last >= 0) {
  9034. timeout = setTimeout(later, wait - last);
  9035. } else {
  9036. timeout = null;
  9037. if (!immediate) {
  9038. result = func.apply(context, args);
  9039. context = args = null;
  9040. }
  9041. }
  9042. };
  9043. var debounced = function(){
  9044. context = this;
  9045. args = arguments;
  9046. timestamp = Date.now();
  9047. var callNow = immediate && !timeout;
  9048. if (!timeout) timeout = setTimeout(later, wait);
  9049. if (callNow) {
  9050. result = func.apply(context, args);
  9051. context = args = null;
  9052. }
  9053. return result;
  9054. };
  9055. debounced.clear = function() {
  9056. if (timeout) {
  9057. clearTimeout(timeout);
  9058. timeout = null;
  9059. }
  9060. };
  9061. debounced.flush = function() {
  9062. if (timeout) {
  9063. result = func.apply(context, args);
  9064. context = args = null;
  9065. clearTimeout(timeout);
  9066. timeout = null;
  9067. }
  9068. };
  9069. return debounced;
  9070. };
  9071. // Adds compatibility for ES modules
  9072. debounce.debounce = debounce;
  9073. module.exports = debounce;
  9074. /***/ }),
  9075. /* 53 */
  9076. /***/ (function(module, exports, __webpack_require__) {
  9077. "use strict";
  9078. Object.defineProperty(exports, "__esModule", { value: true });
  9079. const coc_nvim_1 = __webpack_require__(1);
  9080. const vscode_languageserver_protocol_1 = __webpack_require__(8);
  9081. const util_1 = __webpack_require__(37);
  9082. const codesMap = new Map();
  9083. codesMap.set(1, 'invalid snippet line, trigger requried.');
  9084. codesMap.set(2, 'invalid snippet option, option "$1" not supported.');
  9085. codesMap.set(3, 'invalid python expression, $1');
  9086. codesMap.set(4, 'invalid code interpolation, #! not supported.');
  9087. const validOptions = ['b', 'i', 'w', 'r', 'e', 'A'];
  9088. class LanguageProvider {
  9089. constructor(channel, trace = 'error') {
  9090. this.channel = channel;
  9091. this.trace = trace;
  9092. this.disposables = [];
  9093. this.collection = coc_nvim_1.languages.createDiagnosticCollection('snippets');
  9094. for (let doc of coc_nvim_1.workspace.documents) {
  9095. if (this.shouldValidate(doc.uri)) {
  9096. this.validate(doc.uri, doc.getDocumentContent()).catch(e => {
  9097. channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
  9098. });
  9099. }
  9100. }
  9101. coc_nvim_1.workspace.onDidOpenTextDocument(async (textDocument) => {
  9102. let doc = coc_nvim_1.workspace.getDocument(textDocument.uri);
  9103. if (!this.shouldValidate(doc.uri))
  9104. return;
  9105. await this.validate(doc.uri, doc.getDocumentContent());
  9106. }, null, this.disposables);
  9107. coc_nvim_1.workspace.onDidChangeTextDocument(async (ev) => {
  9108. let doc = coc_nvim_1.workspace.getDocument(ev.textDocument.uri);
  9109. if (!doc || !this.shouldValidate(doc.uri))
  9110. return;
  9111. await this.validate(doc.uri, doc.getDocumentContent());
  9112. }, null, this.disposables);
  9113. coc_nvim_1.workspace.onDidCloseTextDocument(e => {
  9114. this.collection.delete(e.uri);
  9115. }, null, this.disposables);
  9116. }
  9117. shouldValidate(uri) {
  9118. return uri.endsWith('.snippets');
  9119. }
  9120. async validate(uri, content) {
  9121. let lines = content.split('\n');
  9122. let diagnostics = [];
  9123. let curr = 0;
  9124. for (let line of lines) {
  9125. if (/^snippet\s*$/.test(line)) {
  9126. let range = vscode_languageserver_protocol_1.Range.create(curr, 0, curr, line.length);
  9127. diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, codesMap.get(1), vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 1));
  9128. continue;
  9129. }
  9130. if (line.startsWith('snippet ')) {
  9131. let content = util_1.headTail(line)[1];
  9132. let ms = content.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?$/);
  9133. let prefix = ms[1];
  9134. if (prefix.length > 2 && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
  9135. prefix = prefix.slice(1, prefix.length - 1);
  9136. }
  9137. let option = ms[4] || '';
  9138. let isExpression = option.indexOf('r') !== -1;
  9139. let startCharacter = line.length - option.length;
  9140. for (let ch of option) {
  9141. if (validOptions.indexOf(ch) == -1) {
  9142. let range = vscode_languageserver_protocol_1.Range.create(curr, startCharacter, curr, startCharacter + 1);
  9143. let message = codesMap.get(2).replace('$1', ch);
  9144. diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 2));
  9145. }
  9146. startCharacter = startCharacter + 1;
  9147. }
  9148. if (isExpression) {
  9149. try {
  9150. util_1.convertRegex(prefix);
  9151. }
  9152. catch (e) {
  9153. let start = line.indexOf(prefix);
  9154. let range = vscode_languageserver_protocol_1.Range.create(curr, start, curr, start + prefix.length);
  9155. let message = codesMap.get(3).replace('$1', e.message);
  9156. diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 3));
  9157. }
  9158. }
  9159. }
  9160. else {
  9161. let idx = line.indexOf('`#!');
  9162. if (idx !== -1) {
  9163. let range = vscode_languageserver_protocol_1.Range.create(curr, idx, curr, idx + 3);
  9164. let message = codesMap.get(4);
  9165. diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 4));
  9166. }
  9167. }
  9168. curr++;
  9169. }
  9170. if (this.trace == 'verbose') {
  9171. this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] diagnostics of ${uri} -> ${JSON.stringify(diagnostics)}`);
  9172. }
  9173. this.collection.set(uri, diagnostics);
  9174. }
  9175. provideCompletionItems(_document, position, _token, context) {
  9176. let { input, col } = context.option;
  9177. if (context.triggerCharacter == '$') {
  9178. return [{
  9179. label: '$VISUAL',
  9180. kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
  9181. // tslint:disable-next-line: no-invalid-template-strings
  9182. detail: '${VISUAL}',
  9183. insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
  9184. textEdit: {
  9185. range: vscode_languageserver_protocol_1.Range.create(position.line, position.character - 1, position.line, position.character),
  9186. // tslint:disable-next-line: no-invalid-template-strings
  9187. newText: '\\${VISUAL${1::default}\\}'
  9188. }
  9189. }];
  9190. }
  9191. if (col == 0 && 'snippet'.startsWith(input)) {
  9192. return [{
  9193. label: 'snippet',
  9194. kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
  9195. detail: 'Snippet definition',
  9196. insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
  9197. // tslint:disable-next-line: no-invalid-template-strings
  9198. insertText: 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n$0\nendsnippet'
  9199. }];
  9200. }
  9201. return [];
  9202. }
  9203. async resolveCompletionItem(item) {
  9204. // tslint:disable-next-line: deprecation
  9205. let text = item.insertText || item.textEdit.newText;
  9206. // tslint:disable-next-line: deprecation
  9207. let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(text));
  9208. item.documentation = {
  9209. kind: 'markdown',
  9210. value: util_1.markdownBlock(snip.toString(), 'snippets')
  9211. };
  9212. return item;
  9213. }
  9214. }
  9215. exports.default = LanguageProvider;
  9216. /***/ })
  9217. /******/ ])));