forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDefaultProviders.js
More file actions
1 lines (1 loc) · 29.6 KB
/
Copy pathDefaultProviders.js
File metadata and controls
1 lines (1 loc) · 29.6 KB
1
define(function(require,exports,module){var _=require("thirdparty/lodash"),EditorManager=require("editor/EditorManager"),DocumentManager=require("document/DocumentManager"),PreferencesManager=require("preferences/PreferencesManager"),ProjectManager=require("project/ProjectManager"),CommandManager=require("command/CommandManager"),Commands=require("command/Commands"),StringMatch=require("utils/StringMatch"),CodeInspection=require("language/CodeInspection"),LanguageManager=require("language/LanguageManager"),QuickViewManager=require("features/QuickViewManager"),FileSystem=require("filesystem/FileSystem"),PathConverters=require("languageTools/PathConverters"),TabstopManager=require("editor/TabstopManager"),Strings=require("strings"),StringUtils=require("utils/StringUtils"),Metrics=require("utils/Metrics"),FileUtils=require("file/FileUtils"),InlineMenu=require("widgets/InlineMenu").InlineMenu,marked=require("thirdparty/marked.min"),matcher=new StringMatch.StringMatcher({preferPrefixMatches:!0}),$lspDocPopup=null,_docTrackRAF=null,_docTrackList=null,_docLastPos="";function _hideDocPopup(){_docTrackRAF&&(cancelAnimationFrame(_docTrackRAF),_docTrackRAF=null),_docTrackList=null,_docLastPos="",$lspDocPopup&&$lspDocPopup.hide().empty()}function _positionDocPopup(){if($lspDocPopup&&_docTrackList&&_docTrackList.length){var listEl=_docTrackList[0];if(listEl.isConnected){var anchor=listEl.getBoundingClientRect();if(0!==anchor.width||0!==anchor.height){var GAP=0,winW=$(window).width(),winH=$(window).height(),pw=$lspDocPopup.outerWidth(),ph=$lspDocPopup.outerHeight(),left=anchor.right+0;left+pw>winW-8&&(left=anchor.left-pw-0),left=Math.max(8,left);var top=Math.max(8,Math.min(anchor.top,winH-ph-8)),pos=Math.round(left)+","+Math.round(top);pos!==_docLastPos&&(_docLastPos=pos,$lspDocPopup.css({left:left,top:top}))}}else _hideDocPopup()}}function _trackDocPopup(){_positionDocPopup(),_docTrackRAF=requestAnimationFrame(_trackDocPopup)}function _highlightCode(html){var hljs="undefined"!=typeof Phoenix&&Phoenix.libs&&Phoenix.libs.hljs;if(!hljs)return html;var $wrap=$("<div>").html(html);return $wrap.find("pre > code").each(function(){var $code=$(this),match=($code.attr("class")||"").match(/language-([\w-]+)/),lang=match&&match[1];if(lang&&hljs.getLanguage(lang))try{$code.html(hljs.highlight($code.text(),{language:lang}).value).addClass("hljs")}catch(e){}}),$wrap.html()}function _docToHtml(documentation){if(!documentation)return"";var md="string"==typeof documentation?documentation:documentation.value||"";if(!md.trim())return"";try{return _highlightCode(marked.parse(md))}catch(e){return _.escape(md)}}var SIGNATURE_HLJS_LANG={javascript:"typescript",jsx:"tsx",typescript:"typescript",tsx:"tsx"};function _signatureLang(){var editor=EditorManager.getActiveEditor(),id=editor&&editor.getLanguageForSelection&&editor.getLanguageForSelection().getId();return id?SIGNATURE_HLJS_LANG[id]||id:"typescript"}function _docPopupHtml(token){var parts=[],label=(token.label||"").trim(),detail=(token.detail||"").trim(),paramList=(token.labelDetails&&token.labelDetails.detail||"").trim(),signature=detail;if("("===paramList.charAt(0)&&-1===detail.indexOf("(")&&(signature=label+paramList+(detail?": "+detail:"")),signature&&signature!==label)try{parts.push(_highlightCode(marked.parse("```"+_signatureLang()+"\n"+signature+"\n```")))}catch(e){}var docHtml=_docToHtml(token.documentation);return docHtml&&parts.push(docHtml),parts.join("")}const COPY_ICON='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';function _copyText(text){return navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(text):new Promise(function(resolve,reject){try{const ta=document.createElement("textarea");ta.value=text,ta.style.cssText="position:fixed;opacity:0;pointer-events:none;",document.body.appendChild(ta),ta.select(),document.execCommand("copy"),document.body.removeChild(ta),resolve()}catch(e){reject(e)}})}function _addCopyButtons($popup){$popup.find("pre").each(function(){const $pre=$(this);$pre.children(".lsp-copy-btn").length||$("<button>").addClass("lsp-copy-btn").attr({type:"button",title:Strings.CMD_COPY,"aria-label":Strings.CMD_COPY}).html(COPY_ICON).appendTo($pre)})}function _showDocPopup($hint,docHtml){if(!1!==PreferencesManager.get("showCodeHintDocs")){var $menu=$hint.closest(".codehint-menu, .inlinemenu-menu");if(docHtml&&$menu.length){$lspDocPopup&&$lspDocPopup.parent().is($menu)||($lspDocPopup=$("<div>").addClass("lsp-hint-doc-popup").appendTo($menu)).on("mousedown click",function(e){e.stopPropagation()}).on("click",".lsp-copy-btn",function(e){e.preventDefault();const $btn=$(this),text=$btn.closest("pre").find("code").text();text&&_copyText(text).then(function(){$btn.addClass("copied"),setTimeout(function(){$btn.removeClass("copied")},1200)}).catch(function(){})}),$lspDocPopup.empty().html(docHtml),_addCopyButtons($lspDocPopup);var $list=$hint.closest("ul.dropdown-menu");$list.length||($list=$menu),_docTrackList=$list,_docLastPos="",$lspDocPopup.css({display:"block"}),_positionDocPopup(),_docTrackRAF||_trackDocPopup()}else _hideDocPopup()}else _hideDocPopup()}const INLINE_DETAIL_MAX_CHARS=32;function _injectInlineSignature($labelSpan,detail){if(detail&&detail.trim()&&"?"!==detail.trim()){var text=detail.split("->").join(":").replace(/\s+/g," ").trim(),$container=$labelSpan.parent();$container.length||($container=$labelSpan),$container.find(".lsp-hint-sig").remove(),$("<span>").addClass("lsp-hint-sig").text(text).attr("title",text).appendTo($container)}}var DEFAULT_IDENTIFIER_CHARS=/[A-Za-z0-9_$]/;function setClient(client){client&&(this.client=client)}function CodeHintsProvider(client){this.client=client,this.query="",this.ignoreQuery=["-","->",">",":","::","(","()",")","[","[]","]","{","{}","}"]}function filterWithQueryAndMatcher(hints,query){var matchResults;return $.map(hints,function(hint){var searchResult=matcher.match(hint.label,query);if(searchResult)for(var key in hint)searchResult[key]=hint[key];return searchResult})}function _isAutoImport(item){return!(!item.labelDetails||!item.labelDetails.description)}function _clubAutoImports(items){var counts=new Map;items.forEach(function(it){_isAutoImport(it)&&counts.set(it.label,(counts.get(it.label)||0)+1)});var seen=new Set,result=[];return items.forEach(function(it){!_isAutoImport(it)||counts.get(it.label)<2?result.push(it):seen.has(it.label)||(seen.add(it.label),result.push(Object.assign({},it,{_clubbed:!0,_importCount:counts.get(it.label)})))}),result}function _renderHint(element){var $fHint=$("<span>").addClass("brackets-hints"),$label=$("<span>").addClass("lsp-hint-label");return element.stringRanges?element.stringRanges.forEach(function(item){item.matched?$label.append($("<span>").append(_.escape(item.text)).addClass("matched-hint")):$label.append(_.escape(item.text))}):$label.text(element.label),$fHint.append($label),element._clubbed?$("<span>").addClass("lsp-hint-source lsp-hint-import-group").text(StringUtils.format(Strings.CODE_HINT_IMPORT_FROM_N,element._importCount)).appendTo($fHint):element.labelDetails&&element.labelDetails.description&&$("<span>").addClass("lsp-hint-source").text(element.labelDetails.description).attr("title",element.labelDetails.description).appendTo($fHint),$fHint.data("token",element),$fHint}function ParameterHintsProvider(client){this.client=client}function setJumpPosition(curPos){EditorManager.getCurrentFullEditor().setCursorPos(curPos.line,curPos.ch,!0)}CodeHintsProvider.prototype.setClient=setClient,CodeHintsProvider.prototype.hasHints=function(editor,implicitChar){if(!this.client||!this.client.servesDocument(editor))return!1;var serverCapabilities=this.client.getServerCapabilities();if(!serverCapabilities||!serverCapabilities.completionProvider)return!1;if(!implicitChar)return!0;var config=this.client.config||{};if("function"==typeof config.shouldAutoTrigger)return!!config.shouldAutoTrigger(implicitChar,editor);if(DEFAULT_IDENTIFIER_CHARS.test(implicitChar))return!0;var triggerChars=serverCapabilities.completionProvider.triggerCharacters||[];return!(!implicitChar.trim()||-1===triggerChars.indexOf(implicitChar))},CodeHintsProvider.prototype.getHints=function(implicitChar){if(!this.client)return null;var editor=EditorManager.getActiveEditor(),pos=editor.getCursorPos(),docPath=editor.document.file._path,$deferredHints=$.Deferred(),self=this;function computeQuery(){for(var lineText=editor.document.getLine(pos.line),queryStart=pos.ch;queryStart>0&&/[\w$]/.test(lineText.charAt(queryStart-1));)queryStart--;return lineText.substring(queryStart,pos.ch)}return this.client.requestHints({filePath:docPath,cursorPos:pos}).done(function(msgObj){var hints=[];if(self.query=computeQuery(),msgObj){var filteredHints=filterWithQueryAndMatcher(msgObj.items,self.query);if(StringMatch.basicMatchSort(filteredHints),self._importLabel){var wanted=self._importLabel;self._importLabel=null,filteredHints=filteredHints.filter(function(it){return it.label===wanted&&_isAutoImport(it)})}else filteredHints=_clubAutoImports(filteredHints);hints=filteredHints.map(_renderHint)}$deferredHints.resolve({hints:hints,selectInitial:!0})}).fail(function(){Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"hint","Fail."+self.client._metricLabel),self._importLabel=null,$deferredHints.reject()}),$deferredHints},CodeHintsProvider.prototype.onHighlight=function($hint){var self=this;if(this.client){var $span=$hint.closest("li").data("hint"),token=$span&&$span.data&&$span.data("token");token?($hint.closest(".codehint-menu").addClass("lsp-hints"),token._clubbed?_showDocPopup($hint,"<p>"+StringUtils.format(Strings.CODE_HINT_IMPORT_CHOOSE,token._importCount,_.escape(token.label))+"</p>"):!token._lspResolved&&this.client.resolveCompletion?this.client.resolveCompletion(token).done(function(resolved){token._lspResolved=!0,token.detail=resolved.detail||token.detail,token.documentation=resolved.documentation||token.documentation,resolved.additionalTextEdits&&(token.additionalTextEdits=resolved.additionalTextEdits),!token.textEdit&&resolved.textEdit&&(token.textEdit=resolved.textEdit),present()}):present()):_hideDocPopup()}else _hideDocPopup();function present(){token.detail&&!_isAutoImport(token)&&token.detail.length<=INLINE_DETAIL_MAX_CHARS&&_injectInlineSignature($span,token.detail),_showDocPopup($hint,_docPopupHtml(token))}},CodeHintsProvider.prototype.onClose=function(){_hideDocPopup()},CodeHintsProvider.prototype.insertHint=function($hint){var editor=EditorManager.getActiveEditor();if(!editor)return!1;var token=$hint.data("token")||{};if(token._clubbed)return this._importLabel=token.label,setTimeout(function(){CommandManager.execute(Commands.SHOW_CODE_HINTS)},0),!1;var cursor=editor.getCursorPos(),lineText=editor.document.getLine(cursor.line),textEditRange=token.textEdit&&token.textEdit.range,startCh,endCh=cursor.ch;if(textEditRange&&textEditRange.start.line===cursor.line&&textEditRange.start.character<=cursor.ch)startCh=textEditRange.start.character,textEditRange.end.line===cursor.line&&textEditRange.end.character>cursor.ch&&(endCh=textEditRange.end.character);else for(startCh=cursor.ch;startCh>0&&/[\w$]/.test(lineText.charAt(startCh-1));)startCh--;var rawText=token.textEdit&&token.textEdit.newText||token.insertText||token.label||"",startPos={line:cursor.line,ch:startCh},endPos={line:cursor.line,ch:endCh};return 2===token.insertTextFormat?TabstopManager.insertSnippet(editor,rawText,startPos,endPos):editor.document.replaceRange(rawText,startPos,endPos),(token.additionalTextEdits||[]).slice().sort(function(a,b){return b.range.start.line-a.range.start.line||b.range.start.character-a.range.start.character}).forEach(function(te){editor.document.replaceRange(te.newText,{line:te.range.start.line,ch:te.range.start.character},{line:te.range.end.line,ch:te.range.end.character})}),Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"hint","Acc."+this.client._metricLabel),token.additionalTextEdits&&token.additionalTextEdits.length&&Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"hint","Import."+this.client._metricLabel),!1},ParameterHintsProvider.prototype.setClient=setClient,ParameterHintsProvider.prototype.hasParameterHints=function(editor,implicitChar){if(!this.client||!this.client.servesDocument(editor))return!1;var serverCapabilities=this.client.getServerCapabilities();return!(!serverCapabilities||!serverCapabilities.signatureHelpProvider)},ParameterHintsProvider.prototype.getParameterHints=function(){if(!this.client)return null;var editor=EditorManager.getActiveEditor(),pos=editor.getCursorPos(),docPath=editor.document.file._path,metricLabel=this.client._metricLabel,$deferredHints=$.Deferred(),config=this.client.config||{};return"function"!=typeof config.shouldShowParameterHints||config.shouldShowParameterHints(editor)?(this.client.requestParameterHints({filePath:docPath,cursorPos:pos}).done(function(msgObj){let paramList=[];if(msgObj){let res=msgObj.signatures,activeParameter=msgObj.activeParameter;if(res&&res.length){let sig=res[msgObj.activeSignature||0]||res[0];(sig.parameters||[]).forEach(function(ele){paramList.push({label:ele.label,documentation:ele.documentation})});let functionName="";if("string"==typeof sig.label){let paren=sig.label.indexOf("(");functionName=(paren>=0?sig.label.slice(0,paren):sig.label).trim()}$deferredHints.resolve({parameters:paramList,currentIndex:activeParameter,functionDocumentation:sig.documentation,functionName:functionName})}else $deferredHints.reject()}else $deferredHints.reject()}).fail(function(err){err&&Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"sig","Fail."+metricLabel),$deferredHints.reject()}),$deferredHints):$deferredHints.reject(null)};var DECLARATION_SCAN_LIMIT=200,EXCERPT_BODY_MAX_LINES=6;function _indentOf(line){return/^[ \t]*/.exec(line)[0].length}function findEnclosingDeclarationLine(lines,lineIdx){var from=Math.min(lineIdx,lines.length-1),targetIndent=_indentOf(lines[from]);if(0===targetIndent)return null;for(var to=Math.max(0,from-DECLARATION_SCAN_LIMIT),i=from-1;i>=to;i--)if(lines[i].trim()&&_indentOf(lines[i])<targetIndent)return i;return null}function findBlockEndLine(lines,lineIdx){for(var indent=_indentOf(lines[lineIdx]),to=Math.min(lines.length-1,lineIdx+DECLARATION_SCAN_LIMIT),i=lineIdx+1;i<=to;i++)if(lines[i].trim()&&_indentOf(lines[i])<=indent)return i;return null}function _hasNonBlankLineBetween(lines,startExclusive,endExclusive){for(var i=startExclusive+1;i<endExclusive;i++)if(lines[i].trim())return!0;return!1}function buildExcerpt(lines,targetLineIdx){var declLine=findEnclosingDeclarationLine(lines,targetLineIdx),indent=/^[ \t]*/.exec(lines[targetLineIdx])[0],blockEnd=findBlockEndLine(lines,targetLineIdx),naturalEnd=null!==blockEnd?blockEnd:Math.min(lines.length-1,targetLineIdx+EXCERPT_BODY_MAX_LINES-1),bodyEnd=Math.min(naturalEnd,targetLineIdx+EXCERPT_BODY_MAX_LINES-1),bodyLines=lines.slice(targetLineIdx,bodyEnd+1),headerLines;return bodyEnd<naturalEnd&&bodyLines.push(indent+"..."),null===declLine?bodyLines.join("\n"):(_hasNonBlankLineBetween(lines,declLine,targetLineIdx)?[lines[declLine],indent+"..."]:[lines[declLine]]).concat(bodyLines).join("\n")}function getFileLines(path){var openDoc=DocumentManager.getOpenDocumentForPath(path);if(openDoc)return $.Deferred().resolve(openDoc.getText().split("\n")).promise();var deferred=$.Deferred();return FileSystem.getFileForPath(path).read(function(err,content){err||"string"!=typeof content?deferred.reject():deferred.resolve(content.split("\n"))}),deferred.promise()}function excerptHljsLang(path){var language=LanguageManager.getLanguageForPath(path),id=language&&language.getId();return id?SIGNATURE_HLJS_LANG[id]||id:"javascript"}function _locationKey(location){return location.uri+":"+location.range.start.line}function mergeLocations(primary,extras){var seen={},merged=[];return[primary].concat(extras).forEach(function(location){var key=_locationKey(location);seen[key]||(seen[key]=!0,merged.push(location))}),merged}function JumpToDefProvider(client){this.client=client}function LintingProvider(){this._results=new Map,this._promiseMap=new Map,this._lastSignature=new Map,this._validateOnType=!1,this._quickFixClient=null,this._rawDiagnostics=new Map,this._quickFixState=new Map,this._quickFixTimer=null;const self=this;EditorManager.on("activeEditorChange",function(evt,current){current&¤t.document&&self._scheduleQuickFixFetch(current.document.file._path)})}JumpToDefProvider.prototype.setClient=setClient,JumpToDefProvider.prototype.canJumpToDef=function(editor,implicitChar){if(!this.client||!this.client.servesDocument(editor))return!1;var serverCapabilities=this.client.getServerCapabilities();return!(!serverCapabilities||!serverCapabilities.definitionProvider)},JumpToDefProvider.prototype.doJumpToDef=function(editor){if(editor=editor||EditorManager.getFocusedEditor()||EditorManager.getActiveEditor(),!this.client||!editor)return null;const client=this.client,pos=editor.getCursorPos(),docPath=editor.document.file._path,docPathUri=PathConverters.pathToUri(docPath),metricLabel=client._metricLabel,$deferredHints=$.Deferred();function jumpToLocation(location){var docUri=location.uri,startCurPos={line:location.range.start.line,ch:location.range.start.character};if(docUri!==docPathUri){let documentPath=PathConverters.uriToPath(docUri);CommandManager.execute(Commands.FILE_OPEN,{fullPath:documentPath}).done(function(){setJumpPosition(startCurPos),$deferredHints.resolve()}).fail(function(){$deferredHints.reject()})}else setJumpPosition(startCurPos),$deferredHints.resolve()}function showJumpTargetPicker(locations,implementationStartIndex){Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"def","Multi."+metricLabel);var lineCache={};function linesFor(path){return lineCache[path]||(lineCache[path]=getFileLines(path)),lineCache[path]}var items=locations.map(function(location,index){var path=PathConverters.uriToPath(location.uri),relPath=ProjectManager.makeProjectRelativeIfPossible(path),dirPath=FileUtils.getDirectoryPath(relPath),line=location.range.start.line+1,col=location.range.start.character+1,name='<span class="jump-to-def-item-file">'+_.escape(FileUtils.getBaseName(path))+'</span> <span class="jump-to-def-item-loc">'+line+":"+col+"</span>";return dirPath&&(name+=' <span class="jump-to-def-item-path">'+_.escape(dirPath)+"</span>"),void 0!==implementationStartIndex&&index>=implementationStartIndex&&(name+=' <i class="fa fa-code-branch jump-to-def-item-badge" title="'+_.escape(Strings.JUMPTO_DEFINITION_IMPLEMENTATION_BADGE)+'" aria-hidden="true"></i>'),{id:index,name:name}}),inlineMenu=new InlineMenu(editor,Strings.JUMPTO_DEFINITION_SELECT_TARGET),hoverToken=0;function showExcerptFor(id){var myToken=++hoverToken,location=locations[id],path=PathConverters.uriToPath(location.uri),line=location.range.start.line+1,nameHtml=_.escape(FileUtils.getBaseName(path)),titleHtml;if(path!==docPath){var dirPath=FileUtils.getDirectoryPath(ProjectManager.makeProjectRelativeIfPossible(path)).replace(/\/$/,"");dirPath&&(nameHtml+=' <span class="jump-to-def-excerpt-title-path">- '+_.escape(dirPath)+"</span>")}titleHtml='<div class="jump-to-def-excerpt-title"><span class="jump-to-def-excerpt-title-name">'+nameHtml+'</span><span class="jump-to-def-excerpt-title-line">'+_.escape(StringUtils.format(Strings.JUMPTO_DEFINITION_LINE_LABEL,line))+"</span></div>",linesFor(path).done(function(lines){if(myToken===hoverToken){var excerpt=buildExcerpt(lines,location.range.start.line),codeHtml="";if(excerpt.trim())try{codeHtml=_highlightCode(marked.parse("```"+excerptHljsLang(path)+"\n"+excerpt+"\n```"))}catch(e){codeHtml="<pre>"+_.escape(excerpt)+"</pre>"}_showDocPopup(inlineMenu.$menu.find("ul.dropdown-menu"),titleHtml+codeHtml)}}).fail(function(){myToken===hoverToken&&_hideDocPopup()})}inlineMenu.onHover(function(id){inlineMenu.$menu.closest("body").length?showExcerptFor(id):setTimeout(function(){showExcerptFor(id)},0)}),inlineMenu.onSelect(function(id){_hideDocPopup(),inlineMenu.close(),jumpToLocation(locations[id])}),inlineMenu.onClose(function(){_hideDocPopup(),inlineMenu.close(),$deferredHints.reject()}),QuickViewManager.hideQuickView(),inlineMenu.open(items)}function fallBackToImplementations(singleLocation){var serverCapabilities=client.getServerCapabilities();serverCapabilities&&serverCapabilities.implementationProvider?client.gotoImplementation({filePath:docPath,cursorPos:pos}).done(function(implResult){var implLocations=Array.isArray(implResult)?implResult:implResult?[implResult]:[],merged=mergeLocations(singleLocation,implLocations);merged.length>1?(Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"def","Impl."+metricLabel),showJumpTargetPicker(merged,1)):jumpToLocation(merged[0])}).fail(function(){jumpToLocation(singleLocation)}):jumpToLocation(singleLocation)}return client.gotoDefinition({filePath:docPath,cursorPos:pos}).done(function(msgObj){Array.isArray(msgObj)&&msgObj.length>1?showJumpTargetPicker(msgObj):(Array.isArray(msgObj)&&(msgObj=msgObj[msgObj.length-1]),msgObj&&msgObj.range?fallBackToImplementations(msgObj):$deferredHints.reject())}).fail(function(err){err&&Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"def","Fail."+metricLabel),$deferredHints.reject()}),$deferredHints},LintingProvider.prototype.setClient=setClient,LintingProvider.prototype.clearExistingResults=function(filePath){var filePathProvided;!!filePath?(this._results.delete(filePath),this._promiseMap.delete(filePath),this._lastSignature.delete(filePath),this._rawDiagnostics.delete(filePath),this._quickFixState.delete(filePath)):(this._results.clear(),this._promiseMap.clear(),this._lastSignature.clear(),this._rawDiagnostics.clear(),this._quickFixState.clear()),this._quickFixTimer&&(clearTimeout(this._quickFixTimer),this._quickFixTimer=null)},LintingProvider.prototype.setInspectionResults=function(msgObj){let diagnostics=msgObj.diagnostics,filePath=PathConverters.uriToPath(msgObj.uri),errors=[];errors=diagnostics.map(function(obj){return{pos:{line:obj.range.start.line,ch:obj.range.start.character},endPos:{line:obj.range.end.line,ch:obj.range.end.character},message:obj.message,type:1===obj.severity?CodeInspection.Type.ERROR:2===obj.severity?CodeInspection.Type.WARNING:CodeInspection.Type.META,tags:obj.tags}});var signature=JSON.stringify(errors),previous,changed=(this._lastSignature.has(filePath)?this._lastSignature.get(filePath):"[]")!==signature;if(this._lastSignature.set(filePath,signature),!changed&&this._results.has(filePath)||this._results.set(filePath,{errors:errors}),this._promiseMap.get(filePath)&&(this._promiseMap.get(filePath).resolve(this._results.get(filePath)),this._promiseMap.delete(filePath)),this._validateOnType&&changed){var editor=EditorManager.getActiveEditor(),docPath=editor?editor.document.file._path:"";filePath===docPath&&this._isRegisteredInspector(docPath)&&CodeInspection.requestRun()}};var QUICKFIX_IDLE_MS=800,MAX_QUICKFIX_REQUESTS=20;function serverRespToSearchModelFormat(msgObj){var referenceModel={},result=$.Deferred();if(!(msgObj&&msgObj.length&&msgObj.cursorPos))return result.reject();referenceModel.results={},referenceModel.numFiles=0;var fulfilled=0;return msgObj.forEach((element,i)=>{var filePath=PathConverters.uriToPath(element.uri);DocumentManager.getDocumentForPath(filePath).done(function(doc){var startRange={line:element.range.start.line,ch:element.range.start.character},endRange={line:element.range.end.line,ch:element.range.end.character},match={start:startRange,end:endRange,highlightOffset:0,line:doc.getLine(element.range.start.line)};referenceModel.results[filePath]||(referenceModel.numFiles=referenceModel.numFiles+1,referenceModel.results[filePath]={matches:[]}),referenceModel.queryInfo&&msgObj.cursorPos.line!==startRange.line||(referenceModel.queryInfo=doc.getRange(startRange,endRange)),referenceModel.results[filePath].matches.push(match)}).always(function(){++fulfilled===msgObj.length&&(referenceModel.numMatches=msgObj.length,referenceModel.allResultsAvailable=!0,result.resolve(referenceModel))})}),result.promise()}function ReferencesProvider(client){this.client=client}LintingProvider.prototype.updateQuickFixes=function(filePath,rawDiagnostics){this._rawDiagnostics.set(filePath,rawDiagnostics||[]),this._scheduleQuickFixFetch(filePath)},LintingProvider.prototype._scheduleQuickFixFetch=function(filePath){var self=this;if(this._quickFixClient&&this._rawDiagnostics.has(filePath)){var editor=EditorManager.getActiveEditor();if(editor&&editor.document.file._path===filePath&&this._quickFixClient.servesDocument(editor)){var state=this._quickFixState.get(filePath);state&&state.timestamp===editor.document.lastChangeTimestamp&&state.signature===this._lastSignature.get(filePath)||(this._quickFixTimer&&clearTimeout(this._quickFixTimer),this._quickFixTimer=setTimeout(function(){self._quickFixTimer=null,self._fetchQuickFixes(filePath)},800))}}},LintingProvider.prototype._fixFromAction=function(action,editor,filePath){if(!action||!action.title||action.disabled)return null;if(!action.kind||0!==action.kind.indexOf("quickfix"))return null;var edit=action.edit;if(!edit)return null;var uri=null,edits=null;if(edit.documentChanges&&1===edit.documentChanges.length&&edit.documentChanges[0].textDocument)uri=edit.documentChanges[0].textDocument.uri,edits=edit.documentChanges[0].edits;else if(edit.changes){var uris=Object.keys(edit.changes);1===uris.length&&(uri=uris[0],edits=edit.changes[uri])}if(!uri||!edits||1!==edits.length||"string"!=typeof edits[0].newText)return null;var ownUri=this._quickFixClient.uriForPath(filePath);if(PathConverters.uriToPath(uri)!==PathConverters.uriToPath(ownUri))return null;var range=edits[0].range;return{replaceText:edits[0].newText,title:action.title,rangeOffset:{start:editor.indexFromPos({line:range.start.line,ch:range.start.character}),end:editor.indexFromPos({line:range.end.line,ch:range.end.character})}}},LintingProvider.prototype._attachFix=function(errors,action,fix,forDiagnostic){for(var diags=action.diagnostics&&action.diagnostics.length?action.diagnostics:forDiagnostic?[forDiagnostic]:[],d=0;d<diags.length;d++)for(var diag=diags[d],i=0;i<errors.length;i++){var err=errors[i];if(err.pos.line===diag.range.start.line&&err.pos.ch===diag.range.start.character&&err.message===diag.message&&(!err.fix||action.isPreferred))return err.fix=fix,!0}return!1},LintingProvider.prototype._fetchQuickFixes=async function(filePath){var self=this,client=this._quickFixClient,editor=EditorManager.getActiveEditor(),diagnostics=this._rawDiagnostics.get(filePath)||[],cached=this._results.get(filePath);if(client&&editor&&editor.document.file._path===filePath&&client.servesDocument(editor)&&diagnostics.length&&cached){var fetchedAt=editor.document.lastChangeTimestamp;this._quickFixState.set(filePath,{timestamp:fetchedAt,signature:this._lastSignature.get(filePath)});try{var lastLine=editor.lineCount()-1,wholeFile={start:{line:0,character:0},end:{line:lastLine,character:editor.document.getLine(lastLine).length}},actions=await client.requestCodeActions({filePath:filePath,range:wholeFile,diagnostics:diagnostics}),attached=0;if(actions&&actions.length)for(var i=0;i<actions.length;i++){var resolved=await client.resolveCodeAction(actions[i]),fix=this._fixFromAction(resolved,editor,filePath);fix&&this._attachFix(cached.errors,resolved,fix,null)&&attached++}else for(var capped=diagnostics.slice(0,20),d=0;d<capped.length;d++)for(var acts=await client.requestCodeActions({filePath:filePath,range:capped[d].range,diagnostics:[capped[d]]}),a=0;acts&&a<acts.length;a++){var res=await client.resolveCodeAction(acts[a]),f=this._fixFromAction(res,editor,filePath);if(f&&this._attachFix(cached.errors,res,f,capped[d])){attached++;break}}var activeEditor=EditorManager.getActiveEditor();attached&&activeEditor&&activeEditor.document.file._path===filePath&&activeEditor.document.lastChangeTimestamp===fetchedAt&&this._isRegisteredInspector(filePath)&&CodeInspection.requestRun()}catch(err){console.warn("[LSP] quickfix fetch failed:",err&&(err.message||err)),this._quickFixClient&&Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"fix","Fail."+this._quickFixClient._metricLabel)}}},LintingProvider.prototype._isRegisteredInspector=function(filePath){if(!this._inspectionProviderName)return!0;var name=this._inspectionProviderName;return CodeInspection.getProvidersForPath(filePath).some(function(provider){return provider.name===name})},LintingProvider.prototype.getInspectionResultsAsync=function(fileText,filePath){var result=$.Deferred();return this._results.get(filePath)?result.resolve(this._results.get(filePath)):(this._promiseMap.set(filePath,result),result)},LintingProvider.prototype.getInspectionResults=function(fileText,filePath){return this._results.get(filePath)},ReferencesProvider.prototype.setClient=setClient,ReferencesProvider.prototype.hasReferences=function(){if(!this.client||!this.client.servesDocument(EditorManager.getActiveEditor()))return!1;var serverCapabilities=this.client.getServerCapabilities();return!(!serverCapabilities||!serverCapabilities.referencesProvider)},ReferencesProvider.prototype.getReferences=function(hostEditor,curPos){var editor=hostEditor||EditorManager.getActiveEditor(),pos=curPos||editor?editor.getCursorPos():null,docPath=editor.document.file._path,result=$.Deferred();if(this.client){const metricLabel=this.client._metricLabel;return this.client.findReferences({filePath:docPath,cursorPos:pos}).done(function(msgObj){msgObj&&msgObj.length?(msgObj.cursorPos=pos,serverRespToSearchModelFormat(msgObj).done(result.resolve).fail(result.reject)):result.reject()}).fail(function(err){err&&Metrics.countEvent(Metrics.EVENT_TYPE.LSP,"ref","Fail."+metricLabel),result.reject()}),result.promise()}return result.reject()},exports.CodeHintsProvider=CodeHintsProvider,exports.ParameterHintsProvider=ParameterHintsProvider,exports.JumpToDefProvider=JumpToDefProvider,exports.LintingProvider=LintingProvider,exports.ReferencesProvider=ReferencesProvider,exports.serverRespToSearchModelFormat=serverRespToSearchModelFormat,exports.showHintDocPopup=_showDocPopup,exports.hideHintDocPopup=_hideDocPopup,exports._docPopupHtml=_docPopupHtml,exports._buildJumpToDefExcerpt=buildExcerpt,exports._mergeJumpToDefLocations=mergeLocations});