const allDescriptors=[];let applicationDescriptor;const _loadedScripts={};for(const k of[]){}
(function(){const baseUrl=self.location?self.location.origin+self.location.pathname:'';self._importScriptPathPrefix=baseUrl.substring(0,baseUrl.lastIndexOf('/')+1);})();var Runtime=class{constructor(descriptors){this._modules=[];this._modulesMap={};this._extensions=[];this._cachedTypeClasses={};this._descriptorsMap={};for(let i=0;i<descriptors.length;++i)
this._registerModule(descriptors[i]);Runtime._runtimeReadyPromiseCallback();}
static loadResourcePromise(url){return new Promise(load);function load(fulfill,reject){const xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=onreadystatechange;function onreadystatechange(e){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if([0,200,304].indexOf(xhr.status)===-1)
reject(new Error('While loading from url '+url+' server responded with a status of '+xhr.status));else
fulfill(e.target.response);}
xhr.send(null);}}
static normalizePath(path){if(path.indexOf('..')===-1&&path.indexOf('.')===-1)
return path;const normalizedSegments=[];const segments=path.split('/');for(let i=0;i<segments.length;i++){const segment=segments[i];if(segment==='.')
continue;else if(segment==='..')
normalizedSegments.pop();else if(segment)
normalizedSegments.push(segment);}
let normalizedPath=normalizedSegments.join('/');if(normalizedPath[normalizedPath.length-1]==='/')
return normalizedPath;if(path[0]==='/'&&normalizedPath)
normalizedPath='/'+normalizedPath;if((path[path.length-1]==='/')||(segments[segments.length-1]==='.')||(segments[segments.length-1]==='..'))
normalizedPath=normalizedPath+'/';return normalizedPath;}
static _loadScriptsPromise(scriptNames,base){const promises=[];const urls=[];const sources=new Array(scriptNames.length);let scriptToEval=0;for(let i=0;i<scriptNames.length;++i){const scriptName=scriptNames[i];let sourceURL=(base||self._importScriptPathPrefix)+scriptName;const schemaIndex=sourceURL.indexOf('://')+3;let pathIndex=sourceURL.indexOf('/',schemaIndex);if(pathIndex===-1)
pathIndex=sourceURL.length;sourceURL=sourceURL.substring(0,pathIndex)+Runtime.normalizePath(sourceURL.substring(pathIndex));if(_loadedScripts[sourceURL])
continue;urls.push(sourceURL);promises.push(Runtime.loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null,i),scriptSourceLoaded.bind(null,i,undefined)));}
return Promise.all(promises).then(undefined);function scriptSourceLoaded(scriptNumber,scriptSource){sources[scriptNumber]=scriptSource||'';while(typeof sources[scriptToEval]!=='undefined'){evaluateScript(urls[scriptToEval],sources[scriptToEval]);++scriptToEval;}}
function evaluateScript(sourceURL,scriptSource){_loadedScripts[sourceURL]=true;if(!scriptSource){console.error('Empty response arrived for script \''+sourceURL+'\'');return;}
self.eval(scriptSource+'\n//# sourceURL='+sourceURL);}}
static _loadResourceIntoCache(url,appendSourceURL){return Runtime.loadResourcePromise(url).then(cacheResource.bind(this,url),cacheResource.bind(this,url,undefined));function cacheResource(path,content){if(!content){console.error('Failed to load resource: '+path);return;}
const sourceURL=appendSourceURL?Runtime.resolveSourceURL(path):'';Runtime.cachedResources[path]=content+sourceURL;}}
static async runtimeReady(){return Runtime._runtimeReadyPromise;}
static async startApplication(appName){console.timeStamp('Runtime.startApplication');const allDescriptorsByName={};for(let i=0;i<allDescriptors.length;++i){const d=allDescriptors[i];allDescriptorsByName[d['name']]=d;}
if(!applicationDescriptor){let data=await Runtime.loadResourcePromise(appName+'.json');applicationDescriptor=JSON.parse(data);let descriptor=applicationDescriptor;while(descriptor.extends){data=await Runtime.loadResourcePromise(descriptor.extends+'.json');descriptor=JSON.parse(data);applicationDescriptor.modules=descriptor.modules.concat(applicationDescriptor.modules);}}
const configuration=applicationDescriptor.modules;const moduleJSONPromises=[];const coreModuleNames=[];for(let i=0;i<configuration.length;++i){const descriptor=configuration[i];const name=descriptor['name'];const moduleJSON=allDescriptorsByName[name];if(moduleJSON)
moduleJSONPromises.push(Promise.resolve(moduleJSON));else
moduleJSONPromises.push(Runtime.loadResourcePromise(name+'/module.json').then(JSON.parse.bind(JSON)));if(descriptor['type']==='autostart')
coreModuleNames.push(name);}
const moduleDescriptors=await Promise.all(moduleJSONPromises);for(let i=0;i<moduleDescriptors.length;++i){moduleDescriptors[i].name=configuration[i]['name'];moduleDescriptors[i].condition=configuration[i]['condition'];moduleDescriptors[i].remote=configuration[i]['type']==='remote';}
self.runtime=new Runtime(moduleDescriptors);if(coreModuleNames)
return(self.runtime._loadAutoStartModules(coreModuleNames));}
static startWorker(appName){return Runtime.startApplication(appName).then(sendWorkerReady);function sendWorkerReady(){self.postMessage('workerReady');}}
static queryParam(name){return Runtime._queryParamsObject[name]||null;}
static queryParamsString(){return location.search;}
static _experimentsSetting(){try{return(JSON.parse(self.localStorage&&self.localStorage['experiments']?self.localStorage['experiments']:'{}'));}catch(e){console.error('Failed to parse localStorage[\'experiments\']');return{};}}
static _assert(value,message){if(value)
return;Runtime._originalAssert.call(Runtime._console,value,message+' '+new Error().stack);}
static setPlatform(platform){Runtime._platform=platform;}
static _isDescriptorEnabled(descriptor){const activatorExperiment=descriptor['experiment'];if(activatorExperiment==='*')
return Runtime.experiments.supportEnabled();if(activatorExperiment&&activatorExperiment.startsWith('!')&&Runtime.experiments.isEnabled(activatorExperiment.substring(1)))
return false;if(activatorExperiment&&!activatorExperiment.startsWith('!')&&!Runtime.experiments.isEnabled(activatorExperiment))
return false;const condition=descriptor['condition'];if(condition&&!condition.startsWith('!')&&!Runtime.queryParam(condition))
return false;if(condition&&condition.startsWith('!')&&Runtime.queryParam(condition.substring(1)))
return false;return true;}
static resolveSourceURL(path){let sourceURL=self.location.href;if(self.location.search)
sourceURL=sourceURL.replace(self.location.search,'');sourceURL=sourceURL.substring(0,sourceURL.lastIndexOf('/')+1)+path;return'\n/*# sourceURL='+sourceURL+' */';}
useTestBase(){Runtime._remoteBase='http://localhost:8000/inspector-sources/';if(Runtime.queryParam('debugFrontend'))
Runtime._remoteBase+='debug/';}
_registerModule(descriptor){const module=new Runtime.Module(this,descriptor);this._modules.push(module);this._modulesMap[descriptor['name']]=module;}
loadModulePromise(moduleName){return this._modulesMap[moduleName]._loadPromise();}
_loadAutoStartModules(moduleNames){const promises=[];for(let i=0;i<moduleNames.length;++i)
promises.push(this.loadModulePromise(moduleNames[i]));return Promise.all(promises);}
_checkExtensionApplicability(extension,predicate){if(!predicate)
return false;const contextTypes=extension.descriptor().contextTypes;if(!contextTypes)
return true;for(let i=0;i<contextTypes.length;++i){const contextType=this._resolve(contextTypes[i]);const isMatching=!!contextType&&predicate(contextType);if(isMatching)
return true;}
return false;}
isExtensionApplicableToContext(extension,context){if(!context)
return true;return this._checkExtensionApplicability(extension,isInstanceOf);function isInstanceOf(targetType){return context instanceof targetType;}}
isExtensionApplicableToContextTypes(extension,currentContextTypes){if(!extension.descriptor().contextTypes)
return true;return this._checkExtensionApplicability(extension,currentContextTypes?isContextTypeKnown:null);function isContextTypeKnown(targetType){return currentContextTypes.has(targetType);}}
extensions(type,context,sortByTitle){return this._extensions.filter(filter).sort(sortByTitle?titleComparator:orderComparator);function filter(extension){if(extension._type!==type&&extension._typeClass()!==type)
return false;if(!extension.enabled())
return false;return!context||extension.isApplicable(context);}
function orderComparator(extension1,extension2){const order1=extension1.descriptor()['order']||0;const order2=extension2.descriptor()['order']||0;return order1-order2;}
function titleComparator(extension1,extension2){const title1=extension1.title()||'';const title2=extension2.title()||'';return title1.localeCompare(title2);}}
extension(type,context){return this.extensions(type,context)[0]||null;}
allInstances(type,context){return Promise.all(this.extensions(type,context).map(extension=>extension.instance()));}
_resolve(typeName){if(!this._cachedTypeClasses[typeName]){const path=typeName.split('.');let object=self;for(let i=0;object&&(i<path.length);++i)
object=object[path[i]];if(object)
this._cachedTypeClasses[typeName]=(object);}
return this._cachedTypeClasses[typeName]||null;}
sharedInstance(constructorFunction){if(Runtime._instanceSymbol in constructorFunction&&Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol))
return constructorFunction[Runtime._instanceSymbol];const instance=new constructorFunction();constructorFunction[Runtime._instanceSymbol]=instance;return instance;}};Runtime._queryParamsObject={__proto__:null};Runtime._instanceSymbol=Symbol('instance');Runtime.cachedResources={__proto__:null};Runtime._console=console;Runtime._originalAssert=console.assert;Runtime._platform='';Runtime.ModuleDescriptor=class{constructor(){this.name;this.extensions;this.dependencies;this.scripts;this.condition;this.remote;}};Runtime.ExtensionDescriptor=class{constructor(){this.type;this.className;this.factoryName;this.contextTypes;}};Runtime.Module=class{constructor(manager,descriptor){this._manager=manager;this._descriptor=descriptor;this._name=descriptor.name;this._extensions=[];this._extensionsByClassName=new Map();const extensions=(descriptor.extensions);for(let i=0;extensions&&i<extensions.length;++i){const extension=new Runtime.Extension(this,extensions[i]);this._manager._extensions.push(extension);this._extensions.push(extension);}
this._loadedForTest=false;}
name(){return this._name;}
enabled(){return Runtime._isDescriptorEnabled(this._descriptor);}
resource(name){const fullName=this._name+'/'+name;const content=Runtime.cachedResources[fullName];if(!content)
throw new Error(fullName+' not preloaded. Check module.json');return content;}
_loadPromise(){if(!this.enabled())
return Promise.reject(new Error('Module '+this._name+' is not enabled'));if(this._pendingLoadPromise)
return this._pendingLoadPromise;const dependencies=this._descriptor.dependencies;const dependencyPromises=[];for(let i=0;dependencies&&i<dependencies.length;++i)
dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise());this._pendingLoadPromise=Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(()=>this._loadedForTest=true);return this._pendingLoadPromise;}
_loadResources(){const resources=this._descriptor['resources'];if(!resources||!resources.length)
return Promise.resolve();const promises=[];for(let i=0;i<resources.length;++i){const url=this._modularizeURL(resources[i]);promises.push(Runtime._loadResourceIntoCache(url,true));}
return Promise.all(promises).then(undefined);}
_loadScripts(){if(!this._descriptor.scripts||!this._descriptor.scripts.length)
return Promise.resolve();const specialCases={'sdk':'SDK','js_sdk':'JSSDK','browser_sdk':'BrowserSDK','ui':'UI','object_ui':'ObjectUI','perf_ui':'PerfUI','har_importer':'HARImporter','sdk_test_runner':'SDKTestRunner','cpu_profiler_test_runner':'CPUProfilerTestRunner'};const namespace=specialCases[this._name]||this._name.split('_').map(a=>a.substring(0,1).toUpperCase()+a.substring(1)).join('');self[namespace]=self[namespace]||{};return Runtime._loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL,this),this._remoteBase());}
_modularizeURL(resourceName){return Runtime.normalizePath(this._name+'/'+resourceName);}
_remoteBase(){return!Runtime.queryParam('debugFrontend')&&this._descriptor.remote&&Runtime._remoteBase||undefined;}
substituteURL(value){const base=this._remoteBase()||'';return value.replace(/@url\(([^\)]*?)\)/g,convertURL.bind(this));function convertURL(match,url){return base+this._modularizeURL(url);}}};Runtime.Extension=class{constructor(module,descriptor){this._module=module;this._descriptor=descriptor;this._type=descriptor.type;this._hasTypeClass=this._type.charAt(0)==='@';this._className=descriptor.className||null;this._factoryName=descriptor.factoryName||null;}
descriptor(){return this._descriptor;}
module(){return this._module;}
enabled(){return this._module.enabled()&&Runtime._isDescriptorEnabled(this.descriptor());}
_typeClass(){if(!this._hasTypeClass)
return null;return this._module._manager._resolve(this._type.substring(1));}
isApplicable(context){return this._module._manager.isExtensionApplicableToContext(this,context);}
instance(){return this._module._loadPromise().then(this._createInstance.bind(this));}
canInstantiate(){return!!(this._className||this._factoryName);}
_createInstance(){const className=this._className||this._factoryName;if(!className)
throw new Error('Could not instantiate extension with no class');const constructorFunction=self.eval((className));if(!(constructorFunction instanceof Function))
throw new Error('Could not instantiate: '+className);if(this._className)
return this._module._manager.sharedInstance(constructorFunction);return new constructorFunction(this);}
title(){return this._descriptor['title-'+Runtime._platform]||this._descriptor['title'];}
hasContextType(contextType){const contextTypes=this.descriptor().contextTypes;if(!contextTypes)
return false;for(let i=0;i<contextTypes.length;++i){if(contextType===this._module._manager._resolve(contextTypes[i]))
return true;}
return false;}};Runtime.ExperimentsSupport=class{constructor(){this._supportEnabled=Runtime.queryParam('experiments')!==null;this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
allConfigurableExperiments(){const result=[];for(let i=0;i<this._experiments.length;i++){const experiment=this._experiments[i];if(!this._enabledTransiently[experiment.name])
result.push(experiment);}
return result;}
supportEnabled(){return this._supportEnabled;}
_setExperimentsSetting(value){if(!self.localStorage)
return;self.localStorage['experiments']=JSON.stringify(value);}
register(experimentName,experimentTitle,hidden){Runtime._assert(!this._experimentNames[experimentName],'Duplicate registration of experiment '+experimentName);this._experimentNames[experimentName]=true;this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden));}
isEnabled(experimentName){this._checkExperiment(experimentName);if(this._enabledTransiently[experimentName])
return true;if(!this.supportEnabled())
return false;return!!Runtime._experimentsSetting()[experimentName];}
setEnabled(experimentName,enabled){this._checkExperiment(experimentName);const experimentsSetting=Runtime._experimentsSetting();experimentsSetting[experimentName]=enabled;this._setExperimentsSetting(experimentsSetting);}
setDefaultExperiments(experimentNames){for(let i=0;i<experimentNames.length;++i){this._checkExperiment(experimentNames[i]);this._enabledTransiently[experimentNames[i]]=true;}}
enableForTest(experimentName){this._checkExperiment(experimentName);this._enabledTransiently[experimentName]=true;}
clearForTest(){this._experiments=[];this._experimentNames={};this._enabledTransiently={};}
cleanUpStaleExperiments(){const experimentsSetting=Runtime._experimentsSetting();const cleanedUpExperimentSetting={};for(let i=0;i<this._experiments.length;++i){const experimentName=this._experiments[i].name;if(experimentsSetting[experimentName])
cleanedUpExperimentSetting[experimentName]=true;}
this._setExperimentsSetting(cleanedUpExperimentSetting);}
_checkExperiment(experimentName){Runtime._assert(this._experimentNames[experimentName],'Unknown experiment '+experimentName);}};Runtime.Experiment=class{constructor(experiments,name,title,hidden){this.name=name;this.title=title;this.hidden=hidden;this._experiments=experiments;}
isEnabled(){return this._experiments.isEnabled(this.name);}
setEnabled(enabled){this._experiments.setEnabled(this.name,enabled);}};{(function parseQueryParameters(){const queryParams=Runtime.queryParamsString();if(!queryParams)
return;const params=queryParams.substring(1).split('&');for(let i=0;i<params.length;++i){const pair=params[i].split('=');const name=pair.shift();Runtime._queryParamsObject[name]=pair.join('=');}})();}
Runtime.experiments=new Runtime.ExperimentsSupport();Runtime._runtimeReadyPromiseCallback;Runtime._runtimeReadyPromise=new Promise(fulfil=>Runtime._runtimeReadyPromiseCallback=fulfil);Runtime._remoteBase;(function validateRemoteBase(){if(location.href.startsWith('chrome-devtools://devtools/bundled/')&&Runtime.queryParam('remoteBase')){const versionMatch=/\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase'));if(versionMatch)
Runtime._remoteBase=`${location.origin}/remote/serve_file/${versionMatch[1]}/`;}})();function ServicePort(){}
ServicePort.prototype={setHandlers(messageHandler,closeHandler){},send(message){},close(){}};var runtime;allDescriptors.push(...[{"dependencies":["ui","platform","common","cm"],"extensions":[{"className":"TextEditor.CodeMirrorUtils.TokenizerFactory","type":"@TextUtils.TokenizerFactory"},{"className":"TextEditor.CodeMirrorTextEditorFactory","type":"@UI.TextEditorFactory"}],"name":"text_editor","scripts":["text_editor_module.js"],"skip_compilation":["acorn/acorn.js","../cm_web_modes/css.js","../cm_web_modes/javascript.js","../cm_web_modes/xml.js","../cm_web_modes/htmlmixed.js","../cm_web_modes/htmlembedded.js"]},{"skip_compilation":["../InspectorBackendCommands.js"],"dependencies":["common"],"name":"protocol"},{"skip_compilation":["codemirror.js","multiplex.js","matchbrackets.js","closebrackets.js","markselection.js","comment.js","overlay.js","activeline.js"],"name":"cm","scripts":["cm_module.js"]},{"dependencies":["text_editor"],"extensions":[{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-csrc","text/x-c","text/x-chdr","text/x-c++src","text/x-c++hdr","text/x-java","text/x-csharp","text/x-scala","x-shader/x-vertex","x-shader/x-fragment"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clike.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-coffeescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"coffeescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/markdown","text/x-markdown"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"markdown.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["application/x-httpd-php","application/x-httpd-php-open","text/x-php"],"dependencies":["clike.js"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"php.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-python","text/x-cython"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"python.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-sh"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"shell.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-livescript"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"livescript.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-clojure"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"clojure.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/jsx"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"jsx.js"},{"className":"CmModes.DefaultCodeMirrorMimeMode","mimeTypes":["text/x-styl"],"type":"@TextEditor.CodeMirrorMimeMode","fileName":"stylus.js"}],"name":"cm_modes","scripts":["cm_modes_module.js"]},{"dependencies":["components","search","source_frame","snippets","extensions","persistence","quick_open","inline_editor","color_picker","event_listeners","object_ui","formatter"],"extensions":[{"title":"Sources","id":"sources","className":"Sources.SourcesPanel","location":"panel","type":"view","order":30},{"className":"Sources.SourcesPanel","contextTypes":["Workspace.UISourceCode","Workspace.UILocation","SDK.RemoteObject","SDK.NetworkRequest","Sources.UISourceCodeFrame"],"type":"@UI.ContextMenu.Provider"},{"category":"Debugger","iconClass":"largeicon-pause","toggledIconClass":"largeicon-resume","className":"Sources.SourcesPanel.RevealingActionDelegate","contextTypes":["Sources.SourcesPanel","UI.ShortcutRegistry.ForwardedShortcut"],"actionId":"debugger.toggle-pause","bindings":[{"platform":"windows,linux","shortcut":"F8 Ctrl+\\"},{"platform":"mac","shortcut":"F8 Meta+\\"}],"type":"action","options":[{"value":true,"title":"Pause script execution"},{"value":false,"title":"Resume script execution"}]},{"category":"Debugger","iconClass":"largeicon-step-over","title":"Step over next function call","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.step-over","bindings":[{"platform":"windows,linux","shortcut":"F10 Ctrl+'"},{"platform":"mac","shortcut":"F10 Meta+'"}],"type":"action"},{"category":"Debugger","iconClass":"largeicon-step-into","title":"Step into next function call","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.step-into","bindings":[{"platform":"windows,linux","shortcut":"F11 Ctrl+;"},{"platform":"mac","shortcut":"F11 Meta+;"}],"type":"action"},{"category":"Debugger","iconClass":"largeicon-step","title":"Step","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.step","bindings":[{"shortcut":"F9"}],"type":"action"},{"category":"Debugger","iconClass":"largeicon-step-out","title":"Step out of current function","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.step-out","bindings":[{"platform":"windows,linux","shortcut":"Shift+F11 Shift+Ctrl+;"},{"platform":"mac","shortcut":"Shift+F11 Shift+Meta+;"}],"type":"action"},{"iconClass":"largeicon-play","title":"Run snippet","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.run-snippet","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Enter"},{"platform":"mac","shortcut":"Meta+Enter"}],"type":"action"},{"category":"Debugger","iconClass":"largeicon-deactivate-breakpoints","toggledIconClass":"largeicon-activate-breakpoints","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.SourcesPanel"],"actionId":"debugger.toggle-breakpoints-active","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+F8"},{"platform":"mac","shortcut":"Meta+F8"}],"type":"action","options":[{"value":true,"title":"Deactivate breakpoints"},{"value":false,"title":"Activate breakpoints"}]},{"title":"Add selected text to watches","className":"Sources.WatchExpressionsSidebarPane","contextTypes":["Sources.UISourceCodeFrame"],"actionId":"sources.add-to-watch","bindings":[{"shortcut":"Ctrl+Shift+A"}],"type":"action"},{"className":"Sources.WatchExpressionsSidebarPane","contextTypes":["TextEditor.CodeMirrorTextEditor"],"type":"@UI.ContextMenu.Provider"},{"title":"Evaluate in console","className":"Sources.SourcesPanel.DebuggingActionDelegate","contextTypes":["Sources.UISourceCodeFrame"],"actionId":"debugger.evaluate-selection","bindings":[{"shortcut":"Ctrl+Shift+E"}],"type":"action"},{"className":"Sources.OpenFileQuickOpen","prefix":"","type":"@QuickOpen.FilteredListWidget.Provider","title":"Open file"},{"className":"Sources.GoToLineQuickOpen","prefix":":","type":"@QuickOpen.FilteredListWidget.Provider","title":"Go to line"},{"className":"Sources.OutlineQuickOpen","prefix":"@","type":"@QuickOpen.FilteredListWidget.Provider","title":"Go to symbol"},{"type":"context-menu-item","location":"navigatorMenu/default","actionId":"quickOpen.show"},{"className":"Sources.SourcesPanel.UILocationRevealer","contextTypes":["Workspace.UILocation"],"destination":"Sources panel","type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.DebuggerLocationRevealer","contextTypes":["SDK.DebuggerModel.Location"],"destination":"Sources panel","type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.UISourceCodeRevealer","contextTypes":["Workspace.UISourceCode"],"destination":"Sources panel","type":"@Common.Revealer"},{"className":"Sources.SourcesPanel.DebuggerPausedDetailsRevealer","contextTypes":["SDK.DebuggerPausedDetails"],"destination":"Sources panel","type":"@Common.Revealer"},{"className":"Sources.InplaceFormatterEditorAction","type":"@Sources.SourcesView.EditorAction"},{"className":"Sources.ScriptFormatterEditorAction","type":"@Sources.SourcesView.EditorAction"},{"title":"Filesystem","id":"navigator-files","className":"Sources.FilesNavigatorView","location":"navigator-view","type":"view","order":3,"persistence":"permanent"},{"title":"Overrides","id":"navigator-overrides","className":"Sources.OverridesNavigatorView","location":"navigator-view","type":"view","order":4,"persistence":"permanent"},{"title":"Content scripts","id":"navigator-contentScripts","className":"Sources.ContentScriptsNavigatorView","location":"navigator-view","type":"view","order":5,"persistence":"permanent"},{"title":"Snippets","id":"navigator-snippets","className":"Sources.SnippetsNavigatorView","location":"navigator-view","type":"view","order":6,"persistence":"permanent"},{"title":"Search","id":"sources.search-sources-tab","className":"Sources.SearchSourcesView","location":"drawer-view","type":"view","order":7,"persistence":"closeable"},{"className":"Sources.NetworkNavigatorView","viewId":"navigator-network","type":"@Sources.NavigatorView"},{"className":"Sources.FilesNavigatorView","viewId":"navigator-files","type":"@Sources.NavigatorView"},{"className":"Sources.OverridesNavigatorView","viewId":"navigator-overrides","type":"@Sources.NavigatorView"},{"className":"Sources.ContentScriptsNavigatorView","viewId":"navigator-contentScripts","type":"@Sources.NavigatorView"},{"className":"Sources.SnippetsNavigatorView","viewId":"navigator-snippets","type":"@Sources.NavigatorView"},{"className":"Sources.SourcesView.SwitchFileActionDelegate","contextTypes":["Sources.SourcesView"],"bindings":[{"shortcut":"Alt+O"}],"type":"action","actionId":"sources.switch-file"},{"bindings":[{"platform":"windows,linux","shortcut":"F2"},{"platform":"mac","shortcut":"Enter"}],"type":"action","actionId":"sources.rename"},{"defaultValue":"true","type":"setting","settingName":"navigatorGroupByFolder","settingType":"boolean"},{"category":"Sources","title":"Search in anonymous and content scripts","defaultValue":false,"settingName":"searchInAnonymousAndContentScripts","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Search in anonymous and content scripts"},{"value":false,"title":"Do not search in anonymous and content scripts"}]},{"category":"Sources","title":"Automatically reveal files in sidebar","defaultValue":false,"settingName":"autoRevealInNavigator","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Automatically reveal files in sidebar"},{"value":false,"title":"Do not automatically reveal files in sidebar"}]},{"category":"Sources","title":"Enable JavaScript source maps","defaultValue":true,"settingName":"jsSourceMapsEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable JavaScript source maps"},{"value":false,"title":"Disable JavaScript source maps"}]},{"category":"Sources","title":"Detect indentation","defaultValue":true,"settingName":"textEditorAutoDetectIndent","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Detect indentation"},{"value":false,"title":"Do not detect indentation"}]},{"category":"Sources","title":"Autocompletion","defaultValue":true,"settingName":"textEditorAutocompletion","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable autocompletion"},{"value":false,"title":"Disable autocompletion"}]},{"category":"Sources","title":"Bracket matching","defaultValue":true,"settingName":"textEditorBracketMatching","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable bracket matching"},{"value":false,"title":"Disable bracket matching"}]},{"category":"Sources","title":"Show whitespace characters:","defaultValue":"original","settingName":"showWhitespacesInEditor","settingType":"enum","type":"setting","options":[{"text":"None","value":"none","title":"Do not show whitespace characters"},{"text":"All","value":"all","title":"Show all whitespace characters"},{"text":"Trailing","value":"trailing","title":"Show trailing whitespace characters"}]},{"category":"Sources","title":"Display variable values inline while debugging","defaultValue":true,"settingName":"inlineVariableValues","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Display variable values inline while debugging"},{"value":false,"title":"Do not display variable values inline while debugging"}]},{"category":"Sources","title":"Enable CSS source maps","defaultValue":true,"settingName":"cssSourceMapsEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable CSS source maps"},{"value":false,"title":"Disable CSS source maps"}]},{"title":"Quick source","id":"sources.quick","className":"Sources.SourcesPanel.WrapperView","location":"drawer-view","type":"view","order":1000,"persistence":"closeable"},{"category":"Sources","className":"Sources.SourcesView.ActionDelegate","type":"action","actionId":"sources.close-all","title":"Close All"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"shortcut":"Alt+Minus"}],"type":"action","actionId":"sources.jump-to-previous-location"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"shortcut":"Alt+Plus"}],"type":"action","actionId":"sources.jump-to-next-location"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"shortcut":"Alt+w"}],"type":"action","actionId":"sources.close-editor-tab"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"shortcut":"Ctrl+g"}],"type":"action","actionId":"sources.go-to-line"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+o"},{"platform":"mac","shortcut":"Meta+Shift+o"}],"type":"action","actionId":"sources.go-to-member"},{"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+b"},{"platform":"mac","shortcut":"Meta+b"}],"type":"action","actionId":"debugger.toggle-breakpoint"},{"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+b"},{"platform":"mac","shortcut":"Meta+Shift+b"}],"type":"action","actionId":"debugger.toggle-breakpoint-enabled"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+s"},{"platform":"mac","shortcut":"Meta+s"}],"type":"action","actionId":"sources.save"},{"className":"Sources.SourcesView.ActionDelegate","contextTypes":["Sources.SourcesPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+s"},{"platform":"mac","shortcut":"Meta+Alt+s"}],"type":"action","actionId":"sources.save-all"},{"category":"Sources","className":"Sources.SnippetsNavigatorView.CreatingActionDelegate","type":"action","actionId":"sources.create-snippet","title":"Create new snippet"},{"category":"Sources","className":"Sources.SnippetsNavigatorView.CreatingActionDelegate","type":"action","actionId":"sources.add-folder-to-workspace","title":"Add folder to workspace"},{"className":"Sources.SourcesPanel","type":"@UI.ViewLocationResolver","name":"navigator-view"},{"category":"Sources","className":"Sources.SourcesPanel","type":"@UI.ViewLocationResolver","name":"sources-sidebar"},{"className":"Sources.ThreadsSidebarPane","type":"view","id":"sources.threads","persistence":"permanent","title":"Threads"},{"className":"Sources.ScopeChainSidebarPane","type":"view","id":"sources.scopeChain","persistence":"permanent","title":"Scope"},{"title":"Watch","className":"Sources.WatchExpressionsSidebarPane","hasToolbar":true,"type":"view","id":"sources.watch","persistence":"permanent"},{"className":"Sources.JavaScriptBreakpointsSidebarPane","type":"view","id":"sources.jsBreakpoints","persistence":"permanent","title":"Breakpoints"},{"className":"Sources.JavaScriptBreakpointsSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"className":"Sources.CallStackSidebarPane","contextTypes":["SDK.DebuggerPausedDetails"],"type":"@UI.ContextFlavorListener"},{"className":"Sources.ScopeChainSidebarPane","contextTypes":["SDK.DebuggerModel.CallFrame"],"type":"@UI.ContextFlavorListener"},{"category":"Debugger","title":"Previous call frame","className":"Sources.CallStackSidebarPane.ActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.previous-call-frame","bindings":[{"shortcut":"Ctrl+,"}],"type":"action"},{"category":"Debugger","title":"Next call frame","className":"Sources.CallStackSidebarPane.ActionDelegate","contextTypes":["SDK.DebuggerPausedDetails"],"actionId":"debugger.next-call-frame","bindings":[{"shortcut":"Ctrl+."}],"type":"action"},{"category":"DevTools","title":"Search","className":"Sources.SearchSourcesView.ActionDelegate","actionId":"sources.search","bindings":[{"platform":"mac","shortcut":"Meta+Alt+F"},{"platform":"windows,linux","shortcut":"Ctrl+Shift+F"}],"type":"action"},{"type":"context-menu-item","location":"mainMenu/default","actionId":"sources.search"}],"name":"sources","scripts":["sources_module.js"]},{"dependencies":["sdk"],"extensions":[{"category":"Network","title":"Preserve log","storageType":"session","defaultValue":false,"tags":"preserve, clear, reset","settingName":"network_log.preserve-log","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Do not preserve log on page reload / navigation"},{"value":false,"title":"Preserve log on page reload / navigation"}]}],"name":"browser_sdk"},{"dependencies":["common","platform"],"name":"host"},{"skip_compilation":["diff_match_patch.js"],"dependencies":["common"],"name":"diff","scripts":["diff_module.js"]},{"dependencies":["sdk","platform","services","workspace"],"name":"bindings"},{"dependencies":["bindings","quick_open"],"extensions":[{"className":"Snippets.SnippetsQuickOpen","prefix":"!","type":"@QuickOpen.FilteredListWidget.Provider","title":"Run snippet"}],"name":"snippets","scripts":["snippets_module.js"]},{"dependencies":[],"name":"heap_snapshot_model","scripts":["heap_snapshot_model_module.js"]},{"dependencies":["components","data_grid","object_ui","sdk","product_registry","formatter"],"extensions":[{"title":"Console","id":"console","className":"Console.ConsolePanel","location":"panel","type":"view","order":20},{"title":"Console","id":"console-view","className":"Console.ConsolePanel.WrapperView","location":"drawer-view","type":"view","order":0,"persistence":"permanent"},{"className":"Console.ConsolePanel.ConsoleRevealer","contextTypes":["Common.Console"],"type":"@Common.Revealer"},{"className":"Console.ConsoleView.ActionDelegate","bindings":[{"shortcut":"Ctrl+`"}],"type":"action","actionId":"console.show"},{"category":"Console","iconClass":"largeicon-clear","title":"Clear console","className":"Console.ConsoleView.ActionDelegate","actionId":"console.clear","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+L"},{"platform":"mac","shortcut":"Ctrl+L Meta+K"}],"type":"action"},{"category":"Console","className":"Console.ConsoleView.ActionDelegate","type":"action","actionId":"console.clear.history","title":"Clear console history"},{"category":"Console","title":"Hide network messages","defaultValue":false,"settingName":"hideNetworkMessages","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Hide network messages"},{"value":false,"title":"Show network messages"}]},{"category":"Console","title":"Selected context only","storageType":"session","defaultValue":false,"settingName":"selectedContextFilterEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Only show messages from the current context (top, iframe, worker, extension)"},{"value":false,"title":"Show messages from all contexts"}]},{"category":"Console","title":"Log XMLHttpRequests","defaultValue":false,"settingName":"monitoringXHREnabled","settingType":"boolean","type":"setting"},{"category":"Console","title":"Show timestamps","defaultValue":false,"settingName":"consoleTimestampsEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show timestamps"},{"value":false,"title":"Hide timestamps"}]},{"category":"Console","title":"Autocomplete from history","defaultValue":true,"settingName":"consoleHistoryAutocomplete","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Autocomplete from history"},{"value":false,"title":"Do not autocomplete from history"}]},{"category":"Console","title":"Group similar","defaultValue":true,"settingName":"consoleGroupSimilar","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Group similar messages in console"},{"value":false,"title":"Do not group similar messages in console"}]}],"name":"console","scripts":["console_module.js"]},{"dependencies":["platform","ui","host","components","data_grid","source_frame"],"extensions":[{"title":"Protocol monitor","id":"protocol-monitor","className":"ProtocolMonitor.ProtocolMonitor","experiment":"protocolMonitor","location":"drawer-view","type":"view","order":100,"persistence":"closeable"}],"name":"protocol_monitor","scripts":["protocol_monitor_module.js"]},{"dependencies":["workspace","diff","persistence"],"name":"workspace_diff","scripts":["workspace_diff_module.js"]},{"dependencies":["ui","sdk","bindings","source_frame","text_editor"],"extensions":[{"className":"PerfUI.LineLevelProfile.LineDecorator","decoratorType":"performance","type":"@SourceFrame.LineDecorator"},{"category":"Performance","title":"Flamechart mouse wheel action:","defaultValue":"zoom","settingName":"flamechartMouseWheelAction","settingType":"enum","type":"setting","options":[{"text":"Scroll","value":"scroll","title":"Scroll"},{"text":"Zoom","value":"zoom","title":"Zoom"}]},{"iconClass":"largeicon-trash-bin","className":"PerfUI.GCActionDelegate","type":"action","actionId":"components.collect-garbage","title":"Collect garbage"}],"name":"perf_ui","scripts":["perf_ui_module.js"]},{"dependencies":["common","sdk","ui"],"extensions":[{"category":"Appearance","title":"Show third party URL badges","defaultValue":false,"settingName":"product_registry.badges-visible","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show third party badges"},{"value":false,"title":"Do not show third party badges"}]}],"name":"product_registry"},{"experiment":"terminalInDrawer","extensions":[{"title":"Terminal","id":"drawer.xterm","factoryName":"Terminal.TerminalWidget","location":"drawer-view","type":"view","order":10,"persistence":"closeable"}],"name":"terminal","dependencies":["components","ui","services"],"scripts":["terminal_module.js"],"skip_compilation":["xterm.js/build/xterm.js","xterm.js/addons/fit/fit.js"]},{"dependencies":[],"name":"platform"},{"dependencies":["text_editor","ui","platform","persistence","formatter","object_ui","workspace_diff"],"extensions":[{"category":"Sources","title":"Default indentation:","defaultValue":"    ","settingName":"textEditorIndent","settingType":"enum","type":"setting","options":[{"text":"2 spaces","value":"  ","title":"Set indentation to 2 spaces"},{"text":"4 spaces","value":"    ","title":"Set indentation to 4 spaces"},{"text":"8 spaces","value":"        ","title":"Set indentation to 8 spaces"},{"text":"Tab character","value":"\t","title":"Set indentation to tab character"}]}],"name":"source_frame","scripts":["source_frame_module.js"]},{"dependencies":["extensions","host","platform","sdk","persistence"],"extensions":[{"className":"Main.SimpleAppProvider","type":"@Common.AppProvider","order":10},{"className":"Components.Linkifier.ContentProviderContextMenuProvider","contextTypes":["Workspace.UISourceCode","SDK.Resource","SDK.NetworkRequest"],"type":"@UI.ContextMenu.Provider"},{"className":"UI.XLink.ContextMenuProvider","contextTypes":["Node"],"type":"@UI.ContextMenu.Provider"},{"className":"Components.Linkifier.LinkContextMenuProvider","contextTypes":["Node"],"type":"@UI.ContextMenu.Provider"},{"category":"Drawer","title":"Focus debuggee","className":"InspectorMain.FocusDebuggeeActionDelegate","actionId":"inspector_main.focus-debuggee","bindings":[{"shortcut":"F12"}],"type":"action","order":100},{"category":"Drawer","title":"Toggle drawer","className":"UI.InspectorView.DrawerToggleActionDelegate","actionId":"main.toggle-drawer","bindings":[{"shortcut":"Esc"}],"type":"action","order":101},{"className":"Main.ReloadActionDelegate","bindings":[{"shortcut":"Alt+R"}],"type":"action","actionId":"main.debug-reload"},{"category":"DevTools","title":"Restore last dock position","className":"Components.DockController.ToggleDockActionDelegate","actionId":"main.toggle-dock","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+D"},{"platform":"mac","shortcut":"Meta+Shift+D"}],"type":"action"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Plus Ctrl+Shift+Plus Ctrl+NumpadPlus Ctrl+Shift+NumpadPlus"},{"platform":"mac","shortcut":"Meta+Plus Meta+Shift+Plus Meta+NumpadPlus Meta+Shift+NumpadPlus"}],"type":"action","actionId":"main.zoom-in"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Minus Ctrl+Shift+Minus Ctrl+NumpadMinus Ctrl+Shift+NumpadMinus"},{"platform":"mac","shortcut":"Meta+Minus Meta+Shift+Minus Meta+NumpadMinus Meta+Shift+NumpadMinus"}],"type":"action","actionId":"main.zoom-out"},{"className":"Main.Main.ZoomActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+0 Ctrl+Numpad0"},{"platform":"mac","shortcut":"Meta+0 Meta+Numpad0"}],"type":"action","actionId":"main.zoom-reset"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+F"},{"platform":"mac","shortcut":"Meta+F F3"}],"type":"action","actionId":"main.search-in-panel.find"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"shortcut":"Esc"}],"type":"action","actionId":"main.search-in-panel.cancel","order":10},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"mac","shortcut":"Meta+G"}],"type":"action","actionId":"main.search-in-panel.find-next"},{"className":"Main.Main.SearchActionDelegate","bindings":[{"platform":"mac","shortcut":"Meta+Shift+G"}],"type":"action","actionId":"main.search-in-panel.find-previous"},{"separator":true,"type":"@UI.ToolbarItem.Provider","location":"main-toolbar-left","order":100},{"separator":true,"type":"@UI.ToolbarItem.Provider","order":98,"location":"main-toolbar-right"},{"className":"Main.Main.MainMenuItem","type":"@UI.ToolbarItem.Provider","order":99,"location":"main-toolbar-right"},{"className":"Components.DockController.CloseButtonProvider","type":"@UI.ToolbarItem.Provider","order":100,"location":"main-toolbar-right"},{"category":"Appearance","title":"Theme:","defaultValue":"default","tags":"dark, light","settingName":"uiTheme","settingType":"enum","type":"setting","options":[{"text":"Light","value":"default","title":"Switch to light theme"},{"text":"Dark","value":"dark","title":"Switch to dark theme"}]},{"category":"Appearance","title":"Panel layout:","defaultValue":"auto","settingName":"sidebarPosition","settingType":"enum","type":"setting","options":[{"text":"horizontal","value":"bottom","title":"Use horizontal panel layout"},{"text":"vertical","value":"right","title":"Use vertical panel layout"},{"text":"auto","value":"auto","title":"Use automatic panel layout"}]},{"category":"Appearance","title-mac":"Enable \u2318 + 1-9 shortcut to switch panels","title":"Enable Ctrl + 1-9 shortcut to switch panels","defaultValue":false,"settingName":"shortcutPanelSwitch","settingType":"boolean","type":"setting"},{"category":"Extensions","className":"Components.Linkifier.LinkHandlerSettingUI","type":"@UI.SettingUI"},{"category":"DevTools","defaultValue":"right","settingName":"currentDockState","settingType":"enum","type":"setting","options":[{"text":"Right","value":"right","title":"Dock to right"},{"text":"Bottom","value":"bottom","title":"Dock to bottom"},{"text":"Undocked","value":"undocked","title":"Undock into separate window"}]},{"category":"Drawer","className":"UI.InspectorView","type":"@UI.ViewLocationResolver","name":"drawer-view"},{"category":"Panel","className":"UI.InspectorView","type":"@UI.ViewLocationResolver","name":"panel"}],"name":"main"},{"dependencies":["bindings","workspace","components","sdk"],"extensions":[{"title":"Workspace","id":"workspace","className":"Persistence.WorkspaceSettingsTab","location":"settings-view","type":"view","order":1},{"category":"Persistence","title":"Enable Local Overrides","defaultValue":false,"tags":"interception, override, network, rewrite, request","settingName":"persistenceNetworkOverridesEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable override network requests"},{"value":false,"title":"Disable override network requests"}]},{"className":"Persistence.PersistenceActions.ContextMenuProvider","contextTypes":["Workspace.UISourceCode","SDK.Resource","SDK.NetworkRequest"],"type":"@UI.ContextMenu.Provider"}],"name":"persistence"},{"dependencies":["ui"],"name":"inline_editor","scripts":["inline_editor_module.js"]},{"dependencies":["common","ui","sdk"],"extensions":[{"className":"ConsoleCounters.WarningErrorCounter","type":"@UI.ToolbarItem.Provider","order":1,"location":"main-toolbar-right"}],"name":"console_counters"},{"dependencies":["common","host","platform"],"name":"workspace"},{"dependencies":["ui","diff"],"extensions":[{"className":"QuickOpen.CommandMenuProvider","prefix":">","type":"@QuickOpen.FilteredListWidget.Provider","title":"Run command"},{"className":"QuickOpen.HelpQuickOpen","prefix":"?","type":"@QuickOpen.FilteredListWidget.Provider"},{"className":"QuickOpen.CommandMenu.ShowActionDelegate","bindings":[{"platform":"windows,linux","shortcut":"Ctrl+Shift+P"},{"platform":"mac","shortcut":"Meta+Shift+P"}],"type":"action","actionId":"commandMenu.show"},{"title":"Open file","className":"QuickOpen.QuickOpen.ShowActionDelegate","actionId":"quickOpen.show","bindings":[{"platform":"mac","shortcut":"Meta+P Meta+O"},{"platform":"windows,linux","shortcut":"Ctrl+P Ctrl+O"}],"type":"action","order":100},{"type":"context-menu-item","location":"mainMenu/default","actionId":"quickOpen.show"}],"name":"quick_open","scripts":["quick_open_module.js"]},{"dependencies":["components"],"name":"search","scripts":["search_module.js"]},{"dependencies":["ui"],"name":"data_grid","scripts":["data_grid_module.js"]},{"dependencies":["components","browser_sdk","common"],"name":"extensions"},{"dependencies":["sdk","ui","source_frame","sources","data_grid"],"extensions":[{"title":"Coverage","order":100,"className":"Coverage.CoverageView","location":"drawer-view","type":"view","id":"coverage","persistence":"closeable"},{"className":"Coverage.CoverageView.LineDecorator","decoratorType":"coverage","type":"@SourceFrame.LineDecorator"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Coverage.CoverageView.ActionDelegate","toggleWithRedColor":true,"actionId":"coverage.toggle-recording","category":"Performance","type":"action","options":[{"value":true,"title":"Instrument coverage"},{"value":false,"title":"Stop instrumenting coverage and show results"}]},{"iconClass":"largeicon-refresh","category":"Performance","title":"Start instrumenting coverage and reload page","className":"Coverage.CoverageView.ActionDelegate","actionId":"coverage.start-with-reload","type":"action"}],"name":"coverage","scripts":["coverage_module.js"]},{"dependencies":["common","host"],"name":"services"},{"dependencies":["ui","common","components","sdk","object_ui"],"name":"event_listeners","scripts":["event_listeners_module.js"]},{"dependencies":["platform"],"name":"dom_extension"},{"skip_compilation":["../SupportedCSSProperties.js"],"dependencies":["common","host","platform","protocol"],"extensions":[{"defaultValue":"","type":"setting","settingName":"skipStackFramesPattern","settingType":"regex"},{"defaultValue":false,"type":"setting","settingName":"skipContentScripts","settingType":"boolean"},{"category":"Console","title":"Preserve log upon navigation","defaultValue":false,"settingName":"preserveConsoleLog","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Preserve log upon navigation"},{"value":false,"title":"Do not preserve log upon navigation"}]},{"category":"Debugger","defaultValue":false,"settingName":"pauseOnExceptionEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Pause on exceptions"},{"value":false,"title":"Do not pause on exceptions"}]},{"defaultValue":false,"type":"setting","settingName":"pauseOnCaughtException","settingType":"boolean"},{"category":"Debugger","title":"Disable JavaScript","storageType":"session","defaultValue":false,"options":[{"value":true,"title":"Disable JavaScript"},{"value":false,"title":"Enable JavaScript"}],"settingName":"javaScriptDisabled","settingType":"boolean","type":"setting","order":1},{"category":"Debugger","title":"Disable async stack traces","defaultValue":false,"options":[{"value":true,"title":"Do not capture async stack traces"},{"value":false,"title":"Capture async stack traces"}],"settingName":"disableAsyncStackTraces","settingType":"boolean","type":"setting","order":2},{"category":"Debugger","storageType":"session","defaultValue":true,"settingName":"breakpointsActive","settingType":"boolean","type":"setting"},{"category":"Elements","title":"Show rulers","defaultValue":false,"settingName":"showMetricsRulers","settingType":"boolean","type":"setting"},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showPaintRects","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show paint flashing rectangles"},{"value":false,"title":"Hide paint flashing rectangles"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showDebugBorders","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show layer borders"},{"value":false,"title":"Hide layer borders"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showFPSCounter","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show frames per second (FPS) meter"},{"value":false,"title":"Hide frames per second (FPS) meter"}]},{"category":"Rendering","storageType":"session","defaultValue":false,"settingName":"showScrollBottleneckRects","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Show scroll performance bottlenecks"},{"value":false,"title":"Hide scroll performance bottlenecks"}]},{"category":"Rendering","tags":"query","storageType":"session","defaultValue":"","settingName":"emulatedCSSMedia","settingType":"enum","type":"setting","options":[{"text":"No emulation","value":"","title":"Do not emulate CSS media type"},{"text":"print","value":"print","title":"Emulate CSS print media type"},{"text":"screen","value":"screen","title":"Emulate CSS screen media type"}]},{"category":"Console","title":"Enable custom formatters","defaultValue":false,"settingName":"customFormatters","settingType":"boolean","type":"setting"},{"category":"Network","title":"Enable request blocking","storageType":"session","defaultValue":false,"settingName":"requestBlockingEnabled","settingType":"boolean","type":"setting","options":[{"value":true,"title":"Enable request blocking"},{"value":false,"title":"Disable request blocking"}]},{"category":"Network","title":"Disable cache (while DevTools is open)","defaultValue":false,"options":[{"value":true,"title":"Disable cache (while DevTools is open)"},{"value":false,"title":"Enable cache"}],"userActionCondition":"hasOtherClients","settingName":"cacheDisabled","settingType":"boolean","type":"setting","order":0}],"name":"sdk"},{"dependencies":["common"],"name":"formatter","scripts":["formatter_module.js"]},{"dependencies":["components"],"extensions":[{"category":"Settings","title":"Settings","className":"Settings.SettingsScreen.ActionDelegate","actionId":"settings.show","bindings":[{"shortcut":"F1 Shift+?"}],"type":"action"},{"category":"Settings","className":"Settings.SettingsScreen.ActionDelegate","type":"action","actionId":"settings.documentation","title":"Documentation"},{"category":"Settings","className":"Settings.SettingsScreen.ActionDelegate","type":"action","actionId":"settings.shortcuts","title":"Shortcuts"},{"className":"Settings.SettingsScreen.Revealer","contextTypes":["Common.Setting"],"type":"@Common.Revealer"},{"type":"context-menu-item","location":"mainMenu/footer","actionId":"settings.shortcuts"},{"type":"context-menu-item","location":"mainMenuHelp/default","actionId":"settings.documentation"},{"type":"context-menu-item","location":"mainMenu/footer","actionId":"settings.show"},{"title":"Preferences","id":"preferences","className":"Settings.GenericSettingsTab","location":"settings-view","type":"view","order":0},{"title":"Experiments","id":"experiments","className":"Settings.ExperimentsSettingsTab","experiment":"*","location":"settings-view","type":"view","order":3},{"title":"Blackboxing","id":"blackbox","className":"Settings.FrameworkBlackboxSettingsTab","location":"settings-view","type":"view","order":4},{"category":"Settings","className":"Settings.SettingsScreen","type":"@UI.ViewLocationResolver","name":"settings-view"}],"name":"settings","scripts":["settings_module.js"]},{"dependencies":["ui","sdk"],"name":"color_picker","scripts":["color_picker_module.js"]},{"dependencies":["components","perf_ui","data_grid","heap_snapshot_model","object_ui"],"extensions":[{"title":"Memory","id":"heap_profiler","className":"Profiler.HeapProfilerPanel","location":"panel","type":"view","order":60},{"className":"Profiler.HeapProfilerPanel","contextTypes":["SDK.RemoteObject"],"type":"@UI.ContextMenu.Provider"},{"category":"Performance","title":"High resolution CPU profiling","defaultValue":true,"settingName":"highResolutionCpuProfiling","settingType":"boolean","type":"setting"},{"category":"Performance","title":"Show native functions in JS Profile","defaultValue":true,"settingName":"showNativeFunctionsInJSProfile","settingType":"boolean","type":"setting"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Profiler.HeapProfilerPanel","toggleWithRedColor":true,"actionId":"profiler.heap-toggle-recording","contextTypes":["Profiler.HeapProfilerPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"action"},{"iconClass":"largeicon-start-recording","toggledIconClass":"largeicon-stop-recording","className":"Profiler.JSProfilerPanel","toggleWithRedColor":true,"actionId":"profiler.js-toggle-recording","contextTypes":["Profiler.JSProfilerPanel"],"bindings":[{"platform":"windows,linux","shortcut":"Ctrl+E"},{"platform":"mac","shortcut":"Meta+E"}],"type":"action"}],"name":"profiler","scripts":["profiler_module.js"]},{"dependencies":["platform","dom_extension","common","host"],"name":"ui"},{"dependencies":["text_utils","platform"],"name":"common"},{"dependencies":["bindings","platform","ui"],"name":"components"},{"dependencies":["ui","sdk","components"],"extensions":[{"className":"ObjectUI.ObjectPropertiesSection.Renderer","contextTypes":["SDK.RemoteObject"],"type":"@Common.Renderer"}],"name":"object_ui","scripts":["object_ui_module.js"]},{"dependencies":["workspace_diff","text_editor","workspace","diff","bindings","persistence","ui"],"extensions":[{"title":"Changes","className":"Changes.ChangesView","location":"drawer-view","type":"view","id":"changes.changes","persistence":"closeable"}],"name":"changes","scripts":["changes_module.js"]},{"dependencies":["platform"],"name":"text_utils"}]);applicationDescriptor={"has_html":false,"modules":[{"name":"text_editor"},{"type":"autostart","name":"protocol"},{"name":"cm"},{"name":"data_grid"},{"name":"perf_ui"},{"name":"sources"},{"type":"autostart","name":"browser_sdk"},{"name":"diff"},{"type":"autostart","name":"bindings"},{"name":"snippets"},{"name":"heap_snapshot_model"},{"type":"autostart","name":"dom_extension"},{"name":"console"},{"name":"protocol_monitor"},{"name":"workspace_diff"},{"type":"remote","name":"cm_modes"},{"name":"event_listeners"},{"type":"remote","name":"terminal"},{"type":"autostart","name":"platform"},{"type":"autostart","name":"ui"},{"type":"autostart","name":"main"},{"type":"autostart","name":"persistence"},{"name":"inline_editor"},{"type":"autostart","name":"console_counters"},{"type":"autostart","name":"components"},{"name":"quick_open"},{"name":"color_picker"},{"name":"coverage"},{"name":"source_frame"},{"type":"autostart","name":"services"},{"type":"autostart","name":"product_registry"},{"type":"autostart","name":"sdk"},{"name":"search"},{"name":"formatter"},{"name":"settings"},{"type":"autostart","name":"host"},{"name":"profiler"},{"type":"autostart","name":"extensions"},{"type":"autostart","name":"common"},{"type":"autostart","name":"workspace"},{"name":"object_ui"},{"name":"changes"},{"type":"autostart","name":"text_utils"}]}
self['Platform']=self['Platform']||{};let ArrayLike;function mod(m,n){return((m%n)+n)%n;}
String.prototype.findAll=function(string){const matches=[];let i=this.indexOf(string);while(i!==-1){matches.push(i);i=this.indexOf(string,i+string.length);}
return matches;};String.prototype.reverse=function(){return this.split('').reverse().join('');};String.prototype.replaceControlCharacters=function(){return this.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u0080-\u009f]/g,'�');};String.prototype.isWhitespace=function(){return/^\s*$/.test(this);};String.prototype.computeLineEndings=function(){const endings=this.findAll('\n');endings.push(this.length);return endings;};String.prototype.escapeCharacters=function(chars){let foundChar=false;for(let i=0;i<chars.length;++i){if(this.indexOf(chars.charAt(i))!==-1){foundChar=true;break;}}
if(!foundChar)
return String(this);let result='';for(let i=0;i<this.length;++i){if(chars.indexOf(this.charAt(i))!==-1)
result+='\\';result+=this.charAt(i);}
return result;};String.regexSpecialCharacters=function(){return'^[]{}()\\.^$*+?|-,';};String.prototype.escapeForRegExp=function(){return this.escapeCharacters(String.regexSpecialCharacters());};String.filterRegex=function(query){const toEscape=String.regexSpecialCharacters();let regexString='';for(let i=0;i<query.length;++i){let c=query.charAt(i);if(toEscape.indexOf(c)!==-1)
c='\\'+c;if(i)
regexString+='[^\\0'+c+']*';regexString+=c;}
return new RegExp(regexString,'i');};String.prototype.escapeHTML=function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');};String.prototype.unescapeHTML=function(){return this.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&#58;/g,':').replace(/&quot;/g,'"').replace(/&#60;/g,'<').replace(/&#62;/g,'>').replace(/&amp;/g,'&');};String.prototype.collapseWhitespace=function(){return this.replace(/[\s\xA0]+/g,' ');};String.prototype.trimMiddle=function(maxLength){if(this.length<=maxLength)
return String(this);let leftHalf=maxLength>>1;let rightHalf=maxLength-leftHalf-1;if(this.codePointAt(this.length-rightHalf-1)>=0x10000){--rightHalf;++leftHalf;}
if(leftHalf>0&&this.codePointAt(leftHalf-1)>=0x10000)
--leftHalf;return this.substr(0,leftHalf)+'\u2026'+this.substr(this.length-rightHalf,rightHalf);};String.prototype.trimEnd=function(maxLength){if(this.length<=maxLength)
return String(this);return this.substr(0,maxLength-1)+'\u2026';};String.prototype.trimURL=function(baseURLDomain){let result=this.replace(/^(https|http|file):\/\//i,'');if(baseURLDomain){if(result.toLowerCase().startsWith(baseURLDomain.toLowerCase()))
result=result.substr(baseURLDomain.length);}
return result;};String.prototype.toTitleCase=function(){return this.substring(0,1).toUpperCase()+this.substring(1);};String.prototype.compareTo=function(other){if(this>other)
return 1;if(this<other)
return-1;return 0;};String.prototype.removeURLFragment=function(){let fragmentIndex=this.indexOf('#');if(fragmentIndex===-1)
fragmentIndex=this.length;return this.substring(0,fragmentIndex);};String.hashCode=function(string){if(!string)
return 0;const p=((1<<30)*4-5);const z=0x5033d967;const z2=0x59d2f15d;let s=0;let zi=1;for(let i=0;i<string.length;i++){const xi=string.charCodeAt(i)*z2;s=(s+zi*xi)%p;zi=(zi*z)%p;}
s=(s+zi*(p-1))%p;return Math.abs(s|0);};String.isDigitAt=function(string,index){const c=string.charCodeAt(index);return(48<=c&&c<=57);};String.prototype.toBase64=function(){function encodeBits(b){return b<26?b+65:b<52?b+71:b<62?b-4:b===62?43:b===63?47:65;}
const encoder=new TextEncoder();const data=encoder.encode(this.toString());const n=data.length;let encoded='';if(n===0)
return encoded;let shift;let v=0;for(let i=0;i<n;i++){shift=i%3;v|=data[i]<<(16>>>shift&24);if(shift===2){encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),encodeBits(v&63));v=0;}}
if(shift===0)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),61,61);else if(shift===1)
encoded+=String.fromCharCode(encodeBits(v>>>18&63),encodeBits(v>>>12&63),encodeBits(v>>>6&63),61);return encoded;};String.naturalOrderComparator=function(a,b){const chunk=/^\d+|^\D+/;let chunka,chunkb,anum,bnum;while(1){if(a){if(!b)
return 1;}else{if(b)
return-1;else
return 0;}
chunka=a.match(chunk)[0];chunkb=b.match(chunk)[0];anum=!isNaN(chunka);bnum=!isNaN(chunkb);if(anum&&!bnum)
return-1;if(bnum&&!anum)
return 1;if(anum&&bnum){const diff=chunka-chunkb;if(diff)
return diff;if(chunka.length!==chunkb.length){if(!+chunka&&!+chunkb)
return chunka.length-chunkb.length;else
return chunkb.length-chunka.length;}}else if(chunka!==chunkb){return(chunka<chunkb)?-1:1;}
a=a.substring(chunka.length);b=b.substring(chunkb.length);}};String.caseInsensetiveComparator=function(a,b){a=a.toUpperCase();b=b.toUpperCase();if(a===b)
return 0;return a>b?1:-1;};Number.constrain=function(num,min,max){if(num<min)
num=min;else if(num>max)
num=max;return num;};Number.gcd=function(a,b){if(b===0)
return a;else
return Number.gcd(b,a%b);};Number.toFixedIfFloating=function(value){if(!value||isNaN(value))
return value;const number=Number(value);return number%1?number.toFixed(3):String(number);};Date.prototype.isValid=function(){return!isNaN(this.getTime());};Date.prototype.toISO8601Compact=function(){function leadZero(x){return(x>9?'':'0')+x;}
return this.getFullYear()+leadZero(this.getMonth()+1)+leadZero(this.getDate())+'T'+
leadZero(this.getHours())+leadZero(this.getMinutes())+leadZero(this.getSeconds());};Object.defineProperty(Array.prototype,'remove',{value:function(value,firstOnly){let index=this.indexOf(value);if(index===-1)
return false;if(firstOnly){this.splice(index,1);return true;}
for(let i=index+1,n=this.length;i<n;++i){if(this[i]!==value)
this[index++]=this[i];}
this.length=index;return true;}});Object.defineProperty(Array.prototype,'pushAll',{value:function(array){for(let i=0;i<array.length;++i)
this.push(array[i]);}});Object.defineProperty(Array.prototype,'rotate',{value:function(index){const result=[];for(let i=index;i<index+this.length;++i)
result.push(this[i%this.length]);return result;}});Object.defineProperty(Array.prototype,'sortNumbers',{value:function(){function numericComparator(a,b){return a-b;}
this.sort(numericComparator);}});Object.defineProperty(Uint32Array.prototype,'sort',{value:Array.prototype.sort});(function(){const partition={value:function(comparator,left,right,pivotIndex){function swap(array,i1,i2){const temp=array[i1];array[i1]=array[i2];array[i2]=temp;}
const pivotValue=this[pivotIndex];swap(this,right,pivotIndex);let storeIndex=left;for(let i=left;i<right;++i){if(comparator(this[i],pivotValue)<0){swap(this,storeIndex,i);++storeIndex;}}
swap(this,right,storeIndex);return storeIndex;}};Object.defineProperty(Array.prototype,'partition',partition);Object.defineProperty(Uint32Array.prototype,'partition',partition);const sortRange={value:function(comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight){function quickSortRange(array,comparator,left,right,sortWindowLeft,sortWindowRight){if(right<=left)
return;const pivotIndex=Math.floor(Math.random()*(right-left))+left;const pivotNewIndex=array.partition(comparator,left,right,pivotIndex);if(sortWindowLeft<pivotNewIndex)
quickSortRange(array,comparator,left,pivotNewIndex-1,sortWindowLeft,sortWindowRight);if(pivotNewIndex<sortWindowRight)
quickSortRange(array,comparator,pivotNewIndex+1,right,sortWindowLeft,sortWindowRight);}
if(leftBound===0&&rightBound===(this.length-1)&&sortWindowLeft===0&&sortWindowRight>=rightBound)
this.sort(comparator);else
quickSortRange(this,comparator,leftBound,rightBound,sortWindowLeft,sortWindowRight);return this;}};Object.defineProperty(Array.prototype,'sortRange',sortRange);Object.defineProperty(Uint32Array.prototype,'sortRange',sortRange);})();Object.defineProperty(Array.prototype,'stableSort',{value:function(comparator){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;const indices=new Array(this.length);for(let i=0;i<this.length;++i)
indices[i]=i;const self=this;function indexComparator(a,b){const result=comparator(self[a],self[b]);return result?result:a-b;}
indices.sort(indexComparator);for(let i=0;i<this.length;++i){if(indices[i]<0||i===indices[i])
continue;let cyclical=i;const saved=this[i];while(true){const next=indices[cyclical];indices[cyclical]=-1;if(next===i){this[cyclical]=saved;break;}else{this[cyclical]=this[next];cyclical=next;}}}
return this;}});Object.defineProperty(Array.prototype,'qselect',{value:function(k,comparator){if(k<0||k>=this.length)
return;if(!comparator){comparator=function(a,b){return a-b;};}
let low=0;let high=this.length-1;for(;;){const pivotPosition=this.partition(comparator,low,high,Math.floor((high+low)/2));if(pivotPosition===k)
return this[k];else if(pivotPosition>k)
high=pivotPosition-1;else
low=pivotPosition+1;}}});Object.defineProperty(Array.prototype,'lowerBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,'upperBound',{value:function(object,comparator,left,right){function defaultComparator(a,b){return a<b?-1:(a>b?1:0);}
comparator=comparator||defaultComparator;let l=left||0;let r=right!==undefined?right:this.length;while(l<r){const m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Uint32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Uint32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Int32Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Int32Array.prototype,'upperBound',{value:Array.prototype.upperBound});Object.defineProperty(Float64Array.prototype,'lowerBound',{value:Array.prototype.lowerBound});Object.defineProperty(Array.prototype,'binaryIndexOf',{value:function(value,comparator){const index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,'select',{value:function(field){const result=new Array(this.length);for(let i=0;i<this.length;++i)
result[i]=this[i][field];return result;}});Object.defineProperty(Array.prototype,'peekLast',{value:function(){return this[this.length-1];}});(function(){function mergeOrIntersect(array1,array2,comparator,mergeNotIntersect){const result=[];let i=0;let j=0;while(i<array1.length&&j<array2.length){const compareValue=comparator(array1[i],array2[j]);if(mergeNotIntersect||!compareValue)
result.push(compareValue<=0?array1[i]:array2[j]);if(compareValue<=0)
i++;if(compareValue>=0)
j++;}
if(mergeNotIntersect){while(i<array1.length)
result.push(array1[i++]);while(j<array2.length)
result.push(array2[j++]);}
return result;}
Object.defineProperty(Array.prototype,'intersectOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,false);}});Object.defineProperty(Array.prototype,'mergeOrdered',{value:function(array,comparator){return mergeOrIntersect(this,array,comparator,true);}});})();String.sprintf=function(format,var_arg){return String.vsprintf(format,Array.prototype.slice.call(arguments,1));};String.tokenizeFormatString=function(format,formatters){const tokens=[];let substitutionIndex=0;function addStringToken(str){if(tokens.length&&tokens[tokens.length-1].type==='string')
tokens[tokens.length-1].value+=str;else
tokens.push({type:'string',value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex){tokens.push({type:'specifier',specifier:specifier,precision:precision,substitutionIndex:substitutionIndex});}
let index=0;for(let precentIndex=format.indexOf('%',index);precentIndex!==-1;precentIndex=format.indexOf('%',index)){if(format.length===index)
break;addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==='%'){addStringToken('%');++index;continue;}
if(String.isDigitAt(format,index)){const number=parseInt(format.substring(index),10);while(String.isDigitAt(format,index))
++index;if(number>0&&format[index]==='$'){substitutionIndex=(number-1);++index;}}
let precision=-1;if(format[index]==='.'){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision))
precision=0;while(String.isDigitAt(format,index))
++index;}
if(!(format[index]in formatters)){addStringToken(format.substring(precentIndex,index+1));++index;continue;}
addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;}
addStringToken(format.substring(index));return tokens;};String.standardFormatters={d:function(substitution){return!isNaN(substitution)?substitution:0;},f:function(substitution,token){if(substitution&&token.precision>-1)
substitution=substitution.toFixed(token.precision);return!isNaN(substitution)?substitution:(token.precision>-1?Number(0).toFixed(token.precision):0);},s:function(substitution){return substitution;}};String.vsprintf=function(format,substitutions){return String.format(format,substitutions,String.standardFormatters,'',function(a,b){return a+b;}).formattedResult;};String.format=function(format,substitutions,formatters,initialValue,append,tokenizedFormat){if(!format||!substitutions||!substitutions.length)
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName(){return'String.format("'+format+'", "'+Array.prototype.join.call(substitutions,'", "')+'")';}
function warn(msg){console.warn(prettyFunctionName()+': '+msg);}
function error(msg){console.error(prettyFunctionName()+': '+msg);}
let result=initialValue;const tokens=tokenizedFormat||String.tokenizeFormatString(format,formatters);const usedSubstitutionIndexes={};for(let i=0;i<tokens.length;++i){const token=tokens[i];if(token.type==='string'){result=append(result,token.value);continue;}
if(token.type!=='specifier'){error('Unknown token type "'+token.type+'" found.');continue;}
if(token.substitutionIndex>=substitutions.length){error('not enough substitution arguments. Had '+substitutions.length+' but needed '+
(token.substitutionIndex+1)+', so substitution was skipped.');result=append(result,'%'+(token.precision>-1?token.precision:'')+token.specifier);continue;}
usedSubstitutionIndexes[token.substitutionIndex]=true;if(!(token.specifier in formatters)){warn('unsupported format character \u201C'+token.specifier+'\u201D. Treating as a string.');result=append(result,substitutions[token.substitutionIndex]);continue;}
result=append(result,formatters[token.specifier](substitutions[token.substitutionIndex],token));}
const unusedSubstitutions=[];for(let i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions:unusedSubstitutions};};function createSearchRegex(query,caseSensitive,isRegex){const regexFlags=caseSensitive?'g':'gi';let regexObject;if(isRegex){try{regexObject=new RegExp(query,regexFlags);}catch(e){}}
if(!regexObject)
regexObject=createPlainTextSearchRegex(query,regexFlags);return regexObject;}
function createPlainTextSearchRegex(query,flags){const regexSpecialCharacters=String.regexSpecialCharacters();let regex='';for(let i=0;i<query.length;++i){const c=query.charAt(i);if(regexSpecialCharacters.indexOf(c)!==-1)
regex+='\\';regex+=c;}
return new RegExp(regex,flags||'');}
function countRegexMatches(regex,content){let text=content;let result=0;let match;while(text&&(match=regex.exec(text))){if(match[0].length>0)
++result;text=text.substring(match.index+1);}
return result;}
function spacesPadding(spacesCount){return'\u00a0'.repeat(spacesCount);}
function numberToStringWithSpacesPadding(value,symbolsCount){const numberString=value.toString();const paddingLength=Math.max(0,symbolsCount-numberString.length);return spacesPadding(paddingLength)+numberString;}
Set.prototype.valuesArray=function(){return Array.from(this.values());};Set.prototype.firstValue=function(){if(!this.size)
return null;return this.values().next().value;};Set.prototype.addAll=function(iterable){for(const e of iterable)
this.add(e);};Set.prototype.containsAll=function(iterable){for(const e of iterable){if(!this.has(e))
return false;}
return true;};Map.prototype.remove=function(key){const value=this.get(key);this.delete(key);return value;};Map.prototype.valuesArray=function(){return Array.from(this.values());};Map.prototype.keysArray=function(){return Array.from(this.keys());};Map.prototype.inverse=function(){const result=new Multimap();for(const key of this.keys()){const value=this.get(key);result.set(value,key);}
return result;};var Multimap=function(){this._map=new Map();};Multimap.prototype={set:function(key,value){let set=this._map.get(key);if(!set){set=new Set();this._map.set(key,set);}
set.add(value);},get:function(key){let result=this._map.get(key);if(!result)
result=new Set();return result;},has:function(key){return this._map.has(key);},hasValue:function(key,value){const set=this._map.get(key);if(!set)
return false;return set.has(value);},get size(){return this._map.size;},delete:function(key,value){const values=this.get(key);if(!values)
return false;const result=values.delete(value);if(!values.size)
this._map.delete(key);return result;},deleteAll:function(key){this._map.delete(key);},keysArray:function(){return this._map.keysArray();},valuesArray:function(){const result=[];const keys=this.keysArray();for(let i=0;i<keys.length;++i)
result.pushAll(this.get(keys[i]).valuesArray());return result;},clear:function(){this._map.clear();}};function loadXHR(url){return new Promise(load);function load(successCallback,failureCallback){function onReadyStateChanged(){if(xhr.readyState!==XMLHttpRequest.DONE)
return;if(xhr.status!==200){xhr.onreadystatechange=null;failureCallback(new Error(xhr.status));return;}
xhr.onreadystatechange=null;successCallback(xhr.responseText);}
const xhr=new XMLHttpRequest();xhr.withCredentials=false;xhr.open('GET',url,true);xhr.onreadystatechange=onReadyStateChanged;xhr.send(null);}}
function suppressUnused(value){}
self.setImmediate=function(callback){const args=[...arguments].slice(1);Promise.resolve().then(()=>callback(...args));return 0;};Promise.prototype.spread=function(callback){return this.then(spreadPromise);function spreadPromise(arg){return callback.apply(null,arg);}};Promise.prototype.catchException=function(defaultValue){return this.catch(function(error){console.error(error);return defaultValue;});};Map.prototype.diff=function(other,isEqual){const leftKeys=this.keysArray();const rightKeys=other.keysArray();leftKeys.sort((a,b)=>a-b);rightKeys.sort((a,b)=>a-b);const removed=[];const added=[];const equal=[];let leftIndex=0;let rightIndex=0;while(leftIndex<leftKeys.length&&rightIndex<rightKeys.length){const leftKey=leftKeys[leftIndex];const rightKey=rightKeys[rightIndex];if(leftKey===rightKey&&isEqual(this.get(leftKey),other.get(rightKey))){equal.push(this.get(leftKey));++leftIndex;++rightIndex;continue;}
if(leftKey<=rightKey){removed.push(this.get(leftKey));++leftIndex;continue;}
added.push(other.get(rightKey));++rightIndex;}
while(leftIndex<leftKeys.length){const leftKey=leftKeys[leftIndex++];removed.push(this.get(leftKey));}
while(rightIndex<rightKeys.length){const rightKey=rightKeys[rightIndex++];added.push(other.get(rightKey));}
return{added:added,removed:removed,equal:equal};};function runOnWindowLoad(callback){function windowLoaded(){self.removeEventListener('DOMContentLoaded',windowLoaded,false);callback();}
if(document.readyState==='complete'||document.readyState==='interactive')
callback();else
self.addEventListener('DOMContentLoaded',windowLoaded,false);}
const _singletonSymbol=Symbol('singleton');function singleton(constructorFunction){if(_singletonSymbol in constructorFunction)
return constructorFunction[_singletonSymbol];const instance=new constructorFunction();constructorFunction[_singletonSymbol]=instance;return instance;};self['DomExtension']=self['DomExtension']||{};Node.prototype.rangeOfWord=function(offset,stopCharacters,stayWithinNode,direction){let startNode;let startOffset=0;let endNode;let endOffset=0;if(!stayWithinNode)
stayWithinNode=this;if(!direction||direction==='backward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!startNode)
startNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?(offset-1):(node.nodeValue.length-1));for(let i=start;i>=0;--i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){startNode=node;startOffset=i+1;break;}}}
if(startNode)
break;node=node.traversePreviousNode(stayWithinNode);}
if(!startNode){startNode=stayWithinNode;startOffset=0;}}else{startNode=this;startOffset=offset;}
if(!direction||direction==='forward'||direction==='both'){let node=this;while(node){if(node===stayWithinNode){if(!endNode)
endNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){const start=(node===this?offset:0);for(let i=start;i<node.nodeValue.length;++i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){endNode=node;endOffset=i;break;}}}
if(endNode)
break;node=node.traverseNextNode(stayWithinNode);}
if(!endNode){endNode=stayWithinNode;endOffset=stayWithinNode.nodeType===Node.TEXT_NODE?stayWithinNode.nodeValue.length:stayWithinNode.childNodes.length;}}else{endNode=this;endOffset=offset;}
const result=this.ownerDocument.createRange();result.setStart(startNode,startOffset);result.setEnd(endNode,endOffset);return result;};Node.prototype.traverseNextTextNode=function(stayWithin){let node=this.traverseNextNode(stayWithin);if(!node)
return null;const nonTextTags={'STYLE':1,'SCRIPT':1};while(node&&(node.nodeType!==Node.TEXT_NODE||nonTextTags[node.parentElement.nodeName]))
node=node.traverseNextNode(stayWithin);return node;};Element.prototype.positionAt=function(x,y,relativeTo){let shift={x:0,y:0};if(relativeTo)
shift=relativeTo.boxInWindow(this.ownerDocument.defaultView);if(typeof x==='number')
this.style.setProperty('left',(shift.x+x)+'px');else
this.style.removeProperty('left');if(typeof y==='number')
this.style.setProperty('top',(shift.y+y)+'px');else
this.style.removeProperty('top');if(typeof x==='number'||typeof y==='number')
this.style.setProperty('position','absolute');else
this.style.removeProperty('position');};Element.prototype.isScrolledToBottom=function(){return Math.abs(this.scrollTop+this.clientHeight-this.scrollHeight)<=2;};Node.prototype.enclosingNodeOrSelfWithNodeNameInArray=function(nameArray){for(let node=this;node&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){for(let i=0;i<nameArray.length;++i){if(node.nodeName.toLowerCase()===nameArray[i].toLowerCase())
return node;}}
return null;};Node.prototype.enclosingNodeOrSelfWithNodeName=function(nodeName){return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);};Node.prototype.enclosingNodeOrSelfWithClass=function(className,stayWithin){return this.enclosingNodeOrSelfWithClassList([className],stayWithin);};Node.prototype.enclosingNodeOrSelfWithClassList=function(classNames,stayWithin){for(let node=this;node&&node!==stayWithin&&node!==this.ownerDocument;node=node.parentNodeOrShadowHost()){if(node.nodeType===Node.ELEMENT_NODE){let containsAll=true;for(let i=0;i<classNames.length&&containsAll;++i){if(!node.classList.contains(classNames[i]))
containsAll=false;}
if(containsAll)
return(node);}}
return null;};Node.prototype.parentElementOrShadowHost=function(){if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return(this.host);const node=this.parentNode;if(!node)
return null;if(node.nodeType===Node.ELEMENT_NODE)
return(node);if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE)
return(node.host);return null;};Node.prototype.parentNodeOrShadowHost=function(){if(this.parentNode)
return this.parentNode;if(this.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&this.host)
return this.host;return null;};Node.prototype.getComponentSelection=function(){let parent=this.parentNode;while(parent&&parent.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)
parent=parent.parentNode;return parent instanceof ShadowRoot?parent.getSelection():this.window().getSelection();};Node.prototype.hasSelection=function(){const contents=this.querySelectorAll('content');for(const content of contents){if(Array.prototype.some.call(content.getDistributedNodes(),node=>node.hasSelection()))
return true;}
const selection=this.getComponentSelection();if(selection.type!=='Range')
return false;return selection.containsNode(this,true)||selection.anchorNode.isSelfOrDescendant(this)||selection.focusNode.isSelfOrDescendant(this);};Node.prototype.window=function(){return(this.ownerDocument.defaultView);};Element.prototype.removeChildren=function(){if(this.firstChild)
this.textContent='';};function createElement(tagName,customElementType){return document.createElement(tagName,customElementType||'');}
function createTextNode(data){return document.createTextNode(data);}
Document.prototype.createElementWithClass=function(elementName,className,customElementType){const element=this.createElement(elementName,customElementType||'');if(className)
element.className=className;return element;};function createElementWithClass(elementName,className,customElementType){return document.createElementWithClass(elementName,className,customElementType);}
Document.prototype.createSVGElement=function(childType,className){const element=this.createElementNS('http://www.w3.org/2000/svg',childType);if(className)
element.setAttribute('class',className);return element;};function createSVGElement(childType,className){return document.createSVGElement(childType,className);}
function createDocumentFragment(){return document.createDocumentFragment();}
Element.prototype.createChild=function(elementName,className,customElementType){const element=this.ownerDocument.createElementWithClass(elementName,className,customElementType);this.appendChild(element);return element;};DocumentFragment.prototype.createChild=Element.prototype.createChild;Element.prototype.createTextChild=function(text){const element=this.ownerDocument.createTextNode(text);this.appendChild(element);return element;};DocumentFragment.prototype.createTextChild=Element.prototype.createTextChild;Element.prototype.createTextChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.createTextChild(arguments[i]);};DocumentFragment.prototype.createTextChildren=Element.prototype.createTextChildren;Element.prototype.totalOffsetLeft=function(){return this.totalOffset().left;};Element.prototype.totalOffsetTop=function(){return this.totalOffset().top;};Element.prototype.totalOffset=function(){const rect=this.getBoundingClientRect();return{left:rect.left,top:rect.top};};Element.prototype.createSVGChild=function(childType,className){const child=this.ownerDocument.createSVGElement(childType,className);this.appendChild(child);return child;};var AnchorBox=class{constructor(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0;}
contains(x,y){return x>=this.x&&x<=this.x+this.width&&y>=this.y&&y<=this.y+this.height;}};AnchorBox.prototype.relativeTo=function(box){return new AnchorBox(this.x-box.x,this.y-box.y,this.width,this.height);};AnchorBox.prototype.relativeToElement=function(element){return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));};AnchorBox.prototype.equals=function(anchorBox){return!!anchorBox&&this.x===anchorBox.x&&this.y===anchorBox.y&&this.width===anchorBox.width&&this.height===anchorBox.height;};Element.prototype.boxInWindow=function(targetWindow){targetWindow=targetWindow||this.ownerDocument.defaultView;const anchorBox=new AnchorBox();let curElement=this;let curWindow=this.ownerDocument.defaultView;while(curWindow&&curElement){anchorBox.x+=curElement.totalOffsetLeft();anchorBox.y+=curElement.totalOffsetTop();if(curWindow===targetWindow)
break;curElement=curWindow.frameElement;curWindow=curWindow.parent;}
anchorBox.width=Math.min(this.offsetWidth,targetWindow.innerWidth-anchorBox.x);anchorBox.height=Math.min(this.offsetHeight,targetWindow.innerHeight-anchorBox.y);return anchorBox;};Event.prototype.consume=function(preventDefault){this.stopImmediatePropagation();if(preventDefault)
this.preventDefault();this.handled=true;};Text.prototype.select=function(start,end){start=start||0;end=end||this.textContent.length;if(start<0)
start=end+start;const selection=this.getComponentSelection();selection.removeAllRanges();const range=this.ownerDocument.createRange();range.setStart(this,start);range.setEnd(this,end);selection.addRange(range);return this;};Element.prototype.selectionLeftOffset=function(){const selection=this.getComponentSelection();if(!selection.containsNode(this,true))
return null;let leftOffset=selection.anchorOffset;let node=selection.anchorNode;while(node!==this){while(node.previousSibling){node=node.previousSibling;leftOffset+=node.textContent.length;}
node=node.parentNodeOrShadowHost();}
return leftOffset;};Node.prototype.appendChildren=function(var_args){for(let i=0,n=arguments.length;i<n;++i)
this.appendChild(arguments[i]);};Node.prototype.deepTextContent=function(){return this.childTextNodes().map(function(node){return node.textContent;}).join('');};Node.prototype.childTextNodes=function(){let node=this.traverseNextTextNode(this);const result=[];const nonTextTags={'STYLE':1,'SCRIPT':1};while(node){if(!nonTextTags[node.parentElement.nodeName])
result.push(node);node=node.traverseNextTextNode(this);}
return result;};Node.prototype.isAncestor=function(node){if(!node)
return false;let currentNode=node.parentNodeOrShadowHost();while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNodeOrShadowHost();}
return false;};Node.prototype.isDescendant=function(descendant){return!!descendant&&descendant.isAncestor(this);};Node.prototype.isSelfOrAncestor=function(node){return!!node&&(node===this||this.isAncestor(node));};Node.prototype.isSelfOrDescendant=function(node){return!!node&&(node===this||this.isDescendant(node));};Node.prototype.traverseNextNode=function(stayWithin){if(this.shadowRoot)
return this.shadowRoot;const distributedNodes=this.getDistributedNodes?this.getDistributedNodes():[];if(distributedNodes.length)
return distributedNodes[0];if(this.firstChild)
return this.firstChild;let node=this;while(node){if(stayWithin&&node===stayWithin)
return null;const sibling=nextSibling(node);if(sibling)
return sibling;node=insertionPoint(node)||node.parentNodeOrShadowHost();}
function nextSibling(node){const parent=insertionPoint(node);if(!parent)
return node.nextSibling;const distributedNodes=parent.getDistributedNodes?parent.getDistributedNodes():[];const position=Array.prototype.indexOf.call(distributedNodes,node);if(position+1<distributedNodes.length)
return distributedNodes[position+1];return null;}
function insertionPoint(node){const insertionPoints=node.getDestinationInsertionPoints?node.getDestinationInsertionPoints():[];return insertionPoints.length>0?insertionPoints[insertionPoints.length-1]:null;}
return null;};Node.prototype.traversePreviousNode=function(stayWithin){if(stayWithin&&this===stayWithin)
return null;let node=this.previousSibling;while(node&&node.lastChild)
node=node.lastChild;if(node)
return node;return this.parentNodeOrShadowHost();};Node.prototype.setTextContentTruncatedIfNeeded=function(text,placeholder){const maxTextContentLength=10000;if(typeof text==='string'&&text.length>maxTextContentLength){this.textContent=typeof placeholder==='string'?placeholder:text.trimMiddle(maxTextContentLength);return true;}
this.textContent=text;return false;};Event.prototype.deepElementFromPoint=function(){if(!this.which&&!this.pageX&&!this.pageY&&!this.clientX&&!this.clientY&&!this.movementX&&!this.movementY)
return null;const root=this.target&&this.target.getComponentRoot();return root?root.deepElementFromPoint(this.pageX,this.pageY):null;};Document.prototype.deepElementFromPoint=function(x,y){let container=this;let node=null;while(container){const innerNode=container.elementFromPoint(x,y);if(!innerNode||node===innerNode)
break;node=innerNode;container=node.shadowRoot;}
return node;};DocumentFragment.prototype.deepElementFromPoint=Document.prototype.deepElementFromPoint;Document.prototype.deepActiveElement=function(){let activeElement=this.activeElement;while(activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement)
activeElement=activeElement.shadowRoot.activeElement;return activeElement;};DocumentFragment.prototype.deepActiveElement=Document.prototype.deepActiveElement;Element.prototype.hasFocus=function(){const root=this.getComponentRoot();return!!root&&this.isSelfOrAncestor(root.activeElement);};Node.prototype.getComponentRoot=function(){let node=this;while(node&&node.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&node.nodeType!==Node.DOCUMENT_NODE)
node=node.parentNode;return(node);};function isEnterKey(event){return event.keyCode!==229&&event.key==='Enter';}
function isEscKey(event){return event.keyCode===27;};self['TextUtils']=self['TextUtils']||{};TextUtils.Text=class{constructor(value){this._value=value;}
lineEndings(){if(!this._lineEndings)
this._lineEndings=this._value.computeLineEndings();return this._lineEndings;}
value(){return this._value;}
lineCount(){const lineEndings=this.lineEndings();return lineEndings.length;}
offsetFromPosition(lineNumber,columnNumber){return(lineNumber?this.lineEndings()[lineNumber-1]+1:0)+columnNumber;}
positionFromOffset(offset){const lineEndings=this.lineEndings();const lineNumber=lineEndings.lowerBound(offset);return{lineNumber:lineNumber,columnNumber:offset-(lineNumber&&(lineEndings[lineNumber-1]+1))};}
lineAt(lineNumber){const lineEndings=this.lineEndings();const lineStart=lineNumber>0?lineEndings[lineNumber-1]+1:0;const lineEnd=lineEndings[lineNumber];let lineContent=this._value.substring(lineStart,lineEnd);if(lineContent.length>0&&lineContent.charAt(lineContent.length-1)==='\r')
lineContent=lineContent.substring(0,lineContent.length-1);return lineContent;}
toSourceRange(range){const start=this.offsetFromPosition(range.startLine,range.startColumn);const end=this.offsetFromPosition(range.endLine,range.endColumn);return new TextUtils.SourceRange(start,end-start);}
toTextRange(sourceRange){const cursor=new TextUtils.TextCursor(this.lineEndings());const result=TextUtils.TextRange.createFromLocation(0,0);cursor.resetTo(sourceRange.offset);result.startLine=cursor.lineNumber();result.startColumn=cursor.columnNumber();cursor.advance(sourceRange.offset+sourceRange.length);result.endLine=cursor.lineNumber();result.endColumn=cursor.columnNumber();return result;}
replaceRange(range,replacement){const sourceRange=this.toSourceRange(range);return this._value.substring(0,sourceRange.offset)+replacement+
this._value.substring(sourceRange.offset+sourceRange.length);}
extract(range){const sourceRange=this.toSourceRange(range);return this._value.substr(sourceRange.offset,sourceRange.length);}};TextUtils.Text.Position;TextUtils.TextCursor=class{constructor(lineEndings){this._lineEndings=lineEndings;this._offset=0;this._lineNumber=0;this._columnNumber=0;}
advance(offset){this._offset=offset;while(this._lineNumber<this._lineEndings.length&&this._lineEndings[this._lineNumber]<this._offset)
++this._lineNumber;this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
offset(){return this._offset;}
resetTo(offset){this._offset=offset;this._lineNumber=this._lineEndings.lowerBound(offset);this._columnNumber=this._lineNumber?this._offset-this._lineEndings[this._lineNumber-1]-1:this._offset;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}};;TextUtils.TextUtils={isStopChar:function(char){return(char>' '&&char<'0')||(char>'9'&&char<'A')||(char>'Z'&&char<'_')||(char>'_'&&char<'a')||(char>'z'&&char<='~');},isWordChar:function(char){return!TextUtils.TextUtils.isStopChar(char)&&!TextUtils.TextUtils.isSpaceChar(char);},isSpaceChar:function(char){return TextUtils.TextUtils._SpaceCharRegex.test(char);},isWord:function(word){for(let i=0;i<word.length;++i){if(!TextUtils.TextUtils.isWordChar(word.charAt(i)))
return false;}
return true;},isOpeningBraceChar:function(char){return char==='('||char==='{';},isClosingBraceChar:function(char){return char===')'||char==='}';},isBraceChar:function(char){return TextUtils.TextUtils.isOpeningBraceChar(char)||TextUtils.TextUtils.isClosingBraceChar(char);},textToWords:function(text,isWordChar,wordCallback){let startWord=-1;for(let i=0;i<text.length;++i){if(!isWordChar(text.charAt(i))){if(startWord!==-1)
wordCallback(text.substring(startWord,i));startWord=-1;}else if(startWord===-1){startWord=i;}}
if(startWord!==-1)
wordCallback(text.substring(startWord));},lineIndent:function(line){let indentation=0;while(indentation<line.length&&TextUtils.TextUtils.isSpaceChar(line.charAt(indentation)))
++indentation;return line.substr(0,indentation);},isUpperCase:function(text){return text===text.toUpperCase();},isLowerCase:function(text){return text===text.toLowerCase();},splitStringByRegexes(text,regexes){const matches=[];const globalRegexes=[];for(let i=0;i<regexes.length;i++){const regex=regexes[i];if(!regex.global)
globalRegexes.push(new RegExp(regex.source,regex.flags?regex.flags+'g':'g'));else
globalRegexes.push(regex);}
doSplit(text,0,0);return matches;function doSplit(text,regexIndex,startIndex){if(regexIndex>=globalRegexes.length){matches.push({value:text,position:startIndex,regexIndex:-1,captureGroups:[]});return;}
const regex=globalRegexes[regexIndex];let currentIndex=0;let result;regex.lastIndex=0;while((result=regex.exec(text))!==null){const stringBeforeMatch=text.substring(currentIndex,result.index);if(stringBeforeMatch)
doSplit(stringBeforeMatch,regexIndex+1,startIndex+currentIndex);const match=result[0];matches.push({value:match,position:startIndex+result.index,regexIndex:regexIndex,captureGroups:result.slice(1)});currentIndex=result.index+match.length;}
const stringAfterMatches=text.substring(currentIndex);if(stringAfterMatches)
doSplit(stringAfterMatches,regexIndex+1,startIndex+currentIndex);}}};TextUtils.FilterParser=class{constructor(keys){this._keys=keys;}
static cloneFilter(filter){return{key:filter.key,text:filter.text,regex:filter.regex,negative:filter.negative};}
parse(query){const splitResult=TextUtils.TextUtils.splitStringByRegexes(query,[TextUtils.TextUtils._keyValueFilterRegex,TextUtils.TextUtils._regexFilterRegex,TextUtils.TextUtils._textFilterRegex]);const filters=[];for(let i=0;i<splitResult.length;i++){const regexIndex=splitResult[i].regexIndex;if(regexIndex===-1)
continue;const result=splitResult[i].captureGroups;if(regexIndex===0){if(this._keys.indexOf((result[1]))!==-1)
filters.push({key:result[1],text:result[2],negative:!!result[0]});else
filters.push({text:result[1]+':'+result[2],negative:!!result[0]});}else if(regexIndex===1){try{filters.push({regex:new RegExp(result[1],'i'),negative:!!result[0]});}catch(e){filters.push({text:'/'+result[1]+'/',negative:!!result[0]});}}else if(regexIndex===2){filters.push({text:result[1],negative:!!result[0]});}}
return filters;}};TextUtils.FilterParser.ParsedFilter;TextUtils.TextUtils._keyValueFilterRegex=/(?:^|\s)(\-)?([\w\-]+):([^\s]+)/;TextUtils.TextUtils._regexFilterRegex=/(?:^|\s)(\-)?\/([^\s]+)\//;TextUtils.TextUtils._textFilterRegex=/(?:^|\s)(\-)?([^\s]+)/;TextUtils.TextUtils._SpaceCharRegex=/\s/;TextUtils.TextUtils.Indent={TwoSpaces:'  ',FourSpaces:'    ',EightSpaces:'        ',TabCharacter:'\t'};TextUtils.TextUtils.BalancedJSONTokenizer=class{constructor(callback,findMultiple){this._callback=callback;this._index=0;this._balance=0;this._buffer='';this._findMultiple=findMultiple||false;this._closingDoubleQuoteRegex=/[^\\](?:\\\\)*"/g;}
write(chunk){this._buffer+=chunk;const lastIndex=this._buffer.length;const buffer=this._buffer;let index;for(index=this._index;index<lastIndex;++index){const character=buffer[index];if(character==='"'){this._closingDoubleQuoteRegex.lastIndex=index;if(!this._closingDoubleQuoteRegex.test(buffer))
break;index=this._closingDoubleQuoteRegex.lastIndex-1;}else if(character==='{'){++this._balance;}else if(character==='}'){--this._balance;if(this._balance<0){this._reportBalanced();return false;}
if(!this._balance){this._lastBalancedIndex=index+1;if(!this._findMultiple)
break;}}else if(character===']'&&!this._balance){this._reportBalanced();return false;}}
this._index=index;this._reportBalanced();return true;}
_reportBalanced(){if(!this._lastBalancedIndex)
return;this._callback(this._buffer.slice(0,this._lastBalancedIndex));this._buffer=this._buffer.slice(this._lastBalancedIndex);this._index-=this._lastBalancedIndex;this._lastBalancedIndex=0;}
remainder(){return this._buffer;}};TextUtils.TokenizerFactory=function(){};TextUtils.TokenizerFactory.prototype={createTokenizer(mimeType){}};TextUtils.isMinified=function(text){const kMaxNonMinifiedLength=500;let linesToCheck=10;let lastPosition=0;do{let eolIndex=text.indexOf('\n',lastPosition);if(eolIndex<0)
eolIndex=text.length;if(eolIndex-lastPosition>kMaxNonMinifiedLength&&text.substr(lastPosition,3)!=='//#')
return true;lastPosition=eolIndex+1;}while(--linesToCheck>=0&&lastPosition<text.length);return false;};;TextUtils.TextRange=class{constructor(startLine,startColumn,endLine,endColumn){this.startLine=startLine;this.startColumn=startColumn;this.endLine=endLine;this.endColumn=endColumn;}
static createFromLocation(line,column){return new TextUtils.TextRange(line,column,line,column);}
static fromObject(serializedTextRange){return new TextUtils.TextRange(serializedTextRange.startLine,serializedTextRange.startColumn,serializedTextRange.endLine,serializedTextRange.endColumn);}
static comparator(range1,range2){return range1.compareTo(range2);}
static fromEdit(oldRange,newText){let endLine=oldRange.startLine;let endColumn=oldRange.startColumn+newText.length;const lineEndings=newText.computeLineEndings();if(lineEndings.length>1){endLine=oldRange.startLine+lineEndings.length-1;const len=lineEndings.length;endColumn=lineEndings[len-1]-lineEndings[len-2]-1;}
return new TextUtils.TextRange(oldRange.startLine,oldRange.startColumn,endLine,endColumn);}
isEmpty(){return this.startLine===this.endLine&&this.startColumn===this.endColumn;}
immediatelyPrecedes(range){if(!range)
return false;return this.endLine===range.startLine&&this.endColumn===range.startColumn;}
immediatelyFollows(range){if(!range)
return false;return range.immediatelyPrecedes(this);}
follows(range){return(range.endLine===this.startLine&&range.endColumn<=this.startColumn)||range.endLine<this.startLine;}
get linesCount(){return this.endLine-this.startLine;}
collapseToEnd(){return new TextUtils.TextRange(this.endLine,this.endColumn,this.endLine,this.endColumn);}
collapseToStart(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.startLine,this.startColumn);}
normalize(){if(this.startLine>this.endLine||(this.startLine===this.endLine&&this.startColumn>this.endColumn))
return new TextUtils.TextRange(this.endLine,this.endColumn,this.startLine,this.startColumn);else
return this.clone();}
clone(){return new TextUtils.TextRange(this.startLine,this.startColumn,this.endLine,this.endColumn);}
serializeToObject(){const serializedTextRange={};serializedTextRange.startLine=this.startLine;serializedTextRange.startColumn=this.startColumn;serializedTextRange.endLine=this.endLine;serializedTextRange.endColumn=this.endColumn;return serializedTextRange;}
compareTo(other){if(this.startLine>other.startLine)
return 1;if(this.startLine<other.startLine)
return-1;if(this.startColumn>other.startColumn)
return 1;if(this.startColumn<other.startColumn)
return-1;return 0;}
compareToPosition(lineNumber,columnNumber){if(lineNumber<this.startLine||(lineNumber===this.startLine&&columnNumber<this.startColumn))
return-1;if(lineNumber>this.endLine||(lineNumber===this.endLine&&columnNumber>this.endColumn))
return 1;return 0;}
equal(other){return this.startLine===other.startLine&&this.endLine===other.endLine&&this.startColumn===other.startColumn&&this.endColumn===other.endColumn;}
relativeTo(line,column){const relative=this.clone();if(this.startLine===line)
relative.startColumn-=column;if(this.endLine===line)
relative.endColumn-=column;relative.startLine-=line;relative.endLine-=line;return relative;}
relativeFrom(line,column){const relative=this.clone();if(this.startLine===0)
relative.startColumn+=column;if(this.endLine===0)
relative.endColumn+=column;relative.startLine+=line;relative.endLine+=line;return relative;}
rebaseAfterTextEdit(originalRange,editedRange){console.assert(originalRange.startLine===editedRange.startLine);console.assert(originalRange.startColumn===editedRange.startColumn);const rebase=this.clone();if(!this.follows(originalRange))
return rebase;const lineDelta=editedRange.endLine-originalRange.endLine;const columnDelta=editedRange.endColumn-originalRange.endColumn;rebase.startLine+=lineDelta;rebase.endLine+=lineDelta;if(rebase.startLine===editedRange.endLine)
rebase.startColumn+=columnDelta;if(rebase.endLine===editedRange.endLine)
rebase.endColumn+=columnDelta;return rebase;}
toString(){return JSON.stringify(this);}
containsLocation(lineNumber,columnNumber){if(this.startLine===this.endLine)
return this.startLine===lineNumber&&this.startColumn<=columnNumber&&columnNumber<=this.endColumn;if(this.startLine===lineNumber)
return this.startColumn<=columnNumber;if(this.endLine===lineNumber)
return columnNumber<=this.endColumn;return this.startLine<lineNumber&&lineNumber<this.endLine;}};TextUtils.SourceRange=class{constructor(offset,length){this.offset=offset;this.length=length;}};TextUtils.SourceEdit=class{constructor(sourceURL,oldRange,newText){this.sourceURL=sourceURL;this.oldRange=oldRange;this.newText=newText;}
static comparator(edit1,edit2){return TextUtils.TextRange.comparator(edit1.oldRange,edit2.oldRange);}
newRange(){return TextUtils.TextRange.fromEdit(this.oldRange,this.newText);}};;self['Common']=self['Common']||{};Common.Worker=class{constructor(appName){let url=appName+'.js';url+=Runtime.queryParamsString();this._workerPromise=new Promise(fulfill=>{this._worker=new Worker(url);this._worker.onmessage=onMessage.bind(this);function onMessage(event){console.assert(event.data==='workerReady');this._worker.onmessage=null;fulfill(this._worker);this._worker=null;}});}
postMessage(message){this._workerPromise.then(worker=>{if(!this._disposed)
worker.postMessage(message);});}
dispose(){this._disposed=true;this._workerPromise.then(worker=>worker.terminate());}
terminate(){this.dispose();}
set onmessage(listener){this._workerPromise.then(worker=>worker.onmessage=listener);}
set onerror(listener){this._workerPromise.then(worker=>worker.onerror=listener);}};;Common.TextDictionary=class{constructor(){this._words=new Map();this._index=new Common.Trie();}
addWord(word){let count=this._words.get(word)||0;++count;this._words.set(word,count);this._index.add(word);}
removeWord(word){let count=this._words.get(word)||0;if(!count)
return;if(count===1){this._words.delete(word);this._index.remove(word);return;}
--count;this._words.set(word,count);}
wordsWithPrefix(prefix){return this._index.words(prefix);}
hasWord(word){return this._words.has(word);}
wordCount(word){return this._words.get(word)||0;}
reset(){this._words.clear();this._index.clear();}};;Common.Object=class{constructor(){this._listeners;}
addEventListener(eventType,listener,thisObject){if(!listener)
console.assert(false);if(!this._listeners)
this._listeners=new Map();if(!this._listeners.has(eventType))
this._listeners.set(eventType,[]);this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};}
once(eventType){return new Promise(resolve=>{const descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});}
removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType))
return;const listeners=this._listeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject){listeners[i].disposed=true;listeners.splice(i--,1);}}
if(!listeners.length)
this._listeners.delete(eventType);}
hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));}
dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType))
return;const event=({data:eventData});const listeners=this._listeners.get(eventType).slice(0);for(let i=0;i<listeners.length;++i){if(!listeners[i].disposed)
listeners[i].listener.call(listeners[i].thisObject,event);}}};Common.Event;Common.Object._listenerCallbackTuple;Common.EventTarget=function(){};Common.EventTarget.EventDescriptor;Common.EventTarget.removeEventListeners=function(eventList){for(let i=0;i<eventList.length;++i){const eventInfo=eventList[i];eventInfo.eventTarget.removeEventListener(eventInfo.eventType,eventInfo.listener,eventInfo.thisObject);}
eventList.splice(0,eventList.length);};Common.EventTarget.prototype={addEventListener(eventType,listener,thisObject){},once(eventType){},removeEventListener(eventType,listener,thisObject){},hasEventListeners(eventType){},dispatchEventToListeners(eventType,eventData){},};;Common.Color=class{constructor(rgba,format,originalText){this._rgba=rgba;this._originalText=originalText||null;this._originalTextIsValid=!!this._originalText;this._format=format;if(typeof this._rgba[3]==='undefined')
this._rgba[3]=1;for(let i=0;i<4;++i){if(this._rgba[i]<0){this._rgba[i]=0;this._originalTextIsValid=false;}
if(this._rgba[i]>1){this._rgba[i]=1;this._originalTextIsValid=false;}}}
static parse(text){const value=text.toLowerCase().replace(/\s+/g,'');const simple=/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(\w+))$/i;let match=value.match(simple);if(match){if(match[1]){let hex=match[1].toLowerCase();let format;if(hex.length===3){format=Common.Color.Format.ShortHEX;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2);}else if(hex.length===4){format=Common.Color.Format.ShortHEXA;hex=hex.charAt(0)+hex.charAt(0)+hex.charAt(1)+hex.charAt(1)+hex.charAt(2)+hex.charAt(2)+
hex.charAt(3)+hex.charAt(3);}else if(hex.length===6){format=Common.Color.Format.HEX;}else{format=Common.Color.Format.HEXA;}
const r=parseInt(hex.substring(0,2),16);const g=parseInt(hex.substring(2,4),16);const b=parseInt(hex.substring(4,6),16);let a=1;if(hex.length===8)
a=parseInt(hex.substring(6,8),16)/255;return new Common.Color([r/255,g/255,b/255,a],format,text);}
if(match[2]){const nickname=match[2].toLowerCase();if(nickname in Common.Color.Nicknames){const rgba=Common.Color.Nicknames[nickname];const color=Common.Color.fromRGBA(rgba);color._format=Common.Color.Format.Nickname;color._originalText=text;return color;}
return null;}
return null;}
match=text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);if(match){const components=match[3].trim();let values=components.split(/\s*,\s*/);if(values.length===1){values=components.split(/\s+/);if(values[3]==='/'){values.splice(3,1);if(values.length!==4)
return null;}else if((values.length>2&&values[2].indexOf('/')!==-1)||(values.length>3&&values[3].indexOf('/')!==-1)){const alpha=values.slice(2,4).join('');values=values.slice(0,2).concat(alpha.split(/\//)).concat(values.slice(4));}else if(values.length>=4){return null;}}
if(values.length!==3&&values.length!==4||values.indexOf('')>-1)
return null;const hasAlpha=(values[3]!==undefined);if(match[1]){const rgba=[Common.Color._parseRgbNumeric(values[0]),Common.Color._parseRgbNumeric(values[1]),Common.Color._parseRgbNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(rgba.indexOf(null)>-1)
return null;return new Common.Color(rgba,hasAlpha?Common.Color.Format.RGBA:Common.Color.Format.RGB,text);}
if(match[2]){const hsla=[Common.Color._parseHueNumeric(values[0]),Common.Color._parseSatLightNumeric(values[1]),Common.Color._parseSatLightNumeric(values[2]),hasAlpha?Common.Color._parseAlphaNumeric(values[3]):1];if(hsla.indexOf(null)>-1)
return null;const rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,hasAlpha?Common.Color.Format.HSLA:Common.Color.Format.HSL,text);}}
return null;}
static fromRGBA(rgba){return new Common.Color([rgba[0]/255,rgba[1]/255,rgba[2]/255,rgba[3]],Common.Color.Format.RGBA);}
static fromHSVA(hsva){const rgba=[];Common.Color.hsva2rgba(hsva,rgba);return new Common.Color(rgba,Common.Color.Format.HSLA);}
static _parsePercentOrNumber(value){if(isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);if(value.indexOf('%')!==-1){if(value.indexOf('%')!==value.length-1)
return null;return parsed/100;}
return parsed;}
static _parseRgbNumeric(value){const parsed=Common.Color._parsePercentOrNumber(value);if(parsed===null)
return null;if(value.indexOf('%')!==-1)
return parsed;return parsed/255;}
static _parseHueNumeric(value){const angle=value.replace(/(deg|g?rad|turn)$/,'');if(isNaN(angle)||value.match(/\s+(deg|g?rad|turn)/))
return null;const number=parseFloat(angle);if(value.indexOf('turn')!==-1)
return number%1;else if(value.indexOf('grad')!==-1)
return(number/400)%1;else if(value.indexOf('rad')!==-1)
return(number/(2*Math.PI))%1;return(number/360)%1;}
static _parseSatLightNumeric(value){if(value.indexOf('%')!==value.length-1||isNaN(value.replace('%','')))
return null;const parsed=parseFloat(value);return Math.min(1,parsed/100);}
static _parseAlphaNumeric(value){return Common.Color._parsePercentOrNumber(value);}
static _hsva2hsla(hsva,out_hsla){const h=hsva[0];let s=hsva[1];const v=hsva[2];const t=(2-s)*v;if(v===0||s===0)
s=0;else
s*=v/(t<1?t:2-t);out_hsla[0]=h;out_hsla[1]=s;out_hsla[2]=t/2;out_hsla[3]=hsva[3];}
static hsl2rgb(hsl,out_rgb){const h=hsl[0];let s=hsl[1];const l=hsl[2];function hue2rgb(p,q,h){if(h<0)
h+=1;else if(h>1)
h-=1;if((h*6)<1)
return p+(q-p)*h*6;else if((h*2)<1)
return q;else if((h*3)<2)
return p+(q-p)*((2/3)-h)*6;else
return p;}
if(s<0)
s=0;let q;if(l<=0.5)
q=l*(1+s);else
q=l+s-(l*s);const p=2*l-q;const tr=h+(1/3);const tg=h;const tb=h-(1/3);out_rgb[0]=hue2rgb(p,q,tr);out_rgb[1]=hue2rgb(p,q,tg);out_rgb[2]=hue2rgb(p,q,tb);out_rgb[3]=hsl[3];}
static hsva2rgba(hsva,out_rgba){Common.Color._hsva2hsla(hsva,Common.Color.hsva2rgba._tmpHSLA);Common.Color.hsl2rgb(Common.Color.hsva2rgba._tmpHSLA,out_rgba);for(let i=0;i<Common.Color.hsva2rgba._tmpHSLA.length;i++)
Common.Color.hsva2rgba._tmpHSLA[i]=0;}
static luminance(rgba){const rSRGB=rgba[0];const gSRGB=rgba[1];const bSRGB=rgba[2];const r=rSRGB<=0.03928?rSRGB/12.92:Math.pow(((rSRGB+0.055)/1.055),2.4);const g=gSRGB<=0.03928?gSRGB/12.92:Math.pow(((gSRGB+0.055)/1.055),2.4);const b=bSRGB<=0.03928?bSRGB/12.92:Math.pow(((bSRGB+0.055)/1.055),2.4);return 0.2126*r+0.7152*g+0.0722*b;}
static blendColors(fgRGBA,bgRGBA,out_blended){const alpha=fgRGBA[3];out_blended[0]=((1-alpha)*bgRGBA[0])+(alpha*fgRGBA[0]);out_blended[1]=((1-alpha)*bgRGBA[1])+(alpha*fgRGBA[1]);out_blended[2]=((1-alpha)*bgRGBA[2])+(alpha*fgRGBA[2]);out_blended[3]=alpha+(bgRGBA[3]*(1-alpha));}
static calculateContrastRatio(fgRGBA,bgRGBA){Common.Color.blendColors(fgRGBA,bgRGBA,Common.Color.calculateContrastRatio._blendedFg);const fgLuminance=Common.Color.luminance(Common.Color.calculateContrastRatio._blendedFg);const bgLuminance=Common.Color.luminance(bgRGBA);const contrastRatio=(Math.max(fgLuminance,bgLuminance)+0.05)/(Math.min(fgLuminance,bgLuminance)+0.05);for(let i=0;i<Common.Color.calculateContrastRatio._blendedFg.length;i++)
Common.Color.calculateContrastRatio._blendedFg[i]=0;return contrastRatio;}
static desiredLuminance(luminance,contrast,lighter){function computeLuminance(){if(lighter)
return(luminance+0.05)*contrast-0.05;else
return(luminance+0.05)/contrast-0.05;}
let desiredLuminance=computeLuminance();if(desiredLuminance<0||desiredLuminance>1){lighter=!lighter;desiredLuminance=computeLuminance();}
return desiredLuminance;}
static detectColorFormat(color){const cf=Common.Color.Format;let format;const formatSetting=Common.moduleSetting('colorFormat').get();if(formatSetting===cf.Original)
format=cf.Original;else if(formatSetting===cf.RGB)
format=(color.hasAlpha()?cf.RGBA:cf.RGB);else if(formatSetting===cf.HSL)
format=(color.hasAlpha()?cf.HSLA:cf.HSL);else if(formatSetting===cf.HEX)
format=color.detectHEXFormat();else
format=cf.RGBA;return format;}
format(){return this._format;}
hsla(){if(this._hsla)
return this._hsla;const r=this._rgba[0];const g=this._rgba[1];const b=this._rgba[2];const max=Math.max(r,g,b);const min=Math.min(r,g,b);const diff=max-min;const add=max+min;let h;if(min===max)
h=0;else if(r===max)
h=((1/6*(g-b)/diff)+1)%1;else if(g===max)
h=(1/6*(b-r)/diff)+1/3;else
h=(1/6*(r-g)/diff)+2/3;const l=0.5*add;let s;if(l===0)
s=0;else if(l===1)
s=0;else if(l<=0.5)
s=diff/add;else
s=diff/(2-add);this._hsla=[h,s,l,this._rgba[3]];return this._hsla;}
canonicalHSLA(){const hsla=this.hsla();return[Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]];}
hsva(){const hsla=this.hsla();const h=hsla[0];let s=hsla[1];const l=hsla[2];s*=l<0.5?l:1-l;return[h,s!==0?2*s/(l+s):0,(l+s),hsla[3]];}
hasAlpha(){return this._rgba[3]!==1;}
detectHEXFormat(){let canBeShort=true;for(let i=0;i<4;++i){const c=Math.round(this._rgba[i]*255);if(c%17){canBeShort=false;break;}}
const hasAlpha=this.hasAlpha();const cf=Common.Color.Format;if(canBeShort)
return hasAlpha?cf.ShortHEXA:cf.ShortHEX;return hasAlpha?cf.HEXA:cf.HEX;}
asString(format){if(format===this._format&&this._originalTextIsValid)
return this._originalText;if(!format)
format=this._format;function toRgbValue(value){return Math.round(value*255);}
function toHexValue(value){const hex=Math.round(value*255).toString(16);return hex.length===1?'0'+hex:hex;}
function toShortHexValue(value){return(Math.round(value*255)/17).toString(16);}
switch(format){case Common.Color.Format.Original:return this._originalText;case Common.Color.Format.RGB:if(this.hasAlpha())
return null;return String.sprintf('rgb(%d, %d, %d)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]));case Common.Color.Format.RGBA:return String.sprintf('rgba(%d, %d, %d, %f)',toRgbValue(this._rgba[0]),toRgbValue(this._rgba[1]),toRgbValue(this._rgba[2]),this._rgba[3]);case Common.Color.Format.HSL:if(this.hasAlpha())
return null;const hsl=this.hsla();return String.sprintf('hsl(%d, %d%, %d%)',Math.round(hsl[0]*360),Math.round(hsl[1]*100),Math.round(hsl[2]*100));case Common.Color.Format.HSLA:const hsla=this.hsla();return String.sprintf('hsla(%d, %d%, %d%, %f)',Math.round(hsla[0]*360),Math.round(hsla[1]*100),Math.round(hsla[2]*100),hsla[3]);case Common.Color.Format.HEXA:return String.sprintf('#%s%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2]),toHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.HEX:if(this.hasAlpha())
return null;return String.sprintf('#%s%s%s',toHexValue(this._rgba[0]),toHexValue(this._rgba[1]),toHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.ShortHEXA:const hexFormat=this.detectHEXFormat();if(hexFormat!==Common.Color.Format.ShortHEXA&&hexFormat!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2]),toShortHexValue(this._rgba[3])).toLowerCase();case Common.Color.Format.ShortHEX:if(this.hasAlpha())
return null;if(this.detectHEXFormat()!==Common.Color.Format.ShortHEX)
return null;return String.sprintf('#%s%s%s',toShortHexValue(this._rgba[0]),toShortHexValue(this._rgba[1]),toShortHexValue(this._rgba[2])).toLowerCase();case Common.Color.Format.Nickname:return this.nickname();}
return this._originalText;}
rgba(){return this._rgba.slice();}
canonicalRGBA(){const rgba=new Array(4);for(let i=0;i<3;++i)
rgba[i]=Math.round(this._rgba[i]*255);rgba[3]=this._rgba[3];return rgba;}
nickname(){if(!Common.Color._rgbaToNickname){Common.Color._rgbaToNickname={};for(const nickname in Common.Color.Nicknames){let rgba=Common.Color.Nicknames[nickname];if(rgba.length!==4)
rgba=rgba.concat(1);Common.Color._rgbaToNickname[rgba]=nickname;}}
return Common.Color._rgbaToNickname[this.canonicalRGBA()]||null;}
toProtocolRGBA(){const rgba=this.canonicalRGBA();const result={r:rgba[0],g:rgba[1],b:rgba[2]};if(rgba[3]!==1)
result.a=rgba[3];return result;}
invert(){const rgba=[];rgba[0]=1-this._rgba[0];rgba[1]=1-this._rgba[1];rgba[2]=1-this._rgba[2];rgba[3]=this._rgba[3];return new Common.Color(rgba,Common.Color.Format.RGBA);}
setAlpha(alpha){const rgba=this._rgba.slice();rgba[3]=alpha;return new Common.Color(rgba,Common.Color.Format.RGBA);}
blendWith(fgColor){const rgba=[];Common.Color.blendColors(fgColor._rgba,this._rgba,rgba);return new Common.Color(rgba,Common.Color.Format.RGBA);}};Common.Color.Regex=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;Common.Color.Format={Original:'original',Nickname:'nickname',HEX:'hex',ShortHEX:'shorthex',HEXA:'hexa',ShortHEXA:'shorthexa',RGB:'rgb',RGBA:'rgba',HSL:'hsl',HSLA:'hsla'};Common.Color.hsva2rgba._tmpHSLA=[0,0,0,0];Common.Color.calculateContrastRatio._blendedFg=[0,0,0,0];Common.Color.Nicknames={'aliceblue':[240,248,255],'antiquewhite':[250,235,215],'aqua':[0,255,255],'aquamarine':[127,255,212],'azure':[240,255,255],'beige':[245,245,220],'bisque':[255,228,196],'black':[0,0,0],'blanchedalmond':[255,235,205],'blue':[0,0,255],'blueviolet':[138,43,226],'brown':[165,42,42],'burlywood':[222,184,135],'cadetblue':[95,158,160],'chartreuse':[127,255,0],'chocolate':[210,105,30],'coral':[255,127,80],'cornflowerblue':[100,149,237],'cornsilk':[255,248,220],'crimson':[237,20,61],'cyan':[0,255,255],'darkblue':[0,0,139],'darkcyan':[0,139,139],'darkgoldenrod':[184,134,11],'darkgray':[169,169,169],'darkgrey':[169,169,169],'darkgreen':[0,100,0],'darkkhaki':[189,183,107],'darkmagenta':[139,0,139],'darkolivegreen':[85,107,47],'darkorange':[255,140,0],'darkorchid':[153,50,204],'darkred':[139,0,0],'darksalmon':[233,150,122],'darkseagreen':[143,188,143],'darkslateblue':[72,61,139],'darkslategray':[47,79,79],'darkslategrey':[47,79,79],'darkturquoise':[0,206,209],'darkviolet':[148,0,211],'deeppink':[255,20,147],'deepskyblue':[0,191,255],'dimgray':[105,105,105],'dimgrey':[105,105,105],'dodgerblue':[30,144,255],'firebrick':[178,34,34],'floralwhite':[255,250,240],'forestgreen':[34,139,34],'fuchsia':[255,0,255],'gainsboro':[220,220,220],'ghostwhite':[248,248,255],'gold':[255,215,0],'goldenrod':[218,165,32],'gray':[128,128,128],'grey':[128,128,128],'green':[0,128,0],'greenyellow':[173,255,47],'honeydew':[240,255,240],'hotpink':[255,105,180],'indianred':[205,92,92],'indigo':[75,0,130],'ivory':[255,255,240],'khaki':[240,230,140],'lavender':[230,230,250],'lavenderblush':[255,240,245],'lawngreen':[124,252,0],'lemonchiffon':[255,250,205],'lightblue':[173,216,230],'lightcoral':[240,128,128],'lightcyan':[224,255,255],'lightgoldenrodyellow':[250,250,210],'lightgreen':[144,238,144],'lightgray':[211,211,211],'lightgrey':[211,211,211],'lightpink':[255,182,193],'lightsalmon':[255,160,122],'lightseagreen':[32,178,170],'lightskyblue':[135,206,250],'lightslategray':[119,136,153],'lightslategrey':[119,136,153],'lightsteelblue':[176,196,222],'lightyellow':[255,255,224],'lime':[0,255,0],'limegreen':[50,205,50],'linen':[250,240,230],'magenta':[255,0,255],'maroon':[128,0,0],'mediumaquamarine':[102,205,170],'mediumblue':[0,0,205],'mediumorchid':[186,85,211],'mediumpurple':[147,112,219],'mediumseagreen':[60,179,113],'mediumslateblue':[123,104,238],'mediumspringgreen':[0,250,154],'mediumturquoise':[72,209,204],'mediumvioletred':[199,21,133],'midnightblue':[25,25,112],'mintcream':[245,255,250],'mistyrose':[255,228,225],'moccasin':[255,228,181],'navajowhite':[255,222,173],'navy':[0,0,128],'oldlace':[253,245,230],'olive':[128,128,0],'olivedrab':[107,142,35],'orange':[255,165,0],'orangered':[255,69,0],'orchid':[218,112,214],'palegoldenrod':[238,232,170],'palegreen':[152,251,152],'paleturquoise':[175,238,238],'palevioletred':[219,112,147],'papayawhip':[255,239,213],'peachpuff':[255,218,185],'peru':[205,133,63],'pink':[255,192,203],'plum':[221,160,221],'powderblue':[176,224,230],'purple':[128,0,128],'rebeccapurple':[102,51,153],'red':[255,0,0],'rosybrown':[188,143,143],'royalblue':[65,105,225],'saddlebrown':[139,69,19],'salmon':[250,128,114],'sandybrown':[244,164,96],'seagreen':[46,139,87],'seashell':[255,245,238],'sienna':[160,82,45],'silver':[192,192,192],'skyblue':[135,206,235],'slateblue':[106,90,205],'slategray':[112,128,144],'slategrey':[112,128,144],'snow':[255,250,250],'springgreen':[0,255,127],'steelblue':[70,130,180],'tan':[210,180,140],'teal':[0,128,128],'thistle':[216,191,216],'tomato':[255,99,71],'turquoise':[64,224,208],'violet':[238,130,238],'wheat':[245,222,179],'white':[255,255,255],'whitesmoke':[245,245,245],'yellow':[255,255,0],'yellowgreen':[154,205,50],'transparent':[0,0,0,0],};Common.Color.PageHighlight={Content:Common.Color.fromRGBA([111,168,220,.66]),ContentLight:Common.Color.fromRGBA([111,168,220,.5]),ContentOutline:Common.Color.fromRGBA([9,83,148]),Padding:Common.Color.fromRGBA([147,196,125,.55]),PaddingLight:Common.Color.fromRGBA([147,196,125,.4]),Border:Common.Color.fromRGBA([255,229,153,.66]),BorderLight:Common.Color.fromRGBA([255,229,153,.5]),Margin:Common.Color.fromRGBA([246,178,107,.66]),MarginLight:Common.Color.fromRGBA([246,178,107,.5]),EventTarget:Common.Color.fromRGBA([255,196,196,.66]),Shape:Common.Color.fromRGBA([96,82,177,0.8]),ShapeMargin:Common.Color.fromRGBA([96,82,127,.6]),CssGrid:Common.Color.fromRGBA([0x4b,0,0x82,1])};Common.Color.Generator=class{constructor(hueSpace,satSpace,lightnessSpace,alphaSpace){this._hueSpace=hueSpace||{min:0,max:360};this._satSpace=satSpace||67;this._lightnessSpace=lightnessSpace||80;this._alphaSpace=alphaSpace||1;this._colors=new Map();}
setColorForID(id,color){this._colors.set(id,color);}
colorForID(id){let color=this._colors.get(id);if(!color){color=this._generateColorForID(id);this._colors.set(id,color);}
return color;}
_generateColorForID(id){const hash=String.hashCode(id);const h=this._indexToValueInSpace(hash,this._hueSpace);const s=this._indexToValueInSpace(hash>>8,this._satSpace);const l=this._indexToValueInSpace(hash>>16,this._lightnessSpace);const a=this._indexToValueInSpace(hash>>24,this._alphaSpace);return`hsla(${h}, ${s}%, ${l}%, ${a})`;}
_indexToValueInSpace(index,space){if(typeof space==='number')
return space;const count=space.count||space.max-space.min;index%=count;return space.min+Math.floor(index/(count-1)*(space.max-space.min));}};;Common.Console=class extends Common.Object{constructor(){super();this._messages=[];}
addMessage(text,level,show){const message=new Common.Console.Message(text,level||Common.Console.MessageLevel.Info,Date.now(),show||false);this._messages.push(message);this.dispatchEventToListeners(Common.Console.Events.MessageAdded,message);}
log(text){this.addMessage(text,Common.Console.MessageLevel.Info);}
warn(text){this.addMessage(text,Common.Console.MessageLevel.Warning);}
error(text){this.addMessage(text,Common.Console.MessageLevel.Error,true);}
messages(){return this._messages;}
show(){this.showPromise();}
showPromise(){return Common.Revealer.reveal(this);}};Common.Console.Events={MessageAdded:Symbol('messageAdded')};Common.Console.MessageLevel={Info:'info',Warning:'warning',Error:'error'};Common.Console.Message=class{constructor(text,level,timestamp,show){this.text=text;this.level=level;this.timestamp=(typeof timestamp==='number')?timestamp:Date.now();this.show=show;}};Common.console=new Common.Console();;Common.ContentProvider=function(){};Common.ContentProvider.prototype={contentURL(){},contentType(){},contentEncoded(){},requestContent(){},searchInContent(query,caseSensitive,isRegex){}};Common.ContentProvider.SearchMatch=class{constructor(lineNumber,lineContent){this.lineNumber=lineNumber;this.lineContent=lineContent;}};Common.ContentProvider.performSearchInContent=function(content,query,caseSensitive,isRegex){const regex=createSearchRegex(query,caseSensitive,isRegex);const text=new TextUtils.Text(content);const result=[];for(let i=0;i<text.lineCount();++i){const lineContent=text.lineAt(i);regex.lastIndex=0;if(regex.exec(lineContent))
result.push(new Common.ContentProvider.SearchMatch(i,lineContent));}
return result;};Common.ContentProvider.contentAsDataURL=function(content,mimeType,contentEncoded,charset){const maxDataUrlSize=1024*1024;if(content===null||content.length>maxDataUrlSize)
return null;return'data:'+mimeType+(charset?';charset='+charset:'')+(contentEncoded?';base64':'')+','+
content;};;Common.ParsedURL=class{constructor(url){this.isValid=false;this.url=url;this.scheme='';this.user='';this.host='';this.port='';this.path='';this.queryParams='';this.fragment='';this.folderPathComponents='';this.lastPathComponent='';const match=url.match(Common.ParsedURL._urlRegex());if(match){this.isValid=true;this.scheme=match[2].toLowerCase();this.user=match[3];this.host=match[4];this.port=match[5];this.path=match[6]||'/';this.queryParams=match[7]||'';this.fragment=match[8];}else{if(this.url.startsWith('data:')){this.scheme='data';return;}
if(this.url==='about:blank'){this.scheme='about';return;}
this.path=this.url;}
const lastSlashIndex=this.path.lastIndexOf('/');if(lastSlashIndex!==-1){this.folderPathComponents=this.path.substring(0,lastSlashIndex);this.lastPathComponent=this.path.substring(lastSlashIndex+1);}else{this.lastPathComponent=this.path;}}
static platformPathToURL(fileSystemPath){fileSystemPath=fileSystemPath.replace(/\\/g,'/');if(!fileSystemPath.startsWith('file://')){if(fileSystemPath.startsWith('/'))
fileSystemPath='file://'+fileSystemPath;else
fileSystemPath='file:///'+fileSystemPath;}
return fileSystemPath;}
static urlToPlatformPath(fileURL,isWindows){console.assert(fileURL.startsWith('file://'),'This must be a file URL.');if(isWindows)
return fileURL.substr('file:///'.length).replace(/\//g,'\\');return fileURL.substr('file://'.length);}
static urlWithoutHash(url){const hashIndex=url.indexOf('#');if(hashIndex!==-1)
return url.substr(0,hashIndex);return url;}
static _urlRegex(){if(Common.ParsedURL._urlRegexInstance)
return Common.ParsedURL._urlRegexInstance;const schemeRegex=/([A-Za-z][A-Za-z0-9+.-]*):\/\//;const userRegex=/(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;const hostRegex=/((?:\[::\d?\])|(?:[^\s\/:]*))/;const portRegex=/(?::([\d]+))?/;const pathRegex=/(\/[^#?]*)?/;const queryRegex=/(?:\?([^#]*))?/;const fragmentRegex=/(?:#(.*))?/;Common.ParsedURL._urlRegexInstance=new RegExp('^('+schemeRegex.source+userRegex.source+hostRegex.source+portRegex.source+')'+pathRegex.source+
queryRegex.source+fragmentRegex.source+'$');return Common.ParsedURL._urlRegexInstance;}
static extractPath(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.path:'';}
static extractOrigin(url){const parsedURL=url.asParsedURL();return parsedURL?parsedURL.securityOrigin():'';}
static extractExtension(url){url=Common.ParsedURL.urlWithoutHash(url);const indexOfQuestionMark=url.indexOf('?');if(indexOfQuestionMark!==-1)
url=url.substr(0,indexOfQuestionMark);const lastIndexOfSlash=url.lastIndexOf('/');if(lastIndexOfSlash!==-1)
url=url.substr(lastIndexOfSlash+1);const lastIndexOfDot=url.lastIndexOf('.');if(lastIndexOfDot!==-1){url=url.substr(lastIndexOfDot+1);const lastIndexOfPercent=url.indexOf('%');if(lastIndexOfPercent!==-1)
return url.substr(0,lastIndexOfPercent);return url;}
return'';}
static extractName(url){let index=url.lastIndexOf('/');const pathAndQuery=index!==-1?url.substr(index+1):url;index=pathAndQuery.indexOf('?');return index<0?pathAndQuery:pathAndQuery.substr(0,index);}
static completeURL(baseURL,href){const trimmedHref=href.trim();if(trimmedHref.startsWith('data:')||trimmedHref.startsWith('blob:')||trimmedHref.startsWith('javascript:'))
return href;const parsedHref=trimmedHref.asParsedURL();if(parsedHref&&parsedHref.scheme)
return trimmedHref;const parsedURL=baseURL.asParsedURL();if(!parsedURL)
return null;if(parsedURL.isDataURL())
return href;if(href.length>1&&href.charAt(0)==='/'&&href.charAt(1)==='/'){return parsedURL.scheme+':'+href;}
const securityOrigin=parsedURL.securityOrigin();const pathText=parsedURL.path;const queryText=parsedURL.queryParams?'?'+parsedURL.queryParams:'';if(!href.length)
return securityOrigin+pathText+queryText;if(href.charAt(0)==='#')
return securityOrigin+pathText+queryText+href;if(href.charAt(0)==='?')
return securityOrigin+pathText+href;let hrefPath=href.match(/^[^#?]*/)[0];const hrefSuffix=href.substring(hrefPath.length);if(hrefPath.charAt(0)!=='/')
hrefPath=parsedURL.folderPathComponents+'/'+hrefPath;return securityOrigin+Runtime.normalizePath(hrefPath)+hrefSuffix;}
static splitLineAndColumn(string){const beforePathMatch=string.match(Common.ParsedURL._urlRegex());let beforePath='';let pathAndAfter=string;if(beforePathMatch){beforePath=beforePathMatch[1];pathAndAfter=string.substring(beforePathMatch[1].length);}
const lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;const lineColumnMatch=lineColumnRegEx.exec(pathAndAfter);let lineNumber;let columnNumber;console.assert(lineColumnMatch);if(typeof(lineColumnMatch[1])==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}
if(typeof(lineColumnMatch[2])==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}
return{url:beforePath+pathAndAfter.substring(0,pathAndAfter.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}
static isRelativeURL(url){return!(/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url));}
get displayName(){if(this._displayName)
return this._displayName;if(this.isDataURL())
return this.dataURLDisplayName();if(this.isAboutBlank())
return this.url;this._displayName=this.lastPathComponent;if(!this._displayName)
this._displayName=(this.host||'')+'/';if(this._displayName==='/')
this._displayName=this.url;return this._displayName;}
dataURLDisplayName(){if(this._dataURLDisplayName)
return this._dataURLDisplayName;if(!this.isDataURL())
return'';this._dataURLDisplayName=this.url.trimEnd(20);return this._dataURLDisplayName;}
isAboutBlank(){return this.url==='about:blank';}
isDataURL(){return this.scheme==='data';}
lastPathComponentWithFragment(){return this.lastPathComponent+(this.fragment?'#'+this.fragment:'');}
domain(){if(this.isDataURL())
return'data:';return this.host+(this.port?':'+this.port:'');}
securityOrigin(){if(this.isDataURL())
return'data:';return this.scheme+'://'+this.domain();}
urlWithoutScheme(){if(this.scheme&&this.url.startsWith(this.scheme+'://'))
return this.url.substring(this.scheme.length+3);return this.url;}};String.prototype.asParsedURL=function(){const parsedURL=new Common.ParsedURL(this.toString());if(parsedURL.isValid)
return parsedURL;return null;};;Common.Progress=function(){};Common.Progress.prototype={setTotalWork(totalWork){},setTitle(title){},setWorked(worked,title){},worked(worked){},done(){},isCanceled(){return false;},};Common.CompositeProgress=class{constructor(parent){this._parent=parent;this._children=[];this._childrenDone=0;this._parent.setTotalWork(1);this._parent.setWorked(0);}
_childDone(){if(++this._childrenDone!==this._children.length)
return;this._parent.done();}
createSubProgress(weight){const child=new Common.SubProgress(this,weight);this._children.push(child);return child;}
_update(){let totalWeights=0;let done=0;for(let i=0;i<this._children.length;++i){const child=this._children[i];if(child._totalWork)
done+=child._weight*child._worked/child._totalWork;totalWeights+=child._weight;}
this._parent.setWorked(done/totalWeights);}};Common.SubProgress=class{constructor(composite,weight){this._composite=composite;this._weight=weight||1;this._worked=0;}
isCanceled(){return this._composite._parent.isCanceled();}
setTitle(title){this._composite._parent.setTitle(title);}
done(){this.setWorked(this._totalWork);this._composite._childDone();}
setTotalWork(totalWork){this._totalWork=totalWork;this._composite._update();}
setWorked(worked,title){this._worked=worked;if(typeof title!=='undefined')
this.setTitle(title);this._composite._update();}
worked(worked){this.setWorked(this._worked+(worked||1));}};Common.ProgressProxy=class{constructor(delegate,doneCallback){this._delegate=delegate;this._doneCallback=doneCallback;}
isCanceled(){return this._delegate?this._delegate.isCanceled():false;}
setTitle(title){if(this._delegate)
this._delegate.setTitle(title);}
done(){if(this._delegate)
this._delegate.done();if(this._doneCallback)
this._doneCallback();}
setTotalWork(totalWork){if(this._delegate)
this._delegate.setTotalWork(totalWork);}
setWorked(worked,title){if(this._delegate)
this._delegate.setWorked(worked,title);}
worked(worked){if(this._delegate)
this._delegate.worked(worked);}};;Common.ResourceType=class{constructor(name,title,category,isTextType){this._name=name;this._title=title;this._category=category;this._isTextType=isTextType;}
static fromMimeType(mimeType){if(mimeType.startsWith('text/html'))
return Common.resourceTypes.Document;if(mimeType.startsWith('text/css'))
return Common.resourceTypes.Stylesheet;if(mimeType.startsWith('image/'))
return Common.resourceTypes.Image;if(mimeType.startsWith('text/'))
return Common.resourceTypes.Script;if(mimeType.includes('font'))
return Common.resourceTypes.Font;if(mimeType.includes('script'))
return Common.resourceTypes.Script;if(mimeType.includes('octet'))
return Common.resourceTypes.Other;if(mimeType.includes('application'))
return Common.resourceTypes.Script;return Common.resourceTypes.Other;}
static fromURL(url){return Common.ResourceType._resourceTypeByExtension.get(Common.ParsedURL.extractExtension(url))||null;}
static mimeFromURL(url){const name=Common.ParsedURL.extractName(url);if(Common.ResourceType._mimeTypeByName.has(name))
return Common.ResourceType._mimeTypeByName.get(name);const ext=Common.ParsedURL.extractExtension(url).toLowerCase();return Common.ResourceType._mimeTypeByExtension.get(ext);}
name(){return this._name;}
title(){return this._title;}
category(){return this._category;}
isTextType(){return this._isTextType;}
isScript(){return this._name==='script'||this._name==='sm-script'||this._name==='snippet';}
hasScripts(){return this.isScript()||this.isDocument();}
isStyleSheet(){return this._name==='stylesheet'||this._name==='sm-stylesheet';}
isDocument(){return this._name==='document';}
isDocumentOrScriptOrStyleSheet(){return this.isDocument()||this.isScript()||this.isStyleSheet();}
isFromSourceMap(){return this._name.startsWith('sm-');}
toString(){return this._name;}
canonicalMimeType(){if(this.isDocument())
return'text/html';if(this.isScript())
return'text/javascript';if(this.isStyleSheet())
return'text/css';return'';}};Common.ResourceCategory=class{constructor(title,shortTitle){this.title=title;this.shortTitle=shortTitle;}};Common.resourceCategories={XHR:new Common.ResourceCategory('XHR and Fetch','XHR'),Script:new Common.ResourceCategory('Scripts','JS'),Stylesheet:new Common.ResourceCategory('Stylesheets','CSS'),Image:new Common.ResourceCategory('Images','Img'),Media:new Common.ResourceCategory('Media','Media'),Font:new Common.ResourceCategory('Fonts','Font'),Document:new Common.ResourceCategory('Documents','Doc'),WebSocket:new Common.ResourceCategory('WebSockets','WS'),Manifest:new Common.ResourceCategory('Manifest','Manifest'),Other:new Common.ResourceCategory('Other','Other')};Common.resourceTypes={XHR:new Common.ResourceType('xhr','XHR',Common.resourceCategories.XHR,true),Fetch:new Common.ResourceType('fetch','Fetch',Common.resourceCategories.XHR,true),EventSource:new Common.ResourceType('eventsource','EventSource',Common.resourceCategories.XHR,true),Script:new Common.ResourceType('script','Script',Common.resourceCategories.Script,true),Snippet:new Common.ResourceType('snippet','Snippet',Common.resourceCategories.Script,true),Stylesheet:new Common.ResourceType('stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Image:new Common.ResourceType('image','Image',Common.resourceCategories.Image,false),Media:new Common.ResourceType('media','Media',Common.resourceCategories.Media,false),Font:new Common.ResourceType('font','Font',Common.resourceCategories.Font,false),Document:new Common.ResourceType('document','Document',Common.resourceCategories.Document,true),TextTrack:new Common.ResourceType('texttrack','TextTrack',Common.resourceCategories.Other,true),WebSocket:new Common.ResourceType('websocket','WebSocket',Common.resourceCategories.WebSocket,false),Other:new Common.ResourceType('other','Other',Common.resourceCategories.Other,false),SourceMapScript:new Common.ResourceType('sm-script','Script',Common.resourceCategories.Script,true),SourceMapStyleSheet:new Common.ResourceType('sm-stylesheet','Stylesheet',Common.resourceCategories.Stylesheet,true),Manifest:new Common.ResourceType('manifest','Manifest',Common.resourceCategories.Manifest,true),};Common.ResourceType._mimeTypeByName=new Map([['Cakefile','text/x-coffeescript']]);Common.ResourceType._resourceTypeByExtension=new Map([['js',Common.resourceTypes.Script],['css',Common.resourceTypes.Stylesheet],['xsl',Common.resourceTypes.Stylesheet],['jpeg',Common.resourceTypes.Image],['jpg',Common.resourceTypes.Image],['svg',Common.resourceTypes.Image],['gif',Common.resourceTypes.Image],['png',Common.resourceTypes.Image],['ico',Common.resourceTypes.Image],['tiff',Common.resourceTypes.Image],['tif',Common.resourceTypes.Image],['bmp',Common.resourceTypes.Image],['webp',Common.resourceTypes.Media],['ttf',Common.resourceTypes.Font],['otf',Common.resourceTypes.Font],['ttc',Common.resourceTypes.Font],['woff',Common.resourceTypes.Font]]);Common.ResourceType._mimeTypeByExtension=new Map([['js','text/javascript'],['css','text/css'],['html','text/html'],['htm','text/html'],['mjs','text/javascript'],['xml','application/xml'],['xsl','application/xml'],['asp','application/x-aspx'],['aspx','application/x-aspx'],['jsp','application/x-jsp'],['c','text/x-c++src'],['cc','text/x-c++src'],['cpp','text/x-c++src'],['h','text/x-c++src'],['m','text/x-c++src'],['mm','text/x-c++src'],['coffee','text/x-coffeescript'],['dart','text/javascript'],['ts','text/typescript'],['tsx','text/typescript'],['json','application/json'],['gyp','application/json'],['gypi','application/json'],['cs','text/x-csharp'],['java','text/x-java'],['less','text/x-less'],['php','text/x-php'],['phtml','application/x-httpd-php'],['py','text/x-python'],['sh','text/x-sh'],['scss','text/x-scss'],['vtt','text/vtt'],['ls','text/x-livescript'],['md','text/markdown'],['cljs','text/x-clojure'],['cljc','text/x-clojure'],['cljx','text/x-clojure'],['styl','text/x-styl'],['jsx','text/jsx'],['jpeg','image/jpeg'],['jpg','image/jpeg'],['svg','image/svg+xml'],['gif','image/gif'],['webp','image/webp'],['png','image/png'],['ico','image/ico'],['tiff','image/tiff'],['tif','image/tif'],['bmp','image/bmp'],['ttf','font/opentype'],['otf','font/opentype'],['ttc','font/opentype'],['woff','application/font-woff']]);;Common.Settings=class{constructor(globalStorage,localStorage){this._globalStorage=globalStorage;this._localStorage=localStorage;this._sessionStorage=new Common.SettingsStorage({});this._eventSupport=new Common.Object();this._registry=new Map();this._moduleSettings=new Map();self.runtime.extensions('setting').forEach(this._registerModuleSetting.bind(this));}
_registerModuleSetting(extension){const descriptor=extension.descriptor();const settingName=descriptor['settingName'];const isRegex=descriptor['settingType']==='regex';const defaultValue=descriptor['defaultValue'];let storageType;switch(descriptor['storageType']){case('local'):storageType=Common.SettingStorageType.Local;break;case('session'):storageType=Common.SettingStorageType.Session;break;case('global'):storageType=Common.SettingStorageType.Global;break;default:storageType=Common.SettingStorageType.Global;}
const setting=isRegex?this.createRegExpSetting(settingName,defaultValue,undefined,storageType):this.createSetting(settingName,defaultValue,storageType);if(descriptor['title'])
setting.setTitle(descriptor['title']);if(descriptor['userActionCondition'])
setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition']));setting._extension=extension;this._moduleSettings.set(settingName,setting);}
moduleSetting(settingName){const setting=this._moduleSettings.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
settingForTest(settingName){const setting=this._registry.get(settingName);if(!setting)
throw new Error('No setting registered: '+settingName);return setting;}
createSetting(key,defaultValue,storageType){const storage=this._storageFromType(storageType);if(!this._registry.get(key))
this._registry.set(key,new Common.Setting(this,key,defaultValue,this._eventSupport,storage));return(this._registry.get(key));}
createLocalSetting(key,defaultValue){return this.createSetting(key,defaultValue,Common.SettingStorageType.Local);}
createRegExpSetting(key,defaultValue,regexFlags,storageType){if(!this._registry.get(key)){this._registry.set(key,new Common.RegExpSetting(this,key,defaultValue,this._eventSupport,this._storageFromType(storageType),regexFlags));}
return(this._registry.get(key));}
clearAll(){this._globalStorage.removeAll();this._localStorage.removeAll();const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);versionSetting.set(Common.VersionController.currentVersion);}
_storageFromType(storageType){switch(storageType){case(Common.SettingStorageType.Local):return this._localStorage;case(Common.SettingStorageType.Session):return this._sessionStorage;case(Common.SettingStorageType.Global):return this._globalStorage;}
return this._globalStorage;}};Common.SettingsStorage=class{constructor(object,setCallback,removeCallback,removeAllCallback,storagePrefix){this._object=object;this._setCallback=setCallback||function(){};this._removeCallback=removeCallback||function(){};this._removeAllCallback=removeAllCallback||function(){};this._storagePrefix=storagePrefix||'';}
set(name,value){name=this._storagePrefix+name;this._object[name]=value;this._setCallback(name,value);}
has(name){name=this._storagePrefix+name;return name in this._object;}
get(name){name=this._storagePrefix+name;return this._object[name];}
remove(name){name=this._storagePrefix+name;delete this._object[name];this._removeCallback(name);}
removeAll(){this._object={};this._removeAllCallback();}
_dumpSizes(){Common.console.log('Ten largest settings: ');const sizes={__proto__:null};for(const key in this._object)
sizes[key]=this._object[key].length;const keys=Object.keys(sizes);function comparator(key1,key2){return sizes[key2]-sizes[key1];}
keys.sort(comparator);for(let i=0;i<10&&i<keys.length;++i)
Common.console.log('Setting: \''+keys[i]+'\', size: '+sizes[keys[i]]);}};Common.Setting=class{constructor(settings,name,defaultValue,eventSupport,storage){this._settings=settings;this._name=name;this._defaultValue=defaultValue;this._eventSupport=eventSupport;this._storage=storage;this._title='';this._extension=null;}
addChangeListener(listener,thisObject){this._eventSupport.addEventListener(this._name,listener,thisObject);}
removeChangeListener(listener,thisObject){this._eventSupport.removeEventListener(this._name,listener,thisObject);}
get name(){return this._name;}
title(){return this._title;}
setTitle(title){this._title=title;}
setRequiresUserAction(requiresUserAction){this._requiresUserAction=requiresUserAction;}
get(){if(this._requiresUserAction&&!this._hadUserAction)
return this._defaultValue;if(typeof this._value!=='undefined')
return this._value;this._value=this._defaultValue;if(this._storage.has(this._name)){try{this._value=JSON.parse(this._storage.get(this._name));}catch(e){this._storage.remove(this._name);}}
return this._value;}
set(value){this._hadUserAction=true;this._value=value;try{const settingString=JSON.stringify(value);try{this._storage.set(this._name,settingString);}catch(e){this._printSettingsSavingError(e.message,this._name,settingString);}}catch(e){Common.console.error('Cannot stringify setting with name: '+this._name+', error: '+e.message);}
this._eventSupport.dispatchEventToListeners(this._name,value);}
remove(){this._settings._registry.delete(this._name);this._settings._moduleSettings.delete(this._name);this._storage.remove(this._name);}
extension(){return this._extension;}
_printSettingsSavingError(message,name,value){const errorMessage='Error saving setting with name: '+this._name+', value length: '+value.length+'. Error: '+message;console.error(errorMessage);Common.console.error(errorMessage);this._storage._dumpSizes();}};Common.RegExpSetting=class extends Common.Setting{constructor(settings,name,defaultValue,eventSupport,storage,regexFlags){super(settings,name,defaultValue?[{pattern:defaultValue}]:[],eventSupport,storage);this._regexFlags=regexFlags;}
get(){const result=[];const items=this.getAsArray();for(let i=0;i<items.length;++i){const item=items[i];if(item.pattern&&!item.disabled)
result.push(item.pattern);}
return result.join('|');}
getAsArray(){return super.get();}
set(value){this.setAsArray([{pattern:value}]);}
setAsArray(value){delete this._regex;super.set(value);}
asRegExp(){if(typeof this._regex!=='undefined')
return this._regex;this._regex=null;try{const pattern=this.get();if(pattern)
this._regex=new RegExp(pattern,this._regexFlags||'');}catch(e){}
return this._regex;}};Common.VersionController=class{updateVersion(){const localStorageVersion=window.localStorage?window.localStorage[Common.VersionController._currentVersionName]:0;const versionSetting=Common.settings.createSetting(Common.VersionController._currentVersionName,0);const currentVersion=Common.VersionController.currentVersion;const oldVersion=versionSetting.get()||parseInt(localStorageVersion||'0',10);if(oldVersion===0){versionSetting.set(currentVersion);return;}
const methodsToRun=this._methodsToRunToUpdateVersion(oldVersion,currentVersion);for(let i=0;i<methodsToRun.length;++i)
this[methodsToRun[i]].call(this);versionSetting.set(currentVersion);}
_methodsToRunToUpdateVersion(oldVersion,currentVersion){const result=[];for(let i=oldVersion;i<currentVersion;++i)
result.push('_updateVersionFrom'+i+'To'+(i+1));return result;}
_updateVersionFrom0To1(){this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints',[]),500000);}
_updateVersionFrom1To2(){Common.settings.createSetting('previouslyViewedFiles',[]).set([]);}
_updateVersionFrom2To3(){Common.settings.createSetting('fileSystemMapping',{}).set({});Common.settings.createSetting('fileMappingEntries',[]).remove();}
_updateVersionFrom3To4(){const advancedMode=Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties',false);Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());advancedMode.remove();}
_updateVersionFrom4To5(){const settingNames={'FileSystemViewSidebarWidth':'fileSystemViewSplitViewState','elementsSidebarWidth':'elementsPanelSplitViewState','StylesPaneSplitRatio':'stylesPaneSplitViewState','heapSnapshotRetainersViewSize':'heapSnapshotSplitViewState','InspectorView.splitView':'InspectorView.splitViewState','InspectorView.screencastSplitView':'InspectorView.screencastSplitViewState','Inspector.drawerSplitView':'Inspector.drawerSplitViewState','layerDetailsSplitView':'layerDetailsSplitViewState','networkSidebarWidth':'networkPanelSplitViewState','sourcesSidebarWidth':'sourcesPanelSplitViewState','scriptsPanelNavigatorSidebarWidth':'sourcesPanelNavigatorSplitViewState','sourcesPanelSplitSidebarRatio':'sourcesPanelDebuggerSidebarSplitViewState','timeline-details':'timelinePanelDetailsSplitViewState','timeline-split':'timelinePanelRecorsSplitViewState','timeline-view':'timelinePanelTimelineStackSplitViewState','auditsSidebarWidth':'auditsPanelSplitViewState','layersSidebarWidth':'layersPanelSplitViewState','profilesSidebarWidth':'profilesPanelSplitViewState','resourcesSidebarWidth':'resourcesPanelSplitViewState'};const empty={};for(const oldName in settingNames){const newName=settingNames[oldName];const oldNameH=oldName+'H';let newValue=null;const oldSetting=Common.settings.createSetting(oldName,empty);if(oldSetting.get()!==empty){newValue=newValue||{};newValue.vertical={};newValue.vertical.size=oldSetting.get();oldSetting.remove();}
const oldSettingH=Common.settings.createSetting(oldNameH,empty);if(oldSettingH.get()!==empty){newValue=newValue||{};newValue.horizontal={};newValue.horizontal.size=oldSettingH.get();oldSettingH.remove();}
if(newValue)
Common.settings.createSetting(newName,{}).set(newValue);}}
_updateVersionFrom5To6(){const settingNames={'debuggerSidebarHidden':'sourcesPanelSplitViewState','navigatorHidden':'sourcesPanelNavigatorSplitViewState','WebInspector.Drawer.showOnLoad':'Inspector.drawerSplitViewState'};for(const oldName in settingNames){const oldSetting=Common.settings.createSetting(oldName,null);if(oldSetting.get()===null){oldSetting.remove();continue;}
const newName=settingNames[oldName];const invert=oldName==='WebInspector.Drawer.showOnLoad';const hidden=oldSetting.get()!==invert;oldSetting.remove();const showMode=hidden?'OnlyMain':'Both';const newSetting=Common.settings.createSetting(newName,{});const newValue=newSetting.get()||{};newValue.vertical=newValue.vertical||{};newValue.vertical.showMode=showMode;newValue.horizontal=newValue.horizontal||{};newValue.horizontal.showMode=showMode;newSetting.set(newValue);}}
_updateVersionFrom6To7(){const settingNames={'sourcesPanelNavigatorSplitViewState':'sourcesPanelNavigatorSplitViewState','elementsPanelSplitViewState':'elementsPanelSplitViewState','stylesPaneSplitViewState':'stylesPaneSplitViewState','sourcesPanelDebuggerSidebarSplitViewState':'sourcesPanelDebuggerSidebarSplitViewState'};const empty={};for(const name in settingNames){const setting=Common.settings.createSetting(name,empty);const value=setting.get();if(value===empty)
continue;if(value.vertical&&value.vertical.size&&value.vertical.size<1)
value.vertical.size=0;if(value.horizontal&&value.horizontal.size&&value.horizontal.size<1)
value.horizontal.size=0;setting.set(value);}}
_updateVersionFrom7To8(){}
_updateVersionFrom8To9(){const settingNames=['skipStackFramesPattern','workspaceFolderExcludePattern'];for(let i=0;i<settingNames.length;++i){const setting=Common.settings.createSetting(settingNames[i],'');let value=setting.get();if(!value)
return;if(typeof value==='string')
value=[value];for(let j=0;j<value.length;++j){if(typeof value[j]==='string')
value[j]={pattern:value[j]};}
setting.set(value);}}
_updateVersionFrom9To10(){if(!window.localStorage)
return;for(const key in window.localStorage){if(key.startsWith('revision-history'))
window.localStorage.removeItem(key);}}
_updateVersionFrom10To11(){const oldSettingName='customDevicePresets';const newSettingName='customEmulatedDeviceList';const oldSetting=Common.settings.createSetting(oldSettingName,undefined);const list=oldSetting.get();if(!Array.isArray(list))
return;const newList=[];for(let i=0;i<list.length;++i){const value=list[i];const device={};device['title']=value['title'];device['type']='unknown';device['user-agent']=value['userAgent'];device['capabilities']=[];if(value['touch'])
device['capabilities'].push('touch');if(value['mobile'])
device['capabilities'].push('mobile');device['screen']={};device['screen']['vertical']={width:value['width'],height:value['height']};device['screen']['horizontal']={width:value['height'],height:value['width']};device['screen']['device-pixel-ratio']=value['deviceScaleFactor'];device['modes']=[];device['show-by-default']=true;device['show']='Default';newList.push(device);}
if(newList.length)
Common.settings.createSetting(newSettingName,[]).set(newList);oldSetting.remove();}
_updateVersionFrom11To12(){this._migrateSettingsFromLocalStorage();}
_updateVersionFrom12To13(){this._migrateSettingsFromLocalStorage();Common.settings.createSetting('timelineOverviewMode','').remove();}
_updateVersionFrom13To14(){const defaultValue={'throughput':-1,'latency':0};Common.settings.createSetting('networkConditions',defaultValue).set(defaultValue);}
_updateVersionFrom14To15(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const fileSystemPath in oldValue){newValue[fileSystemPath]=[];for(const entry of oldValue[fileSystemPath])
newValue[fileSystemPath].push(entry.path);}
setting.set(newValue);}
_updateVersionFrom15To16(){const setting=Common.settings.createSetting('InspectorView.panelOrder',{});const tabOrders=setting.get();for(const key of Object.keys(tabOrders))
tabOrders[key]=(tabOrders[key]+1)*10;setting.set(tabOrders);}
_updateVersionFrom16To17(){const setting=Common.settings.createSetting('networkConditionsCustomProfiles',[]);const oldValue=setting.get();const newValue=[];if(Array.isArray(oldValue)){for(const preset of oldValue){if(typeof preset.title==='string'&&typeof preset.value==='object'&&typeof preset.value.throughput==='number'&&typeof preset.value.latency==='number'){newValue.push({title:preset.title,value:{download:preset.value.throughput,upload:preset.value.throughput,latency:preset.value.latency}});}}}
setting.set(newValue);}
_updateVersionFrom17To18(){const setting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});const oldValue=setting.get();const newValue={};for(const oldKey in oldValue){let newKey=oldKey.replace(/\\/g,'/');if(!newKey.startsWith('file://')){if(newKey.startsWith('/'))
newKey='file://'+newKey;else
newKey='file:///'+newKey;}
newValue[newKey]=oldValue[oldKey];}
setting.set(newValue);}
_updateVersionFrom18To19(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const visibleColumnSettings=Common.settings.createSetting('networkLogColumnsVisibility',defaultColumns);const visibleColumns=visibleColumnSettings.get();visibleColumns.name=true;visibleColumns.timeline=true;const configs={};for(const columnId in visibleColumns){if(!visibleColumns.hasOwnProperty(columnId))
continue;configs[columnId.toLowerCase()]={visible:visibleColumns[columnId]};}
const newSetting=Common.settings.createSetting('networkLogColumns',{});newSetting.set(configs);visibleColumnSettings.remove();}
_updateVersionFrom19To20(){const oldSetting=Common.settings.createSetting('InspectorView.panelOrder',{});const newSetting=Common.settings.createSetting('panel-tabOrder',{});newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom20To21(){const networkColumns=Common.settings.createSetting('networkLogColumns',{});const columns=(networkColumns.get());delete columns['timeline'];delete columns['waterfall'];networkColumns.set(columns);}
_updateVersionFrom21To22(){const breakpointsSetting=Common.settings.createLocalSetting('breakpoints',[]);const breakpoints=breakpointsSetting.get();for(const breakpoint of breakpoints){breakpoint['url']=breakpoint['sourceFileId'];delete breakpoint['sourceFileId'];}
breakpointsSetting.set(breakpoints);}
_updateVersionFrom22To23(){}
_updateVersionFrom23To24(){const oldSetting=Common.settings.createSetting('searchInContentScripts',false);const newSetting=Common.settings.createSetting('searchInAnonymousAndContentScripts',false);newSetting.set(oldSetting.get());oldSetting.remove();}
_updateVersionFrom24To25(){const defaultColumns={status:true,type:true,initiator:true,size:true,time:true};const networkLogColumnsSetting=Common.settings.createSetting('networkLogColumns',defaultColumns);const columns=networkLogColumnsSetting.get();delete columns.product;networkLogColumnsSetting.set(columns);}
_migrateSettingsFromLocalStorage(){const localSettings=new Set(['advancedSearchConfig','breakpoints','consoleHistory','domBreakpoints','eventListenerBreakpoints','fileSystemMapping','lastSelectedSourcesSidebarPaneTab','previouslyViewedFiles','savedURLs','watchExpressions','workspaceExcludedFolders','xhrBreakpoints']);if(!window.localStorage)
return;for(const key in window.localStorage){if(localSettings.has(key))
continue;const value=window.localStorage[key];window.localStorage.removeItem(key);Common.settings._globalStorage[key]=value;}}
_clearBreakpointsWhenTooMany(breakpointsSetting,maxBreakpointsCount){if(breakpointsSetting.get().length>maxBreakpointsCount)
breakpointsSetting.set([]);}};Common.VersionController._currentVersionName='inspectorVersion';Common.VersionController.currentVersion=25;Common.settings;Common.SettingStorageType={Global:Symbol('Global'),Local:Symbol('Local'),Session:Symbol('Session')};Common.moduleSetting=function(settingName){return Common.settings.moduleSetting(settingName);};Common.settingForTest=function(settingName){return Common.settings.settingForTest(settingName);};;Common.StaticContentProvider=class{constructor(contentURL,contentType,lazyContent){this._contentURL=contentURL;this._contentType=contentType;this._lazyContent=lazyContent;}
static fromString(contentURL,contentType,content){const lazyContent=()=>Promise.resolve(content);return new Common.StaticContentProvider(contentURL,contentType,lazyContent);}
contentURL(){return this._contentURL;}
contentType(){return this._contentType;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){return this._lazyContent();}
async searchInContent(query,caseSensitive,isRegex){const content=await this._lazyContent();return content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[];}};;Common.OutputStream=function(){};Common.OutputStream.prototype={write(data){},close(){}};Common.StringOutputStream=class{constructor(){this._data='';}
async write(chunk){this._data+=chunk;}
close(){}
data(){return this._data;}};;Common.Segment=class{constructor(begin,end,data){if(begin>end)
console.assert(false,'Invalid segment');this.begin=begin;this.end=end;this.data=data;}
intersects(that){return this.begin<that.end&&that.begin<this.end;}};Common.SegmentedRange=class{constructor(mergeCallback){this._segments=[];this._mergeCallback=mergeCallback;}
append(newSegment){let startIndex=this._segments.lowerBound(newSegment,(a,b)=>a.begin-b.begin);let endIndex=startIndex;let merged=null;if(startIndex>0){const precedingSegment=this._segments[startIndex-1];merged=this._tryMerge(precedingSegment,newSegment);if(merged){--startIndex;newSegment=merged;}else if(this._segments[startIndex-1].end>=newSegment.begin){if(newSegment.end<precedingSegment.end){this._segments.splice(startIndex,0,new Common.Segment(newSegment.end,precedingSegment.end,precedingSegment.data));}
precedingSegment.end=newSegment.begin;}}
while(endIndex<this._segments.length&&this._segments[endIndex].end<=newSegment.end)
++endIndex;if(endIndex<this._segments.length){merged=this._tryMerge(newSegment,this._segments[endIndex]);if(merged){endIndex++;newSegment=merged;}else if(newSegment.intersects(this._segments[endIndex])){this._segments[endIndex].begin=newSegment.end;}}
this._segments.splice(startIndex,endIndex-startIndex,newSegment);}
appendRange(that){that.segments().forEach(segment=>this.append(segment));}
segments(){return this._segments;}
_tryMerge(first,second){const merged=this._mergeCallback&&this._mergeCallback(first,second);if(!merged)
return null;merged.begin=first.begin;merged.end=Math.max(first.end,second.end);return merged;}};;Common.Throttler=class{constructor(timeout){this._timeout=timeout;this._isRunningProcess=false;this._asSoonAsPossible=false;this._process=null;this._lastCompleteTime=0;this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});}
_processCompleted(){this._lastCompleteTime=this._getTime();this._isRunningProcess=false;if(this._process)
this._innerSchedule(false);this._processCompletedForTests();}
_processCompletedForTests(){}
_onTimeout(){delete this._processTimeout;this._asSoonAsPossible=false;this._isRunningProcess=true;Promise.resolve().then(this._process).catch(console.error.bind(console)).then(this._processCompleted.bind(this)).then(this._scheduleResolve);this._schedulePromise=new Promise(fulfill=>{this._scheduleResolve=fulfill;});this._process=null;}
schedule(process,asSoonAsPossible){this._process=process;const hasScheduledTasks=!!this._processTimeout||this._isRunningProcess;const okToFire=this._getTime()-this._lastCompleteTime>this._timeout;asSoonAsPossible=!!asSoonAsPossible||(!hasScheduledTasks&&okToFire);const forceTimerUpdate=asSoonAsPossible&&!this._asSoonAsPossible;this._asSoonAsPossible=this._asSoonAsPossible||asSoonAsPossible;this._innerSchedule(forceTimerUpdate);return this._schedulePromise;}
_innerSchedule(forceTimerUpdate){if(this._isRunningProcess)
return;if(this._processTimeout&&!forceTimerUpdate)
return;if(this._processTimeout)
this._clearTimeout(this._processTimeout);const timeout=this._asSoonAsPossible?0:this._timeout;this._processTimeout=this._setTimeout(this._onTimeout.bind(this),timeout);}
_clearTimeout(timeoutId){clearTimeout(timeoutId);}
_setTimeout(operation,timeout){return setTimeout(operation,timeout);}
_getTime(){return window.performance.now();}};Common.Throttler.FinishCallback;;Common.Trie=class{constructor(){this.clear();}
add(word){let node=this._root;++this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];let next=this._edges[node][edge];if(!next){if(this._freeNodes.length){next=this._freeNodes.pop();}else{next=this._size++;this._isWord.push(false);this._wordsInSubtree.push(0);this._edges.push({__proto__:null});}
this._edges[node][edge]=next;}
++this._wordsInSubtree[next];node=next;}
this._isWord[node]=true;}
remove(word){if(!this.has(word))
return false;let node=this._root;--this._wordsInSubtree[this._root];for(let i=0;i<word.length;++i){const edge=word[i];const next=this._edges[node][edge];if(!--this._wordsInSubtree[next]){delete this._edges[node][edge];this._freeNodes.push(next);}
node=next;}
this._isWord[node]=false;return true;}
has(word){let node=this._root;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
return false;}
return this._isWord[node];}
words(prefix){prefix=prefix||'';let node=this._root;for(let i=0;i<prefix.length;++i){node=this._edges[node][prefix[i]];if(!node)
return[];}
const results=[];this._dfs(node,prefix,results);return results;}
_dfs(node,prefix,results){if(this._isWord[node])
results.push(prefix);const edges=this._edges[node];for(const edge in edges)
this._dfs(edges[edge],prefix+edge,results);}
longestPrefix(word,fullWordOnly){let node=this._root;let wordIndex=0;for(let i=0;i<word.length;++i){node=this._edges[node][word[i]];if(!node)
break;if(!fullWordOnly||this._isWord[node])
wordIndex=i+1;}
return word.substring(0,wordIndex);}
clear(){this._size=1;this._root=0;this._edges=[{__proto__:null}];this._isWord=[false];this._wordsInSubtree=[0];this._freeNodes=[];}};;self['Common']=self['Common']||{};Common.UIString=function(string,vararg){return String.vsprintf(Common.localize(string),Array.prototype.slice.call(arguments,1));};Common.localize=function(string){return string;};Common.UIStringFormat=class{constructor(format){this._localizedFormat=Common.localize(format);this._tokenizedFormat=String.tokenizeFormatString(this._localizedFormat,String.standardFormatters);}
static _append(a,b){return a+b;}
format(vararg){return String.format(this._localizedFormat,arguments,String.standardFormatters,'',Common.UIStringFormat._append,this._tokenizedFormat).formattedResult;}};self.ls=function(strings,vararg){if(typeof strings==='string')
return strings;const values=Array.prototype.slice.call(arguments,1);if(!values.length)
return strings[0];let result='';for(let i=0;i<values.length;i++){result+=strings[i];result+=''+values[i];}
return result+strings[values.length];};;Common.Renderer=function(){};Common.Renderer.prototype={render(object,options){}};Common.Renderer.render=function(object,options){if(!object)
return Promise.reject(new Error('Can\'t render '+object));return self.runtime.extension(Common.Renderer,object).instance().then(renderer=>renderer.render(object,options||{}));};Common.Renderer.Options;Common.Revealer=function(){};Common.Revealer.reveal=function(revealable,omitFocus){if(!revealable)
return Promise.reject(new Error('Can\'t reveal '+revealable));return self.runtime.allInstances(Common.Revealer,revealable).then(reveal);function reveal(revealers){const promises=[];for(let i=0;i<revealers.length;++i)
promises.push(revealers[i].reveal((revealable),omitFocus));return Promise.race(promises);}};Common.Revealer.revealDestination=function(revealable){const extension=self.runtime.extension(Common.Revealer,revealable);if(!extension)
return null;return extension.descriptor()['destination'];};Common.Revealer.prototype={reveal(object,omitFocus){}};Common.App=function(){};Common.App.prototype={presentUI(document){}};Common.AppProvider=function(){};Common.AppProvider.prototype={createApp(){}};Common.QueryParamHandler=function(){};Common.QueryParamHandler.prototype={handleQueryParam(value){}};Common.Runnable=function(){};Common.Runnable.prototype={run(){}};Common.Linkifier=function(){};Common.Linkifier.prototype={linkify(object,options){}};Common.Linkifier.linkify=function(object,options){if(!object)
return Promise.reject(new Error('Can\'t linkify '+object));return self.runtime.extension(Common.Linkifier,object).instance().then(linkifier=>linkifier.linkify(object,options));};Common.Linkifier.Options;;Common.CharacterIdMap=class{constructor(){this._elementToCharacter=new Map();this._characterToElement=new Map();this._charCode=33;}
toChar(object){let character=this._elementToCharacter.get(object);if(!character){if(this._charCode>=0xFFFF)
throw new Error('CharacterIdMap ran out of capacity!');character=String.fromCharCode(this._charCode++);this._elementToCharacter.set(object,character);this._characterToElement.set(character,object);}
return character;}
fromChar(character){const object=this._characterToElement.get(character);if(object===undefined)
return null;return object;}};;self['Host']=self['Host']||{};function InspectorFrontendHostAPI(){}
window.InspectorFrontendHostAPI=InspectorFrontendHostAPI;InspectorFrontendHostAPI.ContextMenuDescriptor;InspectorFrontendHostAPI.LoadNetworkResourceResult;InspectorFrontendHostAPI.Events={AddExtensions:Symbol('addExtensions'),AppendedToURL:Symbol('appendedToURL'),CanceledSaveURL:Symbol('canceledSaveURL'),ContextMenuCleared:Symbol('contextMenuCleared'),ContextMenuItemSelected:Symbol('contextMenuItemSelected'),DeviceCountUpdated:Symbol('deviceCountUpdated'),DevicesDiscoveryConfigChanged:Symbol('devicesDiscoveryConfigChanged'),DevicesPortForwardingStatusChanged:Symbol('devicesPortForwardingStatusChanged'),DevicesUpdated:Symbol('devicesUpdated'),DispatchMessage:Symbol('dispatchMessage'),DispatchMessageChunk:Symbol('dispatchMessageChunk'),EnterInspectElementMode:Symbol('enterInspectElementMode'),EyeDropperPickedColor:Symbol('eyeDropperPickedColor'),FileSystemsLoaded:Symbol('fileSystemsLoaded'),FileSystemRemoved:Symbol('fileSystemRemoved'),FileSystemAdded:Symbol('fileSystemAdded'),FileSystemFilesChangedAddedRemoved:Symbol('FileSystemFilesChangedAddedRemoved'),IndexingTotalWorkCalculated:Symbol('indexingTotalWorkCalculated'),IndexingWorked:Symbol('indexingWorked'),IndexingDone:Symbol('indexingDone'),KeyEventUnhandled:Symbol('keyEventUnhandled'),ReloadInspectedPage:Symbol('reloadInspectedPage'),RevealSourceLine:Symbol('revealSourceLine'),SavedURL:Symbol('savedURL'),SearchCompleted:Symbol('searchCompleted'),SetInspectedTabId:Symbol('setInspectedTabId'),SetUseSoftMenu:Symbol('setUseSoftMenu'),ShowPanel:Symbol('showPanel')};InspectorFrontendHostAPI.EventDescriptors=[[InspectorFrontendHostAPI.Events.AddExtensions,'addExtensions',['extensions']],[InspectorFrontendHostAPI.Events.AppendedToURL,'appendedToURL',['url']],[InspectorFrontendHostAPI.Events.CanceledSaveURL,'canceledSaveURL',['url']],[InspectorFrontendHostAPI.Events.ContextMenuCleared,'contextMenuCleared',[]],[InspectorFrontendHostAPI.Events.ContextMenuItemSelected,'contextMenuItemSelected',['id']],[InspectorFrontendHostAPI.Events.DeviceCountUpdated,'deviceCountUpdated',['count']],[InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged,'devicesDiscoveryConfigChanged',['config']],[InspectorFrontendHostAPI.Events.DevicesPortForwardingStatusChanged,'devicesPortForwardingStatusChanged',['status']],[InspectorFrontendHostAPI.Events.DevicesUpdated,'devicesUpdated',['devices']],[InspectorFrontendHostAPI.Events.DispatchMessage,'dispatchMessage',['messageObject']],[InspectorFrontendHostAPI.Events.DispatchMessageChunk,'dispatchMessageChunk',['messageChunk','messageSize']],[InspectorFrontendHostAPI.Events.EnterInspectElementMode,'enterInspectElementMode',[]],[InspectorFrontendHostAPI.Events.EyeDropperPickedColor,'eyeDropperPickedColor',['color']],[InspectorFrontendHostAPI.Events.FileSystemsLoaded,'fileSystemsLoaded',['fileSystems']],[InspectorFrontendHostAPI.Events.FileSystemRemoved,'fileSystemRemoved',['fileSystemPath']],[InspectorFrontendHostAPI.Events.FileSystemAdded,'fileSystemAdded',['errorMessage','fileSystem']],[InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,'fileSystemFilesChangedAddedRemoved',['changed','added','removed']],[InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,'indexingTotalWorkCalculated',['requestId','fileSystemPath','totalWork']],[InspectorFrontendHostAPI.Events.IndexingWorked,'indexingWorked',['requestId','fileSystemPath','worked']],[InspectorFrontendHostAPI.Events.IndexingDone,'indexingDone',['requestId','fileSystemPath']],[InspectorFrontendHostAPI.Events.KeyEventUnhandled,'keyEventUnhandled',['event']],[InspectorFrontendHostAPI.Events.ReloadInspectedPage,'reloadInspectedPage',['hard']],[InspectorFrontendHostAPI.Events.RevealSourceLine,'revealSourceLine',['url','lineNumber','columnNumber']],[InspectorFrontendHostAPI.Events.SavedURL,'savedURL',['url','fileSystemPath']],[InspectorFrontendHostAPI.Events.SearchCompleted,'searchCompleted',['requestId','fileSystemPath','files']],[InspectorFrontendHostAPI.Events.SetInspectedTabId,'setInspectedTabId',['tabId']],[InspectorFrontendHostAPI.Events.SetUseSoftMenu,'setUseSoftMenu',['useSoftMenu']],[InspectorFrontendHostAPI.Events.ShowPanel,'showPanel',['panelName']]];InspectorFrontendHostAPI.prototype={addFileSystem(type){},append(url,content){},loadCompleted(){},indexPath(requestId,fileSystemPath,excludedFolders){},getSelectionBackgroundColor(){},getSelectionForegroundColor(){},getInactiveSelectionBackgroundColor(){},getInactiveSelectionForegroundColor(){},setInspectedPageBounds(bounds){},showCertificateViewer(certChain){},setWhitelistedShortcuts(shortcuts){},setEyeDropperActive(active){},inspectElementCompleted(){},openInNewTab(url){},showItemInFolder(fileSystemPath){},removeFileSystem(fileSystemPath){},requestFileSystems(){},save(url,content,forceSaveAs){},searchInPath(requestId,fileSystemPath,query){},stopIndexing(requestId){},bringToFront(){},closeWindow(){},copyText(text){},inspectedURLChanged(url){},isolatedFileSystem(fileSystemId,registeredName){},loadNetworkResource(url,headers,streamId,callback){},getPreferences(callback){},setPreference(name,value){},removePreference(name){},clearPreferences(){},upgradeDraggedFileSystemPermissions(fileSystem){},platform(){},recordEnumeratedHistogram(actionName,actionCode,bucketSize){},sendMessageToBackend(message){},setDevicesDiscoveryConfig(config){},setDevicesUpdatesEnabled(enabled){},performActionOnRemotePage(pageId,action){},openRemotePage(browserId,url){},openNodeFrontend(){},setInjectedScriptForOrigin(origin,script){},setIsDocked(isDocked,callback){},zoomFactor(){},zoomIn(){},zoomOut(){},resetZoom(){},showContextMenuAtPoint(x,y,items,document){},reattach(callback){},readyForTest(){},connectionReady(){},setOpenNewWindowForPopups(value){},isHostedMode(){}};;Host.InspectorFrontendHostStub=class{constructor(){function stopEventPropagation(event){const zoomModifier=Host.isMac()?event.metaKey:event.ctrlKey;if(zoomModifier&&(event.keyCode===187||event.keyCode===189))
event.stopPropagation();}
document.addEventListener('keydown',stopEventPropagation,true);}
getSelectionBackgroundColor(){return'#6e86ff';}
getSelectionForegroundColor(){return'#ffffff';}
getInactiveSelectionBackgroundColor(){return'#c9c8c8';}
getInactiveSelectionForegroundColor(){return'#323232';}
platform(){let match=navigator.userAgent.match(/Windows NT/);if(match)
return'windows';match=navigator.userAgent.match(/Mac OS X/);if(match)
return'mac';return'linux';}
loadCompleted(){}
bringToFront(){this._windowVisible=true;}
closeWindow(){this._windowVisible=false;}
setIsDocked(isDocked,callback){setTimeout(callback,0);}
setInspectedPageBounds(bounds){}
inspectElementCompleted(){}
setInjectedScriptForOrigin(origin,script){}
inspectedURLChanged(url){document.title=Common.UIString('DevTools - %s',url.replace(/^https?:\/\//,''));}
copyText(text){Common.console.error('Clipboard is not enabled in hosted mode. Please inspect using chrome://inspect');}
openInNewTab(url){window.open(url,'_blank');}
showItemInFolder(fileSystemPath){Common.console.error('Show item in folder is not enabled in hosted mode. Please inspect using chrome://inspect');}
save(url,content,forceSaveAs){Common.console.error('Saving files is not enabled in hosted mode. Please inspect using chrome://inspect');this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.CanceledSaveURL,url);}
append(url,content){Common.console.error('Saving files is not enabled in hosted mode. Please inspect using chrome://inspect');}
sendMessageToBackend(message){}
recordEnumeratedHistogram(actionName,actionCode,bucketSize){}
requestFileSystems(){this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.FileSystemsLoaded,[]);}
addFileSystem(type){}
removeFileSystem(fileSystemPath){}
isolatedFileSystem(fileSystemId,registeredName){return null;}
loadNetworkResource(url,headers,streamId,callback){Runtime.loadResourcePromise(url).then(function(text){Host.ResourceLoader.streamWrite(streamId,text);callback({statusCode:200});}).catch(function(){callback({statusCode:404});});}
getPreferences(callback){const prefs={};for(const name in window.localStorage)
prefs[name]=window.localStorage[name];callback(prefs);}
setPreference(name,value){window.localStorage[name]=value;}
removePreference(name){delete window.localStorage[name];}
clearPreferences(){window.localStorage.clear();}
upgradeDraggedFileSystemPermissions(fileSystem){}
indexPath(requestId,fileSystemPath,excludedFolders){}
stopIndexing(requestId){}
searchInPath(requestId,fileSystemPath,query){}
zoomFactor(){return 1;}
zoomIn(){}
zoomOut(){}
resetZoom(){}
setWhitelistedShortcuts(shortcuts){}
setEyeDropperActive(active){}
showCertificateViewer(certChain){}
reattach(callback){}
readyForTest(){}
connectionReady(){}
setOpenNewWindowForPopups(value){}
setDevicesDiscoveryConfig(config){}
setDevicesUpdatesEnabled(enabled){}
performActionOnRemotePage(pageId,action){}
openRemotePage(browserId,url){}
openNodeFrontend(){}
showContextMenuAtPoint(x,y,items,document){throw'Soft context menu should be used';}
isHostedMode(){return true;}};Host.InspectorFrontendAPIImpl=class{constructor(){this._debugFrontend=!!Runtime.queryParam('debugFrontend')||(window['InspectorTest']&&window['InspectorTest']['debugTest']);const descriptors=InspectorFrontendHostAPI.EventDescriptors;for(let i=0;i<descriptors.length;++i)
this[descriptors[i][1]]=this._dispatch.bind(this,descriptors[i][0],descriptors[i][2],descriptors[i][3]);}
_dispatch(name,signature,runOnceLoaded){const params=Array.prototype.slice.call(arguments,3);if(this._debugFrontend)
setImmediate(innerDispatch);else
innerDispatch();function innerDispatch(){if(signature.length<2){try{InspectorFrontendHost.events.dispatchEventToListeners(name,params[0]);}catch(e){console.error(e+' '+e.stack);}
return;}
const data={};for(let i=0;i<signature.length;++i)
data[signature[i]]=params[i];try{InspectorFrontendHost.events.dispatchEventToListeners(name,data);}catch(e){console.error(e+' '+e.stack);}}}
streamWrite(id,chunk){Host.ResourceLoader.streamWrite(id,chunk);}};let InspectorFrontendHost=window.InspectorFrontendHost||null;window.InspectorFrontendHost=InspectorFrontendHost;(function(){function initializeInspectorFrontendHost(){let proto;if(!InspectorFrontendHost){window.InspectorFrontendHost=InspectorFrontendHost=new Host.InspectorFrontendHostStub();}else{proto=Host.InspectorFrontendHostStub.prototype;for(const name in proto){const value=proto[name];if(typeof value!=='function'||InspectorFrontendHost[name])
continue;InspectorFrontendHost[name]=stub.bind(null,name);}}
function stub(name){console.error('Incompatible embedder: method InspectorFrontendHost.'+name+' is missing. Using stub instead.');const args=Array.prototype.slice.call(arguments,1);return proto[name].apply(InspectorFrontendHost,args);}
InspectorFrontendHost.events=new Common.Object();}
initializeInspectorFrontendHost();window.InspectorFrontendAPI=new Host.InspectorFrontendAPIImpl();})();InspectorFrontendHost.events;Host.isUnderTest=function(prefs){if(Runtime.queryParam('test'))
return true;if(prefs)
return prefs['isUnderTest']==='true';return Common.settings&&Common.settings.createSetting('isUnderTest',false).get();};;Host.platform=function(){if(!Host._platform)
Host._platform=InspectorFrontendHost.platform();return Host._platform;};Host.isMac=function(){if(typeof Host._isMac==='undefined')
Host._isMac=Host.platform()==='mac';return Host._isMac;};Host.isWin=function(){if(typeof Host._isWin==='undefined')
Host._isWin=Host.platform()==='windows';return Host._isWin;};Host.isCustomDevtoolsFrontend=function(){if(typeof Host._isCustomDevtoolsFronend==='undefined')
Host._isCustomDevtoolsFronend=window.location.toString().startsWith('chrome-devtools://devtools/custom/');return Host._isCustomDevtoolsFronend;};Host.fontFamily=function(){if(Host._fontFamily)
return Host._fontFamily;switch(Host.platform()){case'linux':Host._fontFamily='Roboto, Ubuntu, Arial, sans-serif';break;case'mac':Host._fontFamily='\'Lucida Grande\', sans-serif';break;case'windows':Host._fontFamily='\'Segoe UI\', Tahoma, sans-serif';break;}
return Host._fontFamily;};;Host.ResourceLoader={};Host.ResourceLoader._lastStreamId=0;Host.ResourceLoader._boundStreams={};Host.ResourceLoader._bindOutputStream=function(stream){Host.ResourceLoader._boundStreams[++Host.ResourceLoader._lastStreamId]=stream;return Host.ResourceLoader._lastStreamId;};Host.ResourceLoader._discardOutputStream=function(id){Host.ResourceLoader._boundStreams[id].close();delete Host.ResourceLoader._boundStreams[id];};Host.ResourceLoader.streamWrite=function(id,chunk){Host.ResourceLoader._boundStreams[id].write(chunk);};Host.ResourceLoader.load=function(url,headers,callback){const stream=new Common.StringOutputStream();Host.ResourceLoader.loadAsStream(url,headers,stream,mycallback);function mycallback(statusCode,headers){callback(statusCode,headers,stream.data());}};Host.ResourceLoader.loadAsStream=function(url,headers,stream,callback){const streamId=Host.ResourceLoader._bindOutputStream(stream);const parsedURL=new Common.ParsedURL(url);if(parsedURL.isDataURL()){loadXHR(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed);return;}
const rawHeaders=[];if(headers){for(const key in headers)
rawHeaders.push(key+': '+headers[key]);}
InspectorFrontendHost.loadNetworkResource(url,rawHeaders.join('\r\n'),streamId,finishedCallback);function finishedCallback(response){if(callback)
callback(response.statusCode,response.headers||{});Host.ResourceLoader._discardOutputStream(streamId);}
function dataURLDecodeSuccessful(text){Host.ResourceLoader.streamWrite(streamId,text);finishedCallback(({statusCode:200}));}
function dataURLDecodeFailed(){finishedCallback(({statusCode:404}));}};;Host.UserMetrics=class{panelShown(panelName){const code=Host.UserMetrics._PanelCodes[panelName]||0;const size=Object.keys(Host.UserMetrics._PanelCodes).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.PanelShown',code,size);}
drawerShown(drawerId){this.panelShown('drawer-'+drawerId);}
actionTaken(action){const size=Object.keys(Host.UserMetrics.Action).length+1;InspectorFrontendHost.recordEnumeratedHistogram('DevTools.ActionTaken',action,size);}};Host.UserMetrics.Action={WindowDocked:1,WindowUndocked:2,ScriptsBreakpointSet:3,TimelineStarted:4,ProfilesCPUProfileTaken:5,ProfilesHeapProfileTaken:6,AuditsStarted:7,ConsoleEvaluated:8,FileSavedInWorkspace:9,DeviceModeEnabled:10,AnimationsPlaybackRateChanged:11,RevisionApplied:12,FileSystemDirectoryContentReceived:13,StyleRuleEdited:14,CommandEvaluatedInConsolePanel:15,DOMPropertiesExpanded:16,ResizedViewInResponsiveMode:17,TimelinePageReloadStarted:18,ConnectToNodeJSFromFrontend:19,ConnectToNodeJSDirectly:20,CpuThrottlingEnabled:21,CpuProfileNodeFocused:22,CpuProfileNodeExcluded:23,SelectFileFromFilePicker:24,SelectCommandFromCommandMenu:25,ChangeInspectedNodeInElementsPanel:26,StyleRuleCopied:27,CoverageStarted:28,Audits2Started:29,Audits2Finished:30,ShowedThirdPartyBadges:31,};Host.UserMetrics._PanelCodes={elements:1,resources:2,network:3,sources:4,timeline:5,heap_profiler:6,audits:7,console:8,layers:9,'drawer-console-view':10,'drawer-animations':11,'drawer-network.config':12,'drawer-rendering':13,'drawer-sensors':14,'drawer-sources.search':15,security:16,js_profiler:17,audits2:18,};Host.userMetrics=new Host.UserMetrics();;self['UI']=self['UI']||{};UI.XElement=class extends HTMLElement{static get observedAttributes(){return['flex','padding','padding-top','padding-bottom','padding-left','padding-right','margin','margin-top','margin-bottom','margin-left','margin-right','overflow','overflow-x','overflow-y','font-size','color','background','background-color','border','border-top','border-bottom','border-left','border-right','max-width','max-height'];}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='flex'){if(newValue===null)
this.style.removeProperty('flex');else if(newValue==='initial'||newValue==='auto'||newValue==='none'||newValue.indexOf(' ')!==-1)
this.style.setProperty('flex',newValue);else
this.style.setProperty('flex','0 0 '+newValue);return;}
if(newValue===null){this.style.removeProperty(attr);if(attr.startsWith('padding-')||attr.startsWith('margin-')||attr.startsWith('border-')||attr.startsWith('background-')||attr.startsWith('overflow-')){const shorthand=attr.substring(0,attr.indexOf('-'));const shorthandValue=this.getAttribute(shorthand);if(shorthandValue!==null)
this.style.setProperty(shorthand,shorthandValue);}}else{this.style.setProperty(attr,newValue);}}};UI._XBox=class extends UI.XElement{constructor(direction){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction',direction);this.style.setProperty('justify-content','flex-start');}
static get observedAttributes(){return UI.XElement.observedAttributes.concat(['x-start','x-center','x-stretch','x-baseline','justify-content']);}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='x-start'||attr==='x-center'||attr==='x-stretch'||attr==='x-baseline'){if(newValue===null)
this.style.removeProperty('align-items');else
this.style.setProperty('align-items',attr==='x-start'?'flex-start':attr.substr(2));return;}
super.attributeChangedCallback(attr,oldValue,newValue);}};UI.XVBox=class extends UI._XBox{constructor(){super('column');}};UI.XHBox=class extends UI._XBox{constructor(){super('row');}};UI.XCBox=class extends UI.XElement{constructor(){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction','column');this.style.setProperty('justify-content','center');this.style.setProperty('align-items','center');}};UI.XDiv=class extends UI.XElement{constructor(){super();this.style.setProperty('display','block');}};UI.XSpan=class extends UI.XElement{constructor(){super();this.style.setProperty('display','inline');}};UI.XText=class extends UI.XElement{constructor(){super();this.style.setProperty('display','inline');this.style.setProperty('white-space','pre');}};self.customElements.define('x-vbox',UI.XVBox);self.customElements.define('x-hbox',UI.XHBox);self.customElements.define('x-cbox',UI.XCBox);self.customElements.define('x-div',UI.XDiv);self.customElements.define('x-span',UI.XSpan);self.customElements.define('x-text',UI.XText);;UI.Widget=class extends Common.Object{constructor(isWebComponent){super();this.contentElement=createElementWithClass('div','widget');if(isWebComponent){this.element=createElementWithClass('div','vbox flex-auto');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element);this._shadowRoot.appendChild(this.contentElement);}else{this.element=this.contentElement;}
this._isWebComponent=isWebComponent;this.element.__widget=this;this._visible=false;this._isRoot=false;this._isShowing=false;this._children=[];this._hideOnDetach=false;this._notificationDepth=0;this._invalidationsSuspended=0;this._defaultFocusedChild=null;}
static _incrementWidgetCounter(parentElement,childElement){const count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count)
return;while(parentElement){parentElement.__widgetCounter=(parentElement.__widgetCounter||0)+count;parentElement=parentElement.parentElementOrShadowHost();}}
static _decrementWidgetCounter(parentElement,childElement){const count=(childElement.__widgetCounter||0)+(childElement.__widget?1:0);if(!count)
return;while(parentElement){parentElement.__widgetCounter-=count;parentElement=parentElement.parentElementOrShadowHost();}}
static __assert(condition,message){if(!condition)
throw new Error(message);}
static focusWidgetForNode(node){while(node){if(node.__widget)
break;node=node.parentNodeOrShadowHost();}
if(!node)
return;let widget=node.__widget;while(widget._parentWidget){widget._parentWidget._defaultFocusedChild=widget;widget=widget._parentWidget;}}
markAsRoot(){UI.Widget.__assert(!this.element.parentElement,'Attempt to mark as root attached node');this._isRoot=true;}
parentWidget(){return this._parentWidget;}
children(){return this._children;}
childWasDetached(widget){}
isShowing(){return this._isShowing;}
shouldHideOnDetach(){if(!this.element.parentElement)
return false;if(this._hideOnDetach)
return true;for(const child of this._children){if(child.shouldHideOnDetach())
return true;}
return false;}
setHideOnDetach(){this._hideOnDetach=true;}
_inNotification(){return!!this._notificationDepth||(this._parentWidget&&this._parentWidget._inNotification());}
_parentIsShowing(){if(this._isRoot)
return true;return!!this._parentWidget&&this._parentWidget.isShowing();}
_callOnVisibleChildren(method){const copy=this._children.slice();for(let i=0;i<copy.length;++i){if(copy[i]._parentWidget===this&&copy[i]._visible)
method.call(copy[i]);}}
_processWillShow(){this._callOnVisibleChildren(this._processWillShow);this._isShowing=true;}
_processWasShown(){if(this._inNotification())
return;this.restoreScrollPositions();this._notify(this.wasShown);this._callOnVisibleChildren(this._processWasShown);}
_processWillHide(){if(this._inNotification())
return;this.storeScrollPositions();this._callOnVisibleChildren(this._processWillHide);this._notify(this.willHide);this._isShowing=false;}
_processWasHidden(){this._callOnVisibleChildren(this._processWasHidden);}
_processOnResize(){if(this._inNotification())
return;if(!this.isShowing())
return;this._notify(this.onResize);this._callOnVisibleChildren(this._processOnResize);}
_notify(notification){++this._notificationDepth;try{notification.call(this);}finally{--this._notificationDepth;}}
wasShown(){}
willHide(){}
onResize(){}
onLayout(){}
ownerViewDisposed(){}
show(parentElement,insertBefore){UI.Widget.__assert(parentElement,'Attempt to attach widget with no parent element');if(!this._isRoot){let currentParent=parentElement;while(currentParent&&!currentParent.__widget)
currentParent=currentParent.parentElementOrShadowHost();UI.Widget.__assert(currentParent,'Attempt to attach widget to orphan node');this._attach(currentParent.__widget);}
this._showWidget(parentElement,insertBefore);}
_attach(parentWidget){if(parentWidget===this._parentWidget)
return;if(this._parentWidget)
this.detach();this._parentWidget=parentWidget;this._parentWidget._children.push(this);this._isRoot=false;}
showWidget(){if(this._visible)
return;UI.Widget.__assert(this.element.parentElement,'Attempt to show widget that is not hidden using hideWidget().');this._showWidget((this.element.parentElement),this.element.nextSibling);}
_showWidget(parentElement,insertBefore){let currentParent=parentElement;while(currentParent&&!currentParent.__widget)
currentParent=currentParent.parentElementOrShadowHost();if(this._isRoot){UI.Widget.__assert(!currentParent,'Attempt to show root widget under another widget');}else{UI.Widget.__assert(currentParent&&currentParent.__widget===this._parentWidget,'Attempt to show under node belonging to alien widget');}
const wasVisible=this._visible;if(wasVisible&&this.element.parentElement===parentElement)
return;this._visible=true;if(!wasVisible&&this._parentIsShowing())
this._processWillShow();this.element.classList.remove('hidden');if(this.element.parentElement!==parentElement){UI.Widget._incrementWidgetCounter(parentElement,this.element);if(insertBefore)
UI.Widget._originalInsertBefore.call(parentElement,this.element,insertBefore);else
UI.Widget._originalAppendChild.call(parentElement,this.element);}
if(!wasVisible&&this._parentIsShowing())
this._processWasShown();if(this._parentWidget&&this._hasNonZeroConstraints())
this._parentWidget.invalidateConstraints();else
this._processOnResize();}
hideWidget(){if(!this._visible)
return;this._hideWidget(false);}
_hideWidget(removeFromDOM){this._visible=false;const parentElement=this.element.parentElement;if(this._parentIsShowing())
this._processWillHide();if(removeFromDOM){UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);}else{this.element.classList.add('hidden');}
if(this._parentIsShowing())
this._processWasHidden();if(this._parentWidget&&this._hasNonZeroConstraints())
this._parentWidget.invalidateConstraints();}
detach(overrideHideOnDetach){if(!this._parentWidget&&!this._isRoot)
return;const removeFromDOM=overrideHideOnDetach||!this.shouldHideOnDetach();if(this._visible){this._hideWidget(removeFromDOM);}else if(removeFromDOM&&this.element.parentElement){const parentElement=this.element.parentElement;UI.Widget._decrementWidgetCounter(parentElement,this.element);UI.Widget._originalRemoveChild.call(parentElement,this.element);}
if(this._parentWidget){const childIndex=this._parentWidget._children.indexOf(this);UI.Widget.__assert(childIndex>=0,'Attempt to remove non-child widget');this._parentWidget._children.splice(childIndex,1);if(this._parentWidget._defaultFocusedChild===this)
this._parentWidget._defaultFocusedChild=null;this._parentWidget.childWasDetached(this);this._parentWidget=null;}else{UI.Widget.__assert(this._isRoot,'Removing non-root widget from DOM');}}
detachChildWidgets(){const children=this._children.slice();for(let i=0;i<children.length;++i)
children[i].detach();}
elementsToRestoreScrollPositionsFor(){return[this.element];}
storeScrollPositions(){const elements=this.elementsToRestoreScrollPositionsFor();for(let i=0;i<elements.length;++i){const container=elements[i];container._scrollTop=container.scrollTop;container._scrollLeft=container.scrollLeft;}}
restoreScrollPositions(){const elements=this.elementsToRestoreScrollPositionsFor();for(let i=0;i<elements.length;++i){const container=elements[i];if(container._scrollTop)
container.scrollTop=container._scrollTop;if(container._scrollLeft)
container.scrollLeft=container._scrollLeft;}}
doResize(){if(!this.isShowing())
return;if(!this._inNotification())
this._callOnVisibleChildren(this._processOnResize);}
doLayout(){if(!this.isShowing())
return;this._notify(this.onLayout);this.doResize();}
registerRequiredCSS(cssFile){UI.appendStyle(this._isWebComponent?this._shadowRoot:this.element,cssFile);}
printWidgetHierarchy(){const lines=[];this._collectWidgetHierarchy('',lines);console.log(lines.join('\n'));}
_collectWidgetHierarchy(prefix,lines){lines.push(prefix+'['+this.element.className+']'+(this._children.length?' {':''));for(let i=0;i<this._children.length;++i)
this._children[i]._collectWidgetHierarchy(prefix+'    ',lines);if(this._children.length)
lines.push(prefix+'}');}
setDefaultFocusedElement(element){this._defaultFocusedElement=element;}
setDefaultFocusedChild(child){UI.Widget.__assert(child._parentWidget===this,'Attempt to set non-child widget as default focused.');this._defaultFocusedChild=child;}
focus(){if(!this.isShowing())
return;const element=this._defaultFocusedElement;if(element){if(!element.hasFocus())
element.focus();return;}
if(this._defaultFocusedChild&&this._defaultFocusedChild._visible){this._defaultFocusedChild.focus();}else{for(const child of this._children){if(child._visible){child.focus();return;}}
let child=this.contentElement.traverseNextNode(this.contentElement);while(child){if(child instanceof UI.XWidget){child.focus();return;}
child=child.traverseNextNode(this.contentElement);}}}
hasFocus(){return this.element.hasFocus();}
calculateConstraints(){return new UI.Constraints();}
constraints(){if(typeof this._constraints!=='undefined')
return this._constraints;if(typeof this._cachedConstraints==='undefined')
this._cachedConstraints=this.calculateConstraints();return this._cachedConstraints;}
setMinimumAndPreferredSizes(width,height,preferredWidth,preferredHeight){this._constraints=new UI.Constraints(new UI.Size(width,height),new UI.Size(preferredWidth,preferredHeight));this.invalidateConstraints();}
setMinimumSize(width,height){this._constraints=new UI.Constraints(new UI.Size(width,height));this.invalidateConstraints();}
_hasNonZeroConstraints(){const constraints=this.constraints();return!!(constraints.minimum.width||constraints.minimum.height||constraints.preferred.width||constraints.preferred.height);}
suspendInvalidations(){++this._invalidationsSuspended;}
resumeInvalidations(){--this._invalidationsSuspended;if(!this._invalidationsSuspended&&this._invalidationsRequested)
this.invalidateConstraints();}
invalidateConstraints(){if(this._invalidationsSuspended){this._invalidationsRequested=true;return;}
this._invalidationsRequested=false;const cached=this._cachedConstraints;delete this._cachedConstraints;const actual=this.constraints();if(!actual.isEqual(cached)&&this._parentWidget)
this._parentWidget.invalidateConstraints();else
this.doLayout();}};UI.Widget._originalAppendChild=Element.prototype.appendChild;UI.Widget._originalInsertBefore=Element.prototype.insertBefore;UI.Widget._originalRemoveChild=Element.prototype.removeChild;UI.Widget._originalRemoveChildren=Element.prototype.removeChildren;UI.VBox=class extends UI.Widget{constructor(isWebComponent){super(isWebComponent);this.contentElement.classList.add('vbox');}
calculateConstraints(){let constraints=new UI.Constraints();function updateForChild(){const child=this.constraints();constraints=constraints.widthToMax(child);constraints=constraints.addHeight(child);}
this._callOnVisibleChildren(updateForChild);return constraints;}};UI.HBox=class extends UI.Widget{constructor(isWebComponent){super(isWebComponent);this.contentElement.classList.add('hbox');}
calculateConstraints(){let constraints=new UI.Constraints();function updateForChild(){const child=this.constraints();constraints=constraints.addWidth(child);constraints=constraints.heightToMax(child);}
this._callOnVisibleChildren(updateForChild);return constraints;}};UI.VBoxWithResizeCallback=class extends UI.VBox{constructor(resizeCallback){super();this._resizeCallback=resizeCallback;}
onResize(){this._resizeCallback();}};UI.WidgetFocusRestorer=class{constructor(widget){this._widget=widget;this._previous=widget.element.ownerDocument.deepActiveElement();widget.focus();}
restore(){if(!this._widget)
return;if(this._widget.hasFocus()&&this._previous)
this._previous.focus();this._previous=null;this._widget=null;}};Element.prototype.appendChild=function(child){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalAppendChild.call(this,child);};Element.prototype.insertBefore=function(child,anchor){UI.Widget.__assert(!child.__widget||child.parentElement===this,'Attempt to add widget via regular DOM operation.');return UI.Widget._originalInsertBefore.call(this,child,anchor);};Element.prototype.removeChild=function(child){UI.Widget.__assert(!child.__widgetCounter&&!child.__widget,'Attempt to remove element containing widget via regular DOM operation');return UI.Widget._originalRemoveChild.call(this,child);};Element.prototype.removeChildren=function(){UI.Widget.__assert(!this.__widgetCounter,'Attempt to remove element containing widget via regular DOM operation');UI.Widget._originalRemoveChildren.call(this);};;UI.View=function(){};UI.View.prototype={viewId(){},title(){},isCloseable(){},isTransient(){},toolbarItems(){},widget(){},disposeView(){}};UI.View._symbol=Symbol('view');UI.View._widgetSymbol=Symbol('widget');UI.SimpleView=class extends UI.VBox{constructor(title,isWebComponent){super(isWebComponent);this._title=title;this._toolbarItems=[];this[UI.View._symbol]=this;}
viewId(){return this._title;}
title(){return this._title;}
isCloseable(){return false;}
isTransient(){return false;}
toolbarItems(){return Promise.resolve(this.syncToolbarItems());}
syncToolbarItems(){return this._toolbarItems;}
widget(){return(Promise.resolve(this));}
addToolbarItem(item){this._toolbarItems.push(item);}
revealView(){return UI.viewManager.revealView(this);}
disposeView(){}};UI.ProvidedView=class{constructor(extension){this._extension=extension;}
viewId(){return this._extension.descriptor()['id'];}
title(){return this._extension.title();}
isCloseable(){return this._extension.descriptor()['persistence']==='closeable';}
isTransient(){return this._extension.descriptor()['persistence']==='transient';}
toolbarItems(){const actionIds=this._extension.descriptor()['actionIds'];if(actionIds){const result=actionIds.split(',').map(id=>UI.Toolbar.createActionButtonForId(id.trim()));return Promise.resolve(result);}
if(this._extension.descriptor()['hasToolbar'])
return this.widget().then(widget=>(widget).toolbarItems());return Promise.resolve([]);}
async widget(){this._widgetRequested=true;const widget=await this._extension.instance();if(!(widget instanceof UI.Widget))
throw new Error('view className should point to a UI.Widget');widget[UI.View._symbol]=this;return(widget);}
async disposeView(){if(!this._widgetRequested)
return;const widget=await this.widget();widget.ownerViewDisposed();}};UI.ViewLocation=function(){};UI.ViewLocation.prototype={appendApplicableItems(locationName){},appendView(view,insertBefore){},showView(view,insertBefore,userGesture){},removeView(view){},widget(){}};UI.TabbedViewLocation=function(){};UI.TabbedViewLocation.prototype={tabbedPane(){},enableMoreTabsButton(){}};UI.ViewLocationResolver=function(){};UI.ViewLocationResolver.prototype={resolveLocation(location){}};UI.ViewManager=class{constructor(){this._views=new Map();this._locationNameByViewId=new Map();for(const extension of self.runtime.extensions('view')){const descriptor=extension.descriptor();this._views.set(descriptor['id'],new UI.ProvidedView(extension));this._locationNameByViewId.set(descriptor['id'],descriptor['location']);}}
static _populateToolbar(element,toolbarItems){if(!toolbarItems.length)
return;const toolbar=new UI.Toolbar('');element.insertBefore(toolbar.element,element.firstChild);for(const item of toolbarItems)
toolbar.appendToolbarItem(item);}
revealView(view){const location=(view[UI.ViewManager._Location.symbol]);if(!location)
return Promise.resolve();location._reveal();return location.showView(view);}
view(viewId){return this._views.get(viewId);}
materializedWidget(viewId){const view=this.view(viewId);return view?view[UI.View._widgetSymbol]:null;}
showView(viewId,userGesture,omitFocus){const view=this._views.get(viewId);if(!view){console.error('Could not find view for id: \''+viewId+'\' '+new Error().stack);return Promise.resolve();}
const locationName=this._locationNameByViewId.get(viewId);const location=view[UI.ViewManager._Location.symbol];if(location){location._reveal();return location.showView(view,undefined,userGesture,omitFocus);}
return this.resolveLocation(locationName).then(location=>{if(!location)
throw new Error('Could not resolve location for view: '+viewId);location._reveal();return location.showView(view,undefined,userGesture,omitFocus);});}
resolveLocation(location){if(!location)
return(Promise.resolve(null));const resolverExtensions=self.runtime.extensions(UI.ViewLocationResolver).filter(extension=>extension.descriptor()['name']===location);if(!resolverExtensions.length)
throw new Error('Unresolved location: '+location);const resolverExtension=resolverExtensions[0];return resolverExtension.instance().then(resolver=>(resolver.resolveLocation(location)));}
createTabbedLocation(revealCallback,location,restoreSelection,allowReorder,defaultTab){return new UI.ViewManager._TabbedLocation(this,revealCallback,location,restoreSelection,allowReorder,defaultTab);}
createStackLocation(revealCallback,location){return new UI.ViewManager._StackLocation(this,revealCallback,location);}
hasViewsForLocation(location){return!!this._viewsForLocation(location).length;}
_viewsForLocation(location){const result=[];for(const id of this._views.keys()){if(this._locationNameByViewId.get(id)===location)
result.push(this._views.get(id));}
return result;}};UI.ViewManager._ContainerWidget=class extends UI.VBox{constructor(view){super();this.element.classList.add('flex-auto','view-container','overflow-auto');this._view=view;this.element.tabIndex=-1;this.setDefaultFocusedElement(this.element);}
_materialize(){if(this._materializePromise)
return this._materializePromise;const promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this.element)));promises.push(this._view.widget().then(widget=>{const shouldFocus=this.element.hasFocus();this.setDefaultFocusedElement(null);this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);if(shouldFocus)
widget.focus();}));this._materializePromise=Promise.all(promises);return this._materializePromise;}
wasShown(){this._materialize().then(()=>{this._wasShownForTest();});}
_wasShownForTest(){}};UI.ViewManager._ExpandableContainerWidget=class extends UI.VBox{constructor(view){super(true);this.element.classList.add('flex-none');this.registerRequiredCSS('ui/viewContainers.css');this._titleElement=createElementWithClass('div','expandable-view-title');UI.ARIAUtils.markAsLink(this._titleElement);this._titleExpandIcon=UI.Icon.create('smallicon-triangle-right','title-expand-icon');this._titleElement.appendChild(this._titleExpandIcon);this._titleElement.createTextChild(view.title());this._titleElement.tabIndex=0;this._titleElement.addEventListener('click',this._toggleExpanded.bind(this),false);this._titleElement.addEventListener('keydown',this._onTitleKeyDown.bind(this),false);this.contentElement.insertBefore(this._titleElement,this.contentElement.firstChild);this.contentElement.createChild('content');this._view=view;view[UI.ViewManager._ExpandableContainerWidget._symbol]=this;}
_materialize(){if(this._materializePromise)
return this._materializePromise;const promises=[];promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager,this._titleElement)));promises.push(this._view.widget().then(widget=>{this._widget=widget;this._view[UI.View._widgetSymbol]=widget;widget.show(this.element);}));this._materializePromise=Promise.all(promises);return this._materializePromise;}
_expand(){if(this._titleElement.classList.contains('expanded'))
return this._materialize();this._titleElement.classList.add('expanded');UI.ARIAUtils.setExpanded(this._titleElement,true);this._titleExpandIcon.setIconType('smallicon-triangle-down');return this._materialize().then(()=>this._widget.show(this.element));}
_collapse(){if(!this._titleElement.classList.contains('expanded'))
return;this._titleElement.classList.remove('expanded');UI.ARIAUtils.setExpanded(this._titleElement,false);this._titleExpandIcon.setIconType('smallicon-triangle-right');this._materialize().then(()=>this._widget.detach());}
_toggleExpanded(){if(this._titleElement.classList.contains('expanded'))
this._collapse();else
this._expand();}
_onTitleKeyDown(event){if(isEnterKey(event)||event.keyCode===UI.KeyboardShortcut.Keys.Space.code){this._toggleExpanded();}else if(event.key==='ArrowLeft'){this._collapse();}else if(event.key==='ArrowRight'){if(!this._titleElement.classList.contains('expanded'))
this._expand();else if(this._widget)
this._widget.focus();}}};UI.ViewManager._ExpandableContainerWidget._symbol=Symbol('container');UI.ViewManager._Location=class{constructor(manager,widget,revealCallback){this._manager=manager;this._revealCallback=revealCallback;this._widget=widget;}
widget(){return this._widget;}
_reveal(){if(this._revealCallback)
this._revealCallback();}};UI.ViewManager._Location.symbol=Symbol('location');UI.ViewManager._TabbedLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location,restoreSelection,allowReorder,defaultTab){const tabbedPane=new UI.TabbedPane();if(allowReorder)
tabbedPane.setAllowTabReorder(true);super(manager,tabbedPane,revealCallback);this._tabbedPane=tabbedPane;this._allowReorder=allowReorder;this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabClosed,this._tabClosed,this);this._closeableTabSetting=Common.settings.createSetting(location+'-closeableTabs',{});this._tabOrderSetting=Common.settings.createSetting(location+'-tabOrder',{});this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabOrderChanged,this._persistTabOrder,this);if(restoreSelection)
this._lastSelectedTabSetting=Common.settings.createSetting(location+'-selectedTab','');this._defaultTab=defaultTab;this._views=new Map();if(location)
this.appendApplicableItems(location);}
widget(){return this._tabbedPane;}
tabbedPane(){return this._tabbedPane;}
enableMoreTabsButton(){this._tabbedPane.leftToolbar().appendToolbarItem(new UI.ToolbarMenuButton(this._appendTabsToMenu.bind(this)));this._tabbedPane.disableOverflowMenu();}
appendApplicableItems(locationName){const views=this._manager._viewsForLocation(locationName);if(this._allowReorder){let i=0;const persistedOrders=this._tabOrderSetting.get();const orders=new Map();for(const view of views)
orders.set(view.viewId(),persistedOrders[view.viewId()]||(++i)*UI.ViewManager._TabbedLocation.orderStep);views.sort((a,b)=>orders.get(a.viewId())-orders.get(b.viewId()));}
for(const view of views){const id=view.viewId();this._views.set(id,view);view[UI.ViewManager._Location.symbol]=this;if(view.isTransient())
continue;if(!view.isCloseable())
this._appendTab(view);else if(this._closeableTabSetting.get()[id])
this._appendTab(view);}
if(this._defaultTab&&this._tabbedPane.hasTab(this._defaultTab))
this._tabbedPane.selectTab(this._defaultTab);else if(this._lastSelectedTabSetting&&this._tabbedPane.hasTab(this._lastSelectedTabSetting.get()))
this._tabbedPane.selectTab(this._lastSelectedTabSetting.get());}
_appendTabsToMenu(contextMenu){const views=Array.from(this._views.values());views.sort((viewa,viewb)=>viewa.title().localeCompare(viewb.title()));for(const view of views){const title=Common.UIString(view.title());contextMenu.defaultSection().appendItem(title,this.showView.bind(this,view,undefined,true));}}
_appendTab(view,index){this._tabbedPane.appendTab(view.viewId(),view.title(),new UI.ViewManager._ContainerWidget(view),undefined,false,view.isCloseable()||view.isTransient(),index);}
appendView(view,insertBefore){if(this._tabbedPane.hasTab(view.viewId()))
return;const oldLocation=view[UI.ViewManager._Location.symbol];if(oldLocation&&oldLocation!==this)
oldLocation.removeView(view);view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);this._views.set(view.viewId(),view);let index=undefined;const tabIds=this._tabbedPane.tabIds();if(this._allowReorder){const orderSetting=this._tabOrderSetting.get();const order=orderSetting[view.viewId()];for(let i=0;order&&i<tabIds.length;++i){if(orderSetting[tabIds[i]]&&orderSetting[tabIds[i]]>order){index=i;break;}}}else if(insertBefore){for(let i=0;i<tabIds.length;++i){if(tabIds[i]===insertBefore.viewId()){index=i;break;}}}
this._appendTab(view,index);if(view.isCloseable()){const tabs=this._closeableTabSetting.get();const tabId=view.viewId();if(!tabs[tabId]){tabs[tabId]=true;this._closeableTabSetting.set(tabs);}}
this._persistTabOrder();}
showView(view,insertBefore,userGesture,omitFocus){this.appendView(view,insertBefore);this._tabbedPane.selectTab(view.viewId(),userGesture);if(!omitFocus)
this._tabbedPane.focus();const widget=(this._tabbedPane.tabView(view.viewId()));return widget._materialize();}
removeView(view){if(!this._tabbedPane.hasTab(view.viewId()))
return;delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());this._tabbedPane.closeTab(view.viewId());this._views.delete(view.viewId());}
_tabSelected(event){const tabId=(event.data.tabId);if(this._lastSelectedTabSetting&&event.data['isUserGesture'])
this._lastSelectedTabSetting.set(tabId);}
_tabClosed(event){const id=(event.data['tabId']);const tabs=this._closeableTabSetting.get();if(tabs[id]){delete tabs[id];this._closeableTabSetting.set(tabs);}
this._views.get(id).disposeView();}
_persistTabOrder(){const tabIds=this._tabbedPane.tabIds();const tabOrders={};for(let i=0;i<tabIds.length;i++)
tabOrders[tabIds[i]]=(i+1)*UI.ViewManager._TabbedLocation.orderStep;this._tabOrderSetting.set(tabOrders);}};UI.ViewManager._TabbedLocation.orderStep=10;UI.ViewManager._StackLocation=class extends UI.ViewManager._Location{constructor(manager,revealCallback,location){const vbox=new UI.VBox();super(manager,vbox,revealCallback);this._vbox=vbox;this._expandableContainers=new Map();if(location)
this.appendApplicableItems(location);}
appendView(view,insertBefore){const oldLocation=view[UI.ViewManager._Location.symbol];if(oldLocation&&oldLocation!==this)
oldLocation.removeView(view);let container=this._expandableContainers.get(view.viewId());if(!container){view[UI.ViewManager._Location.symbol]=this;this._manager._views.set(view.viewId(),view);container=new UI.ViewManager._ExpandableContainerWidget(view);let beforeElement=null;if(insertBefore){const beforeContainer=insertBefore[UI.ViewManager._ExpandableContainerWidget._symbol];beforeElement=beforeContainer?beforeContainer.element:null;}
container.show(this._vbox.contentElement,beforeElement);this._expandableContainers.set(view.viewId(),container);}}
showView(view,insertBefore){this.appendView(view,insertBefore);const container=this._expandableContainers.get(view.viewId());return container._expand();}
removeView(view){const container=this._expandableContainers.get(view.viewId());if(!container)
return;container.detach();this._expandableContainers.delete(view.viewId());delete view[UI.ViewManager._Location.symbol];this._manager._views.delete(view.viewId());}
appendApplicableItems(locationName){for(const view of this._manager._viewsForLocation(locationName))
this.appendView(view);}};UI.viewManager;;UI.TreeOutline=class extends Common.Object{constructor(){super();this._createRootElement();this.selectedTreeElement=null;this.expandTreeElementsWhenArrowing=false;this._comparator=null;this.contentElement=this._rootElement._childrenListNode;this.contentElement.addEventListener('keydown',this._treeKeyDown.bind(this),true);this._focusable=true;this.setFocusable(this._focusable);if(this._focusable)
this.contentElement.setAttribute('tabIndex',-1);this.element=this.contentElement;UI.ARIAUtils.markAsTree(this.element);this._paddingSize=0;}
_createRootElement(){this._rootElement=new UI.TreeElement();this._rootElement.treeOutline=this;this._rootElement.root=true;this._rootElement.selectable=false;this._rootElement.expanded=true;this._rootElement._childrenListNode.classList.remove('children');}
rootElement(){return this._rootElement;}
firstChild(){return this._rootElement.firstChild();}
_lastDescendent(){let last=this._rootElement.lastChild();while(last.expanded&&last.childCount())
last=last.lastChild();return last;}
appendChild(child){this._rootElement.appendChild(child);}
insertChild(child,index){this._rootElement.insertChild(child,index);}
removeChild(child){this._rootElement.removeChild(child);}
removeChildren(){this._rootElement.removeChildren();}
treeElementFromPoint(x,y){const node=this.contentElement.ownerDocument.deepElementFromPoint(x,y);if(!node)
return null;const listNode=node.enclosingNodeOrSelfWithNodeNameInArray(['ol','li']);if(listNode)
return listNode.parentTreeElement||listNode.treeElement;return null;}
treeElementFromEvent(event){return event?this.treeElementFromPoint(event.pageX,event.pageY):null;}
setComparator(comparator){this._comparator=comparator;}
setFocusable(focusable){if(focusable){this._focusable=true;this.contentElement.setAttribute('tabIndex',-1);if(this.selectedTreeElement)
this.selectedTreeElement._setFocusable(true);}else{this._focusable=false;this.contentElement.removeAttribute('tabIndex');if(this.selectedTreeElement)
this.selectedTreeElement._setFocusable(false);}}
focus(){if(this.selectedTreeElement)
this.selectedTreeElement.listItemElement.focus();else
this.contentElement.focus();}
_bindTreeElement(element){if(element.treeOutline)
console.error('Binding element for the second time: '+new Error().stack);element.treeOutline=this;element.onbind();}
_unbindTreeElement(element){if(!element.treeOutline)
console.error('Unbinding element that was not bound: '+new Error().stack);element.deselect();element.onunbind();element.treeOutline=null;}
selectPrevious(){let nextSelectedElement=this.selectedTreeElement.traversePreviousTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
selectNext(){let nextSelectedElement=this.selectedTreeElement.traverseNextTreeElement(true);while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing);if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
_selectFirst(){let first=this.firstChild();while(first&&!first.selectable)
first=first.traverseNextTreeElement(true);if(!first)
return false;first.select(false,true);return true;}
_selectLast(){let last=this._lastDescendent();while(last&&!last.selectable)
last=last.traversePreviousTreeElement(true);if(!last)
return false;last.select(false,true);return true;}
setPaddingSize(paddingSize){this._paddingSize=paddingSize;}
_treeKeyDown(event){if(!this.selectedTreeElement||event.target!==this.selectedTreeElement.listItemElement||event.shiftKey||event.metaKey||event.ctrlKey)
return;let handled=false;if(event.key==='ArrowUp'&&!event.altKey){handled=this.selectPrevious();}else if(event.key==='ArrowDown'&&!event.altKey){handled=this.selectNext();}else if(event.key==='ArrowLeft'){handled=this.selectedTreeElement.collapseOrAscend(event.altKey);}else if(event.key==='ArrowRight'){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else{handled=this.selectedTreeElement.descendOrExpand(event.altKey);}}else if(event.keyCode===8||event.keyCode===46){handled=this.selectedTreeElement.ondelete();}else if(isEnterKey(event)){handled=this.selectedTreeElement.onenter();}else if(event.keyCode===UI.KeyboardShortcut.Keys.Space.code){handled=this.selectedTreeElement.onspace();}else if(event.key==='Home'){handled=this._selectFirst();}else if(event.key==='End'){handled=this._selectLast();}
if(handled)
event.consume(true);}
_deferredScrollIntoView(treeElement,center){if(!this._treeElementToScrollIntoView)
this.element.window().requestAnimationFrame(deferredScrollIntoView.bind(this));this._treeElementToScrollIntoView=treeElement;this._centerUponScrollIntoView=center;function deferredScrollIntoView(){this._treeElementToScrollIntoView.listItemElement.scrollIntoViewIfNeeded(this._centerUponScrollIntoView);delete this._treeElementToScrollIntoView;delete this._centerUponScrollIntoView;}}};UI.TreeOutline.Events={ElementAttached:Symbol('ElementAttached'),ElementExpanded:Symbol('ElementExpanded'),ElementCollapsed:Symbol('ElementCollapsed'),ElementSelected:Symbol('ElementSelected')};UI.TreeOutlineInShadow=class extends UI.TreeOutline{constructor(){super();this.contentElement.classList.add('tree-outline');this.element=createElement('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/treeoutline.css');this._disclosureElement=this._shadowRoot.createChild('div','tree-outline-disclosure');this._disclosureElement.appendChild(this.contentElement);this._renderSelection=true;}
registerRequiredCSS(cssFile){UI.appendStyle(this._shadowRoot,cssFile);}
hideOverflow(){this._disclosureElement.classList.add('tree-outline-disclosure-hide-overflow');}
makeDense(){this.contentElement.classList.add('tree-outline-dense');}};UI.TreeElement=class{constructor(title,expandable){this.treeOutline=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this._boundOnFocus=this._onFocus.bind(this);this._boundOnBlur=this._onBlur.bind(this);this._listItemNode=createElement('li');this._titleElement=this._listItemNode.createChild('span','tree-element-title');this._listItemNode.treeElement=this;if(title)
this.title=title;this._listItemNode.addEventListener('mousedown',this._handleMouseDown.bind(this),false);this._listItemNode.addEventListener('click',this._treeElementToggled.bind(this),false);this._listItemNode.addEventListener('dblclick',this._handleDoubleClick.bind(this),false);UI.ARIAUtils.markAsTreeitem(this._listItemNode);this._childrenListNode=createElement('ol');this._childrenListNode.parentTreeElement=this;this._childrenListNode.classList.add('children');UI.ARIAUtils.markAsGroup(this._childrenListNode);this._hidden=false;this._selectable=true;this.expanded=false;this.selected=false;this.setExpandable(expandable||false);this._collapsible=true;}
hasAncestor(ancestor){if(!ancestor)
return false;let currentNode=this.parent;while(currentNode){if(ancestor===currentNode)
return true;currentNode=currentNode.parent;}
return false;}
hasAncestorOrSelf(ancestor){return this===ancestor||this.hasAncestor(ancestor);}
children(){return this._children||[];}
childCount(){return this._children?this._children.length:0;}
firstChild(){return this._children?this._children[0]:null;}
lastChild(){return this._children?this._children[this._children.length-1]:null;}
childAt(index){return this._children?this._children[index]:null;}
indexOfChild(child){return this._children?this._children.indexOf(child):-1;}
appendChild(child){if(!this._children)
this._children=[];let insertionIndex;if(this.treeOutline&&this.treeOutline._comparator)
insertionIndex=this._children.lowerBound(child,this.treeOutline._comparator);else
insertionIndex=this._children.length;this.insertChild(child,insertionIndex);}
insertChild(child,index){if(!this._children)
this._children=[];if(!child)
throw'child can\'t be undefined or null';console.assert(!child.parent,'Attempting to insert a child that is already in the tree, reparenting is not supported.');const previousChild=(index>0?this._children[index-1]:null);if(previousChild){previousChild.nextSibling=child;child.previousSibling=previousChild;}else{child.previousSibling=null;}
const nextChild=this._children[index];if(nextChild){nextChild.previousSibling=child;child.nextSibling=nextChild;}else{child.nextSibling=null;}
this._children.splice(index,0,child);this.setExpandable(true);child.parent=this;if(this.treeOutline)
this.treeOutline._bindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._bindTreeElement(current);child.onattach();child._ensureSelection();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementAttached,child);const nextSibling=child.nextSibling?child.nextSibling._listItemNode:null;this._childrenListNode.insertBefore(child._listItemNode,nextSibling);this._childrenListNode.insertBefore(child._childrenListNode,nextSibling);if(child.selected)
child.select();if(child.expanded)
child.expand();}
removeChildAtIndex(childIndex){if(childIndex<0||childIndex>=this._children.length)
throw'childIndex out of range';const child=this._children[childIndex];this._children.splice(childIndex,1);const parent=child.parent;if(this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(child)){if(child.nextSibling)
child.nextSibling.select(true);else if(child.previousSibling)
child.previousSibling.select(true);else if(parent)
parent.select(true);}
if(child.previousSibling)
child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling)
child.nextSibling.previousSibling=child.previousSibling;child.parent=null;if(this.treeOutline)
this.treeOutline._unbindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._unbindTreeElement(current);child._detach();}
removeChild(child){if(!child)
throw'child can\'t be undefined or null';if(child.parent!==this)
return;const childIndex=this._children.indexOf(child);if(childIndex===-1)
throw'child not found in this node\'s children';this.removeChildAtIndex(childIndex);}
removeChildren(){if(!this.root&&this.treeOutline&&this.treeOutline.selectedTreeElement&&this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this))
this.select(true);for(let i=0;this._children&&i<this._children.length;++i){const child=this._children[i];child.previousSibling=null;child.nextSibling=null;child.parent=null;if(this.treeOutline)
this.treeOutline._unbindTreeElement(child);for(let current=child.firstChild();this.treeOutline&&current;current=current.traverseNextTreeElement(false,child,true))
this.treeOutline._unbindTreeElement(current);child._detach();}
this._children=[];}
get selectable(){if(this._hidden)
return false;return this._selectable;}
set selectable(x){this._selectable=x;}
get listItemElement(){return this._listItemNode;}
titleElement(){return this._titleElement;}
get childrenListElement(){return this._childrenListNode;}
get title(){return this._title;}
set title(x){if(this._title===x)
return;this._title=x;if(typeof x==='string'){this._titleElement.textContent=x;this.tooltip=x;}else{this._titleElement=x;this.tooltip='';}
this._listItemNode.removeChildren();if(this._leadingIconsElement)
this._listItemNode.appendChild(this._leadingIconsElement);this._listItemNode.appendChild(this._titleElement);if(this._trailingIconsElement)
this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();}
titleAsText(){if(!this._title)
return'';if(typeof this._title==='string')
return this._title;return this._title.textContent;}
startEditingTitle(editingConfig){UI.InplaceEditor.startEditing(this._titleElement,editingConfig);this.treeOutline._shadowRoot.getSelection().selectAllChildren(this._titleElement);}
setLeadingIcons(icons){if(!this._leadingIconsElement&&!icons.length)
return;if(!this._leadingIconsElement){this._leadingIconsElement=createElementWithClass('div','leading-icons');this._leadingIconsElement.classList.add('icons-container');this._listItemNode.insertBefore(this._leadingIconsElement,this._titleElement);this._ensureSelection();}
this._leadingIconsElement.removeChildren();for(const icon of icons)
this._leadingIconsElement.appendChild(icon);}
setTrailingIcons(icons){if(!this._trailingIconsElement&&!icons.length)
return;if(!this._trailingIconsElement){this._trailingIconsElement=createElementWithClass('div','trailing-icons');this._trailingIconsElement.classList.add('icons-container');this._listItemNode.appendChild(this._trailingIconsElement);this._ensureSelection();}
this._trailingIconsElement.removeChildren();for(const icon of icons)
this._trailingIconsElement.appendChild(icon);}
get tooltip(){return this._tooltip||'';}
set tooltip(x){if(this._tooltip===x)
return;this._tooltip=x;this._listItemNode.title=x;}
isExpandable(){return this._expandable;}
setExpandable(expandable){if(this._expandable===expandable)
return;this._expandable=expandable;this._listItemNode.classList.toggle('parent',expandable);if(!expandable){this.collapse();UI.ARIAUtils.unsetExpanded(this._listItemNode);}else{UI.ARIAUtils.setExpanded(this._listItemNode,false);}}
setCollapsible(collapsible){if(this._collapsible===collapsible)
return;this._collapsible=collapsible;this._listItemNode.classList.toggle('always-parent',!collapsible);if(!collapsible)
this.expand();}
get hidden(){return this._hidden;}
set hidden(x){if(this._hidden===x)
return;this._hidden=x;this._listItemNode.classList.toggle('hidden',x);this._childrenListNode.classList.toggle('hidden',x);}
invalidateChildren(){if(this._children){this.removeChildren();this._children=null;}}
computeLeftMargin(){let treeElement=this.parent;let depth=0;while(treeElement!==null){depth++;treeElement=treeElement.parent;}
return-(this.treeOutline._paddingSize*(depth-1)+4);}
_ensureSelection(){if(!this.treeOutline||!this.treeOutline._renderSelection)
return;if(!this._selectionElement)
this._selectionElement=createElementWithClass('div','selection fill');if(this.treeOutline._paddingSize)
this._selectionElement.style.setProperty('margin-left',this.computeLeftMargin()+'px');this._listItemNode.insertBefore(this._selectionElement,this.listItemElement.firstChild);}
_treeElementToggled(event){const element=event.currentTarget;if(element.treeElement!==this||element.hasSelection())
return;const toggleOnClick=this.toggleOnClick&&!this.selectable;const isInTriangle=this.isEventWithinDisclosureTriangle(event);if(!toggleOnClick&&!isInTriangle)
return;if(this.expanded){if(event.altKey)
this.collapseRecursively();else
this.collapse();}else{if(event.altKey)
this.expandRecursively();else
this.expand();}
event.consume();}
_handleMouseDown(event){const element=event.currentTarget;if(!element)
return;if(!this.selectable)
return;if(element.treeElement!==this)
return;if(this.isEventWithinDisclosureTriangle(event))
return;this.selectOnMouseDown(event);}
_handleDoubleClick(event){const element=event.currentTarget;if(!element||element.treeElement!==this)
return;const handled=this.ondblclick(event);if(handled)
return;if(this._expandable&&!this.expanded)
this.expand();}
_detach(){this._listItemNode.remove();this._childrenListNode.remove();}
collapse(){if(!this.expanded||!this._collapsible)
return;this._listItemNode.classList.remove('expanded');this._childrenListNode.classList.remove('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,false);this.expanded=false;this.oncollapse();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementCollapsed,this);}
collapseRecursively(){let item=this;while(item){if(item.expanded)
item.collapse();item=item.traverseNextTreeElement(false,this,true);}}
collapseChildren(){if(!this._children)
return;for(const child of this._children)
child.collapseRecursively();}
expand(){if(!this._expandable||(this.expanded&&this._children))
return;this.expanded=true;this._populateIfNeeded();this._listItemNode.classList.add('expanded');this._childrenListNode.classList.add('expanded');UI.ARIAUtils.setExpanded(this._listItemNode,true);if(this.treeOutline){this.onexpand();this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementExpanded,this);}}
expandRecursively(maxDepth){let item=this;const info={};let depth=0;if(isNaN(maxDepth))
maxDepth=3;while(item){if(depth<maxDepth)
item.expand();item=item.traverseNextTreeElement(false,this,(depth>=maxDepth),info);depth+=info.depthChange;}}
collapseOrAscend(altKey){if(this.expanded){if(altKey)
this.collapseRecursively();else
this.collapse();return true;}
if(!this.parent||this.parent.root)
return false;if(!this.parent.selectable){this.parent.collapse();return true;}
let nextSelectedElement=this.parent;while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.parent;if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
descendOrExpand(altKey){if(!this._expandable)
return false;if(!this.expanded){if(altKey)
this.expandRecursively();else
this.expand();return true;}
let nextSelectedElement=this.firstChild();while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.nextSibling;if(!nextSelectedElement)
return false;nextSelectedElement.select(false,true);return true;}
reveal(center){let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
currentAncestor.expand();currentAncestor=currentAncestor.parent;}
this.treeOutline._deferredScrollIntoView(this,!!center);}
revealed(){let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
return false;currentAncestor=currentAncestor.parent;}
return true;}
selectOnMouseDown(event){if(this.select(false,true))
event.consume(true);}
select(omitFocus,selectedByUser){if(!this.treeOutline||!this.selectable||this.selected)
return false;const lastSelected=this.treeOutline.selectedTreeElement;this.treeOutline.selectedTreeElement=null;if(this.treeOutline._rootElement===this){if(lastSelected)
lastSelected.deselect();return false;}
this.selected=true;this.treeOutline.selectedTreeElement=this;if(this.treeOutline._focusable)
this._setFocusable(true);if(!omitFocus||this.treeOutline.contentElement.hasFocus())
this.listItemElement.focus();this._listItemNode.classList.add('selected');this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementSelected,this);if(lastSelected)
lastSelected.deselect();return this.onselect(selectedByUser);}
_setFocusable(focusable){if(focusable){this._listItemNode.setAttribute('tabIndex',0);this._listItemNode.addEventListener('focus',this._boundOnFocus,false);this._listItemNode.addEventListener('blur',this._boundOnBlur,false);}else{this._listItemNode.removeAttribute('tabIndex');this._listItemNode.removeEventListener('focus',this._boundOnFocus,false);this._listItemNode.removeEventListener('blur',this._boundOnBlur,false);}}
_onFocus(){this._listItemNode.classList.add('force-white-icons');}
_onBlur(){this._listItemNode.classList.remove('force-white-icons');}
revealAndSelect(omitFocus){this.reveal(true);this.select(omitFocus);}
deselect(){const hadFocus=this._listItemNode.hasFocus();this.selected=false;this._listItemNode.classList.remove('selected');this._setFocusable(false);if(this.treeOutline&&this.treeOutline.selectedTreeElement===this){this.treeOutline.selectedTreeElement=null;if(hadFocus)
this.treeOutline.focus();}}
_populateIfNeeded(){if(this.treeOutline&&this._expandable&&!this._children){this._children=[];this.onpopulate();}}
onpopulate(){}
onenter(){return false;}
ondelete(){return false;}
onspace(){return false;}
onbind(){}
onunbind(){}
onattach(){}
onexpand(){}
oncollapse(){}
ondblclick(e){return false;}
onselect(selectedByUser){return false;}
traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate,info){if(!dontPopulate)
this._populateIfNeeded();if(info)
info.depthChange=0;let element=skipUnrevealed?(this.revealed()?this.firstChild():null):this.firstChild();if(element&&(!skipUnrevealed||(skipUnrevealed&&this.expanded))){if(info)
info.depthChange=1;return element;}
if(this===stayWithin)
return null;element=skipUnrevealed?(this.revealed()?this.nextSibling:null):this.nextSibling;if(element)
return element;element=this;while(element&&!element.root&&!(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling)&&element.parent!==stayWithin){if(info)
info.depthChange-=1;element=element.parent;}
if(!element||element.root)
return null;return(skipUnrevealed?(element.revealed()?element.nextSibling:null):element.nextSibling);}
traversePreviousTreeElement(skipUnrevealed,dontPopulate){let element=skipUnrevealed?(this.revealed()?this.previousSibling:null):this.previousSibling;if(!dontPopulate&&element)
element._populateIfNeeded();while(element&&(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild())){if(!dontPopulate)
element._populateIfNeeded();element=(skipUnrevealed?(element.revealed()&&element.expanded?element.lastChild():null):element.lastChild());}
if(element)
return element;if(!this.parent||this.parent.root)
return null;return this.parent;}
isEventWithinDisclosureTriangle(event){const paddingLeftValue=window.getComputedStyle(this._listItemNode).paddingLeft;console.assert(paddingLeftValue.endsWith('px'));const computedLeftPadding=parseFloat(paddingLeftValue);const left=this._listItemNode.totalOffsetLeft()+computedLeftPadding;return event.pageX>=left&&event.pageX<=left+UI.TreeElement._ArrowToggleWidth&&this._expandable;}};UI.TreeElement._ArrowToggleWidth=10;(function(){const img=new Image();if(window.devicePixelRatio>1)
img.src='Images/treeoutlineTriangles_2x.png';else
img.src='Images/treeoutlineTriangles.png';UI.TreeElement._imagePreload=img;})();;UI.InspectorView=class extends UI.VBox{constructor(){super();UI.GlassPane.setContainer(this.element);this.setMinimumSize(240,72);this._drawerSplitWidget=new UI.SplitWidget(false,true,'Inspector.drawerSplitViewState',200,200);this._drawerSplitWidget.hideSidebar();this._drawerSplitWidget.hideDefaultResizer();this._drawerSplitWidget.enableShowModeSaving();this._drawerSplitWidget.show(this.element);this._drawerTabbedLocation=UI.viewManager.createTabbedLocation(this._showDrawer.bind(this,false),'drawer-view',true,true);this._drawerTabbedLocation.enableMoreTabsButton();this._drawerTabbedPane=this._drawerTabbedLocation.tabbedPane();this._drawerTabbedPane.setMinimumSize(0,27);const closeDrawerButton=new UI.ToolbarButton(Common.UIString('Close drawer'),'largeicon-delete');closeDrawerButton.addEventListener(UI.ToolbarButton.Events.Click,this._closeDrawer,this);this._drawerTabbedPane.rightToolbar().appendToolbarItem(closeDrawerButton);this._drawerSplitWidget.installResizer(this._drawerTabbedPane.headerElement());this._drawerSplitWidget.setSidebarWidget(this._drawerTabbedPane);this._drawerTabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._drawerTabSelected,this);this._tabbedLocation=UI.viewManager.createTabbedLocation(InspectorFrontendHost.bringToFront.bind(InspectorFrontendHost),'panel',true,true,Runtime.queryParam('panel'));this._tabbedPane=this._tabbedLocation.tabbedPane();this._tabbedPane.registerRequiredCSS('ui/inspectorViewTabbedPane.css');this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);this._tabbedPane.setAccessibleName(Common.UIString('Panels'));if(Host.isUnderTest())
this._tabbedPane.setAutoSelectFirstItemOnShow(false);this._drawerSplitWidget.setMainWidget(this._tabbedPane);this._keyDownBound=this._keyDown.bind(this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ShowPanel,showPanel.bind(this));function showPanel(event){const panelName=(event.data);this.showPanel(panelName);}}
static instance(){return(self.runtime.sharedInstance(UI.InspectorView));}
wasShown(){this.element.ownerDocument.addEventListener('keydown',this._keyDownBound,false);}
willHide(){this.element.ownerDocument.removeEventListener('keydown',this._keyDownBound,false);}
resolveLocation(locationName){if(locationName==='drawer-view')
return this._drawerTabbedLocation;if(locationName==='panel')
return this._tabbedLocation;return null;}
createToolbars(){this._tabbedPane.leftToolbar().appendLocationItems('main-toolbar-left');this._tabbedPane.rightToolbar().appendLocationItems('main-toolbar-right');}
addPanel(view){this._tabbedLocation.appendView(view);}
hasPanel(panelName){return this._tabbedPane.hasTab(panelName);}
panel(panelName){return(UI.viewManager.view(panelName).widget());}
onSuspendStateChanged(allTargetsSuspended){this._currentPanelLocked=allTargetsSuspended;this._tabbedPane.setCurrentTabLocked(this._currentPanelLocked);this._tabbedPane.leftToolbar().setEnabled(!this._currentPanelLocked);this._tabbedPane.rightToolbar().setEnabled(!this._currentPanelLocked);}
canSelectPanel(panelName){return!this._currentPanelLocked||this._tabbedPane.selectedTabId===panelName;}
showPanel(panelName){return UI.viewManager.showView(panelName);}
setPanelIcon(panelName,icon){this._tabbedPane.setTabIcon(panelName,icon);}
currentPanelDeprecated(){return(UI.viewManager.materializedWidget(this._tabbedPane.selectedTabId||''));}
_showDrawer(focus){if(this._drawerTabbedPane.isShowing())
return;this._drawerSplitWidget.showBoth();if(focus)
this._focusRestorer=new UI.WidgetFocusRestorer(this._drawerTabbedPane);else
this._focusRestorer=null;}
drawerVisible(){return this._drawerTabbedPane.isShowing();}
_closeDrawer(){if(!this._drawerTabbedPane.isShowing())
return;if(this._focusRestorer)
this._focusRestorer.restore();this._drawerSplitWidget.hideSidebar(true);}
setDrawerMinimized(minimized){this._drawerSplitWidget.setSidebarMinimized(minimized);this._drawerSplitWidget.setResizable(!minimized);}
isDrawerMinimized(){return this._drawerSplitWidget.isSidebarMinimized();}
closeDrawerTab(id,userGesture){this._drawerTabbedPane.closeTab(id,userGesture);}
_keyDown(event){const keyboardEvent=(event);if(!UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent)||event.altKey||event.shiftKey)
return;const panelShortcutEnabled=Common.moduleSetting('shortcutPanelSwitch').get();if(panelShortcutEnabled){let panelIndex=-1;if(event.keyCode>0x30&&event.keyCode<0x3A)
panelIndex=event.keyCode-0x31;else if(event.keyCode>0x60&&event.keyCode<0x6A&&keyboardEvent.location===KeyboardEvent.DOM_KEY_LOCATION_NUMPAD)
panelIndex=event.keyCode-0x61;if(panelIndex!==-1){const panelName=this._tabbedPane.allTabs()[panelIndex];if(panelName){if(!UI.Dialog.hasInstance()&&!this._currentPanelLocked)
this.showPanel(panelName);event.consume(true);}}}
if(event.key==='['){this._tabbedPane.selectPrevTab();event.consume(true);}
if(event.key===']'){this._tabbedPane.selectNextTab();event.consume(true);}}
onResize(){UI.GlassPane.containerMoved(this.element);}
topResizerElement(){return this._tabbedPane.headerElement();}
toolbarItemResized(){this._tabbedPane.headerResized();}
_tabSelected(event){const tabId=(event.data['tabId']);Host.userMetrics.panelShown(tabId);}
_drawerTabSelected(event){const tabId=(event.data['tabId']);Host.userMetrics.drawerShown(tabId);}
setOwnerSplit(splitWidget){this._ownerSplitWidget=splitWidget;}
minimize(){if(this._ownerSplitWidget)
this._ownerSplitWidget.setSidebarMinimized(true);}
restore(){if(this._ownerSplitWidget)
this._ownerSplitWidget.setSidebarMinimized(false);}};UI.inspectorView;UI.InspectorView.DrawerToggleActionDelegate=class{handleAction(context,actionId){if(UI.inspectorView.drawerVisible())
UI.inspectorView._closeDrawer();else
UI.inspectorView._showDrawer(true);return true;}};;UI.ActionRegistry=class{constructor(){this._actionsById=new Map();this._registerActions();}
_registerActions(){self.runtime.extensions('action').forEach(registerExtension,this);function registerExtension(extension){if(!extension.canInstantiate())
return;const actionId=extension.descriptor()['actionId'];console.assert(actionId);console.assert(!this._actionsById.get(actionId));const action=new UI.Action(extension);if(!action.category()||action.title())
this._actionsById.set(actionId,action);else
console.error(`Category actions require a title for command menu: ${actionId}`);}}
availableActions(){return this.applicableActions(this._actionsById.keysArray(),UI.context);}
applicableActions(actionIds,context){const extensions=[];actionIds.forEach(function(actionId){const action=this._actionsById.get(actionId);if(action)
extensions.push(action._extension);},this);return context.applicableExtensions(extensions).valuesArray().map(extensionToAction.bind(this));function extensionToAction(extension){return(this.action(extension.descriptor()['actionId']));}}
action(actionId){return this._actionsById.get(actionId)||null;}};UI.Action=class extends Common.Object{constructor(extension){super();this._extension=extension;this._enabled=true;this._toggled=false;}
id(){return this._extension.descriptor()['actionId'];}
execute(){return this._extension.instance().then(handleAction.bind(this));function handleAction(actionDelegate){const actionId=this._extension.descriptor()['actionId'];const delegate=(actionDelegate);return delegate.handleAction(UI.context,actionId);}}
icon(){return this._extension.descriptor()['iconClass']||'';}
toggledIcon(){return this._extension.descriptor()['toggledIconClass']||'';}
toggleWithRedColor(){return!!this._extension.descriptor()['toggleWithRedColor'];}
setEnabled(enabled){if(this._enabled===enabled)
return;this._enabled=enabled;this.dispatchEventToListeners(UI.Action.Events.Enabled,enabled);}
enabled(){return this._enabled;}
category(){return this._extension.descriptor()['category']||'';}
tags(){return this._extension.descriptor()['tags']||'';}
title(){let title=this._extension.title();const options=this._extension.descriptor()['options'];if(options){for(const pair of options){if(pair['value']!==this._toggled)
title=pair['title'];}}
return title;}
toggled(){return this._toggled;}
setToggled(toggled){if(this._toggled===toggled)
return;this._toggled=toggled;this.dispatchEventToListeners(UI.Action.Events.Toggled,toggled);}};UI.Action.Events={Enabled:Symbol('Enabled'),Toggled:Symbol('Toggled')};UI.ActionDelegate=function(){};UI.ActionDelegate.prototype={handleAction(context,actionId){}};UI.actionRegistry;;UI.ShortcutRegistry=class{constructor(actionRegistry,document){this._actionRegistry=actionRegistry;this._defaultKeyToActions=new Multimap();this._defaultActionToShortcut=new Multimap();this._registerBindings(document);}
_applicableActions(key){return this._actionRegistry.applicableActions(this._defaultActionsForKey(key).valuesArray(),UI.context);}
_defaultActionsForKey(key){return this._defaultKeyToActions.get(String(key));}
shortcutDescriptorsForAction(actionId){return this._defaultActionToShortcut.get(actionId).valuesArray();}
keysForActions(actionIds){const result=[];for(let i=0;i<actionIds.length;++i){const descriptors=this.shortcutDescriptorsForAction(actionIds[i]);for(let j=0;j<descriptors.length;++j)
result.push(descriptors[j].key);}
return result;}
shortcutTitleForAction(actionId){const descriptors=this.shortcutDescriptorsForAction(actionId);if(descriptors.length)
return descriptors[0].name;}
handleShortcut(event){this.handleKey(UI.KeyboardShortcut.makeKeyFromEvent(event),event.key,event);}
eventMatchesAction(event,actionId){console.assert(this._defaultActionToShortcut.has(actionId),'Unknown action '+actionId);const key=UI.KeyboardShortcut.makeKeyFromEvent(event);return this._defaultActionToShortcut.get(actionId).valuesArray().some(descriptor=>descriptor.key===key);}
addShortcutListener(element,actionId,listener,capture){console.assert(this._defaultActionToShortcut.has(actionId),'Unknown action '+actionId);element.addEventListener('keydown',event=>{if(!this.eventMatchesAction((event),actionId)||!listener.call(null))
return;event.consume(true);},capture);}
handleKey(key,domKey,event){const keyModifiers=key>>8;const actions=this._applicableActions(key);if(!actions.length)
return;if(UI.Dialog.hasInstance()){if(event&&!isPossiblyInputKey())
event.consume(true);return;}
if(!isPossiblyInputKey()){if(event)
event.consume(true);processNextAction.call(this,false);}else{this._pendingActionTimer=setTimeout(processNextAction.bind(this,false),0);}
function processNextAction(handled){delete this._pendingActionTimer;const action=actions.shift();if(!action||handled)
return;action.execute().then(processNextAction.bind(this));}
function isPossiblyInputKey(){if(!event||!UI.isEditing()||/^F\d+|Control|Shift|Alt|Meta|Escape|Win|U\+001B$/.test(domKey))
return false;if(!keyModifiers)
return true;const modifiers=UI.KeyboardShortcut.Modifiers;if((keyModifiers&(modifiers.Ctrl|modifiers.Alt))===(modifiers.Ctrl|modifiers.Alt))
return Host.isWin();return!hasModifier(modifiers.Ctrl)&&!hasModifier(modifiers.Alt)&&!hasModifier(modifiers.Meta);}
function hasModifier(mod){return!!(keyModifiers&mod);}}
registerShortcut(actionId,shortcut){const descriptor=UI.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut);if(!descriptor)
return;this._defaultActionToShortcut.set(actionId,descriptor);this._defaultKeyToActions.set(String(descriptor.key),actionId);}
dismissPendingShortcutAction(){if(this._pendingActionTimer){clearTimeout(this._pendingActionTimer);delete this._pendingActionTimer;}}
_registerBindings(document){document.addEventListener('input',this.dismissPendingShortcutAction.bind(this),true);const extensions=self.runtime.extensions('action');extensions.forEach(registerExtension,this);function registerExtension(extension){const descriptor=extension.descriptor();const bindings=descriptor['bindings'];for(let i=0;bindings&&i<bindings.length;++i){if(!platformMatches(bindings[i].platform))
continue;const shortcuts=bindings[i]['shortcut'].split(/\s+/);shortcuts.forEach(this.registerShortcut.bind(this,descriptor['actionId']));}}
function platformMatches(platformsString){if(!platformsString)
return true;const platforms=platformsString.split(',');let isMatch=false;const currentPlatform=Host.platform();for(let i=0;!isMatch&&i<platforms.length;++i)
isMatch=platforms[i]===currentPlatform;return isMatch;}}};UI.ShortcutRegistry.ForwardedShortcut=class{};UI.ShortcutRegistry.ForwardedShortcut.instance=new UI.ShortcutRegistry.ForwardedShortcut();UI.shortcutRegistry;;UI.Context=class{constructor(){this._flavors=new Map();this._eventDispatchers=new Map();}
setFlavor(flavorType,flavorValue){const value=this._flavors.get(flavorType)||null;if(value===flavorValue)
return;if(flavorValue)
this._flavors.set(flavorType,flavorValue);else
this._flavors.remove(flavorType);this._dispatchFlavorChange(flavorType,flavorValue);}
_dispatchFlavorChange(flavorType,flavorValue){for(const extension of self.runtime.extensions(UI.ContextFlavorListener)){if(extension.hasContextType(flavorType)){extension.instance().then(instance=>(instance).flavorChanged(flavorValue));}}
const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher)
return;dispatcher.dispatchEventToListeners(UI.Context.Events.FlavorChanged,flavorValue);}
addFlavorChangeListener(flavorType,listener,thisObject){let dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){dispatcher=new Common.Object();this._eventDispatchers.set(flavorType,dispatcher);}
dispatcher.addEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);}
removeFlavorChangeListener(flavorType,listener,thisObject){const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher)
return;dispatcher.removeEventListener(UI.Context.Events.FlavorChanged,listener,thisObject);if(!dispatcher.hasEventListeners(UI.Context.Events.FlavorChanged))
this._eventDispatchers.remove(flavorType);}
flavor(flavorType){return this._flavors.get(flavorType)||null;}
flavors(){return new Set(this._flavors.keys());}
applicableExtensions(extensions){const targetExtensionSet=new Set();const availableFlavors=this.flavors();extensions.forEach(function(extension){if(self.runtime.isExtensionApplicableToContextTypes(extension,availableFlavors))
targetExtensionSet.add(extension);});return targetExtensionSet;}};UI.Context.Events={FlavorChanged:Symbol('FlavorChanged')};UI.ContextFlavorListener=function(){};UI.ContextFlavorListener.prototype={flavorChanged(object){}};UI.context=new UI.Context();;UI.ContextMenuItem=class{constructor(contextMenu,type,label,disabled,checked){this._type=type;this._label=label;this._disabled=disabled;this._checked=checked;this._contextMenu=contextMenu;if(type==='item'||type==='checkbox')
this._id=contextMenu?contextMenu._nextId():0;}
id(){return this._id;}
type(){return this._type;}
isEnabled(){return!this._disabled;}
setEnabled(enabled){this._disabled=!enabled;}
_buildDescriptor(){switch(this._type){case'item':const result={type:'item',id:this._id,label:this._label,enabled:!this._disabled};if(this._customElement)
result.element=this._customElement;if(this._shortcut)
result.shortcut=this._shortcut;return result;case'separator':return{type:'separator'};case'checkbox':return{type:'checkbox',id:this._id,label:this._label,checked:!!this._checked,enabled:!this._disabled};}
throw new Error('Invalid item type:'+this._type);}
setShortcut(shortcut){this._shortcut=shortcut;}};UI.ContextMenuSection=class{constructor(contextMenu){this._contextMenu=contextMenu;this._items=[];}
appendItem(label,handler,disabled){const item=new UI.ContextMenuItem(this._contextMenu,'item',label,disabled);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;}
appendCustomItem(element){const item=new UI.ContextMenuItem(this._contextMenu,'item','<custom>');item._customElement=element;this._items.push(item);return item;}
appendAction(actionId,label){const action=UI.actionRegistry.action(actionId);if(!action){console.error(`Action ${actionId} was not defined`);return;}
if(!label)
label=action.title();const result=this.appendItem(label,action.execute.bind(action));const shortcut=UI.shortcutRegistry.shortcutTitleForAction(actionId);if(shortcut)
result.setShortcut(shortcut);}
appendSubMenuItem(label,disabled){const item=new UI.ContextSubMenu(this._contextMenu,label,disabled);item._init();this._items.push(item);return item;}
appendCheckboxItem(label,handler,checked,disabled){const item=new UI.ContextMenuItem(this._contextMenu,'checkbox',label,disabled,checked);this._items.push(item);this._contextMenu._setHandler(item.id(),handler);return item;}};UI.ContextSubMenu=class extends UI.ContextMenuItem{constructor(contextMenu,label,disabled){super(contextMenu,'subMenu',label,disabled);this._sections=new Map();this._sectionList=[];}
_init(){UI.ContextMenu._groupWeights.forEach(name=>this.section(name));}
section(name){let section=name?this._sections.get(name):null;if(!section){section=new UI.ContextMenuSection(this._contextMenu);if(name){this._sections.set(name,section);this._sectionList.push(section);}else{this._sectionList.splice(UI.ContextMenu._groupWeights.indexOf('default'),0,section);}}
return section;}
headerSection(){return this.section('header');}
newSection(){return this.section('new');}
revealSection(){return this.section('reveal');}
clipboardSection(){return this.section('clipboard');}
editSection(){return this.section('edit');}
debugSection(){return this.section('debug');}
viewSection(){return this.section('view');}
defaultSection(){return this.section('default');}
saveSection(){return this.section('save');}
footerSection(){return this.section('footer');}
_buildDescriptor(){const result={type:'subMenu',label:this._label,enabled:!this._disabled,subItems:[]};const nonEmptySections=this._sectionList.filter(section=>!!section._items.length);for(const section of nonEmptySections){for(const item of section._items)
result.subItems.push(item._buildDescriptor());if(section!==nonEmptySections.peekLast())
result.subItems.push({type:'separator'});}
return result;}
appendItemsAtLocation(location){for(const extension of self.runtime.extensions('context-menu-item')){const itemLocation=extension.descriptor()['location']||'';if(!itemLocation.startsWith(location+'/'))
continue;const section=itemLocation.substr(location.length+1);if(!section||section.includes('/'))
continue;this.section(section).appendAction(extension.descriptor()['actionId']);}}};UI.ContextMenuItem._uniqueSectionName=0;UI.ContextMenu=class extends UI.ContextSubMenu{constructor(event,useSoftMenu,x,y){super(null);this._contextMenu=this;super._init();this._defaultSection=this.defaultSection();this._pendingPromises=[];this._pendingTargets=[];this._event=event;this._useSoftMenu=!!useSoftMenu;this._x=x===undefined?event.x:x;this._y=y===undefined?event.y:y;this._handlers={};this._id=0;const target=event.deepElementFromPoint();if(target)
this.appendApplicableItems((target));}
static initialize(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetUseSoftMenu,setUseSoftMenu);function setUseSoftMenu(event){UI.ContextMenu._useSoftMenu=(event.data);}}
static installHandler(doc){doc.body.addEventListener('contextmenu',handler,false);function handler(event){const contextMenu=new UI.ContextMenu(event);contextMenu.show();}}
_nextId(){return this._id++;}
show(){Promise.all(this._pendingPromises).then(populate.bind(this)).then(this._innerShow.bind(this));UI.ContextMenu._pendingMenu=this;function populate(appendCallResults){if(UI.ContextMenu._pendingMenu!==this)
return;delete UI.ContextMenu._pendingMenu;for(let i=0;i<appendCallResults.length;++i){const providers=appendCallResults[i];const target=this._pendingTargets[i];for(let j=0;j<providers.length;++j){const provider=(providers[j]);provider.appendApplicableItems(this._event,this,target);}}
this._pendingPromises=[];this._pendingTargets=[];}
this._event.consume(true);}
discard(){if(this._softMenu)
this._softMenu.discard();}
_innerShow(){const menuObject=this._buildMenuDescriptors();if(this._useSoftMenu||UI.ContextMenu._useSoftMenu||InspectorFrontendHost.isHostedMode()){this._softMenu=new UI.SoftContextMenu(menuObject,this._itemSelected.bind(this));this._softMenu.show(this._event.target.ownerDocument,new AnchorBox(this._x,this._y,0,0));}else{InspectorFrontendHost.showContextMenuAtPoint(this._x,this._y,menuObject,this._event.target.ownerDocument);function listenToEvents(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);}
setImmediate(listenToEvents.bind(this));}}
_setHandler(id,handler){if(handler)
this._handlers[id]=handler;}
_buildMenuDescriptors(){return(super._buildDescriptor().subItems);}
_onItemSelected(event){this._itemSelected((event.data));}
_itemSelected(id){if(this._handlers[id])
this._handlers[id].call(this);this._menuCleared();}
_menuCleared(){InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared,this._menuCleared,this);InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected,this._onItemSelected,this);}
appendApplicableItems(target){this._pendingPromises.push(self.runtime.allInstances(UI.ContextMenu.Provider,target));this._pendingTargets.push(target);}};UI.ContextMenu._groupWeights=['header','new','reveal','edit','clipboard','debug','view','default','save','footer'];UI.ContextMenu.Provider=function(){};UI.ContextMenu.Provider.prototype={appendApplicableItems(event,contextMenu,target){}};;UI.GlassPane=class{constructor(){this._widget=new UI.Widget(true);this._widget.markAsRoot();this.element=this._widget.element;this.contentElement=this._widget.contentElement;this._arrowElement=UI.Icon.create('','arrow hidden');this.element.shadowRoot.appendChild(this._arrowElement);this.registerRequiredCSS('ui/glassPane.css');this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.PierceGlassPane);this._onMouseDownBound=this._onMouseDown.bind(this);this._onClickOutsideCallback=null;this._maxSize=null;this._positionX=null;this._positionY=null;this._anchorBox=null;this._anchorBehavior=UI.GlassPane.AnchorBehavior.PreferTop;this._sizeBehavior=UI.GlassPane.SizeBehavior.SetExactSize;this._marginBehavior=UI.GlassPane.MarginBehavior.DefaultMargin;}
isShowing(){return this._widget.isShowing();}
registerRequiredCSS(cssFile){this._widget.registerRequiredCSS(cssFile);}
setDefaultFocusedElement(element){this._widget.setDefaultFocusedElement(element);}
setDimmed(dimmed){this.element.classList.toggle('dimmed-pane',dimmed);}
setPointerEventsBehavior(pointerEventsBehavior){this.element.classList.toggle('no-pointer-events',pointerEventsBehavior!==UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.contentElement.classList.toggle('no-pointer-events',pointerEventsBehavior===UI.GlassPane.PointerEventsBehavior.PierceContents);}
setOutsideClickCallback(callback){this._onClickOutsideCallback=callback;}
setMaxContentSize(size){this._maxSize=size;this._positionContent();}
setSizeBehavior(sizeBehavior){this._sizeBehavior=sizeBehavior;this._positionContent();}
setContentPosition(x,y){this._positionX=x;this._positionY=y;this._positionContent();}
setContentAnchorBox(anchorBox){this._anchorBox=anchorBox;this._positionContent();}
setAnchorBehavior(behavior){this._anchorBehavior=behavior;}
setMarginBehavior(behavior){this._marginBehavior=behavior;this._arrowElement.classList.toggle('hidden',behavior!==UI.GlassPane.MarginBehavior.Arrow);}
show(document){if(this.isShowing())
return;this.element.style.zIndex=3000+1000*UI.GlassPane._panes.size;document.body.addEventListener('mousedown',this._onMouseDownBound,true);this._widget.show(document.body);UI.GlassPane._panes.add(this);this._positionContent();}
hide(){if(!this.isShowing())
return;UI.GlassPane._panes.delete(this);this.element.ownerDocument.body.removeEventListener('mousedown',this._onMouseDownBound,true);this._widget.detach();}
_onMouseDown(event){if(!this._onClickOutsideCallback)
return;const node=event.deepElementFromPoint();if(!node||this.contentElement.isSelfOrAncestor(node))
return;this._onClickOutsideCallback.call(null,event);}
_positionContent(){if(!this.isShowing())
return;const showArrow=this._marginBehavior===UI.GlassPane.MarginBehavior.Arrow;const gutterSize=showArrow?8:(this._marginBehavior===UI.GlassPane.MarginBehavior.NoMargin?0:3);const scrollbarSize=UI.measuredScrollbarWidth(this.element.ownerDocument);const arrowSize=10;const container=UI.GlassPane._containers.get((this.element.ownerDocument));if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){this.contentElement.positionAt(0,0);this.contentElement.style.width='';this.contentElement.style.maxWidth='';this.contentElement.style.height='';this.contentElement.style.maxHeight='';}
const containerWidth=container.offsetWidth;const containerHeight=container.offsetHeight;let width=containerWidth-gutterSize*2;let height=containerHeight-gutterSize*2;let positionX=gutterSize;let positionY=gutterSize;if(this._maxSize){width=Math.min(width,this._maxSize.width);height=Math.min(height,this._maxSize.height);}
if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){const measuredWidth=this.contentElement.offsetWidth;const measuredHeight=this.contentElement.offsetHeight;const widthOverflow=height<measuredHeight?scrollbarSize:0;const heightOverflow=width<measuredWidth?scrollbarSize:0;width=Math.min(width,measuredWidth+widthOverflow);height=Math.min(height,measuredHeight+heightOverflow);}
if(this._anchorBox){const anchorBox=this._anchorBox.relativeToElement(container);let behavior=this._anchorBehavior;this._arrowElement.classList.remove('arrow-none','arrow-top','arrow-bottom','arrow-left','arrow-right');if(behavior===UI.GlassPane.AnchorBehavior.PreferTop||behavior===UI.GlassPane.AnchorBehavior.PreferBottom){const top=anchorBox.y-2*gutterSize;const bottom=containerHeight-anchorBox.y-anchorBox.height-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop&&top<height&&bottom>top)
behavior=UI.GlassPane.AnchorBehavior.PreferBottom;if(behavior===UI.GlassPane.AnchorBehavior.PreferBottom&&bottom<height&&top>bottom)
behavior=UI.GlassPane.AnchorBehavior.PreferTop;let arrowY;let enoughHeight=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferTop){positionY=Math.max(gutterSize,anchorBox.y-height-gutterSize);const spaceTop=anchorBox.y-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceTop){this._arrowElement.classList.add('arrow-none');enoughHeight=false;}}else{height=Math.min(height,spaceTop);}
this._arrowElement.setIconType('mediumicon-arrow-bottom');this._arrowElement.classList.add('arrow-bottom');arrowY=anchorBox.y-gutterSize;}else{positionY=anchorBox.y+anchorBox.height+gutterSize;const spaceBottom=containerHeight-positionY-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(height>spaceBottom){this._arrowElement.classList.add('arrow-none');positionY=containerHeight-gutterSize-height;enoughHeight=false;}}else{height=Math.min(height,spaceBottom);}
this._arrowElement.setIconType('mediumicon-arrow-top');this._arrowElement.classList.add('arrow-top');arrowY=anchorBox.y+anchorBox.height+gutterSize;}
positionX=Math.max(gutterSize,Math.min(anchorBox.x,containerWidth-width-gutterSize));if(!enoughHeight)
positionX=Math.min(positionX+arrowSize,containerWidth-width-gutterSize);else if(showArrow&&positionX-arrowSize>=gutterSize)
positionX-=arrowSize;width=Math.min(width,containerWidth-positionX-gutterSize);if(2*arrowSize>=width){this._arrowElement.classList.add('arrow-none');}else{let arrowX=anchorBox.x+Math.min(50,Math.floor(anchorBox.width/2));arrowX=Number.constrain(arrowX,positionX+arrowSize,positionX+width-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}else{const left=anchorBox.x-2*gutterSize;const right=containerWidth-anchorBox.x-anchorBox.width-2*gutterSize;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft&&left<width&&right>left)
behavior=UI.GlassPane.AnchorBehavior.PreferRight;if(behavior===UI.GlassPane.AnchorBehavior.PreferRight&&right<width&&left>right)
behavior=UI.GlassPane.AnchorBehavior.PreferLeft;let arrowX;let enoughWidth=true;if(behavior===UI.GlassPane.AnchorBehavior.PreferLeft){positionX=Math.max(gutterSize,anchorBox.x-width-gutterSize);const spaceLeft=anchorBox.x-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceLeft){this._arrowElement.classList.add('arrow-none');enoughWidth=false;}}else{width=Math.min(width,spaceLeft);}
this._arrowElement.setIconType('mediumicon-arrow-right');this._arrowElement.classList.add('arrow-right');arrowX=anchorBox.x-gutterSize;}else{positionX=anchorBox.x+anchorBox.width+gutterSize;const spaceRight=containerWidth-positionX-gutterSize;if(this._sizeBehavior===UI.GlassPane.SizeBehavior.MeasureContent){if(width>spaceRight){this._arrowElement.classList.add('arrow-none');positionX=containerWidth-gutterSize-width;enoughWidth=false;}}else{width=Math.min(width,spaceRight);}
this._arrowElement.setIconType('mediumicon-arrow-left');this._arrowElement.classList.add('arrow-left');arrowX=anchorBox.x+anchorBox.width+gutterSize;}
positionY=Math.max(gutterSize,Math.min(anchorBox.y,containerHeight-height-gutterSize));if(!enoughWidth)
positionY=Math.min(positionY+arrowSize,containerHeight-height-gutterSize);else if(showArrow&&positionY-arrowSize>=gutterSize)
positionY-=arrowSize;height=Math.min(height,containerHeight-positionY-gutterSize);if(2*arrowSize>=height){this._arrowElement.classList.add('arrow-none');}else{let arrowY=anchorBox.y+Math.min(50,Math.floor(anchorBox.height/2));arrowY=Number.constrain(arrowY,positionY+arrowSize,positionY+height-arrowSize);this._arrowElement.positionAt(arrowX,arrowY,container);}}}else{positionX=this._positionX!==null?this._positionX:(containerWidth-width)/2;positionY=this._positionY!==null?this._positionY:(containerHeight-height)/2;width=Math.min(width,containerWidth-positionX-gutterSize);height=Math.min(height,containerHeight-positionY-gutterSize);this._arrowElement.classList.add('arrow-none');}
this.contentElement.style.width=width+'px';if(this._sizeBehavior===UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight)
this.contentElement.style.maxHeight=height+'px';else
this.contentElement.style.height=height+'px';this.contentElement.positionAt(positionX,positionY,container);this._widget.doResize();}
widget(){return this._widget;}
static setContainer(element){UI.GlassPane._containers.set((element.ownerDocument),element);UI.GlassPane.containerMoved(element);}
static container(document){return UI.GlassPane._containers.get(document);}
static containerMoved(element){for(const pane of UI.GlassPane._panes){if(pane.isShowing()&&pane.element.ownerDocument===element.ownerDocument)
pane._positionContent();}}};UI.GlassPane.PointerEventsBehavior={BlockedByGlassPane:Symbol('BlockedByGlassPane'),PierceGlassPane:Symbol('PierceGlassPane'),PierceContents:Symbol('PierceContents')};UI.GlassPane.AnchorBehavior={PreferTop:Symbol('PreferTop'),PreferBottom:Symbol('PreferBottom'),PreferLeft:Symbol('PreferLeft'),PreferRight:Symbol('PreferRight'),};UI.GlassPane.SizeBehavior={SetExactSize:Symbol('SetExactSize'),SetExactWidthMaxHeight:Symbol('SetExactWidthMaxHeight'),MeasureContent:Symbol('MeasureContent')};UI.GlassPane.MarginBehavior={Arrow:Symbol('Arrow'),DefaultMargin:Symbol('DefaultMargin'),NoMargin:Symbol('NoMargin')};UI.GlassPane._containers=new Map();UI.GlassPane._panes=new Set();;UI.Dialog=class extends UI.GlassPane{constructor(){super();this.registerRequiredCSS('ui/dialog.css');this.contentElement.tabIndex=0;this.contentElement.addEventListener('focus',()=>this.widget().focus(),false);this.contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);this.widget().setDefaultFocusedElement(this.contentElement);this.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this.setOutsideClickCallback(event=>{this.hide();event.consume(true);});this._tabIndexMap=new Map();this._focusRestorer=null;this._closeOnEscape=true;}
static hasInstance(){return!!UI.Dialog._instance;}
show(where){const document=(where instanceof Document?where:(where||UI.inspectorView.element).ownerDocument);if(UI.Dialog._instance)
UI.Dialog._instance.hide();UI.Dialog._instance=this;this._disableTabIndexOnElements(document);super.show(document);this._focusRestorer=new UI.WidgetFocusRestorer(this.widget());}
hide(){this._focusRestorer.restore();super.hide();this._restoreTabIndexOnElements();delete UI.Dialog._instance;}
setCloseOnEscape(close){this._closeOnEscape=close;}
addCloseButton(){const closeButton=this.contentElement.createChild('div','dialog-close-button','dt-close-button');closeButton.gray=true;closeButton.addEventListener('click',()=>this.hide(),false);}
_disableTabIndexOnElements(document){this._tabIndexMap.clear();for(let node=document;node;node=node.traverseNextNode(document)){if(node instanceof HTMLElement){const element=(node);const tabIndex=element.tabIndex;if(tabIndex>=0){this._tabIndexMap.set(element,tabIndex);element.tabIndex=-1;}}}}
_restoreTabIndexOnElements(){for(const element of this._tabIndexMap.keys())
element.tabIndex=(this._tabIndexMap.get(element));this._tabIndexMap.clear();}
_onKeyDown(event){if(this._closeOnEscape&&event.keyCode===UI.KeyboardShortcut.Keys.Esc.code){event.consume(true);this.hide();}}};;UI.SyntaxHighlighter=class{constructor(mimeType,stripExtraWhitespace){this._mimeType=mimeType;this._stripExtraWhitespace=stripExtraWhitespace;}
createSpan(content,className){const span=createElement('span');span.className='cm-'+className;if(this._stripExtraWhitespace&&className!=='whitespace')
content=content.replace(/^[\n\r]*/,'').replace(/\s*$/,'');span.createTextChild(content);return span;}
syntaxHighlightNode(node){const lines=node.textContent.split('\n');let plainTextStart;let line;return self.runtime.extension(TextUtils.TokenizerFactory).instance().then(processTokens.bind(this));function processTokens(tokenizerFactory){node.removeChildren();const tokenize=tokenizerFactory.createTokenizer(this._mimeType);for(let i=0;i<lines.length;++i){line=lines[i];plainTextStart=0;tokenize(line,processToken.bind(this));if(plainTextStart<line.length){const plainText=line.substring(plainTextStart,line.length);node.createTextChild(plainText);}
if(i<lines.length-1)
node.createTextChild('\n');}}
function processToken(token,tokenType,column,newColumn){if(!tokenType)
return;if(column>plainTextStart){const plainText=line.substring(plainTextStart,column);node.createTextChild(plainText);}
node.appendChild(this.createSpan(token,tokenType));plainTextStart=newColumn;}}};;UI.DropTarget=class{constructor(element,transferTypes,messageText,handleDrop){element.addEventListener('dragenter',this._onDragEnter.bind(this),true);element.addEventListener('dragover',this._onDragOver.bind(this),true);this._element=element;this._transferTypes=transferTypes;this._messageText=messageText;this._handleDrop=handleDrop;this._enabled=true;}
setEnabled(enabled){this._enabled=enabled;}
_onDragEnter(event){if(this._enabled&&this._hasMatchingType(event))
event.consume(true);}
_hasMatchingType(event){for(const transferType of this._transferTypes){const found=Array.from(event.dataTransfer.items).find(item=>{return transferType.kind===item.kind&&!!transferType.type.exec(item.type);});if(found)
return true;}
return false;}
_onDragOver(event){if(!this._enabled||!this._hasMatchingType(event))
return;event.dataTransfer.dropEffect='copy';event.consume(true);if(this._dragMaskElement)
return;this._dragMaskElement=this._element.createChild('div','');const shadowRoot=UI.createShadowRootWithCoreStyles(this._dragMaskElement,'ui/dropTarget.css');shadowRoot.createChild('div','drop-target-message').textContent=this._messageText;this._dragMaskElement.addEventListener('drop',this._onDrop.bind(this),true);this._dragMaskElement.addEventListener('dragleave',this._onDragLeave.bind(this),true);}
_onDrop(event){event.consume(true);this._removeMask();if(this._enabled)
this._handleDrop(event.dataTransfer);}
_onDragLeave(event){event.consume(true);this._removeMask();}
_removeMask(){this._dragMaskElement.remove();delete this._dragMaskElement;}};UI.DropTarget.Type={URI:{kind:'string',type:/text\/uri-list/},Folder:{kind:'file',type:/$^/},File:{kind:'file',type:/.*/},WebFile:{kind:'file',type:/[\w]+/},ImageFile:{kind:'file',type:/image\/.*/},};;UI.EmptyWidget=class extends UI.VBox{constructor(text){super();this.registerRequiredCSS('ui/emptyWidget.css');this.element.classList.add('empty-view-scroller');this._contentElement=this.element.createChild('div','empty-view');this._textElement=this._contentElement.createChild('h2');this._textElement.textContent=text;}
appendParagraph(){return this._contentElement.createChild('p');}
set text(text){this._textElement.textContent=text;}};;UI.FilterBar=class extends UI.HBox{constructor(name,visibleByDefault){super();this.registerRequiredCSS('ui/filter.css');this._enabled=true;this.element.classList.add('filter-bar');this._stateSetting=Common.settings.createSetting('filterBar-'+name+'-toggled',!!visibleByDefault);this._filterButton=new UI.ToolbarSettingToggle(this._stateSetting,'largeicon-filter',Common.UIString('Filter'));this._filters=[];this._updateFilterBar();this._stateSetting.addChangeListener(this._updateFilterBar.bind(this));}
filterButton(){return this._filterButton;}
addFilter(filter){this._filters.push(filter);this.element.appendChild(filter.element());filter.addEventListener(UI.FilterUI.Events.FilterChanged,this._filterChanged,this);this._updateFilterButton();}
setEnabled(enabled){this._enabled=enabled;this._filterButton.setEnabled(enabled);this._updateFilterBar();}
forceShowFilterBar(){this._alwaysShowFilters=true;this._updateFilterBar();}
showOnce(){this._stateSetting.set(true);}
_filterChanged(event){this._updateFilterButton();}
wasShown(){super.wasShown();this._updateFilterBar();}
_updateFilterBar(){if(!this.parentWidget()||this._showingWidget)
return;if(this.visible()){this._showingWidget=true;this.showWidget();this._showingWidget=false;}else{this.hideWidget();}}
focus(){for(let i=0;i<this._filters.length;++i){if(this._filters[i]instanceof UI.TextFilterUI){const textFilterUI=(this._filters[i]);textFilterUI.focus();break;}}}
_updateFilterButton(){let isActive=false;for(const filter of this._filters)
isActive=isActive||filter.isActive();this._filterButton.setDefaultWithRedColor(isActive);this._filterButton.setToggleWithRedColor(isActive);}
clear(){this.element.removeChildren();this._filters=[];this._updateFilterButton();}
setting(){return this._stateSetting;}
visible(){return this._alwaysShowFilters||(this._stateSetting.get()&&this._enabled);}};UI.FilterUI=function(){};UI.FilterUI.Events={FilterChanged:Symbol('FilterChanged')};UI.FilterUI.prototype={isActive(){},element(){}};UI.TextFilterUI=class extends Common.Object{constructor(){super();this._filterElement=createElement('div');this._filterElement.className='filter-text-filter';this._filterInputElement=this._filterElement.createChild('span','filter-input-field');this._prompt=new UI.TextPrompt();this._prompt.initialize(this._completions.bind(this),' ');this._proxyElement=this._prompt.attach(this._filterInputElement);this._proxyElement.title=Common.UIString('e.g. /small[\\d]+/ url:a.com/b');this._prompt.setPlaceholder(Common.UIString('Filter'));this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._valueChanged.bind(this));this._suggestionProvider=null;}
_completions(expression,prefix,force){if(this._suggestionProvider)
return this._suggestionProvider(expression,prefix,force);return Promise.resolve([]);}
isActive(){return!!this._prompt.text();}
element(){return this._filterElement;}
value(){return this._prompt.textWithCurrentSuggestion();}
setValue(value){this._prompt.setText(value);this._valueChanged();}
focus(){this._filterInputElement.focus();}
setSuggestionProvider(suggestionProvider){this._prompt.clearAutocomplete();this._suggestionProvider=suggestionProvider;}
_valueChanged(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}};UI.NamedBitSetFilterUI=class extends Common.Object{constructor(items,setting){super();this._filtersElement=createElementWithClass('div','filter-bitset-filter');this._filtersElement.title=Common.UIString('%sClick to select multiple types',UI.KeyboardShortcut.shortcutToString('',UI.KeyboardShortcut.Modifiers.CtrlOrMeta));this._allowedTypes={};this._typeFilterElements={};this._addBit(UI.NamedBitSetFilterUI.ALL_TYPES,Common.UIString('All'));this._filtersElement.createChild('div','filter-bitset-filter-divider');for(let i=0;i<items.length;++i)
this._addBit(items[i].name,items[i].label,items[i].title);if(setting){this._setting=setting;setting.addChangeListener(this._settingChanged.bind(this));this._settingChanged();}else{this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);}}
reset(){this._toggleTypeFilter(UI.NamedBitSetFilterUI.ALL_TYPES,false);}
isActive(){return!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES];}
element(){return this._filtersElement;}
accept(typeName){return!!this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]||!!this._allowedTypes[typeName];}
_settingChanged(){const allowedTypes=this._setting.get();this._allowedTypes={};for(const typeName in this._typeFilterElements){if(allowedTypes[typeName])
this._allowedTypes[typeName]=true;}
this._update();}
_update(){if((Object.keys(this._allowedTypes).length===0)||this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]){this._allowedTypes={};this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=true;}
for(const typeName in this._typeFilterElements)
this._typeFilterElements[typeName].classList.toggle('selected',this._allowedTypes[typeName]);this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}
_addBit(name,label,title){const typeFilterElement=this._filtersElement.createChild('li',name);typeFilterElement.typeName=name;typeFilterElement.createTextChild(label);if(title)
typeFilterElement.title=title;typeFilterElement.addEventListener('click',this._onTypeFilterClicked.bind(this),false);this._typeFilterElements[name]=typeFilterElement;}
_onTypeFilterClicked(e){let toggle;if(Host.isMac())
toggle=e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey;else
toggle=e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey;this._toggleTypeFilter(e.target.typeName,toggle);}
_toggleTypeFilter(typeName,allowMultiSelect){if(allowMultiSelect&&typeName!==UI.NamedBitSetFilterUI.ALL_TYPES)
this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES]=false;else
this._allowedTypes={};this._allowedTypes[typeName]=!this._allowedTypes[typeName];if(this._setting)
this._setting.set(this._allowedTypes);else
this._update();}};UI.NamedBitSetFilterUI.Item;UI.NamedBitSetFilterUI.ALL_TYPES='all';UI.CheckboxFilterUI=class extends Common.Object{constructor(className,title,activeWhenChecked,setting){super();this._filterElement=createElementWithClass('div','filter-checkbox-filter');this._activeWhenChecked=!!activeWhenChecked;this._label=UI.CheckboxLabel.create(title);this._filterElement.appendChild(this._label);this._checkboxElement=this._label.checkboxElement;if(setting)
UI.SettingsUI.bindCheckbox(this._checkboxElement,setting);else
this._checkboxElement.checked=true;this._checkboxElement.addEventListener('change',this._fireUpdated.bind(this),false);}
isActive(){return this._activeWhenChecked===this._checkboxElement.checked;}
checked(){return this._checkboxElement.checked;}
setChecked(checked){this._checkboxElement.checked=checked;}
element(){return this._filterElement;}
labelElement(){return this._label;}
_fireUpdated(){this.dispatchEventToListeners(UI.FilterUI.Events.FilterChanged,null);}
setColor(backgroundColor,borderColor){this._label.backgroundColor=backgroundColor;this._label.borderColor=borderColor;}};;UI.FilterSuggestionBuilder=class{constructor(keys,valueSorter){this._keys=keys;this._valueSorter=valueSorter||((key,result)=>result.sort());this._valuesMap=new Map();}
completions(expression,prefix,force){if(!prefix&&!force)
return Promise.resolve([]);const negative=prefix.startsWith('-');if(negative)
prefix=prefix.substring(1);const modifier=negative?'-':'';const valueDelimiterIndex=prefix.indexOf(':');const suggestions=[];if(valueDelimiterIndex===-1){const matcher=new RegExp('^'+prefix.escapeForRegExp(),'i');for(const key of this._keys){if(matcher.test(key))
suggestions.push({text:modifier+key+':'});}}else{const key=prefix.substring(0,valueDelimiterIndex).toLowerCase();const value=prefix.substring(valueDelimiterIndex+1);const matcher=new RegExp('^'+value.escapeForRegExp(),'i');const values=Array.from(this._valuesMap.get(key)||new Set());this._valueSorter(key,values);for(const item of values){if(matcher.test(item)&&(item!==value))
suggestions.push({text:modifier+key+':'+item});}}
return Promise.resolve(suggestions);}
addItem(key,value){if(!value)
return;if(!this._valuesMap.get(key))
this._valuesMap.set(key,(new Set()));this._valuesMap.get(key).add(value);}
clear(){this._valuesMap.clear();}};;UI.ForwardedInputEventHandler=class{constructor(){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.KeyEventUnhandled,this._onKeyEventUnhandled,this);}
_onKeyEventUnhandled(event){const data=event.data;const type=(data.type);const key=(data.key);const keyCode=(data.keyCode);const modifiers=(data.modifiers);if(type!=='keydown')
return;UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,UI.ShortcutRegistry.ForwardedShortcut.instance);UI.shortcutRegistry.handleKey(UI.KeyboardShortcut.makeKey(keyCode,modifiers),key);UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut,null);}};UI.forwardedEventHandler=new UI.ForwardedInputEventHandler();;UI.Fragment=class{constructor(element){this._element=element;this._states=new Map();this._elementsById=new Map();}
element(){return this._element;}
$(elementId){return this._elementsById.get(elementId);}
setState(name,toggled){const list=this._states.get(name);if(list===undefined){console.error('Unknown state '+name);return;}
for(const state of list){if(state.toggled===toggled)
continue;state.toggled=toggled;const value=state.attributeValue;state.attributeValue=state.element.getAttribute(state.attributeName);if(value===null)
state.element.removeAttribute(state.attributeName);else
state.element.setAttribute(state.attributeName,value);}}
static build(strings,vararg){const values=Array.prototype.slice.call(arguments,1);return UI.Fragment._render(UI.Fragment._template(strings),values);}
static cached(strings,vararg){const values=Array.prototype.slice.call(arguments,1);let template=UI.Fragment._templateCache.get(strings);if(!template){template=UI.Fragment._template(strings);UI.Fragment._templateCache.set(strings,template);}
return UI.Fragment._render(template,values);}
static _template(strings){let html='';let insideText=false;for(let i=0;i<strings.length-1;i++){html+=strings[i];const close=strings[i].lastIndexOf('>');if(close!==-1){if(strings[i].indexOf('<',close+1)===-1)
insideText=true;else
insideText=false;}
html+=insideText?UI.Fragment._textMarker:UI.Fragment._attributeMarker(i);}
html+=strings[strings.length-1];const template=window.document.createElement('template');template.innerHTML=html;const walker=template.ownerDocument.createTreeWalker(template.content,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,null,false);let valueIndex=0;const emptyTextNodes=[];const binds=[];const nodesToMark=[];while(walker.nextNode()){const node=walker.currentNode;if(node.nodeType===Node.ELEMENT_NODE&&node.hasAttributes()){if(node.hasAttribute('$')){nodesToMark.push(node);binds.push({elementId:node.getAttribute('$')});node.removeAttribute('$');}
const attributesToRemove=[];for(let i=0;i<node.attributes.length;i++){let name=node.attributes[i].name;if(name.startsWith('s-')){attributesToRemove.push(name);name=name.substring(2);const state=name.substring(0,name.indexOf('-'));const attr=name.substring(state.length+1);nodesToMark.push(node);binds.push({state:{name:state,attribute:attr,value:node.attributes[i].value}});continue;}
if(!UI.Fragment._attributeMarkerRegex.test(name)&&!UI.Fragment._attributeMarkerRegex.test(node.attributes[i].value))
continue;attributesToRemove.push(name);nodesToMark.push(node);const bind={attr:{index:valueIndex}};bind.attr.names=name.split(UI.Fragment._attributeMarkerRegex);valueIndex+=bind.attr.names.length-1;bind.attr.values=node.attributes[i].value.split(UI.Fragment._attributeMarkerRegex);valueIndex+=bind.attr.values.length-1;binds.push(bind);}
for(let i=0;i<attributesToRemove.length;i++)
node.removeAttribute(attributesToRemove[i]);}
if(node.nodeType===Node.TEXT_NODE&&node.data.indexOf(UI.Fragment._textMarker)!==-1){const texts=node.data.split(UI.Fragment._textMarkerRegex);node.data=texts[texts.length-1];for(let i=0;i<texts.length-1;i++){if(texts[i])
node.parentNode.insertBefore(createTextNode(texts[i]),node);const nodeToReplace=createElement('span');nodesToMark.push(nodeToReplace);binds.push({replaceNodeIndex:valueIndex++});node.parentNode.insertBefore(nodeToReplace,node);}}
if(node.nodeType===Node.TEXT_NODE&&(!node.previousSibling||node.previousSibling.nodeType===Node.ELEMENT_NODE)&&(!node.nextSibling||node.nextSibling.nodeType===Node.ELEMENT_NODE)&&/^\s*$/.test(node.data))
emptyTextNodes.push(node);}
for(let i=0;i<nodesToMark.length;i++)
nodesToMark[i].classList.add(UI.Fragment._class(i));for(const emptyTextNode of emptyTextNodes)
emptyTextNode.remove();return{template:template,binds:binds};}
static _render(template,values){const content=template.template.ownerDocument.importNode(template.template.content,true);const resultElement=(content.firstChild===content.lastChild?content.firstChild:content);const result=new UI.Fragment(resultElement);const idByElement=new Map();const boundElements=[];for(let i=0;i<template.binds.length;i++){const className=UI.Fragment._class(i);const element=(content.querySelector('.'+className));element.classList.remove(className);boundElements.push(element);}
for(let bindIndex=0;bindIndex<template.binds.length;bindIndex++){const bind=template.binds[bindIndex];const element=boundElements[bindIndex];if('elementId'in bind){result._elementsById.set((bind.elementId),element);idByElement.set(element,bind.elementId);}else if('replaceNodeIndex'in bind){const value=values[(bind.replaceNodeIndex)];let node=null;if(value instanceof Node)
node=value;else if(value instanceof UI.Fragment)
node=value._element;else
node=createTextNode(''+value);element.parentNode.insertBefore(node,element);element.remove();}else if('state'in bind){const list=result._states.get(bind.state.name)||[];list.push({attributeName:bind.state.attribute,attributeValue:bind.state.value,element:element,toggled:false});result._states.set(bind.state.name,list);}else if('attr'in bind){if(bind.attr.names.length===2&&bind.attr.values.length===1&&typeof values[bind.attr.index]==='function'){values[bind.attr.index].call(null,element);}else{let name=bind.attr.names[0];for(let i=1;i<bind.attr.names.length;i++){name+=values[bind.attr.index+i-1];name+=bind.attr.names[i];}
if(name){let value=bind.attr.values[0];for(let i=1;i<bind.attr.values.length;i++){value+=values[bind.attr.index+bind.attr.names.length-1+i-1];value+=bind.attr.values[i];}
element.setAttribute(name,value);}}}else{throw'Unexpected bind';}}
const shadows=result._element.querySelectorAll('x-shadow');for(const shadow of shadows){if(!shadow.parentElement)
throw'There must be a parent element here';const shadowRoot=UI.createShadowRootWithCoreStyles(shadow.parentElement);if(shadow.parentElement.tagName==='X-WIDGET')
shadow.parentElement._shadowRoot=shadowRoot;const children=[];while(shadow.lastChild){children.push(shadow.lastChild);shadow.lastChild.remove();}
for(let i=children.length-1;i>=0;i--)
shadowRoot.appendChild(children[i]);const id=idByElement.get(shadow);if(id)
result._elementsById.set(id,((shadowRoot)));shadow.remove();}
return result;}};UI.Fragment._Template;UI.Fragment._State;UI.Fragment._Bind;UI.Fragment._textMarker='{{template-text}}';UI.Fragment._textMarkerRegex=/{{template-text}}/;UI.Fragment._attributeMarker=index=>'template-attribute'+index;UI.Fragment._attributeMarkerRegex=/template-attribute\d+/;UI.Fragment._class=index=>'template-class-'+index;UI.Fragment._templateCache=new Map();;UI.HistoryInput=class extends HTMLInputElement{static create(){if(!UI.HistoryInput._constructor)
UI.HistoryInput._constructor=UI.registerCustomElement('input','history-input',UI.HistoryInput.prototype);return(new UI.HistoryInput._constructor());}
createdCallback(){this._history=[''];this._historyPosition=0;this.addEventListener('keydown',this._onKeyDown.bind(this),false);this.addEventListener('input',this._onInput.bind(this),false);}
_onInput(event){if(this._history.length===this._historyPosition+1)
this._history[this._history.length-1]=this.value;}
_onKeyDown(event){if(event.keyCode===UI.KeyboardShortcut.Keys.Up.code){this._historyPosition=Math.max(this._historyPosition-1,0);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Down.code){this._historyPosition=Math.min(this._historyPosition+1,this._history.length-1);this.value=this._history[this._historyPosition];this.dispatchEvent(new Event('input',{'bubbles':true,'cancelable':true}));event.consume(true);}else if(event.keyCode===UI.KeyboardShortcut.Keys.Enter.code){this._saveToHistory();}}
_saveToHistory(){if(this._history.length>1&&this._history[this._history.length-2]===this.value)
return;this._history[this._history.length-1]=this.value;this._historyPosition=this._history.length-1;this._history.push('');}};;UI.Icon=class extends HTMLSpanElement{constructor(){super();throw new Error('icon must be created via factory method.');}
static create(iconType,className){if(!UI.Icon._constructor)
UI.Icon._constructor=UI.registerCustomElement('span','ui-icon',UI.Icon.prototype);const icon=(new UI.Icon._constructor());if(className)
icon.className=className;if(iconType)
icon.setIconType(iconType);return icon;}
createdCallback(){this._descriptor=null;this._spriteSheet=null;this._iconType='';}
setIconType(iconType){if(this._descriptor){this.style.removeProperty('--spritesheet-position');this.style.removeProperty('width');this.style.removeProperty('height');this._toggleClasses(false);this._iconType='';this._descriptor=null;this._spriteSheet=null;}
const descriptor=UI.Icon.Descriptors[iconType]||null;if(descriptor){this._iconType=iconType;this._descriptor=descriptor;this._spriteSheet=UI.Icon.SpriteSheets[this._descriptor.spritesheet];console.assert(this._spriteSheet,`ERROR: icon ${this._iconType} has unknown spritesheet: ${this._descriptor.spritesheet}`);this.style.setProperty('--spritesheet-position',this._propertyValue());this.style.setProperty('width',this._spriteSheet.cellWidth+'px');this.style.setProperty('height',this._spriteSheet.cellHeight+'px');this._toggleClasses(true);}else if(iconType){throw new Error(`ERROR: failed to find icon descriptor for type: ${iconType}`);}}
_toggleClasses(value){this.classList.toggle('spritesheet-'+this._descriptor.spritesheet,value);this.classList.toggle(this._iconType,value);this.classList.toggle('icon-mask',value&&!!this._descriptor.isMask);this.classList.toggle('icon-invert',value&&!!this._descriptor.invert);}
_propertyValue(){if(!this._descriptor.coordinates){if(!this._descriptor.position||!UI.Icon._positionRegex.test(this._descriptor.position))
throw new Error(`ERROR: icon '${this._iconType}' has malformed position: '${this._descriptor.position}'`);const column=this._descriptor.position[0].toLowerCase().charCodeAt(0)-97;const row=parseInt(this._descriptor.position.substring(1),10)-1;this._descriptor.coordinates={x:-(this._spriteSheet.cellWidth+this._spriteSheet.padding)*column,y:(this._spriteSheet.cellHeight+this._spriteSheet.padding)*(row+1)-this._spriteSheet.padding};}
return`${this._descriptor.coordinates.x}px ${this._descriptor.coordinates.y}px`;}};UI.Icon._positionRegex=/^[a-z][1-9][0-9]*$/;UI.Icon.Descriptor;UI.Icon.SpriteSheet;UI.Icon.SpriteSheets={'smallicons':{cellWidth:10,cellHeight:10,padding:10},'mediumicons':{cellWidth:16,cellHeight:16,padding:0},'largeicons':{cellWidth:28,cellHeight:24,padding:0},'arrowicons':{cellWidth:19,cellHeight:19,padding:0}};UI.Icon.Descriptors={'smallicon-bezier':{position:'a5',spritesheet:'smallicons',isMask:true},'smallicon-checkmark':{position:'b5',spritesheet:'smallicons'},'smallicon-checkmark-square':{position:'b6',spritesheet:'smallicons',isMask:true},'smallicon-checkmark-behind':{position:'d6',spritesheet:'smallicons',isMask:true},'smallicon-command-result':{position:'a4',spritesheet:'smallicons'},'smallicon-contrast-ratio':{position:'a6',spritesheet:'smallicons',isMask:true},'smallicon-cross':{position:'b4',spritesheet:'smallicons'},'smallicon-device':{position:'c5',spritesheet:'smallicons'},'smallicon-error':{position:'c4',spritesheet:'smallicons'},'smallicon-expand-less':{position:'f5',spritesheet:'smallicons',isMask:true},'smallicon-expand-more':{position:'e6',spritesheet:'smallicons',isMask:true},'smallicon-green-arrow':{position:'a3',spritesheet:'smallicons'},'smallicon-green-ball':{position:'b3',spritesheet:'smallicons'},'smallicon-info':{position:'c3',spritesheet:'smallicons'},'smallicon-inline-breakpoint-conditional':{position:'d4',spritesheet:'smallicons'},'smallicon-inline-breakpoint':{position:'d5',spritesheet:'smallicons'},'smallicon-no':{position:'c6',spritesheet:'smallicons',isMask:true},'smallicon-orange-ball':{position:'d3',spritesheet:'smallicons'},'smallicon-red-ball':{position:'a2',spritesheet:'smallicons'},'smallicon-shadow':{position:'b2',spritesheet:'smallicons',isMask:true},'smallicon-step-in':{position:'c2',spritesheet:'smallicons'},'smallicon-step-out':{position:'d2',spritesheet:'smallicons'},'smallicon-text-prompt':{position:'e5',spritesheet:'smallicons'},'smallicon-thick-left-arrow':{position:'e4',spritesheet:'smallicons'},'smallicon-thick-right-arrow':{position:'e3',spritesheet:'smallicons'},'smallicon-triangle-down':{position:'e2',spritesheet:'smallicons',isMask:true},'smallicon-triangle-right':{position:'a1',spritesheet:'smallicons',isMask:true},'smallicon-triangle-up':{position:'b1',spritesheet:'smallicons',isMask:true},'smallicon-user-command':{position:'c1',spritesheet:'smallicons'},'smallicon-warning':{position:'d1',spritesheet:'smallicons'},'smallicon-network-product':{position:'e1',spritesheet:'smallicons'},'smallicon-clear-warning':{position:'f1',spritesheet:'smallicons',isMask:true},'smallicon-clear-info':{position:'f2',spritesheet:'smallicons'},'smallicon-clear-error':{position:'f3',spritesheet:'smallicons'},'smallicon-account-circle':{position:'f4',spritesheet:'smallicons'},'mediumicon-clear-storage':{position:'a4',spritesheet:'mediumicons',isMask:true},'mediumicon-cookie':{position:'b4',spritesheet:'mediumicons',isMask:true},'mediumicon-database':{position:'c4',spritesheet:'mediumicons',isMask:true},'mediumicon-info':{position:'c1',spritesheet:'mediumicons',isMask:true},'mediumicon-manifest':{position:'d4',spritesheet:'mediumicons',isMask:true},'mediumicon-service-worker':{position:'a3',spritesheet:'mediumicons',isMask:true},'mediumicon-table':{position:'b3',spritesheet:'mediumicons',isMask:true},'mediumicon-arrow-in-circle':{position:'c3',spritesheet:'mediumicons',isMask:true},'mediumicon-file-sync':{position:'d3',spritesheet:'mediumicons',invert:true},'mediumicon-file':{position:'a2',spritesheet:'mediumicons',invert:true},'mediumicon-gray-cross-active':{position:'b2',spritesheet:'mediumicons'},'mediumicon-gray-cross-hover':{position:'c2',spritesheet:'mediumicons'},'mediumicon-red-cross-active':{position:'d2',spritesheet:'mediumicons'},'mediumicon-red-cross-hover':{position:'a1',spritesheet:'mediumicons'},'mediumicon-search':{position:'b1',spritesheet:'mediumicons'},'mediumicon-replace':{position:'c5',spritesheet:'mediumicons',isMask:true},'mediumicon-account-circle':{position:'e4',spritesheet:'mediumicons'},'mediumicon-warning-triangle':{position:'e1',spritesheet:'mediumicons'},'mediumicon-error-circle':{position:'e3',spritesheet:'mediumicons'},'mediumicon-info-circle':{position:'e2',spritesheet:'mediumicons'},'mediumicon-bug':{position:'d1',spritesheet:'mediumicons'},'mediumicon-list':{position:'e5',spritesheet:'mediumicons'},'mediumicon-warning':{position:'d5',spritesheet:'mediumicons',isMask:true},'badge-navigator-file-sync':{position:'a9',spritesheet:'largeicons'},'largeicon-activate-breakpoints':{position:'b9',spritesheet:'largeicons',isMask:true},'largeicon-add':{position:'a8',spritesheet:'largeicons',isMask:true},'largeicon-background-color':{position:'b8',spritesheet:'largeicons',isMask:true},'largeicon-box-shadow':{position:'a7',spritesheet:'largeicons',isMask:true},'largeicon-camera':{position:'b7',spritesheet:'largeicons',isMask:true},'largeicon-center':{position:'c9',spritesheet:'largeicons',isMask:true},'largeicon-checkmark':{position:'c8',spritesheet:'largeicons',isMask:true},'largeicon-chevron':{position:'c7',spritesheet:'largeicons',isMask:true},'largeicon-clear':{position:'a6',spritesheet:'largeicons',isMask:true},'largeicon-copy':{position:'b6',spritesheet:'largeicons',isMask:true},'largeicon-deactivate-breakpoints':{position:'c6',spritesheet:'largeicons',isMask:true},'largeicon-delete':{position:'d9',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-bottom':{position:'d8',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-left':{position:'d7',spritesheet:'largeicons',isMask:true},'largeicon-dock-to-right':{position:'d6',spritesheet:'largeicons',isMask:true},'largeicon-download':{position:'h6',spritesheet:'largeicons',isMask:true},'largeicon-edit':{position:'a5',spritesheet:'largeicons',isMask:true},'largeicon-eyedropper':{position:'b5',spritesheet:'largeicons',isMask:true},'largeicon-filter':{position:'c5',spritesheet:'largeicons',isMask:true},'largeicon-foreground-color':{position:'d5',spritesheet:'largeicons',isMask:true},'largeicon-hide-bottom-sidebar':{position:'e9',spritesheet:'largeicons',isMask:true},'largeicon-hide-left-sidebar':{position:'e8',spritesheet:'largeicons',isMask:true},'largeicon-hide-right-sidebar':{position:'e7',spritesheet:'largeicons',isMask:true},'largeicon-hide-top-sidebar':{position:'e6',spritesheet:'largeicons',isMask:true},'largeicon-large-list':{position:'e5',spritesheet:'largeicons',isMask:true},'largeicon-layout-editor':{position:'a4',spritesheet:'largeicons',isMask:true},'largeicon-load':{position:'h5',spritesheet:'largeicons',isMask:true},'largeicon-longclick-triangle':{position:'b4',spritesheet:'largeicons',isMask:true},'largeicon-menu':{position:'c4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-domain':{position:'d4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-file':{position:'e4',spritesheet:'largeicons',isMask:true},'largeicon-navigator-file-sync':{position:'f9',spritesheet:'largeicons',isMask:true},'largeicon-navigator-folder':{position:'f8',spritesheet:'largeicons',isMask:true},'largeicon-navigator-frame':{position:'f7',spritesheet:'largeicons',isMask:true},'largeicon-navigator-snippet':{position:'f6',spritesheet:'largeicons',isMask:true},'largeicon-navigator-worker':{position:'f5',spritesheet:'largeicons',isMask:true},'largeicon-node-search':{position:'f4',spritesheet:'largeicons',isMask:true},'largeicon-pan':{position:'a3',spritesheet:'largeicons',isMask:true},'largeicon-pause-animation':{position:'b3',spritesheet:'largeicons',isMask:true},'largeicon-pause':{position:'c3',spritesheet:'largeicons',isMask:true},'largeicon-pause-on-exceptions':{position:'d3',spritesheet:'largeicons',isMask:true},'largeicon-phone':{position:'e3',spritesheet:'largeicons',isMask:true},'largeicon-play-animation':{position:'f3',spritesheet:'largeicons',isMask:true},'largeicon-play-back':{position:'a2',spritesheet:'largeicons',isMask:true},'largeicon-play':{position:'b2',spritesheet:'largeicons',isMask:true},'largeicon-pretty-print':{position:'c2',spritesheet:'largeicons',isMask:true},'largeicon-refresh':{position:'d2',spritesheet:'largeicons',isMask:true},'largeicon-replay-animation':{position:'e2',spritesheet:'largeicons',isMask:true},'largeicon-resume':{position:'f2',spritesheet:'largeicons',isMask:true},'largeicon-rotate':{position:'g9',spritesheet:'largeicons',isMask:true},'largeicon-rotate-screen':{position:'g8',spritesheet:'largeicons',isMask:true},'largeicon-search':{position:'h4',spritesheet:'largeicons',isMask:true},'largeicon-settings-gear':{position:'g7',spritesheet:'largeicons',isMask:true},'largeicon-show-bottom-sidebar':{position:'g6',spritesheet:'largeicons',isMask:true},'largeicon-show-left-sidebar':{position:'g5',spritesheet:'largeicons',isMask:true},'largeicon-show-right-sidebar':{position:'g4',spritesheet:'largeicons',isMask:true},'largeicon-show-top-sidebar':{position:'g3',spritesheet:'largeicons',isMask:true},'largeicon-start-recording':{position:'g2',spritesheet:'largeicons',isMask:true},'largeicon-step-into':{position:'a1',spritesheet:'largeicons',isMask:true},'largeicon-step-out':{position:'b1',spritesheet:'largeicons',isMask:true},'largeicon-step-over':{position:'c1',spritesheet:'largeicons',isMask:true},'largeicon-step':{position:'h1',spritesheet:'largeicons',isMask:true},'largeicon-stop-recording':{position:'d1',spritesheet:'largeicons',isMask:true},'largeicon-terminate-execution':{position:'h2',spritesheet:'largeicons',isMask:true},'largeicon-text-shadow':{position:'e1',spritesheet:'largeicons',isMask:true},'largeicon-trash-bin':{position:'f1',spritesheet:'largeicons',isMask:true},'largeicon-undo':{position:'h7',spritesheet:'largeicons',isMask:true},'largeicon-undock':{position:'g1',spritesheet:'largeicons',isMask:true},'largeicon-visibility':{position:'h9',spritesheet:'largeicons',isMask:true},'largeicon-waterfall':{position:'h8',spritesheet:'largeicons',isMask:true},'mediumicon-arrow-top':{position:'a4',spritesheet:'arrowicons'},'mediumicon-arrow-bottom':{position:'a3',spritesheet:'arrowicons'},'mediumicon-arrow-left':{position:'a2',spritesheet:'arrowicons'},'mediumicon-arrow-right':{position:'a1',spritesheet:'arrowicons'}};;UI.Infobar=class{constructor(type,text,disableSetting){this.element=createElementWithClass('div','flex-none');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/infobar.css');this._contentElement=this._shadowRoot.createChild('div','infobar infobar-'+type);this._mainRow=this._contentElement.createChild('div','infobar-main-row');this._mainRow.createChild('div',type+'-icon icon');this._mainRowText=this._mainRow.createChild('div','infobar-main-title');this._mainRowText.textContent=text;this._detailsRows=this._contentElement.createChild('div','infobar-details-rows hidden');this._toggleElement=this._mainRow.createChild('div','infobar-toggle hidden');this._toggleElement.addEventListener('click',this._onToggleDetails.bind(this),false);this._toggleElement.textContent=Common.UIString('more');this._disableSetting=disableSetting||null;if(disableSetting){const disableButton=this._mainRow.createChild('div','infobar-toggle');disableButton.textContent=Common.UIString('never show');disableButton.addEventListener('click',this._onDisable.bind(this),false);}
this._closeButton=this._contentElement.createChild('div','close-button','dt-close-button');this._closeButton.addEventListener('click',this.dispose.bind(this),false);this._closeCallback=null;}
static create(type,text,disableSetting){if(disableSetting&&disableSetting.get())
return null;return new UI.Infobar(type,text,disableSetting);}
dispose(){this.element.remove();this._onResize();if(this._closeCallback)
this._closeCallback.call(null);}
setText(text){this._mainRowText.textContent=text;this._onResize();}
setCloseCallback(callback){this._closeCallback=callback;}
setParentView(parentView){this._parentView=parentView;}
_onResize(){if(this._parentView)
this._parentView.doResize();}
_onDisable(){this._disableSetting.set(true);this.dispose();}
_onToggleDetails(){this._detailsRows.classList.remove('hidden');this._toggleElement.remove();this._onResize();}
createDetailsRowMessage(message){this._toggleElement.classList.remove('hidden');const infobarDetailsRow=this._detailsRows.createChild('div','infobar-details-row');const detailsRowMessage=infobarDetailsRow.createChild('span','infobar-row-message');detailsRowMessage.textContent=message||'';return detailsRowMessage;}};UI.Infobar.Type={Warning:'warning',Info:'info'};;UI.InplaceEditor=class{static startEditing(element,config){if(!UI.InplaceEditor._defaultInstance)
UI.InplaceEditor._defaultInstance=new UI.InplaceEditor();return UI.InplaceEditor._defaultInstance.startEditing(element,config);}
editorContent(editingContext){const element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text')
return element.value;return element.textContent;}
setUpEditor(editingContext){const element=editingContext.element;element.classList.add('editing');element.setAttribute('contenteditable','plaintext-only');const oldTabIndex=element.getAttribute('tabIndex');if(typeof oldTabIndex!=='number'||oldTabIndex<0)
element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(element);editingContext.oldTabIndex=oldTabIndex;}
closeEditor(editingContext){const element=editingContext.element;element.classList.remove('editing');element.removeAttribute('contenteditable');if(typeof editingContext.oldTabIndex!=='number')
element.removeAttribute('tabIndex');else
element.tabIndex=editingContext.oldTabIndex;element.scrollTop=0;element.scrollLeft=0;}
cancelEditing(editingContext){const element=editingContext.element;if(element.tagName==='INPUT'&&element.type==='text')
element.value=editingContext.oldText;else
element.textContent=editingContext.oldText;}
augmentEditingHandle(editingContext,handle){}
startEditing(element,config){if(!UI.markBeingEdited(element,true))
return null;config=config||new UI.InplaceEditor.Config(function(){},function(){});const editingContext={element:element,config:config};const committedCallback=config.commitHandler;const cancelledCallback=config.cancelHandler;const pasteCallback=config.pasteHandler;const context=config.context;let moveDirection='';const self=this;this.setUpEditor(editingContext);editingContext.oldText=this.editorContent(editingContext);function blurEventListener(e){if(config.blurHandler&&!config.blurHandler(element,e))
return;editingCommitted.call(element);}
function cleanUpAfterEditing(){UI.markBeingEdited(element,false);element.removeEventListener('blur',blurEventListener,false);element.removeEventListener('keydown',keyDownEventListener,true);if(pasteCallback)
element.removeEventListener('paste',pasteEventListener,true);if(self._focusRestorer)
self._focusRestorer.restore();self.closeEditor(editingContext);}
function editingCancelled(){self.cancelEditing(editingContext);cleanUpAfterEditing();cancelledCallback(this,context);}
function editingCommitted(){cleanUpAfterEditing();committedCallback(this,self.editorContent(editingContext),editingContext.oldText,context,moveDirection);}
function defaultFinishHandler(event){if(isEnterKey(event))
return'commit';else if(event.keyCode===UI.KeyboardShortcut.Keys.Esc.code||event.key==='Escape')
return'cancel';else if(event.key==='Tab')
return'move-'+(event.shiftKey?'backward':'forward');return'';}
function handleEditingResult(result,event){if(result==='commit'){editingCommitted.call(element);event.consume(true);}else if(result==='cancel'){editingCancelled.call(element);event.consume(true);}else if(result&&result.startsWith('move-')){moveDirection=result.substring(5);if(event.key==='Tab')
event.consume(true);blurEventListener();}}
function pasteEventListener(event){const result=pasteCallback(event);handleEditingResult(result,event);}
function keyDownEventListener(event){let result=defaultFinishHandler(event);if(!result&&config.postKeydownFinishHandler)
result=config.postKeydownFinishHandler(event);handleEditingResult(result,event);}
element.addEventListener('blur',blurEventListener,false);element.addEventListener('keydown',keyDownEventListener,true);if(pasteCallback)
element.addEventListener('paste',pasteEventListener,true);const handle={cancel:editingCancelled.bind(element),commit:editingCommitted.bind(element)};this.augmentEditingHandle(editingContext,handle);return handle;}};UI.InplaceEditor.Controller;UI.InplaceEditor.Config=class{constructor(commitHandler,cancelHandler,context,blurHandler){this.commitHandler=commitHandler;this.cancelHandler=cancelHandler;this.context=context;this.blurHandler=blurHandler;this.pasteHandler;this.postKeydownFinishHandler;}
setPasteHandler(pasteHandler){this.pasteHandler=pasteHandler;}
setPostKeydownFinishHandler(postKeydownFinishHandler){this.postKeydownFinishHandler=postKeydownFinishHandler;}};;UI.TextEditorFactory=function(){};UI.TextEditorFactory.prototype={createEditor(options){}};UI.TextEditor=function(){};UI.TextEditor.prototype={widget(){},fullRange(){},selection(){},setSelection(selection){},text(textRange){},setText(text){},line(lineNumber){},newlineAndIndent(){},addKeyDownHandler(handler){},configureAutocomplete(config){},clearAutocomplete(){},visualCoordinates(lineNumber,columnNumber){},tokenAtTextPosition(lineNumber,columnNumber){}};UI.TextEditor.Events={TextChanged:Symbol('TextChanged')};UI.TextEditor.Options;UI.AutocompleteConfig;;UI.KeyboardShortcut=class{static makeKey(keyCode,modifiers){if(typeof keyCode==='string')
keyCode=keyCode.charCodeAt(0)-(/^[a-z]/.test(keyCode)?32:0);modifiers=modifiers||UI.KeyboardShortcut.Modifiers.None;return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);}
static makeKeyFromEvent(keyboardEvent){let modifiers=UI.KeyboardShortcut.Modifiers.None;if(keyboardEvent.shiftKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Shift;if(keyboardEvent.ctrlKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Ctrl;if(keyboardEvent.altKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Alt;if(keyboardEvent.metaKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Meta;const keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,modifiers);}
static makeKeyFromEventIgnoringModifiers(keyboardEvent){const keyCode=keyboardEvent.keyCode||keyboardEvent['__keyCode'];return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode,UI.KeyboardShortcut.Modifiers.None);}
static eventHasCtrlOrMeta(event){return Host.isMac()?event.metaKey&&!event.ctrlKey:event.ctrlKey&&!event.metaKey;}
static hasNoModifiers(event){return!event.ctrlKey&&!event.shiftKey&&!event.altKey&&!event.metaKey;}
static makeDescriptor(key,modifiers){return{key:UI.KeyboardShortcut.makeKey(typeof key==='string'?key:key.code,modifiers),name:UI.KeyboardShortcut.shortcutToString(key,modifiers)};}
static makeDescriptorFromBindingShortcut(shortcut){const parts=shortcut.split(/\+(?!$)/);let modifiers=0;let keyString;for(let i=0;i<parts.length;++i){if(typeof UI.KeyboardShortcut.Modifiers[parts[i]]!=='undefined'){modifiers|=UI.KeyboardShortcut.Modifiers[parts[i]];continue;}
console.assert(i===parts.length-1,'Only one key other than modifier is allowed in shortcut <'+shortcut+'>');keyString=parts[i];break;}
console.assert(keyString,'Modifiers-only shortcuts are not allowed (encountered <'+shortcut+'>)');if(!keyString)
return null;const key=UI.KeyboardShortcut.Keys[keyString]||UI.KeyboardShortcut.KeyBindings[keyString];if(key&&key.shiftKey)
modifiers|=UI.KeyboardShortcut.Modifiers.Shift;return UI.KeyboardShortcut.makeDescriptor(key?key:keyString,modifiers);}
static shortcutToString(key,modifiers){return UI.KeyboardShortcut._modifiersToString(modifiers)+UI.KeyboardShortcut._keyName(key);}
static _keyName(key){if(typeof key==='string')
return key.toUpperCase();if(typeof key.name==='string')
return key.name;return key.name[Host.platform()]||key.name.other||'';}
static _makeKeyFromCodeAndModifiers(keyCode,modifiers){return(keyCode&255)|(modifiers<<8);}
static keyCodeAndModifiersFromKey(key){return{keyCode:key&255,modifiers:key>>8};}
static _modifiersToString(modifiers){const isMac=Host.isMac();const m=UI.KeyboardShortcut.Modifiers;const modifierNames=new Map([[m.Ctrl,isMac?'Ctrl\u2004':'Ctrl\u200A+\u200A'],[m.Alt,isMac?'\u2325\u2004':'Alt\u200A+\u200A'],[m.Shift,isMac?'\u21e7\u2004':'Shift\u200A+\u200A'],[m.Meta,isMac?'\u2318\u2004':'Win\u200A+\u200A']]);return[m.Meta,m.Ctrl,m.Alt,m.Shift].map(mapModifiers).join('');function mapModifiers(m){return modifiers&m?(modifierNames.get(m)):'';}}};UI.KeyboardShortcut.Modifiers={None:0,Shift:1,Ctrl:2,Alt:4,Meta:8,get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},get ShiftOrOption(){return Host.isMac()?this.Alt:this.Shift;}};UI.KeyboardShortcut.Key;UI.KeyboardShortcut.Keys={Backspace:{code:8,name:'\u21a4'},Tab:{code:9,name:{mac:'\u21e5',other:'Tab'}},Enter:{code:13,name:{mac:'\u21a9',other:'Enter'}},Shift:{code:16,name:{mac:'\u21e7',other:'Shift'}},Ctrl:{code:17,name:'Ctrl'},Esc:{code:27,name:'Esc'},Space:{code:32,name:'Space'},PageUp:{code:33,name:{mac:'\u21de',other:'PageUp'}},PageDown:{code:34,name:{mac:'\u21df',other:'PageDown'}},End:{code:35,name:{mac:'\u2197',other:'End'}},Home:{code:36,name:{mac:'\u2196',other:'Home'}},Left:{code:37,name:'\u2190'},Up:{code:38,name:'\u2191'},Right:{code:39,name:'\u2192'},Down:{code:40,name:'\u2193'},Delete:{code:46,name:'Del'},Zero:{code:48,name:'0'},H:{code:72,name:'H'},N:{code:78,name:'N'},P:{code:80,name:'P'},Meta:{code:91,name:'Meta'},F1:{code:112,name:'F1'},F2:{code:113,name:'F2'},F3:{code:114,name:'F3'},F4:{code:115,name:'F4'},F5:{code:116,name:'F5'},F6:{code:117,name:'F6'},F7:{code:118,name:'F7'},F8:{code:119,name:'F8'},F9:{code:120,name:'F9'},F10:{code:121,name:'F10'},F11:{code:122,name:'F11'},F12:{code:123,name:'F12'},Semicolon:{code:186,name:';'},NumpadPlus:{code:107,name:'Numpad +'},NumpadMinus:{code:109,name:'Numpad -'},Numpad0:{code:96,name:'Numpad 0'},Plus:{code:187,name:'+'},Comma:{code:188,name:','},Minus:{code:189,name:'-'},Period:{code:190,name:'.'},Slash:{code:191,name:'/'},QuestionMark:{code:191,name:'?'},Apostrophe:{code:192,name:'`'},Tilde:{code:192,name:'Tilde'},LeftSquareBracket:{code:219,name:'['},RightSquareBracket:{code:221,name:']'},Backslash:{code:220,name:'\\'},SingleQuote:{code:222,name:'\''},get CtrlOrMeta(){return Host.isMac()?this.Meta:this.Ctrl;},};UI.KeyboardShortcut.KeyBindings={};(function(){for(const key in UI.KeyboardShortcut.Keys){const descriptor=UI.KeyboardShortcut.Keys[key];if(typeof descriptor==='object'&&descriptor['code']){const name=typeof descriptor['name']==='string'?descriptor['name']:key;UI.KeyboardShortcut.KeyBindings[name]=descriptor;}}})();UI.KeyboardShortcut.Descriptor;;UI.ListDelegate=function(){};UI.ListDelegate.prototype={createElementForItem(item){},heightForItem(item){},isItemSelectable(item){},selectedItemChanged(from,to,fromElement,toElement){},};UI.ListMode={NonViewport:Symbol('UI.ListMode.NonViewport'),EqualHeightItems:Symbol('UI.ListMode.EqualHeightItems'),VariousHeightItems:Symbol('UI.ListMode.VariousHeightItems')};UI.ListControl=class{constructor(model,delegate,mode){this.element=createElement('div');this.element.style.overflowY='auto';this._topElement=this.element.createChild('div');this._bottomElement=this.element.createChild('div');this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._itemToElement=new Map();this._selectedIndex=-1;this._selectedItem=null;this.element.tabIndex=-1;this.element.addEventListener('click',this._onClick.bind(this),false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this._delegate=delegate;this._mode=mode||UI.ListMode.EqualHeightItems;this._fixedHeight=0;this._variableOffsets=new Int32Array(0);this._clearContents();if(this._mode!==UI.ListMode.NonViewport){this.element.addEventListener('scroll',()=>{this._updateViewport(this.element.scrollTop,this.element.offsetHeight);},false);}}
setModel(model){this._itemToElement.clear();const length=this._model.length;this._model.removeEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this._model=model;this._model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._replacedItemsInRange,this);this.invalidateRange(0,length);}
_replacedItemsInRange(event){const data=(event.data);const from=data.index;const to=from+data.removed.length;const oldSelectedItem=this._selectedItem;const oldSelectedElement=oldSelectedItem?(this._itemToElement.get(oldSelectedItem)||null):null;for(let i=0;i<data.removed.length;i++)
this._itemToElement.delete(data.removed[i]);this._invalidate(from,to,data.inserted);if(this._selectedIndex>=to){this._selectedIndex+=data.inserted-(to-from);this._selectedItem=this._model.at(this._selectedIndex);}else if(this._selectedIndex>=from){let index=this._findFirstSelectable(from+data.inserted,+1,false);if(index===-1)
index=this._findFirstSelectable(from-1,-1,false);this._select(index,oldSelectedItem,oldSelectedElement);}}
refreshItem(item){const index=this._model.indexOf(item);if(index===-1){console.error('Item to refresh is not present');return;}
this._itemToElement.delete(item);this.invalidateRange(index,index+1);if(this._selectedIndex!==-1)
this._select(this._selectedIndex,null,null);}
invalidateRange(from,to){this._invalidate(from,to,to-from);}
viewportResized(){if(this._mode===UI.ListMode.NonViewport)
return;const scrollTop=this.element.scrollTop;const viewportHeight=this.element.offsetHeight;this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,this._totalHeight()-viewportHeight),viewportHeight);}
invalidateItemHeight(){if(this._mode!==UI.ListMode.EqualHeightItems){console.error('Only supported in equal height items mode');return;}
this._fixedHeight=0;if(this._model.length){this._itemToElement.clear();this._invalidate(0,this._model.length,this._model.length);}}
itemForNode(node){while(node&&node.parentNodeOrShadowHost()!==this.element)
node=node.parentNodeOrShadowHost();if(!node)
return null;const element=(node);const index=this._model.findIndex(item=>this._itemToElement.get(item)===element);return index!==-1?this._model.at(index):null;}
scrollItemIntoView(item,center){const index=this._model.indexOf(item);if(index===-1){console.error('Attempt to scroll onto missing item');return;}
this._scrollIntoView(index,center);}
selectedItem(){return this._selectedItem;}
selectedIndex(){return this._selectedIndex;}
selectItem(item,center,dontScroll){let index=-1;if(item!==null){index=this._model.indexOf(item);if(index===-1){console.error('Attempt to select missing item');return;}
if(!this._delegate.isItemSelectable(item)){console.error('Attempt to select non-selectable item');return;}}
if(this._selectedIndex!==index)
this._select(index);if(index!==-1&&!dontScroll)
this._scrollIntoView(index,center);}
selectPreviousItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap)
return false;let index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex-1;index=this._findFirstSelectable(index,-1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectNextItem(canWrap,center){if(this._selectedIndex===-1&&!canWrap)
return false;let index=this._selectedIndex===-1?0:this._selectedIndex+1;index=this._findFirstSelectable(index,+1,!!canWrap);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectItemPreviousPage(center){if(this._mode===UI.ListMode.NonViewport)
return false;let index=this._selectedIndex===-1?this._model.length-1:this._selectedIndex;index=this._findPageSelectable(index,-1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
selectItemNextPage(center){if(this._mode===UI.ListMode.NonViewport)
return false;let index=this._selectedIndex===-1?0:this._selectedIndex;index=this._findPageSelectable(index,+1);if(index!==-1){this._scrollIntoView(index,center);this._select(index);return true;}
return false;}
_scrollIntoView(index,center){if(this._mode===UI.ListMode.NonViewport){this._elementAtIndex(index).scrollIntoViewIfNeeded(!!center);return;}
const top=this._offsetAtIndex(index);const bottom=this._offsetAtIndex(index+1);const viewportHeight=this.element.offsetHeight;if(center){const scrollTo=(top+bottom)/2-viewportHeight/2;this._updateViewport(Number.constrain(scrollTo,0,this._totalHeight()-viewportHeight),viewportHeight);return;}
const scrollTop=this.element.scrollTop;if(top<scrollTop)
this._updateViewport(top,viewportHeight);else if(bottom>scrollTop+viewportHeight)
this._updateViewport(bottom-viewportHeight,viewportHeight);}
_onClick(event){const item=this.itemForNode((event.target));if(item&&this._delegate.isItemSelectable(item))
this.selectItem(item);}
_onKeyDown(event){let selected=false;switch(event.key){case'ArrowUp':selected=this.selectPreviousItem(true,false);break;case'ArrowDown':selected=this.selectNextItem(true,false);break;case'PageUp':selected=this.selectItemPreviousPage(false);break;case'PageDown':selected=this.selectItemNextPage(false);break;}
if(selected)
event.consume();}
_totalHeight(){return this._offsetAtIndex(this._model.length);}
_indexAtOffset(offset){if(this._mode===UI.ListMode.NonViewport)
throw'There should be no offset conversions in non-viewport mode';if(!this._model.length||offset<0)
return 0;if(this._mode===UI.ListMode.VariousHeightItems){return Math.min(this._model.length-1,this._variableOffsets.lowerBound(offset,undefined,0,this._model.length));}
if(!this._fixedHeight)
this._measureHeight();return Math.min(this._model.length-1,Math.floor(offset/this._fixedHeight));}
_elementAtIndex(index){const item=this._model.at(index);let element=this._itemToElement.get(item);if(!element){element=this._delegate.createElementForItem(item);this._itemToElement.set(item,element);}
return element;}
_offsetAtIndex(index){if(this._mode===UI.ListMode.NonViewport)
throw'There should be no offset conversions in non-viewport mode';if(!this._model.length)
return 0;if(this._mode===UI.ListMode.VariousHeightItems)
return this._variableOffsets[index];if(!this._fixedHeight)
this._measureHeight();return index*this._fixedHeight;}
_measureHeight(){this._fixedHeight=this._delegate.heightForItem(this._model.at(0));if(!this._fixedHeight)
this._fixedHeight=UI.measurePreferredSize(this._elementAtIndex(0),this.element).height;}
_select(index,oldItem,oldElement){if(oldItem===undefined)
oldItem=this._selectedItem;if(oldElement===undefined)
oldElement=this._itemToElement.get(oldItem)||null;this._selectedIndex=index;this._selectedItem=index===-1?null:this._model.at(index);const newItem=this._selectedItem;const newElement=this._selectedIndex!==-1?this._elementAtIndex(index):null;this._delegate.selectedItemChanged(oldItem,newItem,(oldElement),newElement);}
_findFirstSelectable(index,direction,canWrap){const length=this._model.length;if(!length)
return-1;for(let step=0;step<=length;step++){if(index<0||index>=length){if(!canWrap)
return-1;index=(index+length)%length;}
if(this._delegate.isItemSelectable(this._model.at(index)))
return index;index+=direction;}
return-1;}
_findPageSelectable(index,direction){let lastSelectable=-1;const startOffset=this._offsetAtIndex(index);const viewportHeight=this.element.offsetHeight-1;while(index>=0&&index<this._model.length){if(this._delegate.isItemSelectable(this._model.at(index))){if(Math.abs(this._offsetAtIndex(index)-startOffset)>=viewportHeight)
return index;lastSelectable=index;}
index+=direction;}
return lastSelectable;}
_reallocateVariableOffsets(length,copyTo){if(this._variableOffsets.length<length){const variableOffsets=new Int32Array(Math.max(length,this._variableOffsets.length*2));variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}else if(this._variableOffsets.length>=2*length){const variableOffsets=new Int32Array(length);variableOffsets.set(this._variableOffsets.slice(0,copyTo),0);this._variableOffsets=variableOffsets;}}
_invalidate(from,to,inserted){if(this._mode===UI.ListMode.NonViewport){this._invalidateNonViewportMode(from,to-from,inserted);return;}
if(this._mode===UI.ListMode.VariousHeightItems){this._reallocateVariableOffsets(this._model.length+1,from+1);for(let i=from+1;i<=this._model.length;i++)
this._variableOffsets[i]=this._variableOffsets[i-1]+this._delegate.heightForItem(this._model.at(i-1));}
const viewportHeight=this.element.offsetHeight;const totalHeight=this._totalHeight();const scrollTop=this.element.scrollTop;if(this._renderedHeight<viewportHeight||totalHeight<viewportHeight){this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);return;}
const heightDelta=totalHeight-this._renderedHeight;if(to<=this._firstIndex){const topHeight=this._topHeight+heightDelta;this._topElement.style.height=topHeight+'px';this.element.scrollTop=scrollTop+heightDelta;this._topHeight=topHeight;this._renderedHeight=totalHeight;const indexDelta=inserted-(to-from);this._firstIndex+=indexDelta;this._lastIndex+=indexDelta;return;}
if(from>=this._lastIndex){const bottomHeight=this._bottomHeight+heightDelta;this._bottomElement.style.height=bottomHeight+'px';this._bottomHeight=bottomHeight;this._renderedHeight=totalHeight;return;}
this._clearViewport();this._updateViewport(Number.constrain(scrollTop,0,totalHeight-viewportHeight),viewportHeight);}
_invalidateNonViewportMode(start,remove,add){let startElement=this._topElement;for(let index=0;index<start;index++)
startElement=startElement.nextElementSibling;while(remove--)
startElement.nextElementSibling.remove();while(add--)
this.element.insertBefore(this._elementAtIndex(start+add),startElement.nextElementSibling);}
_clearViewport(){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;}
this._firstIndex=0;this._lastIndex=0;this._renderedHeight=0;this._topHeight=0;this._bottomHeight=0;this._clearContents();}
_clearContents(){this._topElement.style.height='0';this._bottomElement.style.height='0';this.element.removeChildren();this.element.appendChild(this._topElement);this.element.appendChild(this._bottomElement);}
_updateViewport(scrollTop,viewportHeight){if(this._mode===UI.ListMode.NonViewport){console.error('There should be no viewport updates in non-viewport mode');return;}
const totalHeight=this._totalHeight();if(!totalHeight){this._firstIndex=0;this._lastIndex=0;this._topHeight=0;this._bottomHeight=0;this._renderedHeight=0;this._topElement.style.height='0';this._bottomElement.style.height='0';return;}
const firstIndex=this._indexAtOffset(scrollTop-viewportHeight);const lastIndex=this._indexAtOffset(scrollTop+2*viewportHeight)+1;while(this._firstIndex<Math.min(firstIndex,this._lastIndex)){this._elementAtIndex(this._firstIndex).remove();this._firstIndex++;}
while(this._lastIndex>Math.max(lastIndex,this._firstIndex)){this._elementAtIndex(this._lastIndex-1).remove();this._lastIndex--;}
this._firstIndex=Math.min(this._firstIndex,lastIndex);this._lastIndex=Math.max(this._lastIndex,firstIndex);for(let index=this._firstIndex-1;index>=firstIndex;index--){const element=this._elementAtIndex(index);this.element.insertBefore(element,this._topElement.nextSibling);}
for(let index=this._lastIndex;index<lastIndex;index++){const element=this._elementAtIndex(index);this.element.insertBefore(element,this._bottomElement);}
this._firstIndex=firstIndex;this._lastIndex=lastIndex;this._topHeight=this._offsetAtIndex(firstIndex);this._topElement.style.height=this._topHeight+'px';this._bottomHeight=totalHeight-this._offsetAtIndex(lastIndex);this._bottomElement.style.height=this._bottomHeight+'px';this._renderedHeight=totalHeight;this.element.scrollTop=scrollTop;}};;UI.ListModel=class extends Common.Object{constructor(items){super();this._items=items||[];}
[Symbol.iterator](){return this._items[Symbol.iterator]();}
get length(){return this._items.length;}
at(index){return this._items[index];}
every(callback){return this._items.every(callback);}
filter(callback){return this._items.filter(callback);}
find(callback){return this._items.find(callback);}
findIndex(callback){return this._items.findIndex(callback);}
indexOf(value,fromIndex){return this._items.indexOf(value,fromIndex);}
insert(index,value){this._items.splice(index,0,value);this._replaced(index,[],1);}
insertWithComparator(value,comparator){this.insert(this._items.lowerBound(value,comparator),value);}
join(separator){return this._items.join(separator);}
remove(index){const result=this._items[index];this._items.splice(index,1);this._replaced(index,[result],0);return result;}
replace(index,value){const oldValue=this._items[index];this._items[index]=value;this._replaced(index,[oldValue],1);return oldValue;}
replaceRange(from,to,items){let removed;if(items.length<10000){removed=this._items.splice(from,to-from,...items);}else{removed=this._items.slice(from,to);const before=this._items.slice(0,from);const after=this._items.slice(to);this._items=[].concat(before,items,after);}
this._replaced(from,removed,items.length);return removed;}
replaceAll(items){const oldItems=this._items.slice();this._items=items;this._replaced(0,oldItems,items.length);return oldItems;}
slice(from,to){return this._items.slice(from,to);}
some(callback){return this._items.some(callback);}
_replaced(index,removed,inserted){this.dispatchEventToListeners(UI.ListModel.Events.ItemsReplaced,{index:index,removed:removed,inserted:inserted});}};UI.ListModel.Events={ItemsReplaced:Symbol('ItemsReplaced'),};;UI.ListWidget=class extends UI.VBox{constructor(delegate){super(true);this.registerRequiredCSS('ui/listWidget.css');this._delegate=delegate;this._list=this.contentElement.createChild('div','list');this.element.tabIndex=-1;this._lastSeparator=false;this._focusRestorer=null;this._items=[];this._editable=[];this._elements=[];this._editor=null;this._editItem=null;this._editElement=null;this._emptyPlaceholder=null;this._updatePlaceholder();}
clear(){this._items=[];this._editable=[];this._elements=[];this._lastSeparator=false;this._list.removeChildren();this._updatePlaceholder();this._stopEditing();}
appendItem(item,editable){if(this._lastSeparator&&this._items.length)
this._list.appendChild(createElementWithClass('div','list-separator'));this._lastSeparator=false;this._items.push(item);this._editable.push(editable);const element=this._list.createChild('div','list-item');element.appendChild(this._delegate.renderItem(item,editable));if(editable){element.classList.add('editable');element.appendChild(this._createControls(item,element));}
this._elements.push(element);this._updatePlaceholder();}
appendSeparator(){this._lastSeparator=true;}
removeItem(index){if(this._editItem===this._items[index])
this._stopEditing();const element=this._elements[index];const previous=element.previousElementSibling;const previousIsSeparator=previous&&previous.classList.contains('list-separator');const next=element.nextElementSibling;const nextIsSeparator=next&&next.classList.contains('list-separator');if(previousIsSeparator&&(nextIsSeparator||!next))
previous.remove();if(nextIsSeparator&&!previous)
next.remove();element.remove();this._elements.splice(index,1);this._items.splice(index,1);this._editable.splice(index,1);this._updatePlaceholder();}
addNewItem(index,item){this._startEditing(item,null,this._elements[index]||null);}
setEmptyPlaceholder(element){this._emptyPlaceholder=element;this._updatePlaceholder();}
_createControls(item,element){const controls=createElementWithClass('div','controls-container fill');controls.createChild('div','controls-gradient');const buttons=controls.createChild('div','controls-buttons');const toolbar=new UI.Toolbar('',buttons);const editButton=new UI.ToolbarButton(Common.UIString('Edit'),'largeicon-edit');editButton.addEventListener(UI.ToolbarButton.Events.Click,onEditClicked.bind(this));toolbar.appendToolbarItem(editButton);const removeButton=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-trash-bin');removeButton.addEventListener(UI.ToolbarButton.Events.Click,onRemoveClicked.bind(this));toolbar.appendToolbarItem(removeButton);return controls;function onEditClicked(){const index=this._elements.indexOf(element);const insertionPoint=this._elements[index+1]||null;this._startEditing(item,element,insertionPoint);}
function onRemoveClicked(){const index=this._elements.indexOf(element);this.element.focus();this._delegate.removeItemRequested(this._items[index],index);}}
wasShown(){super.wasShown();this._stopEditing();}
_updatePlaceholder(){if(!this._emptyPlaceholder)
return;if(!this._elements.length&&!this._editor)
this._list.appendChild(this._emptyPlaceholder);else
this._emptyPlaceholder.remove();}
_startEditing(item,element,insertionPoint){if(element&&this._editElement===element)
return;this._stopEditing();this._focusRestorer=new UI.ElementFocusRestorer(this.element);this._list.classList.add('list-editing');this._editItem=item;this._editElement=element;if(element)
element.classList.add('hidden');const index=element?this._elements.indexOf(element):-1;this._editor=this._delegate.beginEdit(item);this._updatePlaceholder();this._list.insertBefore(this._editor.element,insertionPoint);this._editor.beginEdit(item,index,element?Common.UIString('Save'):Common.UIString('Add'),this._commitEditing.bind(this),this._stopEditing.bind(this));}
_commitEditing(){const editItem=this._editItem;const isNew=!this._editElement;const editor=(this._editor);this._stopEditing();this._delegate.commitEdit(editItem,editor,isNew);}
_stopEditing(){this._list.classList.remove('list-editing');if(this._focusRestorer)
this._focusRestorer.restore();if(this._editElement)
this._editElement.classList.remove('hidden');if(this._editor&&this._editor.element.parentElement)
this._editor.element.remove();this._editor=null;this._editItem=null;this._editElement=null;this._updatePlaceholder();}};UI.ListWidget.Delegate=function(){};UI.ListWidget.Delegate.prototype={renderItem(item,editable){},removeItemRequested(item,index){},beginEdit(item){},commitEdit(item,editor,isNew){}};UI.ListWidget.Editor=class{constructor(){this.element=createElementWithClass('div','editor-container');this.element.addEventListener('keydown',onKeyDown.bind(null,isEscKey,this._cancelClicked.bind(this)),false);this.element.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._commitClicked.bind(this)),false);this._contentElement=this.element.createChild('div','editor-content');const buttonsRow=this.element.createChild('div','editor-buttons');this._commitButton=UI.createTextButton('',this._commitClicked.bind(this),'',true);buttonsRow.appendChild(this._commitButton);this._cancelButton=UI.createTextButton(Common.UIString('Cancel'),this._cancelClicked.bind(this));this._cancelButton.addEventListener('keydown',onKeyDown.bind(null,isEnterKey,this._cancelClicked.bind(this)),false);buttonsRow.appendChild(this._cancelButton);function onKeyDown(predicate,callback,event){if(predicate(event)){event.consume(true);callback();}}
this._controls=[];this._controlByName=new Map();this._validators=[];this._commit=null;this._cancel=null;this._item=null;this._index=-1;}
contentElement(){return this._contentElement;}
createInput(name,type,title,validator){const input=(UI.createInput('',type));input.placeholder=title;input.addEventListener('input',this._validateControls.bind(this,false),false);input.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,input);this._controls.push(input);this._validators.push(validator);return input;}
createSelect(name,options,validator){const select=(createElementWithClass('select','chrome-select'));for(let index=0;index<options.length;++index){const option=select.createChild('option');option.value=options[index];option.textContent=options[index];}
select.addEventListener('input',this._validateControls.bind(this,false),false);select.addEventListener('blur',this._validateControls.bind(this,false),false);this._controlByName.set(name,select);this._controls.push(select);this._validators.push(validator);return select;}
control(name){return(this._controlByName.get(name));}
_validateControls(forceValid){let allValid=true;for(let index=0;index<this._controls.length;++index){const input=this._controls[index];const valid=this._validators[index].call(null,this._item,this._index,input);input.classList.toggle('error-input',!valid&&!forceValid);allValid&=valid;}
this._commitButton.disabled=!allValid;}
beginEdit(item,index,commitButtonTitle,commit,cancel){this._commit=commit;this._cancel=cancel;this._item=item;this._index=index;this._commitButton.textContent=commitButtonTitle;this.element.scrollIntoViewIfNeeded(false);if(this._controls.length)
this._controls[0].focus();this._validateControls(true);}
_commitClicked(){if(this._commitButton.disabled)
return;const commit=this._commit;this._commit=null;this._cancel=null;this._item=null;this._index=-1;commit();}
_cancelClicked(){const cancel=this._cancel;this._commit=null;this._cancel=null;this._item=null;this._index=-1;cancel();}};;UI.panels={};UI.Panel=class extends UI.VBox{constructor(name){super();this.element.classList.add('panel');this.element.setAttribute('aria-label',name);this.element.classList.add(name);this._panelName=name;UI.panels[name]=this;this._shortcuts=({});}
get name(){return this._panelName;}
searchableView(){return null;}
elementsToRestoreScrollPositionsFor(){return[];}
handleShortcut(event){const shortcutKey=UI.KeyboardShortcut.makeKeyFromEvent(event);const handler=this._shortcuts[shortcutKey];if(handler&&handler(event))
event.handled=true;}
showInfobar(infobar){infobar.setCloseCallback(this._onInfobarClosed.bind(this,infobar));if(this.element.firstChild)
this.element.insertBefore(infobar.element,this.element.firstChild);else
this.element.appendChild(infobar.element);infobar.setParentView(this);this.doResize();}
_onInfobarClosed(infobar){infobar.element.remove();this.doResize();}};UI.PanelWithSidebar=class extends UI.Panel{constructor(name,defaultWidth){super(name);this._panelSplitWidget=new UI.SplitWidget(true,false,this._panelName+'PanelSplitViewState',defaultWidth||200);this._panelSplitWidget.show(this.element);this._mainWidget=new UI.VBox();this._panelSplitWidget.setMainWidget(this._mainWidget);this._sidebarWidget=new UI.VBox();this._sidebarWidget.setMinimumSize(100,25);this._panelSplitWidget.setSidebarWidget(this._sidebarWidget);this._sidebarWidget.element.classList.add('panel-sidebar');}
panelSidebarElement(){return this._sidebarWidget.element;}
mainElement(){return this._mainWidget.element;}
splitWidget(){return this._panelSplitWidget;}};;UI.PopoverHelper=class{constructor(container,getRequest){this._disableOnClick=false;this._hasPadding=false;this._getRequest=getRequest;this._scheduledRequest=null;this._hidePopoverCallback=null;this._container=container;this._showTimeout=0;this._hideTimeout=0;this._hidePopoverTimer=null;this._showPopoverTimer=null;this._boundMouseDown=this._mouseDown.bind(this);this._boundMouseMove=this._mouseMove.bind(this);this._boundMouseOut=this._mouseOut.bind(this);this._container.addEventListener('mousedown',this._boundMouseDown,false);this._container.addEventListener('mousemove',this._boundMouseMove,false);this._container.addEventListener('mouseout',this._boundMouseOut,false);this.setTimeout(1000);}
setTimeout(showTimeout,hideTimeout){this._showTimeout=showTimeout;this._hideTimeout=typeof hideTimeout==='number'?hideTimeout:showTimeout/2;}
setHasPadding(hasPadding){this._hasPadding=hasPadding;}
setDisableOnClick(disableOnClick){this._disableOnClick=disableOnClick;}
_eventInScheduledContent(event){return this._scheduledRequest?this._scheduledRequest.box.contains(event.clientX,event.clientY):false;}
_mouseDown(event){if(this._disableOnClick){this.hidePopover();return;}
if(this._eventInScheduledContent(event))
return;this._startHidePopoverTimer(0);this._stopShowPopoverTimer();this._startShowPopoverTimer((event),0);}
_mouseMove(event){if(this._eventInScheduledContent(event))
return;this._startHidePopoverTimer(this._hideTimeout);this._stopShowPopoverTimer();if(event.which&&this._disableOnClick)
return;this._startShowPopoverTimer((event),this.isPopoverVisible()?this._showTimeout*0.6:this._showTimeout);}
_popoverMouseMove(event){this._stopHidePopoverTimer();}
_popoverMouseOut(popover,event){if(!popover.isShowing())
return;if(event.relatedTarget&&!event.relatedTarget.isSelfOrDescendant(popover.contentElement))
this._startHidePopoverTimer(this._hideTimeout);}
_mouseOut(event){if(!this.isPopoverVisible())
return;if(!this._eventInScheduledContent(event))
this._startHidePopoverTimer(this._hideTimeout);}
_startHidePopoverTimer(timeout){if(!this._hidePopoverCallback||this._hidePopoverTimer)
return;this._hidePopoverTimer=setTimeout(()=>{this._hidePopover();this._hidePopoverTimer=null;},timeout);}
_startShowPopoverTimer(event,timeout){this._scheduledRequest=this._getRequest.call(null,event);if(!this._scheduledRequest)
return;this._showPopoverTimer=setTimeout(()=>{this._showPopoverTimer=null;this._stopHidePopoverTimer();this._hidePopover();this._showPopover(event.target.ownerDocument);},timeout);}
_stopShowPopoverTimer(){if(!this._showPopoverTimer)
return;clearTimeout(this._showPopoverTimer);this._showPopoverTimer=null;}
isPopoverVisible(){return!!this._hidePopoverCallback;}
hidePopover(){this._stopShowPopoverTimer();this._hidePopover();}
_hidePopover(){if(!this._hidePopoverCallback)
return;this._hidePopoverCallback.call(null);this._hidePopoverCallback=null;}
_showPopover(document){const popover=new UI.GlassPane();popover.registerRequiredCSS('ui/popover.css');popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow);const request=this._scheduledRequest;request.show.call(null,popover).then(success=>{if(!success)
return;if(this._scheduledRequest!==request){if(request.hide)
request.hide.call(null);return;}
if(UI.PopoverHelper._popoverHelper){console.error('One popover is already visible');UI.PopoverHelper._popoverHelper.hidePopover();}
UI.PopoverHelper._popoverHelper=this;popover.contentElement.classList.toggle('has-padding',this._hasPadding);popover.contentElement.addEventListener('mousemove',this._popoverMouseMove.bind(this),true);popover.contentElement.addEventListener('mouseout',this._popoverMouseOut.bind(this,popover),true);popover.setContentAnchorBox(request.box);popover.show(document);this._hidePopoverCallback=()=>{if(request.hide)
request.hide.call(null);popover.hide();delete UI.PopoverHelper._popoverHelper;};});}
_stopHidePopoverTimer(){if(!this._hidePopoverTimer)
return;clearTimeout(this._hidePopoverTimer);this._hidePopoverTimer=null;this._stopShowPopoverTimer();}
dispose(){this._container.removeEventListener('mousedown',this._boundMouseDown,false);this._container.removeEventListener('mousemove',this._boundMouseMove,false);this._container.removeEventListener('mouseout',this._boundMouseOut,false);}};UI.PopoverRequest;;UI.ProgressIndicator=class{constructor(){this.element=createElementWithClass('div','progress-indicator');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/progressIndicator.css');this._contentElement=this._shadowRoot.createChild('div','progress-indicator-shadow-container');this._labelElement=this._contentElement.createChild('div','title');this._progressElement=this._contentElement.createChild('progress');this._progressElement.value=0;this._stopButton=this._contentElement.createChild('button','progress-indicator-shadow-stop-button');this._stopButton.addEventListener('click',this.cancel.bind(this));this._isCanceled=false;this._worked=0;}
show(parent){parent.appendChild(this.element);}
done(){if(this._isDone)
return;this._isDone=true;this.element.remove();}
cancel(){this._isCanceled=true;}
isCanceled(){return this._isCanceled;}
setTitle(title){this._labelElement.textContent=title;}
setTotalWork(totalWork){this._progressElement.max=totalWork;}
setWorked(worked,title){this._worked=worked;this._progressElement.value=worked;if(title)
this.setTitle(title);}
worked(worked){this.setWorked(this._worked+(worked||1));}};;UI.ResizerWidget=class extends Common.Object{constructor(){super();this._isEnabled=true;this._elements=[];this._installDragOnMouseDownBound=this._installDragOnMouseDown.bind(this);this._cursor='nwse-resize';}
isEnabled(){return this._isEnabled;}
setEnabled(enabled){this._isEnabled=enabled;this.updateElementCursors();}
elements(){return this._elements.slice();}
addElement(element){if(this._elements.indexOf(element)!==-1)
return;this._elements.push(element);element.addEventListener('mousedown',this._installDragOnMouseDownBound,false);this._updateElementCursor(element);}
removeElement(element){if(this._elements.indexOf(element)===-1)
return;this._elements.remove(element);element.removeEventListener('mousedown',this._installDragOnMouseDownBound,false);element.style.removeProperty('cursor');}
updateElementCursors(){this._elements.forEach(this._updateElementCursor.bind(this));}
_updateElementCursor(element){if(this._isEnabled)
element.style.setProperty('cursor',this.cursor());else
element.style.removeProperty('cursor');}
cursor(){return this._cursor;}
setCursor(cursor){this._cursor=cursor;this.updateElementCursors();}
_installDragOnMouseDown(event){if(this._elements.indexOf(event.target)===-1)
return false;UI.elementDragStart((event.target),this._dragStart.bind(this),this._drag.bind(this),this._dragEnd.bind(this),this.cursor(),event);}
_dragStart(event){if(!this._isEnabled)
return false;this._startX=event.pageX;this._startY=event.pageY;this.sendDragStart(this._startX,this._startY);return true;}
sendDragStart(x,y){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startX:x,currentX:x,startY:y,currentY:y});}
_drag(event){if(!this._isEnabled){this._dragEnd(event);return true;}
this.sendDragMove(this._startX,event.pageX,this._startY,event.pageY,event.shiftKey);event.preventDefault();return false;}
sendDragMove(startX,currentX,startY,currentY,shiftKey){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startX:startX,currentX:currentX,startY:startY,currentY:currentY,shiftKey:shiftKey});}
_dragEnd(event){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeEnd);delete this._startX;delete this._startY;}};UI.ResizerWidget.Events={ResizeStart:Symbol('ResizeStart'),ResizeUpdate:Symbol('ResizeUpdate'),ResizeEnd:Symbol('ResizeEnd')};UI.SimpleResizerWidget=class extends UI.ResizerWidget{constructor(){super();this._isVertical=true;}
isVertical(){return this._isVertical;}
setVertical(vertical){this._isVertical=vertical;this.updateElementCursors();}
cursor(){return this._isVertical?'ns-resize':'ew-resize';}
sendDragStart(x,y){const position=this._isVertical?y:x;this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeStart,{startPosition:position,currentPosition:position});}
sendDragMove(startX,currentX,startY,currentY,shiftKey){if(this._isVertical){this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startY,currentPosition:currentY,shiftKey:shiftKey});}else{this.dispatchEventToListeners(UI.ResizerWidget.Events.ResizeUpdate,{startPosition:startX,currentPosition:currentX,shiftKey:shiftKey});}}};;UI.RemoteDebuggingTerminatedScreen=class extends UI.VBox{constructor(reason){super(true);this.registerRequiredCSS('ui/remoteDebuggingTerminatedScreen.css');const message=this.contentElement.createChild('div','message');message.createChild('span').textContent=Common.UIString('Debugging connection was closed. Reason: ');message.createChild('span','reason').textContent=reason;this.contentElement.createChild('div','message').textContent=Common.UIString('Reconnect when ready by reopening DevTools.');const button=UI.createTextButton(Common.UIString('Reconnect DevTools'),()=>window.location.reload());this.contentElement.createChild('div','button').appendChild(button);}
static show(reason){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);new UI.RemoteDebuggingTerminatedScreen(reason).show(dialog.contentElement);dialog.show();}};;UI.ReportView=class extends UI.VBox{constructor(title){super(true);this.registerRequiredCSS('ui/reportView.css');this._contentBox=this.contentElement.createChild('div','report-content-box');this._headerElement=this._contentBox.createChild('div','report-header vbox');this._titleElement=this._headerElement.createChild('div','report-title');this._titleElement.textContent=title;this._sectionList=this._contentBox.createChild('div','vbox');}
setTitle(title){if(this._titleElement.textContent===title)
return;this._titleElement.textContent=title;}
setSubtitle(subtitle){if(this._subtitleElement&&this._subtitleElement.textContent===subtitle)
return;if(!this._subtitleElement)
this._subtitleElement=this._headerElement.createChild('div','report-subtitle');this._subtitleElement.textContent=subtitle;}
setURL(link){if(!this._urlElement)
this._urlElement=this._headerElement.createChild('div','report-url link');this._urlElement.removeChildren();if(link)
this._urlElement.appendChild(link);}
createToolbar(){const toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;}
appendSection(title,className){const section=new UI.ReportView.Section(title,className);section.show(this._sectionList);return section;}
sortSections(comparator){const sections=(this.children().slice());const sorted=sections.every((e,i,a)=>!i||comparator(a[i-1],a[i])<=0);if(sorted)
return;this.detachChildWidgets();sections.sort(comparator);for(const section of sections)
section.show(this._sectionList);}
setHeaderVisible(visible){this._headerElement.classList.toggle('hidden',!visible);}
setBodyScrollable(scrollable){this._contentBox.classList.toggle('no-scroll',!scrollable);}};UI.ReportView.Section=class extends UI.VBox{constructor(title,className){super();this.element.classList.add('report-section');if(className)
this.element.classList.add(className);this._headerElement=this.element.createChild('div','report-section-header');this._titleElement=this._headerElement.createChild('div','report-section-title');this._titleElement.textContent=title;this._fieldList=this.element.createChild('div','vbox');this._fieldMap=new Map();}
title(){return this._titleElement.textContent;}
setTitle(title){if(this._titleElement.textContent!==title)
this._titleElement.textContent=title;}
createToolbar(){const toolbar=new UI.Toolbar('');this._headerElement.appendChild(toolbar.element);return toolbar;}
appendField(title,textValue){let row=this._fieldMap.get(title);if(!row){row=this._fieldList.createChild('div','report-field');row.createChild('div','report-field-name').textContent=title;this._fieldMap.set(title,row);row.createChild('div','report-field-value');}
if(textValue)
row.lastElementChild.textContent=textValue;return(row.lastElementChild);}
removeField(title){const row=this._fieldMap.get(title);if(row)
row.remove();this._fieldMap.delete(title);}
setFieldVisible(title,visible){const row=this._fieldMap.get(title);if(row)
row.classList.toggle('hidden',!visible);}
fieldValue(title){const row=this._fieldMap.get(title);return row?row.lastElementChild:null;}
appendRow(){return this._fieldList.createChild('div','report-row');}
clearContent(){this._fieldList.removeChildren();this._fieldMap.clear();}};;UI.RootView=class extends UI.VBox{constructor(){super();this.markAsRoot();this.element.classList.add('root-view');this.registerRequiredCSS('ui/rootView.css');this.element.setAttribute('spellcheck',false);}
attachToDocument(document){document.defaultView.addEventListener('resize',this.doResize.bind(this),false);this._window=document.defaultView;this.doResize();this.show((document.body));}
doResize(){if(this._window){const size=this.constraints().minimum;const zoom=UI.zoomManager.zoomFactor();const right=Math.min(0,this._window.innerWidth-size.width/zoom);this.element.style.marginRight=right+'px';const bottom=Math.min(0,this._window.innerHeight-size.height/zoom);this.element.style.marginBottom=bottom+'px';}
super.doResize();}};;UI.SearchableView=class extends UI.VBox{constructor(searchable,settingName){super(true);this.registerRequiredCSS('ui/searchableView.css');this.element[UI.SearchableView._symbol]=this;this._searchProvider=searchable;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this._replaceable=false;this.contentElement.createChild('content');this._footerElementContainer=this.contentElement.createChild('div','search-bar hidden');this._footerElementContainer.style.order=100;this._footerElement=this._footerElementContainer.createChild('div','toolbar-search');const replaceToggleToolbar=new UI.Toolbar('replace-toggle-toolbar',this._footerElement);this._replaceToggleButton=new UI.ToolbarToggle(Common.UIString('Replace'),'mediumicon-replace');this._replaceToggleButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleReplace,this);replaceToggleToolbar.appendToolbarItem(this._replaceToggleButton);const searchInputElements=this._footerElement.createChild('div','toolbar-search-inputs');const searchControlElement=searchInputElements.createChild('div','toolbar-search-control');this._searchInputElement=UI.HistoryInput.create();this._searchInputElement.classList.add('search-replace');this._searchInputElement.id='search-input-field';this._searchInputElement.placeholder=Common.UIString('Find');searchControlElement.appendChild(this._searchInputElement);this._matchesElement=searchControlElement.createChild('label','search-results-matches');this._matchesElement.setAttribute('for','search-input-field');const searchNavigationElement=searchControlElement.createChild('div','toolbar-search-navigation-controls');this._searchNavigationPrevElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-prev');this._searchNavigationPrevElement.addEventListener('click',this._onPrevButtonSearch.bind(this),false);this._searchNavigationPrevElement.title=Common.UIString('Search previous');this._searchNavigationNextElement=searchNavigationElement.createChild('div','toolbar-search-navigation toolbar-search-navigation-next');this._searchNavigationNextElement.addEventListener('click',this._onNextButtonSearch.bind(this),false);this._searchNavigationNextElement.title=Common.UIString('Search next');this._searchInputElement.addEventListener('keydown',this._onSearchKeyDown.bind(this),true);this._searchInputElement.addEventListener('input',this._onInput.bind(this),false);this._replaceInputElement=searchInputElements.createChild('input','search-replace toolbar-replace-control hidden');this._replaceInputElement.addEventListener('keydown',this._onReplaceKeyDown.bind(this),true);this._replaceInputElement.placeholder=Common.UIString('Replace');this._buttonsContainer=this._footerElement.createChild('div','toolbar-search-buttons');const firstRowButtons=this._buttonsContainer.createChild('div','first-row-buttons');const toolbar=new UI.Toolbar('toolbar-search-options',firstRowButtons);if(this._searchProvider.supportsCaseSensitiveSearch()){this._caseSensitiveButton=new UI.ToolbarToggle(Common.UIString('Match Case'));this._caseSensitiveButton.setText('Aa');this._caseSensitiveButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleCaseSensitiveSearch,this);toolbar.appendToolbarItem(this._caseSensitiveButton);}
if(this._searchProvider.supportsRegexSearch()){this._regexButton=new UI.ToolbarToggle(Common.UIString('Use Regular Expression'));this._regexButton.setText('.*');this._regexButton.addEventListener(UI.ToolbarButton.Events.Click,this._toggleRegexSearch,this);toolbar.appendToolbarItem(this._regexButton);}
const cancelButtonElement=UI.createTextButton(Common.UIString('Cancel'),this.closeSearch.bind(this),'search-action-button');firstRowButtons.appendChild(cancelButtonElement);this._secondRowButtons=this._buttonsContainer.createChild('div','second-row-buttons hidden');this._replaceButtonElement=UI.createTextButton(Common.UIString('Replace'),this._replace.bind(this),'search-action-button');this._replaceButtonElement.disabled=true;this._secondRowButtons.appendChild(this._replaceButtonElement);this._replaceAllButtonElement=UI.createTextButton(Common.UIString('Replace all'),this._replaceAll.bind(this),'search-action-button');this._secondRowButtons.appendChild(this._replaceAllButtonElement);this._replaceAllButtonElement.disabled=true;this._minimalSearchQuerySize=3;this._loadSetting();}
static fromElement(element){let view=null;while(element&&!view){view=element[UI.SearchableView._symbol];element=element.parentElementOrShadowHost();}
return view;}
_toggleCaseSensitiveSearch(){this._caseSensitiveButton.setToggled(!this._caseSensitiveButton.toggled());this._saveSetting();this._performSearch(false,true);}
_toggleRegexSearch(){this._regexButton.setToggled(!this._regexButton.toggled());this._saveSetting();this._performSearch(false,true);}
_toggleReplace(){this._replaceToggleButton.setToggled(!this._replaceToggleButton.toggled());this._updateSecondRowVisibility();}
_saveSetting(){if(!this._setting)
return;const settingValue=this._setting.get()||{};settingValue.caseSensitive=this._caseSensitiveButton.toggled();settingValue.isRegex=this._regexButton.toggled();this._setting.set(settingValue);}
_loadSetting(){const settingValue=this._setting?(this._setting.get()||{}):{};if(this._searchProvider.supportsCaseSensitiveSearch())
this._caseSensitiveButton.setToggled(!!settingValue.caseSensitive);if(this._searchProvider.supportsRegexSearch())
this._regexButton.setToggled(!!settingValue.isRegex);}
setMinimalSearchQuerySize(minimalSearchQuerySize){this._minimalSearchQuerySize=minimalSearchQuerySize;}
setPlaceholder(placeholder){this._searchInputElement.placeholder=placeholder;}
setReplaceable(replaceable){this._replaceable=replaceable;}
updateSearchMatchesCount(matches){if(this._searchProvider.currentSearchMatches===matches)
return;this._searchProvider.currentSearchMatches=matches;this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentQuery?matches:0,-1);}
updateCurrentMatchIndex(currentMatchIndex){this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentSearchMatches,currentMatchIndex);}
isSearchVisible(){return this._searchIsVisible;}
closeSearch(){this.cancelSearch();if(this._footerElementContainer.hasFocus())
this.focus();}
_toggleSearchBar(toggled){this._footerElementContainer.classList.toggle('hidden',!toggled);this.doResize();}
cancelSearch(){if(!this._searchIsVisible)
return;this.resetSearch();delete this._searchIsVisible;this._toggleSearchBar(false);}
resetSearch(){this._clearSearch();this._updateReplaceVisibility();this._matchesElement.textContent='';}
refreshSearch(){if(!this._searchIsVisible)
return;this.resetSearch();this._performSearch(false,false);}
handleFindNextShortcut(){if(!this._searchIsVisible)
return false;this._searchProvider.jumpToNextSearchResult();return true;}
handleFindPreviousShortcut(){if(!this._searchIsVisible)
return false;this._searchProvider.jumpToPreviousSearchResult();return true;}
handleFindShortcut(){this.showSearchField();return true;}
handleCancelSearchShortcut(){if(!this._searchIsVisible)
return false;this.closeSearch();return true;}
_updateSearchNavigationButtonState(enabled){this._replaceButtonElement.disabled=!enabled;this._replaceAllButtonElement.disabled=!enabled;this._searchNavigationPrevElement.classList.toggle('enabled',enabled);this._searchNavigationNextElement.classList.toggle('enabled',enabled);}
_updateSearchMatchesCountAndCurrentMatchIndex(matches,currentMatchIndex){if(!this._currentQuery)
this._matchesElement.textContent='';else if(matches===0||currentMatchIndex>=0)
this._matchesElement.textContent=Common.UIString('%d of %d',currentMatchIndex+1,matches);else if(matches===1)
this._matchesElement.textContent=Common.UIString('1 match');else
this._matchesElement.textContent=Common.UIString('%d matches',matches);this._updateSearchNavigationButtonState(matches>0);}
showSearchField(){if(this._searchIsVisible)
this.cancelSearch();let queryCandidate;if(!this._searchInputElement.hasFocus()){const selection=UI.inspectorView.element.window().getSelection();if(selection.rangeCount)
queryCandidate=selection.toString().replace(/\r?\n.*/,'');}
this._toggleSearchBar(true);this._updateReplaceVisibility();if(queryCandidate)
this._searchInputElement.value=queryCandidate;this._performSearch(false,false);this._searchInputElement.focus();this._searchInputElement.select();this._searchIsVisible=true;}
_updateReplaceVisibility(){this._replaceToggleButton.setVisible(this._replaceable);if(!this._replaceable){this._replaceToggleButton.setToggled(false);this._updateSecondRowVisibility();}}
_onSearchKeyDown(event){if(isEscKey(event)){this.closeSearch();event.consume(true);return;}
if(!isEnterKey(event))
return;if(!this._currentQuery)
this._performSearch(true,true,event.shiftKey);else
this._jumpToNextSearchResult(event.shiftKey);}
_onReplaceKeyDown(event){if(isEnterKey(event))
this._replace();}
_jumpToNextSearchResult(isBackwardSearch){if(!this._currentQuery||!this._searchNavigationPrevElement.classList.contains('enabled'))
return;if(isBackwardSearch)
this._searchProvider.jumpToPreviousSearchResult();else
this._searchProvider.jumpToNextSearchResult();}
_onNextButtonSearch(event){if(!this._searchNavigationNextElement.classList.contains('enabled'))
return;this._jumpToNextSearchResult();this._searchInputElement.focus();}
_onPrevButtonSearch(event){if(!this._searchNavigationPrevElement.classList.contains('enabled'))
return;this._jumpToNextSearchResult(true);this._searchInputElement.focus();}
_onFindClick(event){if(!this._currentQuery)
this._performSearch(true,true);else
this._jumpToNextSearchResult();this._searchInputElement.focus();}
_onPreviousClick(event){if(!this._currentQuery)
this._performSearch(true,true,true);else
this._jumpToNextSearchResult(true);this._searchInputElement.focus();}
_clearSearch(){delete this._currentQuery;if(!!this._searchProvider.currentQuery){delete this._searchProvider.currentQuery;this._searchProvider.searchCanceled();}
this._updateSearchMatchesCountAndCurrentMatchIndex(0,-1);}
_performSearch(forceSearch,shouldJump,jumpBackwards){const query=this._searchInputElement.value;if(!query||(!forceSearch&&query.length<this._minimalSearchQuerySize&&!this._currentQuery)){this._clearSearch();return;}
this._currentQuery=query;this._searchProvider.currentQuery=query;const searchConfig=this._currentSearchConfig();this._searchProvider.performSearch(searchConfig,shouldJump,jumpBackwards);}
_currentSearchConfig(){const query=this._searchInputElement.value;const caseSensitive=this._caseSensitiveButton?this._caseSensitiveButton.toggled():false;const isRegex=this._regexButton?this._regexButton.toggled():false;return new UI.SearchableView.SearchConfig(query,caseSensitive,isRegex);}
_updateSecondRowVisibility(){const secondRowVisible=this._replaceToggleButton.toggled();this._footerElementContainer.classList.toggle('replaceable',secondRowVisible);this._secondRowButtons.classList.toggle('hidden',!secondRowVisible);this._replaceInputElement.classList.toggle('hidden',!secondRowVisible);if(secondRowVisible)
this._replaceInputElement.focus();else
this._searchInputElement.focus();this.doResize();}
_replace(){const searchConfig=this._currentSearchConfig();(this._searchProvider).replaceSelectionWith(searchConfig,this._replaceInputElement.value);delete this._currentQuery;this._performSearch(true,true);}
_replaceAll(){const searchConfig=this._currentSearchConfig();(this._searchProvider).replaceAllWith(searchConfig,this._replaceInputElement.value);}
_onInput(event){if(this._valueChangedTimeoutId)
clearTimeout(this._valueChangedTimeoutId);const timeout=this._searchInputElement.value.length<3?200:0;this._valueChangedTimeoutId=setTimeout(this._onValueChanged.bind(this),timeout);}
_onValueChanged(){if(!this._searchIsVisible)
return;delete this._valueChangedTimeoutId;this._performSearch(false,true);}};UI.SearchableView._symbol=Symbol('searchableView');UI.Searchable=function(){};UI.Searchable.prototype={searchCanceled(){},performSearch(searchConfig,shouldJump,jumpBackwards){},jumpToNextSearchResult(){},jumpToPreviousSearchResult(){},supportsCaseSensitiveSearch(){},supportsRegexSearch(){}};UI.Replaceable=function(){};UI.Replaceable.prototype={replaceSelectionWith(searchConfig,replacement){},replaceAllWith(searchConfig,replacement){}};UI.SearchableView.SearchConfig=class{constructor(query,caseSensitive,isRegex){this.query=query;this.caseSensitive=caseSensitive;this.isRegex=isRegex;}
toSearchRegex(global){let modifiers=this.caseSensitive?'':'i';if(global)
modifiers+='g';const query=this.isRegex?'/'+this.query+'/':this.query;let regex;try{if(/^\/.+\/$/.test(query)){regex=new RegExp(query.substring(1,query.length-1),modifiers);regex.__fromRegExpQuery=true;}}catch(e){}
if(!regex)
regex=createPlainTextSearchRegex(query,modifiers);return regex;}};;UI.SegmentedButton=class extends UI.HBox{constructor(){super(true);this._buttons=new Map();this._selected=null;this.registerRequiredCSS('ui/segmentedButton.css');this.contentElement.classList.add('segmented-button');}
addSegment(label,value,tooltip){const button=this.contentElement.createChild('button','segmented-button-segment');button.textContent=label;button.title=tooltip;this._buttons.set(value,button);button.addEventListener('click',()=>this.select(value));}
select(value){if(this._selected===value)
return;this._selected=value;for(const key of this._buttons.keys())
this._buttons.get(key).classList.toggle('segmented-button-segment-selected',key===this._selected);}
selected(){return this._selected;}};;UI.SettingsUI={};UI.SettingsUI.createSettingCheckbox=function(name,setting,omitParagraphElement,tooltip){const label=UI.CheckboxLabel.create(name);if(tooltip)
label.title=tooltip;const input=label.checkboxElement;input.name=name;UI.SettingsUI.bindCheckbox(input,setting);if(omitParagraphElement)
return label;const p=createElement('p');p.appendChild(label);return p;};UI.SettingsUI.createSettingSelect=function(name,options,setting){const p=createElement('p');p.createChild('label').textContent=name;const select=p.createChild('select','chrome-select');for(let i=0;i<options.length;++i){const option=options[i];const optionName=option.raw?option.text:Common.UIString(option.text);select.add(new Option(optionName,option.value));}
setting.addChangeListener(settingChanged);settingChanged();select.addEventListener('change',selectChanged,false);return p;function settingChanged(){const newValue=setting.get();for(let i=0;i<options.length;i++){if(options[i].value===newValue)
select.selectedIndex=i;}}
function selectChanged(){setting.set(options[select.selectedIndex].value);}};UI.SettingsUI.bindCheckbox=function(input,setting){function settingChanged(){if(input.checked!==setting.get())
input.checked=setting.get();}
setting.addChangeListener(settingChanged);settingChanged();function inputChanged(){if(setting.get()!==input.checked)
setting.set(input.checked);}
input.addEventListener('change',inputChanged,false);};UI.SettingsUI.createCustomSetting=function(name,element){const p=createElement('p');const fieldsetElement=p.createChild('fieldset');fieldsetElement.createChild('label').textContent=name;fieldsetElement.appendChild(element);return p;};UI.SettingsUI.createControlForSetting=function(setting){if(!setting.extension())
return null;const descriptor=setting.extension().descriptor();const uiTitle=Common.UIString(setting.title()||'');switch(descriptor['settingType']){case'boolean':return UI.SettingsUI.createSettingCheckbox(uiTitle,setting);case'enum':if(Array.isArray(descriptor['options']))
return UI.SettingsUI.createSettingSelect(uiTitle,descriptor['options'],setting);console.error('Enum setting defined without options');return null;default:console.error('Invalid setting type: '+descriptor['settingType']);return null;}};UI.SettingUI=function(){};UI.SettingUI.prototype={settingElement(){}};;UI.SoftContextMenu=class{constructor(items,itemSelectedCallback,parentMenu){this._items=items;this._itemSelectedCallback=itemSelectedCallback;this._parentMenu=parentMenu;}
show(document,anchorBox){if(!this._items.length)
return;this._document=document;this._glassPane=new UI.GlassPane();this._glassPane.setPointerEventsBehavior(this._parentMenu?UI.GlassPane.PointerEventsBehavior.PierceGlassPane:UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._glassPane.registerRequiredCSS('ui/softContextMenu.css');this._glassPane.setContentAnchorBox(anchorBox);this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(this._parentMenu?UI.GlassPane.AnchorBehavior.PreferRight:UI.GlassPane.AnchorBehavior.PreferBottom);this._contextMenuElement=this._glassPane.contentElement.createChild('div','soft-context-menu');this._contextMenuElement.tabIndex=0;this._contextMenuElement.addEventListener('mouseup',e=>e.consume(),false);this._contextMenuElement.addEventListener('keydown',this._menuKeyDown.bind(this),false);for(let i=0;i<this._items.length;++i)
this._contextMenuElement.appendChild(this._createMenuItem(this._items[i]));this._glassPane.show(document);this._focusRestorer=new UI.ElementFocusRestorer(this._contextMenuElement);if(!this._parentMenu){this._onBodyMouseDown=event=>{this.discard();event.consume(true);};this._document.body.addEventListener('mousedown',this._onBodyMouseDown,false);}}
discard(){if(this._subMenu)
this._subMenu.discard();if(this._focusRestorer)
this._focusRestorer.restore();if(this._glassPane){this._glassPane.hide();delete this._glassPane;if(this._onBodyMouseDown){this._document.body.removeEventListener('mousedown',this._onBodyMouseDown,false);delete this._onBodyMouseDown;}}
if(this._parentMenu)
delete this._parentMenu._subMenu;}
_createMenuItem(item){if(item.type==='separator')
return this._createSeparator();if(item.type==='subMenu')
return this._createSubMenu(item);const menuItemElement=createElementWithClass('div','soft-context-menu-item');const checkMarkElement=UI.Icon.create('smallicon-checkmark','checkmark');menuItemElement.appendChild(checkMarkElement);if(!item.checked)
checkMarkElement.style.opacity='0';if(item.element){const wrapper=menuItemElement.createChild('div','soft-context-menu-custom-item');wrapper.appendChild(item.element);menuItemElement._isCustom=true;return menuItemElement;}
if(!item.enabled)
menuItemElement.classList.add('soft-context-menu-disabled');menuItemElement.createTextChild(item.label);menuItemElement.createChild('span','soft-context-menu-shortcut').textContent=item.shortcut;menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);menuItemElement._actionId=item.id;return menuItemElement;}
_createSubMenu(item){const menuItemElement=createElementWithClass('div','soft-context-menu-item');menuItemElement._subItems=item.subItems;const checkMarkElement=UI.Icon.create('smallicon-checkmark','soft-context-menu-item-checkmark');checkMarkElement.classList.add('checkmark');menuItemElement.appendChild(checkMarkElement);checkMarkElement.style.opacity='0';menuItemElement.createTextChild(item.label);const subMenuArrowElement=menuItemElement.createChild('span','soft-context-menu-item-submenu-arrow');subMenuArrowElement.textContent='\u25B6';menuItemElement.addEventListener('mousedown',this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener('mouseup',this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener('mouseover',this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener('mouseleave',this._menuItemMouseLeave.bind(this),false);return menuItemElement;}
_createSeparator(){const separatorElement=createElementWithClass('div','soft-context-menu-separator');separatorElement._isSeparator=true;separatorElement.createChild('div','separator-line');return separatorElement;}
_menuItemMouseDown(event){event.consume(true);}
_menuItemMouseUp(event){this._triggerAction(event.target,event);event.consume();}
_root(){let root=this;while(root._parentMenu)
root=root._parentMenu;return root;}
_triggerAction(menuItemElement,event){if(!menuItemElement._subItems){this._root().discard();event.consume(true);if(typeof menuItemElement._actionId!=='undefined'){this._itemSelectedCallback(menuItemElement._actionId);delete menuItemElement._actionId;}
return;}
this._showSubMenu(menuItemElement);event.consume();}
_showSubMenu(menuItemElement){if(menuItemElement._subMenuTimer){clearTimeout(menuItemElement._subMenuTimer);delete menuItemElement._subMenuTimer;}
if(this._subMenu)
return;this._subMenu=new UI.SoftContextMenu(menuItemElement._subItems,this._itemSelectedCallback,this);const anchorBox=menuItemElement.boxInWindow();anchorBox.y-=5;anchorBox.x+=3;anchorBox.width-=6;anchorBox.height+=10;this._subMenu.show(this._document,anchorBox);}
_menuItemMouseOver(event){this._highlightMenuItem(event.target,true);}
_menuItemMouseLeave(event){if(!this._subMenu||!event.relatedTarget){this._highlightMenuItem(null,true);return;}
const relatedTarget=event.relatedTarget;if(relatedTarget===this._contextMenuElement)
this._highlightMenuItem(null,true);}
_highlightMenuItem(menuItemElement,scheduleSubMenu){if(this._highlightedMenuItemElement===menuItemElement)
return;if(this._subMenu)
this._subMenu.discard();if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.remove('force-white-icons');this._highlightedMenuItemElement.classList.remove('soft-context-menu-item-mouse-over');if(this._highlightedMenuItemElement._subItems&&this._highlightedMenuItemElement._subMenuTimer){clearTimeout(this._highlightedMenuItemElement._subMenuTimer);delete this._highlightedMenuItemElement._subMenuTimer;}}
this._highlightedMenuItemElement=menuItemElement;if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.add('force-white-icons');this._highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over');this._contextMenuElement.focus();if(scheduleSubMenu&&this._highlightedMenuItemElement._subItems&&!this._highlightedMenuItemElement._subMenuTimer){this._highlightedMenuItemElement._subMenuTimer=setTimeout(this._showSubMenu.bind(this,this._highlightedMenuItemElement),150);}}}
_highlightPrevious(){let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.previousSibling:this._contextMenuElement.lastChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement._isCustom))
menuItemElement=menuItemElement.previousSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,false);}
_highlightNext(){let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&(menuItemElement._isSeparator||menuItemElement._isCustom))
menuItemElement=menuItemElement.nextSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,false);}
_menuKeyDown(event){switch(event.key){case'ArrowUp':this._highlightPrevious();break;case'ArrowDown':this._highlightNext();break;case'ArrowLeft':if(this._parentMenu){this._highlightMenuItem(null,false);this.discard();}
break;case'ArrowRight':if(!this._highlightedMenuItemElement)
break;if(this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._highlightNext();}
break;case'Escape':this.discard();break;case'Enter':if(!isEnterKey(event))
break;case' ':if(this._highlightedMenuItemElement)
this._triggerAction(this._highlightedMenuItemElement,event);if(this._highlightedMenuItemElement._subItems)
this._subMenu._highlightNext();break;}
event.consume(true);}};;UI.SoftDropDown=class{constructor(model,delegate){this._delegate=delegate;this._selectedItem=null;this._model=model;this.element=createElementWithClass('button','soft-dropdown');const shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/softDropDownButton.css');this._titleElement=shadowRoot.createChild('span','title');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down');shadowRoot.appendChild(dropdownArrowIcon);this._glassPane=new UI.GlassPane();this._glassPane.setMarginBehavior(UI.GlassPane.MarginBehavior.NoMargin);this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this._hide.bind(this));this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._list=new UI.ListControl(model,this,UI.ListMode.EqualHeightItems);this._list.element.classList.add('item-list');this._rowHeight=36;this._width=315;UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/softDropDown.css').appendChild(this._list.element);this._listWasShowing200msAgo=false;this.element.addEventListener('mousedown',event=>{if(this._listWasShowing200msAgo)
this._hide(event);else if(!this.element.disabled)
this._show(event);},false);this.element.addEventListener('keydown',this._onKeyDown.bind(this),false);this.element.addEventListener('focusout',this._hide.bind(this),false);this._list.element.addEventListener('mousedown',event=>event.consume(true),false);this._list.element.addEventListener('mouseup',event=>{if(event.target===this._list.element)
return;if(!this._listWasShowing200msAgo)
return;this._selectHighlightedItem();this._hide(event);},false);model.addEventListener(UI.ListModel.Events.ItemsReplaced,this._itemsReplaced,this);}
_show(event){if(this._glassPane.isShowing())
return;this._glassPane.setContentAnchorBox(this.element.boxInWindow());this._glassPane.show((this.element.ownerDocument));this._updateGlasspaneSize();if(this._selectedItem)
this._list.selectItem(this._selectedItem);this.element.focus();event.consume(true);setTimeout(()=>this._listWasShowing200msAgo=true,200);}
_updateGlasspaneSize(){const maxHeight=this._rowHeight*(Math.min(this._model.length,9));this._glassPane.setMaxContentSize(new UI.Size(this._width,maxHeight));this._list.viewportResized();}
_hide(event){setTimeout(()=>this._listWasShowing200msAgo=false,200);this._glassPane.hide();this._list.selectItem(null);event.consume(true);}
_onKeyDown(event){let handled=false;switch(event.key){case'ArrowLeft':case'ArrowUp':handled=this._list.selectPreviousItem(false,false);break;case'ArrowRight':case'ArrowDown':handled=this._list.selectNextItem(false,false);break;case'PageUp':handled=this._list.selectItemPreviousPage(false);break;case'PageDown':handled=this._list.selectItemNextPage(false);break;case'Home':for(let i=0;i<this._model.length;i++){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}}
break;case'End':for(let i=this._model.length-1;i>=0;i--){if(this.isItemSelectable(this._model.at(i))){this._list.selectItem(this._model.at(i));handled=true;break;}}
break;case'Escape':this._hide(event);break;case'Tab':if(!this._glassPane.isShowing())
break;this._selectHighlightedItem();this._hide(event);break;case'Enter':if(!this._glassPane.isShowing()){this._show(event);break;}
this._selectHighlightedItem();this._hide(event);break;case' ':this._show(event);break;default:if(event.key.length===1){const selectedIndex=this._list.selectedIndex();const letter=event.key.toUpperCase();for(let i=0;i<this._model.length;i++){const item=this._model.at((selectedIndex+i+1)%this._model.length);if(this._delegate.titleFor(item).toUpperCase().startsWith(letter)){this._list.selectItem(item);break;}}
handled=true;}
break;}
if(handled){event.consume(true);this._selectHighlightedItem();}}
setWidth(width){this._width=width;this._updateGlasspaneSize();}
setRowHeight(rowHeight){this._rowHeight=rowHeight;}
_itemsReplaced(event){const removed=(event.data.removed);if(removed.indexOf(this._selectedItem)!==-1){this._selectedItem=null;this._selectHighlightedItem();}
this._updateGlasspaneSize();}
selectItem(item){this._selectedItem=item;if(this._selectedItem)
this._titleElement.textContent=this._delegate.titleFor(this._selectedItem);else
this._titleElement.textContent='';this._delegate.itemSelected(this._selectedItem);}
createElementForItem(item){const element=createElementWithClass('div','item');element.addEventListener('mousemove',e=>{if((e.movementX||e.movementY)&&this._delegate.isItemSelectable(item))
this._list.selectItem(item,false,true);});element.classList.toggle('disabled',!this._delegate.isItemSelectable(item));element.classList.toggle('highlighted',this._list.selectedItem()===item);element.appendChild(this._delegate.createElementForItem(item));return element;}
heightForItem(item){return this._rowHeight;}
isItemSelectable(item){return this._delegate.isItemSelectable(item);}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('highlighted');if(toElement)
toElement.classList.add('highlighted');this._delegate.highlightedItemChanged(from,to,fromElement&&fromElement.firstElementChild,toElement&&toElement.firstElementChild);}
_selectHighlightedItem(){this.selectItem(this._list.selectedItem());}
refreshItem(item){this._list.refreshItem(item);}};UI.SoftDropDown.Delegate=class{titleFor(item){}
createElementForItem(item){}
isItemSelectable(item){}
itemSelected(item){}
highlightedItemChanged(from,to,fromElement,toElement){}};;UI.SplitWidget=class extends UI.Widget{constructor(isVertical,secondIsSidebar,settingName,defaultSidebarWidth,defaultSidebarHeight,constraintsInDip){super(true);this.element.classList.add('split-widget');this.registerRequiredCSS('ui/splitWidget.css');this.contentElement.classList.add('shadow-split-widget');this._mainElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-main vbox');this._mainElement.createChild('content').select='.insertion-point-main';this._sidebarElement=this.contentElement.createChild('div','shadow-split-widget-contents shadow-split-widget-sidebar vbox');this._sidebarElement.createChild('content').select='.insertion-point-sidebar';this._resizerElement=this.contentElement.createChild('div','shadow-split-widget-resizer');this._resizerElementSize=null;this._resizerWidget=new UI.SimpleResizerWidget();this._resizerWidget.setEnabled(true);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeStart,this._onResizeStart,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate,this);this._resizerWidget.addEventListener(UI.ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);this._defaultSidebarWidth=defaultSidebarWidth||200;this._defaultSidebarHeight=defaultSidebarHeight||this._defaultSidebarWidth;this._constraintsInDip=!!constraintsInDip;this._resizeStartSizeDIP=0;this._setting=settingName?Common.settings.createSetting(settingName,{}):null;this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainWidget=null;this._sidebarWidget=null;this._animationFrameHandle=0;this._animationCallback=null;this._showHideSidebarButtonTitle='';this._showHideSidebarButton=null;this._isVertical=false;this._sidebarMinimized=false;this._detaching=false;this._sidebarSizeDIP=-1;this._savedSidebarSizeDIP=this._sidebarSizeDIP;this._secondIsSidebar=false;this._shouldSaveShowMode=false;this._savedVerticalMainSize=null;this._savedHorizontalMainSize=null;this.setSecondIsSidebar(secondIsSidebar);this._innerSetVertical(isVertical);this._showMode=UI.SplitWidget.ShowMode.Both;this._savedShowMode=this._showMode;this.installResizer(this._resizerElement);}
isVertical(){return this._isVertical;}
setVertical(isVertical){if(this._isVertical===isVertical)
return;this._innerSetVertical(isVertical);if(this.isShowing())
this._updateLayout();}
_innerSetVertical(isVertical){this.contentElement.classList.toggle('vbox',!isVertical);this.contentElement.classList.toggle('hbox',isVertical);this._isVertical=isVertical;this._resizerElementSize=null;this._sidebarSizeDIP=-1;this._restoreSidebarSizeFromSettings();if(this._shouldSaveShowMode)
this._restoreAndApplyShowModeFromSettings();this._updateShowHideSidebarButton();this._resizerWidget.setVertical(!isVertical);this.invalidateConstraints();}
_updateLayout(animate){this._totalSizeCSS=0;this._totalSizeOtherDimensionCSS=0;this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._innerSetSidebarSizeDIP(this._preferredSidebarSizeDIP(),!!animate);}
setMainWidget(widget){if(this._mainWidget===widget)
return;this.suspendInvalidations();if(this._mainWidget)
this._mainWidget.detach();this._mainWidget=widget;if(widget){widget.element.classList.add('insertion-point-main');widget.element.classList.remove('insertion-point-sidebar');if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain||this._showMode===UI.SplitWidget.ShowMode.Both)
widget.show(this.element);}
this.resumeInvalidations();}
setSidebarWidget(widget){if(this._sidebarWidget===widget)
return;this.suspendInvalidations();if(this._sidebarWidget)
this._sidebarWidget.detach();this._sidebarWidget=widget;if(widget){widget.element.classList.add('insertion-point-sidebar');widget.element.classList.remove('insertion-point-main');if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar||this._showMode===UI.SplitWidget.ShowMode.Both)
widget.show(this.element);}
this.resumeInvalidations();}
mainWidget(){return this._mainWidget;}
sidebarWidget(){return this._sidebarWidget;}
childWasDetached(widget){if(this._detaching)
return;if(this._mainWidget===widget)
this._mainWidget=null;if(this._sidebarWidget===widget)
this._sidebarWidget=null;this.invalidateConstraints();}
isSidebarSecond(){return this._secondIsSidebar;}
enableShowModeSaving(){this._shouldSaveShowMode=true;this._restoreAndApplyShowModeFromSettings();}
showMode(){return this._showMode;}
setSecondIsSidebar(secondIsSidebar){this.contentElement.classList.toggle('shadow-split-widget-first-is-sidebar',!secondIsSidebar);this._secondIsSidebar=secondIsSidebar;}
sidebarSide(){if(this._showMode!==UI.SplitWidget.ShowMode.Both)
return null;return this._isVertical?(this._secondIsSidebar?'right':'left'):(this._secondIsSidebar?'bottom':'top');}
resizerElement(){return this._resizerElement;}
hideMain(animate){this._showOnly(this._sidebarWidget,this._mainWidget,this._sidebarElement,this._mainElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlySidebar);}
hideSidebar(animate){this._showOnly(this._mainWidget,this._sidebarWidget,this._mainElement,this._sidebarElement,animate);this._updateShowMode(UI.SplitWidget.ShowMode.OnlyMain);}
setSidebarMinimized(minimized){this._sidebarMinimized=minimized;this.invalidateConstraints();}
isSidebarMinimized(){return this._sidebarMinimized;}
_showOnly(sideToShow,sideToHide,shadowToShow,shadowToHide,animate){this._cancelAnimation();function callback(){if(sideToShow){if(sideToShow===this._mainWidget)
this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);else
this._sidebarWidget.show(this.element);}
if(sideToHide){this._detaching=true;sideToHide.detach();this._detaching=false;}
this._resizerElement.classList.add('hidden');shadowToShow.classList.remove('hidden');shadowToShow.classList.add('maximized');shadowToHide.classList.add('hidden');shadowToHide.classList.remove('maximized');this._removeAllLayoutProperties();this.doResize();this._showFinishedForTest();}
if(animate)
this._animate(true,callback.bind(this));else
callback.call(this);this._sidebarSizeDIP=-1;this.setResizable(false);}
_showFinishedForTest(){}
_removeAllLayoutProperties(){this._sidebarElement.style.removeProperty('flexBasis');this._mainElement.style.removeProperty('width');this._mainElement.style.removeProperty('height');this._sidebarElement.style.removeProperty('width');this._sidebarElement.style.removeProperty('height');this._resizerElement.style.removeProperty('left');this._resizerElement.style.removeProperty('right');this._resizerElement.style.removeProperty('top');this._resizerElement.style.removeProperty('bottom');this._resizerElement.style.removeProperty('margin-left');this._resizerElement.style.removeProperty('margin-right');this._resizerElement.style.removeProperty('margin-top');this._resizerElement.style.removeProperty('margin-bottom');}
showBoth(animate){if(this._showMode===UI.SplitWidget.ShowMode.Both)
animate=false;this._cancelAnimation();this._mainElement.classList.remove('maximized','hidden');this._sidebarElement.classList.remove('maximized','hidden');this._resizerElement.classList.remove('hidden');this.setResizable(true);this.suspendInvalidations();if(this._sidebarWidget)
this._sidebarWidget.show(this.element);if(this._mainWidget)
this._mainWidget.show(this.element,this._sidebarWidget?this._sidebarWidget.element:null);this.resumeInvalidations();this.setSecondIsSidebar(this._secondIsSidebar);this._sidebarSizeDIP=-1;this._updateShowMode(UI.SplitWidget.ShowMode.Both);this._updateLayout(animate);}
setResizable(resizable){this._resizerWidget.setEnabled(resizable);}
isResizable(){return this._resizerWidget.isEnabled();}
setSidebarSize(size){const sizeDIP=UI.zoomManager.cssToDIP(size);this._savedSidebarSizeDIP=sizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(sizeDIP,false,true);}
sidebarSize(){const sizeDIP=Math.max(0,this._sidebarSizeDIP);return UI.zoomManager.dipToCSS(sizeDIP);}
_totalSizeDIP(){if(!this._totalSizeCSS){this._totalSizeCSS=this._isVertical?this.contentElement.offsetWidth:this.contentElement.offsetHeight;this._totalSizeOtherDimensionCSS=this._isVertical?this.contentElement.offsetHeight:this.contentElement.offsetWidth;}
return UI.zoomManager.cssToDIP(this._totalSizeCSS);}
_updateShowMode(showMode){this._showMode=showMode;this._saveShowModeToSettings();this._updateShowHideSidebarButton();this.dispatchEventToListeners(UI.SplitWidget.Events.ShowModeChanged,showMode);this.invalidateConstraints();}
_innerSetSidebarSizeDIP(sizeDIP,animate,userAction){if(this._showMode!==UI.SplitWidget.ShowMode.Both||!this.isShowing())
return;sizeDIP=this._applyConstraints(sizeDIP,userAction);if(this._sidebarSizeDIP===sizeDIP)
return;if(!this._resizerElementSize){this._resizerElementSize=this._isVertical?this._resizerElement.offsetWidth:this._resizerElement.offsetHeight;}
this._removeAllLayoutProperties();const roundSizeCSS=Math.round(UI.zoomManager.dipToCSS(sizeDIP));const sidebarSizeValue=roundSizeCSS+'px';const mainSizeValue=(this._totalSizeCSS-roundSizeCSS)+'px';this._sidebarElement.style.flexBasis=sidebarSizeValue;if(this._isVertical){this._sidebarElement.style.width=sidebarSizeValue;this._mainElement.style.width=mainSizeValue;this._sidebarElement.style.height=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.height=this._totalSizeOtherDimensionCSS+'px';}else{this._sidebarElement.style.height=sidebarSizeValue;this._mainElement.style.height=mainSizeValue;this._sidebarElement.style.width=this._totalSizeOtherDimensionCSS+'px';this._mainElement.style.width=this._totalSizeOtherDimensionCSS+'px';}
if(this._isVertical){if(this._secondIsSidebar){this._resizerElement.style.right=sidebarSizeValue;this._resizerElement.style.marginRight=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.left=sidebarSizeValue;this._resizerElement.style.marginLeft=-this._resizerElementSize/2+'px';}}else{if(this._secondIsSidebar){this._resizerElement.style.bottom=sidebarSizeValue;this._resizerElement.style.marginBottom=-this._resizerElementSize/2+'px';}else{this._resizerElement.style.top=sidebarSizeValue;this._resizerElement.style.marginTop=-this._resizerElementSize/2+'px';}}
this._sidebarSizeDIP=sizeDIP;if(animate){this._animate(false);}else{this.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());}}
_animate(reverse,callback){const animationTime=50;this._animationCallback=callback||null;let animatedMarginPropertyName;if(this._isVertical)
animatedMarginPropertyName=this._secondIsSidebar?'margin-right':'margin-left';else
animatedMarginPropertyName=this._secondIsSidebar?'margin-bottom':'margin-top';const marginFrom=reverse?'0':'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px';const marginTo=reverse?'-'+UI.zoomManager.dipToCSS(this._sidebarSizeDIP)+'px':'0';this.contentElement.style.setProperty(animatedMarginPropertyName,marginFrom);if(!reverse){suppressUnused(this._mainElement.offsetWidth);suppressUnused(this._sidebarElement.offsetWidth);}
if(!reverse)
this._sidebarWidget.doResize();this.contentElement.style.setProperty('transition',animatedMarginPropertyName+' '+animationTime+'ms linear');const boundAnimationFrame=animationFrame.bind(this);let startTime;function animationFrame(){this._animationFrameHandle=0;if(!startTime){this.contentElement.style.setProperty(animatedMarginPropertyName,marginTo);startTime=window.performance.now();}else if(window.performance.now()<startTime+animationTime){if(this._mainWidget)
this._mainWidget.doResize();}else{this._cancelAnimation();if(this._mainWidget)
this._mainWidget.doResize();this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged,this.sidebarSize());return;}
this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);}
this._animationFrameHandle=this.contentElement.window().requestAnimationFrame(boundAnimationFrame);}
_cancelAnimation(){this.contentElement.style.removeProperty('margin-top');this.contentElement.style.removeProperty('margin-right');this.contentElement.style.removeProperty('margin-bottom');this.contentElement.style.removeProperty('margin-left');this.contentElement.style.removeProperty('transition');if(this._animationFrameHandle){this.contentElement.window().cancelAnimationFrame(this._animationFrameHandle);this._animationFrameHandle=0;}
if(this._animationCallback){this._animationCallback();this._animationCallback=null;}}
_applyConstraints(sidebarSize,userAction){const totalSize=this._totalSizeDIP();const zoomFactor=this._constraintsInDip?1:UI.zoomManager.zoomFactor();let constraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();let minSidebarSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minSidebarSize)
minSidebarSize=UI.SplitWidget.MinPadding;minSidebarSize*=zoomFactor;if(this._sidebarMinimized)
sidebarSize=minSidebarSize;let preferredSidebarSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredSidebarSize)
preferredSidebarSize=UI.SplitWidget.MinPadding;preferredSidebarSize*=zoomFactor;if(sidebarSize<preferredSidebarSize)
preferredSidebarSize=Math.max(sidebarSize,minSidebarSize);preferredSidebarSize+=zoomFactor;constraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();let minMainSize=this.isVertical()?constraints.minimum.width:constraints.minimum.height;if(!minMainSize)
minMainSize=UI.SplitWidget.MinPadding;minMainSize*=zoomFactor;let preferredMainSize=this.isVertical()?constraints.preferred.width:constraints.preferred.height;if(!preferredMainSize)
preferredMainSize=UI.SplitWidget.MinPadding;preferredMainSize*=zoomFactor;const savedMainSize=this.isVertical()?this._savedVerticalMainSize:this._savedHorizontalMainSize;if(savedMainSize!==null)
preferredMainSize=Math.min(preferredMainSize,savedMainSize*zoomFactor);if(userAction)
preferredMainSize=minMainSize;const totalPreferred=preferredMainSize+preferredSidebarSize;if(totalPreferred<=totalSize)
return Number.constrain(sidebarSize,preferredSidebarSize,totalSize-preferredMainSize);if(minMainSize+minSidebarSize<=totalSize){const delta=totalPreferred-totalSize;const sidebarDelta=delta*preferredSidebarSize/totalPreferred;sidebarSize=preferredSidebarSize-sidebarDelta;return Number.constrain(sidebarSize,minSidebarSize,totalSize-minMainSize);}
return Math.max(0,totalSize-minMainSize);}
wasShown(){this._forceUpdateLayout();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);}
willHide(){UI.zoomManager.removeEventListener(UI.ZoomManager.Events.ZoomChanged,this._onZoomChanged,this);}
onResize(){this._updateLayout();}
onLayout(){this._updateLayout();}
calculateConstraints(){if(this._showMode===UI.SplitWidget.ShowMode.OnlyMain)
return this._mainWidget?this._mainWidget.constraints():new UI.Constraints();if(this._showMode===UI.SplitWidget.ShowMode.OnlySidebar)
return this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();let mainConstraints=this._mainWidget?this._mainWidget.constraints():new UI.Constraints();let sidebarConstraints=this._sidebarWidget?this._sidebarWidget.constraints():new UI.Constraints();const min=UI.SplitWidget.MinPadding;if(this._isVertical){mainConstraints=mainConstraints.widthToMax(min).addWidth(1);sidebarConstraints=sidebarConstraints.widthToMax(min);return mainConstraints.addWidth(sidebarConstraints).heightToMax(sidebarConstraints);}else{mainConstraints=mainConstraints.heightToMax(min).addHeight(1);sidebarConstraints=sidebarConstraints.heightToMax(min);return mainConstraints.widthToMax(sidebarConstraints).addHeight(sidebarConstraints);}}
_onResizeStart(event){this._resizeStartSizeDIP=this._sidebarSizeDIP;}
_onResizeUpdate(event){const offset=event.data.currentPosition-event.data.startPosition;const offsetDIP=UI.zoomManager.cssToDIP(offset);const newSizeDIP=this._secondIsSidebar?this._resizeStartSizeDIP-offsetDIP:this._resizeStartSizeDIP+offsetDIP;const constrainedSizeDIP=this._applyConstraints(newSizeDIP,true);this._savedSidebarSizeDIP=constrainedSizeDIP;this._saveSetting();this._innerSetSidebarSizeDIP(constrainedSizeDIP,false,true);if(this.isVertical())
this._savedVerticalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;else
this._savedHorizontalMainSize=this._totalSizeDIP()-this._sidebarSizeDIP;}
_onResizeEnd(event){this._resizeStartSizeDIP=0;}
hideDefaultResizer(noSplitter){this.uninstallResizer(this._resizerElement);this._sidebarElement.classList.toggle('no-default-splitter',noSplitter);}
installResizer(resizerElement){this._resizerWidget.addElement(resizerElement);}
uninstallResizer(resizerElement){this._resizerWidget.removeElement(resizerElement);}
hasCustomResizer(){const elements=this._resizerWidget.elements();return elements.length>1||(elements.length===1&&elements[0]!==this._resizerElement);}
toggleResizer(resizer,on){if(on)
this.installResizer(resizer);else
this.uninstallResizer(resizer);}
_settingForOrientation(){const state=this._setting?this._setting.get():{};return this._isVertical?state.vertical:state.horizontal;}
_preferredSidebarSizeDIP(){let size=this._savedSidebarSizeDIP;if(!size){size=this._isVertical?this._defaultSidebarWidth:this._defaultSidebarHeight;if(0<size&&size<1)
size*=this._totalSizeDIP();}
return size;}
_restoreSidebarSizeFromSettings(){const settingForOrientation=this._settingForOrientation();this._savedSidebarSizeDIP=settingForOrientation?settingForOrientation.size:0;}
_restoreAndApplyShowModeFromSettings(){const orientationState=this._settingForOrientation();this._savedShowMode=orientationState&&orientationState.showMode?orientationState.showMode:this._showMode;this._showMode=this._savedShowMode;switch(this._savedShowMode){case UI.SplitWidget.ShowMode.Both:this.showBoth();break;case UI.SplitWidget.ShowMode.OnlyMain:this.hideSidebar();break;case UI.SplitWidget.ShowMode.OnlySidebar:this.hideMain();break;}}
_saveShowModeToSettings(){this._savedShowMode=this._showMode;this._saveSetting();}
_saveSetting(){if(!this._setting)
return;const state=this._setting.get();const orientationState=(this._isVertical?state.vertical:state.horizontal)||{};orientationState.size=this._savedSidebarSizeDIP;if(this._shouldSaveShowMode)
orientationState.showMode=this._savedShowMode;if(this._isVertical)
state.vertical=orientationState;else
state.horizontal=orientationState;this._setting.set(state);}
_forceUpdateLayout(){this._sidebarSizeDIP=-1;this._updateLayout();}
_onZoomChanged(event){this._forceUpdateLayout();}
createShowHideSidebarButton(title){this._showHideSidebarButtonTitle=Common.UIString(title);this._showHideSidebarButton=new UI.ToolbarButton('','');this._showHideSidebarButton.addEventListener(UI.ToolbarButton.Events.Click,buttonClicked,this);this._updateShowHideSidebarButton();function buttonClicked(event){if(this._showMode!==UI.SplitWidget.ShowMode.Both)
this.showBoth(true);else
this.hideSidebar(true);}
return this._showHideSidebarButton;}
_updateShowHideSidebarButton(){if(!this._showHideSidebarButton)
return;const sidebarHidden=this._showMode===UI.SplitWidget.ShowMode.OnlyMain;let glyph='';if(sidebarHidden){glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-show-right-sidebar':'largeicon-show-left-sidebar'):(this.isSidebarSecond()?'largeicon-show-bottom-sidebar':'largeicon-show-top-sidebar');}else{glyph=this.isVertical()?(this.isSidebarSecond()?'largeicon-hide-right-sidebar':'largeicon-hide-left-sidebar'):(this.isSidebarSecond()?'largeicon-hide-bottom-sidebar':'largeicon-hide-top-sidebar');}
this._showHideSidebarButton.setGlyph(glyph);this._showHideSidebarButton.setTitle(sidebarHidden?Common.UIString('Show %s',this._showHideSidebarButtonTitle):Common.UIString('Hide %s',this._showHideSidebarButtonTitle));}};UI.SplitWidget.SettingForOrientation;UI.SplitWidget.ShowMode={Both:'Both',OnlyMain:'OnlyMain',OnlySidebar:'OnlySidebar'};UI.SplitWidget.Events={SidebarSizeChanged:Symbol('SidebarSizeChanged'),ShowModeChanged:Symbol('ShowModeChanged')};UI.SplitWidget.MinPadding=20;;UI.TargetCrashedScreen=class extends UI.VBox{constructor(hideCallback){super(true);this.registerRequiredCSS('ui/targetCrashedScreen.css');this.contentElement.createChild('div','message').textContent=Common.UIString('DevTools was disconnected from the page.');this.contentElement.createChild('div','message').textContent=Common.UIString('Once page is reloaded, DevTools will automatically reconnect.');this._hideCallback=hideCallback;}
willHide(){this._hideCallback.call(null);}};;UI.TextPrompt=class extends Common.Object{constructor(){super();this._proxyElement;this._proxyElementDisplay='inline-block';this._autocompletionTimeout=UI.TextPrompt.DefaultAutocompletionTimeout;this._title='';this._queryRange=null;this._previousText='';this._currentSuggestion='';this._completionRequestId=0;this._ghostTextElement=createElementWithClass('span','auto-complete-text');this._ghostTextElement.setAttribute('contenteditable','false');UI.ARIAUtils.markAsHidden(this._ghostTextElement);}
initialize(completions,stopCharacters){this._loadCompletions=completions;this._completionStopCharacters=stopCharacters||' =:[({;,!+-*/&|^<>.';}
setAutocompletionTimeout(timeout){this._autocompletionTimeout=timeout;}
renderAsBlock(){this._proxyElementDisplay='block';}
attach(element){return this._attachInternal(element);}
attachAndStartEditing(element,blurListener){const proxyElement=this._attachInternal(element);this._startEditing(blurListener);return proxyElement;}
_attachInternal(element){if(this._proxyElement)
throw'Cannot attach an attached TextPrompt';this._element=element;this._boundOnKeyDown=this.onKeyDown.bind(this);this._boundOnInput=this.onInput.bind(this);this._boundOnMouseWheel=this.onMouseWheel.bind(this);this._boundClearAutocomplete=this.clearAutocomplete.bind(this);this._proxyElement=element.ownerDocument.createElement('span');const shadowRoot=UI.createShadowRootWithCoreStyles(this._proxyElement,'ui/textPrompt.css');this._contentElement=shadowRoot.createChild('div','text-prompt-root');this._contentElement.createChild('content');this._proxyElement.style.display=this._proxyElementDisplay;element.parentElement.insertBefore(this._proxyElement,element);this._proxyElement.appendChild(element);this._element.classList.add('text-prompt');UI.ARIAUtils.markAsTextBox(this._element);this._element.setAttribute('contenteditable','plaintext-only');this._element.addEventListener('keydown',this._boundOnKeyDown,false);this._element.addEventListener('input',this._boundOnInput,false);this._element.addEventListener('mousewheel',this._boundOnMouseWheel,false);this._element.addEventListener('selectstart',this._boundClearAutocomplete,false);this._element.addEventListener('blur',this._boundClearAutocomplete,false);this._suggestBox=new UI.SuggestBox(this,20,true);if(this._title)
this._proxyElement.title=this._title;return this._proxyElement;}
detach(){this._removeFromElement();this._focusRestorer.restore();this._proxyElement.parentElement.insertBefore(this._element,this._proxyElement);this._proxyElement.remove();delete this._proxyElement;this._element.classList.remove('text-prompt');this._element.removeAttribute('contenteditable');this._element.removeAttribute('role');}
textWithCurrentSuggestion(){const text=this.text();if(!this._queryRange)
return text;return text.substring(0,this._queryRange.startColumn)+this._currentSuggestion+
text.substring(this._queryRange.endColumn);}
text(){let text=this._element.textContent;if(this._ghostTextElement.parentNode){const addition=this._ghostTextElement.textContent;text=text.substring(0,text.length-addition.length);}
return text;}
setText(text){this.clearAutocomplete();this._element.textContent=text;this._previousText=this.text();if(this._element.hasFocus()){this.moveCaretToEndOfPrompt();this._element.scrollIntoView();}}
focus(){this._element.focus();}
title(){return this._title;}
setTitle(title){this._title=title;if(this._proxyElement)
this._proxyElement.title=title;}
setPlaceholder(placeholder){if(placeholder){this._element.setAttribute('data-placeholder',placeholder);UI.ARIAUtils.setPlaceholder(this._element,placeholder);}else{this._element.removeAttribute('data-placeholder');UI.ARIAUtils.setPlaceholder(this._element,null);}}
setEnabled(enabled){if(enabled)
this._element.setAttribute('contenteditable','plaintext-only');else
this._element.removeAttribute('contenteditable');this._element.classList.toggle('disabled',!enabled);}
_removeFromElement(){this.clearAutocomplete();this._element.removeEventListener('keydown',this._boundOnKeyDown,false);this._element.removeEventListener('input',this._boundOnInput,false);this._element.removeEventListener('selectstart',this._boundClearAutocomplete,false);this._element.removeEventListener('blur',this._boundClearAutocomplete,false);if(this._isEditing)
this._stopEditing();if(this._suggestBox)
this._suggestBox.hide();}
_startEditing(blurListener){this._isEditing=true;this._contentElement.classList.add('text-prompt-editing');if(blurListener){this._blurListener=blurListener;this._element.addEventListener('blur',this._blurListener,false);}
this._oldTabIndex=this._element.tabIndex;if(this._element.tabIndex<0)
this._element.tabIndex=0;this._focusRestorer=new UI.ElementFocusRestorer(this._element);if(!this.text())
this.autoCompleteSoon();}
_stopEditing(){this._element.tabIndex=this._oldTabIndex;if(this._blurListener)
this._element.removeEventListener('blur',this._blurListener,false);this._contentElement.classList.remove('text-prompt-editing');delete this._isEditing;}
onMouseWheel(event){}
onKeyDown(event){let handled=false;if(this._isSuggestBoxVisible()&&this._suggestBox.keyPressed(event)){event.consume(true);return;}
switch(event.key){case'Tab':handled=this.tabKeyPressed(event);break;case'ArrowLeft':case'ArrowUp':case'PageUp':case'Home':this.clearAutocomplete();break;case'PageDown':case'ArrowRight':case'ArrowDown':case'End':if(this._isCaretAtEndOfPrompt())
handled=this.acceptAutoComplete();else
this.clearAutocomplete();break;case'Escape':if(this._isSuggestBoxVisible()){this.clearAutocomplete();handled=true;}
break;case' ':if(event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey){this.autoCompleteSoon(true);handled=true;}
break;}
if(isEnterKey(event))
event.preventDefault();if(handled)
event.consume(true);}
onInput(event){const text=this.text();const hasCommonPrefix=text.startsWith(this._previousText)||this._previousText.startsWith(text);if(this._queryRange&&hasCommonPrefix)
this._queryRange.endColumn+=text.length-this._previousText.length;this._refreshGhostText();this._previousText=text;this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);this.autoCompleteSoon();}
acceptAutoComplete(){let result=false;if(this._isSuggestBoxVisible())
result=this._suggestBox.acceptSuggestion();if(!result)
result=this._acceptSuggestionInternal();return result;}
clearAutocomplete(){const beforeText=this.textWithCurrentSuggestion();if(this._isSuggestBoxVisible())
this._suggestBox.hide();this._clearAutocompleteTimeout();this._queryRange=null;this._refreshGhostText();if(beforeText!==this.textWithCurrentSuggestion())
this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);}
_refreshGhostText(){if(this._queryRange&&this._currentSuggestion&&this._isCaretAtEndOfPrompt()&&this._currentSuggestion.startsWith(this.text().substring(this._queryRange.startColumn))){this._ghostTextElement.textContent=this._currentSuggestion.substring(this._queryRange.endColumn-this._queryRange.startColumn);this._element.appendChild(this._ghostTextElement);}else{this._ghostTextElement.remove();}}
_clearAutocompleteTimeout(){if(this._completeTimeout){clearTimeout(this._completeTimeout);delete this._completeTimeout;}
this._completionRequestId++;}
autoCompleteSoon(force){const immediately=this._isSuggestBoxVisible()||force;if(!this._completeTimeout){this._completeTimeout=setTimeout(this.complete.bind(this,force),immediately?0:this._autocompletionTimeout);}}
async complete(force){this._clearAutocompleteTimeout();const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange)
return;let shouldExit;if(!force&&!this._isCaretAtEndOfPrompt()&&!this._isSuggestBoxVisible())
shouldExit=true;else if(!selection.isCollapsed)
shouldExit=true;if(shouldExit){this.clearAutocomplete();return;}
const wordQueryRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,this._completionStopCharacters,this._element,'backward');const expressionRange=wordQueryRange.cloneRange();expressionRange.collapse(true);expressionRange.setStartBefore(this._proxyElement);const completionRequestId=++this._completionRequestId;const completions=await this._loadCompletions(expressionRange.toString(),wordQueryRange.toString(),!!force);this._completionsReady(completionRequestId,selection,wordQueryRange,!!force,completions);}
disableDefaultSuggestionForEmptyInput(){this._disableDefaultSuggestionForEmptyInput=true;}
_boxForAnchorAtStart(selection,textRange){const rangeCopy=selection.getRangeAt(0).cloneRange();const anchorElement=createElement('span');anchorElement.textContent='\u200B';textRange.insertNode(anchorElement);const box=anchorElement.boxInWindow(window);anchorElement.remove();selection.removeAllRanges();selection.addRange(rangeCopy);return box;}
_createRange(){return document.createRange();}
additionalCompletions(query){return[];}
_completionsReady(completionRequestId,selection,originalWordQueryRange,force,completions){if(this._completionRequestId!==completionRequestId)
return;const query=originalWordQueryRange.toString();const store=new Set();completions=completions.filter(item=>!store.has(item.text)&&!!store.add(item.text));if(query||force){if(query)
completions=completions.concat(this.additionalCompletions(query));else
completions=this.additionalCompletions(query).concat(completions);}
if(!completions.length){this.clearAutocomplete();return;}
const selectionRange=selection.getRangeAt(0);const fullWordRange=this._createRange();fullWordRange.setStart(originalWordQueryRange.startContainer,originalWordQueryRange.startOffset);fullWordRange.setEnd(selectionRange.endContainer,selectionRange.endOffset);if(query+selectionRange.toString()!==fullWordRange.toString())
return;const beforeRange=this._createRange();beforeRange.setStart(this._element,0);beforeRange.setEnd(fullWordRange.startContainer,fullWordRange.startOffset);this._queryRange=new TextUtils.TextRange(0,beforeRange.toString().length,0,beforeRange.toString().length+fullWordRange.toString().length);const shouldSelect=!this._disableDefaultSuggestionForEmptyInput||!!this.text();if(this._suggestBox){this._suggestBox.updateSuggestions(this._boxForAnchorAtStart(selection,fullWordRange),completions,shouldSelect,!this._isCaretAtEndOfPrompt(),this.text());}}
applySuggestion(suggestion,isIntermediateSuggestion){this._currentSuggestion=suggestion;this._refreshGhostText();if(isIntermediateSuggestion)
this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);}
acceptSuggestion(){this._acceptSuggestionInternal();}
_acceptSuggestionInternal(){if(!this._queryRange)
return false;this._element.textContent=this.textWithCurrentSuggestion();this.setDOMSelection(this._queryRange.startColumn+this._currentSuggestion.length,this._queryRange.startColumn+this._currentSuggestion.length);this.clearAutocomplete();this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged);return true;}
setDOMSelection(startColumn,endColumn){this._element.normalize();const node=this._element.childNodes[0];if(!node||node===this._ghostTextElement)
return;const range=this._createRange();range.setStart(node,startColumn);range.setEnd(node,endColumn);const selection=this._element.getComponentSelection();selection.removeAllRanges();selection.addRange(range);}
_isSuggestBoxVisible(){return this._suggestBox&&this._suggestBox.visible();}
isCaretInsidePrompt(){const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed)
return false;return selectionRange.startContainer.isSelfOrDescendant(this._element);}
_isCaretAtEndOfPrompt(){const selection=this._element.getComponentSelection();const selectionRange=selection&&selection.rangeCount?selection.getRangeAt(0):null;if(!selectionRange||!selection.isCollapsed)
return false;let node=selectionRange.startContainer;if(!node.isSelfOrDescendant(this._element))
return false;if(this._ghostTextElement.isAncestor(node))
return true;if(node.nodeType===Node.TEXT_NODE&&selectionRange.startOffset<node.nodeValue.length)
return false;let foundNextText=false;while(node){if(node.nodeType===Node.TEXT_NODE&&node.nodeValue.length){if(foundNextText&&!this._ghostTextElement.isAncestor(node))
return false;foundNextText=true;}
node=node.traverseNextNode(this._element);}
return true;}
moveCaretToEndOfPrompt(){const selection=this._element.getComponentSelection();const selectionRange=this._createRange();let container=this._element;while(container.childNodes.length)
container=container.lastChild;const offset=container.nodeType===Node.TEXT_NODE?container.textContent.length:0;selectionRange.setStart(container,offset);selectionRange.setEnd(container,offset);selection.removeAllRanges();selection.addRange(selectionRange);}
tabKeyPressed(event){return this.acceptAutoComplete();}
proxyElementForTests(){return this._proxyElement||null;}};UI.TextPrompt.DefaultAutocompletionTimeout=250;UI.TextPrompt.Events={TextChanged:Symbol('TextChanged')};;UI.ThrottledWidget=class extends UI.VBox{constructor(isWebComponent,timeout){super(isWebComponent);this._updateThrottler=new Common.Throttler(timeout===undefined?100:timeout);this._updateWhenVisible=false;}
doUpdate(){return Promise.resolve();}
update(){this._updateWhenVisible=!this.isShowing();if(this._updateWhenVisible)
return;this._updateThrottler.schedule(innerUpdate.bind(this));function innerUpdate(){if(this.isShowing())
return this.doUpdate();this._updateWhenVisible=true;return Promise.resolve();}}
wasShown(){super.wasShown();if(this._updateWhenVisible)
this.update();}};;UI.Toolbar=class{constructor(className,parentElement){this._items=[];this._reverse=false;this.element=parentElement?parentElement.createChild('div'):createElement('div');this.element.className=className;this.element.classList.add('toolbar');this._enabled=true;this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/toolbar.css');this._contentElement=this._shadowRoot.createChild('div','toolbar-shadow');this._insertionPoint=this._contentElement.createChild('content');}
static createActionButton(action,toggledOptions,untoggledOptions){const button=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());button.setToggleWithRedColor(action.toggleWithRedColor());button.addEventListener(UI.ToolbarButton.Events.Click,action.execute,action);action.addEventListener(UI.Action.Events.Enabled,enabledChanged);action.addEventListener(UI.Action.Events.Toggled,toggled);let longClickController=null;let longClickButtons=null;let longClickGlyph=null;toggled();button.setEnabled(action.enabled());return button;function enabledChanged(event){button.setEnabled((event.data));}
function toggled(){button.setToggled(action.toggled());if(action.title())
UI.Tooltip.install(button.element,action.title(),action.id());updateOptions();}
function updateOptions(){const buttons=action.toggled()?(toggledOptions||null):(untoggledOptions||null);if(buttons&&buttons.length){if(!longClickController){longClickController=new UI.LongClickController(button.element,showOptions);longClickGlyph=UI.Icon.create('largeicon-longclick-triangle','long-click-glyph');button.element.appendChild(longClickGlyph);longClickButtons=buttons;}}else{if(longClickController){longClickController.dispose();longClickController=null;longClickGlyph.remove();longClickGlyph=null;longClickButtons=null;}}}
function showOptions(){let buttons=longClickButtons.slice();const mainButtonClone=new UI.ToolbarToggle(action.title(),action.icon(),action.toggledIcon());mainButtonClone.addEventListener(UI.ToolbarButton.Events.Click,clicked);function clicked(event){button._clicked((event.data));}
mainButtonClone.setToggled(action.toggled());buttons.push(mainButtonClone);const document=button.element.ownerDocument;document.documentElement.addEventListener('mouseup',mouseUp,false);const optionsGlassPane=new UI.GlassPane();optionsGlassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);optionsGlassPane.show(document);const optionsBar=new UI.Toolbar('fill',optionsGlassPane.contentElement);optionsBar._contentElement.classList.add('floating');const buttonHeight=26;const hostButtonPosition=button.element.boxInWindow().relativeToElement(UI.GlassPane.container(document));const topNotBottom=hostButtonPosition.y+buttonHeight*buttons.length<document.documentElement.offsetHeight;if(topNotBottom)
buttons=buttons.reverse();optionsBar.element.style.height=(buttonHeight*buttons.length)+'px';if(topNotBottom)
optionsBar.element.style.top=(hostButtonPosition.y-5)+'px';else
optionsBar.element.style.top=(hostButtonPosition.y-(buttonHeight*(buttons.length-1))-6)+'px';optionsBar.element.style.left=(hostButtonPosition.x-5)+'px';for(let i=0;i<buttons.length;++i){buttons[i].element.addEventListener('mousemove',mouseOver,false);buttons[i].element.addEventListener('mouseout',mouseOut,false);optionsBar.appendToolbarItem(buttons[i]);}
const hostButtonIndex=topNotBottom?0:buttons.length-1;buttons[hostButtonIndex].element.classList.add('emulate-active');function mouseOver(e){if(e.which!==1)
return;const buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.add('emulate-active');}
function mouseOut(e){if(e.which!==1)
return;const buttonElement=e.target.enclosingNodeOrSelfWithClass('toolbar-item');buttonElement.classList.remove('emulate-active');}
function mouseUp(e){if(e.which!==1)
return;optionsGlassPane.hide();document.documentElement.removeEventListener('mouseup',mouseUp,false);for(let i=0;i<buttons.length;++i){if(buttons[i].element.classList.contains('emulate-active')){buttons[i].element.classList.remove('emulate-active');buttons[i]._clicked(e);break;}}}}}
static createActionButtonForId(actionId){const action=UI.actionRegistry.action(actionId);return UI.Toolbar.createActionButton((action));}
gripElementForResize(){return this._contentElement;}
makeWrappable(reverse,growVertically){this._contentElement.classList.add('wrappable');this._reverse=!!reverse;if(reverse)
this._contentElement.classList.add('wrappable-reverse');if(growVertically)
this._contentElement.classList.add('toolbar-grow-vertical');}
makeVertical(){this._contentElement.classList.add('vertical');}
makeBlueOnHover(){this._contentElement.classList.add('toolbar-blue-on-hover');}
makeToggledGray(){this._contentElement.classList.add('toolbar-toggled-gray');}
renderAsLinks(){this._contentElement.classList.add('toolbar-render-as-links');}
setEnabled(enabled){this._enabled=enabled;for(const item of this._items)
item._applyEnabledState(this._enabled&&item._enabled);}
appendToolbarItem(item){this._items.push(item);item._toolbar=this;if(!this._enabled)
item._applyEnabledState(false);if(this._reverse)
this._contentElement.insertBefore(item.element,this._insertionPoint.nextSibling);else
this._contentElement.insertBefore(item.element,this._insertionPoint);this._hideSeparatorDupes();}
appendSeparator(){this.appendToolbarItem(new UI.ToolbarSeparator());}
appendSpacer(){this.appendToolbarItem(new UI.ToolbarSeparator(true));}
appendText(text){this.appendToolbarItem(new UI.ToolbarText(text));}
removeToolbarItems(){for(const item of this._items)
delete item._toolbar;this._items=[];this._contentElement.removeChildren();this._insertionPoint=this._contentElement.createChild('content');}
setColor(color){const style=createElement('style');style.textContent='.toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);}
setToggledColor(color){const style=createElement('style');style.textContent='.toolbar-button.toolbar-state-on .toolbar-glyph { background-color: '+color+' !important }';this._shadowRoot.appendChild(style);}
_hideSeparatorDupes(){if(!this._items.length)
return;let previousIsSeparator=false;let lastSeparator;let nonSeparatorVisible=false;for(let i=0;i<this._items.length;++i){if(this._items[i]instanceof UI.ToolbarSeparator){this._items[i].setVisible(!previousIsSeparator);previousIsSeparator=true;lastSeparator=this._items[i];continue;}
if(this._items[i].visible()){previousIsSeparator=false;lastSeparator=null;nonSeparatorVisible=true;}}
if(lastSeparator&&lastSeparator!==this._items.peekLast())
lastSeparator.setVisible(false);this.element.classList.toggle('hidden',!!lastSeparator&&lastSeparator.visible()&&!nonSeparatorVisible);}
appendLocationItems(location){const extensions=self.runtime.extensions(UI.ToolbarItem.Provider);const promises=[];for(let i=0;i<extensions.length;++i){if(extensions[i].descriptor()['location']===location)
promises.push(resolveItem(extensions[i]));}
Promise.all(promises).then(appendItemsInOrder.bind(this));function resolveItem(extension){const descriptor=extension.descriptor();if(descriptor['separator'])
return Promise.resolve((new UI.ToolbarSeparator()));if(descriptor['actionId']){return Promise.resolve((UI.Toolbar.createActionButtonForId(descriptor['actionId'])));}
return extension.instance().then(fetchItemFromProvider);function fetchItemFromProvider(provider){return(provider).item();}}
function appendItemsInOrder(items){for(let i=0;i<items.length;++i){const item=items[i];if(item)
this.appendToolbarItem(item);}}}};UI.ToolbarItem=class extends Common.Object{constructor(element){super();this.element=element;this.element.classList.add('toolbar-item');this._visible=true;this._enabled=true;}
setTitle(title){if(this._title===title)
return;this._title=title;UI.ARIAUtils.setAccessibleName(this.element,title);UI.Tooltip.install(this.element,title);}
setEnabled(value){if(this._enabled===value)
return;this._enabled=value;this._applyEnabledState(this._enabled&&(!this._toolbar||this._toolbar._enabled));}
_applyEnabledState(enabled){this.element.disabled=!enabled;}
visible(){return this._visible;}
setVisible(x){if(this._visible===x)
return;this.element.classList.toggle('hidden',!x);this._visible=x;if(this._toolbar&&!(this instanceof UI.ToolbarSeparator))
this._toolbar._hideSeparatorDupes();}
setRightAligned(alignRight){this.element.classList.toggle('toolbar-item-right-aligned',alignRight);}};UI.ToolbarText=class extends UI.ToolbarItem{constructor(text){super(createElementWithClass('div','toolbar-text'));this.element.classList.add('toolbar-text');this.setText(text||'');}
text(){return this.element.textContent;}
setText(text){this.element.textContent=text;}};UI.ToolbarButton=class extends UI.ToolbarItem{constructor(title,glyph,text){super(createElementWithClass('button','toolbar-button'));this.element.addEventListener('click',this._clicked.bind(this),false);this.element.addEventListener('mousedown',this._mouseDown.bind(this),false);this.element.addEventListener('mouseup',this._mouseUp.bind(this),false);this._glyphElement=UI.Icon.create('','toolbar-glyph hidden');this.element.appendChild(this._glyphElement);this._textElement=this.element.createChild('div','toolbar-text hidden');this.setTitle(title);if(glyph)
this.setGlyph(glyph);this.setText(text||'');this._title='';}
setText(text){if(this._text===text)
return;this._textElement.textContent=text;this._textElement.classList.toggle('hidden',!text);this._text=text;}
setGlyph(glyph){if(this._glyph===glyph)
return;this._glyphElement.setIconType(glyph);this._glyphElement.classList.toggle('hidden',!glyph);this.element.classList.toggle('toolbar-has-glyph',!!glyph);this._glyph=glyph;}
setBackgroundImage(iconURL){this.element.style.backgroundImage='url('+iconURL+')';}
setDarkText(){this.element.classList.add('dark-text');}
turnIntoSelect(width){this.element.classList.add('toolbar-has-dropdown');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(width)
this.element.style.width=width+'px';}
_clicked(event){if(!this._enabled)
return;this.dispatchEventToListeners(UI.ToolbarButton.Events.Click,event);event.consume();}
_mouseDown(event){if(!this._enabled)
return;this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseDown,event);}
_mouseUp(event){if(!this._enabled)
return;this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseUp,event);}};UI.ToolbarButton.Events={Click:Symbol('Click'),MouseDown:Symbol('MouseDown'),MouseUp:Symbol('MouseUp')};UI.ToolbarInput=class extends UI.ToolbarItem{constructor(placeholder,growFactor,shrinkFactor,tooltip,completions){super(createElementWithClass('div','toolbar-input'));const internalPromptElement=this.element.createChild('div','toolbar-input-prompt');internalPromptElement.addEventListener('focus',()=>this.element.classList.add('focused'));internalPromptElement.addEventListener('blur',()=>this.element.classList.remove('focused'));this._prompt=new UI.TextPrompt();this._proxyElement=this._prompt.attach(internalPromptElement);this._proxyElement.classList.add('toolbar-prompt-proxy');this._proxyElement.addEventListener('keydown',event=>this._onKeydownCallback(event));this._prompt.initialize(completions||(()=>Promise.resolve([])),' ');if(tooltip)
this._prompt.setTitle(tooltip);this._prompt.setPlaceholder(placeholder);this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged,this._onChangeCallback.bind(this));if(growFactor)
this.element.style.flexGrow=growFactor;if(shrinkFactor)
this.element.style.flexShrink=shrinkFactor;const clearButton=this.element.createChild('div','toolbar-input-clear-button');clearButton.appendChild(UI.Icon.create('mediumicon-gray-cross-hover','search-cancel-button'));clearButton.addEventListener('click',()=>this._internalSetValue('',true));this._updateEmptyStyles();}
_applyEnabledState(enabled){this._prompt.setEnabled(enabled);}
setValue(value){this._internalSetValue(value,false);}
_internalSetValue(value,notify){this._prompt.setText(value);if(notify)
this._onChangeCallback();this._updateEmptyStyles();}
value(){return this._prompt.textWithCurrentSuggestion();}
_onKeydownCallback(event){if(!isEscKey(event)||!this._prompt.text())
return;this._internalSetValue('',true);event.consume(true);}
_onChangeCallback(){this._updateEmptyStyles();this.dispatchEventToListeners(UI.ToolbarInput.Event.TextChanged,this._prompt.text());}
_updateEmptyStyles(){this.element.classList.toggle('toolbar-input-empty',!this._prompt.text());}};UI.ToolbarInput.Event={TextChanged:Symbol('TextChanged')};UI.ToolbarToggle=class extends UI.ToolbarButton{constructor(title,glyph,toggledGlyph){super(title,glyph,'');this._toggled=false;this._untoggledGlyph=glyph;this._toggledGlyph=toggledGlyph;this.element.classList.add('toolbar-state-off');UI.ARIAUtils.setPressed(this.element,false);}
toggled(){return this._toggled;}
setToggled(toggled){if(this._toggled===toggled)
return;this._toggled=toggled;this.element.classList.toggle('toolbar-state-on',toggled);this.element.classList.toggle('toolbar-state-off',!toggled);UI.ARIAUtils.setPressed(this.element,toggled);if(this._toggledGlyph&&this._untoggledGlyph)
this.setGlyph(toggled?this._toggledGlyph:this._untoggledGlyph);}
setDefaultWithRedColor(withRedColor){this.element.classList.toggle('toolbar-default-with-red-color',withRedColor);}
setToggleWithRedColor(toggleWithRedColor){this.element.classList.toggle('toolbar-toggle-with-red-color',toggleWithRedColor);}};UI.ToolbarMenuButton=class extends UI.ToolbarButton{constructor(contextMenuHandler,useSoftMenu){super('','largeicon-menu');this._contextMenuHandler=contextMenuHandler;this._useSoftMenu=!!useSoftMenu;}
_mouseDown(event){if(event.buttons!==1){super._mouseDown(event);return;}
if(!this._triggerTimeout)
this._triggerTimeout=setTimeout(this._trigger.bind(this,event),200);}
_trigger(event){delete this._triggerTimeout;if(this._lastTriggerTime&&Date.now()-this._lastTriggerTime<300)
return;const contextMenu=new UI.ContextMenu(event,this._useSoftMenu,this.element.totalOffsetLeft(),this.element.totalOffsetTop()+this.element.offsetHeight);this._contextMenuHandler(contextMenu);contextMenu.show();this._lastTriggerTime=Date.now();}
_clicked(event){if(this._triggerTimeout)
clearTimeout(this._triggerTimeout);this._trigger(event);}};UI.ToolbarSettingToggle=class extends UI.ToolbarToggle{constructor(setting,glyph,title,toggledTitle){super(title,glyph);this._defaultTitle=title;this._toggledTitle=toggledTitle||title;this._setting=setting;this._settingChanged();this._setting.addChangeListener(this._settingChanged,this);}
_settingChanged(){const toggled=this._setting.get();this.setToggled(toggled);this.setTitle(toggled?this._toggledTitle:this._defaultTitle);}
_clicked(event){this._setting.set(!this.toggled());super._clicked(event);}};UI.ToolbarSeparator=class extends UI.ToolbarItem{constructor(spacer){super(createElementWithClass('div',spacer?'toolbar-spacer':'toolbar-divider'));}};UI.ToolbarItem.Provider=function(){};UI.ToolbarItem.Provider.prototype={item(){}};UI.ToolbarItem.ItemsProvider=function(){};UI.ToolbarItem.ItemsProvider.prototype={toolbarItems(){}};UI.ToolbarComboBox=class extends UI.ToolbarItem{constructor(changeHandler,className){super(createElementWithClass('span','toolbar-select-container'));this._selectElement=this.element.createChild('select','toolbar-item');const dropdownArrowIcon=UI.Icon.create('smallicon-triangle-down','toolbar-dropdown-arrow');this.element.appendChild(dropdownArrowIcon);if(changeHandler)
this._selectElement.addEventListener('change',changeHandler,false);if(className)
this._selectElement.classList.add(className);}
selectElement(){return(this._selectElement);}
size(){return this._selectElement.childElementCount;}
options(){return Array.prototype.slice.call(this._selectElement.children,0);}
addOption(option){this._selectElement.appendChild(option);}
createOption(label,title,value){const option=this._selectElement.createChild('option');option.text=label;if(title)
option.title=title;if(typeof value!=='undefined')
option.value=value;return option;}
_applyEnabledState(enabled){super._applyEnabledState(enabled);this._selectElement.disabled=!enabled;}
removeOption(option){this._selectElement.removeChild(option);}
removeOptions(){this._selectElement.removeChildren();}
selectedOption(){if(this._selectElement.selectedIndex>=0)
return this._selectElement[this._selectElement.selectedIndex];return null;}
select(option){this._selectElement.selectedIndex=Array.prototype.indexOf.call((this._selectElement),option);}
setSelectedIndex(index){this._selectElement.selectedIndex=index;}
selectedIndex(){return this._selectElement.selectedIndex;}
setMaxWidth(width){this._selectElement.style.maxWidth=width+'px';}
setMinWidth(width){this._selectElement.style.minWidth=width+'px';}};UI.ToolbarSettingComboBox=class extends UI.ToolbarComboBox{constructor(options,setting,optGroup){super(null);this._setting=setting;this._options=options;this._selectElement.addEventListener('change',this._valueChanged.bind(this),false);if(optGroup){const optGroupElement=this._selectElement.createChild('optgroup');optGroupElement.label=optGroup;this._optionContainer=optGroupElement;}else{this._optionContainer=this._selectElement;}
this.setOptions(options);setting.addChangeListener(this._settingChanged,this);}
setOptions(options){this._options=options;this._optionContainer.removeChildren();for(let i=0;i<options.length;++i){const dataOption=options[i];const option=this.createOption(dataOption.label,dataOption.title,dataOption.value);this._optionContainer.appendChild(option);if(this._setting.get()===dataOption.value)
this.setSelectedIndex(i);}}
value(){return this._options[this.selectedIndex()].value;}
_settingChanged(){if(this._muteSettingListener)
return;const value=this._setting.get();for(let i=0;i<this._options.length;++i){if(value===this._options[i].value){this.setSelectedIndex(i);break;}}}
_valueChanged(event){const option=this._options[this.selectedIndex()];this._muteSettingListener=true;this._setting.set(option.value);this._muteSettingListener=false;}};UI.ToolbarCheckbox=class extends UI.ToolbarItem{constructor(text,tooltip,listener){super(UI.CheckboxLabel.create(text));this.element.classList.add('checkbox');this.inputElement=this.element.checkboxElement;if(tooltip)
this.element.title=tooltip;if(listener)
this.inputElement.addEventListener('click',listener,false);}
checked(){return this.inputElement.checked;}
setChecked(value){this.inputElement.checked=value;}
_applyEnabledState(enabled){super._applyEnabledState(enabled);this.inputElement.disabled=!enabled;}};UI.ToolbarSettingCheckbox=class extends UI.ToolbarCheckbox{constructor(setting,tooltip,alternateTitle){super(alternateTitle||setting.title()||'',tooltip);UI.SettingsUI.bindCheckbox(this.inputElement,setting);}};;UI.Tooltip=class{constructor(doc){this.element=doc.body.createChild('div');this._shadowRoot=UI.createShadowRootWithCoreStyles(this.element,'ui/tooltip.css');this._tooltipElement=this._shadowRoot.createChild('div','tooltip');doc.addEventListener('mousemove',this._mouseMove.bind(this),true);doc.addEventListener('mousedown',this._hide.bind(this,true),true);doc.addEventListener('mouseleave',this._hide.bind(this,false),true);doc.addEventListener('keydown',this._hide.bind(this,true),true);UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._reset,this);doc.defaultView.addEventListener('resize',this._reset.bind(this),false);}
static installHandler(doc){new UI.Tooltip(doc);}
static install(element,tooltipContent,actionId,options){if(!tooltipContent){delete element[UI.Tooltip._symbol];return;}
element[UI.Tooltip._symbol]={content:tooltipContent,actionId:actionId,options:options||{}};}
static addNativeOverrideContainer(element){UI.Tooltip._nativeOverrideContainer.push(element);}
_mouseMove(event){const mouseEvent=(event);const path=mouseEvent.path;if(!path||mouseEvent.buttons!==0||(mouseEvent.movementX===0&&mouseEvent.movementY===0))
return;if(this._anchorElement&&path.indexOf(this._anchorElement)===-1)
this._hide(false);for(const element of path){if(element===this._anchorElement){return;}else if(element[UI.Tooltip._symbol]){this._show(element,mouseEvent);return;}}}
_show(anchorElement,event){const tooltip=anchorElement[UI.Tooltip._symbol];this._anchorElement=anchorElement;this._tooltipElement.removeChildren();for(const element of UI.Tooltip._nativeOverrideContainer){if(this._anchorElement.isSelfOrDescendant(element)){Object.defineProperty(this._anchorElement,'title',UI.Tooltip._nativeTitle);this._anchorElement.title=tooltip.content;return;}}
if(typeof tooltip.content==='string')
this._tooltipElement.setTextContentTruncatedIfNeeded(tooltip.content);else
this._tooltipElement.appendChild(tooltip.content);if(tooltip.actionId){const shortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction(tooltip.actionId);for(const shortcut of shortcuts){const shortcutElement=this._tooltipElement.createChild('div','tooltip-shortcut');shortcutElement.textContent=shortcut.name;}}
this._tooltipElement.classList.add('shown');this._tooltipElement.positionAt(0,0);const now=Date.now();const instant=(this._tooltipLastClosed&&now-this._tooltipLastClosed<UI.Tooltip.Timing.InstantThreshold);this._tooltipElement.classList.toggle('instant',instant);this._tooltipLastOpened=instant?now:now+UI.Tooltip.Timing.OpeningDelay;const container=UI.GlassPane.container((anchorElement.ownerDocument));const containerBox=container.boxInWindow(this.element.window());const anchorBox=this._anchorElement.boxInWindow(this.element.window());const anchorOffset=2;const pageMargin=2;const cursorOffset=10;this._tooltipElement.classList.toggle('tooltip-breakword',!this._tooltipElement.textContent.match('\\s'));this._tooltipElement.style.maxWidth=(containerBox.width-pageMargin*2)+'px';this._tooltipElement.style.maxHeight='';const tooltipWidth=this._tooltipElement.offsetWidth;const tooltipHeight=this._tooltipElement.offsetHeight;const anchorTooltipAtElement=this._anchorElement.nodeName==='BUTTON'||this._anchorElement.nodeName==='LABEL';let tooltipX=anchorTooltipAtElement?anchorBox.x:event.x+cursorOffset;tooltipX=Number.constrain(tooltipX,containerBox.x+pageMargin,containerBox.x+containerBox.width-tooltipWidth-pageMargin);let tooltipY;if(!anchorTooltipAtElement){tooltipY=event.y+cursorOffset+tooltipHeight<containerBox.y+containerBox.height?event.y+cursorOffset:event.y-tooltipHeight;}else{const onBottom=anchorBox.y+anchorOffset+anchorBox.height+tooltipHeight<containerBox.y+containerBox.height;tooltipY=onBottom?anchorBox.y+anchorBox.height+anchorOffset:anchorBox.y-tooltipHeight-anchorOffset;}
this._tooltipElement.positionAt(tooltipX,tooltipY);}
_hide(removeInstant){delete this._anchorElement;this._tooltipElement.classList.remove('shown');if(Date.now()>this._tooltipLastOpened)
this._tooltipLastClosed=Date.now();if(removeInstant)
delete this._tooltipLastClosed;}
_reset(){this._hide(true);this._tooltipElement.positionAt(0,0);this._tooltipElement.style.maxWidth='0';this._tooltipElement.style.maxHeight='0';}};UI.Tooltip.Timing={'InstantThreshold':300,'OpeningDelay':600};UI.Tooltip._symbol=Symbol('Tooltip');UI.Tooltip._nativeOverrideContainer=[];UI.Tooltip._nativeTitle=(Object.getOwnPropertyDescriptor(HTMLElement.prototype,'title'));Object.defineProperty(HTMLElement.prototype,'title',{get:function(){const tooltip=this[UI.Tooltip._symbol];return tooltip?tooltip.content:'';},set:function(x){UI.Tooltip.install(this,x);}});;UI.SuggestBoxDelegate=function(){};UI.SuggestBoxDelegate.prototype={applySuggestion(suggestion,isIntermediateSuggestion){},acceptSuggestion(){},};UI.SuggestBox=class{constructor(suggestBoxDelegate,maxItemsHeight,captureEnter){this._suggestBoxDelegate=suggestBoxDelegate;this._maxItemsHeight=maxItemsHeight;this._captureEnter=captureEnter;this._rowHeight=17;this._userInteracted=false;this._userEnteredText='';this._defaultSelectionIsDimmed=false;this._onlyCompletion=null;this._items=new UI.ListModel();this._list=new UI.ListControl(this._items,this,UI.ListMode.EqualHeightItems);this._element=this._list.element;this._element.classList.add('suggest-box');this._element.addEventListener('mousedown',event=>event.preventDefault(),true);this._element.addEventListener('click',this._onClick.bind(this),false);this._glassPane=new UI.GlassPane();this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom);this._glassPane.setOutsideClickCallback(this.hide.bind(this));const shadowRoot=UI.createShadowRootWithCoreStyles(this._glassPane.contentElement,'ui/suggestBox.css');shadowRoot.appendChild(this._element);}
setDefaultSelectionIsDimmed(value){this._defaultSelectionIsDimmed=value;this._element.classList.toggle('default-selection-is-dimmed',value);}
_setUserInteracted(value){this._userInteracted=value;this._element.classList.toggle('user-has-interacted',value);}
visible(){return this._glassPane.isShowing();}
setPosition(anchorBox){this._glassPane.setContentAnchorBox(anchorBox);}
_updateMaxSize(items){const maxWidth=this._maxWidth(items);const length=this._maxItemsHeight?Math.min(this._maxItemsHeight,items.length):items.length;const maxHeight=length*this._rowHeight;this._glassPane.setMaxContentSize(new UI.Size(maxWidth,maxHeight));}
_maxWidth(items){const kMaxWidth=300;if(!items.length)
return kMaxWidth;let maxItem;let maxLength=-Infinity;for(let i=0;i<items.length;i++){const length=(items[i].title||items[i].text).length+(items[i].subtitle||'').length;if(length>maxLength){maxLength=length;maxItem=items[i];}}
const element=this.createElementForItem((maxItem));return Math.min(kMaxWidth,UI.measurePreferredSize(element,this._element).width);}
_show(){if(this.visible())
return;this._glassPane.show(document);this._rowHeight=UI.measurePreferredSize(this.createElementForItem({text:'1',subtitle:'12'}),this._element).height;}
hide(){if(!this.visible())
return;this._setUserInteracted(false);this._glassPane.hide();}
_applySuggestion(isIntermediateSuggestion){if(this._onlyCompletion){UI.ARIAUtils.alert(ls`${this._onlyCompletion}, suggestion`,this._element);this._suggestBoxDelegate.applySuggestion(this._onlyCompletion,isIntermediateSuggestion);return true;}
const suggestion=this._list.selectedItem()?this._list.selectedItem().text:'';if(suggestion)
UI.ARIAUtils.alert(ls`${suggestion}, suggestion`,this._element);this._suggestBoxDelegate.applySuggestion(suggestion,isIntermediateSuggestion);return this.visible()&&!!suggestion;}
acceptSuggestion(){const result=this._applySuggestion();this.hide();if(!result)
return false;this._suggestBoxDelegate.acceptSuggestion();return true;}
createElementForItem(item){const query=this._userEnteredText;const element=createElementWithClass('div','suggest-box-content-item source-code');if(item.iconType){const icon=UI.Icon.create(item.iconType,'suggestion-icon');element.appendChild(icon);}
if(item.isSecondary)
element.classList.add('secondary');element.tabIndex=-1;const maxTextLength=50+query.length;const displayText=(item.title||item.text).trimEnd(maxTextLength);const titleElement=element.createChild('span','suggestion-title');const index=displayText.toLowerCase().indexOf(query.toLowerCase());if(index>0)
titleElement.createChild('span').textContent=displayText.substring(0,index);if(index>-1)
titleElement.createChild('span','query').textContent=displayText.substring(index,index+query.length);titleElement.createChild('span').textContent=displayText.substring(index>-1?index+query.length:0);titleElement.createChild('span','spacer');if(item.subtitle){const subtitleElement=element.createChild('span','suggestion-subtitle');subtitleElement.textContent=item.subtitle.trimEnd(maxTextLength-displayText.length);}
return element;}
heightForItem(item){return this._rowHeight;}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement)
fromElement.classList.remove('selected','force-white-icons');if(toElement){toElement.classList.add('selected');if(fromElement||this._userInteracted||!this._defaultSelectionIsDimmed)
toElement.classList.add('force-white-icons');}
this._applySuggestion(true);}
_onClick(event){const item=this._list.itemForNode((event.target));if(!item)
return;this._list.selectItem(item);this._setUserInteracted(true);this.acceptSuggestion();event.consume(true);}
_canShowBox(completions,canShowForSingleItem,userEnteredText){if(!completions||!completions.length)
return false;if(completions.length>1)
return true;if(!completions[0].text.startsWith(userEnteredText))
return true;return canShowForSingleItem&&completions[0].text!==userEnteredText;}
updateSuggestions(anchorBox,completions,selectHighestPriority,canShowForSingleItem,userEnteredText){this._onlyCompletion=null;if(this._canShowBox(completions,canShowForSingleItem,userEnteredText)){this._userEnteredText=userEnteredText;this._show();this._updateMaxSize(completions);this._glassPane.setContentAnchorBox(anchorBox);this._list.invalidateItemHeight();this._items.replaceAll(completions);if(selectHighestPriority){let highestPriorityItem=completions[0];let highestPriority=completions[0].priority||0;for(let i=0;i<completions.length;i++){const priority=completions[i].priority||0;if(highestPriority<priority){highestPriority=priority;highestPriorityItem=completions[i];}}
this._list.selectItem(highestPriorityItem,true);}else{this._list.selectItem(null);}}else{if(completions.length===1){this._onlyCompletion=completions[0].text;this._applySuggestion(true);}
this.hide();}}
keyPressed(event){let selected=false;switch(event.key){case'Enter':return this.enterKeyPressed();case'ArrowUp':selected=this._list.selectPreviousItem(true,false);break;case'ArrowDown':selected=this._list.selectNextItem(true,false);break;case'PageUp':selected=this._list.selectItemPreviousPage(false);break;case'PageDown':selected=this._list.selectItemNextPage(false);break;default:return false;}
if(selected){this._setUserInteracted(true);return true;}
return false;}
enterKeyPressed(){if(!this._userInteracted&&this._captureEnter)
return false;const hasSelectedItem=!!this._list.selectedItem()||!!this._onlyCompletion;this.acceptSuggestion();return hasSelectedItem;}};UI.SuggestBox.Suggestion;UI.SuggestBox.Suggestions;;UI.TabbedPane=class extends UI.VBox{constructor(){super(true);this.registerRequiredCSS('ui/tabbedPane.css');this.element.classList.add('tabbed-pane');this.contentElement.classList.add('tabbed-pane-shadow');this.contentElement.tabIndex=-1;this._headerElement=this.contentElement.createChild('div','tabbed-pane-header');this._headerContentsElement=this._headerElement.createChild('div','tabbed-pane-header-contents');this._tabSlider=createElementWithClass('div','tabbed-pane-tab-slider');this._tabsElement=this._headerContentsElement.createChild('div','tabbed-pane-header-tabs');this._tabsElement.setAttribute('role','tablist');this._tabsElement.addEventListener('keydown',this._keyDown.bind(this),false);this._contentElement=this.contentElement.createChild('div','tabbed-pane-content');this._contentElement.setAttribute('role','tabpanel');this._contentElement.createChild('content');this._tabs=[];this._tabsHistory=[];this._tabsById=new Map();this._currentTabLocked=false;this._autoSelectFirstItemOnShow=true;this._dropDownButton=this._createDropDownButton();UI.zoomManager.addEventListener(UI.ZoomManager.Events.ZoomChanged,this._zoomChanged,this);this.makeTabSlider();}
setAccessibleName(name){UI.ARIAUtils.setAccessibleName(this._tabsElement,name);}
setCurrentTabLocked(locked){this._currentTabLocked=locked;this._headerElement.classList.toggle('locked',this._currentTabLocked);}
setAutoSelectFirstItemOnShow(autoSelect){this._autoSelectFirstItemOnShow=autoSelect;}
get visibleView(){return this._currentTab?this._currentTab.view:null;}
tabIds(){return this._tabs.map(tab=>tab._id);}
tabIndex(tabId){return this._tabs.findIndex(tab=>tab.id===tabId);}
tabViews(){return this._tabs.map(tab=>tab.view);}
tabView(tabId){return this._tabsById.has(tabId)?this._tabsById.get(tabId).view:null;}
get selectedTabId(){return this._currentTab?this._currentTab.id:null;}
setShrinkableTabs(shrinkableTabs){this._shrinkableTabs=shrinkableTabs;}
makeVerticalTabLayout(){this._verticalTabLayout=true;this._setTabSlider(false);this.contentElement.classList.add('vertical-tab-layout');this.invalidateConstraints();}
setCloseableTabs(closeableTabs){this._closeableTabs=closeableTabs;}
focus(){if(this.visibleView)
this.visibleView.focus();else
this.contentElement.focus();}
headerElement(){return this._headerElement;}
isTabCloseable(id){const tab=this._tabsById.get(id);return tab?tab.isCloseable():false;}
setTabDelegate(delegate){const tabs=this._tabs.slice();for(let i=0;i<tabs.length;++i)
tabs[i].setDelegate(delegate);this._delegate=delegate;}
appendTab(id,tabTitle,view,tabTooltip,userGesture,isCloseable,index){isCloseable=typeof isCloseable==='boolean'?isCloseable:this._closeableTabs;const tab=new UI.TabbedPaneTab(this,id,tabTitle,isCloseable,view,tabTooltip);tab.setDelegate(this._delegate);console.assert(!this._tabsById.has(id),`Tabbed pane already contains a tab with id '${id}'`);this._tabsById.set(id,tab);if(index!==undefined)
this._tabs.splice(index,0,tab);else
this._tabs.push(tab);this._tabsHistory.push(tab);if(this._tabsHistory[0]===tab&&this.isShowing())
this.selectTab(tab.id,userGesture);this._updateTabElements();}
closeTab(id,userGesture){this.closeTabs([id],userGesture);}
closeTabs(ids,userGesture){const focused=this.hasFocus();for(let i=0;i<ids.length;++i)
this._innerCloseTab(ids[i],userGesture);this._updateTabElements();if(this._tabsHistory.length)
this.selectTab(this._tabsHistory[0].id,false);if(focused)
this.focus();}
_innerCloseTab(id,userGesture){if(!this._tabsById.has(id))
return;if(userGesture&&!this._tabsById.get(id)._closeable)
return;if(this._currentTab&&this._currentTab.id===id)
this._hideCurrentTab();const tab=this._tabsById.get(id);this._tabsById.delete(id);this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabs.splice(this._tabs.indexOf(tab),1);if(tab._shown)
this._hideTabElement(tab);const eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabClosed,eventData);return true;}
hasTab(tabId){return this._tabsById.has(tabId);}
allTabs(){return this._tabs.map(function(tab){return tab.id;});}
otherTabs(id){const result=[];for(let i=0;i<this._tabs.length;++i){if(this._tabs[i].id!==id)
result.push(this._tabs[i].id);}
return result;}
_tabsToTheRight(id){let index=-1;for(let i=0;i<this._tabs.length;++i){if(this._tabs[i].id===id){index=i;break;}}
if(index===-1)
return[];return this._tabs.slice(index+1).map(function(tab){return tab.id;});}
_viewHasFocus(){if(this.visibleView)
return this.visibleView.hasFocus();return this.contentElement===this.contentElement.getComponentRoot().activeElement;}
selectTab(id,userGesture){if(this._currentTabLocked)
return false;const focused=this._viewHasFocus();const tab=this._tabsById.get(id);if(!tab)
return false;if(this._currentTab&&this._currentTab.id===id)
return true;this.suspendInvalidations();this._hideCurrentTab();this._showTab(tab);this.resumeInvalidations();this._currentTab=tab;this._tabsHistory.splice(this._tabsHistory.indexOf(tab),1);this._tabsHistory.splice(0,0,tab);this._updateTabElements();if(focused)
this.focus();const eventData={tabId:id,view:tab.view,isUserGesture:userGesture};this.dispatchEventToListeners(UI.TabbedPane.Events.TabSelected,eventData);return true;}
selectNextTab(){const index=this._tabs.indexOf(this._currentTab);const nextIndex=mod(index+1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);}
selectPrevTab(){const index=this._tabs.indexOf(this._currentTab);const nextIndex=mod(index-1,this._tabs.length);this.selectTab(this._tabs[nextIndex].id,true);}
lastOpenedTabIds(tabsCount){function tabToTabId(tab){return tab.id;}
return this._tabsHistory.slice(0,tabsCount).map(tabToTabId);}
setTabIcon(id,icon){const tab=this._tabsById.get(id);tab._setIcon(icon);this._updateTabElements();}
setTabEnabled(id,enabled){const tab=this._tabsById.get(id);tab.tabElement.classList.toggle('disabled',!enabled);}
toggleTabClass(id,className,force){const tab=this._tabsById.get(id);if(tab._toggleClass(className,force))
this._updateTabElements();}
_zoomChanged(event){for(let i=0;i<this._tabs.length;++i)
delete this._tabs[i]._measuredWidth;if(this.isShowing())
this._updateTabElements();}
changeTabTitle(id,tabTitle,tabTooltip){const tab=this._tabsById.get(id);if(tabTooltip!==undefined)
tab.tooltip=tabTooltip;if(tab.title!==tabTitle){tab.title=tabTitle;this._updateTabElements();}}
changeTabView(id,view){const tab=this._tabsById.get(id);if(tab.view===view)
return;this.suspendInvalidations();const isSelected=this._currentTab&&this._currentTab.id===id;const shouldFocus=tab.view.hasFocus();if(isSelected)
this._hideTab(tab);tab.view=view;if(isSelected)
this._showTab(tab);if(shouldFocus)
tab.view.focus();this.resumeInvalidations();}
onResize(){this._updateTabElements();}
headerResized(){this._updateTabElements();}
wasShown(){const effectiveTab=this._currentTab||this._tabsHistory[0];if(effectiveTab&&this._autoSelectFirstItemOnShow)
this.selectTab(effectiveTab.id);}
makeTabSlider(){if(this._verticalTabLayout)
return;this._setTabSlider(true);}
_setTabSlider(enable){this._sliderEnabled=enable;this._tabSlider.classList.toggle('enabled',enable);}
calculateConstraints(){let constraints=super.calculateConstraints();const minContentConstraints=new UI.Constraints(new UI.Size(0,0),new UI.Size(50,50));constraints=constraints.widthToMax(minContentConstraints).heightToMax(minContentConstraints);if(this._verticalTabLayout)
constraints=constraints.addWidth(new UI.Constraints(new UI.Size(120,0)));else
constraints=constraints.addHeight(new UI.Constraints(new UI.Size(0,30)));return constraints;}
_updateTabElements(){UI.invokeOnceAfterBatchUpdate(this,this._innerUpdateTabElements);}
setPlaceholderElement(element){this._placeholderElement=element;if(this._placeholderContainerElement){this._placeholderContainerElement.removeChildren();this._placeholderContainerElement.appendChild(element);}}
_innerUpdateTabElements(){if(!this.isShowing())
return;if(!this._tabs.length){this._contentElement.classList.add('has-no-tabs');if(this._placeholderElement&&!this._placeholderContainerElement){this._placeholderContainerElement=this._contentElement.createChild('div','tabbed-pane-placeholder fill');this._placeholderContainerElement.appendChild(this._placeholderElement);}}else{this._contentElement.classList.remove('has-no-tabs');if(this._placeholderContainerElement){this._placeholderContainerElement.remove();delete this._placeholderContainerElement;}}
this._measureDropDownButton();this._updateWidths();this._updateTabsDropDown();this._updateTabSlider();}
_showTabElement(index,tab){if(index>=this._tabsElement.children.length)
this._tabsElement.appendChild(tab.tabElement);else
this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.children[index]);tab._shown=true;}
_hideTabElement(tab){this._tabsElement.removeChild(tab.tabElement);tab._shown=false;}
_createDropDownButton(){const dropDownContainer=createElementWithClass('div','tabbed-pane-header-tabs-drop-down-container');const chevronIcon=UI.Icon.create('largeicon-chevron','chevron-icon');dropDownContainer.appendChild(chevronIcon);dropDownContainer.addEventListener('click',this._onDropDownMouseDown.bind(this));dropDownContainer.addEventListener('mousedown',this._onDropDownMouseDown.bind(this));return dropDownContainer;}
_onDropDownMouseDown(event){if(event.which!==1)
return;const rect=this._dropDownButton.getBoundingClientRect();const menu=new UI.ContextMenu(event,false,rect.left,rect.bottom);for(let i=0;i<this._tabs.length;++i){const tab=this._tabs[i];if(tab._shown)
continue;menu.defaultSection().appendCheckboxItem(tab.title,this._dropDownMenuItemSelected.bind(this,tab),this._tabsHistory[0]===tab);}
menu.show();}
_dropDownMenuItemSelected(tab){this._lastSelectedOverflowTab=tab;this.selectTab(tab.id,true);}
_totalWidth(){return this._headerContentsElement.getBoundingClientRect().width;}
_numberOfTabsShown(){let numTabsShown=0;for(const tab of this._tabs){if(tab._shown)
numTabsShown++;}
return numTabsShown;}
disableOverflowMenu(){this._overflowDisabled=true;}
_updateTabsDropDown(){const tabsToShowIndexes=this._tabsToShowIndexes(this._tabs,this._tabsHistory,this._totalWidth(),this._measuredDropDownButtonWidth||0);if(this._lastSelectedOverflowTab&&this._numberOfTabsShown()!==tabsToShowIndexes.length){delete this._lastSelectedOverflowTab;this._updateTabsDropDown();return;}
for(let i=0;i<this._tabs.length;++i){if(this._tabs[i]._shown&&tabsToShowIndexes.indexOf(i)===-1)
this._hideTabElement(this._tabs[i]);}
for(let i=0;i<tabsToShowIndexes.length;++i){const tab=this._tabs[tabsToShowIndexes[i]];if(!tab._shown)
this._showTabElement(i,tab);}
if(!this._overflowDisabled)
this._maybeShowDropDown(tabsToShowIndexes.length!==this._tabs.length);}
_maybeShowDropDown(hasMoreTabs){if(hasMoreTabs&&!this._dropDownButton.parentElement)
this._headerContentsElement.appendChild(this._dropDownButton);else if(!hasMoreTabs&&this._dropDownButton.parentElement)
this._headerContentsElement.removeChild(this._dropDownButton);}
_measureDropDownButton(){if(this._overflowDisabled||this._measuredDropDownButtonWidth)
return;this._dropDownButton.classList.add('measuring');this._headerContentsElement.appendChild(this._dropDownButton);this._measuredDropDownButtonWidth=this._dropDownButton.getBoundingClientRect().width;this._headerContentsElement.removeChild(this._dropDownButton);this._dropDownButton.classList.remove('measuring');}
_updateWidths(){const measuredWidths=this._measureWidths();const maxWidth=this._shrinkableTabs?this._calculateMaxWidth(measuredWidths.slice(),this._totalWidth()):Number.MAX_VALUE;let i=0;for(const tab of this._tabs)
tab.setWidth(this._verticalTabLayout?-1:Math.min(maxWidth,measuredWidths[i++]));}
_measureWidths(){this._tabsElement.style.setProperty('width','2000px');const measuringTabElements=[];for(const tab of this._tabs){if(typeof tab._measuredWidth==='number')
continue;const measuringTabElement=tab._createTabElement(true);measuringTabElement.__tab=tab;measuringTabElements.push(measuringTabElement);this._tabsElement.appendChild(measuringTabElement);}
for(let i=0;i<measuringTabElements.length;++i){const width=measuringTabElements[i].getBoundingClientRect().width;measuringTabElements[i].__tab._measuredWidth=Math.ceil(width);}
for(let i=0;i<measuringTabElements.length;++i)
measuringTabElements[i].remove();const measuredWidths=[];for(const tab of this._tabs)
measuredWidths.push(tab._measuredWidth);this._tabsElement.style.removeProperty('width');return measuredWidths;}
_calculateMaxWidth(measuredWidths,totalWidth){if(!measuredWidths.length)
return 0;measuredWidths.sort(function(x,y){return x-y;});let totalMeasuredWidth=0;for(let i=0;i<measuredWidths.length;++i)
totalMeasuredWidth+=measuredWidths[i];if(totalWidth>=totalMeasuredWidth)
return measuredWidths[measuredWidths.length-1];let totalExtraWidth=0;for(let i=measuredWidths.length-1;i>0;--i){const extraWidth=measuredWidths[i]-measuredWidths[i-1];totalExtraWidth+=(measuredWidths.length-i)*extraWidth;if(totalWidth+totalExtraWidth>=totalMeasuredWidth){return measuredWidths[i-1]+
(totalWidth+totalExtraWidth-totalMeasuredWidth)/(measuredWidths.length-i);}}
return totalWidth/measuredWidths.length;}
_tabsToShowIndexes(tabsOrdered,tabsHistory,totalWidth,measuredDropDownButtonWidth){const tabsToShowIndexes=[];let totalTabsWidth=0;const tabCount=tabsOrdered.length;const tabsToLookAt=tabsOrdered.slice(0);if(this._currentTab!==undefined)
tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._currentTab),1)[0]);if(this._lastSelectedOverflowTab!==undefined)
tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._lastSelectedOverflowTab),1)[0]);for(let i=0;i<tabCount;++i){const tab=this._automaticReorder?tabsHistory[i]:tabsToLookAt[i];totalTabsWidth+=tab.width();let minimalRequiredWidth=totalTabsWidth;if(i!==tabCount-1)
minimalRequiredWidth+=measuredDropDownButtonWidth;if(!this._verticalTabLayout&&minimalRequiredWidth>totalWidth)
break;tabsToShowIndexes.push(tabsOrdered.indexOf(tab));}
tabsToShowIndexes.sort(function(x,y){return x-y;});return tabsToShowIndexes;}
_hideCurrentTab(){if(!this._currentTab)
return;this._hideTab(this._currentTab);delete this._currentTab;}
_showTab(tab){tab.tabElement.tabIndex=0;tab.tabElement.classList.add('selected');UI.ARIAUtils.setSelected(tab.tabElement,true);tab.view.show(this.element);this._updateTabSlider();}
_updateTabSlider(){if(!this._sliderEnabled)
return;if(!this._currentTab){this._tabSlider.style.width=0;return;}
let left=0;for(let i=0;i<this._tabs.length&&this._currentTab!==this._tabs[i];i++){if(this._tabs[i]._shown)
left+=this._tabs[i]._measuredWidth;}
const sliderWidth=this._currentTab._shown?this._currentTab._measuredWidth:this._dropDownButton.offsetWidth;const scaleFactor=window.devicePixelRatio>=1.5?' scaleY(0.75)':'';this._tabSlider.style.transform='translateX('+left+'px)'+scaleFactor;this._tabSlider.style.width=sliderWidth+'px';if(this._tabSlider.parentElement!==this._headerContentsElement)
this._headerContentsElement.appendChild(this._tabSlider);}
_hideTab(tab){tab.tabElement.removeAttribute('tabIndex');tab.tabElement.classList.remove('selected');tab.tabElement.setAttribute('aria-selected','false');tab.view.detach();}
elementsToRestoreScrollPositionsFor(){return[this._contentElement];}
_insertBefore(tab,index){this._tabsElement.insertBefore(tab.tabElement,this._tabsElement.childNodes[index]);const oldIndex=this._tabs.indexOf(tab);this._tabs.splice(oldIndex,1);if(oldIndex<index)
--index;this._tabs.splice(index,0,tab);this.dispatchEventToListeners(UI.TabbedPane.Events.TabOrderChanged,this._tabs);}
leftToolbar(){if(!this._leftToolbar){this._leftToolbar=new UI.Toolbar('tabbed-pane-left-toolbar');this._headerElement.insertBefore(this._leftToolbar.element,this._headerElement.firstChild);}
return this._leftToolbar;}
rightToolbar(){if(!this._rightToolbar){this._rightToolbar=new UI.Toolbar('tabbed-pane-right-toolbar');this._headerElement.appendChild(this._rightToolbar.element);}
return this._rightToolbar;}
setAllowTabReorder(allow,automatic){this._allowTabReorder=allow;this._automaticReorder=automatic;}
_keyDown(event){if(!this._currentTab)
return;let nextTabElement=null;switch(event.key){case'ArrowUp':case'ArrowLeft':nextTabElement=this._currentTab.tabElement.previousElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement)
nextTabElement=this._currentTab.tabElement.parentElement.lastElementChild;break;case'ArrowDown':case'ArrowRight':nextTabElement=this._currentTab.tabElement.nextElementSibling;if(!nextTabElement&&!this._dropDownButton.parentElement)
nextTabElement=this._currentTab.tabElement.parentElement.firstElementChild;break;case'Enter':case'Space':this._currentTab.view.focus();return;default:return;}
if(!nextTabElement){this._dropDownButton.click();return;}
const tab=this._tabs.find(tab=>tab.tabElement===nextTabElement);this.selectTab(tab.id,true);nextTabElement.focus();}};UI.TabbedPane.Events={TabSelected:Symbol('TabSelected'),TabClosed:Symbol('TabClosed'),TabOrderChanged:Symbol('TabOrderChanged')};UI.TabbedPaneTab=class{constructor(tabbedPane,id,title,closeable,view,tooltip){this._closeable=closeable;this._tabbedPane=tabbedPane;this._id=id;this._title=title;this._tooltip=tooltip;this._view=view;this._shown=false;this._measuredWidth;this._tabElement;this._iconContainer=null;}
get id(){return this._id;}
get title(){return this._title;}
set title(title){if(title===this._title)
return;this._title=title;if(this._titleElement)
this._titleElement.textContent=title;delete this._measuredWidth;}
isCloseable(){return this._closeable;}
_setIcon(icon){this._icon=icon;if(this._tabElement)
this._createIconElement(this._tabElement,this._titleElement,false);delete this._measuredWidth;}
_toggleClass(className,force){const element=this.tabElement;const hasClass=element.classList.contains(className);if(hasClass===force)
return false;element.classList.toggle(className,force);delete this._measuredWidth;return true;}
get view(){return this._view;}
set view(view){this._view=view;}
get tooltip(){return this._tooltip;}
set tooltip(tooltip){this._tooltip=tooltip;if(this._titleElement)
this._titleElement.title=tooltip||'';}
get tabElement(){if(!this._tabElement)
this._tabElement=this._createTabElement(false);return this._tabElement;}
width(){return this._width;}
setWidth(width){this.tabElement.style.width=width===-1?'':(width+'px');this._width=width;}
setDelegate(delegate){this._delegate=delegate;}
_createIconElement(tabElement,titleElement,measuring){if(tabElement.__iconElement){tabElement.__iconElement.remove();tabElement.__iconElement=null;}
if(!this._icon)
return;const iconContainer=createElementWithClass('span','tabbed-pane-header-tab-icon');const iconNode=measuring?this._icon.cloneNode(true):this._icon;iconContainer.appendChild(iconNode);tabElement.insertBefore(iconContainer,titleElement);tabElement.__iconElement=iconContainer;}
_createTabElement(measuring){const tabElement=createElementWithClass('div','tabbed-pane-header-tab');tabElement.id='tab-'+this._id;UI.ARIAUtils.markAsTab(tabElement);UI.ARIAUtils.setSelected(tabElement,false);const titleElement=tabElement.createChild('span','tabbed-pane-header-tab-title');titleElement.textContent=this.title;titleElement.title=this.tooltip||'';this._createIconElement(tabElement,titleElement,measuring);if(!measuring)
this._titleElement=titleElement;if(this._closeable){tabElement.createChild('div','tabbed-pane-close-button','dt-close-button').gray=true;tabElement.classList.add('closeable');}
if(measuring){tabElement.classList.add('measuring');}else{tabElement.addEventListener('click',this._tabClicked.bind(this),false);tabElement.addEventListener('auxclick',this._tabClicked.bind(this),false);tabElement.addEventListener('mousedown',this._tabMouseDown.bind(this),false);tabElement.addEventListener('mouseup',this._tabMouseUp.bind(this),false);tabElement.addEventListener('contextmenu',this._tabContextMenu.bind(this),false);if(this._tabbedPane._allowTabReorder){UI.installDragHandle(tabElement,this._startTabDragging.bind(this),this._tabDragging.bind(this),this._endTabDragging.bind(this),'-webkit-grabbing','pointer',200);}}
return tabElement;}
_tabClicked(event){const middleButton=event.button===1;const shouldClose=this._closeable&&(middleButton||event.target.classList.contains('tabbed-pane-close-button'));if(!shouldClose){this._tabbedPane.focus();return;}
this._closeTabs([this.id]);event.consume(true);}
_tabMouseDown(event){if(event.target.classList.contains('tabbed-pane-close-button')||event.button===1)
return;this._tabbedPane.selectTab(this.id,true);}
_tabMouseUp(event){if(event.button===1)
event.consume(true);}
_closeTabs(ids){if(this._delegate){this._delegate.closeTabs(this._tabbedPane,ids);return;}
this._tabbedPane.closeTabs(ids,true);}
_tabContextMenu(event){function close(){this._closeTabs([this.id]);}
function closeOthers(){this._closeTabs(this._tabbedPane.otherTabs(this.id));}
function closeAll(){this._closeTabs(this._tabbedPane.allTabs());}
function closeToTheRight(){this._closeTabs(this._tabbedPane._tabsToTheRight(this.id));}
const contextMenu=new UI.ContextMenu(event);if(this._closeable){contextMenu.defaultSection().appendItem(Common.UIString('Close'),close.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close others'),closeOthers.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close tabs to the right'),closeToTheRight.bind(this));contextMenu.defaultSection().appendItem(Common.UIString('Close all'),closeAll.bind(this));}
if(this._delegate)
this._delegate.onContextMenu(this.id,contextMenu);contextMenu.show();}
_startTabDragging(event){if(event.target.classList.contains('tabbed-pane-close-button'))
return false;this._dragStartX=event.pageX;this._tabElement.classList.add('dragging');this._tabbedPane._tabSlider.remove();return true;}
_tabDragging(event){const tabElements=this._tabbedPane._tabsElement.childNodes;for(let i=0;i<tabElements.length;++i){let tabElement=tabElements[i];if(tabElement===this._tabElement)
continue;const intersects=tabElement.offsetLeft+tabElement.clientWidth>this._tabElement.offsetLeft&&this._tabElement.offsetLeft+this._tabElement.clientWidth>tabElement.offsetLeft;if(!intersects)
continue;if(Math.abs(event.pageX-this._dragStartX)<tabElement.clientWidth/2+5)
break;if(event.pageX-this._dragStartX>0){tabElement=tabElement.nextSibling;++i;}
const oldOffsetLeft=this._tabElement.offsetLeft;this._tabbedPane._insertBefore(this,i);this._dragStartX+=this._tabElement.offsetLeft-oldOffsetLeft;break;}
if(!this._tabElement.previousSibling&&event.pageX-this._dragStartX<0){this._tabElement.style.setProperty('left','0px');return;}
if(!this._tabElement.nextSibling&&event.pageX-this._dragStartX>0){this._tabElement.style.setProperty('left','0px');return;}
this._tabElement.style.setProperty('left',(event.pageX-this._dragStartX)+'px');}
_endTabDragging(event){this._tabElement.classList.remove('dragging');this._tabElement.style.removeProperty('left');delete this._dragStartX;this._tabbedPane._updateTabSlider();}};UI.TabbedPaneTabDelegate=function(){};UI.TabbedPaneTabDelegate.prototype={closeTabs(tabbedPane,ids){},onContextMenu(tabId,contextMenu){}};;UI.highlightedSearchResultClassName='highlighted-search-result';UI.highlightedCurrentSearchResultClassName='current-search-result';UI.installDragHandle=function(element,elementDragStart,elementDrag,elementDragEnd,cursor,hoverCursor,startDelay){function onMouseDown(event){const dragHandler=new UI.DragHandler();const dragStart=dragHandler.elementDragStart.bind(dragHandler,element,elementDragStart,elementDrag,elementDragEnd,cursor,event);if(startDelay)
startTimer=setTimeout(dragStart,startDelay);else
dragStart();}
function onMouseUp(){if(startTimer)
clearTimeout(startTimer);startTimer=null;}
let startTimer;element.addEventListener('mousedown',onMouseDown,false);if(startDelay)
element.addEventListener('mouseup',onMouseUp,false);if(hoverCursor!==null)
element.style.cursor=hoverCursor||cursor||'';};UI.elementDragStart=function(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){const dragHandler=new UI.DragHandler();dragHandler.elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event);};UI.DragHandler=class{constructor(){this._elementDragMove=this._elementDragMove.bind(this);this._elementDragEnd=this._elementDragEnd.bind(this);this._mouseOutWhileDragging=this._mouseOutWhileDragging.bind(this);}
_createGlassPane(){this._glassPaneInUse=true;if(!UI.DragHandler._glassPaneUsageCount++){UI.DragHandler._glassPane=new UI.GlassPane();UI.DragHandler._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane);UI.DragHandler._glassPane.show(UI.DragHandler._documentForMouseOut);}}
_disposeGlassPane(){if(!this._glassPaneInUse)
return;this._glassPaneInUse=false;if(--UI.DragHandler._glassPaneUsageCount)
return;UI.DragHandler._glassPane.hide();delete UI.DragHandler._glassPane;delete UI.DragHandler._documentForMouseOut;}
elementDragStart(targetElement,elementDragStart,elementDrag,elementDragEnd,cursor,event){if(event.button||(Host.isMac()&&event.ctrlKey))
return;if(this._elementDraggingEventListener)
return;if(elementDragStart&&!elementDragStart((event)))
return;const targetDocument=event.target.ownerDocument;this._elementDraggingEventListener=elementDrag;this._elementEndDraggingEventListener=elementDragEnd;console.assert((UI.DragHandler._documentForMouseOut||targetDocument)===targetDocument,'Dragging on multiple documents.');UI.DragHandler._documentForMouseOut=targetDocument;this._dragEventsTargetDocument=targetDocument;try{this._dragEventsTargetDocumentTop=targetDocument.defaultView.top.document;}catch(e){this._dragEventsTargetDocumentTop=this._dragEventsTargetDocument;}
targetDocument.addEventListener('mousemove',this._elementDragMove,true);targetDocument.addEventListener('mouseup',this._elementDragEnd,true);targetDocument.addEventListener('mouseout',this._mouseOutWhileDragging,true);if(targetDocument!==this._dragEventsTargetDocumentTop)
this._dragEventsTargetDocumentTop.addEventListener('mouseup',this._elementDragEnd,true);if(typeof cursor==='string'){this._restoreCursorAfterDrag=restoreCursor.bind(this,targetElement.style.cursor);targetElement.style.cursor=cursor;targetDocument.body.style.cursor=cursor;}
function restoreCursor(oldCursor){targetDocument.body.style.removeProperty('cursor');targetElement.style.cursor=oldCursor;this._restoreCursorAfterDrag=null;}
event.preventDefault();}
_mouseOutWhileDragging(){this._unregisterMouseOutWhileDragging();this._createGlassPane();}
_unregisterMouseOutWhileDragging(){if(!UI.DragHandler._documentForMouseOut)
return;UI.DragHandler._documentForMouseOut.removeEventListener('mouseout',this._mouseOutWhileDragging,true);}
_unregisterDragEvents(){if(!this._dragEventsTargetDocument)
return;this._dragEventsTargetDocument.removeEventListener('mousemove',this._elementDragMove,true);this._dragEventsTargetDocument.removeEventListener('mouseup',this._elementDragEnd,true);if(this._dragEventsTargetDocument!==this._dragEventsTargetDocumentTop)
this._dragEventsTargetDocumentTop.removeEventListener('mouseup',this._elementDragEnd,true);delete this._dragEventsTargetDocument;delete this._dragEventsTargetDocumentTop;}
_elementDragMove(event){if(event.buttons!==1){this._elementDragEnd(event);return;}
if(this._elementDraggingEventListener((event)))
this._cancelDragEvents(event);}
_cancelDragEvents(event){this._unregisterDragEvents();this._unregisterMouseOutWhileDragging();if(this._restoreCursorAfterDrag)
this._restoreCursorAfterDrag();this._disposeGlassPane();delete this._elementDraggingEventListener;delete this._elementEndDraggingEventListener;}
_elementDragEnd(event){const elementDragEnd=this._elementEndDraggingEventListener;this._cancelDragEvents((event));event.preventDefault();if(elementDragEnd)
elementDragEnd((event));}};UI.DragHandler._glassPaneUsageCount=0;UI.isBeingEdited=function(node){if(!node||node.nodeType!==Node.ELEMENT_NODE)
return false;let element=(node);if(element.classList.contains('text-prompt')||element.nodeName==='INPUT'||element.nodeName==='TEXTAREA')
return true;if(!UI.__editingCount)
return false;while(element){if(element.__editing)
return true;element=element.parentElementOrShadowHost();}
return false;};UI.isEditing=function(){if(UI.__editingCount)
return true;const focused=document.deepActiveElement();if(!focused)
return false;return focused.classList.contains('text-prompt')||focused.nodeName==='INPUT'||focused.nodeName==='TEXTAREA';};UI.markBeingEdited=function(element,value){if(value){if(element.__editing)
return false;element.classList.add('being-edited');element.__editing=true;UI.__editingCount=(UI.__editingCount||0)+1;}else{if(!element.__editing)
return false;element.classList.remove('being-edited');delete element.__editing;--UI.__editingCount;}
return true;};UI._numberRegex=/^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;UI.StyleValueDelimiters=' \xA0\t\n"\':;,/()';UI._valueModificationDirection=function(event){let direction=null;if(event.type==='mousewheel'){if(event.wheelDeltaY>0||event.wheelDeltaX>0)
direction='Up';else if(event.wheelDeltaY<0||event.wheelDeltaX<0)
direction='Down';}else{if(event.key==='ArrowUp'||event.key==='PageUp')
direction='Up';else if(event.key==='ArrowDown'||event.key==='PageDown')
direction='Down';}
return direction;};UI._modifiedHexValue=function(hexString,event){const direction=UI._valueModificationDirection(event);if(!direction)
return null;const mouseEvent=(event);const number=parseInt(hexString,16);if(isNaN(number)||!isFinite(number))
return null;const hexStrLen=hexString.length;const channelLen=hexStrLen/3;if(channelLen!==1&&channelLen!==2)
return null;let delta=0;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent))
delta+=Math.pow(16,channelLen*2);if(mouseEvent.shiftKey)
delta+=Math.pow(16,channelLen);if(mouseEvent.altKey)
delta+=1;if(delta===0)
delta=1;if(direction==='Down')
delta*=-1;const maxValue=Math.pow(16,hexStrLen)-1;const result=Number.constrain(number+delta,0,maxValue);let resultString=result.toString(16).toUpperCase();for(let i=0,lengthDelta=hexStrLen-resultString.length;i<lengthDelta;++i)
resultString='0'+resultString;return resultString;};UI._modifiedFloatNumber=function(number,event,modifierMultiplier){const direction=UI._valueModificationDirection(event);if(!direction)
return null;const mouseEvent=(event);let delta=1;if(UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent))
delta=100;else if(mouseEvent.shiftKey)
delta=10;else if(mouseEvent.altKey)
delta=0.1;if(direction==='Down')
delta*=-1;if(modifierMultiplier)
delta*=modifierMultiplier;const result=Number((number+delta).toFixed(6));if(!String(result).match(UI._numberRegex))
return null;return result;};UI.createReplacementString=function(wordString,event,customNumberHandler){let prefix;let suffix;let number;let replacementString=null;let matches=/(.*#)([\da-fA-F]+)(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedHexValue(matches[2],event);if(number!==null)
replacementString=prefix+number+suffix;}else{matches=/(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);if(matches&&matches.length){prefix=matches[1];suffix=matches[3];number=UI._modifiedFloatNumber(parseFloat(matches[2]),event);if(number!==null){replacementString=customNumberHandler?customNumberHandler(prefix,number,suffix):prefix+number+suffix;}}}
return replacementString;};UI.handleElementValueModifications=function(event,element,finishHandler,suggestionHandler,customNumberHandler){function createRange(){return document.createRange();}
const arrowKeyOrMouseWheelEvent=(event.key==='ArrowUp'||event.key==='ArrowDown'||event.type==='mousewheel');const pageKeyPressed=(event.key==='PageUp'||event.key==='PageDown');if(!arrowKeyOrMouseWheelEvent&&!pageKeyPressed)
return false;const selection=element.getComponentSelection();if(!selection.rangeCount)
return false;const selectionRange=selection.getRangeAt(0);if(!selectionRange.commonAncestorContainer.isSelfOrDescendant(element))
return false;const originalValue=element.textContent;const wordRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,UI.StyleValueDelimiters,element);const wordString=wordRange.toString();if(suggestionHandler&&suggestionHandler(wordString))
return false;const replacementString=UI.createReplacementString(wordString,event,customNumberHandler);if(replacementString){const replacementTextNode=createTextNode(replacementString);wordRange.deleteContents();wordRange.insertNode(replacementTextNode);const finalSelectionRange=createRange();finalSelectionRange.setStart(replacementTextNode,0);finalSelectionRange.setEnd(replacementTextNode,replacementString.length);selection.removeAllRanges();selection.addRange(finalSelectionRange);event.handled=true;event.preventDefault();if(finishHandler)
finishHandler(originalValue,replacementString);return true;}
return false;};Number.preciseMillisToString=function(ms,precision){precision=precision||0;const format='%.'+precision+'f\xa0ms';return Common.UIString(format,ms);};UI._microsFormat=new Common.UIStringFormat('%.0f\xa0\u03bcs');UI._subMillisFormat=new Common.UIStringFormat('%.2f\xa0ms');UI._millisFormat=new Common.UIStringFormat('%.0f\xa0ms');UI._secondsFormat=new Common.UIStringFormat('%.2f\xa0s');UI._minutesFormat=new Common.UIStringFormat('%.1f\xa0min');UI._hoursFormat=new Common.UIStringFormat('%.1f\xa0hrs');UI._daysFormat=new Common.UIStringFormat('%.1f\xa0days');Number.millisToString=function(ms,higherResolution){if(!isFinite(ms))
return'-';if(ms===0)
return'0';if(higherResolution&&ms<0.1)
return UI._microsFormat.format(ms*1000);if(higherResolution&&ms<1000)
return UI._subMillisFormat.format(ms);if(ms<1000)
return UI._millisFormat.format(ms);const seconds=ms/1000;if(seconds<60)
return UI._secondsFormat.format(seconds);const minutes=seconds/60;if(minutes<60)
return UI._minutesFormat.format(minutes);const hours=minutes/60;if(hours<24)
return UI._hoursFormat.format(hours);const days=hours/24;return UI._daysFormat.format(days);};Number.secondsToString=function(seconds,higherResolution){if(!isFinite(seconds))
return'-';return Number.millisToString(seconds*1000,higherResolution);};Number.bytesToString=function(bytes){if(bytes<1024)
return Common.UIString('%.0f\xa0B',bytes);const kilobytes=bytes/1024;if(kilobytes<100)
return Common.UIString('%.1f\xa0KB',kilobytes);if(kilobytes<1024)
return Common.UIString('%.0f\xa0KB',kilobytes);const megabytes=kilobytes/1024;if(megabytes<100)
return Common.UIString('%.1f\xa0MB',megabytes);else
return Common.UIString('%.0f\xa0MB',megabytes);};Number.withThousandsSeparator=function(num){let str=num+'';const re=/(\d+)(\d{3})/;while(str.match(re))
str=str.replace(re,'$1\xa0$2');return str;};UI.formatLocalized=function(format,substitutions){const formatters={s:substitution=>substitution};function append(a,b){a.appendChild(typeof b==='string'?createTextNode(b):b);return a;}
return String.format(Common.UIString(format),substitutions,formatters,createElement('span'),append).formattedResult;};UI.openLinkExternallyLabel=function(){return Common.UIString('Open in new tab');};UI.copyLinkAddressLabel=function(){return Common.UIString('Copy link address');};UI.anotherProfilerActiveLabel=function(){return Common.UIString('Another profiler is already active');};UI.asyncStackTraceLabel=function(description){if(description){if(description==='Promise.resolve')
description=Common.UIString('Promise resolved');else if(description==='Promise.reject')
description=Common.UIString('Promise rejected');return description+' '+Common.UIString('(async)');}
return Common.UIString('Async Call');};UI.installComponentRootStyles=function(element){UI.appendStyle(element,'ui/inspectorCommon.css');UI.themeSupport.injectHighlightStyleSheets(element);UI.themeSupport.injectCustomStyleSheets(element);element.classList.add('platform-'+Host.platform());if(!Host.isMac()&&UI.measuredScrollbarWidth(element.ownerDocument)===0)
element.classList.add('overlay-scrollbar-enabled');};UI.measuredScrollbarWidth=function(document){if(typeof UI._measuredScrollbarWidth==='number')
return UI._measuredScrollbarWidth;if(!document)
return 16;const scrollDiv=document.createElement('div');scrollDiv.setAttribute('style','width: 100px; height: 100px; overflow: scroll;');document.body.appendChild(scrollDiv);UI._measuredScrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth;document.body.removeChild(scrollDiv);return UI._measuredScrollbarWidth;};UI.createShadowRootWithCoreStyles=function(element,cssFile){const shadowRoot=element.createShadowRoot();UI.appendStyle(shadowRoot,'ui/inspectorCommon.css');UI.themeSupport.injectHighlightStyleSheets(shadowRoot);UI.themeSupport.injectCustomStyleSheets(shadowRoot);if(cssFile)
UI.appendStyle(shadowRoot,cssFile);shadowRoot.addEventListener('focus',UI._focusChanged.bind(UI),true);return shadowRoot;};UI._windowFocused=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE)
document.body.classList.remove('inactive');UI._keyboardFocus=true;const listener=()=>{const activeElement=document.deepActiveElement();if(activeElement)
activeElement.removeAttribute('data-keyboard-focus');UI._keyboardFocus=false;};document.defaultView.requestAnimationFrame(()=>{UI._keyboardFocus=false;document.removeEventListener('mousedown',listener,true);});document.addEventListener('mousedown',listener,true);};UI._windowBlurred=function(document,event){if(event.target.document.nodeType===Node.DOCUMENT_NODE)
document.body.classList.add('inactive');};UI._focusChanged=function(event){const document=event.target&&event.target.ownerDocument;const element=document?document.deepActiveElement():null;UI.Widget.focusWidgetForNode(element);UI.XWidget.focusWidgetForNode(element);if(!UI._keyboardFocus)
return;element.setAttribute('data-keyboard-focus','true');element.addEventListener('blur',()=>element.removeAttribute('data-keyboard-focus'),{once:true,capture:true});};UI.ElementFocusRestorer=class{constructor(element){this._element=element;this._previous=element.ownerDocument.deepActiveElement();element.focus();}
restore(){if(!this._element)
return;if(this._element.hasFocus()&&this._previous)
this._previous.focus();this._previous=null;this._element=null;}};UI.highlightSearchResult=function(element,offset,length,domChanges){const result=UI.highlightSearchResults(element,[new TextUtils.SourceRange(offset,length)],domChanges);return result.length?result[0]:null;};UI.highlightSearchResults=function(element,resultRanges,changes){return UI.highlightRangesWithStyleClass(element,resultRanges,UI.highlightedSearchResultClassName,changes);};UI.runCSSAnimationOnce=function(element,className){function animationEndCallback(){element.classList.remove(className);element.removeEventListener('webkitAnimationEnd',animationEndCallback,false);}
if(element.classList.contains(className))
element.classList.remove(className);element.addEventListener('webkitAnimationEnd',animationEndCallback,false);element.classList.add(className);};UI.highlightRangesWithStyleClass=function(element,resultRanges,styleClass,changes){changes=changes||[];const highlightNodes=[];const textNodes=element.childTextNodes();const lineText=textNodes.map(function(node){return node.textContent;}).join('');const ownerDocument=element.ownerDocument;if(textNodes.length===0)
return highlightNodes;const nodeRanges=[];let rangeEndOffset=0;for(let i=0;i<textNodes.length;++i){const range={};range.offset=rangeEndOffset;range.length=textNodes[i].textContent.length;rangeEndOffset=range.offset+range.length;nodeRanges.push(range);}
let startIndex=0;for(let i=0;i<resultRanges.length;++i){const startOffset=resultRanges[i].offset;const endOffset=startOffset+resultRanges[i].length;while(startIndex<textNodes.length&&nodeRanges[startIndex].offset+nodeRanges[startIndex].length<=startOffset)
startIndex++;let endIndex=startIndex;while(endIndex<textNodes.length&&nodeRanges[endIndex].offset+nodeRanges[endIndex].length<endOffset)
endIndex++;if(endIndex===textNodes.length)
break;const highlightNode=ownerDocument.createElement('span');highlightNode.className=styleClass;highlightNode.textContent=lineText.substring(startOffset,endOffset);const lastTextNode=textNodes[endIndex];const lastText=lastTextNode.textContent;lastTextNode.textContent=lastText.substring(endOffset-nodeRanges[endIndex].offset);changes.push({node:lastTextNode,type:'changed',oldText:lastText,newText:lastTextNode.textContent});if(startIndex===endIndex){lastTextNode.parentElement.insertBefore(highlightNode,lastTextNode);changes.push({node:highlightNode,type:'added',nextSibling:lastTextNode,parent:lastTextNode.parentElement});highlightNodes.push(highlightNode);const prefixNode=ownerDocument.createTextNode(lastText.substring(0,startOffset-nodeRanges[startIndex].offset));lastTextNode.parentElement.insertBefore(prefixNode,highlightNode);changes.push({node:prefixNode,type:'added',nextSibling:highlightNode,parent:lastTextNode.parentElement});}else{const firstTextNode=textNodes[startIndex];const firstText=firstTextNode.textContent;const anchorElement=firstTextNode.nextSibling;firstTextNode.parentElement.insertBefore(highlightNode,anchorElement);changes.push({node:highlightNode,type:'added',nextSibling:anchorElement,parent:firstTextNode.parentElement});highlightNodes.push(highlightNode);firstTextNode.textContent=firstText.substring(0,startOffset-nodeRanges[startIndex].offset);changes.push({node:firstTextNode,type:'changed',oldText:firstText,newText:firstTextNode.textContent});for(let j=startIndex+1;j<endIndex;j++){const textNode=textNodes[j];const text=textNode.textContent;textNode.textContent='';changes.push({node:textNode,type:'changed',oldText:text,newText:textNode.textContent});}}
startIndex=endIndex;nodeRanges[startIndex].offset=endOffset;nodeRanges[startIndex].length=lastTextNode.textContent.length;}
return highlightNodes;};UI.applyDomChanges=function(domChanges){for(let i=0,size=domChanges.length;i<size;++i){const entry=domChanges[i];switch(entry.type){case'added':entry.parent.insertBefore(entry.node,entry.nextSibling);break;case'changed':entry.node.textContent=entry.newText;break;}}};UI.revertDomChanges=function(domChanges){for(let i=domChanges.length-1;i>=0;--i){const entry=domChanges[i];switch(entry.type){case'added':entry.node.remove();break;case'changed':entry.node.textContent=entry.oldText;break;}}};UI.measurePreferredSize=function(element,containerElement){const oldParent=element.parentElement;const oldNextSibling=element.nextSibling;containerElement=containerElement||element.ownerDocument.body;containerElement.appendChild(element);element.positionAt(0,0);const result=element.getBoundingClientRect();element.positionAt(undefined,undefined);if(oldParent)
oldParent.insertBefore(element,oldNextSibling);else
element.remove();return new UI.Size(result.width,result.height);};UI.InvokeOnceHandlers=class{constructor(autoInvoke){this._handlers=null;this._autoInvoke=autoInvoke;}
add(object,method){if(!this._handlers){this._handlers=new Map();if(this._autoInvoke)
this.scheduleInvoke();}
let methods=this._handlers.get(object);if(!methods){methods=new Set();this._handlers.set(object,methods);}
methods.add(method);}
scheduleInvoke(){if(this._handlers)
requestAnimationFrame(this._invoke.bind(this));}
_invoke(){const handlers=this._handlers;this._handlers=null;const keys=handlers.keysArray();for(let i=0;i<keys.length;++i){const object=keys[i];const methods=handlers.get(object).valuesArray();for(let j=0;j<methods.length;++j)
methods[j].call(object);}}};UI._coalescingLevel=0;UI._postUpdateHandlers=null;UI.startBatchUpdate=function(){if(!UI._coalescingLevel++)
UI._postUpdateHandlers=new UI.InvokeOnceHandlers(false);};UI.endBatchUpdate=function(){if(--UI._coalescingLevel)
return;UI._postUpdateHandlers.scheduleInvoke();UI._postUpdateHandlers=null;};UI.invokeOnceAfterBatchUpdate=function(object,method){if(!UI._postUpdateHandlers)
UI._postUpdateHandlers=new UI.InvokeOnceHandlers(true);UI._postUpdateHandlers.add(object,method);};UI.animateFunction=function(window,func,params,duration,animationComplete){const start=window.performance.now();let raf=window.requestAnimationFrame(animationStep);function animationStep(timestamp){const progress=Number.constrain((timestamp-start)/duration,0,1);func(...params.map(p=>p.from+(p.to-p.from)*progress));if(progress<1)
raf=window.requestAnimationFrame(animationStep);else if(animationComplete)
animationComplete();}
return()=>window.cancelAnimationFrame(raf);};UI.LongClickController=class extends Common.Object{constructor(element,callback){super();this._element=element;this._callback=callback;this._enable();}
reset(){if(this._longClickInterval){clearInterval(this._longClickInterval);delete this._longClickInterval;}}
_enable(){if(this._longClickData)
return;const boundMouseDown=mouseDown.bind(this);const boundMouseUp=mouseUp.bind(this);const boundReset=this.reset.bind(this);this._element.addEventListener('mousedown',boundMouseDown,false);this._element.addEventListener('mouseout',boundReset,false);this._element.addEventListener('mouseup',boundMouseUp,false);this._element.addEventListener('click',boundReset,true);this._longClickData={mouseUp:boundMouseUp,mouseDown:boundMouseDown,reset:boundReset};function mouseDown(e){if(e.which!==1)
return;const callback=this._callback;this._longClickInterval=setTimeout(callback.bind(null,e),200);}
function mouseUp(e){if(e.which!==1)
return;this.reset();}}
dispose(){if(!this._longClickData)
return;this._element.removeEventListener('mousedown',this._longClickData.mouseDown,false);this._element.removeEventListener('mouseout',this._longClickData.reset,false);this._element.removeEventListener('mouseup',this._longClickData.mouseUp,false);this._element.addEventListener('click',this._longClickData.reset,true);delete this._longClickData;}};UI.initializeUIUtils=function(document,themeSetting){document.body.classList.toggle('inactive',!document.hasFocus());document.defaultView.addEventListener('focus',UI._windowFocused.bind(UI,document),false);document.defaultView.addEventListener('blur',UI._windowBlurred.bind(UI,document),false);document.addEventListener('focus',UI._focusChanged.bind(UI),true);document.addEventListener('keydown',event=>{UI._keyboardFocus=true;document.defaultView.requestAnimationFrame(()=>void(UI._keyboardFocus=false));},true);if(!UI.themeSupport)
UI.themeSupport=new UI.ThemeSupport(themeSetting);UI.themeSupport.applyTheme(document);const body=(document.body);UI.appendStyle(body,'ui/inspectorStyle.css');UI.GlassPane.setContainer((document.body));};UI.beautifyFunctionName=function(name){return name||Common.UIString('(anonymous)');};UI.registerCustomElement=function(localName,typeExtension,prototype){return document.registerElement(typeExtension,{prototype:Object.create(prototype),extends:localName});};UI.createTextButton=function(text,clickHandler,className,primary){const element=createElementWithClass('button',className||'','text-button');element.textContent=text;if(primary)
element.classList.add('primary-button');if(clickHandler)
element.addEventListener('click',clickHandler,false);return element;};UI.createInput=function(className,type){const element=createElementWithClass('input',className||'');element.spellcheck=false;element.classList.add('harmony-input');if(type)
element.type=type;return element;};UI.createRadioLabel=function(name,title,checked){const element=createElement('label','dt-radio');element.radioElement.name=name;element.radioElement.checked=!!checked;element.createTextChild(title);return element;};UI.createLabel=function(title,iconClass){const element=createElement('label','dt-icon-label');element.createChild('span').textContent=title;element.type=iconClass;return element;};UI.createSliderLabel=function(min,max,tabIndex){const element=createElement('label','dt-slider');element.sliderElement.min=min;element.sliderElement.max=max;element.sliderElement.step=1;element.sliderElement.tabIndex=tabIndex;return element;};UI.appendStyle=function(node,cssFile){const content=Runtime.cachedResources[cssFile]||'';if(!content)
console.error(cssFile+' not preloaded. Check module.json');let styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=content;node.appendChild(styleElement);const themeStyleSheet=UI.themeSupport.themeStyleSheet(cssFile,content);if(themeStyleSheet){styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=themeStyleSheet+'\n'+Runtime.resolveSourceURL(cssFile+'.theme');node.appendChild(styleElement);}};UI.CheckboxLabel=class extends HTMLLabelElement{constructor(){super();this._shadowRoot;this.checkboxElement;this.textElement;throw new Error('Checkbox must be created via factory method.');}
createdCallback(){UI.CheckboxLabel._lastId=(UI.CheckboxLabel._lastId||0)+1;const id='ui-checkbox-label'+UI.CheckboxLabel._lastId;this._shadowRoot=UI.createShadowRootWithCoreStyles(this,'ui/checkboxTextLabel.css');this.checkboxElement=(this._shadowRoot.createChild('input'));this.checkboxElement.type='checkbox';this.checkboxElement.setAttribute('id',id);this.textElement=this._shadowRoot.createChild('label','dt-checkbox-text');this.textElement.setAttribute('for',id);this._shadowRoot.createChild('content');}
static create(title,checked,subtitle){if(!UI.CheckboxLabel._constructor)
UI.CheckboxLabel._constructor=UI.registerCustomElement('label','dt-checkbox',UI.CheckboxLabel.prototype);const element=(new UI.CheckboxLabel._constructor());element.checkboxElement.checked=!!checked;if(title!==undefined){element.textElement.textContent=title;if(subtitle!==undefined)
element.textElement.createChild('div','dt-checkbox-subtitle').textContent=subtitle;}
return element;}
set backgroundColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.backgroundColor=color;}
set checkColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');const stylesheet=createElement('style');stylesheet.textContent='input.dt-checkbox-themed:checked:after { background-color: '+color+'}';this._shadowRoot.appendChild(stylesheet);}
set borderColor(color){this.checkboxElement.classList.add('dt-checkbox-themed');this.checkboxElement.style.borderColor=color;}};(function(){UI.registerCustomElement('button','text-button',{createdCallback:function(){this.type='button';const root=UI.createShadowRootWithCoreStyles(this,'ui/textButton.css');root.createChild('content');},__proto__:HTMLButtonElement.prototype});UI.registerCustomElement('label','dt-radio',{createdCallback:function(){this.radioElement=this.createChild('input','dt-radio-button');this.radioElement.type='radio';const root=UI.createShadowRootWithCoreStyles(this,'ui/radioButton.css');root.createChild('content').select='.dt-radio-button';root.createChild('content');this.addEventListener('click',radioClickHandler,false);},__proto__:HTMLLabelElement.prototype});function radioClickHandler(event){if(this.radioElement.checked||this.radioElement.disabled)
return;this.radioElement.checked=true;this.radioElement.dispatchEvent(new Event('change'));}
UI.registerCustomElement('label','dt-icon-label',{createdCallback:function(){const root=UI.createShadowRootWithCoreStyles(this);this._iconElement=UI.Icon.create();this._iconElement.style.setProperty('margin-right','4px');root.appendChild(this._iconElement);root.createChild('content');},set type(type){this._iconElement.setIconType(type);},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('label','dt-slider',{createdCallback:function(){const root=UI.createShadowRootWithCoreStyles(this,'ui/slider.css');this.sliderElement=createElementWithClass('input','dt-range-input');this.sliderElement.type='range';root.appendChild(this.sliderElement);},set value(amount){this.sliderElement.value=amount;},get value(){return this.sliderElement.value;},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('label','dt-small-bubble',{createdCallback:function(){const root=UI.createShadowRootWithCoreStyles(this,'ui/smallBubble.css');this._textElement=root.createChild('div');this._textElement.className='info';this._textElement.createChild('content');},set type(type){this._textElement.className=type;},__proto__:HTMLLabelElement.prototype});UI.registerCustomElement('div','dt-close-button',{createdCallback:function(){const root=UI.createShadowRootWithCoreStyles(this,'ui/closeButton.css');this._buttonElement=root.createChild('div','close-button');const regularIcon=UI.Icon.create('smallicon-cross','default-icon');this._hoverIcon=UI.Icon.create('mediumicon-red-cross-hover','hover-icon');this._activeIcon=UI.Icon.create('mediumicon-red-cross-active','active-icon');this._buttonElement.appendChild(regularIcon);this._buttonElement.appendChild(this._hoverIcon);this._buttonElement.appendChild(this._activeIcon);},set gray(gray){if(gray){this._hoverIcon.setIconType('mediumicon-gray-cross-hover');this._activeIcon.setIconType('mediumicon-gray-cross-active');}else{this._hoverIcon.setIconType('mediumicon-red-cross-hover');this._activeIcon.setIconType('mediumicon-red-cross-active');}},__proto__:HTMLDivElement.prototype});})();UI.bindInput=function(input,apply,validate,numeric,modifierMultiplier){input.addEventListener('change',onChange,false);input.addEventListener('input',onInput,false);input.addEventListener('keydown',onKeyDown,false);input.addEventListener('focus',input.select.bind(input),false);function onInput(){input.classList.toggle('error-input',!validate(input.value));}
function onChange(){const valid=validate(input.value);input.classList.toggle('error-input',!valid);if(valid)
apply(input.value);}
function onKeyDown(event){if(isEnterKey(event)){if(validate(input.value))
apply(input.value);event.preventDefault();return;}
if(!numeric)
return;const value=UI._modifiedFloatNumber(parseFloat(input.value),event,modifierMultiplier);const stringValue=value?String(value):'';if(!validate(stringValue)||!value)
return;input.value=stringValue;apply(input.value);event.preventDefault();}
function setValue(value){if(value===input.value)
return;const valid=validate(value);input.classList.toggle('error-input',!valid);input.value=value;}
return setValue;};UI.trimText=function(context,text,maxWidth,trimFunction){const maxLength=200;if(maxWidth<=10)
return'';if(text.length>maxLength)
text=trimFunction(text,maxLength);const textWidth=UI.measureTextWidth(context,text);if(textWidth<=maxWidth)
return text;let l=0;let r=text.length;let lv=0;let rv=textWidth;while(l<r&&lv!==rv&&lv!==maxWidth){const m=Math.ceil(l+(r-l)*(maxWidth-lv)/(rv-lv));const mv=UI.measureTextWidth(context,trimFunction(text,m));if(mv<=maxWidth){l=m;lv=mv;}else{r=m-1;rv=mv;}}
text=trimFunction(text,l);return text!=='\u2026'?text:'';};UI.trimTextMiddle=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimMiddle(width));};UI.trimTextEnd=function(context,text,maxWidth){return UI.trimText(context,text,maxWidth,(text,width)=>text.trimEnd(width));};UI.measureTextWidth=function(context,text){const maxCacheableLength=200;if(text.length>maxCacheableLength)
return context.measureText(text).width;let widthCache=UI.measureTextWidth._textWidthCache;if(!widthCache){widthCache=new Map();UI.measureTextWidth._textWidthCache=widthCache;}
const font=context.font;let textWidths=widthCache.get(font);if(!textWidths){textWidths=new Map();widthCache.set(font,textWidths);}
let width=textWidths.get(text);if(!width){width=context.measureText(text).width;textWidths.set(text,width);}
return width;};UI.ThemeSupport=class{constructor(setting){this._themeName=setting.get()||'default';this._themableProperties=new Set(['color','box-shadow','text-shadow','outline-color','background-image','background-color','border-left-color','border-right-color','border-top-color','border-bottom-color','-webkit-border-image']);this._cachedThemePatches=new Map();this._setting=setting;this._customSheets=new Set();}
hasTheme(){return this._themeName!=='default';}
themeName(){return this._themeName;}
injectHighlightStyleSheets(element){this._injectingStyleSheet=true;UI.appendStyle(element,'ui/inspectorSyntaxHighlight.css');if(this._themeName==='dark')
UI.appendStyle(element,'ui/inspectorSyntaxHighlightDark.css');this._injectingStyleSheet=false;}
injectCustomStyleSheets(element){for(const sheet of this._customSheets){const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=sheet;element.appendChild(styleElement);}}
addCustomStylesheet(sheetText){this._customSheets.add(sheetText);}
applyTheme(document){if(!this.hasTheme())
return;if(this._themeName==='dark')
document.documentElement.classList.add('-theme-with-dark-background');const styleSheets=document.styleSheets;const result=[];for(let i=0;i<styleSheets.length;++i)
result.push(this._patchForTheme(styleSheets[i].href,styleSheets[i]));result.push('/*# sourceURL=inspector.css.theme */');const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=result.join('\n');document.head.appendChild(styleElement);}
themeStyleSheet(id,text){if(!this.hasTheme()||this._injectingStyleSheet)
return'';let patch=this._cachedThemePatches.get(id);if(!patch){const styleElement=createElement('style');styleElement.type='text/css';styleElement.textContent=text;document.body.appendChild(styleElement);patch=this._patchForTheme(id,styleElement.sheet);document.body.removeChild(styleElement);}
return patch;}
_patchForTheme(id,styleSheet){const cached=this._cachedThemePatches.get(id);if(cached)
return cached;try{const rules=styleSheet.cssRules;const result=[];for(let j=0;j<rules.length;++j){if(rules[j]instanceof CSSImportRule){result.push(this._patchForTheme(rules[j].styleSheet.href,rules[j].styleSheet));continue;}
const output=[];const style=rules[j].style;const selectorText=rules[j].selectorText;for(let i=0;style&&i<style.length;++i)
this._patchProperty(selectorText,style,style[i],output);if(output.length)
result.push(rules[j].selectorText+'{'+output.join('')+'}');}
const fullText=result.join('\n');this._cachedThemePatches.set(id,fullText);return fullText;}catch(e){this._setting.set('default');return'';}}
_patchProperty(selectorText,style,name,output){if(!this._themableProperties.has(name))
return;const value=style.getPropertyValue(name);if(!value||value==='none'||value==='inherit'||value==='initial'||value==='transparent')
return;if(name==='background-image'&&value.indexOf('gradient')===-1)
return;if(selectorText.indexOf('-theme-')!==-1)
return;let colorUsage=UI.ThemeSupport.ColorUsage.Unknown;if(name.indexOf('background')===0||name.indexOf('border')===0)
colorUsage|=UI.ThemeSupport.ColorUsage.Background;if(name.indexOf('background')===-1)
colorUsage|=UI.ThemeSupport.ColorUsage.Foreground;output.push(name);output.push(':');const items=value.replace(Common.Color.Regex,'\0$1\0').split('\0');for(let i=0;i<items.length;++i)
output.push(this.patchColorText(items[i],colorUsage));if(style.getPropertyPriority(name))
output.push(' !important');output.push(';');}
patchColorText(text,colorUsage){const color=Common.Color.parse(text);if(!color)
return text;const outColor=this.patchColor(color,colorUsage);let outText=outColor.asString(null);if(!outText)
outText=outColor.asString(outColor.hasAlpha()?Common.Color.Format.RGBA:Common.Color.Format.RGB);return outText||text;}
patchColor(color,colorUsage){const hsla=color.hsla();this._patchHSLA(hsla,colorUsage);const rgba=[];Common.Color.hsl2rgb(hsla,rgba);return new Common.Color(rgba,color.format());}
_patchHSLA(hsla,colorUsage){const hue=hsla[0];const sat=hsla[1];let lit=hsla[2];const alpha=hsla[3];switch(this._themeName){case'dark':const minCap=colorUsage&UI.ThemeSupport.ColorUsage.Background?0.14:0;const maxCap=colorUsage&UI.ThemeSupport.ColorUsage.Foreground?0.9:1;lit=1-lit;if(lit<minCap*2)
lit=minCap+lit/2;else if(lit>2*maxCap-1)
lit=maxCap-1/2+lit/2;break;}
hsla[0]=Number.constrain(hue,0,1);hsla[1]=Number.constrain(sat,0,1);hsla[2]=Number.constrain(lit,0,1);hsla[3]=Number.constrain(alpha,0,1);}};UI.ThemeSupport.ColorUsage={Unknown:0,Foreground:1<<0,Background:1<<1,};UI.createDocumentationLink=function(article,title){return UI.XLink.create('https://developers.google.com/web/tools/chrome-devtools/'+article,title);};UI.loadImage=function(url){return new Promise(fulfill=>{const image=new Image();image.addEventListener('load',()=>fulfill(image));image.addEventListener('error',()=>fulfill(null));image.src=url;});};UI.loadImageFromData=function(data){return data?UI.loadImage('data:image/jpg;base64,'+data):Promise.resolve(null);};UI.themeSupport;UI.createFileSelectorElement=function(callback){const fileSelectorElement=createElement('input');fileSelectorElement.type='file';fileSelectorElement.style.display='none';fileSelectorElement.setAttribute('tabindex',-1);fileSelectorElement.onchange=onChange;function onChange(event){callback(fileSelectorElement.files[0]);}
return fileSelectorElement;};UI.MaxLengthForDisplayedURLs=150;UI.MessageDialog=class{static async show(message,where){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);const shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');const content=shadowRoot.createChild('div','widget');await new Promise(resolve=>{const okButton=UI.createTextButton(Common.UIString('OK'),resolve,'',true);content.createChild('div','message').createChild('span').textContent=message;content.createChild('div','button').appendChild(okButton);dialog.setOutsideClickCallback(event=>{event.consume();resolve();});dialog.show(where);okButton.focus();});dialog.hide();}};UI.ConfirmDialog=class{static async show(message,where){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setDimmed(true);const shadowRoot=UI.createShadowRootWithCoreStyles(dialog.contentElement,'ui/confirmDialog.css');const content=shadowRoot.createChild('div','widget');content.createChild('div','message').createChild('span').textContent=message;const buttonsBar=content.createChild('div','button');const result=await new Promise(resolve=>{buttonsBar.appendChild(UI.createTextButton(Common.UIString('OK'),()=>resolve(true),'',true));buttonsBar.appendChild(UI.createTextButton(Common.UIString('Cancel'),()=>resolve(false)));dialog.setOutsideClickCallback(event=>{event.consume();resolve(false);});dialog.show(where);});dialog.hide();return result;}};UI.createInlineButton=function(toolbarButton){const element=createElement('span');const shadowRoot=UI.createShadowRootWithCoreStyles(element,'ui/inlineButton.css');element.classList.add('inline-button');const toolbar=new UI.Toolbar('');toolbar.appendToolbarItem(toolbarButton);shadowRoot.appendChild(toolbar.element);return element;};;UI.ARIAUtils={};UI.ARIAUtils.markAsButton=function(element){element.setAttribute('role','button');};UI.ARIAUtils.markAsGroup=function(element){element.setAttribute('role','group');};UI.ARIAUtils.markAsLink=function(element){element.setAttribute('role','link');};UI.ARIAUtils.markAsTab=function(element){element.setAttribute('role','tab');};UI.ARIAUtils.markAsTree=function(element){element.setAttribute('role','tree');};UI.ARIAUtils.markAsTreeitem=function(element){element.setAttribute('role','treeitem');};UI.ARIAUtils.markAsTextBox=function(element){element.setAttribute('role','textbox');};UI.ARIAUtils.markAsHidden=function(element){element.setAttribute('aria-hidden','true');};UI.ARIAUtils.setPlaceholder=function(element,placeholder){if(placeholder)
element.setAttribute('aria-placeholder',placeholder);else
element.removeAttribute('aria-placeholder');};UI.ARIAUtils.markAsPresentation=function(element){element.setAttribute('role','presentation');};UI.ARIAUtils.setControls=function(element,controlledElement){if(!controlledElement){element.removeAttribute('aria-controls');return;}
if(controlledElement.id==='')
throw new Error('Controlled element must have ID');element.setAttribute('aria-controls',controlledElement.id);};UI.ARIAUtils.setExpanded=function(element,value){element.setAttribute('aria-expanded',!!value);};UI.ARIAUtils.unsetExpanded=function(element){element.removeAttribute('aria-expanded');};UI.ARIAUtils.setSelected=function(element,value){element.setAttribute('aria-selected',!!value);};UI.ARIAUtils.setPressed=function(element,value){element.setAttribute('aria-pressed',!!value);};UI.ARIAUtils.setAccessibleName=function(element,name){element.setAttribute('aria-label',name);};UI.ARIAUtils.alert=function(message,element){const document=element.ownerDocument;if(!document[UI.ARIAUtils.AlertElementSymbol]){const alertElement=document.body.createChild('div');alertElement.style.position='absolute';alertElement.style.left='-999em';alertElement.setAttribute('role','alert');alertElement.setAttribute('aria-atomic','true');document[UI.ARIAUtils.AlertElementSymbol]=alertElement;}
document[UI.ARIAUtils.AlertElementSymbol].textContent=message;};UI.ARIAUtils.AlertElementSymbol=Symbol('AlertElementSybmol');;UI.ZoomManager=class extends Common.Object{constructor(window,frontendHost){super();this._frontendHost=frontendHost;this._zoomFactor=this._frontendHost.zoomFactor();window.addEventListener('resize',this._onWindowResize.bind(this),true);}
zoomFactor(){return this._zoomFactor;}
cssToDIP(value){return value*this._zoomFactor;}
dipToCSS(valueDIP){return valueDIP/this._zoomFactor;}
_onWindowResize(){const oldZoomFactor=this._zoomFactor;this._zoomFactor=this._frontendHost.zoomFactor();if(oldZoomFactor!==this._zoomFactor)
this.dispatchEventToListeners(UI.ZoomManager.Events.ZoomChanged,{from:oldZoomFactor,to:this._zoomFactor});}};UI.ZoomManager.Events={ZoomChanged:Symbol('ZoomChanged')};UI.zoomManager;;UI.ShortcutsScreen=class{constructor(){this._sections={};}
static registerShortcuts(){const elementsSection=UI.shortcutsScreen.section(Common.UIString('Elements Panel'));const navigate=UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateUp.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.NavigateDown);elementsSection.addRelatedKeys(navigate,Common.UIString('Navigate elements'));const expandCollapse=UI.ShortcutsScreen.ElementsPanelShortcuts.Expand.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.Collapse);elementsSection.addRelatedKeys(expandCollapse,Common.UIString('Expand/collapse'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.EditAttribute,Common.UIString('Edit attribute'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.HideElement,Common.UIString('Hide element'));elementsSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.ToggleEditAsHTML,Common.UIString('Toggle edit as HTML'));const stylesPaneSection=UI.shortcutsScreen.section(Common.UIString('Styles Pane'));const nextPreviousProperty=UI.ShortcutsScreen.ElementsPanelShortcuts.NextProperty.concat(UI.ShortcutsScreen.ElementsPanelShortcuts.PreviousProperty);stylesPaneSection.addRelatedKeys(nextPreviousProperty,Common.UIString('Next/previous property'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementValue,Common.UIString('Increment value'));stylesPaneSection.addRelatedKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementValue,Common.UIString('Decrement value'));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10,Common.UIString('Increment by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10,Common.UIString('Decrement by %f',10));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100,Common.UIString('Increment by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100,Common.UIString('Decrement by %f',100));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01,Common.UIString('Increment by %f',0.1));stylesPaneSection.addAlternateKeys(UI.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01,Common.UIString('Decrement by %f',0.1));let section=UI.shortcutsScreen.section(Common.UIString('Debugger'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-pause'),Common.UIString('Pause/ Continue'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-over'),Common.UIString('Step over'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-into'),Common.UIString('Step into'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.step-out'),Common.UIString('Step out'));const nextAndPrevFrameKeys=UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.next-call-frame').concat(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.previous-call-frame'));section.addRelatedKeys(nextAndPrevFrameKeys,Common.UIString('Next/previous call frame'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.EvaluateSelectionInConsole,Common.UIString('Evaluate selection in console'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.AddSelectionToWatch,Common.UIString('Add selection to watch'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoint'),Common.UIString('Toggle breakpoint'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoint-enabled'),Common.UIString('Toggle breakpoint enabled'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('debugger.toggle-breakpoints-active'),Common.UIString('Toggle all breakpoints'));section=UI.shortcutsScreen.section(Common.UIString('Text Editor'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.go-to-member'),Common.UIString('Go to member'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion,Common.UIString('Autocompletion'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.go-to-line'),Common.UIString('Go to line'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.jump-to-previous-location'),Common.UIString('Jump to previous editing location'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.jump-to-next-location'),Common.UIString('Jump to next editing location'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.ToggleComment,Common.UIString('Toggle comment'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByOne,Common.UIString('Increment CSS unit by 1'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByOne,Common.UIString('Decrement CSS unit by 1'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByTen,Common.UIString('Increment CSS unit by 10'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByTen,Common.UIString('Decrement CSS unit by 10'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SelectNextOccurrence,Common.UIString('Select next occurrence'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo,Common.UIString('Soft undo'));section.addAlternateKeys(UI.ShortcutsScreen.SourcesPanelShortcuts.GotoMatchingBracket,Common.UIString('Go to matching bracket'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.close-editor-tab'),Common.UIString('Close editor tab'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('sources.switch-file'),Common.UIString('Switch between files with the same name and different extensions.'));section=UI.shortcutsScreen.section(Common.UIString('Performance Panel'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording'),Common.UIString('Start/stop recording'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.record-reload'),Common.UIString('Record page reload'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.save-to-file'),Common.UIString('Save profile'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.load-from-file'),Common.UIString('Load profile'));section.addRelatedKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.jump-to-previous-frame').concat(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.jump-to-next-frame')),Common.UIString('Jump to previous/next frame'));section.addRelatedKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.show-history'),Common.UIString('Pick a recording from history'));section.addRelatedKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.previous-recording').concat(UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.next-recording')),Common.UIString('Show previous/next recording'));section=UI.shortcutsScreen.section(Common.UIString('Memory Panel'));section.addAlternateKeys(UI.shortcutRegistry.shortcutDescriptorsForAction('profiler.heap-toggle-recording'),Common.UIString('Start/stop recording'));section=UI.shortcutsScreen.section(Common.UIString('Layers Panel'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ResetView,Common.UIString('Reset view'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.PanMode,Common.UIString('Switch to pan mode'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.RotateMode,Common.UIString('Switch to rotate mode'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.TogglePanRotate,Common.UIString('Temporarily toggle pan/rotate mode while held'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomIn,Common.UIString('Zoom in'));section.addAlternateKeys(UI.ShortcutsScreen.LayersPanelShortcuts.ZoomOut,Common.UIString('Zoom out'));section.addRelatedKeys(UI.ShortcutsScreen.LayersPanelShortcuts.Up.concat(UI.ShortcutsScreen.LayersPanelShortcuts.Down),Common.UIString('Pan or rotate up/down'));section.addRelatedKeys(UI.ShortcutsScreen.LayersPanelShortcuts.Left.concat(UI.ShortcutsScreen.LayersPanelShortcuts.Right),Common.UIString('Pan or rotate left/right'));}
section(name){let section=this._sections[name];if(!section)
this._sections[name]=section=new UI.ShortcutsSection(name);return section;}
createShortcutsTabView(){const orderedSections=[];for(const section in this._sections)
orderedSections.push(this._sections[section]);function compareSections(a,b){return a.order-b.order;}
orderedSections.sort(compareSections);const widget=new UI.Widget();widget.element.className='settings-tab-container';widget.element.createChild('header').createChild('h3').createTextChild(Common.UIString('Shortcuts'));const scrollPane=widget.element.createChild('div','settings-container-wrapper');const container=scrollPane.createChild('div');container.className='settings-content settings-container';for(let i=0;i<orderedSections.length;++i)
orderedSections[i].renderSection(container);const note=scrollPane.createChild('p','settings-footnote');note.appendChild(UI.createDocumentationLink('iterate/inspect-styles/shortcuts',Common.UIString('Full list of DevTools keyboard shortcuts and gestures')));return widget;}};UI.shortcutsScreen;UI.ShortcutsSection=class{constructor(name){this.name=name;this._lines=([]);this.order=++UI.ShortcutsSection._sequenceNumber;}
addKey(key,description){this._addLine(this._renderKey(key),description);}
addRelatedKeys(keys,description){this._addLine(this._renderSequence(keys,'/'),description);}
addAlternateKeys(keys,description){this._addLine(this._renderSequence(keys,Common.UIString('or')),description);}
_addLine(keyElement,description){this._lines.push({key:keyElement,text:description});}
renderSection(container){const parent=container.createChild('div','settings-block');const headLine=parent.createChild('div','settings-line');headLine.createChild('div','settings-key-cell');headLine.createChild('div','settings-section-title settings-cell').textContent=this.name;for(let i=0;i<this._lines.length;++i){const line=parent.createChild('div','settings-line');const keyCell=line.createChild('div','settings-key-cell');keyCell.appendChild(this._lines[i].key);keyCell.appendChild(this._createSpan('settings-key-delimiter',':'));line.createChild('div','settings-cell').textContent=this._lines[i].text;}}
_renderSequence(sequence,delimiter){const delimiterSpan=this._createSpan('settings-key-delimiter',delimiter);return this._joinNodes(sequence.map(this._renderKey.bind(this)),delimiterSpan);}
_renderKey(key){const keyName=key.name;const plus=this._createSpan('settings-combine-keys','+');return this._joinNodes(keyName.split(' + ').map(this._createSpan.bind(this,'settings-key')),plus);}
_createSpan(className,textContent){const node=createElement('span');node.className=className;node.textContent=textContent;return node;}
_joinNodes(nodes,delimiter){const result=createDocumentFragment();for(let i=0;i<nodes.length;++i){if(i>0)
result.appendChild(delimiter.cloneNode(true));result.appendChild(nodes[i]);}
return result;}};UI.ShortcutsSection._sequenceNumber=0;UI.ShortcutsScreen.ElementsPanelShortcuts={NavigateUp:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],NavigateDown:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],Expand:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right)],Collapse:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left)],EditAttribute:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Enter)],HideElement:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.H)],ToggleEditAsHTML:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.F2)],NextProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab)],PreviousProperty:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Tab,UI.KeyboardShortcut.Modifiers.Shift)],IncrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up)],DecrementValue:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down)],IncrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy10:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Shift)],DecrementBy100:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Shift)],IncrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecrementBy01:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)]};UI.ShortcutsScreen.SourcesPanelShortcuts={SelectNextOccurrence:[UI.KeyboardShortcut.makeDescriptor('d',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],SoftUndo:[UI.KeyboardShortcut.makeDescriptor('u',UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],GotoMatchingBracket:[UI.KeyboardShortcut.makeDescriptor('m',UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleAutocompletion:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Space,UI.KeyboardShortcut.Modifiers.Ctrl)],IncreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByOne:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down,UI.KeyboardShortcut.Modifiers.Alt)],IncreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageUp,UI.KeyboardShortcut.Modifiers.Alt)],DecreaseCSSUnitByTen:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.PageDown,UI.KeyboardShortcut.Modifiers.Alt)],EvaluateSelectionInConsole:[UI.KeyboardShortcut.makeDescriptor('e',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],AddSelectionToWatch:[UI.KeyboardShortcut.makeDescriptor('a',UI.KeyboardShortcut.Modifiers.Shift|UI.KeyboardShortcut.Modifiers.Ctrl)],ToggleComment:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Slash,UI.KeyboardShortcut.Modifiers.CtrlOrMeta)],};UI.ShortcutsScreen.LayersPanelShortcuts={ResetView:[UI.KeyboardShortcut.makeDescriptor('0')],PanMode:[UI.KeyboardShortcut.makeDescriptor('x')],RotateMode:[UI.KeyboardShortcut.makeDescriptor('v')],TogglePanRotate:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Shift)],ZoomIn:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Plus,UI.KeyboardShortcut.Modifiers.Shift),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadPlus)],ZoomOut:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Minus,UI.KeyboardShortcut.Modifiers.Shift),UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.NumpadMinus)],Up:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Up),UI.KeyboardShortcut.makeDescriptor('w')],Down:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Down),UI.KeyboardShortcut.makeDescriptor('s')],Left:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Left),UI.KeyboardShortcut.makeDescriptor('a')],Right:[UI.KeyboardShortcut.makeDescriptor(UI.KeyboardShortcut.Keys.Right),UI.KeyboardShortcut.makeDescriptor('d')]};;UI.Geometry={};UI.Geometry._Eps=1e-5;UI.Geometry.Vector=class{constructor(x,y,z){this.x=x;this.y=y;this.z=z;}
length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}
normalize(){const length=this.length();if(length<=UI.Geometry._Eps)
return;this.x/=length;this.y/=length;this.z/=length;}};UI.Geometry.Point=class{constructor(x,y){this.x=x;this.y=y;}
distanceTo(p){return Math.sqrt(Math.pow(p.x-this.x,2)+Math.pow(p.y-this.y,2));}
projectOn(line){if(line.x===0&&line.y===0)
return new UI.Geometry.Point(0,0);return line.scale((this.x*line.x+this.y*line.y)/(Math.pow(line.x,2)+Math.pow(line.y,2)));}
scale(scalar){return new UI.Geometry.Point(this.x*scalar,this.y*scalar);}
toString(){return Math.round(this.x*100)/100+', '+Math.round(this.y*100)/100;}};UI.Geometry.CubicBezier=class{constructor(point1,point2){this.controlPoints=[point1,point2];}
static parse(text){const keywordValues=UI.Geometry.CubicBezier.KeywordValues;const value=text.toLowerCase().replace(/\s+/g,'');if(Object.keys(keywordValues).indexOf(value)!==-1)
return UI.Geometry.CubicBezier.parse(keywordValues[value]);const bezierRegex=/^cubic-bezier\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/;const match=value.match(bezierRegex);if(match){const control1=new UI.Geometry.Point(parseFloat(match[1]),parseFloat(match[2]));const control2=new UI.Geometry.Point(parseFloat(match[3]),parseFloat(match[4]));return new UI.Geometry.CubicBezier(control1,control2);}
return null;}
evaluateAt(t){function evaluate(v1,v2,t){return 3*(1-t)*(1-t)*t*v1+3*(1-t)*t*t*v2+Math.pow(t,3);}
const x=evaluate(this.controlPoints[0].x,this.controlPoints[1].x,t);const y=evaluate(this.controlPoints[0].y,this.controlPoints[1].y,t);return new UI.Geometry.Point(x,y);}
asCSSText(){const raw='cubic-bezier('+this.controlPoints.join(', ')+')';const keywordValues=UI.Geometry.CubicBezier.KeywordValues;for(const keyword in keywordValues){if(raw===keywordValues[keyword])
return keyword;}
return raw;}};UI.Geometry.CubicBezier.Regex=/((cubic-bezier\([^)]+\))|\b(linear|ease-in-out|ease-in|ease-out|ease)\b)/g;UI.Geometry.CubicBezier.KeywordValues={'linear':'cubic-bezier(0, 0, 1, 1)','ease':'cubic-bezier(0.25, 0.1, 0.25, 1)','ease-in':'cubic-bezier(0.42, 0, 1, 1)','ease-in-out':'cubic-bezier(0.42, 0, 0.58, 1)','ease-out':'cubic-bezier(0, 0, 0.58, 1)'};UI.Geometry.EulerAngles=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;}
static fromRotationMatrix(rotationMatrix){const beta=Math.atan2(rotationMatrix.m23,rotationMatrix.m33);const gamma=Math.atan2(-rotationMatrix.m13,Math.sqrt(rotationMatrix.m11*rotationMatrix.m11+rotationMatrix.m12*rotationMatrix.m12));const alpha=Math.atan2(rotationMatrix.m12,rotationMatrix.m11);return new UI.Geometry.EulerAngles(UI.Geometry.radiansToDegrees(alpha),UI.Geometry.radiansToDegrees(beta),UI.Geometry.radiansToDegrees(gamma));}
toRotate3DString(){const gammaAxisY=-Math.sin(UI.Geometry.degreesToRadians(this.beta));const gammaAxisZ=Math.cos(UI.Geometry.degreesToRadians(this.beta));const axis={alpha:[0,1,0],beta:[-1,0,0],gamma:[0,gammaAxisY,gammaAxisZ]};return'rotate3d('+axis.alpha.join(',')+','+this.alpha+'deg) '+'rotate3d('+axis.beta.join(',')+','+this.beta+'deg) '+'rotate3d('+axis.gamma.join(',')+','+this.gamma+'deg)';}};UI.Geometry.scalarProduct=function(u,v){return u.x*v.x+u.y*v.y+u.z*v.z;};UI.Geometry.crossProduct=function(u,v){const x=u.y*v.z-u.z*v.y;const y=u.z*v.x-u.x*v.z;const z=u.x*v.y-u.y*v.x;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.subtract=function(u,v){const x=u.x-v.x;const y=u.y-v.y;const z=u.z-v.z;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.multiplyVectorByMatrixAndNormalize=function(v,m){const t=v.x*m.m14+v.y*m.m24+v.z*m.m34+m.m44;const x=(v.x*m.m11+v.y*m.m21+v.z*m.m31+m.m41)/t;const y=(v.x*m.m12+v.y*m.m22+v.z*m.m32+m.m42)/t;const z=(v.x*m.m13+v.y*m.m23+v.z*m.m33+m.m43)/t;return new UI.Geometry.Vector(x,y,z);};UI.Geometry.calculateAngle=function(u,v){const uLength=u.length();const vLength=v.length();if(uLength<=UI.Geometry._Eps||vLength<=UI.Geometry._Eps)
return 0;const cos=UI.Geometry.scalarProduct(u,v)/uLength/vLength;if(Math.abs(cos)>1)
return 0;return UI.Geometry.radiansToDegrees(Math.acos(cos));};UI.Geometry.degreesToRadians=function(deg){return deg*Math.PI/180;};UI.Geometry.radiansToDegrees=function(rad){return rad*180/Math.PI;};UI.Geometry.boundsForTransformedPoints=function(matrix,points,aggregateBounds){if(!aggregateBounds)
aggregateBounds={minX:Infinity,maxX:-Infinity,minY:Infinity,maxY:-Infinity};if(points.length%3)
console.assert('Invalid size of points array');for(let p=0;p<points.length;p+=3){let vector=new UI.Geometry.Vector(points[p],points[p+1],points[p+2]);vector=UI.Geometry.multiplyVectorByMatrixAndNormalize(vector,matrix);aggregateBounds.minX=Math.min(aggregateBounds.minX,vector.x);aggregateBounds.maxX=Math.max(aggregateBounds.maxX,vector.x);aggregateBounds.minY=Math.min(aggregateBounds.minY,vector.y);aggregateBounds.maxY=Math.max(aggregateBounds.maxY,vector.y);}
return aggregateBounds;};UI.Size=class{constructor(width,height){this.width=width;this.height=height;}
clipTo(size){if(!size)
return this;return new UI.Size(Math.min(this.width,size.width),Math.min(this.height,size.height));}
scale(scale){return new UI.Size(this.width*scale,this.height*scale);}};UI.Size.prototype.isEqual=function(size){return!!size&&this.width===size.width&&this.height===size.height;};UI.Size.prototype.widthToMax=function(size){return new UI.Size(Math.max(this.width,(typeof size==='number'?size:size.width)),this.height);};UI.Size.prototype.addWidth=function(size){return new UI.Size(this.width+(typeof size==='number'?size:size.width),this.height);};UI.Size.prototype.heightToMax=function(size){return new UI.Size(this.width,Math.max(this.height,(typeof size==='number'?size:size.height)));};UI.Size.prototype.addHeight=function(size){return new UI.Size(this.width,this.height+(typeof size==='number'?size:size.height));};UI.Insets=class{constructor(left,top,right,bottom){this.left=left;this.top=top;this.right=right;this.bottom=bottom;}
isEqual(insets){return!!insets&&this.left===insets.left&&this.top===insets.top&&this.right===insets.right&&this.bottom===insets.bottom;}};UI.Rect=class{constructor(left,top,width,height){this.left=left;this.top=top;this.width=width;this.height=height;}
isEqual(rect){return!!rect&&this.left===rect.left&&this.top===rect.top&&this.width===rect.width&&this.height===rect.height;}
scale(scale){return new UI.Rect(this.left*scale,this.top*scale,this.width*scale,this.height*scale);}
size(){return new UI.Size(this.width,this.height);}
relativeTo(origin){return new UI.Rect(this.left-origin.left,this.top-origin.top,this.width,this.height);}
rebaseTo(origin){return new UI.Rect(this.left+origin.left,this.top+origin.top,this.width,this.height);}};UI.Constraints=class{constructor(minimum,preferred){this.minimum=minimum||new UI.Size(0,0);this.preferred=preferred||this.minimum;if(this.minimum.width>this.preferred.width||this.minimum.height>this.preferred.height)
throw new Error('Minimum size is greater than preferred.');}};UI.Constraints.prototype.isEqual=function(constraints){return!!constraints&&this.minimum.isEqual(constraints.minimum)&&this.preferred.isEqual(constraints.preferred);};UI.Constraints.prototype.widthToMax=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.widthToMax(value),this.preferred.widthToMax(value));return new UI.Constraints(this.minimum.widthToMax(value.minimum),this.preferred.widthToMax(value.preferred));};UI.Constraints.prototype.addWidth=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.addWidth(value),this.preferred.addWidth(value));return new UI.Constraints(this.minimum.addWidth(value.minimum),this.preferred.addWidth(value.preferred));};UI.Constraints.prototype.heightToMax=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.heightToMax(value),this.preferred.heightToMax(value));return new UI.Constraints(this.minimum.heightToMax(value.minimum),this.preferred.heightToMax(value.preferred));};UI.Constraints.prototype.addHeight=function(value){if(typeof value==='number')
return new UI.Constraints(this.minimum.addHeight(value),this.preferred.addHeight(value));return new UI.Constraints(this.minimum.addHeight(value.minimum),this.preferred.addHeight(value.preferred));};;UI.XLink=class extends UI.XElement{static create(url,linkText,className,preventClick){if(!linkText)
linkText=url;className=className||'';return(UI.Fragment.cached`
        <x-link href='${url}' class='${className} devtools-link' ${preventClick ? 'no-click' : ''}
        >${linkText.trimMiddle(UI.MaxLengthForDisplayedURLs)}</x-link>`).element();}
constructor(){super();this.style.setProperty('display','inline');UI.ARIAUtils.markAsLink(this);this.tabIndex=0;this.setAttribute('target','_blank');this._href=null;this._clickable=true;this._onClick=event=>{event.consume(true);InspectorFrontendHost.openInNewTab((this._href));};this._onKeyDown=event=>{if(event.key!==' '&&!isEnterKey(event))
return;event.consume(true);InspectorFrontendHost.openInNewTab((this._href));};}
static get observedAttributes(){return UI.XElement.observedAttributes.concat(['href','no-click']);}
attributeChangedCallback(attr,oldValue,newValue){if(attr==='no-click'){this._clickable=!newValue;this._updateClick();return;}
if(attr==='href'){let href=newValue;if(newValue.trim().toLowerCase().startsWith('javascript:'))
href=null;if(Common.ParsedURL.isRelativeURL(newValue))
href=null;this._href=href;this.title=newValue;this._updateClick();return;}
super.attributeChangedCallback(attr,oldValue,newValue);}
_updateClick(){if(this._href!==null&&this._clickable){this.addEventListener('click',this._onClick,false);this.addEventListener('keydown',this._onKeyDown,false);this.style.setProperty('cursor','pointer');}else{this.removeEventListener('click',this._onClick,false);this.removeEventListener('keydown',this._onKeyDown,false);this.style.removeProperty('cursor');}}};UI.XLink.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){let targetNode=(target);while(targetNode&&!(targetNode instanceof UI.XLink))
targetNode=targetNode.parentNodeOrShadowHost();if(!targetNode||!targetNode._href)
return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(targetNode._href));contextMenu.revealSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(targetNode._href));}};self.customElements.define('x-link',UI.XLink);;UI.XWidget=class extends UI.XElement{constructor(){super();this.style.setProperty('display','flex');this.style.setProperty('flex-direction','column');this.style.setProperty('align-items','stretch');this.style.setProperty('justify-content','flex-start');this.style.setProperty('contain','layout style');this._visible=false;this._shadowRoot;this._defaultFocusedElement=null;this._elementsToRestoreScrollPositionsFor=[];this._onShownCallback;this._onHiddenCallback;this._onResizedCallback;if(!UI.XWidget._observer){UI.XWidget._observer=new ResizeObserver(entries=>{for(const entry of entries){if(entry.target._visible&&entry.target._onResizedCallback)
entry.target._onResizedCallback.call(null);}});}
UI.XWidget._observer.observe(this);this.setElementsToRestoreScrollPositionsFor([this]);}
static focusWidgetForNode(node){node=node&&node.parentNodeOrShadowHost();let widget=null;while(node){if(node instanceof UI.XWidget){if(widget)
node._defaultFocusedElement=widget;widget=node;}
node=node.parentNodeOrShadowHost();}}
isShowing(){return this._visible;}
registerRequiredCSS(cssFile){UI.appendStyle(this._shadowRoot||this,cssFile);}
setOnShown(callback){this._onShownCallback=callback;}
setOnHidden(callback){this._onHiddenCallback=callback;}
setOnResized(callback){this._onResizedCallback=callback;}
setElementsToRestoreScrollPositionsFor(elements){for(const element of this._elementsToRestoreScrollPositionsFor)
element.removeEventListener('scroll',UI.XWidget._storeScrollPosition,{passive:true,capture:false});this._elementsToRestoreScrollPositionsFor=elements;for(const element of this._elementsToRestoreScrollPositionsFor)
element.addEventListener('scroll',UI.XWidget._storeScrollPosition,{passive:true,capture:false});}
restoreScrollPositions(){for(const element of this._elementsToRestoreScrollPositionsFor){if(element._scrollTop)
element.scrollTop=element._scrollTop;if(element._scrollLeft)
element.scrollLeft=element._scrollLeft;}}
static _storeScrollPosition(event){const element=event.currentTarget;element._scrollTop=element.scrollTop;element._scrollLeft=element.scrollLeft;}
setDefaultFocusedElement(element){if(element&&!this.isSelfOrAncestor(element))
throw new Error('Default focus must be descendant');this._defaultFocusedElement=element;}
focus(){if(!this._visible)
return;let element;if(this._defaultFocusedElement&&this.isSelfOrAncestor(this._defaultFocusedElement)){element=this._defaultFocusedElement;}else if(this.tabIndex!==-1){element=this;}else{let child=this.traverseNextNode(this);while(child){if((child instanceof UI.XWidget)&&child._visible){element=child;break;}
child=child.traverseNextNode(this);}}
if(!element||element.hasFocus())
return;if(element===this)
HTMLElement.prototype.focus.call(this);else
element.focus();}
connectedCallback(){this._visible=true;this.restoreScrollPositions();if(this._onShownCallback)
this._onShownCallback.call(null);}
disconnectedCallback(){this._visible=false;if(this._onHiddenCallback)
this._onHiddenCallback.call(null);}};self.customElements.define('x-widget',UI.XWidget);;self['Protocol']=self['Protocol']||{};Protocol.Error=Symbol('Protocol.Error');Protocol.InspectorBackend=class{constructor(){this._agentPrototypes={};this._dispatcherPrototypes={};this._initialized=false;}
static reportProtocolError(error,messageObject){console.error(error+': '+JSON.stringify(messageObject));}
isInitialized(){return this._initialized;}
_addAgentGetterMethodToProtocolTargetPrototype(domain){let upperCaseLength=0;while(upperCaseLength<domain.length&&domain[upperCaseLength].toLowerCase()!==domain[upperCaseLength])
++upperCaseLength;const methodName=domain.substr(0,upperCaseLength).toLowerCase()+domain.slice(upperCaseLength)+'Agent';function agentGetter(){return this._agents[domain];}
Protocol.TargetBase.prototype[methodName]=agentGetter;function registerDispatcher(dispatcher){this.registerDispatcher(domain,dispatcher);}
Protocol.TargetBase.prototype['register'+domain+'Dispatcher']=registerDispatcher;}
_agentPrototype(domain){if(!this._agentPrototypes[domain]){this._agentPrototypes[domain]=new Protocol.InspectorBackend._AgentPrototype(domain);this._addAgentGetterMethodToProtocolTargetPrototype(domain);}
return this._agentPrototypes[domain];}
_dispatcherPrototype(domain){if(!this._dispatcherPrototypes[domain])
this._dispatcherPrototypes[domain]=new Protocol.InspectorBackend._DispatcherPrototype();return this._dispatcherPrototypes[domain];}
registerCommand(method,signature,replyArgs,hasErrorData){const domainAndMethod=method.split('.');this._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod[1],signature,replyArgs,hasErrorData);this._initialized=true;}
registerEnum(type,values){const domainAndName=type.split('.');const domain=domainAndName[0];if(!Protocol[domain])
Protocol[domain]={};Protocol[domain][domainAndName[1]]=values;this._initialized=true;}
registerEvent(eventName,params){const domain=eventName.split('.')[0];this._dispatcherPrototype(domain).registerEvent(eventName,params);this._initialized=true;}
wrapClientCallback(clientCallback,errorPrefix,constructor,defaultValue){function callbackWrapper(error,value){if(error){console.error(errorPrefix+error);clientCallback(defaultValue);return;}
if(constructor)
clientCallback(new constructor(value));else
clientCallback(value);}
return callbackWrapper;}};Protocol.InspectorBackend._ConnectionClosedErrorCode=-32000;Protocol.InspectorBackend.DevToolsStubErrorCode=-32015;Protocol.inspectorBackend=new Protocol.InspectorBackend();Protocol.InspectorBackend.Connection=function(){};Protocol.InspectorBackend.Connection.prototype={sendMessage(message){},disconnect(){},};Protocol.InspectorBackend.Connection.Params;Protocol.InspectorBackend.Connection.Factory;Protocol.TargetBase=class extends Common.Object{constructor(connectionFactory){super();this._connection=connectionFactory({onMessage:this._onMessage.bind(this),onDisconnect:this._onDisconnect.bind(this)});this._lastMessageId=1;this._pendingResponsesCount=0;this._agents={};this._dispatchers={};this._callbacks={};this._initialize(Protocol.inspectorBackend._agentPrototypes,Protocol.inspectorBackend._dispatcherPrototypes);this._domainToLogger=new Map();if(!Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches){Protocol.InspectorBackend.deprecatedRunAfterPendingDispatches=this._deprecatedRunAfterPendingDispatches.bind(this);}
if(!Protocol.InspectorBackend.sendRawMessageForTesting)
Protocol.InspectorBackend.sendRawMessageForTesting=this._sendRawMessageForTesting.bind(this);}
_initialize(agentPrototypes,dispatcherPrototypes){for(const domain in agentPrototypes){this._agents[domain]=Object.create(agentPrototypes[domain]);this._agents[domain].setTarget(this);}
for(const domain in dispatcherPrototypes){this._dispatchers[domain]=Object.create(dispatcherPrototypes[domain]);this._dispatchers[domain].initialize();}}
_nextMessageId(){return this._lastMessageId++;}
_agent(domain){return this._agents[domain];}
_wrapCallbackAndSendMessageObject(domain,method,params,callback){if(!this._connection){if(callback)
this._dispatchConnectionErrorResponse(domain,method,callback);return;}
const messageObject={};const messageId=this._nextMessageId();messageObject.id=messageId;messageObject.method=method;if(params)
messageObject.params=params;const wrappedCallback=this._wrap(callback,domain,method);const message=JSON.stringify(messageObject);if(Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages)
this._dumpProtocolMessage('frontend: '+message,'[FE] '+domain);if(this.hasEventListeners(Protocol.TargetBase.Events.MessageSent)){this.dispatchEventToListeners(Protocol.TargetBase.Events.MessageSent,{domain,method,params:JSON.parse(JSON.stringify(params)),id:messageId});}
this._connection.sendMessage(message);++this._pendingResponsesCount;this._callbacks[messageId]=wrappedCallback;}
_wrap(callback,domain,method){if(!callback)
callback=function(){};callback.methodName=method;callback.domain=domain;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
callback.sendRequestTime=Date.now();return callback;}
_sendRawMessageForTesting(method,params,callback){const domain=method.split('.')[0];this._wrapCallbackAndSendMessageObject(domain,method,params,callback);}
_onMessage(message){if(Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages){this._dumpProtocolMessage('backend: '+((typeof message==='string')?message:JSON.stringify(message)),'Backend');}
if(this.hasEventListeners(Protocol.TargetBase.Events.MessageReceived)){this.dispatchEventToListeners(Protocol.TargetBase.Events.MessageReceived,{message:JSON.parse((typeof message==='string')?message:JSON.stringify(message)),});}
const messageObject=((typeof message==='string')?JSON.parse(message):message);if('id'in messageObject){const callback=this._callbacks[messageObject.id];if(!callback){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message with wrong id',messageObject);return;}
const timingLabel='time-stats: '+callback.methodName;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
Protocol.InspectorBackend._timeLogger.time(timingLabel);this._agent(callback.domain).dispatchResponse(messageObject,callback.methodName,callback);--this._pendingResponsesCount;delete this._callbacks[messageObject.id];if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);if(this._scripts&&!this._pendingResponsesCount)
this._deprecatedRunAfterPendingDispatches();}else{if(!('method'in messageObject)){Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message without method',messageObject);return;}
const method=messageObject.method.split('.');const domainName=method[0];if(!(domainName in this._dispatchers)){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: the message ${messageObject.method} is for non-existing domain '${domainName}'`,messageObject);return;}
this._dispatchers[domainName].dispatch(method[1],messageObject);}}
registerDispatcher(domain,dispatcher){if(!this._dispatchers[domain])
return;this._dispatchers[domain].addDomainDispatcher(dispatcher);}
_deprecatedRunAfterPendingDispatches(script){if(!this._scripts)
this._scripts=[];if(script)
this._scripts.push(script);setTimeout(function(){if(!this._pendingResponsesCount)
this._executeAfterPendingDispatches();else
this._deprecatedRunAfterPendingDispatches();}.bind(this),0);}
_executeAfterPendingDispatches(){if(!this._pendingResponsesCount){const scripts=this._scripts;this._scripts=[];for(let id=0;id<scripts.length;++id)
scripts[id].call(this);}}
_dumpProtocolMessage(message,context){if(!this._domainToLogger.get(context))
this._domainToLogger.set(context,console.context?console.context(context):console);const logger=this._domainToLogger.get(context);logger.log(message);}
_onDisconnect(reason){this._connection=null;this._runPendingCallbacks();this.dispose();}
dispose(){}
isDisposed(){return!this._connection;}
_runPendingCallbacks(){const keys=Object.keys(this._callbacks).map(function(num){return parseInt(num,10);});for(let i=0;i<keys.length;++i){const callback=this._callbacks[keys[i]];this._dispatchConnectionErrorResponse(callback.domain,callback.methodName,callback);}
this._callbacks={};}
_dispatchConnectionErrorResponse(domain,methodName,callback){const error={message:'Connection is closed, can\'t dispatch pending '+methodName,code:Protocol.InspectorBackend._ConnectionClosedErrorCode,data:null};const messageObject={error:error};setTimeout(Protocol.InspectorBackend._AgentPrototype.prototype.dispatchResponse.bind(this._agent(domain),messageObject,methodName,callback),0);}};Protocol.TargetBase.Events={MessageSent:Symbol('MessageSent'),MessageReceived:Symbol('MessageReceived')};Protocol.InspectorBackend._AgentPrototype=class{constructor(domain){this._replyArgs={};this._hasErrorData={};this._domain=domain;}
setTarget(target){this._target=target;}
registerCommand(methodName,signature,replyArgs,hasErrorData){const domainAndMethod=this._domain+'.'+methodName;function sendMessagePromise(vararg){const params=Array.prototype.slice.call(arguments);return Protocol.InspectorBackend._AgentPrototype.prototype._sendMessageToBackendPromise.call(this,domainAndMethod,signature,params);}
this[methodName]=sendMessagePromise;function invoke(request){return this._invoke(domainAndMethod,request);}
this['invoke_'+methodName]=invoke;this._replyArgs[domainAndMethod]=replyArgs;if(hasErrorData)
this._hasErrorData[domainAndMethod]=true;}
_prepareParameters(method,signature,args,errorCallback){const params={};let hasParams=false;for(const param of signature){const paramName=param['name'];const typeName=param['type'];const optionalFlag=param['optional'];if(!args.length&&!optionalFlag){errorCallback(`Protocol Error: Invalid number of arguments for method '${method}' call. `+`It must have the following arguments ${JSON.stringify(signature)}'.`);return null;}
const value=args.shift();if(optionalFlag&&typeof value==='undefined')
continue;if(typeof value!==typeName){errorCallback(`Protocol Error: Invalid type of argument '${paramName}' for method '${method}' call. `+`It must be '${typeName}' but it is '${typeof value}'.`);return null;}
params[paramName]=value;hasParams=true;}
if(args.length){errorCallback(`Protocol Error: Extra ${args.length} arguments in a call to method '${method}'.`);return null;}
return hasParams?params:null;}
_sendMessageToBackendPromise(method,signature,args){let errorMessage;function onError(message){console.error(message);errorMessage=message;}
const params=this._prepareParameters(method,signature,args,onError);if(errorMessage)
return Promise.resolve(null);return new Promise(resolve=>{this._target._wrapCallbackAndSendMessageObject(this._domain,method,params,(error,result)=>{if(error){resolve(null);return;}
const args=this._replyArgs[method];resolve(result&&args.length?result[args[0]]:undefined);});});}
_invoke(method,request){return new Promise(fulfill=>{this._target._wrapCallbackAndSendMessageObject(this._domain,method,request,(error,result)=>{if(!result)
result={};if(error)
result[Protocol.Error]=error.message;fulfill(result);});});}
dispatchResponse(messageObject,methodName,callback){if(messageObject.error&&messageObject.error.code!==Protocol.InspectorBackend._ConnectionClosedErrorCode&&messageObject.error.code!==Protocol.InspectorBackend.DevToolsStubErrorCode&&!Protocol.InspectorBackend.Options.suppressRequestErrors){const id=Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages?' with id = '+messageObject.id:'';console.error('Request '+methodName+id+' failed. '+JSON.stringify(messageObject.error));}
callback(messageObject.error,messageObject.result);}};Protocol.InspectorBackend._DispatcherPrototype=class{constructor(){this._eventArgs={};}
registerEvent(eventName,params){this._eventArgs[eventName]=params;}
initialize(){this._dispatchers=[];}
addDomainDispatcher(dispatcher){this._dispatchers.push(dispatcher);}
dispatch(functionName,messageObject){if(!this._dispatchers.length)
return;if(!this._eventArgs[messageObject.method]){Protocol.InspectorBackend.reportProtocolError(`Protocol Error: Attempted to dispatch an unspecified method '${messageObject.method}'`,messageObject);return;}
const params=[];if(messageObject.params){const paramNames=this._eventArgs[messageObject.method];for(let i=0;i<paramNames.length;++i)
params.push(messageObject.params[paramNames[i]]);}
const timingLabel='time-stats: '+messageObject.method;if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
Protocol.InspectorBackend._timeLogger.time(timingLabel);for(let index=0;index<this._dispatchers.length;++index){const dispatcher=this._dispatchers[index];if(functionName in dispatcher)
dispatcher[functionName].apply(dispatcher,params);}
if(Protocol.InspectorBackend.Options.dumpInspectorTimeStats)
Protocol.InspectorBackend._timeLogger.timeEnd(timingLabel);}};Protocol.InspectorBackend.Options={dumpInspectorTimeStats:false,dumpInspectorProtocolMessages:false,suppressRequestErrors:false};Protocol.InspectorBackend._timeLogger=console.context?console.context('Protocol timing'):console;;Protocol.inspectorBackend.registerEnum("Accessibility.AXValueType",{Boolean:"boolean",Tristate:"tristate",BooleanOrUndefined:"booleanOrUndefined",Idref:"idref",IdrefList:"idrefList",Integer:"integer",Node:"node",NodeList:"nodeList",Number:"number",String:"string",ComputedString:"computedString",Token:"token",TokenList:"tokenList",DomRelation:"domRelation",Role:"role",InternalRole:"internalRole",ValueUndefined:"valueUndefined"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueSourceType",{Attribute:"attribute",Implicit:"implicit",Style:"style",Contents:"contents",Placeholder:"placeholder",RelatedElement:"relatedElement"});Protocol.inspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType",{Figcaption:"figcaption",Label:"label",Labelfor:"labelfor",Labelwrapped:"labelwrapped",Legend:"legend",Tablecaption:"tablecaption",Title:"title",Other:"other"});Protocol.inspectorBackend.registerEnum("Accessibility.AXPropertyName",{Busy:"busy",Disabled:"disabled",Hidden:"hidden",HiddenRoot:"hiddenRoot",Invalid:"invalid",Keyshortcuts:"keyshortcuts",Roledescription:"roledescription",Live:"live",Atomic:"atomic",Relevant:"relevant",Root:"root",Autocomplete:"autocomplete",Haspopup:"haspopup",Level:"level",Multiselectable:"multiselectable",Orientation:"orientation",Multiline:"multiline",Readonly:"readonly",Required:"required",Valuemin:"valuemin",Valuemax:"valuemax",Valuetext:"valuetext",Checked:"checked",Expanded:"expanded",Modal:"modal",Pressed:"pressed",Selected:"selected",Activedescendant:"activedescendant",Controls:"controls",Describedby:"describedby",Details:"details",Errormessage:"errormessage",Flowto:"flowto",Labelledby:"labelledby",Owns:"owns"});Protocol.inspectorBackend.registerCommand("Accessibility.getPartialAXTree",[{"name":"nodeId","type":"number","optional":false},{"name":"fetchRelatives","type":"boolean","optional":true}],["nodes"],false);Protocol.inspectorBackend.registerEnum("Animation.AnimationType",{CSSTransition:"CSSTransition",CSSAnimation:"CSSAnimation",WebAnimation:"WebAnimation"});Protocol.inspectorBackend.registerEvent("Animation.animationCanceled",["id"]);Protocol.inspectorBackend.registerEvent("Animation.animationCreated",["id"]);Protocol.inspectorBackend.registerEvent("Animation.animationStarted",["animation"]);Protocol.inspectorBackend.registerCommand("Animation.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Animation.getCurrentTime",[{"name":"id","type":"string","optional":false}],["currentTime"],false);Protocol.inspectorBackend.registerCommand("Animation.getPlaybackRate",[],["playbackRate"],false);Protocol.inspectorBackend.registerCommand("Animation.releaseAnimations",[{"name":"animations","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.resolveAnimation",[{"name":"animationId","type":"string","optional":false}],["remoteObject"],false);Protocol.inspectorBackend.registerCommand("Animation.seekAnimations",[{"name":"animations","type":"object","optional":false},{"name":"currentTime","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setPaused",[{"name":"animations","type":"object","optional":false},{"name":"paused","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setPlaybackRate",[{"name":"playbackRate","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Animation.setTiming",[{"name":"animationId","type":"string","optional":false},{"name":"duration","type":"number","optional":false},{"name":"delay","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated",["frameId","manifestURL","status"]);Protocol.inspectorBackend.registerEvent("ApplicationCache.networkStateUpdated",["isNowOnline"]);Protocol.inspectorBackend.registerCommand("ApplicationCache.enable",[],[],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame",[{"name":"frameId","type":"string","optional":false}],["applicationCache"],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests",[],["frameIds"],false);Protocol.inspectorBackend.registerCommand("ApplicationCache.getManifestForFrame",[{"name":"frameId","type":"string","optional":false}],["manifestURL"],false);Protocol.inspectorBackend.registerCommand("Audits.getEncodedResponse",[{"name":"requestId","type":"string","optional":false},{"name":"encoding","type":"string","optional":false},{"name":"quality","type":"number","optional":true},{"name":"sizeOnly","type":"boolean","optional":true}],["body","originalSize","encodedSize"],false);Protocol.inspectorBackend.registerEnum("Browser.WindowState",{Normal:"normal",Minimized:"minimized",Maximized:"maximized",Fullscreen:"fullscreen"});Protocol.inspectorBackend.registerCommand("Browser.close",[],[],false);Protocol.inspectorBackend.registerCommand("Browser.getVersion",[],["protocolVersion","product","revision","userAgent","jsVersion"],false);Protocol.inspectorBackend.registerCommand("Browser.getBrowserCommandLine",[],["arguments"],false);Protocol.inspectorBackend.registerCommand("Browser.getHistograms",[{"name":"query","type":"string","optional":true}],["histograms"],false);Protocol.inspectorBackend.registerCommand("Browser.getHistogram",[{"name":"name","type":"string","optional":false}],["histogram"],false);Protocol.inspectorBackend.registerCommand("Browser.getWindowBounds",[{"name":"windowId","type":"number","optional":false}],["bounds"],false);Protocol.inspectorBackend.registerCommand("Browser.getWindowForTarget",[{"name":"targetId","type":"string","optional":false}],["windowId","bounds"],false);Protocol.inspectorBackend.registerCommand("Browser.setWindowBounds",[{"name":"windowId","type":"number","optional":false},{"name":"bounds","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("CSS.StyleSheetOrigin",{Injected:"injected",UserAgent:"user-agent",Inspector:"inspector",Regular:"regular"});Protocol.inspectorBackend.registerEnum("CSS.CSSMediaSource",{MediaRule:"mediaRule",ImportRule:"importRule",LinkedSheet:"linkedSheet",InlineSheet:"inlineSheet"});Protocol.inspectorBackend.registerEvent("CSS.fontsUpdated",["font"]);Protocol.inspectorBackend.registerEvent("CSS.mediaQueryResultChanged",[]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetAdded",["header"]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetChanged",["styleSheetId"]);Protocol.inspectorBackend.registerEvent("CSS.styleSheetRemoved",["styleSheetId"]);Protocol.inspectorBackend.registerCommand("CSS.addRule",[{"name":"styleSheetId","type":"string","optional":false},{"name":"ruleText","type":"string","optional":false},{"name":"location","type":"object","optional":false}],["rule"],false);Protocol.inspectorBackend.registerCommand("CSS.collectClassNames",[{"name":"styleSheetId","type":"string","optional":false}],["classNames"],false);Protocol.inspectorBackend.registerCommand("CSS.createStyleSheet",[{"name":"frameId","type":"string","optional":false}],["styleSheetId"],false);Protocol.inspectorBackend.registerCommand("CSS.disable",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.enable",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.forcePseudoState",[{"name":"nodeId","type":"number","optional":false},{"name":"forcedPseudoClasses","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CSS.getBackgroundColors",[{"name":"nodeId","type":"number","optional":false}],["backgroundColors","computedFontSize","computedFontWeight","computedBodyFontSize"],false);Protocol.inspectorBackend.registerCommand("CSS.getComputedStyleForNode",[{"name":"nodeId","type":"number","optional":false}],["computedStyle"],false);Protocol.inspectorBackend.registerCommand("CSS.getInlineStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle"],false);Protocol.inspectorBackend.registerCommand("CSS.getMatchedStylesForNode",[{"name":"nodeId","type":"number","optional":false}],["inlineStyle","attributesStyle","matchedCSSRules","pseudoElements","inherited","cssKeyframesRules"],false);Protocol.inspectorBackend.registerCommand("CSS.getMediaQueries",[],["medias"],false);Protocol.inspectorBackend.registerCommand("CSS.getPlatformFontsForNode",[{"name":"nodeId","type":"number","optional":false}],["fonts"],false);Protocol.inspectorBackend.registerCommand("CSS.getStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false}],["text"],false);Protocol.inspectorBackend.registerCommand("CSS.setEffectivePropertyValueForNode",[{"name":"nodeId","type":"number","optional":false},{"name":"propertyName","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CSS.setKeyframeKey",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"keyText","type":"string","optional":false}],["keyText"],false);Protocol.inspectorBackend.registerCommand("CSS.setMediaText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"text","type":"string","optional":false}],["media"],false);Protocol.inspectorBackend.registerCommand("CSS.setRuleSelector",[{"name":"styleSheetId","type":"string","optional":false},{"name":"range","type":"object","optional":false},{"name":"selector","type":"string","optional":false}],["selectorList"],false);Protocol.inspectorBackend.registerCommand("CSS.setStyleSheetText",[{"name":"styleSheetId","type":"string","optional":false},{"name":"text","type":"string","optional":false}],["sourceMapURL"],false);Protocol.inspectorBackend.registerCommand("CSS.setStyleTexts",[{"name":"edits","type":"object","optional":false}],["styles"],false);Protocol.inspectorBackend.registerCommand("CSS.startRuleUsageTracking",[],[],false);Protocol.inspectorBackend.registerCommand("CSS.stopRuleUsageTracking",[],["ruleUsage"],false);Protocol.inspectorBackend.registerCommand("CSS.takeCoverageDelta",[],["coverage"],false);Protocol.inspectorBackend.registerCommand("CacheStorage.deleteCache",[{"name":"cacheId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CacheStorage.deleteEntry",[{"name":"cacheId","type":"string","optional":false},{"name":"request","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestCacheNames",[{"name":"securityOrigin","type":"string","optional":false}],["caches"],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestCachedResponse",[{"name":"cacheId","type":"string","optional":false},{"name":"requestURL","type":"string","optional":false}],["response"],false);Protocol.inspectorBackend.registerCommand("CacheStorage.requestEntries",[{"name":"cacheId","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false}],["cacheDataEntries","hasMore"],false);Protocol.inspectorBackend.registerEnum("DOM.PseudoType",{FirstLine:"first-line",FirstLetter:"first-letter",Before:"before",After:"after",Backdrop:"backdrop",Selection:"selection",FirstLineInherited:"first-line-inherited",Scrollbar:"scrollbar",ScrollbarThumb:"scrollbar-thumb",ScrollbarButton:"scrollbar-button",ScrollbarTrack:"scrollbar-track",ScrollbarTrackPiece:"scrollbar-track-piece",ScrollbarCorner:"scrollbar-corner",Resizer:"resizer",InputListButton:"input-list-button"});Protocol.inspectorBackend.registerEnum("DOM.ShadowRootType",{UserAgent:"user-agent",Open:"open",Closed:"closed"});Protocol.inspectorBackend.registerEvent("DOM.attributeModified",["nodeId","name","value"]);Protocol.inspectorBackend.registerEvent("DOM.attributeRemoved",["nodeId","name"]);Protocol.inspectorBackend.registerEvent("DOM.characterDataModified",["nodeId","characterData"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeCountUpdated",["nodeId","childNodeCount"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeInserted",["parentNodeId","previousNodeId","node"]);Protocol.inspectorBackend.registerEvent("DOM.childNodeRemoved",["parentNodeId","nodeId"]);Protocol.inspectorBackend.registerEvent("DOM.distributedNodesUpdated",["insertionPointId","distributedNodes"]);Protocol.inspectorBackend.registerEvent("DOM.documentUpdated",[]);Protocol.inspectorBackend.registerEvent("DOM.inlineStyleInvalidated",["nodeIds"]);Protocol.inspectorBackend.registerEvent("DOM.pseudoElementAdded",["parentId","pseudoElement"]);Protocol.inspectorBackend.registerEvent("DOM.pseudoElementRemoved",["parentId","pseudoElementId"]);Protocol.inspectorBackend.registerEvent("DOM.setChildNodes",["parentId","nodes"]);Protocol.inspectorBackend.registerEvent("DOM.shadowRootPopped",["hostId","rootId"]);Protocol.inspectorBackend.registerEvent("DOM.shadowRootPushed",["hostId","root"]);Protocol.inspectorBackend.registerCommand("DOM.collectClassNamesFromSubtree",[{"name":"nodeId","type":"number","optional":false}],["classNames"],false);Protocol.inspectorBackend.registerCommand("DOM.copyTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.describeNode",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["node"],false);Protocol.inspectorBackend.registerCommand("DOM.disable",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.discardSearchResults",[{"name":"searchId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.enable",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.focus",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.getAttributes",[{"name":"nodeId","type":"number","optional":false}],["attributes"],false);Protocol.inspectorBackend.registerCommand("DOM.getBoxModel",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],["model"],false);Protocol.inspectorBackend.registerCommand("DOM.getDocument",[{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["root"],false);Protocol.inspectorBackend.registerCommand("DOM.getFlattenedDocument",[{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["nodes"],false);Protocol.inspectorBackend.registerCommand("DOM.getNodeForLocation",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.getOuterHTML",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],["outerHTML"],false);Protocol.inspectorBackend.registerCommand("DOM.getRelayoutBoundary",[{"name":"nodeId","type":"number","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.getSearchResults",[{"name":"searchId","type":"string","optional":false},{"name":"fromIndex","type":"number","optional":false},{"name":"toIndex","type":"number","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.hideHighlight",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.highlightNode",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.highlightRect",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.markUndoableState",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.moveTo",[{"name":"nodeId","type":"number","optional":false},{"name":"targetNodeId","type":"number","optional":false},{"name":"insertBeforeNodeId","type":"number","optional":true}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.performSearch",[{"name":"query","type":"string","optional":false},{"name":"includeUserAgentShadowDOM","type":"boolean","optional":true}],["searchId","resultCount"],false);Protocol.inspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend",[{"name":"path","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend",[{"name":"backendNodeIds","type":"object","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.querySelector",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.querySelectorAll",[{"name":"nodeId","type":"number","optional":false},{"name":"selector","type":"string","optional":false}],["nodeIds"],false);Protocol.inspectorBackend.registerCommand("DOM.redo",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.removeAttribute",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.removeNode",[{"name":"nodeId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.requestChildNodes",[{"name":"nodeId","type":"number","optional":false},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.requestNode",[{"name":"objectId","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.resolveNode",[{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true}],["object"],false);Protocol.inspectorBackend.registerCommand("DOM.setAttributeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setAttributesAsText",[{"name":"nodeId","type":"number","optional":false},{"name":"text","type":"string","optional":false},{"name":"name","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setFileInputFiles",[{"name":"files","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setInspectedNode",[{"name":"nodeId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setNodeName",[{"name":"nodeId","type":"number","optional":false},{"name":"name","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerCommand("DOM.setNodeValue",[{"name":"nodeId","type":"number","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.setOuterHTML",[{"name":"nodeId","type":"number","optional":false},{"name":"outerHTML","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOM.undo",[],[],false);Protocol.inspectorBackend.registerCommand("DOM.getFrameOwner",[{"name":"frameId","type":"string","optional":false}],["nodeId"],false);Protocol.inspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType",{SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed"});Protocol.inspectorBackend.registerCommand("DOMDebugger.getEventListeners",[{"name":"objectId","type":"string","optional":false},{"name":"depth","type":"number","optional":true},{"name":"pierce","type":"boolean","optional":true}],["listeners"],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint",[{"name":"nodeId","type":"number","optional":false},{"name":"type","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint",[{"name":"eventName","type":"string","optional":false},{"name":"targetName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint",[{"name":"eventName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint",[{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMSnapshot.getSnapshot",[{"name":"computedStyleWhitelist","type":"object","optional":false},{"name":"includeEventListeners","type":"boolean","optional":true},{"name":"includePaintOrder","type":"boolean","optional":true}],["domNodes","layoutTreeNodes","computedStyles"],false);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemAdded",["storageId","key","newValue"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved",["storageId","key"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated",["storageId","key","oldValue","newValue"]);Protocol.inspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared",["storageId"]);Protocol.inspectorBackend.registerCommand("DOMStorage.clear",[{"name":"storageId","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.disable",[],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.enable",[],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.getDOMStorageItems",[{"name":"storageId","type":"object","optional":false}],["entries"],false);Protocol.inspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("DOMStorage.setDOMStorageItem",[{"name":"storageId","type":"object","optional":false},{"name":"key","type":"string","optional":false},{"name":"value","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("Database.addDatabase",["database"]);Protocol.inspectorBackend.registerCommand("Database.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Database.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Database.executeSQL",[{"name":"databaseId","type":"string","optional":false},{"name":"query","type":"string","optional":false}],["columnNames","values","sqlError"],false);Protocol.inspectorBackend.registerCommand("Database.getDatabaseTableNames",[{"name":"databaseId","type":"string","optional":false}],["tableNames"],false);Protocol.inspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Emulation.ScreenOrientationType",{PortraitPrimary:"portraitPrimary",PortraitSecondary:"portraitSecondary",LandscapePrimary:"landscapePrimary",LandscapeSecondary:"landscapeSecondary"});Protocol.inspectorBackend.registerEnum("Emulation.VirtualTimePolicy",{Advance:"advance",Pause:"pause",PauseIfNetworkFetchesPending:"pauseIfNetworkFetchesPending"});Protocol.inspectorBackend.registerEvent("Emulation.virtualTimeAdvanced",["virtualTimeElapsed"]);Protocol.inspectorBackend.registerEvent("Emulation.virtualTimeBudgetExpired",[]);Protocol.inspectorBackend.registerEvent("Emulation.virtualTimePaused",["virtualTimeElapsed"]);Protocol.inspectorBackend.registerCommand("Emulation.canEmulate",[],["result"],false);Protocol.inspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.clearGeolocationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.resetPageScaleFactor",[],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setCPUThrottlingRate",[{"name":"rate","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setDefaultBackgroundColorOverride",[{"name":"color","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true},{"name":"dontSetVisibleSize","type":"boolean","optional":true},{"name":"screenOrientation","type":"object","optional":true},{"name":"viewport","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setEmitTouchEventsForMouse",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setEmulatedMedia",[{"name":"media","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setNavigatorOverrides",[{"name":"platform","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setPageScaleFactor",[{"name":"pageScaleFactor","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled",[{"name":"value","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"maxTouchPoints","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Emulation.setVirtualTimePolicy",[{"name":"policy","type":"string","optional":false},{"name":"budget","type":"number","optional":true},{"name":"maxVirtualTimeTaskStarvationCount","type":"number","optional":true},{"name":"waitForNavigation","type":"boolean","optional":true}],["virtualTimeBase","virtualTimeTicksBase"],false);Protocol.inspectorBackend.registerCommand("Emulation.setVisibleSize",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("HeadlessExperimental.ScreenshotParamsFormat",{Jpeg:"jpeg",Png:"png"});Protocol.inspectorBackend.registerEvent("HeadlessExperimental.needsBeginFramesChanged",["needsBeginFrames"]);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.beginFrame",[{"name":"frameTime","type":"number","optional":true},{"name":"frameTimeTicks","type":"number","optional":true},{"name":"deadline","type":"number","optional":true},{"name":"deadlineTicks","type":"number","optional":true},{"name":"interval","type":"number","optional":true},{"name":"noDisplayUpdates","type":"boolean","optional":true},{"name":"screenshot","type":"object","optional":true}],["hasDamage","screenshotData"],false);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.enterDeterministicMode",[{"name":"initialDate","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.disable",[],[],false);Protocol.inspectorBackend.registerCommand("HeadlessExperimental.enable",[],[],false);Protocol.inspectorBackend.registerCommand("IO.close",[{"name":"handle","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IO.read",[{"name":"handle","type":"string","optional":false},{"name":"offset","type":"number","optional":true},{"name":"size","type":"number","optional":true}],["base64Encoded","data","eof"],false);Protocol.inspectorBackend.registerCommand("IO.resolveBlob",[{"name":"objectId","type":"string","optional":false}],["uuid"],false);Protocol.inspectorBackend.registerEnum("IndexedDB.KeyType",{Number:"number",String:"string",Date:"date",Array:"array"});Protocol.inspectorBackend.registerEnum("IndexedDB.KeyPathType",{Null:"null",String:"string",Array:"array"});Protocol.inspectorBackend.registerCommand("IndexedDB.clearObjectStore",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.deleteDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.deleteObjectStoreEntries",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false},{"name":"keyRange","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.disable",[],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.enable",[],[],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestData",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false},{"name":"objectStoreName","type":"string","optional":false},{"name":"indexName","type":"string","optional":false},{"name":"skipCount","type":"number","optional":false},{"name":"pageSize","type":"number","optional":false},{"name":"keyRange","type":"object","optional":true}],["objectStoreDataEntries","hasMore"],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestDatabase",[{"name":"securityOrigin","type":"string","optional":false},{"name":"databaseName","type":"string","optional":false}],["databaseWithObjectStores"],false);Protocol.inspectorBackend.registerCommand("IndexedDB.requestDatabaseNames",[{"name":"securityOrigin","type":"string","optional":false}],["databaseNames"],false);Protocol.inspectorBackend.registerEnum("Input.GestureSourceType",{Default:"default",Touch:"touch",Mouse:"mouse"});Protocol.inspectorBackend.registerCommand("Input.dispatchKeyEvent",[{"name":"type","type":"string","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"text","type":"string","optional":true},{"name":"unmodifiedText","type":"string","optional":true},{"name":"keyIdentifier","type":"string","optional":true},{"name":"code","type":"string","optional":true},{"name":"key","type":"string","optional":true},{"name":"windowsVirtualKeyCode","type":"number","optional":true},{"name":"nativeVirtualKeyCode","type":"number","optional":true},{"name":"autoRepeat","type":"boolean","optional":true},{"name":"isKeypad","type":"boolean","optional":true},{"name":"isSystemKey","type":"boolean","optional":true},{"name":"location","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.dispatchMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true},{"name":"button","type":"string","optional":true},{"name":"clickCount","type":"number","optional":true},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.dispatchTouchEvent",[{"name":"type","type":"string","optional":false},{"name":"touchPoints","type":"object","optional":false},{"name":"modifiers","type":"number","optional":true},{"name":"timestamp","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent",[{"name":"type","type":"string","optional":false},{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"button","type":"string","optional":false},{"name":"timestamp","type":"number","optional":true},{"name":"deltaX","type":"number","optional":true},{"name":"deltaY","type":"number","optional":true},{"name":"modifiers","type":"number","optional":true},{"name":"clickCount","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.setIgnoreInputEvents",[{"name":"ignore","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizePinchGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"scaleFactor","type":"number","optional":false},{"name":"relativeSpeed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizeScrollGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"xDistance","type":"number","optional":true},{"name":"yDistance","type":"number","optional":true},{"name":"xOverscroll","type":"number","optional":true},{"name":"yOverscroll","type":"number","optional":true},{"name":"preventFling","type":"boolean","optional":true},{"name":"speed","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true},{"name":"repeatCount","type":"number","optional":true},{"name":"repeatDelayMs","type":"number","optional":true},{"name":"interactionMarkerName","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Input.synthesizeTapGesture",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"duration","type":"number","optional":true},{"name":"tapCount","type":"number","optional":true},{"name":"gestureSourceType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerEvent("Inspector.detached",["reason"]);Protocol.inspectorBackend.registerEvent("Inspector.targetCrashed",[]);Protocol.inspectorBackend.registerEvent("Inspector.targetReloadedAfterCrash",[]);Protocol.inspectorBackend.registerCommand("Inspector.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Inspector.enable",[],[],false);Protocol.inspectorBackend.registerEnum("LayerTree.ScrollRectType",{RepaintsOnScroll:"RepaintsOnScroll",TouchEventHandler:"TouchEventHandler",WheelEventHandler:"WheelEventHandler"});Protocol.inspectorBackend.registerEvent("LayerTree.layerPainted",["layerId","clip"]);Protocol.inspectorBackend.registerEvent("LayerTree.layerTreeDidChange",["layers"]);Protocol.inspectorBackend.registerCommand("LayerTree.compositingReasons",[{"name":"layerId","type":"string","optional":false}],["compositingReasons"],false);Protocol.inspectorBackend.registerCommand("LayerTree.disable",[],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.enable",[],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.loadSnapshot",[{"name":"tiles","type":"object","optional":false}],["snapshotId"],false);Protocol.inspectorBackend.registerCommand("LayerTree.makeSnapshot",[{"name":"layerId","type":"string","optional":false}],["snapshotId"],false);Protocol.inspectorBackend.registerCommand("LayerTree.profileSnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"minRepeatCount","type":"number","optional":true},{"name":"minDuration","type":"number","optional":true},{"name":"clipRect","type":"object","optional":true}],["timings"],false);Protocol.inspectorBackend.registerCommand("LayerTree.releaseSnapshot",[{"name":"snapshotId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("LayerTree.replaySnapshot",[{"name":"snapshotId","type":"string","optional":false},{"name":"fromStep","type":"number","optional":true},{"name":"toStep","type":"number","optional":true},{"name":"scale","type":"number","optional":true}],["dataURL"],false);Protocol.inspectorBackend.registerCommand("LayerTree.snapshotCommandLog",[{"name":"snapshotId","type":"string","optional":false}],["commandLog"],false);Protocol.inspectorBackend.registerEnum("Log.LogEntrySource",{XML:"xml",Javascript:"javascript",Network:"network",Storage:"storage",Appcache:"appcache",Rendering:"rendering",Security:"security",Deprecation:"deprecation",Worker:"worker",Violation:"violation",Intervention:"intervention",Recommendation:"recommendation",Other:"other"});Protocol.inspectorBackend.registerEnum("Log.LogEntryLevel",{Verbose:"verbose",Info:"info",Warning:"warning",Error:"error"});Protocol.inspectorBackend.registerEnum("Log.ViolationSettingName",{LongTask:"longTask",LongLayout:"longLayout",BlockedEvent:"blockedEvent",BlockedParser:"blockedParser",DiscouragedAPIUse:"discouragedAPIUse",Handler:"handler",RecurringHandler:"recurringHandler"});Protocol.inspectorBackend.registerEvent("Log.entryAdded",["entry"]);Protocol.inspectorBackend.registerCommand("Log.clear",[],[],false);Protocol.inspectorBackend.registerCommand("Log.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Log.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Log.startViolationsReport",[{"name":"config","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Log.stopViolationsReport",[],[],false);Protocol.inspectorBackend.registerEnum("Memory.PressureLevel",{Moderate:"moderate",Critical:"critical"});Protocol.inspectorBackend.registerCommand("Memory.getDOMCounters",[],["documents","nodes","jsEventListeners"],false);Protocol.inspectorBackend.registerCommand("Memory.prepareForLeakDetection",[],[],false);Protocol.inspectorBackend.registerCommand("Memory.setPressureNotificationsSuppressed",[{"name":"suppressed","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Memory.simulatePressureNotification",[{"name":"level","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Memory.startSampling",[{"name":"samplingInterval","type":"number","optional":true},{"name":"suppressRandomness","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Memory.stopSampling",[],[],false);Protocol.inspectorBackend.registerCommand("Memory.getAllTimeSamplingProfile",[],["profile"],false);Protocol.inspectorBackend.registerCommand("Memory.getBrowserSamplingProfile",[],["profile"],false);Protocol.inspectorBackend.registerCommand("Memory.getSamplingProfile",[],["profile"],false);Protocol.inspectorBackend.registerEnum("Network.ErrorReason",{Failed:"Failed",Aborted:"Aborted",TimedOut:"TimedOut",AccessDenied:"AccessDenied",ConnectionClosed:"ConnectionClosed",ConnectionReset:"ConnectionReset",ConnectionRefused:"ConnectionRefused",ConnectionAborted:"ConnectionAborted",ConnectionFailed:"ConnectionFailed",NameNotResolved:"NameNotResolved",InternetDisconnected:"InternetDisconnected",AddressUnreachable:"AddressUnreachable"});Protocol.inspectorBackend.registerEnum("Network.ConnectionType",{None:"none",Cellular2g:"cellular2g",Cellular3g:"cellular3g",Cellular4g:"cellular4g",Bluetooth:"bluetooth",Ethernet:"ethernet",Wifi:"wifi",Wimax:"wimax",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.CookieSameSite",{Strict:"Strict",Lax:"Lax"});Protocol.inspectorBackend.registerEnum("Network.ResourcePriority",{VeryLow:"VeryLow",Low:"Low",Medium:"Medium",High:"High",VeryHigh:"VeryHigh"});Protocol.inspectorBackend.registerEnum("Network.RequestReferrerPolicy",{UnsafeUrl:"unsafe-url",NoReferrerWhenDowngrade:"no-referrer-when-downgrade",NoReferrer:"no-referrer",Origin:"origin",OriginWhenCrossOrigin:"origin-when-cross-origin",SameOrigin:"same-origin",StrictOrigin:"strict-origin",StrictOriginWhenCrossOrigin:"strict-origin-when-cross-origin"});Protocol.inspectorBackend.registerEnum("Network.CertificateTransparencyCompliance",{Unknown:"unknown",NotCompliant:"not-compliant",Compliant:"compliant"});Protocol.inspectorBackend.registerEnum("Network.BlockedReason",{Csp:"csp",MixedContent:"mixed-content",Origin:"origin",Inspector:"inspector",SubresourceFilter:"subresource-filter",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.InitiatorType",{Parser:"parser",Script:"script",Preload:"preload",Other:"other"});Protocol.inspectorBackend.registerEnum("Network.AuthChallengeSource",{Server:"Server",Proxy:"Proxy"});Protocol.inspectorBackend.registerEnum("Network.AuthChallengeResponseResponse",{Default:"Default",CancelAuth:"CancelAuth",ProvideCredentials:"ProvideCredentials"});Protocol.inspectorBackend.registerEnum("Network.InterceptionStage",{Request:"Request",HeadersReceived:"HeadersReceived"});Protocol.inspectorBackend.registerEvent("Network.dataReceived",["requestId","timestamp","dataLength","encodedDataLength"]);Protocol.inspectorBackend.registerEvent("Network.eventSourceMessageReceived",["requestId","timestamp","eventName","eventId","data"]);Protocol.inspectorBackend.registerEvent("Network.loadingFailed",["requestId","timestamp","type","errorText","canceled","blockedReason"]);Protocol.inspectorBackend.registerEvent("Network.loadingFinished",["requestId","timestamp","encodedDataLength","blockedCrossSiteDocument"]);Protocol.inspectorBackend.registerEvent("Network.requestIntercepted",["interceptionId","request","frameId","resourceType","isNavigationRequest","redirectUrl","authChallenge","responseErrorReason","responseStatusCode","responseHeaders"]);Protocol.inspectorBackend.registerEvent("Network.requestServedFromCache",["requestId"]);Protocol.inspectorBackend.registerEvent("Network.requestWillBeSent",["requestId","loaderId","documentURL","request","timestamp","wallTime","initiator","redirectResponse","type","frameId","hasUserGesture"]);Protocol.inspectorBackend.registerEvent("Network.resourceChangedPriority",["requestId","newPriority","timestamp"]);Protocol.inspectorBackend.registerEvent("Network.responseReceived",["requestId","loaderId","timestamp","type","response","frameId"]);Protocol.inspectorBackend.registerEvent("Network.webSocketClosed",["requestId","timestamp"]);Protocol.inspectorBackend.registerEvent("Network.webSocketCreated",["requestId","url","initiator"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameError",["requestId","timestamp","errorMessage"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameReceived",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.webSocketFrameSent",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived",["requestId","timestamp","response"]);Protocol.inspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest",["requestId","timestamp","wallTime","request"]);Protocol.inspectorBackend.registerCommand("Network.canClearBrowserCache",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.canClearBrowserCookies",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.canEmulateNetworkConditions",[],["result"],false);Protocol.inspectorBackend.registerCommand("Network.clearBrowserCache",[],[],false);Protocol.inspectorBackend.registerCommand("Network.clearBrowserCookies",[],[],false);Protocol.inspectorBackend.registerCommand("Network.continueInterceptedRequest",[{"name":"interceptionId","type":"string","optional":false},{"name":"errorReason","type":"string","optional":true},{"name":"rawResponse","type":"string","optional":true},{"name":"url","type":"string","optional":true},{"name":"method","type":"string","optional":true},{"name":"postData","type":"string","optional":true},{"name":"headers","type":"object","optional":true},{"name":"authChallengeResponse","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.deleteCookies",[{"name":"name","type":"string","optional":false},{"name":"url","type":"string","optional":true},{"name":"domain","type":"string","optional":true},{"name":"path","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Network.emulateNetworkConditions",[{"name":"offline","type":"boolean","optional":false},{"name":"latency","type":"number","optional":false},{"name":"downloadThroughput","type":"number","optional":false},{"name":"uploadThroughput","type":"number","optional":false},{"name":"connectionType","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.enable",[{"name":"maxTotalBufferSize","type":"number","optional":true},{"name":"maxResourceBufferSize","type":"number","optional":true},{"name":"maxPostDataSize","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Network.getAllCookies",[],["cookies"],false);Protocol.inspectorBackend.registerCommand("Network.getCertificate",[{"name":"origin","type":"string","optional":false}],["tableNames"],false);Protocol.inspectorBackend.registerCommand("Network.getCookies",[{"name":"urls","type":"object","optional":true}],["cookies"],false);Protocol.inspectorBackend.registerCommand("Network.getResponseBody",[{"name":"requestId","type":"string","optional":false}],["body","base64Encoded"],false);Protocol.inspectorBackend.registerCommand("Network.getRequestPostData",[{"name":"requestId","type":"string","optional":false}],["postData"],false);Protocol.inspectorBackend.registerCommand("Network.getResponseBodyForInterception",[{"name":"interceptionId","type":"string","optional":false}],["body","base64Encoded"],false);Protocol.inspectorBackend.registerCommand("Network.replayXHR",[{"name":"requestId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.searchInResponseBody",[{"name":"requestId","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("Network.setBlockedURLs",[{"name":"urls","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setBypassServiceWorker",[{"name":"bypass","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setCacheDisabled",[{"name":"cacheDisabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setCookie",[{"name":"name","type":"string","optional":false},{"name":"value","type":"string","optional":false},{"name":"url","type":"string","optional":true},{"name":"domain","type":"string","optional":true},{"name":"path","type":"string","optional":true},{"name":"secure","type":"boolean","optional":true},{"name":"httpOnly","type":"boolean","optional":true},{"name":"sameSite","type":"string","optional":true},{"name":"expires","type":"number","optional":true}],["success"],false);Protocol.inspectorBackend.registerCommand("Network.setCookies",[{"name":"cookies","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setDataSizeLimitsForTest",[{"name":"maxTotalSize","type":"number","optional":false},{"name":"maxResourceSize","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setExtraHTTPHeaders",[{"name":"headers","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setRequestInterception",[{"name":"patterns","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Network.setUserAgentOverride",[{"name":"userAgent","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Overlay.InspectMode",{SearchForNode:"searchForNode",SearchForUAShadowDOM:"searchForUAShadowDOM",None:"none"});Protocol.inspectorBackend.registerEvent("Overlay.inspectNodeRequested",["backendNodeId"]);Protocol.inspectorBackend.registerEvent("Overlay.nodeHighlightRequested",["nodeId"]);Protocol.inspectorBackend.registerEvent("Overlay.screenshotRequested",["viewport"]);Protocol.inspectorBackend.registerCommand("Overlay.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.getHighlightObjectForTest",[{"name":"nodeId","type":"number","optional":false}],["highlight"],false);Protocol.inspectorBackend.registerCommand("Overlay.hideHighlight",[],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightFrame",[{"name":"frameId","type":"string","optional":false},{"name":"contentColor","type":"object","optional":true},{"name":"contentOutlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightNode",[{"name":"highlightConfig","type":"object","optional":false},{"name":"nodeId","type":"number","optional":true},{"name":"backendNodeId","type":"number","optional":true},{"name":"objectId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightQuad",[{"name":"quad","type":"object","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.highlightRect",[{"name":"x","type":"number","optional":false},{"name":"y","type":"number","optional":false},{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"color","type":"object","optional":true},{"name":"outlineColor","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setInspectMode",[{"name":"mode","type":"string","optional":false},{"name":"highlightConfig","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setPausedInDebuggerMessage",[{"name":"message","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowDebugBorders",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowFPSCounter",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowPaintRects",[{"name":"result","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowScrollBottleneckRects",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setShowViewportSizeOnResize",[{"name":"show","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Overlay.setSuspended",[{"name":"suspended","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Page.ResourceType",{Document:"Document",Stylesheet:"Stylesheet",Image:"Image",Media:"Media",Font:"Font",Script:"Script",TextTrack:"TextTrack",XHR:"XHR",Fetch:"Fetch",EventSource:"EventSource",WebSocket:"WebSocket",Manifest:"Manifest",Other:"Other"});Protocol.inspectorBackend.registerEnum("Page.TransitionType",{Link:"link",Typed:"typed",Auto_bookmark:"auto_bookmark",Auto_subframe:"auto_subframe",Manual_subframe:"manual_subframe",Generated:"generated",Auto_toplevel:"auto_toplevel",Form_submit:"form_submit",Reload:"reload",Keyword:"keyword",Keyword_generated:"keyword_generated",Other:"other"});Protocol.inspectorBackend.registerEnum("Page.DialogType",{Alert:"alert",Confirm:"confirm",Prompt:"prompt",Beforeunload:"beforeunload"});Protocol.inspectorBackend.registerEvent("Page.domContentEventFired",["timestamp"]);Protocol.inspectorBackend.registerEvent("Page.frameAttached",["frameId","parentFrameId","stack"]);Protocol.inspectorBackend.registerEvent("Page.frameClearedScheduledNavigation",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameDetached",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameNavigated",["frame"]);Protocol.inspectorBackend.registerEvent("Page.frameResized",[]);Protocol.inspectorBackend.registerEvent("Page.frameScheduledNavigation",["frameId","delay","reason","url"]);Protocol.inspectorBackend.registerEvent("Page.frameStartedLoading",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.frameStoppedLoading",["frameId"]);Protocol.inspectorBackend.registerEvent("Page.interstitialHidden",[]);Protocol.inspectorBackend.registerEvent("Page.interstitialShown",[]);Protocol.inspectorBackend.registerEvent("Page.javascriptDialogClosed",["result","userInput"]);Protocol.inspectorBackend.registerEvent("Page.javascriptDialogOpening",["url","message","type","hasBrowserHandler","defaultPrompt"]);Protocol.inspectorBackend.registerEvent("Page.lifecycleEvent",["frameId","loaderId","name","timestamp"]);Protocol.inspectorBackend.registerEvent("Page.loadEventFired",["timestamp"]);Protocol.inspectorBackend.registerEvent("Page.navigatedWithinDocument",["frameId","url"]);Protocol.inspectorBackend.registerEvent("Page.screencastFrame",["data","metadata","sessionId"]);Protocol.inspectorBackend.registerEvent("Page.screencastVisibilityChanged",["visible"]);Protocol.inspectorBackend.registerEvent("Page.windowOpen",["url","windowName","windowFeatures","userGesture"]);Protocol.inspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad",[{"name":"scriptSource","type":"string","optional":false}],["identifier"],false);Protocol.inspectorBackend.registerCommand("Page.addScriptToEvaluateOnNewDocument",[{"name":"source","type":"string","optional":false}],["identifier"],false);Protocol.inspectorBackend.registerCommand("Page.bringToFront",[],[],false);Protocol.inspectorBackend.registerCommand("Page.captureScreenshot",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"clip","type":"object","optional":true},{"name":"fromSurface","type":"boolean","optional":true}],["data"],false);Protocol.inspectorBackend.registerCommand("Page.clearDeviceMetricsOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.clearDeviceOrientationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.clearGeolocationOverride",[],[],false);Protocol.inspectorBackend.registerCommand("Page.createIsolatedWorld",[{"name":"frameId","type":"string","optional":false},{"name":"worldName","type":"string","optional":true},{"name":"grantUniveralAccess","type":"boolean","optional":true}],["executionContextId"],false);Protocol.inspectorBackend.registerCommand("Page.deleteCookie",[{"name":"cookieName","type":"string","optional":false},{"name":"url","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Page.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Page.getAppManifest",[],["url","errors","data"],false);Protocol.inspectorBackend.registerCommand("Page.getCookies",[],["cookies"],false);Protocol.inspectorBackend.registerCommand("Page.getFrameTree",[],["frameTree"],false);Protocol.inspectorBackend.registerCommand("Page.getLayoutMetrics",[],["layoutViewport","visualViewport","contentSize"],false);Protocol.inspectorBackend.registerCommand("Page.getNavigationHistory",[],["currentIndex","entries"],false);Protocol.inspectorBackend.registerCommand("Page.getResourceContent",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false}],["content","base64Encoded"],false);Protocol.inspectorBackend.registerCommand("Page.getResourceTree",[],["frameTree"],false);Protocol.inspectorBackend.registerCommand("Page.handleJavaScriptDialog",[{"name":"accept","type":"boolean","optional":false},{"name":"promptText","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.navigate",[{"name":"url","type":"string","optional":false},{"name":"referrer","type":"string","optional":true},{"name":"transitionType","type":"string","optional":true},{"name":"frameId","type":"string","optional":true}],["frameId","loaderId","errorText"],false);Protocol.inspectorBackend.registerCommand("Page.navigateToHistoryEntry",[{"name":"entryId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.printToPDF",[{"name":"landscape","type":"boolean","optional":true},{"name":"displayHeaderFooter","type":"boolean","optional":true},{"name":"printBackground","type":"boolean","optional":true},{"name":"scale","type":"number","optional":true},{"name":"paperWidth","type":"number","optional":true},{"name":"paperHeight","type":"number","optional":true},{"name":"marginTop","type":"number","optional":true},{"name":"marginBottom","type":"number","optional":true},{"name":"marginLeft","type":"number","optional":true},{"name":"marginRight","type":"number","optional":true},{"name":"pageRanges","type":"string","optional":true},{"name":"ignoreInvalidPageRanges","type":"boolean","optional":true},{"name":"headerTemplate","type":"string","optional":true},{"name":"footerTemplate","type":"string","optional":true},{"name":"preferCSSPageSize","type":"boolean","optional":true}],["data"],false);Protocol.inspectorBackend.registerCommand("Page.reload",[{"name":"ignoreCache","type":"boolean","optional":true},{"name":"scriptToEvaluateOnLoad","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad",[{"name":"identifier","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnNewDocument",[{"name":"identifier","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.requestAppBanner",[],[],false);Protocol.inspectorBackend.registerCommand("Page.screencastFrameAck",[{"name":"sessionId","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.searchInResource",[{"name":"frameId","type":"string","optional":false},{"name":"url","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("Page.setAdBlockingEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setBypassCSP",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setDeviceMetricsOverride",[{"name":"width","type":"number","optional":false},{"name":"height","type":"number","optional":false},{"name":"deviceScaleFactor","type":"number","optional":false},{"name":"mobile","type":"boolean","optional":false},{"name":"scale","type":"number","optional":true},{"name":"screenWidth","type":"number","optional":true},{"name":"screenHeight","type":"number","optional":true},{"name":"positionX","type":"number","optional":true},{"name":"positionY","type":"number","optional":true},{"name":"dontSetVisibleSize","type":"boolean","optional":true},{"name":"screenOrientation","type":"object","optional":true},{"name":"viewport","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.setDeviceOrientationOverride",[{"name":"alpha","type":"number","optional":false},{"name":"beta","type":"number","optional":false},{"name":"gamma","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setDocumentContent",[{"name":"frameId","type":"string","optional":false},{"name":"html","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setDownloadBehavior",[{"name":"behavior","type":"string","optional":false},{"name":"downloadPath","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.setGeolocationOverride",[{"name":"latitude","type":"number","optional":true},{"name":"longitude","type":"number","optional":true},{"name":"accuracy","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.setLifecycleEventsEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Page.setTouchEmulationEnabled",[{"name":"enabled","type":"boolean","optional":false},{"name":"configuration","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.startScreencast",[{"name":"format","type":"string","optional":true},{"name":"quality","type":"number","optional":true},{"name":"maxWidth","type":"number","optional":true},{"name":"maxHeight","type":"number","optional":true},{"name":"everyNthFrame","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Page.stopLoading",[],[],false);Protocol.inspectorBackend.registerCommand("Page.crash",[],[],false);Protocol.inspectorBackend.registerCommand("Page.stopScreencast",[],[],false);Protocol.inspectorBackend.registerEvent("Performance.metrics",["metrics","title"]);Protocol.inspectorBackend.registerCommand("Performance.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Performance.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Performance.getMetrics",[],["metrics"],false);Protocol.inspectorBackend.registerEnum("Security.MixedContentType",{Blockable:"blockable",OptionallyBlockable:"optionally-blockable",None:"none"});Protocol.inspectorBackend.registerEnum("Security.SecurityState",{Unknown:"unknown",Neutral:"neutral",Insecure:"insecure",Secure:"secure",Info:"info"});Protocol.inspectorBackend.registerEnum("Security.CertificateErrorAction",{Continue:"continue",Cancel:"cancel"});Protocol.inspectorBackend.registerEvent("Security.certificateError",["eventId","errorType","requestURL"]);Protocol.inspectorBackend.registerEvent("Security.securityStateChanged",["securityState","schemeIsCryptographic","explanations","insecureContentStatus","summary"]);Protocol.inspectorBackend.registerCommand("Security.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Security.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Security.setIgnoreCertificateErrors",[{"name":"ignore","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Security.handleCertificateError",[{"name":"eventId","type":"number","optional":false},{"name":"action","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Security.setOverrideCertificateErrors",[{"name":"override","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus",{Stopped:"stopped",Starting:"starting",Running:"running",Stopping:"stopping"});Protocol.inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus",{New:"new",Installing:"installing",Installed:"installed",Activating:"activating",Activated:"activated",Redundant:"redundant"});Protocol.inspectorBackend.registerEvent("ServiceWorker.workerErrorReported",["errorMessage"]);Protocol.inspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated",["registrations"]);Protocol.inspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated",["versions"]);Protocol.inspectorBackend.registerCommand("ServiceWorker.deliverPushMessage",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"data","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.disable",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.dispatchSyncEvent",[{"name":"origin","type":"string","optional":false},{"name":"registrationId","type":"string","optional":false},{"name":"tag","type":"string","optional":false},{"name":"lastChance","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.enable",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.inspectWorker",[{"name":"versionId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.setForceUpdateOnPageLoad",[{"name":"forceUpdateOnPageLoad","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.skipWaiting",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.startWorker",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.stopAllWorkers",[],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.stopWorker",[{"name":"versionId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.unregister",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("ServiceWorker.updateRegistration",[{"name":"scopeURL","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Storage.StorageType",{Appcache:"appcache",Cookies:"cookies",File_systems:"file_systems",Indexeddb:"indexeddb",Local_storage:"local_storage",Shader_cache:"shader_cache",Websql:"websql",Service_workers:"service_workers",Cache_storage:"cache_storage",All:"all",Other:"other"});Protocol.inspectorBackend.registerEvent("Storage.cacheStorageContentUpdated",["origin","cacheName"]);Protocol.inspectorBackend.registerEvent("Storage.cacheStorageListUpdated",["origin"]);Protocol.inspectorBackend.registerEvent("Storage.indexedDBContentUpdated",["origin","databaseName","objectStoreName"]);Protocol.inspectorBackend.registerEvent("Storage.indexedDBListUpdated",["origin"]);Protocol.inspectorBackend.registerCommand("Storage.clearDataForOrigin",[{"name":"origin","type":"string","optional":false},{"name":"storageTypes","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.getUsageAndQuota",[{"name":"origin","type":"string","optional":false}],["usage","quota","usageBreakdown"],false);Protocol.inspectorBackend.registerCommand("Storage.trackCacheStorageForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.trackIndexedDBForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.untrackCacheStorageForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Storage.untrackIndexedDBForOrigin",[{"name":"origin","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("SystemInfo.getInfo",[],["gpu","modelName","modelVersion","commandLine"],false);Protocol.inspectorBackend.registerEvent("Target.attachedToTarget",["sessionId","targetInfo","waitingForDebugger"]);Protocol.inspectorBackend.registerEvent("Target.detachedFromTarget",["sessionId","targetId"]);Protocol.inspectorBackend.registerEvent("Target.receivedMessageFromTarget",["sessionId","message","targetId"]);Protocol.inspectorBackend.registerEvent("Target.targetCreated",["targetInfo"]);Protocol.inspectorBackend.registerEvent("Target.targetDestroyed",["targetId"]);Protocol.inspectorBackend.registerEvent("Target.targetInfoChanged",["targetInfo"]);Protocol.inspectorBackend.registerCommand("Target.activateTarget",[{"name":"targetId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.attachToTarget",[{"name":"targetId","type":"string","optional":false}],["sessionId"],false);Protocol.inspectorBackend.registerCommand("Target.closeTarget",[{"name":"targetId","type":"string","optional":false}],["success"],false);Protocol.inspectorBackend.registerCommand("Target.createBrowserContext",[],["browserContextId"],false);Protocol.inspectorBackend.registerCommand("Target.createTarget",[{"name":"url","type":"string","optional":false},{"name":"width","type":"number","optional":true},{"name":"height","type":"number","optional":true},{"name":"browserContextId","type":"string","optional":true},{"name":"enableBeginFrameControl","type":"boolean","optional":true}],["targetId"],false);Protocol.inspectorBackend.registerCommand("Target.detachFromTarget",[{"name":"sessionId","type":"string","optional":true},{"name":"targetId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Target.disposeBrowserContext",[{"name":"browserContextId","type":"string","optional":false}],["success"],false);Protocol.inspectorBackend.registerCommand("Target.getTargetInfo",[{"name":"targetId","type":"string","optional":false}],["targetInfo"],false);Protocol.inspectorBackend.registerCommand("Target.getTargets",[],["targetInfos"],false);Protocol.inspectorBackend.registerCommand("Target.sendMessageToTarget",[{"name":"message","type":"string","optional":false},{"name":"sessionId","type":"string","optional":true},{"name":"targetId","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Target.setAutoAttach",[{"name":"autoAttach","type":"boolean","optional":false},{"name":"waitForDebuggerOnStart","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.setDiscoverTargets",[{"name":"discover","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Target.setRemoteLocations",[{"name":"locations","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerEvent("Tethering.accepted",["port","connectionId"]);Protocol.inspectorBackend.registerCommand("Tethering.bind",[{"name":"port","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Tethering.unbind",[{"name":"port","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerEnum("Tracing.TraceConfigRecordMode",{RecordUntilFull:"recordUntilFull",RecordContinuously:"recordContinuously",RecordAsMuchAsPossible:"recordAsMuchAsPossible",EchoToConsole:"echoToConsole"});Protocol.inspectorBackend.registerEnum("Tracing.StreamCompression",{None:"none",Gzip:"gzip"});Protocol.inspectorBackend.registerEvent("Tracing.bufferUsage",["percentFull","eventCount","value"]);Protocol.inspectorBackend.registerEvent("Tracing.dataCollected",["value"]);Protocol.inspectorBackend.registerEvent("Tracing.tracingComplete",["stream","streamCompression"]);Protocol.inspectorBackend.registerCommand("Tracing.end",[],[],false);Protocol.inspectorBackend.registerCommand("Tracing.getCategories",[],["categories"],false);Protocol.inspectorBackend.registerCommand("Tracing.recordClockSyncMarker",[{"name":"syncId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Tracing.requestMemoryDump",[],["dumpGuid","success"],false);Protocol.inspectorBackend.registerCommand("Tracing.start",[{"name":"categories","type":"string","optional":true},{"name":"options","type":"string","optional":true},{"name":"bufferUsageReportingInterval","type":"number","optional":true},{"name":"transferMode","type":"string","optional":true},{"name":"streamCompression","type":"string","optional":true},{"name":"traceConfig","type":"object","optional":true}],[],false);Protocol.inspectorBackend.registerEnum("Debugger.ScopeType",{Global:"global",Local:"local",With:"with",Closure:"closure",Catch:"catch",Block:"block",Script:"script",Eval:"eval",Module:"module"});Protocol.inspectorBackend.registerEnum("Debugger.BreakLocationType",{DebuggerStatement:"debuggerStatement",Call:"call",Return:"return"});Protocol.inspectorBackend.registerEvent("Debugger.breakpointResolved",["breakpointId","location"]);Protocol.inspectorBackend.registerEvent("Debugger.paused",["callFrames","reason","data","hitBreakpoints","asyncStackTrace","asyncStackTraceId","asyncCallStackTraceId"]);Protocol.inspectorBackend.registerEvent("Debugger.resumed",[]);Protocol.inspectorBackend.registerEvent("Debugger.scriptFailedToParse",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","hash","executionContextAuxData","sourceMapURL","hasSourceURL","isModule","length","stackTrace"]);Protocol.inspectorBackend.registerEvent("Debugger.scriptParsed",["scriptId","url","startLine","startColumn","endLine","endColumn","executionContextId","hash","executionContextAuxData","isLiveEdit","sourceMapURL","hasSourceURL","isModule","length","stackTrace"]);Protocol.inspectorBackend.registerCommand("Debugger.continueToLocation",[{"name":"location","type":"object","optional":false},{"name":"targetCallFrames","type":"string","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.enable",[],["debuggerId"],false);Protocol.inspectorBackend.registerCommand("Debugger.evaluateOnCallFrame",[{"name":"callFrameId","type":"string","optional":false},{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"throwOnSideEffect","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Debugger.getPossibleBreakpoints",[{"name":"start","type":"object","optional":false},{"name":"end","type":"object","optional":true},{"name":"restrictToFunction","type":"boolean","optional":true}],["locations"],false);Protocol.inspectorBackend.registerCommand("Debugger.getScriptSource",[{"name":"scriptId","type":"string","optional":false}],["scriptSource"],false);Protocol.inspectorBackend.registerCommand("Debugger.getStackTrace",[{"name":"stackTraceId","type":"object","optional":false}],["stackTrace"],false);Protocol.inspectorBackend.registerCommand("Debugger.pause",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.pauseOnAsyncCall",[{"name":"parentStackTraceId","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.removeBreakpoint",[{"name":"breakpointId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.restartFrame",[{"name":"callFrameId","type":"string","optional":false}],["callFrames","asyncStackTrace","asyncStackTraceId"],false);Protocol.inspectorBackend.registerCommand("Debugger.resume",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.scheduleStepIntoAsync",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.searchInContent",[{"name":"scriptId","type":"string","optional":false},{"name":"query","type":"string","optional":false},{"name":"caseSensitive","type":"boolean","optional":true},{"name":"isRegex","type":"boolean","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth",[{"name":"maxDepth","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBlackboxPatterns",[{"name":"patterns","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBlackboxedRanges",[{"name":"scriptId","type":"string","optional":false},{"name":"positions","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpoint",[{"name":"location","type":"object","optional":false},{"name":"condition","type":"string","optional":true}],["breakpointId","actualLocation"],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpointByUrl",[{"name":"lineNumber","type":"number","optional":false},{"name":"url","type":"string","optional":true},{"name":"urlRegex","type":"string","optional":true},{"name":"scriptHash","type":"string","optional":true},{"name":"columnNumber","type":"number","optional":true},{"name":"condition","type":"string","optional":true}],["breakpointId","locations"],false);Protocol.inspectorBackend.registerCommand("Debugger.setBreakpointsActive",[{"name":"active","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setPauseOnExceptions",[{"name":"state","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setReturnValue",[{"name":"newValue","type":"object","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setScriptSource",[{"name":"scriptId","type":"string","optional":false},{"name":"scriptSource","type":"string","optional":false},{"name":"dryRun","type":"boolean","optional":true}],["callFrames","stackChanged","asyncStackTrace","asyncStackTraceId","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Debugger.setSkipAllPauses",[{"name":"skip","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.setVariableValue",[{"name":"scopeNumber","type":"number","optional":false},{"name":"variableName","type":"string","optional":false},{"name":"newValue","type":"object","optional":false},{"name":"callFrameId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepInto",[{"name":"breakOnAsyncCall","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepOut",[],[],false);Protocol.inspectorBackend.registerCommand("Debugger.stepOver",[],[],false);Protocol.inspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk",["chunk"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate",["statsUpdate"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId",["lastSeenObjectId","timestamp"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress",["done","total","finished"]);Protocol.inspectorBackend.registerEvent("HeapProfiler.resetProfiles",[]);Protocol.inspectorBackend.registerCommand("HeapProfiler.addInspectedHeapObject",[{"name":"heapObjectId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.collectGarbage",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.disable",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.enable",[],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.getHeapObjectId",[{"name":"objectId","type":"string","optional":false}],["heapSnapshotObjectId"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId",[{"name":"objectId","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true}],["result"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.getSamplingProfile",[],["profile"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.startSampling",[{"name":"samplingInterval","type":"number","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects",[{"name":"trackAllocations","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.stopSampling",[],["profile"],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot",[{"name":"reportProgress","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerEvent("Profiler.consoleProfileFinished",["id","location","profile","title"]);Protocol.inspectorBackend.registerEvent("Profiler.consoleProfileStarted",["id","location","title"]);Protocol.inspectorBackend.registerCommand("Profiler.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.getBestEffortCoverage",[],["result"],false);Protocol.inspectorBackend.registerCommand("Profiler.setSamplingInterval",[{"name":"interval","type":"number","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Profiler.start",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.startPreciseCoverage",[{"name":"callCount","type":"boolean","optional":true},{"name":"detailed","type":"boolean","optional":true}],[],false);Protocol.inspectorBackend.registerCommand("Profiler.startTypeProfile",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.stop",[],["profile"],false);Protocol.inspectorBackend.registerCommand("Profiler.stopPreciseCoverage",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.stopTypeProfile",[],[],false);Protocol.inspectorBackend.registerCommand("Profiler.takePreciseCoverage",[],["result"],false);Protocol.inspectorBackend.registerCommand("Profiler.takeTypeProfile",[],["result"],false);Protocol.inspectorBackend.registerEnum("Runtime.RemoteObjectType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Bigint:"bigint"});Protocol.inspectorBackend.registerEnum("Runtime.RemoteObjectSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error",Proxy:"proxy",Promise:"promise",Typedarray:"typedarray"});Protocol.inspectorBackend.registerEnum("Runtime.ObjectPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Bigint:"bigint"});Protocol.inspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error"});Protocol.inspectorBackend.registerEnum("Runtime.PropertyPreviewType",{Object:"object",Function:"function",Undefined:"undefined",String:"string",Number:"number",Boolean:"boolean",Symbol:"symbol",Accessor:"accessor",Bigint:"bigint"});Protocol.inspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype",{Array:"array",Null:"null",Node:"node",Regexp:"regexp",Date:"date",Map:"map",Set:"set",Weakmap:"weakmap",Weakset:"weakset",Iterator:"iterator",Generator:"generator",Error:"error"});Protocol.inspectorBackend.registerEvent("Runtime.consoleAPICalled",["type","args","executionContextId","timestamp","stackTrace","context"]);Protocol.inspectorBackend.registerEvent("Runtime.exceptionRevoked",["reason","exceptionId"]);Protocol.inspectorBackend.registerEvent("Runtime.exceptionThrown",["timestamp","exceptionDetails"]);Protocol.inspectorBackend.registerEvent("Runtime.executionContextCreated",["context"]);Protocol.inspectorBackend.registerEvent("Runtime.executionContextDestroyed",["executionContextId"]);Protocol.inspectorBackend.registerEvent("Runtime.executionContextsCleared",[]);Protocol.inspectorBackend.registerEvent("Runtime.inspectRequested",["object","hints"]);Protocol.inspectorBackend.registerCommand("Runtime.awaitPromise",[{"name":"promiseObjectId","type":"string","optional":false},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.callFunctionOn",[{"name":"functionDeclaration","type":"string","optional":false},{"name":"objectId","type":"string","optional":true},{"name":"arguments","type":"object","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"userGesture","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true},{"name":"executionContextId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.compileScript",[{"name":"expression","type":"string","optional":false},{"name":"sourceURL","type":"string","optional":false},{"name":"persistScript","type":"boolean","optional":false},{"name":"executionContextId","type":"number","optional":true}],["scriptId","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.disable",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.discardConsoleEntries",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.enable",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.evaluate",[{"name":"expression","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"contextId","type":"number","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"userGesture","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true},{"name":"throwOnSideEffect","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.getIsolateId",[],["id"],false);Protocol.inspectorBackend.registerCommand("Runtime.getHeapUsage",[],["usedSize","totalSize"],false);Protocol.inspectorBackend.registerCommand("Runtime.getProperties",[{"name":"objectId","type":"string","optional":false},{"name":"ownProperties","type":"boolean","optional":true},{"name":"accessorPropertiesOnly","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true}],["result","internalProperties","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.globalLexicalScopeNames",[{"name":"executionContextId","type":"number","optional":true}],["names"],false);Protocol.inspectorBackend.registerCommand("Runtime.queryObjects",[{"name":"prototypeObjectId","type":"string","optional":false},{"name":"objectGroup","type":"string","optional":true}],["objects"],false);Protocol.inspectorBackend.registerCommand("Runtime.releaseObject",[{"name":"objectId","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.releaseObjectGroup",[{"name":"objectGroup","type":"string","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.runIfWaitingForDebugger",[],[],false);Protocol.inspectorBackend.registerCommand("Runtime.runScript",[{"name":"scriptId","type":"string","optional":false},{"name":"executionContextId","type":"number","optional":true},{"name":"objectGroup","type":"string","optional":true},{"name":"silent","type":"boolean","optional":true},{"name":"includeCommandLineAPI","type":"boolean","optional":true},{"name":"returnByValue","type":"boolean","optional":true},{"name":"generatePreview","type":"boolean","optional":true},{"name":"awaitPromise","type":"boolean","optional":true}],["result","exceptionDetails"],false);Protocol.inspectorBackend.registerCommand("Runtime.setCustomObjectFormatterEnabled",[{"name":"enabled","type":"boolean","optional":false}],[],false);Protocol.inspectorBackend.registerCommand("Runtime.terminateExecution",[],[],false);Protocol.inspectorBackend.registerCommand("Schema.getDomains",[],["domains"],false);;self['SDK']=self['SDK']||{};SDK.Target=class extends Protocol.TargetBase{constructor(targetManager,id,name,capabilitiesMask,connectionFactory,parentTarget,suspended){super(connectionFactory);this._targetManager=targetManager;this._name=name;this._inspectedURL='';this._capabilitiesMask=capabilitiesMask;this._parentTarget=parentTarget;this._id=id;this._modelByConstructor=new Map();this._isSuspended=suspended;}
createModels(required){this._creatingModels=true;this.model(SDK.ResourceTreeModel);const registered=Array.from(SDK.SDKModel._registeredModels.keys());for(const modelClass of registered){const info=SDK.SDKModel._registeredModels.get(modelClass);if(info.autostart||required.has(modelClass))
this.model(modelClass);}
this._creatingModels=false;}
isNodeJS(){return this._capabilitiesMask===SDK.Target.Capability.JS||this._isNodeJSForTest;}
setIsNodeJSForTest(){this._isNodeJSForTest=true;}
id(){return this._id;}
name(){return this._name||this._inspectedURLName;}
targetManager(){return this._targetManager;}
hasAllCapabilities(capabilitiesMask){return(this._capabilitiesMask&capabilitiesMask)===capabilitiesMask;}
decorateLabel(label){return!this.hasBrowserCapability()?'\u2699 '+label:label;}
hasBrowserCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Browser);}
hasJSCapability(){return this.hasAllCapabilities(SDK.Target.Capability.JS);}
hasLogCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Log);}
hasNetworkCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Network);}
hasTargetCapability(){return this.hasAllCapabilities(SDK.Target.Capability.Target);}
hasDOMCapability(){return this.hasAllCapabilities(SDK.Target.Capability.DOM);}
parentTarget(){return this._parentTarget;}
dispose(){this._targetManager.removeTarget(this);for(const model of this._modelByConstructor.valuesArray())
model.dispose();}
model(modelClass){if(!this._modelByConstructor.get(modelClass)){const info=SDK.SDKModel._registeredModels.get(modelClass);if(info===undefined)
throw'Model class is not registered @'+new Error().stack;if((this._capabilitiesMask&info.capabilities)===info.capabilities){const model=new modelClass(this);this._modelByConstructor.set(modelClass,model);if(!this._creatingModels)
this._targetManager.modelAdded(this,modelClass,model);}}
return this._modelByConstructor.get(modelClass)||null;}
models(){return this._modelByConstructor;}
inspectedURL(){return this._inspectedURL;}
setInspectedURL(inspectedURL){this._inspectedURL=inspectedURL;const parsedURL=inspectedURL.asParsedURL();this._inspectedURLName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+this._id;if(!this.parentTarget())
InspectorFrontendHost.inspectedURLChanged(inspectedURL||'');this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.InspectedURLChanged,this);if(!this._name)
this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.NameChanged,this);}
suspend(){if(this._isSuspended)
return Promise.resolve();this._isSuspended=true;const promises=[];for(const model of this.models().values())
promises.push(model.suspendModel());return Promise.all(promises);}
resume(){if(!this._isSuspended)
return Promise.resolve();this._isSuspended=false;const promises=[];for(const model of this.models().values())
promises.push(model.resumeModel());return Promise.all(promises);}
suspended(){return this._isSuspended;}};SDK.Target.Capability={Browser:1<<0,DOM:1<<1,JS:1<<2,Log:1<<3,Network:1<<4,Target:1<<5,ScreenCapture:1<<6,Tracing:1<<7,Emulation:1<<8,Security:1<<9,Input:1<<10,Inspector:1<<11,DeviceEmulation:1<<12,None:0,AllForTests:(1<<13)-1};SDK.SDKModel=class extends Common.Object{constructor(target){super();this._target=target;}
target(){return this._target;}
suspendModel(){return Promise.resolve();}
resumeModel(){return Promise.resolve();}
dispose(){}};SDK.SDKModel.register=function(modelClass,capabilities,autostart){if(!SDK.SDKModel._registeredModels)
SDK.SDKModel._registeredModels=new Map();SDK.SDKModel._registeredModels.set(modelClass,{capabilities:capabilities,autostart:autostart});};SDK.SDKModel._registeredModels;;SDK.TargetManager=class extends Common.Object{constructor(){super();this._targets=[];this._observers=[];this._observerCapabiliesMaskSymbol=Symbol('observerCapabilitiesMask');this._modelListeners=new Map();this._modelObservers=new Map();this._isSuspended=false;}
suspendAllTargets(){if(this._isSuspended)
return Promise.resolve();this._isSuspended=true;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);return Promise.all(this._targets.map(target=>target.suspend()));}
resumeAllTargets(){if(!this._isSuspended)
return Promise.resolve();this._isSuspended=false;this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged);return Promise.all(this._targets.map(target=>target.resume()));}
allTargetsSuspended(){return this._isSuspended;}
models(modelClass){const result=[];for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
result.push(model);}
return result;}
inspectedURL(){return this._targets[0]?this._targets[0].inspectedURL():'';}
observeModels(modelClass,observer){if(!this._modelObservers.has(modelClass))
this._modelObservers.set(modelClass,[]);this._modelObservers.get(modelClass).push(observer);for(const model of this.models(modelClass))
observer.modelAdded(model);}
unobserveModels(modelClass,observer){if(!this._modelObservers.has(modelClass))
return;const observers=this._modelObservers.get(modelClass);observers.remove(observer);if(!observers.length)
this._modelObservers.delete(modelClass);}
modelAdded(target,modelClass,model){if(!this._modelObservers.has(modelClass))
return;for(const observer of this._modelObservers.get(modelClass).slice())
observer.modelAdded(model);}
_modelRemoved(target,modelClass,model){if(!this._modelObservers.has(modelClass))
return;for(const observer of this._modelObservers.get(modelClass).slice())
observer.modelRemoved(model);}
addModelListener(modelClass,eventType,listener,thisObject){for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
model.addEventListener(eventType,listener,thisObject);}
if(!this._modelListeners.has(eventType))
this._modelListeners.set(eventType,[]);this._modelListeners.get(eventType).push({modelClass:modelClass,thisObject:thisObject,listener:listener});}
removeModelListener(modelClass,eventType,listener,thisObject){if(!this._modelListeners.has(eventType))
return;for(let i=0;i<this._targets.length;++i){const model=this._targets[i].model(modelClass);if(model)
model.removeEventListener(eventType,listener,thisObject);}
const listeners=this._modelListeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].modelClass===modelClass&&listeners[i].listener===listener&&listeners[i].thisObject===thisObject)
listeners.splice(i--,1);}
if(!listeners.length)
this._modelListeners.delete(eventType);}
observeTargets(targetObserver,capabilitiesMask){if(this._observerCapabiliesMaskSymbol in targetObserver)
throw new Error('Observer can only be registered once');targetObserver[this._observerCapabiliesMaskSymbol]=capabilitiesMask||0;this.targets(capabilitiesMask).forEach(targetObserver.targetAdded.bind(targetObserver));this._observers.push(targetObserver);}
unobserveTargets(targetObserver){delete targetObserver[this._observerCapabiliesMaskSymbol];this._observers.remove(targetObserver);}
createTarget(id,name,capabilitiesMask,connectionFactory,parentTarget){const target=new SDK.Target(this,id,name,capabilitiesMask,connectionFactory,parentTarget,this._isSuspended);target.createModels(new Set(this._modelObservers.keys()));this._targets.push(target);const copy=this._observersForTarget(target);for(let i=0;i<copy.length;++i)
copy[i].targetAdded(target);for(const modelClass of target.models().keys())
this.modelAdded(target,modelClass,target.models().get(modelClass));for(const pair of this._modelListeners){const listeners=pair[1];for(let i=0;i<listeners.length;++i){const model=target.model(listeners[i].modelClass);if(model)
model.addEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}}
return target;}
_observersForTarget(target){return this._observers.filter(observer=>target.hasAllCapabilities(observer[this._observerCapabiliesMaskSymbol]||0));}
removeTarget(target){if(!this._targets.includes(target))
return;this._targets.remove(target);for(const modelClass of target.models().keys())
this._modelRemoved(target,modelClass,target.models().get(modelClass));const copy=this._observersForTarget(target);for(let i=0;i<copy.length;++i)
copy[i].targetRemoved(target);for(const pair of this._modelListeners){const listeners=pair[1];for(let i=0;i<listeners.length;++i){const model=target.model(listeners[i].modelClass);if(model)
model.removeEventListener((pair[0]),listeners[i].listener,listeners[i].thisObject);}}}
targets(capabilitiesMask){if(!capabilitiesMask)
return this._targets.slice();else
return this._targets.filter(target=>target.hasAllCapabilities(capabilitiesMask||0));}
targetById(id){for(let i=0;i<this._targets.length;++i){if(this._targets[i].id()===id)
return this._targets[i];}
return null;}
mainTarget(){return this._targets[0]||null;}};SDK.TargetManager.Events={AvailableTargetsChanged:Symbol('AvailableTargetsChanged'),InspectedURLChanged:Symbol('InspectedURLChanged'),NameChanged:Symbol('NameChanged'),SuspendStateChanged:Symbol('SuspendStateChanged')};SDK.TargetManager.Observer=function(){};SDK.TargetManager.Observer.prototype={targetAdded(target){},targetRemoved(target){},};SDK.SDKModelObserver=function(){};SDK.SDKModelObserver.prototype={modelAdded(model){},modelRemoved(model){},};SDK.targetManager=new SDK.TargetManager();;SDK.MainConnection=class{constructor(params){this._onMessage=params.onMessage;this._onDisconnect=params.onDisconnect;this._disconnected=false;this._eventListeners=[InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessage,this._dispatchMessage,this),InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessageChunk,this._dispatchMessageChunk,this),];}
sendMessage(message){if(!this._disconnected)
InspectorFrontendHost.sendMessageToBackend(message);}
_dispatchMessage(event){this._onMessage.call(null,(event.data));}
_dispatchMessageChunk(event){const messageChunk=(event.data['messageChunk']);const messageSize=(event.data['messageSize']);if(messageSize){this._messageBuffer='';this._messageSize=messageSize;}
this._messageBuffer+=messageChunk;if(this._messageBuffer.length===this._messageSize){this._onMessage.call(null,this._messageBuffer);this._messageBuffer='';this._messageSize=0;}}
disconnect(){const onDisconnect=this._onDisconnect;Common.EventTarget.removeEventListeners(this._eventListeners);this._onDisconnect=null;this._onMessage=null;this._disconnected=true;let fulfill;const promise=new Promise(f=>fulfill=f);InspectorFrontendHost.reattach(()=>{onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.WebSocketConnection=class{constructor(url,onWebSocketDisconnect,params){this._socket=new WebSocket(url);this._socket.onerror=this._onError.bind(this);this._socket.onopen=this._onOpen.bind(this);this._socket.onmessage=messageEvent=>params.onMessage.call(null,(messageEvent.data));this._socket.onclose=this._onClose.bind(this);this._onDisconnect=params.onDisconnect;this._onWebSocketDisconnect=onWebSocketDisconnect;this._connected=false;this._messages=[];}
_onError(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'connection failed');this._close();}
_onOpen(){this._socket.onerror=console.error;this._connected=true;for(const message of this._messages)
this._socket.send(message);this._messages=[];}
_onClose(){this._onWebSocketDisconnect.call(null);this._onDisconnect.call(null,'websocket closed');this._close();}
_close(callback){this._socket.onerror=null;this._socket.onopen=null;this._socket.onclose=callback||null;this._socket.onmessage=null;this._socket.close();this._socket=null;this._onWebSocketDisconnect=null;}
sendMessage(message){if(this._connected)
this._socket.send(message);else
this._messages.push(message);}
disconnect(){let fulfill;const promise=new Promise(f=>fulfill=f);this._close(()=>{this._onDisconnect.call(null,'force disconnect');fulfill();});return promise;}};SDK.StubConnection=class{constructor(params){this._onMessage=params.onMessage;this._onDisconnect=params.onDisconnect;}
sendMessage(message){setTimeout(this._respondWithError.bind(this,message),0);}
_respondWithError(message){const messageObject=JSON.parse(message);const error={message:'This is a stub connection, can\'t dispatch message.',code:Protocol.InspectorBackend.DevToolsStubErrorCode,data:messageObject};this._onMessage.call(null,{id:messageObject.id,error:error});}
disconnect(){this._onDisconnect.call(null,'force disconnect');this._onDisconnect=null;this._onMessage=null;return Promise.resolve();}};SDK.ChildConnection=class{constructor(agent,sessionId,params){this._agent=agent;this._sessionId=sessionId;this.onMessage=params.onMessage;this.onDisconnect=params.onDisconnect;}
sendMessage(message){this._agent.sendMessageToTarget(message,this._sessionId);}
disconnect(){throw'Not implemented';}};SDK.createMainConnection=function(params,connectionLostCallback){const wsParam=Runtime.queryParam('ws');const wssParam=Runtime.queryParam('wss');if(wsParam||wssParam){const ws=wsParam?`ws://${wsParam}`:`wss://${wssParam}`;return new SDK.WebSocketConnection(ws,connectionLostCallback,params);}
if(InspectorFrontendHost.isHostedMode())
return new SDK.StubConnection(params);return new SDK.MainConnection(params);};;SDK.CompilerSourceMappingContentProvider=class{constructor(sourceURL,contentType){this._sourceURL=sourceURL;this._contentType=contentType;}
contentURL(){return this._sourceURL;}
contentType(){return this._contentType;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){let callback;const promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(this._sourceURL,contentLoaded.bind(this));return promise;function contentLoaded(statusCode,headers,content){if(statusCode>=400){console.error('Could not load content for '+this._sourceURL+' : '+'HTTP status code: '+statusCode);callback(null);return;}
callback(content);}}
async searchInContent(query,caseSensitive,isRegex){const content=await this.requestContent();if(typeof content!=='string')
return[];return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}};;SDK.CookieModel=class extends SDK.SDKModel{constructor(target){super(target);}
static _parseProtocolCookie(protocolCookie){const cookie=new SDK.Cookie(protocolCookie.name,protocolCookie.value,null);cookie.addAttribute('domain',protocolCookie['domain']);cookie.addAttribute('path',protocolCookie['path']);cookie.addAttribute('port',protocolCookie['port']);if(protocolCookie['expires'])
cookie.addAttribute('expires',protocolCookie['expires']*1000);if(protocolCookie['httpOnly'])
cookie.addAttribute('httpOnly');if(protocolCookie['secure'])
cookie.addAttribute('secure');if(protocolCookie['sameSite'])
cookie.addAttribute('sameSite',protocolCookie['sameSite']);cookie.setSize(protocolCookie['size']);return cookie;}
static cookieMatchesResourceURL(cookie,resourceURL){const url=resourceURL.asParsedURL();if(!url||!SDK.CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(),url.host))
return false;return(url.path.startsWith(cookie.path())&&(!cookie.port()||url.port===cookie.port())&&(!cookie.secure()||url.scheme==='https'));}
static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain){if(cookieDomain.charAt(0)!=='.')
return resourceDomain===cookieDomain;return!!resourceDomain.match(new RegExp('^([^\\.]+\\.)*'+cookieDomain.substring(1).escapeForRegExp()+'$','i'));}
getCookies(urls){return this.target().networkAgent().getCookies(urls).then(cookies=>(cookies||[]).map(cookie=>SDK.CookieModel._parseProtocolCookie(cookie)));}
deleteCookie(cookie,callback){this._deleteAll([cookie],callback);}
clear(domain,callback){this.getCookiesForDomain(domain||null).then(cookies=>this._deleteAll(cookies,callback));}
saveCookie(cookie){let domain=cookie.domain();if(!domain.startsWith('.'))
domain='';let expires=undefined;if(cookie.expires())
expires=Math.floor(Date.parse(cookie.expires())/1000);return this.target().networkAgent().setCookie(cookie.name(),cookie.value(),cookie.url(),domain,cookie.path(),cookie.secure(),cookie.httpOnly(),cookie.sameSite(),expires).then(success=>!!success);}
getCookiesForDomain(domain){const resourceURLs=[];function populateResourceURLs(resource){const url=resource.documentURL.asParsedURL();if(url&&(!domain||url.securityOrigin()===domain))
resourceURLs.push(resource.url);}
const resourceTreeModel=this.target().model(SDK.ResourceTreeModel);if(resourceTreeModel)
resourceTreeModel.forAllResources(populateResourceURLs);return this.getCookies(resourceURLs);}
_deleteAll(cookies,callback){const networkAgent=this.target().networkAgent();Promise.all(cookies.map(cookie=>networkAgent.deleteCookies(cookie.name(),undefined,cookie.domain(),cookie.path()))).then(callback||function(){});}};SDK.SDKModel.register(SDK.CookieModel,SDK.Target.Capability.Network,false);;SDK.CookieParser=class{constructor(){}
static parseCookie(header){return(new SDK.CookieParser()).parseCookie(header);}
static parseSetCookie(header){return(new SDK.CookieParser()).parseSetCookie(header);}
cookies(){return this._cookies;}
parseCookie(cookieHeader){if(!this._initialize(cookieHeader))
return null;for(let kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(kv.key.charAt(0)==='$'&&this._lastCookie)
this._lastCookie.addAttribute(kv.key.slice(1),kv.value);else if(kv.key.toLowerCase()!=='$version'&&typeof kv.value==='string')
this._addCookie(kv,SDK.Cookie.Type.Request);this._advanceAndCheckCookieDelimiter();}
this._flushCookie();return this._cookies;}
parseSetCookie(setCookieHeader){if(!this._initialize(setCookieHeader))
return null;for(let kv=this._extractKeyValue();kv;kv=this._extractKeyValue()){if(this._lastCookie)
this._lastCookie.addAttribute(kv.key,kv.value);else
this._addCookie(kv,SDK.Cookie.Type.Response);if(this._advanceAndCheckCookieDelimiter())
this._flushCookie();}
this._flushCookie();return this._cookies;}
_initialize(headerValue){this._input=headerValue;if(typeof headerValue!=='string')
return false;this._cookies=[];this._lastCookie=null;this._originalInputLength=this._input.length;return true;}
_flushCookie(){if(this._lastCookie)
this._lastCookie.setSize(this._originalInputLength-this._input.length-this._lastCookiePosition);this._lastCookie=null;}
_extractKeyValue(){if(!this._input||!this._input.length)
return null;const keyValueMatch=/^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input);if(!keyValueMatch){console.error('Failed parsing cookie header before: '+this._input);return null;}
const result=new SDK.CookieParser.KeyValue(keyValueMatch[1],keyValueMatch[2]&&keyValueMatch[2].trim(),this._originalInputLength-this._input.length);this._input=this._input.slice(keyValueMatch[0].length);return result;}
_advanceAndCheckCookieDelimiter(){const match=/^\s*[\n;]\s*/.exec(this._input);if(!match)
return false;this._input=this._input.slice(match[0].length);return match[0].match('\n')!==null;}
_addCookie(keyValue,type){if(this._lastCookie)
this._lastCookie.setSize(keyValue.position-this._lastCookiePosition);this._lastCookie=typeof keyValue.value==='string'?new SDK.Cookie(keyValue.key,keyValue.value,type):new SDK.Cookie('',keyValue.key,type);this._lastCookiePosition=keyValue.position;this._cookies.push(this._lastCookie);}};SDK.CookieParser.KeyValue=class{constructor(key,value,position){this.key=key;this.value=value;this.position=position;}};SDK.Cookie=class{constructor(name,value,type){this._name=name;this._value=value;this._type=type;this._attributes={};this._size=0;}
name(){return this._name;}
value(){return this._value;}
type(){return this._type;}
httpOnly(){return'httponly'in this._attributes;}
secure(){return'secure'in this._attributes;}
sameSite(){return(this._attributes['samesite']);}
session(){return!('expires'in this._attributes||'max-age'in this._attributes);}
path(){return this._attributes['path'];}
port(){return this._attributes['port'];}
domain(){return this._attributes['domain'];}
expires(){return this._attributes['expires'];}
maxAge(){return this._attributes['max-age'];}
size(){return this._size;}
url(){return(this.secure()?'https://':'http://')+this.domain()+this.path();}
setSize(size){this._size=size;}
expiresDate(requestDate){if(this.maxAge()){const targetDate=requestDate===null?new Date():requestDate;return new Date(targetDate.getTime()+1000*this.maxAge());}
if(this.expires())
return new Date(this.expires());return null;}
attributes(){return this._attributes;}
addAttribute(key,value){this._attributes[key.toLowerCase()]=value;}};SDK.Cookie.Type={Request:0,Response:1};;SDK.ProfileNode=class{constructor(callFrame){this.callFrame=callFrame;this.callUID=`${this.callFrame.functionName}@${this.callFrame.scriptId}:${this.callFrame.lineNumber}`;this.self=0;this.total=0;this.id=0;this.parent=null;this.children=[];}
get functionName(){return this.callFrame.functionName;}
get scriptId(){return this.callFrame.scriptId;}
get url(){return this.callFrame.url;}
get lineNumber(){return this.callFrame.lineNumber;}
get columnNumber(){return this.callFrame.columnNumber;}};SDK.ProfileTreeModel=class{initialize(root){this.root=root;this._assignDepthsAndParents();this.total=this._calculateTotals(this.root);}
_assignDepthsAndParents(){const root=this.root;root.depth=-1;root.parent=null;this.maxDepth=0;const nodesToTraverse=[root];while(nodesToTraverse.length){const parent=nodesToTraverse.pop();const depth=parent.depth+1;if(depth>this.maxDepth)
this.maxDepth=depth;const children=parent.children;const length=children.length;for(let i=0;i<length;++i){const child=children[i];child.depth=depth;child.parent=parent;if(child.children.length)
nodesToTraverse.push(child);}}}
_calculateTotals(root){const nodesToTraverse=[root];const dfsList=[];while(nodesToTraverse.length){const node=nodesToTraverse.pop();node.total=node.self;dfsList.push(node);nodesToTraverse.push(...node.children);}
while(dfsList.length>1){const node=dfsList.pop();node.parent.total+=node.total;}
return root.total;}};;SDK.ServerTiming=class{constructor(metric,value,description){this.metric=metric;this.value=value;this.description=description;}
static parseHeaders(headers){const rawServerTimingHeaders=headers.filter(item=>item.name.toLowerCase()==='server-timing');if(!rawServerTimingHeaders.length)
return null;const serverTimings=rawServerTimingHeaders.reduce((memo,header)=>{const timing=this.createFromHeaderValue(header.value);memo.pushAll(timing.map(function(entry){return new SDK.ServerTiming(entry.name,entry.hasOwnProperty('dur')?entry.dur:null,entry.hasOwnProperty('desc')?entry.desc:'');}));return memo;},[]);serverTimings.sort((a,b)=>a.metric.toLowerCase().compareTo(b.metric.toLowerCase()));return serverTimings;}
static createFromHeaderValue(valueString){function trimLeadingWhiteSpace(){valueString=valueString.replace(/^\s*/,'');}
function consumeDelimiter(char){console.assert(char.length===1);trimLeadingWhiteSpace();if(valueString.charAt(0)!==char)
return false;valueString=valueString.substring(1);return true;}
function consumeToken(){const result=/^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(valueString);if(!result)
return null;valueString=result[2];return result[1];}
function consumeTokenOrQuotedString(){trimLeadingWhiteSpace();if(valueString.charAt(0)==='"')
return consumeQuotedString();return consumeToken();}
function consumeQuotedString(){console.assert(valueString.charAt(0)==='"');valueString=valueString.substring(1);let value='';while(valueString.length){const result=/^([^"\\]*)(.*)/.exec(valueString);value+=result[1];if(result[2].charAt(0)==='"'){valueString=result[2].substring(1);return value;}
console.assert(result[2].charAt(0)==='\\');value+=result[2].charAt(1);valueString=result[2].substring(2);}
return null;}
function consumeExtraneous(){const result=/([,;].*)/.exec(valueString);if(result)
valueString=result[1];}
const result=[];let name;while((name=consumeToken())!==null){const entry={name};if(valueString.charAt(0)==='=')
this.showWarning(ls`Deprecated syntax found. Please use: <name>;dur=<duration>;desc=<description>`);while(consumeDelimiter(';')){let paramName;if((paramName=consumeToken())===null)
continue;paramName=paramName.toLowerCase();const parseParameter=this.getParserForParameter(paramName);let paramValue=null;if(consumeDelimiter('=')){paramValue=consumeTokenOrQuotedString();consumeExtraneous();}
if(parseParameter){if(entry.hasOwnProperty(paramName)){this.showWarning(ls`Duplicate parameter \"${paramName}\" ignored.`);continue;}
if(paramValue===null)
this.showWarning(ls`No value found for parameter \"${paramName}\".`);parseParameter.call(this,entry,paramValue);}else{this.showWarning(ls`Unrecognized parameter \"${paramName}\".`);}}
result.push(entry);if(!consumeDelimiter(','))
break;}
if(valueString.length)
this.showWarning(ls`Extraneous trailing characters.`);return result;}
static getParserForParameter(paramName){switch(paramName){case'dur':return function(entry,paramValue){entry.dur=0;if(paramValue!==null){const duration=parseFloat(paramValue);if(isNaN(duration)){this.showWarning(ls`Unable to parse \"${paramName}\" value \"${paramValue}\".`);return;}
entry.dur=duration;}};case'desc':return function(entry,paramValue){entry.desc=paramValue||'';};default:return null;}}
static showWarning(msg){Common.console.warn(Common.UIString(`ServerTiming: ${msg}`));}};;SDK.CPUProfileNode=class extends SDK.ProfileNode{constructor(node,sampleTime){const callFrame=node.callFrame||({functionName:node['functionName'],scriptId:node['scriptId'],url:node['url'],lineNumber:node['lineNumber']-1,columnNumber:node['columnNumber']-1});super(callFrame);this.id=node.id;this.self=node.hitCount*sampleTime;this.positionTicks=node.positionTicks;this.deoptReason=node.deoptReason&&node.deoptReason!=='no reason'?node.deoptReason:null;}};SDK.CPUProfileDataModel=class extends SDK.ProfileTreeModel{constructor(profile){super();const isLegacyFormat=!!profile['head'];if(isLegacyFormat){this.profileStartTime=profile.startTime*1000;this.profileEndTime=profile.endTime*1000;this.timestamps=profile.timestamps;this._compatibilityConversionHeadToNodes(profile);}else{this.profileStartTime=profile.startTime/1000;this.profileEndTime=profile.endTime/1000;this.timestamps=this._convertTimeDeltas(profile);}
this.samples=profile.samples;this.totalHitCount=0;this.profileHead=this._translateProfileTree(profile.nodes);this.initialize(this.profileHead);this._extractMetaNodes();if(this.samples){this._buildIdToNodeMap();this._sortSamples();this._normalizeTimestamps();this._fixMissingSamples();}}
_compatibilityConversionHeadToNodes(profile){if(!profile.head||profile.nodes)
return;const nodes=[];convertNodesTree(profile.head);profile.nodes=nodes;delete profile.head;function convertNodesTree(node){nodes.push(node);node.children=((node.children)).map(convertNodesTree);return node.id;}}
_convertTimeDeltas(profile){if(!profile.timeDeltas)
return null;let lastTimeUsec=profile.startTime;const timestamps=new Array(profile.timeDeltas.length+1);for(let i=0;i<profile.timeDeltas.length;++i){timestamps[i]=lastTimeUsec;lastTimeUsec+=profile.timeDeltas[i];}
timestamps[profile.timeDeltas.length]=lastTimeUsec;return timestamps;}
_translateProfileTree(nodes){function isNativeNode(node){if(node.callFrame)
return!!node.callFrame.url&&node.callFrame.url.startsWith('native ');return!!node['url']&&node['url'].startsWith('native ');}
function buildChildrenFromParents(nodes){if(nodes[0].children)
return;nodes[0].children=[];for(let i=1;i<nodes.length;++i){const node=nodes[i];const parentNode=nodeByIdMap.get(node.parent);if(parentNode.children)
parentNode.children.push(node.id);else
parentNode.children=[node.id];}}
const nodeByIdMap=new Map();for(let i=0;i<nodes.length;++i){const node=nodes[i];nodeByIdMap.set(node.id,node);}
buildChildrenFromParents(nodes);this.totalHitCount=nodes.reduce((acc,node)=>acc+node.hitCount,0);const sampleTime=(this.profileEndTime-this.profileStartTime)/this.totalHitCount;const keepNatives=!!Common.moduleSetting('showNativeFunctionsInJSProfile').get();const root=nodes[0];const idMap=new Map([[root.id,root.id]]);const resultRoot=new SDK.CPUProfileNode(root,sampleTime);const parentNodeStack=root.children.map(()=>resultRoot);const sourceNodeStack=root.children.map(id=>nodeByIdMap.get(id));while(sourceNodeStack.length){let parentNode=parentNodeStack.pop();const sourceNode=sourceNodeStack.pop();if(!sourceNode.children)
sourceNode.children=[];const targetNode=new SDK.CPUProfileNode(sourceNode,sampleTime);if(keepNatives||!isNativeNode(sourceNode)){parentNode.children.push(targetNode);parentNode=targetNode;}else{parentNode.self+=targetNode.self;}
idMap.set(sourceNode.id,parentNode.id);parentNodeStack.push.apply(parentNodeStack,sourceNode.children.map(()=>parentNode));sourceNodeStack.push.apply(sourceNodeStack,sourceNode.children.map(id=>nodeByIdMap.get(id)));}
if(this.samples)
this.samples=this.samples.map(id=>idMap.get(id));return resultRoot;}
_sortSamples(){const timestamps=this.timestamps;if(!timestamps)
return;const samples=this.samples;const indices=timestamps.map((x,index)=>index);indices.sort((a,b)=>timestamps[a]-timestamps[b]);for(let i=0;i<timestamps.length;++i){let index=indices[i];if(index===i)
continue;const savedTimestamp=timestamps[i];const savedSample=samples[i];let currentIndex=i;while(index!==i){samples[currentIndex]=samples[index];timestamps[currentIndex]=timestamps[index];currentIndex=index;index=indices[index];indices[currentIndex]=currentIndex;}
samples[currentIndex]=savedSample;timestamps[currentIndex]=savedTimestamp;}}
_normalizeTimestamps(){let timestamps=this.timestamps;if(!timestamps){const profileStartTime=this.profileStartTime;const interval=(this.profileEndTime-profileStartTime)/this.samples.length;timestamps=new Float64Array(this.samples.length+1);for(let i=0;i<timestamps.length;++i)
timestamps[i]=profileStartTime+i*interval;this.timestamps=timestamps;return;}
for(let i=0;i<timestamps.length;++i)
timestamps[i]/=1000;if(this.samples.length===timestamps.length){const averageSample=(timestamps.peekLast()-timestamps[0])/(timestamps.length-1);this.timestamps.push(timestamps.peekLast()+averageSample);}
this.profileStartTime=timestamps[0];this.profileEndTime=timestamps.peekLast();}
_buildIdToNodeMap(){this._idToNode=new Map();const idToNode=this._idToNode;const stack=[this.profileHead];while(stack.length){const node=stack.pop();idToNode.set(node.id,node);stack.push.apply(stack,node.children);}}
_extractMetaNodes(){const topLevelNodes=this.profileHead.children;for(let i=0;i<topLevelNodes.length&&!(this.gcNode&&this.programNode&&this.idleNode);i++){const node=topLevelNodes[i];if(node.functionName==='(garbage collector)')
this.gcNode=node;else if(node.functionName==='(program)')
this.programNode=node;else if(node.functionName==='(idle)')
this.idleNode=node;}}
_fixMissingSamples(){const samples=this.samples;const samplesCount=samples.length;if(!this.programNode||samplesCount<3)
return;const idToNode=this._idToNode;const programNodeId=this.programNode.id;const gcNodeId=this.gcNode?this.gcNode.id:-1;const idleNodeId=this.idleNode?this.idleNode.id:-1;let prevNodeId=samples[0];let nodeId=samples[1];let count=0;for(let sampleIndex=1;sampleIndex<samplesCount-1;sampleIndex++){const nextNodeId=samples[sampleIndex+1];if(nodeId===programNodeId&&!isSystemNode(prevNodeId)&&!isSystemNode(nextNodeId)&&bottomNode(idToNode.get(prevNodeId))===bottomNode(idToNode.get(nextNodeId))){++count;samples[sampleIndex]=prevNodeId;}
prevNodeId=nodeId;nodeId=nextNodeId;}
Common.console.warn(ls`DevTools: CPU profile parser is fixing ${count} missing samples.`);function bottomNode(node){while(node.parent&&node.parent.parent)
node=node.parent;return node;}
function isSystemNode(nodeId){return nodeId===programNodeId||nodeId===gcNodeId||nodeId===idleNodeId;}}
forEachFrame(openFrameCallback,closeFrameCallback,startTime,stopTime){if(!this.profileHead||!this.samples)
return;startTime=startTime||0;stopTime=stopTime||Infinity;const samples=this.samples;const timestamps=this.timestamps;const idToNode=this._idToNode;const gcNode=this.gcNode;const samplesCount=samples.length;const startIndex=timestamps.lowerBound(startTime);let stackTop=0;const stackNodes=[];let prevId=this.profileHead.id;let sampleTime;let gcParentNode=null;const stackDepth=this.maxDepth+3;if(!this._stackStartTimes)
this._stackStartTimes=new Float64Array(stackDepth);const stackStartTimes=this._stackStartTimes;if(!this._stackChildrenDuration)
this._stackChildrenDuration=new Float64Array(stackDepth);const stackChildrenDuration=this._stackChildrenDuration;let node;let sampleIndex;for(sampleIndex=startIndex;sampleIndex<samplesCount;sampleIndex++){sampleTime=timestamps[sampleIndex];if(sampleTime>=stopTime)
break;const id=samples[sampleIndex];if(id===prevId)
continue;node=idToNode.get(id);let prevNode=idToNode.get(prevId);if(node===gcNode){gcParentNode=prevNode;openFrameCallback(gcParentNode.depth+1,gcNode,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;prevId=id;continue;}
if(prevNode===gcNode){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,gcNode,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevNode=gcParentNode;prevId=prevNode.id;gcParentNode=null;}
while(node.depth>prevNode.depth){stackNodes.push(node);node=node.parent;}
while(prevNode!==node){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(prevNode.depth,(prevNode),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;if(node.depth===prevNode.depth){stackNodes.push(node);node=node.parent;}
prevNode=prevNode.parent;}
while(stackNodes.length){node=stackNodes.pop();openFrameCallback(node.depth,node,sampleTime);stackStartTimes[++stackTop]=sampleTime;stackChildrenDuration[stackTop]=0;}
prevId=id;}
sampleTime=timestamps[sampleIndex]||this.profileEndTime;if(idToNode.get(prevId)===gcNode){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(gcParentNode.depth+1,node,start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;prevId=gcParentNode.id;}
for(let node=idToNode.get(prevId);node.parent;node=node.parent){const start=stackStartTimes[stackTop];const duration=sampleTime-start;stackChildrenDuration[stackTop-1]+=duration;closeFrameCallback(node.depth,(node),start,duration,duration-stackChildrenDuration[stackTop]);--stackTop;}}
nodeByIndex(index){return this._idToNode.get(this.samples[index])||null;}};;SDK.CPUProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._isRecording=false;this._nextAnonymousConsoleProfileNumber=1;this._anonymousConsoleProfileIdToTitle=new Map();this._profilerAgent=target.profilerAgent();target.registerProfilerDispatcher(this);this._profilerAgent.enable();this._debuggerModel=(target.model(SDK.DebuggerModel));}
runtimeModel(){return this._debuggerModel.runtimeModel();}
debuggerModel(){return this._debuggerModel;}
consoleProfileStarted(id,scriptLocation,title){if(!title){title=Common.UIString('Profile %d',this._nextAnonymousConsoleProfileNumber++);this._anonymousConsoleProfileIdToTitle.set(id,title);}
this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,id,scriptLocation,title);}
consoleProfileFinished(id,scriptLocation,cpuProfile,title){if(!title){title=this._anonymousConsoleProfileIdToTitle.get(id);this._anonymousConsoleProfileIdToTitle.delete(id);}
self.runtime.loadModulePromise('profiler').then(()=>{this._dispatchProfileEvent(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,id,scriptLocation,title,cpuProfile);});}
_dispatchProfileEvent(eventName,id,scriptLocation,title,cpuProfile){const debuggerLocation=SDK.DebuggerModel.Location.fromPayload(this._debuggerModel,scriptLocation);const globalId=this.target().id()+'.'+id;const data=({id:globalId,scriptLocation:debuggerLocation,cpuProfile:cpuProfile,title:title,cpuProfilerModel:this});this.dispatchEventToListeners(eventName,data);}
isRecordingProfile(){return this._isRecording;}
startRecording(){this._isRecording=true;const intervalUs=Common.moduleSetting('highResolutionCpuProfiling').get()?100:1000;this._profilerAgent.setSamplingInterval(intervalUs);return this._profilerAgent.start();}
stopRecording(){this._isRecording=false;return this._profilerAgent.stop();}
startPreciseCoverage(){const callCount=false;const detailed=true;return this._profilerAgent.startPreciseCoverage(callCount,detailed);}
takePreciseCoverage(){return this._profilerAgent.takePreciseCoverage().then(result=>result||[]);}
stopPreciseCoverage(){return this._profilerAgent.stopPreciseCoverage();}
bestEffortCoverage(){return this._profilerAgent.getBestEffortCoverage().then(result=>result||[]);}};SDK.SDKModel.register(SDK.CPUProfilerModel,SDK.Target.Capability.JS,true);SDK.CPUProfilerModel.Events={ConsoleProfileStarted:Symbol('ConsoleProfileStarted'),ConsoleProfileFinished:Symbol('ConsoleProfileFinished')};SDK.CPUProfilerModel.EventData;;SDK.CSSMatchedStyles=class{constructor(cssModel,node,inlinePayload,attributesPayload,matchedPayload,pseudoPayload,inheritedPayload,animationsPayload){this._cssModel=cssModel;this._node=node;this._addedStyles=new Map();this._matchingSelectors=new Map();this._keyframes=[];if(animationsPayload)
this._keyframes=animationsPayload.map(rule=>new SDK.CSSKeyframesRule(cssModel,rule));this._nodeForStyle=new Map();this._inheritedStyles=new Set();this._mainDOMCascade=this._buildMainCascade(inlinePayload,attributesPayload,matchedPayload,inheritedPayload);this._pseudoDOMCascades=this._buildPseudoCascades(pseudoPayload);this._styleToDOMCascade=new Map();for(const domCascade of Array.from(this._pseudoDOMCascades.values()).concat(this._mainDOMCascade)){for(const style of domCascade.styles())
this._styleToDOMCascade.set(style,domCascade);}}
_buildMainCascade(inlinePayload,attributesPayload,matchedPayload,inheritedPayload){const nodeCascades=[];const nodeStyles=[];function addAttributesStyle(){if(!attributesPayload)
return;const style=new SDK.CSSStyleDeclaration(this._cssModel,null,attributesPayload,SDK.CSSStyleDeclaration.Type.Attributes);this._nodeForStyle.set(style,this._node);nodeStyles.push(style);}
if(inlinePayload&&this._node.nodeType()===Node.ELEMENT_NODE){const style=new SDK.CSSStyleDeclaration(this._cssModel,null,inlinePayload,SDK.CSSStyleDeclaration.Type.Inline);this._nodeForStyle.set(style,this._node);nodeStyles.push(style);}
let addedAttributesStyle;for(let i=matchedPayload.length-1;i>=0;--i){const rule=new SDK.CSSStyleRule(this._cssModel,matchedPayload[i].rule);if((rule.isInjected()||rule.isUserAgent())&&!addedAttributesStyle){addedAttributesStyle=true;addAttributesStyle.call(this);}
this._nodeForStyle.set(rule.style,this._node);nodeStyles.push(rule.style);this._addMatchingSelectors(this._node,rule,matchedPayload[i].matchingSelectors);}
if(!addedAttributesStyle)
addAttributesStyle.call(this);nodeCascades.push(new SDK.CSSMatchedStyles.NodeCascade(this,nodeStyles,false));let parentNode=this._node.parentNode;for(let i=0;parentNode&&inheritedPayload&&i<inheritedPayload.length;++i){const inheritedStyles=[];const entryPayload=inheritedPayload[i];const inheritedInlineStyle=entryPayload.inlineStyle?new SDK.CSSStyleDeclaration(this._cssModel,null,entryPayload.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline):null;if(inheritedInlineStyle&&this._containsInherited(inheritedInlineStyle)){this._nodeForStyle.set(inheritedInlineStyle,parentNode);inheritedStyles.push(inheritedInlineStyle);this._inheritedStyles.add(inheritedInlineStyle);}
const inheritedMatchedCSSRules=entryPayload.matchedCSSRules||[];for(let j=inheritedMatchedCSSRules.length-1;j>=0;--j){const inheritedRule=new SDK.CSSStyleRule(this._cssModel,inheritedMatchedCSSRules[j].rule);this._addMatchingSelectors(parentNode,inheritedRule,inheritedMatchedCSSRules[j].matchingSelectors);if(!this._containsInherited(inheritedRule.style))
continue;this._nodeForStyle.set(inheritedRule.style,parentNode);inheritedStyles.push(inheritedRule.style);this._inheritedStyles.add(inheritedRule.style);}
parentNode=parentNode.parentNode;nodeCascades.push(new SDK.CSSMatchedStyles.NodeCascade(this,inheritedStyles,true));}
return new SDK.CSSMatchedStyles.DOMInheritanceCascade(nodeCascades);}
_buildPseudoCascades(pseudoPayload){const pseudoCascades=new Map();if(!pseudoPayload)
return pseudoCascades;for(let i=0;i<pseudoPayload.length;++i){const entryPayload=pseudoPayload[i];const pseudoElement=this._node.pseudoElements().get(entryPayload.pseudoType)||null;const pseudoStyles=[];const rules=entryPayload.matches||[];for(let j=rules.length-1;j>=0;--j){const pseudoRule=new SDK.CSSStyleRule(this._cssModel,rules[j].rule);pseudoStyles.push(pseudoRule.style);this._nodeForStyle.set(pseudoRule.style,pseudoElement);if(pseudoElement)
this._addMatchingSelectors(pseudoElement,pseudoRule,rules[j].matchingSelectors);}
const nodeCascade=new SDK.CSSMatchedStyles.NodeCascade(this,pseudoStyles,false);pseudoCascades.set(entryPayload.pseudoType,new SDK.CSSMatchedStyles.DOMInheritanceCascade([nodeCascade]));}
return pseudoCascades;}
_addMatchingSelectors(node,rule,matchingSelectorIndices){for(const matchingSelectorIndex of matchingSelectorIndices){const selector=rule.selectors[matchingSelectorIndex];this._setSelectorMatches(node,selector.text,true);}}
node(){return this._node;}
cssModel(){return this._cssModel;}
hasMatchingSelectors(rule){const matchingSelectors=this.matchingSelectors(rule);return matchingSelectors.length>0&&this.mediaMatches(rule.style);}
matchingSelectors(rule){const node=this.nodeForStyle(rule.style);if(!node)
return[];const map=this._matchingSelectors.get(node.id);if(!map)
return[];const result=[];for(let i=0;i<rule.selectors.length;++i){if(map.get(rule.selectors[i].text))
result.push(i);}
return result;}
recomputeMatchingSelectors(rule){const node=this.nodeForStyle(rule.style);if(!node)
return Promise.resolve();const promises=[];for(const selector of rule.selectors)
promises.push(querySelector.call(this,node,selector.text));return Promise.all(promises);async function querySelector(node,selectorText){const ownerDocument=node.ownerDocument||null;const map=this._matchingSelectors.get(node.id);if((map&&map.has(selectorText))||!ownerDocument)
return;const matchingNodeIds=await this._node.domModel().querySelectorAll(ownerDocument.id,selectorText);if(matchingNodeIds)
this._setSelectorMatches(node,selectorText,matchingNodeIds.indexOf(node.id)!==-1);}}
addNewRule(rule,node){this._addedStyles.set(rule.style,node);return this.recomputeMatchingSelectors(rule);}
_setSelectorMatches(node,selectorText,value){let map=this._matchingSelectors.get(node.id);if(!map){map=new Map();this._matchingSelectors.set(node.id,map);}
map.set(selectorText,value);}
mediaMatches(style){const media=style.parentRule?style.parentRule.media:[];for(let i=0;media&&i<media.length;++i){if(!media[i].active())
return false;}
return true;}
nodeStyles(){return this._mainDOMCascade.styles();}
keyframes(){return this._keyframes;}
pseudoStyles(pseudoType){const domCascade=this._pseudoDOMCascades.get(pseudoType);return domCascade?domCascade.styles():[];}
pseudoTypes(){return new Set(this._pseudoDOMCascades.keys());}
_containsInherited(style){const properties=style.allProperties();for(let i=0;i<properties.length;++i){const property=properties[i];if(property.activeInStyle()&&SDK.cssMetadata().isPropertyInherited(property.name))
return true;}
return false;}
nodeForStyle(style){return this._addedStyles.get(style)||this._nodeForStyle.get(style)||null;}
availableCSSVariables(style){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.availableCSSVariables(style):[];}
computeCSSVariable(style,variableName){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.computeCSSVariable(style,variableName):null;}
computeValue(style,value){const domCascade=this._styleToDOMCascade.get(style)||null;return domCascade?domCascade.computeValue(style,value):null;}
isInherited(style){return this._inheritedStyles.has(style);}
propertyState(property){const domCascade=this._styleToDOMCascade.get(property.ownerStyle);return domCascade?domCascade.propertyState(property):null;}
resetActiveProperties(){this._mainDOMCascade.reset();for(const domCascade of this._pseudoDOMCascades.values())
domCascade.reset();}};SDK.CSSMatchedStyles.NodeCascade=class{constructor(matchedStyles,styles,isInherited){this._matchedStyles=matchedStyles;this._styles=styles;this._isInherited=isInherited;this._propertiesState=new Map();this._activeProperties=new Map();}
_computeActiveProperties(){this._propertiesState.clear();this._activeProperties.clear();for(const style of this._styles){const rule=style.parentRule;if(rule&&!(rule instanceof SDK.CSSStyleRule))
continue;if(rule&&!this._matchedStyles.hasMatchingSelectors(rule))
continue;for(const property of style.allProperties()){if(this._isInherited&&!SDK.cssMetadata().isPropertyInherited(property.name))
continue;if(!property.activeInStyle()){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);const activeProperty=this._activeProperties.get(canonicalName);if(activeProperty&&(activeProperty.important||!property.important)){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
if(activeProperty)
this._propertiesState.set(activeProperty,SDK.CSSMatchedStyles.PropertyState.Overloaded);this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Active);this._activeProperties.set(canonicalName,property);}}}};SDK.CSSMatchedStyles.DOMInheritanceCascade=class{constructor(nodeCascades){this._nodeCascades=nodeCascades;this._propertiesState=new Map();this._availableCSSVariables=new Map();this._computedCSSVariables=new Map();this._initialized=false;this._styleToNodeCascade=new Map();for(const nodeCascade of nodeCascades){for(const style of nodeCascade._styles)
this._styleToNodeCascade.set(style,nodeCascade);}}
availableCSSVariables(style){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return[];this._ensureInitialized();return Array.from(this._availableCSSVariables.get(nodeCascade).keys());}
computeCSSVariable(style,variableName){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return null;this._ensureInitialized();const availableCSSVariables=this._availableCSSVariables.get(nodeCascade);const computedCSSVariables=this._computedCSSVariables.get(nodeCascade);return this._innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,variableName);}
computeValue(style,value){const nodeCascade=this._styleToNodeCascade.get(style);if(!nodeCascade)
return null;this._ensureInitialized();const availableCSSVariables=this._availableCSSVariables.get(nodeCascade);const computedCSSVariables=this._computedCSSVariables.get(nodeCascade);return this._innerComputeValue(availableCSSVariables,computedCSSVariables,value);}
_innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,variableName){if(!availableCSSVariables.has(variableName))
return null;if(computedCSSVariables.has(variableName))
return computedCSSVariables.get(variableName);computedCSSVariables.set(variableName,null);const definedValue=availableCSSVariables.get(variableName);const computedValue=this._innerComputeValue(availableCSSVariables,computedCSSVariables,definedValue);computedCSSVariables.set(variableName,computedValue);return computedValue;}
_innerComputeValue(availableCSSVariables,computedCSSVariables,value){const results=TextUtils.TextUtils.splitStringByRegexes(value,[SDK.CSSMetadata.VariableRegex]);const tokens=[];for(const result of results){if(result.regexIndex===-1){tokens.push(result.value);continue;}
const regexMatch=result.value.match(/^var\((--[a-zA-Z0-9-_]+)[,]?\s*(.*)\)$/);if(!regexMatch)
return null;const cssVariable=regexMatch[1];const computedValue=this._innerComputeCSSVariable(availableCSSVariables,computedCSSVariables,cssVariable);if(computedValue===null&&!regexMatch[2])
return null;if(computedValue===null)
tokens.push(regexMatch[2]);else
tokens.push(computedValue);}
return tokens.map(token=>token.trim()).join(' ');}
styles(){return Array.from(this._styleToNodeCascade.keys());}
propertyState(property){this._ensureInitialized();return this._propertiesState.get(property)||null;}
reset(){this._initialized=false;this._propertiesState.clear();this._availableCSSVariables.clear();this._computedCSSVariables.clear();}
_ensureInitialized(){if(this._initialized)
return;this._initialized=true;const activeProperties=new Map();for(const nodeCascade of this._nodeCascades){nodeCascade._computeActiveProperties();for(const entry of nodeCascade._propertiesState.entries()){const property=(entry[0]);const state=(entry[1]);if(state===SDK.CSSMatchedStyles.PropertyState.Overloaded){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);if(activeProperties.has(canonicalName)){this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Overloaded);continue;}
activeProperties.set(canonicalName,property);this._propertiesState.set(property,SDK.CSSMatchedStyles.PropertyState.Active);}}
for(const entry of activeProperties.entries()){const canonicalName=(entry[0]);const shorthandProperty=(entry[1]);const shorthandStyle=shorthandProperty.ownerStyle;const longhands=shorthandStyle.longhandProperties(shorthandProperty.name);if(!longhands.length)
continue;let hasActiveLonghands=false;for(const longhand of longhands){const longhandCanonicalName=SDK.cssMetadata().canonicalPropertyName(longhand.name);const longhandActiveProperty=activeProperties.get(longhandCanonicalName);if(!longhandActiveProperty)
continue;if(longhandActiveProperty.ownerStyle===shorthandStyle){hasActiveLonghands=true;break;}}
if(hasActiveLonghands)
continue;activeProperties.delete(canonicalName);this._propertiesState.set(shorthandProperty,SDK.CSSMatchedStyles.PropertyState.Overloaded);}
const accumulatedCSSVariables=new Map();for(let i=this._nodeCascades.length-1;i>=0;--i){const nodeCascade=this._nodeCascades[i];for(const entry of nodeCascade._activeProperties.entries()){const propertyName=(entry[0]);const property=(entry[1]);if(propertyName.startsWith('--'))
accumulatedCSSVariables.set(propertyName,property.value);}
this._availableCSSVariables.set(nodeCascade,new Map(accumulatedCSSVariables));this._computedCSSVariables.set(nodeCascade,new Map());}}};SDK.CSSMatchedStyles.PropertyState={Active:'Active',Overloaded:'Overloaded'};;SDK.CSSMediaQuery=class{constructor(payload){this._active=payload.active;this._expressions=[];for(let j=0;j<payload.expressions.length;++j)
this._expressions.push(SDK.CSSMediaQueryExpression.parsePayload(payload.expressions[j]));}
static parsePayload(payload){return new SDK.CSSMediaQuery(payload);}
active(){return this._active;}
expressions(){return this._expressions;}};SDK.CSSMediaQueryExpression=class{constructor(payload){this._value=payload.value;this._unit=payload.unit;this._feature=payload.feature;this._valueRange=payload.valueRange?TextUtils.TextRange.fromObject(payload.valueRange):null;this._computedLength=payload.computedLength||null;}
static parsePayload(payload){return new SDK.CSSMediaQueryExpression(payload);}
value(){return this._value;}
unit(){return this._unit;}
feature(){return this._feature;}
valueRange(){return this._valueRange;}
computedLength(){return this._computedLength;}};SDK.CSSMedia=class{constructor(cssModel,payload){this._cssModel=cssModel;this._reinitialize(payload);}
static parsePayload(cssModel,payload){return new SDK.CSSMedia(cssModel,payload);}
static parseMediaArrayPayload(cssModel,payload){const result=[];for(let i=0;i<payload.length;++i)
result.push(SDK.CSSMedia.parsePayload(cssModel,payload[i]));return result;}
_reinitialize(payload){this.text=payload.text;this.source=payload.source;this.sourceURL=payload.sourceURL||'';this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;this.styleSheetId=payload.styleSheetId;this.mediaList=null;if(payload.mediaList){this.mediaList=[];for(let i=0;i<payload.mediaList.length;++i)
this.mediaList.push(SDK.CSSMediaQuery.parsePayload(payload.mediaList[i]));}}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range)
return;if(edit.oldRange.equal(this.range))
this._reinitialize((edit.payload));else
this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}
equal(other){if(!this.styleSheetId||!this.range||!other.range)
return false;return this.styleSheetId===other.styleSheetId&&this.range.equal(other.range);}
active(){if(!this.mediaList)
return true;for(let i=0;i<this.mediaList.length;++i){if(this.mediaList[i].active())
return true;}
return false;}
lineNumberInSource(){if(!this.range)
return undefined;const header=this.header();if(!header)
return undefined;return header.lineNumberInSource(this.range.startLine);}
columnNumberInSource(){if(!this.range)
return undefined;const header=this.header();if(!header)
return undefined;return header.columnNumberInSource(this.range.startLine,this.range.startColumn);}
header(){return this.styleSheetId?this._cssModel.styleSheetHeaderForId(this.styleSheetId):null;}
rawLocation(){const header=this.header();if(!header||this.lineNumberInSource()===undefined)
return null;const lineNumber=Number(this.lineNumberInSource());return new SDK.CSSLocation(header,lineNumber,this.columnNumberInSource());}};SDK.CSSMedia.Source={LINKED_SHEET:'linkedSheet',INLINE_SHEET:'inlineSheet',MEDIA_RULE:'mediaRule',IMPORT_RULE:'importRule'};;SDK.CSSMetadata=class{constructor(properties){this._values=([]);this._longhands=new Map();this._shorthands=new Map();this._inherited=new Set();this._svgProperties=new Set();for(let i=0;i<properties.length;++i){const property=properties[i];const propertyName=property.name;if(!CSS.supports(propertyName,'initial'))
continue;this._values.push(propertyName);if(property.inherited)
this._inherited.add(propertyName);if(property.svg)
this._svgProperties.add(propertyName);const longhands=properties[i].longhands;if(longhands){this._longhands.set(propertyName,longhands);for(let j=0;j<longhands.length;++j){const longhandName=longhands[j];let shorthands=this._shorthands.get(longhandName);if(!shorthands){shorthands=[];this._shorthands.set(longhandName,shorthands);}
shorthands.push(propertyName);}}}
this._values.sort();this._valuesSet=new Set(this._values);}
allProperties(){return this._values;}
isSVGProperty(name){name=name.toLowerCase();return this._svgProperties.has(name);}
longhands(shorthand){return this._longhands.get(shorthand)||null;}
shorthands(longhand){return this._shorthands.get(longhand)||null;}
isColorAwareProperty(propertyName){return!!SDK.CSSMetadata._colorAwareProperties.has(propertyName.toLowerCase())||this.isCustomProperty(propertyName.toLowerCase());}
isLengthProperty(propertyName){propertyName=propertyName.toLowerCase();if(propertyName==='line-height')
return false;return SDK.CSSMetadata._distanceProperties.has(propertyName)||propertyName.startsWith('margin')||propertyName.startsWith('padding')||propertyName.indexOf('width')!==-1||propertyName.indexOf('height')!==-1;}
isBezierAwareProperty(propertyName){propertyName=propertyName.toLowerCase();return!!SDK.CSSMetadata._bezierAwareProperties.has(propertyName)||this.isCustomProperty(propertyName);}
isCustomProperty(propertyName){return propertyName.startsWith('--');}
canonicalPropertyName(name){name=name.toLowerCase();if(!name||name.length<9||name.charAt(0)!=='-')
return name;const match=name.match(/(?:-webkit-)(.+)/);if(!match||!this._valuesSet.has(match[1]))
return name;return match[1];}
isCSSPropertyName(propertyName){propertyName=propertyName.toLowerCase();if(propertyName.startsWith('-moz-')||propertyName.startsWith('-o-')||propertyName.startsWith('-webkit-')||propertyName.startsWith('-ms-'))
return true;return this._valuesSet.has(propertyName);}
isPropertyInherited(propertyName){propertyName=propertyName.toLowerCase();return propertyName.startsWith('--')||this._inherited.has(this.canonicalPropertyName(propertyName))||this._inherited.has(propertyName);}
propertyValues(propertyName){const acceptedKeywords=['inherit','initial','unset'];propertyName=propertyName.toLowerCase();const unprefixedName=propertyName.replace(/^-webkit-/,'');const entry=SDK.CSSMetadata._propertyDataMap[propertyName]||SDK.CSSMetadata._propertyDataMap[unprefixedName];if(entry&&entry.values)
acceptedKeywords.pushAll(entry.values);if(this.isColorAwareProperty(propertyName)){acceptedKeywords.push('currentColor');for(const color in Common.Color.Nicknames)
acceptedKeywords.push(color);}
return acceptedKeywords.sort();}
propertyUsageWeight(property){return SDK.CSSMetadata.Weight[property]||SDK.CSSMetadata.Weight[this.canonicalPropertyName(property)]||0;}};SDK.CSSMetadata.VariableRegex=/(var\(--.*?\))/g;SDK.CSSMetadata.URLRegex=/url\(\s*('.+?'|".+?"|[^)]+)\s*\)/g;SDK.cssMetadata=function(){if(!SDK.CSSMetadata._instance)
SDK.CSSMetadata._instance=new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties||[]);return SDK.CSSMetadata._instance;};SDK.CSSMetadata._distanceProperties=new Set(['background-position','border-spacing','bottom','font-size','height','left','letter-spacing','max-height','max-width','min-height','min-width','right','text-indent','top','width','word-spacing','grid-row-gap','grid-column-gap']);SDK.CSSMetadata._bezierAwareProperties=new Set(['animation','animation-timing-function','transition','transition-timing-function','-webkit-animation','-webkit-animation-timing-function','-webkit-transition','-webkit-transition-timing-function']);SDK.CSSMetadata._colorAwareProperties=new Set(['backdrop-filter','background','background-color','background-image','border','border-color','border-image','border-image-source','border-bottom','border-bottom-color','border-left','border-left-color','border-right','border-right-color','border-top','border-top-color','box-shadow','caret-color','color','column-rule','column-rule-color','fill','list-style','list-style-image','outline','outline-color','stroke','text-decoration-color','text-shadow','-webkit-border-after','-webkit-border-after-color','-webkit-border-before','-webkit-border-before-color','-webkit-border-end','-webkit-border-end-color','-webkit-border-start','-webkit-border-start-color','-webkit-box-reflect','-webkit-box-shadow','-webkit-column-rule-color','-webkit-filter','-webkit-mask','-webkit-mask-box-image','-webkit-mask-box-image-source','-webkit-mask-image','-webkit-tap-highlight-color','-webkit-text-decoration-color','-webkit-text-emphasis','-webkit-text-emphasis-color','-webkit-text-fill-color','-webkit-text-stroke','-webkit-text-stroke-color']);SDK.CSSMetadata._propertyDataMap={'table-layout':{values:['auto','fixed']},'visibility':{values:['hidden','visible','collapse']},'background-repeat':{values:['repeat','repeat-x','repeat-y','no-repeat','space','round']},'content':{values:['none','normal','close-quote','no-close-quote','no-open-quote','open-quote']},'list-style-image':{values:['none']},'clear':{values:['none','left','right','both']},'overflow-x':{values:['hidden','auto','visible','overlay','scroll']},'stroke-linejoin':{values:['round','miter','bevel']},'baseline-shift':{values:['baseline','sub','super']},'border-bottom-width':{values:['medium','thick','thin']},'margin-top-collapse':{values:['collapse','separate','discard']},'max-height':{values:['none','min-content','max-content','-webkit-fill-available','fit-content']},'box-orient':{values:['horizontal','vertical','inline-axis','block-axis'],},'font-stretch':{values:['normal','ultra-condensed','extra-condensed','condensed','semi-condensed','semi-expanded','expanded','extra-expanded','ultra-expanded']},'border-left-width':{values:['medium','thick','thin']},'box-shadow':{values:['inset','none']},'-webkit-writing-mode':{values:['horizontal-tb','vertical-rl','vertical-lr']},'writing-mode':{values:['lr','rl','tb','lr-tb','rl-tb','tb-rl','horizontal-tb','vertical-rl','vertical-lr']},'border-collapse':{values:['collapse','separate']},'page-break-inside':{values:['auto','avoid']},'border-top-width':{values:['medium','thick','thin']},'outline-style':{values:['auto','none','inset','groove','ridge','outset','dotted','dashed','solid','double']},'cursor':{values:['none','copy','auto','crosshair','default','pointer','move','vertical-text','cell','context-menu','alias','progress','no-drop','not-allowed','-webkit-zoom-in','-webkit-zoom-out','e-resize','ne-resize','nw-resize','n-resize','se-resize','sw-resize','s-resize','w-resize','ew-resize','ns-resize','nesw-resize','nwse-resize','col-resize','row-resize','text','wait','help','all-scroll','zoom-in','zoom-out','-webkit-grab','-webkit-grabbing']},'border-width':{values:['medium','thick','thin']},'border-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'size':{values:['auto','a3','a4','a5','b4','b5','landscape','ledger','legal','letter','portrait']},'background-size':{values:['auto','contain','cover']},'direction':{values:['ltr','rtl']},'enable-background':{values:['accumulate','new']},'float':{values:['none','left','right']},'overflow-y':{values:['hidden','auto','visible','overlay','scroll','-webkit-paged-x','-webkit-paged-y']},'margin-bottom-collapse':{values:['collapse','separate','discard']},'box-reflect':{values:['left','right','above','below']},'overflow':{values:['hidden','auto','visible','overlay','scroll','-webkit-paged-x','-webkit-paged-y']},'contain':{values:['none','strict','content','size','layout','style','paint']},'text-rendering':{values:['auto','optimizeSpeed','optimizeLegibility','geometricPrecision']},'text-align':{values:['-webkit-auto','start','end','left','right','center','justify','-webkit-left','-webkit-right','-webkit-center','-webkit-match-parent']},'list-style-position':{values:['outside','inside']},'margin-bottom':{values:['auto']},'color-interpolation':{values:['auto','sRGB','linearRGB']},'background-origin':{values:['border-box','content-box','padding-box']},'word-wrap':{values:['normal','break-word']},'font-weight':{values:['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900']},'margin-before-collapse':{values:['collapse','separate','discard']},'text-transform':{values:['none','capitalize','uppercase','lowercase']},'border-right-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'border-left-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'-webkit-text-emphasis':{values:['circle','filled','open','dot','double-circle','triangle','sesame','none']},'font-style':{values:['italic','oblique','normal']},'speak':{values:['none','normal','spell-out','digits','literal-punctuation','no-punctuation']},'color-rendering':{values:['auto','optimizeSpeed','optimizeQuality']},'list-style-type':{values:['none','disc','circle','square','decimal','decimal-leading-zero','arabic-indic','bengali','cambodian','khmer','devanagari','gujarati','gurmukhi','kannada','lao','malayalam','mongolian','myanmar','oriya','persian','urdu','telugu','tibetan','thai','lower-roman','upper-roman','lower-greek','lower-alpha','lower-latin','upper-alpha','upper-latin','ethiopic-halehame','ethiopic-halehame-am','ethiopic-halehame-ti-er','ethiopic-halehame-ti-et','cjk-earthly-branch','cjk-heavenly-stem','hangul-consonant','hangul','korean-hangul-formal','korean-hanja-formal','korean-hanja-informal','simp-chinese-formal','simp-chinese-informal','trad-chinese-formal','trad-chinese-informal','hebrew','armenian','lower-armenian','upper-armenian','georgian','cjk-ideographic','hiragana','katakana','hiragana-iroha','katakana-iroha']},'text-combine-upright':{values:['none','all']},'-webkit-text-combine':{values:['none','horizontal']},'text-orientation':{values:['mixed','upright','sideways','sideways-right']},'outline':{values:['none','inset','groove','ridge','outset','dotted','dashed','solid','double','medium','auto','thick','thin']},'font':{values:['caption','icon','menu','message-box','small-caption','-webkit-mini-control','-webkit-small-control','-webkit-control','status-bar','italic','oblique','small-caps','normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','xx-small','x-small','small','medium','large','x-large','xx-large','-webkit-xxx-large','smaller','larger','serif','sans-serif','cursive','fantasy','monospace','-webkit-body','-webkit-pictograph']},'dominant-baseline':{values:['middle','auto','central','text-before-edge','text-after-edge','ideographic','alphabetic','hanging','mathematical','use-script','no-change','reset-size']},'display':{values:['none','inline','block','flow-root','list-item','inline-block','table','inline-table','table-row-group','table-header-group','table-footer-group','table-row','table-column-group','table-column','table-cell','table-caption','-webkit-box','-webkit-inline-box','flex','inline-flex','grid','inline-grid','contents']},'-webkit-text-emphasis-position':{values:['over','under']},'image-rendering':{values:['auto','pixelated','-webkit-optimize-contrast']},'alignment-baseline':{values:['baseline','middle','auto','before-edge','after-edge','central','text-before-edge','text-after-edge','ideographic','alphabetic','hanging','mathematical']},'outline-width':{values:['medium','thick','thin']},'box-align':{values:['baseline','center','stretch','start','end']},'border-right-width':{values:['medium','thick','thin']},'border-top-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'line-height':{values:['normal']},'text-overflow':{values:['clip','ellipsis']},'overflow-wrap':{values:['normal','break-word']},'box-direction':{values:['normal','reverse']},'margin-after-collapse':{values:['collapse','separate','discard']},'page-break-before':{values:['left','right','auto','always','avoid']},'border-image':{values:['repeat','stretch','none','space','round']},'text-decoration':{values:['none','blink','line-through','overline','underline','wavy','double','solid','dashed','dotted']},'position':{values:['absolute','fixed','relative','static','sticky']},'font-family':{values:['serif','sans-serif','cursive','fantasy','monospace','-webkit-body','-webkit-pictograph']},'text-overflow-mode':{values:['clip','ellipsis']},'border-bottom-style':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double']},'unicode-bidi':{values:['normal','bidi-override','embed','isolate','isolate-override','plaintext']},'clip-rule':{values:['nonzero','evenodd']},'margin-left':{values:['auto']},'margin-top':{values:['auto']},'zoom':{values:['normal']},'max-width':{values:['none','min-content','max-content','-webkit-fill-available','fit-content']},'caption-side':{values:['top','bottom']},'empty-cells':{values:['hide','show']},'pointer-events':{values:['none','all','auto','visible','visiblepainted','visiblefill','visiblestroke','painted','fill','stroke','bounding-box']},'letter-spacing':{values:['normal']},'background-clip':{values:['border-box','content-box','padding-box']},'-webkit-font-smoothing':{values:['none','auto','antialiased','subpixel-antialiased']},'border':{values:['none','hidden','inset','groove','ridge','outset','dotted','dashed','solid','double','medium','thick','thin']},'font-size':{values:['xx-small','x-small','small','medium','large','x-large','xx-large','-webkit-xxx-large','smaller','larger']},'font-variant':{values:['small-caps','normal','none','common-ligatures','no-common-ligatures','discretionary-ligatures','no-discretionary-ligatures','historical-ligatures','no-historical-ligatures','contextual','no-contextual','all-small-caps','petite-caps','all-petite-caps','unicase','titling-caps','lining-nums','oldstyle-nums','proportional-nums','tabular-nums','diagonal-fractions','stacked-fractions','ordinal','slashed-zero','jis78','jis83','jis90','jis04','simplified','traditional','full-width','proportional-width','ruby']},'vertical-align':{values:['baseline','middle','sub','super','text-top','text-bottom','top','bottom','-webkit-baseline-middle']},'white-space':{values:['normal','nowrap','pre','pre-line','pre-wrap']},'page-break-after':{values:['left','right','auto','always','avoid']},'clip-path':{values:['none']},'margin':{values:['auto']},'margin-right':{values:['auto']},'word-break':{values:['normal','break-all','break-word','keep-all']},'word-spacing':{values:['normal']},'-webkit-text-emphasis-style':{values:['circle','filled','open','dot','double-circle','triangle','sesame','none']},'transform':{values:['scale','scaleX','scaleY','scale3d','rotate','rotateX','rotateY','rotateZ','rotate3d','skew','skewX','skewY','translate','translateX','translateY','translateZ','translate3d','matrix','matrix3d','perspective','none']},'image-resolution':{values:['from-image','snap']},'box-sizing':{values:['content-box','border-box']},'clip':{values:['auto']},'resize':{values:['none','both','horizontal','vertical','auto']},'align-content':{values:['normal','baseline','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right']},'justify-content':{values:['normal','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right','baseline']},'place-content':{values:['normal','space-between','space-around','space-evenly','stretch','unsafe','safe','center','start','end','flex-start','flex-end','left','right','baseline']},'align-items':{values:['normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'justify-items':{values:['normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right','legacy','auto']},'place-items':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'align-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'justify-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'place-self':{values:['auto','normal','stretch','baseline','unsafe','safe','center','start','end','self-start','self-end','flex-start','flex-end','left','right']},'flex-direction':{values:['row','row-reverse','column','column-reverse']},'flex-wrap':{values:['nowrap','wrap','wrap-reverse']},'perspective':{values:['none']},'perspective-origin':{values:['left','center','right','top','bottom']},'transform-origin':{values:['left','center','right','top','bottom']},'transform-style':{values:['flat','preserve-3d']},'transition-timing-function':{values:['ease','linear','ease-in','ease-out','ease-in-out','step-start','step-end','steps','frames','cubic-bezier','step-middle']},'animation-timing-function':{values:['ease','linear','ease-in','ease-out','ease-in-out','step-start','step-end','steps','frames','cubic-bezier','step-middle']},'animation-direction':{values:['normal','reverse','alternate','alternate-reverse']},'animation-play-state':{values:['running','paused']},'animation-fill-mode':{values:['none','forwards','backwards','both']},'-webkit-backface-visibility':{values:['visible','hidden']},'-webkit-box-decoration-break':{values:['slice','clone']},'-webkit-column-break-after':{values:['auto','always','avoid','left','right','page','column','avoid-page','avoid-column']},'-webkit-column-break-before':{values:['auto','always','avoid','left','right','page','column','avoid-page','avoid-column']},'-webkit-column-break-inside':{values:['auto','avoid','avoid-page','avoid-column']},'-webkit-column-span':{values:['none','all']},'-webkit-column-count':{values:['auto']},'-webkit-column-gap':{values:['normal']},'filter':{values:['url','blur','brightness','contrast','drop-shadow','grayscale','hue-rotate','invert','opacity','saturate','sepia','none']},'line-break':{values:['auto','loose','normal','strict','after-white-space']},'user-select':{values:['none','text','all','auto']},'-webkit-user-modify':{values:['read-only','read-write','read-write-plaintext-only']},'text-align-last':{values:['auto','start','end','left','right','center','justify']},'-webkit-text-decoration-line':{values:['none','underline','overline','line-through','blink']},'-webkit-text-decoration-style':{values:['solid','double','dotted','dashed','wavy']},'-webkit-text-decoration-skip':{values:['none','objects','spaces','ink','edges','box-decoration']},'mix-blend-mode':{values:['normal','multiply','screen','overlay','darken','lighten','color-dodge','color-burn','hard-light','soft-light','difference','exclusion','hue','saturation','color','luminosity','unset']},'background-blend-mode':{values:['normal','multiply','screen','overlay','darken','lighten','color-dodge','color-burn','hard-light','soft-light','difference','exclusion','hue','saturation','color','luminosity','unset']},'caret-color':{values:['auto']},'grid-template-columns':{values:['none','auto','min-content','max-content']},'grid-template-rows':{values:['none','auto','min-content','max-content']},'grid-template-areas':{values:['none']},'grid-template':{values:['none']},'grid-auto-columns':{values:['auto','min-content','max-content']},'grid-auto-rows':{values:['auto','min-content','max-content']},'grid-auto-flow':{values:['row','column','dense']},'grid':{values:['none']},'grid-row-start':{values:['auto']},'grid-column-start':{values:['auto']},'grid-row-end':{values:['auto']},'grid-column-end':{values:['auto']},'grid-row':{values:['auto']},'grid-column':{values:['auto']},'grid-area':{values:['auto']},'animation-iteration-count':{values:['infinite']},'font-feature-settings':{values:['normal']},'font-kerning':{values:['none','normal','auto']},'font-size-adjust':{values:['none']},'font-variant-caps':{values:['small-caps','all-small-caps','petite-caps','all-petite-caps','unicase','titling-caps','normal']},'font-variant-east-asian':{values:['jis78','jis83','jis90','jis04','simplified','traditional','full-width','proportional-width','ruby']},'font-variant-ligatures':{values:['none','common-ligatures','no-common-ligatures','discretionary-ligatures','no-discretionary-ligatures','historical-ligatures','no-historical-ligatures','contextual','no-contextual','normal']},'font-variant-numeric':{values:['lining-nums','oldstyle-nums','proportional-nums','tabular-nums','diagonal-fractions','stacked-fractions','ordinal','slashed-zero','normal']},'font-variation-settings':{values:['normal']},'-webkit-locale':{values:['auto']},'backdrop-filter':{values:['none']},'backface-visibility':{values:['hidden','visible']},'background':{values:['none','repeat','repeat-x','repeat-y','no-repeat','top','bottom','left','right','center','fixed','local','scroll','space','round','border-box','content-box','padding-box']},'background-attachment':{values:['fixed','local','scroll']},'background-image':{values:['none']},'background-position':{values:['top','bottom','left','right','center']},'background-position-x':{values:['left','right','center']},'background-position-y':{values:['top','bottom','center']},'background-repeat-x':{values:['repeat','no-repeat']},'background-repeat-y':{values:['repeat','no-repeat']},'border-bottom':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-image-repeat':{values:['repeat','stretch','space','round']},'border-image-source':{values:['none']},'border-image-width':{values:['auto']},'border-left':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-right':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'border-top':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'bottom':{values:['auto']},'break-after':{values:['left','right','auto','avoid','column','avoid-page','page','recto','verso','avoid-column']},'break-before':{values:['left','right','auto','avoid','column','avoid-page','page','recto','verso','avoid-column']},'break-inside':{values:['auto','avoid','avoid-page','avoid-column']},'buffered-rendering':{values:['auto','static','dynamic']},'color-interpolation-filters':{values:['auto','srgb','linearrgb']},'column-count':{values:['auto']},'column-fill':{values:['auto','balance']},'column-gap':{values:['normal']},'column-rule':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'column-rule-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'column-rule-width':{values:['medium','thick','thin']},'column-span':{values:['none','all']},'column-width':{values:['auto']},'columns':{values:['auto']},'d':{values:['none']},'fill':{values:['none']},'fill-rule':{values:['nonzero','evenodd']},'flex':{values:['none','auto']},'flex-basis':{values:['auto']},'flex-flow':{values:['nowrap','row','row-reverse','column','column-reverse','wrap','wrap-reverse']},'height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'hyphens':{values:['none','manual']},'inline-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'isolation':{values:['auto','isolate']},'left':{values:['auto']},'list-style':{values:['none','outside','inside','disc','circle','square','decimal','decimal-leading-zero','arabic-indic','bengali','cambodian','khmer','devanagari','gujarati','gurmukhi','kannada','lao','malayalam','mongolian','myanmar','oriya','persian','urdu','telugu','tibetan','thai','lower-roman','upper-roman','lower-greek','lower-alpha','lower-latin','upper-alpha','upper-latin','cjk-earthly-branch','cjk-heavenly-stem','ethiopic-halehame','ethiopic-halehame-am','ethiopic-halehame-ti-er','ethiopic-halehame-ti-et','hangul','hangul-consonant','korean-hangul-formal','korean-hanja-formal','korean-hanja-informal','hebrew','armenian','lower-armenian','upper-armenian','georgian','cjk-ideographic','simp-chinese-formal','simp-chinese-informal','trad-chinese-formal','trad-chinese-informal','hiragana','katakana','hiragana-iroha','katakana-iroha']},'marker':{values:['none']},'marker-end':{values:['none']},'marker-mid':{values:['none']},'marker-start':{values:['none']},'mask':{values:['none']},'mask-source-type':{values:['auto','alpha','luminance']},'mask-type':{values:['alpha','luminance']},'max-block-size':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'max-inline-size':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'min-block-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-inline-size':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'min-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'object-fit':{values:['none','contain','cover','fill','scale-down']},'object-position':{values:['top','bottom','left','right','center']},'offset-anchor':{values:['top','bottom','left','right','center','auto']},'offset-path':{values:['none']},'offset-position':{values:['top','bottom','left','right','center','auto']},'offset-rotate':{values:['auto','reverse']},'overflow-anchor':{values:['none','auto','visible']},'paint-order':{values:['normal','fill','stroke','markers']},'quotes':{values:['none']},'right':{values:['auto']},'rotate':{values:['none']},'rx':{values:['auto']},'ry':{values:['auto']},'scale':{values:['none']},'scroll-behavior':{values:['auto','smooth']},'scroll-customization':{values:['none','auto','pan-x','pan-y','pan-left','pan-right','pan-up','pan-down',]},'shape-outside':{values:['none','border-box','content-box','padding-box','margin-box']},'shape-rendering':{values:['auto','optimizespeed','geometricprecision','crispedges']},'stroke':{values:['none']},'stroke-dasharray':{values:['none']},'stroke-linecap':{values:['square','round','butt']},'text-anchor':{values:['middle','start','end']},'text-decoration-line':{values:['none','blink','line-through','overline','underline']},'text-decoration-skip':{values:['objects','ink']},'text-decoration-style':{values:['dotted','dashed','solid','double','wavy']},'text-justify':{values:['none','inter-word','distribute','auto']},'text-shadow':{values:['none']},'text-size-adjust':{values:['none','auto']},'text-underline-position':{values:['auto','under']},'top':{values:['auto']},'touch-action':{values:['none','auto','pan-x','pan-y','pan-left','pan-right','pan-up','pan-down','manipulation','pinch-zoom']},'transform-box':{values:['border-box','fill-box','view-box']},'translate':{values:['none']},'vector-effect':{values:['none','non-scaling-stroke']},'-webkit-app-region':{values:['drag','no-drag']},'-webkit-appearance':{values:['none','checkbox','radio','push-button','square-button','button','button-bevel','inner-spin-button','listbox','listitem','media-enter-fullscreen-button','media-exit-fullscreen-button','media-mute-button','media-play-button','media-overlay-play-button','media-toggle-closed-captions-button','media-slider','media-sliderthumb','media-volume-slider-container','media-volume-slider','media-volume-sliderthumb','media-controls-background','media-controls-fullscreen-background','media-current-time-display','media-time-remaining-display','menulist','menulist-button','menulist-text','menulist-textfield','meter','progress-bar','progress-bar-value','slider-horizontal','slider-vertical','sliderthumb-horizontal','sliderthumb-vertical','caret','searchfield','searchfield-cancel-button','textfield','textarea']},'-webkit-border-after':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-after-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-after-width':{values:['medium','thick','thin']},'-webkit-border-before':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-before-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-before-width':{values:['medium','thick','thin']},'-webkit-border-end':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-end-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-end-width':{values:['medium','thick','thin']},'-webkit-border-start':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double','medium','thick','thin']},'-webkit-border-start-style':{values:['none','hidden','inset','groove','outset','ridge','dotted','dashed','solid','double']},'-webkit-border-start-width':{values:['medium','thick','thin']},'-webkit-box-pack':{values:['center','justify','start','end']},'-webkit-highlight':{values:['none']},'-webkit-hyphenate-character':{values:['auto']},'-webkit-logical-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-logical-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-margin-after':{values:['auto']},'-webkit-margin-before':{values:['auto']},'-webkit-margin-collapse':{values:['collapse','separate','discard']},'-webkit-margin-end':{values:['auto']},'-webkit-margin-start':{values:['auto']},'-webkit-mask-box-image':{values:['none','repeat','stretch','space','round']},'-webkit-mask-box-image-repeat':{values:['repeat','stretch','space','round']},'-webkit-mask-box-image-source':{values:['none']},'-webkit-mask-box-image-width':{values:['auto']},'-webkit-mask-clip':{values:['text','border','border-box','content','content-box','padding','padding-box']},'-webkit-mask-composite':{values:['clear','copy','source-over','source-in','source-out','source-atop','destination-over','destination-in','destination-out','destination-atop','xor','plus-lighter']},'-webkit-mask-image':{values:['none']},'-webkit-mask-origin':{values:['border','border-box','content','content-box','padding','padding-box']},'-webkit-mask-position':{values:['top','bottom','left','right','center']},'-webkit-mask-position-x':{values:['left','right','center']},'-webkit-mask-position-y':{values:['top','bottom','center']},'-webkit-mask-repeat':{values:['repeat','repeat-x','repeat-y','no-repeat','space','round']},'-webkit-mask-size':{values:['auto','contain','cover']},'-webkit-max-logical-height':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-max-logical-width':{values:['none','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-min-logical-height':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-min-logical-width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'-webkit-perspective-origin-x':{values:['left','right','center']},'-webkit-perspective-origin-y':{values:['top','bottom','center']},'-webkit-print-color-adjust':{values:['economy','exact']},'-webkit-rtl-ordering':{values:['logical','visual']},'-webkit-ruby-position':{values:['after','before']},'-webkit-text-decorations-in-effect':{values:['none','blink','line-through','overline','underline']},'-webkit-text-security':{values:['none','disc','circle','square']},'-webkit-text-stroke':{values:['medium','thick','thin']},'-webkit-text-stroke-width':{values:['medium','thick','thin']},'-webkit-transform-origin-x':{values:['left','right','center']},'-webkit-transform-origin-y':{values:['top','bottom','center']},'-webkit-user-drag':{values:['none','auto','element']},'width':{values:['auto','-webkit-fill-available','min-content','max-content','fit-content']},'z-index':{values:['auto']}};SDK.CSSMetadata.Weight={'align-content':57,'align-items':129,'align-self':55,'animation':175,'animation-delay':114,'animation-direction':113,'animation-duration':137,'animation-fill-mode':132,'animation-iteration-count':124,'animation-name':139,'animation-play-state':104,'animation-timing-function':141,'backface-visibility':123,'background':260,'background-attachment':119,'background-clip':165,'background-color':259,'background-image':246,'background-origin':107,'background-position':237,'background-position-x':108,'background-position-y':93,'background-repeat':234,'background-size':203,'border':263,'border-bottom':233,'border-bottom-color':190,'border-bottom-left-radius':186,'border-bottom-right-radius':185,'border-bottom-style':150,'border-bottom-width':179,'border-collapse':209,'border-color':226,'border-image':89,'border-image-outset':50,'border-image-repeat':49,'border-image-slice':58,'border-image-source':32,'border-image-width':52,'border-left':221,'border-left-color':174,'border-left-style':142,'border-left-width':172,'border-radius':224,'border-right':223,'border-right-color':182,'border-right-style':130,'border-right-width':178,'border-spacing':198,'border-style':206,'border-top':231,'border-top-color':192,'border-top-left-radius':187,'border-top-right-radius':189,'border-top-style':152,'border-top-width':180,'border-width':214,'bottom':227,'box-shadow':213,'box-sizing':216,'caption-side':96,'clear':229,'clip':173,'clip-rule':5,'color':256,'content':219,'counter-increment':111,'counter-reset':110,'cursor':250,'direction':176,'display':262,'empty-cells':99,'fill':140,'fill-opacity':82,'fill-rule':22,'filter':160,'flex':133,'flex-basis':66,'flex-direction':85,'flex-flow':94,'flex-grow':112,'flex-shrink':61,'flex-wrap':68,'float':252,'font':211,'font-family':254,'font-kerning':18,'font-size':264,'font-stretch':77,'font-style':220,'font-variant':161,'font-weight':257,'height':266,'image-rendering':90,'justify-content':127,'left':248,'letter-spacing':188,'line-height':244,'list-style':215,'list-style-image':145,'list-style-position':149,'list-style-type':199,'margin':267,'margin-bottom':241,'margin-left':243,'margin-right':238,'margin-top':253,'mask':20,'max-height':205,'max-width':225,'min-height':217,'min-width':218,'object-fit':33,'opacity':251,'order':117,'orphans':146,'outline':222,'outline-color':153,'outline-offset':147,'outline-style':151,'outline-width':148,'overflow':255,'overflow-wrap':105,'overflow-x':184,'overflow-y':196,'padding':265,'padding-bottom':230,'padding-left':235,'padding-right':232,'padding-top':240,'page':8,'page-break-after':120,'page-break-before':69,'page-break-inside':121,'perspective':92,'perspective-origin':103,'pointer-events':183,'position':261,'quotes':158,'resize':168,'right':245,'shape-rendering':38,'size':64,'speak':118,'src':170,'stop-color':42,'stop-opacity':31,'stroke':98,'stroke-dasharray':36,'stroke-dashoffset':3,'stroke-linecap':30,'stroke-linejoin':21,'stroke-miterlimit':12,'stroke-opacity':34,'stroke-width':87,'table-layout':171,'tab-size':46,'text-align':260,'text-anchor':35,'text-decoration':247,'text-indent':207,'text-overflow':204,'text-rendering':155,'text-shadow':208,'text-transform':202,'top':258,'touch-action':80,'transform':181,'transform-origin':162,'transform-style':86,'transition':193,'transition-delay':134,'transition-duration':135,'transition-property':131,'transition-timing-function':122,'unicode-bidi':156,'unicode-range':136,'vertical-align':236,'visibility':242,'-webkit-appearance':191,'-webkit-backface-visibility':154,'-webkit-background-clip':164,'-webkit-background-origin':40,'-webkit-background-size':163,'-webkit-border-end':9,'-webkit-border-horizontal-spacing':81,'-webkit-border-image':75,'-webkit-border-radius':212,'-webkit-border-start':10,'-webkit-border-start-color':16,'-webkit-border-start-width':13,'-webkit-border-vertical-spacing':43,'-webkit-box-align':101,'-webkit-box-direction':51,'-webkit-box-flex':128,'-webkit-box-ordinal-group':91,'-webkit-box-orient':144,'-webkit-box-pack':106,'-webkit-box-reflect':39,'-webkit-box-shadow':210,'-webkit-column-break-inside':60,'-webkit-column-count':84,'-webkit-column-gap':76,'-webkit-column-rule':25,'-webkit-column-rule-color':23,'-webkit-columns':44,'-webkit-column-span':29,'-webkit-column-width':47,'-webkit-filter':159,'-webkit-font-feature-settings':59,'-webkit-font-smoothing':177,'-webkit-highlight':1,'-webkit-line-break':45,'-webkit-line-clamp':126,'-webkit-margin-after':67,'-webkit-margin-before':70,'-webkit-margin-collapse':14,'-webkit-margin-end':65,'-webkit-margin-start':100,'-webkit-margin-top-collapse':78,'-webkit-mask':19,'-webkit-mask-box-image':72,'-webkit-mask-image':88,'-webkit-mask-position':54,'-webkit-mask-repeat':63,'-webkit-mask-size':79,'-webkit-padding-after':15,'-webkit-padding-before':28,'-webkit-padding-end':48,'-webkit-padding-start':73,'-webkit-print-color-adjust':83,'-webkit-rtl-ordering':7,'-webkit-tap-highlight-color':169,'-webkit-text-emphasis-color':11,'-webkit-text-fill-color':71,'-webkit-text-security':17,'-webkit-text-stroke':56,'-webkit-text-stroke-color':37,'-webkit-text-stroke-width':53,'-webkit-user-drag':95,'-webkit-user-modify':62,'-webkit-user-select':194,'-webkit-writing-mode':4,'white-space':228,'widows':115,'width':268,'will-change':74,'word-break':166,'word-spacing':157,'word-wrap':197,'writing-mode':41,'z-index':239,'zoom':200};;SDK.CSSModel=class extends SDK.SDKModel{constructor(target){super(target);this._domModel=(target.model(SDK.DOMModel));this._sourceMapManager=new SDK.SourceMapManager(target);this._agent=target.cssAgent();this._styleLoader=new SDK.CSSModel.ComputedStyleLoader(this);this._resourceTreeModel=target.model(SDK.ResourceTreeModel);if(this._resourceTreeModel){this._resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._resetStyleSheets,this);}
target.registerCSSDispatcher(new SDK.CSSDispatcher(this));if(!target.suspended())
this._enable();this._styleSheetIdToHeader=new Map();this._styleSheetIdsForURL=new Map();this._originalStyleSheetText=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('cssSourceMapsEnabled').get());Common.moduleSetting('cssSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));}
sourceMapManager(){return this._sourceMapManager;}
static trimSourceURL(text){let sourceURLIndex=text.lastIndexOf('/*# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=text.lastIndexOf('/*@ sourceURL=');if(sourceURLIndex===-1)
return text;}
const sourceURLLineIndex=text.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1)
return text;const sourceURLLine=text.substr(sourceURLLineIndex+1).split('\n',1)[0];const sourceURLRegex=/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/;if(sourceURLLine.search(sourceURLRegex)===-1)
return text;return text.substr(0,sourceURLLineIndex)+text.substr(sourceURLLineIndex+sourceURLLine.length+1);}
domModel(){return this._domModel;}
setStyleText(styleSheetId,range,text,majorChange){const original=this._innerSetStyleTexts.bind(this,[styleSheetId],[range],[text],majorChange);const header=this.styleSheetHeaderForId(styleSheetId);if(!header)
return original();const sourceMap=this._sourceMapManager.sourceMapForClient(header);if(!sourceMap)
return original();const originalAndDetach=originalAndDetachIfSuccess.bind(this,header);if(!sourceMap.editable())
return original();return(sourceMap.editCompiled([range],[text]).then(onEditingDone.bind(this)).catch(onError.bind(this,header)));function onEditingDone(editResult){if(!editResult)
return Promise.resolve(false);let edits=editResult.compiledEdits;if(!edits.length)
return onCSSPatched.call(this,editResult,true);edits.sort(TextUtils.SourceEdit.comparator);edits=edits.reverse();const styleSheetIds=[];const ranges=[];const texts=[];for(const edit of edits){styleSheetIds.push(header.id);ranges.push(edit.oldRange);texts.push(edit.newText);}
return this._innerSetStyleTexts(styleSheetIds,ranges,texts,majorChange).then(onCSSPatched.bind(this,editResult));}
function onCSSPatched(editResult,success){if(!success)
return originalAndDetach();this._sourceMapManager.applySourceMapEdit(editResult);return Promise.resolve(true);}
function onError(header,error){Common.console.error(Common.UIString('LiveSASS failed: %s',sourceMap.compiledURL()));console.error(error);this._sourceMapManager.detachSourceMap(header);return original();}
function originalAndDetachIfSuccess(header){return this._innerSetStyleTexts([styleSheetId],[range],[text],majorChange).then(detachIfSuccess.bind(this));function detachIfSuccess(success){if(success)
this._sourceMapManager.detachSourceMap(header);return success;}}}
async _innerSetStyleTexts(styleSheetIds,ranges,texts,majorChange){console.assert(styleSheetIds.length===ranges.length&&ranges.length===texts.length,'Array lengths must be equal');const edits=[];const ensureContentPromises=[];for(let i=0;i<styleSheetIds.length;++i){edits.push({styleSheetId:styleSheetIds[i],range:ranges[i].serializeToObject(),text:texts[i]});ensureContentPromises.push(this._ensureOriginalStyleSheetText(styleSheetIds[i]));}
try{await Promise.all(ensureContentPromises);const stylePayloads=await this._agent.setStyleTexts(edits);if(!stylePayloads||stylePayloads.length!==ranges.length)
return false;this._domModel.markUndoableState(!majorChange);for(let i=0;i<ranges.length;++i){const edit=new SDK.CSSModel.Edit(styleSheetIds[i],ranges[i],texts[i],stylePayloads[i]);this._fireStyleSheetChanged(styleSheetIds[i],edit);}
return true;}catch(e){return false;}}
async setSelectorText(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const selectorPayload=await this._agent.setRuleSelector(styleSheetId,range,text);if(!selectorPayload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,text,selectorPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
async setKeyframeKey(styleSheetId,range,text){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const payload=await this._agent.setKeyframeKey(styleSheetId,range,text);if(!payload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,text,payload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
startCoverage(){this._agent.startRuleUsageTracking();}
takeCoverageDelta(){return this._agent.takeCoverageDelta().then(ruleUsage=>ruleUsage||[]);}
stopCoverage(){return this._agent.stopRuleUsageTracking();}
async mediaQueriesPromise(){const payload=await this._agent.getMediaQueries();return payload?SDK.CSSMedia.parseMediaArrayPayload(this,payload):[];}
isEnabled(){return this._isEnabled;}
async _enable(){await this._agent.enable();this._isEnabled=true;this.dispatchEventToListeners(SDK.CSSModel.Events.ModelWasEnabled);}
async matchedStylesPromise(nodeId){const response=await this._agent.invoke_getMatchedStylesForNode({nodeId});if(response[Protocol.Error])
return null;const node=this._domModel.nodeForId(nodeId);if(!node)
return null;return new SDK.CSSMatchedStyles(this,(node),response.inlineStyle||null,response.attributesStyle||null,response.matchedCSSRules||[],response.pseudoElements||[],response.inherited||[],response.cssKeyframesRules||[]);}
classNamesPromise(styleSheetId){return this._agent.collectClassNames(styleSheetId).then(classNames=>classNames||[]);}
computedStylePromise(nodeId){return this._styleLoader.computedStylePromise(nodeId);}
async backgroundColorsPromise(nodeId){const response=this._agent.invoke_getBackgroundColors({nodeId});if(response[Protocol.Error])
return null;return response;}
platformFontsPromise(nodeId){return this._agent.getPlatformFontsForNode(nodeId);}
allStyleSheets(){const values=this._styleSheetIdToHeader.valuesArray();function styleSheetComparator(a,b){if(a.sourceURL<b.sourceURL)
return-1;else if(a.sourceURL>b.sourceURL)
return 1;return a.startLine-b.startLine||a.startColumn-b.startColumn;}
values.sort(styleSheetComparator);return values;}
async inlineStylesPromise(nodeId){const response=await this._agent.invoke_getInlineStylesForNode({nodeId});if(response[Protocol.Error]||!response.inlineStyle)
return null;const inlineStyle=new SDK.CSSStyleDeclaration(this,null,response.inlineStyle,SDK.CSSStyleDeclaration.Type.Inline);const attributesStyle=response.attributesStyle?new SDK.CSSStyleDeclaration(this,null,response.attributesStyle,SDK.CSSStyleDeclaration.Type.Attributes):null;return new SDK.CSSModel.InlineStyleResult(inlineStyle,attributesStyle);}
forcePseudoState(node,pseudoClass,enable){const pseudoClasses=node.marker(SDK.CSSModel.PseudoStateMarker)||[];if(enable){if(pseudoClasses.indexOf(pseudoClass)>=0)
return false;pseudoClasses.push(pseudoClass);node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);}else{if(pseudoClasses.indexOf(pseudoClass)<0)
return false;pseudoClasses.remove(pseudoClass);if(pseudoClasses.length)
node.setMarker(SDK.CSSModel.PseudoStateMarker,pseudoClasses);else
node.setMarker(SDK.CSSModel.PseudoStateMarker,null);}
this._agent.forcePseudoState(node.id,pseudoClasses);this.dispatchEventToListeners(SDK.CSSModel.Events.PseudoStateForced,{node:node,pseudoClass:pseudoClass,enable:enable});return true;}
pseudoState(node){return node.marker(SDK.CSSModel.PseudoStateMarker)||[];}
async setMediaText(styleSheetId,range,newMediaText){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this._ensureOriginalStyleSheetText(styleSheetId);const mediaPayload=await this._agent.setMediaText(styleSheetId,range,newMediaText);if(!mediaPayload)
return false;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,range,newMediaText,mediaPayload);this._fireStyleSheetChanged(styleSheetId,edit);return true;}catch(e){return false;}}
async addRule(styleSheetId,ruleText,ruleLocation){try{await this._ensureOriginalStyleSheetText(styleSheetId);const rulePayload=await this._agent.addRule(styleSheetId,ruleText,ruleLocation);if(!rulePayload)
return null;this._domModel.markUndoableState();const edit=new SDK.CSSModel.Edit(styleSheetId,ruleLocation,ruleText,rulePayload);this._fireStyleSheetChanged(styleSheetId,edit);return new SDK.CSSStyleRule(this,rulePayload);}catch(e){return null;}}
async requestViaInspectorStylesheet(node){const frameId=node.frameId()||(this._resourceTreeModel?this._resourceTreeModel.mainFrame.id:'');const headers=this._styleSheetIdToHeader.valuesArray();const styleSheetHeader=headers.find(header=>header.frameId===frameId&&header.isViaInspector());if(styleSheetHeader)
return styleSheetHeader;try{const styleSheetId=await this._agent.createStyleSheet(frameId);return styleSheetId&&this._styleSheetIdToHeader.get(styleSheetId)||null;}catch(e){return null;}}
mediaQueryResultChanged(){this.dispatchEventToListeners(SDK.CSSModel.Events.MediaQueryResultChanged);}
fontsUpdated(){this.dispatchEventToListeners(SDK.CSSModel.Events.FontsUpdated);}
styleSheetHeaderForId(id){return this._styleSheetIdToHeader.get(id)||null;}
styleSheetHeaders(){return this._styleSheetIdToHeader.valuesArray();}
_fireStyleSheetChanged(styleSheetId,edit){this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetChanged,{styleSheetId:styleSheetId,edit:edit});}
_ensureOriginalStyleSheetText(styleSheetId){const header=this.styleSheetHeaderForId(styleSheetId);if(!header)
return Promise.resolve((null));let promise=this._originalStyleSheetText.get(header);if(!promise){promise=this.getStyleSheetText(header.id);this._originalStyleSheetText.set(header,promise);this._originalContentRequestedForTest(header);}
return promise;}
_originalContentRequestedForTest(header){}
originalStyleSheetText(header){return this._ensureOriginalStyleSheetText(header.id);}
_styleSheetAdded(header){console.assert(!this._styleSheetIdToHeader.get(header.styleSheetId));const styleSheetHeader=new SDK.CSSStyleSheetHeader(this,header);this._styleSheetIdToHeader.set(header.styleSheetId,styleSheetHeader);const url=styleSheetHeader.resourceURL();if(!this._styleSheetIdsForURL.get(url))
this._styleSheetIdsForURL.set(url,{});const frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);let styleSheetIds=frameIdToStyleSheetIds[styleSheetHeader.frameId];if(!styleSheetIds){styleSheetIds=[];frameIdToStyleSheetIds[styleSheetHeader.frameId]=styleSheetIds;}
styleSheetIds.push(styleSheetHeader.id);this._sourceMapManager.attachSourceMap(styleSheetHeader,styleSheetHeader.sourceURL,styleSheetHeader.sourceMapURL);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetAdded,styleSheetHeader);}
_styleSheetRemoved(id){const header=this._styleSheetIdToHeader.get(id);console.assert(header);if(!header)
return;this._styleSheetIdToHeader.remove(id);const url=header.resourceURL();const frameIdToStyleSheetIds=(this._styleSheetIdsForURL.get(url));console.assert(frameIdToStyleSheetIds,'No frameId to styleSheetId map is available for given style sheet URL.');frameIdToStyleSheetIds[header.frameId].remove(id);if(!frameIdToStyleSheetIds[header.frameId].length){delete frameIdToStyleSheetIds[header.frameId];if(!Object.keys(frameIdToStyleSheetIds).length)
this._styleSheetIdsForURL.remove(url);}
this._originalStyleSheetText.remove(header);this._sourceMapManager.detachSourceMap(header);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,header);}
styleSheetIdsForURL(url){const frameIdToStyleSheetIds=this._styleSheetIdsForURL.get(url);if(!frameIdToStyleSheetIds)
return[];let result=[];for(const frameId in frameIdToStyleSheetIds)
result=result.concat(frameIdToStyleSheetIds[frameId]);return result;}
async setStyleSheetText(styleSheetId,newText,majorChange){const header=(this._styleSheetIdToHeader.get(styleSheetId));console.assert(header);newText=SDK.CSSModel.trimSourceURL(newText);if(header.hasSourceURL)
newText+='\n/*# sourceURL='+header.sourceURL+' */';await this._ensureOriginalStyleSheetText(styleSheetId);const response=await this._agent.invoke_setStyleSheetText({styleSheetId:header.id,text:newText});const sourceMapURL=response.sourceMapURL;this._sourceMapManager.detachSourceMap(header);header.setSourceMapURL(sourceMapURL);this._sourceMapManager.attachSourceMap(header,header.sourceURL,header.sourceMapURL);if(sourceMapURL===null)
return'Error in CSS.setStyleSheetText';this._domModel.markUndoableState(!majorChange);this._fireStyleSheetChanged(styleSheetId);return null;}
async getStyleSheetText(styleSheetId){try{const text=await this._agent.getStyleSheetText(styleSheetId);return text&&SDK.CSSModel.trimSourceURL(text);}catch(e){return null;}}
_resetStyleSheets(){const headers=this._styleSheetIdToHeader.valuesArray();this._styleSheetIdsForURL.clear();this._styleSheetIdToHeader.clear();for(let i=0;i<headers.length;++i){this._sourceMapManager.detachSourceMap(headers[i]);this.dispatchEventToListeners(SDK.CSSModel.Events.StyleSheetRemoved,headers[i]);}}
suspendModel(){this._isEnabled=false;return this._agent.disable().then(this._resetStyleSheets.bind(this));}
async resumeModel(){return this._enable();}
setEffectivePropertyValueForNode(nodeId,name,value){this._agent.setEffectivePropertyValueForNode(nodeId,name,value);}
cachedMatchedCascadeForNode(node){if(this._cachedMatchedCascadeNode!==node)
this.discardCachedMatchedCascade();this._cachedMatchedCascadeNode=node;if(!this._cachedMatchedCascadePromise)
this._cachedMatchedCascadePromise=this.matchedStylesPromise(node.id);return this._cachedMatchedCascadePromise;}
discardCachedMatchedCascade(){delete this._cachedMatchedCascadeNode;delete this._cachedMatchedCascadePromise;}
dispose(){super.dispose();this._sourceMapManager.dispose();}};SDK.SDKModel.register(SDK.CSSModel,SDK.Target.Capability.DOM,true);SDK.CSSModel.RuleUsage;SDK.CSSModel.ContrastInfo;SDK.CSSModel.Events={FontsUpdated:Symbol('FontsUpdated'),MediaQueryResultChanged:Symbol('MediaQueryResultChanged'),ModelWasEnabled:Symbol('ModelWasEnabled'),PseudoStateForced:Symbol('PseudoStateForced'),StyleSheetAdded:Symbol('StyleSheetAdded'),StyleSheetChanged:Symbol('StyleSheetChanged'),StyleSheetRemoved:Symbol('StyleSheetRemoved')};SDK.CSSModel.MediaTypes=['all','braille','embossed','handheld','print','projection','screen','speech','tty','tv'];SDK.CSSModel.PseudoStateMarker='pseudo-state-marker';SDK.CSSModel.Edit=class{constructor(styleSheetId,oldRange,newText,payload){this.styleSheetId=styleSheetId;this.oldRange=oldRange;this.newRange=TextUtils.TextRange.fromEdit(oldRange,newText);this.newText=newText;this.payload=payload;}};SDK.CSSLocation=class{constructor(header,lineNumber,columnNumber){this._cssModel=header.cssModel();this.styleSheetId=header.id;this.url=header.resourceURL();this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;}
cssModel(){return this._cssModel;}
header(){return this._cssModel.styleSheetHeaderForId(this.styleSheetId);}};SDK.CSSDispatcher=class{constructor(cssModel){this._cssModel=cssModel;}
mediaQueryResultChanged(){this._cssModel.mediaQueryResultChanged();}
fontsUpdated(){this._cssModel.fontsUpdated();}
styleSheetChanged(styleSheetId){this._cssModel._fireStyleSheetChanged(styleSheetId);}
styleSheetAdded(header){this._cssModel._styleSheetAdded(header);}
styleSheetRemoved(id){this._cssModel._styleSheetRemoved(id);}};SDK.CSSModel.ComputedStyleLoader=class{constructor(cssModel){this._cssModel=cssModel;this._nodeIdToPromise=new Map();}
computedStylePromise(nodeId){let promise=this._nodeIdToPromise.get(nodeId);if(promise)
return promise;promise=this._cssModel._agent.getComputedStyleForNode(nodeId).then(parsePayload.bind(this));this._nodeIdToPromise.set(nodeId,promise);return promise;function parsePayload(computedPayload){this._nodeIdToPromise.delete(nodeId);if(!computedPayload||!computedPayload.length)
return null;const result=new Map();for(const property of computedPayload)
result.set(property.name,property.value);return result;}}};SDK.CSSModel.InlineStyleResult=class{constructor(inlineStyle,attributesStyle){this.inlineStyle=inlineStyle;this.attributesStyle=attributesStyle;}};;SDK.CSSProperty=class{constructor(ownerStyle,index,name,value,important,disabled,parsedOk,implicit,text,range){this.ownerStyle=ownerStyle;this.index=index;this.name=name;this.value=value;this.important=important;this.disabled=disabled;this.parsedOk=parsedOk;this.implicit=implicit;this.text=text;this.range=range?TextUtils.TextRange.fromObject(range):null;this._active=true;this._nameRange=null;this._valueRange=null;}
static parsePayload(ownerStyle,index,payload){const result=new SDK.CSSProperty(ownerStyle,index,payload.name,payload.value,payload.important||false,payload.disabled||false,('parsedOk'in payload)?!!payload.parsedOk:true,!!payload.implicit,payload.text,payload.range);return result;}
_ensureRanges(){if(this._nameRange&&this._valueRange)
return;const range=this.range;const text=this.text?new TextUtils.Text(this.text):null;if(!range||!text)
return;const nameIndex=text.value().indexOf(this.name);const valueIndex=text.value().lastIndexOf(this.value);if(nameIndex===-1||valueIndex===-1||nameIndex>valueIndex)
return;const nameSourceRange=new TextUtils.SourceRange(nameIndex,this.name.length);const valueSourceRange=new TextUtils.SourceRange(valueIndex,this.value.length);this._nameRange=rebase(text.toTextRange(nameSourceRange),range.startLine,range.startColumn);this._valueRange=rebase(text.toTextRange(valueSourceRange),range.startLine,range.startColumn);function rebase(oneLineRange,lineOffset,columnOffset){if(oneLineRange.startLine===0){oneLineRange.startColumn+=columnOffset;oneLineRange.endColumn+=columnOffset;}
oneLineRange.startLine+=lineOffset;oneLineRange.endLine+=lineOffset;return oneLineRange;}}
nameRange(){this._ensureRanges();return this._nameRange;}
valueRange(){this._ensureRanges();return this._valueRange;}
rebase(edit){if(this.ownerStyle.styleSheetId!==edit.styleSheetId)
return;if(this.range)
this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}
setActive(active){this._active=active;}
get propertyText(){if(this.text!==undefined)
return this.text;if(this.name==='')
return'';return this.name+': '+this.value+(this.important?' !important':'')+';';}
activeInStyle(){return this._active;}
setText(propertyText,majorChange,overwrite){if(!this.ownerStyle)
return Promise.reject(new Error('No ownerStyle for property'));if(!this.ownerStyle.styleSheetId)
return Promise.reject(new Error('No owner style id'));if(!this.range||!this.ownerStyle.range)
return Promise.reject(new Error('Style not editable'));if(majorChange)
Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);if(overwrite&&propertyText===this.propertyText){this.ownerStyle.cssModel().domModel().markUndoableState(!majorChange);return Promise.resolve(true);}
const range=this.range.relativeTo(this.ownerStyle.range.startLine,this.ownerStyle.range.startColumn);const indentation=this.ownerStyle.cssText?this._detectIndentation(this.ownerStyle.cssText):Common.moduleSetting('textEditorIndent').get();const endIndentation=this.ownerStyle.cssText?indentation.substring(0,this.ownerStyle.range.endColumn):'';const text=new TextUtils.Text(this.ownerStyle.cssText||'');const newStyleText=text.replaceRange(range,String.sprintf(';%s;',propertyText));return self.runtime.extension(TextUtils.TokenizerFactory).instance().then(this._formatStyle.bind(this,newStyleText,indentation,endIndentation)).then(setStyleText.bind(this));function setStyleText(styleText){return this.ownerStyle.setText(styleText,majorChange);}}
_formatStyle(styleText,indentation,endIndentation,tokenizerFactory){if(indentation)
indentation='\n'+indentation;let result='';let propertyText;let insideProperty=false;const tokenize=tokenizerFactory.createTokenizer('text/css');tokenize('*{'+styleText+'}',processToken);if(insideProperty)
result+=propertyText;result=result.substring(2,result.length-1).trimRight();return result+(indentation?'\n'+endIndentation:'');function processToken(token,tokenType,column,newColumn){if(!insideProperty){const disabledProperty=tokenType&&tokenType.includes('css-comment')&&isDisabledProperty(token);const isPropertyStart=tokenType&&(tokenType.includes('css-string')||tokenType.includes('css-meta')||tokenType.includes('css-property')||tokenType.includes('css-variable-2'));if(disabledProperty){result=result.trimRight()+indentation+token;}else if(isPropertyStart){insideProperty=true;propertyText=token;}else if(token!==';'){result+=token;}
return;}
if(token==='}'||token===';'){result=result.trimRight()+indentation+propertyText.trim()+';';insideProperty=false;if(token==='}')
result+='}';}else{propertyText+=token;}}
function isDisabledProperty(text){const colon=text.indexOf(':');if(colon===-1)
return false;const propertyName=text.substring(2,colon).trim();return SDK.cssMetadata().isCSSPropertyName(propertyName);}}
_detectIndentation(text){const lines=text.split('\n');if(lines.length<2)
return'';return TextUtils.TextUtils.lineIndent(lines[1]);}
setValue(newValue,majorChange,overwrite,userCallback){const text=this.name+': '+newValue+(this.important?' !important':'')+';';this.setText(text,majorChange,overwrite).then(userCallback);}
setDisabled(disabled){if(!this.ownerStyle)
return Promise.resolve(false);if(disabled===this.disabled)
return Promise.resolve(true);const propertyText=this.text.trim();const text=disabled?'/* '+propertyText+' */':this.text.substring(2,propertyText.length-2).trim();return this.setText(text,true,true);}};;SDK.CSSValue=class{constructor(payload){this.text=payload.text;if(payload.range)
this.range=TextUtils.TextRange.fromObject(payload.range);}
rebase(edit){if(!this.range)
return;this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);}};SDK.CSSRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this.styleSheetId=payload.styleSheetId;if(this.styleSheetId){const styleSheetHeader=cssModel.styleSheetHeaderForId(this.styleSheetId);this.sourceURL=styleSheetHeader.sourceURL;}
this.origin=payload.origin;this.style=new SDK.CSSStyleDeclaration(this._cssModel,this,payload.style,SDK.CSSStyleDeclaration.Type.Regular);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId)
return;this.style.rebase(edit);}
resourceURL(){if(!this.styleSheetId)
return'';const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.resourceURL();}
isUserAgent(){return this.origin===Protocol.CSS.StyleSheetOrigin.UserAgent;}
isInjected(){return this.origin===Protocol.CSS.StyleSheetOrigin.Injected;}
isViaInspector(){return this.origin===Protocol.CSS.StyleSheetOrigin.Inspector;}
isRegular(){return this.origin===Protocol.CSS.StyleSheetOrigin.Regular;}
cssModel(){return this._cssModel;}};SDK.CSSStyleRule=class extends SDK.CSSRule{constructor(cssModel,payload,wasUsed){super(cssModel,payload);this._reinitializeSelectors(payload.selectorList);this.media=payload.media?SDK.CSSMedia.parseMediaArrayPayload(cssModel,payload.media):[];this.wasUsed=wasUsed||false;}
static createDummyRule(cssModel,selectorText){const dummyPayload={selectorList:{selectors:[{text:selectorText}],},style:{styleSheetId:'0',range:new TextUtils.TextRange(0,0,0,0),shorthandEntries:[],cssProperties:[]}};return new SDK.CSSStyleRule(cssModel,(dummyPayload));}
_reinitializeSelectors(selectorList){this.selectors=[];for(let i=0;i<selectorList.selectors.length;++i)
this.selectors.push(new SDK.CSSValue(selectorList.selectors[i]));}
setSelectorText(newSelector){const styleSheetId=this.styleSheetId;if(!styleSheetId)
throw'No rule stylesheet id';const range=this.selectorRange();if(!range)
throw'Rule selector is not editable';return this._cssModel.setSelectorText(styleSheetId,range,newSelector);}
selectorText(){return this.selectors.select('text').join(', ');}
selectorRange(){const firstRange=this.selectors[0].range;if(!firstRange)
return null;const lastRange=this.selectors.peekLast().range;return new TextUtils.TextRange(firstRange.startLine,firstRange.startColumn,lastRange.endLine,lastRange.endColumn);}
lineNumberInSource(selectorIndex){const selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId)
return 0;const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);return styleSheetHeader.lineNumberInSource(selector.range.startLine);}
columnNumberInSource(selectorIndex){const selector=this.selectors[selectorIndex];if(!selector||!selector.range||!this.styleSheetId)
return undefined;const styleSheetHeader=this._cssModel.styleSheetHeaderForId(this.styleSheetId);console.assert(styleSheetHeader);return styleSheetHeader.columnNumberInSource(selector.range.startLine,selector.range.startColumn);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId)
return;if(this.selectorRange().equal(edit.oldRange)){this._reinitializeSelectors((edit.payload));}else{for(let i=0;i<this.selectors.length;++i)
this.selectors[i].rebase(edit);}
for(const media of this.media)
media.rebase(edit);super.rebase(edit);}};SDK.CSSKeyframesRule=class{constructor(cssModel,payload){this._cssModel=cssModel;this._animationName=new SDK.CSSValue(payload.animationName);this._keyframes=payload.keyframes.map(keyframeRule=>new SDK.CSSKeyframeRule(cssModel,keyframeRule));}
name(){return this._animationName;}
keyframes(){return this._keyframes;}};SDK.CSSKeyframeRule=class extends SDK.CSSRule{constructor(cssModel,payload){super(cssModel,payload);this._reinitializeKey(payload.keyText);}
key(){return this._keyText;}
_reinitializeKey(payload){this._keyText=new SDK.CSSValue(payload);}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this._keyText.range)
return;if(edit.oldRange.equal(this._keyText.range))
this._reinitializeKey((edit.payload));else
this._keyText.rebase(edit);super.rebase(edit);}
setKeyText(newKeyText){const styleSheetId=this.styleSheetId;if(!styleSheetId)
throw'No rule stylesheet id';const range=this._keyText.range;if(!range)
throw'Keyframe key is not editable';return this._cssModel.setKeyframeKey(styleSheetId,range,newKeyText);}};;SDK.CSSStyleDeclaration=class{constructor(cssModel,parentRule,payload,type){this._cssModel=cssModel;this.parentRule=parentRule;this._allProperties;this.styleSheetId;this.range;this.cssText;this._shorthandValues;this._shorthandIsImportant;this._activePropertyMap;this._leadingProperties;this._reinitialize(payload);this.type=type;}
rebase(edit){if(this.styleSheetId!==edit.styleSheetId||!this.range)
return;if(edit.oldRange.equal(this.range)){this._reinitialize((edit.payload));}else{this.range=this.range.rebaseAfterTextEdit(edit.oldRange,edit.newRange);for(let i=0;i<this._allProperties.length;++i)
this._allProperties[i].rebase(edit);}}
_reinitialize(payload){this.styleSheetId=payload.styleSheetId;this.range=payload.range?TextUtils.TextRange.fromObject(payload.range):null;const shorthandEntries=payload.shorthandEntries;this._shorthandValues=new Map();this._shorthandIsImportant=new Set();for(let i=0;i<shorthandEntries.length;++i){this._shorthandValues.set(shorthandEntries[i].name,shorthandEntries[i].value);if(shorthandEntries[i].important)
this._shorthandIsImportant.add(shorthandEntries[i].name);}
this._allProperties=[];for(let i=0;i<payload.cssProperties.length;++i){const property=SDK.CSSProperty.parsePayload(this,i,payload.cssProperties[i]);this._allProperties.push(property);}
this._generateSyntheticPropertiesIfNeeded();this._computeInactiveProperties();this._activePropertyMap=new Map();for(const property of this._allProperties){if(!property.activeInStyle())
continue;this._activePropertyMap.set(property.name,property);}
this.cssText=payload.cssText;this._leadingProperties=null;}
_generateSyntheticPropertiesIfNeeded(){if(this.range)
return;if(!this._shorthandValues.size)
return;const propertiesSet=new Set();for(const property of this._allProperties)
propertiesSet.add(property.name);const generatedProperties=[];for(const property of this._allProperties){const shorthands=SDK.cssMetadata().shorthands(property.name)||[];for(const shorthand of shorthands){if(propertiesSet.has(shorthand))
continue;const shorthandValue=this._shorthandValues.get(shorthand);if(!shorthandValue)
continue;const shorthandImportance=!!this._shorthandIsImportant.has(shorthand);const shorthandProperty=new SDK.CSSProperty(this,this.allProperties().length,shorthand,shorthandValue,shorthandImportance,false,true,false);generatedProperties.push(shorthandProperty);propertiesSet.add(shorthand);}}
this._allProperties=this._allProperties.concat(generatedProperties);}
_computeLeadingProperties(){function propertyHasRange(property){return!!property.range;}
if(this.range)
return this._allProperties.filter(propertyHasRange);const leadingProperties=[];for(const property of this._allProperties){const shorthands=SDK.cssMetadata().shorthands(property.name)||[];let belongToAnyShorthand=false;for(const shorthand of shorthands){if(this._shorthandValues.get(shorthand)){belongToAnyShorthand=true;break;}}
if(!belongToAnyShorthand)
leadingProperties.push(property);}
return leadingProperties;}
leadingProperties(){if(!this._leadingProperties)
this._leadingProperties=this._computeLeadingProperties();return this._leadingProperties;}
target(){return this._cssModel.target();}
cssModel(){return this._cssModel;}
_computeInactiveProperties(){const activeProperties={};for(let i=0;i<this._allProperties.length;++i){const property=this._allProperties[i];if(property.disabled||!property.parsedOk){property.setActive(false);continue;}
const canonicalName=SDK.cssMetadata().canonicalPropertyName(property.name);const activeProperty=activeProperties[canonicalName];if(!activeProperty){activeProperties[canonicalName]=property;}else if(!activeProperty.important||property.important){activeProperty.setActive(false);activeProperties[canonicalName]=property;}else{property.setActive(false);}}}
allProperties(){return this._allProperties;}
getPropertyValue(name){const property=this._activePropertyMap.get(name);return property?property.value:'';}
isPropertyImplicit(name){const property=this._activePropertyMap.get(name);return property?property.implicit:false;}
longhandProperties(name){const longhands=SDK.cssMetadata().longhands(name);const result=[];for(let i=0;longhands&&i<longhands.length;++i){const property=this._activePropertyMap.get(longhands[i]);if(property)
result.push(property);}
return result;}
propertyAt(index){return(index<this.allProperties().length)?this.allProperties()[index]:null;}
pastLastSourcePropertyIndex(){for(let i=this.allProperties().length-1;i>=0;--i){if(this.allProperties()[i].range)
return i+1;}
return 0;}
_insertionRange(index){const property=this.propertyAt(index);return property&&property.range?property.range.collapseToStart():this.range.collapseToEnd();}
newBlankProperty(index){index=(typeof index==='undefined')?this.pastLastSourcePropertyIndex():index;const property=new SDK.CSSProperty(this,index,'','',false,false,true,false,'',this._insertionRange(index));return property;}
setText(text,majorChange){if(!this.range||!this.styleSheetId)
return Promise.resolve(false);return this._cssModel.setStyleText(this.styleSheetId,this.range,text,majorChange);}
insertPropertyAt(index,name,value,userCallback){this.newBlankProperty(index).setText(name+': '+value+';',false,true).then(userCallback);}
appendProperty(name,value,userCallback){this.insertPropertyAt(this.allProperties().length,name,value,userCallback);}};SDK.CSSStyleDeclaration.Type={Regular:'Regular',Inline:'Inline',Attributes:'Attributes'};;SDK.CSSStyleSheetHeader=class{constructor(cssModel,payload){this._cssModel=cssModel;this.id=payload.styleSheetId;this.frameId=payload.frameId;this.sourceURL=payload.sourceURL;this.hasSourceURL=!!payload.hasSourceURL;this.origin=payload.origin;this.title=payload.title;this.disabled=payload.disabled;this.isInline=payload.isInline;this.startLine=payload.startLine;this.startColumn=payload.startColumn;this.contentLength=payload.length;if(payload.ownerNode)
this.ownerNode=new SDK.DeferredDOMNode(cssModel.target(),payload.ownerNode);this.setSourceMapURL(payload.sourceMapURL);}
originalContentProvider(){if(!this._originalContentProvider){const lazyContent=this._cssModel.originalStyleSheetText.bind(this._cssModel,this);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),(lazyContent));}
return this._originalContentProvider;}
setSourceMapURL(sourceMapURL){this.sourceMapURL=sourceMapURL;}
cssModel(){return this._cssModel;}
isAnonymousInlineStyleSheet(){return!this.resourceURL()&&!this._cssModel.sourceMapManager().sourceMapForClient(this);}
resourceURL(){return this.isViaInspector()?this._viaInspectorResourceURL():this.sourceURL;}
_viaInspectorResourceURL(){const frame=this._cssModel.target().model(SDK.ResourceTreeModel).frameForId(this.frameId);console.assert(frame);const parsedURL=new Common.ParsedURL(frame.url);let fakeURL='inspector://'+parsedURL.host+parsedURL.folderPathComponents;if(!fakeURL.endsWith('/'))
fakeURL+='/';fakeURL+='inspector-stylesheet';return fakeURL;}
lineNumberInSource(lineNumberInStyleSheet){return this.startLine+lineNumberInStyleSheet;}
columnNumberInSource(lineNumberInStyleSheet,columnNumberInStyleSheet){return(lineNumberInStyleSheet?0:this.startColumn)+columnNumberInStyleSheet;}
contentURL(){return this.resourceURL();}
contentType(){return Common.resourceTypes.Stylesheet;}
contentEncoded(){return Promise.resolve(false);}
requestContent(){return this._cssModel.getStyleSheetText(this.id);}
async searchInContent(query,caseSensitive,isRegex){const content=await this.requestContent();return Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex);}
isViaInspector(){return this.origin==='inspector';}};;SDK.ChildTargetManager=class extends SDK.SDKModel{constructor(parentTarget){super(parentTarget);this._targetManager=parentTarget.targetManager();this._parentTarget=parentTarget;this._targetAgent=parentTarget.targetAgent();this._targetInfos=new Map();this._childConnections=new Map();parentTarget.registerTargetDispatcher(this);this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true});if(!parentTarget.parentTarget()){this._targetAgent.setDiscoverTargets(true);this._targetAgent.setRemoteLocations([{host:'localhost',port:9229}]);}}
static install(attachCallback){SDK.ChildTargetManager._attachCallback=attachCallback;SDK.SDKModel.register(SDK.ChildTargetManager,SDK.Target.Capability.Target,true);}
suspendModel(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:false});}
resumeModel(){return this._targetAgent.invoke_setAutoAttach({autoAttach:true,waitForDebuggerOnStart:true});}
dispose(){for(const sessionId of this._childConnections.keys())
this.detachedFromTarget(sessionId,undefined);}
_capabilitiesForType(type){if(type==='worker')
return SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network;if(type==='service_worker')
return SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target;if(type==='iframe'){return SDK.Target.Capability.Browser|SDK.Target.Capability.DOM|SDK.Target.Capability.JS|SDK.Target.Capability.Log|SDK.Target.Capability.Network|SDK.Target.Capability.Target|SDK.Target.Capability.Tracing|SDK.Target.Capability.Emulation|SDK.Target.Capability.Input;}
return 0;}
targetCreated(targetInfo){this._targetInfos.set(targetInfo.targetId,targetInfo);this._fireAvailableTargetsChanged();}
targetInfoChanged(targetInfo){this._targetInfos.set(targetInfo.targetId,targetInfo);this._fireAvailableTargetsChanged();}
targetDestroyed(targetId){this._targetInfos.delete(targetId);this._fireAvailableTargetsChanged();}
_fireAvailableTargetsChanged(){SDK.targetManager.dispatchEventToListeners(SDK.TargetManager.Events.AvailableTargetsChanged,this._targetInfos.valuesArray());}
attachedToTarget(sessionId,targetInfo,waitingForDebugger){let targetName='';if(targetInfo.type!=='iframe'){const parsedURL=targetInfo.url.asParsedURL();targetName=parsedURL?parsedURL.lastPathComponentWithFragment():'#'+(++SDK.ChildTargetManager._lastAnonymousTargetId);}
const target=this._targetManager.createTarget(targetInfo.targetId,targetName,this._capabilitiesForType(targetInfo.type),this._createChildConnection.bind(this,this._targetAgent,sessionId),this._parentTarget);if(SDK.ChildTargetManager._attachCallback)
SDK.ChildTargetManager._attachCallback({target,waitingForDebugger});target.runtimeAgent().runIfWaitingForDebugger();}
detachedFromTarget(sessionId,childTargetId){this._childConnections.get(sessionId).onDisconnect.call(null,'target terminated');this._childConnections.delete(sessionId);}
receivedMessageFromTarget(sessionId,message,childTargetId){const connection=this._childConnections.get(sessionId);if(connection)
connection.onMessage.call(null,message);}
_createChildConnection(agent,sessionId,params){const connection=new SDK.ChildConnection(agent,sessionId,params);this._childConnections.set(sessionId,connection);return connection;}};SDK.ChildTargetManager._lastAnonymousTargetId=0;SDK.ChildTargetManager._attachCallback;;SDK.DOMDebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domdebuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._domModel=(target.model(SDK.DOMModel));this._domModel.addEventListener(SDK.DOMModel.Events.DocumentUpdated,this._documentUpdated,this);this._domModel.addEventListener(SDK.DOMModel.Events.NodeRemoved,this._nodeRemoved,this);this._domBreakpoints=[];this._domBreakpointsSetting=Common.settings.createLocalSetting('domBreakpoints',[]);if(this._domModel.existingDocument())
this._documentUpdated();}
runtimeModel(){return this._runtimeModel;}
async eventListeners(remoteObject){console.assert(remoteObject.runtimeModel()===this._runtimeModel);if(!remoteObject.objectId)
return[];const payloads=await this._agent.getEventListeners((remoteObject.objectId));const eventListeners=[];for(const payload of payloads||[]){const location=this._runtimeModel.debuggerModel().createRawLocationByScriptId(payload.scriptId,payload.lineNumber,payload.columnNumber);if(!location)
continue;eventListeners.push(new SDK.EventListener(this,remoteObject,payload.type,payload.useCapture,payload.passive,payload.once,payload.handler?this._runtimeModel.createRemoteObject(payload.handler):null,payload.originalHandler?this._runtimeModel.createRemoteObject(payload.originalHandler):null,location,null));}
return eventListeners;}
retrieveDOMBreakpoints(){this._domModel.requestDocument();}
domBreakpoints(){return this._domBreakpoints.slice();}
hasDOMBreakpoint(node,type){return this._domBreakpoints.some(breakpoint=>(breakpoint.node===node&&breakpoint.type===type));}
setDOMBreakpoint(node,type){for(const breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.type===type){this.toggleDOMBreakpoint(breakpoint,true);return breakpoint;}}
const breakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,type,true);this._domBreakpoints.push(breakpoint);this._saveDOMBreakpoints();this._enableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,breakpoint);return breakpoint;}
removeDOMBreakpoint(node,type){this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node&&breakpoint.type===type);}
removeAllDOMBreakpoints(){this._removeDOMBreakpoints(breakpoint=>true);}
toggleDOMBreakpoint(breakpoint,enabled){if(enabled===breakpoint.enabled)
return;breakpoint.enabled=enabled;if(enabled)
this._enableDOMBreakpoint(breakpoint);else
this._disableDOMBreakpoint(breakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointToggled,breakpoint);}
_enableDOMBreakpoint(breakpoint){this._agent.setDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,true);}
_disableDOMBreakpoint(breakpoint){this._agent.removeDOMBreakpoint(breakpoint.node.id,breakpoint.type);breakpoint.node.setMarker(SDK.DOMDebuggerModel.DOMBreakpoint.Marker,this._nodeHasBreakpoints(breakpoint.node)?true:null);}
_nodeHasBreakpoints(node){for(const breakpoint of this._domBreakpoints){if(breakpoint.node===node&&breakpoint.enabled)
return true;}
return false;}
resolveDOMBreakpointData(auxData){const type=auxData['type'];const node=this._domModel.nodeForId(auxData['nodeId']);if(!type||!node)
return null;let targetNode=null;let insertion=false;if(type===SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified){insertion=auxData['insertion']||false;targetNode=this._domModel.nodeForId(auxData['targetNodeId']);}
return{type:type,node:node,targetNode:targetNode,insertion:insertion};}
_currentURL(){const domDocument=this._domModel.existingDocument();return domDocument?domDocument.documentURL:'';}
_documentUpdated(){const removed=this._domBreakpoints;this._domBreakpoints=[];this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);const currentURL=this._currentURL();for(const breakpoint of this._domBreakpointsSetting.get()){if(breakpoint.url===currentURL)
this._domModel.pushNodeByPathToFrontend(breakpoint.path).then(appendBreakpoint.bind(this,breakpoint));}
function appendBreakpoint(breakpoint,nodeId){const node=nodeId?this._domModel.nodeForId(nodeId):null;if(!node)
return;const domBreakpoint=new SDK.DOMDebuggerModel.DOMBreakpoint(this,node,breakpoint.type,breakpoint.enabled);this._domBreakpoints.push(domBreakpoint);if(breakpoint.enabled)
this._enableDOMBreakpoint(domBreakpoint);this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded,domBreakpoint);}}
_removeDOMBreakpoints(filter){const removed=[];const left=[];for(const breakpoint of this._domBreakpoints){if(filter(breakpoint)){removed.push(breakpoint);if(breakpoint.enabled){breakpoint.enabled=false;this._disableDOMBreakpoint(breakpoint);}}else{left.push(breakpoint);}}
if(!removed.length)
return;this._domBreakpoints=left;this._saveDOMBreakpoints();this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved,removed);}
_nodeRemoved(event){const node=(event.data.node);const children=node.children()||[];this._removeDOMBreakpoints(breakpoint=>breakpoint.node===node||children.indexOf(breakpoint.node)!==-1);}
_saveDOMBreakpoints(){const currentURL=this._currentURL();const breakpoints=this._domBreakpointsSetting.get().filter(breakpoint=>breakpoint.url!==currentURL);for(const breakpoint of this._domBreakpoints){breakpoints.push({url:currentURL,path:breakpoint.node.path(),type:breakpoint.type,enabled:breakpoint.enabled});}
this._domBreakpointsSetting.set(breakpoints);}};SDK.SDKModel.register(SDK.DOMDebuggerModel,SDK.Target.Capability.DOM,false);SDK.DOMDebuggerModel.Events={DOMBreakpointAdded:Symbol('DOMBreakpointAdded'),DOMBreakpointToggled:Symbol('DOMBreakpointToggled'),DOMBreakpointsRemoved:Symbol('DOMBreakpointsRemoved'),};SDK.DOMDebuggerModel.DOMBreakpoint=class{constructor(domDebuggerModel,node,type,enabled){this.domDebuggerModel=domDebuggerModel;this.node=node;this.type=type;this.enabled=enabled;}};SDK.DOMDebuggerModel.DOMBreakpoint.Type=Protocol.DOMDebugger.DOMBreakpointType;SDK.DOMDebuggerModel.DOMBreakpoint.Marker='breakpoint-marker';SDK.EventListener=class{constructor(domDebuggerModel,eventTarget,type,useCapture,passive,once,handler,originalHandler,location,customRemoveFunction,origin){this._domDebuggerModel=domDebuggerModel;this._eventTarget=eventTarget;this._type=type;this._useCapture=useCapture;this._passive=passive;this._once=once;this._handler=handler;this._originalHandler=originalHandler||handler;this._location=location;const script=location.script();this._sourceURL=script?script.contentURL():'';this._customRemoveFunction=customRemoveFunction;this._origin=origin||SDK.EventListener.Origin.Raw;}
domDebuggerModel(){return this._domDebuggerModel;}
type(){return this._type;}
useCapture(){return this._useCapture;}
passive(){return this._passive;}
once(){return this._once;}
handler(){return this._handler;}
location(){return this._location;}
sourceURL(){return this._sourceURL;}
originalHandler(){return this._originalHandler;}
canRemove(){return!!this._customRemoveFunction||this._origin!==SDK.EventListener.Origin.FrameworkUser;}
remove(){if(!this.canRemove())
return Promise.resolve();if(this._origin!==SDK.EventListener.Origin.FrameworkUser){function removeListener(type,listener,useCapture){this.removeEventListener(type,listener,useCapture);if(this['on'+type])
this['on'+type]=undefined;}
return(this._eventTarget.callFunctionPromise(removeListener,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture)]));}
return this._customRemoveFunction.callFunctionPromise(callCustomRemove,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]).then(()=>undefined);function callCustomRemove(type,listener,useCapture,passive){this.call(null,type,listener,useCapture,passive);}}
canTogglePassive(){return this._origin!==SDK.EventListener.Origin.FrameworkUser;}
togglePassive(){return(this._eventTarget.callFunctionPromise(callTogglePassive,[SDK.RemoteObject.toCallArgument(this._type),SDK.RemoteObject.toCallArgument(this._originalHandler),SDK.RemoteObject.toCallArgument(this._useCapture),SDK.RemoteObject.toCallArgument(this._passive),]));function callTogglePassive(type,listener,useCapture,passive){this.removeEventListener(type,listener,{capture:useCapture});this.addEventListener(type,listener,{capture:useCapture,passive:!passive});}}
origin(){return this._origin;}
markAsFramework(){this._origin=SDK.EventListener.Origin.Framework;}
isScrollBlockingType(){return this._type==='touchstart'||this._type==='touchmove'||this._type==='mousewheel'||this._type==='wheel';}};SDK.EventListener.Origin={Raw:'Raw',Framework:'Framework',FrameworkUser:'FrameworkUser'};SDK.DOMDebuggerModel.EventListenerBreakpoint=class{constructor(instrumentationName,eventName,eventTargetNames,category,title){this._instrumentationName=instrumentationName;this._eventName=eventName;this._eventTargetNames=eventTargetNames;this._category=category;this._title=title;this._enabled=false;}
category(){return this._category;}
enabled(){return this._enabled;}
setEnabled(enabled){if(this._enabled===enabled)
return;this._enabled=enabled;for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
this._updateOnModel(model);}
_updateOnModel(model){if(this._instrumentationName){if(this._enabled)
model._agent.setInstrumentationBreakpoint(this._instrumentationName);else
model._agent.removeInstrumentationBreakpoint(this._instrumentationName);}else{for(const eventTargetName of this._eventTargetNames){if(this._enabled)
model._agent.setEventListenerBreakpoint(this._eventName,eventTargetName);else
model._agent.removeEventListenerBreakpoint(this._eventName,eventTargetName);}}}
title(){return this._title;}};SDK.DOMDebuggerModel.EventListenerBreakpoint._listener='listener:';SDK.DOMDebuggerModel.EventListenerBreakpoint._instrumentation='instrumentation:';SDK.DOMDebuggerManager=class{constructor(){this._xhrBreakpointsSetting=Common.settings.createLocalSetting('xhrBreakpoints',[]);this._xhrBreakpoints=new Map();for(const breakpoint of this._xhrBreakpointsSetting.get())
this._xhrBreakpoints.set(breakpoint.url,breakpoint.enabled);this._eventListenerBreakpoints=[];this._createInstrumentationBreakpoints(Common.UIString('Animation'),['requestAnimationFrame','cancelAnimationFrame','requestAnimationFrame.callback']);this._createInstrumentationBreakpoints(Common.UIString('Canvas'),['canvasContextCreated','webglErrorFired','webglWarningFired']);this._createInstrumentationBreakpoints(Common.UIString('Geolocation'),['Geolocation.getCurrentPosition','Geolocation.watchPosition']);this._createInstrumentationBreakpoints(Common.UIString('Notification'),['Notification.requestPermission']);this._createInstrumentationBreakpoints(Common.UIString('Parse'),['Element.setInnerHTML','Document.write']);this._createInstrumentationBreakpoints(Common.UIString('Script'),['scriptFirstStatement','scriptBlockedByCSP']);this._createInstrumentationBreakpoints(Common.UIString('Timer'),['setTimeout','clearTimeout','setInterval','clearInterval','setTimeout.callback','setInterval.callback']);this._createInstrumentationBreakpoints(Common.UIString('Window'),['DOMWindow.close']);this._createEventListenerBreakpoints(Common.UIString('Media'),['play','pause','playing','canplay','canplaythrough','seeking','seeked','timeupdate','ended','ratechange','durationchange','volumechange','loadstart','progress','suspend','abort','error','emptied','stalled','loadedmetadata','loadeddata','waiting'],['audio','video']);this._createEventListenerBreakpoints(Common.UIString('Clipboard'),['copy','cut','paste','beforecopy','beforecut','beforepaste'],['*']);this._createEventListenerBreakpoints(Common.UIString('Control'),['resize','scroll','zoom','focus','blur','select','change','submit','reset'],['*']);this._createEventListenerBreakpoints(Common.UIString('Device'),['deviceorientation','devicemotion'],['*']);this._createEventListenerBreakpoints(Common.UIString('DOM Mutation'),['DOMActivate','DOMFocusIn','DOMFocusOut','DOMAttrModified','DOMCharacterDataModified','DOMNodeInserted','DOMNodeInsertedIntoDocument','DOMNodeRemoved','DOMNodeRemovedFromDocument','DOMSubtreeModified','DOMContentLoaded'],['*']);this._createEventListenerBreakpoints(Common.UIString('Drag / drop'),['drag','dragstart','dragend','dragenter','dragover','dragleave','drop'],['*']);this._createEventListenerBreakpoints(Common.UIString('Keyboard'),['keydown','keyup','keypress','input'],['*']);this._createEventListenerBreakpoints(Common.UIString('Load'),['load','beforeunload','unload','abort','error','hashchange','popstate'],['*']);this._createEventListenerBreakpoints(Common.UIString('Mouse'),['auxclick','click','dblclick','mousedown','mouseup','mouseover','mousemove','mouseout','mouseenter','mouseleave','mousewheel','wheel','contextmenu'],['*']);this._createEventListenerBreakpoints(Common.UIString('Pointer'),['pointerover','pointerout','pointerenter','pointerleave','pointerdown','pointerup','pointermove','pointercancel','gotpointercapture','lostpointercapture'],['*']);this._createEventListenerBreakpoints(Common.UIString('Touch'),['touchstart','touchmove','touchend','touchcancel'],['*']);this._createEventListenerBreakpoints(Common.UIString('Worker'),['message','messageerror'],['*']);this._createEventListenerBreakpoints(Common.UIString('XHR'),['readystatechange','load','loadstart','loadend','abort','error','progress','timeout'],['xmlhttprequest','xmlhttprequestupload']);this._resolveEventListenerBreakpoint('instrumentation:setTimeout.callback')._title=Common.UIString('setTimeout fired');this._resolveEventListenerBreakpoint('instrumentation:setInterval.callback')._title=Common.UIString('setInterval fired');this._resolveEventListenerBreakpoint('instrumentation:scriptFirstStatement')._title=Common.UIString('Script First Statement');this._resolveEventListenerBreakpoint('instrumentation:scriptBlockedByCSP')._title=Common.UIString('Script Blocked by Content Security Policy');this._resolveEventListenerBreakpoint('instrumentation:requestAnimationFrame')._title=Common.UIString('Request Animation Frame');this._resolveEventListenerBreakpoint('instrumentation:cancelAnimationFrame')._title=Common.UIString('Cancel Animation Frame');this._resolveEventListenerBreakpoint('instrumentation:requestAnimationFrame.callback')._title=Common.UIString('Animation Frame Fired');this._resolveEventListenerBreakpoint('instrumentation:webglErrorFired')._title=Common.UIString('WebGL Error Fired');this._resolveEventListenerBreakpoint('instrumentation:webglWarningFired')._title=Common.UIString('WebGL Warning Fired');this._resolveEventListenerBreakpoint('instrumentation:Element.setInnerHTML')._title=Common.UIString('Set innerHTML');this._resolveEventListenerBreakpoint('instrumentation:canvasContextCreated')._title=Common.UIString('Create canvas context');this._resolveEventListenerBreakpoint('instrumentation:Geolocation.getCurrentPosition')._title='getCurrentPosition';this._resolveEventListenerBreakpoint('instrumentation:Geolocation.watchPosition')._title='watchPosition';this._resolveEventListenerBreakpoint('instrumentation:Notification.requestPermission')._title='requestPermission';this._resolveEventListenerBreakpoint('instrumentation:DOMWindow.close')._title='window.close';this._resolveEventListenerBreakpoint('instrumentation:Document.write')._title='document.write';SDK.targetManager.observeModels(SDK.DOMDebuggerModel,this);}
_createInstrumentationBreakpoints(category,instrumentationNames){for(const instrumentationName of instrumentationNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint(instrumentationName,'',[],category,instrumentationName));}}
_createEventListenerBreakpoints(category,eventNames,eventTargetNames){for(const eventName of eventNames){this._eventListenerBreakpoints.push(new SDK.DOMDebuggerModel.EventListenerBreakpoint('',eventName,eventTargetNames,category,eventName));}}
_resolveEventListenerBreakpoint(eventName,eventTargetName){const instrumentationPrefix='instrumentation:';const listenerPrefix='listener:';let instrumentationName='';if(eventName.startsWith(instrumentationPrefix)){instrumentationName=eventName.substring(instrumentationPrefix.length);eventName='';}else if(eventName.startsWith(listenerPrefix)){eventName=eventName.substring(listenerPrefix.length);}else{return null;}
eventTargetName=(eventTargetName||'*').toLowerCase();let result=null;for(const breakpoint of this._eventListenerBreakpoints){if(instrumentationName&&breakpoint._instrumentationName===instrumentationName)
result=breakpoint;if(eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf(eventTargetName)!==-1)
result=breakpoint;if(!result&&eventName&&breakpoint._eventName===eventName&&breakpoint._eventTargetNames.indexOf('*')!==-1)
result=breakpoint;}
return result;}
eventListenerBreakpoints(){return this._eventListenerBreakpoints.slice();}
resolveEventListenerBreakpointTitle(auxData){const id=auxData['eventName'];if(id==='instrumentation:webglErrorFired'&&auxData['webglErrorName']){let errorName=auxData['webglErrorName'];errorName=errorName.replace(/^.*(0x[0-9a-f]+).*$/i,'$1');return Common.UIString('WebGL Error Fired (%s)',errorName);}
if(id==='instrumentation:scriptBlockedByCSP'&&auxData['directiveText'])
return Common.UIString('Script blocked due to Content Security Policy directive: %s',auxData['directiveText']);const breakpoint=this._resolveEventListenerBreakpoint(id,auxData['targetName']);if(!breakpoint)
return'';if(auxData['targetName'])
return auxData['targetName']+'.'+breakpoint._title;return breakpoint._title;}
resolveEventListenerBreakpoint(auxData){return this._resolveEventListenerBreakpoint(auxData['eventName'],auxData['targetName']);}
xhrBreakpoints(){return this._xhrBreakpoints;}
_saveXHRBreakpoints(){const breakpoints=[];for(const url of this._xhrBreakpoints.keys())
breakpoints.push({url:url,enabled:this._xhrBreakpoints.get(url)});this._xhrBreakpointsSetting.set(breakpoints);}
addXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);if(enabled){for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
model._agent.setXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
removeXHRBreakpoint(url){const enabled=this._xhrBreakpoints.get(url);this._xhrBreakpoints.delete(url);if(enabled){for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel))
model._agent.removeXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
toggleXHRBreakpoint(url,enabled){this._xhrBreakpoints.set(url,enabled);for(const model of SDK.targetManager.models(SDK.DOMDebuggerModel)){if(enabled)
model._agent.setXHRBreakpoint(url);else
model._agent.removeXHRBreakpoint(url);}
this._saveXHRBreakpoints();}
modelAdded(domDebuggerModel){for(const url of this._xhrBreakpoints.keys()){if(this._xhrBreakpoints.get(url))
domDebuggerModel._agent.setXHRBreakpoint(url);}
for(const breakpoint of this._eventListenerBreakpoints){if(breakpoint._enabled)
breakpoint._updateOnModel(domDebuggerModel);}}
modelRemoved(domDebuggerModel){}};SDK.domDebuggerManager;;SDK.DOMNode=class{constructor(domModel){this._domModel=domModel;}
static create(domModel,doc,isInShadowTree,payload){const node=new SDK.DOMNode(domModel);node._init(doc,isInShadowTree,payload);return node;}
_init(doc,isInShadowTree,payload){this._agent=this._domModel._agent;this.ownerDocument=doc;this._isInShadowTree=isInShadowTree;this.id=payload.nodeId;this._backendNodeId=payload.backendNodeId;this._domModel._idToDOMNode[this.id]=this;this._nodeType=payload.nodeType;this._nodeName=payload.nodeName;this._localName=payload.localName;this._nodeValue=payload.nodeValue;this._pseudoType=payload.pseudoType;this._shadowRootType=payload.shadowRootType;this._frameOwnerFrameId=payload.frameId||null;this._xmlVersion=payload.xmlVersion;this._isSVGNode=!!payload.isSVG;this._shadowRoots=[];this._attributes=[];this._attributesMap={};if(payload.attributes)
this._setAttributesPayload(payload.attributes);this._markers=new Map();this._subtreeMarkerCount=0;this._childNodeCount=payload.childNodeCount||0;this._children=null;this.nextSibling=null;this.previousSibling=null;this.firstChild=null;this.lastChild=null;this.parentNode=null;if(payload.shadowRoots){for(let i=0;i<payload.shadowRoots.length;++i){const root=payload.shadowRoots[i];const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,root);this._shadowRoots.push(node);node.parentNode=this;}}
if(payload.templateContent){this._templateContent=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.templateContent);this._templateContent.parentNode=this;this._children=[];}
if(payload.contentDocument){this._contentDocument=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.contentDocument);this._contentDocument.parentNode=this;this._children=[];}else if(payload.nodeName==='IFRAME'&&payload.frameId&&Runtime.experiments.isEnabled('oopifInlineDOM')){const childTarget=SDK.targetManager.targetById(payload.frameId);const childModel=childTarget?childTarget.model(SDK.DOMModel):null;if(childModel)
this._childDocumentPromiseForTesting=childModel.requestDocument();this._children=[];}
if(payload.importedDocument){this._importedDocument=SDK.DOMNode.create(this._domModel,this.ownerDocument,true,payload.importedDocument);this._importedDocument.parentNode=this;this._children=[];}
if(payload.distributedNodes)
this._setDistributedNodePayloads(payload.distributedNodes);if(payload.children)
this._setChildrenPayload(payload.children);this._setPseudoElements(payload.pseudoElements);if(this._nodeType===Node.ELEMENT_NODE){if(this.ownerDocument&&!this.ownerDocument.documentElement&&this._nodeName==='HTML')
this.ownerDocument.documentElement=this;if(this.ownerDocument&&!this.ownerDocument.body&&this._nodeName==='BODY')
this.ownerDocument.body=this;}else if(this._nodeType===Node.DOCUMENT_TYPE_NODE){this.publicId=payload.publicId;this.systemId=payload.systemId;this.internalSubset=payload.internalSubset;}else if(this._nodeType===Node.ATTRIBUTE_NODE){this.name=payload.name;this.value=payload.value;}}
isSVGNode(){return this._isSVGNode;}
domModel(){return this._domModel;}
backendNodeId(){return this._backendNodeId;}
children(){return this._children?this._children.slice():null;}
hasAttributes(){return this._attributes.length>0;}
childNodeCount(){return this._childNodeCount;}
hasShadowRoots(){return!!this._shadowRoots.length;}
shadowRoots(){return this._shadowRoots.slice();}
templateContent(){return this._templateContent||null;}
contentDocument(){return this._contentDocument||null;}
isIframe(){return this._nodeName==='IFRAME';}
importedDocument(){return this._importedDocument||null;}
nodeType(){return this._nodeType;}
nodeName(){return this._nodeName;}
pseudoType(){return this._pseudoType;}
hasPseudoElements(){return this._pseudoElements.size>0;}
pseudoElements(){return this._pseudoElements;}
beforePseudoElement(){if(!this._pseudoElements)
return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.Before);}
afterPseudoElement(){if(!this._pseudoElements)
return null;return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.After);}
isInsertionPoint(){return!this.isXMLNode()&&(this._nodeName==='SHADOW'||this._nodeName==='CONTENT'||this._nodeName==='SLOT');}
distributedNodes(){return this._distributedNodes||[];}
isInShadowTree(){return this._isInShadowTree;}
ancestorShadowHost(){const ancestorShadowRoot=this.ancestorShadowRoot();return ancestorShadowRoot?ancestorShadowRoot.parentNode:null;}
ancestorShadowRoot(){if(!this._isInShadowTree)
return null;let current=this;while(current&&!current.isShadowRoot())
current=current.parentNode;return current;}
ancestorUserAgentShadowRoot(){const ancestorShadowRoot=this.ancestorShadowRoot();if(!ancestorShadowRoot)
return null;return ancestorShadowRoot.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?ancestorShadowRoot:null;}
isShadowRoot(){return!!this._shadowRootType;}
shadowRootType(){return this._shadowRootType||null;}
nodeNameInCorrectCase(){const shadowRootType=this.shadowRootType();if(shadowRootType)
return'#shadow-root ('+shadowRootType+')';if(!this.localName())
return this.nodeName();if(this.localName().length!==this.nodeName().length)
return this.nodeName();return this.localName();}
setNodeName(name,callback){this._agent.invoke_setNodeName({nodeId:this.id,name}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,this._domModel.nodeForId(response.nodeId));});}
localName(){return this._localName;}
nodeValue(){return this._nodeValue;}
setNodeValue(value,callback){this._agent.invoke_setNodeValue({nodeId:this.id,value}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
getAttribute(name){const attr=this._attributesMap[name];return attr?attr.value:undefined;}
setAttribute(name,text,callback){this._agent.invoke_setAttributesAsText({nodeId:this.id,text,name}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
setAttributeValue(name,value,callback){this._agent.invoke_setAttributeValue({nodeId:this.id,name,value}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
setAttributeValuePromise(name,value){return new Promise(fulfill=>this.setAttributeValue(name,value,fulfill));}
attributes(){return this._attributes;}
async removeAttribute(name){const response=await this._agent.invoke_removeAttribute({nodeId:this.id,name});if(response[Protocol.Error])
return;delete this._attributesMap[name];const index=this._attributes.findIndex(attr=>attr.name===name);if(index!==-1)
this._attributes.splice(index,1);this._domModel.markUndoableState();}
getChildNodes(callback){if(this._children){callback(this.children());return;}
this._agent.invoke_requestChildNodes({nodeId:this.id}).then(response=>{callback(response[Protocol.Error]?null:this.children());});}
async getSubtree(depth,pierce){const response=await this._agent.invoke_requestChildNodes({nodeId:this.id,depth:depth,pierce:pierce});return response[Protocol.Error]?null:this._children;}
getOuterHTML(){return this._agent.getOuterHTML(this.id);}
setOuterHTML(html,callback){this._agent.invoke_setOuterHTML({nodeId:this.id,outerHTML:html}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
removeNode(callback){this._agent.invoke_removeNode({nodeId:this.id}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null);});}
async copyNode(){const text=await this._agent.getOuterHTML(this.id);if(text!==null)
InspectorFrontendHost.copyText(text);return text;}
path(){function canPush(node){return node&&('index'in node||(node.isShadowRoot()&&node.parentNode))&&node._nodeName.length;}
const path=[];let node=this;while(canPush(node)){const index=typeof node.index==='number'?node.index:(node.shadowRootType()===SDK.DOMNode.ShadowRootTypes.UserAgent?'u':'a');path.push([index,node._nodeName]);node=node.parentNode;}
path.reverse();return path.join(',');}
isAncestor(node){if(!node)
return false;let currentNode=node.parentNode;while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNode;}
return false;}
isDescendant(descendant){return descendant!==null&&descendant.isAncestor(this);}
frameId(){let node=this.parentNode||this;while(!node._frameOwnerFrameId&&node.parentNode)
node=node.parentNode;return node._frameOwnerFrameId;}
_setAttributesPayload(attrs){let attributesChanged=!this._attributes||attrs.length!==this._attributes.length*2;const oldAttributesMap=this._attributesMap||{};this._attributes=[];this._attributesMap={};for(let i=0;i<attrs.length;i+=2){const name=attrs[i];const value=attrs[i+1];this._addAttribute(name,value);if(attributesChanged)
continue;if(!oldAttributesMap[name]||oldAttributesMap[name].value!==value)
attributesChanged=true;}
return attributesChanged;}
_insertChild(prev,payload){const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.splice(this._children.indexOf(prev)+1,0,node);this._renumber();return node;}
_removeChild(node){if(node.pseudoType()){this._pseudoElements.delete(node.pseudoType());}else{const shadowRootIndex=this._shadowRoots.indexOf(node);if(shadowRootIndex!==-1){this._shadowRoots.splice(shadowRootIndex,1);}else{console.assert(this._children.indexOf(node)!==-1);this._children.splice(this._children.indexOf(node),1);}}
node.parentNode=null;this._subtreeMarkerCount-=node._subtreeMarkerCount;if(node._subtreeMarkerCount)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,this);this._renumber();}
_setChildrenPayload(payloads){this._children=[];for(let i=0;i<payloads.length;++i){const payload=payloads[i];const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payload);this._children.push(node);}
this._renumber();}
_setPseudoElements(payloads){this._pseudoElements=new Map();if(!payloads)
return;for(let i=0;i<payloads.length;++i){const node=SDK.DOMNode.create(this._domModel,this.ownerDocument,this._isInShadowTree,payloads[i]);node.parentNode=this;this._pseudoElements.set(node.pseudoType(),node);}}
_setDistributedNodePayloads(payloads){this._distributedNodes=[];for(const payload of payloads){this._distributedNodes.push(new SDK.DOMNodeShortcut(this._domModel.target(),payload.backendNodeId,payload.nodeType,payload.nodeName));}}
_renumber(){this._childNodeCount=this._children.length;if(this._childNodeCount===0){this.firstChild=null;this.lastChild=null;return;}
this.firstChild=this._children[0];this.lastChild=this._children[this._childNodeCount-1];for(let i=0;i<this._childNodeCount;++i){const child=this._children[i];child.index=i;child.nextSibling=i+1<this._childNodeCount?this._children[i+1]:null;child.previousSibling=i-1>=0?this._children[i-1]:null;child.parentNode=this;}}
_addAttribute(name,value){const attr={name:name,value:value,_node:this};this._attributesMap[name]=attr;this._attributes.push(attr);}
_setAttribute(name,value){const attr=this._attributesMap[name];if(attr)
attr.value=value;else
this._addAttribute(name,value);}
_removeAttribute(name){const attr=this._attributesMap[name];if(attr){this._attributes.remove(attr);delete this._attributesMap[name];}}
copyTo(targetNode,anchorNode,callback){this._agent.invoke_copyTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,response.nodeId);});}
moveTo(targetNode,anchorNode,callback){this._agent.invoke_moveTo({nodeId:this.id,targetNodeId:targetNode.id,insertBeforeNodeId:anchorNode?anchorNode.id:undefined}).then(response=>{if(!response[Protocol.Error])
this._domModel.markUndoableState();if(callback)
callback(response[Protocol.Error]||null,this._domModel.nodeForId(response.nodeId));});}
isXMLNode(){return!!this._xmlVersion;}
setMarker(name,value){if(value===null){if(!this._markers.has(name))
return;this._markers.delete(name);for(let node=this;node;node=node.parentNode)
--node._subtreeMarkerCount;for(let node=this;node;node=node.parentNode)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);return;}
if(this.parentNode&&!this._markers.has(name)){for(let node=this;node;node=node.parentNode)
++node._subtreeMarkerCount;}
this._markers.set(name,value);for(let node=this;node;node=node.parentNode)
this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged,node);}
marker(name){return this._markers.get(name)||null;}
traverseMarkers(visitor){function traverse(node){if(!node._subtreeMarkerCount)
return;for(const marker of node._markers.keys())
visitor(node,marker);if(!node._children)
return;for(const child of node._children)
traverse(child);}
traverse(this);}
resolveURL(url){if(!url)
return url;for(let frameOwnerCandidate=this;frameOwnerCandidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandidate.baseURL)
return Common.ParsedURL.completeURL(frameOwnerCandidate.baseURL,url);}
return null;}
highlight(mode,objectId){this._domModel.overlayModel().highlightDOMNode(this.id,mode,undefined,objectId);}
highlightForTwoSeconds(){this._domModel.overlayModel().highlightDOMNodeForTwoSeconds(this.id);}
async resolveToObject(objectGroup){const object=await this._agent.resolveNode(this.id,undefined,objectGroup);return object&&this._domModel._runtimeModel.createRemoteObject(object);}
boxModel(){return this._agent.getBoxModel(this.id);}
setAsInspectedNode(){let node=this;while(true){let ancestor=node.ancestorUserAgentShadowRoot();if(!ancestor)
break;ancestor=node.ancestorShadowHost();if(!ancestor)
break;node=ancestor;}
this._agent.setInspectedNode(node.id);}
enclosingElementOrSelf(){let node=this;if(node&&node.nodeType()===Node.TEXT_NODE&&node.parentNode)
node=node.parentNode;if(node&&node.nodeType()!==Node.ELEMENT_NODE)
node=null;return node;}
async scrollIntoView(){const node=this.enclosingElementOrSelf();const object=await node.resolveToObject();if(!object)
return;object.callFunction(scrollIntoView);object.release();node.highlightForTwoSeconds();function scrollIntoView(){this.scrollIntoViewIfNeeded(true);}}
async focus(){const node=this.enclosingElementOrSelf();const object=await node.resolveToObject();if(!object)
return;await object.callFunctionPromise(focusInPage);object.release();node.highlightForTwoSeconds();this._domModel.target().pageAgent().bringToFront();function focusInPage(){this.focus();}}
simpleSelector(){const lowerCaseName=this.localName()||this.nodeName().toLowerCase();if(this.nodeType()!==Node.ELEMENT_NODE)
return lowerCaseName;if(lowerCaseName==='input'&&this.getAttribute('type')&&!this.getAttribute('id')&&!this.getAttribute('class'))
return lowerCaseName+'[type="'+this.getAttribute('type')+'"]';if(this.getAttribute('id'))
return lowerCaseName+'#'+this.getAttribute('id');if(this.getAttribute('class')){return(lowerCaseName==='div'?'':lowerCaseName)+'.'+
this.getAttribute('class').trim().replace(/\s+/g,'.');}
return lowerCaseName;}};SDK.DOMNode.PseudoElementNames={Before:'before',After:'after'};SDK.DOMNode.ShadowRootTypes={UserAgent:'user-agent',Open:'open',Closed:'closed'};SDK.DOMNode.Attribute;SDK.DeferredDOMNode=class{constructor(target,backendNodeId){this._domModel=(target.model(SDK.DOMModel));this._backendNodeId=backendNodeId;}
resolve(callback){this.resolvePromise().then(callback);}
async resolvePromise(){const nodeIds=await this._domModel.pushNodesByBackendIdsToFrontend(new Set([this._backendNodeId]));return nodeIds&&nodeIds.get(this._backendNodeId)||null;}
backendNodeId(){return this._backendNodeId;}
domModel(){return this._domModel;}
highlight(){this._domModel.overlayModel().highlightDOMNode(undefined,undefined,this._backendNodeId);}};SDK.DOMNodeShortcut=class{constructor(target,backendNodeId,nodeType,nodeName){this.nodeType=nodeType;this.nodeName=nodeName;this.deferredNode=new SDK.DeferredDOMNode(target,backendNodeId);}};SDK.DOMDocument=class extends SDK.DOMNode{constructor(domModel,payload){super(domModel);this._init(this,false,payload);this.documentURL=payload.documentURL||'';this.baseURL=payload.baseURL||'';}};SDK.DOMModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.domAgent();this._idToDOMNode={};this._document=null;this._attributeLoadNodeIds=new Set();target.registerDOMDispatcher(new SDK.DOMDispatcher(this));this._runtimeModel=(target.model(SDK.RuntimeModel));if(!target.suspended())
this._agent.enable();}
runtimeModel(){return this._runtimeModel;}
cssModel(){return(this.target().model(SDK.CSSModel));}
overlayModel(){return(this.target().model(SDK.OverlayModel));}
static cancelSearch(){for(const domModel of SDK.targetManager.models(SDK.DOMModel))
domModel._cancelSearch();}
_scheduleMutationEvent(node){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated))
return;this._lastMutationId=(this._lastMutationId||0)+1;Promise.resolve().then(callObserve.bind(this,node,this._lastMutationId));function callObserve(node,mutationId){if(!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)||this._lastMutationId!==mutationId)
return;this.dispatchEventToListeners(SDK.DOMModel.Events.DOMMutated,node);}}
requestDocument(){if(this._document)
return Promise.resolve(this._document);if(!this._pendingDocumentRequestPromise)
this._pendingDocumentRequestPromise=this._requestDocument();return this._pendingDocumentRequestPromise;}
async _requestDocument(){const documentPayload=await this._agent.getDocument();delete this._pendingDocumentRequestPromise;if(documentPayload)
this._setDocument(documentPayload);if(!this._document){console.error('No document');return null;}
const parentModel=this.parentModel();if(parentModel&&!this._frameOwnerNode){await parentModel.requestDocument();const response=await parentModel._agent.invoke_getFrameOwner({frameId:this.target().id()});if(!response[Protocol.Error])
this._frameOwnerNode=parentModel.nodeForId(response.nodeId);}
if(this._frameOwnerNode){const oldDocument=this._frameOwnerNode._contentDocument;this._frameOwnerNode._contentDocument=this._document;this._frameOwnerNode._children=[];if(this._document){this._document.parentNode=this._frameOwnerNode;this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,this._document);}else if(oldDocument){this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:oldDocument,parent:this._frameOwnerNode});}}
return this._document;}
existingDocument(){return this._document;}
async pushNodeToFrontend(objectId){await this.requestDocument();const nodeId=await this._agent.requestNode(objectId);return nodeId?this.nodeForId(nodeId):null;}
pushNodeByPathToFrontend(path){return this.requestDocument().then(()=>this._agent.pushNodeByPathToFrontend(path));}
async pushNodesByBackendIdsToFrontend(backendNodeIds){await this.requestDocument();const backendNodeIdsArray=backendNodeIds.valuesArray();const nodeIds=await this._agent.pushNodesByBackendIdsToFrontend(backendNodeIdsArray);if(!nodeIds)
return null;const map=new Map();for(let i=0;i<nodeIds.length;++i){if(nodeIds[i])
map.set(backendNodeIdsArray[i],this.nodeForId(nodeIds[i]));}
return map;}
_wrapClientCallback(callback){function wrapper(error,result){callback(error?null:result||null);}
return wrapper;}
_attributeModified(nodeId,name,value){const node=this._idToDOMNode[nodeId];if(!node)
return;node._setAttribute(name,value);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:name});this._scheduleMutationEvent(node);}
_attributeRemoved(nodeId,name){const node=this._idToDOMNode[nodeId];if(!node)
return;node._removeAttribute(name);this.dispatchEventToListeners(SDK.DOMModel.Events.AttrRemoved,{node:node,name:name});this._scheduleMutationEvent(node);}
_inlineStyleInvalidated(nodeIds){this._attributeLoadNodeIds.addAll(nodeIds);if(!this._loadNodeAttributesTimeout)
this._loadNodeAttributesTimeout=setTimeout(this._loadNodeAttributes.bind(this),20);}
_loadNodeAttributes(){delete this._loadNodeAttributesTimeout;for(const nodeId of this._attributeLoadNodeIds){this._agent.getAttributes(nodeId).then(attributes=>{if(!attributes){return;}
const node=this._idToDOMNode[nodeId];if(!node)
return;if(node._setAttributesPayload(attributes)){this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified,{node:node,name:'style'});this._scheduleMutationEvent(node);}});}
this._attributeLoadNodeIds.clear();}
_characterDataModified(nodeId,newValue){const node=this._idToDOMNode[nodeId];node._nodeValue=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.CharacterDataModified,node);this._scheduleMutationEvent(node);}
nodeForId(nodeId){return this._idToDOMNode[nodeId]||null;}
_documentUpdated(){const documentWasRequested=this._document||this._pendingDocumentRequestPromise;this._setDocument(null);if(this.parentModel()&&documentWasRequested)
this.requestDocument();}
_setDocument(payload){this._idToDOMNode={};if(payload&&'nodeId'in payload)
this._document=new SDK.DOMDocument(this,payload);else
this._document=null;SDK.domModelUndoStack._dispose(this);if(!this.parentModel())
this.dispatchEventToListeners(SDK.DOMModel.Events.DocumentUpdated,this);}
_setDetachedRoot(payload){if(payload.nodeName==='#document')
new SDK.DOMDocument(this,payload);else
SDK.DOMNode.create(this,null,false,payload);}
_setChildNodes(parentId,payloads){if(!parentId&&payloads.length){this._setDetachedRoot(payloads[0]);return;}
const parent=this._idToDOMNode[parentId];parent._setChildrenPayload(payloads);}
_childNodeCountUpdated(nodeId,newValue){const node=this._idToDOMNode[nodeId];node._childNodeCount=newValue;this.dispatchEventToListeners(SDK.DOMModel.Events.ChildNodeCountUpdated,node);this._scheduleMutationEvent(node);}
_childNodeInserted(parentId,prevId,payload){const parent=this._idToDOMNode[parentId];const prev=this._idToDOMNode[prevId];const node=parent._insertChild(prev,payload);this._idToDOMNode[node.id]=node;this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_childNodeRemoved(parentId,nodeId){const parent=this._idToDOMNode[parentId];const node=this._idToDOMNode[nodeId];parent._removeChild(node);this._unbind(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:node,parent:parent});this._scheduleMutationEvent(node);}
_shadowRootPushed(hostId,root){const host=this._idToDOMNode[hostId];if(!host)
return;const node=SDK.DOMNode.create(this,host.ownerDocument,true,root);node.parentNode=host;this._idToDOMNode[node.id]=node;host._shadowRoots.unshift(node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_shadowRootPopped(hostId,rootId){const host=this._idToDOMNode[hostId];if(!host)
return;const root=this._idToDOMNode[rootId];if(!root)
return;host._removeChild(root);this._unbind(root);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:root,parent:host});this._scheduleMutationEvent(root);}
_pseudoElementAdded(parentId,pseudoElement){const parent=this._idToDOMNode[parentId];if(!parent)
return;const node=SDK.DOMNode.create(this,parent.ownerDocument,false,pseudoElement);node.parentNode=parent;this._idToDOMNode[node.id]=node;console.assert(!parent._pseudoElements.get(node.pseudoType()));parent._pseudoElements.set(node.pseudoType(),node);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeInserted,node);this._scheduleMutationEvent(node);}
_pseudoElementRemoved(parentId,pseudoElementId){const parent=this._idToDOMNode[parentId];if(!parent)
return;const pseudoElement=this._idToDOMNode[pseudoElementId];if(!pseudoElement)
return;parent._removeChild(pseudoElement);this._unbind(pseudoElement);this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved,{node:pseudoElement,parent:parent});this._scheduleMutationEvent(pseudoElement);}
_distributedNodesUpdated(insertionPointId,distributedNodes){const insertionPoint=this._idToDOMNode[insertionPointId];if(!insertionPoint)
return;insertionPoint._setDistributedNodePayloads(distributedNodes);this.dispatchEventToListeners(SDK.DOMModel.Events.DistributedNodesChanged,insertionPoint);this._scheduleMutationEvent(insertionPoint);}
_unbind(node){delete this._idToDOMNode[node.id];for(let i=0;node._children&&i<node._children.length;++i)
this._unbind(node._children[i]);for(let i=0;i<node._shadowRoots.length;++i)
this._unbind(node._shadowRoots[i]);const pseudoElements=node.pseudoElements();for(const value of pseudoElements.values())
this._unbind(value);if(node._templateContent)
this._unbind(node._templateContent);}
async performSearch(query,includeUserAgentShadowDOM){const response=await this._agent.invoke_performSearch({query,includeUserAgentShadowDOM});if(!response[Protocol.Error])
this._searchId=response.searchId;return response[Protocol.Error]?0:response.resultCount;}
async searchResult(index){if(!this._searchId)
return null;const nodeIds=await this._agent.getSearchResults(this._searchId,index,index+1);return nodeIds&&nodeIds.length===1?this.nodeForId(nodeIds[0]):null;}
_cancelSearch(){if(!this._searchId)
return;this._agent.discardSearchResults(this._searchId);delete this._searchId;}
classNamesPromise(nodeId){return this._agent.collectClassNamesFromSubtree(nodeId).then(classNames=>classNames||[]);}
querySelector(nodeId,selectors){return this._agent.querySelector(nodeId,selectors);}
querySelectorAll(nodeId,selectors){return this._agent.querySelectorAll(nodeId,selectors);}
markUndoableState(minorChange){SDK.domModelUndoStack._markUndoableState(this,minorChange||false);}
nodeForLocation(x,y,includeUserAgentShadowDOM){return this._agent.getNodeForLocation(x,y,includeUserAgentShadowDOM).then(nodeId=>nodeId?this.nodeForId(nodeId):null);}
pushObjectAsNodeToFrontend(object){return object.isNode()?this.pushNodeToFrontend((object.objectId)):Promise.resolve(null);}
suspendModel(){return this._agent.disable().then(()=>this._setDocument(null));}
resumeModel(){return this._agent.enable();}
dispose(){SDK.domModelUndoStack._dispose(this);}
parentModel(){if(!Runtime.experiments.isEnabled('oopifInlineDOM'))
return null;const parentTarget=this.target().parentTarget();return parentTarget?parentTarget.model(SDK.DOMModel):null;}};SDK.SDKModel.register(SDK.DOMModel,SDK.Target.Capability.DOM,true);SDK.DOMModel.Events={AttrModified:Symbol('AttrModified'),AttrRemoved:Symbol('AttrRemoved'),CharacterDataModified:Symbol('CharacterDataModified'),DOMMutated:Symbol('DOMMutated'),NodeInserted:Symbol('NodeInserted'),NodeRemoved:Symbol('NodeRemoved'),DocumentUpdated:Symbol('DocumentUpdated'),ChildNodeCountUpdated:Symbol('ChildNodeCountUpdated'),DistributedNodesChanged:Symbol('DistributedNodesChanged'),MarkersChanged:Symbol('MarkersChanged')};SDK.DOMDispatcher=class{constructor(domModel){this._domModel=domModel;}
documentUpdated(){this._domModel._documentUpdated();}
attributeModified(nodeId,name,value){this._domModel._attributeModified(nodeId,name,value);}
attributeRemoved(nodeId,name){this._domModel._attributeRemoved(nodeId,name);}
inlineStyleInvalidated(nodeIds){this._domModel._inlineStyleInvalidated(nodeIds);}
characterDataModified(nodeId,characterData){this._domModel._characterDataModified(nodeId,characterData);}
setChildNodes(parentId,payloads){this._domModel._setChildNodes(parentId,payloads);}
childNodeCountUpdated(nodeId,childNodeCount){this._domModel._childNodeCountUpdated(nodeId,childNodeCount);}
childNodeInserted(parentNodeId,previousNodeId,payload){this._domModel._childNodeInserted(parentNodeId,previousNodeId,payload);}
childNodeRemoved(parentNodeId,nodeId){this._domModel._childNodeRemoved(parentNodeId,nodeId);}
shadowRootPushed(hostId,root){this._domModel._shadowRootPushed(hostId,root);}
shadowRootPopped(hostId,rootId){this._domModel._shadowRootPopped(hostId,rootId);}
pseudoElementAdded(parentId,pseudoElement){this._domModel._pseudoElementAdded(parentId,pseudoElement);}
pseudoElementRemoved(parentId,pseudoElementId){this._domModel._pseudoElementRemoved(parentId,pseudoElementId);}
distributedNodesUpdated(insertionPointId,distributedNodes){this._domModel._distributedNodesUpdated(insertionPointId,distributedNodes);}};SDK.DOMModelUndoStack=class{constructor(){this._stack=[];this._index=0;this._lastModelWithMinorChange=null;}
_markUndoableState(model,minorChange){if(this._lastModelWithMinorChange&&model!==this._lastModelWithMinorChange){this._lastModelWithMinorChange.markUndoableState();this._lastModelWithMinorChange=null;}
if(minorChange&&this._lastModelWithMinorChange===model)
return;this._stack=this._stack.slice(0,this._index);this._stack.push(model);this._index=this._stack.length;if(minorChange){this._lastModelWithMinorChange=model;}else{model._agent.markUndoableState();this._lastModelWithMinorChange=null;}}
undo(){if(this._index===0)
return Promise.resolve();--this._index;this._lastModelWithMinorChange=null;return this._stack[this._index]._agent.undo();}
redo(){if(this._index>=this._stack.length)
return Promise.resolve();++this._index;this._lastModelWithMinorChange=null;return this._stack[this._index-1]._agent.redo();}
_dispose(model){let shift=0;for(let i=0;i<this._index;++i){if(this._stack[i]===model)
++shift;}
this._stack.remove(model);this._index-=shift;if(this._lastModelWithMinorChange===model)
this._lastModelWithMinorChange=null;}};SDK.domModelUndoStack=new SDK.DOMModelUndoStack();;SDK.DebuggerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerDebuggerDispatcher(new SDK.DebuggerDispatcher(this));this._agent=target.debuggerAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));this._sourceMapManager=new SDK.SourceMapManager(target);this._sourceMapIdToScript=new Map();this._debuggerPausedDetails=null;this._scripts=new Map();this._scriptsBySourceURL=new Map();this._discardableScripts=[];this._breakpointResolvedEventTarget=new Common.Object();this._isPausing=false;Common.moduleSetting('pauseOnExceptionEnabled').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').addChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').addChangeListener(this._asyncStackTracesStateChanged,this);Common.moduleSetting('breakpointsActive').addChangeListener(this._breakpointsActiveChanged,this);if(!target.suspended())
this._enableDebugger();this._stringMap=new Map();this._sourceMapManager.setEnabled(Common.moduleSetting('jsSourceMapsEnabled').get());Common.moduleSetting('jsSourceMapsEnabled').addChangeListener(event=>this._sourceMapManager.setEnabled((event.data)));}
static _sourceMapId(executionContextId,sourceURL,sourceMapURL){if(!sourceMapURL)
return null;return executionContextId+':'+sourceURL+':'+sourceMapURL;}
sourceMapManager(){return this._sourceMapManager;}
runtimeModel(){return this._runtimeModel;}
debuggerEnabled(){return!!this._debuggerEnabled;}
_enableDebugger(){if(this._debuggerEnabled)
return Promise.resolve();this._debuggerEnabled=true;const enablePromise=this._agent.enable();enablePromise.then(this._registerDebugger.bind(this));this._pauseOnExceptionStateChanged();this._asyncStackTracesStateChanged();if(!Common.moduleSetting('breakpointsActive').get())
this._breakpointsActiveChanged();if(SDK.DebuggerModel._scheduledPauseOnAsyncCall)
this._pauseOnAsyncCall(SDK.DebuggerModel._scheduledPauseOnAsyncCall);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasEnabled,this);return enablePromise;}
_registerDebugger(debuggerId){if(!debuggerId)
return;SDK.DebuggerModel._debuggerIdToModel.set(debuggerId,this);this._debuggerId=debuggerId;}
static modelForDebuggerId(debuggerId){return SDK.DebuggerModel._debuggerIdToModel.get(debuggerId)||null;}
_disableDebugger(){if(!this._debuggerEnabled)
return Promise.resolve();this._debuggerEnabled=false;const disablePromise=this._agent.disable();this._isPausing=false;this._asyncStackTracesStateChanged();this.globalObjectCleared();this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasDisabled);SDK.DebuggerModel._debuggerIdToModel.delete(this._debuggerId);return disablePromise;}
_skipAllPauses(skip){if(this._skipAllPausesTimeout){clearTimeout(this._skipAllPausesTimeout);delete this._skipAllPausesTimeout;}
this._agent.setSkipAllPauses(skip);}
skipAllPausesUntilReloadOrTimeout(timeout){if(this._skipAllPausesTimeout)
clearTimeout(this._skipAllPausesTimeout);this._agent.setSkipAllPauses(true);this._skipAllPausesTimeout=setTimeout(this._skipAllPauses.bind(this,false),timeout);}
_pauseOnExceptionStateChanged(){let state;if(!Common.moduleSetting('pauseOnExceptionEnabled').get())
state=SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions;else if(Common.moduleSetting('pauseOnCaughtException').get())
state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions;else
state=SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions;this._agent.setPauseOnExceptions(state);}
_asyncStackTracesStateChanged(){const maxAsyncStackChainDepth=32;const enabled=!Common.moduleSetting('disableAsyncStackTraces').get()&&this._debuggerEnabled;this._agent.setAsyncCallStackDepth(enabled?maxAsyncStackChainDepth:0);}
_breakpointsActiveChanged(){this._agent.setBreakpointsActive(Common.moduleSetting('breakpointsActive').get());}
stepInto(){this._agent.stepInto();}
stepOver(){this._agent.stepOver();}
stepOut(){this._agent.stepOut();}
scheduleStepIntoAsync(){this._agent.invoke_stepInto({breakOnAsyncCall:true});}
resume(){this._agent.resume();this._isPausing=false;}
pause(){this._isPausing=true;this._skipAllPauses(false);this._agent.pause();}
_pauseOnAsyncCall(parentStackTraceId){return this._agent.invoke_pauseOnAsyncCall({parentStackTraceId:parentStackTraceId});}
async setBreakpointByURL(url,lineNumber,columnNumber,condition){if(this.target().isNodeJS())
url=Common.ParsedURL.urlToPlatformPath(url,Host.isWin());let minColumnNumber=0;const scripts=this._scriptsBySourceURL.get(url)||[];for(let i=0,l=scripts.length;i<l;++i){const script=scripts[i];if(lineNumber===script.lineOffset)
minColumnNumber=minColumnNumber?Math.min(minColumnNumber,script.columnOffset):script.columnOffset;}
columnNumber=Math.max(columnNumber,minColumnNumber);const response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,url:url,columnNumber:columnNumber,condition:condition});if(response[Protocol.Error])
return{locations:[],breakpointId:null};let locations;if(response.locations)
locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};}
async setBreakpointInAnonymousScript(scriptId,scriptHash,lineNumber,columnNumber,condition){const response=await this._agent.invoke_setBreakpointByUrl({lineNumber:lineNumber,scriptHash:scriptHash,columnNumber:columnNumber,condition:condition});const error=response[Protocol.Error];if(error){if(error!=='Either url or urlRegex must be specified.')
return{locations:[],breakpointId:null};return this._setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition);}
let locations;if(response.locations)
locations=response.locations.map(payload=>SDK.DebuggerModel.Location.fromPayload(this,payload));return{locations:locations,breakpointId:response.breakpointId};}
async _setBreakpointBySourceId(scriptId,lineNumber,columnNumber,condition){const response=await this._agent.invoke_setBreakpoint({location:{scriptId:scriptId,lineNumber:lineNumber,columnNumber:columnNumber},condition:condition});if(response[Protocol.Error])
return{breakpointId:null,locations:[]};let actualLocation=[];if(response.actualLocation)
actualLocation=[SDK.DebuggerModel.Location.fromPayload(this,response.actualLocation)];return{locations:actualLocation,breakpointId:response.breakpointId};}
async removeBreakpoint(breakpointId){const response=await this._agent.invoke_removeBreakpoint({breakpointId});if(response[Protocol.Error])
console.error('Failed to remove breakpoint: '+response[Protocol.Error]);}
async getPossibleBreakpoints(startLocation,endLocation,restrictToFunction){const response=await this._agent.invoke_getPossibleBreakpoints({start:startLocation.payload(),end:endLocation?endLocation.payload():undefined,restrictToFunction:restrictToFunction});if(response[Protocol.Error]||!response.locations)
return[];return response.locations.map(location=>SDK.DebuggerModel.BreakLocation.fromPayload(this,location));}
async fetchAsyncStackTrace(stackId){const response=await this._agent.invoke_getStackTrace({stackTraceId:stackId});return response[Protocol.Error]?null:response.stackTrace;}
_breakpointResolved(breakpointId,location){this._breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId,SDK.DebuggerModel.Location.fromPayload(this,location));}
globalObjectCleared(){this._setDebuggerPausedDetails(null);this._reset();this.dispatchEventToListeners(SDK.DebuggerModel.Events.GlobalObjectCleared,this);}
_reset(){for(const scriptWithSourceMap of this._sourceMapIdToScript.values())
this._sourceMapManager.detachSourceMap(scriptWithSourceMap);this._sourceMapIdToScript.clear();this._scripts.clear();this._scriptsBySourceURL.clear();this._stringMap.clear();this._discardableScripts=[];}
scripts(){return Array.from(this._scripts.values());}
scriptForId(scriptId){return this._scripts.get(scriptId)||null;}
scriptsForSourceURL(sourceURL){if(!sourceURL)
return[];return this._scriptsBySourceURL.get(sourceURL)||[];}
scriptsForExecutionContext(executionContext){const result=[];for(const script of this._scripts.values()){if(script.executionContextId===executionContext.id)
result.push(script);}
return result;}
setScriptSource(scriptId,newSource,callback){this._scripts.get(scriptId).editSource(newSource,this._didEditScriptSource.bind(this,scriptId,newSource,callback));}
_didEditScriptSource(scriptId,newSource,callback,error,exceptionDetails,callFrames,asyncStackTrace,asyncStackTraceId,needsStepIn){callback(error,exceptionDetails);if(needsStepIn){this.stepInto();return;}
if(!error&&callFrames&&callFrames.length){this._pausedScript(callFrames,this._debuggerPausedDetails.reason,this._debuggerPausedDetails.auxData,this._debuggerPausedDetails.breakpointIds,asyncStackTrace,asyncStackTraceId);}}
get callFrames(){return this._debuggerPausedDetails?this._debuggerPausedDetails.callFrames:null;}
debuggerPausedDetails(){return this._debuggerPausedDetails;}
_setDebuggerPausedDetails(debuggerPausedDetails){this._isPausing=false;this._debuggerPausedDetails=debuggerPausedDetails;if(this._debuggerPausedDetails){if(Runtime.experiments.isEnabled('emptySourceMapAutoStepping')&&this._beforePausedCallback){if(!this._beforePausedCallback.call(null,this._debuggerPausedDetails))
return false;}
this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerPaused,this);}
if(debuggerPausedDetails)
this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);else
this.setSelectedCallFrame(null);return true;}
setBeforePausedCallback(callback){this._beforePausedCallback=callback;}
async _pausedScript(callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId){if(asyncCallStackTraceId){SDK.DebuggerModel._scheduledPauseOnAsyncCall=asyncCallStackTraceId;const promises=[];for(const model of SDK.DebuggerModel._debuggerIdToModel.values())
promises.push(model._pauseOnAsyncCall(asyncCallStackTraceId));await Promise.all(promises);this.resume();return;}
const pausedDetails=new SDK.DebuggerPausedDetails(this,callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId);if(pausedDetails&&this._continueToLocationCallback){const callback=this._continueToLocationCallback;delete this._continueToLocationCallback;if(callback(pausedDetails))
return;}
if(!this._setDebuggerPausedDetails(pausedDetails))
this._agent.stepInto();SDK.DebuggerModel._scheduledPauseOnAsyncCall=null;}
_resumedScript(){this._setDebuggerPausedDetails(null);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerResumed,this);}
_parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURLComment,hasSyntaxError,length){let isContentScript=false;if(executionContextAuxData&&('isDefault'in executionContextAuxData))
isContentScript=!executionContextAuxData['isDefault'];if(this.target().isNodeJS()&&sourceURL&&!hasSourceURLComment){const nodeJSPath=sourceURL;sourceURL=Common.ParsedURL.platformPathToURL(nodeJSPath);sourceURL=this._internString(sourceURL);}else{sourceURL=this._internString(sourceURL);}
const script=new SDK.Script(this,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,this._internString(hash),isContentScript,isLiveEdit,sourceMapURL,hasSourceURLComment,length);this._registerScript(script);if(!hasSyntaxError)
this.dispatchEventToListeners(SDK.DebuggerModel.Events.ParsedScriptSource,script);else
this.dispatchEventToListeners(SDK.DebuggerModel.Events.FailedToParseScriptSource,script);const sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&!hasSyntaxError){const previousScript=this._sourceMapIdToScript.get(sourceMapId);if(previousScript)
this._sourceMapManager.detachSourceMap(previousScript);this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);}
const isDiscardable=hasSyntaxError&&script.isAnonymousScript();if(isDiscardable){this._discardableScripts.push(script);this._collectDiscardedScripts();}
return script;}
setSourceMapURL(script,newSourceMapURL){let sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(sourceMapId&&this._sourceMapIdToScript.get(sourceMapId)===script)
this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);script.sourceMapURL=newSourceMapURL;sourceMapId=SDK.DebuggerModel._sourceMapId(script.executionContextId,script.sourceURL,script.sourceMapURL);if(!sourceMapId)
return;this._sourceMapIdToScript.set(sourceMapId,script);this._sourceMapManager.attachSourceMap(script,script.sourceURL,script.sourceMapURL);}
executionContextDestroyed(executionContext){const sourceMapIds=Array.from(this._sourceMapIdToScript.keys());for(const sourceMapId of sourceMapIds){const script=this._sourceMapIdToScript.get(sourceMapId);if(script.executionContextId===executionContext.id){this._sourceMapIdToScript.delete(sourceMapId);this._sourceMapManager.detachSourceMap(script);}}}
_registerScript(script){this._scripts.set(script.scriptId,script);if(script.isAnonymousScript())
return;let scripts=this._scriptsBySourceURL.get(script.sourceURL);if(!scripts){scripts=[];this._scriptsBySourceURL.set(script.sourceURL,scripts);}
scripts.push(script);}
_unregisterScript(script){console.assert(script.isAnonymousScript());this._scripts.delete(script.scriptId);}
_collectDiscardedScripts(){if(this._discardableScripts.length<1000)
return;const scriptsToDiscard=this._discardableScripts.splice(0,100);for(const script of scriptsToDiscard){this._unregisterScript(script);this.dispatchEventToListeners(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,script);}}
createRawLocation(script,lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this,script.scriptId,lineNumber,columnNumber);}
createRawLocationByURL(sourceURL,lineNumber,columnNumber){let closestScript=null;const scripts=this._scriptsBySourceURL.get(sourceURL)||[];for(let i=0,l=scripts.length;i<l;++i){const script=scripts[i];if(!closestScript)
closestScript=script;if(script.lineOffset>lineNumber||(script.lineOffset===lineNumber&&script.columnOffset>columnNumber))
continue;if(script.endLine<lineNumber||(script.endLine===lineNumber&&script.endColumn<=columnNumber))
continue;closestScript=script;break;}
return closestScript?new SDK.DebuggerModel.Location(this,closestScript.scriptId,lineNumber,columnNumber):null;}
createRawLocationByScriptId(scriptId,lineNumber,columnNumber){const script=this.scriptForId(scriptId);return script?this.createRawLocation(script,lineNumber,columnNumber):null;}
createRawLocationsByStackTrace(stackTrace){const frames=[];while(stackTrace){for(const frame of stackTrace.callFrames)
frames.push(frame);stackTrace=stackTrace.parent;}
const rawLocations=[];for(const frame of frames){const rawLocation=this.createRawLocationByScriptId(frame.scriptId,frame.lineNumber,frame.columnNumber);if(rawLocation)
rawLocations.push(rawLocation);}
return rawLocations;}
isPaused(){return!!this.debuggerPausedDetails();}
isPausing(){return this._isPausing;}
setSelectedCallFrame(callFrame){if(this._selectedCallFrame===callFrame)
return;this._selectedCallFrame=callFrame;this.dispatchEventToListeners(SDK.DebuggerModel.Events.CallFrameSelected,this);}
selectedCallFrame(){return this._selectedCallFrame;}
evaluateOnSelectedCallFrame(options){return this.selectedCallFrame().evaluate(options);}
functionDetailsPromise(remoteObject){return remoteObject.getAllPropertiesPromise(false,false).then(buildDetails.bind(this));function buildDetails(response){if(!response)
return null;let location=null;if(response.internalProperties){for(const prop of response.internalProperties){if(prop.name==='[[FunctionLocation]]')
location=prop.value;}}
let functionName=null;if(response.properties){for(const prop of response.properties){if(prop.name==='name'&&prop.value&&prop.value.type==='string')
functionName=prop.value;if(prop.name==='displayName'&&prop.value&&prop.value.type==='string'){functionName=prop.value;break;}}}
let debuggerLocation=null;if(location){debuggerLocation=this.createRawLocationByScriptId(location.value.scriptId,location.value.lineNumber,location.value.columnNumber);}
return{location:debuggerLocation,functionName:functionName?functionName.value:''};}}
async setVariableValue(scopeNumber,variableName,newValue,callFrameId){const response=await this._agent.invoke_setVariableValue({scopeNumber,variableName,newValue,callFrameId});const error=response[Protocol.Error];if(error)
console.error(error);return error;}
addBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.addEventListener(breakpointId,listener,thisObject);}
removeBreakpointListener(breakpointId,listener,thisObject){this._breakpointResolvedEventTarget.removeEventListener(breakpointId,listener,thisObject);}
async setBlackboxPatterns(patterns){const response=await this._agent.invoke_setBlackboxPatterns({patterns});const error=response[Protocol.Error];if(error)
console.error(error);return!error;}
dispose(){this._sourceMapManager.dispose();SDK.DebuggerModel._debuggerIdToModel.delete(this._debuggerId);Common.moduleSetting('pauseOnExceptionEnabled').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('pauseOnCaughtException').removeChangeListener(this._pauseOnExceptionStateChanged,this);Common.moduleSetting('disableAsyncStackTraces').removeChangeListener(this._asyncStackTracesStateChanged,this);}
async suspendModel(){await this._disableDebugger();}
async resumeModel(){await this._enableDebugger();}
_internString(string){if(!this._stringMap.has(string))
this._stringMap.set(string,string);return this._stringMap.get(string);}};SDK.DebuggerModel._debuggerIdToModel=new Map();SDK.DebuggerModel._scheduledPauseOnAsyncCall=null;SDK.SDKModel.register(SDK.DebuggerModel,SDK.Target.Capability.JS,true);SDK.DebuggerModel.FunctionDetails;SDK.DebuggerModel.PauseOnExceptionsState={DontPauseOnExceptions:'none',PauseOnAllExceptions:'all',PauseOnUncaughtExceptions:'uncaught'};SDK.DebuggerModel.Events={DebuggerWasEnabled:Symbol('DebuggerWasEnabled'),DebuggerWasDisabled:Symbol('DebuggerWasDisabled'),DebuggerPaused:Symbol('DebuggerPaused'),DebuggerResumed:Symbol('DebuggerResumed'),ParsedScriptSource:Symbol('ParsedScriptSource'),FailedToParseScriptSource:Symbol('FailedToParseScriptSource'),DiscardedAnonymousScriptSource:Symbol('DiscardedAnonymousScriptSource'),GlobalObjectCleared:Symbol('GlobalObjectCleared'),CallFrameSelected:Symbol('CallFrameSelected'),ConsoleCommandEvaluatedInSelectedCallFrame:Symbol('ConsoleCommandEvaluatedInSelectedCallFrame')};SDK.DebuggerModel.BreakReason={DOM:'DOM',EventListener:'EventListener',XHR:'XHR',Exception:'exception',PromiseRejection:'promiseRejection',Assert:'assert',DebugCommand:'debugCommand',OOM:'OOM',Other:'other'};SDK.DebuggerModel.BreakLocationType={Return:'return',Call:'call',DebuggerStatement:'debuggerStatement'};SDK.DebuggerEventTypes={JavaScriptPause:0,JavaScriptBreakpoint:1,NativeBreakpoint:2};SDK.DebuggerModel.ContinueToLocationTargetCallFrames={Any:'any',Current:'current'};SDK.DebuggerModel.SetBreakpointResult;SDK.DebuggerDispatcher=class{constructor(debuggerModel){this._debuggerModel=debuggerModel;}
paused(callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId){this._debuggerModel._pausedScript(callFrames,reason,auxData,breakpointIds||[],asyncStackTrace,asyncStackTraceId,asyncCallStackTraceId);}
resumed(){this._debuggerModel._resumedScript();}
scriptParsed(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,isLiveEdit,sourceMapURL,hasSourceURL,isModule,length){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,!!isLiveEdit,sourceMapURL,!!hasSourceURL,false,length||0);}
scriptFailedToParse(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,sourceMapURL,hasSourceURL,isModule,length){this._debuggerModel._parsedScriptSource(scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,executionContextAuxData,false,sourceMapURL,!!hasSourceURL,true,length||0);}
breakpointResolved(breakpointId,location){this._debuggerModel._breakpointResolved(breakpointId,location);}};SDK.DebuggerModel.Location=class{constructor(debuggerModel,scriptId,lineNumber,columnNumber){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.lineNumber=lineNumber;this.columnNumber=columnNumber||0;}
static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.Location(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber);}
payload(){return{scriptId:this.scriptId,lineNumber:this.lineNumber,columnNumber:this.columnNumber};}
script(){return this.debuggerModel.scriptForId(this.scriptId);}
continueToLocation(pausedCallback){if(pausedCallback)
this.debuggerModel._continueToLocationCallback=this._paused.bind(this,pausedCallback);this.debuggerModel._agent.continueToLocation(this.payload(),SDK.DebuggerModel.ContinueToLocationTargetCallFrames.Current);}
_paused(pausedCallback,debuggerPausedDetails){const location=debuggerPausedDetails.callFrames[0].location();if(location.scriptId===this.scriptId&&location.lineNumber===this.lineNumber&&location.columnNumber===this.columnNumber){pausedCallback();return true;}
return false;}
id(){return this.debuggerModel.target().id()+':'+this.scriptId+':'+this.lineNumber+':'+this.columnNumber;}};SDK.DebuggerModel.BreakLocation=class extends SDK.DebuggerModel.Location{constructor(debuggerModel,scriptId,lineNumber,columnNumber,type){super(debuggerModel,scriptId,lineNumber,columnNumber);if(type)
this.type=type;}
static fromPayload(debuggerModel,payload){return new SDK.DebuggerModel.BreakLocation(debuggerModel,payload.scriptId,payload.lineNumber,payload.columnNumber,payload.type);}};SDK.DebuggerModel.CallFrame=class{constructor(debuggerModel,script,payload){this.debuggerModel=debuggerModel;this._script=script;this._payload=payload;this._location=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.location);this._scopeChain=[];this._localScope=null;for(let i=0;i<payload.scopeChain.length;++i){const scope=new SDK.DebuggerModel.Scope(this,i);this._scopeChain.push(scope);if(scope.type()===Protocol.Debugger.ScopeType.Local)
this._localScope=scope;}
if(payload.functionLocation)
this._functionLocation=SDK.DebuggerModel.Location.fromPayload(debuggerModel,payload.functionLocation);this._returnValue=payload.returnValue?this.debuggerModel._runtimeModel.createRemoteObject(payload.returnValue):null;}
static fromPayloadArray(debuggerModel,callFrames){const result=[];for(let i=0;i<callFrames.length;++i){const callFrame=callFrames[i];const script=debuggerModel.scriptForId(callFrame.location.scriptId);if(script)
result.push(new SDK.DebuggerModel.CallFrame(debuggerModel,script,callFrame));}
return result;}
get script(){return this._script;}
get id(){return this._payload.callFrameId;}
scopeChain(){return this._scopeChain;}
localScope(){return this._localScope;}
thisObject(){return this._payload.this?this.debuggerModel._runtimeModel.createRemoteObject(this._payload.this):null;}
returnValue(){return this._returnValue;}
async setReturnValue(expression){if(!this._returnValue)
return null;const evaluateResponse=await this.debuggerModel._agent.invoke_evaluateOnCallFrame({callFrameId:this.id,expression:expression,silent:true,objectGroup:'backtrace'});if(evaluateResponse[Protocol.Error]||evaluateResponse.exceptionDetails)
return null;const response=await this.debuggerModel._agent.invoke_setReturnValue({newValue:evaluateResponse.result});if(response[Protocol.Error])
return null;this._returnValue=this.debuggerModel._runtimeModel.createRemoteObject(evaluateResponse.result);return this._returnValue;}
get functionName(){return this._payload.functionName;}
location(){return this._location;}
functionLocation(){return this._functionLocation||null;}
async evaluate(options){const runtimeModel=this.debuggerModel.runtimeModel();if(options.throwOnSideEffect&&(runtimeModel.hasSideEffectSupport()===false||(runtimeModel.hasSideEffectSupport()===null&&!await runtimeModel.checkSideEffectSupport())))
return{error:'Side-effect checks not supported by backend.'};const response=await this.debuggerModel._agent.invoke_evaluateOnCallFrame({callFrameId:this.id,expression:options.expression,objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,returnByValue:options.returnByValue,generatePreview:options.generatePreview,throwOnSideEffect:options.throwOnSideEffect});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:runtimeModel.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async restart(){const response=await this.debuggerModel._agent.invoke_restartFrame({callFrameId:this._payload.callFrameId});if(!response[Protocol.Error])
this.debuggerModel.stepInto();}};SDK.DebuggerModel.Scope=class{constructor(callFrame,ordinal){this._callFrame=callFrame;this._payload=callFrame._payload.scopeChain[ordinal];this._type=this._payload.type;this._name=this._payload.name;this._ordinal=ordinal;this._startLocation=this._payload.startLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.startLocation):null;this._endLocation=this._payload.endLocation?SDK.DebuggerModel.Location.fromPayload(callFrame.debuggerModel,this._payload.endLocation):null;}
callFrame(){return this._callFrame;}
type(){return this._type;}
typeName(){switch(this._type){case Protocol.Debugger.ScopeType.Local:return Common.UIString('Local');case Protocol.Debugger.ScopeType.Closure:return Common.UIString('Closure');case Protocol.Debugger.ScopeType.Catch:return Common.UIString('Catch');case Protocol.Debugger.ScopeType.Block:return Common.UIString('Block');case Protocol.Debugger.ScopeType.Script:return Common.UIString('Script');case Protocol.Debugger.ScopeType.With:return Common.UIString('With Block');case Protocol.Debugger.ScopeType.Global:return Common.UIString('Global');case Protocol.Debugger.ScopeType.Module:return Common.UIString('Module');}
return'';}
name(){return this._name;}
startLocation(){return this._startLocation;}
endLocation(){return this._endLocation;}
object(){if(this._object)
return this._object;const runtimeModel=this._callFrame.debuggerModel._runtimeModel;const declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;if(declarativeScope){this._object=runtimeModel.createScopeRemoteObject(this._payload.object,new SDK.ScopeRef(this._ordinal,this._callFrame.id));}else{this._object=runtimeModel.createRemoteObject(this._payload.object);}
return this._object;}
description(){const declarativeScope=this._type!==Protocol.Debugger.ScopeType.With&&this._type!==Protocol.Debugger.ScopeType.Global;return declarativeScope?'':(this._payload.object.description||'');}};SDK.DebuggerPausedDetails=class{constructor(debuggerModel,callFrames,reason,auxData,breakpointIds,asyncStackTrace,asyncStackTraceId){this.debuggerModel=debuggerModel;this.callFrames=SDK.DebuggerModel.CallFrame.fromPayloadArray(debuggerModel,callFrames);this.reason=reason;this.auxData=auxData;this.breakpointIds=breakpointIds;if(asyncStackTrace)
this.asyncStackTrace=this._cleanRedundantFrames(asyncStackTrace);this.asyncStackTraceId=asyncStackTraceId;}
exception(){if(this.reason!==SDK.DebuggerModel.BreakReason.Exception&&this.reason!==SDK.DebuggerModel.BreakReason.PromiseRejection)
return null;return this.debuggerModel._runtimeModel.createRemoteObject((this.auxData));}
_cleanRedundantFrames(asyncStackTrace){let stack=asyncStackTrace;let previous=null;while(stack){if(stack.description==='async function'&&stack.callFrames.length)
stack.callFrames.shift();if(previous&&!stack.callFrames.length)
previous.parent=stack.parent;else
previous=stack;stack=stack.parent;}
return asyncStackTrace;}};;SDK.EmulationModel=class extends SDK.SDKModel{constructor(target){super(target);this._emulationAgent=target.emulationAgent();this._pageAgent=target.pageAgent();this._deviceOrientationAgent=target.deviceOrientationAgent();this._cssModel=target.model(SDK.CSSModel);this._overlayModel=target.model(SDK.OverlayModel);if(this._overlayModel)
this._overlayModel.addEventListener(SDK.OverlayModel.Events.InspectModeWillBeToggled,this._updateTouch,this);const disableJavascriptSetting=Common.settings.moduleSetting('javaScriptDisabled');disableJavascriptSetting.addChangeListener(()=>this._emulationAgent.setScriptExecutionDisabled(disableJavascriptSetting.get()));if(disableJavascriptSetting.get())
this._emulationAgent.setScriptExecutionDisabled(true);const mediaSetting=Common.moduleSetting('emulatedCSSMedia');mediaSetting.addChangeListener(()=>this._emulateCSSMedia(mediaSetting.get()));if(mediaSetting.get())
this._emulateCSSMedia(mediaSetting.get());this._touchEnabled=false;this._touchMobile=false;this._customTouchEnabled=false;this._touchConfiguration={enabled:false,configuration:'mobile',scriptId:''};}
supportsDeviceEmulation(){return this.target().hasAllCapabilities(SDK.Target.Capability.DeviceEmulation);}
resetPageScaleFactor(){return this._emulationAgent.resetPageScaleFactor();}
emulateDevice(metrics){if(metrics)
return this._emulationAgent.invoke_setDeviceMetricsOverride(metrics);else
return this._emulationAgent.clearDeviceMetricsOverride();}
overlayModel(){return this._overlayModel;}
emulateGeolocation(geolocation){if(!geolocation){this._emulationAgent.clearGeolocationOverride();return;}
if(geolocation.error){this._emulationAgent.setGeolocationOverride();}else{this._emulationAgent.setGeolocationOverride(geolocation.latitude,geolocation.longitude,SDK.EmulationModel.Geolocation.DefaultMockAccuracy);}}
emulateDeviceOrientation(deviceOrientation){if(deviceOrientation){this._deviceOrientationAgent.setDeviceOrientationOverride(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);}else{this._deviceOrientationAgent.clearDeviceOrientationOverride();}}
_emulateCSSMedia(media){this._emulationAgent.setEmulatedMedia(media);if(this._cssModel)
this._cssModel.mediaQueryResultChanged();}
setCPUThrottlingRate(rate){this._emulationAgent.setCPUThrottlingRate(rate);}
emulateTouch(enabled,mobile){this._touchEnabled=enabled;this._touchMobile=mobile;this._updateTouch();}
overrideEmulateTouch(enabled){this._customTouchEnabled=enabled;this._updateTouch();}
_updateTouch(){let configuration={enabled:this._touchEnabled,configuration:this._touchMobile?'mobile':'desktop',};if(this._customTouchEnabled)
configuration={enabled:true,configuration:'mobile'};if(this._overlayModel&&this._overlayModel.inspectModeEnabled())
configuration={enabled:false,configuration:'mobile'};if(!this._touchConfiguration.enabled&&!configuration.enabled)
return;if(this._touchConfiguration.enabled&&configuration.enabled&&this._touchConfiguration.configuration===configuration.configuration)
return;this._touchConfiguration=configuration;this._emulationAgent.setTouchEmulationEnabled(configuration.enabled,1);this._emulationAgent.setEmitTouchEventsForMouse(configuration.enabled,configuration.configuration);}};SDK.SDKModel.register(SDK.EmulationModel,SDK.Target.Capability.Emulation,true);SDK.EmulationModel.Geolocation=class{constructor(latitude,longitude,error){this.latitude=latitude;this.longitude=longitude;this.error=error;}
static parseSetting(value){if(value){const splitError=value.split(':');if(splitError.length===2){const splitPosition=splitError[0].split('@');if(splitPosition.length===2){return new SDK.EmulationModel.Geolocation(parseFloat(splitPosition[0]),parseFloat(splitPosition[1]),!!splitError[1]);}}}
return new SDK.EmulationModel.Geolocation(0,0,false);}
static parseUserInput(latitudeString,longitudeString,errorStatus){if(!latitudeString&&!longitudeString)
return null;const isLatitudeValid=SDK.EmulationModel.Geolocation.latitudeValidator(latitudeString);const isLongitudeValid=SDK.EmulationModel.Geolocation.longitudeValidator(longitudeString);if(!isLatitudeValid&&!isLongitudeValid)
return null;const latitude=isLatitudeValid?parseFloat(latitudeString):-1;const longitude=isLongitudeValid?parseFloat(longitudeString):-1;return new SDK.EmulationModel.Geolocation(latitude,longitude,!!errorStatus);}
static latitudeValidator(value){const numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-90&&numValue<=90;}
static longitudeValidator(value){const numValue=parseFloat(value);return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value)&&numValue>=-180&&numValue<=180;}
toSetting(){return this.latitude+'@'+this.longitude+':'+(this.error||'');}};SDK.EmulationModel.Geolocation.DefaultMockAccuracy=150;SDK.EmulationModel.DeviceOrientation=class{constructor(alpha,beta,gamma){this.alpha=alpha;this.beta=beta;this.gamma=gamma;}
static parseSetting(value){if(value){const jsonObject=JSON.parse(value);return new SDK.EmulationModel.DeviceOrientation(jsonObject.alpha,jsonObject.beta,jsonObject.gamma);}
return new SDK.EmulationModel.DeviceOrientation(0,0,0);}
static parseUserInput(alphaString,betaString,gammaString){if(!alphaString&&!betaString&&!gammaString)
return null;const isAlphaValid=SDK.EmulationModel.DeviceOrientation.validator(alphaString);const isBetaValid=SDK.EmulationModel.DeviceOrientation.validator(betaString);const isGammaValid=SDK.EmulationModel.DeviceOrientation.validator(gammaString);if(!isAlphaValid&&!isBetaValid&&!isGammaValid)
return null;const alpha=isAlphaValid?parseFloat(alphaString):-1;const beta=isBetaValid?parseFloat(betaString):-1;const gamma=isGammaValid?parseFloat(gammaString):-1;return new SDK.EmulationModel.DeviceOrientation(alpha,beta,gamma);}
static validator(value){return/^([+-]?[\d]+(\.\d+)?|[+-]?\.\d+)$/.test(value);}
toSetting(){return JSON.stringify(this);}};;SDK.SnapshotWithRect;SDK.Layer=function(){};SDK.Layer.prototype={id(){},parentId(){},parent(){},isRoot(){},children(){},addChild(child){},node(){},nodeForSelfOrAncestor(){},offsetX(){},offsetY(){},width(){},height(){},transform(){},quad(){},anchorPoint(){},invisible(){},paintCount(){},lastPaintRect(){},scrollRects(){},stickyPositionConstraint(){},gpuMemoryUsage(){},requestCompositingReasons(){},drawsContent(){},snapshots(){}};SDK.Layer.ScrollRectType={NonFastScrollable:'NonFastScrollable',TouchEventHandler:'TouchEventHandler',WheelEventHandler:'WheelEventHandler',RepaintsOnScroll:'RepaintsOnScroll'};SDK.Layer.StickyPositionConstraint=class{constructor(layerTree,constraint){this._stickyBoxRect=constraint.stickyBoxRect;this._containingBlockRect=constraint.containingBlockRect;this._nearestLayerShiftingStickyBox=null;if(layerTree&&constraint.nearestLayerShiftingStickyBox)
this._nearestLayerShiftingStickyBox=layerTree.layerById(constraint.nearestLayerShiftingStickyBox);this._nearestLayerShiftingContainingBlock=null;if(layerTree&&constraint.nearestLayerShiftingContainingBlock)
this._nearestLayerShiftingContainingBlock=layerTree.layerById(constraint.nearestLayerShiftingContainingBlock);}
stickyBoxRect(){return this._stickyBoxRect;}
containingBlockRect(){return this._containingBlockRect;}
nearestLayerShiftingStickyBox(){return this._nearestLayerShiftingStickyBox;}
nearestLayerShiftingContainingBlock(){return this._nearestLayerShiftingContainingBlock;}};SDK.LayerTreeBase=class{constructor(target){this._target=target;this._domModel=target?target.model(SDK.DOMModel):null;this._layersById={};this._root=null;this._contentRoot=null;this._backendNodeIdToNode=new Map();}
target(){return this._target;}
root(){return this._root;}
setRoot(root){this._root=root;}
contentRoot(){return this._contentRoot;}
setContentRoot(contentRoot){this._contentRoot=contentRoot;}
forEachLayer(callback,root){if(!root){root=this.root();if(!root)
return false;}
return callback(root)||root.children().some(this.forEachLayer.bind(this,callback));}
layerById(id){return this._layersById[id]||null;}
async resolveBackendNodeIds(requestedNodeIds){if(!requestedNodeIds.size||!this._domModel)
return;const nodesMap=await this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds);if(!nodesMap)
return;for(const nodeId of nodesMap.keysArray())
this._backendNodeIdToNode.set(nodeId,nodesMap.get(nodeId)||null);}
backendNodeIdToNode(){return this._backendNodeIdToNode;}
setViewportSize(viewportSize){this._viewportSize=viewportSize;}
viewportSize(){return this._viewportSize;}
_nodeForId(id){return this._domModel?this._domModel.nodeForId(id):null;}};;SDK.LogModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerLogDispatcher(this);this._logAgent=target.logAgent();this._logAgent.enable();if(!Host.isUnderTest()){this._logAgent.startViolationsReport([{name:'longTask',threshold:200},{name:'longLayout',threshold:30},{name:'blockedEvent',threshold:100},{name:'blockedParser',threshold:-1},{name:'handler',threshold:150},{name:'recurringHandler',threshold:50},{name:'discouragedAPIUse',threshold:-1}]);}}
entryAdded(payload){this.dispatchEventToListeners(SDK.LogModel.Events.EntryAdded,{logModel:this,entry:payload});}
requestClear(){this._logAgent.clear();}};SDK.SDKModel.register(SDK.LogModel,SDK.Target.Capability.Log,true);SDK.LogModel.Events={EntryAdded:Symbol('EntryAdded')};;SDK.ServiceWorkerManager=class extends SDK.SDKModel{constructor(target){super(target);target.registerServiceWorkerDispatcher(new SDK.ServiceWorkerDispatcher(this));this._lastAnonymousTargetId=0;this._agent=target.serviceWorkerAgent();this._registrations=new Map();this.enable();this._forceUpdateSetting=Common.settings.createSetting('serviceWorkerUpdateOnReload',false);if(this._forceUpdateSetting.get())
this._forceUpdateSettingChanged();this._forceUpdateSetting.addChangeListener(this._forceUpdateSettingChanged,this);new SDK.ServiceWorkerContextNamer(target,this);}
enable(){if(this._enabled)
return;this._enabled=true;this._agent.enable();}
disable(){if(!this._enabled)
return;this._enabled=false;this._registrations.clear();this._agent.disable();}
registrations(){return this._registrations;}
findVersion(versionId){for(const registration of this.registrations().values()){const version=registration.versions.get(versionId);if(version)
return version;}
return null;}
deleteRegistration(registrationId){const registration=this._registrations.get(registrationId);if(!registration)
return;if(registration._isRedundant()){this._registrations.delete(registrationId);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);return;}
registration._deleting=true;for(const version of registration.versions.values())
this.stopWorker(version.id);this._unregister(registration.scopeURL);}
updateRegistration(registrationId){const registration=this._registrations.get(registrationId);if(!registration)
return;this._agent.updateRegistration(registration.scopeURL);}
deliverPushMessage(registrationId,data){const registration=this._registrations.get(registrationId);if(!registration)
return;const origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.deliverPushMessage(origin,registrationId,data);}
dispatchSyncEvent(registrationId,tag,lastChance){const registration=this._registrations.get(registrationId);if(!registration)
return;const origin=Common.ParsedURL.extractOrigin(registration.scopeURL);this._agent.dispatchSyncEvent(origin,registrationId,tag,lastChance);}
_unregister(scope){this._agent.unregister(scope);}
startWorker(scope){this._agent.startWorker(scope);}
skipWaiting(scope){this._agent.skipWaiting(scope);}
stopWorker(versionId){this._agent.stopWorker(versionId);}
inspectWorker(versionId){this._agent.inspectWorker(versionId);}
_workerRegistrationUpdated(registrations){for(const payload of registrations){let registration=this._registrations.get(payload.registrationId);if(!registration){registration=new SDK.ServiceWorkerRegistration(payload);this._registrations.set(payload.registrationId,registration);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);continue;}
registration._update(payload);if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}}
_workerVersionUpdated(versions){const registrations=new Set();for(const payload of versions){const registration=this._registrations.get(payload.registrationId);if(!registration)
continue;registration._updateVersion(payload);registrations.add(registration);}
for(const registration of registrations){if(registration._shouldBeRemoved()){this._registrations.delete(registration.id);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted,registration);}else{this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationUpdated,registration);}}}
_workerErrorReported(payload){const registration=this._registrations.get(payload.registrationId);if(!registration)
return;registration.errors.push(payload);this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationErrorAdded,{registration:registration,error:payload});}
forceUpdateOnReloadSetting(){return this._forceUpdateSetting;}
_forceUpdateSettingChanged(){this._agent.setForceUpdateOnPageLoad(this._forceUpdateSetting.get());}};SDK.SDKModel.register(SDK.ServiceWorkerManager,SDK.Target.Capability.Target|SDK.Target.Capability.Browser,true);SDK.ServiceWorkerManager.Events={RegistrationUpdated:Symbol('RegistrationUpdated'),RegistrationErrorAdded:Symbol('RegistrationErrorAdded'),RegistrationDeleted:Symbol('RegistrationDeleted')};SDK.ServiceWorkerDispatcher=class{constructor(manager){this._manager=manager;}
workerRegistrationUpdated(registrations){this._manager._workerRegistrationUpdated(registrations);}
workerVersionUpdated(versions){this._manager._workerVersionUpdated(versions);}
workerErrorReported(errorMessage){this._manager._workerErrorReported(errorMessage);}};SDK.ServiceWorkerVersion=class{constructor(registration,payload){this.registration=registration;this._update(payload);}
_update(payload){this.id=payload.versionId;this.scriptURL=payload.scriptURL;const parsedURL=new Common.ParsedURL(payload.scriptURL);this.securityOrigin=parsedURL.securityOrigin();this.runningStatus=payload.runningStatus;this.status=payload.status;this.scriptLastModified=payload.scriptLastModified;this.scriptResponseTime=payload.scriptResponseTime;this.controlledClients=[];for(let i=0;i<payload.controlledClients.length;++i)
this.controlledClients.push(payload.controlledClients[i]);this.targetId=payload.targetId||null;}
isStartable(){return!this.registration.isDeleted&&this.isActivated()&&this.isStopped();}
isStoppedAndRedundant(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped&&this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;}
isStopped(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopped;}
isStarting(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Starting;}
isRunning(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Running;}
isStopping(){return this.runningStatus===Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus.Stopping;}
isNew(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.New;}
isInstalling(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installing;}
isInstalled(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installed;}
isActivating(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activating;}
isActivated(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activated;}
isRedundant(){return this.status===Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant;}
mode(){if(this.isNew()||this.isInstalling())
return SDK.ServiceWorkerVersion.Modes.Installing;else if(this.isInstalled())
return SDK.ServiceWorkerVersion.Modes.Waiting;else if(this.isActivating()||this.isActivated())
return SDK.ServiceWorkerVersion.Modes.Active;return SDK.ServiceWorkerVersion.Modes.Redundant;}};SDK.ServiceWorkerVersion.Modes={Installing:'installing',Waiting:'waiting',Active:'active',Redundant:'redundant'};SDK.ServiceWorkerRegistration=class{constructor(payload){this._update(payload);this.versions=new Map();this._deleting=false;this.errors=[];}
_update(payload){this._fingerprint=Symbol('fingerprint');this.id=payload.registrationId;this.scopeURL=payload.scopeURL;const parsedURL=new Common.ParsedURL(payload.scopeURL);this.securityOrigin=parsedURL.securityOrigin();this.isDeleted=payload.isDeleted;this.forceUpdateOnPageLoad=payload.forceUpdateOnPageLoad;}
fingerprint(){return this._fingerprint;}
versionsByMode(){const result=new Map();for(const version of this.versions.values())
result.set(version.mode(),version);return result;}
_updateVersion(payload){this._fingerprint=Symbol('fingerprint');let version=this.versions.get(payload.versionId);if(!version){version=new SDK.ServiceWorkerVersion(this,payload);this.versions.set(payload.versionId,version);return version;}
version._update(payload);return version;}
_isRedundant(){for(const version of this.versions.values()){if(!version.isStoppedAndRedundant())
return false;}
return true;}
_shouldBeRemoved(){return this._isRedundant()&&(!this.errors.length||this._deleting);}
canBeRemoved(){return this.isDeleted||this._deleting;}
clearErrors(){this._fingerprint=Symbol('fingerprint');this.errors=[];}};SDK.ServiceWorkerContextNamer=class{constructor(target,serviceWorkerManager){this._target=target;this._serviceWorkerManager=serviceWorkerManager;this._versionByTargetId=new Map();serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationUpdated,this._registrationsUpdated,this);serviceWorkerManager.addEventListener(SDK.ServiceWorkerManager.Events.RegistrationDeleted,this._registrationsUpdated,this);SDK.targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._executionContextCreated,this);}
_registrationsUpdated(event){this._versionByTargetId.clear();const registrations=this._serviceWorkerManager.registrations().valuesArray();for(const registration of registrations){const versions=registration.versions.valuesArray();for(const version of versions){if(version.targetId)
this._versionByTargetId.set(version.targetId,version);}}
this._updateAllContextLabels();}
_executionContextCreated(event){const executionContext=(event.data);const serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(executionContext.target());if(!serviceWorkerTargetId)
return;this._updateContextLabel(executionContext,this._versionByTargetId.get(serviceWorkerTargetId)||null);}
_serviceWorkerTargetIdForWorker(target){const parent=target.parentTarget();if(!parent||parent.parentTarget()!==this._target)
return null;return parent.id();}
_updateAllContextLabels(){for(const target of SDK.targetManager.targets()){const serviceWorkerTargetId=this._serviceWorkerTargetIdForWorker(target);if(!serviceWorkerTargetId)
continue;const version=this._versionByTargetId.get(serviceWorkerTargetId)||null;const runtimeModel=target.model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];for(const context of executionContexts)
this._updateContextLabel(context,version);}}
_updateContextLabel(context,version){if(!version){context.setLabel('');return;}
const parsedUrl=context.origin.asParsedURL();const label=parsedUrl?parsedUrl.lastPathComponentWithFragment():context.name;context.setLabel(label+' #'+version.id+' ('+version.status+')');}};;SDK.TracingManagerClient=function(){};SDK.TracingManagerClient.prototype={traceEventsCollected(events){},tracingComplete(){},tracingBufferUsage(usage){},eventsRetrievalProgress(progress){}};SDK.TracingManager=class extends SDK.SDKModel{constructor(target){super(target);this._tracingAgent=target.tracingAgent();target.registerTracingDispatcher(new SDK.TracingDispatcher(this));this._activeClient=null;this._eventBufferSize=0;this._eventsRetrieved=0;}
_bufferUsage(usage,eventCount,percentFull){this._eventBufferSize=eventCount;this._activeClient.tracingBufferUsage(usage||percentFull||0);}
_eventsCollected(events){this._activeClient.traceEventsCollected(events);this._eventsRetrieved+=events.length;if(!this._eventBufferSize)
return;if(this._eventsRetrieved>this._eventBufferSize)
this._eventsRetrieved=this._eventBufferSize;this._activeClient.eventsRetrievalProgress(this._eventsRetrieved/this._eventBufferSize);}
_tracingComplete(){this._eventBufferSize=0;this._eventsRetrieved=0;this._activeClient.tracingComplete();this._activeClient=null;this._finishing=false;}
start(client,categoryFilter,options){if(this._activeClient)
throw new Error('Tracing is already started');const bufferUsageReportingIntervalMs=500;this._activeClient=client;return this._tracingAgent.start(categoryFilter,options,bufferUsageReportingIntervalMs,SDK.TracingManager.TransferMode.ReportEvents);}
stop(){if(!this._activeClient)
throw new Error('Tracing is not started');if(this._finishing)
throw new Error('Tracing is already being stopped');this._finishing=true;this._tracingAgent.end();}};SDK.SDKModel.register(SDK.TracingManager,SDK.Target.Capability.Tracing,false);SDK.TracingManager.EventPayload;SDK.TracingManager.TransferMode={ReportEvents:'ReportEvents',ReturnAsStream:'ReturnAsStream'};SDK.TracingDispatcher=class{constructor(tracingManager){this._tracingManager=tracingManager;}
bufferUsage(usage,eventCount,percentFull){this._tracingManager._bufferUsage(usage,eventCount,percentFull);}
dataCollected(data){this._tracingManager._eventsCollected(data);}
tracingComplete(){this._tracingManager._tracingComplete();}};;SDK.TracingModel=class{constructor(backingStorage){this._backingStorage=backingStorage;this._firstWritePending=true;this._processById=new Map();this._processByName=new Map();this._minimumRecordTime=0;this._maximumRecordTime=0;this._devToolsMetadataEvents=[];this._asyncEvents=[];this._openAsyncEvents=new Map();this._openNestableAsyncEvents=new Map();this._profileGroups=new Map();this._parsedCategories=new Map();}
static isNestableAsyncPhase(phase){return phase==='b'||phase==='e'||phase==='n';}
static isAsyncBeginPhase(phase){return phase==='S'||phase==='b';}
static isAsyncPhase(phase){return SDK.TracingModel.isNestableAsyncPhase(phase)||phase==='S'||phase==='T'||phase==='F'||phase==='p';}
static isFlowPhase(phase){return phase==='s'||phase==='t'||phase==='f';}
static isTopLevelEvent(event){return event.hasCategory(SDK.TracingModel.TopLevelEventCategory)||event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)&&event.name==='Program';}
static _extractId(payload){const scope=payload.scope||'';if(typeof payload.id2==='undefined')
return scope&&payload.id?`${scope}@${payload.id}`:payload.id;const id2=payload.id2;if(typeof id2==='object'&&('global'in id2)!==('local'in id2)){return typeof id2['global']!=='undefined'?`:${scope}:${id2['global']}`:`:${scope}:${payload.pid}:${id2['local']}`;}
console.error(`Unexpected id2 field at ${payload.ts / 1000}, one and only one of 'local' and 'global' should be present.`);}
static browserMainThread(tracingModel){const processes=tracingModel.sortedProcesses();if(!processes.length)
return null;const browserProcesses=[];const crRendererMainThreads=[];for(const process of processes){if(process.name().toLowerCase().endsWith('browser'))
browserProcesses.push(process);crRendererMainThreads.push(...process.sortedThreads().filter(t=>t.name()==='CrBrowserMain'));}
if(crRendererMainThreads.length===1)
return crRendererMainThreads[0];if(browserProcesses.length===1)
return browserProcesses[0].threadByName('CrBrowserMain');const tracingStartedInBrowser=tracingModel.devToolsMetadataEvents().filter(e=>e.name==='TracingStartedInBrowser');if(tracingStartedInBrowser.length===1)
return tracingStartedInBrowser[0].thread;Common.console.error('Failed to find browser main thread in trace, some timeline features may be unavailable');return null;}
devToolsMetadataEvents(){return this._devToolsMetadataEvents;}
addEvents(events){for(let i=0;i<events.length;++i)
this._addEvent(events[i]);}
tracingComplete(){this._processPendingAsyncEvents();this._backingStorage.appendString(this._firstWritePending?'[]':']');this._backingStorage.finishWriting();this._firstWritePending=false;for(const process of this._processById.values()){for(const thread of process._threads.values())
thread.tracingComplete();}}
dispose(){if(!this._firstWritePending)
this._backingStorage.reset();}
adjustTime(offset){this._minimumRecordTime+=offset;this._maximumRecordTime+=offset;for(const process of this._processById.values()){for(const thread of process._threads.values()){for(const event of thread.events()){event.startTime+=offset;if(typeof event.endTime==='number')
event.endTime+=offset;}
for(const event of thread.asyncEvents()){event.startTime+=offset;if(typeof event.endTime==='number')
event.endTime+=offset;}}}}
_addEvent(payload){let process=this._processById.get(payload.pid);if(!process){process=new SDK.TracingModel.Process(this,payload.pid);this._processById.set(payload.pid,process);}
const phase=SDK.TracingModel.Phase;const eventsDelimiter=',\n';this._backingStorage.appendString(this._firstWritePending?'[':eventsDelimiter);this._firstWritePending=false;const stringPayload=JSON.stringify(payload);const isAccessible=payload.ph===phase.SnapshotObject;let backingStorage=null;const keepStringsLessThan=10000;if(isAccessible&&stringPayload.length>keepStringsLessThan)
backingStorage=this._backingStorage.appendAccessibleString(stringPayload);else
this._backingStorage.appendString(stringPayload);const timestamp=payload.ts/1000;if(timestamp&&(!this._minimumRecordTime||timestamp<this._minimumRecordTime)&&(payload.ph===phase.Begin||payload.ph===phase.Complete||payload.ph===phase.Instant))
this._minimumRecordTime=timestamp;const endTimeStamp=(payload.ts+(payload.dur||0))/1000;this._maximumRecordTime=Math.max(this._maximumRecordTime,endTimeStamp);const event=process._addEvent(payload);if(!event)
return;if(payload.ph===phase.Sample){this._addSampleEvent(event);return;}
if(SDK.TracingModel.isAsyncPhase(payload.ph))
this._asyncEvents.push(event);event._setBackingStorage(backingStorage);if(event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory))
this._devToolsMetadataEvents.push(event);if(payload.ph!==phase.Metadata)
return;switch(payload.name){case SDK.TracingModel.MetadataEvent.ProcessSortIndex:process._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ProcessName:const processName=payload.args['name'];process._setName(processName);this._processByName.set(processName,process);break;case SDK.TracingModel.MetadataEvent.ThreadSortIndex:process.threadById(payload.tid)._setSortIndex(payload.args['sort_index']);break;case SDK.TracingModel.MetadataEvent.ThreadName:process.threadById(payload.tid)._setName(payload.args['name']);break;}}
_addSampleEvent(event){const group=this._profileGroups.get(event.id);if(group)
group._addChild(event);else
this._profileGroups.set(event.id,new SDK.TracingModel.ProfileEventsGroup(event));}
profileGroup(id){return this._profileGroups.get(id)||null;}
minimumRecordTime(){return this._minimumRecordTime;}
maximumRecordTime(){return this._maximumRecordTime;}
sortedProcesses(){return SDK.TracingModel.NamedObject._sort(this._processById.valuesArray());}
processByName(name){return this._processByName.get(name);}
threadByName(processName,threadName){const process=this.processByName(processName);return process&&process.threadByName(threadName);}
_processPendingAsyncEvents(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartTime);for(let i=0;i<this._asyncEvents.length;++i){const event=this._asyncEvents[i];if(SDK.TracingModel.isNestableAsyncPhase(event.phase))
this._addNestableAsyncEvent(event);else
this._addAsyncEvent(event);}
this._asyncEvents=[];this._closeOpenAsyncEvents();}
_closeOpenAsyncEvents(){for(const event of this._openAsyncEvents.values()){event.setEndTime(this._maximumRecordTime);event.steps[0].setEndTime(this._maximumRecordTime);}
this._openAsyncEvents.clear();for(const eventStack of this._openNestableAsyncEvents.values()){while(eventStack.length)
eventStack.pop().setEndTime(this._maximumRecordTime);}
this._openNestableAsyncEvents.clear();}
_addNestableAsyncEvent(event){const phase=SDK.TracingModel.Phase;const key=event.categoriesString+'.'+event.id;let openEventsStack=this._openNestableAsyncEvents.get(key);switch(event.phase){case phase.NestableAsyncBegin:if(!openEventsStack){openEventsStack=[];this._openNestableAsyncEvents.set(key,openEventsStack);}
const asyncEvent=new SDK.TracingModel.AsyncEvent(event);openEventsStack.push(asyncEvent);event.thread._addAsyncEvent(asyncEvent);break;case phase.NestableAsyncInstant:if(openEventsStack&&openEventsStack.length)
openEventsStack.peekLast()._addStep(event);break;case phase.NestableAsyncEnd:if(!openEventsStack||!openEventsStack.length)
break;const top=openEventsStack.pop();if(top.name!==event.name){console.error(`Begin/end event mismatch for nestable async event, ${top.name} vs. ${event.name}, key: ${key}`);break;}
top._addStep(event);}}
_addAsyncEvent(event){const phase=SDK.TracingModel.Phase;const key=event.categoriesString+'.'+event.name+'.'+event.id;let asyncEvent=this._openAsyncEvents.get(key);if(event.phase===phase.AsyncBegin){if(asyncEvent){console.error(`Event ${event.name} has already been started`);return;}
asyncEvent=new SDK.TracingModel.AsyncEvent(event);this._openAsyncEvents.set(key,asyncEvent);event.thread._addAsyncEvent(asyncEvent);return;}
if(!asyncEvent){return;}
if(event.phase===phase.AsyncEnd){asyncEvent._addStep(event);this._openAsyncEvents.delete(key);return;}
if(event.phase===phase.AsyncStepInto||event.phase===phase.AsyncStepPast){const lastStep=asyncEvent.steps.peekLast();if(lastStep.phase!==phase.AsyncBegin&&lastStep.phase!==event.phase){console.assert(false,'Async event step phase mismatch: '+lastStep.phase+' at '+lastStep.startTime+' vs. '+
event.phase+' at '+event.startTime);return;}
asyncEvent._addStep(event);return;}
console.assert(false,'Invalid async event phase');}
backingStorage(){return this._backingStorage;}
_parsedCategoriesForString(str){let parsedCategories=this._parsedCategories.get(str);if(!parsedCategories){parsedCategories=new Set(str.split(','));this._parsedCategories.set(str,parsedCategories);}
return parsedCategories;}};SDK.TracingModel.Phase={Begin:'B',End:'E',Complete:'X',Instant:'I',AsyncBegin:'S',AsyncStepInto:'T',AsyncStepPast:'p',AsyncEnd:'F',NestableAsyncBegin:'b',NestableAsyncEnd:'e',NestableAsyncInstant:'n',FlowBegin:'s',FlowStep:'t',FlowEnd:'f',Metadata:'M',Counter:'C',Sample:'P',CreateObject:'N',SnapshotObject:'O',DeleteObject:'D'};SDK.TracingModel.MetadataEvent={ProcessSortIndex:'process_sort_index',ProcessName:'process_name',ThreadSortIndex:'thread_sort_index',ThreadName:'thread_name'};SDK.TracingModel.TopLevelEventCategory='toplevel';SDK.TracingModel.DevToolsMetadataEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.DevToolsTimelineEventCategory='disabled-by-default-devtools.timeline';SDK.TracingModel.FrameLifecycleEventCategory='cc,devtools';SDK.BackingStorage=function(){};SDK.BackingStorage.prototype={appendString(string){},appendAccessibleString(string){},finishWriting(){},reset(){}};SDK.TracingModel.Event=class{constructor(categories,name,phase,startTime,thread){this.categoriesString=categories;this._parsedCategories=thread._model._parsedCategoriesForString(categories);this.name=name;this.phase=phase;this.startTime=startTime;this.thread=thread;this.args={};this.selfTime=0;}
static fromPayload(payload,thread){const event=new SDK.TracingModel.Event(payload.cat,payload.name,(payload.ph),payload.ts/1000,thread);if(payload.args)
event.addArgs(payload.args);else
console.error('Missing mandatory event argument \'args\' at '+payload.ts/1000);if(typeof payload.dur==='number')
event.setEndTime((payload.ts+payload.dur)/1000);const id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined')
event.id=id;if(payload.bind_id)
event.bind_id=payload.bind_id;return event;}
static compareStartTime(a,b){return a.startTime-b.startTime;}
static compareStartAndEndTime(a,b){return a.startTime-b.startTime||(b.endTime!==undefined&&a.endTime!==undefined&&b.endTime-a.endTime)||0;}
static orderedCompareStartTime(a,b){return a.startTime-b.startTime||a.ordinal-b.ordinal||-1;}
hasCategory(categoryName){return this._parsedCategories.has(categoryName);}
setEndTime(endTime){if(endTime<this.startTime){console.assert(false,'Event out of order: '+this.name);return;}
this.endTime=endTime;this.duration=endTime-this.startTime;}
addArgs(args){for(const name in args){if(name in this.args)
console.error('Same argument name ('+name+') is used for begin and end phases of '+this.name);this.args[name]=args[name];}}
_complete(endEvent){if(endEvent.args)
this.addArgs(endEvent.args);else
console.error('Missing mandatory event argument \'args\' at '+endEvent.startTime);this.setEndTime(endEvent.startTime);}
_setBackingStorage(backingStorage){}};SDK.TracingModel.ObjectSnapshot=class extends SDK.TracingModel.Event{constructor(category,name,startTime,thread){super(category,name,SDK.TracingModel.Phase.SnapshotObject,startTime,thread);this._backingStorage=null;this.id;this._objectPromise=null;}
static fromPayload(payload,thread){const snapshot=new SDK.TracingModel.ObjectSnapshot(payload.cat,payload.name,payload.ts/1000,thread);const id=SDK.TracingModel._extractId(payload);if(typeof id!=='undefined')
snapshot.id=id;if(!payload.args||!payload.args['snapshot']){console.error('Missing mandatory \'snapshot\' argument at '+payload.ts/1000);return snapshot;}
if(payload.args)
snapshot.addArgs(payload.args);return snapshot;}
requestObject(callback){const snapshot=this.args['snapshot'];if(snapshot){callback(snapshot);return;}
this._backingStorage().then(onRead,callback.bind(null,null));function onRead(result){if(!result){callback(null);return;}
try{const payload=JSON.parse(result);callback(payload['args']['snapshot']);}catch(e){Common.console.error('Malformed event data in backing storage');callback(null);}}}
objectPromise(){if(!this._objectPromise)
this._objectPromise=new Promise(this.requestObject.bind(this));return this._objectPromise;}
_setBackingStorage(backingStorage){if(!backingStorage)
return;this._backingStorage=backingStorage;this.args={};}};SDK.TracingModel.AsyncEvent=class extends SDK.TracingModel.Event{constructor(startEvent){super(startEvent.categoriesString,startEvent.name,startEvent.phase,startEvent.startTime,startEvent.thread);this.addArgs(startEvent.args);this.steps=[startEvent];}
_addStep(event){this.steps.push(event);if(event.phase===SDK.TracingModel.Phase.AsyncEnd||event.phase===SDK.TracingModel.Phase.NestableAsyncEnd){this.setEndTime(event.startTime);this.steps[0].setEndTime(event.startTime);}}};SDK.TracingModel.ProfileEventsGroup=class{constructor(event){this.children=[event];}
_addChild(event){this.children.push(event);}};SDK.TracingModel.NamedObject=class{constructor(model,id){this._model=model;this._id=id;this._name='';this._sortIndex=0;}
static _sort(array){function comparator(a,b){return a._sortIndex!==b._sortIndex?a._sortIndex-b._sortIndex:a.name().localeCompare(b.name());}
return array.sort(comparator);}
_setName(name){this._name=name;}
name(){return this._name;}
_setSortIndex(sortIndex){this._sortIndex=sortIndex;}};SDK.TracingModel.Process=class extends SDK.TracingModel.NamedObject{constructor(model,id){super(model,id);this._threads=new Map();this._threadByName=new Map();}
id(){return this._id;}
threadById(id){let thread=this._threads.get(id);if(!thread){thread=new SDK.TracingModel.Thread(this,id);this._threads.set(id,thread);}
return thread;}
threadByName(name){return this._threadByName.get(name)||null;}
_setThreadByName(name,thread){this._threadByName.set(name,thread);}
_addEvent(payload){return this.threadById(payload.tid)._addEvent(payload);}
sortedThreads(){return SDK.TracingModel.NamedObject._sort(this._threads.valuesArray());}};SDK.TracingModel.Thread=class extends SDK.TracingModel.NamedObject{constructor(process,id){super(process._model,id);this._process=process;this._events=[];this._asyncEvents=[];this._lastTopLevelEvent=null;}
tracingComplete(){this._asyncEvents.stableSort(SDK.TracingModel.Event.compareStartAndEndTime);this._events.stableSort(SDK.TracingModel.Event.compareStartTime);const phases=SDK.TracingModel.Phase;const stack=[];for(let i=0;i<this._events.length;++i){const e=this._events[i];e.ordinal=i;switch(e.phase){case phases.End:this._events[i]=null;if(!stack.length)
continue;const top=stack.pop();if(top.name!==e.name||top.categoriesString!==e.categoriesString){console.error('B/E events mismatch at '+top.startTime+' ('+top.name+') vs. '+e.startTime+' ('+e.name+')');}else{top._complete(e);}
break;case phases.Begin:stack.push(e);break;}}
while(stack.length)
stack.pop().setEndTime(this._model.maximumRecordTime());this._events.remove(null,false);}
_addEvent(payload){const event=payload.ph===SDK.TracingModel.Phase.SnapshotObject?SDK.TracingModel.ObjectSnapshot.fromPayload(payload,this):SDK.TracingModel.Event.fromPayload(payload,this);if(SDK.TracingModel.isTopLevelEvent(event)){if(this._lastTopLevelEvent&&this._lastTopLevelEvent.endTime>event.startTime)
return null;this._lastTopLevelEvent=event;}
this._events.push(event);return event;}
_addAsyncEvent(asyncEvent){this._asyncEvents.push(asyncEvent);}
_setName(name){super._setName(name);this._process._setThreadByName(name,this);}
id(){return this._id;}
process(){return this._process;}
events(){return this._events;}
asyncEvents(){return this._asyncEvents;}};;SDK.OverlayModel=class extends SDK.SDKModel{constructor(target){super(target);this._domModel=(target.model(SDK.DOMModel));target.registerOverlayDispatcher(this);this._overlayAgent=target.overlayAgent();this._overlayAgent.enable();this._overlayAgent.setShowViewportSizeOnResize(true);this._debuggerModel=target.model(SDK.DebuggerModel);if(this._debuggerModel){Common.moduleSetting('disablePausedStateOverlay').addChangeListener(this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerPaused,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerResumed,this._updatePausedInDebuggerMessage,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._updatePausedInDebuggerMessage,this);}
this._inspectModeEnabled=false;this._hideHighlightTimeout=null;this._defaultHighlighter=new SDK.OverlayModel.DefaultHighlighter(this);this._highlighter=this._defaultHighlighter;this._showPaintRectsSetting=Common.moduleSetting('showPaintRects');this._showPaintRectsSetting.addChangeListener(()=>this._overlayAgent.setShowPaintRects(this._showPaintRectsSetting.get()));if(this._showPaintRectsSetting.get())
this._overlayAgent.setShowPaintRects(true);this._showDebugBordersSetting=Common.moduleSetting('showDebugBorders');this._showDebugBordersSetting.addChangeListener(()=>this._overlayAgent.setShowDebugBorders(this._showDebugBordersSetting.get()));if(this._showDebugBordersSetting.get())
this._overlayAgent.setShowDebugBorders(true);this._showFPSCounterSetting=Common.moduleSetting('showFPSCounter');this._showFPSCounterSetting.addChangeListener(()=>this._overlayAgent.setShowFPSCounter(this._showFPSCounterSetting.get()));if(this._showFPSCounterSetting.get())
this._overlayAgent.setShowFPSCounter(true);this._showScrollBottleneckRectsSetting=Common.moduleSetting('showScrollBottleneckRects');this._showScrollBottleneckRectsSetting.addChangeListener(()=>this._overlayAgent.setShowScrollBottleneckRects(this._showScrollBottleneckRectsSetting.get()));if(this._showScrollBottleneckRectsSetting.get())
this._overlayAgent.setShowScrollBottleneckRects(true);if(target.suspended())
this._overlayAgent.setSuspended(true);}
static highlightObjectAsDOMNode(object){const domModel=object.runtimeModel().target().model(SDK.DOMModel);if(domModel)
domModel.overlayModel().highlightDOMNode(undefined,undefined,undefined,object.objectId);}
static hideDOMNodeHighlight(){for(const overlayModel of SDK.targetManager.models(SDK.OverlayModel))
overlayModel.highlightDOMNode(0);}
static muteHighlight(){SDK.OverlayModel.hideDOMNodeHighlight();SDK.OverlayModel._highlightDisabled=true;}
static unmuteHighlight(){SDK.OverlayModel._highlightDisabled=false;}
suspendModel(){return this._overlayAgent.setSuspended(true);}
resumeModel(){return this._overlayAgent.setSuspended(false);}
setShowViewportSizeOnResize(show){this._overlayAgent.setShowViewportSizeOnResize(show);}
_updatePausedInDebuggerMessage(){const message=this._debuggerModel.isPaused()&&!Common.moduleSetting('disablePausedStateOverlay').get()?Common.UIString('Paused in debugger'):undefined;this._overlayAgent.setPausedInDebuggerMessage(message);}
setHighlighter(highlighter){this._highlighter=highlighter||this._defaultHighlighter;}
async setInspectMode(mode){await this._domModel.requestDocument();this._inspectModeEnabled=mode!==Protocol.Overlay.InspectMode.None;this.dispatchEventToListeners(SDK.OverlayModel.Events.InspectModeWillBeToggled,this);this._highlighter.setInspectMode(mode,this._buildHighlightConfig());}
inspectModeEnabled(){return this._inspectModeEnabled;}
highlightDOMNode(nodeId,mode,backendNodeId,objectId){this.highlightDOMNodeWithConfig(nodeId,{mode:mode},backendNodeId,objectId);}
highlightDOMNodeWithConfig(nodeId,config,backendNodeId,objectId){if(SDK.OverlayModel._highlightDisabled)
return;config=config||{mode:'all',showInfo:undefined,selectors:undefined};if(this._hideHighlightTimeout){clearTimeout(this._hideHighlightTimeout);this._hideHighlightTimeout=null;}
const highlightConfig=this._buildHighlightConfig(config.mode);if(typeof config.showInfo!=='undefined')
highlightConfig.showInfo=config.showInfo;if(typeof config.selectors!=='undefined')
highlightConfig.selectorList=config.selectors;this._highlighter.highlightDOMNode(this._domModel.nodeForId(nodeId||0),highlightConfig,backendNodeId,objectId);}
highlightDOMNodeForTwoSeconds(nodeId){this.highlightDOMNode(nodeId);this._hideHighlightTimeout=setTimeout(()=>this.highlightDOMNode(0),2000);}
highlightFrame(frameId){if(SDK.OverlayModel._highlightDisabled)
return;this._highlighter.highlightFrame(frameId);}
_buildHighlightConfig(mode){mode=mode||'all';const showRulers=Common.moduleSetting('showMetricsRulers').get();const highlightConfig={showInfo:mode==='all',showRulers:showRulers,showExtensionLines:showRulers};if(mode==='all'||mode==='content')
highlightConfig.contentColor=Common.Color.PageHighlight.Content.toProtocolRGBA();if(mode==='all'||mode==='padding')
highlightConfig.paddingColor=Common.Color.PageHighlight.Padding.toProtocolRGBA();if(mode==='all'||mode==='border')
highlightConfig.borderColor=Common.Color.PageHighlight.Border.toProtocolRGBA();if(mode==='all'||mode==='margin')
highlightConfig.marginColor=Common.Color.PageHighlight.Margin.toProtocolRGBA();if(mode==='all'){highlightConfig.eventTargetColor=Common.Color.PageHighlight.EventTarget.toProtocolRGBA();highlightConfig.shapeColor=Common.Color.PageHighlight.Shape.toProtocolRGBA();highlightConfig.shapeMarginColor=Common.Color.PageHighlight.ShapeMargin.toProtocolRGBA();highlightConfig.displayAsMaterial=true;}
if(mode==='all')
highlightConfig.cssGridColor=Common.Color.PageHighlight.CssGrid.toProtocolRGBA();return highlightConfig;}
nodeHighlightRequested(nodeId){const node=this._domModel.nodeForId(nodeId);if(node)
this.dispatchEventToListeners(SDK.OverlayModel.Events.HighlightNodeRequested,node);}
inspectNodeRequested(backendNodeId){const deferredNode=new SDK.DeferredDOMNode(this.target(),backendNodeId);this.dispatchEventToListeners(SDK.OverlayModel.Events.InspectNodeRequested,deferredNode);}
screenshotRequested(viewport){this.dispatchEventToListeners(SDK.OverlayModel.Events.ScreenshotRequested,viewport);}};SDK.SDKModel.register(SDK.OverlayModel,SDK.Target.Capability.DOM,true);SDK.OverlayModel.Events={InspectModeWillBeToggled:Symbol('InspectModeWillBeToggled'),HighlightNodeRequested:Symbol('HighlightNodeRequested'),InspectNodeRequested:Symbol('InspectNodeRequested'),ScreenshotRequested:Symbol('ScreenshotRequested'),};SDK.OverlayModel.Highlighter=function(){};SDK.OverlayModel.Highlighter.prototype={highlightDOMNode(node,config,backendNodeId,objectId){},setInspectMode(mode,config){},highlightFrame(frameId){}};SDK.OverlayModel.DefaultHighlighter=class{constructor(model){this._model=model;}
highlightDOMNode(node,config,backendNodeId,objectId){if(objectId||node||backendNodeId){this._model._overlayAgent.highlightNode(config,(objectId||backendNodeId)?undefined:node.id,backendNodeId,objectId);}else{this._model._overlayAgent.hideHighlight();}}
setInspectMode(mode,config){return this._model._overlayAgent.setInspectMode(mode,config);}
highlightFrame(frameId){this._model._overlayAgent.highlightFrame(frameId,Common.Color.PageHighlight.Content.toProtocolRGBA(),Common.Color.PageHighlight.ContentOutline.toProtocolRGBA());}};;SDK.RuntimeModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.runtimeAgent();this.target().registerRuntimeDispatcher(new SDK.RuntimeDispatcher(this));this._agent.enable();this._executionContextById=new Map();this._executionContextComparator=SDK.ExecutionContext.comparator;this._hasSideEffectSupport=null;if(Common.moduleSetting('customFormatters').get())
this._agent.setCustomObjectFormatterEnabled(true);Common.moduleSetting('customFormatters').addChangeListener(this._customFormattersStateChanged.bind(this));}
static wrapObjectLiteralExpressionIfNeeded(code){if(!(/^\s*\{/.test(code)&&/\}\s*$/.test(code)))
return code;const parse=(async()=>0).constructor;try{parse('return '+code+';');const wrappedCode='('+code+')';parse(wrappedCode);return wrappedCode;}catch(e){return code;}}
debuggerModel(){return(this.target().model(SDK.DebuggerModel));}
heapProfilerModel(){return(this.target().model(SDK.HeapProfilerModel));}
executionContexts(){return this._executionContextById.valuesArray().sort(this.executionContextComparator());}
setExecutionContextComparator(comparator){this._executionContextComparator=comparator;}
executionContextComparator(){return this._executionContextComparator;}
defaultExecutionContext(){for(const context of this.executionContexts()){if(context.isDefault)
return context;}
return null;}
executionContext(id){return this._executionContextById.get(id)||null;}
_executionContextCreated(context){const data=context.auxData||{isDefault:true};const executionContext=new SDK.ExecutionContext(this,context.id,context.name,context.origin,data['isDefault'],data['frameId']);this._executionContextById.set(executionContext.id,executionContext);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextCreated,executionContext);}
_executionContextDestroyed(executionContextId){const executionContext=this._executionContextById.get(executionContextId);if(!executionContext)
return;this.debuggerModel().executionContextDestroyed(executionContext);this._executionContextById.delete(executionContextId);this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,executionContext);}
fireExecutionContextOrderChanged(){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this);}
_executionContextsCleared(){this.debuggerModel().globalObjectCleared();const contexts=this.executionContexts();this._executionContextById.clear();for(let i=0;i<contexts.length;++i)
this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed,contexts[i]);}
createRemoteObject(payload){console.assert(typeof payload==='object','Remote object payload should only be an object');return new SDK.RemoteObjectImpl(this,payload.objectId,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview,payload.customPreview);}
createScopeRemoteObject(payload,scopeRef){return new SDK.ScopeRemoteObject(this,payload.objectId,scopeRef,payload.type,payload.subtype,payload.value,payload.unserializableValue,payload.description,payload.preview);}
createRemoteObjectFromPrimitiveValue(value){const type=typeof value;let unserializableValue=undefined;if(type==='number'){const description=String(value);if(value===0&&1/value<0)
unserializableValue=SDK.RemoteObject.UnserializableNumber.Negative0;else if(description===SDK.RemoteObject.UnserializableNumber.NaN||description===SDK.RemoteObject.UnserializableNumber.Infinity||description===SDK.RemoteObject.UnserializableNumber.NegativeInfinity)
unserializableValue=description;}
if(type==='bigint')
unserializableValue=(String(value)+'n');if(typeof unserializableValue!=='undefined')
value=undefined;return new SDK.RemoteObjectImpl(this,undefined,type,undefined,value,unserializableValue);}
createRemotePropertyFromPrimitiveValue(name,value){return new SDK.RemoteObjectProperty(name,this.createRemoteObjectFromPrimitiveValue(value));}
discardConsoleEntries(){this._agent.discardConsoleEntries();}
releaseObjectGroup(objectGroupName){this._agent.releaseObjectGroup(objectGroupName);}
runIfWaitingForDebugger(){this._agent.runIfWaitingForDebugger();}
_customFormattersStateChanged(event){const enabled=(event.data);this._agent.setCustomObjectFormatterEnabled(enabled);}
async compileScript(expression,sourceURL,persistScript,executionContextId){const response=await this._agent.invoke_compileScript({expression:expression,sourceURL:sourceURL,persistScript:persistScript,executionContextId:executionContextId});if(response[Protocol.Error]){console.error(response[Protocol.Error]);return null;}
return{scriptId:response.scriptId,exceptionDetails:response.exceptionDetails};}
async runScript(scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise){const response=await this._agent.invoke_runScript({scriptId,executionContextId,objectGroup,silent,includeCommandLineAPI,returnByValue,generatePreview,awaitPromise});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:this.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async queryObjects(prototype){if(!prototype.objectId)
return{error:'Prototype should be an Object.'};const response=await this._agent.invoke_queryObjects({prototypeObjectId:(prototype.objectId),objectGroup:'console'});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{objects:this.createRemoteObject(response.objects)};}
async isolateId(){return(await this._agent.getIsolateId())||this.target().id();}
async heapUsage(){const result=await this._agent.invoke_getHeapUsage({});return result[Protocol.Error]?null:result;}
_inspectRequested(payload,hints){const object=this.createRemoteObject(payload);if(hints.copyToClipboard){this._copyRequested(object);return;}
if(hints.queryObjects){this._queryObjectsRequested(object);return;}
if(object.isNode()){Common.Revealer.reveal(object).then(object.release.bind(object));return;}
if(object.type==='function'){SDK.RemoteFunction.objectAsFunction(object).targetFunctionDetails().then(didGetDetails);return;}
function didGetDetails(response){object.release();if(!response||!response.location)
return;Common.Revealer.reveal(response.location);}
object.release();}
_copyRequested(object){if(!object.objectId){InspectorFrontendHost.copyText(object.unserializableValue()||object.value);return;}
object.callFunctionJSON(toStringForClipboard,[{value:object.subtype}],InspectorFrontendHost.copyText.bind(InspectorFrontendHost));function toStringForClipboard(subtype){if(subtype==='node')
return this.outerHTML;if(subtype&&typeof this==='undefined')
return subtype+'';try{return JSON.stringify(this,null,'  ');}catch(e){return''+this;}}}
async _queryObjectsRequested(object){const result=await this.queryObjects(object);object.release();if(result.error){Common.console.error(result.error);return;}
this.dispatchEventToListeners(SDK.RuntimeModel.Events.QueryObjectRequested,{objects:result.objects});}
static simpleTextFromException(exceptionDetails){let text=exceptionDetails.text;if(exceptionDetails.exception&&exceptionDetails.exception.description){let description=exceptionDetails.exception.description;if(description.indexOf('\n')!==-1)
description=description.substring(0,description.indexOf('\n'));text+=' '+description;}
return text;}
exceptionThrown(timestamp,exceptionDetails){const exceptionWithTimestamp={timestamp:timestamp,details:exceptionDetails};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionThrown,exceptionWithTimestamp);}
_exceptionRevoked(exceptionId){this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExceptionRevoked,exceptionId);}
_consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){const consoleAPICall={type:type,args:args,executionContextId:executionContextId,timestamp:timestamp,stackTrace:stackTrace,context:context};this.dispatchEventToListeners(SDK.RuntimeModel.Events.ConsoleAPICalled,consoleAPICall);}
executionContextIdForScriptId(scriptId){const script=this.debuggerModel().scriptForId(scriptId);return script?script.executionContextId:0;}
executionContextForStackTrace(stackTrace){while(stackTrace&&!stackTrace.callFrames.length)
stackTrace=stackTrace.parent;if(!stackTrace||!stackTrace.callFrames.length)
return 0;return this.executionContextIdForScriptId(stackTrace.callFrames[0].scriptId);}
hasSideEffectSupport(){return this._hasSideEffectSupport;}
async checkSideEffectSupport(){const testContext=this.executionContexts().peekLast();if(!testContext)
return false;const response=await this._agent.invoke_evaluate({expression:SDK.RuntimeModel._sideEffectTestExpression,contextId:testContext.id,throwOnSideEffect:true});const exceptionDetails=!response[Protocol.Error]&&response.exceptionDetails;const supports=!!(exceptionDetails&&exceptionDetails.exception&&exceptionDetails.exception.description.startsWith('EvalError: Possible side-effect in debug-evaluate'));this._hasSideEffectSupport=supports;return supports;}
terminateExecution(){return this._agent.invoke_terminateExecution({});}};SDK.SDKModel.register(SDK.RuntimeModel,SDK.Target.Capability.JS,true);SDK.RuntimeModel._sideEffectTestExpression='(async function(){ await 1; })()';SDK.RuntimeModel.Events={ExecutionContextCreated:Symbol('ExecutionContextCreated'),ExecutionContextDestroyed:Symbol('ExecutionContextDestroyed'),ExecutionContextChanged:Symbol('ExecutionContextChanged'),ExecutionContextOrderChanged:Symbol('ExecutionContextOrderChanged'),ExceptionThrown:Symbol('ExceptionThrown'),ExceptionRevoked:Symbol('ExceptionRevoked'),ConsoleAPICalled:Symbol('ConsoleAPICalled'),QueryObjectRequested:Symbol('QueryObjectRequested'),};SDK.RuntimeModel.ExceptionWithTimestamp;SDK.RuntimeModel.CompileScriptResult;SDK.RuntimeModel.EvaluationOptions;SDK.RuntimeModel.EvaluationResult;SDK.RuntimeModel.QueryObjectResult;SDK.RuntimeModel.ConsoleAPICall;SDK.RuntimeDispatcher=class{constructor(runtimeModel){this._runtimeModel=runtimeModel;}
executionContextCreated(context){this._runtimeModel._executionContextCreated(context);}
executionContextDestroyed(executionContextId){this._runtimeModel._executionContextDestroyed(executionContextId);}
executionContextsCleared(){this._runtimeModel._executionContextsCleared();}
exceptionThrown(timestamp,exceptionDetails){this._runtimeModel.exceptionThrown(timestamp,exceptionDetails);}
exceptionRevoked(reason,exceptionId){this._runtimeModel._exceptionRevoked(exceptionId);}
consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context){this._runtimeModel._consoleAPICalled(type,args,executionContextId,timestamp,stackTrace,context);}
inspectRequested(payload,hints){this._runtimeModel._inspectRequested(payload,hints);}};SDK.ExecutionContext=class{constructor(runtimeModel,id,name,origin,isDefault,frameId){this.id=id;this.name=name;this.origin=origin;this.isDefault=isDefault;this.runtimeModel=runtimeModel;this.debuggerModel=runtimeModel.debuggerModel();this.frameId=frameId;this._setLabel('');}
target(){return this.runtimeModel.target();}
static comparator(a,b){function targetWeight(target){if(!target.parentTarget())
return 4;if(target.hasBrowserCapability())
return 3;if(target.hasJSCapability())
return 2;return 1;}
const weightDiff=targetWeight(a.target())-targetWeight(b.target());if(weightDiff)
return-weightDiff;if(a.isDefault)
return-1;if(b.isDefault)
return+1;return a.name.localeCompare(b.name);}
evaluate(options,userGesture,awaitPromise){if(this.debuggerModel.selectedCallFrame())
return this.debuggerModel.evaluateOnSelectedCallFrame(options);if(!options.throwOnSideEffect||this.runtimeModel.hasSideEffectSupport())
return this._evaluateGlobal(options,userGesture,awaitPromise);const unsupportedError={error:'Side-effect checks not supported by backend.'};if(this.runtimeModel.hasSideEffectSupport()===false)
return Promise.resolve(unsupportedError);return this.runtimeModel.checkSideEffectSupport().then(()=>{if(this.runtimeModel.hasSideEffectSupport())
return this._evaluateGlobal(options,userGesture,awaitPromise);return Promise.resolve(unsupportedError);});}
globalObject(objectGroup,generatePreview){return this._evaluateGlobal({expression:'this',objectGroup:objectGroup,includeCommandLineAPI:false,silent:true,returnByValue:false,generatePreview:generatePreview},false,false);}
async _evaluateGlobal(options,userGesture,awaitPromise){if(!options.expression){options.expression='this';}
const response=await this.runtimeModel._agent.invoke_evaluate({expression:options.expression,objectGroup:options.objectGroup,includeCommandLineAPI:options.includeCommandLineAPI,silent:options.silent,contextId:this.id,returnByValue:options.returnByValue,generatePreview:options.generatePreview,userGesture:userGesture,awaitPromise:awaitPromise,throwOnSideEffect:options.throwOnSideEffect});const error=response[Protocol.Error];if(error){console.error(error);return{error:error};}
return{object:this.runtimeModel.createRemoteObject(response.result),exceptionDetails:response.exceptionDetails};}
async globalLexicalScopeNames(){const response=await this.runtimeModel._agent.invoke_globalLexicalScopeNames({executionContextId:this.id});return response[Protocol.Error]?[]:response.names;}
label(){return this._label;}
setLabel(label){this._setLabel(label);this.runtimeModel.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextChanged,this);}
_setLabel(label){if(label){this._label=label;return;}
if(this.name){this._label=this.name;return;}
const parsedUrl=this.origin.asParsedURL();this._label=parsedUrl?parsedUrl.lastPathComponentWithFragment():'';}};;SDK.ScreenCaptureModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.pageAgent();this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;target.registerPageDispatcher(this);}
startScreencast(format,quality,width,height,everyNthFrame,onFrame,onVisibilityChanged){this._onScreencastFrame=onFrame;this._onScreencastVisibilityChanged=onVisibilityChanged;this._agent.startScreencast(format,quality,width,height,everyNthFrame);}
stopScreencast(){this._onScreencastFrame=null;this._onScreencastVisibilityChanged=null;this._agent.stopScreencast();}
captureScreenshot(format,quality,clip){return this._agent.captureScreenshot(format,quality,clip,true);}
async fetchLayoutMetrics(){const response=await this._agent.invoke_getLayoutMetrics({});if(response[Protocol.Error])
return null;return{viewportX:response.visualViewport.pageX,viewportY:response.visualViewport.pageY,viewportScale:response.visualViewport.scale,contentWidth:response.contentSize.width,contentHeight:response.contentSize.height};}
screencastFrame(data,metadata,sessionId){this._agent.screencastFrameAck(sessionId);if(this._onScreencastFrame)
this._onScreencastFrame.call(null,data,metadata);}
screencastVisibilityChanged(visible){if(this._onScreencastVisibilityChanged)
this._onScreencastVisibilityChanged.call(null,visible);}
domContentEventFired(time){}
loadEventFired(time){}
lifecycleEvent(frameId,loaderId,name,time){}
navigatedWithinDocument(frameId,url){}
frameAttached(frameId,parentFrameId){}
frameNavigated(frame){}
frameDetached(frameId){}
frameStartedLoading(frameId){}
frameStoppedLoading(frameId){}
frameScheduledNavigation(frameId,delay){}
frameClearedScheduledNavigation(frameId){}
frameResized(){}
javascriptDialogOpening(url,message,dialogType,hasBrowserHandler,prompt){}
javascriptDialogClosed(result,userInput){}
interstitialShown(){}
interstitialHidden(){}
windowOpen(url,windowName,windowFeatures,userGesture){}};SDK.SDKModel.register(SDK.ScreenCaptureModel,SDK.Target.Capability.ScreenCapture,false);;SDK.Script=class{constructor(debuggerModel,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,executionContextId,hash,isContentScript,isLiveEdit,sourceMapURL,hasSourceURL,length){this.debuggerModel=debuggerModel;this.scriptId=scriptId;this.sourceURL=sourceURL;this.lineOffset=startLine;this.columnOffset=startColumn;this.endLine=endLine;this.endColumn=endColumn;this.executionContextId=executionContextId;this.hash=hash;this._isContentScript=isContentScript;this._isLiveEdit=isLiveEdit;this.sourceMapURL=sourceMapURL;this.hasSourceURL=hasSourceURL;this.contentLength=length;this._originalContentProvider=null;this._originalSource=null;}
static _trimSourceURLComment(source){let sourceURLIndex=source.lastIndexOf('//# sourceURL=');if(sourceURLIndex===-1){sourceURLIndex=source.lastIndexOf('//@ sourceURL=');if(sourceURLIndex===-1)
return source;}
const sourceURLLineIndex=source.lastIndexOf('\n',sourceURLIndex);if(sourceURLLineIndex===-1)
return source;const sourceURLLine=source.substr(sourceURLLineIndex+1).split('\n',1)[0];if(sourceURLLine.search(SDK.Script.sourceURLRegex)===-1)
return source;return source.substr(0,sourceURLLineIndex)+source.substr(sourceURLLineIndex+sourceURLLine.length+1);}
isContentScript(){return this._isContentScript;}
executionContext(){return this.debuggerModel.runtimeModel().executionContext(this.executionContextId);}
isLiveEdit(){return this._isLiveEdit;}
contentURL(){return this.sourceURL;}
contentType(){return Common.resourceTypes.Script;}
contentEncoded(){return Promise.resolve(false);}
async requestContent(){if(this._source)
return this._source;if(!this.scriptId)
return'';const source=await this.debuggerModel.target().debuggerAgent().getScriptSource(this.scriptId);this._source=source?SDK.Script._trimSourceURLComment(source):'';if(this._originalSource===null)
this._originalSource=this._source;return this._source;}
originalContentProvider(){if(!this._originalContentProvider){const lazyContent=()=>this.requestContent().then(()=>this._originalSource);this._originalContentProvider=new Common.StaticContentProvider(this.contentURL(),this.contentType(),lazyContent);}
return this._originalContentProvider;}
async searchInContent(query,caseSensitive,isRegex){if(!this.scriptId)
return[];const matches=await this.debuggerModel.target().debuggerAgent().searchInContent(this.scriptId,query,caseSensitive,isRegex);return(matches||[]).map(match=>new Common.ContentProvider.SearchMatch(match.lineNumber,match.lineContent));}
_appendSourceURLCommentIfNeeded(source){if(!this.hasSourceURL)
return source;return source+'\n //# sourceURL='+this.sourceURL;}
async editSource(newSource,callback){newSource=SDK.Script._trimSourceURLComment(newSource);newSource=this._appendSourceURLCommentIfNeeded(newSource);if(!this.scriptId){callback('Script failed to parse');return;}
await this.requestContent();if(this._source===newSource){callback(null);return;}
const response=await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({scriptId:this.scriptId,scriptSource:newSource});if(!response[Protocol.Error]&&!response.exceptionDetails)
this._source=newSource;const needsStepIn=!!response.stackChanged;callback(response[Protocol.Error],response.exceptionDetails,response.callFrames,response.asyncStackTrace,response.asyncStackTraceId,needsStepIn);}
rawLocation(lineNumber,columnNumber){return new SDK.DebuggerModel.Location(this.debuggerModel,this.scriptId,lineNumber,columnNumber||0);}
isInlineScript(){const startsAtZero=!this.lineOffset&&!this.columnOffset;return!!this.sourceURL&&!startsAtZero;}
isAnonymousScript(){return!this.sourceURL;}
isInlineScriptWithSourceURL(){return!!this.hasSourceURL&&this.isInlineScript();}
async setBlackboxedRanges(positions){const response=await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({scriptId:this.scriptId,positions});const error=response[Protocol.Error];if(error)
console.error(error);return!error;}};SDK.Script.sourceURLRegex=/^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;;SDK.ServiceWorkerCacheModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerStorageDispatcher(this);this._caches=new Map();this._cacheAgent=target.cacheStorageAgent();this._storageAgent=target.storageAgent();this._securityOriginManager=target.model(SDK.SecurityOriginManager);this._originsUpdated=new Set();this._throttler=new Common.Throttler(2000);this._enabled=false;}
enable(){if(this._enabled)
return;this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins())
this._addOrigin(securityOrigin);this._enabled=true;}
clearForOrigin(origin){this._removeOrigin(origin);this._addOrigin(origin);}
refreshCacheNames(){for(const cache of this._caches.values())
this._cacheRemoved(cache);this._caches.clear();const securityOrigins=this._securityOriginManager.securityOrigins();for(const securityOrigin of securityOrigins)
this._loadCacheNames(securityOrigin);}
async deleteCache(cache){const response=await this._cacheAgent.invoke_deleteCache({cacheId:cache.cacheId});if(response[Protocol.Error]){console.error(`ServiceWorkerCacheAgent error deleting cache ${cache.toString()}: ${response[Protocol.Error]}`);return;}
this._caches.delete(cache.cacheId);this._cacheRemoved(cache);}
async deleteCacheEntry(cache,request){const response=await this._cacheAgent.invoke_deleteEntry({cacheId:cache.cacheId,request});if(!response[Protocol.Error])
return;Common.console.error(Common.UIString('ServiceWorkerCacheAgent error deleting cache entry %s in cache: %s',cache.toString(),response[Protocol.Error]));}
loadCacheData(cache,skipCount,pageSize,callback){this._requestEntries(cache,skipCount,pageSize,callback);}
caches(){const caches=new Array();for(const cache of this._caches.values())
caches.push(cache);return caches;}
dispose(){for(const cache of this._caches.values())
this._cacheRemoved(cache);this._caches.clear();if(this._enabled){this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.removeEventListener(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);}}
_addOrigin(securityOrigin){this._loadCacheNames(securityOrigin);if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.trackCacheStorageForOrigin(securityOrigin);}
_removeOrigin(securityOrigin){for(const opaqueId of this._caches.keys()){const cache=this._caches.get(opaqueId);if(cache.securityOrigin===securityOrigin){this._caches.delete(opaqueId);this._cacheRemoved(cache);}}
if(this._isValidSecurityOrigin(securityOrigin))
this._storageAgent.untrackCacheStorageForOrigin(securityOrigin);}
_isValidSecurityOrigin(securityOrigin){const parsedURL=securityOrigin.asParsedURL();return!!parsedURL&&parsedURL.scheme.startsWith('http');}
async _loadCacheNames(securityOrigin){const caches=await this._cacheAgent.requestCacheNames(securityOrigin);if(!caches)
return;this._updateCacheNames(securityOrigin,caches);}
_updateCacheNames(securityOrigin,cachesJson){function deleteAndSaveOldCaches(cache){if(cache.securityOrigin===securityOrigin&&!updatingCachesIds.has(cache.cacheId)){oldCaches.set(cache.cacheId,cache);this._caches.delete(cache.cacheId);}}
const updatingCachesIds=new Set();const newCaches=new Map();const oldCaches=new Map();for(const cacheJson of cachesJson){const cache=new SDK.ServiceWorkerCacheModel.Cache(this,cacheJson.securityOrigin,cacheJson.cacheName,cacheJson.cacheId);updatingCachesIds.add(cache.cacheId);if(this._caches.has(cache.cacheId))
continue;newCaches.set(cache.cacheId,cache);this._caches.set(cache.cacheId,cache);}
this._caches.forEach(deleteAndSaveOldCaches,this);newCaches.forEach(this._cacheAdded,this);oldCaches.forEach(this._cacheRemoved,this);}
_securityOriginAdded(event){const securityOrigin=(event.data);this._addOrigin(securityOrigin);}
_securityOriginRemoved(event){const securityOrigin=(event.data);this._removeOrigin(securityOrigin);}
_cacheAdded(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheAdded,{model:this,cache:cache});}
_cacheRemoved(cache){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheRemoved,{model:this,cache:cache});}
async _requestEntries(cache,skipCount,pageSize,callback){const response=await this._cacheAgent.invoke_requestEntries({cacheId:cache.cacheId,skipCount,pageSize});if(response[Protocol.Error]){console.error('ServiceWorkerCacheAgent error while requesting entries: ',response[Protocol.Error]);return;}
callback(response.cacheDataEntries,response.hasMore);}
cacheStorageListUpdated(origin){this._originsUpdated.add(origin);this._throttler.schedule(()=>{const promises=Array.from(this._originsUpdated,origin=>this._loadCacheNames(origin));this._originsUpdated.clear();return Promise.all(promises);});}
cacheStorageContentUpdated(origin,cacheName){this.dispatchEventToListeners(SDK.ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,{origin:origin,cacheName:cacheName});}
indexedDBListUpdated(origin){}
indexedDBContentUpdated(origin,databaseName,objectStoreName){}};SDK.SDKModel.register(SDK.ServiceWorkerCacheModel,SDK.Target.Capability.Browser,false);SDK.ServiceWorkerCacheModel.Events={CacheAdded:Symbol('CacheAdded'),CacheRemoved:Symbol('CacheRemoved'),CacheStorageContentUpdated:Symbol('CacheStorageContentUpdated')};SDK.ServiceWorkerCacheModel.Cache=class{constructor(model,securityOrigin,cacheName,cacheId){this._model=model;this.securityOrigin=securityOrigin;this.cacheName=cacheName;this.cacheId=cacheId;}
equals(cache){return this.cacheId===cache.cacheId;}
toString(){return this.securityOrigin+this.cacheName;}
requestCachedResponse(url){return this._model._cacheAgent.requestCachedResponse(this.cacheId,url);}};;SDK.CallFunctionResult;SDK.RemoteObject=class{static fromLocalObject(value){return new SDK.LocalJSONObject(value);}
static type(remoteObject){if(remoteObject===null)
return'null';const type=typeof remoteObject;if(type!=='object'&&type!=='function')
return type;return remoteObject.type;}
static arrayNameFromDescription(description){return description.replace(SDK.RemoteObject._descriptionLengthParenRegex,'').replace(SDK.RemoteObject._descriptionLengthSquareRegex,'');}
static arrayLength(object){if(object.subtype!=='array'&&object.subtype!=='typedarray')
return 0;const parenMatches=object.description.match(SDK.RemoteObject._descriptionLengthParenRegex);const squareMatches=object.description.match(SDK.RemoteObject._descriptionLengthSquareRegex);return parenMatches?parseInt(parenMatches[1],10):(squareMatches?parseInt(squareMatches[1],10):0);}
static toCallArgument(object){const type=typeof object;if(type==='undefined')
return{};if(type==='number'){const description=String(object);if(object===0&&1/object<0)
return{unserializableValue:SDK.RemoteObject.UnserializableNumber.Negative0};if(description===SDK.RemoteObject.UnserializableNumber.NaN||description===SDK.RemoteObject.UnserializableNumber.Infinity||description===SDK.RemoteObject.UnserializableNumber.NegativeInfinity)
return{unserializableValue:description};return{value:object};}
if(type==='bigint'){const value=String(object)+'n';return{unserializableValue:(value)};}
if(type==='string'||type==='boolean')
return{value:object};if(!object)
return{value:null};const isSDKRemoteObject=object instanceof SDK.RemoteObjectImpl;if(!isSDKRemoteObject&&typeof object.unserializableValue!=='undefined')
return{unserializableValue:object.unserializableValue};if(isSDKRemoteObject&&typeof object._unserializableValue!=='undefined')
return{unserializableValue:object._unserializableValue};if(typeof object.objectId!=='undefined')
return{objectId:object.objectId};return{value:object.value};}
static loadFromObjectPerProto(object,generatePreview,callback){let savedOwnProperties;let savedAccessorProperties;let savedInternalProperties;let resultCounter=2;function processCallback(){if(--resultCounter)
return;if(savedOwnProperties&&savedAccessorProperties){const propertiesMap=new Map();const propertySymbols=[];for(let i=0;i<savedAccessorProperties.length;i++){const property=savedAccessorProperties[i];if(property.symbol)
propertySymbols.push(property);else
propertiesMap.set(property.name,property);}
for(let i=0;i<savedOwnProperties.length;i++){const property=savedOwnProperties[i];if(property.isAccessorProperty())
continue;if(property.symbol)
propertySymbols.push(property);else
propertiesMap.set(property.name,property);}
return callback(propertiesMap.valuesArray().concat(propertySymbols),savedInternalProperties?savedInternalProperties:null);}else{callback(null,null);}}
function allAccessorPropertiesCallback(properties,internalProperties){savedAccessorProperties=properties;processCallback();}
function ownPropertiesCallback(properties,internalProperties){savedOwnProperties=properties;savedInternalProperties=internalProperties;processCallback();}
object.getAllProperties(true,generatePreview,allAccessorPropertiesCallback);object.getOwnProperties(generatePreview,ownPropertiesCallback);}
customPreview(){return null;}
get objectId(){return'Not implemented';}
get type(){throw'Not implemented';}
get subtype(){throw'Not implemented';}
get value(){throw'Not implemented';}
unserializableValue(){throw'Not implemented';}
get description(){throw'Not implemented';}
get hasChildren(){throw'Not implemented';}
get preview(){return undefined;}
arrayLength(){throw'Not implemented';}
getOwnProperties(generatePreview,callback){throw'Not implemented';}
getOwnPropertiesPromise(generatePreview){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.getOwnProperties(!!generatePreview,getOwnPropertiesCallback.bind(null,success));}
function getOwnPropertiesCallback(callback,properties,internalProperties){callback({properties:properties,internalProperties:internalProperties});}}
getAllProperties(accessorPropertiesOnly,generatePreview,callback){throw'Not implemented';}
getAllPropertiesPromise(accessorPropertiesOnly,generatePreview){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.getAllProperties(accessorPropertiesOnly,generatePreview,getAllPropertiesCallback.bind(null,success));}
function getAllPropertiesCallback(callback,properties,internalProperties){callback({properties:properties,internalProperties:internalProperties});}}
getProperty(propertyPath,callback){throw'Not implemented';}
async deleteProperty(name){throw'Not implemented';}
async setPropertyValue(name,value){throw'Not implemented';}
callFunction(functionDeclaration,args,callback){throw'Not implemented';}
callFunctionPromise(functionDeclaration,args){return new Promise(promiseConstructor.bind(this));function promiseConstructor(success){this.callFunction(functionDeclaration,args,callFunctionCallback.bind(null,success));}
function callFunctionCallback(callback,object,wasThrown){callback({object:object,wasThrown:wasThrown});}}
callFunctionJSON(functionDeclaration,args,callback){throw'Not implemented';}
callFunctionJSONPromise(functionDeclaration,args){return new Promise(success=>this.callFunctionJSON(functionDeclaration,args,success));}
release(){}
debuggerModel(){throw new Error('DebuggerModel-less object');}
runtimeModel(){throw new Error('RuntimeModel-less object');}
isNode(){return false;}};SDK.RemoteObjectImpl=class extends SDK.RemoteObject{constructor(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview,customPreview){super();this._runtimeModel=runtimeModel;this._runtimeAgent=runtimeModel.target().runtimeAgent();this._type=type;this._subtype=subtype;if(objectId){this._objectId=objectId;this._description=description;this._hasChildren=(type!=='symbol');this._preview=preview;}else{this._description=description;if(!this.description&&unserializableValue)
this._description=unserializableValue;if(!this._description&&(typeof value!=='object'||value===null))
this._description=value+'';this._hasChildren=false;if(typeof unserializableValue==='string'){this._unserializableValue=unserializableValue;if(unserializableValue===SDK.RemoteObject.UnserializableNumber.Infinity||unserializableValue===SDK.RemoteObject.UnserializableNumber.NegativeInfinity||unserializableValue===SDK.RemoteObject.UnserializableNumber.Negative0||unserializableValue===SDK.RemoteObject.UnserializableNumber.NaN)
this._value=Number(unserializableValue);else if(type==='bigint'&&unserializableValue.endsWith('n'))
this._value=BigInt(unserializableValue.substring(0,unserializableValue.length-1));else
this._value=unserializableValue;}else{this._value=value;}}
this._customPreview=customPreview||null;}
customPreview(){return this._customPreview;}
get objectId(){return this._objectId;}
get type(){return this._type;}
get subtype(){return this._subtype;}
get value(){return this._value;}
unserializableValue(){return this._unserializableValue;}
get description(){return this._description;}
get hasChildren(){return this._hasChildren;}
get preview(){return this._preview;}
getOwnProperties(generatePreview,callback){this.doGetProperties(true,false,generatePreview,callback);}
getAllProperties(accessorPropertiesOnly,generatePreview,callback){this.doGetProperties(false,accessorPropertiesOnly,generatePreview,callback);}
getProperty(propertyPath,callback){function remoteFunction(arrayStr){let result=this;const properties=JSON.parse(arrayStr);for(let i=0,n=properties.length;i<n;++i)
result=result[properties[i]];return result;}
const args=[{value:JSON.stringify(propertyPath)}];this.callFunction(remoteFunction,args,callback);}
doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,callback){if(!this._objectId){callback(null,null);return;}
this._runtimeAgent.invoke_getProperties({objectId:this._objectId,ownProperties,accessorPropertiesOnly,generatePreview}).then(remoteObjectBinder.bind(this));function remoteObjectBinder(response){if(response[Protocol.Error]){callback(null,null);return;}
if(response.exceptionDetails){this._runtimeModel.exceptionThrown(Date.now(),response.exceptionDetails);callback(null,null);return;}
const properties=response.result;const internalProperties=response.internalProperties;const result=[];for(let i=0;properties&&i<properties.length;++i){const property=properties[i];const propertyValue=property.value?this._runtimeModel.createRemoteObject(property.value):null;const propertySymbol=property.symbol?this._runtimeModel.createRemoteObject(property.symbol):null;const remoteProperty=new SDK.RemoteObjectProperty(property.name,propertyValue,!!property.enumerable,!!property.writable,!!property.isOwn,!!property.wasThrown,propertySymbol);if(typeof property.value==='undefined'){if(property.get&&property.get.type!=='undefined')
remoteProperty.getter=this._runtimeModel.createRemoteObject(property.get);if(property.set&&property.set.type!=='undefined')
remoteProperty.setter=this._runtimeModel.createRemoteObject(property.set);}
result.push(remoteProperty);}
let internalPropertiesResult=null;if(internalProperties){internalPropertiesResult=[];for(let i=0;i<internalProperties.length;i++){const property=internalProperties[i];if(!property.value)
continue;const propertyValue=this._runtimeModel.createRemoteObject(property.value);internalPropertiesResult.push(new SDK.RemoteObjectProperty(property.name,propertyValue,true,false));}}
callback(result,internalPropertiesResult);}}
async setPropertyValue(name,value){if(!this._objectId)
return`Can't set a property of non-object.`;const response=await this._runtimeAgent.invoke_evaluate({expression:value,silent:true});if(response[Protocol.Error]||response.exceptionDetails){return response[Protocol.Error]||(response.result.type!=='string'?response.result.description:(response.result.value));}
if(typeof name==='string')
name=SDK.RemoteObject.toCallArgument(name);const resultPromise=this.doSetObjectPropertyValue(response.result,name);if(response.result.objectId)
this._runtimeAgent.releaseObject(response.result.objectId);return resultPromise;}
async doSetObjectPropertyValue(result,name){const setPropertyValueFunction='function(a, b) { this[a] = b; }';const argv=[name,SDK.RemoteObject.toCallArgument(result)];const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:setPropertyValueFunction,arguments:argv,silent:true});const error=response[Protocol.Error];return error||response.exceptionDetails?error||response.result.description:undefined;}
async deleteProperty(name){if(!this._objectId)
return`Can't delete a property of non-object.`;const deletePropertyFunction='function(a) { delete this[a]; return !(a in this); }';const response=await this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:deletePropertyFunction,arguments:[name],silent:true});if(response[Protocol.Error]||response.exceptionDetails)
return response[Protocol.Error]||response.result.description;if(!response.result.value)
return'Failed to delete property.';}
callFunction(functionDeclaration,args,callback){this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true}).then(response=>{if(!callback)
return;if(response[Protocol.Error])
callback(null,false);else
callback(this._runtimeModel.createRemoteObject(response.result),!!response.exceptionDetails);});}
callFunctionJSON(functionDeclaration,args,callback){this._runtimeAgent.invoke_callFunctionOn({objectId:this._objectId,functionDeclaration:functionDeclaration.toString(),arguments:args,silent:true,returnByValue:true}).then(response=>callback(response[Protocol.Error]||response.exceptionDetails?null:response.result.value));}
release(){if(!this._objectId)
return;this._runtimeAgent.releaseObject(this._objectId);}
arrayLength(){return SDK.RemoteObject.arrayLength(this);}
debuggerModel(){return this._runtimeModel.debuggerModel();}
runtimeModel(){return this._runtimeModel;}
isNode(){return!!this._objectId&&this.type==='object'&&this.subtype==='node';}};SDK.ScopeRemoteObject=class extends SDK.RemoteObjectImpl{constructor(runtimeModel,objectId,scopeRef,type,subtype,value,unserializableValue,description,preview){super(runtimeModel,objectId,type,subtype,value,unserializableValue,description,preview);this._scopeRef=scopeRef;this._savedScopeProperties=undefined;}
doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,callback){if(accessorPropertiesOnly){callback([],[]);return;}
if(this._savedScopeProperties){callback(this._savedScopeProperties.slice(),[]);return;}
function wrappedCallback(properties,internalProperties){if(this._scopeRef&&Array.isArray(properties)){this._savedScopeProperties=properties.slice();if(!this._scopeRef.callFrameId){for(const property of this._savedScopeProperties)
property.writable=false;}}
callback(properties,internalProperties);}
generatePreview=true;super.doGetProperties(ownProperties,accessorPropertiesOnly,generatePreview,wrappedCallback.bind(this));}
async doSetObjectPropertyValue(result,argumentName){const name=(argumentName.value);const error=await this.debuggerModel().setVariableValue(this._scopeRef.number,name,SDK.RemoteObject.toCallArgument(result),this._scopeRef.callFrameId);if(error)
return error;if(this._savedScopeProperties){for(const property of this._savedScopeProperties){if(property.name===name)
property.value=this._runtimeModel.createRemoteObject(result);}}}};SDK.ScopeRef=class{constructor(number,callFrameId){this.number=number;this.callFrameId=callFrameId;}};SDK.RemoteObjectProperty=class{constructor(name,value,enumerable,writable,isOwn,wasThrown,symbol,synthetic,syntheticSetter){this.name=name;if(value!==null)
this.value=value;this.enumerable=typeof enumerable!=='undefined'?enumerable:true;const isNonSyntheticOrSyntheticWritable=!synthetic||!!syntheticSetter;this.writable=typeof writable!=='undefined'?writable:isNonSyntheticOrSyntheticWritable;this.isOwn=!!isOwn;this.wasThrown=!!wasThrown;if(symbol)
this.symbol=symbol;this.synthetic=!!synthetic;if(syntheticSetter)
this.syntheticSetter=syntheticSetter;}
async setSyntheticValue(expression){if(!this.syntheticSetter)
return false;const result=await this.syntheticSetter(expression);if(result)
this.value=result;return!!result;}
isAccessorProperty(){return!!(this.getter||this.setter);}};SDK.LocalJSONObject=class extends SDK.RemoteObject{constructor(value){super();this._value=value;this._cachedDescription;this._cachedChildren;}
get objectId(){return undefined;}
get value(){return this._value;}
get description(){if(this._cachedDescription)
return this._cachedDescription;function formatArrayItem(property){return this._formatValue(property.value);}
function formatObjectItem(property){let name=property.name;if(/^\s|\s$|^$|\n/.test(name))
name='"'+name.replace(/\n/g,'\u21B5')+'"';return name+': '+this._formatValue(property.value);}
if(this.type==='object'){switch(this.subtype){case'array':this._cachedDescription=this._concatenate('[',']',formatArrayItem.bind(this));break;case'date':this._cachedDescription=''+this._value;break;case'null':this._cachedDescription='null';break;default:this._cachedDescription=this._concatenate('{','}',formatObjectItem.bind(this));}}else{this._cachedDescription=String(this._value);}
return this._cachedDescription;}
_formatValue(value){if(!value)
return'undefined';const description=value.description||'';if(value.type==='string')
return'"'+description.replace(/\n/g,'\u21B5')+'"';return description;}
_concatenate(prefix,suffix,formatProperty){const previewChars=100;let buffer=prefix;const children=this._children();for(let i=0;i<children.length;++i){const itemDescription=formatProperty(children[i]);if(buffer.length+itemDescription.length>previewChars){buffer+=',\u2026';break;}
if(i)
buffer+=', ';buffer+=itemDescription;}
buffer+=suffix;return buffer;}
get type(){return typeof this._value;}
get subtype(){if(this._value===null)
return'null';if(Array.isArray(this._value))
return'array';if(this._value instanceof Date)
return'date';return undefined;}
get hasChildren(){if((typeof this._value!=='object')||(this._value===null))
return false;return!!Object.keys((this._value)).length;}
getOwnProperties(generatePreview,callback){callback(this._children(),null);}
getAllProperties(accessorPropertiesOnly,generatePreview,callback){if(accessorPropertiesOnly)
callback([],null);else
callback(this._children(),null);}
_children(){if(!this.hasChildren)
return[];const value=(this._value);function buildProperty(propName){let propValue=value[propName];if(!(propValue instanceof SDK.RemoteObject))
propValue=SDK.RemoteObject.fromLocalObject(propValue);return new SDK.RemoteObjectProperty(propName,propValue);}
if(!this._cachedChildren)
this._cachedChildren=Object.keys(value).map(buildProperty);return this._cachedChildren;}
isError(){return false;}
arrayLength(){return Array.isArray(this._value)?this._value.length:0;}
callFunction(functionDeclaration,args,callback){const target=(this._value);const rawArgs=args?args.map(arg=>arg.value):[];let result;let wasThrown=false;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){wasThrown=true;}
if(!callback)
return;callback(SDK.RemoteObject.fromLocalObject(result),wasThrown);}
callFunctionJSON(functionDeclaration,args,callback){const target=(this._value);const rawArgs=args?args.map(arg=>arg.value):[];let result;try{result=functionDeclaration.apply(target,rawArgs);}catch(e){result=null;}
callback(result);}};SDK.RemoteArray=class{constructor(object){this._object=object;}
static objectAsArray(object){if(!object||object.type!=='object'||(object.subtype!=='array'&&object.subtype!=='typedarray'))
throw new Error('Object is empty or not an array');return new SDK.RemoteArray(object);}
static createFromRemoteObjects(objects){if(!objects.length)
throw new Error('Input array is empty');const objectArguments=[];for(let i=0;i<objects.length;++i)
objectArguments.push(SDK.RemoteObject.toCallArgument(objects[i]));return objects[0].callFunctionPromise(createArray,objectArguments).then(returnRemoteArray);function createArray(){if(arguments.length>1)
return new Array(arguments);return[arguments[0]];}
function returnRemoteArray(result){if(result.wasThrown||!result.object)
throw new Error('Call function throws exceptions or returns empty value');return SDK.RemoteArray.objectAsArray(result.object);}}
at(index){if(index<0||index>this._object.arrayLength())
throw new Error('Out of range');return this._object.callFunctionPromise(at,[SDK.RemoteObject.toCallArgument(index)]).then(assertCallFunctionResult);function at(index){return this[index];}
function assertCallFunctionResult(result){if(result.wasThrown||!result.object)
throw new Error('Exception in callFunction or result value is empty');return result.object;}}
length(){return this._object.arrayLength();}
map(func){const promises=[];for(let i=0;i<this.length();++i)
promises.push(this.at(i).then(func));return Promise.all(promises);}
object(){return this._object;}};SDK.RemoteFunction=class{constructor(object){this._object=object;}
static objectAsFunction(object){if(!object||object.type!=='function')
throw new Error('Object is empty or not a function');return new SDK.RemoteFunction(object);}
targetFunction(){return this._object.getOwnPropertiesPromise(false).then(targetFunction.bind(this));function targetFunction(ownProperties){if(!ownProperties.internalProperties)
return this._object;const internalProperties=ownProperties.internalProperties;for(const property of internalProperties){if(property.name==='[[TargetFunction]]')
return property.value;}
return this._object;}}
targetFunctionDetails(){return this.targetFunction().then(functionDetails.bind(this));function functionDetails(targetFunction){const boundReleaseFunctionDetails=releaseTargetFunction.bind(null,this._object!==targetFunction?targetFunction:null);return targetFunction.debuggerModel().functionDetailsPromise(targetFunction).then(boundReleaseFunctionDetails);}
function releaseTargetFunction(targetFunction,functionDetails){if(targetFunction)
targetFunction.release();return functionDetails;}}
object(){return this._object;}};SDK.RemoteObject._descriptionLengthParenRegex=/\(([0-9]+)\)/;SDK.RemoteObject._descriptionLengthSquareRegex=/\[([0-9]+)\]/;SDK.RemoteObject.UnserializableNumber={Negative0:('-0'),NaN:('NaN'),Infinity:('Infinity'),NegativeInfinity:('-Infinity')};;SDK.Resource=class{constructor(resourceTreeModel,request,url,documentURL,frameId,loaderId,type,mimeType,lastModified,contentSize){this._resourceTreeModel=resourceTreeModel;this._request=request;this.url=url;this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._type=type||Common.resourceTypes.Other;this._mimeType=mimeType;this._lastModified=lastModified&&lastModified.isValid()?lastModified:null;this._contentSize=contentSize;this._content;this._contentEncoded;this._pendingContentCallbacks=[];if(this._request&&!this._request.finished)
this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);}
lastModified(){if(this._lastModified||!this._request)
return this._lastModified;const lastModifiedHeader=this._request.responseLastModified();const date=lastModifiedHeader?new Date(lastModifiedHeader):null;this._lastModified=date&&date.isValid()?date:null;return this._lastModified;}
contentSize(){if(typeof this._contentSize==='number'||!this._request)
return this._contentSize;return this._request.resourceSize;}
get request(){return this._request;}
get url(){return this._url;}
set url(x){this._url=x;this._parsedURL=new Common.ParsedURL(x);}
get parsedURL(){return this._parsedURL;}
get documentURL(){return this._documentURL;}
get frameId(){return this._frameId;}
get loaderId(){return this._loaderId;}
get displayName(){return this._parsedURL.displayName;}
resourceType(){return this._request?this._request.resourceType():this._type;}
get mimeType(){return this._request?this._request.mimeType:this._mimeType;}
get content(){return this._content;}
contentURL(){return this._url;}
contentType(){if(this.resourceType()===Common.resourceTypes.Document&&this.mimeType.indexOf('javascript')!==-1)
return Common.resourceTypes.Script;return this.resourceType();}
async contentEncoded(){await this.requestContent();return this._contentEncoded;}
requestContent(){if(typeof this._content!=='undefined')
return Promise.resolve(this._content);let callback;const promise=new Promise(fulfill=>callback=fulfill);this._pendingContentCallbacks.push(callback);if(!this._request||this._request.finished)
this._innerRequestContent();return promise;}
canonicalMimeType(){return this.contentType().canonicalMimeType()||this.mimeType;}
async searchInContent(query,caseSensitive,isRegex){if(!this.frameId)
return[];if(this.request)
return this.request.searchInContent(query,caseSensitive,isRegex);const result=await this._resourceTreeModel.target().pageAgent().searchInResource(this.frameId,this.url,query,caseSensitive,isRegex);return result||[];}
populateImageSource(image){function onResourceContent(content){let imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,true);if(imageSrc===null)
imageSrc=this._url;image.src=imageSrc;}
this.requestContent().then(onResourceContent.bind(this));}
_requestFinished(){this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this._requestFinished,this);if(this._pendingContentCallbacks.length)
this._innerRequestContent();}
async _innerRequestContent(){if(this._contentRequested)
return;this._contentRequested=true;if(this.request){const contentData=await this.request.contentData();this._content=contentData.content;this._contentEncoded=contentData.encoded;}else{const response=await this._resourceTreeModel.target().pageAgent().invoke_getResourceContent({frameId:this.frameId,url:this.url});this._content=response[Protocol.Error]?null:response.content;this._contentEncoded=response.base64Encoded;}
if(this._content===null)
this._contentEncoded=false;for(const callback of this._pendingContentCallbacks.splice(0))
callback(this._content);delete this._contentRequested;}
hasTextContent(){if(this._type.isTextType())
return true;if(this._type===Common.resourceTypes.Other)
return!!this._content&&!this._contentEncoded;return false;}
frame(){return this._resourceTreeModel.frameForId(this._frameId);}};;SDK.ResourceTreeModel=class extends SDK.SDKModel{constructor(target){super(target);const networkManager=target.model(SDK.NetworkManager);if(networkManager){networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestFinished,this);networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdateDropped,this._onRequestUpdateDropped,this);}
this._agent=target.pageAgent();this._agent.enable();this._securityOriginManager=target.model(SDK.SecurityOriginManager);target.registerPageDispatcher(new SDK.PageDispatcher(this));this._frames=new Map();this._cachedResourcesProcessed=false;this._pendingReloadOptions=null;this._reloadSuspensionCount=0;this._isInterstitialShowing=false;this.mainFrame=null;this._agent.getResourceTree().then(this._processCachedResources.bind(this));}
static frameForRequest(request){const networkManager=SDK.NetworkManager.forRequest(request);const resourceTreeModel=networkManager?networkManager.target().model(SDK.ResourceTreeModel):null;if(!resourceTreeModel)
return null;return resourceTreeModel.frameForId(request.frameId);}
static frames(){let result=[];for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
result=result.concat(resourceTreeModel._frames.valuesArray());return result;}
static resourceForURL(url){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){const mainFrame=resourceTreeModel.mainFrame;const result=mainFrame?mainFrame.resourceForURL(url):null;if(result)
return result;}
return null;}
static reloadAllPages(bypassCache,scriptToEvaluateOnLoad){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){if(!resourceTreeModel.target().parentTarget())
resourceTreeModel.reloadPage(bypassCache,scriptToEvaluateOnLoad);}}
domModel(){return(this.target().model(SDK.DOMModel));}
_processCachedResources(mainFramePayload){if(mainFramePayload){this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillLoadCachedResources);this._addFramesRecursively(null,mainFramePayload);this.target().setInspectedURL(mainFramePayload.frame.url);}
this._cachedResourcesProcessed=true;const runtimeModel=this.target().model(SDK.RuntimeModel);if(runtimeModel){runtimeModel.setExecutionContextComparator(this._executionContextComparator.bind(this));runtimeModel.fireExecutionContextOrderChanged();}
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,this);}
cachedResourcesLoaded(){return this._cachedResourcesProcessed;}
isInterstitialShowing(){return this._isInterstitialShowing;}
_addFrame(frame,aboutToNavigate){this._frames.set(frame.id,frame);if(frame.isMainFrame())
this.mainFrame=frame;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameAdded,frame);this._updateSecurityOrigins();}
_frameAttached(frameId,parentFrameId,stackTrace){const parentFrame=parentFrameId?(this._frames.get(parentFrameId)||null):null;if(!this._cachedResourcesProcessed&&parentFrame)
return null;if(this._frames.has(frameId))
return null;const frame=new SDK.ResourceTreeFrame(this,parentFrame,frameId,null,stackTrace||null);if(parentFrameId&&!parentFrame)
frame._crossTargetParentFrameId=parentFrameId;if(frame.isMainFrame()&&this.mainFrame){this._frameDetached(this.mainFrame.id);}
this._addFrame(frame,true);return frame;}
_frameNavigated(framePayload){const parentFrame=framePayload.parentId?(this._frames.get(framePayload.parentId)||null):null;if(!this._cachedResourcesProcessed&&parentFrame)
return;let frame=this._frames.get(framePayload.id);if(!frame){frame=this._frameAttached(framePayload.id,framePayload.parentId||'');console.assert(frame);}
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameWillNavigate,frame);frame._navigate(framePayload);this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameNavigated,frame);if(frame.isMainFrame())
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.MainFrameNavigated,frame);const resources=frame.resources();for(let i=0;i<resources.length;++i)
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resources[i]);if(frame.isMainFrame())
this.target().setInspectedURL(frame.url);this._updateSecurityOrigins();}
_frameDetached(frameId){if(!this._cachedResourcesProcessed)
return;const frame=this._frames.get(frameId);if(!frame)
return;if(frame.parentFrame)
frame.parentFrame._removeChildFrame(frame);else
frame._remove();this._updateSecurityOrigins();}
_onRequestFinished(event){if(!this._cachedResourcesProcessed)
return;const request=(event.data);if(request.failed||request.resourceType()===Common.resourceTypes.XHR)
return;const frame=this._frames.get(request.frameId);if(frame)
frame._addRequest(request);}
_onRequestUpdateDropped(event){if(!this._cachedResourcesProcessed)
return;const frameId=event.data.frameId;const frame=this._frames.get(frameId);if(!frame)
return;const url=event.data.url;if(frame._resourcesMap[url])
return;const resource=new SDK.Resource(this,null,url,frame.url,frameId,event.data.loaderId,Common.resourceTypes[event.data.resourceType],event.data.mimeType,event.data.lastModified,null);frame.addResource(resource);}
frameForId(frameId){return this._frames.get(frameId);}
forAllResources(callback){if(this.mainFrame)
return this.mainFrame._callForFrameResources(callback);return false;}
frames(){return this._frames.valuesArray();}
resourceForURL(url){return this.mainFrame?this.mainFrame.resourceForURL(url):null;}
_addFramesRecursively(parentFrame,frameTreePayload){const framePayload=frameTreePayload.frame;const frame=new SDK.ResourceTreeFrame(this,parentFrame,framePayload.id,framePayload,null);if(!parentFrame&&framePayload.parentId)
frame._crossTargetParentFrameId=framePayload.parentId;this._addFrame(frame);for(let i=0;frameTreePayload.childFrames&&i<frameTreePayload.childFrames.length;++i)
this._addFramesRecursively(frame,frameTreePayload.childFrames[i]);for(let i=0;i<frameTreePayload.resources.length;++i){const subresource=frameTreePayload.resources[i];const resource=this._createResourceFromFramePayload(framePayload,subresource.url,Common.resourceTypes[subresource.type],subresource.mimeType,subresource.lastModified||null,subresource.contentSize||null);frame.addResource(resource);}
if(!frame._resourcesMap[framePayload.url]){const frameResource=this._createResourceFromFramePayload(framePayload,framePayload.url,Common.resourceTypes.Document,framePayload.mimeType,null,null);frame.addResource(frameResource);}}
_createResourceFromFramePayload(frame,url,type,mimeType,lastModifiedTime,contentSize){const lastModified=typeof lastModifiedTime==='number'?new Date(lastModifiedTime*1000):null;return new SDK.Resource(this,null,url,frame.url,frame.id,frame.loaderId,type,mimeType,lastModified,contentSize);}
suspendReload(){this._reloadSuspensionCount++;}
resumeReload(){this._reloadSuspensionCount--;console.assert(this._reloadSuspensionCount>=0,'Unbalanced call to ResourceTreeModel.resumeReload()');if(!this._reloadSuspensionCount&&this._pendingReloadOptions)
this.reloadPage.apply(this,this._pendingReloadOptions);}
reloadPage(bypassCache,scriptToEvaluateOnLoad){if(!this._pendingReloadOptions)
this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.PageReloadRequested,this);if(this._reloadSuspensionCount){this._pendingReloadOptions=[bypassCache,scriptToEvaluateOnLoad];return;}
this._pendingReloadOptions=null;this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.WillReloadPage);this._agent.reload(bypassCache,scriptToEvaluateOnLoad);}
navigate(url){return this._agent.navigate(url);}
async navigationHistory(){const response=await this._agent.invoke_getNavigationHistory({});if(response[Protocol.Error])
return null;return{currentIndex:response.currentIndex,entries:response.entries};}
navigateToHistoryEntry(entry){this._agent.navigateToHistoryEntry(entry.id);}
async fetchAppManifest(callback){const response=await this._agent.invoke_getAppManifest({});if(response[Protocol.Error])
callback(response.url,null,[]);else
callback(response.url,response.data||null,response.errors);}
_executionContextComparator(a,b){function framePath(frame){let currentFrame=frame;const parents=[];while(currentFrame){parents.push(currentFrame);currentFrame=currentFrame.parentFrame;}
return parents.reverse();}
if(a.target()!==b.target())
return SDK.ExecutionContext.comparator(a,b);const framesA=a.frameId?framePath(this.frameForId(a.frameId)):[];const framesB=b.frameId?framePath(this.frameForId(b.frameId)):[];let frameA;let frameB;for(let i=0;;i++){if(!framesA[i]||!framesB[i]||(framesA[i]!==framesB[i])){frameA=framesA[i];frameB=framesB[i];break;}}
if(!frameA&&frameB)
return-1;if(!frameB&&frameA)
return 1;if(frameA&&frameB)
return frameA.id.localeCompare(frameB.id);return SDK.ExecutionContext.comparator(a,b);}
_updateSecurityOrigins(){const securityOrigins=new Set();let mainSecurityOrigin=null;for(const frame of this._frames.values()){const origin=frame.securityOrigin;if(!origin)
continue;securityOrigins.add(origin);if(frame.isMainFrame())
mainSecurityOrigin=origin;}
this._securityOriginManager.updateSecurityOrigins(securityOrigins);this._securityOriginManager.setMainSecurityOrigin(mainSecurityOrigin||'');}};SDK.SDKModel.register(SDK.ResourceTreeModel,SDK.Target.Capability.DOM,true);SDK.ResourceTreeModel.Events={FrameAdded:Symbol('FrameAdded'),FrameNavigated:Symbol('FrameNavigated'),FrameDetached:Symbol('FrameDetached'),FrameResized:Symbol('FrameResized'),FrameWillNavigate:Symbol('FrameWillNavigate'),MainFrameNavigated:Symbol('MainFrameNavigated'),ResourceAdded:Symbol('ResourceAdded'),WillLoadCachedResources:Symbol('WillLoadCachedResources'),CachedResourcesLoaded:Symbol('CachedResourcesLoaded'),DOMContentLoaded:Symbol('DOMContentLoaded'),LifecycleEvent:Symbol('LifecycleEvent'),Load:Symbol('Load'),PageReloadRequested:Symbol('PageReloadRequested'),WillReloadPage:Symbol('WillReloadPage'),InterstitialShown:Symbol('InterstitialShown'),InterstitialHidden:Symbol('InterstitialHidden')};SDK.ResourceTreeFrame=class{constructor(model,parentFrame,frameId,payload,creationStackTrace){this._model=model;this._parentFrame=parentFrame;this._id=frameId;this._url='';this._crossTargetParentFrameId=null;if(payload){this._loaderId=payload.loaderId;this._name=payload.name;this._url=payload.url;this._securityOrigin=payload.securityOrigin;this._mimeType=payload.mimeType;}
this._creationStackTrace=creationStackTrace;this._childFrames=[];this._resourcesMap={};if(this._parentFrame)
this._parentFrame._childFrames.push(this);}
resourceTreeModel(){return this._model;}
get id(){return this._id;}
get name(){return this._name||'';}
get url(){return this._url;}
get securityOrigin(){return this._securityOrigin;}
get loaderId(){return this._loaderId;}
get parentFrame(){return this._parentFrame;}
get childFrames(){return this._childFrames;}
crossTargetParentFrame(){if(!this._crossTargetParentFrameId)
return null;if(!this._model.target().parentTarget())
return null;const parentModel=this._model.target().parentTarget().model(SDK.ResourceTreeModel);if(!parentModel)
return null;return parentModel._frames.get(this._crossTargetParentFrameId)||null;}
findCreationCallFrame(searchFn){let stackTrace=this._creationStackTrace;while(stackTrace){const foundEntry=stackTrace.callFrames.find(searchFn);if(foundEntry)
return foundEntry;stackTrace=this.parent;}
return null;}
isMainFrame(){return!this._parentFrame;}
isTopFrame(){return!this._parentFrame&&!this._crossTargetParentFrameId;}
_navigate(framePayload){this._loaderId=framePayload.loaderId;this._name=framePayload.name;this._url=framePayload.url;this._securityOrigin=framePayload.securityOrigin;this._mimeType=framePayload.mimeType;const mainResource=this._resourcesMap[this._url];this._resourcesMap={};this._removeChildFrames();if(mainResource&&mainResource.loaderId===this._loaderId)
this.addResource(mainResource);}
get mainResource(){return this._resourcesMap[this._url];}
_removeChildFrame(frame){this._childFrames.remove(frame);frame._remove();}
_removeChildFrames(){const frames=this._childFrames;this._childFrames=[];for(let i=0;i<frames.length;++i)
frames[i]._remove();}
_remove(){this._removeChildFrames();this._model._frames.delete(this.id);this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameDetached,this);}
addResource(resource){if(this._resourcesMap[resource.url]===resource){return;}
this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);}
_addRequest(request){let resource=this._resourcesMap[request.url()];if(resource&&resource.request===request){return;}
resource=new SDK.Resource(this._model,request,request.url(),request.documentURL,request.frameId,request.loaderId,request.resourceType(),request.mimeType,null,null);this._resourcesMap[resource.url]=resource;this._model.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded,resource);}
resources(){const result=[];for(const url in this._resourcesMap)
result.push(this._resourcesMap[url]);return result;}
resourceForURL(url){let resource=this._resourcesMap[url]||null;if(resource)
return resource;for(let i=0;!resource&&i<this._childFrames.length;++i)
resource=this._childFrames[i].resourceForURL(url);return resource;}
_callForFrameResources(callback){for(const url in this._resourcesMap){if(callback(this._resourcesMap[url]))
return true;}
for(let i=0;i<this._childFrames.length;++i){if(this._childFrames[i]._callForFrameResources(callback))
return true;}
return false;}
displayName(){if(this.isTopFrame())
return Common.UIString('top');const subtitle=new Common.ParsedURL(this._url).displayName;if(subtitle){if(!this._name)
return subtitle;return this._name+' ('+subtitle+')';}
return Common.UIString('<iframe>');}};SDK.PageDispatcher=class{constructor(resourceTreeModel){this._resourceTreeModel=resourceTreeModel;}
domContentEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.DOMContentLoaded,time);}
loadEventFired(time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.Load,{resourceTreeModel:this._resourceTreeModel,loadTime:time});}
lifecycleEvent(frameId,loaderId,name,time){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.LifecycleEvent,{frameId,name});}
frameAttached(frameId,parentFrameId,stackTrace){this._resourceTreeModel._frameAttached(frameId,parentFrameId,stackTrace);}
frameNavigated(frame){this._resourceTreeModel._frameNavigated(frame);}
frameDetached(frameId){this._resourceTreeModel._frameDetached(frameId);}
frameStartedLoading(frameId){}
frameStoppedLoading(frameId){}
frameScheduledNavigation(frameId,delay){}
frameClearedScheduledNavigation(frameId){}
navigatedWithinDocument(frameId,url){}
frameResized(){this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameResized,null);}
javascriptDialogOpening(url,message,dialogType,hasBrowserHandler,prompt){if(!hasBrowserHandler)
this._resourceTreeModel._agent.handleJavaScriptDialog(false);}
javascriptDialogClosed(result,userInput){}
screencastFrame(data,metadata,sessionId){}
screencastVisibilityChanged(visible){}
interstitialShown(){this._resourceTreeModel._isInterstitialShowing=true;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialShown);}
interstitialHidden(){this._resourceTreeModel._isInterstitialShowing=false;this._resourceTreeModel.dispatchEventToListeners(SDK.ResourceTreeModel.Events.InterstitialHidden);}
windowOpen(url,windowName,windowFeatures,userGesture){}};;SDK.SecurityOriginManager=class extends SDK.SDKModel{constructor(target){super(target);this._securityOrigins=new Set();this._mainSecurityOrigin='';}
updateSecurityOrigins(securityOrigins){const oldOrigins=this._securityOrigins;this._securityOrigins=securityOrigins;for(const origin of oldOrigins){if(!this._securityOrigins.has(origin))
this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginRemoved,origin);}
for(const origin of this._securityOrigins){if(!oldOrigins.has(origin))
this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginAdded,origin);}}
securityOrigins(){return this._securityOrigins.valuesArray();}
mainSecurityOrigin(){return this._mainSecurityOrigin;}
setMainSecurityOrigin(securityOrigin){this._mainSecurityOrigin=securityOrigin;this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.MainSecurityOriginChanged,securityOrigin);}};SDK.SDKModel.register(SDK.SecurityOriginManager,SDK.Target.Capability.None,false);SDK.SecurityOriginManager.Events={SecurityOriginAdded:Symbol('SecurityOriginAdded'),SecurityOriginRemoved:Symbol('SecurityOriginRemoved'),MainSecurityOriginChanged:Symbol('MainSecurityOriginChanged')};;SDK.SourceMapV3=class{constructor(){this.version;this.file;this.sources;this.sections;this.mappings;this.sourceRoot;this.names;}};SDK.SourceMapV3.Section=class{constructor(){this.map;this.offset;}};SDK.SourceMapV3.Offset=class{constructor(){this.line;this.column;}};SDK.SourceMapEntry=class{constructor(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,name){this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.sourceURL=sourceURL;this.sourceLineNumber=sourceLineNumber;this.sourceColumnNumber=sourceColumnNumber;this.name=name;}
static compare(entry1,entry2){if(entry1.lineNumber!==entry2.lineNumber)
return entry1.lineNumber-entry2.lineNumber;return entry1.columnNumber-entry2.columnNumber;}};SDK.SourceMap=function(){};SDK.SourceMap.prototype={compiledURL(){},url(){},sourceURLs(){},sourceContentProvider(sourceURL,contentType){},embeddedContentByURL(sourceURL){},findEntry(lineNumber,columnNumber){},editable(){},editCompiled(ranges,texts){},};SDK.SourceMap.EditResult=class{constructor(map,compiledEdits,newSources){this.map=map;this.compiledEdits=compiledEdits;this.newSources=newSources;}};SDK.SourceMapFactory=function(){};SDK.SourceMapFactory.prototype={editableSourceMap(target,sourceMap){},};SDK.TextSourceMap=class{constructor(compiledURL,sourceMappingURL,payload){if(!SDK.TextSourceMap._base64Map){const base64Digits='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';SDK.TextSourceMap._base64Map={};for(let i=0;i<base64Digits.length;++i)
SDK.TextSourceMap._base64Map[base64Digits.charAt(i)]=i;}
this._json=payload;this._compiledURL=compiledURL;this._sourceMappingURL=sourceMappingURL;this._baseURL=sourceMappingURL.startsWith('data:')?compiledURL:sourceMappingURL;this._mappings=null;this._sourceInfos=new Map();this._eachSection(this._parseSources.bind(this));}
static load(sourceMapURL,compiledURL){let callback;const promise=new Promise(fulfill=>callback=fulfill);SDK.multitargetNetworkManager.loadResource(sourceMapURL,contentLoaded);return promise;function contentLoaded(statusCode,headers,content){if(!content||statusCode>=400){callback(null);return;}
if(content.slice(0,3)===')]}')
content=content.substring(content.indexOf('\n'));try{const payload=(JSON.parse(content));callback(new SDK.TextSourceMap(compiledURL,sourceMapURL,payload));}catch(e){console.error(e);Common.console.warn('DevTools failed to parse SourceMap: '+sourceMapURL);callback(null);}}}
compiledURL(){return this._compiledURL;}
url(){return this._sourceMappingURL;}
sourceURLs(){return this._sourceInfos.keysArray();}
sourceContentProvider(sourceURL,contentType){const info=this._sourceInfos.get(sourceURL);if(info.content)
return Common.StaticContentProvider.fromString(sourceURL,contentType,info.content);return new SDK.CompilerSourceMappingContentProvider(sourceURL,contentType);}
embeddedContentByURL(sourceURL){if(!this._sourceInfos.has(sourceURL))
return null;return this._sourceInfos.get(sourceURL).content;}
editable(){return false;}
editCompiled(ranges,texts){return Promise.resolve((null));}
findEntry(lineNumber,columnNumber){const mappings=this.mappings();const index=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.lineNumber||columnNumber-entry.columnNumber);return index?mappings[index-1]:null;}
sourceLineMapping(sourceURL,lineNumber,columnNumber){const mappings=this._reversedMappings(sourceURL);const first=mappings.lowerBound(lineNumber,lineComparator);const last=mappings.upperBound(lineNumber,lineComparator);if(first>=mappings.length||mappings[first].sourceLineNumber!==lineNumber)
return null;const columnMappings=mappings.slice(first,last);const index=columnMappings.lowerBound(columnNumber,(columnNumber,mapping)=>columnNumber-mapping.sourceColumnNumber);if(index>=columnMappings.length)
return null;return columnMappings[index];function lineComparator(lineNumber,mapping){return lineNumber-mapping.sourceLineNumber;}}
findReverseEntries(sourceURL,lineNumber,columnNumber){const mappings=this._reversedMappings(sourceURL);const endIndex=mappings.upperBound(undefined,(unused,entry)=>lineNumber-entry.sourceLineNumber||columnNumber-entry.sourceColumnNumber);let startIndex=endIndex;while(startIndex>0&&mappings[startIndex-1].sourceLineNumber===mappings[endIndex-1].sourceLineNumber&&mappings[startIndex-1].sourceColumnNumber===mappings[endIndex-1].sourceColumnNumber)
--startIndex;return mappings.slice(startIndex,endIndex);}
mappings(){if(this._mappings===null){this._mappings=[];this._eachSection(this._parseMap.bind(this));this._json=null;}
return(this._mappings);}
_reversedMappings(sourceURL){if(!this._sourceInfos.has(sourceURL))
return[];const mappings=this.mappings();const info=this._sourceInfos.get(sourceURL);if(info.reverseMappings===null)
info.reverseMappings=mappings.filter(mapping=>mapping.sourceURL===sourceURL).sort(sourceMappingComparator);return info.reverseMappings;function sourceMappingComparator(a,b){if(a.sourceLineNumber!==b.sourceLineNumber)
return a.sourceLineNumber-b.sourceLineNumber;if(a.sourceColumnNumber!==b.sourceColumnNumber)
return a.sourceColumnNumber-b.sourceColumnNumber;if(a.lineNumber!==b.lineNumber)
return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}}
_eachSection(callback){if(!this._json.sections){callback(this._json,0,0);return;}
for(const section of this._json.sections)
callback(section.map,section.offset.line,section.offset.column);}
_parseSources(sourceMap){const sourcesList=[];let sourceRoot=sourceMap.sourceRoot||'';if(sourceRoot&&!sourceRoot.endsWith('/'))
sourceRoot+='/';for(let i=0;i<sourceMap.sources.length;++i){const href=sourceRoot+sourceMap.sources[i];let url=Common.ParsedURL.completeURL(this._baseURL,href)||href;const source=sourceMap.sourcesContent&&sourceMap.sourcesContent[i];if(url===this._compiledURL&&source)
url+=Common.UIString('? [sm]');this._sourceInfos.set(url,new SDK.TextSourceMap.SourceInfo(source,null));sourcesList.push(url);}
sourceMap[SDK.TextSourceMap._sourcesListSymbol]=sourcesList;}
_parseMap(map,lineNumber,columnNumber){let sourceIndex=0;let sourceLineNumber=0;let sourceColumnNumber=0;let nameIndex=0;const sources=map[SDK.TextSourceMap._sourcesListSymbol];const names=map.names||[];const stringCharIterator=new SDK.TextSourceMap.StringCharIterator(map.mappings);let sourceURL=sources[sourceIndex];while(true){if(stringCharIterator.peek()===','){stringCharIterator.next();}else{while(stringCharIterator.peek()===';'){lineNumber+=1;columnNumber=0;stringCharIterator.next();}
if(!stringCharIterator.hasNext())
break;}
columnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber));continue;}
const sourceIndexDelta=this._decodeVLQ(stringCharIterator);if(sourceIndexDelta){sourceIndex+=sourceIndexDelta;sourceURL=sources[sourceIndex];}
sourceLineNumber+=this._decodeVLQ(stringCharIterator);sourceColumnNumber+=this._decodeVLQ(stringCharIterator);if(!stringCharIterator.hasNext()||this._isSeparator(stringCharIterator.peek())){this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber));continue;}
nameIndex+=this._decodeVLQ(stringCharIterator);this._mappings.push(new SDK.SourceMapEntry(lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber,names[nameIndex]));}
this._mappings.stableSort(SDK.SourceMapEntry.compare);}
_isSeparator(char){return char===','||char===';';}
_decodeVLQ(stringCharIterator){let result=0;let shift=0;let digit;do{digit=SDK.TextSourceMap._base64Map[stringCharIterator.next()];result+=(digit&SDK.TextSourceMap._VLQ_BASE_MASK)<<shift;shift+=SDK.TextSourceMap._VLQ_BASE_SHIFT;}while(digit&SDK.TextSourceMap._VLQ_CONTINUATION_MASK);const negative=result&1;result>>=1;return negative?-result:result;}
reverseMapTextRange(url,textRange){function comparator(position,mapping){if(position.lineNumber!==mapping.sourceLineNumber)
return position.lineNumber-mapping.sourceLineNumber;return position.columnNumber-mapping.sourceColumnNumber;}
const mappings=this._reversedMappings(url);const startIndex=mappings.lowerBound({lineNumber:textRange.startLine,columnNumber:textRange.startColumn},comparator);const endIndex=mappings.upperBound({lineNumber:textRange.endLine,columnNumber:textRange.endColumn},comparator);const startMapping=mappings[startIndex];const endMapping=mappings[endIndex];return new TextUtils.TextRange(startMapping.lineNumber,startMapping.columnNumber,endMapping.lineNumber,endMapping.columnNumber);}};SDK.TextSourceMap._VLQ_BASE_SHIFT=5;SDK.TextSourceMap._VLQ_BASE_MASK=(1<<5)-1;SDK.TextSourceMap._VLQ_CONTINUATION_MASK=1<<5;SDK.TextSourceMap.StringCharIterator=class{constructor(string){this._string=string;this._position=0;}
next(){return this._string.charAt(this._position++);}
peek(){return this._string.charAt(this._position);}
hasNext(){return this._position<this._string.length;}};SDK.TextSourceMap.SourceInfo=class{constructor(content,reverseMappings){this.content=content;this.reverseMappings=reverseMappings;}};SDK.TextSourceMap._sourcesListSymbol=Symbol('sourcesList');;SDK.SourceMapManager=class extends Common.Object{constructor(target){super();this._target=target;this._isEnabled=true;this._relativeSourceURL=new Map();this._relativeSourceMapURL=new Map();this._resolvedSourceMapURL=new Map();this._sourceMapByURL=new Map();this._sourceMapURLToLoadingClients=new Multimap();this._sourceMapURLToClients=new Multimap();SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);}
setEnabled(isEnabled){if(isEnabled===this._isEnabled)
return;this._isEnabled=isEnabled;const clients=Array.from(this._resolvedSourceMapURL.keys());for(const client of clients){const relativeSourceURL=this._relativeSourceURL.get(client);const relativeSourceMapURL=this._relativeSourceMapURL.get(client);this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}}
_inspectedURLChanged(event){if(event.data!==this._target)
return;const clients=Array.from(this._resolvedSourceMapURL.keys());for(const client of clients){const relativeSourceURL=this._relativeSourceURL.get(client);const relativeSourceMapURL=this._relativeSourceMapURL.get(client);const resolvedSourceMapURL=this._resolvedSourceMapURL.get(client);const sourceMapURL=this._resolveRelativeURLs(relativeSourceURL,relativeSourceMapURL).sourceMapURL;if(sourceMapURL!==resolvedSourceMapURL){this.detachSourceMap(client);this.attachSourceMap(client,relativeSourceURL,relativeSourceMapURL);}}}
sourceMapForClient(client){const sourceMapURL=this._resolvedSourceMapURL.get(client);return sourceMapURL?this._sourceMapByURL.get(sourceMapURL)||null:null;}
clientsForSourceMap(sourceMap){if(this._sourceMapURLToClients.has(sourceMap.url()))
return this._sourceMapURLToClients.get(sourceMap.url()).valuesArray();return this._sourceMapURLToLoadingClients.get(sourceMap.url()).valuesArray();}
applySourceMapEdit(editResult){console.assert(this._sourceMapByURL.has(editResult.map.url()),'Cannot apply edit result for non-existing source map');this._sourceMapByURL.set(editResult.map.url(),editResult.map);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapChanged,{sourceMap:editResult.map,newSources:editResult.newSources});}
_resolveRelativeURLs(sourceURL,sourceMapURL){const resolvedSourceURL=Common.ParsedURL.completeURL(this._target.inspectedURL(),sourceURL);const resolvedSourceMapURL=resolvedSourceURL?Common.ParsedURL.completeURL(resolvedSourceURL,sourceMapURL):null;return{sourceURL:resolvedSourceURL,sourceMapURL:resolvedSourceMapURL};}
attachSourceMap(client,sourceURL,sourceMapURL){if(!sourceMapURL)
return;console.assert(!this._resolvedSourceMapURL.has(client),'SourceMap is already attached to client');const resolvedURLs=this._resolveRelativeURLs(sourceURL,sourceMapURL);if(!resolvedURLs.sourceURL||!resolvedURLs.sourceMapURL)
return;this._relativeSourceURL.set(client,sourceURL);this._relativeSourceMapURL.set(client,sourceMapURL);this._resolvedSourceMapURL.set(client,resolvedURLs.sourceMapURL);sourceURL=resolvedURLs.sourceURL;sourceMapURL=resolvedURLs.sourceMapURL;if(!this._isEnabled)
return;this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapWillAttach,client);if(this._sourceMapByURL.has(sourceMapURL)){attach.call(this,sourceMapURL,client);return;}
if(!this._sourceMapURLToLoadingClients.has(sourceMapURL)){SDK.TextSourceMap.load(sourceMapURL,sourceURL).then(onTextSourceMapLoaded.bind(this,sourceMapURL)).then(onSourceMap.bind(this,sourceMapURL));}
this._sourceMapURLToLoadingClients.set(sourceMapURL,client);function onTextSourceMapLoaded(sourceMapURL,sourceMap){if(!sourceMap)
return Promise.resolve((null));const factoryExtension=this._factoryForSourceMap(sourceMap);if(!factoryExtension)
return Promise.resolve((sourceMap));return factoryExtension.instance().then(factory=>factory.editableSourceMap(this._target,sourceMap)).then(map=>map||sourceMap).catchException((null));}
function onSourceMap(sourceMapURL,sourceMap){this._sourceMapLoadedForTest();const clients=this._sourceMapURLToLoadingClients.get(sourceMapURL);this._sourceMapURLToLoadingClients.deleteAll(sourceMapURL);if(!clients.size)
return;if(!sourceMap){for(const client of clients)
this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;}
this._sourceMapByURL.set(sourceMapURL,sourceMap);for(const client of clients)
attach.call(this,sourceMapURL,client);}
function attach(sourceMapURL,client){this._sourceMapURLToClients.set(sourceMapURL,client);const sourceMap=this._sourceMapByURL.get(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapAttached,{client:client,sourceMap:sourceMap});}}
_factoryForSourceMap(sourceMap){const sourceExtensions=new Set();for(const url of sourceMap.sourceURLs())
sourceExtensions.add(Common.ParsedURL.extractExtension(url));for(const runtimeExtension of self.runtime.extensions(SDK.SourceMapFactory)){const supportedExtensions=new Set(runtimeExtension.descriptor()['extensions']);if(supportedExtensions.containsAll(sourceExtensions))
return runtimeExtension;}
return null;}
detachSourceMap(client){const sourceMapURL=this._resolvedSourceMapURL.get(client);this._relativeSourceURL.delete(client);this._relativeSourceMapURL.delete(client);this._resolvedSourceMapURL.delete(client);if(!sourceMapURL)
return;if(!this._sourceMapURLToClients.hasValue(sourceMapURL,client)){if(this._sourceMapURLToLoadingClients.delete(sourceMapURL,client))
this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach,client);return;}
this._sourceMapURLToClients.delete(sourceMapURL,client);const sourceMap=this._sourceMapByURL.get(sourceMapURL);if(!this._sourceMapURLToClients.has(sourceMapURL))
this._sourceMapByURL.delete(sourceMapURL);this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapDetached,{client:client,sourceMap:sourceMap});}
_sourceMapLoadedForTest(){}
dispose(){SDK.targetManager.removeEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);}};SDK.SourceMapManager.Events={SourceMapWillAttach:Symbol('SourceMapWillAttach'),SourceMapFailedToAttach:Symbol('SourceMapFailedToAttach'),SourceMapAttached:Symbol('SourceMapAttached'),SourceMapDetached:Symbol('SourceMapDetached'),SourceMapChanged:Symbol('SourceMapChanged')};;SDK.NetworkManager=class extends SDK.SDKModel{constructor(target){super(target);this._dispatcher=new SDK.NetworkDispatcher(this);this._networkAgent=target.networkAgent();target.registerNetworkDispatcher(this._dispatcher);if(Common.moduleSetting('cacheDisabled').get())
this._networkAgent.setCacheDisabled(true);this._networkAgent.enable(undefined,undefined,SDK.NetworkManager.MAX_EAGER_POST_REQUEST_BODY_LENGTH);this._bypassServiceWorkerSetting=Common.settings.createSetting('bypassServiceWorker',false);if(this._bypassServiceWorkerSetting.get())
this._bypassServiceWorkerChanged();this._bypassServiceWorkerSetting.addChangeListener(this._bypassServiceWorkerChanged,this);Common.moduleSetting('cacheDisabled').addChangeListener(this._cacheDisabledSettingChanged,this);}
static forRequest(request){return request[SDK.NetworkManager._networkManagerForRequestSymbol];}
static canReplayRequest(request){return!!request[SDK.NetworkManager._networkManagerForRequestSymbol]&&request.resourceType()===Common.resourceTypes.XHR;}
static replayRequest(request){const manager=request[SDK.NetworkManager._networkManagerForRequestSymbol];if(!manager)
return;manager._networkAgent.replayXHR(request.requestId());}
static async searchInRequest(request,query,caseSensitive,isRegex){const manager=SDK.NetworkManager.forRequest(request);if(!manager)
return[];const response=await manager._networkAgent.invoke_searchInResponseBody({requestId:request.requestId(),query:query,caseSensitive:caseSensitive,isRegex:isRegex});return response.result||[];}
static async requestContentData(request){if(request.resourceType()===Common.resourceTypes.WebSocket)
return{error:'Content for WebSockets is currently not supported',content:null,encoded:false};if(!request.finished)
await request.once(SDK.NetworkRequest.Events.FinishedLoading);const manager=SDK.NetworkManager.forRequest(request);if(!manager)
return{error:'No network manager for request',content:null,encoded:false};const response=await manager._networkAgent.invoke_getResponseBody({requestId:request.requestId()});const error=response[Protocol.Error]||null;return{error:error,content:error?null:response.body,encoded:response.base64Encoded};}
static requestPostData(request){const manager=SDK.NetworkManager.forRequest(request);if(manager)
return manager._networkAgent.getRequestPostData(request.backendRequestId());console.error('No network manager for request');return(Promise.resolve(null));}
static _connectionType(conditions){if(!conditions.download&&!conditions.upload)
return Protocol.Network.ConnectionType.None;let types=SDK.NetworkManager._connectionTypes;if(!types){SDK.NetworkManager._connectionTypes=[];types=SDK.NetworkManager._connectionTypes;types.push(['2g',Protocol.Network.ConnectionType.Cellular2g]);types.push(['3g',Protocol.Network.ConnectionType.Cellular3g]);types.push(['4g',Protocol.Network.ConnectionType.Cellular4g]);types.push(['bluetooth',Protocol.Network.ConnectionType.Bluetooth]);types.push(['wifi',Protocol.Network.ConnectionType.Wifi]);types.push(['wimax',Protocol.Network.ConnectionType.Wimax]);}
for(const type of types){if(conditions.title.toLowerCase().indexOf(type[0])!==-1)
return type[1];}
return Protocol.Network.ConnectionType.Other;}
static lowercaseHeaders(headers){const newHeaders={};for(const headerName in headers)
newHeaders[headerName.toLowerCase()]=headers[headerName];return newHeaders;}
inflightRequestForURL(url){return this._dispatcher._inflightRequestsByURL[url];}
_cacheDisabledSettingChanged(event){const enabled=(event.data);this._networkAgent.setCacheDisabled(enabled);}
dispose(){Common.moduleSetting('cacheDisabled').removeChangeListener(this._cacheDisabledSettingChanged,this);}
_bypassServiceWorkerChanged(){this._networkAgent.setBypassServiceWorker(this._bypassServiceWorkerSetting.get());}};SDK.SDKModel.register(SDK.NetworkManager,SDK.Target.Capability.Network,true);SDK.NetworkManager.Events={RequestStarted:Symbol('RequestStarted'),RequestUpdated:Symbol('RequestUpdated'),RequestFinished:Symbol('RequestFinished'),RequestUpdateDropped:Symbol('RequestUpdateDropped'),ResponseReceived:Symbol('ResponseReceived'),MessageGenerated:Symbol('MessageGenerated'),RequestRedirected:Symbol('RequestRedirected'),};SDK.NetworkManager.Message;SDK.NetworkManager._MIMETypes={'text/html':{'document':true},'text/xml':{'document':true},'text/plain':{'document':true},'application/xhtml+xml':{'document':true},'image/svg+xml':{'document':true},'text/css':{'stylesheet':true},'text/xsl':{'stylesheet':true},'text/vtt':{'texttrack':true},};SDK.NetworkManager.Conditions;SDK.NetworkManager.NoThrottlingConditions={title:Common.UIString('Online'),download:-1,upload:-1,latency:0};SDK.NetworkManager.OfflineConditions={title:Common.UIString('Offline'),download:0,upload:0,latency:0,};SDK.NetworkManager.Slow3GConditions={title:Common.UIString('Slow 3G'),download:500*1024/8*.8,upload:500*1024/8*.8,latency:400*5,};SDK.NetworkManager.Fast3GConditions={title:Common.UIString('Fast 3G'),download:1.6*1024*1024/8*.9,upload:750*1024/8*.9,latency:150*3.75,};SDK.NetworkManager.BlockedPattern;SDK.NetworkManager._networkManagerForRequestSymbol=Symbol('NetworkManager');SDK.NetworkManager.MAX_EAGER_POST_REQUEST_BODY_LENGTH=64*1024;SDK.NetworkDispatcher=class{constructor(manager){this._manager=manager;this._inflightRequestsById={};this._inflightRequestsByURL={};}
_headersMapToHeadersArray(headersMap){const result=[];for(const name in headersMap){const values=headersMap[name].split('\n');for(let i=0;i<values.length;++i)
result.push({name:name,value:values[i]});}
return result;}
_updateNetworkRequestWithRequest(networkRequest,request){networkRequest.requestMethod=request.method;networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setRequestFormData(!!request.hasPostData,request.postData||null);networkRequest.setInitialPriority(request.initialPriority);networkRequest.mixedContentType=request.mixedContentType||Protocol.Security.MixedContentType.None;networkRequest.setReferrerPolicy(request.referrerPolicy);}
_updateNetworkRequestWithResponse(networkRequest,response){if(response.url&&networkRequest.url()!==response.url)
networkRequest.setUrl(response.url);networkRequest.mimeType=response.mimeType;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);if(response.encodedDataLength>=0)
networkRequest.setTransferSize(response.encodedDataLength);if(response.headersText)
networkRequest.responseHeadersText=response.headersText;if(response.requestHeaders){networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));networkRequest.setRequestHeadersText(response.requestHeadersText||'');}
networkRequest.connectionReused=response.connectionReused;networkRequest.connectionId=String(response.connectionId);if(response.remoteIPAddress)
networkRequest.setRemoteAddress(response.remoteIPAddress,response.remotePort||-1);if(response.fromServiceWorker)
networkRequest.fetchedViaServiceWorker=true;if(response.fromDiskCache)
networkRequest.setFromDiskCache();networkRequest.timing=response.timing;networkRequest.protocol=response.protocol;networkRequest.setSecurityState(response.securityState);if(!this._mimeTypeIsConsistentWithType(networkRequest)){const message=Common.UIString('Resource interpreted as %s but transferred with MIME type %s: "%s".',networkRequest.resourceType().title(),networkRequest.mimeType,networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:true});}
if(response.securityDetails)
networkRequest.setSecurityDetails(response.securityDetails);}
_mimeTypeIsConsistentWithType(networkRequest){if(networkRequest.hasErrorStatusCode()||networkRequest.statusCode===304||networkRequest.statusCode===204)
return true;const resourceType=networkRequest.resourceType();if(resourceType!==Common.resourceTypes.Stylesheet&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.TextTrack)
return true;if(!networkRequest.mimeType)
return true;if(networkRequest.mimeType in SDK.NetworkManager._MIMETypes)
return resourceType.name()in SDK.NetworkManager._MIMETypes[networkRequest.mimeType];return false;}
resourceChangedPriority(requestId,newPriority,timestamp){const networkRequest=this._inflightRequestsById[requestId];if(networkRequest)
networkRequest.setPriority(newPriority);}
requestWillBeSent(requestId,loaderId,documentURL,request,time,wallTime,initiator,redirectResponse,resourceType,frameId){let networkRequest=this._inflightRequestsById[requestId];if(networkRequest){if(!redirectResponse)
return;this.responseReceived(requestId,loaderId,time,Protocol.Page.ResourceType.Other,redirectResponse,frameId);networkRequest=this._appendRedirect(requestId,time,request.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestRedirected,networkRequest);}else{networkRequest=this._createNetworkRequest(requestId,frameId||'',loaderId,request.url,documentURL,initiator);}
networkRequest.hasNetworkData=true;this._updateNetworkRequestWithRequest(networkRequest,request);networkRequest.setIssueTime(time,wallTime);networkRequest.setResourceType(resourceType?Common.resourceTypes[resourceType]:Protocol.Page.ResourceType.Other);this._startNetworkRequest(networkRequest);}
requestServedFromCache(requestId){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.setFromMemoryCache();}
responseReceived(requestId,loaderId,time,resourceType,response,frameId){const networkRequest=this._inflightRequestsById[requestId];const lowercaseHeaders=SDK.NetworkManager.lowercaseHeaders(response.headers);if(!networkRequest){const eventData={};eventData.url=response.url;eventData.frameId=frameId||'';eventData.loaderId=loaderId;eventData.resourceType=resourceType;eventData.mimeType=response.mimeType;const lastModifiedHeader=lowercaseHeaders['last-modified'];eventData.lastModified=lastModifiedHeader?new Date(lastModifiedHeader):null;this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdateDropped,eventData);return;}
networkRequest.responseReceivedTime=time;networkRequest.setResourceType(Common.resourceTypes[resourceType]);if('set-cookie'in lowercaseHeaders&&lowercaseHeaders['set-cookie'].length>4096){const message=Common.UIString('Set-Cookie header is ignored in response from url: %s. Cookie length should be less than or equal to 4096 characters.',response.url);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});}
this._updateNetworkRequestWithResponse(networkRequest,response);this._updateNetworkRequest(networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.ResponseReceived,networkRequest);}
dataReceived(requestId,time,dataLength,encodedDataLength){let networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
networkRequest=this._maybeAdoptMainResourceRequest(requestId);if(!networkRequest)
return;networkRequest.resourceSize+=dataLength;if(encodedDataLength!==-1)
networkRequest.increaseTransferSize(encodedDataLength);networkRequest.endTime=time;this._updateNetworkRequest(networkRequest);}
loadingFinished(requestId,finishTime,encodedDataLength,blockedCrossSiteDocument){let networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
networkRequest=this._maybeAdoptMainResourceRequest(requestId);if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,finishTime,encodedDataLength,blockedCrossSiteDocument);}
loadingFailed(requestId,time,resourceType,localizedDescription,canceled,blockedReason){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.failed=true;networkRequest.setResourceType(Common.resourceTypes[resourceType]);networkRequest.canceled=!!canceled;if(blockedReason){networkRequest.setBlockedReason(blockedReason);if(blockedReason===Protocol.Network.BlockedReason.Inspector){const message=Common.UIString('Request was blocked by DevTools: "%s".',networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:requestId,warning:true});}}
networkRequest.localizedFailDescription=localizedDescription;this._finishNetworkRequest(networkRequest,time,-1);}
webSocketCreated(requestId,requestURL,initiator){const networkRequest=new SDK.NetworkRequest(requestId,requestURL,'','','',initiator||null);networkRequest[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;networkRequest.setResourceType(Common.resourceTypes.WebSocket);this._startNetworkRequest(networkRequest);}
webSocketWillSendHandshakeRequest(requestId,time,wallTime,request){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.requestMethod='GET';networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));networkRequest.setIssueTime(time,wallTime);this._updateNetworkRequest(networkRequest);}
webSocketHandshakeResponseReceived(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.statusCode=response.status;networkRequest.statusText=response.statusText;networkRequest.responseHeaders=this._headersMapToHeadersArray(response.headers);networkRequest.responseHeadersText=response.headersText||'';if(response.requestHeaders)
networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));if(response.requestHeadersText)
networkRequest.setRequestHeadersText(response.requestHeadersText);networkRequest.responseReceivedTime=time;networkRequest.protocol='websocket';this._updateNetworkRequest(networkRequest);}
webSocketFrameReceived(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrame(response,time,false);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketFrameSent(requestId,time,response){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrame(response,time,true);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketFrameError(requestId,time,errorMessage){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addFrameError(errorMessage,time);networkRequest.responseReceivedTime=time;this._updateNetworkRequest(networkRequest);}
webSocketClosed(requestId,time){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;this._finishNetworkRequest(networkRequest,time,-1);}
eventSourceMessageReceived(requestId,time,eventName,eventId,data){const networkRequest=this._inflightRequestsById[requestId];if(!networkRequest)
return;networkRequest.addEventSourceMessage(time,eventName,eventId,data);}
requestIntercepted(interceptionId,request,frameId,resourceType,isNavigationRequest,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders){SDK.multitargetNetworkManager._requestIntercepted(new SDK.MultitargetNetworkManager.InterceptedRequest(this._manager.target().networkAgent(),interceptionId,request,frameId,resourceType,isNavigationRequest,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders));}
_appendRedirect(requestId,time,redirectURL){const originalNetworkRequest=this._inflightRequestsById[requestId];let redirectCount=0;for(let redirect=originalNetworkRequest.redirectSource();redirect;redirect=redirect.redirectSource())
redirectCount++;originalNetworkRequest.markAsRedirect(redirectCount);this._finishNetworkRequest(originalNetworkRequest,time,-1);const newNetworkRequest=this._createNetworkRequest(requestId,originalNetworkRequest.frameId,originalNetworkRequest.loaderId,redirectURL,originalNetworkRequest.documentURL,originalNetworkRequest.initiator());newNetworkRequest.setRedirectSource(originalNetworkRequest);return newNetworkRequest;}
_maybeAdoptMainResourceRequest(requestId){const request=SDK.multitargetNetworkManager._inflightMainResourceRequests.get(requestId);if(!request)
return null;const oldDispatcher=SDK.NetworkManager.forRequest(request)._dispatcher;delete oldDispatcher._inflightRequestsById[requestId];delete oldDispatcher._inflightRequestsByURL[request.url()];this._inflightRequestsById[requestId]=request;this._inflightRequestsByURL[request.url()]=request;request[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;return request;}
_startNetworkRequest(networkRequest){this._inflightRequestsById[networkRequest.requestId()]=networkRequest;this._inflightRequestsByURL[networkRequest.url()]=networkRequest;if(networkRequest.loaderId===networkRequest.requestId())
SDK.multitargetNetworkManager._inflightMainResourceRequests.set(networkRequest.requestId(),networkRequest);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestStarted,networkRequest);}
_updateNetworkRequest(networkRequest){this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestUpdated,networkRequest);}
_finishNetworkRequest(networkRequest,finishTime,encodedDataLength,blockedCrossSiteDocument){networkRequest.endTime=finishTime;networkRequest.finished=true;if(encodedDataLength>=0)
networkRequest.setTransferSize(encodedDataLength);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestFinished,networkRequest);delete this._inflightRequestsById[networkRequest.requestId()];delete this._inflightRequestsByURL[networkRequest.url()];SDK.multitargetNetworkManager._inflightMainResourceRequests.delete(networkRequest.requestId());if(blockedCrossSiteDocument){const message=Common.UIString(`Blocked current origin from receiving cross-site document at %s with MIME type %s.`,networkRequest.url(),networkRequest.mimeType);this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:true});}
if(Common.moduleSetting('monitoringXHREnabled').get()&&networkRequest.resourceType().category()===Common.resourceCategories.XHR){const message=Common.UIString((networkRequest.failed||networkRequest.hasErrorStatusCode())?'%s failed loading: %s "%s".':'%s finished loading: %s "%s".',networkRequest.resourceType().title(),networkRequest.requestMethod,networkRequest.url());this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:networkRequest.requestId(),warning:false});}}
_createNetworkRequest(requestId,frameId,loaderId,url,documentURL,initiator){const request=new SDK.NetworkRequest(requestId,url,documentURL,frameId,loaderId,initiator);request[SDK.NetworkManager._networkManagerForRequestSymbol]=this._manager;return request;}};SDK.MultitargetNetworkManager=class extends Common.Object{constructor(){super();this._userAgentOverride='';this._agents=new Set();this._inflightMainResourceRequests=new Map();this._networkConditions=SDK.NetworkManager.NoThrottlingConditions;this._updatingInterceptionPatternsPromise=null;this._blockingEnabledSetting=Common.moduleSetting('requestBlockingEnabled');this._blockedPatternsSetting=Common.settings.createSetting('networkBlockedPatterns',[]);this._effectiveBlockedURLs=[];this._updateBlockedPatterns();this._urlsForRequestInterceptor=new Multimap();SDK.targetManager.observeTargets(this,SDK.Target.Capability.Network);}
static patchUserAgentWithChromeVersion(uaString){const chromeRegex=new RegExp('(?:^|\\W)Chrome/(\\S+)');const chromeMatch=navigator.userAgent.match(chromeRegex);if(chromeMatch&&chromeMatch.length>1)
return String.sprintf(uaString,chromeMatch[1]);return uaString;}
targetAdded(target){const networkAgent=target.networkAgent();if(this._extraHeaders)
networkAgent.setExtraHTTPHeaders(this._extraHeaders);if(this._currentUserAgent())
networkAgent.setUserAgentOverride(this._currentUserAgent());if(this._effectiveBlockedURLs.length)
networkAgent.setBlockedURLs(this._effectiveBlockedURLs);if(this.isIntercepting())
networkAgent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray());this._agents.add(networkAgent);if(this.isThrottling())
this._updateNetworkConditions(networkAgent);}
targetRemoved(target){for(const entry of this._inflightMainResourceRequests){const manager=SDK.NetworkManager.forRequest((entry[1]));if(manager.target()!==target)
continue;this._inflightMainResourceRequests.delete((entry[0]));}
this._agents.delete(target.networkAgent());}
isThrottling(){return this._networkConditions.download>=0||this._networkConditions.upload>=0||this._networkConditions.latency>0;}
isOffline(){return!this._networkConditions.download&&!this._networkConditions.upload;}
setNetworkConditions(conditions){this._networkConditions=conditions;for(const agent of this._agents)
this._updateNetworkConditions(agent);this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.ConditionsChanged);}
networkConditions(){return this._networkConditions;}
_updateNetworkConditions(networkAgent){const conditions=this._networkConditions;if(!this.isThrottling()){networkAgent.emulateNetworkConditions(false,0,0,0);}else{networkAgent.emulateNetworkConditions(this.isOffline(),conditions.latency,conditions.download<0?0:conditions.download,conditions.upload<0?0:conditions.upload,SDK.NetworkManager._connectionType(conditions));}}
setExtraHTTPHeaders(headers){this._extraHeaders=headers;for(const agent of this._agents)
agent.setExtraHTTPHeaders(this._extraHeaders);}
_currentUserAgent(){return this._customUserAgent?this._customUserAgent:this._userAgentOverride;}
_updateUserAgentOverride(){const userAgent=this._currentUserAgent();for(const agent of this._agents)
agent.setUserAgentOverride(userAgent);}
setUserAgentOverride(userAgent){if(this._userAgentOverride===userAgent)
return;this._userAgentOverride=userAgent;if(!this._customUserAgent)
this._updateUserAgentOverride();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.UserAgentChanged);}
userAgentOverride(){return this._userAgentOverride;}
setCustomUserAgentOverride(userAgent){this._customUserAgent=userAgent;this._updateUserAgentOverride();}
blockedPatterns(){return this._blockedPatternsSetting.get().slice();}
blockingEnabled(){return this._blockingEnabledSetting.get();}
isBlocking(){return!!this._effectiveBlockedURLs.length;}
setBlockedPatterns(patterns){this._blockedPatternsSetting.set(patterns);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);}
setBlockingEnabled(enabled){if(this._blockingEnabledSetting.get()===enabled)
return;this._blockingEnabledSetting.set(enabled);this._updateBlockedPatterns();this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged);}
_updateBlockedPatterns(){const urls=[];if(this._blockingEnabledSetting.get()){for(const pattern of this._blockedPatternsSetting.get()){if(pattern.enabled)
urls.push(pattern.url);}}
if(!urls.length&&!this._effectiveBlockedURLs.length)
return;this._effectiveBlockedURLs=urls;for(const agent of this._agents)
agent.setBlockedURLs(this._effectiveBlockedURLs);}
isIntercepting(){return!!this._urlsForRequestInterceptor.size;}
setInterceptionHandlerForPatterns(patterns,requestInterceptor){this._urlsForRequestInterceptor.deleteAll(requestInterceptor);for(const newPattern of patterns)
this._urlsForRequestInterceptor.set(requestInterceptor,newPattern);return this._updateInterceptionPatternsOnNextTick();}
_updateInterceptionPatternsOnNextTick(){if(!this._updatingInterceptionPatternsPromise)
this._updatingInterceptionPatternsPromise=Promise.resolve().then(this._updateInterceptionPatterns.bind(this));return this._updatingInterceptionPatternsPromise;}
_updateInterceptionPatterns(){if(!Common.moduleSetting('cacheDisabled').get())
Common.moduleSetting('cacheDisabled').set(true);this._updatingInterceptionPatternsPromise=null;const promises=([]);for(const agent of this._agents)
promises.push(agent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray()));this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.InterceptorsChanged);return Promise.all(promises);}
async _requestIntercepted(interceptedRequest){for(const requestInterceptor of this._urlsForRequestInterceptor.keysArray()){await requestInterceptor(interceptedRequest);if(interceptedRequest.hasResponded())
return;}
if(!interceptedRequest.hasResponded())
interceptedRequest.continueRequestWithoutChange();}
clearBrowserCache(){for(const agent of this._agents)
agent.clearBrowserCache();}
clearBrowserCookies(){for(const agent of this._agents)
agent.clearBrowserCookies();}
getCertificate(origin){const target=SDK.targetManager.mainTarget();return target.networkAgent().getCertificate(origin).then(certificate=>certificate||[]);}
loadResource(url,callback){const headers={};const currentUserAgent=this._currentUserAgent();if(currentUserAgent)
headers['User-Agent']=currentUserAgent;if(Common.moduleSetting('cacheDisabled').get())
headers['Cache-Control']='no-cache';Host.ResourceLoader.load(url,headers,callback);}};SDK.MultitargetNetworkManager.Events={BlockedPatternsChanged:Symbol('BlockedPatternsChanged'),ConditionsChanged:Symbol('ConditionsChanged'),UserAgentChanged:Symbol('UserAgentChanged'),InterceptorsChanged:Symbol('InterceptorsChanged')};SDK.MultitargetNetworkManager.InterceptedRequest=class{constructor(networkAgent,interceptionId,request,frameId,resourceType,isNavigationRequest,redirectUrl,authChallenge,responseErrorReason,responseStatusCode,responseHeaders){this._networkAgent=networkAgent;this._interceptionId=interceptionId;this._hasResponded=false;this.request=request;this.frameId=frameId;this.resourceType=resourceType;this.isNavigationRequest=isNavigationRequest;this.redirectUrl=redirectUrl;this.authChallenge=authChallenge;this.responseErrorReason=responseErrorReason;this.responseStatusCode=responseStatusCode;this.responseHeaders=responseHeaders;}
hasResponded(){return this._hasResponded;}
async continueRequestWithContent(contentBlob){this._hasResponded=true;const headers=['HTTP/1.1 200 OK','Date: '+(new Date()).toUTCString(),'Server: Chrome Devtools Request Interceptor','Connection: closed','Content-Length: '+contentBlob.size,'Content-Type: '+contentBlob.type||'text/x-unknown',];const encodedResponse=await blobToBase64(new Blob([headers.join('\r\n'),'\r\n\r\n',contentBlob]));this._networkAgent.continueInterceptedRequest(this._interceptionId,undefined,encodedResponse);async function blobToBase64(blob){const reader=new FileReader();const fileContentsLoadedPromise=new Promise(resolve=>reader.onloadend=resolve);reader.readAsDataURL(blob);await fileContentsLoadedPromise;if(reader.error){console.error('Could not convert blob to base64.',reader.error);return'';}
const result=reader.result;if(result===undefined){console.error('Could not convert blob to base64.');return'';}
return result.substring(result.indexOf(',')+1);}}
continueRequestWithoutChange(){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId);}
continueRequestWithError(errorReason){console.assert(!this._hasResponded);this._hasResponded=true;this._networkAgent.continueInterceptedRequest(this._interceptionId,errorReason);}
async responseBody(){const response=await this._networkAgent.invoke_getResponseBodyForInterception({interceptionId:this._interceptionId});const error=response[Protocol.Error]||null;return{error:error,content:error?null:response.body,encoded:response.base64Encoded};}};SDK.MultitargetNetworkManager.InterceptionPattern;SDK.MultitargetNetworkManager.RequestInterceptor;SDK.multitargetNetworkManager;;SDK.NetworkRequest=class extends Common.Object{constructor(requestId,url,documentURL,frameId,loaderId,initiator){super();this._requestId=requestId;this._backendRequestId=requestId;this.setUrl(url);this._documentURL=documentURL;this._frameId=frameId;this._loaderId=loaderId;this._initiator=initiator;this._redirectSource=null;this._issueTime=-1;this._startTime=-1;this._endTime=-1;this._blockedReason=undefined;this.statusCode=0;this.statusText='';this.requestMethod='';this.requestTime=0;this.protocol='';this.mixedContentType=Protocol.Security.MixedContentType.None;this._initialPriority=null;this._currentPriority=null;this._resourceType=Common.resourceTypes.Other;this._contentData=null;this._frames=[];this._eventSourceMessages=[];this._responseHeaderValues={};this._responseHeadersText='';this._requestHeaders=[];this._requestHeaderValues={};this._remoteAddress='';this._referrerPolicy=null;this._securityState=Protocol.Security.SecurityState.Unknown;this._securityDetails=null;this.connectionId='0';this._formParametersPromise=null;this._requestFormDataPromise=(Promise.resolve(null));}
indentityCompare(other){const thisId=this.requestId();const thatId=other.requestId();if(thisId>thatId)
return 1;if(thisId<thatId)
return-1;return 0;}
requestId(){return this._requestId;}
backendRequestId(){return this._backendRequestId;}
url(){return this._url;}
setUrl(x){if(this._url===x)
return;this._url=x;this._parsedURL=new Common.ParsedURL(x);delete this._queryString;delete this._parsedQueryParameters;delete this._name;delete this._path;}
get documentURL(){return this._documentURL;}
get parsedURL(){return this._parsedURL;}
get frameId(){return this._frameId;}
get loaderId(){return this._loaderId;}
setRemoteAddress(ip,port){this._remoteAddress=ip+':'+port;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RemoteAddressChanged,this);}
remoteAddress(){return this._remoteAddress;}
setReferrerPolicy(referrerPolicy){this._referrerPolicy=referrerPolicy;}
referrerPolicy(){return this._referrerPolicy;}
securityState(){return this._securityState;}
setSecurityState(securityState){this._securityState=securityState;}
securityDetails(){return this._securityDetails;}
setSecurityDetails(securityDetails){this._securityDetails=securityDetails;}
get startTime(){return this._startTime||-1;}
setIssueTime(monotonicTime,wallTime){this._issueTime=monotonicTime;this._wallIssueTime=wallTime;this._startTime=monotonicTime;}
issueTime(){return this._issueTime;}
pseudoWallTime(monotonicTime){return this._wallIssueTime?this._wallIssueTime-this._issueTime+monotonicTime:monotonicTime;}
get responseReceivedTime(){return this._responseReceivedTime||-1;}
set responseReceivedTime(x){this._responseReceivedTime=x;}
get endTime(){return this._endTime||-1;}
set endTime(x){if(this.timing&&this.timing.requestTime){this._endTime=Math.max(x,this.responseReceivedTime);}else{this._endTime=x;if(this._responseReceivedTime>x)
this._responseReceivedTime=x;}
this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);}
get duration(){if(this._endTime===-1||this._startTime===-1)
return-1;return this._endTime-this._startTime;}
get latency(){if(this._responseReceivedTime===-1||this._startTime===-1)
return-1;return this._responseReceivedTime-this._startTime;}
get resourceSize(){return this._resourceSize||0;}
set resourceSize(x){this._resourceSize=x;}
get transferSize(){return this._transferSize||0;}
increaseTransferSize(x){this._transferSize=(this._transferSize||0)+x;}
setTransferSize(x){this._transferSize=x;}
get finished(){return this._finished;}
set finished(x){if(this._finished===x)
return;this._finished=x;if(x)
this.dispatchEventToListeners(SDK.NetworkRequest.Events.FinishedLoading,this);}
get failed(){return this._failed;}
set failed(x){this._failed=x;}
get canceled(){return this._canceled;}
set canceled(x){this._canceled=x;}
blockedReason(){return this._blockedReason;}
setBlockedReason(reason){this._blockedReason=reason;}
wasBlocked(){return!!this._blockedReason;}
cached(){return(!!this._fromMemoryCache||!!this._fromDiskCache)&&!this._transferSize;}
cachedInMemory(){return!!this._fromMemoryCache&&!this._transferSize;}
setFromMemoryCache(){this._fromMemoryCache=true;delete this._timing;}
setFromDiskCache(){this._fromDiskCache=true;}
get fetchedViaServiceWorker(){return this._fetchedViaServiceWorker;}
set fetchedViaServiceWorker(x){this._fetchedViaServiceWorker=x;}
get timing(){return this._timing;}
set timing(timingInfo){if(!timingInfo||this._fromMemoryCache)
return;this._startTime=timingInfo.requestTime;const headersReceivedTime=timingInfo.requestTime+timingInfo.receiveHeadersEnd/1000.0;if((this._responseReceivedTime||-1)<0||this._responseReceivedTime>headersReceivedTime)
this._responseReceivedTime=headersReceivedTime;if(this._startTime>this._responseReceivedTime)
this._responseReceivedTime=this._startTime;this._timing=timingInfo;this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged,this);}
get mimeType(){return this._mimeType;}
set mimeType(x){this._mimeType=x;}
get displayName(){return this._parsedURL.displayName;}
name(){if(this._name)
return this._name;this._parseNameAndPathFromURL();return this._name;}
path(){if(this._path)
return this._path;this._parseNameAndPathFromURL();return this._path;}
_parseNameAndPathFromURL(){if(this._parsedURL.isDataURL()){this._name=this._parsedURL.dataURLDisplayName();this._path='';}else if(this._parsedURL.isAboutBlank()){this._name=this._parsedURL.url;this._path='';}else{this._path=this._parsedURL.host+this._parsedURL.folderPathComponents;const networkManager=SDK.NetworkManager.forRequest(this);const inspectedURL=networkManager?networkManager.target().inspectedURL().asParsedURL():null;this._path=this._path.trimURL(inspectedURL?inspectedURL.host:'');if(this._parsedURL.lastPathComponent||this._parsedURL.queryParams){this._name=this._parsedURL.lastPathComponent+(this._parsedURL.queryParams?'?'+this._parsedURL.queryParams:'');}else if(this._parsedURL.folderPathComponents){this._name=this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf('/')+1)+'/';this._path=this._path.substring(0,this._path.lastIndexOf('/'));}else{this._name=this._parsedURL.host;this._path='';}}}
get folder(){let path=this._parsedURL.path;const indexOfQuery=path.indexOf('?');if(indexOfQuery!==-1)
path=path.substring(0,indexOfQuery);const lastSlashIndex=path.lastIndexOf('/');return lastSlashIndex!==-1?path.substring(0,lastSlashIndex):'';}
resourceType(){return this._resourceType;}
setResourceType(resourceType){this._resourceType=resourceType;}
get domain(){return this._parsedURL.host;}
get scheme(){return this._parsedURL.scheme;}
redirectSource(){return this._redirectSource;}
setRedirectSource(originatingRequest){this._redirectSource=originatingRequest;}
requestHeaders(){return this._requestHeaders;}
setRequestHeaders(headers){this._requestHeaders=headers;delete this._requestCookies;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);}
requestHeadersText(){return this._requestHeadersText;}
setRequestHeadersText(text){this._requestHeadersText=text;this.dispatchEventToListeners(SDK.NetworkRequest.Events.RequestHeadersChanged);}
requestHeaderValue(headerName){if(headerName in this._requestHeaderValues)
return this._requestHeaderValues[headerName];this._requestHeaderValues[headerName]=this._computeHeaderValue(this.requestHeaders(),headerName);return this._requestHeaderValues[headerName];}
get requestCookies(){if(!this._requestCookies)
this._requestCookies=SDK.CookieParser.parseCookie(this.requestHeaderValue('Cookie'));return this._requestCookies;}
requestFormData(){if(!this._requestFormDataPromise)
this._requestFormDataPromise=SDK.NetworkManager.requestPostData(this);return this._requestFormDataPromise;}
setRequestFormData(hasData,data){this._requestFormDataPromise=(hasData&&data===null)?null:Promise.resolve(data);this._formParametersPromise=null;}
_filteredProtocolName(){const protocol=this.protocol.toLowerCase();if(protocol==='h2')
return'http/2.0';return protocol.replace(/^http\/2(\.0)?\+/,'http/2.0+');}
requestHttpVersion(){const headersText=this.requestHeadersText();if(!headersText){const version=this.requestHeaderValue('version')||this.requestHeaderValue(':version');if(version)
return version;return this._filteredProtocolName();}
const firstLine=headersText.split(/\r\n/)[0];const match=firstLine.match(/(HTTP\/\d+\.\d+)$/);return match?match[1]:'HTTP/0.9';}
get responseHeaders(){return this._responseHeaders||[];}
set responseHeaders(x){this._responseHeaders=x;delete this._sortedResponseHeaders;delete this._serverTimings;delete this._responseCookies;this._responseHeaderValues={};this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);}
get responseHeadersText(){return this._responseHeadersText;}
set responseHeadersText(x){this._responseHeadersText=x;this.dispatchEventToListeners(SDK.NetworkRequest.Events.ResponseHeadersChanged);}
get sortedResponseHeaders(){if(this._sortedResponseHeaders!==undefined)
return this._sortedResponseHeaders;this._sortedResponseHeaders=this.responseHeaders.slice();this._sortedResponseHeaders.sort(function(a,b){return a.name.toLowerCase().compareTo(b.name.toLowerCase());});return this._sortedResponseHeaders;}
responseHeaderValue(headerName){if(headerName in this._responseHeaderValues)
return this._responseHeaderValues[headerName];this._responseHeaderValues[headerName]=this._computeHeaderValue(this.responseHeaders,headerName);return this._responseHeaderValues[headerName];}
get responseCookies(){if(!this._responseCookies)
this._responseCookies=SDK.CookieParser.parseSetCookie(this.responseHeaderValue('Set-Cookie'));return this._responseCookies;}
responseLastModified(){return this.responseHeaderValue('last-modified');}
get serverTimings(){if(typeof this._serverTimings==='undefined')
this._serverTimings=SDK.ServerTiming.parseHeaders(this.responseHeaders);return this._serverTimings;}
queryString(){if(this._queryString!==undefined)
return this._queryString;let queryString=null;const url=this.url();const questionMarkPosition=url.indexOf('?');if(questionMarkPosition!==-1){queryString=url.substring(questionMarkPosition+1);const hashSignPosition=queryString.indexOf('#');if(hashSignPosition!==-1)
queryString=queryString.substring(0,hashSignPosition);}
this._queryString=queryString;return this._queryString;}
get queryParameters(){if(this._parsedQueryParameters)
return this._parsedQueryParameters;const queryString=this.queryString();if(!queryString)
return null;this._parsedQueryParameters=this._parseParameters(queryString);return this._parsedQueryParameters;}
async _parseFormParameters(){const requestContentType=this.requestContentType();if(!requestContentType||!requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i))
return null;const formData=await this.requestFormData();if(formData)
return this._parseParameters(formData);return null;}
formParameters(){if(!this._formParametersPromise)
this._formParametersPromise=this._parseFormParameters();return this._formParametersPromise;}
responseHttpVersion(){const headersText=this._responseHeadersText;if(!headersText){const version=this.responseHeaderValue('version')||this.responseHeaderValue(':version');if(version)
return version;return this._filteredProtocolName();}
const firstLine=headersText.split(/\r\n/)[0];const match=firstLine.match(/^(HTTP\/\d+\.\d+)/);return match?match[1]:'HTTP/0.9';}
_parseParameters(queryString){function parseNameValue(pair){const position=pair.indexOf('=');if(position===-1)
return{name:pair,value:''};else
return{name:pair.substring(0,position),value:pair.substring(position+1)};}
return queryString.split('&').map(parseNameValue);}
_computeHeaderValue(headers,headerName){headerName=headerName.toLowerCase();const values=[];for(let i=0;i<headers.length;++i){if(headers[i].name.toLowerCase()===headerName)
values.push(headers[i].value);}
if(!values.length)
return undefined;if(headerName==='set-cookie')
return values.join('\n');return values.join(', ');}
contentData(){if(this._contentData)
return this._contentData;if(this._contentDataProvider)
this._contentData=this._contentDataProvider();else
this._contentData=SDK.NetworkManager.requestContentData(this);return this._contentData;}
setContentDataProvider(dataProvider){console.assert(!this._contentData,'contentData can only be set once.');this._contentDataProvider=dataProvider;}
contentURL(){return this._url;}
contentType(){return this._resourceType;}
async contentEncoded(){return(await this.contentData()).encoded;}
async requestContent(){return(await this.contentData()).content;}
searchInContent(query,caseSensitive,isRegex){return SDK.NetworkManager.searchInRequest(this,query,caseSensitive,isRegex);}
isHttpFamily(){return!!this.url().match(/^https?:/i);}
requestContentType(){return this.requestHeaderValue('Content-Type');}
hasErrorStatusCode(){return this.statusCode>=400;}
setInitialPriority(priority){this._initialPriority=priority;}
initialPriority(){return this._initialPriority;}
setPriority(priority){this._currentPriority=priority;}
priority(){return this._currentPriority||this._initialPriority||null;}
populateImageSource(image){function onResourceContent(content){let imageSrc=Common.ContentProvider.contentAsDataURL(content,this._mimeType,true);const cacheControl=this.responseHeaderValue('cache-control');if(imageSrc===null&&(!cacheControl||!cacheControl.includes('no-cache')))
imageSrc=this._url;image.src=imageSrc;}
this.requestContent().then(onResourceContent.bind(this));}
initiator(){return this._initiator;}
frames(){return this._frames;}
addFrameError(errorMessage,time){this._addFrame({type:SDK.NetworkRequest.WebSocketFrameType.Error,text:errorMessage,time:this.pseudoWallTime(time),opCode:-1,mask:false});}
addFrame(response,time,sent){const type=sent?SDK.NetworkRequest.WebSocketFrameType.Send:SDK.NetworkRequest.WebSocketFrameType.Receive;this._addFrame({type:type,text:response.payloadData,time:this.pseudoWallTime(time),opCode:response.opcode,mask:response.mask});}
_addFrame(frame){this._frames.push(frame);this.dispatchEventToListeners(SDK.NetworkRequest.Events.WebsocketFrameAdded,frame);}
eventSourceMessages(){return this._eventSourceMessages;}
addEventSourceMessage(time,eventName,eventId,data){const message={time:this.pseudoWallTime(time),eventName:eventName,eventId:eventId,data:data};this._eventSourceMessages.push(message);this.dispatchEventToListeners(SDK.NetworkRequest.Events.EventSourceMessageAdded,message);}
markAsRedirect(redirectCount){this._requestId=`${this._backendRequestId}:redirected.${redirectCount}`;}
setRequestIdForTest(requestId){this._backendRequestId=requestId;this._requestId=requestId;}};SDK.NetworkRequest.Events={FinishedLoading:Symbol('FinishedLoading'),TimingChanged:Symbol('TimingChanged'),RemoteAddressChanged:Symbol('RemoteAddressChanged'),RequestHeadersChanged:Symbol('RequestHeadersChanged'),ResponseHeadersChanged:Symbol('ResponseHeadersChanged'),WebsocketFrameAdded:Symbol('WebsocketFrameAdded'),EventSourceMessageAdded:Symbol('EventSourceMessageAdded')};SDK.NetworkRequest.InitiatorType={Other:'other',Parser:'parser',Redirect:'redirect',Script:'script',Preload:'preload'};SDK.NetworkRequest.NameValue;SDK.NetworkRequest.WebSocketFrameType={Send:'send',Receive:'receive',Error:'error'};SDK.NetworkRequest.WebSocketFrame;SDK.NetworkRequest.EventSourceMessage;SDK.NetworkRequest.ContentData;;SDK.PaintProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);this._layerTreeAgent=target.layerTreeAgent();}
async loadSnapshotFromFragments(fragments){const snapshotId=await this._layerTreeAgent.loadSnapshot(fragments);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);}
loadSnapshot(encodedPicture){const fragment={x:0,y:0,picture:encodedPicture};return this.loadSnapshotFromFragments([fragment]);}
async makeSnapshot(layerId){const snapshotId=await this._layerTreeAgent.makeSnapshot(layerId);return snapshotId&&new SDK.PaintProfilerSnapshot(this,snapshotId);}};SDK.SDKModel.register(SDK.PaintProfilerModel,SDK.Target.Capability.DOM,false);SDK.PictureFragment;SDK.PaintProfilerSnapshot=class{constructor(paintProfilerModel,snapshotId){this._paintProfilerModel=paintProfilerModel;this._id=snapshotId;this._refCount=1;}
release(){console.assert(this._refCount>0,'release is already called on the object');if(!--this._refCount)
this._paintProfilerModel._layerTreeAgent.releaseSnapshot(this._id);}
addReference(){++this._refCount;console.assert(this._refCount>0,'Referencing a dead object');}
replay(scale,firstStep,lastStep){return this._paintProfilerModel._layerTreeAgent.replaySnapshot(this._id,firstStep,lastStep,scale||1.0);}
profile(clipRect){return this._paintProfilerModel._layerTreeAgent.profileSnapshot(this._id,5,1,clipRect||undefined);}
async commandLog(){const log=await this._paintProfilerModel._layerTreeAgent.snapshotCommandLog(this._id);return log&&log.map((entry,index)=>new SDK.PaintProfilerLogItem(entry,index));}};SDK.RawPaintProfilerLogItem;SDK.PaintProfilerLogItem=class{constructor(rawEntry,commandIndex){this.method=rawEntry.method;this.params=rawEntry.params;this.commandIndex=commandIndex;}};;SDK.HeapProfilerModel=class extends SDK.SDKModel{constructor(target){super(target);target.registerHeapProfilerDispatcher(new SDK.HeapProfilerDispatcher(this));this._enabled=false;this._heapProfilerAgent=target.heapProfilerAgent();this._memoryAgent=target.memoryAgent();this._runtimeModel=(target.model(SDK.RuntimeModel));}
debuggerModel(){return this._runtimeModel.debuggerModel();}
runtimeModel(){return this._runtimeModel;}
enable(){if(this._enabled)
return;this._enabled=true;this._heapProfilerAgent.enable();}
startSampling(){const defaultSamplingIntervalInBytes=16384;this._heapProfilerAgent.startSampling(defaultSamplingIntervalInBytes);}
stopSampling(){this._isRecording=false;return this._heapProfilerAgent.stopSampling();}
startNativeSampling(){const defaultSamplingIntervalInBytes=65536;this._memoryAgent.startSampling(defaultSamplingIntervalInBytes);}
async stopNativeSampling(){const rawProfile=await this._memoryAgent.getSamplingProfile();this._memoryAgent.stopSampling();return this._convertNativeProfile(rawProfile);}
async takeNativeSnapshot(){const rawProfile=await this._memoryAgent.getAllTimeSamplingProfile();return this._convertNativeProfile(rawProfile);}
_convertNativeProfile(rawProfile){const head={children:new Map(),selfSize:0,callFrame:{functionName:'(root)',url:''}};for(const sample of rawProfile.samples){const node=sample.stack.reverse().reduce((node,name)=>{let child=node.children.get(name);if(child)
return child;const namespace=/^([^:]*)::/.exec(name);child={children:new Map(),callFrame:{functionName:name,url:namespace&&namespace[1]||''},selfSize:0};node.children.set(name,child);return child;},head);node.selfSize+=sample.total;}
function convertChildren(node){node.children=Array.from(node.children.values());node.children.forEach(convertChildren);}
convertChildren(head);return({head});}
collectGarbage(){return this._heapProfilerAgent.collectGarbage();}
snapshotObjectIdForObjectId(objectId){return this._heapProfilerAgent.getHeapObjectId(objectId);}
objectForSnapshotObjectId(snapshotObjectId,objectGroupName){return this._heapProfilerAgent.getObjectByHeapObjectId(snapshotObjectId,objectGroupName).then(result=>result&&result.type?this._runtimeModel.createRemoteObject(result):null);}
addInspectedHeapObject(snapshotObjectId){return this._heapProfilerAgent.addInspectedHeapObject(snapshotObjectId);}
takeHeapSnapshot(reportProgress){return this._heapProfilerAgent.takeHeapSnapshot(reportProgress);}
startTrackingHeapObjects(recordAllocationStacks){return this._heapProfilerAgent.startTrackingHeapObjects(recordAllocationStacks);}
stopTrackingHeapObjects(reportProgress){return this._heapProfilerAgent.stopTrackingHeapObjects(reportProgress);}
heapStatsUpdate(samples){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.HeapStatsUpdate,samples);}
lastSeenObjectId(lastSeenObjectId,timestamp){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.LastSeenObjectId,{lastSeenObjectId:lastSeenObjectId,timestamp:timestamp});}
addHeapSnapshotChunk(chunk){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk,chunk);}
reportHeapSnapshotProgress(done,total,finished){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress,{done:done,total:total,finished:finished});}
resetProfiles(){this.dispatchEventToListeners(SDK.HeapProfilerModel.Events.ResetProfiles,this);}};SDK.SDKModel.register(SDK.HeapProfilerModel,SDK.Target.Capability.JS,false);SDK.HeapProfilerModel.Events={HeapStatsUpdate:Symbol('HeapStatsUpdate'),LastSeenObjectId:Symbol('LastSeenObjectId'),AddHeapSnapshotChunk:Symbol('AddHeapSnapshotChunk'),ReportHeapSnapshotProgress:Symbol('ReportHeapSnapshotProgress'),ResetProfiles:Symbol('ResetProfiles')};SDK.HeapProfilerDispatcher=class{constructor(model){this._heapProfilerModel=model;}
heapStatsUpdate(samples){this._heapProfilerModel.heapStatsUpdate(samples);}
lastSeenObjectId(lastSeenObjectId,timestamp){this._heapProfilerModel.lastSeenObjectId(lastSeenObjectId,timestamp);}
addHeapSnapshotChunk(chunk){this._heapProfilerModel.addHeapSnapshotChunk(chunk);}
reportHeapSnapshotProgress(done,total,finished){this._heapProfilerModel.reportHeapSnapshotProgress(done,total,finished);}
resetProfiles(){this._heapProfilerModel.resetProfiles();}};;SDK.PerformanceMetricsModel=class extends SDK.SDKModel{constructor(target){super(target);this._agent=target.performanceAgent();const mode=SDK.PerformanceMetricsModel.MetricMode;this._metricModes=new Map([['TaskDuration',mode.CumulativeTime],['ScriptDuration',mode.CumulativeTime],['LayoutDuration',mode.CumulativeTime],['RecalcStyleDuration',mode.CumulativeTime],['LayoutCount',mode.CumulativeCount],['RecalcStyleCount',mode.CumulativeCount]]);this._metricData=new Map();}
enable(){return this._agent.enable();}
disable(){return this._agent.disable();}
async requestMetrics(){const rawMetrics=await this._agent.getMetrics()||[];const metrics=new Map();const timestamp=performance.now();for(const metric of rawMetrics){let data=this._metricData.get(metric.name);if(!data){data={};this._metricData.set(metric.name,data);}
let value;switch(this._metricModes.get(metric.name)){case SDK.PerformanceMetricsModel.MetricMode.CumulativeTime:value=data.lastTimestamp?Number.constrain((metric.value-data.lastValue)*1000/(timestamp-data.lastTimestamp),0,1):0;data.lastValue=metric.value;data.lastTimestamp=timestamp;break;case SDK.PerformanceMetricsModel.MetricMode.CumulativeCount:value=data.lastTimestamp?Math.max(0,(metric.value-data.lastValue)*1000/(timestamp-data.lastTimestamp)):0;data.lastValue=metric.value;data.lastTimestamp=timestamp;break;default:value=metric.value;break;}
metrics.set(metric.name,value);}
const totalMemoryUsage=await this._requestTotalMemory();metrics.set('JSHeapUsedSize',totalMemoryUsage.usedSize);metrics.set('JSHeapTotalSize',totalMemoryUsage.totalSize);return{metrics:metrics,timestamp:timestamp};}
async _requestTotalMemory(){const models=SDK.targetManager.models(SDK.RuntimeModel);const isolates=await Promise.all(models.map(model=>model.isolateId()));const modelsByIsolate=new Map();for(let i=0;i<isolates.length;++i)
modelsByIsolate.set(isolates[i],models[i]);const usages=await Promise.all(modelsByIsolate.valuesArray().map(model=>model.heapUsage()));let totalSize=0;let usedSize=0;for(const usage of usages){totalSize+=usage?usage.totalSize:0;usedSize+=usage?usage.usedSize:0;}
return{totalSize,usedSize};}};SDK.PerformanceMetricsModel.MetricMode={CumulativeTime:Symbol('CumulativeTime'),CumulativeCount:Symbol('CumulativeCount'),};SDK.SDKModel.register(SDK.PerformanceMetricsModel,SDK.Target.Capability.Browser,false);;SDK.CSSMetadata._generatedProperties=[{"name":"-webkit-app-region"},{"name":"-webkit-appearance"},{"longhands":["-webkit-border-after-width","-webkit-border-after-style","-webkit-border-after-color"],"name":"-webkit-border-after"},{"name":"-webkit-border-after-color"},{"name":"-webkit-border-after-style"},{"name":"-webkit-border-after-width"},{"longhands":["-webkit-border-before-width","-webkit-border-before-style","-webkit-border-before-color"],"name":"-webkit-border-before"},{"name":"-webkit-border-before-color"},{"name":"-webkit-border-before-style"},{"name":"-webkit-border-before-width"},{"longhands":["-webkit-border-end-width","-webkit-border-end-style","-webkit-border-end-color"],"name":"-webkit-border-end"},{"name":"-webkit-border-end-color"},{"name":"-webkit-border-end-style"},{"name":"-webkit-border-end-width"},{"name":"-webkit-border-horizontal-spacing","inherited":true},{"name":"-webkit-border-image"},{"longhands":["-webkit-border-start-width","-webkit-border-start-style","-webkit-border-start-color"],"name":"-webkit-border-start"},{"name":"-webkit-border-start-color"},{"name":"-webkit-border-start-style"},{"name":"-webkit-border-start-width"},{"name":"-webkit-border-vertical-spacing","inherited":true},{"name":"-webkit-box-align"},{"name":"-webkit-box-decoration-break"},{"name":"-webkit-box-direction","inherited":true},{"name":"-webkit-box-flex"},{"name":"-webkit-box-ordinal-group"},{"name":"-webkit-box-orient"},{"name":"-webkit-box-pack"},{"name":"-webkit-box-reflect"},{"longhands":["break-after"],"name":"-webkit-column-break-after"},{"longhands":["break-before"],"name":"-webkit-column-break-before"},{"longhands":["break-inside"],"name":"-webkit-column-break-inside"},{"name":"-webkit-font-size-delta"},{"name":"-webkit-font-smoothing","inherited":true},{"name":"-webkit-highlight","inherited":true},{"name":"-webkit-hyphenate-character","inherited":true},{"name":"-webkit-line-break","inherited":true},{"name":"-webkit-line-clamp"},{"name":"-webkit-locale","inherited":true},{"name":"-webkit-logical-height"},{"name":"-webkit-logical-width"},{"name":"-webkit-margin-after"},{"name":"-webkit-margin-after-collapse"},{"name":"-webkit-margin-before"},{"name":"-webkit-margin-before-collapse"},{"name":"-webkit-margin-bottom-collapse"},{"longhands":["-webkit-margin-before-collapse","-webkit-margin-after-collapse"],"name":"-webkit-margin-collapse"},{"name":"-webkit-margin-end"},{"name":"-webkit-margin-start"},{"name":"-webkit-margin-top-collapse"},{"longhands":["-webkit-mask-image","-webkit-mask-position-x","-webkit-mask-position-y","-webkit-mask-size","-webkit-mask-repeat-x","-webkit-mask-repeat-y","-webkit-mask-origin","-webkit-mask-clip"],"name":"-webkit-mask"},{"longhands":["-webkit-mask-box-image-source","-webkit-mask-box-image-slice","-webkit-mask-box-image-width","-webkit-mask-box-image-outset","-webkit-mask-box-image-repeat"],"name":"-webkit-mask-box-image"},{"name":"-webkit-mask-box-image-outset"},{"name":"-webkit-mask-box-image-repeat"},{"name":"-webkit-mask-box-image-slice"},{"name":"-webkit-mask-box-image-source"},{"name":"-webkit-mask-box-image-width"},{"name":"-webkit-mask-clip"},{"name":"-webkit-mask-composite"},{"name":"-webkit-mask-image"},{"name":"-webkit-mask-origin"},{"longhands":["-webkit-mask-position-x","-webkit-mask-position-y"],"name":"-webkit-mask-position"},{"name":"-webkit-mask-position-x"},{"name":"-webkit-mask-position-y"},{"longhands":["-webkit-mask-repeat-x","-webkit-mask-repeat-y"],"name":"-webkit-mask-repeat"},{"name":"-webkit-mask-repeat-x"},{"name":"-webkit-mask-repeat-y"},{"name":"-webkit-mask-size"},{"name":"-webkit-max-logical-height"},{"name":"-webkit-max-logical-width"},{"name":"-webkit-min-logical-height"},{"name":"-webkit-min-logical-width"},{"name":"-webkit-padding-after"},{"name":"-webkit-padding-before"},{"name":"-webkit-padding-end"},{"name":"-webkit-padding-start"},{"name":"-webkit-perspective-origin-x"},{"name":"-webkit-perspective-origin-y"},{"name":"-webkit-print-color-adjust","inherited":true},{"name":"-webkit-rtl-ordering","inherited":true},{"name":"-webkit-ruby-position","inherited":true},{"name":"-webkit-tap-highlight-color","inherited":true},{"name":"-webkit-text-combine","inherited":true},{"name":"-webkit-text-decorations-in-effect","inherited":true},{"longhands":["-webkit-text-emphasis-style","-webkit-text-emphasis-color"],"name":"-webkit-text-emphasis","inherited":true},{"name":"-webkit-text-emphasis-color","inherited":true},{"name":"-webkit-text-emphasis-position","inherited":true},{"name":"-webkit-text-emphasis-style","inherited":true},{"name":"-webkit-text-fill-color","inherited":true},{"name":"-webkit-text-orientation","inherited":true},{"name":"-webkit-text-security","inherited":true},{"longhands":["-webkit-text-stroke-width","-webkit-text-stroke-color"],"name":"-webkit-text-stroke","inherited":true},{"name":"-webkit-text-stroke-color","inherited":true},{"name":"-webkit-text-stroke-width","inherited":true},{"name":"-webkit-transform-origin-x"},{"name":"-webkit-transform-origin-y"},{"name":"-webkit-transform-origin-z"},{"name":"-webkit-user-drag"},{"name":"-webkit-user-modify","inherited":true},{"name":"-webkit-writing-mode","inherited":true},{"name":"align-content"},{"name":"align-items"},{"name":"align-self"},{"svg":true,"name":"alignment-baseline"},{"name":"all"},{"longhands":["animation-name","animation-duration","animation-timing-function","animation-delay","animation-iteration-count","animation-direction","animation-fill-mode","animation-play-state"],"name":"animation"},{"name":"animation-delay"},{"name":"animation-direction"},{"name":"animation-duration"},{"name":"animation-fill-mode"},{"name":"animation-iteration-count"},{"name":"animation-name"},{"name":"animation-play-state"},{"name":"animation-timing-function"},{"name":"backdrop-filter"},{"name":"backface-visibility"},{"longhands":["background-image","background-position-x","background-position-y","background-size","background-repeat-x","background-repeat-y","background-attachment","background-origin","background-clip","background-color"],"name":"background"},{"name":"background-attachment"},{"name":"background-blend-mode"},{"name":"background-clip"},{"name":"background-color"},{"name":"background-image"},{"name":"background-origin"},{"longhands":["background-position-x","background-position-y"],"name":"background-position"},{"name":"background-position-x"},{"name":"background-position-y"},{"longhands":["background-repeat-x","background-repeat-y"],"name":"background-repeat"},{"name":"background-repeat-x"},{"name":"background-repeat-y"},{"name":"background-size"},{"name":"baseline-shift","svg":true},{"name":"block-size"},{"longhands":["border-top-color","border-top-style","border-top-width","border-right-color","border-right-style","border-right-width","border-bottom-color","border-bottom-style","border-bottom-width","border-left-color","border-left-style","border-left-width","border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],"name":"border"},{"longhands":["border-bottom-width","border-bottom-style","border-bottom-color"],"name":"border-bottom"},{"name":"border-bottom-color"},{"name":"border-bottom-left-radius"},{"name":"border-bottom-right-radius"},{"name":"border-bottom-style"},{"name":"border-bottom-width"},{"name":"border-collapse","inherited":true},{"longhands":["border-top-color","border-right-color","border-bottom-color","border-left-color"],"name":"border-color"},{"longhands":["border-image-source","border-image-slice","border-image-width","border-image-outset","border-image-repeat"],"name":"border-image"},{"name":"border-image-outset"},{"name":"border-image-repeat"},{"name":"border-image-slice"},{"name":"border-image-source"},{"name":"border-image-width"},{"longhands":["border-left-width","border-left-style","border-left-color"],"name":"border-left"},{"name":"border-left-color"},{"name":"border-left-style"},{"name":"border-left-width"},{"longhands":["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],"name":"border-radius"},{"longhands":["border-right-width","border-right-style","border-right-color"],"name":"border-right"},{"name":"border-right-color"},{"name":"border-right-style"},{"name":"border-right-width"},{"longhands":["-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing"],"name":"border-spacing","inherited":true},{"longhands":["border-top-style","border-right-style","border-bottom-style","border-left-style"],"name":"border-style"},{"longhands":["border-top-width","border-top-style","border-top-color"],"name":"border-top"},{"name":"border-top-color"},{"name":"border-top-left-radius"},{"name":"border-top-right-radius"},{"name":"border-top-style"},{"name":"border-top-width"},{"longhands":["border-top-width","border-right-width","border-bottom-width","border-left-width"],"name":"border-width"},{"name":"bottom"},{"name":"box-shadow"},{"name":"box-sizing"},{"name":"break-after"},{"name":"break-before"},{"name":"break-inside"},{"svg":true,"name":"buffered-rendering"},{"name":"caption-side","inherited":true},{"name":"caret-color","inherited":true},{"name":"clear"},{"name":"clip"},{"name":"clip-path"},{"svg":true,"name":"clip-rule","inherited":true},{"name":"color","inherited":true},{"svg":true,"name":"color-interpolation","inherited":true},{"svg":true,"name":"color-interpolation-filters","inherited":true},{"svg":true,"name":"color-rendering","inherited":true},{"name":"column-count"},{"name":"column-fill"},{"name":"column-gap"},{"longhands":["column-rule-width","column-rule-style","column-rule-color"],"name":"column-rule"},{"name":"column-rule-color"},{"name":"column-rule-style"},{"name":"column-rule-width"},{"name":"column-span"},{"name":"column-width"},{"longhands":["column-width","column-count"],"name":"columns"},{"name":"contain"},{"name":"content"},{"name":"counter-increment"},{"name":"counter-reset"},{"name":"cursor","inherited":true},{"svg":true,"name":"cx"},{"svg":true,"name":"cy"},{"svg":true,"name":"d"},{"name":"direction","inherited":true},{"name":"display"},{"svg":true,"name":"dominant-baseline","inherited":true},{"name":"empty-cells","inherited":true},{"name":"fill","svg":true,"inherited":true},{"svg":true,"inherited":true,"name":"fill-opacity"},{"svg":true,"name":"fill-rule","inherited":true},{"name":"filter"},{"longhands":["flex-grow","flex-shrink","flex-basis"],"name":"flex"},{"name":"flex-basis"},{"name":"flex-direction"},{"longhands":["flex-direction","flex-wrap"],"name":"flex-flow"},{"name":"flex-grow"},{"name":"flex-shrink"},{"name":"flex-wrap"},{"name":"float"},{"svg":true,"name":"flood-color"},{"svg":true,"name":"flood-opacity"},{"longhands":["font-style","font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian","font-weight","font-stretch","font-size","line-height","font-family"],"name":"font","inherited":true},{"name":"font-display"},{"name":"font-family","inherited":true},{"name":"font-feature-settings","inherited":true},{"name":"font-kerning","inherited":true},{"name":"font-size","inherited":true},{"name":"font-size-adjust","inherited":true},{"name":"font-stretch","inherited":true},{"name":"font-style","inherited":true},{"longhands":["font-variant-ligatures","font-variant-caps","font-variant-numeric","font-variant-east-asian"],"name":"font-variant","inherited":true},{"inherited":true,"name":"font-variant-caps"},{"inherited":true,"name":"font-variant-east-asian"},{"name":"font-variant-ligatures","inherited":true},{"inherited":true,"name":"font-variant-numeric"},{"name":"font-variation-settings","inherited":true},{"name":"font-weight","inherited":true},{"longhands":["row-gap","column-gap"],"name":"gap"},{"longhands":["grid-template-rows","grid-template-columns","grid-template-areas","grid-auto-flow","grid-auto-rows","grid-auto-columns"],"name":"grid"},{"longhands":["grid-row-start","grid-column-start","grid-row-end","grid-column-end"],"name":"grid-area"},{"name":"grid-auto-columns"},{"name":"grid-auto-flow"},{"name":"grid-auto-rows"},{"longhands":["grid-column-start","grid-column-end"],"name":"grid-column"},{"name":"grid-column-end"},{"longhands":["column-gap"],"name":"grid-column-gap"},{"name":"grid-column-start"},{"longhands":["row-gap","column-gap"],"name":"grid-gap"},{"longhands":["grid-row-start","grid-row-end"],"name":"grid-row"},{"name":"grid-row-end"},{"longhands":["row-gap"],"name":"grid-row-gap"},{"name":"grid-row-start"},{"longhands":["grid-template-rows","grid-template-columns","grid-template-areas"],"name":"grid-template"},{"name":"grid-template-areas"},{"name":"grid-template-columns"},{"name":"grid-template-rows"},{"name":"height"},{"name":"hyphens","inherited":true},{"name":"image-orientation","inherited":true},{"name":"image-rendering","inherited":true},{"name":"inline-size"},{"name":"isolation"},{"name":"justify-content"},{"name":"justify-items"},{"name":"justify-self"},{"name":"left"},{"name":"letter-spacing","inherited":true},{"svg":true,"name":"lighting-color"},{"name":"line-break","inherited":true},{"name":"line-height","inherited":true},{"name":"line-height-step","inherited":true},{"longhands":["list-style-type","list-style-position","list-style-image"],"name":"list-style","inherited":true},{"name":"list-style-image","inherited":true},{"name":"list-style-position","inherited":true},{"name":"list-style-type","inherited":true},{"longhands":["margin-top","margin-right","margin-bottom","margin-left"],"name":"margin"},{"name":"margin-bottom"},{"name":"margin-left"},{"name":"margin-right"},{"name":"margin-top"},{"longhands":["marker-start","marker-mid","marker-end"],"name":"marker","inherited":true},{"svg":true,"inherited":true,"name":"marker-end"},{"svg":true,"inherited":true,"name":"marker-mid"},{"svg":true,"inherited":true,"name":"marker-start"},{"svg":true,"name":"mask"},{"name":"mask-source-type"},{"svg":true,"name":"mask-type"},{"name":"max-block-size"},{"name":"max-height"},{"name":"max-inline-size"},{"name":"max-width"},{"name":"max-zoom"},{"name":"min-block-size"},{"name":"min-height"},{"name":"min-inline-size"},{"name":"min-width"},{"name":"min-zoom"},{"name":"mix-blend-mode"},{"name":"object-fit"},{"name":"object-position"},{"longhands":["offset-position","offset-path","offset-distance","offset-rotate","offset-anchor"],"name":"offset"},{"name":"offset-anchor"},{"name":"offset-distance"},{"name":"offset-path"},{"name":"offset-position"},{"name":"offset-rotate"},{"name":"opacity"},{"name":"order"},{"name":"orientation"},{"name":"orphans","inherited":true},{"longhands":["outline-color","outline-style","outline-width"],"name":"outline"},{"name":"outline-color"},{"name":"outline-offset"},{"name":"outline-style"},{"name":"outline-width"},{"longhands":["overflow-x","overflow-y"],"name":"overflow"},{"name":"overflow-anchor","inherited":false},{"name":"overflow-wrap","inherited":true},{"name":"overflow-x"},{"name":"overflow-y"},{"longhands":["overscroll-behavior-x","overscroll-behavior-y"],"name":"overscroll-behavior"},{"name":"overscroll-behavior-x"},{"name":"overscroll-behavior-y"},{"longhands":["padding-top","padding-right","padding-bottom","padding-left"],"name":"padding"},{"name":"padding-bottom"},{"name":"padding-left"},{"name":"padding-right"},{"name":"padding-top"},{"name":"page"},{"longhands":["break-after"],"name":"page-break-after"},{"longhands":["break-before"],"name":"page-break-before"},{"longhands":["break-inside"],"name":"page-break-inside"},{"svg":true,"name":"paint-order","inherited":true},{"name":"perspective"},{"name":"perspective-origin"},{"longhands":["align-content","justify-content"],"name":"place-content"},{"longhands":["align-items","justify-items"],"name":"place-items"},{"longhands":["align-self","justify-self"],"name":"place-self"},{"name":"pointer-events","inherited":true},{"name":"position"},{"name":"quotes","inherited":true},{"svg":true,"name":"r"},{"name":"resize"},{"name":"right"},{"name":"rotate"},{"name":"row-gap"},{"name":"rx","svg":true},{"name":"ry","svg":true},{"name":"scale"},{"name":"scroll-behavior"},{"name":"scroll-customization"},{"longhands":["scroll-margin-top","scroll-margin-right","scroll-margin-bottom","scroll-margin-left"],"name":"scroll-margin"},{"longhands":["scroll-margin-block-start","scroll-margin-block-end"],"name":"scroll-margin-block"},{"name":"scroll-margin-block-end"},{"name":"scroll-margin-block-start"},{"name":"scroll-margin-bottom"},{"longhands":["scroll-margin-inline-start","scroll-margin-inline-end"],"name":"scroll-margin-inline"},{"name":"scroll-margin-inline-end"},{"name":"scroll-margin-inline-start"},{"name":"scroll-margin-left"},{"name":"scroll-margin-right"},{"name":"scroll-margin-top"},{"longhands":["scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left"],"name":"scroll-padding"},{"longhands":["scroll-padding-block-start","scroll-padding-block-end"],"name":"scroll-padding-block"},{"name":"scroll-padding-block-end"},{"name":"scroll-padding-block-start"},{"name":"scroll-padding-bottom"},{"longhands":["scroll-padding-inline-start","scroll-padding-inline-end"],"name":"scroll-padding-inline"},{"name":"scroll-padding-inline-end"},{"name":"scroll-padding-inline-start"},{"name":"scroll-padding-left"},{"name":"scroll-padding-right"},{"name":"scroll-padding-top"},{"name":"scroll-snap-align"},{"name":"scroll-snap-stop"},{"name":"scroll-snap-type"},{"name":"shape-image-threshold"},{"name":"shape-margin"},{"name":"shape-outside"},{"svg":true,"name":"shape-rendering","inherited":true},{"name":"size"},{"name":"speak","inherited":true},{"name":"src"},{"svg":true,"name":"stop-color"},{"svg":true,"name":"stop-opacity"},{"name":"stroke","svg":true,"inherited":true},{"name":"stroke-dasharray","svg":true,"inherited":true},{"name":"stroke-dashoffset","svg":true,"inherited":true},{"name":"stroke-linecap","svg":true,"inherited":true},{"name":"stroke-linejoin","svg":true,"inherited":true},{"name":"stroke-miterlimit","svg":true,"inherited":true},{"svg":true,"inherited":true,"name":"stroke-opacity"},{"svg":true,"inherited":true,"name":"stroke-width"},{"name":"tab-size","inherited":true},{"name":"table-layout"},{"name":"text-align","inherited":true},{"name":"text-align-last","inherited":true},{"name":"text-anchor","svg":true,"inherited":true},{"name":"text-combine-upright","inherited":true},{"longhands":["text-decoration-line","text-decoration-style","text-decoration-color"],"name":"text-decoration"},{"name":"text-decoration-color"},{"name":"text-decoration-line"},{"name":"text-decoration-skip-ink","inherited":true},{"name":"text-decoration-style"},{"name":"text-indent","inherited":true},{"name":"text-justify","inherited":true},{"name":"text-orientation","inherited":true},{"name":"text-overflow"},{"name":"text-rendering","inherited":true},{"name":"text-shadow","inherited":true},{"name":"text-size-adjust","inherited":true},{"name":"text-transform","inherited":true},{"name":"text-underline-position","inherited":true},{"name":"top"},{"name":"touch-action"},{"name":"transform"},{"name":"transform-box"},{"name":"transform-origin"},{"name":"transform-style"},{"longhands":["transition-property","transition-duration","transition-timing-function","transition-delay"],"name":"transition"},{"name":"transition-delay"},{"name":"transition-duration"},{"name":"transition-property"},{"name":"transition-timing-function"},{"name":"translate"},{"name":"unicode-bidi"},{"name":"unicode-range"},{"name":"user-select","inherited":true},{"name":"user-zoom"},{"svg":true,"name":"vector-effect"},{"name":"vertical-align"},{"name":"visibility","inherited":true},{"name":"white-space","inherited":true},{"name":"widows","inherited":true},{"name":"width"},{"name":"will-change"},{"name":"word-break","inherited":true},{"name":"word-spacing","inherited":true},{"name":"word-wrap","inherited":true},{"name":"writing-mode","inherited":true},{"svg":true,"name":"x"},{"svg":true,"name":"y"},{"name":"z-index"},{"name":"zoom"}];;SDK.FilmStripModel=class{constructor(tracingModel,zeroTime){this.reset(tracingModel,zeroTime);}
reset(tracingModel,zeroTime){this._zeroTime=zeroTime||tracingModel.minimumRecordTime();this._spanTime=tracingModel.maximumRecordTime()-this._zeroTime;this._frames=[];const browserMain=SDK.TracingModel.browserMainThread(tracingModel);if(!browserMain)
return;const events=browserMain.events();for(let i=0;i<events.length;++i){const event=events[i];if(event.startTime<this._zeroTime)
continue;if(!event.hasCategory(SDK.FilmStripModel._category))
continue;if(event.name===SDK.FilmStripModel.TraceEvents.CaptureFrame){const data=event.args['data'];if(data)
this._frames.push(SDK.FilmStripModel.Frame._fromEvent(this,event,this._frames.length));}else if(event.name===SDK.FilmStripModel.TraceEvents.Screenshot){this._frames.push(SDK.FilmStripModel.Frame._fromSnapshot(this,(event),this._frames.length));}}}
frames(){return this._frames;}
zeroTime(){return this._zeroTime;}
spanTime(){return this._spanTime;}
frameByTimestamp(timestamp){const index=this._frames.upperBound(timestamp,(timestamp,frame)=>timestamp-frame.timestamp)-1;return index>=0?this._frames[index]:null;}};SDK.FilmStripModel._category='disabled-by-default-devtools.screenshot';SDK.FilmStripModel.TraceEvents={CaptureFrame:'CaptureFrame',Screenshot:'Screenshot'};SDK.FilmStripModel.Frame=class{constructor(model,timestamp,index){this._model=model;this.timestamp=timestamp;this.index=index;this._imageData=null;this._snapshot=null;}
static _fromEvent(model,event,index){const frame=new SDK.FilmStripModel.Frame(model,event.startTime,index);frame._imageData=event.args['data'];return frame;}
static _fromSnapshot(model,snapshot,index){const frame=new SDK.FilmStripModel.Frame(model,snapshot.startTime,index);frame._snapshot=snapshot;return frame;}
model(){return this._model;}
imageDataPromise(){if(this._imageData||!this._snapshot)
return Promise.resolve(this._imageData);return(this._snapshot.objectPromise());}};;SDK.ConsoleModel=class extends Common.Object{constructor(){super();this._messages=[];this._messageByExceptionId=new Map();this._warnings=0;this._errors=0;this._pageLoadSequenceNumber=0;SDK.targetManager.observeTargets(this);}
targetAdded(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel||resourceTreeModel.cachedResourcesLoaded()){this._initTarget(target);return;}
const eventListener=resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded,()=>{Common.EventTarget.removeEventListeners([eventListener]);this._initTarget(target);});}
_initTarget(target){const eventListeners=[];const cpuProfilerModel=target.model(SDK.CPUProfilerModel);if(cpuProfilerModel){eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileStarted,this._consoleProfileStarted.bind(this,cpuProfilerModel)));eventListeners.push(cpuProfilerModel.addEventListener(SDK.CPUProfilerModel.Events.ConsoleProfileFinished,this._consoleProfileFinished.bind(this,cpuProfilerModel)));}
const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(resourceTreeModel&&!target.parentTarget()){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._mainFrameNavigated,this));}
const runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel){eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionThrown,this._exceptionThrown.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExceptionRevoked,this._exceptionRevoked.bind(this,runtimeModel)));eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.ConsoleAPICalled,this._consoleAPICalled.bind(this,runtimeModel)));if(!target.parentTarget()){eventListeners.push(runtimeModel.debuggerModel().addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._clearIfNecessary,this));}
eventListeners.push(runtimeModel.addEventListener(SDK.RuntimeModel.Events.QueryObjectRequested,this._queryObjectRequested.bind(this,runtimeModel)));}
target[SDK.ConsoleModel._events]=eventListeners;}
targetRemoved(target){const runtimeModel=target.model(SDK.RuntimeModel);if(runtimeModel)
this._messageByExceptionId.delete(runtimeModel);Common.EventTarget.removeEventListeners(target[SDK.ConsoleModel._events]||[]);}
async evaluateCommandInConsole(executionContext,originatingMessage,expression,useCommandLineAPI,awaitPromise){const result=await executionContext.evaluate({expression:expression,objectGroup:'console',includeCommandLineAPI:useCommandLineAPI,silent:false,returnByValue:false,generatePreview:true},true,awaitPromise);Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConsoleEvaluated);if(result.error)
return;await Common.console.showPromise();this.dispatchEventToListeners(SDK.ConsoleModel.Events.CommandEvaluated,{result:result.object,commandMessage:originatingMessage,exceptionDetails:result.exceptionDetails});}
addCommandMessage(executionContext,text){const commandMessage=new SDK.ConsoleMessage(executionContext.runtimeModel,SDK.ConsoleMessage.MessageSource.JS,null,text,SDK.ConsoleMessage.MessageType.Command);commandMessage.setExecutionContextId(executionContext.id);this.addMessage(commandMessage);return commandMessage;}
addMessage(msg){if(msg.source===SDK.ConsoleMessage.MessageSource.Worker&&SDK.targetManager.targetById(msg.workerId))
return;msg._pageLoadSequenceNumber=this._pageLoadSequenceNumber;if(msg.source===SDK.ConsoleMessage.MessageSource.ConsoleAPI&&msg.type===SDK.ConsoleMessage.MessageType.Clear)
this._clearIfNecessary();this._messages.push(msg);const runtimeModel=msg.runtimeModel();if(msg._exceptionId&&runtimeModel){let modelMap=this._messageByExceptionId.get(runtimeModel);if(!modelMap){modelMap=new Map();this._messageByExceptionId.set(runtimeModel,modelMap);}
modelMap.set(msg._exceptionId,msg);}
this._incrementErrorWarningCount(msg);this.dispatchEventToListeners(SDK.ConsoleModel.Events.MessageAdded,msg);}
_exceptionThrown(runtimeModel,event){const exceptionWithTimestamp=(event.data);const consoleMessage=SDK.ConsoleMessage.fromException(runtimeModel,exceptionWithTimestamp.details,undefined,exceptionWithTimestamp.timestamp,undefined);consoleMessage.setExceptionId(exceptionWithTimestamp.details.exceptionId);this.addMessage(consoleMessage);}
_exceptionRevoked(runtimeModel,event){const exceptionId=(event.data);const modelMap=this._messageByExceptionId.get(runtimeModel);const exceptionMessage=modelMap?modelMap.get(exceptionId):null;if(!exceptionMessage)
return;this._errors--;exceptionMessage.level=SDK.ConsoleMessage.MessageLevel.Info;this.dispatchEventToListeners(SDK.ConsoleModel.Events.MessageUpdated,exceptionMessage);}
_consoleAPICalled(runtimeModel,event){const call=(event.data);let level=SDK.ConsoleMessage.MessageLevel.Info;if(call.type===SDK.ConsoleMessage.MessageType.Debug)
level=SDK.ConsoleMessage.MessageLevel.Verbose;else if(call.type===SDK.ConsoleMessage.MessageType.Error||call.type===SDK.ConsoleMessage.MessageType.Assert)
level=SDK.ConsoleMessage.MessageLevel.Error;else if(call.type===SDK.ConsoleMessage.MessageType.Warning)
level=SDK.ConsoleMessage.MessageLevel.Warning;else if(call.type===SDK.ConsoleMessage.MessageType.Info||call.type===SDK.ConsoleMessage.MessageType.Log)
level=SDK.ConsoleMessage.MessageLevel.Info;let message='';if(call.args.length&&call.args[0].unserializableValue)
message=call.args[0].unserializableValue;else if(call.args.length&&(typeof call.args[0].value!=='object'||call.args[0].value===null))
message=call.args[0].value+'';else if(call.args.length&&call.args[0].description)
message=call.args[0].description;const callFrame=call.stackTrace&&call.stackTrace.callFrames.length?call.stackTrace.callFrames[0]:null;const consoleMessage=new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.ConsoleAPI,level,(message),call.type,callFrame?callFrame.url:undefined,callFrame?callFrame.lineNumber:undefined,callFrame?callFrame.columnNumber:undefined,call.args,call.stackTrace,call.timestamp,call.executionContextId,undefined,undefined,call.context);this.addMessage(consoleMessage);}
_queryObjectRequested(runtimeModel,event){const consoleMessage=new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.ConsoleAPI,SDK.ConsoleMessage.MessageLevel.Info,'',SDK.ConsoleMessage.MessageType.QueryObjectResult,undefined,undefined,undefined,[event.data.objects]);this.addMessage(consoleMessage);}
_clearIfNecessary(){if(!Common.moduleSetting('preserveConsoleLog').get())
this._clear();++this._pageLoadSequenceNumber;}
_mainFrameNavigated(event){if(Common.moduleSetting('preserveConsoleLog').get())
Common.console.log(Common.UIString('Navigated to %s',event.data.url));}
_consoleProfileStarted(cpuProfilerModel,event){const data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,SDK.ConsoleMessage.MessageType.Profile,data.scriptLocation,Common.UIString('Profile \'%s\' started.',data.title));}
_consoleProfileFinished(cpuProfilerModel,event){const data=(event.data);this._addConsoleProfileMessage(cpuProfilerModel,SDK.ConsoleMessage.MessageType.ProfileEnd,data.scriptLocation,Common.UIString('Profile \'%s\' finished.',data.title));}
_addConsoleProfileMessage(cpuProfilerModel,type,scriptLocation,messageText){const stackTrace=[{functionName:'',scriptId:scriptLocation.scriptId,url:scriptLocation.script()?scriptLocation.script().contentURL():'',lineNumber:scriptLocation.lineNumber,columnNumber:scriptLocation.columnNumber||0}];this.addMessage(new SDK.ConsoleMessage(cpuProfilerModel.runtimeModel(),SDK.ConsoleMessage.MessageSource.ConsoleAPI,SDK.ConsoleMessage.MessageLevel.Info,messageText,type,undefined,undefined,undefined,stackTrace));}
_incrementErrorWarningCount(msg){if(msg.source===SDK.ConsoleMessage.MessageSource.Violation)
return;switch(msg.level){case SDK.ConsoleMessage.MessageLevel.Warning:this._warnings++;break;case SDK.ConsoleMessage.MessageLevel.Error:this._errors++;break;}}
messages(){return this._messages;}
requestClearMessages(){for(const logModel of SDK.targetManager.models(SDK.LogModel))
logModel.requestClear();for(const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel))
runtimeModel.discardConsoleEntries();this._clear();}
_clear(){this._messages=[];this._messageByExceptionId.clear();this._errors=0;this._warnings=0;this.dispatchEventToListeners(SDK.ConsoleModel.Events.ConsoleCleared);}
errors(){return this._errors;}
warnings(){return this._warnings;}};SDK.ConsoleModel.Events={ConsoleCleared:Symbol('ConsoleCleared'),MessageAdded:Symbol('MessageAdded'),MessageUpdated:Symbol('MessageUpdated'),CommandEvaluated:Symbol('CommandEvaluated')};SDK.ConsoleMessage=class{constructor(runtimeModel,source,level,messageText,type,url,line,column,parameters,stackTrace,timestamp,executionContextId,scriptId,workerId,context){this._runtimeModel=runtimeModel;this.source=source;this.level=(level);this.messageText=messageText;this.type=type||SDK.ConsoleMessage.MessageType.Log;this.url=url||undefined;this.line=line||0;this.column=column||0;this.parameters=parameters;this.stackTrace=stackTrace;this.timestamp=timestamp||Date.now();this.executionContextId=executionContextId||0;this.scriptId=scriptId||null;this.workerId=workerId||null;if(!this.executionContextId&&this._runtimeModel){if(this.scriptId)
this.executionContextId=this._runtimeModel.executionContextIdForScriptId(this.scriptId);else if(this.stackTrace)
this.executionContextId=this._runtimeModel.executionContextForStackTrace(this.stackTrace);}
if(context)
this.context=context.match(/[^#]*/)[0];}
static fromException(runtimeModel,exceptionDetails,messageType,timestamp,forceUrl){return new SDK.ConsoleMessage(runtimeModel,SDK.ConsoleMessage.MessageSource.JS,SDK.ConsoleMessage.MessageLevel.Error,SDK.RuntimeModel.simpleTextFromException(exceptionDetails),messageType,forceUrl||exceptionDetails.url,exceptionDetails.lineNumber,exceptionDetails.columnNumber,exceptionDetails.exception?[SDK.RemoteObject.fromLocalObject(exceptionDetails.text),exceptionDetails.exception]:undefined,exceptionDetails.stackTrace,timestamp,exceptionDetails.executionContextId,exceptionDetails.scriptId);}
runtimeModel(){return this._runtimeModel;}
target(){return this._runtimeModel?this._runtimeModel.target():null;}
setOriginatingMessage(originatingMessage){this._originatingConsoleMessage=originatingMessage;this.executionContextId=originatingMessage.executionContextId;}
setExecutionContextId(executionContextId){this.executionContextId=executionContextId;}
setExceptionId(exceptionId){this._exceptionId=exceptionId;}
originatingMessage(){return this._originatingConsoleMessage;}
isGroupMessage(){return this.type===SDK.ConsoleMessage.MessageType.StartGroup||this.type===SDK.ConsoleMessage.MessageType.StartGroupCollapsed||this.type===SDK.ConsoleMessage.MessageType.EndGroup;}
isGroupStartMessage(){return this.type===SDK.ConsoleMessage.MessageType.StartGroup||this.type===SDK.ConsoleMessage.MessageType.StartGroupCollapsed;}
isErrorOrWarning(){return(this.level===SDK.ConsoleMessage.MessageLevel.Warning||this.level===SDK.ConsoleMessage.MessageLevel.Error);}
isGroupable(){const isUngroupableError=this.level===SDK.ConsoleMessage.MessageLevel.Error&&(this.source===SDK.ConsoleMessage.MessageSource.JS||this.source===SDK.ConsoleMessage.MessageSource.Network);return(this.source!==SDK.ConsoleMessage.MessageSource.ConsoleAPI&&this.type!==SDK.ConsoleMessage.MessageType.Command&&this.type!==SDK.ConsoleMessage.MessageType.Result&&this.type!==SDK.ConsoleMessage.MessageType.System&&!isUngroupableError);}
groupCategoryKey(){return[this.source,this.level,this.type,this._pageLoadSequenceNumber].join(':');}
isEqual(msg){if(!msg)
return false;if(!this._isEqualStackTraces(this.stackTrace,msg.stackTrace))
return false;if(this.parameters){if(!msg.parameters||this.parameters.length!==msg.parameters.length)
return false;for(let i=0;i<msg.parameters.length;++i){if(msg.parameters[i].type==='object'&&msg.parameters[i].subtype!=='error')
return false;if(this.parameters[i].type!==msg.parameters[i].type||this.parameters[i].value!==msg.parameters[i].value||this.parameters[i].description!==msg.parameters[i].description)
return false;}}
return(this.runtimeModel()===msg.runtimeModel())&&(this.source===msg.source)&&(this.type===msg.type)&&(this.level===msg.level)&&(this.line===msg.line)&&(this.url===msg.url)&&(this.messageText===msg.messageText)&&(this.request===msg.request)&&(this.executionContextId===msg.executionContextId);}
_isEqualStackTraces(stackTrace1,stackTrace2){if(!stackTrace1!==!stackTrace2)
return false;if(!stackTrace1)
return true;const callFrames1=stackTrace1.callFrames;const callFrames2=stackTrace2.callFrames;if(callFrames1.length!==callFrames2.length)
return false;for(let i=0,n=callFrames1.length;i<n;++i){if(callFrames1[i].url!==callFrames2[i].url||callFrames1[i].functionName!==callFrames2[i].functionName||callFrames1[i].lineNumber!==callFrames2[i].lineNumber||callFrames1[i].columnNumber!==callFrames2[i].columnNumber)
return false;}
return this._isEqualStackTraces(stackTrace1.parent,stackTrace2.parent);}};SDK.ConsoleMessage.MessageSource={XML:'xml',JS:'javascript',Network:'network',ConsoleAPI:'console-api',Storage:'storage',AppCache:'appcache',Rendering:'rendering',CSS:'css',Security:'security',Deprecation:'deprecation',Worker:'worker',Violation:'violation',Intervention:'intervention',Recommendation:'recommendation',Other:'other'};SDK.ConsoleMessage.MessageType={Log:'log',Debug:'debug',Info:'info',Error:'error',Warning:'warning',Dir:'dir',DirXML:'dirxml',Table:'table',Trace:'trace',Clear:'clear',StartGroup:'startGroup',StartGroupCollapsed:'startGroupCollapsed',EndGroup:'endGroup',Assert:'assert',Result:'result',Profile:'profile',ProfileEnd:'profileEnd',Command:'command',System:'system',QueryObjectResult:'queryObjectResult'};SDK.ConsoleMessage.MessageLevel={Verbose:'verbose',Info:'info',Warning:'warning',Error:'error'};SDK.ConsoleMessage.MessageSourceDisplayName=new Map([[SDK.ConsoleMessage.MessageSource.XML,'xml'],[SDK.ConsoleMessage.MessageSource.JS,'javascript'],[SDK.ConsoleMessage.MessageSource.Network,'network'],[SDK.ConsoleMessage.MessageSource.ConsoleAPI,'console-api'],[SDK.ConsoleMessage.MessageSource.Storage,'storage'],[SDK.ConsoleMessage.MessageSource.AppCache,'appcache'],[SDK.ConsoleMessage.MessageSource.Rendering,'rendering'],[SDK.ConsoleMessage.MessageSource.CSS,'css'],[SDK.ConsoleMessage.MessageSource.Security,'security'],[SDK.ConsoleMessage.MessageSource.Deprecation,'deprecation'],[SDK.ConsoleMessage.MessageSource.Worker,'worker'],[SDK.ConsoleMessage.MessageSource.Violation,'violation'],[SDK.ConsoleMessage.MessageSource.Intervention,'intervention'],[SDK.ConsoleMessage.MessageSource.Recommendation,'recommendation'],[SDK.ConsoleMessage.MessageSource.Other,'other']]);SDK.ConsoleModel._events=Symbol('SDK.ConsoleModel.events');SDK.consoleModel;;self['Services']=self['Services']||{};Services.ServiceManager=class{createRemoteService(serviceName){if(!this._remoteConnection){const url=Runtime.queryParam('service-backend');if(!url){console.error('No endpoint address specified');return(Promise.resolve(null));}
this._remoteConnection=new Services.ServiceManager.Connection(new Services.ServiceManager.RemoteServicePort(url));}
return this._remoteConnection._createService(serviceName);}
createAppService(appName,serviceName){let url=appName+'.js';const remoteBase=Runtime.queryParam('remoteBase');const debugFrontend=Runtime.queryParam('debugFrontend');const isUnderTest=Host.isUnderTest();const queryParams=[];if(remoteBase)
queryParams.push('remoteBase='+remoteBase);if(debugFrontend)
queryParams.push('debugFrontend='+debugFrontend);if(isUnderTest)
queryParams.push('isUnderTest=true');if(queryParams.length)
url+=`?${queryParams.join('&')}`;const worker=new Worker(url);const connection=new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker));return connection._createService(serviceName);}};Services.ServiceManager.Connection=class{constructor(port){this._port=port;this._port.setHandlers(this._onMessage.bind(this),this._connectionClosed.bind(this));this._lastId=1;this._callbacks=new Map();this._services=new Map();}
_createService(serviceName){return this._sendCommand(serviceName+'.create').then(result=>{if(!result){console.error('Could not initialize service: '+serviceName);return null;}
const service=new Services.ServiceManager.Service(this,serviceName,result.id);this._services.set(serviceName+':'+result.id,service);return service;});}
_serviceDisposed(service){this._services.delete(service._serviceName+':'+service._objectId);if(!this._services.size){this._port.close();}}
_sendCommand(method,params){const id=this._lastId++;const message=JSON.stringify({id:id,method:method,params:params||{}});return this._port.send(message).then(success=>{if(!success)
return Promise.resolve(null);return new Promise(fulfill=>this._callbacks.set(id,fulfill));});}
_onMessage(data){let object;try{object=JSON.parse(data);}catch(e){console.error(e);return;}
if(object.id){if(object.error)
console.error('Service error: '+object.error);this._callbacks.get(object.id)(object.error?null:object.result);this._callbacks.delete(object.id);return;}
const tokens=object.method.split('.');const serviceName=tokens[0];const methodName=tokens[1];const service=this._services.get(serviceName+':'+object.params.id);if(!service){console.error('Unable to lookup stub for '+serviceName+':'+object.params.id);return;}
service._dispatchNotification(methodName,object.params);}
_connectionClosed(){for(const callback of this._callbacks.values())
callback(null);this._callbacks.clear();for(const service of this._services.values())
service._dispatchNotification('disposed');this._services.clear();}};Services.ServiceManager.Service=class{constructor(connection,serviceName,objectId){this._connection=connection;this._serviceName=serviceName;this._objectId=objectId;this._notificationHandlers=new Map();}
dispose(){const params={id:this._objectId};return this._connection._sendCommand(this._serviceName+'.dispose',params).then(()=>{this._connection._serviceDisposed(this);});}
on(methodName,handler){this._notificationHandlers.set(methodName,handler);}
send(methodName,params){params=params||{};params.id=this._objectId;return this._connection._sendCommand(this._serviceName+'.'+methodName,params);}
_dispatchNotification(methodName,params){const handler=this._notificationHandlers.get(methodName);if(!handler){console.error('Could not report notification \''+methodName+'\' on \''+this._objectId+'\'');return;}
handler(params);}};Services.ServiceManager.RemoteServicePort=class{constructor(url){this._url=url;}
setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;}
_open(){if(!this._connectionPromise)
this._connectionPromise=new Promise(promiseBody.bind(this));return this._connectionPromise;function promiseBody(fulfill){let socket;try{socket=new WebSocket((this._url));socket.onmessage=onMessage.bind(this);socket.onclose=onClose.bind(this);socket.onopen=onConnect.bind(this);}catch(e){fulfill(false);}
function onConnect(){this._socket=socket;fulfill(true);}
function onMessage(event){this._messageHandler(event.data);}
function onClose(){if(!this._socket)
fulfill(false);this._socketClosed(!!this._socket);}}}
send(message){return this._open().then(()=>{if(this._socket){this._socket.send(message);return true;}
return false;});}
close(){return this._open().then(()=>{if(this._socket){this._socket.close();this._socketClosed(true);}
return true;});}
_socketClosed(notifyClient){this._socket=null;delete this._connectionPromise;if(notifyClient)
this._closeHandler();}};Services.ServiceManager.WorkerServicePort=class{constructor(worker){this._worker=worker;let fulfill;this._workerPromise=new Promise(resolve=>fulfill=resolve);this._worker.onmessage=onMessage.bind(this);this._worker.onclose=this._closeHandler;function onMessage(event){if(event.data==='workerReady'){fulfill(true);return;}
this._messageHandler(event.data);}}
setHandlers(messageHandler,closeHandler){this._messageHandler=messageHandler;this._closeHandler=closeHandler;}
send(message){return this._workerPromise.then(()=>{try{this._worker.postMessage(message);return true;}catch(e){return false;}});}
close(){return this._workerPromise.then(()=>{if(this._worker)
this._worker.terminate();return false;});}};Services.serviceManager=new Services.ServiceManager();;self['Workspace']=self['Workspace']||{};Workspace.FileManager=class extends Common.Object{constructor(){super();this._saveCallbacks=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SavedURL,this._savedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.CanceledSaveURL,this._canceledSavedURL,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AppendedToURL,this._appendedToURL,this);}
save(url,content,forceSaveAs){InspectorFrontendHost.save(url,content,forceSaveAs);return new Promise(resolve=>this._saveCallbacks.set(url,resolve));}
_savedURL(event){const url=(event.data.url);const callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback)
callback({fileSystemPath:(event.data.fileSystemPath)});}
_canceledSavedURL(event){const url=(event.data);const callback=this._saveCallbacks.get(url);this._saveCallbacks.delete(url);if(callback)
callback(null);}
append(url,content){InspectorFrontendHost.append(url,content);}
close(url){}
_appendedToURL(event){const url=(event.data);this.dispatchEventToListeners(Workspace.FileManager.Events.AppendedToURL,url);}};Workspace.FileManager.Events={AppendedToURL:Symbol('AppendedToURL')};Workspace.fileManager;;Workspace.UISourceCode=class extends Common.Object{constructor(project,url,contentType){super();this._project=project;this._url=url;const parsedURL=url.asParsedURL();if(parsedURL){this._origin=parsedURL.securityOrigin();this._parentURL=this._origin+parsedURL.folderPathComponents;this._name=parsedURL.lastPathComponent;if(parsedURL.queryParams)
this._name+='?'+parsedURL.queryParams;}else{this._origin='';this._parentURL='';this._name=url;}
this._contentType=contentType;this._requestContentPromise=null;this._decorations=null;this._hasCommits=false;this._messages=null;this._contentLoaded=false;this._content=null;this._contentEncoded;this._forceLoadOnCheckContent=false;this._checkingContent=false;this._lastAcceptedContent=null;this._workingCopy=null;this._workingCopyGetter=null;}
requestMetadata(){return this._project.requestMetadata(this);}
name(){return this._name;}
mimeType(){return this._project.mimeType(this);}
url(){return this._url;}
parentURL(){return this._parentURL;}
origin(){return this._origin;}
fullDisplayName(){return this._project.fullDisplayName(this);}
displayName(skipTrim){if(!this._name)
return Common.UIString('(index)');let name=this._name;try{if(this.project().type()===Workspace.projectTypes.FileSystem)
name=unescape(name);else
name=decodeURI(name);}catch(e){}
return skipTrim?name:name.trimEnd(100);}
canRename(){return this._project.canRename();}
rename(newName){let fulfill;const promise=new Promise(x=>fulfill=x);this._project.rename(this,newName,innerCallback.bind(this));return promise;function innerCallback(success,newName,newURL,newContentType){if(success){this._updateName((newName),(newURL),(newContentType));}
fulfill(success);}}
remove(){this._project.deleteFile(this);}
_updateName(name,url,contentType){const oldURL=this._url;this._url=this._url.substring(0,this._url.length-this._name.length)+name;this._name=name;if(url)
this._url=url;if(contentType)
this._contentType=contentType;this.dispatchEventToListeners(Workspace.UISourceCode.Events.TitleChanged,this);this.project().workspace().dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRenamed,{oldURL:oldURL,uiSourceCode:this});}
contentURL(){return this.url();}
contentType(){return this._contentType;}
async contentEncoded(){await this.requestContent();return this._contentEncoded||false;}
project(){return this._project;}
requestContent(){if(this._requestContentPromise)
return this._requestContentPromise;if(this._contentLoaded){this._requestContentPromise=Promise.resolve(this._content);}else{let fulfill;this._requestContentPromise=new Promise(x=>fulfill=x);this._project.requestFileContent(this,(content,encoded)=>{if(!this._contentLoaded){this._contentLoaded=true;this._content=content;this._contentEncoded=encoded;}
fulfill(content);});}
return this._requestContentPromise;}
checkContentUpdated(){if(!this._contentLoaded&&!this._forceLoadOnCheckContent)
return;if(!this._project.canSetFileContent()||this._checkingContent)
return;this._checkingContent=true;this._project.requestFileContent(this,contentLoaded.bind(this));async function contentLoaded(updatedContent,encoded){this._checkingContent=false;if(updatedContent===null){const workingCopy=this.workingCopy();this._contentCommitted('',false);this.setWorkingCopy(workingCopy);return;}
if(this._lastAcceptedContent===updatedContent)
return;if(this._content===updatedContent){this._lastAcceptedContent=null;return;}
if(!this.isDirty()||this._workingCopy===updatedContent){this._contentCommitted((updatedContent),false);return;}
await Common.Revealer.reveal(this);await new Promise(resolve=>setTimeout(resolve,0));const shouldUpdate=window.confirm(Common.UIString('This file was changed externally. Would you like to reload it?'));if(shouldUpdate)
this._contentCommitted((updatedContent),false);else
this._lastAcceptedContent=updatedContent;}}
forceLoadOnCheckContent(){this._forceLoadOnCheckContent=true;}
_commitContent(content){if(this._project.canSetFileContent())
this._project.setFileContent(this,content,false,function(){});this._contentCommitted(content,true);}
_contentCommitted(content,committedByUser){this._lastAcceptedContent=null;this._content=content;this._contentLoaded=true;this._requestContentPromise=null;this._hasCommits=true;this._innerResetWorkingCopy();this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyCommitted,{uiSourceCode:this,content:content});this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommitted,{uiSourceCode:this,content:content});if(committedByUser){this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommittedByUser,{uiSourceCode:this,content:content});}}
addRevision(content){this._commitContent(content);}
hasCommits(){return this._hasCommits;}
workingCopy(){if(this._workingCopyGetter){this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;}
if(this.isDirty())
return(this._workingCopy);return this._content||'';}
resetWorkingCopy(){this._innerResetWorkingCopy();this._workingCopyChanged();}
_innerResetWorkingCopy(){this._workingCopy=null;this._workingCopyGetter=null;}
setWorkingCopy(newWorkingCopy){this._workingCopy=newWorkingCopy;this._workingCopyGetter=null;this._workingCopyChanged();}
setContent(content,isBase64){if(this._project.canSetFileContent())
this._project.setFileContent(this,content,isBase64,function(){});this._contentCommitted(content,true);}
setWorkingCopyGetter(workingCopyGetter){this._workingCopyGetter=workingCopyGetter;this._workingCopyChanged();}
_workingCopyChanged(){this._removeAllMessages();this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyChanged,this);this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyChanged,{uiSourceCode:this});}
removeWorkingCopyGetter(){if(!this._workingCopyGetter)
return;this._workingCopy=this._workingCopyGetter();this._workingCopyGetter=null;}
commitWorkingCopy(){if(this.isDirty())
this._commitContent(this.workingCopy());}
isDirty(){return this._workingCopy!==null||this._workingCopyGetter!==null;}
extension(){return Common.ParsedURL.extractExtension(this._name);}
content(){return this._content;}
searchInContent(query,caseSensitive,isRegex){const content=this.content();if(!content)
return this._project.searchInFileContent(this,query,caseSensitive,isRegex);return Promise.resolve(Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex));}
contentLoaded(){return this._contentLoaded;}
uiLocation(lineNumber,columnNumber){if(typeof columnNumber==='undefined')
columnNumber=0;return new Workspace.UILocation(this,lineNumber,columnNumber);}
messages(){return this._messages?new Set(this._messages):new Set();}
addLineMessage(level,text,lineNumber,columnNumber){return this.addMessage(level,text,new TextUtils.TextRange(lineNumber,columnNumber||0,lineNumber,columnNumber||0));}
addMessage(level,text,range){const message=new Workspace.UISourceCode.Message(this,level,text,range);if(!this._messages)
this._messages=new Set();this._messages.add(message);this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageAdded,message);return message;}
removeMessage(message){if(this._messages&&this._messages.delete(message))
this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);}
_removeAllMessages(){if(!this._messages)
return;for(const message of this._messages)
this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved,message);this._messages=null;}
addLineDecoration(lineNumber,type,data){this.addDecoration(TextUtils.TextRange.createFromLocation(lineNumber,0),type,data);}
addDecoration(range,type,data){const marker=new Workspace.UISourceCode.LineMarker(range,type,data);if(!this._decorations)
this._decorations=new Multimap();this._decorations.set(type,marker);this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationAdded,marker);}
removeDecorationsForType(type){if(!this._decorations)
return;const markers=this._decorations.get(type);this._decorations.deleteAll(type);markers.forEach(marker=>{this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker);});}
allDecorations(){return this._decorations?this._decorations.valuesArray():[];}
removeAllDecorations(){if(!this._decorations)
return;const decorationList=this._decorations.valuesArray();this._decorations.clear();decorationList.forEach(marker=>this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationRemoved,marker));}
decorationsForType(type){return this._decorations?this._decorations.get(type):null;}};Workspace.UISourceCode.Events={WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),TitleChanged:Symbol('TitleChanged'),MessageAdded:Symbol('MessageAdded'),MessageRemoved:Symbol('MessageRemoved'),LineDecorationAdded:Symbol('LineDecorationAdded'),LineDecorationRemoved:Symbol('LineDecorationRemoved')};Workspace.UILocation=class{constructor(uiSourceCode,lineNumber,columnNumber){this.uiSourceCode=uiSourceCode;this.lineNumber=lineNumber;this.columnNumber=columnNumber;}
linkText(skipTrim){let linkText=this.uiSourceCode.displayName(skipTrim);if(typeof this.lineNumber==='number')
linkText+=':'+(this.lineNumber+1);return linkText;}
id(){return this.uiSourceCode.project().id()+':'+this.uiSourceCode.url()+':'+this.lineNumber+':'+
this.columnNumber;}
toUIString(){return this.uiSourceCode.url()+':'+(this.lineNumber+1);}
static comparator(location1,location2){return location1.compareTo(location2);}
compareTo(other){if(this.uiSourceCode.url()!==other.uiSourceCode.url())
return this.uiSourceCode.url()>other.uiSourceCode.url()?1:-1;if(this.lineNumber!==other.lineNumber)
return this.lineNumber-other.lineNumber;return this.columnNumber-other.columnNumber;}};Workspace.UISourceCode.Message=class{constructor(uiSourceCode,level,text,range){this._uiSourceCode=uiSourceCode;this._level=level;this._text=text;this._range=range;}
uiSourceCode(){return this._uiSourceCode;}
level(){return this._level;}
text(){return this._text;}
range(){return this._range;}
lineNumber(){return this._range.startLine;}
columnNumber(){return this._range.startColumn;}
isEqual(another){return this._uiSourceCode===another._uiSourceCode&&this.text()===another.text()&&this.level()===another.level()&&this.range().equal(another.range());}
remove(){this._uiSourceCode.removeMessage(this);}};Workspace.UISourceCode.Message.Level={Error:'Error',Warning:'Warning'};Workspace.UISourceCode.LineMarker=class{constructor(range,type,data){this._range=range;this._type=type;this._data=data;}
range(){return this._range;}
type(){return this._type;}
data(){return this._data;}};Workspace.UISourceCodeMetadata=class{constructor(modificationTime,contentSize){this.modificationTime=modificationTime;this.contentSize=contentSize;}};;Workspace.ProjectSearchConfig=function(){};Workspace.ProjectSearchConfig.prototype={query(){},ignoreCase(){},isRegex(){},queries(){},filePathMatchesFileQuery(filePath){}};Workspace.Project=function(){};Workspace.Project.prototype={workspace(){},id(){},type(){},isServiceProject(){},displayName(){},requestMetadata(uiSourceCode){},requestFileContent(uiSourceCode,callback){},canSetFileContent(){},setFileContent(uiSourceCode,newContent,isBase64,callback){},fullDisplayName(uiSourceCode){},mimeType(uiSourceCode){},canRename(){},rename(uiSourceCode,newName,callback){},excludeFolder(path){},canExcludeFolder(path){},createFile(path,name,content,isBase64){},canCreateFile(){},deleteFile(uiSourceCode){},remove(){},searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){},findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){},indexContent(progress){},uiSourceCodeForURL(url){},uiSourceCodes(){}};Workspace.projectTypes={Debugger:'debugger',Formatter:'formatter',Network:'network',Snippets:'snippets',FileSystem:'filesystem',ContentScripts:'contentscripts',Service:'service'};Workspace.ProjectStore=class{constructor(workspace,id,type,displayName){this._workspace=workspace;this._id=id;this._type=type;this._displayName=displayName;this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];this._project=(this);}
id(){return this._id;}
type(){return this._type;}
displayName(){return this._displayName;}
workspace(){return this._workspace;}
createUISourceCode(url,contentType){return new Workspace.UISourceCode(this._project,url,contentType);}
addUISourceCode(uiSourceCode){const url=uiSourceCode.url();if(this.uiSourceCodeForURL(url))
return false;this._uiSourceCodesMap.set(url,{uiSourceCode:uiSourceCode,index:this._uiSourceCodesList.length});this._uiSourceCodesList.push(uiSourceCode);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeAdded,uiSourceCode);return true;}
removeUISourceCode(url){const uiSourceCode=this.uiSourceCodeForURL(url);if(!uiSourceCode)
return;const entry=this._uiSourceCodesMap.get(url);const movedUISourceCode=this._uiSourceCodesList[this._uiSourceCodesList.length-1];this._uiSourceCodesList[entry.index]=movedUISourceCode;const movedEntry=this._uiSourceCodesMap.get(movedUISourceCode.url());movedEntry.index=entry.index;this._uiSourceCodesList.splice(this._uiSourceCodesList.length-1,1);this._uiSourceCodesMap.delete(url);this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeRemoved,entry.uiSourceCode);}
removeProject(){this._workspace._removeProject(this._project);this._uiSourceCodesMap=new Map();this._uiSourceCodesList=[];}
uiSourceCodeForURL(url){const entry=this._uiSourceCodesMap.get(url);return entry?entry.uiSourceCode:null;}
uiSourceCodes(){return this._uiSourceCodesList;}
renameUISourceCode(uiSourceCode,newName){const oldPath=uiSourceCode.url();const newPath=uiSourceCode.parentURL()?uiSourceCode.parentURL()+'/'+newName:newName;const value=(this._uiSourceCodesMap.get(oldPath));this._uiSourceCodesMap.set(newPath,value);this._uiSourceCodesMap.delete(oldPath);}};Workspace.Workspace=class extends Common.Object{constructor(){super();this._projects=new Map();this._hasResourceContentTrackingExtensions=false;}
uiSourceCode(projectId,url){const project=this._projects.get(projectId);return project?project.uiSourceCodeForURL(url):null;}
uiSourceCodeForURL(url){for(const project of this._projects.values()){const uiSourceCode=project.uiSourceCodeForURL(url);if(uiSourceCode)
return uiSourceCode;}
return null;}
uiSourceCodesForProjectType(type){let result=[];for(const project of this._projects.values()){if(project.type()===type)
result=result.concat(project.uiSourceCodes());}
return result;}
addProject(project){console.assert(!this._projects.has(project.id()),`A project with id ${project.id()} already exists!`);this._projects.set(project.id(),project);this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectAdded,project);}
_removeProject(project){this._projects.delete(project.id());this.dispatchEventToListeners(Workspace.Workspace.Events.ProjectRemoved,project);}
project(projectId){return this._projects.get(projectId)||null;}
projects(){return this._projects.valuesArray();}
projectsForType(type){function filterByType(project){return project.type()===type;}
return this.projects().filter(filterByType);}
uiSourceCodes(){let result=[];for(const project of this._projects.values())
result=result.concat(project.uiSourceCodes());return result;}
setHasResourceContentTrackingExtensions(hasExtensions){this._hasResourceContentTrackingExtensions=hasExtensions;}
hasResourceContentTrackingExtensions(){return this._hasResourceContentTrackingExtensions;}};Workspace.Workspace.Events={UISourceCodeAdded:Symbol('UISourceCodeAdded'),UISourceCodeRemoved:Symbol('UISourceCodeRemoved'),UISourceCodeRenamed:Symbol('UISourceCodeRenamed'),WorkingCopyChanged:Symbol('WorkingCopyChanged'),WorkingCopyCommitted:Symbol('WorkingCopyCommitted'),WorkingCopyCommittedByUser:Symbol('WorkingCopyCommittedByUser'),ProjectAdded:Symbol('ProjectAdded'),ProjectRemoved:Symbol('ProjectRemoved')};Workspace.workspace;;self['Bindings']=self['Bindings']||{};Bindings.LiveLocation=function(){};Bindings.LiveLocation.prototype={update(){},uiLocation(){},dispose(){},isBlackboxed(){}};Bindings.LiveLocationWithPool=class{constructor(updateDelegate,locationPool){this._updateDelegate=updateDelegate;this._locationPool=locationPool;this._locationPool._add(this);}
update(){this._updateDelegate(this);}
uiLocation(){throw'Not implemented';}
dispose(){this._locationPool._delete(this);this._updateDelegate=null;}
isBlackboxed(){throw'Not implemented';}};Bindings.LiveLocationPool=class{constructor(){this._locations=new Set();}
_add(location){this._locations.add(location);}
_delete(location){this._locations.delete(location);}
disposeAll(){for(const location of this._locations)
location.dispose();}};;Bindings.ResourceMapping=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();targetManager.observeModels(SDK.ResourceTreeModel,this);}
modelAdded(resourceTreeModel){const info=new Bindings.ResourceMapping.ModelInfo(this._workspace,resourceTreeModel);this._modelToInfo.set(resourceTreeModel,info);}
modelRemoved(resourceTreeModel){const info=this._modelToInfo.get(resourceTreeModel);info.dispose();this._modelToInfo.delete(resourceTreeModel);}
_infoForTarget(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);return resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;}
cssLocationToUILocation(cssLocation){const header=cssLocation.header();if(!header)
return null;const info=this._infoForTarget(cssLocation.cssModel().target());if(!info)
return null;const uiSourceCode=info._project.uiSourceCodeForURL(cssLocation.url);if(!uiSourceCode)
return null;const offset=header[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(header.startLine,header.startColumn);const lineNumber=cssLocation.lineNumber+offset.startLine-header.startLine;let columnNumber=cssLocation.columnNumber;if(cssLocation.lineNumber===header.startLine)
columnNumber+=offset.startColumn-header.startColumn;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
jsLocationToUILocation(jsLocation){const script=jsLocation.script();if(!script)
return null;const info=this._infoForTarget(jsLocation.debuggerModel.target());if(!info)
return null;const uiSourceCode=info._project.uiSourceCodeForURL(script.sourceURL);if(!uiSourceCode)
return null;const offset=script[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(script.lineOffset,script.columnOffset);const lineNumber=jsLocation.lineNumber+offset.startLine-script.lineOffset;let columnNumber=jsLocation.columnNumber;if(jsLocation.lineNumber===script.lineOffset)
columnNumber+=offset.startColumn-script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToJSLocation(uiSourceCode,lineNumber,columnNumber){if(!uiSourceCode[Bindings.ResourceMapping._symbol])
return null;const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);if(!target)
return null;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return null;return debuggerModel.createRawLocationByURL(uiSourceCode.url(),lineNumber,columnNumber);}
_resetForTest(target){const resourceTreeModel=target.model(SDK.ResourceTreeModel);const info=resourceTreeModel?this._modelToInfo.get(resourceTreeModel):null;if(info)
info._resetForTest();}};Bindings.ResourceMapping.ModelInfo=class{constructor(workspace,resourceTreeModel){const target=resourceTreeModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'resources:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._bindings=new Map();const cssModel=target.model(SDK.CSSModel);this._cssModel=cssModel;this._eventListeners=[resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded,this._resourceAdded,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameWillNavigate,this._frameWillNavigate,this),resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameDetached,this._frameDetached,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._styleSheetChanged,this)];}
_styleSheetChanged(event){const header=this._cssModel.styleSheetHeaderForId(event.data.styleSheetId);if(!header||!header.isInline)
return;const binding=this._bindings.get(header.resourceURL());if(!binding)
return;binding._styleSheetChanged(header,event.data.edit);}
_acceptsResource(resource){const resourceType=resource.resourceType();if(resourceType!==Common.resourceTypes.Image&&resourceType!==Common.resourceTypes.Font&&resourceType!==Common.resourceTypes.Document&&resourceType!==Common.resourceTypes.Manifest)
return false;if(resourceType===Common.resourceTypes.Image&&resource.mimeType&&!resource.mimeType.startsWith('image'))
return false;if(resourceType===Common.resourceTypes.Font&&resource.mimeType&&!resource.mimeType.includes('font'))
return false;if((resourceType===Common.resourceTypes.Image||resourceType===Common.resourceTypes.Font)&&resource.contentURL().startsWith('data:'))
return false;return true;}
_resourceAdded(event){const resource=(event.data);if(!this._acceptsResource(resource))
return;let binding=this._bindings.get(resource.url);if(!binding){binding=new Bindings.ResourceMapping.Binding(this._project,resource);this._bindings.set(resource.url,binding);}else{binding.addResource(resource);}}
_removeFrameResources(frame){for(const resource of frame.resources()){if(!this._acceptsResource(resource))
continue;const binding=this._bindings.get(resource.url);if(binding._resources.size===1){binding.dispose();this._bindings.delete(resource.url);}else{binding.removeResource(resource);}}}
_frameWillNavigate(event){const frame=(event.data);this._removeFrameResources(frame);}
_frameDetached(event){const frame=(event.data);this._removeFrameResources(frame);}
_resetForTest(){for(const binding of this._bindings.valuesArray())
binding.dispose();this._bindings.clear();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(const binding of this._bindings.valuesArray())
binding.dispose();this._bindings.clear();this._project.removeProject();}};Bindings.ResourceMapping.Binding=class{constructor(project,resource){this._resources=new Set([resource]);this._project=project;this._uiSourceCode=this._project.createUISourceCode(resource.url,resource.contentType());this._uiSourceCode[Bindings.ResourceMapping._symbol]=true;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,resource.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,Bindings.resourceMetadata(resource),resource.mimeType);this._edits=[];}
_inlineStyles(){const target=Bindings.NetworkProject.targetForUISourceCode(this._uiSourceCode);const cssModel=target.model(SDK.CSSModel);const stylesheets=[];if(cssModel){for(const headerId of cssModel.styleSheetIdsForURL(this._uiSourceCode.url())){const header=cssModel.styleSheetHeaderForId(headerId);if(header)
stylesheets.push(header);}}
return stylesheets;}
_inlineScripts(){const target=Bindings.NetworkProject.targetForUISourceCode(this._uiSourceCode);const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return[];return debuggerModel.scriptsForSourceURL(this._uiSourceCode.url());}
async _styleSheetChanged(stylesheet,edit){this._edits.push({stylesheet,edit});if(this._edits.length>1)
return;const content=await this._uiSourceCode.requestContent();if(content!==null)
this._innerStyleSheetChanged(content);this._edits=[];}
_innerStyleSheetChanged(content){const scripts=this._inlineScripts();const styles=this._inlineStyles();let text=new TextUtils.Text(content);for(const data of this._edits){const edit=data.edit;const stylesheet=data.stylesheet;const startLocation=stylesheet[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(stylesheet.startLine,stylesheet.startColumn);const oldRange=edit.oldRange.relativeFrom(startLocation.startLine,startLocation.startColumn);const newRange=edit.newRange.relativeFrom(startLocation.startLine,startLocation.startColumn);text=new TextUtils.Text(text.replaceRange(oldRange,edit.newText));for(const script of scripts){const scriptOffset=script[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(script.lineOffset,script.columnOffset);if(!scriptOffset.follows(oldRange))
continue;script[Bindings.ResourceMapping._offsetSymbol]=scriptOffset.rebaseAfterTextEdit(oldRange,newRange);Bindings.debuggerWorkspaceBinding.updateLocations(script);}
for(const style of styles){const styleOffset=style[Bindings.ResourceMapping._offsetSymbol]||TextUtils.TextRange.createFromLocation(style.startLine,style.startColumn);if(!styleOffset.follows(oldRange))
continue;style[Bindings.ResourceMapping._offsetSymbol]=styleOffset.rebaseAfterTextEdit(oldRange,newRange);Bindings.cssWorkspaceBinding.updateLocations(style);}}
this._uiSourceCode.addRevision(text.value());}
addResource(resource){this._resources.add(resource);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,resource.frameId);}
removeResource(resource){this._resources.delete(resource);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,resource.frameId);}
dispose(){this._project.removeFile(this._uiSourceCode.url());}
contentURL(){return this._resources.firstValue().contentURL();}
contentType(){return this._resources.firstValue().contentType();}
contentEncoded(){return this._resources.firstValue().contentEncoded();}
requestContent(){return this._resources.firstValue().requestContent();}
searchInContent(query,caseSensitive,isRegex){return this._resources.firstValue().searchInContent(query,caseSensitive,isRegex);}};Bindings.ResourceMapping._symbol=Symbol('Bindings.ResourceMapping._symbol');Bindings.ResourceMapping._offsetSymbol=Symbol('Bindings.ResourceMapping._offsetSymbol');;Bindings.CompilerScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._sourceMapManager=this._debuggerModel.sourceMapManager();this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;const target=debuggerModel.target();this._regularProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps::'+target.id(),Workspace.projectTypes.Network,'',false);this._contentScriptsProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:extensions:'+target.id(),Workspace.projectTypes.ContentScripts,'',false);Bindings.NetworkProject.setTargetForProject(this._regularProject,target);Bindings.NetworkProject.setTargetForProject(this._contentScriptsProject,target);this._regularBindings=new Map();this._contentScriptsBindings=new Map();this._stubUISourceCodes=new Map();this._stubProject=new Bindings.ContentProviderBasedProject(workspace,'jsSourceMaps:stub:'+target.id(),Workspace.projectTypes.Service,'',true);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapWillAttach,this._sourceMapWillAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapFailedToAttach,this._sourceMapFailedToAttach,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),];}
_addStubUISourceCode(script){const stubUISourceCode=this._stubProject.addContentProvider(script.sourceURL+':sourcemap',Common.StaticContentProvider.fromString(script.sourceURL,Common.resourceTypes.Script,'\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!'),'text/javascript');this._stubUISourceCodes.set(script,stubUISourceCode);}
_removeStubUISourceCode(script){const uiSourceCode=this._stubUISourceCodes.get(script);this._stubUISourceCodes.delete(script);this._stubProject.removeFile(uiSourceCode.url());this._debuggerWorkspaceBinding.updateLocations(script);}
static uiSourceCodeOrigin(uiSourceCode){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return null;return sourceMap.compiledURL();}
mapsToSourceCode(rawLocation){const script=rawLocation.script();const sourceMap=script?this._sourceMapManager.sourceMapForClient(script):null;if(!sourceMap)
return true;return!!sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);}
uiSourceCodeForURL(url,isContentScript){return isContentScript?this._contentScriptsProject.uiSourceCodeForURL(url):this._regularProject.uiSourceCodeForURL(url);}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const lineNumber=rawLocation.lineNumber-script.lineOffset;let columnNumber=rawLocation.columnNumber;if(!lineNumber)
columnNumber-=script.columnOffset;const stubUISourceCode=this._stubUISourceCodes.get(script);if(stubUISourceCode)
return new Workspace.UILocation(stubUISourceCode,lineNumber,columnNumber);const sourceMap=this._sourceMapManager.sourceMapForClient(script);if(!sourceMap)
return null;const entry=sourceMap.findEntry(lineNumber,columnNumber);if(!entry||!entry.sourceURL)
return null;const uiSourceCode=script.isContentScript()?this._contentScriptsProject.uiSourceCodeForURL(entry.sourceURL):this._regularProject.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode)
return null;return uiSourceCode.uiLocation((entry.sourceLineNumber),(entry.sourceColumnNumber));}
uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return null;const scripts=this._sourceMapManager.clientsForSourceMap(sourceMap);const script=scripts.length?scripts[0]:null;if(!script)
return null;const entry=sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,columnNumber);if(!entry)
return null;return this._debuggerModel.createRawLocation(script,entry.lineNumber+script.lineOffset,!entry.lineNumber?entry.columnNumber+script.columnOffset:entry.columnNumber);}
_sourceMapWillAttach(event){const script=(event.data);this._addStubUISourceCode(script);this._debuggerWorkspaceBinding.updateLocations(script);}
_sourceMapFailedToAttach(event){const script=(event.data);this._removeStubUISourceCode(script);}
_sourceMapAttached(event){const script=(event.data.client);const sourceMap=(event.data.sourceMap);this._removeStubUISourceCode(script);if(Bindings.blackboxManager.isBlackboxedURL(script.sourceURL,script.isContentScript()))
return;Bindings.blackboxManager.sourceMapLoaded(script,sourceMap);this._populateSourceMapSources(script,sourceMap);this._sourceMapAttachedForTest(sourceMap);}
_sourceMapDetached(event){const script=(event.data.client);const frameId=script[Bindings.CompilerScriptMapping._frameIdSymbol];const sourceMap=(event.data.sourceMap);const bindings=script.isContentScript()?this._contentScriptsBindings:this._regularBindings;for(const sourceURL of sourceMap.sourceURLs()){const binding=bindings.get(sourceURL);binding.removeSourceMap(sourceMap,frameId);if(!binding._uiSourceCode)
bindings.delete(sourceURL);}
this._debuggerWorkspaceBinding.updateLocations(script);}
sourceMapForScript(script){return this._sourceMapManager.sourceMapForClient(script);}
maybeLoadSourceMap(script){const sourceMap=this._sourceMapManager.sourceMapForClient(script);if(!sourceMap)
return;this._populateSourceMapSources(script,sourceMap);}
_sourceMapAttachedForTest(sourceMap){}
_populateSourceMapSources(script,sourceMap){const frameId=Bindings.frameIdForScript(script);script[Bindings.CompilerScriptMapping._frameIdSymbol]=frameId;const project=script.isContentScript()?this._contentScriptsProject:this._regularProject;const bindings=script.isContentScript()?this._contentScriptsBindings:this._regularBindings;for(const sourceURL of sourceMap.sourceURLs()){let binding=bindings.get(sourceURL);if(!binding){binding=new Bindings.CompilerScriptMapping.Binding(project,sourceURL);bindings.set(sourceURL,binding);}
binding.addSourceMap(sourceMap,frameId);}
this._debuggerWorkspaceBinding.updateLocations(script);}
static uiLineHasMapping(uiSourceCode,lineNumber){const sourceMap=uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol];if(!sourceMap)
return true;return!!sourceMap.sourceLineMapping(uiSourceCode.url(),lineNumber,0);}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._regularProject.dispose();this._contentScriptsProject.dispose();this._stubProject.dispose();}};Bindings.CompilerScriptMapping._frameIdSymbol=Symbol('Bindings.CompilerScriptMapping._frameIdSymbol');Bindings.CompilerScriptMapping._sourceMapSymbol=Symbol('Bindings.CompilerScriptMapping._sourceMapSymbol');Bindings.CompilerScriptMapping.Binding=class{constructor(project,url){this._project=project;this._url=url;this._referringSourceMaps=[];this._activeSourceMap=null;this._uiSourceCode=null;}
_recreateUISourceCodeIfNeeded(frameId){const sourceMap=this._referringSourceMaps.peekLast();if(this._activeSourceMap===sourceMap)
return;this._activeSourceMap=sourceMap;const newUISourceCode=this._project.createUISourceCode(this._url,Common.resourceTypes.SourceMapScript);newUISourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]=sourceMap;const contentProvider=sourceMap.sourceContentProvider(this._url,Common.resourceTypes.SourceMapScript);const mimeType=Common.ResourceType.mimeFromURL(this._url)||'text/javascript';const embeddedContent=sourceMap.embeddedContentByURL(this._url);const metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;if(this._uiSourceCode){Bindings.NetworkProject.cloneInitialFrameAttribution(this._uiSourceCode,newUISourceCode);this._project.removeFile(this._uiSourceCode.url());}else{Bindings.NetworkProject.setInitialFrameAttribution(newUISourceCode,frameId);}
this._uiSourceCode=newUISourceCode;this._project.addUISourceCodeWithProvider(this._uiSourceCode,contentProvider,metadata,mimeType);}
addSourceMap(sourceMap,frameId){if(this._uiSourceCode)
Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,frameId);this._referringSourceMaps.push(sourceMap);this._recreateUISourceCodeIfNeeded(frameId);}
removeSourceMap(sourceMap,frameId){Bindings.NetworkProject.removeFrameAttribution((this._uiSourceCode),frameId);const lastIndex=this._referringSourceMaps.lastIndexOf(sourceMap);if(lastIndex!==-1)
this._referringSourceMaps.splice(lastIndex,1);if(!this._referringSourceMaps.length){this._project.removeFile(this._uiSourceCode.url());this._uiSourceCode=null;}else{this._recreateUISourceCodeIfNeeded(frameId);}}};;Bindings.ResourceScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._workspace=workspace;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._uiSourceCodeToScriptFile=new Map();this._projects=new Map();this._acceptedScripts=new Set();const runtimeModel=debuggerModel.runtimeModel();this._eventListeners=[this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,this._parsedScriptSource,this),this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this),runtimeModel.addEventListener(SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._executionContextDestroyed,this),];}
_project(script){const frameId=script[Bindings.ResourceScriptMapping._frameIdSymbol];const prefix=script.isContentScript()?'js:extensions:':'js::';const projectId=prefix+this._debuggerModel.target().id()+':'+frameId;let project=this._projects.get(projectId);if(!project){const projectType=script.isContentScript()?Workspace.projectTypes.ContentScripts:Workspace.projectTypes.Network;project=new Bindings.ContentProviderBasedProject(this._workspace,projectId,projectType,'',false);Bindings.NetworkProject.setTargetForProject(project,this._debuggerModel.target());this._projects.set(projectId,project);}
return project;}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const project=this._project(script);const uiSourceCode=project.uiSourceCodeForURL(script.sourceURL);if(!uiSourceCode)
return null;const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);if(!scriptFile)
return null;if((scriptFile.hasDivergedFromVM()&&!scriptFile.isMergingToVM())||scriptFile.isDivergingFromVM())
return null;if(!scriptFile._hasScripts([script]))
return null;const lineNumber=rawLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);let columnNumber=rawLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber)
columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);if(!scriptFile)
return null;const script=scriptFile._script;if(script.isInlineScriptWithSourceURL()){return this._debuggerModel.createRawLocation(script,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset);}
return this._debuggerModel.createRawLocation(script,lineNumber,columnNumber);}
_acceptsScript(script){if(!script.sourceURL||script.isLiveEdit()||(script.isInlineScript()&&!script.hasSourceURL))
return false;if(script.isContentScript()&&!script.hasSourceURL){const parsedURL=new Common.ParsedURL(script.sourceURL);if(!parsedURL.isValid)
return false;}
return true;}
_parsedScriptSource(event){const script=(event.data);if(!this._acceptsScript(script))
return;this._acceptedScripts.add(script);const originalContentProvider=script.originalContentProvider();const frameId=Bindings.frameIdForScript(script);script[Bindings.ResourceScriptMapping._frameIdSymbol]=frameId;const url=script.sourceURL;const project=this._project(script);const oldUISourceCode=project.uiSourceCodeForURL(url);if(oldUISourceCode){const scriptFile=this._uiSourceCodeToScriptFile.get(oldUISourceCode);this._removeScript(scriptFile._script);}
const uiSourceCode=project.createUISourceCode(url,originalContentProvider.contentType());Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,frameId);const metadata=Bindings.metadataForURL(this._debuggerModel.target(),frameId,url);const scriptFile=new Bindings.ResourceScriptFile(this,uiSourceCode,[script]);this._uiSourceCodeToScriptFile.set(uiSourceCode,scriptFile);project.addUISourceCodeWithProvider(uiSourceCode,originalContentProvider,metadata,'text/javascript');this._debuggerWorkspaceBinding.updateLocations(script);}
scriptFile(uiSourceCode){return this._uiSourceCodeToScriptFile.get(uiSourceCode)||null;}
_removeScript(script){if(!this._acceptedScripts.has(script))
return;this._acceptedScripts.delete(script);const project=this._project(script);const uiSourceCode=(project.uiSourceCodeForURL(script.sourceURL));const scriptFile=this._uiSourceCodeToScriptFile.get(uiSourceCode);scriptFile.dispose();this._uiSourceCodeToScriptFile.delete(uiSourceCode);project.removeFile(script.sourceURL);this._debuggerWorkspaceBinding.updateLocations(script);}
_executionContextDestroyed(event){const executionContext=(event.data);const scripts=this._debuggerModel.scriptsForExecutionContext(executionContext);for(const script of scripts)
this._removeScript(script);}
_globalObjectCleared(event){const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);}
resetForTest(){const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);const scripts=Array.from(this._acceptedScripts);for(const script of scripts)
this._removeScript(script);for(const project of this._projects.values())
project.removeProject();this._projects.clear();}};Bindings.ResourceScriptFile=class extends Common.Object{constructor(resourceScriptMapping,uiSourceCode,scripts){super();console.assert(scripts.length);this._resourceScriptMapping=resourceScriptMapping;this._uiSourceCode=uiSourceCode;if(this._uiSourceCode.contentType().isScript())
this._script=scripts[scripts.length-1];this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);}
_hasScripts(scripts){return this._script&&this._script===scripts[0];}
_isDiverged(){if(this._uiSourceCode.isDirty())
return true;if(!this._script)
return false;if(typeof this._scriptSource==='undefined')
return false;const workingCopy=this._uiSourceCode.workingCopy();if(!workingCopy)
return false;if(!workingCopy.startsWith(this._scriptSource.trimRight()))
return true;const suffix=this._uiSourceCode.workingCopy().substr(this._scriptSource.length);return!!suffix.length&&!suffix.match(SDK.Script.sourceURLRegex);}
_workingCopyChanged(event){this._update();}
_workingCopyCommitted(event){if(this._uiSourceCode.project().canSetFileContent())
return;if(!this._script)
return;const debuggerModel=this._resourceScriptMapping._debuggerModel;const breakpoints=Bindings.breakpointManager.breakpointsForUISourceCode(this._uiSourceCode);const source=this._uiSourceCode.workingCopy();debuggerModel.setScriptSource(this._script.scriptId,source,scriptSourceWasSet.bind(this));async function scriptSourceWasSet(error,exceptionDetails){if(!error&&!exceptionDetails)
this._scriptSource=source;this._update();if(!error&&!exceptionDetails){breakpoints.map(breakpoint=>breakpoint.refreshInDebugger());return;}
if(!exceptionDetails){Common.console.addMessage(Common.UIString('LiveEdit failed: %s',error),Common.Console.MessageLevel.Warning);return;}
const messageText=Common.UIString('LiveEdit compile failed: %s',exceptionDetails.text);this._uiSourceCode.addLineMessage(Workspace.UISourceCode.Message.Level.Error,messageText,exceptionDetails.lineNumber,exceptionDetails.columnNumber);}}
_update(){if(this._isDiverged()&&!this._hasDivergedFromVM)
this._divergeFromVM();else if(!this._isDiverged()&&this._hasDivergedFromVM)
this._mergeToVM();}
_divergeFromVM(){this._isDivergingFromVM=true;this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);delete this._isDivergingFromVM;this._hasDivergedFromVM=true;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidDivergeFromVM,this._uiSourceCode);}
_mergeToVM(){delete this._hasDivergedFromVM;this._isMergingToVM=true;this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);delete this._isMergingToVM;this.dispatchEventToListeners(Bindings.ResourceScriptFile.Events.DidMergeToVM,this._uiSourceCode);}
hasDivergedFromVM(){return this._hasDivergedFromVM;}
isDivergingFromVM(){return this._isDivergingFromVM;}
isMergingToVM(){return this._isMergingToVM;}
checkMapping(){if(!this._script||typeof this._scriptSource!=='undefined'){this._mappingCheckedForTest();return;}
this._script.requestContent().then(callback.bind(this));function callback(source){this._scriptSource=source;this._update();this._mappingCheckedForTest();}}
_mappingCheckedForTest(){}
dispose(){this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this);this._uiSourceCode.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this);}
addSourceMapURL(sourceMapURL){if(!this._script)
return;this._script.debuggerModel.setSourceMapURL(this._script,sourceMapURL);}
hasSourceMapURL(){return this._script&&!!this._script.sourceMapURL;}};Bindings.ResourceScriptMapping._frameIdSymbol=Symbol('frameid');Bindings.ResourceScriptFile.Events={DidMergeToVM:Symbol('DidMergeToVM'),DidDivergeFromVM:Symbol('DidDivergeFromVM'),};;Bindings.SASSSourceMapping=class{constructor(target,sourceMapManager,workspace){this._sourceMapManager=sourceMapManager;this._project=new Bindings.ContentProviderBasedProject(workspace,'cssSourceMaps:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._eventListeners=[this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapAttached,this._sourceMapAttached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapDetached,this._sourceMapDetached,this),this._sourceMapManager.addEventListener(SDK.SourceMapManager.Events.SourceMapChanged,this._sourceMapChanged,this)];}
_sourceMapAttachedForTest(sourceMap){}
_sourceMapAttached(event){const header=(event.data.client);const sourceMap=(event.data.sourceMap);for(const sassURL of sourceMap.sourceURLs()){let uiSourceCode=this._project.uiSourceCodeForURL(sassURL);if(uiSourceCode){Bindings.NetworkProject.addFrameAttribution(uiSourceCode,header.frameId);continue;}
const contentProvider=sourceMap.sourceContentProvider(sassURL,Common.resourceTypes.SourceMapStyleSheet);const mimeType=Common.ResourceType.mimeFromURL(sassURL)||contentProvider.contentType().canonicalMimeType();const embeddedContent=sourceMap.embeddedContentByURL(sassURL);const metadata=typeof embeddedContent==='string'?new Workspace.UISourceCodeMetadata(null,embeddedContent.length):null;uiSourceCode=this._project.createUISourceCode(sassURL,contentProvider.contentType());Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode,header.frameId);uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol]=sourceMap;this._project.addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType);}
Bindings.cssWorkspaceBinding.updateLocations(header);this._sourceMapAttachedForTest(sourceMap);}
_sourceMapDetached(event){const header=(event.data.client);const sourceMap=(event.data.sourceMap);const headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(const sassURL of sourceMap.sourceURLs()){if(headers.length){const uiSourceCode=(this._project.uiSourceCodeForURL(sassURL));Bindings.NetworkProject.removeFrameAttribution(uiSourceCode,header.frameId);}else{this._project.removeFile(sassURL);}}
Bindings.cssWorkspaceBinding.updateLocations(header);}
_sourceMapChanged(event){const sourceMap=(event.data.sourceMap);const newSources=(event.data.newSources);const headers=this._sourceMapManager.clientsForSourceMap(sourceMap);for(const sourceURL of newSources.keys()){const uiSourceCode=this._project.uiSourceCodeForURL(sourceURL);if(!uiSourceCode){console.error('Failed to update source for '+sourceURL);continue;}
const sassText=(newSources.get(sourceURL));uiSourceCode.setWorkingCopy(sassText);}
for(const header of headers)
Bindings.cssWorkspaceBinding.updateLocations(header);}
rawLocationToUILocation(rawLocation){const header=rawLocation.header();if(!header)
return null;const sourceMap=this._sourceMapManager.sourceMapForClient(header);if(!sourceMap)
return null;const entry=sourceMap.findEntry(rawLocation.lineNumber,rawLocation.columnNumber);if(!entry||!entry.sourceURL)
return null;const uiSourceCode=this._project.uiSourceCodeForURL(entry.sourceURL);if(!uiSourceCode)
return null;return uiSourceCode.uiLocation(entry.sourceLineNumber||0,entry.sourceColumnNumber);}
uiLocationToRawLocations(uiLocation){const sourceMap=uiLocation.uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol];if(!sourceMap)
return[];const entries=sourceMap.findReverseEntries(uiLocation.uiSourceCode.url(),uiLocation.lineNumber,uiLocation.columnNumber);const locations=[];for(const header of this._sourceMapManager.clientsForSourceMap(sourceMap))
locations.pushAll(entries.map(entry=>new SDK.CSSLocation(header,entry.lineNumber,entry.columnNumber)));return locations;}
dispose(){this._project.dispose();Common.EventTarget.removeEventListeners(this._eventListeners);}};Bindings.SASSSourceMapping._sourceMapSymbol=Symbol('sourceMap');;Bindings.StylesSourceMapping=class{constructor(cssModel,workspace){this._cssModel=cssModel;const target=this._cssModel.target();this._project=new Bindings.ContentProviderBasedProject(workspace,'css:'+target.id(),Workspace.projectTypes.Network,'',false);Bindings.NetworkProject.setTargetForProject(this._project,target);this._styleFiles=new Map();this._eventListeners=[this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this),this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged,this._styleSheetChanged,this),];}
rawLocationToUILocation(rawLocation){const header=rawLocation.header();if(!header||!this._acceptsHeader(header))
return null;const styleFile=this._styleFiles.get(header.resourceURL());if(!styleFile)
return null;let lineNumber=rawLocation.lineNumber;let columnNumber=rawLocation.columnNumber;if(header.isInline&&header.hasSourceURL){lineNumber-=header.lineNumberInSource(0);columnNumber-=header.columnNumberInSource(lineNumber,0);}
return styleFile._uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocations(uiLocation){const styleFile=uiLocation.uiSourceCode[Bindings.StyleFile._symbol];if(!styleFile)
return[];const rawLocations=[];for(const header of styleFile._headers){let lineNumber=uiLocation.lineNumber;let columnNumber=uiLocation.columnNumber;if(header.isInline&&header.hasSourceURL){columnNumber=header.columnNumberInSource(lineNumber,columnNumber);lineNumber=header.lineNumberInSource(lineNumber);}
rawLocations.push(new SDK.CSSLocation(header,lineNumber,columnNumber));}
return rawLocations;}
_acceptsHeader(header){if(header.isInline&&!header.hasSourceURL&&header.origin!=='inspector')
return false;if(!header.resourceURL())
return false;return true;}
_styleSheetAdded(event){const header=(event.data);if(!this._acceptsHeader(header))
return;const url=header.resourceURL();let styleFile=this._styleFiles.get(url);if(!styleFile){styleFile=new Bindings.StyleFile(this._cssModel,this._project,header);this._styleFiles.set(url,styleFile);}else{styleFile.addHeader(header);}}
_styleSheetRemoved(event){const header=(event.data);if(!this._acceptsHeader(header))
return;const url=header.resourceURL();const styleFile=this._styleFiles.get(url);if(styleFile._headers.size===1){styleFile.dispose();this._styleFiles.delete(url);}else{styleFile.removeHeader(header);}}
_styleSheetChanged(event){const header=this._cssModel.styleSheetHeaderForId(event.data.styleSheetId);if(!header||!this._acceptsHeader(header))
return;const styleFile=this._styleFiles.get(header.resourceURL());styleFile._styleSheetChanged(header);}
dispose(){for(const styleFile of this._styleFiles.values())
styleFile.dispose();this._styleFiles.clear();Common.EventTarget.removeEventListeners(this._eventListeners);this._project.removeProject();}};Bindings.StyleFile=class{constructor(cssModel,project,header){this._cssModel=cssModel;this._project=project;this._headers=new Set([header]);const target=cssModel.target();const url=header.resourceURL();const metadata=Bindings.metadataForURL(target,header.frameId,url);this._uiSourceCode=this._project.createUISourceCode(url,header.contentType());this._uiSourceCode[Bindings.StyleFile._symbol]=this;Bindings.NetworkProject.setInitialFrameAttribution(this._uiSourceCode,header.frameId);this._project.addUISourceCodeWithProvider(this._uiSourceCode,this,metadata,'text/css');this._eventListeners=[this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._workingCopyChanged,this),this._uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._workingCopyCommitted,this)];this._throttler=new Common.Throttler(Bindings.StyleFile.updateTimeout);this._terminated=false;}
addHeader(header){this._headers.add(header);Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode,header.frameId);}
removeHeader(header){this._headers.delete(header);Bindings.NetworkProject.removeFrameAttribution(this._uiSourceCode,header.frameId);}
_styleSheetChanged(header){console.assert(this._headers.has(header));if(this._isUpdatingHeaders||!this._headers.has(header))
return;const mirrorContentBound=this._mirrorContent.bind(this,header,true);this._throttler.schedule(mirrorContentBound,false);}
_workingCopyCommitted(event){if(this._isAddingRevision)
return;const mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,true);this._throttler.schedule(mirrorContentBound,true);}
_workingCopyChanged(event){if(this._isAddingRevision)
return;const mirrorContentBound=this._mirrorContent.bind(this,this._uiSourceCode,false);this._throttler.schedule(mirrorContentBound,false);}
async _mirrorContent(fromProvider,majorChange){if(this._terminated){this._styleFileSyncedForTest();return;}
let newContent=null;if(fromProvider===this._uiSourceCode){newContent=this._uiSourceCode.workingCopy();}else{newContent=await fromProvider.requestContent();}
if(newContent===null||this._terminated){this._styleFileSyncedForTest();return;}
if(fromProvider!==this._uiSourceCode){this._isAddingRevision=true;this._uiSourceCode.addRevision(newContent);this._isAddingRevision=false;}
this._isUpdatingHeaders=true;const promises=[];for(const header of this._headers){if(header===fromProvider)
continue;promises.push(this._cssModel.setStyleSheetText(header.id,newContent,majorChange));}
await Promise.all(promises);this._isUpdatingHeaders=false;this._styleFileSyncedForTest();}
_styleFileSyncedForTest(){}
dispose(){if(this._terminated)
return;this._terminated=true;this._project.removeFile(this._uiSourceCode.url());Common.EventTarget.removeEventListeners(this._eventListeners);}
contentURL(){return this._headers.firstValue().originalContentProvider().contentURL();}
contentType(){return this._headers.firstValue().originalContentProvider().contentType();}
contentEncoded(){return this._headers.firstValue().originalContentProvider().contentEncoded();}
requestContent(){return this._headers.firstValue().originalContentProvider().requestContent();}
searchInContent(query,caseSensitive,isRegex){return this._headers.firstValue().originalContentProvider().searchInContent(query,caseSensitive,isRegex);}};Bindings.StyleFile._symbol=Symbol('Bindings.StyleFile._symbol');Bindings.StyleFile.updateTimeout=200;;Bindings.CSSWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._modelToInfo=new Map();this._sourceMappings=[];targetManager.observeModels(SDK.CSSModel,this);}
modelAdded(cssModel){this._modelToInfo.set(cssModel,new Bindings.CSSWorkspaceBinding.ModelInfo(cssModel,this._workspace));}
modelRemoved(cssModel){this._modelToInfo.get(cssModel)._dispose();this._modelToInfo.delete(cssModel);}
updateLocations(header){this._modelToInfo.get(header.cssModel())._updateLocations(header);}
createLiveLocation(rawLocation,updateDelegate,locationPool){return this._modelToInfo.get(rawLocation.cssModel())._createLiveLocation(rawLocation,updateDelegate,locationPool);}
propertyUILocation(cssProperty,forName){const style=cssProperty.ownerStyle;if(!style||style.type!==SDK.CSSStyleDeclaration.Type.Regular||!style.styleSheetId)
return null;const header=style.cssModel().styleSheetHeaderForId(style.styleSheetId);if(!header)
return null;const range=forName?cssProperty.nameRange():cssProperty.valueRange();if(!range)
return null;const lineNumber=range.startLine;const columnNumber=range.startColumn;const rawLocation=new SDK.CSSLocation(header,header.lineNumberInSource(lineNumber),header.columnNumberInSource(lineNumber,columnNumber));return this.rawLocationToUILocation(rawLocation);}
rawLocationToUILocation(rawLocation){for(let i=this._sourceMappings.length-1;i>=0;--i){const uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation)
return uiLocation;}
return this._modelToInfo.get(rawLocation.cssModel())._rawLocationToUILocation(rawLocation);}
uiLocationToRawLocations(uiLocation){for(let i=this._sourceMappings.length-1;i>=0;--i){const rawLocations=this._sourceMappings[i].uiLocationToRawLocations(uiLocation);if(rawLocations.length)
return rawLocations;}
const rawLocations=[];for(const modelInfo of this._modelToInfo.values())
rawLocations.pushAll(modelInfo._uiLocationToRawLocations(uiLocation));return rawLocations;}
addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);}};Bindings.CSSWorkspaceBinding.SourceMapping=function(){};Bindings.CSSWorkspaceBinding.SourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocations(uiLocation){},};Bindings.CSSWorkspaceBinding.ModelInfo=class{constructor(cssModel,workspace){this._eventListeners=[cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded,this._styleSheetAdded,this),cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved,this._styleSheetRemoved,this)];this._stylesSourceMapping=new Bindings.StylesSourceMapping(cssModel,workspace);const sourceMapManager=cssModel.sourceMapManager();this._sassSourceMapping=new Bindings.SASSSourceMapping(cssModel.target(),sourceMapManager,workspace);this._locations=new Multimap();this._unboundLocations=new Multimap();}
_createLiveLocation(rawLocation,updateDelegate,locationPool){const location=new Bindings.CSSWorkspaceBinding.LiveLocation(rawLocation,this,updateDelegate,locationPool);const header=rawLocation.header();if(header){location._header=header;this._locations.set(header,location);location.update();}else{this._unboundLocations.set(rawLocation.url,location);}
return location;}
_disposeLocation(location){if(location._header)
this._locations.delete(location._header,location);else
this._unboundLocations.delete(location._url,location);}
_updateLocations(header){for(const location of this._locations.get(header))
location.update();}
_styleSheetAdded(event){const header=(event.data);if(!header.sourceURL)
return;for(const location of this._unboundLocations.get(header.sourceURL)){location._header=header;this._locations.set(header,location);location.update();}
this._unboundLocations.deleteAll(header.sourceURL);}
_styleSheetRemoved(event){const header=(event.data);for(const location of this._locations.get(header)){location._header=null;this._unboundLocations.set(location._url,location);location.update();}
this._locations.deleteAll(header);}
_rawLocationToUILocation(rawLocation){let uiLocation=null;uiLocation=uiLocation||this._sassSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._stylesSourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.cssLocationToUILocation(rawLocation);return uiLocation;}
_uiLocationToRawLocations(uiLocation){const rawLocations=this._sassSourceMapping.uiLocationToRawLocations(uiLocation);if(rawLocations.length)
return rawLocations;return this._stylesSourceMapping.uiLocationToRawLocations(uiLocation);}
_dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._stylesSourceMapping.dispose();this._sassSourceMapping.dispose();}};Bindings.CSSWorkspaceBinding.LiveLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocation,info,updateDelegate,locationPool){super(updateDelegate,locationPool);this._url=rawLocation.url;this._lineNumber=rawLocation.lineNumber;this._columnNumber=rawLocation.columnNumber;this._info=info;this._header=null;}
uiLocation(){if(!this._header)
return null;const rawLocation=new SDK.CSSLocation(this._header,this._lineNumber,this._columnNumber);return Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation);}
dispose(){super.dispose();this._info._disposeLocation(this);}
isBlackboxed(){return false;}};Bindings.cssWorkspaceBinding;;Bindings.DebuggerWorkspaceBinding=class{constructor(targetManager,workspace){this._workspace=workspace;this._sourceMappings=[];this._debuggerModelToData=new Map();targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this);targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerResumed,this._debuggerResumed,this);targetManager.observeModels(SDK.DebuggerModel,this);}
addSourceMapping(sourceMapping){this._sourceMappings.push(sourceMapping);}
modelAdded(debuggerModel){this._debuggerModelToData.set(debuggerModel,new Bindings.DebuggerWorkspaceBinding.ModelData(debuggerModel,this));}
modelRemoved(debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);modelData._dispose();this._debuggerModelToData.remove(debuggerModel);}
updateLocations(script){const modelData=this._debuggerModelToData.get(script.debuggerModel);if(modelData)
modelData._updateLocations(script);}
createLiveLocation(rawLocation,updateDelegate,locationPool){const modelData=this._debuggerModelToData.get(rawLocation.script().debuggerModel);return modelData._createLiveLocation(rawLocation,updateDelegate,locationPool);}
createStackTraceTopFrameLiveLocation(rawLocations,updateDelegate,locationPool){console.assert(rawLocations.length);const location=new Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation(rawLocations,this,updateDelegate,locationPool);location.update();return location;}
createCallFrameLiveLocation(location,updateDelegate,locationPool){const script=location.script();if(!script)
return null;const debuggerModel=location.debuggerModel;const liveLocation=this.createLiveLocation(location,updateDelegate,locationPool);this._registerCallFrameLiveLocation(debuggerModel,liveLocation);return liveLocation;}
rawLocationToUILocation(rawLocation){for(let i=0;i<this._sourceMappings.length;++i){const uiLocation=this._sourceMappings[i].rawLocationToUILocation(rawLocation);if(uiLocation)
return uiLocation;}
const modelData=this._debuggerModelToData.get(rawLocation.debuggerModel);return modelData._rawLocationToUILocation(rawLocation);}
uiSourceCodeForSourceMapSourceURL(debuggerModel,url,isContentScript){const modelData=this._debuggerModelToData.get(debuggerModel);if(!modelData)
return null;return modelData._compilerMapping.uiSourceCodeForURL(url,isContentScript);}
uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){for(let i=0;i<this._sourceMappings.length;++i){const rawLocation=this._sourceMappings[i].uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(rawLocation)
return rawLocation;}
for(const modelData of this._debuggerModelToData.values()){const rawLocation=modelData._uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(rawLocation)
return rawLocation;}
return null;}
normalizeUILocation(uiLocation){const rawLocation=this.uiLocationToRawLocation(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber);if(rawLocation)
return this.rawLocationToUILocation(rawLocation)||uiLocation;return uiLocation;}
scriptFile(uiSourceCode,debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);return modelData?modelData._resourceMapping.scriptFile(uiSourceCode):null;}
sourceMapForScript(script){const modelData=this._debuggerModelToData.get(script.debuggerModel);if(!modelData)
return null;return modelData._compilerMapping.sourceMapForScript(script);}
maybeLoadSourceMap(script){const modelData=this._debuggerModelToData.get(script.debuggerModel);if(!modelData)
return;modelData._compilerMapping.maybeLoadSourceMap(script);}
_globalObjectCleared(event){const debuggerModel=(event.data);this._reset(debuggerModel);}
_reset(debuggerModel){const modelData=this._debuggerModelToData.get(debuggerModel);modelData.callFrameLocations.valuesArray().forEach(location=>this._removeLiveLocation(location));modelData.callFrameLocations.clear();}
_resetForTest(target){const debuggerModel=(target.model(SDK.DebuggerModel));const modelData=this._debuggerModelToData.get(debuggerModel);modelData._resourceMapping.resetForTest();}
_registerCallFrameLiveLocation(debuggerModel,location){const locations=this._debuggerModelToData.get(debuggerModel).callFrameLocations;locations.add(location);}
_removeLiveLocation(location){const modelData=this._debuggerModelToData.get(location._script.debuggerModel);if(modelData)
modelData._disposeLocation(location);}
_debuggerResumed(event){const debuggerModel=(event.data);this._reset(debuggerModel);}};Bindings.DebuggerWorkspaceBinding.ModelData=class{constructor(debuggerModel,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this.callFrameLocations=new Set();const workspace=debuggerWorkspaceBinding._workspace;this._defaultMapping=new Bindings.DefaultScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._resourceMapping=new Bindings.ResourceScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._compilerMapping=new Bindings.CompilerScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding);this._locations=new Multimap();debuggerModel.setBeforePausedCallback(this._beforePaused.bind(this));}
_createLiveLocation(rawLocation,updateDelegate,locationPool){const script=(rawLocation.script());console.assert(script);const location=new Bindings.DebuggerWorkspaceBinding.Location(script,rawLocation,this._debuggerWorkspaceBinding,updateDelegate,locationPool);this._locations.set(script,location);location.update();return location;}
_disposeLocation(location){this._locations.delete(location._script,location);}
_updateLocations(script){for(const location of this._locations.get(script))
location.update();}
_rawLocationToUILocation(rawLocation){let uiLocation=null;uiLocation=uiLocation||this._compilerMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||this._resourceMapping.rawLocationToUILocation(rawLocation);uiLocation=uiLocation||Bindings.resourceMapping.jsLocationToUILocation(rawLocation);uiLocation=uiLocation||this._defaultMapping.rawLocationToUILocation(rawLocation);return(uiLocation);}
_uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){let rawLocation=null;rawLocation=rawLocation||this._compilerMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||this._resourceMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||Bindings.resourceMapping.uiLocationToJSLocation(uiSourceCode,lineNumber,columnNumber);rawLocation=rawLocation||this._defaultMapping.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);return rawLocation;}
_beforePaused(debuggerPausedDetails){return!!this._compilerMapping.mapsToSourceCode(debuggerPausedDetails.callFrames[0].location());}
_dispose(){this._debuggerModel.setBeforePausedCallback(null);this._compilerMapping.dispose();this._resourceMapping.dispose();this._defaultMapping.dispose();}};Bindings.DebuggerWorkspaceBinding.Location=class extends Bindings.LiveLocationWithPool{constructor(script,rawLocation,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._script=script;this._rawLocation=rawLocation;this._binding=binding;}
uiLocation(){const debuggerModelLocation=this._rawLocation;return this._binding.rawLocationToUILocation(debuggerModelLocation);}
dispose(){super.dispose();this._binding._removeLiveLocation(this);}
isBlackboxed(){return Bindings.blackboxManager.isBlackboxedRawLocation(this._rawLocation);}};Bindings.DebuggerWorkspaceBinding.StackTraceTopFrameLocation=class extends Bindings.LiveLocationWithPool{constructor(rawLocations,binding,updateDelegate,locationPool){super(updateDelegate,locationPool);this._updateScheduled=true;this._current=null;this._locations=rawLocations.map(location=>binding.createLiveLocation(location,this._scheduleUpdate.bind(this),locationPool));this._updateLocation();}
uiLocation(){return this._current.uiLocation();}
isBlackboxed(){return this._current.isBlackboxed();}
dispose(){super.dispose();for(const location of this._locations)
location.dispose();this._locations=null;this._current=null;}
_scheduleUpdate(){if(this._updateScheduled)
return;this._updateScheduled=true;setImmediate(this._updateLocation.bind(this));}
_updateLocation(){this._updateScheduled=false;if(!this._locations)
return;this._current=this._locations.find(location=>!location.isBlackboxed())||this._locations[0];this.update();}};Bindings.DebuggerSourceMapping=function(){};Bindings.DebuggerSourceMapping.prototype={rawLocationToUILocation(rawLocation){},uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){},};Bindings.debuggerWorkspaceBinding;;Bindings.BreakpointManager=class extends Common.Object{constructor(workspace,targetManager,debuggerWorkspaceBinding){super();this._storage=new Bindings.BreakpointManager.Storage();this._workspace=workspace;this._targetManager=targetManager;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._breakpointsForUISourceCode=new Map();this._breakpointByStorageId=new Map();this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,this._projectRemoved,this);this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this._uiSourceCodeAdded,this);this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this._uiSourceCodeRemoved,this);}
static _breakpointStorageId(url,lineNumber,columnNumber){if(!url)
return'';return url+':'+lineNumber+':'+columnNumber;}
copyBreakpoints(fromURL,toSourceCode){const breakpointItems=this._storage.breakpointItems(fromURL);for(const item of breakpointItems)
this.setBreakpoint(toSourceCode,item.lineNumber,item.columnNumber,item.condition,item.enabled);}
_restoreBreakpoints(uiSourceCode){const url=uiSourceCode.url();if(!url)
return;this._storage.mute();const breakpointItems=this._storage.breakpointItems(url);for(const item of breakpointItems)
this._innerSetBreakpoint(uiSourceCode,item.lineNumber,item.columnNumber,item.condition,item.enabled);this._storage.unmute();}
_uiSourceCodeAdded(event){const uiSourceCode=(event.data);this._restoreBreakpoints(uiSourceCode);}
_uiSourceCodeRemoved(event){const uiSourceCode=(event.data);this._removeUISourceCode(uiSourceCode);}
_removeUISourceCode(uiSourceCode){const breakpoints=uiSourceCode[Bindings.BreakpointManager._breakpointsSymbol]||new Set();for(const breakpoint of breakpoints)
breakpoint._resetLocations();}
setBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){let uiLocation=new Workspace.UILocation(uiSourceCode,lineNumber,columnNumber);const normalizedLocation=this._debuggerWorkspaceBinding.normalizeUILocation(uiLocation);if(normalizedLocation.id()!==uiLocation.id()){Common.Revealer.reveal(normalizedLocation);uiLocation=normalizedLocation;}
return this._innerSetBreakpoint(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber,condition,enabled);}
_innerSetBreakpoint(uiSourceCode,lineNumber,columnNumber,condition,enabled){const itemId=Bindings.BreakpointManager._breakpointStorageId(uiSourceCode.url(),lineNumber,columnNumber);let breakpoint=this._breakpointByStorageId.get(itemId);if(breakpoint){breakpoint.setPrimaryUISourceCode(uiSourceCode);breakpoint._updateState(condition,enabled);breakpoint._updateBreakpoint();return breakpoint;}
breakpoint=new Bindings.BreakpointManager.Breakpoint(this,uiSourceCode,uiSourceCode.url(),lineNumber,columnNumber,condition,enabled);this._breakpointByStorageId.set(itemId,breakpoint);return breakpoint;}
findBreakpoints(uiSourceCode,lineNumber){const breakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);const lineBreakpoints=breakpoints?breakpoints.get(lineNumber):null;return lineBreakpoints?lineBreakpoints.valuesArray()[0]:[];}
findBreakpoint(uiSourceCode,lineNumber,columnNumber){const breakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);const lineBreakpoints=breakpoints?breakpoints.get(lineNumber):null;const columnBreakpoints=lineBreakpoints?lineBreakpoints.get(columnNumber):null;return columnBreakpoints?columnBreakpoints[0]:null;}
possibleBreakpoints(uiSourceCode,textRange){const startLocation=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,textRange.startLine,textRange.startColumn);const endLocation=Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,textRange.endLine,textRange.endColumn);if(!startLocation||!endLocation||startLocation.debuggerModel!==endLocation.debuggerModel)
return Promise.resolve([]);return startLocation.debuggerModel.getPossibleBreakpoints(startLocation,endLocation,false).then(toUILocations.bind(this));function toUILocations(locations){let sortedLocations=locations.map(location=>this._debuggerWorkspaceBinding.rawLocationToUILocation(location));sortedLocations=sortedLocations.filter(location=>location&&location.uiSourceCode===uiSourceCode);sortedLocations.sort(Workspace.UILocation.comparator);if(!sortedLocations.length)
return[];const result=[sortedLocations[0]];let lastLocation=sortedLocations[0];for(let i=1;i<sortedLocations.length;++i){if(sortedLocations[i].id()===lastLocation.id())
continue;result.push(sortedLocations[i]);lastLocation=sortedLocations[i];}
return result;}}
breakpointsForUISourceCode(uiSourceCode){let result=[];const uiSourceCodeBreakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);const breakpoints=uiSourceCodeBreakpoints?uiSourceCodeBreakpoints.valuesArray():[];for(let i=0;i<breakpoints.length;++i){const lineBreakpoints=breakpoints[i];const columnBreakpointArrays=lineBreakpoints?lineBreakpoints.valuesArray():[];result=result.concat.apply(result,columnBreakpointArrays);}
return result;}
_allBreakpoints(){let result=[];const uiSourceCodes=this._breakpointsForUISourceCode.keysArray();for(let i=0;i<uiSourceCodes.length;++i)
result=result.concat(this.breakpointsForUISourceCode(uiSourceCodes[i]));return result;}
breakpointLocationsForUISourceCode(uiSourceCode){const uiSourceCodeBreakpoints=this._breakpointsForUISourceCode.get(uiSourceCode);const lineNumbers=uiSourceCodeBreakpoints?uiSourceCodeBreakpoints.keysArray():[];const result=[];for(let i=0;i<lineNumbers.length;++i){const lineBreakpoints=uiSourceCodeBreakpoints.get(lineNumbers[i]);const columnNumbers=lineBreakpoints.keysArray();for(let j=0;j<columnNumbers.length;++j){const columnBreakpoints=lineBreakpoints.get(columnNumbers[j]);const lineNumber=parseInt(lineNumbers[i],10);const columnNumber=parseInt(columnNumbers[j],10);for(let k=0;k<columnBreakpoints.length;++k){const breakpoint=columnBreakpoints[k];const uiLocation=uiSourceCode.uiLocation(lineNumber,columnNumber);result.push({breakpoint:breakpoint,uiLocation:uiLocation});}}}
return result;}
allBreakpointLocations(){let result=[];const uiSourceCodes=this._breakpointsForUISourceCode.keysArray();for(let i=0;i<uiSourceCodes.length;++i)
result=result.concat(this.breakpointLocationsForUISourceCode(uiSourceCodes[i]));return result;}
toggleAllBreakpoints(toggleState){const breakpoints=this._allBreakpoints();for(let i=0;i<breakpoints.length;++i)
breakpoints[i].setEnabled(toggleState);}
removeAllBreakpoints(){const breakpoints=this._allBreakpoints();for(let i=0;i<breakpoints.length;++i)
breakpoints[i].remove(false);}
removeOtherBreakpoints(selectedBreakpoints){const allBreakpoints=this._allBreakpoints();allBreakpoints.forEach(breakpoint=>{if(!selectedBreakpoints.has(breakpoint))
breakpoint.remove(false);});}
_projectRemoved(event){const project=(event.data);const uiSourceCodes=project.uiSourceCodes();for(let i=0;i<uiSourceCodes.length;++i)
this._removeUISourceCode(uiSourceCodes[i]);}
_removeBreakpoint(breakpoint,removeFromStorage){if(removeFromStorage)
this._storage._removeBreakpoint(breakpoint);this._breakpointByStorageId.delete(breakpoint._breakpointStorageId());}
_uiLocationAdded(breakpoint,uiLocation){let breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints){breakpoints=new Map();this._breakpointsForUISourceCode.set(uiLocation.uiSourceCode,breakpoints);}
let lineBreakpoints=breakpoints.get(uiLocation.lineNumber);if(!lineBreakpoints){lineBreakpoints=new Map();breakpoints.set(uiLocation.lineNumber,lineBreakpoints);}
let columnBreakpoints=lineBreakpoints.get(uiLocation.columnNumber);if(!columnBreakpoints){columnBreakpoints=[];lineBreakpoints.set(uiLocation.columnNumber,columnBreakpoints);}
columnBreakpoints.push(breakpoint);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointAdded,{breakpoint:breakpoint,uiLocation:uiLocation});}
_uiLocationRemoved(breakpoint,uiLocation){const breakpoints=this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);if(!breakpoints)
return;const lineBreakpoints=breakpoints.get(uiLocation.lineNumber);if(!lineBreakpoints)
return;const columnBreakpoints=lineBreakpoints.get(uiLocation.columnNumber);if(!columnBreakpoints)
return;columnBreakpoints.remove(breakpoint);if(!columnBreakpoints.length)
lineBreakpoints.remove(uiLocation.columnNumber);if(!lineBreakpoints.size)
breakpoints.remove(uiLocation.lineNumber);if(!breakpoints.size)
this._breakpointsForUISourceCode.remove(uiLocation.uiSourceCode);this.dispatchEventToListeners(Bindings.BreakpointManager.Events.BreakpointRemoved,{breakpoint:breakpoint,uiLocation:uiLocation});}};Bindings.BreakpointManager.Events={BreakpointAdded:Symbol('breakpoint-added'),BreakpointRemoved:Symbol('breakpoint-removed')};Bindings.BreakpointManager.Breakpoint=class{constructor(breakpointManager,primaryUISourceCode,url,lineNumber,columnNumber,condition,enabled){this._breakpointManager=breakpointManager;this._url=url;this._lineNumber=lineNumber;this._columnNumber=columnNumber;this.setPrimaryUISourceCode(primaryUISourceCode);this._numberOfDebuggerLocationForUILocation=new Map();this._condition;this._enabled;this._isRemoved;this._fakePrimaryLocation;this._currentState=null;this._modelBreakpoints=new Map();this._updateState(condition,enabled);this._breakpointManager._targetManager.observeModels(SDK.DebuggerModel,this);}
refreshInDebugger(){if(this._isRemoved)
return;for(const breakpoint of this._modelBreakpoints.values())
breakpoint._refreshBreakpoint();}
modelAdded(debuggerModel){const debuggerWorkspaceBinding=this._breakpointManager._debuggerWorkspaceBinding;this._modelBreakpoints.set(debuggerModel,new Bindings.BreakpointManager.ModelBreakpoint(debuggerModel,this,debuggerWorkspaceBinding));}
modelRemoved(debuggerModel){const modelBreakpoint=this._modelBreakpoints.remove(debuggerModel);modelBreakpoint._cleanUpAfterDebuggerIsGone();modelBreakpoint._removeEventListeners();}
setPrimaryUISourceCode(primaryUISourceCode){const symbol=Bindings.BreakpointManager._breakpointsSymbol;if(this._primaryUISourceCode)
this._primaryUISourceCode[symbol].delete(this);this._primaryUISourceCode=primaryUISourceCode;if(!primaryUISourceCode)
return;if(!this._primaryUISourceCode[symbol])
this._primaryUISourceCode[symbol]=new Set();this._primaryUISourceCode[symbol].add(this);}
url(){return this._url;}
lineNumber(){return this._lineNumber;}
columnNumber(){return this._columnNumber;}
_replaceUILocation(oldUILocation,newUILocation){if(this._isRemoved)
return;this._removeUILocation(oldUILocation,true);this._removeFakeBreakpointAtPrimaryLocation();const current=(this._numberOfDebuggerLocationForUILocation.get(newUILocation.id())||0)+1;this._numberOfDebuggerLocationForUILocation.set(newUILocation.id(),current);if(current===1)
this._breakpointManager._uiLocationAdded(this,newUILocation);}
_removeUILocation(uiLocation,muteCreationFakeBreakpoint){if(!uiLocation||!this._numberOfDebuggerLocationForUILocation.has(uiLocation.id()))
return;const current=(this._numberOfDebuggerLocationForUILocation.get(uiLocation.id())||0)-1;this._numberOfDebuggerLocationForUILocation.set(uiLocation.id(),current);if(current!==0)
return;this._numberOfDebuggerLocationForUILocation.delete(uiLocation.id());this._breakpointManager._uiLocationRemoved(this,uiLocation);if(!muteCreationFakeBreakpoint)
this._fakeBreakpointAtPrimaryLocation();}
enabled(){return this._enabled;}
setEnabled(enabled){this._updateState(this._condition,enabled);}
condition(){return this._condition;}
setCondition(condition){this._updateState(condition,this._enabled);}
_updateState(condition,enabled){if(this._enabled===enabled&&this._condition===condition)
return;this._enabled=enabled;this._condition=condition;this._breakpointManager._storage._updateBreakpoint(this);this._updateBreakpoint();}
_updateBreakpoint(){this._removeFakeBreakpointAtPrimaryLocation();this._fakeBreakpointAtPrimaryLocation();const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i)
modelBreakpoints[i]._scheduleUpdateInDebugger();}
remove(keepInStorage){this._isRemoved=true;const removeFromStorage=!keepInStorage;this._removeFakeBreakpointAtPrimaryLocation();const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i){modelBreakpoints[i]._scheduleUpdateInDebugger();modelBreakpoints[i]._removeEventListeners();}
this.setPrimaryUISourceCode(null);this._breakpointManager._removeBreakpoint(this,removeFromStorage);this._breakpointManager._targetManager.unobserveModels(SDK.DebuggerModel,this);}
_updateInDebuggerForModel(debuggerModel){this._modelBreakpoints.get(debuggerModel)._scheduleUpdateInDebugger();}
_breakpointStorageId(){return Bindings.BreakpointManager._breakpointStorageId(this._url,this._lineNumber,this._columnNumber);}
_fakeBreakpointAtPrimaryLocation(){if(this._isRemoved||this._numberOfDebuggerLocationForUILocation.size||this._fakePrimaryLocation)
return;if(!this._primaryUISourceCode)
return;this._fakePrimaryLocation=this._primaryUISourceCode.uiLocation(this._lineNumber,this._columnNumber);if(this._fakePrimaryLocation)
this._breakpointManager._uiLocationAdded(this,this._fakePrimaryLocation);}
_removeFakeBreakpointAtPrimaryLocation(){if(this._fakePrimaryLocation){this._breakpointManager._uiLocationRemoved(this,this._fakePrimaryLocation);delete this._fakePrimaryLocation;}}
_resetLocations(){this.setPrimaryUISourceCode(null);this._removeFakeBreakpointAtPrimaryLocation();const modelBreakpoints=this._modelBreakpoints.valuesArray();for(let i=0;i<modelBreakpoints.length;++i)
modelBreakpoints[i]._resetLocations();}};Bindings.BreakpointManager._breakpointsSymbol=Symbol('breakpoints');Bindings.BreakpointManager.ModelBreakpoint=class{constructor(debuggerModel,breakpoint,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._breakpoint=breakpoint;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._liveLocations=new Bindings.LiveLocationPool();this._uiLocations=new Map();this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);this._hasPendingUpdate=false;this._isUpdating=false;this._cancelCallback=false;this._currentState=null;if(this._debuggerModel.debuggerEnabled())
this._scheduleUpdateInDebugger();}
_resetLocations(){for(const uiLocation of this._uiLocations.values())
this._breakpoint._removeUILocation(uiLocation);this._uiLocations.clear();this._liveLocations.disposeAll();}
_scheduleUpdateInDebugger(){if(this._isUpdating){this._hasPendingUpdate=true;return;}
this._isUpdating=true;this._updateInDebugger(this._didUpdateInDebugger.bind(this));}
_didUpdateInDebugger(){this._isUpdating=false;if(this._hasPendingUpdate){this._hasPendingUpdate=false;this._scheduleUpdateInDebugger();}}
_scriptDiverged(){const uiSourceCode=this._breakpoint._primaryUISourceCode;if(!uiSourceCode)
return false;const scriptFile=this._debuggerWorkspaceBinding.scriptFile(uiSourceCode,this._debuggerModel);return!!scriptFile&&scriptFile.hasDivergedFromVM();}
async _updateInDebugger(callback){if(this._debuggerModel.target().isDisposed()){this._cleanUpAfterDebuggerIsGone();callback();return;}
const uiSourceCode=this._breakpoint._primaryUISourceCode;const lineNumber=this._breakpoint._lineNumber;const columnNumber=this._breakpoint._columnNumber;const condition=this._breakpoint.condition();let debuggerLocation=uiSourceCode&&Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber);if(debuggerLocation&&debuggerLocation.debuggerModel!==this._debuggerModel)
debuggerLocation=null;let newState;if(this._breakpoint._isRemoved||!this._breakpoint.enabled()||this._scriptDiverged()){newState=null;}else if(debuggerLocation){const script=debuggerLocation.script();if(script.sourceURL){newState=new Bindings.BreakpointManager.Breakpoint.State(script.sourceURL,null,null,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}else{newState=new Bindings.BreakpointManager.Breakpoint.State(null,script.scriptId,script.hash,debuggerLocation.lineNumber,debuggerLocation.columnNumber,condition);}}else if(this._breakpoint._currentState&&this._breakpoint._currentState.url){const position=this._breakpoint._currentState;newState=new Bindings.BreakpointManager.Breakpoint.State(position.url,null,null,position.lineNumber,position.columnNumber,condition);}else if(uiSourceCode){newState=new Bindings.BreakpointManager.Breakpoint.State(uiSourceCode.url(),null,null,lineNumber,columnNumber,condition);}
if(this._debuggerId&&Bindings.BreakpointManager.Breakpoint.State.equals(newState,this._currentState)){callback();return;}
this._breakpoint._currentState=newState;if(this._debuggerId){await this._refreshBreakpoint();callback();return;}
if(!newState){callback();return;}
let result;this._currentState=newState;if(newState.url){result=await this._debuggerModel.setBreakpointByURL(newState.url,newState.lineNumber,newState.columnNumber,newState.condition);}else if(newState.scriptId&&newState.scriptHash){result=await this._debuggerModel.setBreakpointInAnonymousScript(newState.scriptId,newState.scriptHash,newState.lineNumber,newState.columnNumber,newState.condition);}
if(result&&result.breakpointId)
this._didSetBreakpointInDebugger(callback,result.breakpointId,result.locations);else
this._didSetBreakpointInDebugger(callback,null,[]);}
async _refreshBreakpoint(){if(!this._debuggerId)
return;this._resetLocations();await this._debuggerModel.removeBreakpoint(this._debuggerId);this._didRemoveFromDebugger();this._currentState=null;this._scheduleUpdateInDebugger();}
_didSetBreakpointInDebugger(callback,breakpointId,locations){if(this._cancelCallback){this._cancelCallback=false;callback();return;}
if(!breakpointId){this._breakpoint.remove(true);callback();return;}
this._debuggerId=breakpointId;this._debuggerModel.addBreakpointListener(this._debuggerId,this._breakpointResolved,this);for(let i=0;i<locations.length;++i){if(!this._addResolvedLocation(locations[i]))
break;}
callback();}
_didRemoveFromDebugger(){if(this._cancelCallback){this._cancelCallback=false;return;}
this._resetLocations();this._debuggerModel.removeBreakpointListener(this._debuggerId,this._breakpointResolved,this);delete this._debuggerId;}
_breakpointResolved(event){this._addResolvedLocation((event.data));}
_locationUpdated(location,liveLocation){const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;const oldUILocation=this._uiLocations.get(location.id())||null;this._uiLocations.set(location.id(),uiLocation);this._breakpoint._replaceUILocation(oldUILocation,uiLocation);}
_addResolvedLocation(location){const uiLocation=this._debuggerWorkspaceBinding.rawLocationToUILocation(location);if(!uiLocation)
return false;const breakpoint=this._breakpoint._breakpointManager.findBreakpoint(uiLocation.uiSourceCode,uiLocation.lineNumber,uiLocation.columnNumber);if(breakpoint&&breakpoint!==this._breakpoint){this._breakpoint.remove(false);return false;}
this._debuggerWorkspaceBinding.createLiveLocation(location,this._locationUpdated.bind(this,location),this._liveLocations);return true;}
_cleanUpAfterDebuggerIsGone(){if(this._isUpdating)
this._cancelCallback=true;this._resetLocations();this._currentState=null;if(this._debuggerId)
this._didRemoveFromDebugger();}
_removeEventListeners(){this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasDisabled,this._cleanUpAfterDebuggerIsGone,this);this._debuggerModel.removeEventListener(SDK.DebuggerModel.Events.DebuggerWasEnabled,this._scheduleUpdateInDebugger,this);}};Bindings.BreakpointManager.Breakpoint.State=class{constructor(url,scriptId,scriptHash,lineNumber,columnNumber,condition){this.url=url;this.scriptId=scriptId;this.scriptHash=scriptHash;this.lineNumber=lineNumber;this.columnNumber=columnNumber;this.condition=condition;}
static equals(stateA,stateB){if(!stateA||!stateB)
return false;return stateA.url===stateB.url&&stateA.scriptId===stateB.scriptId&&stateA.scriptHash===stateB.scriptHash&&stateA.lineNumber===stateB.lineNumber&&stateA.columnNumber===stateB.columnNumber&&stateA.condition===stateB.condition;}};Bindings.BreakpointManager.Storage=class{constructor(){this._setting=Common.settings.createLocalSetting('breakpoints',[]);this._breakpoints=new Map();const items=(this._setting.get());for(const item of items){item.columnNumber=item.columnNumber||0;this._breakpoints.set(Bindings.BreakpointManager._breakpointStorageId(item.url,item.lineNumber,item.columnNumber),item);}
this._muted;}
mute(){this._muted=true;}
unmute(){delete this._muted;}
breakpointItems(url){return Array.from(this._breakpoints.values()).filter(item=>item.url===url);}
_updateBreakpoint(breakpoint){if(this._muted||!breakpoint._breakpointStorageId())
return;this._breakpoints.set(breakpoint._breakpointStorageId(),new Bindings.BreakpointManager.Storage.Item(breakpoint));this._save();}
_removeBreakpoint(breakpoint){if(this._muted)
return;this._breakpoints.delete(breakpoint._breakpointStorageId());this._save();}
_save(){this._setting.set(Array.from(this._breakpoints.values()));}};Bindings.BreakpointManager.Storage.Item=class{constructor(breakpoint){this.url=breakpoint._url;this.lineNumber=breakpoint.lineNumber();this.columnNumber=breakpoint.columnNumber();this.condition=breakpoint.condition();this.enabled=breakpoint.enabled();}};Bindings.breakpointManager;;Bindings.ContentProviderBasedProject=class extends Workspace.ProjectStore{constructor(workspace,id,type,displayName,isServiceProject){super(workspace,id,type,displayName);this._contentProviders={};this._isServiceProject=isServiceProject;workspace.addProject(this);}
requestFileContent(uiSourceCode,callback){const contentProvider=this._contentProviders[uiSourceCode.url()];(async()=>{callback(await contentProvider.requestContent(),await contentProvider.contentEncoded());})();}
isServiceProject(){return this._isServiceProject;}
requestMetadata(uiSourceCode){return Promise.resolve(uiSourceCode[Bindings.ContentProviderBasedProject._metadata]);}
canSetFileContent(){return false;}
setFileContent(uiSourceCode,newContent,isBase64,callback){callback(null);}
fullDisplayName(uiSourceCode){let parentPath=uiSourceCode.parentURL().replace(/^(?:https?|file)\:\/\//,'');try{parentPath=decodeURI(parentPath);}catch(e){}
return parentPath+'/'+uiSourceCode.displayName(true);}
mimeType(uiSourceCode){return(uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]);}
canRename(){return false;}
rename(uiSourceCode,newName,callback){const path=uiSourceCode.url();this.performRename(path,newName,innerCallback.bind(this));function innerCallback(success,newName){if(success&&newName){const copyOfPath=path.split('/');copyOfPath[copyOfPath.length-1]=newName;const newPath=copyOfPath.join('/');this._contentProviders[newPath]=this._contentProviders[path];delete this._contentProviders[path];this.renameUISourceCode(uiSourceCode,newName);}
callback(success,newName);}}
excludeFolder(path){}
canExcludeFolder(path){return false;}
createFile(path,name,content,isBase64){}
canCreateFile(){return false;}
deleteFile(uiSourceCode){}
remove(){}
performRename(path,newName,callback){callback(false);}
searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){const contentProvider=this._contentProviders[uiSourceCode.url()];return contentProvider.searchInContent(query,caseSensitive,isRegex);}
async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){const result=[];progress.setTotalWork(filesMathingFileQuery.length);await Promise.all(filesMathingFileQuery.map(searchInContent.bind(this)));progress.done();return result;async function searchInContent(path){const provider=this._contentProviders[path];let allMatchesFound=true;for(const query of searchConfig.queries().slice()){const searchMatches=await provider.searchInContent(query,!searchConfig.ignoreCase(),searchConfig.isRegex());if(!searchMatches.length){allMatchesFound=false;break;}}
if(allMatchesFound)
result.push(path);progress.worked(1);}}
indexContent(progress){setImmediate(progress.done.bind(progress));}
addUISourceCodeWithProvider(uiSourceCode,contentProvider,metadata,mimeType){uiSourceCode[Bindings.ContentProviderBasedProject._mimeType]=mimeType;this._contentProviders[uiSourceCode.url()]=contentProvider;uiSourceCode[Bindings.ContentProviderBasedProject._metadata]=metadata;this.addUISourceCode(uiSourceCode);}
addContentProvider(url,contentProvider,mimeType){const uiSourceCode=this.createUISourceCode(url,contentProvider.contentType());this.addUISourceCodeWithProvider(uiSourceCode,contentProvider,null,mimeType);return uiSourceCode;}
removeFile(path){delete this._contentProviders[path];this.removeUISourceCode(path);}
reset(){this._contentProviders={};this.removeProject();this.workspace().addProject(this);}
dispose(){this._contentProviders={};this.removeProject();}};Bindings.ContentProviderBasedProject._metadata=Symbol('ContentProviderBasedProject.Metadata');Bindings.ContentProviderBasedProject._mimeType=Symbol('Bindings.ContentProviderBasedProject._mimeType');;Bindings.DefaultScriptMapping=class{constructor(debuggerModel,workspace,debuggerWorkspaceBinding){this._debuggerModel=debuggerModel;this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;this._project=new Bindings.ContentProviderBasedProject(workspace,'debugger:'+debuggerModel.target().id(),Workspace.projectTypes.Debugger,'',true);this._eventListeners=[debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,this._parsedScriptSource,this),debuggerModel.addEventListener(SDK.DebuggerModel.Events.DiscardedAnonymousScriptSource,this._discardedScriptSource,this)];}
static scriptForUISourceCode(uiSourceCode){return uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol]||null;}
rawLocationToUILocation(rawLocation){const script=rawLocation.script();if(!script)
return null;const uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];const lineNumber=rawLocation.lineNumber-(script.isInlineScriptWithSourceURL()?script.lineOffset:0);let columnNumber=rawLocation.columnNumber||0;if(script.isInlineScriptWithSourceURL()&&!lineNumber&&columnNumber)
columnNumber-=script.columnOffset;return uiSourceCode.uiLocation(lineNumber,columnNumber);}
uiLocationToRawLocation(uiSourceCode,lineNumber,columnNumber){const script=uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol];if(!script)
return null;if(script.isInlineScriptWithSourceURL()){return this._debuggerModel.createRawLocation(script,lineNumber+script.lineOffset,lineNumber?columnNumber:columnNumber+script.columnOffset);}
return this._debuggerModel.createRawLocation(script,lineNumber,columnNumber);}
_parsedScriptSource(event){const script=(event.data);const name=Common.ParsedURL.extractName(script.sourceURL);const url='debugger:///VM'+script.scriptId+(name?' '+name:'');const uiSourceCode=this._project.createUISourceCode(url,Common.resourceTypes.Script);uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol]=script;script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]=uiSourceCode;this._project.addUISourceCodeWithProvider(uiSourceCode,script,null,'text/javascript');this._debuggerWorkspaceBinding.updateLocations(script);}
_discardedScriptSource(event){const script=(event.data);const uiSourceCode=script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];if(!uiSourceCode)
return;delete script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol];delete uiSourceCode[Bindings.DefaultScriptMapping._scriptSymbol];this._project.removeUISourceCode(uiSourceCode.url());}
_debuggerReset(){this._project.reset();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);this._debuggerReset();this._project.dispose();}};Bindings.DefaultScriptMapping._scriptSymbol=Symbol('symbol');Bindings.DefaultScriptMapping._uiSourceCodeSymbol=Symbol('uiSourceCodeSymbol');;Bindings.ChunkedReader=function(){};Bindings.ChunkedReader.prototype={fileSize(){},loadedSize(){},fileName(){},cancel(){},error(){}};Bindings.ChunkedFileReader=class{constructor(blob,chunkSize,chunkTransferredCallback){this._file=blob;this._fileSize=blob.size;this._loadedSize=0;this._chunkSize=chunkSize;this._chunkTransferredCallback=chunkTransferredCallback;this._decoder=new TextDecoder();this._isCanceled=false;this._error=null;}
read(output){if(this._chunkTransferredCallback)
this._chunkTransferredCallback(this);this._output=output;this._reader=new FileReader();this._reader.onload=this._onChunkLoaded.bind(this);this._reader.onerror=this._onError.bind(this);this._loadChunk();return new Promise(resolve=>this._transferFinished=resolve);}
cancel(){this._isCanceled=true;}
loadedSize(){return this._loadedSize;}
fileSize(){return this._fileSize;}
fileName(){return this._file.name;}
error(){return this._error;}
_onChunkLoaded(event){if(this._isCanceled)
return;if(event.target.readyState!==FileReader.DONE)
return;const buffer=event.target.result;this._loadedSize+=buffer.byteLength;const endOfFile=this._loadedSize===this._fileSize;const decodedString=this._decoder.decode(buffer,{stream:!endOfFile});this._output.write(decodedString);if(this._isCanceled)
return;if(this._chunkTransferredCallback)
this._chunkTransferredCallback(this);if(endOfFile){this._file=null;this._reader=null;this._output.close();this._transferFinished(!this._error);return;}
this._loadChunk();}
_loadChunk(){const chunkStart=this._loadedSize;const chunkEnd=Math.min(this._fileSize,chunkStart+this._chunkSize);const nextPart=this._file.slice(chunkStart,chunkEnd);this._reader.readAsArrayBuffer(nextPart);}
_onError(event){this._error=event.target.error;this._transferFinished(false);}};Bindings.FileOutputStream=class{async open(fileName){this._closed=false;this._writeCallbacks=[];this._fileName=fileName;const saveResponse=await Workspace.fileManager.save(this._fileName,'',true);if(saveResponse)
Workspace.fileManager.addEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);return!!saveResponse;}
write(data){return new Promise(resolve=>{this._writeCallbacks.push(resolve);Workspace.fileManager.append(this._fileName,data);});}
close(){this._closed=true;if(this._writeCallbacks.length)
return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);}
_onAppendDone(event){if(event.data!==this._fileName)
return;this._writeCallbacks.shift()();if(this._writeCallbacks.length)
return;if(!this._closed)
return;Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL,this._onAppendDone,this);Workspace.fileManager.close(this._fileName);}};;Bindings.BlackboxManager=class{constructor(debuggerWorkspaceBinding){this._debuggerWorkspaceBinding=debuggerWorkspaceBinding;SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.ParsedScriptSource,this._parsedScriptSource,this);SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.GlobalObjectCleared,this._globalObjectCleared,this);Common.moduleSetting('skipStackFramesPattern').addChangeListener(this._patternChanged.bind(this));Common.moduleSetting('skipContentScripts').addChangeListener(this._patternChanged.bind(this));this._listeners=new Set();this._debuggerModelData=new Map();this._isBlackboxedURLCache=new Map();SDK.targetManager.observeModels(SDK.DebuggerModel,this);}
addChangeListener(listener){this._listeners.add(listener);}
removeChangeListener(listener){this._listeners.delete(listener);}
modelAdded(debuggerModel){this._setBlackboxPatterns(debuggerModel);}
modelRemoved(debuggerModel){this._debuggerModelData.delete(debuggerModel);this._isBlackboxedURLCache.clear();}
_setBlackboxPatterns(debuggerModel){const regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const patterns=([]);for(const item of regexPatterns){if(!item.disabled&&item.pattern)
patterns.push(item.pattern);}
return debuggerModel.setBlackboxPatterns(patterns);}
isBlackboxedRawLocation(location){const script=location.script();if(!script)
return false;const positions=this._scriptPositions(script);if(!positions)
return this._isBlackboxedScript(script);const index=positions.lowerBound(location,comparator);return!!(index%2);function comparator(a,b){if(a.lineNumber!==b.lineNumber)
return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}}
isBlackboxedUISourceCode(uiSourceCode){const projectType=uiSourceCode.project().type();const isContentScript=projectType===Workspace.projectTypes.ContentScripts;if(isContentScript&&Common.moduleSetting('skipContentScripts').get())
return true;const url=this._uiSourceCodeURL(uiSourceCode);return url?this.isBlackboxedURL(url):false;}
isBlackboxedURL(url,isContentScript){if(this._isBlackboxedURLCache.has(url))
return!!this._isBlackboxedURLCache.get(url);if(isContentScript&&Common.moduleSetting('skipContentScripts').get())
return true;const regex=Common.moduleSetting('skipStackFramesPattern').asRegExp();const isBlackboxed=regex&&regex.test(url);this._isBlackboxedURLCache.set(url,isBlackboxed);return isBlackboxed;}
sourceMapLoaded(script,sourceMap){if(!sourceMap)
return Promise.resolve();const previousScriptState=this._scriptPositions(script);if(!previousScriptState)
return Promise.resolve();const hasBlackboxedMappings=sourceMap.sourceURLs().some(url=>this.isBlackboxedURL(url));const mappings=hasBlackboxedMappings?sourceMap.mappings().slice():[];if(!mappings.length){if(previousScriptState.length>0)
return this._setScriptState(script,[]);return Promise.resolve();}
mappings.sort(mappingComparator);let currentBlackboxed=false;let isBlackboxed=false;const positions=[];if(mappings[0].lineNumber!==0||mappings[0].columnNumber!==0){positions.push({lineNumber:0,columnNumber:0});currentBlackboxed=true;}
for(const mapping of mappings){if(mapping.sourceURL&&currentBlackboxed!==this.isBlackboxedURL(mapping.sourceURL)){positions.push({lineNumber:mapping.lineNumber,columnNumber:mapping.columnNumber});currentBlackboxed=!currentBlackboxed;}
isBlackboxed=currentBlackboxed||isBlackboxed;}
return this._setScriptState(script,!isBlackboxed?[]:positions);function mappingComparator(a,b){if(a.lineNumber!==b.lineNumber)
return a.lineNumber-b.lineNumber;return a.columnNumber-b.columnNumber;}}
_uiSourceCodeURL(uiSourceCode){return uiSourceCode.project().type()===Workspace.projectTypes.Debugger?null:uiSourceCode.url();}
canBlackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);return url?!!this._urlToRegExpString(url):false;}
blackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);if(url)
this._blackboxURL(url);}
unblackboxUISourceCode(uiSourceCode){const url=this._uiSourceCodeURL(uiSourceCode);if(url)
this._unblackboxURL(url);}
blackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(true);}
unblackboxContentScripts(){Common.moduleSetting('skipContentScripts').set(false);}
_blackboxURL(url){const regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const regexValue=this._urlToRegExpString(url);if(!regexValue)
return;let found=false;for(let i=0;i<regexPatterns.length;++i){const item=regexPatterns[i];if(item.pattern===regexValue){item.disabled=false;found=true;break;}}
if(!found)
regexPatterns.push({pattern:regexValue});Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);}
_unblackboxURL(url){let regexPatterns=Common.moduleSetting('skipStackFramesPattern').getAsArray();const regexValue=Bindings.blackboxManager._urlToRegExpString(url);if(!regexValue)
return;regexPatterns=regexPatterns.filter(function(item){return item.pattern!==regexValue;});for(let i=0;i<regexPatterns.length;++i){const item=regexPatterns[i];if(item.disabled)
continue;try{const regex=new RegExp(item.pattern);if(regex.test(url))
item.disabled=true;}catch(e){}}
Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns);}
_patternChanged(){this._isBlackboxedURLCache.clear();const promises=[];for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)){promises.push(this._setBlackboxPatterns(debuggerModel));for(const script of debuggerModel.scripts())
promises.push(this._addScript(script).then(loadSourceMap.bind(this,script)));}
Promise.all(promises).then(()=>{const listeners=Array.from(this._listeners);for(const listener of listeners)
listener();this._patternChangeFinishedForTests();});function loadSourceMap(script){return this.sourceMapLoaded(script,this._debuggerWorkspaceBinding.sourceMapForScript(script));}}
_patternChangeFinishedForTests(){}
_globalObjectCleared(event){const debuggerModel=(event.data);this._debuggerModelData.delete(debuggerModel);this._isBlackboxedURLCache.clear();}
_parsedScriptSource(event){const script=(event.data);this._addScript(script);}
_addScript(script){if(!script.sourceURL&&!script.sourceMapURL)
return Promise.resolve();const blackboxed=this._isBlackboxedScript(script);return this._setScriptState(script,blackboxed?[{lineNumber:0,columnNumber:0}]:[]);}
_isBlackboxedScript(script){return this.isBlackboxedURL(script.sourceURL,script.isContentScript());}
_scriptPositions(script){if(this._debuggerModelData.has(script.debuggerModel))
return this._debuggerModelData.get(script.debuggerModel).get(script.scriptId)||null;return null;}
_setScriptPositions(script,positions){const debuggerModel=script.debuggerModel;if(!this._debuggerModelData.has(debuggerModel))
this._debuggerModelData.set(debuggerModel,new Map());this._debuggerModelData.get(debuggerModel).set(script.scriptId,positions);}
_setScriptState(script,positions){const previousScriptState=this._scriptPositions(script);if(previousScriptState){let hasChanged=false;hasChanged=previousScriptState.length!==positions.length;for(let i=0;!hasChanged&&i<positions.length;++i){hasChanged=positions[i].lineNumber!==previousScriptState[i].lineNumber||positions[i].columnNumber!==previousScriptState[i].columnNumber;}
if(!hasChanged)
return Promise.resolve();}else{if(positions.length===0)
return Promise.resolve().then(updateState.bind(this,false));}
return script.setBlackboxedRanges(positions).then(updateState.bind(this));function updateState(success){if(success){this._setScriptPositions(script,positions);this._debuggerWorkspaceBinding.updateLocations(script);const isBlackboxed=positions.length!==0;if(!isBlackboxed&&script.sourceMapURL)
this._debuggerWorkspaceBinding.maybeLoadSourceMap(script);}else{const hasPositions=!!this._scriptPositions(script);if(!hasPositions)
this._setScriptPositions(script,[]);}}}
_urlToRegExpString(url){const parsedURL=new Common.ParsedURL(url);if(parsedURL.isAboutBlank()||parsedURL.isDataURL())
return'';if(!parsedURL.isValid)
return'^'+url.escapeForRegExp()+'$';let name=parsedURL.lastPathComponent;if(name)
name='/'+name;else if(parsedURL.folderPathComponents)
name=parsedURL.folderPathComponents+'/';if(!name)
name=parsedURL.host;if(!name)
return'';const scheme=parsedURL.scheme;let prefix='';if(scheme&&scheme!=='http'&&scheme!=='https'){prefix='^'+scheme+'://';if(scheme==='chrome-extension')
prefix+=parsedURL.host+'\\b';prefix+='.*';}
return prefix+name.escapeForRegExp()+(url.endsWith(name)?'$':'\\b');}};Bindings.blackboxManager;;Bindings.NetworkProjectManager=class extends Common.Object{};Bindings.NetworkProjectManager.Events={FrameAttributionAdded:Symbol('FrameAttributionAdded'),FrameAttributionRemoved:Symbol('FrameAttributionRemoved')};Bindings.NetworkProject=class{static _resolveFrame(uiSourceCode,frameId){const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);return resourceTreeModel?resourceTreeModel.frameForId(frameId):null;}
static setInitialFrameAttribution(uiSourceCode,frameId){const frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame)
return;const attribution=new Map();attribution.set(frameId,{frame:frame,count:1});uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]=attribution;}
static cloneInitialFrameAttribution(fromUISourceCode,toUISourceCode){const fromAttribution=fromUISourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!fromAttribution)
return;const toAttribution=new Map();toUISourceCode[Bindings.NetworkProject._frameAttributionSymbol]=toAttribution;for(const frameId of fromAttribution.keys()){const value=fromAttribution.get(frameId);toAttribution.set(frameId,{frame:value.frame,count:value.count});}}
static addFrameAttribution(uiSourceCode,frameId){const frame=Bindings.NetworkProject._resolveFrame(uiSourceCode,frameId);if(!frame)
return;const frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];const attributionInfo=frameAttribution.get(frameId)||{frame:frame,count:0};attributionInfo.count+=1;frameAttribution.set(frameId,attributionInfo);if(attributionInfo.count!==1)
return;const data={uiSourceCode:uiSourceCode,frame:frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionAdded,data);}
static removeFrameAttribution(uiSourceCode,frameId){const frameAttribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];const attributionInfo=frameAttribution.get(frameId);console.assert(attributionInfo,'Failed to remove frame attribution for url: '+uiSourceCode.url());attributionInfo.count-=1;if(attributionInfo.count>0)
return;frameAttribution.delete(frameId);const data={uiSourceCode:uiSourceCode,frame:attributionInfo.frame};Bindings.networkProjectManager.dispatchEventToListeners(Bindings.NetworkProjectManager.Events.FrameAttributionRemoved,data);}
static targetForUISourceCode(uiSourceCode){return uiSourceCode.project()[Bindings.NetworkProject._targetSymbol]||null;}
static setTargetForProject(project,target){project[Bindings.NetworkProject._targetSymbol]=target;}
static framesForUISourceCode(uiSourceCode){const target=Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);const attribution=uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol];if(!resourceTreeModel||!attribution)
return[];const frames=Array.from(attribution.keys()).map(frameId=>resourceTreeModel.frameForId(frameId));return frames.filter(frame=>!!frame);}};Bindings.NetworkProject._targetSymbol=Symbol('target');Bindings.NetworkProject._frameAttributionSymbol=Symbol('Bindings.NetworkProject._frameAttributionSymbol');;Bindings.PresentationConsoleMessageManager=class{constructor(){SDK.targetManager.observeModels(SDK.DebuggerModel,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared,this._consoleCleared,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded,event=>this._consoleMessageAdded((event.data)));SDK.consoleModel.messages().forEach(this._consoleMessageAdded,this);}
modelAdded(debuggerModel){debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]=new Bindings.PresentationConsoleMessageHelper(debuggerModel);}
modelRemoved(debuggerModel){debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleCleared();}
_consoleMessageAdded(message){if(!message.isErrorOrWarning()||!message.runtimeModel()||message.source===SDK.ConsoleMessage.MessageSource.Violation)
return;const debuggerModel=message.runtimeModel().debuggerModel();debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleMessageAdded(message);}
_consoleCleared(){for(const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel))
debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleCleared();}};Bindings.PresentationConsoleMessageManager._symbol=Symbol('PresentationConsoleMessageHelper');Bindings.PresentationConsoleMessageHelper=class{constructor(debuggerModel){this._debuggerModel=debuggerModel;this._pendingConsoleMessages={};this._presentationConsoleMessages=[];debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource,event=>setImmediate(this._parsedScriptSource.bind(this,event)));debuggerModel.addEventListener(SDK.DebuggerModel.Events.FailedToParseScriptSource,event=>setImmediate(this._parsedScriptSource.bind(this,event)));debuggerModel.addEventListener(SDK.DebuggerModel.Events.GlobalObjectCleared,this._debuggerReset,this);this._locationPool=new Bindings.LiveLocationPool();}
_consoleMessageAdded(message){const rawLocation=this._rawLocation(message);if(rawLocation)
this._addConsoleMessageToScript(message,rawLocation);else
this._addPendingConsoleMessage(message);}
_rawLocation(message){if(message.scriptId)
return this._debuggerModel.createRawLocationByScriptId(message.scriptId,message.line,message.column);const callFrame=message.stackTrace&&message.stackTrace.callFrames?message.stackTrace.callFrames[0]:null;if(callFrame){return this._debuggerModel.createRawLocationByScriptId(callFrame.scriptId,callFrame.lineNumber,callFrame.columnNumber);}
if(message.url)
return this._debuggerModel.createRawLocationByURL(message.url,message.line,message.column);return null;}
_addConsoleMessageToScript(message,rawLocation){this._presentationConsoleMessages.push(new Bindings.PresentationConsoleMessage(message,rawLocation,this._locationPool));}
_addPendingConsoleMessage(message){if(!message.url)
return;if(!this._pendingConsoleMessages[message.url])
this._pendingConsoleMessages[message.url]=[];this._pendingConsoleMessages[message.url].push(message);}
_parsedScriptSource(event){const script=(event.data);const messages=this._pendingConsoleMessages[script.sourceURL];if(!messages)
return;const pendingMessages=[];for(let i=0;i<messages.length;i++){const message=messages[i];const rawLocation=this._rawLocation(message);if(!rawLocation)
continue;if(script.scriptId===rawLocation.scriptId)
this._addConsoleMessageToScript(message,rawLocation);else
pendingMessages.push(message);}
if(pendingMessages.length)
this._pendingConsoleMessages[script.sourceURL]=pendingMessages;else
delete this._pendingConsoleMessages[script.sourceURL];}
_consoleCleared(){this._pendingConsoleMessages={};this._debuggerReset();}
_debuggerReset(){for(const message of this._presentationConsoleMessages)
message.dispose();this._presentationConsoleMessages=[];this._locationPool.disposeAll();}};Bindings.PresentationConsoleMessage=class{constructor(message,rawLocation,locationPool){this._text=message.messageText;this._level=message.level===SDK.ConsoleMessage.MessageLevel.Error?Workspace.UISourceCode.Message.Level.Error:Workspace.UISourceCode.Message.Level.Warning;Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateLocation.bind(this),locationPool);}
_updateLocation(liveLocation){if(this._uiMessage)
this._uiMessage.remove();const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;this._uiMessage=uiLocation.uiSourceCode.addLineMessage(this._level,this._text,uiLocation.lineNumber,uiLocation.columnNumber);}
dispose(){if(this._uiMessage)
this._uiMessage.remove();}};;Bindings.resourceForURL=function(url){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)){const resource=resourceTreeModel.resourceForURL(url);if(resource)
return resource;}
return null;};Bindings.forAllResources=function(callback){for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
resourceTreeModel.forAllResources(callback);};Bindings.displayNameForURL=function(url){if(!url)
return'';const resource=Bindings.resourceForURL(url);if(resource)
return resource.displayName;const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode)
return uiSourceCode.displayName();const mainTarget=SDK.targetManager.mainTarget();const inspectedURL=mainTarget&&mainTarget.inspectedURL();if(!inspectedURL)
return url.trimURL('');const parsedURL=inspectedURL.asParsedURL();const lastPathComponent=parsedURL?parsedURL.lastPathComponent:parsedURL;const index=inspectedURL.indexOf(lastPathComponent);if(index!==-1&&index+lastPathComponent.length===inspectedURL.length){const baseURL=inspectedURL.substring(0,index);if(url.startsWith(baseURL))
return url.substring(index);}
if(!parsedURL)
return url;const displayName=url.trimURL(parsedURL.host);return displayName==='/'?parsedURL.host+'/':displayName;};Bindings.metadataForURL=function(target,frameId,url){const resourceTreeModel=target.model(SDK.ResourceTreeModel);if(!resourceTreeModel)
return null;const frame=resourceTreeModel.frameForId(frameId);if(!frame)
return null;return Bindings.resourceMetadata(frame.resourceForURL(url));};Bindings.resourceMetadata=function(resource){if(!resource||(typeof resource.contentSize()!=='number'&&!resource.lastModified()))
return null;return new Workspace.UISourceCodeMetadata(resource.lastModified(),resource.contentSize());};Bindings.frameIdForScript=function(script){const executionContext=script.executionContext();if(executionContext)
return executionContext.frameId||'';const resourceTreeModel=script.debuggerModel.target().model(SDK.ResourceTreeModel);if(!resourceTreeModel||!resourceTreeModel.mainFrame)
return'';return resourceTreeModel.mainFrame.id;};;Bindings.TempFile=class{constructor(){this._lastBlob=null;}
write(pieces){if(this._lastBlob)
pieces.unshift(this._lastBlob);this._lastBlob=new Blob(pieces,{type:'text/plain'});}
read(){return this.readRange();}
size(){return this._lastBlob?this._lastBlob.size:0;}
async readRange(startOffset,endOffset){if(!this._lastBlob){Common.console.error('Attempt to read a temp file that was never written');return Promise.resolve('');}
const blob=typeof startOffset==='number'||typeof endOffset==='number'?this._lastBlob.slice((startOffset),(endOffset)):this._lastBlob;const reader=new FileReader();try{await new Promise((resolve,reject)=>{reader.onloadend=resolve;reader.onerror=reject;reader.readAsText(blob);});}catch(error){Common.console.error('Failed to read from temp file: '+error.message);}
return reader.result;}
copyToOutputStream(outputStream,progress){if(!this._lastBlob){outputStream.close();return Promise.resolve((null));}
const reader=new Bindings.ChunkedFileReader((this._lastBlob),10*1000*1000,progress);return reader.read(outputStream).then(success=>success?null:reader.error());}
remove(){this._lastBlob=null;}};Bindings.TempFileBackingStorage=class{constructor(){this._file=null;this._strings;this._stringsLength;this.reset();}
appendString(string){this._strings.push(string);this._stringsLength+=string.length;const flushStringLength=10*1024*1024;if(this._stringsLength>flushStringLength)
this._flush();}
appendAccessibleString(string){this._flush();const startOffset=this._file.size();this._strings.push(string);this._flush();return this._file.readRange.bind(this._file,startOffset,this._file.size());}
_flush(){if(!this._strings.length)
return;if(!this._file)
this._file=new Bindings.TempFile();this._stringsLength=0;this._file.write(this._strings.splice(0));}
finishWriting(){this._flush();}
reset(){if(this._file)
this._file.remove();this._file=null;this._strings=[];this._stringsLength=0;}
writeToStream(outputStream){return this._file?this._file.copyToOutputStream(outputStream):Promise.resolve(null);}};Bindings.TempFileBackingStorage.Chunk;;self['Components']=self['Components']||{};Components.JSPresentationUtils={};Components.JSPresentationUtils.buildStackTracePreviewContents=function(target,linkifier,stackTrace,contentUpdated){const element=createElement('span');element.style.display='inline-block';const shadowRoot=UI.createShadowRootWithCoreStyles(element,'components/jsUtils.css');const contentElement=shadowRoot.createChild('table','stack-preview-container');const debuggerModel=target?target.model(SDK.DebuggerModel):null;let totalHiddenCallFramesCount=0;function appendStackTrace(stackTrace){let hiddenCallFrames=0;for(const stackFrame of stackTrace.callFrames){const row=createElement('tr');row.createChild('td').textContent='\n';row.createChild('td','function-name').textContent=UI.beautifyFunctionName(stackFrame.functionName);const link=linkifier.maybeLinkifyConsoleCallFrame(target,stackFrame);if(link){link.addEventListener('contextmenu',populateContextMenu.bind(null,link));if(debuggerModel){const location=debuggerModel.createRawLocationByScriptId(stackFrame.scriptId,stackFrame.lineNumber,stackFrame.columnNumber);if(location&&Bindings.blackboxManager.isBlackboxedRawLocation(location)){row.classList.add('blackboxed');++hiddenCallFrames;}}
row.createChild('td').textContent=' @ ';row.createChild('td').appendChild(link);}
contentElement.appendChild(row);}
totalHiddenCallFramesCount+=hiddenCallFrames;return stackTrace.callFrames.length===hiddenCallFrames;}
function populateContextMenu(link,event){const contextMenu=new UI.ContextMenu(event);event.consume(true);const uiLocation=Components.Linkifier.uiLocation(link);if(uiLocation&&Bindings.blackboxManager.canBlackboxUISourceCode(uiLocation.uiSourceCode)){if(Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode)){contextMenu.debugSection().appendItem(ls`Stop blackboxing`,()=>Bindings.blackboxManager.unblackboxUISourceCode(uiLocation.uiSourceCode));}else{contextMenu.debugSection().appendItem(ls`Blackbox script`,()=>Bindings.blackboxManager.blackboxUISourceCode(uiLocation.uiSourceCode));}}
contextMenu.appendApplicableItems(event);contextMenu.show();}
if(!stackTrace)
return element;appendStackTrace(stackTrace);let asyncStackTrace=stackTrace.parent;while(asyncStackTrace){if(!asyncStackTrace.callFrames.length){asyncStackTrace=asyncStackTrace.parent;continue;}
const row=contentElement.createChild('tr');row.createChild('td').textContent='\n';row.createChild('td','stack-preview-async-description').textContent=UI.asyncStackTraceLabel(asyncStackTrace.description);row.createChild('td');row.createChild('td');if(appendStackTrace(asyncStackTrace))
row.classList.add('blackboxed');asyncStackTrace=asyncStackTrace.parent;}
if(totalHiddenCallFramesCount){const row=contentElement.createChild('tr','show-blackboxed-link');row.createChild('td').textContent='\n';const cell=row.createChild('td');cell.colSpan=4;const showAllLink=cell.createChild('span','link');if(totalHiddenCallFramesCount===1)
showAllLink.textContent=ls`Show 1 more blackboxed frame`;else
showAllLink.textContent=ls`Show ${totalHiddenCallFramesCount} more blackboxed frames`;showAllLink.addEventListener('click',()=>{contentElement.classList.add('show-blackboxed');if(contentUpdated)
contentUpdated();},false);}
return element;};;Components.DockController=class extends Common.Object{constructor(canDock){super();this._canDock=canDock;this._closeButton=new UI.ToolbarButton(Common.UIString('Close'),'largeicon-delete');this._closeButton.addEventListener(UI.ToolbarButton.Events.Click,InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost));if(!canDock){this._dockSide=Components.DockController.State.Undocked;this._closeButton.setVisible(false);return;}
this._states=[Components.DockController.State.DockedToRight,Components.DockController.State.DockedToBottom,Components.DockController.State.DockedToLeft,Components.DockController.State.Undocked];this._currentDockStateSetting=Common.settings.moduleSetting('currentDockState');this._currentDockStateSetting.addChangeListener(this._dockSideChanged,this);this._lastDockStateSetting=Common.settings.createSetting('lastDockState','bottom');if(this._states.indexOf(this._currentDockStateSetting.get())===-1)
this._currentDockStateSetting.set('right');if(this._states.indexOf(this._lastDockStateSetting.get())===-1)
this._currentDockStateSetting.set('bottom');}
initialize(){if(!this._canDock)
return;this._titles=[Common.UIString('Dock to right'),Common.UIString('Dock to bottom'),Common.UIString('Dock to left'),Common.UIString('Undock into separate window')];this._dockSideChanged();}
_dockSideChanged(){this.setDockSide(this._currentDockStateSetting.get());}
dockSide(){return this._dockSide;}
canDock(){return this._canDock;}
isVertical(){return this._dockSide===Components.DockController.State.DockedToRight||this._dockSide===Components.DockController.State.DockedToLeft;}
setDockSide(dockSide){if(this._states.indexOf(dockSide)===-1)
dockSide=this._states[0];if(this._dockSide===dockSide)
return;if(this._dockSide)
this._lastDockStateSetting.set(this._dockSide);this._savedFocus=document.deepActiveElement();const eventData={from:this._dockSide,to:dockSide};this.dispatchEventToListeners(Components.DockController.Events.BeforeDockSideChanged,eventData);console.timeStamp('DockController.setIsDocked');this._dockSide=dockSide;this._currentDockStateSetting.set(dockSide);InspectorFrontendHost.setIsDocked(dockSide!==Components.DockController.State.Undocked,this._setIsDockedResponse.bind(this,eventData));this._closeButton.setVisible(this._dockSide!==Components.DockController.State.Undocked);this.dispatchEventToListeners(Components.DockController.Events.DockSideChanged,eventData);}
_setIsDockedResponse(eventData){this.dispatchEventToListeners(Components.DockController.Events.AfterDockSideChanged,eventData);if(this._savedFocus){this._savedFocus.focus();this._savedFocus=null;}}
_toggleDockSide(){if(this._lastDockStateSetting.get()===this._currentDockStateSetting.get()){const index=this._states.indexOf(this._currentDockStateSetting.get())||0;this._lastDockStateSetting.set(this._states[(index+1)%this._states.length]);}
this.setDockSide(this._lastDockStateSetting.get());}};Components.DockController.State={DockedToBottom:'bottom',DockedToRight:'right',DockedToLeft:'left',Undocked:'undocked'};Components.DockController.Events={BeforeDockSideChanged:Symbol('BeforeDockSideChanged'),DockSideChanged:Symbol('DockSideChanged'),AfterDockSideChanged:Symbol('AfterDockSideChanged')};Components.DockController.ToggleDockActionDelegate=class{handleAction(context,actionId){Components.dockController._toggleDockSide();return true;}};Components.DockController.CloseButtonProvider=class{item(){return Components.dockController._closeButton;}};Components.dockController;;Components.Linkifier=class{constructor(maxLengthForDisplayedURLs,useLinkDecorator){this._maxLength=maxLengthForDisplayedURLs||UI.MaxLengthForDisplayedURLs;this._anchorsByTarget=new Map();this._locationPoolByTarget=new Map();this._useLinkDecorator=!!useLinkDecorator;Components.Linkifier._instances.add(this);SDK.targetManager.observeTargets(this);}
static setLinkDecorator(decorator){console.assert(!Components.Linkifier._decorator,'Cannot re-register link decorator.');Components.Linkifier._decorator=decorator;decorator.addEventListener(Components.LinkDecorator.Events.LinkIconChanged,onLinkIconChanged);for(const linkifier of Components.Linkifier._instances)
linkifier._updateAllAnchorDecorations();function onLinkIconChanged(event){const uiSourceCode=(event.data);const links=uiSourceCode[Components.Linkifier._sourceCodeAnchors]||[];for(const link of links)
Components.Linkifier._updateLinkDecorations(link);}}
_updateAllAnchorDecorations(){for(const anchors of this._anchorsByTarget.values()){for(const anchor of anchors)
Components.Linkifier._updateLinkDecorations(anchor);}}
static _bindUILocation(anchor,uiLocation){Components.Linkifier._linkInfo(anchor).uiLocation=uiLocation;if(!uiLocation)
return;const uiSourceCode=uiLocation.uiSourceCode;let sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(!sourceCodeAnchors){sourceCodeAnchors=new Set();uiSourceCode[Components.Linkifier._sourceCodeAnchors]=sourceCodeAnchors;}
sourceCodeAnchors.add(anchor);}
static _unbindUILocation(anchor){const info=Components.Linkifier._linkInfo(anchor);if(!info.uiLocation)
return;const uiSourceCode=info.uiLocation.uiSourceCode;info.uiLocation=null;const sourceCodeAnchors=uiSourceCode[Components.Linkifier._sourceCodeAnchors];if(sourceCodeAnchors)
sourceCodeAnchors.delete(anchor);}
targetAdded(target){this._anchorsByTarget.set(target,[]);this._locationPoolByTarget.set(target,new Bindings.LiveLocationPool());}
targetRemoved(target){const locationPool=(this._locationPoolByTarget.remove(target));locationPool.disposeAll();const anchors=this._anchorsByTarget.remove(target);for(const anchor of anchors){const info=Components.Linkifier._linkInfo(anchor);info.liveLocation=null;Components.Linkifier._unbindUILocation(anchor);if(info.fallback){anchor.href=info.fallback.href;anchor.title=info.fallback.title;anchor.className=info.fallback.className;anchor.textContent=info.fallback.textContent;anchor[Components.Linkifier._infoSymbol]=info.fallback[Components.Linkifier._infoSymbol];}}}
maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){let fallbackAnchor=null;if(sourceURL){fallbackAnchor=Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});}
if(!target||target.isDisposed())
return fallbackAnchor;const debuggerModel=target.model(SDK.DebuggerModel);if(!debuggerModel)
return fallbackAnchor;const rawLocation=(scriptId?debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber||0):null)||debuggerModel.createRawLocationByURL(sourceURL,lineNumber,columnNumber||0);if(!rawLocation)
return fallbackAnchor;const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.debuggerModel.target())));const anchors=(this._anchorsByTarget.get(rawLocation.debuggerModel.target()));anchors.push(anchor);return anchor;}
linkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes){const scriptLink=this.maybeLinkifyScriptLocation(target,scriptId,sourceURL,lineNumber,columnNumber,classes);return scriptLink||Components.Linkifier.linkifyURL(sourceURL,{className:classes,lineNumber:lineNumber,columnNumber:columnNumber,maxLength:this._maxLength});}
linkifyRawLocation(rawLocation,fallbackUrl,classes){return this.linkifyScriptLocation(rawLocation.debuggerModel.target(),rawLocation.scriptId,fallbackUrl,rawLocation.lineNumber,rawLocation.columnNumber,classes);}
maybeLinkifyConsoleCallFrame(target,callFrame,classes){return this.maybeLinkifyScriptLocation(target,callFrame.scriptId,callFrame.url,callFrame.lineNumber,callFrame.columnNumber,classes);}
linkifyStackTraceTopFrame(target,stackTrace,classes){console.assert(stackTrace.callFrames&&stackTrace.callFrames.length);const topFrame=stackTrace.callFrames[0];const fallbackAnchor=Components.Linkifier.linkifyURL(topFrame.url,{className:classes,lineNumber:topFrame.lineNumber,columnNumber:topFrame.columnNumber,maxLength:this._maxLength});if(target.isDisposed())
return fallbackAnchor;const debuggerModel=target.model(SDK.DebuggerModel);const rawLocations=debuggerModel.createRawLocationsByStackTrace(stackTrace);if(rawLocations.length===0)
return fallbackAnchor;const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.fallback=fallbackAnchor;info.liveLocation=Bindings.debuggerWorkspaceBinding.createStackTraceTopFrameLiveLocation(rawLocations,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(target)));const anchors=(this._anchorsByTarget.get(target));anchors.push(anchor);return anchor;}
linkifyCSSLocation(rawLocation,classes){const anchor=Components.Linkifier._createLink('',classes||'');const info=Components.Linkifier._linkInfo(anchor);info.enableDecorator=this._useLinkDecorator;info.liveLocation=Bindings.cssWorkspaceBinding.createLiveLocation(rawLocation,this._updateAnchor.bind(this,anchor),(this._locationPoolByTarget.get(rawLocation.cssModel().target())));const anchors=(this._anchorsByTarget.get(rawLocation.cssModel().target()));anchors.push(anchor);return anchor;}
reset(){for(const target of this._anchorsByTarget.keysArray()){this.targetRemoved(target);this.targetAdded(target);}}
dispose(){for(const target of this._anchorsByTarget.keysArray())
this.targetRemoved(target);SDK.targetManager.unobserveTargets(this);Components.Linkifier._instances.delete(this);}
_updateAnchor(anchor,liveLocation){Components.Linkifier._unbindUILocation(anchor);const uiLocation=liveLocation.uiLocation();if(!uiLocation)
return;Components.Linkifier._bindUILocation(anchor,uiLocation);const text=uiLocation.linkText(true);Components.Linkifier._setTrimmedText(anchor,text,this._maxLength);let titleText=uiLocation.uiSourceCode.url();if(typeof uiLocation.lineNumber==='number')
titleText+=':'+(uiLocation.lineNumber+1);anchor.title=titleText;anchor.classList.toggle('webkit-html-blackbox-link',liveLocation.isBlackboxed());Components.Linkifier._updateLinkDecorations(anchor);}
static _updateLinkDecorations(anchor){const info=Components.Linkifier._linkInfo(anchor);if(!info||!info.enableDecorator)
return;if(!Components.Linkifier._decorator||!info.uiLocation)
return;if(info.icon&&info.icon.parentElement)
anchor.removeChild(info.icon);const icon=Components.Linkifier._decorator.linkIcon(info.uiLocation.uiSourceCode);if(icon){icon.style.setProperty('margin-right','2px');anchor.insertBefore(icon,anchor.firstChild);}
info.icon=icon;}
static linkifyURL(url,options){options=options||{};const text=options.text;const className=options.className||'';const lineNumber=options.lineNumber;const columnNumber=options.columnNumber;const preventClick=options.preventClick;const maxLength=options.maxLength||UI.MaxLengthForDisplayedURLs;if(!url||url.trim().toLowerCase().startsWith('javascript:')){const element=createElementWithClass('span',className);element.textContent=text||url||Common.UIString('(unknown)');return element;}
let linkText=text||Bindings.displayNameForURL(url);if(typeof lineNumber==='number'&&!text)
linkText+=':'+(lineNumber+1);const title=linkText!==url?url:'';const link=Components.Linkifier._createLink(linkText,className,maxLength,title,url,preventClick);const info=Components.Linkifier._linkInfo(link);if(typeof lineNumber==='number')
info.lineNumber=lineNumber;if(typeof columnNumber==='number')
info.columnNumber=columnNumber;return link;}
static linkifyRevealable(revealable,text,fallbackHref){const link=Components.Linkifier._createLink(text,'',UI.MaxLengthForDisplayedURLs,undefined,fallbackHref);Components.Linkifier._linkInfo(link).revealable=revealable;return link;}
static _createLink(text,className,maxLength,title,href,preventClick){const link=createElementWithClass('span',className);link.classList.add('devtools-link');if(title)
link.title=title;if(href)
link.href=href;Components.Linkifier._setTrimmedText(link,text,maxLength);link[Components.Linkifier._infoSymbol]={icon:null,enableDecorator:false,uiLocation:null,liveLocation:null,url:href||null,lineNumber:null,columnNumber:null,revealable:null,fallback:null};if(!preventClick)
link.addEventListener('click',Components.Linkifier._handleClick,false);else
link.classList.add('devtools-link-prevent-click');return link;}
static _setTrimmedText(link,text,maxLength){link.removeChildren();if(maxLength&&text.length>maxLength){const middleSplit=splitMiddle(text,maxLength);appendTextWithoutHashes(middleSplit[0]);appendHiddenText(middleSplit[1]);appendTextWithoutHashes(middleSplit[2]);}else{appendTextWithoutHashes(text);}
function appendHiddenText(string){const ellipsisNode=link.createChild('span','devtools-link-ellipsis').createTextChild('\u2026');ellipsisNode[Components.Linkifier._untruncatedNodeTextSymbol]=string;}
function appendTextWithoutHashes(string){const hashSplit=TextUtils.TextUtils.splitStringByRegexes(string,[/[a-f0-9]{20,}/g]);for(const match of hashSplit){if(match.regexIndex===-1){link.createTextChild(match.value);}else{link.createTextChild(match.value.substring(0,7));appendHiddenText(match.value.substring(7));}}}
function splitMiddle(string,maxLength){let leftIndex=Math.floor(maxLength/2);let rightIndex=string.length-Math.ceil(maxLength/2)+1;if(string.codePointAt(rightIndex-1)>=0x10000){rightIndex++;leftIndex++;}
if(leftIndex>0&&string.codePointAt(leftIndex-1)>=0x10000)
leftIndex--;return[string.substring(0,leftIndex),string.substring(leftIndex,rightIndex),string.substring(rightIndex)];}}
static untruncatedNodeText(node){return node[Components.Linkifier._untruncatedNodeTextSymbol]||node.textContent;}
static _linkInfo(link){return(link?link[Components.Linkifier._infoSymbol]||null:null);}
static _handleClick(event){const link=(event.currentTarget);event.consume(true);if(UI.isBeingEdited((event.target))||link.hasSelection())
return;const actions=Components.Linkifier._linkActions(link);if(actions.length)
actions[0].handler.call(null);}
static _linkHandlerSetting(){if(!Components.Linkifier._linkHandlerSettingInstance){Components.Linkifier._linkHandlerSettingInstance=Common.settings.createSetting('openLinkHandler',Common.UIString('auto'));}
return Components.Linkifier._linkHandlerSettingInstance;}
static registerLinkHandler(title,handler){Components.Linkifier._linkHandlers.set(title,handler);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();}
static unregisterLinkHandler(title){Components.Linkifier._linkHandlers.delete(title);self.runtime.sharedInstance(Components.Linkifier.LinkHandlerSettingUI)._update();}
static uiLocation(link){const info=Components.Linkifier._linkInfo(link);return info?info.uiLocation:null;}
static _linkActions(link){const info=Components.Linkifier._linkInfo(link);const result=[];if(!info)
return result;let url='';let uiLocation=null;if(info.uiLocation){uiLocation=info.uiLocation;url=uiLocation.uiSourceCode.contentURL();}else if(info.url){url=info.url;const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url)||Workspace.workspace.uiSourceCodeForURL(Common.ParsedURL.urlWithoutHash(url));uiLocation=uiSourceCode?uiSourceCode.uiLocation(info.lineNumber||0,info.columnNumber||0):null;}
const resource=url?Bindings.resourceForURL(url):null;const contentProvider=uiLocation?uiLocation.uiSourceCode:resource;const revealable=info.revealable||uiLocation||resource;if(revealable){const destination=Common.Revealer.revealDestination(revealable);result.push({section:'reveal',title:destination?ls`Reveal in ${destination}`:ls`Reveal`,handler:()=>Common.Revealer.reveal(revealable)});}
if(contentProvider){const lineNumber=uiLocation?uiLocation.lineNumber:info.lineNumber||0;for(const title of Components.Linkifier._linkHandlers.keys()){const handler=Components.Linkifier._linkHandlers.get(title);const action={section:'reveal',title:Common.UIString('Open using %s',title),handler:handler.bind(null,contentProvider,lineNumber)};if(title===Components.Linkifier._linkHandlerSetting().get())
result.unshift(action);else
result.push(action);}}
if(resource||info.url){result.push({section:'reveal',title:UI.openLinkExternallyLabel(),handler:()=>InspectorFrontendHost.openInNewTab(url)});result.push({section:'clipboard',title:UI.copyLinkAddressLabel(),handler:()=>InspectorFrontendHost.copyText(url)});}
return result;}};Components.Linkifier._instances=new Set();Components.Linkifier._decorator=null;Components.Linkifier._sourceCodeAnchors=Symbol('Linkifier.anchors');Components.Linkifier._infoSymbol=Symbol('Linkifier.info');Components.Linkifier._untruncatedNodeTextSymbol=Symbol('Linkifier.untruncatedNodeText');Components._LinkInfo;Components.LinkifyURLOptions;Components.Linkifier.MaxLengthToIgnoreLinkifier=10000;Components.Linkifier.LinkHandler;Components.Linkifier._linkHandlers=new Map();Components.LinkDecorator=function(){};Components.LinkDecorator.prototype={linkIcon(uiSourceCode){}};Components.LinkDecorator.Events={LinkIconChanged:Symbol('LinkIconChanged')};Components.Linkifier.LinkContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){let targetNode=(target);while(targetNode&&!targetNode[Components.Linkifier._infoSymbol])
targetNode=targetNode.parentNodeOrShadowHost();const link=(targetNode);const actions=Components.Linkifier._linkActions(link);for(const action of actions)
contextMenu.section(action.section).appendItem(action.title,action.handler);}};Components.Linkifier.LinkHandlerSettingUI=class{constructor(){this._element=createElementWithClass('select','chrome-select');this._element.addEventListener('change',this._onChange.bind(this),false);this._update();}
_update(){this._element.removeChildren();const names=Components.Linkifier._linkHandlers.keysArray();names.unshift(Common.UIString('auto'));for(const name of names){const option=createElement('option');option.textContent=name;option.selected=name===Components.Linkifier._linkHandlerSetting().get();this._element.appendChild(option);}
this._element.disabled=names.length<=1;}
_onChange(event){const value=event.target.value;Components.Linkifier._linkHandlerSetting().set(value);}
settingElement(){return UI.SettingsUI.createCustomSetting(Common.UIString('Link handling:'),this._element);}};Components.Linkifier.ContentProviderContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){const contentProvider=(target);if(!contentProvider.contentURL())
return;contextMenu.revealSection().appendItem(UI.openLinkExternallyLabel(),()=>InspectorFrontendHost.openInNewTab(contentProvider.contentURL()));for(const title of Components.Linkifier._linkHandlers.keys()){const handler=Components.Linkifier._linkHandlers.get(title);contextMenu.revealSection().appendItem(Common.UIString('Open using %s',title),handler.bind(null,contentProvider,0));}
if(contentProvider instanceof SDK.NetworkRequest)
return;contextMenu.clipboardSection().appendItem(UI.copyLinkAddressLabel(),()=>InspectorFrontendHost.copyText(contentProvider.contentURL()));}};;Components.reload=function(){if(Components.dockController.canDock()&&Components.dockController.dockSide()===Components.DockController.State.Undocked)
InspectorFrontendHost.setIsDocked(true,function(){});window.location.reload();};;Components.TargetDetachedDialog=class extends SDK.SDKModel{constructor(target){super(target);if(target.parentTarget())
return;target.registerInspectorDispatcher(this);target.inspectorAgent().enable();this._hideCrashedDialog=null;Components.TargetDetachedDialog._disconnectedScreenWithReasonWasShown=false;}
detached(reason){Components.TargetDetachedDialog._disconnectedScreenWithReasonWasShown=true;UI.RemoteDebuggingTerminatedScreen.show(reason);}
static webSocketConnectionLost(){UI.RemoteDebuggingTerminatedScreen.show('WebSocket disconnected');}
targetCrashed(){const dialog=new UI.Dialog();dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.addCloseButton();dialog.setDimmed(true);this._hideCrashedDialog=dialog.hide.bind(dialog);new UI.TargetCrashedScreen(()=>this._hideCrashedDialog=null).show(dialog.contentElement);dialog.show();}
targetReloadedAfterCrash(){if(this._hideCrashedDialog){this._hideCrashedDialog.call(null);this._hideCrashedDialog=null;}}};SDK.SDKModel.register(Components.TargetDetachedDialog,0,true);;self['Persistence']=self['Persistence']||{};Persistence.IsolatedFileSystem=class{constructor(manager,path,embedderPath,domFileSystem,type){this._manager=manager;this._path=path;this._embedderPath=embedderPath;this._domFileSystem=domFileSystem;this._type=type;this._excludedFoldersSetting=Common.settings.createLocalSetting('workspaceExcludedFolders',{});this._excludedFolders=new Set(this._excludedFoldersSetting.get()[path]||[]);this._excludedEmbedderFolders=[];this._initialFilePaths=new Set();this._initialGitFolders=new Set();}
static create(manager,path,embedderPath,type,name,rootURL){const domFileSystem=InspectorFrontendHost.isolatedFileSystem(name,rootURL);if(!domFileSystem)
return Promise.resolve((null));const fileSystem=new Persistence.IsolatedFileSystem(manager,path,embedderPath,domFileSystem,type);return fileSystem._initializeFilePaths().then(()=>fileSystem).catchException((null));}
static errorMessage(error){return Common.UIString('File system error: %s',error.message);}
getMetadata(path){let fulfill;const promise=new Promise(f=>fulfill=f);this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded,errorHandler);return promise;function fileEntryLoaded(entry){entry.getMetadata(fulfill,errorHandler);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting file metadata \''+path);fulfill(null);}}
initialFilePaths(){return this._initialFilePaths.valuesArray();}
initialGitFolders(){return this._initialGitFolders.valuesArray();}
path(){return this._path;}
embedderPath(){return this._embedderPath;}
type(){return this._type;}
_initializeFilePaths(){let fulfill;const promise=new Promise(x=>fulfill=x);let pendingRequests=1;const boundInnerCallback=innerCallback.bind(this);this._requestEntries('',boundInnerCallback);return promise;function innerCallback(entries){for(let i=0;i<entries.length;++i){const entry=entries[i];if(!entry.isDirectory){if(this.isFileExcluded(entry.fullPath))
continue;this._initialFilePaths.add(entry.fullPath.substr(1));}else{if(entry.fullPath.endsWith('/.git')){const lastSlash=entry.fullPath.lastIndexOf('/');const parentFolder=entry.fullPath.substring(1,lastSlash);this._initialGitFolders.add(parentFolder);}
if(this.isFileExcluded(entry.fullPath+'/')){this._excludedEmbedderFolders.push(Common.ParsedURL.urlToPlatformPath(this._path+entry.fullPath,Host.isWin()));continue;}
++pendingRequests;this._requestEntries(entry.fullPath,boundInnerCallback);}}
if((--pendingRequests===0))
fulfill();}}
async _createFoldersIfNotExist(folderPath){let dirEntry=await new Promise(resolve=>this._domFileSystem.root.getDirectory(folderPath,undefined,resolve,()=>resolve(null)));if(dirEntry)
return dirEntry;const paths=folderPath.split('/');let activePath='';for(const path of paths){activePath=activePath+'/'+path;dirEntry=await this._innerCreateFolderIfNeeded(activePath);if(!dirEntry)
return null;}
return dirEntry;}
_innerCreateFolderIfNeeded(path){return new Promise(resolve=>{this._domFileSystem.root.getDirectory(path,{create:true},dirEntry=>resolve(dirEntry),error=>{const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' trying to create directory \''+path+'\'');resolve(null);});});}
async createFile(path,name){const dirEntry=await this._createFoldersIfNotExist(path);if(!dirEntry)
return null;const fileEntry=await createFileCandidate.call(this,name||'NewFile');if(!fileEntry)
return null;return fileEntry.fullPath.substr(1);function createFileCandidate(name,newFileIndex){return new Promise(resolve=>{const nameCandidate=name+(newFileIndex||'');dirEntry.getFile(nameCandidate,{create:true,exclusive:true},resolve,error=>{if(error.name==='InvalidModificationError'){resolve(createFileCandidate.call(this,name,(newFileIndex?newFileIndex+1:1)));return;}
const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when testing if file exists \''+(this._path+'/'+path+'/'+nameCandidate)+'\'');resolve(null);});});}}
deleteFile(path){let resolveCallback;const promise=new Promise(resolve=>resolveCallback=resolve);this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));return promise;function fileEntryLoaded(fileEntry){fileEntry.remove(fileEntryRemoved,errorHandler.bind(this));}
function fileEntryRemoved(){resolveCallback(true);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when deleting file \''+(this._path+'/'+path)+'\'');resolveCallback(false);}}
requestFileBlob(path){return new Promise(resolve=>{this._domFileSystem.root.getFile(path,undefined,entry=>{entry.file(resolve,errorHandler.bind(this));},errorHandler.bind(this));function errorHandler(error){if(error.name==='NotFoundError'){resolve(null);return;}
const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when getting content for file \''+(this._path+'/'+path)+'\'');resolve(null);}});}
async requestFileContent(path,callback){const blob=await this.requestFileBlob(path);if(!blob)
return null;const reader=new FileReader();const extension=Common.ParsedURL.extractExtension(path);const encoded=Persistence.IsolatedFileSystem.BinaryExtensions.has(extension);reader.onloadend=content=>{if(reader.error){console.error('Can\'t read file: '+path+': '+reader.error);callback(null,false);return;}
let result;try{result=reader.result;}catch(e){result=null;console.error('Can\'t read file: '+path+': '+e);}
if(result===undefined||result===null){callback(null,false);return;}
callback(encoded?btoa(result):result,encoded);};if(encoded)
reader.readAsBinaryString(blob);else
reader.readAsText(blob);}
setFileContent(path,content,isBase64,callback){Host.userMetrics.actionTaken(Host.UserMetrics.Action.FileSavedInWorkspace);this._domFileSystem.root.getFile(path,{create:true},fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(entry){entry.createWriter(fileWriterCreated.bind(this),errorHandler.bind(this));}
async function fileWriterCreated(fileWriter){fileWriter.onerror=errorHandler.bind(this);fileWriter.onwriteend=fileWritten;let blob;if(isBase64)
blob=await(await fetch(`data:application/octet-stream;base64,${content}`)).blob();else
blob=new Blob([content],{type:'text/plain'});fileWriter.write(blob);function fileWritten(){fileWriter.onwriteend=callback;fileWriter.truncate(blob.size);}}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when setting content for file \''+(this._path+'/'+path)+'\'');callback();}}
renameFile(path,newName,callback){newName=newName?newName.trim():newName;if(!newName||newName.indexOf('/')!==-1){callback(false);return;}
let fileEntry;let dirEntry;this._domFileSystem.root.getFile(path,undefined,fileEntryLoaded.bind(this),errorHandler.bind(this));function fileEntryLoaded(entry){if(entry.name===newName){callback(false);return;}
fileEntry=entry;fileEntry.getParent(dirEntryLoaded.bind(this),errorHandler.bind(this));}
function dirEntryLoaded(entry){dirEntry=entry;dirEntry.getFile(newName,null,newFileEntryLoaded,newFileEntryLoadErrorHandler.bind(this));}
function newFileEntryLoaded(entry){callback(false);}
function newFileEntryLoadErrorHandler(error){if(error.name!=='NotFoundError'){callback(false);return;}
fileEntry.moveTo(dirEntry,newName,fileRenamed,errorHandler.bind(this));}
function fileRenamed(entry){callback(true,entry.name);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when renaming file \''+(this._path+'/'+path)+'\' to \''+newName+'\'');callback(false);}}
_readDirectory(dirEntry,callback){const dirReader=dirEntry.createReader();let entries=[];function innerCallback(results){if(!results.length){callback(entries.sort());}else{entries=entries.concat(toArray(results));dirReader.readEntries(innerCallback,errorHandler);}}
function toArray(list){return Array.prototype.slice.call(list||[],0);}
dirReader.readEntries(innerCallback,errorHandler);function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when reading directory \''+dirEntry.fullPath+'\'');callback([]);}}
_requestEntries(path,callback){this._domFileSystem.root.getDirectory(path,undefined,innerCallback.bind(this),errorHandler);function innerCallback(dirEntry){this._readDirectory(dirEntry,callback);}
function errorHandler(error){const errorMessage=Persistence.IsolatedFileSystem.errorMessage(error);console.error(errorMessage+' when requesting entry \''+path+'\'');callback([]);}}
_saveExcludedFolders(){const settingValue=this._excludedFoldersSetting.get();settingValue[this._path]=this._excludedFolders.valuesArray();this._excludedFoldersSetting.set(settingValue);}
addExcludedFolder(path){this._excludedFolders.add(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,path);}
removeExcludedFolder(path){this._excludedFolders.delete(path);this._saveExcludedFolders();this._manager.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,path);}
fileSystemRemoved(){const settingValue=this._excludedFoldersSetting.get();delete settingValue[this._path];this._excludedFoldersSetting.set(settingValue);}
isFileExcluded(folderPath){if(this._excludedFolders.has(folderPath))
return true;const regex=this._manager.workspaceFolderExcludePatternSetting().asRegExp();return!!(regex&&regex.test(folderPath));}
excludedFolders(){return this._excludedFolders;}
searchInPath(query,progress){return new Promise(resolve=>{const requestId=this._manager.registerCallback(innerCallback);InspectorFrontendHost.searchInPath(requestId,this._embedderPath,query);function innerCallback(files){resolve(files.map(path=>Common.ParsedURL.platformPathToURL(path)));progress.worked(1);}});}
indexContent(progress){progress.setTotalWork(1);const requestId=this._manager.registerProgress(progress);InspectorFrontendHost.indexPath(requestId,this._embedderPath,JSON.stringify(this._excludedEmbedderFolders));}};Persistence.IsolatedFileSystem.ImageExtensions=new Set(['jpeg','jpg','svg','gif','webp','png','ico','tiff','tif','bmp']);Persistence.IsolatedFileSystem.BinaryExtensions=new Set(['cmd','com','exe','a','ar','iso','tar','bz2','gz','lz','lzma','z','7z','apk','arc','cab','dmg','jar','pak','rar','zip','3gp','aac','aiff','flac','m4a','mmf','mp3','ogg','oga','raw','sln','wav','wma','webm','mkv','flv','vob','ogv','gifv','avi','mov','qt','mp4','m4p','m4v','mpg','mpeg','jpeg','jpg','gif','webp','png','ico','tiff','tif','bmp']);;Persistence.IsolatedFileSystemManager=class extends Common.Object{constructor(){super();this._fileSystems=new Map();this._callbacks=new Map();this._progresses=new Map();InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemRemoved,this._onFileSystemRemoved,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemAdded,this._onFileSystemAdded,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,this._onFileSystemFilesChanged,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,this._onIndexingTotalWorkCalculated,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingWorked,this._onIndexingWorked,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingDone,this._onIndexingDone,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SearchCompleted,this._onSearchCompleted,this);this._initExcludePatterSetting();this._fileSystemRequestResolve=null;this._fileSystemsLoadedPromise=this._requestFileSystems();}
_requestFileSystems(){let fulfill;const promise=new Promise(f=>fulfill=f);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemsLoaded,onFileSystemsLoaded,this);InspectorFrontendHost.requestFileSystems();return promise;function onFileSystemsLoaded(event){const fileSystems=(event.data);const promises=[];for(let i=0;i<fileSystems.length;++i)
promises.push(this._innerAddFileSystem(fileSystems[i],false));Promise.all(promises).then(onFileSystemsAdded);}
function onFileSystemsAdded(fileSystems){fulfill(fileSystems.filter(fs=>!!fs));}}
addFileSystem(type){return new Promise(resolve=>{this._fileSystemRequestResolve=resolve;InspectorFrontendHost.addFileSystem(type||'');});}
removeFileSystem(fileSystem){InspectorFrontendHost.removeFileSystem(fileSystem.embedderPath());}
waitForFileSystems(){return this._fileSystemsLoadedPromise;}
_innerAddFileSystem(fileSystem,dispatchEvent){const embedderPath=fileSystem.fileSystemPath;const fileSystemURL=Common.ParsedURL.platformPathToURL(fileSystem.fileSystemPath);const promise=Persistence.IsolatedFileSystem.create(this,fileSystemURL,embedderPath,fileSystem.type,fileSystem.fileSystemName,fileSystem.rootURL);return promise.then(storeFileSystem.bind(this));function storeFileSystem(fileSystem){if(!fileSystem)
return null;this._fileSystems.set(fileSystemURL,fileSystem);if(dispatchEvent)
this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,fileSystem);return fileSystem;}}
async _onFileSystemAdded(event){const errorMessage=(event.data['errorMessage']);let fileSystem=(event.data['fileSystem']);if(errorMessage){Common.console.error(Common.UIString('Unable to add filesystem: %s',errorMessage));if(!this._fileSystemRequestResolve)
return;this._fileSystemRequestResolve.call(null,null);this._fileSystemRequestResolve=null;}else if(fileSystem){fileSystem=await this._innerAddFileSystem(fileSystem,true);if(this._fileSystemRequestResolve){this._fileSystemRequestResolve.call(null,fileSystem);this._fileSystemRequestResolve=null;}}}
_onFileSystemRemoved(event){const embedderPath=(event.data);const fileSystemPath=Common.ParsedURL.platformPathToURL(embedderPath);const isolatedFileSystem=this._fileSystems.get(fileSystemPath);if(!isolatedFileSystem)
return;this._fileSystems.delete(fileSystemPath);isolatedFileSystem.fileSystemRemoved();this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,isolatedFileSystem);}
_onFileSystemFilesChanged(event){const urlPaths={changed:groupFilePathsIntoFileSystemPaths.call(this,event.data.changed),added:groupFilePathsIntoFileSystemPaths.call(this,event.data.added),removed:groupFilePathsIntoFileSystemPaths.call(this,event.data.removed)};this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,urlPaths);function groupFilePathsIntoFileSystemPaths(embedderPaths){const paths=new Multimap();for(const embedderPath of embedderPaths){const filePath=Common.ParsedURL.platformPathToURL(embedderPath);for(const fileSystemPath of this._fileSystems.keys()){if(this._fileSystems.get(fileSystemPath).isFileExcluded(embedderPath))
continue;const pathPrefix=fileSystemPath.endsWith('/')?fileSystemPath:fileSystemPath+'/';if(!filePath.startsWith(pathPrefix))
continue;paths.set(fileSystemPath,filePath);}}
return paths;}}
fileSystems(){return this._fileSystems.valuesArray();}
fileSystem(fileSystemPath){return this._fileSystems.get(fileSystemPath)||null;}
_initExcludePatterSetting(){const defaultCommonExcludedFolders=['/node_modules/','/bower_components/','/\\.devtools','/\\.git/','/\\.sass-cache/','/\\.hg/','/\\.idea/','/\\.svn/','/\\.cache/','/\\.project/'];const defaultWinExcludedFolders=['/Thumbs.db$','/ehthumbs.db$','/Desktop.ini$','/\\$RECYCLE.BIN/'];const defaultMacExcludedFolders=['/\\.DS_Store$','/\\.Trashes$','/\\.Spotlight-V100$','/\\.AppleDouble$','/\\.LSOverride$','/Icon$','/\\._.*$'];const defaultLinuxExcludedFolders=['/.*~$'];let defaultExcludedFolders=defaultCommonExcludedFolders;if(Host.isWin())
defaultExcludedFolders=defaultExcludedFolders.concat(defaultWinExcludedFolders);else if(Host.isMac())
defaultExcludedFolders=defaultExcludedFolders.concat(defaultMacExcludedFolders);else
defaultExcludedFolders=defaultExcludedFolders.concat(defaultLinuxExcludedFolders);const defaultExcludedFoldersPattern=defaultExcludedFolders.join('|');this._workspaceFolderExcludePatternSetting=Common.settings.createRegExpSetting('workspaceFolderExcludePattern',defaultExcludedFoldersPattern,Host.isWin()?'i':'');}
workspaceFolderExcludePatternSetting(){return this._workspaceFolderExcludePatternSetting;}
registerCallback(callback){const requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._callbacks.set(requestId,callback);return requestId;}
registerProgress(progress){const requestId=++Persistence.IsolatedFileSystemManager._lastRequestId;this._progresses.set(requestId,progress);return requestId;}
_onIndexingTotalWorkCalculated(event){const requestId=(event.data['requestId']);const totalWork=(event.data['totalWork']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.setTotalWork(totalWork);}
_onIndexingWorked(event){const requestId=(event.data['requestId']);const worked=(event.data['worked']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.worked(worked);if(progress.isCanceled()){InspectorFrontendHost.stopIndexing(requestId);this._onIndexingDone(event);}}
_onIndexingDone(event){const requestId=(event.data['requestId']);const progress=this._progresses.get(requestId);if(!progress)
return;progress.done();this._progresses.delete(requestId);}
_onSearchCompleted(event){const requestId=(event.data['requestId']);const files=(event.data['files']);const callback=this._callbacks.get(requestId);if(!callback)
return;callback.call(null,files);this._callbacks.delete(requestId);}};Persistence.IsolatedFileSystemManager.FileSystem;Persistence.IsolatedFileSystemManager.FilesChangedData;Persistence.IsolatedFileSystemManager.Events={FileSystemAdded:Symbol('FileSystemAdded'),FileSystemRemoved:Symbol('FileSystemRemoved'),FileSystemFilesChanged:Symbol('FileSystemFilesChanged'),ExcludedFolderAdded:Symbol('ExcludedFolderAdded'),ExcludedFolderRemoved:Symbol('ExcludedFolderRemoved')};Persistence.IsolatedFileSystemManager._lastRequestId=0;Persistence.isolatedFileSystemManager;;Persistence.FileSystemWorkspaceBinding=class{constructor(isolatedFileSystemManager,workspace){this._isolatedFileSystemManager=isolatedFileSystemManager;this._workspace=workspace;this._eventListeners=[this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,this._onFileSystemAdded,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,this._onFileSystemRemoved,this),this._isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemFilesChanged,this._fileSystemFilesChanged,this)];this._boundFileSystems=new Map();this._isolatedFileSystemManager.waitForFileSystems().then(this._onFileSystemsLoaded.bind(this));}
static projectId(fileSystemPath){return fileSystemPath;}
static relativePath(uiSourceCode){const baseURL=(uiSourceCode.project())._fileSystemBaseURL;return uiSourceCode.url().substring(baseURL.length).split('/');}
static fileSystemType(project){const fileSystem=(project)._fileSystem;return fileSystem.type();}
static completeURL(project,relativePath){const fsProject=(project);return fsProject._fileSystemBaseURL+relativePath;}
static _contentTypeForExtension(extension){if(Persistence.FileSystemWorkspaceBinding._styleSheetExtensions.has(extension))
return Common.resourceTypes.Stylesheet;if(Persistence.FileSystemWorkspaceBinding._documentExtensions.has(extension))
return Common.resourceTypes.Document;if(Persistence.FileSystemWorkspaceBinding._imageExtensions.has(extension))
return Common.resourceTypes.Image;if(Persistence.FileSystemWorkspaceBinding._scriptExtensions.has(extension))
return Common.resourceTypes.Script;return Persistence.FileSystemWorkspaceBinding._binaryExtensions.has(extension)?Common.resourceTypes.Other:Common.resourceTypes.Document;}
static fileSystemPath(projectId){return projectId;}
fileSystemManager(){return this._isolatedFileSystemManager;}
_onFileSystemsLoaded(fileSystems){for(const fileSystem of fileSystems)
this._addFileSystem(fileSystem);}
_onFileSystemAdded(event){const fileSystem=(event.data);this._addFileSystem(fileSystem);}
_addFileSystem(fileSystem){const boundFileSystem=new Persistence.FileSystemWorkspaceBinding.FileSystem(this,fileSystem,this._workspace);this._boundFileSystems.set(fileSystem.path(),boundFileSystem);}
_onFileSystemRemoved(event){const fileSystem=(event.data);const boundFileSystem=this._boundFileSystems.get(fileSystem.path());boundFileSystem.dispose();this._boundFileSystems.remove(fileSystem.path());}
_fileSystemFilesChanged(event){const paths=(event.data);for(const fileSystemPath of paths.changed.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.changed.get(fileSystemPath).forEach(path=>fileSystem._fileChanged(path));}
for(const fileSystemPath of paths.added.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.added.get(fileSystemPath).forEach(path=>fileSystem._fileChanged(path));}
for(const fileSystemPath of paths.removed.keysArray()){const fileSystem=this._boundFileSystems.get(fileSystemPath);if(!fileSystem)
continue;paths.removed.get(fileSystemPath).forEach(path=>fileSystem.removeUISourceCode(path));}}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);for(const fileSystem of this._boundFileSystems.values()){fileSystem.dispose();this._boundFileSystems.remove(fileSystem._fileSystem.path());}}};Persistence.FileSystemWorkspaceBinding._styleSheetExtensions=new Set(['css','scss','sass','less']);Persistence.FileSystemWorkspaceBinding._documentExtensions=new Set(['htm','html','asp','aspx','phtml','jsp']);Persistence.FileSystemWorkspaceBinding._scriptExtensions=new Set(['asp','aspx','c','cc','cljs','coffee','cpp','cs','dart','java','js','jsp','jsx','h','m','mjs','mm','py','sh','ts','tsx','ls']);Persistence.FileSystemWorkspaceBinding._imageExtensions=Persistence.IsolatedFileSystem.ImageExtensions;Persistence.FileSystemWorkspaceBinding._binaryExtensions=Persistence.IsolatedFileSystem.BinaryExtensions;Persistence.FileSystemWorkspaceBinding.FileSystem=class extends Workspace.ProjectStore{constructor(fileSystemWorkspaceBinding,isolatedFileSystem,workspace){const fileSystemPath=isolatedFileSystem.path();const id=Persistence.FileSystemWorkspaceBinding.projectId(fileSystemPath);console.assert(!workspace.project(id));const displayName=fileSystemPath.substr(fileSystemPath.lastIndexOf('/')+1);super(workspace,id,Workspace.projectTypes.FileSystem,displayName);this._fileSystem=isolatedFileSystem;this._fileSystemBaseURL=this._fileSystem.path()+'/';this._fileSystemParentURL=this._fileSystemBaseURL.substr(0,fileSystemPath.lastIndexOf('/')+1);this._fileSystemWorkspaceBinding=fileSystemWorkspaceBinding;this._fileSystemPath=fileSystemPath;this._creatingFilesGuard=new Set();workspace.addProject(this);this.populate();}
fileSystemPath(){return this._fileSystemPath;}
mimeType(uiSourceCode){return Common.ResourceType.mimeFromURL(uiSourceCode.url())||'text/plain';}
initialGitFolders(){return this._fileSystem.initialGitFolders().map(folder=>this._fileSystemPath+'/'+folder);}
_filePathForUISourceCode(uiSourceCode){return uiSourceCode.url().substring(this._fileSystemPath.length);}
isServiceProject(){return false;}
requestMetadata(uiSourceCode){if(uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata])
return uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata];const relativePath=this._filePathForUISourceCode(uiSourceCode);const promise=this._fileSystem.getMetadata(relativePath).then(onMetadata);uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=promise;return promise;function onMetadata(metadata){if(!metadata)
return null;return new Workspace.UISourceCodeMetadata(metadata.modificationTime,metadata.size);}}
requestFileBlob(uiSourceCode){return this._fileSystem.requestFileBlob(this._filePathForUISourceCode(uiSourceCode));}
requestFileContent(uiSourceCode,callback){const filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,callback);}
canSetFileContent(){return true;}
setFileContent(uiSourceCode,newContent,isBase64,callback){const filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.setFileContent(filePath,newContent,isBase64,callback.bind(this,''));}
fullDisplayName(uiSourceCode){const baseURL=(uiSourceCode.project())._fileSystemParentURL;return uiSourceCode.url().substring(baseURL.length);}
canRename(){return true;}
rename(uiSourceCode,newName,callback){if(newName===uiSourceCode.name()){callback(true,uiSourceCode.name(),uiSourceCode.url(),uiSourceCode.contentType());return;}
let filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.renameFile(filePath,newName,innerCallback.bind(this));function innerCallback(success,newName){if(!success||!newName){callback(false,newName);return;}
console.assert(newName);const slash=filePath.lastIndexOf('/');const parentPath=filePath.substring(0,slash);filePath=parentPath+'/'+newName;filePath=filePath.substr(1);const extension=this._extensionForPath(newName);const newURL=this._fileSystemBaseURL+filePath;const newContentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(extension);this.renameUISourceCode(uiSourceCode,newName);callback(true,newName,newURL,newContentType);}}
searchInFileContent(uiSourceCode,query,caseSensitive,isRegex){return new Promise(resolve=>{const filePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.requestFileContent(filePath,contentCallback);function contentCallback(content){resolve(content?Common.ContentProvider.performSearchInContent(content,query,caseSensitive,isRegex):[]);}});}
async findFilesMatchingSearchRequest(searchConfig,filesMathingFileQuery,progress){let result=filesMathingFileQuery;const queriesToRun=searchConfig.queries().slice();if(!queriesToRun.length)
queriesToRun.push('');progress.setTotalWork(queriesToRun.length);for(const query of queriesToRun){const files=await this._fileSystem.searchInPath(searchConfig.isRegex()?'':query,progress);result=result.intersectOrdered(files.sort(),String.naturalOrderComparator);progress.worked(1);}
progress.done();return result;}
indexContent(progress){this._fileSystem.indexContent(progress);}
_extensionForPath(path){return Common.ParsedURL.extractExtension(path);}
populate(){const chunkSize=1000;const filePaths=this._fileSystem.initialFilePaths();reportFileChunk.call(this,0);function reportFileChunk(from){const to=Math.min(from+chunkSize,filePaths.length);for(let i=from;i<to;++i)
this._addFile(filePaths[i]);if(to<filePaths.length)
setTimeout(reportFileChunk.bind(this,to),100);}}
excludeFolder(url){let relativeFolder=url.substring(this._fileSystemBaseURL.length);if(!relativeFolder.startsWith('/'))
relativeFolder='/'+relativeFolder;if(!relativeFolder.endsWith('/'))
relativeFolder+='/';this._fileSystem.addExcludedFolder(relativeFolder);const uiSourceCodes=this.uiSourceCodes().slice();for(let i=0;i<uiSourceCodes.length;++i){const uiSourceCode=uiSourceCodes[i];if(uiSourceCode.url().startsWith(url))
this.removeUISourceCode(uiSourceCode.url());}}
canExcludeFolder(path){return!!path&&Persistence.FileSystemWorkspaceBinding.fileSystemType(this)!=='overrides';}
canCreateFile(){return true;}
async createFile(path,name,content,isBase64){const guardFileName=this._fileSystemPath+path+(!path.endsWith('/')?'/':'')+name;this._creatingFilesGuard.add(guardFileName);const filePath=await this._fileSystem.createFile(path,name);if(!filePath)
return null;if(content)
await new Promise(resolve=>this._fileSystem.setFileContent(filePath,content,isBase64||false,resolve));this._creatingFilesGuard.delete(guardFileName);return this._addFile(filePath);}
deleteFile(uiSourceCode){const relativePath=this._filePathForUISourceCode(uiSourceCode);this._fileSystem.deleteFile(relativePath).then(success=>{if(success)
this.removeUISourceCode(uiSourceCode.url());});}
remove(){this._fileSystemWorkspaceBinding._isolatedFileSystemManager.removeFileSystem(this._fileSystem);}
_addFile(filePath){const extension=this._extensionForPath(filePath);const contentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(extension);const uiSourceCode=this.createUISourceCode(this._fileSystemBaseURL+filePath,contentType);this.addUISourceCode(uiSourceCode);return uiSourceCode;}
_fileChanged(path){if(this._creatingFilesGuard.has(path))
return;const uiSourceCode=this.uiSourceCodeForURL(path);if(!uiSourceCode){const contentType=Persistence.FileSystemWorkspaceBinding._contentTypeForExtension(this._extensionForPath(path));this.addUISourceCode(this.createUISourceCode(path,contentType));return;}
uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]=null;uiSourceCode.checkContentUpdated();}
dispose(){this.removeProject();}};Persistence.FileSystemWorkspaceBinding._metadata=Symbol('FileSystemWorkspaceBinding.Metadata');;Persistence.Automapping=class{constructor(workspace,onStatusAdded,onStatusRemoved){this._workspace=workspace;this._onStatusAdded=onStatusAdded;this._onStatusRemoved=onStatusRemoved;this._statuses=new Set();this._fileSystemUISourceCodes=new Map();this._sweepThrottler=new Common.Throttler(100);const pathEncoder=new Persistence.PathEncoder();this._filesIndex=new Persistence.Automapping.FilePathIndex(pathEncoder);this._projectFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._activeFoldersIndex=new Persistence.Automapping.FolderIndex(pathEncoder);this._eventListeners=[this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),this._workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,this._onUISourceCodeRenamed,this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data)),this),this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data)),this),];for(const fileSystem of workspace.projects())
this._onProjectAdded(fileSystem);for(const uiSourceCode of workspace.uiSourceCodes())
this._onUISourceCodeAdded(uiSourceCode);}
_scheduleRemap(){for(const status of this._statuses.valuesArray())
this._clearNetworkStatus(status.network);this._scheduleSweep();}
_scheduleSweep(){this._sweepThrottler.schedule(sweepUnmapped.bind(this));function sweepUnmapped(){const networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(const networkProject of networkProjects){for(const uiSourceCode of networkProject.uiSourceCodes())
this._computeNetworkStatus(uiSourceCode);}
this._onSweepHappenedForTest();return Promise.resolve();}}
_onSweepHappenedForTest(){}
_onProjectRemoved(project){for(const uiSourceCode of project.uiSourceCodes())
this._onUISourceCodeRemoved(uiSourceCode);if(project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystem=(project);for(const gitFolder of fileSystem.initialGitFolders())
this._projectFoldersIndex.removeFolder(gitFolder);this._projectFoldersIndex.removeFolder(fileSystem.fileSystemPath());this._scheduleRemap();}
_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem)
return;const fileSystem=(project);for(const gitFolder of fileSystem.initialGitFolders())
this._projectFoldersIndex.addFolder(gitFolder);this._projectFoldersIndex.addFolder(fileSystem.fileSystemPath());project.uiSourceCodes().forEach(this._onUISourceCodeAdded.bind(this));this._scheduleRemap();}
_onUISourceCodeAdded(uiSourceCode){const project=uiSourceCode.project();if(project.type()===Workspace.projectTypes.FileSystem){if(Persistence.FileSystemWorkspaceBinding.fileSystemType(project))
return;this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();}else if(project.type()===Workspace.projectTypes.Network){this._computeNetworkStatus(uiSourceCode);}}
_onUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){this._filesIndex.removePath(uiSourceCode.url());this._fileSystemUISourceCodes.delete(uiSourceCode.url());const status=uiSourceCode[Persistence.Automapping._status];if(status)
this._clearNetworkStatus(status.network);}else if(uiSourceCode.project().type()===Workspace.projectTypes.Network){this._clearNetworkStatus(uiSourceCode);}}
_onUISourceCodeRenamed(event){const uiSourceCode=(event.data.uiSourceCode);const oldURL=(event.data.oldURL);if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem)
return;this._filesIndex.removePath(oldURL);this._fileSystemUISourceCodes.delete(oldURL);const status=uiSourceCode[Persistence.Automapping._status];if(status)
this._clearNetworkStatus(status.network);this._filesIndex.addPath(uiSourceCode.url());this._fileSystemUISourceCodes.set(uiSourceCode.url(),uiSourceCode);this._scheduleSweep();}
_computeNetworkStatus(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]||networkSourceCode[Persistence.Automapping._status])
return;const createBindingPromise=this._createBinding(networkSourceCode).then(validateStatus.bind(this)).then(onStatus.bind(this));networkSourceCode[Persistence.Automapping._processingPromise]=createBindingPromise;async function validateStatus(status){if(!status)
return null;if(status.network.contentType().isFromSourceMap()||!status.fileSystem.contentType().isTextType())
return status;if(status.fileSystem.isDirty()&&(status.network.isDirty()||status.network.hasCommits()))
return null;const contents=await Promise.all([status.fileSystem.requestContent(),new Promise(x=>status.network.project().requestFileContent(status.network,x))]);const fileSystemContent=contents[0];const networkContent=contents[1];if(fileSystemContent===null||networkContent===null)
return null;if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise)
return null;const target=Bindings.NetworkProject.targetForUISourceCode(status.network);let isValid=false;if(target&&target.isNodeJS()){const rewrappedNetworkContent=Persistence.Persistence.rewrapNodeJSContent(status.fileSystem,fileSystemContent,networkContent);isValid=fileSystemContent===rewrappedNetworkContent;}else{isValid=fileSystemContent.trimRight()===networkContent.trimRight();}
if(!isValid){this._prevalidationFailedForTest(status);return null;}
return status;}
function onStatus(status){if(networkSourceCode[Persistence.Automapping._processingPromise]!==createBindingPromise)
return;networkSourceCode[Persistence.Automapping._processingPromise]=null;if(!status||this._disposed){this._onBindingFailedForTest();return;}
if(status.network[Persistence.Automapping._status]||status.fileSystem[Persistence.Automapping._status])
return;this._statuses.add(status);status.network[Persistence.Automapping._status]=status;status.fileSystem[Persistence.Automapping._status]=status;if(status.exactMatch){const projectFolder=this._projectFoldersIndex.closestParentFolder(status.fileSystem.url());const newFolderAdded=projectFolder?this._activeFoldersIndex.addFolder(projectFolder):false;if(newFolderAdded)
this._scheduleSweep();}
this._onStatusAdded.call(null,status);}}
_prevalidationFailedForTest(binding){}
_onBindingFailedForTest(){}
_clearNetworkStatus(networkSourceCode){if(networkSourceCode[Persistence.Automapping._processingPromise]){networkSourceCode[Persistence.Automapping._processingPromise]=null;return;}
const status=networkSourceCode[Persistence.Automapping._status];if(!status)
return;this._statuses.delete(status);status.network[Persistence.Automapping._status]=null;status.fileSystem[Persistence.Automapping._status]=null;if(status.exactMatch){const projectFolder=this._projectFoldersIndex.closestParentFolder(status.fileSystem.url());if(projectFolder)
this._activeFoldersIndex.removeFolder(projectFolder);}
this._onStatusRemoved.call(null,status);}
_createBinding(networkSourceCode){if(networkSourceCode.url().startsWith('file://')){const fileSourceCode=this._fileSystemUISourceCodes.get(networkSourceCode.url());const status=fileSourceCode?new Persistence.AutomappingStatus(networkSourceCode,fileSourceCode,false):null;return Promise.resolve(status);}
let networkPath=Common.ParsedURL.extractPath(networkSourceCode.url());if(networkPath===null)
return Promise.resolve((null));if(networkPath.endsWith('/'))
networkPath+='index.html';const similarFiles=this._filesIndex.similarFiles(networkPath).map(path=>this._fileSystemUISourceCodes.get(path));if(!similarFiles.length)
return Promise.resolve((null));return this._pullMetadatas(similarFiles.concat(networkSourceCode)).then(onMetadatas.bind(this));function onMetadatas(){const activeFiles=similarFiles.filter(file=>!!this._activeFoldersIndex.closestParentFolder(file.url()));const networkMetadata=networkSourceCode[Persistence.Automapping._metadata];if(!networkMetadata||(!networkMetadata.modificationTime&&typeof networkMetadata.contentSize!=='number')){if(activeFiles.length!==1)
return null;return new Persistence.AutomappingStatus(networkSourceCode,activeFiles[0],false);}
let exactMatches=this._filterWithMetadata(activeFiles,networkMetadata);if(!exactMatches.length)
exactMatches=this._filterWithMetadata(similarFiles,networkMetadata);if(exactMatches.length!==1)
return null;return new Persistence.AutomappingStatus(networkSourceCode,exactMatches[0],true);}}
_pullMetadatas(uiSourceCodes){const promises=uiSourceCodes.map(file=>fetchMetadata(file));return Promise.all(promises);function fetchMetadata(file){return file.requestMetadata().then(metadata=>file[Persistence.Automapping._metadata]=metadata);}}
_filterWithMetadata(files,networkMetadata){return files.filter(file=>{const fileMetadata=file[Persistence.Automapping._metadata];if(!fileMetadata)
return false;const timeMatches=!networkMetadata.modificationTime||Math.abs(networkMetadata.modificationTime-fileMetadata.modificationTime)<1000;const contentMatches=!networkMetadata.contentSize||fileMetadata.contentSize===networkMetadata.contentSize;return timeMatches&&contentMatches;});}
dispose(){if(this._disposed)
return;this._disposed=true;Common.EventTarget.removeEventListeners(this._eventListeners);for(const status of this._statuses.valuesArray())
this._clearNetworkStatus(status.network);}};Persistence.Automapping._status=Symbol('Automapping.Status');Persistence.Automapping._processingPromise=Symbol('Automapping.ProcessingPromise');Persistence.Automapping._metadata=Symbol('Automapping.Metadata');Persistence.Automapping.FilePathIndex=class{constructor(encoder){this._encoder=encoder;this._reversedIndex=new Common.Trie();}
addPath(path){const encodedPath=this._encoder.encode(path);this._reversedIndex.add(encodedPath.reverse());}
removePath(path){const encodedPath=this._encoder.encode(path);this._reversedIndex.remove(encodedPath.reverse());}
similarFiles(networkPath){const encodedPath=this._encoder.encode(networkPath);const longestCommonPrefix=this._reversedIndex.longestPrefix(encodedPath.reverse(),false);if(!longestCommonPrefix)
return[];return this._reversedIndex.words(longestCommonPrefix).map(encodedPath=>this._encoder.decode(encodedPath.reverse()));}};Persistence.Automapping.FolderIndex=class{constructor(encoder){this._encoder=encoder;this._index=new Common.Trie();this._folderCount=new Map();}
addFolder(path){if(path.endsWith('/'))
path=path.substring(0,path.length-1);const encodedPath=this._encoder.encode(path);this._index.add(encodedPath);const count=this._folderCount.get(encodedPath)||0;this._folderCount.set(encodedPath,count+1);return count===0;}
removeFolder(path){if(path.endsWith('/'))
path=path.substring(0,path.length-1);const encodedPath=this._encoder.encode(path);const count=this._folderCount.get(encodedPath)||0;if(!count)
return false;if(count>1){this._folderCount.set(encodedPath,count-1);return false;}
this._index.remove(encodedPath);this._folderCount.delete(encodedPath);return true;}
closestParentFolder(path){const encodedPath=this._encoder.encode(path);const commonPrefix=this._index.longestPrefix(encodedPath,true);return this._encoder.decode(commonPrefix);}};Persistence.AutomappingStatus=class{constructor(network,fileSystem,exactMatch){this.network=network;this.fileSystem=fileSystem;this.exactMatch=exactMatch;}};;Persistence.NetworkPersistenceManager=class extends Common.Object{constructor(workspace){super();this._bindingSymbol=Symbol('NetworkPersistenceBinding');this._originalResponseContentPromiseSymbol=Symbol('OriginalResponsePromise');this._savingSymbol=Symbol('SavingForOverrides');this._enabledSetting=Common.settings.moduleSetting('persistenceNetworkOverridesEnabled');this._enabledSetting.addChangeListener(this._enabledChanged,this);this._workspace=workspace;this._networkUISourceCodeForEncodedPath=new Map();this._interceptionHandlerBound=this._interceptionHandler.bind(this);this._updateInterceptionThrottler=new Common.Throttler(50);this._project=null;this._activeProject=null;this._active=false;this._enabled=false;this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded,event=>this._onProjectAdded((event.data)));this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved,event=>this._onProjectRemoved((event.data)));this._eventDescriptors=[];this._enabledChanged();}
active(){return this._active;}
project(){return this._project;}
originalContentForUISourceCode(uiSourceCode){if(!uiSourceCode[this._bindingSymbol])
return null;const fileSystemUISourceCode=uiSourceCode[this._bindingSymbol].fileSystem;return fileSystemUISourceCode[this._originalResponseContentPromiseSymbol]||null;}
_enabledChanged(){if(this._enabled===this._enabledSetting.get())
return;this._enabled=this._enabledSetting.get();if(this._enabled){this._eventDescriptors=[Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRenamed,event=>{const uiSourceCode=(event.data.uiSourceCode);this._onUISourceCodeRemoved(uiSourceCode);this._onUISourceCodeAdded(uiSourceCode);}),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,event=>this._onUISourceCodeAdded((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,event=>this._onUISourceCodeRemoved((event.data))),Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommitted,event=>this._onUISourceCodeWorkingCopyCommitted((event.data.uiSourceCode)))];this._updateActiveProject();}else{Common.EventTarget.removeEventListeners(this._eventDescriptors);this._updateActiveProject();}}
_updateActiveProject(){const wasActive=this._active;this._active=!!(this._enabledSetting.get()&&SDK.targetManager.mainTarget()&&this._project);if(this._active===wasActive)
return;if(this._active){this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this));const networkProjects=this._workspace.projectsForType(Workspace.projectTypes.Network);for(const networkProject of networkProjects)
networkProject.uiSourceCodes().forEach(this._networkUISourceCodeAdded.bind(this));}else if(this._project){this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this));this._networkUISourceCodeForEncodedPath.clear();}
Persistence.persistence.setAutomappingEnabled(!this._active);}
_encodedPathFromUrl(url){if(!this._active)
return'';let urlPath=Common.ParsedURL.urlWithoutHash(url.replace(/^https?:\/\//,''));if(urlPath.endsWith('/')&&urlPath.indexOf('?')===-1)
urlPath=urlPath+'index.html';let encodedPathParts=encodeUrlPathToLocalPathParts(urlPath);const projectPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id());const encodedPath=encodedPathParts.join('/');if(projectPath.length+encodedPath.length>200){const domain=encodedPathParts[0];const encodedFileName=encodedPathParts[encodedPathParts.length-1];const shortFileName=encodedFileName?encodedFileName.substr(0,10)+'-':'';const extension=Common.ParsedURL.extractExtension(urlPath);const extensionPart=extension?'.'+extension.substr(0,10):'';encodedPathParts=[domain,'longurls',shortFileName+String.hashCode(encodedPath).toString(16)+extensionPart];}
return encodedPathParts.join('/');function encodeUrlPathToLocalPathParts(urlPath){const encodedParts=[];for(const pathPart of fileNamePartsFromUrlPath(urlPath)){if(!pathPart)
continue;let encodedName=encodeURI(pathPart).replace(/[\/:\?\*]/g,match=>'%'+match[0].charCodeAt(0).toString(16));if(Persistence.NetworkPersistenceManager._reservedFileNames.has(encodedName.toLowerCase()))
encodedName=encodedName.split('').map(char=>'%'+char.charCodeAt(0).toString(16)).join('');const lastChar=encodedName.charAt(encodedName.length-1);if(lastChar==='.')
encodedName=encodedName.substr(0,encodedName.length-1)+'%2e';encodedParts.push(encodedName);}
return encodedParts;}
function fileNamePartsFromUrlPath(urlPath){urlPath=Common.ParsedURL.urlWithoutHash(urlPath);const queryIndex=urlPath.indexOf('?');if(queryIndex===-1)
return urlPath.split('/');if(queryIndex===0)
return[urlPath];const endSection=urlPath.substr(queryIndex);const parts=urlPath.substr(0,urlPath.length-endSection.length).split('/');parts[parts.length-1]+=endSection;return parts;}}
_decodeLocalPathToUrlPath(path){try{return unescape(path);}catch(e){console.error(e);}
return path;}
_unbind(uiSourceCode){const binding=uiSourceCode[this._bindingSymbol];if(!binding)
return;delete binding.network[this._bindingSymbol];delete binding.fileSystem[this._bindingSymbol];Persistence.persistence.removeBinding(binding);}
async _bind(networkUISourceCode,fileSystemUISourceCode){if(networkUISourceCode[this._bindingSymbol])
this._unbind(networkUISourceCode);if(fileSystemUISourceCode[this._bindingSymbol])
this._unbind(fileSystemUISourceCode);const binding=new Persistence.PersistenceBinding(networkUISourceCode,fileSystemUISourceCode);networkUISourceCode[this._bindingSymbol]=binding;fileSystemUISourceCode[this._bindingSymbol]=binding;Persistence.persistence.addBinding(binding);const uiSourceCodeOfTruth=networkUISourceCode[this._savingSymbol]?networkUISourceCode:fileSystemUISourceCode;const content=await uiSourceCodeOfTruth.requestContent();Persistence.persistence.syncContent(uiSourceCodeOfTruth,content);}
_onUISourceCodeWorkingCopyCommitted(uiSourceCode){this.saveUISourceCodeForOverrides(uiSourceCode);}
canSaveUISourceCodeForOverrides(uiSourceCode){return this._active&&uiSourceCode.project().type()===Workspace.projectTypes.Network&&!uiSourceCode[this._bindingSymbol]&&!uiSourceCode[this._savingSymbol];}
async saveUISourceCodeForOverrides(uiSourceCode){if(!this.canSaveUISourceCodeForOverrides(uiSourceCode))
return;uiSourceCode[this._savingSymbol]=true;let encodedPath=this._encodedPathFromUrl(uiSourceCode.url());const content=await uiSourceCode.requestContent();const encoded=await uiSourceCode.contentEncoded();const lastIndexOfSlash=encodedPath.lastIndexOf('/');const encodedFileName=encodedPath.substr(lastIndexOfSlash+1);encodedPath=encodedPath.substr(0,lastIndexOfSlash);await this._project.createFile(encodedPath,encodedFileName,content,encoded);this._fileCreatedForTest(encodedPath,encodedFileName);uiSourceCode[this._savingSymbol]=false;}
_fileCreatedForTest(path,fileName){}
_patternForFileSystemUISourceCode(uiSourceCode){const relativePathParts=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode);if(relativePathParts.length<2)
return'';if(relativePathParts[1]==='longurls'&&relativePathParts.length!==2)
return'http?://'+relativePathParts[0]+'/*';return'http?://'+this._decodeLocalPathToUrlPath(relativePathParts.join('/'));}
_onUISourceCodeAdded(uiSourceCode){this._networkUISourceCodeAdded(uiSourceCode);this._filesystemUISourceCodeAdded(uiSourceCode);}
_networkUISourceCodeAdded(uiSourceCode){if(!this._active||uiSourceCode.project().type()!==Workspace.projectTypes.Network)
return;const url=Common.ParsedURL.urlWithoutHash(uiSourceCode.url());this._networkUISourceCodeForEncodedPath.set(this._encodedPathFromUrl(url),uiSourceCode);const fileSystemUISourceCode=this._project.uiSourceCodeForURL(this._project.fileSystemPath()+'/'+this._encodedPathFromUrl(url));if(!fileSystemUISourceCode)
return;this._bind(uiSourceCode,fileSystemUISourceCode);}
_filesystemUISourceCodeAdded(uiSourceCode){if(!this._active||uiSourceCode.project()!==this._project)
return;this._updateInterceptionPatterns();const relativePath=Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode);const networkUISourceCode=this._networkUISourceCodeForEncodedPath.get(relativePath.join('/'));if(networkUISourceCode)
this._bind(networkUISourceCode,uiSourceCode);}
_updateInterceptionPatterns(){this._updateInterceptionThrottler.schedule(innerUpdateInterceptionPatterns.bind(this));function innerUpdateInterceptionPatterns(){if(!this._active)
return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns([],this._interceptionHandlerBound);const patterns=new Set();const indexFileName='index.html';for(const uiSourceCode of this._project.uiSourceCodes()){const pattern=this._patternForFileSystemUISourceCode(uiSourceCode);patterns.add(pattern);if(pattern.endsWith('/'+indexFileName))
patterns.add(pattern.substr(0,pattern.length-indexFileName.length));}
return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns(Array.from(patterns).map(pattern=>({urlPattern:pattern,interceptionStage:Protocol.Network.InterceptionStage.HeadersReceived})),this._interceptionHandlerBound);}}
_onUISourceCodeRemoved(uiSourceCode){this._networkUISourceCodeRemoved(uiSourceCode);this._filesystemUISourceCodeRemoved(uiSourceCode);}
_networkUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project().type()!==Workspace.projectTypes.Network)
return;this._unbind(uiSourceCode);this._networkUISourceCodeForEncodedPath.delete(this._encodedPathFromUrl(uiSourceCode.url()));}
_filesystemUISourceCodeRemoved(uiSourceCode){if(uiSourceCode.project()!==this._project)
return;this._updateInterceptionPatterns();delete uiSourceCode[this._originalResponseContentPromiseSymbol];this._unbind(uiSourceCode);}
_setProject(project){if(project===this._project)
return;if(this._project)
this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this));this._project=project;if(this._project)
this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this));this._updateActiveProject();this.dispatchEventToListeners(Persistence.NetworkPersistenceManager.Events.ProjectChanged,this._project);}
_onProjectAdded(project){if(project.type()!==Workspace.projectTypes.FileSystem||Persistence.FileSystemWorkspaceBinding.fileSystemType(project)!=='overrides')
return;const fileSystemPath=Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id());if(!fileSystemPath)
return;if(this._project)
this._project.remove();this._setProject(project);}
_onProjectRemoved(project){if(project!==this._project)
return;this._setProject(null);}
async _interceptionHandler(interceptedRequest){const method=interceptedRequest.request.method;if(!this._active||(method!=='GET'&&method!=='POST'))
return;const path=this._project.fileSystemPath()+'/'+this._encodedPathFromUrl(interceptedRequest.request.url);const fileSystemUISourceCode=this._project.uiSourceCodeForURL(path);if(!fileSystemUISourceCode)
return;let mimeType='';if(interceptedRequest.responseHeaders){const responseHeaders=SDK.NetworkManager.lowercaseHeaders(interceptedRequest.responseHeaders);mimeType=responseHeaders['content-type'];}
if(!mimeType){const expectedResourceType=Common.resourceTypes[interceptedRequest.resourceType]||Common.resourceTypes.Other;mimeType=fileSystemUISourceCode.mimeType();if(Common.ResourceType.fromMimeType(mimeType)!==expectedResourceType)
mimeType=expectedResourceType.canonicalMimeType();}
const project=(fileSystemUISourceCode.project());fileSystemUISourceCode[this._originalResponseContentPromiseSymbol]=interceptedRequest.responseBody().then(response=>{if(response.error||response.content===null)
return null;return response.encoded?atob(response.content):response.content;});const blob=await project.requestFileBlob(fileSystemUISourceCode);interceptedRequest.continueRequestWithContent(new Blob([blob],{type:mimeType}));}};Persistence.NetworkPersistenceManager._reservedFileNames=new Set(['con','prn','aux','nul','com1','com2','com3','com4','com5','com6','com7','com8','com9','lpt1','lpt2','lpt3','lpt4','lpt5','lpt6','lpt7','lpt8','lpt9']);Persistence.NetworkPersistenceManager.Events={ProjectChanged:Symbol('ProjectChanged')};Persistence.networkPersistenceManager;;Persistence.Persistence=class extends Common.Object{constructor(workspace,breakpointManager){super();this._workspace=workspace;this._breakpointManager=breakpointManager;this._filePathPrefixesToBindingCount=new Map();this._subscribedBindingEventListeners=new Multimap();const linkDecorator=new Persistence.PersistenceUtils.LinkDecorator(this);Components.Linkifier.setLinkDecorator(linkDecorator);this._mapping=null;this.setAutomappingEnabled(true);}
setAutomappingEnabled(enabled){if(enabled===!!this._mapping)
return;if(!enabled){this._mapping.dispose();this._mapping=null;}else{this._mapping=new Persistence.Automapping(this._workspace,this._onStatusAdded.bind(this),this._onStatusRemoved.bind(this));}}
addBinding(binding){this._innerAddBinding(binding);}
addBindingForTest(binding){this._innerAddBinding(binding);}
removeBinding(binding){this._innerRemoveBinding(binding);}
removeBindingForTest(binding){this._innerRemoveBinding(binding);}
_innerAddBinding(binding){binding.network[Persistence.Persistence._binding]=binding;binding.fileSystem[Persistence.Persistence._binding]=binding;binding.fileSystem.forceLoadOnCheckContent();binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._addFilePathBindingPrefixes(binding.fileSystem.url());this._moveBreakpoints(binding.fileSystem,binding.network);console.assert(!binding.fileSystem.isDirty()||!binding.network.isDirty());if(binding.fileSystem.isDirty()){this._syncWorkingCopy(binding.fileSystem);}else if(binding.network.isDirty()){this._syncWorkingCopy(binding.network);}else if(binding.network.hasCommits()){binding.network.setWorkingCopy(binding.network.content());this._syncWorkingCopy(binding.network);}
this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingCreated,binding);}
_innerRemoveBinding(binding){if(binding.network[Persistence.Persistence._binding]!==binding)
return;console.assert(binding.network[Persistence.Persistence._binding]===binding.fileSystem[Persistence.Persistence._binding],'ERROR: inconsistent binding for networkURL '+binding.network.url());binding.network[Persistence.Persistence._binding]=null;binding.fileSystem[Persistence.Persistence._binding]=null;binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyCommitted,this._onWorkingCopyCommitted,this);binding.network.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);binding.fileSystem.removeEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged,this._onWorkingCopyChanged,this);this._removeFilePathBindingPrefixes(binding.fileSystem.url());this._breakpointManager.copyBreakpoints(binding.network.url(),binding.fileSystem);this._notifyBindingEvent(binding.network);this._notifyBindingEvent(binding.fileSystem);this.dispatchEventToListeners(Persistence.Persistence.Events.BindingRemoved,binding);}
_onStatusAdded(status){const binding=new Persistence.PersistenceBinding(status.network,status.fileSystem);status[Persistence.Persistence._binding]=binding;this._innerAddBinding(binding);}
_onStatusRemoved(status){const binding=(status[Persistence.Persistence._binding]);this._innerRemoveBinding(binding);}
_onWorkingCopyChanged(event){const uiSourceCode=(event.data);this._syncWorkingCopy(uiSourceCode);}
_syncWorkingCopy(uiSourceCode){const binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteWorkingCopy])
return;const other=binding.network===uiSourceCode?binding.fileSystem:binding.network;if(!uiSourceCode.isDirty()){binding[Persistence.Persistence._muteWorkingCopy]=true;other.resetWorkingCopy();binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();return;}
const target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.isNodeJS()){const newContent=uiSourceCode.workingCopy();other.requestContent().then(()=>{const nodeJSContent=Persistence.Persistence.rewrapNodeJSContent(other,other.workingCopy(),newContent);setWorkingCopy.call(this,()=>nodeJSContent);});return;}
setWorkingCopy.call(this,()=>uiSourceCode.workingCopy());function setWorkingCopy(workingCopyGetter){binding[Persistence.Persistence._muteWorkingCopy]=true;other.setWorkingCopyGetter(workingCopyGetter);binding[Persistence.Persistence._muteWorkingCopy]=false;this._contentSyncedForTest();}}
_onWorkingCopyCommitted(event){const uiSourceCode=(event.data.uiSourceCode);const newContent=(event.data.content);this.syncContent(uiSourceCode,newContent);}
syncContent(uiSourceCode,newContent){const binding=uiSourceCode[Persistence.Persistence._binding];if(!binding||binding[Persistence.Persistence._muteCommit])
return;const other=binding.network===uiSourceCode?binding.fileSystem:binding.network;const target=Bindings.NetworkProject.targetForUISourceCode(binding.network);if(target.isNodeJS()){other.requestContent().then(currentContent=>{const nodeJSContent=Persistence.Persistence.rewrapNodeJSContent(other,currentContent,newContent);setContent.call(this,nodeJSContent);});return;}
setContent.call(this,newContent);function setContent(newContent){binding[Persistence.Persistence._muteCommit]=true;other.addRevision(newContent);binding[Persistence.Persistence._muteCommit]=false;this._contentSyncedForTest();}}
static rewrapNodeJSContent(uiSourceCode,currentContent,newContent){if(uiSourceCode.project().type()===Workspace.projectTypes.FileSystem){if(newContent.startsWith(Persistence.Persistence._NodePrefix)&&newContent.endsWith(Persistence.Persistence._NodeSuffix)){newContent=newContent.substring(Persistence.Persistence._NodePrefix.length,newContent.length-Persistence.Persistence._NodeSuffix.length);}
if(currentContent.startsWith(Persistence.Persistence._NodeShebang))
newContent=Persistence.Persistence._NodeShebang+newContent;}else{if(newContent.startsWith(Persistence.Persistence._NodeShebang))
newContent=newContent.substring(Persistence.Persistence._NodeShebang.length);if(currentContent.startsWith(Persistence.Persistence._NodePrefix)&&currentContent.endsWith(Persistence.Persistence._NodeSuffix))
newContent=Persistence.Persistence._NodePrefix+newContent+Persistence.Persistence._NodeSuffix;}
return newContent;}
_contentSyncedForTest(){}
_moveBreakpoints(from,to){const breakpoints=this._breakpointManager.breakpointsForUISourceCode(from);for(const breakpoint of breakpoints){breakpoint.remove(false);this._breakpointManager.setBreakpoint(to,breakpoint.lineNumber(),breakpoint.columnNumber(),breakpoint.condition(),breakpoint.enabled());}}
hasUnsavedCommittedChanges(uiSourceCode){if(this._workspace.hasResourceContentTrackingExtensions())
return false;if(uiSourceCode.project().canSetFileContent())
return false;if(uiSourceCode[Persistence.Persistence._binding])
return false;return!!uiSourceCode.hasCommits();}
binding(uiSourceCode){return uiSourceCode[Persistence.Persistence._binding]||null;}
subscribeForBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.set(uiSourceCode,listener);}
unsubscribeFromBindingEvent(uiSourceCode,listener){this._subscribedBindingEventListeners.delete(uiSourceCode,listener);}
_notifyBindingEvent(uiSourceCode){if(!this._subscribedBindingEventListeners.has(uiSourceCode))
return;const listeners=Array.from(this._subscribedBindingEventListeners.get(uiSourceCode));for(const listener of listeners)
listener.call(null);}
fileSystem(uiSourceCode){const binding=this.binding(uiSourceCode);return binding?binding.fileSystem:null;}
_addFilePathBindingPrefixes(filePath){let relative='';for(const token of filePath.split('/')){relative+=token+'/';const count=this._filePathPrefixesToBindingCount.get(relative)||0;this._filePathPrefixesToBindingCount.set(relative,count+1);}}
_removeFilePathBindingPrefixes(filePath){let relative='';for(const token of filePath.split('/')){relative+=token+'/';const count=this._filePathPrefixesToBindingCount.get(relative);if(count===1)
this._filePathPrefixesToBindingCount.delete(relative);else
this._filePathPrefixesToBindingCount.set(relative,count-1);}}
filePathHasBindings(filePath){if(!filePath.endsWith('/'))
filePath+='/';return this._filePathPrefixesToBindingCount.has(filePath);}
dispose(){if(this._mapping){this._mapping.dispose();this._mapping=null;}}};Persistence.Persistence._binding=Symbol('Persistence.Binding');Persistence.Persistence._muteCommit=Symbol('Persistence.MuteCommit');Persistence.Persistence._muteWorkingCopy=Symbol('Persistence.MuteWorkingCopy');Persistence.Persistence._NodePrefix='(function (exports, require, module, __filename, __dirname) { ';Persistence.Persistence._NodeSuffix='\n});';Persistence.Persistence._NodeShebang='#!/usr/bin/env node';Persistence.Persistence.Events={BindingCreated:Symbol('BindingCreated'),BindingRemoved:Symbol('BindingRemoved')};Persistence.PathEncoder=class{constructor(){this._encoder=new Common.CharacterIdMap();}
encode(path){return path.split('/').map(token=>this._encoder.toChar(token)).join('');}
decode(path){return path.split('').map(token=>this._encoder.fromChar(token)).join('/');}};Persistence.PersistenceBinding=class{constructor(network,fileSystem){this.network=network;this.fileSystem=fileSystem;}};Persistence.MappingSystem=function(){};Persistence.MappingSystem.prototype={dispose:function(){}};Persistence.persistence;;Persistence.PersistenceActions={};Persistence.PersistenceActions.ContextMenuProvider=class{appendApplicableItems(event,contextMenu,target){const contentProvider=(target);async function saveAs(){if(contentProvider instanceof Workspace.UISourceCode)
(contentProvider).commitWorkingCopy();const content=await contentProvider.requestContent();const url=contentProvider.contentURL();Workspace.fileManager.save(url,(content),true);Workspace.fileManager.close(url);}
if(contentProvider.contentType().isDocumentOrScriptOrStyleSheet())
contextMenu.saveSection().appendItem(Common.UIString('Save as...'),saveAs);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(contentProvider.contentURL());if(uiSourceCode&&Persistence.networkPersistenceManager.canSaveUISourceCodeForOverrides(uiSourceCode)){contextMenu.saveSection().appendItem(Common.UIString('Save for overrides'),()=>{uiSourceCode.commitWorkingCopy();Persistence.networkPersistenceManager.saveUISourceCodeForOverrides((uiSourceCode));Common.Revealer.reveal(uiSourceCode);});}
const binding=uiSourceCode&&Persistence.persistence.binding(uiSourceCode);const fileURL=binding?binding.fileSystem.contentURL():contentProvider.contentURL();if(fileURL.startsWith('file://')){const path=Common.ParsedURL.urlToPlatformPath(fileURL,Host.isWin());contextMenu.revealSection().appendItem(Common.UIString('Open in containing folder'),()=>InspectorFrontendHost.showItemInFolder(path));}}};;Persistence.PersistenceUtils=class{static tooltipForUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);if(!binding)
return'';if(uiSourceCode===binding.network)
return Common.UIString('Persisted to file system: %s',binding.fileSystem.url().trimMiddle(150));if(binding.network.contentType().isFromSourceMap())
return Common.UIString('Linked to source map: %s',binding.network.url().trimMiddle(150));return Common.UIString('Linked to %s',binding.network.url().trimMiddle(150));}
static iconForUISourceCode(uiSourceCode){const binding=Persistence.persistence.binding(uiSourceCode);if(binding){const icon=UI.Icon.create('mediumicon-file-sync');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(binding.fileSystem);if(Persistence.networkPersistenceManager.project()===binding.fileSystem.project())
icon.style.filter='hue-rotate(160deg)';return icon;}
if(uiSourceCode.project().type()!==Workspace.projectTypes.FileSystem)
return null;const icon=UI.Icon.create('mediumicon-file');icon.title=Persistence.PersistenceUtils.tooltipForUISourceCode(uiSourceCode);return icon;}};Persistence.PersistenceUtils.LinkDecorator=class extends Common.Object{constructor(persistence){super();persistence.addEventListener(Persistence.Persistence.Events.BindingCreated,this._bindingChanged,this);persistence.addEventListener(Persistence.Persistence.Events.BindingRemoved,this._bindingChanged,this);}
_bindingChanged(event){const binding=(event.data);this.dispatchEventToListeners(Components.LinkDecorator.Events.LinkIconChanged,binding.network);}
linkIcon(uiSourceCode){return Persistence.PersistenceUtils.iconForUISourceCode(uiSourceCode);}};;Persistence.EditFileSystemView=class extends UI.VBox{constructor(fileSystemPath){super(true);this.registerRequiredCSS('persistence/editFileSystemView.css');this._fileSystemPath=fileSystemPath;this._eventListeners=[Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded,this._update,this),Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved,this._update,this)];const excludedFoldersHeader=this.contentElement.createChild('div','file-system-header');excludedFoldersHeader.createChild('div','file-system-header-text').textContent=Common.UIString('Excluded folders');excludedFoldersHeader.appendChild(UI.createTextButton(Common.UIString('Add'),this._addExcludedFolderButtonClicked.bind(this),'add-button'));this._excludedFoldersList=new UI.ListWidget(this);this._excludedFoldersList.element.classList.add('file-system-list');this._excludedFoldersList.registerRequiredCSS('persistence/editFileSystemView.css');const excludedFoldersPlaceholder=createElementWithClass('div','file-system-list-empty');excludedFoldersPlaceholder.textContent=Common.UIString('None');this._excludedFoldersList.setEmptyPlaceholder(excludedFoldersPlaceholder);this._excludedFoldersList.show(this.contentElement);this.contentElement.tabIndex=0;this._update();}
dispose(){Common.EventTarget.removeEventListeners(this._eventListeners);}
_update(){if(this._muteUpdate)
return;this._excludedFoldersList.clear();this._excludedFolders=[];for(const folder of Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().values()){this._excludedFolders.push(folder);this._excludedFoldersList.appendItem(folder,true);}}
_addExcludedFolderButtonClicked(){this._excludedFoldersList.addNewItem(0,'');}
renderItem(item,editable){const element=createElementWithClass('div','file-system-list-item');const pathPrefix=(editable?item:Common.UIString('%s (via .devtools)',item));const pathPrefixElement=element.createChild('div','file-system-value');pathPrefixElement.textContent=pathPrefix;pathPrefixElement.title=pathPrefix;return element;}
removeItemRequested(item,index){Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder(this._excludedFolders[index]);}
commitEdit(item,editor,isNew){this._muteUpdate=true;if(!isNew){Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).removeExcludedFolder((item));}
Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).addExcludedFolder(this._normalizePrefix(editor.control('pathPrefix').value));this._muteUpdate=false;this._update();}
beginEdit(item){const editor=this._createExcludedFolderEditor();editor.control('pathPrefix').value=item;return editor;}
_createExcludedFolderEditor(){if(this._excludedFolderEditor)
return this._excludedFolderEditor;const editor=new UI.ListWidget.Editor();this._excludedFolderEditor=editor;const content=editor.contentElement();const titles=content.createChild('div','file-system-edit-row');titles.createChild('div','file-system-value').textContent=Common.UIString('Folder path');const fields=content.createChild('div','file-system-edit-row');fields.createChild('div','file-system-value').appendChild(editor.createInput('pathPrefix','text','/path/to/folder/',pathPrefixValidator.bind(this)));return editor;function pathPrefixValidator(item,index,input){const prefix=this._normalizePrefix(input.value);const configurableCount=Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().size;for(let i=0;i<configurableCount;++i){if(i!==index&&this._excludedFolders[i]===prefix)
return false;}
return!!prefix;}}
_normalizePrefix(prefix){if(!prefix)
return'';return prefix+(prefix[prefix.length-1]==='/'?'':'/');}};;Persistence.WorkspaceSettingsTab=class extends UI.VBox{constructor(){super();this.registerRequiredCSS('persistence/workspaceSettingsTab.css');const header=this.element.createChild('header');header.createChild('h3').createTextChild(Common.UIString('Workspace'));this.containerElement=this.element.createChild('div','settings-container-wrapper').createChild('div','settings-tab settings-content settings-container');Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded,event=>this._fileSystemAdded((event.data)),this);Persistence.isolatedFileSystemManager.addEventListener(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved,event=>this._fileSystemRemoved((event.data)),this);const folderExcludePatternInput=this._createFolderExcludePatternInput();folderExcludePatternInput.classList.add('folder-exclude-pattern');this.containerElement.appendChild(folderExcludePatternInput);const div=this.containerElement.createChild('div','settings-info-message');div.createTextChild(Common.UIString('Mappings are inferred automatically. Please '));div.appendChild(UI.XLink.create('https://bugs.chromium.org/p/chromium/issues/entry?template=Defect%20report%20from%20user&components=Platform%3EDevTools%3EAuthoring&comment=DevTools%20failed%20to%20link%20network%20resource%20to%20filesystem.%0A%0APlatform%3A%20%3CLinux%2FWin%2FMac%3E%0AChrome%20version%3A%20%3Cyour%20chrome%20version%3E%0A%0AWhat%20are%20the%20details%20of%20your%20project%3F%0A-%20Source%20code%20(if%20any)%3A%20http%3A%2F%2Fgithub.com%2Fexample%2Fexample%0A-%20Build%20System%3A%20gulp%2Fgrunt%2Fwebpack%2Frollup%2F...%0A-%20HTTP%20server%3A%20node%20HTTP%2Fnginx%2Fapache...%0A%0AAssets%20failed%20to%20link%20(or%20incorrectly%20linked)%3A%0A1.%0A2.%0A3.%0A%0AIf%20possible%2C%20please%20attach%20a%20screenshot%20of%20network%20sources%20navigator%20which%20should%0Ashow%20which%20resources%20failed%20to%20map',Common.UIString('report')));div.createTextChild(Common.UIString(' any bugs.'));this._fileSystemsListContainer=this.containerElement.createChild('div','');this.containerElement.appendChild(UI.createTextButton(Common.UIString('Add folder\u2026'),this._addFileSystemClicked.bind(this)));this._elementByPath=new Map();this._mappingViewByPath=new Map();const fileSystems=Persistence.isolatedFileSystemManager.fileSystems();for(let i=0;i<fileSystems.length;++i)
this._addItem(fileSystems[i]);}
_createFolderExcludePatternInput(){const p=createElement('p');const labelElement=p.createChild('label');labelElement.textContent=Common.UIString('Folder exclude pattern');const inputElement=UI.createInput('','text');p.appendChild(inputElement);inputElement.style.width='270px';const folderExcludeSetting=Persistence.isolatedFileSystemManager.workspaceFolderExcludePatternSetting();const setValue=UI.bindInput(inputElement,folderExcludeSetting.set.bind(folderExcludeSetting),regexValidator,false);folderExcludeSetting.addChangeListener(()=>setValue.call(null,folderExcludeSetting.get()));setValue(folderExcludeSetting.get());return p;function regexValidator(value){let regex;try{regex=new RegExp(value);}catch(e){}
return!!regex;}}
_addItem(fileSystem){const networkPersistenceProject=Persistence.networkPersistenceManager.project();if(networkPersistenceProject&&Persistence.isolatedFileSystemManager.fileSystem(networkPersistenceProject.fileSystemPath())===fileSystem)
return;const element=this._renderFileSystem(fileSystem);this._elementByPath.set(fileSystem.path(),element);this._fileSystemsListContainer.appendChild(element);const mappingView=new Persistence.EditFileSystemView(fileSystem.path());this._mappingViewByPath.set(fileSystem.path(),mappingView);mappingView.element.classList.add('file-system-mapping-view');mappingView.show(element);}
_renderFileSystem(fileSystem){const fileSystemPath=fileSystem.path();const lastIndexOfSlash=fileSystemPath.lastIndexOf(Host.isWin()?'\\':'/');const folderName=fileSystemPath.substr(lastIndexOfSlash+1);const element=createElementWithClass('div','file-system-container');const header=element.createChild('div','file-system-header');header.createChild('div','file-system-name').textContent=folderName;const path=header.createChild('div','file-system-path');path.textContent=fileSystemPath;path.title=fileSystemPath;const toolbar=new UI.Toolbar('');const button=new UI.ToolbarButton(Common.UIString('Remove'),'largeicon-delete');button.addEventListener(UI.ToolbarButton.Events.Click,this._removeFileSystemClicked.bind(this,fileSystem));toolbar.appendToolbarItem(button);header.appendChild(toolbar.element);return element;}
_removeFileSystemClicked(fileSystem){Persistence.isolatedFileSystemManager.removeFileSystem(fileSystem);}
_addFileSystemClicked(){Persistence.isolatedFileSystemManager.addFileSystem();}
_fileSystemAdded(fileSystem){this._addItem(fileSystem);}
_fileSystemRemoved(fileSystem){const mappingView=this._mappingViewByPath.get(fileSystem.path());if(mappingView){mappingView.dispose();this._mappingViewByPath.delete(fileSystem.path());}
const element=this._elementByPath.get(fileSystem.path());if(element){this._elementByPath.delete(fileSystem.path());element.remove();}}};;self['BrowserSDK']=self['BrowserSDK']||{};BrowserSDK.LogManager=class{constructor(){SDK.targetManager.observeModels(SDK.LogModel,this);}
modelAdded(logModel){const eventListeners=[];eventListeners.push(logModel.addEventListener(SDK.LogModel.Events.EntryAdded,this._logEntryAdded,this));logModel[BrowserSDK.LogManager._eventSymbol]=eventListeners;}
modelRemoved(logModel){Common.EventTarget.removeEventListeners(logModel[BrowserSDK.LogManager._eventSymbol]);}
_logEntryAdded(event){const data=(event.data);const target=data.logModel.target();const consoleMessage=new SDK.ConsoleMessage(target.model(SDK.RuntimeModel),data.entry.source,data.entry.level,data.entry.text,undefined,data.entry.url,data.entry.lineNumber,undefined,[data.entry.text,...(data.entry.args||[])],data.entry.stackTrace,data.entry.timestamp,undefined,undefined,data.entry.workerId);if(data.entry.networkRequestId)
BrowserSDK.networkLog.associateConsoleMessageWithRequest(consoleMessage,data.entry.networkRequestId);SDK.consoleModel.addMessage(consoleMessage);}};BrowserSDK.LogManager._eventSymbol=Symbol('_events');new BrowserSDK.LogManager();;BrowserSDK.NetworkLog=class extends Common.Object{constructor(){super();this._requests=[];this._requestsSet=new Set();this._pageLoadForManager=new Map();this._isRecording=true;SDK.targetManager.observeModels(SDK.NetworkManager,this);}
modelAdded(networkManager){const eventListeners=[];eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted,this._onRequestStarted,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestUpdated,this._onRequestUpdated,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestRedirected,this._onRequestRedirect,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished,this._onRequestUpdated,this));eventListeners.push(networkManager.addEventListener(SDK.NetworkManager.Events.MessageGenerated,this._networkMessageGenerated.bind(this,networkManager)));const resourceTreeModel=networkManager.target().model(SDK.ResourceTreeModel);if(resourceTreeModel){eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.WillReloadPage,this._willReloadPage,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated,this._onMainFrameNavigated,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load,this._onLoad,this));eventListeners.push(resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,this._onDOMContentLoaded.bind(this,resourceTreeModel)));}
networkManager[BrowserSDK.NetworkLog._events]=eventListeners;}
modelRemoved(networkManager){this._removeNetworkManagerListeners(networkManager);}
_removeNetworkManagerListeners(networkManager){Common.EventTarget.removeEventListeners(networkManager[BrowserSDK.NetworkLog._events]);}
setIsRecording(enabled){if(this._isRecording===enabled)
return;this._isRecording=enabled;if(enabled){SDK.targetManager.observeModels(SDK.NetworkManager,this);}else{SDK.targetManager.unobserveModels(SDK.NetworkManager,this);SDK.targetManager.models(SDK.NetworkManager).forEach(this._removeNetworkManagerListeners.bind(this));}}
requestForURL(url){return this._requests.find(request=>request.url()===url)||null;}
requests(){return this._requests;}
requestByManagerAndId(networkManager,requestId){for(let i=this._requests.length-1;i>=0;i--){const request=this._requests[i];if(requestId===request.requestId()&&networkManager===SDK.NetworkManager.forRequest(request))
return request;}
return null;}
_requestByManagerAndURL(networkManager,url){for(const request of this._requests){if(url===request.url()&&networkManager===SDK.NetworkManager.forRequest(request))
return request;}
return null;}
_initializeInitiatorSymbolIfNeeded(request){if(!request[BrowserSDK.NetworkLog._initiatorDataSymbol]){request[BrowserSDK.NetworkLog._initiatorDataSymbol]={info:null,chain:null,request:undefined,};}}
initiatorInfoForRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[BrowserSDK.NetworkLog._initiatorDataSymbol].info)
return request[BrowserSDK.NetworkLog._initiatorDataSymbol].info;let type=SDK.NetworkRequest.InitiatorType.Other;let url='';let lineNumber=-Infinity;let columnNumber=-Infinity;let scriptId=null;let initiatorStack=null;const initiator=request.initiator();const redirectSource=request.redirectSource();if(redirectSource){type=SDK.NetworkRequest.InitiatorType.Redirect;url=redirectSource.url();}else if(initiator){if(initiator.type===Protocol.Network.InitiatorType.Parser){type=SDK.NetworkRequest.InitiatorType.Parser;url=initiator.url?initiator.url:url;lineNumber=initiator.lineNumber?initiator.lineNumber:lineNumber;}else if(initiator.type===Protocol.Network.InitiatorType.Script){for(let stack=initiator.stack;stack;stack=stack.parent){const topFrame=stack.callFrames.length?stack.callFrames[0]:null;if(!topFrame)
continue;type=SDK.NetworkRequest.InitiatorType.Script;url=topFrame.url||Common.UIString('<anonymous>');lineNumber=topFrame.lineNumber;columnNumber=topFrame.columnNumber;scriptId=topFrame.scriptId;break;}
if(!initiator.stack&&initiator.url){type=SDK.NetworkRequest.InitiatorType.Script;url=initiator.url;lineNumber=initiator.lineNumber||0;}
if(initiator.stack&&initiator.stack.callFrames&&initiator.stack.callFrames.length)
initiatorStack=initiator.stack||null;}else if(initiator.type===Protocol.Network.InitiatorType.Preload){type=SDK.NetworkRequest.InitiatorType.Preload;}}
request[BrowserSDK.NetworkLog._initiatorDataSymbol].info={type:type,url:url,lineNumber:lineNumber,columnNumber:columnNumber,scriptId:scriptId,stack:initiatorStack};return request[BrowserSDK.NetworkLog._initiatorDataSymbol].info;}
initiatorGraphForRequest(request){const initiated=new Set();const networkManager=SDK.NetworkManager.forRequest(request);for(const otherRequest of this._requests){const otherRequestManager=SDK.NetworkManager.forRequest(request);if(networkManager===otherRequestManager&&this._initiatorChain(otherRequest).has(request))
initiated.add(otherRequest);}
return{initiators:this._initiatorChain(request),initiated:initiated};}
_initiatorChain(request){this._initializeInitiatorSymbolIfNeeded(request);let initiatorChainCache=(request[BrowserSDK.NetworkLog._initiatorDataSymbol].chain);if(initiatorChainCache)
return initiatorChainCache;initiatorChainCache=new Set();let checkRequest=request;do{if(checkRequest[BrowserSDK.NetworkLog._initiatorDataSymbol].chain){initiatorChainCache.addAll(checkRequest[BrowserSDK.NetworkLog._initiatorDataSymbol].chain);break;}
if(initiatorChainCache.has(checkRequest))
break;initiatorChainCache.add(checkRequest);checkRequest=this._initiatorRequest(checkRequest);}while(checkRequest);request[BrowserSDK.NetworkLog._initiatorDataSymbol].chain=initiatorChainCache;return initiatorChainCache;}
_initiatorRequest(request){this._initializeInitiatorSymbolIfNeeded(request);if(request[BrowserSDK.NetworkLog._initiatorDataSymbol].request!==undefined)
return request[BrowserSDK.NetworkLog._initiatorDataSymbol].request;const url=this.initiatorInfoForRequest(request).url;const networkManager=SDK.NetworkManager.forRequest(request);request[BrowserSDK.NetworkLog._initiatorDataSymbol].request=networkManager?this._requestByManagerAndURL(networkManager,url):null;return request[BrowserSDK.NetworkLog._initiatorDataSymbol].request;}
_willReloadPage(){if(!Common.moduleSetting('network_log.preserve-log').get())
this.reset();}
_onMainFrameNavigated(event){const mainFrame=(event.data);const manager=mainFrame.resourceTreeModel().target().model(SDK.NetworkManager);if(!manager||mainFrame.resourceTreeModel().target().parentTarget())
return;const oldManagerRequests=this._requests.filter(request=>SDK.NetworkManager.forRequest(request)===manager);const oldRequestsSet=this._requestsSet;this._requests=[];this._requestsSet=new Set();this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.Reset);let currentPageLoad=null;const requestsToAdd=[];for(const request of oldManagerRequests){if(request.loaderId!==mainFrame.loaderId)
continue;if(!currentPageLoad){currentPageLoad=new BrowserSDK.PageLoad(request);let redirectSource=request.redirectSource();while(redirectSource){requestsToAdd.push(redirectSource);redirectSource=redirectSource.redirectSource();}}
requestsToAdd.push(request);}
for(const request of requestsToAdd){oldRequestsSet.delete(request);this._requests.push(request);this._requestsSet.add(request);currentPageLoad.bindRequest(request);this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.RequestAdded,request);}
if(Common.moduleSetting('network_log.preserve-log').get()){for(const request of oldRequestsSet){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.RequestAdded,request);}}
if(currentPageLoad)
this._pageLoadForManager.set(manager,currentPageLoad);}
importRequests(requests){this.reset();this._requests=[];this._requestsSet.clear();for(const request of requests){this._requests.push(request);this._requestsSet.add(request);this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.RequestAdded,request);}}
_onRequestStarted(event){const request=(event.data);this._requests.push(request);this._requestsSet.add(request);const manager=SDK.NetworkManager.forRequest(request);const pageLoad=manager?this._pageLoadForManager.get(manager):null;if(pageLoad)
pageLoad.bindRequest(request);this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.RequestAdded,request);}
_onRequestUpdated(event){const request=(event.data);if(!this._requestsSet.has(request))
return;this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.RequestUpdated,request);}
_onRequestRedirect(event){const request=(event.data);delete request[BrowserSDK.NetworkLog._initiatorDataSymbol];}
_onDOMContentLoaded(resourceTreeModel,event){const networkManager=resourceTreeModel.target().model(SDK.NetworkManager);const pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad)
pageLoad.contentLoadTime=(event.data);}
_onLoad(event){const networkManager=event.data.resourceTreeModel.target().model(SDK.NetworkManager);const pageLoad=networkManager?this._pageLoadForManager.get(networkManager):null;if(pageLoad)
pageLoad.loadTime=(event.data.loadTime);}
reset(){this._requests=[];this._requestsSet.clear();const managers=new Set(SDK.targetManager.models(SDK.NetworkManager));for(const manager of this._pageLoadForManager.keys()){if(!managers.has(manager))
this._pageLoadForManager.delete(manager);}
this.dispatchEventToListeners(BrowserSDK.NetworkLog.Events.Reset);}
_networkMessageGenerated(networkManager,event){const message=(event.data);const consoleMessage=new SDK.ConsoleMessage(networkManager.target().model(SDK.RuntimeModel),SDK.ConsoleMessage.MessageSource.Network,message.warning?SDK.ConsoleMessage.MessageLevel.Warning:SDK.ConsoleMessage.MessageLevel.Info,message.message);this.associateConsoleMessageWithRequest(consoleMessage,message.requestId);SDK.consoleModel.addMessage(consoleMessage);}
associateConsoleMessageWithRequest(consoleMessage,requestId){const target=consoleMessage.target();const networkManager=target?target.model(SDK.NetworkManager):null;if(!networkManager)
return;const request=this.requestByManagerAndId(networkManager,requestId);if(!request)
return;consoleMessage[BrowserSDK.NetworkLog._requestSymbol]=request;const initiator=request.initiator();if(initiator){consoleMessage.stackTrace=initiator.stack||undefined;if(initiator.url){consoleMessage.url=initiator.url;consoleMessage.line=initiator.lineNumber||0;}}}
static requestForConsoleMessage(consoleMessage){return consoleMessage[BrowserSDK.NetworkLog._requestSymbol]||null;}};BrowserSDK.PageLoad=class{constructor(mainRequest){this.id=++BrowserSDK.PageLoad._lastIdentifier;this.url=mainRequest.url();this.startTime=mainRequest.startTime;this.loadTime;this.contentLoadTime;this.mainRequest=mainRequest;this._showDataSaverWarningIfNeeded();}
async _showDataSaverWarningIfNeeded(){const manager=SDK.NetworkManager.forRequest(this.mainRequest);if(!manager)
return;if(!this.mainRequest.finished)
await this.mainRequest.once(SDK.NetworkRequest.Events.FinishedLoading);const saveDataHeader=this.mainRequest.requestHeaderValue('Save-Data');if(!BrowserSDK.PageLoad._dataSaverMessageWasShown&&saveDataHeader&&saveDataHeader==='on'){const message=Common.UIString('Consider disabling %s while debugging. For more info see: %s',Common.UIString('Chrome Data Saver'),'https://support.google.com/chrome/?p=datasaver');manager.dispatchEventToListeners(SDK.NetworkManager.Events.MessageGenerated,{message:message,requestId:this.mainRequest.requestId(),warning:true});BrowserSDK.PageLoad._dataSaverMessageWasShown=true;}}
static forRequest(request){return request[BrowserSDK.PageLoad._pageLoadForRequestSymbol]||null;}
bindRequest(request){request[BrowserSDK.PageLoad._pageLoadForRequestSymbol]=this;}};BrowserSDK.PageLoad._lastIdentifier=0;BrowserSDK.PageLoad._pageLoadForRequestSymbol=Symbol('PageLoadForRequest');BrowserSDK.NetworkLog._requestSymbol=Symbol('_request');BrowserSDK.PageLoad._dataSaverMessageWasShown=false;BrowserSDK.NetworkLog.InitiatorGraph;BrowserSDK.NetworkLog.Events={Reset:Symbol('Reset'),RequestAdded:Symbol('RequestAdded'),RequestUpdated:Symbol('RequestUpdated')};BrowserSDK.NetworkLog._InitiatorInfo;BrowserSDK.NetworkLog._initiatorDataSymbol=Symbol('InitiatorData');BrowserSDK.NetworkLog._events=Symbol('BrowserSDK.NetworkLog.events');BrowserSDK.networkLog=new BrowserSDK.NetworkLog();;BrowserSDK.HAREntry=class{constructor(request){this._request=request;}
static _toMilliseconds(time){return time===-1?-1:time*1000;}
static async build(request){const harEntry=new BrowserSDK.HAREntry(request);let ipAddress=harEntry._request.remoteAddress();const portPositionInString=ipAddress.lastIndexOf(':');if(portPositionInString!==-1)
ipAddress=ipAddress.substr(0,portPositionInString);const timings=harEntry._buildTimings();let time=0;for(const t of[timings.blocked,timings.dns,timings.connect,timings.send,timings.wait,timings.receive])
time+=Math.max(t,0);const entry={startedDateTime:BrowserSDK.HARLog.pseudoWallTime(harEntry._request,harEntry._request.issueTime()).toJSON(),time:time,request:await harEntry._buildRequest(),response:harEntry._buildResponse(),cache:{},timings:timings,serverIPAddress:ipAddress.replace(/\[\]/g,'')};if(harEntry._request.cached())
entry._fromCache=harEntry._request.cachedInMemory()?'memory':'disk';if(harEntry._request.connectionId!=='0')
entry.connection=harEntry._request.connectionId;const page=BrowserSDK.PageLoad.forRequest(harEntry._request);if(page)
entry.pageref='page_'+page.id;return entry;}
async _buildRequest(){const headersText=this._request.requestHeadersText();const res={method:this._request.requestMethod,url:this._buildRequestURL(this._request.url()),httpVersion:this._request.requestHttpVersion(),headers:this._request.requestHeaders(),queryString:this._buildParameters(this._request.queryParameters||[]),cookies:this._buildCookies(this._request.requestCookies||[]),headersSize:headersText?headersText.length:-1,bodySize:this.requestBodySize};const postData=await this._buildPostData();if(postData)
res.postData=postData;return res;}
_buildResponse(){const headersText=this._request.responseHeadersText;return{status:this._request.statusCode,statusText:this._request.statusText,httpVersion:this._request.responseHttpVersion(),headers:this._request.responseHeaders,cookies:this._buildCookies(this._request.responseCookies||[]),content:this._buildContent(),redirectURL:this._request.responseHeaderValue('Location')||'',headersSize:headersText?headersText.length:-1,bodySize:this.responseBodySize,_transferSize:this._request.transferSize,_error:this._request.localizedFailDescription};}
_buildContent(){const content={size:this._request.resourceSize,mimeType:this._request.mimeType||'x-unknown',};const compression=this.responseCompression;if(typeof compression==='number')
content.compression=compression;return content;}
_buildTimings(){const timing=this._request.timing;const issueTime=this._request.issueTime();const startTime=this._request.startTime;const result={blocked:-1,dns:-1,ssl:-1,connect:-1,send:0,wait:0,receive:0,_blocked_queueing:-1};const queuedTime=(issueTime<startTime)?startTime-issueTime:-1;result.blocked=queuedTime;result._blocked_queueing=BrowserSDK.HAREntry._toMilliseconds(queuedTime);let highestTime=0;if(timing){const blockedStart=leastNonNegative([timing.dnsStart,timing.connectStart,timing.sendStart]);if(blockedStart!==Infinity)
result.blocked+=blockedStart;if(timing.proxyEnd!==-1)
result._blocked_proxy=timing.proxyEnd-timing.proxyStart;if(result._blocked_proxy&&result._blocked_proxy>result.blocked)
result.blocked=result._blocked_proxy;const dnsStart=timing.dnsEnd>=0?blockedStart:0;const dnsEnd=timing.dnsEnd>=0?timing.dnsEnd:-1;result.dns=dnsEnd-dnsStart;const sslStart=timing.sslEnd>0?timing.sslStart:0;const sslEnd=timing.sslEnd>0?timing.sslEnd:-1;result.ssl=sslEnd-sslStart;const connectStart=timing.connectEnd>=0?leastNonNegative([dnsEnd,blockedStart]):0;const connectEnd=timing.connectEnd>=0?timing.connectEnd:-1;result.connect=connectEnd-connectStart;const sendStart=timing.sendEnd>=0?Math.max(connectEnd,dnsEnd,blockedStart):0;const sendEnd=timing.sendEnd>=0?timing.sendEnd:0;result.send=sendEnd-sendStart;if(result.send<0)
result.send=0;highestTime=Math.max(sendEnd,connectEnd,sslEnd,dnsEnd,blockedStart,0);}else if(this._request.responseReceivedTime===-1){result.blocked=this._request.endTime-issueTime;return result;}
const requestTime=timing?timing.requestTime:startTime;const waitStart=highestTime;const waitEnd=BrowserSDK.HAREntry._toMilliseconds(this._request.responseReceivedTime-requestTime);result.wait=waitEnd-waitStart;const receiveStart=waitEnd;const receiveEnd=BrowserSDK.HAREntry._toMilliseconds(this._request.endTime-issueTime);result.receive=Math.max(receiveEnd-receiveStart,0);return result;function leastNonNegative(values){return values.reduce((best,value)=>(value>=0&&value<best)?value:best,Infinity);}}
async _buildPostData(){const postData=await this._request.requestFormData();if(!postData)
return null;const res={mimeType:this._request.requestContentType(),text:postData};const formParameters=await this._request.formParameters();if(formParameters)
res.params=this._buildParameters(formParameters);return res;}
_buildParameters(parameters){return parameters.slice();}
_buildRequestURL(url){return url.split('#',2)[0];}
_buildCookies(cookies){return cookies.map(this._buildCookie.bind(this));}
_buildCookie(cookie){const c={name:cookie.name(),value:cookie.value(),path:cookie.path(),domain:cookie.domain(),expires:cookie.expiresDate(BrowserSDK.HARLog.pseudoWallTime(this._request,this._request.startTime)),httpOnly:cookie.httpOnly(),secure:cookie.secure()};if(cookie.sameSite())
c.sameSite=cookie.sameSite();return c;}
get requestBodySize(){return!this._request.requestFormData?0:this._request.requestFormData.length;}
get responseBodySize(){if(this._request.cached()||this._request.statusCode===304)
return 0;if(!this._request.responseHeadersText)
return-1;return this._request.transferSize-this._request.responseHeadersText.length;}
get responseCompression(){if(this._request.cached()||this._request.statusCode===304||this._request.statusCode===206)
return;if(!this._request.responseHeadersText)
return;return this._request.resourceSize-this.responseBodySize;}};BrowserSDK.HAREntry.Timing;BrowserSDK.HARLog=class{static pseudoWallTime(request,monotonicTime){return new Date(request.pseudoWallTime(monotonicTime)*1000);}
static async build(requests){const log=new BrowserSDK.HARLog();const entryPromises=[];for(const request of requests)
entryPromises.push(BrowserSDK.HAREntry.build(request));const entries=await Promise.all(entryPromises);return{version:'1.2',creator:log._creator(),pages:log._buildPages(requests),entries:entries};}
_creator(){const webKitVersion=/AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent);return{name:'WebInspector',version:webKitVersion?webKitVersion[1]:'n/a'};}
_buildPages(requests){const seenIdentifiers={};const pages=[];for(let i=0;i<requests.length;++i){const request=requests[i];const page=BrowserSDK.PageLoad.forRequest(request);if(!page||seenIdentifiers[page.id])
continue;seenIdentifiers[page.id]=true;pages.push(this._convertPage(page,request));}
return pages;}
_convertPage(page,request){return{startedDateTime:BrowserSDK.HARLog.pseudoWallTime(request,page.startTime).toJSON(),id:'page_'+page.id,title:page.url,pageTimings:{onContentLoad:this._pageEventTime(page,page.contentLoadTime),onLoad:this._pageEventTime(page,page.loadTime)}};}
_pageEventTime(page,time){const startTime=page.startTime;if(time===-1||startTime===-1)
return-1;return BrowserSDK.HAREntry._toMilliseconds(time-startTime);}};;self['Extensions']=self['Extensions']||{};function defineCommonExtensionSymbols(apiPrivate){if(!apiPrivate.panels)
apiPrivate.panels={};apiPrivate.panels.SearchAction={CancelSearch:'cancelSearch',PerformSearch:'performSearch',NextSearchResult:'nextSearchResult',PreviousSearchResult:'previousSearchResult'};apiPrivate.Events={ButtonClicked:'button-clicked-',PanelObjectSelected:'panel-objectSelected-',NetworkRequestFinished:'network-request-finished',OpenResource:'open-resource',PanelSearch:'panel-search-',RecordingStarted:'trace-recording-started-',RecordingStopped:'trace-recording-stopped-',ResourceAdded:'resource-added',ResourceContentCommitted:'resource-content-committed',ViewShown:'view-shown-',ViewHidden:'view-hidden-'};apiPrivate.Commands={AddRequestHeaders:'addRequestHeaders',AddTraceProvider:'addTraceProvider',ApplyStyleSheet:'applyStyleSheet',CompleteTraceSession:'completeTraceSession',CreatePanel:'createPanel',CreateSidebarPane:'createSidebarPane',CreateToolbarButton:'createToolbarButton',EvaluateOnInspectedPage:'evaluateOnInspectedPage',ForwardKeyboardEvent:'_forwardKeyboardEvent',GetHAR:'getHAR',GetPageResources:'getPageResources',GetRequestContent:'getRequestContent',GetResourceContent:'getResourceContent',InspectedURLChanged:'inspectedURLChanged',OpenResource:'openResource',Reload:'Reload',Subscribe:'subscribe',SetOpenResourceHandler:'setOpenResourceHandler',SetResourceContent:'setResourceContent',SetSidebarContent:'setSidebarContent',SetSidebarHeight:'setSidebarHeight',SetSidebarPage:'setSidebarPage',ShowPanel:'showPanel',Unsubscribe:'unsubscribe',UpdateButton:'updateButton'};}
function injectedExtensionAPI(extensionInfo,inspectedTabId,themeName,testHook,injectedScriptId){const chrome=window.chrome||{};const devtools_descriptor=Object.getOwnPropertyDescriptor(chrome,'devtools');if(devtools_descriptor)
return;const apiPrivate={};defineCommonExtensionSymbols(apiPrivate);const commands=apiPrivate.Commands;const events=apiPrivate.Events;let userAction=false;function EventSinkImpl(type,customDispatch){this._type=type;this._listeners=[];this._customDispatch=customDispatch;}
EventSinkImpl.prototype={addListener:function(callback){if(typeof callback!=='function')
throw'addListener: callback is not a function';if(this._listeners.length===0)
extensionServer.sendRequest({command:commands.Subscribe,type:this._type});this._listeners.push(callback);extensionServer.registerHandler('notify-'+this._type,this._dispatch.bind(this));},removeListener:function(callback){const listeners=this._listeners;for(let i=0;i<listeners.length;++i){if(listeners[i]===callback){listeners.splice(i,1);break;}}
if(this._listeners.length===0)
extensionServer.sendRequest({command:commands.Unsubscribe,type:this._type});},_fire:function(vararg){const listeners=this._listeners.slice();for(let i=0;i<listeners.length;++i)
listeners[i].apply(null,arguments);},_dispatch:function(request){if(this._customDispatch)
this._customDispatch.call(this,request);else
this._fire.apply(this,request.arguments);}};function InspectorExtensionAPI(){this.inspectedWindow=new InspectedWindow();this.panels=new Panels();this.network=new Network();this.timeline=new Timeline();defineDeprecatedProperty(this,'webInspector','resources','network');}
function Network(){function dispatchRequestEvent(message){const request=message.arguments[1];request.__proto__=new Request(message.arguments[0]);this._fire(request);}
this.onRequestFinished=new EventSink(events.NetworkRequestFinished,dispatchRequestEvent);defineDeprecatedProperty(this,'network','onFinished','onRequestFinished');this.onNavigated=new EventSink(events.InspectedURLChanged);}
Network.prototype={getHAR:function(callback){function callbackWrapper(result){const entries=(result&&result.entries)||[];for(let i=0;i<entries.length;++i){entries[i].__proto__=new Request(entries[i]._requestId);delete entries[i]._requestId;}
callback(result);}
extensionServer.sendRequest({command:commands.GetHAR},callback&&callbackWrapper);},addRequestHeaders:function(headers){extensionServer.sendRequest({command:commands.AddRequestHeaders,headers:headers,extensionId:window.location.hostname});}};function RequestImpl(id){this._id=id;}
RequestImpl.prototype={getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);}
extensionServer.sendRequest({command:commands.GetRequestContent,id:this._id},callback&&callbackWrapper);}};function Panels(){const panels={elements:new ElementsPanel(),sources:new SourcesPanel(),};function panelGetter(name){return panels[name];}
for(const panel in panels)
this.__defineGetter__(panel,panelGetter.bind(null,panel));this.applyStyleSheet=function(styleSheet){extensionServer.sendRequest({command:commands.ApplyStyleSheet,styleSheet:styleSheet});};}
Panels.prototype={create:function(title,icon,page,callback){const id='extension-panel-'+extensionServer.nextObjectId();const request={command:commands.CreatePanel,id:id,title:title,icon:icon,page:page};extensionServer.sendRequest(request,callback&&callback.bind(this,new ExtensionPanel(id)));},setOpenResourceHandler:function(callback){const hadHandler=extensionServer.hasHandler(events.OpenResource);function callbackWrapper(message){userAction=true;try{callback.call(null,new Resource(message.resource),message.lineNumber);}finally{userAction=false;}}
if(!callback)
extensionServer.unregisterHandler(events.OpenResource);else
extensionServer.registerHandler(events.OpenResource,callbackWrapper);if(hadHandler===!callback)
extensionServer.sendRequest({command:commands.SetOpenResourceHandler,'handlerPresent':!!callback});},openResource:function(url,lineNumber,callback){extensionServer.sendRequest({command:commands.OpenResource,'url':url,'lineNumber':lineNumber},callback);},get SearchAction(){return apiPrivate.panels.SearchAction;}};function ExtensionViewImpl(id){this._id=id;function dispatchShowEvent(message){const frameIndex=message.arguments[0];if(typeof frameIndex==='number')
this._fire(window.parent.frames[frameIndex]);else
this._fire();}
if(id){this.onShown=new EventSink(events.ViewShown+id,dispatchShowEvent);this.onHidden=new EventSink(events.ViewHidden+id);}}
function PanelWithSidebarImpl(hostPanelName){ExtensionViewImpl.call(this,null);this._hostPanelName=hostPanelName;this.onSelectionChanged=new EventSink(events.PanelObjectSelected+hostPanelName);}
PanelWithSidebarImpl.prototype={createSidebarPane:function(title,callback){const id='extension-sidebar-'+extensionServer.nextObjectId();const request={command:commands.CreateSidebarPane,panel:this._hostPanelName,id:id,title:title};function callbackWrapper(){callback(new ExtensionSidebarPane(id));}
extensionServer.sendRequest(request,callback&&callbackWrapper);},__proto__:ExtensionViewImpl.prototype};function declareInterfaceClass(implConstructor){return function(){const impl={__proto__:implConstructor.prototype};implConstructor.apply(impl,arguments);populateInterfaceClass(this,impl);};}
function defineDeprecatedProperty(object,className,oldName,newName){let warningGiven=false;function getter(){if(!warningGiven){console.warn(className+'.'+oldName+' is deprecated. Use '+className+'.'+newName+' instead');warningGiven=true;}
return object[newName];}
object.__defineGetter__(oldName,getter);}
function extractCallbackArgument(args){const lastArgument=args[args.length-1];return typeof lastArgument==='function'?lastArgument:undefined;}
const Button=declareInterfaceClass(ButtonImpl);const EventSink=declareInterfaceClass(EventSinkImpl);const ExtensionPanel=declareInterfaceClass(ExtensionPanelImpl);const ExtensionSidebarPane=declareInterfaceClass(ExtensionSidebarPaneImpl);const PanelWithSidebar=declareInterfaceClass(PanelWithSidebarImpl);const Request=declareInterfaceClass(RequestImpl);const Resource=declareInterfaceClass(ResourceImpl);const TraceSession=declareInterfaceClass(TraceSessionImpl);function ElementsPanel(){PanelWithSidebar.call(this,'elements');}
ElementsPanel.prototype={__proto__:PanelWithSidebar.prototype};function SourcesPanel(){PanelWithSidebar.call(this,'sources');}
SourcesPanel.prototype={__proto__:PanelWithSidebar.prototype};function ExtensionPanelImpl(id){ExtensionViewImpl.call(this,id);this.onSearch=new EventSink(events.PanelSearch+id);}
ExtensionPanelImpl.prototype={createStatusBarButton:function(iconPath,tooltipText,disabled){const id='button-'+extensionServer.nextObjectId();const request={command:commands.CreateToolbarButton,panel:this._id,id:id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);return new Button(id);},show:function(){if(!userAction)
return;const request={command:commands.ShowPanel,id:this._id};extensionServer.sendRequest(request);},__proto__:ExtensionViewImpl.prototype};function ExtensionSidebarPaneImpl(id){ExtensionViewImpl.call(this,id);}
ExtensionSidebarPaneImpl.prototype={setHeight:function(height){extensionServer.sendRequest({command:commands.SetSidebarHeight,id:this._id,height:height});},setExpression:function(expression,rootTitle,evaluateOptions){const request={command:commands.SetSidebarContent,id:this._id,expression:expression,rootTitle:rootTitle,evaluateOnPage:true,};if(typeof evaluateOptions==='object')
request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,extractCallbackArgument(arguments));},setObject:function(jsonObject,rootTitle,callback){extensionServer.sendRequest({command:commands.SetSidebarContent,id:this._id,expression:jsonObject,rootTitle:rootTitle},callback);},setPage:function(page){extensionServer.sendRequest({command:commands.SetSidebarPage,id:this._id,page:page});},__proto__:ExtensionViewImpl.prototype};function ButtonImpl(id){this._id=id;this.onClicked=new EventSink(events.ButtonClicked+id);}
ButtonImpl.prototype={update:function(iconPath,tooltipText,disabled){const request={command:commands.UpdateButton,id:this._id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);}};function Timeline(){}
Timeline.prototype={addTraceProvider:function(categoryName,categoryTooltip){const id='extension-trace-provider-'+extensionServer.nextObjectId();extensionServer.sendRequest({command:commands.AddTraceProvider,id:id,categoryName:categoryName,categoryTooltip:categoryTooltip});return new TraceProvider(id);}};function TraceSessionImpl(id){this._id=id;}
TraceSessionImpl.prototype={complete:function(url,timeOffset){const request={command:commands.CompleteTraceSession,id:this._id,url:url||'',timeOffset:timeOffset||0};extensionServer.sendRequest(request);}};function TraceProvider(id){function dispatchRecordingStarted(message){const sessionId=message.arguments[0];this._fire(new TraceSession(sessionId));}
this.onRecordingStarted=new EventSink(events.RecordingStarted+id,dispatchRecordingStarted);this.onRecordingStopped=new EventSink(events.RecordingStopped+id);}
function InspectedWindow(){function dispatchResourceEvent(message){this._fire(new Resource(message.arguments[0]));}
function dispatchResourceContentEvent(message){this._fire(new Resource(message.arguments[0]),message.arguments[1]);}
this.onResourceAdded=new EventSink(events.ResourceAdded,dispatchResourceEvent);this.onResourceContentCommitted=new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent);}
InspectedWindow.prototype={reload:function(optionsOrUserAgent){let options=null;if(typeof optionsOrUserAgent==='object'){options=optionsOrUserAgent;}else if(typeof optionsOrUserAgent==='string'){options={userAgent:optionsOrUserAgent};console.warn('Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. '+'Use inspectedWindow.reload({ userAgent: value}) instead.');}
extensionServer.sendRequest({command:commands.Reload,options:options});},eval:function(expression,evaluateOptions){const callback=extractCallbackArgument(arguments);function callbackWrapper(result){if(result.isError||result.isException)
callback(undefined,result);else
callback(result.value);}
const request={command:commands.EvaluateOnInspectedPage,expression:expression};if(typeof evaluateOptions==='object')
request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,callback&&callbackWrapper);return null;},getResources:function(callback){function wrapResource(resourceData){return new Resource(resourceData);}
function callbackWrapper(resources){callback(resources.map(wrapResource));}
extensionServer.sendRequest({command:commands.GetPageResources},callback&&callbackWrapper);}};function ResourceImpl(resourceData){this._url=resourceData.url;this._type=resourceData.type;}
ResourceImpl.prototype={get url(){return this._url;},get type(){return this._type;},getContent:function(callback){function callbackWrapper(response){callback(response.content,response.encoding);}
extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback){extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}};function getTabId(){return inspectedTabId;}
let keyboardEventRequestQueue=[];let forwardTimer=null;function forwardKeyboardEvent(event){if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.key)&&event.key!=='Escape')
return;const requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,keyIdentifier:event.keyIdentifier,key:event.key,code:event.code,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer)
forwardTimer=setTimeout(forwardEventQueue,0);}
function forwardEventQueue(){forwardTimer=null;const request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];}
document.addEventListener('keydown',forwardKeyboardEvent,false);document.addEventListener('keypress',forwardKeyboardEvent,false);function ExtensionServerClient(){this._callbacks={};this._handlers={};this._lastRequestId=0;this._lastObjectId=0;this.registerHandler('callback',this._onCallback.bind(this));const channel=new MessageChannel();this._port=channel.port1;this._port.addEventListener('message',this._onMessage.bind(this),false);this._port.start();window.parent.postMessage('registerExtension','*',[channel.port2]);}
ExtensionServerClient.prototype={sendRequest:function(message,callback){if(typeof callback==='function')
message.requestId=this._registerCallback(callback);this._port.postMessage(message);},hasHandler:function(command){return!!this._handlers[command];},registerHandler:function(command,handler){this._handlers[command]=handler;},unregisterHandler:function(command){delete this._handlers[command];},nextObjectId:function(){return injectedScriptId.toString()+'_'+ ++this._lastObjectId;},_registerCallback:function(callback){const id=++this._lastRequestId;this._callbacks[id]=callback;return id;},_onCallback:function(request){if(request.requestId in this._callbacks){const callback=this._callbacks[request.requestId];delete this._callbacks[request.requestId];callback(request.result);}},_onMessage:function(event){const request=event.data;const handler=this._handlers[request.command];if(handler)
handler.call(this,request);}};function populateInterfaceClass(interfaze,implementation){for(const member in implementation){if(member.charAt(0)==='_')
continue;let descriptor=null;for(let owner=implementation;owner&&!descriptor;owner=owner.__proto__)
descriptor=Object.getOwnPropertyDescriptor(owner,member);if(!descriptor)
continue;if(typeof descriptor.value==='function')
interfaze[member]=descriptor.value.bind(implementation);else if(typeof descriptor.get==='function')
interfaze.__defineGetter__(member,descriptor.get.bind(implementation));else
Object.defineProperty(interfaze,member,descriptor);}}
const extensionServer=new ExtensionServerClient();const coreAPI=new InspectorExtensionAPI();Object.defineProperty(chrome,'devtools',{value:{},enumerable:true});chrome.devtools.inspectedWindow={};chrome.devtools.inspectedWindow.__defineGetter__('tabId',getTabId);chrome.devtools.inspectedWindow.__proto__=coreAPI.inspectedWindow;chrome.devtools.network=coreAPI.network;chrome.devtools.panels=coreAPI.panels;chrome.devtools.panels.themeName=themeName;if(extensionInfo.exposeExperimentalAPIs!==false){chrome.experimental=chrome.experimental||{};chrome.experimental.devtools=chrome.experimental.devtools||{};const properties=Object.getOwnPropertyNames(coreAPI);for(let i=0;i<properties.length;++i){const descriptor=Object.getOwnPropertyDescriptor(coreAPI,properties[i]);if(descriptor)
Object.defineProperty(chrome.experimental.devtools,properties[i],descriptor);}
chrome.experimental.devtools.inspectedWindow=chrome.devtools.inspectedWindow;}
if(extensionInfo.exposeWebInspectorNamespace)
window.webInspector=coreAPI;testHook(extensionServer,coreAPI);}
function buildExtensionAPIInjectedScript(extensionInfo,inspectedTabId,themeName,testHook){const argumentsJSON=[extensionInfo,inspectedTabId||null,themeName].map(_=>JSON.stringify(_)).join(',');if(!testHook)
testHook=()=>{};return'(function(injectedScriptId){ '+defineCommonExtensionSymbols.toString()+';'+'('+injectedExtensionAPI.toString()+')('+argumentsJSON+','+testHook+', injectedScriptId);'+'})';};if(!window.InspectorExtensionRegistry){Extensions.InspectorExtensionRegistryStub=class{getExtensionsAsync(){}};self.InspectorExtensionRegistry=new Extensions.InspectorExtensionRegistryStub();};Extensions.ExtensionTraceProvider=class{constructor(extensionOrigin,id,categoryName,categoryTooltip){this._extensionOrigin=extensionOrigin;this._id=id;this._categoryName=categoryName;this._categoryTooltip=categoryTooltip;}
start(session){const sessionId=String(++Extensions.ExtensionTraceProvider._lastSessionId);Extensions.extensionServer.startTraceRecording(this._id,sessionId,session);}
stop(){Extensions.extensionServer.stopTraceRecording(this._id);}
shortDisplayName(){return this._categoryName;}
longDisplayName(){return this._categoryTooltip;}
persistentIdentifier(){return`${this._extensionOrigin}/${this._categoryName}`;}};Extensions.ExtensionTraceProvider._lastSessionId=0;Extensions.TracingSession=function(){};Extensions.TracingSession.prototype={complete:function(url,timeOffsetMicroseconds){}};;Extensions.ExtensionServer=class extends Common.Object{constructor(){super();this._clientObjects={};this._handlers={};this._subscribers={};this._subscriptionStartHandlers={};this._subscriptionStopHandlers={};this._extraHeaders={};this._requests={};this._lastRequestId=0;this._registeredExtensions={};this._status=new Extensions.ExtensionStatus();this._sidebarPanes=[];this._traceProviders=[];this._traceSessions=new Map();const commands=Extensions.extensionAPI.Commands;this._registerHandler(commands.AddRequestHeaders,this._onAddRequestHeaders.bind(this));this._registerHandler(commands.AddTraceProvider,this._onAddTraceProvider.bind(this));this._registerHandler(commands.ApplyStyleSheet,this._onApplyStyleSheet.bind(this));this._registerHandler(commands.CompleteTraceSession,this._onCompleteTraceSession.bind(this));this._registerHandler(commands.CreatePanel,this._onCreatePanel.bind(this));this._registerHandler(commands.CreateSidebarPane,this._onCreateSidebarPane.bind(this));this._registerHandler(commands.CreateToolbarButton,this._onCreateToolbarButton.bind(this));this._registerHandler(commands.EvaluateOnInspectedPage,this._onEvaluateOnInspectedPage.bind(this));this._registerHandler(commands.ForwardKeyboardEvent,this._onForwardKeyboardEvent.bind(this));this._registerHandler(commands.GetHAR,this._onGetHAR.bind(this));this._registerHandler(commands.GetPageResources,this._onGetPageResources.bind(this));this._registerHandler(commands.GetRequestContent,this._onGetRequestContent.bind(this));this._registerHandler(commands.GetResourceContent,this._onGetResourceContent.bind(this));this._registerHandler(commands.Reload,this._onReload.bind(this));this._registerHandler(commands.SetOpenResourceHandler,this._onSetOpenResourceHandler.bind(this));this._registerHandler(commands.SetResourceContent,this._onSetResourceContent.bind(this));this._registerHandler(commands.SetSidebarHeight,this._onSetSidebarHeight.bind(this));this._registerHandler(commands.SetSidebarContent,this._onSetSidebarContent.bind(this));this._registerHandler(commands.SetSidebarPage,this._onSetSidebarPage.bind(this));this._registerHandler(commands.ShowPanel,this._onShowPanel.bind(this));this._registerHandler(commands.Subscribe,this._onSubscribe.bind(this));this._registerHandler(commands.OpenResource,this._onOpenResource.bind(this));this._registerHandler(commands.Unsubscribe,this._onUnsubscribe.bind(this));this._registerHandler(commands.UpdateButton,this._onUpdateButton.bind(this));window.addEventListener('message',this._onWindowMessage.bind(this),false);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AddExtensions,this._addExtensions,this);InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetInspectedTabId,this._setInspectedTabId,this);this._initExtensions();}
initializeExtensions(){this._initializeCommandIssued=true;if(this._pendingExtensionInfos){this._pendingExtensionInfos.forEach(this._addExtension,this);delete this._pendingExtensionInfos;}}
hasExtensions(){return!!Object.keys(this._registeredExtensions).length;}
notifySearchAction(panelId,action,searchString){this._postNotification(Extensions.extensionAPI.Events.PanelSearch+panelId,action,searchString);}
notifyViewShown(identifier,frameIndex){this._postNotification(Extensions.extensionAPI.Events.ViewShown+identifier,frameIndex);}
notifyViewHidden(identifier){this._postNotification(Extensions.extensionAPI.Events.ViewHidden+identifier);}
notifyButtonClicked(identifier){this._postNotification(Extensions.extensionAPI.Events.ButtonClicked+identifier);}
_inspectedURLChanged(event){if(event.data!==SDK.targetManager.mainTarget())
return;this._requests={};const url=event.data.inspectedURL();this._postNotification(Extensions.extensionAPI.Events.InspectedURLChanged,url);}
startTraceRecording(providerId,sessionId,session){this._traceSessions.set(sessionId,session);this._postNotification('trace-recording-started-'+providerId,sessionId);}
stopTraceRecording(providerId){this._postNotification('trace-recording-stopped-'+providerId);}
hasSubscribers(type){return!!this._subscribers[type];}
_postNotification(type,vararg){const subscribers=this._subscribers[type];if(!subscribers)
return;const message={command:'notify-'+type,arguments:Array.prototype.slice.call(arguments,1)};for(let i=0;i<subscribers.length;++i)
subscribers[i].postMessage(message);}
_onSubscribe(message,port){const subscribers=this._subscribers[message.type];if(subscribers){subscribers.push(port);}else{this._subscribers[message.type]=[port];if(this._subscriptionStartHandlers[message.type])
this._subscriptionStartHandlers[message.type]();}}
_onUnsubscribe(message,port){const subscribers=this._subscribers[message.type];if(!subscribers)
return;subscribers.remove(port);if(!subscribers.length){delete this._subscribers[message.type];if(this._subscriptionStopHandlers[message.type])
this._subscriptionStopHandlers[message.type]();}}
_onAddRequestHeaders(message){const id=message.extensionId;if(typeof id!=='string')
return this._status.E_BADARGTYPE('extensionId',typeof id,'string');let extensionHeaders=this._extraHeaders[id];if(!extensionHeaders){extensionHeaders={};this._extraHeaders[id]=extensionHeaders;}
for(const name in message.headers)
extensionHeaders[name]=message.headers[name];const allHeaders=({});for(const extension in this._extraHeaders){const headers=this._extraHeaders[extension];for(const name in headers){if(typeof headers[name]==='string')
allHeaders[name]=headers[name];}}
SDK.multitargetNetworkManager.setExtraHTTPHeaders(allHeaders);}
_onApplyStyleSheet(message){if(!Runtime.experiments.isEnabled('applyCustomStylesheet'))
return;const styleSheet=createElement('style');styleSheet.textContent=message.styleSheet;document.head.appendChild(styleSheet);UI.themeSupport.addCustomStylesheet(message.styleSheet);for(let node=document.body;node;node=node.traverseNextNode(document.body)){if(node instanceof ShadowRoot)
UI.themeSupport.injectCustomStyleSheets(node);}}
_onCreatePanel(message,port){const id=message.id;if(id in this._clientObjects||UI.inspectorView.hasPanel(id))
return this._status.E_EXISTS(id);const page=this._expandResourcePath(port._extensionOrigin,message.page);let persistentId=port._extensionOrigin+message.title;persistentId=persistentId.replace(/\s/g,'');const panelView=new Extensions.ExtensionServerPanelView(persistentId,message.title,new Extensions.ExtensionPanel(this,persistentId,id,page));this._clientObjects[id]=panelView;UI.inspectorView.addPanel(panelView);return this._status.OK();}
_onShowPanel(message){let panelViewId=message.id;const panelView=this._clientObjects[message.id];if(panelView&&panelView instanceof Extensions.ExtensionServerPanelView)
panelViewId=panelView.viewId();UI.inspectorView.showPanel(panelViewId);}
_onCreateToolbarButton(message,port){const panelView=this._clientObjects[message.panel];if(!panelView||!(panelView instanceof Extensions.ExtensionServerPanelView))
return this._status.E_NOTFOUND(message.panel);const button=new Extensions.ExtensionButton(this,message.id,this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);this._clientObjects[message.id]=button;panelView.widget().then(appendButton);function appendButton(panel){(panel).addToolbarItem(button.toolbarButton());}
return this._status.OK();}
_onUpdateButton(message,port){const button=this._clientObjects[message.id];if(!button||!(button instanceof Extensions.ExtensionButton))
return this._status.E_NOTFOUND(message.id);button.update(this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);return this._status.OK();}
_onCompleteTraceSession(message){const session=this._traceSessions.get(message.id);if(!session)
return this._status.E_NOTFOUND(message.id);this._traceSessions.delete(message.id);session.complete(message.url,message.timeOffset);}
_onCreateSidebarPane(message){if(message.panel!=='elements'&&message.panel!=='sources')
return this._status.E_NOTFOUND(message.panel);const id=message.id;const sidebar=new Extensions.ExtensionSidebarPane(this,message.panel,message.title,id);this._sidebarPanes.push(sidebar);this._clientObjects[id]=sidebar;this.dispatchEventToListeners(Extensions.ExtensionServer.Events.SidebarPaneAdded,sidebar);return this._status.OK();}
sidebarPanes(){return this._sidebarPanes;}
_onSetSidebarHeight(message){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);sidebar.setHeight(message.height);return this._status.OK();}
_onSetSidebarContent(message,port){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);function callback(error){const result=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,result);}
if(message.evaluateOnPage){return sidebar.setExpression(message.expression,message.rootTitle,message.evaluateOptions,port._extensionOrigin,callback.bind(this));}
sidebar.setObject(message.expression,message.rootTitle,callback.bind(this));}
_onSetSidebarPage(message,port){const sidebar=this._clientObjects[message.id];if(!sidebar)
return this._status.E_NOTFOUND(message.id);sidebar.setPage(this._expandResourcePath(port._extensionOrigin,message.page));}
_onOpenResource(message){const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(message.url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(message.lineNumber,0));return this._status.OK();}
const resource=Bindings.resourceForURL(message.url);if(resource){Common.Revealer.reveal(resource);return this._status.OK();}
const request=BrowserSDK.networkLog.requestForURL(message.url);if(request){Common.Revealer.reveal(request);return this._status.OK();}
return this._status.E_NOTFOUND(message.url);}
_onSetOpenResourceHandler(message,port){const name=this._registeredExtensions[port._extensionOrigin].name||('Extension '+port._extensionOrigin);if(message.handlerPresent)
Components.Linkifier.registerLinkHandler(name,this._handleOpenURL.bind(this,port));else
Components.Linkifier.unregisterLinkHandler(name);}
_handleOpenURL(port,contentProvider,lineNumber){port.postMessage({command:'open-resource',resource:this._makeResource(contentProvider),lineNumber:lineNumber+1});}
_onReload(message){const options=(message.options||{});SDK.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent==='string'?options.userAgent:'');let injectedScript;if(options.injectedScript)
injectedScript='(function(){'+options.injectedScript+'})()';SDK.ResourceTreeModel.reloadAllPages(!!options.ignoreCache,injectedScript);return this._status.OK();}
_onEvaluateOnInspectedPage(message,port){function callback(error,object,wasThrown){let result;if(error||!object)
result=this._status.E_PROTOCOLERROR(error.toString());else if(wasThrown)
result={isException:true,value:object.description};else
result={value:object.value};this._dispatchCallback(message.requestId,port,result);}
return this.evaluate(message.expression,true,true,message.evaluateOptions,port._extensionOrigin,callback.bind(this));}
async _onGetHAR(){const requests=BrowserSDK.networkLog.requests();const harLog=await BrowserSDK.HARLog.build(requests);for(let i=0;i<harLog.entries.length;++i)
harLog.entries[i]._requestId=this._requestId(requests[i]);return harLog;}
_makeResource(contentProvider){return{url:contentProvider.contentURL(),type:contentProvider.contentType().name()};}
_onGetPageResources(){const resources=new Map();function pushResourceData(contentProvider){if(!resources.has(contentProvider.contentURL()))
resources.set(contentProvider.contentURL(),this._makeResource(contentProvider));}
let uiSourceCodes=Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network);uiSourceCodes=uiSourceCodes.concat(Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts));uiSourceCodes.forEach(pushResourceData.bind(this));for(const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel))
resourceTreeModel.forAllResources(pushResourceData.bind(this));return resources.valuesArray();}
async _getResourceContent(contentProvider,message,port){const content=await contentProvider.requestContent();const encoded=await contentProvider.contentEncoded();this._dispatchCallback(message.requestId,port,{encoding:encoded?'base64':'',content:content});}
_onGetRequestContent(message,port){const request=this._requestById(message.id);if(!request)
return this._status.E_NOTFOUND(message.id);this._getResourceContent(request,message,port);}
_onGetResourceContent(message,port){const url=(message.url);const contentProvider=Workspace.workspace.uiSourceCodeForURL(url)||Bindings.resourceForURL(url);if(!contentProvider)
return this._status.E_NOTFOUND(url);this._getResourceContent(contentProvider,message,port);}
_onSetResourceContent(message,port){function callbackWrapper(error){const response=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,response);}
const url=(message.url);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(!uiSourceCode||!uiSourceCode.contentType().isDocumentOrScriptOrStyleSheet()){const resource=SDK.ResourceTreeModel.resourceForURL(url);if(!resource)
return this._status.E_NOTFOUND(url);return this._status.E_NOTSUPPORTED('Resource is not editable');}
uiSourceCode.setWorkingCopy(message.content);if(message.commit)
uiSourceCode.commitWorkingCopy();callbackWrapper.call(this,null);}
_requestId(request){if(!request._extensionRequestId){request._extensionRequestId=++this._lastRequestId;this._requests[request._extensionRequestId]=request;}
return request._extensionRequestId;}
_requestById(id){return this._requests[id];}
_onAddTraceProvider(message,port){const provider=new Extensions.ExtensionTraceProvider(port._extensionOrigin,message.id,message.categoryName,message.categoryTooltip);this._clientObjects[message.id]=provider;this._traceProviders.push(provider);this.dispatchEventToListeners(Extensions.ExtensionServer.Events.TraceProviderAdded,provider);}
traceProviders(){return this._traceProviders;}
_onForwardKeyboardEvent(message){message.entries.forEach(handleEventEntry);function handleEventEntry(entry){if(!entry.ctrlKey&&!entry.altKey&&!entry.metaKey&&!/^F\d+$/.test(entry.key)&&entry.key!=='Escape')
return;const event=new window.KeyboardEvent(entry.eventType,{key:entry.key,code:entry.code,keyCode:entry.keyCode,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);}
function keyCodeForEntry(entry){let keyCode=entry.keyCode;if(!keyCode){if(entry.key==='Escape')
keyCode=27;}
return keyCode||0;}}
_dispatchCallback(requestId,port,result){if(requestId)
port.postMessage({command:'callback',requestId:requestId,result:result});}
_initExtensions(){this._registerAutosubscriptionHandler(Extensions.extensionAPI.Events.ResourceAdded,Workspace.workspace,Workspace.Workspace.Events.UISourceCodeAdded,this._notifyResourceAdded);this._registerAutosubscriptionTargetManagerHandler(Extensions.extensionAPI.Events.NetworkRequestFinished,SDK.NetworkManager,SDK.NetworkManager.Events.RequestFinished,this._notifyRequestFinished);function onElementsSubscriptionStarted(){UI.context.addFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);}
function onElementsSubscriptionStopped(){UI.context.removeFlavorChangeListener(SDK.DOMNode,this._notifyElementsSelectionChanged,this);}
this._registerSubscriptionHandler(Extensions.extensionAPI.Events.PanelObjectSelected+'elements',onElementsSubscriptionStarted.bind(this),onElementsSubscriptionStopped.bind(this));this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted);SDK.targetManager.addEventListener(SDK.TargetManager.Events.InspectedURLChanged,this._inspectedURLChanged,this);self.InspectorExtensionRegistry.getExtensionsAsync();}
_notifyResourceAdded(event){const uiSourceCode=(event.data);this._postNotification(Extensions.extensionAPI.Events.ResourceAdded,this._makeResource(uiSourceCode));}
_notifyUISourceCodeContentCommitted(event){const uiSourceCode=(event.data.uiSourceCode);const content=(event.data.content);this._postNotification(Extensions.extensionAPI.Events.ResourceContentCommitted,this._makeResource(uiSourceCode),content);}
async _notifyRequestFinished(event){const request=(event.data);const entry=await BrowserSDK.HAREntry.build(request);this._postNotification(Extensions.extensionAPI.Events.NetworkRequestFinished,this._requestId(request),entry);}
_notifyElementsSelectionChanged(){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'elements');}
sourceSelectionChanged(url,range){this._postNotification(Extensions.extensionAPI.Events.PanelObjectSelected+'sources',{startLine:range.startLine,startColumn:range.startColumn,endLine:range.endLine,endColumn:range.endColumn,url:url,});}
_addExtensions(event){if(Extensions.extensionServer._overridePlatformExtensionAPIForTest)
window.buildPlatformExtensionAPI=Extensions.extensionServer._overridePlatformExtensionAPIForTest;const extensionInfos=(event.data);if(this._initializeCommandIssued)
extensionInfos.forEach(this._addExtension,this);else
this._pendingExtensionInfos=extensionInfos;}
_setInspectedTabId(event){this._inspectedTabId=(event.data);}
_addExtension(extensionInfo){const urlOriginRegExp=new RegExp('([^:]+:\/\/[^/]*)\/');const startPage=extensionInfo.startPage;const name=extensionInfo.name;try{const originMatch=urlOriginRegExp.exec(startPage);if(!originMatch){console.error('Skipping extension with invalid URL: '+startPage);return false;}
const extensionOrigin=originMatch[1];if(!this._registeredExtensions[extensionOrigin]){const injectedAPI=buildExtensionAPIInjectedScript(extensionInfo,this._inspectedTabId,UI.themeSupport.themeName(),Extensions.extensionServer['_extensionAPITestHook']);InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin,injectedAPI);this._registeredExtensions[extensionOrigin]={name:name};}
const iframe=createElement('iframe');iframe.src=startPage;iframe.style.display='none';document.body.appendChild(iframe);}catch(e){console.error('Failed to initialize extension '+startPage+':'+e);return false;}
return true;}
_registerExtension(origin,port){if(!this._registeredExtensions.hasOwnProperty(origin)){if(origin!==window.location.origin)
console.error('Ignoring unauthorized client request from '+origin);return;}
port._extensionOrigin=origin;port.addEventListener('message',this._onmessage.bind(this),false);port.start();}
_onWindowMessage(event){if(event.data==='registerExtension')
this._registerExtension(event.origin,event.ports[0]);}
async _onmessage(event){const message=event.data;let result;if(message.command in this._handlers)
result=await this._handlers[message.command](message,event.target);else
result=this._status.E_NOTSUPPORTED(message.command);if(result&&message.requestId)
this._dispatchCallback(message.requestId,event.target,result);}
_registerHandler(command,callback){console.assert(command);this._handlers[command]=callback;}
_registerSubscriptionHandler(eventTopic,onSubscribeFirst,onUnsubscribeLast){this._subscriptionStartHandlers[eventTopic]=onSubscribeFirst;this._subscriptionStopHandlers[eventTopic]=onUnsubscribeLast;}
_registerAutosubscriptionHandler(eventTopic,eventTarget,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,eventTarget.addEventListener.bind(eventTarget,frontendEventType,handler,this),eventTarget.removeEventListener.bind(eventTarget,frontendEventType,handler,this));}
_registerAutosubscriptionTargetManagerHandler(eventTopic,modelClass,frontendEventType,handler){this._registerSubscriptionHandler(eventTopic,SDK.targetManager.addModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this),SDK.targetManager.removeModelListener.bind(SDK.targetManager,modelClass,frontendEventType,handler,this));}
_registerResourceContentCommittedHandler(handler){function addFirstEventListener(){Workspace.workspace.addEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);Workspace.workspace.setHasResourceContentTrackingExtensions(true);}
function removeLastEventListener(){Workspace.workspace.setHasResourceContentTrackingExtensions(false);Workspace.workspace.removeEventListener(Workspace.Workspace.Events.WorkingCopyCommittedByUser,handler,this);}
this._registerSubscriptionHandler(Extensions.extensionAPI.Events.ResourceContentCommitted,addFirstEventListener.bind(this),removeLastEventListener.bind(this));}
_expandResourcePath(extensionPath,resourcePath){if(!resourcePath)
return;return extensionPath+this._normalizePath(resourcePath);}
_normalizePath(path){const source=path.split('/');const result=[];for(let i=0;i<source.length;++i){if(source[i]==='.')
continue;if(source[i]==='')
continue;if(source[i]==='..')
result.pop();else
result.push(source[i]);}
return'/'+result.join('/');}
evaluate(expression,exposeCommandLineAPI,returnByValue,options,securityOrigin,callback){let context;function resolveURLToFrame(url){let found;function hasMatchingURL(frame){found=(frame.url===url)?frame:null;return found;}
SDK.ResourceTreeModel.frames().some(hasMatchingURL);return found;}
options=options||{};let frame;if(options.frameURL){frame=resolveURLToFrame(options.frameURL);}else{const target=SDK.targetManager.mainTarget();const resourceTreeModel=target&&target.model(SDK.ResourceTreeModel);frame=resourceTreeModel&&resourceTreeModel.mainFrame;}
if(!frame){if(options.frameURL)
console.warn('evaluate: there is no frame with URL '+options.frameURL);else
console.warn('evaluate: the main frame is not yet available');return this._status.E_NOTFOUND(options.frameURL||'<top>');}
let contextSecurityOrigin;if(options.useContentScriptContext)
contextSecurityOrigin=securityOrigin;else if(options.scriptExecutionContext)
contextSecurityOrigin=options.scriptExecutionContext;const runtimeModel=frame.resourceTreeModel().target().model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(contextSecurityOrigin){for(let i=0;i<executionContexts.length;++i){const executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.origin===contextSecurityOrigin&&!executionContext.isDefault)
context=executionContext;}
if(!context){console.warn('The JavaScript context '+contextSecurityOrigin+' was not found in the frame '+frame.url);return this._status.E_NOTFOUND(contextSecurityOrigin);}}else{for(let i=0;i<executionContexts.length;++i){const executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.isDefault)
context=executionContext;}
if(!context)
return this._status.E_FAILED(frame.url+' has no execution context');}
context.evaluate({expression:expression,objectGroup:'extension',includeCommandLineAPI:exposeCommandLineAPI,silent:true,returnByValue:returnByValue,generatePreview:false},false,false).then(onEvaluate);function onEvaluate(result){if(result.error){callback(result.error,null,false);return;}
callback(null,result.object||null,!!result.exceptionDetails);}}};Extensions.ExtensionServer.Events={SidebarPaneAdded:Symbol('SidebarPaneAdded'),TraceProviderAdded:Symbol('TraceProviderAdded')};Extensions.ExtensionServerPanelView=class extends UI.SimpleView{constructor(name,title,panel){super(title);this._name=name;this._panel=panel;}
viewId(){return this._name;}
widget(){return(Promise.resolve(this._panel));}};Extensions.ExtensionStatus=class{constructor(){function makeStatus(code,description){const details=Array.prototype.slice.call(arguments,2);const status={code:code,description:description,details:details};if(code!=='OK'){status.isError=true;console.error('Extension server error: '+String.vsprintf(description,details));}
return status;}
this.OK=makeStatus.bind(null,'OK','OK');this.E_EXISTS=makeStatus.bind(null,'E_EXISTS','Object already exists: %s');this.E_BADARG=makeStatus.bind(null,'E_BADARG','Invalid argument %s: %s');this.E_BADARGTYPE=makeStatus.bind(null,'E_BADARGTYPE','Invalid type for argument %s: got %s, expected %s');this.E_NOTFOUND=makeStatus.bind(null,'E_NOTFOUND','Object not found: %s');this.E_NOTSUPPORTED=makeStatus.bind(null,'E_NOTSUPPORTED','Object does not support requested operation: %s');this.E_PROTOCOLERROR=makeStatus.bind(null,'E_PROTOCOLERROR','Inspector protocol error: %s');this.E_FAILED=makeStatus.bind(null,'E_FAILED','Operation failed: %s');}};Extensions.ExtensionStatus.Record;Extensions.extensionAPI={};defineCommonExtensionSymbols(Extensions.extensionAPI);Extensions.extensionServer;;Extensions.ExtensionPanel=class extends UI.Panel{constructor(server,panelName,id,pageURL){super(panelName);this._server=server;this._id=id;this.setHideOnDetach();this._panelToolbar=new UI.Toolbar('hidden',this.element);this._searchableView=new UI.SearchableView(this);this._searchableView.show(this.element);const extensionView=new Extensions.ExtensionView(server,this._id,pageURL,'extension');extensionView.show(this._searchableView.element);}
addToolbarItem(item){this._panelToolbar.element.classList.remove('hidden');this._panelToolbar.appendToolbarItem(item);}
searchCanceled(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.CancelSearch);this._searchableView.updateSearchMatchesCount(0);}
searchableView(){return this._searchableView;}
performSearch(searchConfig,shouldJump,jumpBackwards){const query=searchConfig.query;this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PerformSearch,query);}
jumpToNextSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.NextSearchResult);}
jumpToPreviousSearchResult(){this._server.notifySearchAction(this._id,Extensions.extensionAPI.panels.SearchAction.PreviousSearchResult);}
supportsCaseSensitiveSearch(){return false;}
supportsRegexSearch(){return false;}};Extensions.ExtensionButton=class{constructor(server,id,iconURL,tooltip,disabled){this._id=id;this._toolbarButton=new UI.ToolbarButton('','');this._toolbarButton.addEventListener(UI.ToolbarButton.Events.Click,server.notifyButtonClicked.bind(server,this._id));this.update(iconURL,tooltip,disabled);}
update(iconURL,tooltip,disabled){if(typeof iconURL==='string')
this._toolbarButton.setBackgroundImage(iconURL);if(typeof tooltip==='string')
this._toolbarButton.setTitle(tooltip);if(typeof disabled==='boolean')
this._toolbarButton.setEnabled(!disabled);}
toolbarButton(){return this._toolbarButton;}};Extensions.ExtensionSidebarPane=class extends UI.SimpleView{constructor(server,panelName,title,id){super(title);this.element.classList.add('fill');this._panelName=panelName;this._server=server;this._id=id;}
id(){return this._id;}
panelName(){return this._panelName;}
setObject(object,title,callback){this._createObjectPropertiesView();this._setObject(SDK.RemoteObject.fromLocalObject(object),title,callback);}
setExpression(expression,title,evaluateOptions,securityOrigin,callback){this._createObjectPropertiesView();this._server.evaluate(expression,true,false,evaluateOptions,securityOrigin,this._onEvaluate.bind(this,title,callback));}
setPage(url){if(this._objectPropertiesView){this._objectPropertiesView.detach();delete this._objectPropertiesView;}
if(this._extensionView)
this._extensionView.detach(true);this._extensionView=new Extensions.ExtensionView(this._server,this._id,url,'extension fill');this._extensionView.show(this.element);if(!this.element.style.height)
this.setHeight('150px');}
setHeight(height){this.element.style.height=height;}
_onEvaluate(title,callback,error,result,wasThrown){if(error||!result)
callback(error.toString());else
this._setObject(result,title,callback);}
_createObjectPropertiesView(){if(this._objectPropertiesView)
return;if(this._extensionView){this._extensionView.detach(true);delete this._extensionView;}
this._objectPropertiesView=new Extensions.ExtensionNotifierView(this._server,this._id);this._objectPropertiesView.show(this.element);}
_setObject(object,title,callback){if(!this._objectPropertiesView){callback('operation cancelled');return;}
this._objectPropertiesView.element.removeChildren();Common.Renderer.render(object,{title:title,expanded:true,editable:false,}).then(element=>{this._objectPropertiesView.element.appendChild(element);callback();});}};;Extensions.ExtensionView=class extends UI.Widget{constructor(server,id,src,className){super();this.setHideOnDetach();this.element.className='vbox flex-auto';this._server=server;this._id=id;this._iframe=createElement('iframe');this._iframe.addEventListener('load',this._onLoad.bind(this),false);this._iframe.src=src;this._iframe.className=className;this.setDefaultFocusedElement(this._iframe);this.element.appendChild(this._iframe);}
wasShown(){if(typeof this._frameIndex==='number')
this._server.notifyViewShown(this._id,this._frameIndex);}
willHide(){if(typeof this._frameIndex==='number')
this._server.notifyViewHidden(this._id);}
_onLoad(){const frames=(window.frames);this._frameIndex=Array.prototype.indexOf.call(frames,this._iframe.contentWindow);if(this.isShowing())
this._server.notifyViewShown(this._id,this._frameIndex);}};Extensions.ExtensionNotifierView=class extends UI.VBox{constructor(server,id){super();this._server=server;this._id=id;}
wasShown(){this._server.notifyViewShown(this._id);}
willHide(){this._server.notifyViewHidden(this._id);}};;self['ProductRegistry']=self['ProductRegistry']||{};ProductRegistry.BadgePool=class{constructor(forceShow){this._showTitles=false;this._badgeElements=new Map();if(!forceShow){this._setting=Common.settings.moduleSetting('product_registry.badges-visible');this._setting.addChangeListener(this._settingUpdated.bind(this));if(this._setting.get())
Host.userMetrics.actionTaken(Host.UserMetrics.Action.ShowedThirdPartyBadges);}}
setShowTitles(value){this._showTitles=value;}
badgeForFrame(frame){return this._badgeForFrameOrUrl(this._resolveUrl.bind(this,frame));}
badgeForURL(parsedUrl){return this._badgeForFrameOrUrl(()=>Promise.resolve(parsedUrl));}
reset(){this._badgeElements.clear();}
_badgeForFrameOrUrl(urlResolver){const element=createElementWithClass('span','hidden');const root=UI.createShadowRootWithCoreStyles(element,'product_registry/badge.css');const badgeElement=root.createChild('span');badgeElement.classList.toggle('hide-badge-title',!this._showTitles);badgeElement.addEventListener('mousedown',event=>event.consume());badgeElement.addEventListener('click',event=>{this._showPopup(badgeElement);event.consume();},false);this._badgeElements.set(badgeElement,urlResolver);this._renderBadge(badgeElement);return element;}
async _resolveUrl(frame){const registry=await ProductRegistry.instance();let parsedUrl=new Common.ParsedURL(frame.url);const entry=registry.entryForUrl(parsedUrl);if(!entry){frame.findCreationCallFrame(callFrame=>{if(!callFrame.url)
return false;parsedUrl=new Common.ParsedURL(callFrame.url);return!!registry.entryForUrl(parsedUrl);});}
return parsedUrl;}
async _renderBadge(badgeElement){if(badgeElement.children.length||!this._isVisible(badgeElement)){this._updateBadgeElementVisibility(badgeElement);return;}
const parsedUrl=await this._badgeElements.get(badgeElement)();const registry=await ProductRegistry.instance();const entryName=parsedUrl&&registry.nameForUrl(parsedUrl);if(!entryName)
return;const tokens=entryName.replace(/[a-z]*/g,'').split(' ');let label;if(tokens.length>1)
label=tokens[0][0]+tokens[1][0];else
label=entryName;const iconElement=badgeElement.createChild('span','product-registry-badge monospace');iconElement.setAttribute('data-initial',label.substring(0,2).toUpperCase());iconElement.title=entryName;iconElement.style.backgroundColor=ProductRegistry.BadgePool.colorForEntryName(entryName);badgeElement.createChild('span','product-registry-badge-title').textContent=entryName;this._updateBadgeElementVisibility(badgeElement);}
_settingUpdated(){for(const badgeElement of this._badgeElements.keys())
this._renderBadge(badgeElement);}
_isVisible(badgeElement){return!this._setting||this._setting.get();}
_updateBadgeElementVisibility(badgeElement){badgeElement.parentNodeOrShadowHost().parentNodeOrShadowHost().classList.toggle('hidden',!this._isVisible(badgeElement));}
async _showPopup(badgeElement){if(!this._badgeElements.has(badgeElement))
return;const registry=await ProductRegistry.instance();const parsedUrl=await this._badgeElements.get(badgeElement)();const entryName=registry.nameForUrl(parsedUrl);const element=createElement('div');const root=UI.createShadowRootWithCoreStyles(element,'product_registry/popup.css');const popupElement=root.createChild('div','product-registry-popup');const domainElement=popupElement.createChild('div','product-registry-domain');domainElement.textContent=parsedUrl.domain();const entryNameElement=popupElement.createChild('div','product-registry-name');entryNameElement.textContent=entryName;const reportLink='https://docs.google.com/forms/d/e/1FAIpQLSchz2FdcQ-rRllzl8BbhWaTRRY-12BpPjW6Hr9e1-BpCA083w/viewform'+'?entry_1425918171='+encodeURIComponent((parsedUrl.domain()+parsedUrl.path).substr(0,100));popupElement.appendChild(UI.XLink.create(reportLink,'Report mismatch','product-registry-link'));const dialog=new UI.Dialog();dialog.setContentAnchorBox(badgeElement.boxInWindow());dialog.contentElement.appendChild(element);dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);dialog.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferTop);dialog.addCloseButton();dialog.show((badgeElement.ownerDocument));}
static colorForEntryName(entryName){if(!ProductRegistry.BadgePool._colorGenerator){ProductRegistry.BadgePool._colorGenerator=new Common.Color.Generator({min:30,max:330},{min:50,max:80,count:3},80);}
return ProductRegistry.BadgePool._colorGenerator.colorForID(entryName);}};;ProductRegistry.instance=function(){const extension=self.runtime.extension(ProductRegistry.Registry);if(extension)
return extension.instance();return Promise.resolve(self.singleton(ProductRegistry.RegistryStub));};ProductRegistry.Registry=function(){};ProductRegistry.Registry.prototype={nameForUrl:function(parsedUrl){},entryForUrl:function(parsedUrl){},typeForUrl:function(parsedUrl){}};ProductRegistry.RegistryStub=class{nameForUrl(parsedUrl){return null;}
entryForUrl(parsedUrl){return null;}
typeForUrl(parsedUrl){return null;}};ProductRegistry.Registry.ProductEntry;;self['Main']=self['Main']||{};Main.SimpleApp=class{presentUI(document){const rootView=new UI.RootView();UI.inspectorView.show(rootView.element);rootView.attachToDocument(document);rootView.focus();}};Main.SimpleAppProvider=class{createApp(){return new Main.SimpleApp();}};;Main.ExecutionContextSelector=class{constructor(targetManager,context){targetManager.observeTargets(this,SDK.Target.Capability.JS);context.addFlavorChangeListener(SDK.ExecutionContext,this._executionContextChanged,this);context.addFlavorChangeListener(SDK.Target,this._targetChanged,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextCreated,this._onExecutionContextCreated,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextDestroyed,this._onExecutionContextDestroyed,this);targetManager.addModelListener(SDK.RuntimeModel,SDK.RuntimeModel.Events.ExecutionContextOrderChanged,this._onExecutionContextOrderChanged,this);this._targetManager=targetManager;this._context=context;}
targetAdded(target){setImmediate(deferred.bind(this));function deferred(){if(!this._context.flavor(SDK.Target))
this._context.setFlavor(SDK.Target,target);}}
targetRemoved(target){const currentExecutionContext=this._context.flavor(SDK.ExecutionContext);if(currentExecutionContext&&currentExecutionContext.target()===target)
this._currentExecutionContextGone();const targets=this._targetManager.targets(SDK.Target.Capability.JS);if(this._context.flavor(SDK.Target)===target&&targets.length)
this._context.setFlavor(SDK.Target,targets[0]);}
_executionContextChanged(event){const newContext=(event.data);if(newContext){this._context.setFlavor(SDK.Target,newContext.target());if(!this._ignoreContextChanged)
this._lastSelectedContextId=this._contextPersistentId(newContext);}}
_contextPersistentId(executionContext){return executionContext.isDefault?executionContext.target().name()+':'+executionContext.frameId:'';}
_targetChanged(event){const newTarget=(event.data);const currentContext=this._context.flavor(SDK.ExecutionContext);if(!newTarget||(currentContext&&currentContext.target()===newTarget))
return;const runtimeModel=newTarget.model(SDK.RuntimeModel);const executionContexts=runtimeModel?runtimeModel.executionContexts():[];if(!executionContexts.length)
return;let newContext=null;for(let i=0;i<executionContexts.length&&!newContext;++i){if(this._shouldSwitchToContext(executionContexts[i]))
newContext=executionContexts[i];}
for(let i=0;i<executionContexts.length&&!newContext;++i){if(this._isDefaultContext(executionContexts[i]))
newContext=executionContexts[i];}
this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext||executionContexts[0]);this._ignoreContextChanged=false;}
_shouldSwitchToContext(executionContext){if(this._lastSelectedContextId&&this._lastSelectedContextId===this._contextPersistentId(executionContext))
return true;if(!this._lastSelectedContextId&&this._isDefaultContext(executionContext))
return true;return false;}
_isDefaultContext(executionContext){if(!executionContext.isDefault||!executionContext.frameId)
return false;if(executionContext.target().parentTarget())
return false;const resourceTreeModel=executionContext.target().model(SDK.ResourceTreeModel);const frame=resourceTreeModel&&resourceTreeModel.frameForId(executionContext.frameId);if(frame&&frame.isTopFrame())
return true;return false;}
_onExecutionContextCreated(event){this._switchContextIfNecessary((event.data));}
_onExecutionContextDestroyed(event){const executionContext=(event.data);if(this._context.flavor(SDK.ExecutionContext)===executionContext)
this._currentExecutionContextGone();}
_onExecutionContextOrderChanged(event){const runtimeModel=(event.data);const executionContexts=runtimeModel.executionContexts();for(let i=0;i<executionContexts.length;i++){if(this._switchContextIfNecessary(executionContexts[i]))
break;}}
_switchContextIfNecessary(executionContext){if(!this._context.flavor(SDK.ExecutionContext)||this._shouldSwitchToContext(executionContext)){this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,executionContext);this._ignoreContextChanged=false;return true;}
return false;}
_currentExecutionContextGone(){const runtimeModels=this._targetManager.models(SDK.RuntimeModel);let newContext=null;for(let i=0;i<runtimeModels.length&&!newContext;++i){const executionContexts=runtimeModels[i].executionContexts();for(const executionContext of executionContexts){if(this._isDefaultContext(executionContext)){newContext=executionContext;break;}}}
if(!newContext){for(let i=0;i<runtimeModels.length&&!newContext;++i){const executionContexts=runtimeModels[i].executionContexts();if(executionContexts.length){newContext=executionContexts[0];break;}}}
this._ignoreContextChanged=true;this._context.setFlavor(SDK.ExecutionContext,newContext);this._ignoreContextChanged=false;}};;Main.Main=class{constructor(){Main.Main._instanceForTest=this;runOnWindowLoad(this._loaded.bind(this));}
static time(label){if(Host.isUnderTest())
return;console.time(label);}
static timeEnd(label){if(Host.isUnderTest())
return;console.timeEnd(label);}
async _loaded(){console.timeStamp('Main._loaded');await Runtime.runtimeReady();Runtime.setPlatform(Host.platform());InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this));}
_gotPreferences(prefs){console.timeStamp('Main._gotPreferences');if(Host.isUnderTest(prefs))
self.runtime.useTestBase();this._createSettings(prefs);this._createAppUI();}
_createSettings(prefs){this._initializeExperiments();let storagePrefix='';if(Host.isCustomDevtoolsFrontend())
storagePrefix='__custom__';else if(!Runtime.queryParam('can_dock')&&!!Runtime.queryParam('debugFrontend')&&!Host.isUnderTest())
storagePrefix='__bundled__';let localStorage;if(!Host.isUnderTest()&&window.localStorage){localStorage=new Common.SettingsStorage(window.localStorage,undefined,undefined,()=>window.localStorage.clear(),storagePrefix);}else{localStorage=new Common.SettingsStorage({},undefined,undefined,undefined,storagePrefix);}
const globalStorage=new Common.SettingsStorage(prefs,InspectorFrontendHost.setPreference,InspectorFrontendHost.removePreference,InspectorFrontendHost.clearPreferences,storagePrefix);Common.settings=new Common.Settings(globalStorage,localStorage);if(!Host.isUnderTest())
new Common.VersionController().updateVersion();}
_initializeExperiments(){Runtime.experiments.register('applyCustomStylesheet','Allow custom UI themes');Runtime.experiments.register('blackboxJSFramesOnTimeline','Blackbox JavaScript frames on Timeline',true);Runtime.experiments.register('colorContrastRatio','Color contrast ratio line in color picker',true);Runtime.experiments.register('emptySourceMapAutoStepping','Empty sourcemap auto-stepping');Runtime.experiments.register('inputEventsOnTimelineOverview','Input events on Timeline overview',true);Runtime.experiments.register('nativeHeapProfiler','Native memory sampling heap profiler',true);Runtime.experiments.register('networkSearch','Network search');Runtime.experiments.register('oopifInlineDOM','OOPIF: inline DOM ',true);Runtime.experiments.register('protocolMonitor','Protocol Monitor');Runtime.experiments.register('sourceDiff','Source diff');Runtime.experiments.register('stepIntoAsync','Introduce separate step action, stepInto becomes powerful enough to go inside async call');Runtime.experiments.register('terminalInDrawer','Terminal in drawer',true);Runtime.experiments.register('timelineEventInitiators','Timeline: event initiators');Runtime.experiments.register('timelineFlowEvents','Timeline: flow events',true);Runtime.experiments.register('timelineInvalidationTracking','Timeline: invalidation tracking',true);Runtime.experiments.register('timelinePaintTimingMarkers','Timeline: paint timing markers',true);Runtime.experiments.register('timelineShowAllEvents','Timeline: show all events',true);Runtime.experiments.register('timelineShowAllProcesses','Timeline: show all processes',true);Runtime.experiments.register('timelineTracingJSProfile','Timeline: tracing based JS profiler',true);Runtime.experiments.register('timelineV8RuntimeCallStats','Timeline: V8 Runtime Call Stats on Timeline',true);Runtime.experiments.cleanUpStaleExperiments();if(Host.isUnderTest()){const testPath=Runtime.queryParam('test');if(testPath.indexOf('oopif/')!==-1)
Runtime.experiments.enableForTest('oopifInlineDOM');if(testPath.indexOf('network/')!==-1)
Runtime.experiments.enableForTest('networkSearch');}
Runtime.experiments.setDefaultExperiments(['colorContrastRatio','stepIntoAsync','oopifInlineDOM']);}
async _createAppUI(){Main.Main.time('Main._createAppUI');UI.viewManager=new UI.ViewManager();Persistence.isolatedFileSystemManager=new Persistence.IsolatedFileSystemManager();const themeSetting=Common.settings.createSetting('uiTheme','default');UI.initializeUIUtils(document,themeSetting);themeSetting.addChangeListener(Components.reload.bind(Components));UI.installComponentRootStyles((document.body));this._addMainEventListeners(document);const canDock=!!Runtime.queryParam('can_dock');UI.zoomManager=new UI.ZoomManager(window,InspectorFrontendHost);UI.inspectorView=UI.InspectorView.instance();UI.ContextMenu.initialize();UI.ContextMenu.installHandler(document);UI.Tooltip.installHandler(document);Components.dockController=new Components.DockController(canDock);SDK.consoleModel=new SDK.ConsoleModel();SDK.multitargetNetworkManager=new SDK.MultitargetNetworkManager();SDK.domDebuggerManager=new SDK.DOMDebuggerManager();SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged.bind(this));UI.shortcutsScreen=new UI.ShortcutsScreen();UI.shortcutsScreen.section(Common.UIString('Elements Panel'));UI.shortcutsScreen.section(Common.UIString('Styles Pane'));UI.shortcutsScreen.section(Common.UIString('Debugger'));UI.shortcutsScreen.section(Common.UIString('Console'));Workspace.fileManager=new Workspace.FileManager();Workspace.workspace=new Workspace.Workspace();Bindings.networkProjectManager=new Bindings.NetworkProjectManager();Bindings.resourceMapping=new Bindings.ResourceMapping(SDK.targetManager,Workspace.workspace);new Bindings.PresentationConsoleMessageManager();Bindings.cssWorkspaceBinding=new Bindings.CSSWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.debuggerWorkspaceBinding=new Bindings.DebuggerWorkspaceBinding(SDK.targetManager,Workspace.workspace);Bindings.breakpointManager=new Bindings.BreakpointManager(Workspace.workspace,SDK.targetManager,Bindings.debuggerWorkspaceBinding);Extensions.extensionServer=new Extensions.ExtensionServer();new Persistence.FileSystemWorkspaceBinding(Persistence.isolatedFileSystemManager,Workspace.workspace);Persistence.persistence=new Persistence.Persistence(Workspace.workspace,Bindings.breakpointManager);Persistence.networkPersistenceManager=new Persistence.NetworkPersistenceManager(Workspace.workspace);new Main.ExecutionContextSelector(SDK.targetManager,UI.context);Bindings.blackboxManager=new Bindings.BlackboxManager(Bindings.debuggerWorkspaceBinding);new Main.Main.PauseListener();UI.actionRegistry=new UI.ActionRegistry();UI.shortcutRegistry=new UI.ShortcutRegistry(UI.actionRegistry,document);UI.ShortcutsScreen.registerShortcuts();this._registerForwardedShortcuts();this._registerMessageSinkListener();Main.Main.timeEnd('Main._createAppUI');this._showAppUI(await self.runtime.extension(Common.AppProvider).instance());}
_showAppUI(appProvider){Main.Main.time('Main._showAppUI');const app=(appProvider).createApp();Components.dockController.initialize();app.presentUI(document);const toggleSearchNodeAction=UI.actionRegistry.action('elements.toggle-element-search');if(toggleSearchNodeAction){InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EnterInspectElementMode,toggleSearchNodeAction.execute.bind(toggleSearchNodeAction),this);}
InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.RevealSourceLine,this._revealSourceLine,this);UI.inspectorView.createToolbars();InspectorFrontendHost.loadCompleted();const extensions=self.runtime.extensions(Common.QueryParamHandler);for(const extension of extensions){const value=Runtime.queryParam(extension.descriptor()['name']);if(value!==null)
extension.instance().then(handleQueryParam.bind(null,value));}
function handleQueryParam(value,handler){handler.handleQueryParam(value);}
setTimeout(this._initializeTarget.bind(this),0);Main.Main.timeEnd('Main._showAppUI');}
async _initializeTarget(){Main.Main.time('Main._initializeTarget');const instances=await Promise.all(self.runtime.extensions('early-initialization').map(extension=>extension.instance()));for(const instance of instances)
(instance).run();InspectorFrontendHost.readyForTest();setTimeout(this._lateInitialization.bind(this),100);Main.Main.timeEnd('Main._initializeTarget');}
_lateInitialization(){Main.Main.time('Main._lateInitialization');this._registerShortcuts();Extensions.extensionServer.initializeExtensions();if(!Host.isUnderTest()){for(const extension of self.runtime.extensions('late-initialization'))
extension.instance().then(instance=>((instance)).run());}
Main.Main.timeEnd('Main._lateInitialization');}
_registerForwardedShortcuts(){const forwardedActions=['main.toggle-dock','debugger.toggle-breakpoints-active','debugger.toggle-pause','commandMenu.show','console.show'];const actionKeys=UI.shortcutRegistry.keysForActions(forwardedActions).map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey);InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys));}
_registerMessageSinkListener(){Common.console.addEventListener(Common.Console.Events.MessageAdded,messageAdded);function messageAdded(event){const message=(event.data);if(message.show)
Common.console.show();}}
_revealSourceLine(event){const url=(event.data['url']);const lineNumber=(event.data['lineNumber']);const columnNumber=(event.data['columnNumber']);const uiSourceCode=Workspace.workspace.uiSourceCodeForURL(url);if(uiSourceCode){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));return;}
function listener(event){const uiSourceCode=(event.data);if(uiSourceCode.url()===url){Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber,columnNumber));Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);}}
Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,listener);}
_registerShortcuts(){const shortcut=UI.KeyboardShortcut;const section=UI.shortcutsScreen.section(Common.UIString('All Panels'));let keys=[shortcut.makeDescriptor('[',shortcut.Modifiers.CtrlOrMeta),shortcut.makeDescriptor(']',shortcut.Modifiers.CtrlOrMeta)];section.addRelatedKeys(keys,Common.UIString('Go to the panel to the left/right'));const toggleConsoleLabel=Common.UIString('Show console');section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tilde,shortcut.Modifiers.Ctrl),toggleConsoleLabel);section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc),Common.UIString('Toggle drawer'));if(Components.dockController.canDock()){section.addKey(shortcut.makeDescriptor('M',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle device mode'));section.addKey(shortcut.makeDescriptor('D',shortcut.Modifiers.CtrlOrMeta|shortcut.Modifiers.Shift),Common.UIString('Toggle dock side'));}
section.addKey(shortcut.makeDescriptor('f',shortcut.Modifiers.CtrlOrMeta),Common.UIString('Search'));const advancedSearchShortcutModifier=Host.isMac()?UI.KeyboardShortcut.Modifiers.Meta|UI.KeyboardShortcut.Modifiers.Alt:UI.KeyboardShortcut.Modifiers.Ctrl|UI.KeyboardShortcut.Modifiers.Shift;const advancedSearchShortcut=shortcut.makeDescriptor('f',advancedSearchShortcutModifier);section.addKey(advancedSearchShortcut,Common.UIString('Search across all sources'));const inspectElementModeShortcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('elements.toggle-element-search');if(inspectElementModeShortcuts.length)
section.addKey(inspectElementModeShortcuts[0],Common.UIString('Select node to inspect'));const openResourceShortcut=UI.KeyboardShortcut.makeDescriptor('p',UI.KeyboardShortcut.Modifiers.CtrlOrMeta);section.addKey(openResourceShortcut,Common.UIString('Go to source'));if(Host.isMac()){keys=[shortcut.makeDescriptor('g',shortcut.Modifiers.Meta),shortcut.makeDescriptor('g',shortcut.Modifiers.Meta|shortcut.Modifiers.Shift)];section.addRelatedKeys(keys,Common.UIString('Find next/previous'));}}
_postDocumentKeyDown(event){if(event.handled)
return;if(!UI.Dialog.hasInstance()&&UI.inspectorView.currentPanelDeprecated()){UI.inspectorView.currentPanelDeprecated().handleShortcut(event);if(event.handled){event.consume(true);return;}}
UI.shortcutRegistry.handleShortcut(event);}
_redispatchClipboardEvent(event){const eventCopy=new CustomEvent('clipboard-'+event.type,{bubbles:true});eventCopy['original']=event;const document=event.target&&event.target.ownerDocument;const target=document?document.deepActiveElement():null;if(target)
target.dispatchEvent(eventCopy);if(eventCopy.handled)
event.preventDefault();}
_contextMenuEventFired(event){if(event.handled||event.target.classList.contains('popup-glasspane'))
event.preventDefault();}
_addMainEventListeners(document){document.addEventListener('keydown',this._postDocumentKeyDown.bind(this),false);document.addEventListener('beforecopy',this._redispatchClipboardEvent.bind(this),true);document.addEventListener('copy',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('cut',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('paste',this._redispatchClipboardEvent.bind(this),false);document.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),true);}
_onSuspendStateChanged(){const suspended=SDK.targetManager.allTargetsSuspended();UI.inspectorView.onSuspendStateChanged(suspended);}};Main.Main.ZoomActionDelegate=class{handleAction(context,actionId){if(InspectorFrontendHost.isHostedMode())
return false;switch(actionId){case'main.zoom-in':InspectorFrontendHost.zoomIn();return true;case'main.zoom-out':InspectorFrontendHost.zoomOut();return true;case'main.zoom-reset':InspectorFrontendHost.resetZoom();return true;}
return false;}};Main.Main.SearchActionDelegate=class{handleAction(context,actionId){const searchableView=UI.SearchableView.fromElement(document.deepActiveElement())||UI.inspectorView.currentPanelDeprecated().searchableView();if(!searchableView)
return false;switch(actionId){case'main.search-in-panel.find':return searchableView.handleFindShortcut();case'main.search-in-panel.cancel':return searchableView.handleCancelSearchShortcut();case'main.search-in-panel.find-next':return searchableView.handleFindNextShortcut();case'main.search-in-panel.find-previous':return searchableView.handleFindPreviousShortcut();}
return false;}};Main.Main.MainMenuItem=class{constructor(){this._item=new UI.ToolbarMenuButton(this._handleContextMenu.bind(this),true);this._item.setTitle(Common.UIString('Customize and control DevTools'));}
item(){return this._item;}
_handleContextMenu(contextMenu){if(Components.dockController.canDock()){const dockItemElement=createElementWithClass('div','flex-centered flex-auto');const titleElement=dockItemElement.createChild('span','flex-auto');titleElement.textContent=Common.UIString('Dock side');const toggleDockSideShorcuts=UI.shortcutRegistry.shortcutDescriptorsForAction('main.toggle-dock');titleElement.title=Common.UIString('Placement of DevTools relative to the page. (%s to restore last position)',toggleDockSideShorcuts[0].name);dockItemElement.appendChild(titleElement);const dockItemToolbar=new UI.Toolbar('',dockItemElement);dockItemToolbar.makeBlueOnHover();const undock=new UI.ToolbarToggle(Common.UIString('Undock into separate window'),'largeicon-undock');const bottom=new UI.ToolbarToggle(Common.UIString('Dock to bottom'),'largeicon-dock-to-bottom');const right=new UI.ToolbarToggle(Common.UIString('Dock to right'),'largeicon-dock-to-right');const left=new UI.ToolbarToggle(Common.UIString('Dock to left'),'largeicon-dock-to-left');undock.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());bottom.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());right.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());left.addEventListener(UI.ToolbarButton.Events.MouseDown,event=>event.data.consume());undock.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.Undocked));bottom.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToBottom));right.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToRight));left.addEventListener(UI.ToolbarButton.Events.MouseUp,setDockSide.bind(null,Components.DockController.State.DockedToLeft));undock.setToggled(Components.dockController.dockSide()===Components.DockController.State.Undocked);bottom.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToBottom);right.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToRight);left.setToggled(Components.dockController.dockSide()===Components.DockController.State.DockedToLeft);dockItemToolbar.appendToolbarItem(undock);dockItemToolbar.appendToolbarItem(left);dockItemToolbar.appendToolbarItem(bottom);dockItemToolbar.appendToolbarItem(right);contextMenu.headerSection().appendCustomItem(dockItemElement);}
function setDockSide(side){Components.dockController.setDockSide(side);contextMenu.discard();}
if(Components.dockController.dockSide()===Components.DockController.State.Undocked&&SDK.targetManager.mainTarget()&&SDK.targetManager.mainTarget().hasBrowserCapability())
contextMenu.defaultSection().appendAction('inspector_main.focus-debuggee',Common.UIString('Focus debuggee'));contextMenu.defaultSection().appendAction('main.toggle-drawer',UI.inspectorView.drawerVisible()?Common.UIString('Hide console drawer'):Common.UIString('Show console drawer'));contextMenu.appendItemsAtLocation('mainMenu');const moreTools=contextMenu.defaultSection().appendSubMenuItem(Common.UIString('More tools'));const extensions=self.runtime.extensions('view',undefined,true);for(const extension of extensions){const descriptor=extension.descriptor();if(descriptor['persistence']!=='closeable')
continue;if(descriptor['location']!=='drawer-view'&&descriptor['location']!=='panel')
continue;moreTools.defaultSection().appendItem(extension.title(),UI.viewManager.showView.bind(UI.viewManager,descriptor['id']));}
const helpSubMenu=contextMenu.footerSection().appendSubMenuItem(Common.UIString('Help'));helpSubMenu.appendItemsAtLocation('mainMenuHelp');}};Main.Main.PauseListener=class{constructor(){SDK.targetManager.addModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);}
_debuggerPaused(event){SDK.targetManager.removeModelListener(SDK.DebuggerModel,SDK.DebuggerModel.Events.DebuggerPaused,this._debuggerPaused,this);const debuggerModel=(event.data);const debuggerPausedDetails=debuggerModel.debuggerPausedDetails();UI.context.setFlavor(SDK.Target,debuggerModel.target());Common.Revealer.reveal(debuggerPausedDetails);}};Main.sendOverProtocol=function(method,params){return new Promise((resolve,reject)=>{Protocol.InspectorBackend.sendRawMessageForTesting(method,params,(err,...results)=>{if(err)
return reject(err);return resolve(results);});});};Main.ReloadActionDelegate=class{handleAction(context,actionId){switch(actionId){case'main.debug-reload':Components.reload();return true;}
return false;}};new Main.Main();;self['ConsoleCounters']=self['ConsoleCounters']||{};ConsoleCounters.WarningErrorCounter=class{constructor(){ConsoleCounters.WarningErrorCounter._instanceForTest=this;this._counter=createElement('div');this._counter.addEventListener('click',Common.console.show.bind(Common.console),false);this._toolbarItem=new UI.ToolbarItem(this._counter);const shadowRoot=UI.createShadowRootWithCoreStyles(this._counter,'console_counters/errorWarningCounter.css');this._errors=this._createItem(shadowRoot,'smallicon-error');this._warnings=this._createItem(shadowRoot,'smallicon-warning');this._titles=[];this._errorCount=-1;this._warningCount=-1;this._throttler=new Common.Throttler(100);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.ConsoleCleared,this._update,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded,this._update,this);SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageUpdated,this._update,this);this._update();}
_updatedForTest(){}
_createItem(shadowRoot,iconType){const item=createElementWithClass('span','counter-item');const icon=item.createChild('label','','dt-icon-label');icon.type=iconType;const text=icon.createChild('span');shadowRoot.appendChild(item);return{item:item,text:text};}
_updateItem(item,count,first,title){item.item.classList.toggle('hidden',!count);item.item.classList.toggle('counter-item-first',first);item.text.textContent=count;if(count)
this._titles.push(title);}
_update(){this._updatingForTest=true;this._throttler.schedule(this._updateThrottled.bind(this));}
_updateThrottled(){const errors=SDK.consoleModel.errors();const warnings=SDK.consoleModel.warnings();if(errors===this._errorCount&&warnings===this._warningCount)
return Promise.resolve();this._errorCount=errors;this._warningCount=warnings;this._titles=[];this._toolbarItem.setVisible(!!(errors||warnings));this._updateItem(this._errors,errors,false,Common.UIString(errors===1?'%d error':'%d errors',errors));this._updateItem(this._warnings,warnings,!errors,Common.UIString(warnings===1?'%d warning':'%d warnings',warnings));this._counter.title=this._titles.join(', ');UI.inspectorView.toolbarItemResized();this._updatingForTest=false;this._updatedForTest();return Promise.resolve();}
item(){return this._toolbarItem;}};;;Runtime.cachedResources["ui/checkboxTextLabel.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    padding: 0;\n    margin: 0;\n    display: inline-flex;\n    flex-shrink: 0;\n    align-items: center !important;\n}\n\ninput {\n    height: 12px;\n    width: 12px;\n    flex-shrink: 0;\n}\n\ninput:focus {\n    outline: auto 5px -webkit-focus-ring-color;\n}\n\ninput.dt-checkbox-themed {\n    -webkit-appearance: none;\n    margin: auto 5px auto 2px;\n    border: 1px solid rgb(45, 45, 45);\n    border-radius: 3px;\n    background-color: rgb(102, 102, 102);\n}\n\ninput.dt-checkbox-themed:after {\n    content: '';\n    line-height: 10px;\n    position: absolute;\n    cursor: pointer;\n    width: 12px;\n    height: 12px;\n    background: none;\n}\n\ninput.dt-checkbox-themed:checked:after {\n    background-color: #333;\n}\n\ninput.dt-checkbox-themed:after {\n    -webkit-mask-image: url(Images/checkboxCheckmark.png);\n    -webkit-mask-size: 11px 11px;\n    -webkit-mask-position: 0 0;\n}\n\n:host-context(.-theme-with-dark-background) input:not(.dt-checkbox-themed) {\n    filter: invert(80%);\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\ninput.dt-checkbox-themed:after {\n    -webkit-mask-image: url(Images/checkboxCheckmark_2x.png);\n}\n\n} /* media */\n\n.dt-checkbox-text {\n    margin-left: 3px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.dt-checkbox-subtitle {\n    color: gray;\n}\n\n/*# sourceURL=ui/checkboxTextLabel.css */";Runtime.cachedResources["ui/closeButton.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.close-button {\n    width: 14px;\n    height: 14px;\n    cursor: default;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n}\n\n.hover-icon, .active-icon {\n    display: none;\n}\n\n.close-button:hover .default-icon, .close-button:active .default-icon {\n    display: none;\n}\n\n.close-button:hover .hover-icon {\n    display: block;\n}\n\n.close-button:active .hover-icon {\n    display: none !important;\n}\n\n.close-button:active .active-icon {\n    display: block;\n}\n\n/*# sourceURL=ui/closeButton.css */";Runtime.cachedResources["ui/confirmDialog.css"]="/*\n * Copyright (c) 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n    padding: 20px;\n}\n\n.message, .button {\n    font-size: larger;\n    white-space: pre;\n    margin: 5px;\n}\n\n.button {\n    text-align: center;\n    margin-top: 10px;\n}\n\n.button button {\n    min-width: 80px;\n}\n\n.reason {\n    color: #8b0000;\n}\n\n/*# sourceURL=ui/confirmDialog.css */";Runtime.cachedResources["ui/dialog.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n    box-shadow: var(--drop-shadow);\n    background: white;\n    justify-content: flex-start;\n    align-items: stretch;\n    display: flex;\n}\n\n.dialog-close-button {\n    position: absolute;\n    right: 9px;\n    top: 9px;\n    z-index: 1;\n}\n/*# sourceURL=ui/dialog.css */";Runtime.cachedResources["ui/dropTarget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    display: flex;\n    background-color: rgba(255,255,255,0.8);\n    z-index: 1000;\n}\n\n.drop-target-message {\n    flex: auto;\n    font-size: 30px;\n    color: #999;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    margin: 20px;\n    border: 4px dashed #ddd;\n    pointer-events: none;\n}\n\n/*# sourceURL=ui/dropTarget.css */";Runtime.cachedResources["ui/emptyWidget.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.empty-view {\n    color: hsla(0, 0%, 65%, 1);\n    padding: 30px;\n    display: flex;\n    align-items: center;\n    flex-direction: column;\n    min-width: 70px;\n}\n\n.empty-view-scroller {\n    justify-content: center;\n    overflow: auto;\n}\n\n.empty-view p {\n    white-space: initial;\n    line-height: 18px;\n    max-width: 300px;\n}\n\n/*# sourceURL=ui/emptyWidget.css */";Runtime.cachedResources["ui/filter.css"]="/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.filter-bar {\n    background-color: var(--toolbar-bg-color);\n    flex: none;\n    flex-wrap: wrap;\n    align-items: center;\n    border-bottom: var(--divider-border);\n}\n\n.filter-text-filter {\n    display: inline-flex;\n    margin-left: 1px;\n    margin-right: 2px;\n    min-width: 40px;\n    max-width: 200px;\n    height: 24px;\n    align-items: center;\n}\n\n.filter-text-filter label {\n    margin: auto 0;\n}\n\n.filter-bitset-filter {\n    padding: 2px;\n    display: inline-flex;\n    overflow: hidden;\n    height: 24px;\n    position: relative;\n}\n\n.filter-bitset-filter li {\n    display: inline-block;\n    flex: none;\n    margin: auto 2px;\n    padding: 3px;\n    background: transparent;\n    text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0;\n    border-radius: 6px;\n    overflow: hidden;\n}\n\n.filter-bitset-filter-divider {\n    background-color: #ccc;\n    height: 16px;\n    width: 1px;\n    margin: auto 2px;\n    display: inline-block;\n}\n\n.filter-bitset-filter li.selected,\n.filter-bitset-filter li:hover,\n.filter-bitset-filter li:active {\n    color: white;\n    text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0;\n}\n\n.filter-bitset-filter li:hover {\n    background: rgba(0, 0, 0, 0.2);\n}\n\n.filter-bitset-filter li.selected {\n    background: rgba(0, 0, 0, 0.3);\n}\n\n.filter-bitset-filter li:active {\n    background: rgba(0, 0, 0, 0.5);\n}\n\n.filter-combobox-filter {\n    margin-left: 5px;\n    margin-right: 2px;\n    flex: 0 0 auto;\n    display: inline-block;\n}\n\n.filter-checkbox-filter {\n    padding-left: 4px;\n    padding-right: 2px;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    overflow: hidden;\n    display: inline-flex;\n    vertical-align: middle;\n    height: 24px;\n    position: relative;\n}\n\n.filter-checkbox-filter > label {\n    display: flex;\n    margin: auto 0;\n}\n\n.filter-checkbox-filter .checkbox-filter-checkbox {\n    width: 10px;\n    height: 10px;\n    margin: auto 3px;\n    padding: 0;\n    border-radius: 2px;\n    border: solid 1px;\n    display: inline-block;\n    overflow: visible;\n    opacity: 0.8;\n    flex-shrink: 0;\n}\n\n.filter-input-field {\n    margin: 0 3px;\n    padding-left: 3px;\n    width: 163px;\n    height: 18px;\n    line-height: 20px;\n    display: inline-block;\n    background: #FFF;\n    overflow: hidden;\n    white-space: nowrap;\n    cursor: auto;\n}\n\n.filter-input-field:hover {\n    box-shadow: var(--focus-ring-inactive-shadow);\n}\n\n.filter-input-field:focus {\n    box-shadow: var(--focus-ring-active-shadow);\n}\n\n/*# sourceURL=ui/filter.css */";Runtime.cachedResources["ui/glassPane.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    position: absolute !important;\n    top: 0;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    overflow: hidden;\n    contain: strict;\n    background-color: transparent;\n}\n\n:host-context(.dimmed-pane) {\n    background-color: rgba(255, 255, 255, 0.5);\n}\n\n:host-context(.no-pointer-events) {\n    pointer-events: none;\n}\n\n.widget {\n    display: flex;\n    background-color: transparent;\n    pointer-events: auto;\n    flex: none;\n}\n\n.no-pointer-events {\n    pointer-events: none;\n}\n\n.arrow-top {\n    margin-top: -19px;\n    margin-left: -9px;\n}\n\n.arrow-bottom {\n    margin-left: -9px;\n}\n\n.arrow-left {\n    margin-left: -19px;\n    margin-top: -9px;\n}\n\n.arrow-right {\n    margin-top: -9px;\n}\n\n.arrow-none {\n    display: none;\n}\n\n:host-context(.-theme-with-dark-background) .arrow {\n    -webkit-filter: invert(80%);\n}\n\n/*# sourceURL=ui/glassPane.css */";Runtime.cachedResources["ui/infobar.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.infobar {\n    color: rgb(34, 34, 34);\n    display: flex;\n    flex: auto;\n    border-bottom: 1px solid rgb(171, 171, 171);\n    flex-direction: column;\n    align-items: stretch;\n    position: relative;\n}\n\n.infobar-warning {\n    background-color: rgb(253, 242, 192);\n}\n\n.infobar-info {\n    background-color: rgb(255, 255, 255);\n}\n\n.infobar-main-row {\n    display: flex;\n    flex-direction: row;\n    flex: auto;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    justify-content: space-between;\n    margin-right: 20px;\n    min-height: 25px;\n    align-items: center;\n    padding-left: 4px;\n}\n\n.infobar-main-row > * {\n    flex: none;\n    padding: 0 3px;\n}\n\n.infobar-main-title {\n    flex: auto;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.infobar-details-rows {\n    padding: 5px 5px 0 5px;\n}\n\n.infobar-details-row {\n    display: flex;\n    flex-direction: column;\n    line-height: 18px;\n    padding-bottom: 6px;\n}\n\n.close-button {\n    position: absolute;\n    top: 5px;\n    right: 6px;\n}\n\n.infobar-toggle {\n    color: hsl(214, 92%, 50%);\n    cursor: pointer;\n}\n\n.infobar-toggle:hover {\n    color: hsl(214, 92%, 30%);\n}\n\n.info-icon {\n    -webkit-mask-image: url(Images/ic_info_black_18dp.svg);\n    background-color: hsl(214, 92%, 50%);\n}\n\n.warning-icon {\n    -webkit-mask-image: url(Images/ic_warning_black_18dp.svg);\n    background-color: hsl(44, 92%, 50%);\n}\n\n.icon {\n    -webkit-mask-size: 18px 18px;\n    width: 18px;\n    height: 19px;\n}\n\n/*# sourceURL=ui/infobar.css */";Runtime.cachedResources["ui/inlineButton.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n  display: inline-block;\n  border: 1px solid #ddd;\n  position: relative;\n  top: 7px;\n  margin: 2px;\n  background-color: var(--toolbar-bg-color);\n}\n\n:host > * {\n  position: relative;\n  left: -2px;\n  width: 28px;\n  height: 26px;\n}\n/*# sourceURL=ui/inlineButton.css */";Runtime.cachedResources["ui/inspectorCommon.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n* {\n    /* This is required for correct sizing of flex items because we rely\n     * on an old version of the flexbox spec.\n     * Longer-term we should remove this, see crbug.com/473625 */\n    min-width: 0;\n    min-height: 0;\n}\n\n:host-context(.platform-mac) .monospace,\n:host-context(.platform-mac) .source-code,\n.platform-mac .monospace,\n.platform-mac .source-code {\n    font-size: 11px !important;\n    font-family: Menlo, monospace;\n}\n\n:host-context(.platform-windows) .monospace,\n:host-context(.platform-windows) .source-code,\n.platform-windows .monospace,\n.platform-windows .source-code {\n    font-size: 12px !important;\n    font-family: Consolas, Lucida Console, Courier New, monospace;\n}\n\n:host-context(.platform-linux) .monospace,\n:host-context(.platform-linux) .source-code,\n.platform-linux .monospace,\n.platform-linux .source-code {\n    font-size: 11px !important;\n    font-family: dejavu sans mono, monospace;\n}\n\n.source-code {\n    font-family: monospace;\n    font-size: 11px !important;\n    white-space: pre-wrap;\n}\n\n* {\n    box-sizing: border-box;\n}\n\n:focus {\n    outline-width: 0;\n}\n\nimg {\n    -webkit-user-drag: none;\n}\n\niframe,\na img {\n    border: none;\n}\n\n.fill {\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n}\n\niframe.fill {\n    width: 100%;\n    height: 100%;\n}\n\n.widget {\n    position: relative;\n    flex: auto;\n    contain: layout style;\n}\n\n.hbox {\n    display: flex;\n    flex-direction: row !important;\n    position: relative;\n}\n\n.vbox {\n    display: flex;\n    flex-direction: column !important;\n    position: relative;\n}\n\n.view-container > .toolbar {\n    border-bottom: 1px solid #eee;\n}\n\n.flex-auto {\n    flex: auto;\n}\n\n.flex-auto-important {\n    flex: auto !important;\n}\n\n.flex-none {\n    flex: none;\n}\n\n.flex-centered {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n}\n\n.overflow-auto {\n    overflow: auto;\n}\n\niframe.widget {\n    position: absolute;\n    width: 100%;\n    height: 100%;\n    left: 0;\n    right: 0;\n    top: 0;\n    bottom: 0;\n}\n\n.hidden {\n    display: none !important;\n}\n\n.monospace {\n    font-size: 10px !important;\n    font-family: monospace;\n}\n\n.highlighted-search-result {\n    border-radius: 1px;\n    padding: 1px;\n    margin: -1px;\n    background-color: rgba(255, 255, 0, 0.8);\n}\n\n.-theme-with-dark-background .highlighted-search-result,\n:host-context(.-theme-with-dark-background) .highlighted-search-result {\n    background-color: hsl(133, 100%, 30%);\n    color: #333;\n}\n\n.link {\n    cursor: pointer;\n    text-decoration: underline;\n    color: rgb(17, 85, 204);\n}\n\nbutton,\ninput,\nselect {\n    font-family: inherit;\n    font-size: inherit;\n    color: inherit;\n}\n\ninput {\n    background-color: white;\n}\n\n:host-context(.-theme-with-dark-background) input[type=\"checkbox\"]::not(.-theme-preserve) {\n    -webkit-filter: invert(80%);\n}\n\n.harmony-input:not([type]),\n.harmony-input[type=number],\n.harmony-input[type=text] {\n    padding: 3px 6px;\n    height: 24px;\n    border: none;\n}\n\n.harmony-input:not([type]):not(.error-input):not(:invalid):hover,\n.harmony-input[type=number]:not(.error-input):not(:invalid):hover,\n.harmony-input[type=text]:not(.error-input):not(:invalid):hover {\n    box-shadow: var(--focus-ring-inactive-shadow);\n}\n\n.harmony-input:not([type]):not(.error-input):not(:invalid):focus,\n.harmony-input[type=number]:not(.error-input):not(:invalid):focus,\n.harmony-input[type=text]:not(.error-input):not(:invalid):focus {\n    box-shadow: var(--focus-ring-active-shadow);\n}\n\n.highlighted-search-result.current-search-result {\n    border-radius: 1px;\n    padding: 1px;\n    margin: -1px;\n    background-color: rgba(255, 127, 0, 0.8);\n}\n\n.dimmed {\n    opacity: 0.6;\n}\n\n.editing {\n    box-shadow: var(--drop-shadow);\n    background-color: white;\n    text-overflow: clip !important;\n    padding-left: 2px;\n    margin-left: -2px;\n    padding-right: 2px;\n    margin-right: -2px;\n    margin-bottom: -1px;\n    padding-bottom: 1px;\n    opacity: 1.0 !important;\n}\n\n.editing,\n.editing * {\n    color: #222 !important;\n    text-decoration: none !important;\n}\n\n.harmony-input:not([type]).error-input,\n.harmony-input[type=number].error-input,\n.harmony-input[type=text].error-input,\n.harmony-input:not([type]):invalid,\n.harmony-input[type=number]:invalid,\n.harmony-input[type=text]:invalid {\n    box-shadow: 0 0 0 1px #ff1a00;\n}\n\n.chrome-select {\n    -webkit-appearance: none;\n    -webkit-user-select: none;\n    border: 1px solid rgba(0, 0, 0, 0.2);\n    border-radius: 2px;\n    color: #333;\n    font: inherit;\n    margin: 0;\n    outline: none;\n    padding-right: 20px;\n    padding-left: 6px;\n    background-image: -webkit-image-set(url(Images/chromeSelect.png) 1x, url(Images/chromeSelect_2x.png) 2x);\n    background-color: hsl(0, 0%, 98%);\n    background-position: right center;\n    background-repeat: no-repeat;\n    min-height: 24px;\n    min-width: 80px;\n    background-size: 15px;\n}\n\n.chrome-select:enabled:active,\n.chrome-select:enabled:focus,\n.chrome-select:enabled:hover {\n    background-color: hsl(0, 0%, 96%);\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n.chrome-select:enabled:active {\n    background-color: #f2f2f2;\n}\n\n.chrome-select:enabled:focus {\n    border-color: transparent;\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n.chrome-select:disabled {\n    opacity: 0.38;\n}\n\n.chrome-select optgroup,\n.chrome-select option {\n    background-color: #EEEEEE;\n    color: #222;\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar {\n    width: 14px;\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar-track,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar-track {\n    -webkit-box-shadow: inset 0 0 1px rgba(255,255,255,0.3);\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar-thumb,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar-thumb {\n    border-radius: 2px;\n    background-color: #333;\n    -webkit-box-shadow: inset 0 0 1px rgba(255,255,255,0.5);\n}\n\n:not(.platform-mac).-theme-with-dark-background ::-webkit-scrollbar-corner,\n:host-context(:not(.platform-mac).-theme-with-dark-background) ::-webkit-scrollbar-corner {\n    background-color: #242424;\n}\n\n.gray-info-message {\n    text-align: center;\n    font-style: italic;\n    padding: 6px;\n    color: #888;\n    white-space: nowrap;\n}\n\nlabel[is=dt-icon-label] {\n    flex: none;\n}\n\n.full-widget-dimmed-banner a {\n    color: inherit;\n}\n\n.full-widget-dimmed-banner {\n    color: #777;\n    background-color: white;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    text-align: center;\n    padding: 20px;\n    position: absolute;\n    top: 0;\n    right: 0;\n    bottom: 0;\n    left: 0;\n    font-size: 13px;\n    overflow: auto;\n    z-index: 500;\n}\n\n[is=ui-icon] {\n    display: inline-block;\n    flex-shrink: 0;\n}\n\n.-theme-with-dark-background [is=ui-icon].icon-invert,\n:host-context(.-theme-with-dark-background) [is=ui-icon].icon-invert {\n    filter: invert(80%) hue-rotate(180deg);\n}\n\n[is=ui-icon].icon-mask {\n    background-color: rgb(110, 110, 110);\n    -webkit-mask-position: var(--spritesheet-position);\n}\n\n[is=ui-icon]:not(.icon-mask) {\n    background-position: var(--spritesheet-position);\n}\n\n.spritesheet-smallicons:not(.icon-mask) {\n    background-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n}\n\n.spritesheet-smallicons.icon-mask {\n    -webkit-mask-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n}\n\n.spritesheet-largeicons:not(.icon-mask) {\n    background-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n}\n\n.spritesheet-largeicons.icon-mask {\n    -webkit-mask-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n}\n\n.spritesheet-mediumicons:not(.icon-mask) {\n    background-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n}\n\n.spritesheet-mediumicons.icon-mask {\n    -webkit-mask-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n}\n\n.spritesheet-arrowicons {\n    background-image: url(Images/popoverArrows.png);\n}\n\n.force-white-icons [is=ui-icon].spritesheet-smallicons, [is=ui-icon].force-white-icons.spritesheet-smallicons, -theme-preserve {\n    -webkit-mask-image: -webkit-image-set(url(Images/smallIcons.png) 1x, url(Images/smallIcons_2x.png) 2x);\n    -webkit-mask-position: var(--spritesheet-position);\n    background: #fafafa !important;\n}\n\n.force-white-icons [is=ui-icon].spritesheet-largeicons, [is=ui-icon].force-white-icons.spritesheet-largeicons, -theme-preserve {\n    -webkit-mask-image: -webkit-image-set(url(Images/largeIcons.png) 1x, url(Images/largeIcons_2x.png) 2x);\n    -webkit-mask-position: var(--spritesheet-position);\n    background: #fafafa !important;\n}\n\n.force-white-icons [is=ui-icon].spritesheet-mediumicons, [is=ui-icon].force-white-icons.spritesheet-mediumicons, -theme-preserve {\n    -webkit-mask-image: -webkit-image-set(url(Images/mediumIcons.png) 1x, url(Images/mediumIcons_2x.png) 2x);\n    -webkit-mask-position: var(--spritesheet-position);\n    background: #fafafa !important;\n}\n\n/*# sourceURL=ui/inspectorCommon.css */";Runtime.cachedResources["ui/inspectorStyle.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:root {\n    height: 100%;\n    overflow: hidden;\n}\n\n:root {\n    --accent-color: #03a9f4;\n    --accent-color-b: #2196f3;\n    --accent-color-c: #3e82f7;\n    --toolbar-bg-color: #f3f3f3;\n    --toolbar-hover-bg-color: #eaeaea;\n    --selection-fg-color: white;\n    --selection-inactive-bg-color: #dadada;\n    --tab-selected-fg-color: #333;\n    --tab-selected-bg-color: var(--toolbar-bg-color);\n    --drop-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05),\n                   0 2px 4px rgba(0, 0, 0, 0.2),\n                   0 2px 6px rgba(0, 0, 0, 0.1);\n    --divider-color: #d0d0d0;\n    --focus-ring-inactive-shadow: 0 0 0 1px #e0e0e0;\n}\n\n.-theme-with-dark-background {\n    --accent-color: #32699f;\n    --accent-color-b: #2f84da;\n    --accent-color-c: #1f4061;\n    --toolbar-bg-color: #333333;\n    --toolbar-hover-bg-color: #202020;\n    --selection-fg-color: #cdcdcd;\n    --selection-inactive-bg-color: #333333;\n    --tab-selected-fg-color: #eaeaea;\n    --tab-selected-bg-color: black;\n    --drop-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2),\n                   0 2px 4px 2px rgba(0, 0, 0, 0.2),\n                   0 2px 6px 2px rgba(0, 0, 0, 0.1);\n    --divider-color: #525252;\n    --focus-ring-inactive-shadow: 0 0 0 1px #5a5a5a;\n}\n\n:root {\n    --focus-ring-active-shadow: 0 0 0 1px var(--accent-color);\n    --selection-bg-color: var(--accent-color-b);\n    --divider-border: 1px solid var(--divider-color);\n}\n\nbody {\n    height: 100%;\n    width: 100%;\n    position: relative;\n    overflow: hidden;\n    margin: 0;\n    cursor: default;\n    font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n    font-size: 12px;\n    tab-size: 4;\n    -webkit-user-select: none;\n    color: #222;\n}\n\n.platform-linux {\n    color: rgb(48, 57, 66);\n    font-family: Roboto, Ubuntu, Arial, sans-serif;\n}\n\n.platform-mac {\n    color: rgb(48, 57, 66);\n    font-family: '.SFNSDisplay-Regular', 'Helvetica Neue', 'Lucida Grande', sans-serif;\n}\n\n.platform-windows {\n    font-family: 'Segoe UI', Tahoma, sans-serif;\n}\n\n.panel {\n    display: flex;\n    overflow: hidden;\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    z-index: 0;\n    background-color: white;\n}\n\n.panel-sidebar {\n    overflow-x: hidden;\n    background-color: var(--toolbar-bg-color);\n}\n\niframe.extension {\n    flex: auto;\n    width: 100%;\n    height: 100%;\n}\n\niframe.panel.extension {\n    display: block;\n    height: 100%;\n}\n\n/*# sourceURL=ui/inspectorStyle.css */";Runtime.cachedResources["ui/inspectorSyntaxHighlight.css"]="/*\n * Copyright (C) 2009 Apple Inc.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n.cm-js-keyword {color: hsl(310, 86%, 36%);}\n.cm-js-number {color: hsl(248, 100%, 41%);}\n.cm-js-comment {color: hsl(120, 100%, 23%); font-style: italic;}\n.cm-js-string {color: hsl(1, 80%, 43%);}\n.cm-js-string-2 {color: hsl(1, 99%, 39%);}\n.cm-js-atom {color: hsl(310, 86%, 36%);}\n.cm-js-def {color: hsl(240, 73%, 38%);}\n.cm-js-operator {color: hsl(27, 100%, 30%);}\n.cm-js-meta {color: hsl(27, 100%, 30%);}\n.cm-js-variable-2 {color: hsl(240, 73%, 38%);}\n\n.cm-css-keyword { color: rgb(7, 144, 154);}\n.cm-css-number {color: rgb(50, 0, 255);}\n.cm-css-comment {color: rgb(0, 116, 0);}\n.cm-css-def {color: rgb(200, 0, 0);}\n.cm-css-meta {color: rgb(200, 0, 0);}\n.cm-css-atom {color: rgb(7, 144, 154);}\n.cm-css-string {color: rgb(7, 144, 154);}\n.cm-css-string-2 {color: rgb(7, 144, 154);}\n.cm-css-link {color: rgb(7, 144, 154);}\n.cm-css-variable {color: rgb(200, 0, 0);}\n.cm-css-variable-2 {color: rgb(0, 0, 128);}\n.cm-css-property, .webkit-css-property {color: rgb(200, 0, 0);}\n\n.cm-xml-meta {color: rgb(192, 192, 192);}\n.cm-xml-comment {color: rgb(35, 110, 37);}\n.cm-xml-string {color: rgb(26, 26, 166);}\n.cm-xml-tag {color: var(--dom-tag-name-color);}\n.cm-xml-attribute {color: rgb(153, 69, 0);}\n.cm-xml-link {color: #00e;}\n\n:root {\n    --dom-tag-name-color: rgb(136, 18, 128);\n    --dom-attribute-name-color: rgb(153, 69, 0);\n}\n\n.webkit-html-comment {\n    /* Keep this in sync with view-source.css (.webkit-html-comment) */\n    color: rgb(35, 110, 37);\n}\n\n.webkit-html-tag {\n    color: rgb(168, 148, 166);\n}\n\n.webkit-html-tag-name, .webkit-html-close-tag-name {\n    /* Keep this in sync with view-source.css (.webkit-html-tag) */\n    color: var(--dom-tag-name-color);\n}\n\n.webkit-html-pseudo-element {\n    /* This one is non-standard. */\n    color: brown;\n}\n\n.webkit-html-js-node,\n.webkit-html-css-node {\n    white-space: pre-wrap;\n}\n\n.webkit-html-text-node {\n    unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-entity-value {\n    /* This one is non-standard. */\n    background-color: rgba(0, 0, 0, 0.15);\n    unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-doctype {\n    /* Keep this in sync with view-source.css (.webkit-html-doctype) */\n    color: rgb(192, 192, 192);\n}\n\n.webkit-html-attribute-name {\n    /* Keep this in sync with view-source.css (.webkit-html-attribute-name) */\n    color: var(--dom-attribute-name-color);\n    unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-attribute-value {\n    /* Keep this in sync with view-source.css (.webkit-html-attribute-value) */\n    color: rgb(26, 26, 166);\n    unicode-bidi: -webkit-isolate;\n}\n\n.devtools-link {\n    color: rgb(17, 85, 204);\n    text-decoration: underline;\n}\n\n.devtools-link [is=ui-icon] {\n    vertical-align: middle;\n}\n\n.devtools-link[data-keyboard-focus=\"true\"]:focus {\n    outline-width: unset;\n}\n\n.devtools-link:not(.devtools-link-prevent-click) {\n    cursor: pointer;\n}\n\n.-theme-with-dark-background .devtools-link,\n:host-context(.-theme-with-dark-background) .devtools-link {\n    color: hsl(0, 0%, 67%);\n}\n\n.webkit-html-end-of-file {\n    /* Keep this in sync with view-source.css (.webkit-html-end-of-file) */\n    color: rgb(255, 0, 0);\n    font-weight: bold;\n}\n\n/* Default CodeMirror Theme */\n.cm-negative {color: #d44;}\n.cm-positive {color: #292;}\n.cm-header, .cm-strong {font-weight: bold;}\n.cm-em {font-style: italic;}\n.cm-link {text-decoration: underline;}\n.cm-strikethrough {text-decoration: line-through;}\n\n.cm-invalidchar {color: #f00;}\n\n.cm-header {color: blue;}\n.cm-quote {color: #090;}\n\n.cm-keyword {color: #708;}\n.cm-atom {color: #219;}\n.cm-number {color: #164;}\n.cm-def {color: #00f;}\n.cm-variable-2 {color: #05a;}\n.cm-variable-3, .cm-type {color: #085;}\n.cm-comment {color: #a50;}\n.cm-string {color: #a11;}\n.cm-string-2 {color: #f50;}\n.cm-meta {color: #555;}\n.cm-qualifier {color: #555;}\n.cm-builtin {color: #30a;}\n.cm-bracket {color: #997;}\n.cm-tag {color: #170;}\n.cm-attribute {color: #00c;}\n.cm-hr {color: #999;}\n.cm-link {color: #00c;}\n\n.cm-error {color: #f00;}\n\n/*# sourceURL=ui/inspectorSyntaxHighlight.css */";Runtime.cachedResources["ui/inspectorSyntaxHighlightDark.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.cm-js-atom{color:rgb(161, 247, 181);}\n.cm-js-attribute{color:rgb(97, 148, 198);}\n.cm-js-builtin{color:rgb(159, 180, 214);}\n.cm-js-comment{color:rgb(116, 116, 116);}\n.cm-js-def{color:var(--dom-tag-name-color);}\n.cm-js-keyword{color:rgb(154, 127, 213);}\n.cm-js-link{color:rgb(159, 180, 214);}\n.cm-js-meta{color:rgb(221, 251, 85);}\n.cm-js-number{color:rgb(161, 247, 181);}\n.cm-js-operator{color:rgb(210, 192, 87);}\n.cm-js-property{color:rgb(210, 192, 87);}\n.cm-js-string{color:rgb(242, 139, 84);}\n.cm-js-string-2{color:rgb(242, 139, 84);}\n.cm-js-tag{color:var(--dom-tag-name-color);}\n.cm-js-variable{color:rgb(217, 217, 217);}\n.cm-js-variable-2{color:rgb(217, 217, 217);}\n.cm-atom{color:rgb(161, 247, 181);}\n.cm-comment{color:rgb(116, 116, 116);}\n.cm-variable{color:rgb(217, 217, 217);}\n.cm-string{color:rgb(242, 139, 84);}\n.cm-keyword{color:rgb(154, 127, 213);}\n.cm-number{color:rgb(161, 247, 181);}\n.cm-operator{color:rgb(210, 192, 87);}\n.cm-css-atom{color:rgb(217, 217, 217);}\n.cm-css-builtin{color:rgb(255, 163, 79);}\n.cm-css-def{color:rgb(255, 163, 79);}\n.cm-css-comment{color:rgb(116, 116, 116);}\n.cm-css-meta{color:rgb(132, 240, 255);}\n.cm-css-number{color:rgb(217, 217, 217);}\n.cm-css-operator{color:rgb(217, 217, 217);}\n.cm-css-property{color:rgb(132, 240, 255);}\n.cm-css-qualifier{color:rgb(255, 163, 79);}\n.cm-css-string{color:rgb(231, 194, 111);}\n.cm-css-string-2{color:rgb(217, 217, 217);}\n.cm-css-tag{color:rgb(255, 163, 79);}\n.cm-css-variable{color:rgb(255, 163, 79);}\n.cm-css-variable-2{color:rgb(255, 163, 79);}\n.cm-xml-comment{color:rgb(137, 137, 137);}\n.cm-xml-error{color:rgb(198, 95, 95);}\n.cm-xml-string{color:rgb(242, 151, 102);}\n.cm-xml-tag{color:var(--dom-tag-name-color);}\n.cm-xml-attribute{color:var(--dom-attribute-name-color);}\n.cm-xml-link{color:rgb(231, 194, 111);}\n\n.webkit-html-attribute-name{color:var(--dom-attribute-name-color);}\n.webkit-html-attribute-value{color:rgb(242, 151, 102);}\n.webkit-html-comment{color:rgb(137, 137, 137);}\n.devtools-link{color:rgb(231, 194, 111);}\n.webkit-html-tag{color:var(--dom-tag-name-color);}\n.webkit-html-tag-name{color:var(--dom-tag-name-color);}\n.webkit-html-close-tag-name{color:var(--dom-tag-name-color);}\n.webkit-html-text-node{color:rgb(207, 208, 208);}\n.webkit-html-css-node{color:rgb(207, 208, 208);}\n.webkit-html-js-node{color:rgb(207, 208, 208);}\n.webkit-html-pseudo-element{color:rgb(93, 175, 215);}\n.webkit-css-selector{color:rgb(255, 163, 79);}\n.webkit-css-at-rule{color:rgb(188, 164, 197);}\n.webkit-css-color{color:rgb(255, 163, 79);}\n.webkit-css-comment{color:rgb(116, 116, 116);}\n.webkit-css-important{color:rgb(255, 26, 26);}\n.webkit-css-keyword{color:rgb(255, 163, 79);}\n.webkit-css-number{color:rgb(217, 217, 217);}\n.webkit-css-property{color: rgb(53, 212, 199);}\n.webkit-css-string{color:rgb(231, 194, 111);}\n.webkit-css-url{color:rgb(231, 194, 111);}\n\n.cm-def{color:var(--dom-tag-name-color);}\n.cm-header{color:var(--dom-tag-name-color);}\n.cm-variable-2{color:rgb(217, 217, 217);}\n\n.cm-variable-2 {color: #05a;}\n.cm-variable-3, .cm-type {color: rgb(93, 176, 215);}\n.cm-string {color: rgb(242, 139, 84);}\n.cm-meta {color: #555;}\n.cm-meta {color:rgb(221, 251, 85);}\n.cm-qualifier{color:rgb(255, 163, 79);}\n.cm-builtin{color:rgb(159, 180, 214);}\n.cm-bracket {color: #997;}\n.cm-tag{color:var(--dom-tag-name-color);}\n.cm-attribute{color:rgb(97, 148, 198);}\n.cm-hr {color: #999;}\n.cm-link{color:rgb(159, 180, 214);}\n\n:root {\n    --dom-tag-name-color: rgb(93, 176, 215);\n    --dom-attribute-name-color: rgb(155, 187, 220);\n}\n\n/*# sourceURL=ui/inspectorSyntaxHighlightDark.css */";Runtime.cachedResources["ui/inspectorViewTabbedPane.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tabbed-pane-header-tab,\n.tabbed-pane-header-tab.selected {\n    height: 26px;\n    margin: 0;\n    border: none;\n    border-left: 2px solid transparent;\n    border-right: 2px solid transparent;\n}\n\n.tabbed-pane-header-tab.selected {\n    border-width: 0 2px 0 2px;\n}\n\n.tabbed-pane-header-contents {\n    margin-left: 0;\n}\n\n.tabbed-pane-left-toolbar {\n    margin-right: 0 !important;\n}\n\n/*# sourceURL=ui/inspectorViewTabbedPane.css */";Runtime.cachedResources["ui/listWidget.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.list {\n    flex: auto 0 1;\n    overflow-y: auto;\n    border: 1px solid rgb(231, 231, 231);\n    flex-direction: column;\n}\n\n.list-separator {\n    background: rgb(231, 231, 231);\n    height: 1px;\n}\n\n.list-item {\n    flex: none;\n    min-height: 30px;\n    display: flex;\n    align-items: center;\n    position: relative;\n    overflow: hidden;\n}\n\n.list-item:hover {\n    background: hsl(0, 0%, 96%);\n}\n\n.controls-container {\n    display: flex;\n    flex-direction: row;\n    justify-content: flex-end;\n    align-items: stretch;\n    pointer-events: none;\n}\n\n.controls-gradient {\n    flex: 0 1 50px;\n}\n\n.list-item:hover .controls-gradient {\n    background-image: linear-gradient(90deg, transparent, hsl(0, 0%, 96%));\n}\n\n.controls-buttons {\n    flex: none;\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n    pointer-events: auto;\n    visibility: hidden;\n}\n\n.list-item:hover .controls-buttons {\n    background-color: hsl(0, 0%, 96%);\n    visibility: visible;\n}\n\n.editor-container {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    flex: none;\n    background: hsl(0, 0%, 96%);\n    overflow: hidden;\n}\n\n.editor-content {\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n}\n\n.editor-buttons {\n    flex: none;\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n    justify-content: flex-start;\n    padding: 5px;\n}\n\n.editor-buttons > button {\n    flex: none;\n    margin-right: 10px;\n}\n\n.editor-content input {\n    margin-right: 10px;\n}\n\n.editor-content input.error-input {\n    background-color: white;\n}\n\n/*# sourceURL=ui/listWidget.css */";Runtime.cachedResources["ui/popover.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n    display: flex;\n    background: white;\n    box-shadow: var(--drop-shadow);\n    border-radius: 2px;\n    overflow: auto;\n    -webkit-user-select: text;\n    line-height: 11px;\n}\n\n.widget.has-padding {\n    padding: 6px;\n}\n\n/*# sourceURL=ui/popover.css */";Runtime.cachedResources["ui/progressIndicator.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.progress-indicator-shadow-stop-button {\n    background-color: rgb(216, 0, 0) !important;\n    border: 0;\n    width: 10px;\n    height: 12px;\n    border-radius: 2px;\n}\n\n.progress-indicator-shadow-container {\n    display: flex;\n    flex: 1 0 auto;\n    align-items: center;\n}\n\n.progress-indicator-shadow-container .title {\n    text-overflow: ellipsis;\n    overflow: hidden;\n    max-width: 150px;\n    margin-right: 2px;\n    color: #777;\n}\n\n.progress-indicator-shadow-container progress {\n    flex: auto;\n    margin: 0 2px;\n    width: 100px\n}\n\n/*# sourceURL=ui/progressIndicator.css */";Runtime.cachedResources["ui/radioButton.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n::content .dt-radio-button {\n    height: 17px;\n    width: 17px;\n    min-width: 17px;\n    border: 1px solid rgb(165, 165, 165);\n    background-image: linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n    border-radius: 8px;\n    -webkit-appearance: none;\n    vertical-align: middle;\n    margin: 0 5px 5px 0;\n}\n\n::content .dt-radio-button:active:not(:disabled) {\n    background-image: linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n::content .dt-radio-button:checked {\n    background: url(Images/radioDot.png) center no-repeat,\n                linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n}\n\n::content .dt-radio-button:checked:active {\n    background: url(Images/radioDot.png) center no-repeat,\n                linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n/*# sourceURL=ui/radioButton.css */";Runtime.cachedResources["ui/remoteDebuggingTerminatedScreen.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n    padding: 20px;\n}\n\n.message, .button {\n    font-size: larger;\n    white-space: pre;\n    margin: 5px;\n}\n\n.button {\n    text-align: center;\n    margin-top: 10px;\n}\n\n.reason {\n    color: #8b0000;\n}\n\n/*# sourceURL=ui/remoteDebuggingTerminatedScreen.css */";Runtime.cachedResources["ui/reportView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    background-color: #f9f9f9;\n}\n\n.report-content-box {\n    background-color: white;\n    white-space: nowrap;\n    overflow: auto;\n}\n\n.report-content-box.no-scroll {\n    overflow: visible;\n}\n\n.report-header {\n    border-bottom: 1px solid rgb(230, 230, 230);\n    padding: 12px 24px;\n}\n\n.report-header .toolbar {\n    margin-bottom: -8px;\n}\n\n.report-header .toolbar {\n    margin-top: 5px;\n    margin-left: -8px;\n}\n\n.report-title {\n    font-size: 15px;\n}\n\n.report-url, .report-subtitle {\n    font-size: 12px;\n    margin-top: 10px;\n}\n\n.report-section {\n    display: flex;\n    padding: 12px;\n    border-bottom: 1px solid rgb(230, 230, 230);\n    flex-direction: column;\n}\n\n.report-section-header {\n    margin-left: 18px;\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n}\n\n.report-section-title {\n    flex: auto;\n    text-overflow: ellipsis;\n    overflow: hidden;\n    font-weight: bold;\n    color: #555;\n}\n\n.report-field {\n    margin-top: 8px;\n    display: flex;\n    line-height: 28px;\n}\n\n.report-row {\n    margin: 10px 0 2px 18px;\n}\n\n.report-field-name {\n    color: #888;\n    flex: 0 0 128px;\n    text-align: right;\n    padding: 0 6px;\n    white-space: pre;\n}\n\n.report-field-value {\n    flex: auto;\n    padding: 0 6px;\n    white-space: pre;\n}\n\n.report-field-value-subtitle {\n    color: #888;\n    line-height: 14px;\n}\n\n/*# sourceURL=ui/reportView.css */";Runtime.cachedResources["ui/rootView.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.root-view {\n    background-color: white;\n    overflow: hidden;\n    position: absolute !important;\n    left: 0;\n    top: 0;\n    right: 0;\n    bottom: 0;\n}\n\n/*# sourceURL=ui/rootView.css */";Runtime.cachedResources["ui/searchableView.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.search-bar {\n    flex: 0 0 31px;\n    background-color: #eee;\n    border-top: 1px solid #ccc;\n    display: flex;\n    overflow: hidden;\n    z-index: 0;\n}\n\n.search-bar.replaceable {\n    flex: 0 0 57px;\n}\n\n.search-replace {\n    -webkit-appearance: none;\n    border: 0;\n    padding: 0 3px;\n    margin: 0;\n    flex: 1;\n}\n\n.search-replace:focus {\n    outline: none;\n}\n\n.toolbar-search {\n    display: flex;\n    width: 100%;\n}\n\n.toolbar-search > div {\n    margin: 2px 2px;\n    flex-shrink: 0;\n}\n\n.toolbar-search-inputs {\n    flex-grow: 1;\n    min-width: 150px;\n}\n\n.toolbar-search-navigation-controls {\n    align-self: stretch;\n}\n\n.toolbar-search-navigation {\n    display: inline-block;\n    width: 20px;\n    height: 20px;\n    background-repeat: no-repeat;\n    background-position: 4px 7px;\n    border-left: 1px solid rgb(170, 170, 170);\n    opacity: 0.3;\n}\n\n.toolbar-search-navigation.enabled {\n    opacity: 1.0;\n}\n\n.toolbar-search button.search-action-button {\n    font-weight: 400;\n    height: 22px;\n    width: 87px;\n}\n\n.toolbar-search-control {\n    display: -webkit-flex;\n    position: relative;\n    background-color: white;\n}\n\n.toolbar-search-buttons {\n    display: flex;\n    flex-direction: column;\n}\n\n.toolbar-replace-control,\n#search-input-field {\n    margin-top: 1px;\n    line-height: 17px;\n}\n\n.toolbar-search-control, .toolbar-replace-control {\n    border: 1px solid rgb(163, 163, 163);\n    height: 22px;\n    border-radius: 2px;\n    width: 100%;\n    margin-top: 2px;\n    margin-bottom: 2px;\n}\n\n.toolbar-search-navigation.enabled:active {\n    background-position: 4px 7px, 0 0;\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev {\n    background-image: url(Images/searchPrev.png);\n    border-left: 1px solid rgb(163, 163, 163);\n}\n\n:host-context(.-theme-with-dark-background) .toolbar-search-navigation {\n    -webkit-filter: invert(90%);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev.enabled:active {\n    background-image: url(Images/searchPrev.png), #f2f2f2;\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next {\n    background-image: url(Images/searchNext.png);\n    border-left: 1px solid rgb(230, 230, 230);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next.enabled:active {\n    background-image: url(Images/searchNext.png), #f2f2f2;\n}\n\n.search-results-matches {\n    display: inline-block;\n    text-align: right;\n    padding: 0 4px;\n    color: rgb(165, 165, 165);\n    align-self: center;\n}\n\n.first-row-buttons {\n    display: flex;\n    justify-content: space-between;\n}\n\n.toolbar-search > .replace-toggle-toolbar {\n    margin: 2px -2px 0 0;\n}\n\n.toolbar-search-options {\n    margin: 0 auto;\n}\n\n/*# sourceURL=ui/searchableView.css */";Runtime.cachedResources["ui/slider.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.dt-range-input {\n    -webkit-appearance: none;\n    margin: 0;\n    padding: 0;\n    height: 10px;\n    width: 88px;\n    outline: none;\n    background: none;\n}\n\n.dt-range-input::-webkit-slider-thumb, -theme-preserve {\n    -webkit-appearance: none;\n    margin: 0;\n    padding: 0;\n    border: 0;\n    width: 12px;\n    height: 12px;\n    margin-top: -5px;\n    border-radius: 50%;\n    background-color: #4285F4;\n}\n\n.dt-range-input::-webkit-slider-runnable-track {\n    -webkit-appearance: none;\n    margin: 0;\n    padding: 0;\n    width: 100%;\n    height: 2px;\n    background-color: rgba(0, 0, 0, 0.26);\n}\n\n.dt-range-input:focus::-webkit-slider-thumb, -theme-preserve {\n    box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n.dt-range-input:disabled::-webkit-slider-thumb {\n    background-color: #bdbdbd;\n}\n\n/*# sourceURL=ui/slider.css */";Runtime.cachedResources["ui/smallBubble.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ndiv {\n    display: inline-block;\n    height: 14px;\n    vertical-align: middle;\n    white-space: nowrap;\n    padding: 1px 4px;\n    text-align: left;\n    font-size: 11px;\n    line-height: normal;\n    font-weight: bold;\n    text-shadow: none;\n    color: white;\n    margin-top: -1px;\n    border-radius: 7px;\n}\n\ndiv.verbose {\n    background-color: rgb(0, 0, 255);\n}\n\ndiv.info {\n    background-color: rgb(128, 151, 189);\n}\n\ndiv.warning {\n    background-color: rgb(232, 164, 0);\n}\n\ndiv.error {\n    background-color: rgb(216, 35, 35);\n}\n\n/*# sourceURL=ui/smallBubble.css */";Runtime.cachedResources["ui/segmentedButton.css"]="/*\n * Copyright 2018 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.segmented-button {\n  align-items: center;\n  align-content: center;\n  display: flex;\n}\n\n.segmented-button-segment {\n  background-color: white;\n  border: var(--divider-border);\n  border-right-style: none;\n  color: #5a5a5a;\n  flex: 1 1 0;\n  font-weight: 700;\n  margin-left: -1px;\n  padding: 4px 16px;\n}\n\n.segmented-button-segment:hover {\n  background-color: #F4F4F4;\n  color: #333;\n}\n\n.segmented-button-segment:first-child {\n  border-bottom-left-radius: 4px;\n  border-top-left-radius: 4px;\n}\n\n.segmented-button-segment:last-child {\n  border-bottom-right-radius: 4px;\n  border-right-style: solid;\n  border-top-right-radius: 4px;\n}\n\n.segmented-button-segment.segmented-button-segment-selected {\n  background-color: hsl(218, 81%, 59%);\n  border-color: transparent;\n  color: #FAFAFA;\n}\n\n.segmented-button-segment.segmented-button-segment-selected:hover {\n  background-color: hsl(218, 81%, 62%);\n  color: #FFF;\n}\n\n/* Remove a border between the selected button and its siblin */\n.segmented-button-segment-selected + .segmented-button-segment {\n  border-left-color: transparent;\n}\n\n/*# sourceURL=ui/segmentedButton.css */";Runtime.cachedResources["ui/softContextMenu.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.soft-context-menu {\n    border: 1px solid rgba(196, 196, 196, 0.9);\n    border-top: 1px solid rgba(196, 196, 196, 0.5);\n    /* NOTE: Keep padding in sync with padding adjustment in SoftContextMenu.js */\n    padding: 4px 0 4px 0;\n    border-radius: 4px;\n    background-color: rgb(240, 240, 240);\n    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.25);\n    overflow-y: auto;\n    min-width: 160px !important;\n}\n\n:host-context(.-theme-with-dark-background) .soft-context-menu {\n    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.25);\n}\n\n.soft-context-menu-item {\n    display: flex;\n    width: 100%;\n    line-height: 14px;\n    font-size: 12px;\n    border-top: 1px solid transparent;\n    border-bottom: 1px solid transparent;\n    padding: 2px 7px 2px 8px;\n    margin: 0 13px 0 0;\n    white-space: nowrap;\n}\n\n.soft-context-menu-disabled {\n    color: #999;\n    pointer-events: none;\n}\n\n.soft-context-menu-separator {\n    height: 10px;\n    margin: 0 1px;\n}\n\n.soft-context-menu-separator > .separator-line {\n    margin: 0;\n    height: 5px;\n    border-bottom: 1px solid rgb(222, 222, 222);\n    pointer-events: none;\n}\n\n.soft-context-menu-item-mouse-over,\n.-theme-selection-color {\n    border-top: 1px solid var(--selection-bg-color);\n    border-bottom: 1px solid var(--selection-bg-color);\n    background-color: var(--selection-bg-color);\n    color: white;\n}\n\n:host-context(.platform-mac) .soft-context-menu-item-mouse-over, -theme-preserve {\n    border-top: 1px solid transparent;\n    border-bottom: 1px solid transparent;\n    background-image: linear-gradient(to right, hsl(214, 81%, 60%), hsl(214, 100%, 56%));\n}\n\n:host-context(.platform-mac) .separator-line {\n    border-width: 2px;\n}\n\n.soft-context-menu-item-submenu-arrow {\n    color: #222;\n    pointer-events: none;\n    font-size: 11px;\n    flex: 1 1 auto;\n    text-align: right;\n}\n\n.soft-context-menu-item-mouse-over .soft-context-menu-item-checkmark {\n    color: var(--selection-fg-color);\n}\n\n.soft-context-menu-custom-item {\n    display: inline-flex;\n    justify-content: center;\n    align-items: center;\n    flex: auto;\n}\n\n.soft-context-menu-shortcut {\n    color: gray;\n    pointer-events: none;\n    flex: 1 1 auto;\n    text-align: right;\n    padding-left: 10px;\n}\n\n.soft-context-menu-item-mouse-over .soft-context-menu-shortcut {\n    color: inherit;\n}\n\n.checkmark {\n    opacity: 0.7;\n    pointer-events: none;\n    margin: auto 5px auto 0px;\n}\n\n.soft-context-menu-item-mouse-over .checkmark {\n    opacity: 1;\n}\n\n/*# sourceURL=ui/softContextMenu.css */";Runtime.cachedResources["ui/softDropDown.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.item.disabled {\n    opacity: 0.5;\n}\n\n.item-list {\n    background-color: white;\n    box-shadow: var(--drop-shadow);\n    overflow-x: hidden;\n    overflow-y: auto;\n    width: 100%;\n}\n\n.item.highlighted {\n    color: var(--selection-fg-color);\n    background-color: var(--selection-bg-color);\n}\n\n/*# sourceURL=ui/softDropDown.css */";Runtime.cachedResources["ui/softDropDownButton.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n:host {\n    height: 26px;\n    text-align: left;\n    position: relative;\n    border: none;\n    background: none;\n}\n\n:host([disabled]) {\n    opacity: .5;\n}\n\n:host .title {\n    padding-right: 5px;\n    width: 120px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n:host([data-keyboard-focus=\"true\"]:focus)::before {\n    content: \"\";\n    position: absolute;\n    top: 2px;\n    left: 2px;\n    right: 2px;\n    bottom: 2px;\n    border-radius: 2px;\n    background: rgba(0, 0, 0, 0.08);\n}\n\n:host(.warning) {\n    background: #ffd7d7 !important;\n}\n\n/*# sourceURL=ui/softDropDownButton.css */";Runtime.cachedResources["ui/splitWidget.css"]="/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n    overflow: hidden;\n}\n\n.shadow-split-widget {\n    display: flex;\n    overflow: hidden;\n}\n\n.shadow-split-widget-contents {\n    display: flex;\n    position: relative;\n    flex-direction: column;\n    contain: layout size style;\n}\n\n.shadow-split-widget-sidebar {\n    flex: none;\n}\n\n.shadow-split-widget-main, .shadow-split-widget-sidebar.maximized {\n    flex: auto;\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-resizer {\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    width: 6px;\n    z-index: 500;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-resizer {\n    position: absolute;\n    left: 0;\n    right: 0;\n    height: 6px;\n    z-index: 500;\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar {\n    flex-direction: row-reverse !important;\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar {\n    flex-direction: column-reverse !important;\n}\n\n.shadow-split-widget-resizer-border {\n    pointer-events: none;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-sidebar.no-default-splitter {\n    border: 0 !important;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-sidebar:not(.maximized) {\n    border: 0;\n    border-top: 1px solid var(--divider-color);\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n    border: 0;\n    border-bottom: 1px solid var(--divider-color);\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-sidebar:not(.maximized) {\n    border: 0;\n    border-left: 1px solid var(--divider-color);\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n    border: 0;\n    border-right: 1px solid var(--divider-color);\n}\n\n/*# sourceURL=ui/splitWidget.css */";Runtime.cachedResources["ui/toolbar.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    flex: none;\n    padding: 0 2px;\n}\n\n.toolbar-shadow {\n    position: relative;\n    white-space: nowrap;\n    height: 26px;\n    overflow: hidden;\n    z-index: 12;\n    display: flex;\n    flex: none;\n    align-items: center;\n}\n\n.toolbar-shadow.wrappable {\n    flex-wrap: wrap;\n    overflow: visible;\n}\n\n.toolbar-shadow.wrappable-reverse {\n    flex-direction: row-reverse;\n}\n\n.toolbar-shadow.toolbar-grow-vertical {\n    height: initial;\n}\n\n.toolbar-shadow.vertical {\n    flex-direction: column;\n    height: auto;\n    align-items: flex-start;\n}\n\n.toolbar-item {\n    position: relative;\n    display: flex;\n    background-color: transparent;\n    flex: none;\n    align-items: center;\n    justify-content: center;\n    padding: 0;\n    height: 26px;\n    border: none;\n    color: #5a5a5a;\n}\n\nselect.toolbar-item:disabled {\n    opacity: 0.5;\n}\n\n.toolbar-dropdown-arrow {\n    background-color: #6D6D6D;\n    pointer-events: none;\n    flex: none;\n}\n\nselect.toolbar-item:disabled + .toolbar-dropdown-arrow {\n    opacity: 0.5;\n}\n\n/* Toolbar item */\n\n.toolbar-button {\n    white-space: nowrap;\n    overflow: hidden;\n    min-width: 28px;\n    background: transparent;\n    border-radius: 0;\n}\n\n.toolbar-text {\n    margin: 0 5px;\n    flex: none;\n    color: #5a5a5a;\n}\n\n.toolbar-text:empty {\n    margin: 0;\n}\n\n.toolbar-has-dropdown {\n    justify-content: space-between;\n    padding: 0 3px 0 5px;\n}\n\n.toolbar-has-dropdown .toolbar-text {\n    margin: 0 4px 0 0;\n    text-overflow: ellipsis;\n    flex: auto;\n    overflow: hidden;\n    text-align: right;\n}\n\n.toolbar-button.dark-text .toolbar-dropdown-arrow {\n    background-color: #333;\n}\n\n.toolbar-has-glyph .toolbar-text {\n    margin-left: -4px;\n}\n\n.toolbar-button:not(.toolbar-has-glyph):not(.toolbar-has-dropdown):not(.largeicon-menu) {\n    font-weight: bold;\n}\n\n.toolbar-render-as-links * {\n    font-weight: initial;\n    color: rgb(17, 85, 204);\n    text-decoration: underline;\n    cursor: pointer;\n}\n\n.toolbar-toggled-gray:not(.toolbar-render-as-links) .toolbar-button:not(.toolbar-has-glyph):not(.toolbar-has-dropdown):not(.largeicon-menu):hover {\n    background-color: var(--toolbar-bg-color);\n}\n\n.toolbar-glyph {\n    background-color: #5a5a5a;\n    flex: none;\n}\n\n/* Button */\n\n.toolbar-button:disabled {\n    opacity: 0.5;\n}\n\n.toolbar-button.dark-text .toolbar-text{\n    color: #333 !important;\n}\n\n:not(.toolbar-render-as-links) .toolbar-button:enabled:hover:not(:active) .toolbar-glyph {\n    background-color: #333;\n}\n\n:not(.toolbar-render-as-links) .toolbar-button:enabled:hover:not(:active) .toolbar-text {\n    color: #333;\n}\n\n.toolbar-button.toolbar-state-on .toolbar-glyph,\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover:not(:active),\n.-theme-selection-color {\n    background-color: var(--accent-color-b);\n}\n\n.toolbar-button.toolbar-state-on .toolbar-text,\n.-theme-selection-color {\n    color: var(--accent-color-b);\n}\n\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover .toolbar-glyph {\n    background-color: white;\n}\n\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:hover .toolbar-text {\n    color: white;\n}\n\n.toolbar-button.toolbar-state-on:enabled:hover:not(:active) .toolbar-glyph,\n.toolbar-blue-on-hover .toolbar-button:not(.toolbar-state-on):enabled:active:hover,\n.-theme-selection-color {\n    background-color: var(--accent-color-b);\n}\n\n.toolbar-button.toolbar-state-on:enabled:hover:not(:active) .toolbar-text,\n.-theme-selection-color {\n    color: var(--accent-color-b);\n}\n\n.toolbar-toggled-gray .toolbar-button.toolbar-state-on {\n    background-color: var(--toolbar-bg-color) !important;\n}\n\n.toolbar-button.toolbar-state-on.toolbar-toggle-with-red-color .toolbar-glyph,\n.toolbar-button.toolbar-state-off.toolbar-default-with-red-color .toolbar-glyph {\n    background-color: rgb(216, 0, 0) !important;\n}\n\n:host-context(.-theme-with-dark-background) .toolbar-button.toolbar-state-on.toolbar-toggle-with-red-color .toolbar-glyph,\n:host-context(.-theme-with-dark-background) .toolbar-button.toolbar-state-off.toolbar-default-with-red-color .toolbar-glyph {\n    background-color: hsl(0, 100%, 65%) !important;\n}\n\n\n/* Checkbox */\n\n.toolbar-item.checkbox {\n    padding: 0 5px 0 2px;\n}\n\n.toolbar-item.checkbox:hover {\n    color: #333;\n}\n\n/* Select */\n\n.toolbar-select-container {\n    display: inline-flex;\n    flex-shrink: 0;\n    margin-right: 6px;\n}\n\nselect.toolbar-item {\n    min-width: 38px;\n    -webkit-appearance: none;\n    border: 0;\n    border-radius: 0;\n    padding: 0 13px 0 5px;\n    margin-right: -10px;\n    position: relative;\n    height: 22px;\n    margin-top: 2px;\n    margin-bottom: 2px;\n}\n\nselect.toolbar-item[data-keyboard-focus=\"true\"]:focus {\n    background: rgba(0, 0, 0, 0.08);\n    border-radius: 2px;\n}\n\nselect.toolbar-item[data-keyboard-focus=\"true\"]:focus > * {\n    background: white;\n}\n\n/* Input */\n\n.toolbar-input {\n    width: 120px;\n    height: 19px;\n    padding: 4px 3px 3px 3px;\n    margin: 1px 3px;\n    background-color: white;\n    border: 1px solid transparent ;\n    min-width: 35px;\n}\n\n.toolbar-input:hover {\n    box-shadow: var(--focus-ring-inactive-shadow);\n}\n\n.toolbar-input.focused {\n    box-shadow: var(--focus-ring-active-shadow);\n}\n\n.toolbar-input > input {\n    border: none;\n    flex-grow: 1;\n}\n\n.toolbar-input-clear-button {\n    opacity: 0.7;\n    flex-basis: 13px;\n    flex-shrink: 0;\n    height: 16px;\n}\n\n.toolbar-input-clear-button:hover {\n    opacity: 1;\n}\n\n.toolbar-input-empty .toolbar-input-clear-button {\n    display: none;\n}\n\n.toolbar-prompt-proxy {\n    flex: 1;\n}\n\n.toolbar-input-prompt {\n    flex: 1;\n    overflow: hidden;\n    white-space: nowrap;\n    cursor: auto;\n}\n\n/* Separator */\n\n.toolbar-divider {\n    background-color: #ccc;\n    width: 1px;\n    margin: 5px 4px;\n    height: 16px;\n}\n\n.toolbar-spacer {\n    flex: auto;\n}\n\n/* Long click */\n\n.long-click-glyph {\n    position: absolute;\n    background-color: #5a5a5a;\n    top: 0;\n    left:  0;\n}\n\n.toolbar-button.emulate-active {\n    background-color: rgb(163, 163, 163);\n}\n\n.toolbar-button[data-keyboard-focus=\"true\"]:focus::after {\n    position: absolute;\n    top: 2px;\n    bottom: 2px;\n    left: 2px;\n    right: 2px;\n    background-color: rgba(0, 0, 0, 0.08);\n    border-radius: 2px;\n    content: \"\";\n}\n\n.toolbar-shadow.floating {\n    flex-direction: column;\n    height: auto;\n    background-color: white;\n    border: 1px solid #ccc;\n    margin-top: -1px;\n    width: 28px;\n    left: -2px;\n}\n\ninput[is=history-input] {\n    border: none;\n    line-height: 16px;\n    padding: 1px;\n}\n\ninput[is=history-input]:hover {\n    box-shadow: var(--focus-ring-inactive-shadow);\n}\n\ninput[is=history-input]:focus {\n    box-shadow: var(--focus-ring-active-shadow);\n}\n\n/*# sourceURL=ui/toolbar.css */";Runtime.cachedResources["ui/suggestBox.css"]="/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n    display: flex;\n    flex: auto;\n}\n\n.suggest-box {\n    flex: auto;\n    background-color: #FFFFFF;\n    pointer-events: auto;\n    margin-left: -3px;\n    box-shadow: var(--drop-shadow);\n    overflow-x: hidden;\n}\n\n.suggest-box-content-item {\n    padding: 1px 0 1px 1px;\n    margin: 0;\n    border: 1px solid transparent;\n    white-space: nowrap;\n    display: flex;\n}\n\n.suggest-box-content-item.secondary {\n    background-color: #f9f9f9;\n}\n\n.suggestion-title {\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.suggestion-subtitle {\n    flex: auto;\n    text-align: right;\n    color: #999;\n    margin-right: 3px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.suggestion-icon {\n    user-select: none;\n    align-self: center;\n    flex-shrink: 0;\n}\n\n.suggest-box-content-item .query {\n    font-weight: bold;\n}\n\n.suggest-box-content-item .spacer {\n    display: inline-block;\n    width: 20px;\n}\n\n.suggest-box-content-item.selected {\n    background-color: var(--selection-bg-color);\n}\n\n.suggest-box-content-item.selected > span {\n    color: var(--selection-fg-color);\n}\n\n.default-selection-is-dimmed .suggest-box-content-item.selected {\n    background-color: #E0E0E0;\n}\n\n.default-selection-is-dimmed .suggest-box-content-item.selected > span {\n    color: inherit;\n}\n\n.user-has-interacted .suggest-box-content-item.selected {\n    background-color: var(--selection-bg-color);\n}\n\n.user-has-interacted .suggest-box-content-item.selected > span {\n   color: var(--selection-fg-color);\n}}\n\n.suggest-box-content-item:hover:not(.selected) {\n    background-color: rgba(56, 121, 217, 0.1);\n}\n\n/*# sourceURL=ui/suggestBox.css */";Runtime.cachedResources["ui/tabbedPane.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.tabbed-pane {\n    flex: auto;\n    overflow: hidden;\n}\n\n.tabbed-pane-content {\n    position: relative;\n    overflow: auto;\n    flex: auto;\n    display: flex;\n    flex-direction: column;\n}\n\n.tabbed-pane-content.has-no-tabs {\n    background-color: lightgray;\n}\n\n.tabbed-pane-placeholder {\n    font-size: 14px;\n    text-align: center;\n    margin-top: 20px;\n    text-shadow: rgba(255, 255, 255, 0.75) 0 1px 0;\n    line-height: 28px;\n    overflow: hidden;\n}\n\n.tabbed-pane-placeholder-row {\n    display: flex;\n    white-space: nowrap;\n}\n\n.tabbed-pane-placeholder-key {\n    flex: 1;\n    text-align: right;\n    padding-right: 14px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.tabbed-pane-placeholder-value {\n    flex: 1;\n    text-align: left;\n    padding-left: 14px;\n}\n\n.tabbed-pane-header {\n    display: flex;\n    flex: 0 0 27px;\n    border-bottom: 1px solid #ccc;\n    overflow: visible;\n    width: 100%;\n    background-color: var(--toolbar-bg-color);\n}\n\n.tabbed-pane-header-contents {\n    flex: auto;\n    pointer-events: none;\n    margin-left: 0;\n    position: relative;\n}\n\n.tabbed-pane-header-contents > * {\n    pointer-events: initial;\n}\n\n.tabbed-pane-header-tab-icon {\n    min-width: 14px;\n    display: flex;\n    align-items: center;\n    margin-right: 2px;\n}\n\n.tabbed-pane-header-tab {\n    float: left;\n    padding: 2px 0.8em;\n    height: 26px;\n    line-height: 15px;\n    white-space: nowrap;\n    cursor: default;\n    display: flex;\n    align-items: center;\n    color: #5a5a5a;\n}\n\n.tabbed-pane-header-tab.closeable {\n    padding-right: 4px;\n}\n\n.tabbed-pane-header-tab:hover,\n.tabbed-pane-shadow .tabbed-pane-header-tab[data-keyboard-focus=\"true\"]:focus {\n    color: #333;\n    background-color: var(--toolbar-hover-bg-color);\n}\n\n.tabbed-pane-header-tab-title {\n    text-overflow: ellipsis;\n    overflow: hidden;\n}\n\n.tabbed-pane-header-tab.measuring {\n    visibility: hidden;\n}\n\n.tabbed-pane-header-tab.selected {\n    border-bottom: none;\n}\n\n.tabbed-pane-header-tab.selected {\n    background-color: var(--tab-selected-bg-color);\n    color: var(--tab-selected-fg-color);\n}\n\n.tabbed-pane-header-tab.dragging {\n    position: relative;\n    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);\n    background-color: #e5e5e5;\n}\n\n.tabbed-pane-header-tab .tabbed-pane-close-button {\n    margin: 0 -3px 0 4px;\n    visibility: hidden;\n}\n\n.tabbed-pane-header-tab:hover .tabbed-pane-close-button,\n.tabbed-pane-header-tab.selected .tabbed-pane-close-button {\n    visibility: visible;\n}\n\n.tabbed-pane-header-tabs-drop-down-container {\n    float: left;\n    opacity: 0.8;\n    cursor: pointer;\n    display: flex;\n    align-items: center;\n    height: 100%;\n}\n\n.tabbed-pane-header-tabs-drop-down-container > .chevron-icon {\n    background-color: hsla(0,0%,20%,1);\n    display: block;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n    background-color: rgb(229, 229, 229);\n}\n\n.tabbed-pane-header-tabs-drop-down-container.measuring {\n    visibility: hidden;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n    opacity: 1.0;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:active {\n    opacity: 0.8;\n}\n\n/* Web page style */\n\n.tabbed-pane-shadow.vertical-tab-layout {\n    flex-direction: row !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header {\n    background-color: transparent;\n    border: none transparent !important;\n    width: auto;\n    flex: 0 0 auto;\n    flex-direction: column;\n    padding-top: 10px;\n    overflow: hidden;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-content {\n    padding: 10px 10px 10px 0;\n    overflow-x: hidden;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-contents {\n    margin: 0;\n    flex: none;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tabs {\n    display: flex;\n    flex-direction: column;\n    width: 120px;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab {\n    background-color: transparent;\n    border: none transparent;\n    font-weight: normal;\n    text-shadow: none;\n    color: #777;\n    height: 26px;\n    padding-left: 10px;\n    border-left: 6px solid transparent;\n    margin: 0;\n    display: flex;\n    align-items: center;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab:not(.selected) {\n    cursor: pointer !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab.selected {\n    color: inherit;\n    border: none transparent;\n    border-left: 6px solid #666;\n}\n\n.tabbed-pane-tab-slider {\n    height: 2px;\n    position: absolute;\n    bottom: -1px;\n    background-color: #03a9f4;\n    left: 0;\n    z-index: 50;\n    transform-origin: 0 100%;\n    transition: transform 150ms cubic-bezier(0, 0, 0.2, 1);\n    visibility: hidden;\n}\n\n:host-context(.-theme-with-dark-background) .tabbed-pane-tab-slider {\n    display: none;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n    .tabbed-pane-tab-slider {\n        border-top: none;\n    }\n}\n\n.tabbed-pane-tab-slider.enabled {\n    visibility: visible;\n}\n\n.tabbed-pane-header-tab.disabled {\n    opacity: 0.5;\n    pointer-events: none;\n}\n\n.tabbed-pane-left-toolbar {\n    margin-right: -4px;\n    flex: none;\n}\n\n.tabbed-pane-right-toolbar {\n    margin-left: -4px;\n    flex: none;\n}\n\n/*# sourceURL=ui/tabbedPane.css */";Runtime.cachedResources["ui/targetCrashedScreen.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.widget {\n    padding: 25px;\n}\n\n.message {\n    font-size: larger;\n    white-space: pre;\n    margin: 5px;\n}\n\n/*# sourceURL=ui/targetCrashedScreen.css */";Runtime.cachedResources["ui/textButton.css"]="/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    margin: 2px;\n    height: 24px;\n    font-size: 12px;\n    border: 1px solid rgba(0, 0, 0, 0.2);\n    border-radius: 2px;\n    padding: 0px 12px;\n    font-weight: 500;\n    color: #333;\n    background-color: #fff;\n    flex: none;\n    white-space: nowrap;\n}\n\n:host(:not(:disabled):focus),\n:host(:not(:disabled):hover),\n:host(:not(:disabled):active) {\n    background-color: var(--toolbar-bg-color);\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n    cursor: pointer;\n}\n\n:host(:not(:disabled):active) {\n    background-color: #f2f2f2;\n}\n\n:host(:not(:disabled):focus) {\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(66, 133, 244, 0.4);\n}\n\n:host(:disabled) {\n    opacity: 0.38;\n}\n\n:host(.primary-button), -theme-preserve {\n    background-color: #4285F4;\n    border: none;\n    color: #fff;\n}\n\n:host(.primary-button:not(:disabled):focus),\n:host(.primary-button:not(:disabled):hover), -theme-preserve {\n    background-color: #3B78E7;\n}\n\n:host(.primary-button:not(:disabled):active), -theme-preserve {\n    background-color: #3367D6;\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):focus),\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):hover),\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):active) {\n    background-color: #313131;\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):focus) {\n    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 0 2px rgba(94, 151, 246, 0.6);\n}\n\n:host-context(.-theme-with-dark-background):host(:not(.primary-button):not(:disabled):active) {\n    background-color: #3e3e3e;\n}\n\n/*# sourceURL=ui/textButton.css */";Runtime.cachedResources["ui/textPrompt.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.text-prompt-root {\n    display: flex;\n    align-items: center;\n}\n\n.text-prompt-editing {\n    box-shadow: var(--drop-shadow);\n    background-color: white;\n    text-overflow: clip !important;\n    padding-left: 2px;\n    margin-left: -2px;\n    padding-right: 2px;\n    margin-right: -2px;\n    margin-bottom: -1px;\n    padding-bottom: 1px;\n    opacity: 1.0 !important;\n}\n\n.text-prompt-editing,\n.text-prompt-editing ::content * {\n    color: #222 !important;\n    text-decoration: none !important;\n    white-space: pre;\n}\n\n::content .auto-complete-text {\n    color: rgb(128, 128, 128) !important;\n}\n\n::content .text-prompt[data-placeholder]:empty::before {\n    content: attr(data-placeholder);\n    color: rgb(128, 128, 128);\n}\n\n::content .text-prompt:not([data-placeholder]):empty::after {\n    content: '\\00A0';\n    width: 0;\n    display: block;\n}\n\n::content .text-prompt {\n    cursor: text;\n}\n\n::content .text-prompt.disabled {\n    opacity: 0.5;\n    cursor: default;\n}\n\n.text-prompt-editing ::content br {\n    display: none;\n}\n\n/*# sourceURL=ui/textPrompt.css */";Runtime.cachedResources["ui/tooltip.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tooltip {\n    background: hsl(0, 0%, 95%);\n    border-radius: 2px;\n    color: hsl(0, 0%, 20%);\n    padding: 5px 8px;\n    line-height: 14px;\n    display: flex;\n    align-items: center;\n    -webkit-filter: drop-shadow(0 1px 2px hsla(0, 0%, 0%, 0.3));\n    border: 1px solid hsla(0, 0%, 0%, 0.1);\n    background-clip: padding-box;\n    box-sizing: border-box;\n    position: absolute;\n    visibility: hidden;\n    transition: visibility 0s 100ms, opacity 150ms cubic-bezier(0, 0, .2, 1);\n    z-index: 20001;\n    top: 0;\n    left: 0;\n    opacity: 0;\n    text-overflow: ellipsis;\n    overflow: hidden;\n}\n\n.tooltip-breakword {\n    word-break: break-word;\n}\n\n.tooltip.shown {\n    visibility: visible;\n    transition-delay: 600ms;\n    opacity: 1;\n}\n\n.tooltip.shown.instant {\n    transition-delay: 0s;\n}\n\n.tooltip-shortcut {\n    color: hsl(0, 0%, 45%);\n    display: inline-block;\n    margin-left: 8px;\n    flex: 0 0 auto;\n}\n\n/*# sourceURL=ui/tooltip.css */";Runtime.cachedResources["ui/treeoutline.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    flex: 1 1;\n    padding: 2px 0 0 0;\n}\n\n.tree-outline-disclosure:not(.tree-outline-disclosure-hide-overflow) {\n    min-width: 100%;\n    display: inline-block;\n}\n\n.tree-outline {\n    padding: 0 0 4px 4px;\n    margin: 0;\n    z-index: 0;\n    position: relative;\n}\n\n.tree-outline li.hovered:not(.selected) .selection {\n    display: block;\n    left: 3px;\n    right: 3px;\n    background-color: rgba(56, 121, 217, 0.1);\n    border-radius: 5px;\n}\n\n.tree-outline li .selection {\n    display: none;\n    z-index: -1;\n    margin-left: -10000px;\n}\n\n.tree-outline li.selected .selection {\n    display: block;\n    background-color: var(--selection-inactive-bg-color);\n}\n\n.tree-outline li.in-clipboard .highlight {\n    outline: 1px dotted darkgrey;\n}\n\n.tree-outline li.elements-drag-over .selection {\n    display: block;\n    margin-top: -2px;\n    border-top: 2px solid;\n    border-top-color: var(--selection-bg-color);\n}\n\nol.tree-outline li.selected:focus .selection {\n    background-color: var(--selection-bg-color);\n}\n\nol.tree-outline li.parent.selected:focus::before {\n    background-color: var(--selection-fg-color);\n}\n\nol.tree-outline,\n.tree-outline ol {\n    list-style-type: none;\n}\n\n.tree-outline-no-padding {\n    padding: 0;\n}\n\n.tree-outline ol {\n    padding-left: 12px;\n}\n\n.tree-outline li {\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    position: relative;\n    display: flex;\n    align-items: center;\n    min-height: 16px;\n}\n\nol.tree-outline li.selected:focus {\n    color: var(--selection-fg-color);\n}\n\nol.tree-outline li.selected:focus * {\n    color: inherit;\n}\n\n.tree-outline li .icons-container {\n    align-self: center;\n    display: flex;\n    align-items: center;\n}\n\n.tree-outline li .leading-icons {\n    margin-right: 4px;\n}\n\n.tree-outline li .trailing-icons {\n    margin-left: 4px;\n}\n\n.tree-outline li::before {\n    -webkit-user-select: none;\n    -webkit-mask-image: url(Images/treeoutlineTriangles.png);\n    -webkit-mask-size: 32px 24px;\n    content: \"aa\";\n    color: transparent;\n    text-shadow: none;\n    margin-right: -2px;\n    height: 12px;\n}\n\n.tree-outline li:not(.parent)::before {\n    background-color: transparent;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.1) {\n.tree-outline li::before {\n    -webkit-mask-image: url(Images/treeoutlineTriangles_2x.png);\n}\n} /* media */\n\n.tree-outline li::before {\n    -webkit-mask-position: 0 0;\n    background-color: #727272;\n}\n\n.tree-outline li.parent.expanded::before {\n    -webkit-mask-position: -16px 0;\n}\n\n.tree-outline ol.children {\n    display: none;\n}\n\n.tree-outline ol.children.expanded {\n    display: block;\n}\n\n.tree-outline.tree-outline-dense li {\n    margin-top: 1px;\n    min-height: 12px;\n}\n\n.tree-outline.tree-outline-dense li.parent {\n    margin-top: 0;\n}\n\n.tree-outline.tree-outline-dense li.parent::before {\n    top: 0;\n}\n\n.tree-outline.tree-outline-dense ol {\n    padding-left: 10px;\n}\n\n/*# sourceURL=ui/treeoutline.css */";Runtime.cachedResources["ui/viewContainers.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.sidebar-hidden-override {\n    display: none !important;\n}\n\n.expandable-view-title {\n    display: flex;\n    align-items: center;\n    background-color: var(--toolbar-bg-color);\n    height: 22px;\n    padding: 0 5px;\n    border-top: var(--divider-border);\n    white-space: nowrap;\n    overflow: hidden;\n    position: relative;\n    border-bottom: 1px solid transparent;\n}\n\n.expandable-view-title.expanded,\n.expandable-view-title:last-child {\n    border-bottom: 1px solid #ddd;\n}\n\n.expandable-view-title .toolbar {\n    margin-top: -3px;\n}\n\n.expandable-view-title:not(.expanded) .toolbar {\n    display: none;\n}\n\n.title-expand-icon {\n    margin-right: 2px;\n    margin-bottom: -2px;\n}\n\n.expandable-view-title[data-keyboard-focus=\"true\"]:focus {\n    background-color: #e0e0e0;\n}\n\n.expandable-view-title > .toolbar {\n    position: absolute;\n    right: 0;\n    top: 0;\n}\n\n.sidebar-pane-container .toolbar {\n    border-bottom: 1px solid #eee;\n}\n\n.sidebar-pane-container .toolbar > * {\n    pointer-events: auto;\n}\n\n/*# sourceURL=ui/viewContainers.css */";Runtime.cachedResources["components/jsUtils.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n  display: inline;\n}\n\n.stack-preview-async-description {\n    padding: 3px 0 1px;\n    font-style: italic;\n}\n\n.stack-preview-container .webkit-html-blackbox-link {\n    opacity: 0.6;\n}\n\n.stack-preview-container > tr {\n    height: 16px;\n    line-height: 16px;\n}\n\n.stack-preview-container td {\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.stack-preview-container .function-name {\n    max-width: 80em;\n}\n\n.stack-preview-container:not(.show-blackboxed) > tr.blackboxed {\n    display: none;\n}\n\n.stack-preview-container.show-blackboxed > tr.show-blackboxed-link {\n    display: none;\n}\n\n.stack-preview-container > tr.show-blackboxed-link {\n    font-style: italic;\n}\n\n/*# sourceURL=components/jsUtils.css */";Runtime.cachedResources["persistence/editFileSystemView.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.file-system-header {\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n    flex: auto;\n    margin: 10px 0;\n}\n\n.file-system-header-text {\n    flex: 1 0 auto;\n}\n\n.add-button {\n    margin-left: 10px;\n    align-self: flex-start;\n}\n\n.file-system-list {\n    flex: auto;\n}\n\n.file-system-list-empty {\n    flex: auto;\n    height: 30px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    text-align: center;\n}\n\n.file-system-list-item {\n    padding: 3px 5px 3px 5px;\n    height: 30px;\n    display: flex;\n    align-items: center;\n    flex: auto 1 1;\n}\n\n.list-item .file-system-value {\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    -webkit-user-select: none;\n    overflow: hidden;\n}\n\n.file-system-value {\n    flex: 1 1 0px;\n}\n\n.file-system-edit-row {\n    flex: none;\n    display: flex;\n    flex-direction: row;\n    margin: 6px 5px;\n    align-items: center;\n}\n\n.file-system-edit-row input {\n    width: 100%;\n    text-align: inherit;\n}\n\n/*# sourceURL=persistence/editFileSystemView.css */";Runtime.cachedResources["persistence/workspaceSettingsTab.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\nheader {\n    padding: 0 0 6px;\n    border-bottom: 1px solid #EEEEEE;\n}\n\nheader > h3 {\n    font-size: 18px;\n    font-weight: normal;\n    margin: 0;\n    padding-bottom: 3px;\n}\n\n.settings-content {\n    overflow-y: auto;\n    overflow-x: hidden;\n    margin: 8px 8px 8px 0;\n    padding: 0 4px;\n    flex: auto;\n}\n\n.settings-container {\n    width: 100%;\n    -webkit-column-width: 288px;\n}\n\n\n.settings-tab.settings-container {\n    -webkit-column-width: 308px;\n}\n\n.settings-tab label {\n    padding-right: 4px;\n    display: inline-flex;\n}\n\n.settings-container-wrapper {\n    position: absolute;\n    top: 31px;\n    left: 0px;\n    right: 0;\n    bottom: 0;\n    overflow: auto;\n    padding-top: 9px;\n}\n\n.settings-tab.settings-content {\n    margin: 0;\n    padding: 0;\n}\n\n.settings-tab p {\n    margin: 12px 0;\n}\n\np.folder-exclude-pattern {\n    display: flex;\n    align-items: center;\n}\n\np.folder-exclude-pattern > input {\n    flex: auto;\n}\n\n.settings-tab .file-system-container {\n    border-top: 1px solid #aaa;\n    padding: 19px 0 10px;\n    margin: 20px 0;\n}\n\n.settings-tab .file-system-header {\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n}\n\n.settings-tab .file-system-name {\n    font-weight: bold;\n    flex: none;\n    margin-right: 10px;\n    font-size: 15px;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    max-width: 70%;\n}\n\n.settings-tab .file-system-path {\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    flex: auto;\n}\n\n.settings-info-message {\n    background-color: #eee;\n    padding: 10px;\n    margin: 20px 0;\n}\n\n.settings-tab.settings-content.settings-container {\n    -webkit-column-width: initial;\n    overflow: hidden;\n    padding-right: 10px;\n}\n\n/*# sourceURL=persistence/workspaceSettingsTab.css */";Runtime.cachedResources["product_registry/badge.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.product-registry-badge {\n  background-color: rgba(0, 0, 0, 0.2);\n  border-radius: 2px;\n  padding: 1px 2px;\n  white-space: pre;\n  cursor: pointer;\n}\n\n.product-registry-badge::before {\n  content: attr(data-initial);\n  color: #222;\n}\n\n.hide-badge-title .product-registry-badge-title {\n  display: none;\n}\n\n.product-registry-badge-title {\n  padding-left: 4px;\n}\n/*# sourceURL=product_registry/badge.css */";Runtime.cachedResources["product_registry/popup.css"]="/*\n * Copyright 2017 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.product-registry-popup {\n    background-color: white;\n    padding: 15px 45px 15px 15px;\n    border-radius: 4px;\n    white-space: nowrap;\n    box-shadow: 0px 1px 2px 0px gray;\n}\n\n.product-registry-domain {\n    font-weight: bold;\n}\n\n.product-registry-name {\n    padding: 10px 0;\n}\n\n.product-registry-link {\n    display: block;\n}\n\ndiv[is=dt-close-button] {\n  position: absolute;\n  top: 5px;\n  right: 5px;\n}\n\n/*# sourceURL=product_registry/popup.css */";Runtime.cachedResources["console_counters/errorWarningCounter.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n    cursor: pointer;\n    padding: 0 2px;\n    min-width: 26px;\n}\n\n:host:hover {\n    color: #333;\n}\n\n.counter-item {\n    margin-left: 6px;\n}\n\n.counter-item label {\n    cursor: inherit;\n}\n\n.counter-item.counter-item-first {\n    margin-left: 0;\n}\n\n/*# sourceURL=console_counters/errorWarningCounter.css */";