define(function(require,exports,module){require("widgets/bootstrap-dropdown"),require("widgets/bootstrap-modal"),require("widgets/bootstrap-twipsy-mod"),require("thirdparty/jquery.knob.modified"),require("thirdparty/marked.min"),require("thirdparty/CodeMirror/addon/comment/continuecomment"),require("thirdparty/CodeMirror/addon/edit/closebrackets"),require("thirdparty/CodeMirror/addon/edit/closetag"),require("thirdparty/CodeMirror/addon/edit/matchbrackets"),require("thirdparty/CodeMirror/addon/edit/matchtags"),require("thirdparty/CodeMirror/addon/fold/xml-fold"),require("thirdparty/CodeMirror/addon/mode/multiplex"),require("thirdparty/CodeMirror/addon/mode/overlay"),require("thirdparty/CodeMirror/addon/mode/simple"),require("thirdparty/CodeMirror/addon/scroll/scrollpastend"),require("thirdparty/CodeMirror/addon/search/match-highlighter"),require("thirdparty/CodeMirror/addon/search/searchcursor"),require("thirdparty/CodeMirror/addon/selection/active-line"),require("thirdparty/CodeMirror/addon/selection/mark-selection"),require("thirdparty/CodeMirror/addon/display/rulers"),require("thirdparty/CodeMirror/addon/comment/comment"),require("thirdparty/CodeMirror/keymap/sublime"),require("utils/EventDispatcher"),require("worker/WorkerComm"),require("utils/ZipUtils"),require("NodeConnector"),require("command/KeyboardOverlayMode"),require("editor/EditorManager"),require("project/FileViewController");const AppInit=require("utils/AppInit"),LanguageManager=require("language/LanguageManager"),ProjectManager=require("project/ProjectManager"),FileSyncManager=require("project/FileSyncManager"),Commands=require("command/Commands"),CommandManager=require("command/CommandManager"),PerfUtils=require("utils/PerfUtils"),FileSystem=require("filesystem/FileSystem"),Strings=require("strings"),Dialogs=require("widgets/Dialogs"),DefaultDialogs=require("widgets/DefaultDialogs"),ExtensionLoader=require("utils/ExtensionLoader"),ExtensionInterface=require("utils/ExtensionInterface"),EventManager=require("utils/EventManager"),FeatureGate=require("utils/FeatureGate"),Async=require("utils/Async"),UrlParams=require("utils/UrlParams").UrlParams,PreferencesManager=require("preferences/PreferencesManager"),DragAndDrop=require("utils/DragAndDrop"),NativeApp=require("utils/NativeApp"),DeprecationWarning=require("utils/DeprecationWarning"),ViewCommandHandlers=require("view/ViewCommandHandlers"),NotificationUI=require("widgets/NotificationUI"),Metrics=require("utils/Metrics");require("view/MainViewManager"),window.EventManager=EventManager,window.ExtensionInterface=ExtensionInterface,window.FeatureGate=FeatureGate,window.Strings=Strings,window.NotificationUI=NotificationUI,Phoenix.globalAPI.NotificationUI=NotificationUI,Phoenix.globalAPI.PreferencesManager=PreferencesManager,require("utils/Global"),require("editor/CSSInlineEditor"),require("project/WorkingSetSort"),require("search/QuickOpen"),require("search/QuickOpenHelper"),require("file/FileUtils"),require("project/SidebarView"),require("view/SidebarTabs"),require("view/CentralControlBar"),require("utils/Resizer"),require("LiveDevelopment/main"),require("utils/NodeConnection"),require("utils/NodeDomain"),require("utils/NodeUtils"),require("utils/ColorUtils"),require("view/ThemeManager"),require("view/DefaultPanelView"),require("thirdparty/lodash"),require("language/XMLUtils"),require("language/JSONUtils"),require("widgets/InlineMenu"),require("thirdparty/tinycolor"),require("utils/LocalizationUtils"),require("phoenix-builder/main"),require("phoenix-builder/debug-overrides");const CodeMirror=require("thirdparty/CodeMirror/lib/codemirror");Object.defineProperty(window,"CodeMirror",{get:function(){return DeprecationWarning.deprecationWarning('Use brackets.getModule("thirdparty/CodeMirror/lib/codemirror") instead of global CodeMirror.',!0),CodeMirror}});const Mustache=require("thirdparty/mustache/mustache");Object.defineProperty(window,"Mustache",{get:function(){return DeprecationWarning.deprecationWarning('Use brackets.getModule("thirdparty/mustache/mustache") instead of global Mustache.',!0),Mustache}});const PathUtils=require("thirdparty/path-utils/path-utils");Object.defineProperty(window,"PathUtils",{get:function(){return DeprecationWarning.deprecationWarning('Use brackets.getModule("thirdparty/path-utils/path-utils") instead of global PathUtils.',!0),PathUtils}}),require("features/ParameterHintsManager"),require("features/JumpToDefManager"),require("features/QuickViewManager"),require("features/SelectionViewManager"),require("features/TaskManager"),require("features/BeautificationManager"),require("features/NewFileContentManager"),require("command/DefaultMenus"),require("document/ChangedDocumentTracker"),require("editor/EditorCommandHandlers"),require("editor/EditorOptionHandlers"),require("editor/EditorStatusBar"),require("editor/ImageViewer"),require("editor/MediaViewer"),require("editor/TabstopManager"),require("extensibility/ExtensionDownloader"),require("extensibility/InstallExtensionDialog"),require("extensibility/ExtensionManagerDialog"),require("help/HelpCommandHandlers"),require("search/FindInFilesUI"),require("search/FindReplace"),require("features/FindReferencesManager"),require("JSUtils/Session"),require("JSUtils/ScopeManager"),require("worker/IndexingWorker"),require("worker/ExtensionsWorker"),PerfUtils.addMeasurement("brackets module dependencies resolved");const params=new UrlParams;function _initTest(){brackets.test={BeautificationManager:require("features/BeautificationManager"),CodeHintManager:require("editor/CodeHintManager"),CodeInspection:require("language/CodeInspection"),CommandManager:require("command/CommandManager"),Commands:require("command/Commands"),CSSUtils:require("language/CSSUtils"),DefaultDialogs:require("widgets/DefaultDialogs"),Dialogs:require("widgets/Dialogs"),DocumentCommandHandlers:require("document/DocumentCommandHandlers"),DocumentManager:require("document/DocumentManager"),DocumentModule:require("document/Document"),DragAndDrop:require("utils/DragAndDrop"),EditorManager:require("editor/EditorManager"),Editor:require("editor/Editor"),EventManager:require("utils/EventManager"),ExtensionLoader:require("utils/ExtensionLoader"),ExtensionUtils:require("utils/ExtensionUtils"),ExtensionInterface:require("utils/ExtensionInterface"),FeatureGate:require("utils/FeatureGate"),File:require("filesystem/File"),FileFilters:require("search/FileFilters"),FileSyncManager:require("project/FileSyncManager"),FileSystem:require("filesystem/FileSystem"),FileUtils:require("file/FileUtils"),FileViewController:require("project/FileViewController"),FindInFiles:require("search/FindInFiles"),FindInFilesUI:require("search/FindInFilesUI"),FindUtils:require("search/FindUtils"),HTMLInstrumentation:require("LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation"),InstallExtensionDialog:require("extensibility/InstallExtensionDialog"),JSUtils:require("language/JSUtils"),KeyBindingManager:require("command/KeyBindingManager"),LanguageManager:require("language/LanguageManager"),LiveDevMultiBrowser:require("LiveDevelopment/LiveDevMultiBrowser"),LiveDevServerManager:require("LiveDevelopment/LiveDevServerManager"),LiveDevProtocol:require("LiveDevelopment/MultiBrowserImpl/protocol/LiveDevProtocol"),MainViewFactory:require("view/MainViewFactory"),MainViewManager:require("view/MainViewManager"),Menus:require("command/Menus"),MultiRangeInlineEditor:require("editor/MultiRangeInlineEditor").MultiRangeInlineEditor,NativeApp:require("utils/NativeApp"),NodeUtils:require("utils/NodeUtils"),PerfUtils:require("utils/PerfUtils"),PreferencesManager:require("preferences/PreferencesManager"),ProjectManager:require("project/ProjectManager"),QuickViewManager:require("features/QuickViewManager"),SelectionViewManager:require("features/SelectionViewManager"),TaskManager:require("features/TaskManager"),StatusBar:require("widgets/StatusBar"),ThemeManager:require("view/ThemeManager"),WorkspaceManager:require("view/WorkspaceManager"),SearchResultsView:require("search/SearchResultsView"),ScrollTrackMarkers:require("search/ScrollTrackMarkers"),SidebarTabs:require("view/SidebarTabs"),SidebarView:require("project/SidebarView"),WorkingSetView:require("project/WorkingSetView"),doneLoading:!1},AppInit.appReady(function(){brackets.test.doneLoading=!0})}function _removePhoenixLoadingOverlay(){window.splashScreenPresent&&(document.getElementById("phoenix-loading-splash-screen-overlay").remove(),window.splashScreenPresent=!1,ProjectManager.off(ProjectManager.EVENT_PROJECT_OPEN_FAILED,_removePhoenixLoadingOverlay),ProjectManager.off(ProjectManager.EVENT_PROJECT_OPEN,_removePhoenixLoadingOverlay))}function _startupBrackets(){console.log("Starting Brackets...");const extensionPathOverride=params.get("extensions"),extensionLoaderPromise=ExtensionLoader.init(extensionPathOverride?extensionPathOverride.split(","):null);ViewCommandHandlers.restoreFontSize(),ProjectManager.getStartupProjectPath().then(initialProjectPath=>{ProjectManager.openProject(initialProjectPath).always(function(){(Phoenix.isTestWindow||window._phoenixBuilder)&&_initTest();const deferred=new $.Deferred;params.get("skipSampleProjectLoad")||PreferencesManager.getViewState("afterFirstLaunch")?deferred.resolve():(PreferencesManager.setViewState("afterFirstLaunch","true"),ProjectManager.isWelcomeProjectPath(initialProjectPath)?FileSystem.resolve(initialProjectPath+"index.html",function(err,file){if(err)deferred.reject();else{const promise=CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN,{fullPath:file.fullPath});promise.then(deferred.resolve,deferred.reject)}}):deferred.resolve()),deferred.always(function(){extensionLoaderPromise.always(function(){if(AppInit._dispatchReady(AppInit.EXTENSIONS_LOADED),AppInit._dispatchReady(AppInit.APP_READY),PerfUtils.addMeasurement("Application Startup"),PreferencesManager._isUserScopeCorrupt()){const userPrefFullPath=PreferencesManager.getUserPrefFile();let file;Metrics.countEvent(Metrics.EVENT_TYPE.STORAGE,"prefs.corrupt","startup"),FileSystem.getFileForPath(userPrefFullPath).unlinkAsync().finally(function(){Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR,Strings.ERROR_PREFS_RESET_TITLE,Strings.ERROR_PREFS_CORRUPT_RESET)})}})})})})}function _onReady(){PerfUtils.addMeasurement("window.document Ready");const osxMatch=/Mac OS X 10\D([\d+])\D/.exec(window.navigator.userAgent);if(osxMatch&&osxMatch[1]&&Number(osxMatch[1])>=7){const $testDiv=$("
").appendTo(window.document.body);$testDiv.outerWidth()===$testDiv.get(0).clientWidth&&$(".sidebar").removeClass("quiet-scrollbars"),$testDiv.remove()}Async.waitForAll([LanguageManager.ready,PreferencesManager.ready]).always(function(){window._phoenixfsAppDirsCreatePromise.finally(_startupBrackets)})}function _beforeHTMLReady(){const $body=$("body");$body.addClass("platform-"+brackets.platform),Phoenix.isNativeApp&&$body.addClass("tauri"),$body.addClass("in-appshell"),$("#toolbar-extension-manager").prop("title",Strings.EXTENSION_MANAGER_TITLE),$("#update-notification").prop("title",Strings.UPDATE_NOTIFICATION_TOOLTIP),$("title").text(brackets.config.app_title),DragAndDrop.attachHandlers(),$(window).focus(function(){FileSyncManager.syncOpenDocuments(),Phoenix.browser.isTauri||ProjectManager.refreshFileTree()}),$("html").on("mousedown",".inline-widget",function(e){1===e.button&&e.preventDefault()}),$("html").on("mousedown",".no-focus",function(e){const $target=$(e.target),isFormElement=$target.is("input")||$target.is("textarea")||$target.is("select");isFormElement||e.preventDefault()}),window.document.body.addEventListener("click",function(e){if(2===e.button||"mac"===brackets.platform&&e.ctrlKey)return;let node=e.target,url;for(;node;){if("A"===node.tagName){(url=node.getAttribute("href"))&&!url.match(/^#/)&&(NativeApp.openURLInDefaultBrowser(url),e.stopPropagation()),e.preventDefault();break}node=node.parentElement}},!0);const DefaultCtor=jQuery.fn.init;jQuery.fn.init=function(firstArg,secondArg){const jQObject=new DefaultCtor(firstArg,secondArg);return firstArg&&firstArg._EventDispatcher&&(jQObject.on=firstArg.on.bind(firstArg),jQObject.one=firstArg.one.bind(firstArg),jQObject.off=firstArg.off.bind(firstArg),DeprecationWarning.deprecationWarning("Deprecated: Do not use $().on/off() on Brackets modules and model objects. Call on()/off() directly on the object without a $() wrapper.",!0,4)),jQObject}}params.parse(),ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN_FAILED,_removePhoenixLoadingOverlay),ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN,_removePhoenixLoadingOverlay),_beforeHTMLReady(),AppInit._dispatchReady(AppInit.HTML_READY),$(window.document).ready(_onReady)}),define("JSUtils/HintUtils",function(require,exports,module){var Acorn=require("thirdparty/acorn/dist/acorn"),LANGUAGE_ID="javascript",JSX_LANGUAGE_ID="jsx",HTML_LANGUAGE_ID="html",PHP_LANGUAGE_ID="php",SUPPORTED_LANGUAGES=[LANGUAGE_ID,"jsx","html","php"],SINGLE_QUOTE="'",DOUBLE_QUOTE='"';function makeToken(value,positions){return{value:value,positions:positions=positions||[]}}function maybeIdentifier(key){var result=!1,i;for(i=0;i0&&(baseRegExp&&settings.push("/"+baseRegExp.source+"/"),settings.forEach(function(value,index){var isRegExp;"string"==typeof value&&(value="/"===value[0]&&"/"===value[value.length-1]?value.substring(1,value.length-1):"^"+(value=(value=(value=StringUtils.regexEscape(value)).replace("\\?",".?")).replace("\\*",".*"))+"$",index>0&&(regExpString+="|"),regExpString=regExpString.concat(value))})),!regExpString){var defaultParts=[];if(baseRegExp&&defaultParts.push(baseRegExp.source),defaultRegExp&&defaultParts.push(defaultRegExp.source),!(defaultParts.length>0))return null;regExpString=defaultParts.join("|")}return new RegExp(regExpString)}function Preferences(prefs){var BASE_EXCLUDED_DIRECTORIES=null,DEFAULT_EXCLUDED_DIRECTORIES=/node_modules/,BASE_EXCLUDED_FILES=/^require.*\.js$|^jquery.*\.js$/,DEFAULT_MAX_FILE_COUNT=100,DEFAULT_MAX_FILE_SIZE=524288;prefs?(this._excludedDirectories=settingsToRegExp(prefs["excluded-directories"],null,DEFAULT_EXCLUDED_DIRECTORIES),this._excludedFiles=settingsToRegExp(prefs["excluded-files"],BASE_EXCLUDED_FILES),this._maxFileCount=prefs["max-file-count"],this._maxFileSize=prefs["max-file-size"],(!this._maxFileCount||this._maxFileCount<0)&&(this._maxFileCount=100),(!this._maxFileSize||this._maxFileSize<0)&&(this._maxFileSize=524288)):(this._excludedDirectories=DEFAULT_EXCLUDED_DIRECTORIES,this._excludedFiles=BASE_EXCLUDED_FILES,this._maxFileCount=100,this._maxFileSize=524288)}Preferences.FILE_NAME=".jscodehints",Preferences.prototype.getExcludedDirectories=function(){return this._excludedDirectories},Preferences.prototype.getExcludedFiles=function(){return this._excludedFiles},Preferences.prototype.getMaxFileCount=function(){return this._maxFileCount},Preferences.prototype.getMaxFileSize=function(){return this._maxFileSize},module.exports=Preferences}),define("JSUtils/ScopeManager",function(require,exports,module){var _=require("thirdparty/lodash");const CodeMirror=require("thirdparty/CodeMirror/lib/codemirror"),DefaultDialogs=require("widgets/DefaultDialogs"),Dialogs=require("widgets/Dialogs"),DocumentManager=require("document/DocumentManager"),EditorManager=require("editor/EditorManager"),FileSystem=require("filesystem/FileSystem"),FileUtils=require("file/FileUtils"),LanguageManager=require("language/LanguageManager"),PreferencesManager=require("preferences/PreferencesManager"),ProjectManager=require("project/ProjectManager"),Strings=require("strings"),StringUtils=require("utils/StringUtils"),InMemoryFile=require("document/InMemoryFile"),IndexingWorker=require("worker/IndexingWorker");IndexingWorker.loadScriptInWorker(`${Phoenix.baseURL}JSUtils/worker/tern-main.js`);var HintUtils=require("./HintUtils"),MessageIds=JSON.parse(require("text!./MessageIds.json")),Preferences=require("./Preferences");let ternEnvironment=[],ternConfigInitDone=!1,pendingTernRequests={},builtinLibraryNames=[],isDocumentDirty=!1,_hintCount=0,currentModule=null,documentChanges=null,preferences=null,deferredPreferences=null;const MAX_HINTS=30,LARGE_LINE_CHANGE=100,LARGE_LINE_COUNT=1e4,OFFSET_ZERO={line:0,ch:0};var config={};function getBuiltins(){return builtinLibraryNames}function initTernEnv(){const builtinDefinitionFiles=JSON.parse('["browser.json","chai.json","ecmascript.json","jquery.json","react.json","underscore.json"]');for(let fileName of builtinDefinitionFiles){let fileUrl=`${Phoenix.baseURL}thirdparty/tern/defs/${fileName}`;console.log("loading tern definition file: ",fileUrl),fetch(fileUrl).then(async contents=>{const ternDefsLibrary=await contents.json();builtinLibraryNames.push(ternDefsLibrary["!name"]),ternEnvironment.push(ternDefsLibrary)}).catch(e=>{console.error("failed to init from tern definition file "+fileName,e)})}}function initPreferences(projectRootPath){deferredPreferences&&"pending"===deferredPreferences.state()&&deferredPreferences.reject(),deferredPreferences=$.Deferred();var pr=ProjectManager.getProjectRoot();if(pr)projectRootPath=pr.fullPath;else if(!projectRootPath)return console.log("initPreferences: projectRootPath has no value. Using Defaults."),void(preferences=new Preferences);var path=projectRootPath+Preferences.FILE_NAME;preferences=new Preferences,FileSystem.resolve(path,function(err,file){err?deferredPreferences.resolve():FileUtils.readAsText(file).done(function(text){var configObj=null;try{configObj=JSON.parse(text)}catch(e){console.log("Error parsing preference file: "+path),e instanceof SyntaxError&&console.log(e.message)}preferences=new Preferences(configObj),deferredPreferences.resolve()}).fail(function(error){preferences=new Preferences,deferredPreferences.resolve()})})}function ensurePreferences(){deferredPreferences||initPreferences()}function postMessage(msg){currentModule&¤tModule.postMessage(msg)}function isDirectoryExcluded(path){var excludes=preferences.getExcludedDirectories();if(!excludes)return!1;var testPath=ProjectManager.makeProjectRelativeIfPossible(path);return testPath=FileUtils.stripTrailingSlash(testPath),excludes.test(testPath)}function isFileBeingEdited(filePath){var currentEditor=EditorManager.getActiveEditor(),currentDoc=currentEditor&¤tEditor.document;return currentDoc&¤tDoc.file.fullPath===filePath}function isFileExcludedInternal(path){var detectedExclusions=PreferencesManager.get("jscodehints.detectedExclusions")||[];return!(!detectedExclusions||-1===detectedExclusions.indexOf(path))}function isFileExcluded(file){if("."===file.name[0])return!0;var languageID;if(LanguageManager.getLanguageForPath(file.fullPath).getId()!==HintUtils.LANGUAGE_ID)return!0;var excludes=preferences.getExcludedFiles();return!(!excludes||!excludes.test(file.name))||!!isFileExcludedInternal(file.fullPath)}function addPendingRequest(file,offset,type){var requests,key=file+"@"+offset.line+"@"+offset.ch,$deferredRequest;return isFileExcludedInternal(file)?(new $.Deferred).reject().promise():(_.has(pendingTernRequests,key)?requests=pendingTernRequests[key]:(requests={},pendingTernRequests[key]=requests),_.has(requests,type)?$deferredRequest=requests[type]:requests[type]=$deferredRequest=new $.Deferred,$deferredRequest.promise())}function getPendingRequest(file,offset,type){var key=file+"@"+offset.line+"@"+offset.ch;if(_.has(pendingTernRequests,key)){var requests=pendingTernRequests[key],requestType=requests[type];return delete pendingTernRequests[key][type],Object.keys(requests).length||delete pendingTernRequests[key],requestType}}function getResolvedPath(file){return currentModule.getResolvedPath(file)}function getJumptoDef(fileInfo,offset){return postMessage({type:MessageIds.TERN_JUMPTODEF_MSG,fileInfo:fileInfo,offset:offset}),addPendingRequest(fileInfo.name,offset,MessageIds.TERN_JUMPTODEF_MSG)}function filterText(text){ensurePreferences();var newText=text;return text.length>preferences.getMaxFileSize()&&(newText=""),newText}function getTextFromDocument(document){var text=document.getText();return text=filterText(text)}function handleRename(response){if(response.error)return;let file,offset,$deferredFindRefs=getPendingRequest(response.file,response.offset,MessageIds.TERN_REFS);$deferredFindRefs&&$deferredFindRefs.resolveWith(null,[response])}function requestJumptoDef(session,document,offset){var path=document.file.fullPath,fileInfo,ternPromise;return{promise:getJumptoDef({type:MessageIds.TERN_FILE_INFO_TYPE_FULL,name:path,offsetLines:0,text:filterText(session.getJavascriptText())},offset)}}function handleJumptoDef(response){var file,offset,$deferredJump=getPendingRequest(response.file,response.offset,MessageIds.TERN_JUMPTODEF_MSG);$deferredJump&&(response.fullPath=getResolvedPath(response.resultFile),$deferredJump.resolveWith(null,[response]))}function handleScopeData(response){var file,offset,$deferredJump=getPendingRequest(response.file,response.offset,MessageIds.TERN_SCOPEDATA_MSG);$deferredJump&&$deferredJump.resolveWith(null,[response])}function getTernHints(fileInfo,offset,isProperty){return postMessage({type:MessageIds.TERN_COMPLETIONS_MSG,fileInfo:fileInfo,offset:offset,isProperty:isProperty}),addPendingRequest(fileInfo.name,offset,MessageIds.TERN_COMPLETIONS_MSG)}function getTernFunctionType(fileInfo,offset){return postMessage({type:MessageIds.TERN_CALLED_FUNC_TYPE_MSG,fileInfo:fileInfo,offset:offset}),addPendingRequest(fileInfo.name,offset,MessageIds.TERN_CALLED_FUNC_TYPE_MSG)}function getFragmentAround(session,start){var minIndent=null,minLine=null,endLine,cm=session.editor._codeMirror,tabSize=cm.getOption("tabSize"),document=session.editor.document,p,min,indent,line;for(p=start.line-1,min=Math.max(0,p-100);p>=min;--p){var fn=(line=session.getLine(p)).search(/\bfunction\b/);fn>=0&&(indent=CodeMirror.countColumn(line,null,tabSize),(null===minIndent||minIndent>indent)&&"keyword"===session.getToken({line:p,ch:fn+1}).type&&(minIndent=indent,minLine=p))}null===minIndent&&(minIndent=0),null===minLine&&(minLine=min);var max=Math.min(cm.lastLine(),start.line+100),endCh=0;for(endLine=start.line+1;endLine0&&(indent=CodeMirror.countColumn(line,null,tabSize))<=minIndent){endCh=line.length;break}var from={line:minLine,ch:0},to={line:endLine,ch:endCh};return{type:MessageIds.TERN_FILE_INFO_TYPE_PART,name:document.file.fullPath,offsetLines:from.line,text:document.getRange(from,to)}}function getFileInfo(session,preventPartialUpdates){var start=session.getCursor(),end=start,document=session.editor.document,path=document.file.fullPath,isHtmlFile,result;return result="html"===LanguageManager.getLanguageForPath(path).getId()?{type:MessageIds.TERN_FILE_INFO_TYPE_FULL,name:path,text:session.getJavascriptText()}:documentChanges?!preventPartialUpdates&&session.editor.lineCount()>LARGE_LINE_COUNT&&documentChanges.to-documentChanges.fromend.line?getFragmentAround(session,start):{type:MessageIds.TERN_FILE_INFO_TYPE_FULL,name:path,text:getTextFromDocument(document)}:{type:MessageIds.TERN_FILE_INFO_TYPE_EMPTY,name:path,text:""},documentChanges=null,result}function getOffset(session,fileInfo,offset){var newOffset;return newOffset=offset?{line:offset.line,ch:offset.ch}:session.getCursor(),fileInfo.type===MessageIds.TERN_FILE_INFO_TYPE_PART&&(newOffset.line=Math.max(0,newOffset.line-fileInfo.offsetLines)),newOffset}function requestGuesses(session,document){var $deferred=$.Deferred(),fileInfo=getFileInfo(session),offset=getOffset(session,fileInfo),promise;return postMessage({type:MessageIds.TERN_GET_GUESSES_MSG,fileInfo:fileInfo,offset:offset}),addPendingRequest(fileInfo.name,offset,MessageIds.TERN_GET_GUESSES_MSG).done(function(guesses){session.setGuesses(guesses),$deferred.resolve()}).fail(function(){$deferred.reject()}),$deferred.promise()}function handleTernCompletions(response){var file=response.file,offset=response.offset,completions=response.completions,properties=response.properties,fnType=response.fnType,type=response.type,error=response.error,$deferredHints=getPendingRequest(file,offset,type);$deferredHints&&(error?$deferredHints.reject():completions?$deferredHints.resolveWith(null,[{completions:completions}]):properties?$deferredHints.resolveWith(null,[{properties:properties}]):fnType&&$deferredHints.resolveWith(null,[fnType]))}function handleGetGuesses(response){var path=response.file,type=response.type,offset,$deferredHints=getPendingRequest(path,response.offset,type);$deferredHints&&$deferredHints.resolveWith(null,[response.properties])}function handleUpdateFile(response){var path=response.path,type=response.type,$deferredHints=getPendingRequest(path,OFFSET_ZERO,type);$deferredHints&&$deferredHints.resolve()}function handleTimedOut(response){var detectedExclusions=PreferencesManager.get("jscodehints.detectedExclusions")||[],filePath=response.file;isFileBeingEdited(filePath)||(-1===detectedExclusions.indexOf(filePath)?(detectedExclusions.push(filePath),PreferencesManager.set("jscodehints.detectedExclusions",detectedExclusions,{location:{scope:"project"}}),Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_INFO,Strings.DETECTED_EXCLUSION_TITLE,StringUtils.format(Strings.DETECTED_EXCLUSION_INFO,StringUtils.breakableUrl(filePath)),[{className:Dialogs.DIALOG_BTN_CLASS_PRIMARY,id:Dialogs.DIALOG_BTN_OK,text:Strings.OK}])):console.log("JavaScriptCodeHints.handleTimedOut: file already in detectedExclusions array timed out: "+filePath))}function TernModule(){var ternPromise=null,addFilesPromise=null,rootTernDir=null,projectRoot=null,stopAddingFiles=!1,resolvedFiles={},numInitialFiles=0,numResolvedFiles=0,numAddedFiles=0;function getResolvedPath(file){return resolvedFiles[file]}function usingModules(){return numInitialFiles!==numResolvedFiles}function postMessage(msg){addFilesPromise.done(function(){config.debug&&console.debug("Sending message",msg),IndexingWorker.execPeer("invokeTernCommand",msg)})}function _postMessageByPass(msg){ternPromise.done(function(){config.debug&&console.debug("Sending message",msg),IndexingWorker.execPeer("invokeTernCommand",msg)})}function updateTernFile(document){var path=document.file.fullPath;return _postMessageByPass({type:MessageIds.TERN_UPDATE_FILE_MSG,path:path,text:getTextFromDocument(document)}),addPendingRequest(path,OFFSET_ZERO,MessageIds.TERN_UPDATE_FILE_MSG)}function handleTernGetFile(request){function replyWith(name,txt){_postMessageByPass({type:MessageIds.TERN_GET_FILE_MSG,file:name,text:txt})}var name=request.file;function getDocText(filePath){if(filePath.startsWith("/")||(filePath=`/${filePath}`),!FileSystem.isAbsolutePath(filePath)||"//"===filePath.slice(0,2))return(new $.Deferred).reject().promise();var file=FileSystem.getFileForPath(filePath),promise=DocumentManager.getDocumentText(file);return promise.done(function(docText){resolvedFiles[name]=filePath,numResolvedFiles++,replyWith(name,filterText(docText))}),promise}function findNameInProject(){var fileName=name.substring(name.lastIndexOf("/")+1);function _fileFilter(entry){return entry.name===fileName}ProjectManager.getAllFiles(_fileFilter).done(function(files){var file;1===(files=files.filter(function(file){var pos;return file.fullPath.length-name.length===file.fullPath.lastIndexOf(name)})).length&&(file=files[0]),file?getDocText(file.fullPath).fail(function(){replyWith(name,"")}):replyWith(name,"")})}isFileExcludedInternal(name)||getDocText(name).fail(function(){getDocText(rootTernDir+name).fail(function(){getDocText(projectRoot+name).fail(findNameInProject)})})}function primePump(path,isUntitledDoc){return _postMessageByPass({type:MessageIds.TERN_PRIME_PUMP_MSG,path:path,isUntitledDoc:isUntitledDoc}),addPendingRequest(path,OFFSET_ZERO,MessageIds.TERN_PRIME_PUMP_MSG)}function handlePrimePumpCompletion(response){var path=response.path,type=response.type,$deferredHints=getPendingRequest(path,OFFSET_ZERO,type);$deferredHints&&$deferredHints.resolve()}function addFilesToTern(files){var maxFileCount=preferences.getMaxFileCount();if(numResolvedFiles+numAddedFiles{moduleDeferred.resolveWith(null)}))}function initTernServer(dir,files){initTernModule(),numResolvedFiles=0,numAddedFiles=0,stopAddingFiles=!1,numInitialFiles=files.length,ternPromise.done(function(){var msg={type:MessageIds.TERN_INIT_MSG,dir:dir,files:files,env:ternEnvironment,timeout:PreferencesManager.get("jscodehints.inferenceTimeout")};IndexingWorker.execPeer("invokeTernCommand",msg)}),rootTernDir=dir.endsWith("/")?dir:dir+"/"}function canSkipTernInitialization(newFile){return void 0!==resolvedFiles[newFile]}function doEditorChange(session,document,previousDocument){var file=document.file,path=file.fullPath,dir=file.parentPath,pr,addFilesDeferred=$.Deferred(),updateFilePromise;(documentChanges=null,addFilesPromise=addFilesDeferred.promise(),pr=ProjectManager.getProjectRoot()?ProjectManager.getProjectRoot().fullPath:null,canSkipTernInitialization(path))?(isDocumentDirty&&previousDocument?updateTernFile(previousDocument).done(function(){primePump(path,document.isUntitled()),addFilesDeferred.resolveWith(null)}):addFilesDeferred.resolveWith(null),isDocumentDirty=!1):(previousDocument&&previousDocument.isDirty&&updateTernFile(previousDocument),isDocumentDirty=!1,resolvedFiles={},projectRoot=pr,ensurePreferences(),deferredPreferences.done(function(){var hintsPromise;if(file instanceof InMemoryFile)return initTernServer(pr,[]),void primePump(path,!0).done(function(){addFilesDeferred.resolveWith(null)});FileSystem.resolve(dir,function(err,directory){if(err)return console.error("Error resolving",dir),void addFilesDeferred.resolveWith(null);directory.getContents(function(err,contents){if(err)return console.error("Error getting contents for",directory),void addFilesDeferred.resolveWith(null);var files=contents.filter(function(entry){return entry.isFile&&!isFileExcluded(entry)}).map(function(entry){return entry.fullPath}),hintsPromise;initTernServer(dir,files),primePump(path,!1).done(function(){usingModules()?addFilesDeferred.resolveWith(null):addAllFilesAndSubdirectories(dir,function(){var currentDir=dir+"/";projectRoot&¤tDir!==projectRoot&&0===currentDir.indexOf(projectRoot)?addAllFilesAndSubdirectories(projectRoot,function(){primePump(path,!1),addFilesDeferred.resolveWith(null)}):addFilesDeferred.resolveWith(null)})})})})}))}function handleEditorChange(session,document,previousDocument){null===addFilesPromise?doEditorChange(session,document,previousDocument):addFilesPromise.done(function(){doEditorChange(session,document,previousDocument)})}function resetModule(){function resetTernServer(){IndexingWorker.execPeer("resetTernServer")}addFilesPromise?addFilesPromise.done(resetTernServer).fail(resetTernServer):resetTernServer()}function whenReady(func){addFilesPromise.done(func)}return this.resetModule=resetModule,this.handleEditorChange=handleEditorChange,this.postMessage=postMessage,this.getResolvedPath=getResolvedPath,this.whenReady=whenReady,this}initTernEnv(),DocumentManager.on("dirtyFlagChange",function(event,changedDoc){changedDoc.file.fullPath&&postMessage({type:MessageIds.TERN_UPDATE_DIRTY_FILE,name:changedDoc.file.fullPath,action:changedDoc.isDirty})}),ProjectManager.on("beforeProjectClose",function(){postMessage({type:MessageIds.TERN_CLEAR_DIRTY_FILES_LIST})});var resettingDeferred=null;function _maybeReset(session,document,force){var newTernModule;if(!resettingDeferred){if(!(currentModule.resetForced||force||!config.noReset&&++_hintCount>MAX_HINTS)){var d=new $.Deferred;return d.resolve(currentModule),d.promise()}config.debug&&console.debug("Resetting tern module"),resettingDeferred=new $.Deferred,(newTernModule=new TernModule).handleEditorChange(session,document,null),newTernModule.whenReady(function(){currentModule.resetModule(),currentModule=newTernModule,resettingDeferred.resolve(currentModule),resettingDeferred=null}),_hintCount=0}return resettingDeferred.promise()}function requestParameterHint(session,functionOffset){var $deferredHints=$.Deferred(),fileInfo=getFileInfo(session,!0),offset,fnTypePromise=getTernFunctionType(fileInfo,getOffset(session,fileInfo,functionOffset));return $.when(fnTypePromise).done(function(fnType){session.setFnType(fnType),session.setFunctionCallPos(functionOffset),$deferredHints.resolveWith(null,[fnType])}).fail(function(){$deferredHints.reject()}),$deferredHints.promise()}function requestHints(session,document){var $deferredHints=$.Deferred(),hintPromise,sessionType=session.getType(),fileInfo=getFileInfo(session),offset=getOffset(session,fileInfo,null);return _maybeReset(session,document),hintPromise=getTernHints(fileInfo,offset,sessionType.property),$.when(hintPromise).done(function(completions,fnType){completions.completions?(session.setTernHints(completions.completions),session.setGuesses(null)):(session.setTernHints([]),session.setGuesses(completions.properties)),$deferredHints.resolveWith(null)}).fail(function(){$deferredHints.reject()}),$deferredHints.promise()}function trackChange(changeList){var changed=documentChanges,i;for(null===changed&&(documentChanges=changed={from:changeList[0].from.line,to:changeList[0].from.line},config.debug&&console.debug("ScopeManager: document has changed")),i=0;i=changed.to&&(changed.to=end+1),changed.from>thisChange.from.line&&(changed.from=thisChange.from.line)}}function handleFileChange(changeList){isDocumentDirty=!0,trackChange(changeList)}function handleEditorChange(session,document,previousDocument){return currentModule||(currentModule=new TernModule),currentModule.handleEditorChange(session,document,previousDocument)}function handleProjectClose(){currentModule&¤tModule.resetModule()}function handleProjectOpen(projectRootPath){initPreferences(projectRootPath)}function _readyPromise(){return deferredPreferences}function _setConfig(configUpdate){config=brackets._configureJSCodeHints.config,postMessage({type:MessageIds.SET_CONFIG,config:configUpdate})}exports._setConfig=_setConfig,exports._maybeReset=_maybeReset,exports.getBuiltins=getBuiltins,exports.getResolvedPath=getResolvedPath,exports.getTernHints=getTernHints,exports.handleEditorChange=handleEditorChange,exports.requestGuesses=requestGuesses,exports.handleFileChange=handleFileChange,exports.requestHints=requestHints,exports.requestJumptoDef=requestJumptoDef,exports.requestParameterHint=requestParameterHint,exports.handleProjectClose=handleProjectClose,exports.handleProjectOpen=handleProjectOpen,exports._readyPromise=_readyPromise,exports.filterText=filterText,exports.postMessage=postMessage,exports.addPendingRequest=addPendingRequest}),define("JSUtils/Session",function(require,exports,module){var StringMatch=require("utils/StringMatch"),TokenUtils=require("utils/TokenUtils"),LanguageManager=require("language/LanguageManager"),HTMLUtils=require("language/HTMLUtils"),HintUtils=require("JSUtils/HintUtils"),ScopeManager=require("JSUtils/ScopeManager"),Acorn=require("thirdparty/acorn/dist/acorn"),Acorn_Loose=require("thirdparty/acorn/dist/acorn_loose");function Session(editor){this.editor=editor,this.path=editor.document.file.fullPath,this.ternHints=[],this.ternGuesses=null,this.fnType=null,this.builtins=null}function getLexicalState(token){return token.state.lexical?token.state.lexical:token.state.localState&&token.state.localState.lexical?token.state.localState.lexical:void 0}function penalizeUnderscoreValueCompare(a,b){var aName=a.value.toLowerCase(),bName=b.value.toLowerCase();return"_"===aName[0]&&"_"!==bName[0]?1:"_"===bName[0]&&"_"!==aName[0]?-1:aNamebName?1:0}Session.prototype._getBuiltins=function(){return this.builtins||(this.builtins=ScopeManager.getBuiltins(),this.builtins.push("requirejs.js")),this.builtins},Session.prototype.getPath=function(){return this.path},Session.prototype.getCursor=function(){return this.editor.getCursorPos()},Session.prototype.getLine=function(line){var doc;return this.editor.document.getLine(line)},Session.prototype.getOffset=function(){var cursor=this.getCursor();return this.getOffsetFromCursor(cursor)},Session.prototype.getOffsetFromCursor=function(cursor){return this.editor.indexFromPos(cursor)},Session.prototype.getToken=function(cursor){var cm=this.editor._codeMirror;return cursor?TokenUtils.getTokenAt(cm,cursor):TokenUtils.getTokenAt(cm,this.getCursor())},Session.prototype.getNextTokenOnLine=function(cursor){return(cursor=this.getNextCursorOnLine(cursor))?this.getToken(cursor):null},Session.prototype.getNextCursorOnLine=function(cursor){var doc,line=this.editor.document.getLine(cursor.line);return cursor.ch0)cursor.ch=prev.start-1;else{if(!(cursor.line>0))break;cursor.ch=doc.getLine(cursor.line-1).length,cursor.line--}prev=this.getToken(cursor)}while(!/\S/.test(prev.string));return prev},Session.prototype.getNextToken=function(cursor,skipWhitespace){var token,next=this.getToken(cursor),doc=this.editor.document;do{if(next.end>cursor.ch)cursor.ch=next.end;else if(next.end0&&HintUtils.maybeIdentifier(line[start-1]);)start--;query=line.substring(start,end)}return query},Session.prototype.getContext=function(cursor,depth){var token=this.getToken(cursor);return void 0===depth&&(depth=0),")"===token.string?(this._getPreviousToken(cursor),this.getContext(cursor,++depth)):"("===token.string?(this._getPreviousToken(cursor),this.getContext(cursor,--depth)):depth>0||"."===token.string?(this._getPreviousToken(cursor),this.getContext(cursor,depth)):token.string},Session.prototype.findPreviousDot=function(){var cursor=this.getCursor(),token=this.getToken(cursor);return token&&"."===token.string?cursor:(token=this._getPreviousToken(cursor))&&"."===token.string?cursor:void 0},Session.prototype.getFunctionInfo=function(){var inFunctionCall=!1,cursor=this.getCursor(),functionCallPos,token=this.getToken(cursor),lexical,self=this,foundCall=!1;function isOnFunctionIdentifier(){var type=token.type,nextToken,localLexical,localCursor={line:cursor.line,ch:token.end};return"variable-2"!==type&&"variable"!==type&&"property"!==type||!(nextToken=self.getNextToken(localCursor,!0))||"("!==nextToken.string?null:localLexical=getLexicalState(nextToken)}function isInFunctionalCall(lex){return lex&&("call"===lex.info||void 0===lex.info&&("]"===lex.type||"}"===lex.type)&&"call"===lex.prev.info)}if(token&&((foundCall=isInFunctionalCall(lexical=getLexicalState(token)))||(foundCall=isInFunctionalCall(lexical=isOnFunctionIdentifier())),foundCall)){void 0===lexical.info&&(lexical=lexical.prev);var col="call"===lexical.info?lexical.column:lexical.prev.column,line,e,found;for(line=this.getCursor().line,e=Math.max(0,line-9),found=!1;line>=e;--line)if("("===this.getLine(line).charAt(col)){found=!0;break}found&&(inFunctionCall=!0,functionCallPos={line:line,ch:col})}return{inFunctionCall:inFunctionCall,functionCallPos:functionCallPos}},Session.prototype.getType=function(){var propertyLookup=!1,context=null,cursor=this.getCursor(),token=this.getToken(cursor);return token&&("property"===token.type&&(propertyLookup=!0),(cursor=this.findPreviousDot())&&(propertyLookup=!0,context=this.getContext(cursor))),{property:propertyLookup,context:context}},Session.prototype.getHints=function(query,matcher){void 0===query&&(query="");var MAX_DISPLAYED_HINTS=500,type=this.getType(),builtins=this._getBuiltins(),needGuesses=!1,hints;function isBuiltin(origin){return-1!==builtins.indexOf(origin)}function filterWithQueryAndMatcher(hints,matcher){var matchResults;return $.map(hints,function(hint){var searchResult=matcher.match(hint.value,query);return searchResult&&(searchResult.value=hint.value,searchResult.guess=hint.guess,searchResult.type=hint.type,void 0!==hint.keyword&&(searchResult.keyword=hint.keyword),void 0!==hint.literal&&(searchResult.literal=hint.literal),void 0!==hint.depth&&(searchResult.depth=hint.depth),hint.doc&&(searchResult.doc=hint.doc),hint.url&&(searchResult.url=hint.url),!type.property&&!type.showFunctionType&&hint.origin&&isBuiltin(hint.origin)?searchResult.builtin=1:searchResult.builtin=0),searchResult})}return type.property?(0===(hints=filterWithQueryAndMatcher(hints=this.ternHints||[],matcher)).length&&(this.ternGuesses?hints=filterWithQueryAndMatcher(this.ternGuesses,matcher):needGuesses=!0),StringMatch.multiFieldSort(hints,["matchGoodness",penalizeUnderscoreValueCompare])):(hints=filterWithQueryAndMatcher(hints=(hints=(hints=this.ternHints||[]).concat(HintUtils.LITERALS)).concat(HintUtils.KEYWORDS),matcher),StringMatch.multiFieldSort(hints,["matchGoodness","depth","builtin",penalizeUnderscoreValueCompare])),hints.length>500&&(hints=hints.slice(0,500)),{hints:hints,needGuesses:needGuesses}},Session.prototype.setTernHints=function(newHints){this.ternHints=newHints},Session.prototype.setGuesses=function(newGuesses){this.ternGuesses=newGuesses},Session.prototype.setFnType=function(newFnType){this.fnType=newFnType},Session.prototype.setFunctionCallPos=function(functionCallPos){this.functionCallPos=functionCallPos},Session.prototype.getParameterHint=function(){var fnHint=this.fnType,cursor=this.getCursor(),token=this.getToken(this.functionCallPos),start={line:this.functionCallPos.line,ch:token.start},fragment=this.editor.document.getRange(start,{line:this.functionCallPos.line+10,ch:0}),ast;try{ast=Acorn.parse(fragment)}catch(e){ast=Acorn_Loose.parse(fragment,{})}var startOffset=this.getOffsetFromCursor(start),cursorOffset=this.getOffsetFromCursor(cursor),offset=cursorOffset-startOffset,node=ast.body[0],currentArg=-1;if("ExpressionStatement"===node.type&&("SequenceExpression"===(node=node.expression).type&&(node=node.expressions[0]),"BinaryExpression"===node.type&&("CallExpression"===node.left.type?node=node.left:"CallExpression"===node.right.type&&(node=node.right)),"CallExpression"===node.type)){var args=node.arguments,i,n=args.length,lastEnd=offset,text;for(i=0;i=(node=args[i]).start&&offset<=node.end){currentArg=i;break}if(offset=offset-lastEnd)i--;else if(0===i&&-1!==text.indexOf("(")){currentArg=-1;break}currentArg=Math.max(0,i);break}i+1===n&&-1!==(text=fragment.substring(node.end,offset)).indexOf(",")&&(currentArg=i+1),lastEnd=node.end}0===n&&cursorOffset>this.getOffsetFromCursor(this.functionCallPos)&&(currentArg=0)}return{parameters:fnHint,currentIndex:currentArg}},Session.prototype.getJavascriptText=function(){if("html"===LanguageManager.getLanguageForPath(this.editor.document.file.fullPath).getId()){var text="",editor=this.editor,scriptBlocks=HTMLUtils.findBlocks(editor,"javascript"),htmlStart={line:0,ch:0};return scriptBlocks.forEach(function(scriptBlock){var start=scriptBlock.start,end=scriptBlock.end,htmlText=editor.document.getRange(htmlStart,start);htmlText=htmlText.replace(/./g," "),htmlStart=end,text+=htmlText+scriptBlock.text}),text}return this.editor.document.getText()},Session.prototype.isFunctionName=function(){var cursor=this.getCursor(),prevToken;return"function"===this._getPreviousToken(cursor).string},module.exports=Session}),define("LiveDevelopment/LiveDevMultiBrowser",function(require,exports,module){const STATUS_INACTIVE=exports.STATUS_INACTIVE=0,STATUS_CONNECTING=exports.STATUS_CONNECTING=1,STATUS_ACTIVE=exports.STATUS_ACTIVE=2,STATUS_OUT_OF_SYNC=exports.STATUS_OUT_OF_SYNC=3,STATUS_SYNC_ERROR=exports.STATUS_SYNC_ERROR=4,STATUS_RELOADING=exports.STATUS_RELOADING=5,STATUS_RESTARTING=exports.STATUS_RESTARTING=6,EVENT_OPEN_PREVIEW_URL="openPreviewURL",EVENT_CONNECTION_CLOSE="ConnectionClose",EVENT_STATUS_CHANGE="statusChange",Dialogs=require("widgets/Dialogs"),DefaultDialogs=require("widgets/DefaultDialogs"),DocumentManager=require("document/DocumentManager"),EditorManager=require("editor/EditorManager"),EventDispatcher=require("utils/EventDispatcher"),MainViewManager=require("view/MainViewManager"),ProjectManager=require("project/ProjectManager"),Strings=require("strings"),LiveDevelopmentUtils=require("LiveDevelopment/LiveDevelopmentUtils"),LiveDevServerManager=require("LiveDevelopment/LiveDevServerManager"),LivePreviewTransport=require("LiveDevelopment/MultiBrowserImpl/transports/LivePreviewTransport"),LiveDevProtocol=require("LiveDevelopment/MultiBrowserImpl/protocol/LiveDevProtocol"),Metrics=require("utils/Metrics"),WorkspaceManager=require("view/WorkspaceManager"),FileSystem=require("filesystem/FileSystem"),PageLoaderWorkerScript=require("text!LiveDevelopment/BrowserScripts/pageLoaderWorker.js"),LiveCSSDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveCSSDocument"),LiveHTMLDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveHTMLDocument");var _liveDocument;let livePreviewUrlPinned=!1,currentPreviewFilePath;var _relatedDocuments={},_protocol=LiveDevProtocol,_server;let _config={},_lastPreviewedHTMLFilePath;function _classForDocument(doc){return"css"===doc.getLanguage().getId()?LiveCSSDocument:LiveDevelopmentUtils.isHtmlFileExt(doc.file.fullPath)?LiveHTMLDocument:null}function isActive(){return exports.status>STATUS_INACTIVE}function getLiveDocForPath(path){return _server?_server.get(path):null}function _closeDocument(liveDocument){liveDocument.off(".livedev"),_protocol.off(".livedev"),liveDocument.close()}function _handleRelatedDocumentDeleted(url){const liveDoc=_relatedDocuments[url];liveDoc&&(delete _relatedDocuments[url],_server&&_server.remove(liveDoc),_closeDocument(liveDoc))}function _setStatus(status,closeReason){if(status!==exports.status){exports.status=status;var reason=status===STATUS_INACTIVE?closeReason:null;exports.trigger(EVENT_STATUS_CHANGE,status,reason)}}function _closeDocuments(){_liveDocument&&(_closeDocument(_liveDocument),_liveDocument=void 0),Object.keys(_relatedDocuments).forEach(function(url){_closeDocument(_relatedDocuments[url]),delete _relatedDocuments[url]}),_server&&_server.clear()}function _resolveUrl(path){return _server&&_server.pathToUrl(path)}function _createLiveDocument(doc,editor,roots){var DocClass=_classForDocument(doc),liveDocument;return DocClass?((liveDocument=new DocClass(_protocol,_resolveUrl,doc,editor,roots)).on("errorStatusChanged.livedev",function(event,hasErrors){isActive()&&_setStatus(hasErrors?STATUS_SYNC_ERROR:STATUS_ACTIVE)}),liveDocument):null}function _docIsOutOfSync(doc){var liveDoc=_server&&_server.get(doc.file.fullPath),isLiveEditingEnabled=liveDoc&&liveDoc.isLiveEditingEnabled();return doc.isDirty&&!isLiveEditingEnabled}function _styleSheetAdded(event,url,roots){var path=_server&&_server.urlToPath(url),alreadyAdded=!!_relatedDocuments[url],docPromise;path&&!alreadyAdded&&DocumentManager.getDocumentForPath(path).done(function(doc){if(!(_relatedDocuments[url]||_classForDocument(doc)!==LiveCSSDocument||_liveDocument&&doc===_liveDocument.doc)){var liveDoc=_createLiveDocument(doc,doc._masterEditor,roots);liveDoc&&(_server.add(liveDoc),_relatedDocuments[url]=liveDoc,liveDoc.on("updateDoc",function(event,url){var path,doc;getLiveDocForPath(_server.urlToPath(url))._updateBrowser()}))}})}function _close(doCloseWindow,reason){exports.status!==STATUS_INACTIVE&&(_closeDocuments(),_protocol.closeAllConnections(),_server&&(_server.stop(),_server=null)),_setStatus(STATUS_INACTIVE,reason||"explicit_close")}function close(){return _close(!0),(new $.Deferred).resolve().promise()}function _showLiveDevServerNotReadyError(){Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR,Strings.LIVE_DEVELOPMENT_ERROR_TITLE,Strings.LIVE_DEV_SERVER_NOT_READY_MESSAGE)}function _updateVirtualServerScripts(){_server&&_liveDocument&&_liveDocument.doc&&(_server.addVirtualContentAtPath(`${_liveDocument.doc.file.parentPath}${LiveDevProtocol.LIVE_DEV_REMOTE_SCRIPTS_FILE_NAME}`,_protocol.getRemoteScriptContents()),_server.addVirtualContentAtPath(`${_liveDocument.doc.file.parentPath}${LiveDevProtocol.LIVE_DEV_REMOTE_WORKER_SCRIPTS_FILE_NAME}`,PageLoaderWorkerScript))}function _createLiveDocumentForFrame(doc){doc._ensureMasterEditor(),(_liveDocument=_createLiveDocument(doc,doc._masterEditor))&&(_server.add(_liveDocument),_updateVirtualServerScripts())}function _launch(url,fullPath){exports.trigger(EVENT_OPEN_PREVIEW_URL,{url:url,fullPath:fullPath})}function _open(doc){doc&&_liveDocument&&doc===_liveDocument.doc&&(_server?(exports.status=1){const url=new URL(msg.url),urlString=`${url.origin}${url.pathname}`;_liveDocument&&urlString===_resolveUrl(_liveDocument.doc.file.fullPath)&&_setStatus(STATUS_ACTIVE)}Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW,"connect",`${_protocol.getConnectionIds().length}-preview`)}).on("ConnectionClose.livedev",function(event,{clientId:clientId}){exports.trigger(EVENT_CONNECTION_CLOSE,{clientId:clientId}),window.logger.livePreview.log("Live Preview: Phoenix received ConnectionClose, live preview left: ",_protocol.getConnectionIds().length,clientId)}).on("DocumentRelated.livedev",function(event,msg){var relatedDocs=msg.related,docs;Object.keys(relatedDocs.stylesheets).forEach(function(url){_styleSheetAdded(null,url,relatedDocs.stylesheets[url])})}).on("StylesheetAdded.livedev",function(event,msg){_styleSheetAdded(null,msg.href,msg.roots)}).on("StylesheetRemoved.livedev",function(event,msg){_handleRelatedDocumentDeleted(msg.href)}).on(LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED+".livedev",function(event,msg){exports.trigger(LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED,msg)}).on(LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD+".livedev",function(event,clients){exports.trigger(LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD,clients)})):console.error("LiveDevelopment._open(): No server active"))}function _prepareServer(doc){const deferred=new $.Deferred;let initialServePath=doc&&doc.file.fullPath;initialServePath||(initialServePath=`${ProjectManager.getProjectRoot().fullPath}index.html`);const readyPromise=(_server=LiveDevServerManager.getServer(initialServePath)).readyToServe();return readyPromise?readyPromise.then(deferred.resolve,function(){_showLiveDevServerNotReadyError(),deferred.reject()}):(_showLiveDevServerNotReadyError(),deferred.reject()),deferred.promise()}function _onFileChange(){let doc=DocumentManager.getCurrentDocument();if(!isActive()||!doc||livePreviewUrlPinned)return;let docUrl=_resolveUrl(doc.file.fullPath),isViewable=_server&&_server.canServe(doc.file.fullPath);_liveDocument&&_liveDocument.doc.url!==docUrl&&isViewable&&open()}async function _resolveLivePreviewDocument(){let activeDocument=DocumentManager.getCurrentDocument(),fileExists;return livePreviewUrlPinned?jsPromise(DocumentManager.getDocumentForPath(currentPreviewFilePath)):activeDocument&&"html"===activeDocument.getLanguage().getId()?(_lastPreviewedHTMLFilePath=activeDocument.file.fullPath,activeDocument):await FileSystem.existsAsync(_lastPreviewedHTMLFilePath)?jsPromise(DocumentManager.getDocumentForPath(_lastPreviewedHTMLFilePath)):activeDocument}async function open(){let doc=await _resolveLivePreviewDocument();_prepareServer(doc).done(function(){_server&&(_setStatus(STATUS_CONNECTING),_closeDocuments(),doc&&_createLiveDocumentForFrame(doc),_server.isActive()?doc&&_open(doc):_server.start().then(()=>{doc&&_open(doc)}))}).fail(function(){console.log("Live preview: no document to preview.")})}function _onDocumentSaved(event,doc){if(isActive()&&_server&&_liveDocument){var absolutePath=doc.file.fullPath,liveDocument=absolutePath&&_server.get(absolutePath),liveEditingEnabled;liveDocument&&liveDocument.isLiveEditingEnabled&&liveDocument.isLiveEditingEnabled()||_liveDocument.isRelated&&_liveDocument.isRelated(absolutePath)&&"javascript"===doc.getLanguage().getId()&&(_setStatus(STATUS_RELOADING),_protocol.reload())}}function _onDirtyFlagChange(event,doc){if(isActive()&&_server&&_liveDocument&&_liveDocument.isRelated){var absolutePath=doc.file.fullPath;_liveDocument.isRelated&&_liveDocument.isRelated(absolutePath)&&_setStatus(_docIsOutOfSync(doc)?STATUS_OUT_OF_SYNC:STATUS_ACTIVE)}}function setTransport(transport){_protocol.setTransport(transport)}function init(config){_config=config,MainViewManager.on("currentFileChange",_onFileChange),DocumentManager.on("documentSaved",_onDocumentSaved).on("dirtyFlagChange",_onDirtyFlagChange),setTransport(LivePreviewTransport),_setStatus(STATUS_INACTIVE)}function getLiveDocForEditor(editor){return editor?getLiveDocForPath(editor.document.file.fullPath):null}function showHighlight(){var doc=getLiveDocForEditor(EditorManager.getActiveEditor());doc&&doc.updateHighlight&&doc.updateHighlight()}function hideHighlight(){_protocol&&_protocol.evaluate("_LD.hideHighlight()")}function redrawHighlight(){_protocol&&_protocol.evaluate("_LD.redrawHighlights()")}function clearHoverState(){_protocol&&_protocol.evaluate("_LD.clearHoverState && _LD.clearHoverState()")}function updateConfig(config){const previousConfig=_config;_config=config,_updateVirtualServerScripts(),refreshConfig();const modeChanged=!previousConfig||previousConfig.mode!==config.mode,oldHighlights=previousConfig&&previousConfig.elemHighlights?previousConfig.elemHighlights.toLowerCase():"hover",newHighlights=config.elemHighlights?config.elemHighlights.toLowerCase():"hover";if(modeChanged||oldHighlights!==newHighlights){const doc=getLiveDocForEditor(EditorManager.getActiveEditor());doc&&(doc._lastHighlight=null)}}function refreshConfig(){_protocol&&_protocol.evaluate("_LD.updateConfig("+JSON.stringify(_config)+")")}function _handleLivePreviewEscapeKey(event){const currLiveDoc=getCurrentLiveDoc();return currLiveDoc&&currLiveDoc.protocol&&currLiveDoc.protocol.evaluate&&currLiveDoc.protocol.evaluate("_LD.escapeKeyPressInEditor()"),!1}function getConfig(){return JSON.parse(JSON.stringify(_config||{}))}function reconnect(){return $.Deferred().resolve()}function reload(){_protocol&&_protocol.reload()}function setLivePreviewPinned(urlPinned,currentPinnedFilePath){livePreviewUrlPinned=urlPinned,currentPreviewFilePath=currentPinnedFilePath}function getCurrentLiveDoc(){return _liveDocument}function getConnectionIds(){return _protocol.getConnectionIds()}function getLivePreviewDetails(){return{liveDocument:_liveDocument,URL:_liveDocument?_resolveUrl(_liveDocument.doc.file.fullPath):null}}ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN,()=>{_lastPreviewedHTMLFilePath=null}),WorkspaceManager.addEscapeKeyEventHandler("livePreview",_handleLivePreviewEscapeKey),EventDispatcher.makeEventDispatcher(exports),exports._server=_server,exports.EVENT_OPEN_PREVIEW_URL=EVENT_OPEN_PREVIEW_URL,exports.EVENT_CONNECTION_CLOSE=EVENT_CONNECTION_CLOSE,exports.EVENT_STATUS_CHANGE=EVENT_STATUS_CHANGE,exports.EVENT_LIVE_PREVIEW_CLICKED=LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED,exports.EVENT_LIVE_PREVIEW_RELOAD=LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD,exports.open=open,exports.close=close,exports.reconnect=reconnect,exports.reload=reload,exports.getLiveDocForPath=getLiveDocForPath,exports.showHighlight=showHighlight,exports.hideHighlight=hideHighlight,exports.redrawHighlight=redrawHighlight,exports.clearHoverState=clearHoverState,exports.getConfig=getConfig,exports.updateConfig=updateConfig,exports.refreshConfig=refreshConfig,exports.init=init,exports.isActive=isActive,exports.setLivePreviewPinned=setLivePreviewPinned,exports.getCurrentLiveDoc=getCurrentLiveDoc,exports.getLivePreviewDetails=getLivePreviewDetails,exports.getConnectionIds=getConnectionIds,exports.setTransport=setTransport}),define("LiveDevelopment/LiveDevServerManager",function(require,exports,module){const ProjectManager=require("project/ProjectManager");let _serverProviders=[];function _providerSort(a,b){return b.priority-a.priority}function getServer(localPath){let provider,server,i,highestPriorityServer;for(i=0;i<_serverProviders.length;i++)if((provider=_serverProviders[i])._createdServer&&provider._createdServer.getProjectRoot()===ProjectManager.getProjectRoot().fullPath||(provider._createdServer=provider.create()),server=provider._createdServer,highestPriorityServer||(highestPriorityServer=server),server.canServe(localPath))return server;return highestPriorityServer}function registerServer(provider,priority){if(provider.create){var providerObj={};return providerObj.create=provider.create,providerObj.priority=priority||0,_serverProviders.push(providerObj),_serverProviders.sort(_providerSort),providerObj}console.error("Incompatible live development server provider")}function removeServer(provider){var i;for(i=0;i<_serverProviders.length;i++)provider===_serverProviders[i]&&_serverProviders.splice(i,1)}exports.getProvider=getServer,exports.registerProvider=registerServer,exports.getServer=getServer,exports.registerServer=registerServer,exports.removeServer=removeServer}),define("LiveDevelopment/LiveDevelopmentUtils",function(require,exports,module){var LanguageManager=require("language/LanguageManager");const _staticHtmlFileExts=["htm","html","xhtml"];function isStaticHtmlFileExt(filePath){return!!filePath&&-1!==_staticHtmlFileExts.indexOf(LanguageManager.getLanguageForPath(filePath).getId())}function isHtmlFileExt(ext){return isStaticHtmlFileExt(ext)}exports.isHtmlFileExt=isHtmlFileExt,exports.isStaticHtmlFileExt=isStaticHtmlFileExt}),define("LiveDevelopment/LivePreviewConstants",function main(require,exports,module){exports.LIVE_PREVIEW_MODE="preview",exports.LIVE_HIGHLIGHT_MODE="highlight",exports.LIVE_EDIT_MODE="edit",exports.PREFERENCE_LIVE_PREVIEW_MODE="livePreviewMode",exports.PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT="livePreviewInspectElement",exports.HIGHLIGHT_HOVER="hover",exports.HIGHLIGHT_CLICK="click",exports.PREFERENCE_SHOW_RULER_LINES="livePreviewShowMeasurements",exports.PREFERENCE_SHOW_STYLES_BAR="livePreviewShowStylesBar",exports.PREFERENCE_SHOW_STARTER_BAR="livePreviewShowStarterBar",exports.PREFERENCE_STYLES_BAR_POSITION="livePreviewStylesBarPosition"}),define("LiveDevelopment/MultiBrowserImpl/documents/LiveCSSDocument",function LiveCSSDocumentModule(require,exports,module){var _=require("thirdparty/lodash"),CSSUtils=require("language/CSSUtils"),EventDispatcher=require("utils/EventDispatcher"),LiveDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveDocument"),PathUtils=require("thirdparty/path-utils/path-utils"),LiveCSSDocument=function LiveCSSDocument(protocol,urlResolver,doc,editor,roots){LiveDocument.apply(this,arguments),this.doc.addRef(),this.onChange=this.onChange.bind(this),this.onDeleted=this.onDeleted.bind(this),this.doc.on("change.LiveCSSDocument",this.onChange),this.doc.on("deleted.LiveCSSDocument",this.onDeleted),editor&&this._attachToEditor(editor)};(LiveCSSDocument.prototype=Object.create(LiveDocument.prototype)).constructor=LiveCSSDocument,LiveCSSDocument.prototype.parentClass=LiveDocument.prototype,EventDispatcher.makeEventDispatcher(LiveCSSDocument.prototype),LiveCSSDocument.prototype.close=function(){this.doc.off(".LiveCSSDocument"),this.doc.releaseRef(),this.parentClass.close.call(this)},LiveCSSDocument.prototype._updateBrowser=function(){var i,docUrl=this.doc.url;function makeUrlsRelativeToCss(match,quotationMark,url){var absUrl;return PathUtils.isRelativeUrl(url)?"url("+quotationMark+PathUtils.makeUrlAbsolute(url,docUrl)+quotationMark+")":match}for(i=0;i>>0}function LiveDocument(protocol,urlResolver,doc,editor,roots){this.protocol=protocol,this.urlResolver=urlResolver,this.doc=doc,this.roots=roots||[],this._onActiveEditorChange=this._onActiveEditorChange.bind(this),this._onCursorActivity=this._onCursorActivity.bind(this),this.fileHashForEvents=_simpleHash(this.doc.file.fullPath),EditorManager.off(`activeEditorChange.LiveDocument-${this.fileHashForEvents}`),EditorManager.on(`activeEditorChange.LiveDocument-${this.fileHashForEvents}`,this._onActiveEditorChange),editor&&this._attachToEditor(editor)}EventDispatcher.makeEventDispatcher(LiveDocument.prototype),LiveDocument.prototype.close=function(){EditorManager.off(`activeEditorChange.LiveDocument-${this.fileHashForEvents}`),this._clearErrorDisplay(),this._detachFromEditor()},LiveDocument.prototype.isLiveEditingEnabled=function(){return!1},LiveDocument.prototype.setInstrumentationEnabled=function(enabled){},LiveDocument.prototype.getResponseData=function(enabled){return{body:this.doc.getText()}},LiveDocument.prototype._onActiveEditorChange=function(event,newActive,oldActive){this._detachFromEditor(),newActive&&newActive.document.file.fullPath===this.doc.file.fullPath&&this._attachToEditor(newActive)},LiveDocument.prototype._attachToEditor=function(editor){this.editor=editor,this.editor&&(this.setInstrumentationEnabled(!0,!0),this.editor.off("cursorActivity",this._onCursorActivity),this.editor.on("cursorActivity",this._onCursorActivity),this.updateHighlight())},LiveDocument.prototype._detachFromEditor=function(){this.editor&&(this._cancelPendingHighlight(),this.hideHighlight(),this.editor.off("cursorActivity",this._onCursorActivity))};let _disableHighlightOnCursor=!1,_cursorHighlightGeneration=0;LiveDocument.prototype.disableHighlightOnCursorActivity=function(shouldDisable){_disableHighlightOnCursor=shouldDisable,shouldDisable&&(_cursorHighlightGeneration++,this._cancelPendingHighlight())},LiveDocument.prototype.isCursorHighlightDisabled=function(){return _disableHighlightOnCursor},LiveDocument.prototype._onCursorActivity=function(event,editor){if(this._cancelPendingHighlight(),!this.editor||_disableHighlightOnCursor)return;const self=this,generation=_cursorHighlightGeneration;this._highlightTimer=window.setTimeout(function(){self._highlightTimer=null,self.editor&&!_disableHighlightOnCursor&&generation===_cursorHighlightGeneration&&self.updateHighlight()},80)},LiveDocument.prototype._cancelPendingHighlight=function(){this._highlightTimer&&(window.clearTimeout(this._highlightTimer),this._highlightTimer=null)},LiveDocument.prototype._updateErrorDisplay=function(){var self=this,startLine,endLine,i,lineHandle;this.editor&&(this.editor._codeMirror.operation(function(){self._clearErrorDisplay(),self._errorLineHandles=self._errorLineHandles||[],self.errors.forEach(function(error){for(startLine=error.startPos.line,endLine=error.endPos.line,i=startLine;i1&&changedLineCount===change[0].removed.length&&_isSamePos(change[0].from,0,0)?(this.protocol.reload(),PerfUtils.addMeasurement(perfTimerName)):(applyEditsPromise=this.protocol.evaluate("_LD.applyDOMEdits("+JSON.stringify(result.edits)+")")).always(function(){isNestedTimer||PerfUtils.addMeasurement(perfTimerName)})}this.errors=result.errors||[],this._updateErrorDisplay(),this._debug&&(console.log("Edits applied to browser were:"),console.log(JSON.stringify(result.edits,null,2)),applyEditsPromise.done(function(){self._compareWithBrowser(change)}))}},LiveHTMLDocument.prototype._onRelated=function(event,msg){this._relatedDocuments=msg.related},LiveHTMLDocument.prototype._onStylesheetAdded=function(event,msg){this._relatedDocuments.stylesheets[msg.href]=!0},LiveHTMLDocument.prototype._onStylesheetRemoved=function(event,msg){delete this._relatedDocuments.stylesheets[msg.href]},LiveHTMLDocument.prototype._onScriptAdded=function(event,msg){this._relatedDocuments.scripts[msg.src]=!0},LiveHTMLDocument.prototype._onScriptRemoved=function(event,msg){delete this._relatedDocuments.scripts[msg.src]},LiveHTMLDocument.prototype.isRelated=function(fullPath){return this._relatedDocuments.scripts[this.urlResolver(fullPath)]||this._relatedDocuments.stylesheets[this.urlResolver(fullPath)]},LiveHTMLDocument.prototype.getRelated=function(){return this._relatedDocuments},module.exports=LiveHTMLDocument}),define("LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation",function(require,exports,module){var DocumentManager=require("document/DocumentManager"),HTMLDOMDiff=require("language/HTMLDOMDiff"),HTMLSimpleDOM=require("LiveDevelopment/MultiBrowserImpl/language/HTMLSimpleDOM"),_=require("thirdparty/lodash"),allowIncremental=!0,_cachedValues={};function _removeDocFromCache(evt,document){_cachedValues.hasOwnProperty(document.file.fullPath)&&(delete _cachedValues[document.file.fullPath],document.off(".htmlInstrumentation"))}function _posEq(pos1,pos2){return pos1&&pos2&&pos1.line===pos2.line&&pos1.ch===pos2.ch}function _getSortedTagMarks(marks,markCache){return(marks=marks.filter(function(mark){return!!mark.tagID}).map(function(mark){return markCache[mark.tagID]||(markCache[mark.tagID]={mark:mark,range:mark.find()}),markCache[mark.tagID]})).sort(function(mark1,mark2){return mark1.range.from.line===mark2.range.from.line?mark1.range.from.ch-mark2.range.from.ch:mark1.range.from.line-mark2.range.from.line}),marks}function _getMarkerAtDocumentPos(editor,pos,preferParent,markCache){var marks,match;return markCache=markCache||{},(marks=_getSortedTagMarks(editor._codeMirror.findMarksAt(pos),markCache)).length?(match=marks[marks.length-1],preferParent&&(_posEq(match.range.from,pos)||_posEq(match.range.to,pos))&&(match=marks.length>1?marks[marks.length-2]:null),match.mark):null}function _getTagIDAtDocumentPos(editor,pos,markCache){var match=_getMarkerAtDocumentPos(editor,pos,!1,markCache);return match?match.tagID:-1}function _markTags(cm,node){var mark;node.children.forEach(function(childNode){childNode.isElement()&&_markTags(cm,childNode)}),cm.markText(node.startPos,node.endPos).tagID=node.tagID}function _markTextFromDOM(editor,dom){var cm=editor._codeMirror,marks=cm.getAllMarks();cm.operation(function(){marks.forEach(function(mark){mark.hasOwnProperty("tagID")&&mark.clear()})}),_markTags(cm,dom)}function DOMUpdater(previousDOM,editor,changeList){var text,startOffset=0,startOffsetPos;function isDangerousEdit(text){return/[<>\/=\"\']/.test(text)}if(this.isIncremental=!1,changeList&&1===changeList.length){var change=changeList[0];if(!isDangerousEdit(change.text)&&!isDangerousEdit(change.removed)){var startMark=_getMarkerAtDocumentPos(editor,change.from,!0);if(startMark){var range=startMark.find();range&&(text=editor._codeMirror.getRange(range.from,range.to),this.changedTagID=startMark.tagID,startOffsetPos=range.from,startOffset=editor._codeMirror.indexFromPos(startOffsetPos),this.isIncremental=!0)}}}this.changedTagID||(text=editor.document.getText()),HTMLSimpleDOM.Builder.call(this,text,startOffset,startOffsetPos),this.editor=editor,this.cm=editor._codeMirror,this.previousDOM=previousDOM}function _hasAncestorWithID(node,id){for(var ancestor=node.parent;ancestor&&ancestor.tagID!==id;)ancestor=ancestor.parent;return!!ancestor}function _updateDOM(previousDOM,editor,changeList){allowIncremental||(changeList=void 0);var updater=new DOMUpdater(previousDOM,editor,changeList),result=updater.update();if(!result)return{errors:updater.errors};var edits=HTMLDOMDiff.domdiff(result.oldSubtree,result.newSubtree);return result.newSubtree!==result.newDOM&&delete result.newSubtree.nodeMap,{dom:result.newDOM,edits:edits,_wasIncremental:updater.isIncremental}}function getUnappliedEditList(editor,changeList){const cachedValue=_cachedValues[editor.document.file.fullPath];cachedValue&&cachedValue.dom&&!cachedValue.invalid||(changeList=null);var result=_updateDOM(cachedValue&&cachedValue.dom,editor,changeList);return result.errors?(cachedValue&&(cachedValue.invalid=!0),{errors:result.errors}):(_cachedValues[editor.document.file.fullPath]={timestamp:editor.document.diskTimestamp,dom:result.dom,dirty:!1},result.dom.fullBuild=!1,{edits:result.edits})}function _processBrowserSimpleDOM(browserRoot,editorRootTagID){var nodeMap={},root;function _processElement(elem){elem.tagID=elem.attributes["data-brackets-id"],delete elem.attributes["data-brackets-id"],elem.children.forEach(function(child){child.parent=elem,child.isElement()?_processElement(child):child.isText()&&(child.update(),child.tagID=HTMLSimpleDOM.getTextNodeID(child),nodeMap[child.tagID]=child)}),elem.update(),nodeMap[elem.tagID]=elem,elem.tagID===editorRootTagID&&(root=elem)}return _processElement(browserRoot),(root=root||browserRoot).nodeMap=nodeMap,root}function _getBrowserDiff(editor,browserSimpleDOM){var cachedValue,editorRoot=_cachedValues[editor.document.file.fullPath].dom,browserRoot;return browserRoot=_processBrowserSimpleDOM(browserSimpleDOM,editorRoot.tagID),{diff:HTMLDOMDiff.domdiff(editorRoot,browserRoot),browser:browserRoot,editor:editorRoot}}function scanDocument(doc){_cachedValues.hasOwnProperty(doc.file.fullPath)||(_cachedValues[doc.file.fullPath]=null);var cachedValue=_cachedValues[doc.file.fullPath];if(cachedValue&&!cachedValue.invalid&&cachedValue.timestamp===doc.diskTimestamp)return cachedValue.dom;var text=doc.getText(),dom=HTMLSimpleDOM.build(text);return dom&&(_cachedValues[doc.file.fullPath]={timestamp:doc.diskTimestamp,dom:dom,dirty:!1},dom.fullBuild=!0),dom}function generateInstrumentedHTML(editor,remoteScript){var doc=editor.document,dom=scanDocument(doc),orig=doc.getText(),gen="",lastIndex=0,remoteScriptInserted=!1,markCache;if(!dom)return null;function walk(node){if(node.tag){var attrText=" data-brackets-id='"+node.tagID+"'",startOffset;if(dom.fullBuild)startOffset=node.start;else{var mark=markCache[node.tagID];mark?startOffset=editor._codeMirror.indexFromPos(mark.range.from):(console.warn("generateInstrumentedHTML(): couldn't find existing mark for tagID "+node.tagID),startOffset=node.start)}var insertIndex=startOffset+node.tag.length+1;gen+=orig.substr(lastIndex,insertIndex-lastIndex)+attrText,lastIndex=insertIndex,remoteScript&&!remoteScriptInserted&&"head"===node.tag&&(insertIndex=node.openEnd,gen+=orig.substr(lastIndex,insertIndex-lastIndex)+remoteScript,lastIndex=insertIndex,remoteScriptInserted=!0)}node.isElement()&&node.children.forEach(walk)}return dom.fullBuild?_markTextFromDOM(editor,dom):(markCache={},editor._codeMirror.getAllMarks().forEach(function(mark){mark.tagID&&(markCache[mark.tagID]={mark:mark,range:mark.find()})}),0===Object.keys(markCache).length&&dom.nodeMap&&Object.keys(dom.nodeMap).length>0&&(console.warn("generateInstrumentedHTML: No marks found, forcing re-mark"),_markTextFromDOM(editor,dom),markCache={},editor._codeMirror.getAllMarks().forEach(function(mark){mark.tagID&&(markCache[mark.tagID]={mark:mark,range:mark.find()})}))),walk(dom),gen+=orig.substr(lastIndex),remoteScript&&!remoteScriptInserted&&(gen+=remoteScript),gen}function _markText(editor){var cache=_cachedValues[editor.document.file.fullPath],dom=cache&&cache.dom;if(dom){var existingMarks=editor._codeMirror.getAllMarks().filter(function(mark){return mark.hasOwnProperty("tagID")});!dom.fullBuild&&existingMarks.length>0?console.error("Tried to mark text from a stale DOM for "+editor.document.file.fullPath):_markTextFromDOM(editor,dom)}else console.error("Couldn't find the dom for "+editor.document.file.fullPath)}function _resetCache(){_cachedValues={}}function _rebuildTagIdMarkMap(cm){const map=new Map;return cm.getAllMarks().forEach(function(mark){mark.hasOwnProperty("tagID")&&map.set(mark.tagID,mark)}),cm._phTagIdMarks=map,map}function getPositionFromTagId(editor,tagId){const cm=editor._codeMirror;let map=cm._phTagIdMarks||_rebuildTagIdMarkMap(cm),mark=map.get(tagId),range=mark&&mark.find();return range||(range=(mark=(map=_rebuildTagIdMarkMap(cm)).get(tagId))&&mark.find()),range?{from:range.from,to:range.to}:null}DOMUpdater.prototype=Object.create(HTMLSimpleDOM.Builder.prototype),DOMUpdater.prototype.getID=function(newTag,markCache){var currentTagID=_getTagIDAtDocumentPos(this.editor,HTMLSimpleDOM._offsetPos(newTag.startPos,1),markCache);if(-1===currentTagID||_hasAncestorWithID(newTag,currentTagID))currentTagID=this.getNewID();else{var oldNode=this.previousDOM.nodeMap[currentTagID];oldNode&&oldNode.tag===newTag.tag||(currentTagID=this.getNewID())}return currentTagID},DOMUpdater.prototype._updateMarkedRanges=function(nodeMap,markCache){var updateIDs=Object.keys(nodeMap),cm=this.cm,marks=cm.getAllMarks();cm.operation(function(){marks.forEach(function(mark){if(mark.hasOwnProperty("tagID")&&nodeMap[mark.tagID]){var node=nodeMap[mark.tagID],markInfo=markCache[mark.tagID];markInfo&&_posEq(markInfo.range.from,node.startPos)&&_posEq(markInfo.range.to,node.endPos)||(mark.clear(),(mark=cm.markText(node.startPos,node.endPos)).tagID=node.tagID),updateIDs.splice(updateIDs.indexOf(String(node.tagID)),1)}}),updateIDs.forEach(function(id){var node=nodeMap[id],mark;node.isElement()&&((mark=cm.markText(node.startPos,node.endPos)).tagID=Number(id))})})},DOMUpdater.prototype._buildNodeMap=function(root){var nodeMap={};function walk(node){node.tagID&&(nodeMap[node.tagID]=node),node.isElement()&&node.children.forEach(walk)}walk(root),root.nodeMap=nodeMap},DOMUpdater.prototype._handleDeletions=function(nodeMap,oldSubtreeMap,newSubtreeMap){var deletedIDs=[],marks;(Object.keys(oldSubtreeMap).forEach(function(key){newSubtreeMap.hasOwnProperty(key)||(deletedIDs.push(key),delete nodeMap[key])}),deletedIDs.length)&&this.cm.getAllMarks().forEach(function(mark){mark.hasOwnProperty("tagID")&&-1!==deletedIDs.indexOf(mark.tagID)&&mark.clear()})},DOMUpdater.prototype.update=function(){var markCache={},newSubtree=this.build(!0,markCache),result={newDOM:newSubtree,oldSubtree:this.previousDOM,newSubtree:newSubtree};if(!newSubtree)return null;if(this.changedTagID){var oldSubtree=this.previousDOM.nodeMap[this.changedTagID],parent=oldSubtree.parent;if(parent){var childIndex=parent.children.indexOf(oldSubtree);if(-1===childIndex)console.error("DOMUpdater.update(): couldn't locate old subtree in tree");else{oldSubtree.parent=null,newSubtree.parent=parent,parent.children[childIndex]=newSubtree,$.extend(this.previousDOM.nodeMap,newSubtree.nodeMap),this._updateMarkedRanges(newSubtree.nodeMap,markCache),this._buildNodeMap(oldSubtree),this._handleDeletions(this.previousDOM.nodeMap,oldSubtree.nodeMap,newSubtree.nodeMap);for(var curParent=parent;curParent;)curParent.update(),curParent=curParent.parent;result.newDOM=this.previousDOM,result.oldSubtree=oldSubtree}}}else _markTextFromDOM(this.editor,result.newDOM);return result},DocumentManager.on("beforeDocumentDelete",_removeDocFromCache),exports._markText=_markText,exports._getMarkerAtDocumentPos=_getMarkerAtDocumentPos,exports._getTagIDAtDocumentPos=_getTagIDAtDocumentPos,exports._markTextFromDOM=_markTextFromDOM,exports._updateDOM=_updateDOM,exports._allowIncremental=allowIncremental,exports._getBrowserDiff=_getBrowserDiff,exports._resetCache=_resetCache,exports.getPositionFromTagId=getPositionFromTagId,exports.scanDocument=scanDocument,exports.generateInstrumentedHTML=generateInstrumentedHTML,exports.getUnappliedEditList=getUnappliedEditList}),define("LiveDevelopment/MultiBrowserImpl/language/HTMLSimpleDOM",function(require,exports,module){var Tokenizer=require("language/HTMLTokenizer").Tokenizer,MurmurHash3=require("thirdparty/murmurhash3_gc"),PerfUtils=require("utils/PerfUtils"),seed=Math.floor(65535*Math.random()),tagID=1,openImpliesClose={li:{li:!0},dt:{dd:!0,dt:!0},dd:{dd:!0,dt:!0},address:{p:!0},article:{p:!0},aside:{p:!0},blockquote:{p:!0},dir:{p:!0},div:{p:!0},dl:{p:!0},fieldset:{p:!0},footer:{p:!0},form:{p:!0},h1:{p:!0},h2:{p:!0},h3:{p:!0},h4:{p:!0},h5:{p:!0},h6:{p:!0},header:{p:!0},hgroup:{p:!0},hr:{p:!0},main:{p:!0},menu:{p:!0},nav:{p:!0},ol:{p:!0},p:{p:!0},pre:{p:!0},section:{p:!0},table:{p:!0},ul:{p:!0},rt:{rp:!0,rt:!0},rp:{rp:!0,rt:!0},optgroup:{optgroup:!0,option:!0},option:{option:!0},tbody:{thead:!0,tbody:!0,tfoot:!0},tfoot:{tbody:!0},tr:{tr:!0,th:!0,td:!0},th:{th:!0,td:!0},td:{thead:!0,th:!0,td:!0},body:{head:!0,link:!0,script:!0}},voidElements={area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,menuitem:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0};function SimpleNode(properties){$.extend(this,properties)}function getTextNodeID(textNode){var childIndex=textNode.parent.children.indexOf(textNode);return 0===childIndex?textNode.parent.tagID+".0":textNode.parent.children[childIndex-1].tagID+"t"}function _addPos(pos1,pos2){return{line:pos1.line+pos2.line,ch:0===pos2.line?pos1.ch+pos2.ch:pos2.ch}}function _offsetPos(pos,offset){return{line:pos.line,ch:pos.ch+offset}}function Builder(text,startOffset,startOffsetPos){this.stack=[],this.text=text,this.t=new Tokenizer(text),this.currentTag=null,this.startOffset=startOffset||0,this.startOffsetPos=startOffsetPos||{line:0,ch:0}}function build(text,strict){var builder;return new Builder(text).build(strict)}function _dumpDOM(root){var result="",indent="";function walk(node){node.tag?result+=indent+"TAG "+node.tagID+" "+node.tag+" "+JSON.stringify(node.attributes)+"\n":result+=indent+"TEXT "+(node.tagID||"- ")+node.content+"\n",node.isElement()&&(indent+=" ",node.children.forEach(walk),indent=indent.slice(2))}return walk(root),result}SimpleNode.prototype={update:function(){if(this.isElement()){var i,subtreeHashes="",childHashes="",child;for(i=0;i0&&closable.hasOwnProperty(stack[stack.length-1].tag);)closeTag(token.start-1,_offsetPos(token.startPos,-1));(newTag=new SimpleNode({tag:token.contents.toLowerCase(),children:[],attributes:{},parent:stack.length?stack[stack.length-1]:null,start:this.startOffset+token.start-1,startPos:_addPos(this.startOffsetPos,_offsetPos(token.startPos,-1))})).tagID=this.getID(newTag,markCache),nodeMap[newTag.tagID]&&(newTag.tagID=this.getNewID()),nodeMap[newTag.tagID]=newTag,newTag.parent&&newTag.parent.children.push(newTag),this.currentTag=newTag,voidElements.hasOwnProperty(newTag.tag)?newTag.update():stack.push(newTag)}else if("opentagend"===token.type||"selfclosingtag"===token.type)this.currentTag&&("selfclosingtag"===token.type&&stack.length&&stack[stack.length-1]===this.currentTag?closeTag(token.end,token.endPos):(this.currentTag.openEnd=this.currentTag.end=this.startOffset+token.end,this.currentTag.endPos=_addPos(this.startOffsetPos,token.endPos),lastClosedTag=this.currentTag,this.currentTag.updateAttributeSignature(),this.currentTag=null));else if("closetag"===token.type){var closeTagName=token.contents.toLowerCase();if(!voidElements.hasOwnProperty(closeTagName)){var i;for(i=stack.length-1;i>=0&&stack[i].tag!==closeTagName;i--);if(strict&&i!==stack.length-1)return PerfUtils.finalizeMeasurement(timerBuildFull),PerfUtils.addMeasurement(timerBuildPart),this._logError(token),null;if(i>=0)do{stack.length===i+1?closeTag(token.end+1,_offsetPos(token.endPos,1)):closeTag(token.start-2,_offsetPos(token.startPos,-2))}while(stack.length>i);else if(strict)return PerfUtils.finalizeMeasurement(timerBuildFull),PerfUtils.addMeasurement(timerBuildPart),this._logError(token),null}}else if("attribname"===token.type)attributeName=token.contents.toLowerCase(),this.currentTag.attributes[attributeName]="";else if("attribvalue"===token.type&&null!==attributeName)this.currentTag.attributes[attributeName]=token.contents,attributeName=null;else if("text"===token.type&&stack.length){var parent=stack[stack.length-1],newNode;lastTextNode?(newNode=lastTextNode).content+=token.contents:(newNode=new SimpleNode({parent:stack[stack.length-1],content:token.contents}),parent.children.push(newNode),newNode.tagID=getTextNodeID(newNode),nodeMap[newNode.tagID]=newNode,lastTextNode=newNode),newNode.update()}}if(stack.length){if(strict)return PerfUtils.finalizeMeasurement(timerBuildFull),PerfUtils.addMeasurement(timerBuildPart),this._logError(token),null;for(var lines=this.text.split("\n"),lastPos={line:lines.length-1,ch:lines[lines.length-1].length};stack.length;)closeTag(this.text.length,lastPos)}var dom=lastClosedTag;return dom?(dom.nodeMap=nodeMap,PerfUtils.addMeasurement(timerBuildFull),PerfUtils.finalizeMeasurement(timerBuildPart),dom):(this._logError(token),null)},Builder.prototype.getNewID=function(){return tagID++},Builder.prototype.getID=Builder.prototype.getNewID,exports.build=build,exports.Builder=Builder,exports.SimpleNode=SimpleNode,exports._dumpDOM=_dumpDOM,exports._offsetPos=_offsetPos,exports._getTextNodeID=getTextNodeID,exports._seed=seed}),define("LiveDevelopment/MultiBrowserImpl/protocol/LiveDevProtocol",function(require,exports,module){const EventDispatcher=require("utils/EventDispatcher"),CONSTANTS=require("LiveDevelopment/LivePreviewConstants"),LiveDevProtocolRemote=require("text!LiveDevelopment/BrowserScripts/LiveDevProtocolRemote.js"),DocumentObserver=require("text!LiveDevelopment/BrowserScripts/DocumentObserver.js"),LanguageManager=require("language/LanguageManager"),RemoteFunctions=require("text!LiveDevelopment/BrowserScripts/RemoteFunctions.js"),EditorManager=require("editor/EditorManager"),LiveDevMultiBrowser=require("LiveDevelopment/LiveDevMultiBrowser"),PreferencesManager=require("preferences/PreferencesManager"),HTMLInstrumentation=require("LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation"),StringUtils=require("utils/StringUtils"),FileViewController=require("project/FileViewController"),MainViewManager=require("view/MainViewManager"),WorkspaceManager=require("view/WorkspaceManager"),LIVE_DEV_REMOTE_SCRIPTS_FILE_NAME=`phoenix_live_preview_scripts_instrumented_${StringUtils.randomString(8)}.js`,LIVE_DEV_REMOTE_WORKER_SCRIPTS_FILE_NAME=`pageLoaderWorker_${StringUtils.randomString(8)}.js`,EVENT_LIVE_PREVIEW_CLICKED="livePreviewClicked",EVENT_LIVE_PREVIEW_RELOAD="livePreviewReload",MAX_PENDING_LP_CALLS_1000=1e3;var _connections={},_transport=null,_nextMsgId=1;const pendingLpResponses=new Phoenix.libs.LRUCache({max:1e3}),pendingCallsByClient=new Map;function _trackPending(fnCallID,clientId,deferred){pendingLpResponses.set(fnCallID,{deferred:deferred,clientId:clientId});let set=pendingCallsByClient.get(clientId);set||(set=new Set,pendingCallsByClient.set(clientId,set)),set.add(fnCallID)}function _untrackPending(fnCallID){const pendingHandler=pendingLpResponses.get(fnCallID);if(pendingHandler){if(pendingLpResponses.delete(fnCallID),pendingHandler.clientId){const set=pendingCallsByClient.get(pendingHandler.clientId);set&&(set.delete(fnCallID),0===set.size&&pendingCallsByClient.delete(pendingHandler.clientId))}return pendingHandler}}function rejectAllPendingForClient(clientId){const set=pendingCallsByClient.get(clientId);if(!set||0===set.size)return;const callIds=Array.from(set);for(const fnCallID of callIds){const pendingHandler=_untrackPending(fnCallID);pendingHandler&&pendingHandler.deferred.reject(new Error(`Live Preview client disconnected: ${clientId}`))}}let _remoteFunctionProvider=null;function setCustomRemoteFunctionProvider(callbackFn){_remoteFunctionProvider=callbackFn}function getConnectionIds(){return Object.keys(_connections)}function _forwardKeyboardShortcutFromIframe(data){const event=new KeyboardEvent("keydown",{key:data.key,code:data.code,ctrlKey:!!data.ctrlKey,metaKey:!!data.metaKey,shiftKey:!!data.shiftKey,altKey:!!data.altKey,bubbles:!0,cancelable:!0});document.body.dispatchEvent(event)}const KEEP_FOCUS_WINDOW_MS=1500;let _keepFocusUntil=0;function keepFocusOnNextSelect(){_keepFocusUntil=Date.now()+KEEP_FOCUS_WINDOW_MS}function _shouldKeepFocus(){return Date.now()<_keepFocusUntil}function _focusEditorIfNeeded(editor,tagName,contentEditable){if(WorkspaceManager.isInDesignMode()||_shouldKeepFocus())return;const focusShouldBeInLivePreview=["INPUT","TEXTAREA"].includes(tagName)||contentEditable;focusShouldBeInLivePreview||editor.focus()}const cssLangIDS=["css","scss","sass","less"],lessLangIDS=["scss","sass","less"];function _isLessOrSCSS(editor){if(!editor)return!1;const language=LanguageManager.getLanguageForPath(editor.document.file.fullPath);return language&&lessLangIDS.includes(language.getId())}function _searchAndCursorIfCSS(editor,allSelectors,nodeName){const codeMirror=editor._codeMirror,language=LanguageManager.getLanguageForPath(editor.document.file.fullPath);if(!language||!cssLangIDS.includes(language.getId()))return;if(allSelectors&&allSelectors.length)for(let selector of allSelectors){const cursor=codeMirror.getSearchCursor(selector),found=cursor.findNext();if(found)return void editor.setCursorPos(cursor.from().line,cursor.from().ch,!0)}const htmlTagSearch=new RegExp(nodeName,"i"),cursor=codeMirror.getSearchCursor(htmlTagSearch),found=cursor.findNext();found&&editor.setCursorPos(cursor.from().line,cursor.from().ch,!0)}function _tagSelectedInLivePreview(tagId,nodeName,contentEditable,allSelectors){const livePreviewMode=PreferencesManager.get(CONSTANTS.PREFERENCE_LIVE_PREVIEW_MODE);if(livePreviewMode===CONSTANTS.LIVE_PREVIEW_MODE)return;const liveDoc=LiveDevMultiBrowser.getCurrentLiveDoc(),activeEditor=EditorManager.getActiveEditor(),activeFullEditor=EditorManager.getCurrentFullEditor(),liveDocPath=liveDoc?liveDoc.doc.file.fullPath:null,activeEditorPath=activeEditor?activeEditor.document.file.fullPath:null,activeFullEditorPath=activeFullEditor?activeFullEditor.document.file.fullPath:null;if(!liveDocPath)return void(!activeEditor||WorkspaceManager.isInDesignMode()||_shouldKeepFocus()||activeEditor.focus());if(!tagId)return void(activeEditor&&(liveDoc.isRelated(activeEditorPath)||_isLessOrSCSS(activeEditor))&&_searchAndCursorIfCSS(activeEditor,allSelectors,nodeName));const allOpenFileCount=MainViewManager.getWorkingSetSize(MainViewManager.ALL_PANES);function selectInHTMLEditor(fullHtmlEditor){const positionResult=HTMLInstrumentation.getPositionFromTagId(fullHtmlEditor,parseInt(tagId,10));if(positionResult&&positionResult.from&&fullHtmlEditor){const position=positionResult.from,masterEditor=fullHtmlEditor.document._masterEditor||fullHtmlEditor;masterEditor.setCursorPos(position.line,position.ch,!0),_focusEditorIfNeeded(masterEditor,nodeName,contentEditable)}}liveDocPath===activeFullEditorPath?selectInHTMLEditor(activeFullEditor):liveDoc.isRelated(activeEditorPath)||_isLessOrSCSS(activeEditor)?(_focusEditorIfNeeded(activeEditor,nodeName,contentEditable),_searchAndCursorIfCSS(activeEditor,allSelectors,nodeName)):allOpenFileCount||FileViewController.openAndSelectDocument(liveDocPath,FileViewController.WORKING_SET_VIEW,MainViewManager.ACTIVE_PANE).done(()=>{selectInHTMLEditor(EditorManager.getActiveEditor())})}const processedMessageIDs=new Phoenix.libs.LRUCache({max:1e3});let _livePreviewMessageHandler;function setLivePreviewMessageHandler(handler){_livePreviewMessageHandler=handler}function _receive(clientId,msgStr,messageID){const msg=JSON.parse(msgStr),event=msg.method||"event";if(!messageID||!processedMessageIDs.has(messageID))if(messageID&&processedMessageIDs.set(messageID,!0),msg&&"object"==typeof msg&&msg.execFnName)_executePhoenixFn(msg.execFnName,msg.paramObj,msg.fnExecID,clientId);else{if(_livePreviewMessageHandler){let preventDefault;if(_livePreviewMessageHandler(msg))return}if(msg.requestConfigRefresh)LiveDevMultiBrowser.refreshConfig();else if(msg.id){const pendingHandler=_untrackPending(msg.id);pendingHandler&&(msg.error?pendingHandler.deferred.reject(msg):pendingHandler.deferred.resolve(msg))}else if(msg.keyForward)_forwardKeyboardShortcutFromIframe(msg);else if(msg.clicked&&(msg.tagId||msg.sourceless)){const livePreviewMode=PreferencesManager.get(CONSTANTS.PREFERENCE_LIVE_PREVIEW_MODE),editMode=livePreviewMode===CONSTANTS.LIVE_EDIT_MODE,liveDoc=LiveDevMultiBrowser.getCurrentLiveDoc();editMode&&liveDoc&&liveDoc.disableHighlightOnCursorActivity(!0);try{_tagSelectedInLivePreview(msg.tagId,msg.nodeName,msg.contentEditable,msg.allSelectors),exports.trigger(EVENT_LIVE_PREVIEW_CLICKED,msg)}catch(e){console.error("error in tag selection",e)}_keepFocusUntil=0,editMode&&liveDoc&&liveDoc.disableHighlightOnCursorActivity(!1),liveDoc&&!msg.sourceless&&liveDoc.updateHighlight()}else msg.clientId=clientId,exports.trigger(event,msg)}}function _send(msg,clients){var id=_nextMsgId++,result=new $.Deferred;if(!_transport)return console.error("Cannot send message before live preview transport initialised"),result.reject(),result.promise();if(clients=clients||getConnectionIds(),msg.id=id,Array.isArray(clients)||(clients=[clients]),0===clients.length)return result.reject(new Error("No live preview clients connected")),result.promise();const clientId=clients[0];return _trackPending(id,clientId,result),_transport.send(clients,JSON.stringify(msg)),result.promise()}function _connect(clientId,url){_connections[clientId]=!0,exports.trigger("ConnectionConnect",{clientId:clientId,url:url}),triggerLPFn("PH_LP_COMM_READY","",clientId)}function _close(clientId){_connections[clientId]&&(rejectAllPendingForClient(clientId),delete _connections[clientId],exports.trigger("ConnectionClose",{clientId:clientId}))}function setTransport(transport){_transport&&_transport.off(".livedev"),(_transport=transport).on("connect.livedev",function(event,msg){_connect(msg[0],msg[1])}).on("message.livedev",function(event,msg){_receive(msg[0],msg[1],msg[2])}).on("close.livedev",function(event,msg){_close(msg[0])}),_transport.start()}function _getRemoteFunctionsScript(){let script="";return script+=DocumentObserver,"\n"+(script+=_remoteFunctionProvider?_remoteFunctionProvider():"\nwindow._LD=("+RemoteFunctions+"("+JSON.stringify(LiveDevMultiBrowser.getConfig())+"))")+"\n"}function getRemoteScriptContents(){const transportScript=_transport.getRemoteScript()||"",remoteFunctionsScript=_getRemoteFunctionsScript()||"";return transportScript+"\n"+LiveDevProtocolRemote+"\n"+remoteFunctionsScript}function getRemoteScript(){return`\n\t\t