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("languageTools/LSPInstallSupport"),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");function handleLinkClick(e){if(2===e.button||"mac"===brackets.platform&&e.ctrlKey)return;const path=e.composedPath?e.composedPath():[];let node=path[0]||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}}$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 eventPath=e.originalEvent&&e.originalEvent.composedPath?e.originalEvent.composedPath():[],$target=$(eventPath[0]||e.target),isFormElement=$target.is("input")||$target.is("textarea")||$target.is("select");isFormElement||e.preventDefault()}),window.document.body.addEventListener("click",handleLinkClick,!0),window.document.body.addEventListener("auxclick",handleLinkClick,!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){const previousRequest=deferredPreferences,request=$.Deferred();deferredPreferences=request,previousRequest&&"pending"===previousRequest.state()&&previousRequest.reject();const pr=ProjectManager.getProjectRoot();if(pr)projectRootPath=pr.fullPath;else if(!projectRootPath)return console.log("initPreferences: projectRootPath has no value. Using Defaults."),preferences=new Preferences,void request.resolve();var path=projectRootPath+Preferences.FILE_NAME;preferences=new Preferences,FileSystem.resolve(path,function(err,file){deferredPreferences===request&&(err?request.resolve():FileUtils.readAsText(file).done(function(text){if(deferredPreferences===request){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),request.resolve()}}).fail(function(error){deferredPreferences===request&&(preferences=new Preferences,request.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 filterTernFileText(path,text){const languageId=LanguageManager.getLanguageForPath(path).getId();return"html"===languageId||"php"===languageId?"":filterText(text)}function getTextFromDocument(document){return filterTernFileText(document.file.fullPath,document.getText())}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){const languageId=LanguageManager.getLanguageForPath(session.editor.document.file.fullPath).getId();var start=session.getCursor(),end=start,document=session.editor.document,path=document.file.fullPath,result;return result="html"===languageId||"php"===languageId?{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,filterTernFileText(filePath,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):(ternPromise&&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)})})})})}).fail(function(){addFilesDeferred.resolveWith(null)}))}function handleEditorChange(session,document,previousDocument){addFilesPromise&&"pending"===addFilesPromise.state()?addFilesPromise.done(function(){handleEditorChange(session,document,previousDocument)}):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(){const languageId=LanguageManager.getLanguageForPath(this.editor.document.file.fullPath).getId();if("html"===languageId||"php"===languageId){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_ASK_AI="livePreviewShowAskAI",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,_selectionHolder=null;function _isSelectionHeld(liveDoc){return!!_selectionHolder&&!0===_selectionHolder(liveDoc)}LiveDocument.setSelectionHolder=function(holder){_selectionHolder=holder||null},LiveDocument.CURSOR_HIGHLIGHT_DEBOUNCE_MS=80,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;i{this._lastHighlight===highlight&&(this._lastHighlight=null)}))},LiveDocument.prototype.highlightDomElement=function(ids){var selector="";Array.isArray(ids)||(ids=[ids]),_.each(ids,function(id){""!==selector&&(selector+=","),selector+="[data-brackets-id='"+id+"']"}),this.highlightRule(selector)},LiveDocument.prototype.redrawHighlights=function(){this.isHighlightEnabled()&&this.protocol.evaluate("_LD.redrawHighlights()")},module.exports=LiveDocument}),define("LiveDevelopment/MultiBrowserImpl/documents/LiveHTMLDocument",function(require,exports,module){var EventDispatcher=require("utils/EventDispatcher"),PerfUtils=require("utils/PerfUtils"),_=require("thirdparty/lodash"),LiveDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveDocument"),HTMLInstrumentation=require("LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation"),HTMLUtils=require("language/HTMLUtils"),CSSUtils=require("language/CSSUtils");function LiveHTMLDocument(protocol,urlResolver,doc,editor){LiveDocument.apply(this,arguments),this.doc.addRef(),this._instrumentationEnabled=!1,this._relatedDocuments={stylesheets:{},scripts:{}},this._onChange=this._onChange.bind(this),this.doc.on("change",this._onChange),this._onDeleted=this._onDeleted.bind(this),this.doc.on("deleted",this._onDeleted),this._onRelated=this._onRelated.bind(this),this.protocol.on("DocumentRelated",this._onRelated),this._onStylesheetAdded=this._onStylesheetAdded.bind(this),this.protocol.on("StylesheetAdded",this._onStylesheetAdded),this._onStylesheetRemoved=this._onStylesheetRemoved.bind(this),this.protocol.on("StylesheetRemoved",this._onStylesheetRemoved),this._onScriptAdded=this._onScriptAdded.bind(this),this.protocol.on("ScriptAdded",this._onScriptAdded),this._onScriptRemoved=this._onScriptRemoved.bind(this),this.protocol.on("ScriptRemoved",this._onScriptRemoved)}function _injectIntoUnfinishedHTML(html,remoteScript){const preamble=/^(?:\uFEFF|[\t\n\f\r ]|