/*
 * Copyright (C) 2007-2021 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Matt Lilek. All rights reserved.
 * Copyright (C) 2008-2009 Anthony Ricaud <rik@webkit.org>
 * Copyright (C) 2009-2010 Joseph Pecoraro. All rights reserved.
 * Copyright (C) 2009-2011 Google Inc. All rights reserved.
 * Copyright (C) 2009 280 North Inc. All Rights Reserved.
 * Copyright (C) 2010 Nikita Vasilyev. All rights reserved.
 * Copyright (C) 2011 Brian Grinstead All rights reserved.
 * Copyright (C) 2013 Matt Holden <jftholden@yahoo.com>
 * Copyright (C) 2013 Samsung Electronics. All rights reserved.
 * Copyright (C) 2013 Seokju Kwon (seokju.kwon@gmail.com)
 * Copyright (C) 2013 Adobe Systems Inc. All rights reserved.
 * Copyright (C) 2013-2015 University of Washington. All rights reserved.
 * Copyright (C) 2014-2015 Saam Barati <saambarati1@gmail.com>
 * Copyright (C) 2014 Antoine Quint
 * Copyright (C) 2015 Tobias Reiss <tobi+webkit@basecode.de>
 * Copyright (C) 2015-2017 Devin Rousso <webkit@devinrousso.com>. All rights reserved.
 * Copyright (C) 2017 The Chromium Authors
 * Copyright (C) 2017-2018 Sony Interactive Entertainment Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
var WI={};WI.Platform={name:InspectorFrontendHost.platform,version:{name:InspectorFrontendHost.platformVersionName,}};



class Debouncer
{constructor(callback)
{this._callback=callback;this._lastArguments=[];this._timeoutIdentifier=undefined;this._animationFrameIdentifier=undefined;this._promiseIdentifier=undefined;} 
force()
{this._lastArguments=arguments;this._execute();}
delayForTime(time,...args)
{this.cancel();this._lastArguments=args;this._timeoutIdentifier=setTimeout(()=>{this._execute();},time);}
delayForFrame()
{this.cancel();this._lastArguments=arguments;this._animationFrameIdentifier=requestAnimationFrame(()=>{this._execute();});}
delayForMicrotask()
{this.cancel();this._lastArguments=arguments;let promiseIdentifier=Symbol("next-microtask");this._promiseIdentifier=promiseIdentifier;queueMicrotask(()=>{if(this._promiseIdentifier===promiseIdentifier)
this._execute();});}
cancel()
{this._lastArguments=[];if(this._timeoutIdentifier){clearTimeout(this._timeoutIdentifier);this._timeoutIdentifier=undefined;}
if(this._animationFrameIdentifier){cancelAnimationFrame(this._animationFrameIdentifier);this._animationFrameIdentifier=undefined;}
if(this._promiseIdentifier)
this._promiseIdentifier=undefined;} 
_execute()
{let args=this._lastArguments;this.cancel();this._callback.apply(undefined,args);}}
WI.DebuggableType={ITML:"itml",JavaScript:"javascript",Page:"page",ServiceWorker:"service-worker",WebPage:"web-page",};WI.DebuggableType.fromString=function(type){switch(type){case"itml":return WI.DebuggableType.ITML;case"javascript":return WI.DebuggableType.JavaScript;case"page":return WI.DebuggableType.Page;case"service-worker":return WI.DebuggableType.ServiceWorker;case"web-page":return WI.DebuggableType.WebPage;}
return null;};WI.DebuggableType.supportedTargetTypes=function(debuggableType){let targetTypes=new Set;switch(debuggableType){case WI.DebuggableType.ITML:targetTypes.add(WI.TargetType.ITML);break;case WI.DebuggableType.JavaScript:targetTypes.add(WI.TargetType.JavaScript);break;case WI.DebuggableType.Page:targetTypes.add(WI.TargetType.Page);targetTypes.add(WI.TargetType.Worker);break;case WI.DebuggableType.ServiceWorker:targetTypes.add(WI.TargetType.ServiceWorker);break;case WI.DebuggableType.WebPage:targetTypes.add(WI.TargetType.Page);targetTypes.add(WI.TargetType.WebPage);targetTypes.add(WI.TargetType.Worker);break;}
return targetTypes;};class Multimap
{constructor(items=[])
{this._map=new Map;for(let[key,value]of items)
this.add(key,value);} 
get size()
{return this._map.size;}
has(key,value)
{let valueSet=this._map.get(key);if(!valueSet)
return false;return value===undefined||valueSet.has(value);}
get(key)
{return this._map.get(key);}
add(key,value)
{let valueSet=this._map.get(key);if(!valueSet){valueSet=new Set;this._map.set(key,valueSet);}
valueSet.add(value);return this;}
delete(key,value)
{if(arguments.length===1)
return this._map.delete(key);let valueSet=this._map.get(key);if(!valueSet)
return false;let deleted=valueSet.delete(value);if(!valueSet.size)
this._map.delete(key);return deleted;}
take(key,value)
{if(arguments.length===1)
return this._map.take(key);let valueSet=this._map.get(key);if(!valueSet)
return undefined;let result=valueSet.take(value);if(!valueSet.size)
this._map.delete(key);return result;}
clear()
{this._map.clear();}
keys()
{return this._map.keys();}*values()
{for(let valueSet of this._map.values()){for(let value of valueSet)
yield value;}}
sets()
{return this._map.entries();}*[Symbol.iterator]()
{for(let[key,valueSet]of this._map){for(let value of valueSet)
yield[key,value];}}
copy()
{return new Multimap(this.toJSON());}
toJSON()
{return Array.from(this);}}
WI.Object=class WebInspectorObject
{constructor()
{this._listeners=null;} 
static addEventListener(eventType,listener,thisObject)
{thisObject??=this;let data={listener,thisObjectWeakRef:new WeakRef(thisObject),};WI.Object._listenerThisObjectFinalizationRegistry.register(thisObject,{eventTargetWeakRef:new WeakRef(this),eventType,data},data);this._listeners??=new Multimap;this._listeners.add(eventType,data);return listener;}
static singleFireEventListener(eventType,listener,thisObject)
{let eventTargetWeakRef=new WeakRef(this);return this.addEventListener(eventType,function wrappedCallback(){eventTargetWeakRef.deref()?.removeEventListener(eventType,wrappedCallback,this);listener.apply(this,arguments);},thisObject);}
static awaitEvent(eventType,thisObject)
{return new Promise((resolve,reject)=>{this.singleFireEventListener(eventType,resolve,thisObject);});}
static removeEventListener(eventType,listener,thisObject)
{if(!this._listeners)
return;thisObject??=this;let listenersForEventType=this._listeners.get(eventType);if(!listenersForEventType)
return;let didDelete=false;for(let data of listenersForEventType){let unwrapped=data.thisObjectWeakRef.deref();if(!unwrapped||unwrapped!==thisObject||data.listener!==listener)
continue;if(this._listeners.delete(eventType,data))
didDelete=true;WI.Object._listenerThisObjectFinalizationRegistry.unregister(data);}} 
addEventListener(){return WI.Object.addEventListener.apply(this,arguments);}
singleFireEventListener(){return WI.Object.singleFireEventListener.apply(this,arguments);}
awaitEvent(){return WI.Object.awaitEvent.apply(this,arguments);}
removeEventListener(){return WI.Object.removeEventListener.apply(this,arguments);}
dispatchEventToListeners(eventType,eventData)
{let event=new WI.Event(this,eventType,eventData);function dispatch(object)
{if(!object||event._stoppedPropagation)
return;let listeners=object._listeners;if(!listeners||!object.hasOwnProperty("_listeners")||!listeners.size)
return;let listenersForEventType=listeners.get(eventType);if(!listenersForEventType)
return;for(let data of Array.from(listenersForEventType)){let unwrapped=data.thisObjectWeakRef.deref();if(!unwrapped)
continue;data.listener.call(unwrapped,event);if(event._stoppedPropagation)
break;}}
dispatch(this);event._stoppedPropagation=false;let constructor=this.constructor;while(constructor){dispatch(constructor);if(!constructor.prototype.__proto__)
break;constructor=constructor.prototype.__proto__.constructor;}
return event.defaultPrevented;} 
static hasEventListeners(eventType)
{return this._listeners?.has(eventType);}
static activelyListeningObjectsWithPrototype(proto)
{let results=new Set;if(this._listeners){for(let data of this._listeners.values()){let unwrapped=data.thisObjectWeakRef.deref();if(unwrapped instanceof proto)
results.add(unwrapped);}}
return results;}
hasEventListeners(){return WI.Object.hasEventListeners.apply(this,arguments);}
activelyListeningObjectsWithPrototype(){return WI.Object.activelyListeningObjectsWithPrototype.apply(this,arguments);}};WI.Object._listenerThisObjectFinalizationRegistry=new FinalizationRegistry((heldValue)=>{heldValue.eventTargetWeakRef.deref()?._listeners.delete(heldValue.eventType,heldValue.data);});WI.Event=class Event
{constructor(target,type,data)
{this.target=target;this.type=type;this.data=data;this.defaultPrevented=false;this._stoppedPropagation=false;}
stopPropagation()
{this._stoppedPropagation=true;}
preventDefault()
{this.defaultPrevented=true;}};WI.notifications=new WI.Object;WI.Notification={GlobalModifierKeysDidChange:"global-modifiers-did-change",PageArchiveStarted:"page-archive-started",PageArchiveEnded:"page-archive-ended",ExtraDomainsActivated:"extra-domains-activated", VisibilityStateDidChange:"visibility-state-did-change",TransitionPageTarget:"transition-page-target",};WI.ReferencePage={DOMBreakpoints:"dom-breakpoints",EventBreakpoints:"event-breakpoints",JavaScriptBreakpoints:"javascript-breakpoints",LocalOverrides:"local-overrides",URLBreakpoints:"url-breakpoints",};WI.TargetType={ITML:"itml",JavaScript:"javascript",Page:"page",ServiceWorker:"service-worker",WebPage:"web-page",Worker:"worker",};WI.TargetType.all=Object.values(WI.TargetType);


class Throttler
{constructor(callback,delay)
{this._callback=callback;this._delay=delay;this._lastArguments=[];this._timeoutIdentifier=undefined;this._lastFireTime=-this._delay;} 
force()
{this._lastArguments=arguments;this._execute();}
fire()
{this._lastArguments=arguments;let remaining=this._delay-(Date.now()-this._lastFireTime);if(remaining<=0){this._execute();return;}
if(this._timeoutIdentifier)
return;this._timeoutIdentifier=setTimeout(()=>{this._execute();},remaining);}
cancel()
{this._lastArguments=[];if(this._timeoutIdentifier){clearTimeout(this._timeoutIdentifier);this._timeoutIdentifier=undefined;}} 
_execute()
{this._lastFireTime=Date.now();let args=this._lastArguments;this.cancel();this._callback.apply(undefined,args);}}
WI.BlobUtilities=class BlobUtilities{static blobForContent(content,base64Encoded,mimeType)
{if(base64Encoded)
return BlobUtilities.decodeBase64ToBlob(content,mimeType);return BlobUtilities.textToBlob(content,mimeType);}
static decodeBase64ToBlob(base64Data,mimeType)
{mimeType=mimeType||"";const sliceSize=1024;let byteCharacters=atob(base64Data);let bytesLength=byteCharacters.length;let slicesCount=Math.ceil(bytesLength/sliceSize);let byteArrays=new Array(slicesCount);for(let sliceIndex=0;sliceIndex<slicesCount;++sliceIndex){let begin=sliceIndex*sliceSize;let end=Math.min(begin+sliceSize,bytesLength);let bytes=new Array(end-begin);for(let offset=begin,i=0;offset<end;++i,++offset)
bytes[i]=byteCharacters[offset].charCodeAt(0);byteArrays[sliceIndex]=new Uint8Array(bytes);}
return new Blob(byteArrays,{type:mimeType});}
static textToBlob(text,mimeType)
{return new Blob([text],{type:mimeType});}
static blobAsText(blob,callback)
{let fileReader=new FileReader;fileReader.addEventListener("loadend",()=>{callback(fileReader.result);});fileReader.readAsText(blob);}};WI.roleSelectorForNode=function(node)
{ var title="";var role=node.computedRole();if(role)
title=":role("+role+")";return title;};WI.linkifyAccessibilityNodeReference=function(node)
{if(!node)
return null;var link=WI.linkifyNodeReference(node);var tagIdSelector=link.title;var classSelectorIndex=tagIdSelector.indexOf(".");if(classSelectorIndex>-1)
tagIdSelector=tagIdSelector.substring(0,classSelectorIndex);var roleSelector=WI.roleSelectorForNode(node);link.textContent=tagIdSelector+roleSelector;link.title+=roleSelector;return link;};WI.linkifyNodeReference=function(node,options={})
{let displayName=node.displayName;if(!isNaN(options.maxLength))
displayName=displayName.truncate(options.maxLength);let link=document.createElement("span");link.append(displayName);return WI.linkifyNodeReferenceElement(node,link,{...options,displayName});};WI.linkifyNodeReferenceElement=function(node,element,options={})
{element.setAttribute("role","link");element.title=options.displayName||node.displayName;let nodeType=node.nodeType();if((nodeType!==Node.DOCUMENT_NODE||node.parentNode)&&nodeType!==Node.TEXT_NODE)
element.classList.add("node-link");WI.bindInteractionsForNodeToElement(node,element,options);return element;};WI.bindInteractionsForNodeToElement=function(node,element,options={}){if(!options.ignoreClick){element.addEventListener("click",(event)=>{WI.domManager.inspectElement(node.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});}
element.addEventListener("mouseover",(event)=>{node.highlight();});element.addEventListener("mouseout",(event)=>{WI.domManager.hideDOMNodeHighlight();});element.addEventListener("contextmenu",(event)=>{let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNode(contextMenu,node,options);});};function createSVGElement(tagName)
{return document.createElementNS("http://www.w3.org/2000/svg",tagName);}
WI.cssPath=function(node,options={})
{if(node.nodeType()!==Node.ELEMENT_NODE)
return"";let suffix="";if(node.isPseudoElement()){suffix="::"+node.pseudoType();node=node.parentNode;}
let components=[];while(node){let component=WI.cssPathComponent(node,options);if(!component)
break;components.push(component);if(component.done)
break;node=node.parentNode;}
components.reverse();return components.map((x)=>x.value).join(" > ")+suffix;};WI.cssPathComponent=function(node,options={})
{if(node.nodeType()!==Node.ELEMENT_NODE)
return null;let nodeName=node.nodeNameInCorrectCase();if(!node.parentNode||node.parentNode.nodeType()===Node.DOCUMENT_NODE)
return{value:nodeName,done:true};if(options.full){function getUniqueAttributes(domNode){let uniqueAttributes=new Map;for(let attribute of domNode.attributes()){let values=[attribute.value];if(attribute.name==="id"||attribute.name==="class")
values=attribute.value.split(/\s+/);uniqueAttributes.set(attribute.name,new Set(values));}
return uniqueAttributes;}
let nodeIndex=0;let needsNthChild=false;let uniqueAttributes=getUniqueAttributes(node);node.parentNode.children.forEach((child,i)=>{if(child.nodeType()!==Node.ELEMENT_NODE)
return;if(child===node){nodeIndex=i;return;}
if(needsNthChild||child.nodeNameInCorrectCase()!==nodeName)
return;let childUniqueAttributes=getUniqueAttributes(child);let subsetCount=0;for(let[name,values]of uniqueAttributes){let childValues=childUniqueAttributes.get(name);if(childValues&&values.size<=childValues.size&&values.isSubsetOf(childValues))
++subsetCount;}
if(subsetCount===uniqueAttributes.size)
needsNthChild=true;});function selectorForAttribute(values,prefix="",shouldCSSEscape=false){if(!values||!values.size)
return"";values=Array.from(values);values=values.filter((value)=>value&&value.length);if(!values.length)
return"";values=values.map((value)=>shouldCSSEscape?CSS.escape(value):value.escapeCharacters("\""));return prefix+values.join(prefix);}
let selector=nodeName;selector+=selectorForAttribute(uniqueAttributes.get("id"),"#",true);selector+=selectorForAttribute(uniqueAttributes.get("class"),".",true);for(let[attribute,values]of uniqueAttributes){if(attribute!=="id"&&attribute!=="class")
selector+=`[${attribute}="${selectorForAttribute(values)}"]`;}
if(needsNthChild)
selector+=`:nth-child(${nodeIndex + 1})`;return{value:selector,done:false};}
let lowerNodeName=node.nodeName().toLowerCase();if(lowerNodeName==="body"||lowerNodeName==="head"||lowerNodeName==="html")
return{value:nodeName,done:true};let id=node.getAttribute("id");if(id)
return{value:node.escapedIdSelector,done:true};

function classNames(node){let classAttribute=node.getAttribute("class");return classAttribute?classAttribute.trim().split(/\s+/):[];}
let nthChildIndex=-1;let hasUniqueTagName=true;let uniqueClasses=new Set(classNames(node));let siblings=node.parentNode.children;let elementIndex=0;for(let sibling of siblings){if(sibling.nodeType()!==Node.ELEMENT_NODE)
continue;elementIndex++;if(sibling===node){nthChildIndex=elementIndex;continue;}
if(sibling.nodeNameInCorrectCase()===nodeName)
hasUniqueTagName=false;if(uniqueClasses.size){let siblingClassNames=classNames(sibling);for(let className of siblingClassNames)
uniqueClasses.delete(className);}}
let selector=nodeName;if(lowerNodeName==="input"&&node.getAttribute("type")&&!uniqueClasses.size)
selector+=`[type="${node.getAttribute("type")}"]`;if(!hasUniqueTagName){if(uniqueClasses.size)
selector+=node.escapedClassSelector;else
selector+=`:nth-child(${nthChildIndex})`;}
return{value:selector,done:false};};WI.xpath=function(node)
{if(node.nodeType()===Node.DOCUMENT_NODE)
return"/";let components=[];while(node){let component=WI.xpathComponent(node);if(!component)
break;components.push(component);if(component.done)
break;node=node.parentNode;}
components.reverse();let prefix=components.length&&components[0].done?"":"/";return prefix+components.map((x)=>x.value).join("/");};WI.xpathComponent=function(node)
{let index=WI.xpathIndex(node);if(index===-1)
return null;let value;switch(node.nodeType()){case Node.DOCUMENT_NODE:return{value:"",done:true};case Node.ELEMENT_NODE:var id=node.getAttribute("id");if(id)
return{value:`//*[@id="${id}"]`,done:true};value=node.localName();break;case Node.ATTRIBUTE_NODE:value=`@${node.nodeName()}`;break;case Node.TEXT_NODE:case Node.CDATA_SECTION_NODE:value="text()";break;case Node.COMMENT_NODE:value="comment()";break;case Node.PROCESSING_INSTRUCTION_NODE:value="processing-instruction()";break;default:value="";break;}
if(index>0)
value+=`[${index}]`;return{value,done:false};};WI.xpathIndex=function(node)
{if(!node.parentNode)
return 0;let siblings=node.parentNode.children;if(siblings.length<=1)
return 0;
 function isSimiliarNode(a,b){if(a===b)
return true;let aType=a.nodeType();let bType=b.nodeType();if(aType===Node.ELEMENT_NODE&&bType===Node.ELEMENT_NODE)
return a.localName()===b.localName();if(aType===Node.CDATA_SECTION_NODE)
return aType===Node.TEXT_NODE;if(bType===Node.CDATA_SECTION_NODE)
return bType===Node.TEXT_NODE;return aType===bType;}
let unique=true;let xPathIndex=-1;let xPathIndexCounter=1;for(let sibling of siblings){if(!isSimiliarNode(node,sibling))
continue;if(node===sibling){xPathIndex=xPathIndexCounter;if(!unique)
return xPathIndex;}else{unique=false;if(xPathIndex!==-1)
return xPathIndex;}
xPathIndexCounter++;}
if(unique)
return 0;return xPathIndex;};WI.FileUtilities=class FileUtilities{static screenshotString()
{let date=new Date;let values=[date.getFullYear(),Number.zeroPad(date.getMonth()+1,2),Number.zeroPad(date.getDate(),2),Number.zeroPad(date.getHours(),2),Number.zeroPad(date.getMinutes(),2),Number.zeroPad(date.getSeconds(),2),];return WI.UIString("Screen Shot %s-%s-%s at %s.%s.%s").format(...values);}
static sanitizeFilename(filename)
{return filename.replace(/:+/g,"-");}
static inspectorURLForFilename(filename)
{return"web-inspector:///"+encodeURIComponent(FileUtilities.sanitizeFilename(filename));}
static save(saveData,forceSaveAs)
{if(!saveData)
return;if(typeof saveData.customSaveHandler==="function"){saveData.customSaveHandler(forceSaveAs);return;}
if(!saveData.content)
return;let suggestedName=saveData.suggestedName;if(!suggestedName){let url=saveData.url||"";suggestedName=parseURL(url).lastPathComponent;if(!suggestedName){suggestedName=WI.UIString("Untitled");let dataURLTypeMatch=/^data:([^;]+)/.exec(url);if(dataURLTypeMatch){let fileExtension=WI.fileExtensionForMIMEType(dataURLTypeMatch[1]);if(fileExtension)
suggestedName+="."+fileExtension;}}}
suggestedName=FileUtilities.inspectorURLForFilename(suggestedName);if(typeof saveData.content==="string"){const base64Encoded=saveData.base64Encoded||false;InspectorFrontendHost.save(suggestedName,saveData.content,base64Encoded,forceSaveAs||saveData.forceSaveAs);return;}
let fileReader=new FileReader;fileReader.addEventListener("loadend",()=>{let dataURLComponents=parseDataURL(fileReader.result);const base64Encoded=true;InspectorFrontendHost.save(suggestedName,dataURLComponents.data,base64Encoded,forceSaveAs||saveData.forceSaveAs);});fileReader.readAsDataURL(saveData.content);}
static import(callback,{multiple}={})
{let inputElement=document.createElement("input");inputElement.type="file";inputElement.value=null;inputElement.multiple=!!multiple;inputElement.addEventListener("change",(event)=>{callback(inputElement.files);});inputElement.click();
FileUtilities.importInputElement=inputElement;}
static importText(callback,options={})
{FileUtilities.import((files)=>{FileUtilities.readText(files,callback);},options);}
static importJSON(callback,options={})
{FileUtilities.import((files)=>{FileUtilities.readJSON(files,callback);},options);}
static importData(callback,options={})
{FileUtilities.import((files)=>{FileUtilities.readData(files,callback);},options);}
static async readText(fileOrList,callback)
{await FileUtilities._read(fileOrList,async(file,result)=>{await new Promise((resolve,reject)=>{let reader=new FileReader;reader.addEventListener("loadend",(event)=>{result.text=reader.result;resolve(event);});reader.addEventListener("error",reject);reader.readAsText(file);});},callback);}
static async readJSON(fileOrList,callback)
{await WI.FileUtilities.readText(fileOrList,async(result)=>{if(result.text&&!result.error){try{result.json=JSON.parse(result.text);}catch(e){result.error=e;}}
await callback(result);});}
static async readData(fileOrList,callback)
{await FileUtilities._read(fileOrList,async(file,result)=>{await new Promise((resolve,reject)=>{let reader=new FileReader;reader.addEventListener("loadend",(event)=>{let{mimeType,base64,data}=parseDataURL(reader.result);if(!mimeType||mimeType==="text/plain"){let extension=WI.fileExtensionForFilename(result.filename);if(extension)
mimeType=WI.mimeTypeForFileExtension(extension);}
result.mimeType=mimeType;result.base64Encoded=base64;result.content=data;resolve(event);});reader.addEventListener("error",reject);reader.readAsDataURL(file);});},callback);} 
static async _read(fileOrList,operation,callback)
{let files=[];if(fileOrList instanceof File)
files.push(fileOrList);else if(fileOrList instanceof FileList)
files=Array.from(fileOrList);for(let file of files){let result={filename:file.name,};try{await operation(file,result);}catch(e){result.error=e;}
await callback(result);}}};WI.HTTPUtilities=class HTTPUtilities{static statusTextForStatusCode(code)
{switch(code){case 0:return"OK";case 100:return"Continue";case 101:return"Switching Protocols";case 200:return"OK";case 201:return"Created";case 202:return"Accepted";case 203:return"Non-Authoritative Information";case 204:return"No Content";case 205:return"Reset Content";case 206:return"Partial Content";case 207:return"Multi-Status";case 300:return"Multiple Choices";case 301:return"Moved Permanently";case 302:return"Found";case 303:return"See Other";case 304:return"Not Modified";case 305:return"Use Proxy";case 307:return"Temporary Redirect";case 308:return"Permanent Redirect";case 400:return"Bad Request";case 401:return"Unauthorized";case 402:return"Payment Required";case 403:return"Forbidden";case 404:return"Not Found";case 405:return"Method Not Allowed";case 406:return"Not Acceptable";case 407:return"Proxy Authentication Required";case 408:return"Request Time-out";case 409:return"Conflict";case 410:return"Gone";case 411:return"Length Required";case 412:return"Precondition Failed";case 413:return"Request Entity Too Large";case 414:return"Request-URI Too Large";case 415:return"Unsupported Media Type";case 416:return"Requested range not satisfiable";case 417:return"Expectation Failed";case 500:return"Internal Server Error";case 501:return"Not Implemented";case 502:return"Bad Gateway";case 503:return"Service Unavailable";case 504:return"Gateway Time-out";case 505:return"HTTP Version not supported";}
if(code<200)
return"Continue";if(code<300)
return"OK";if(code<400)
return"Multiple Choices";if(code<500)
return"Bad Request";return"Internal Server Error";}};WI.HTTPUtilities.RequestMethod={CONNECT:"CONNECT",DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST",PUT:"PUT",TRACE:"TRACE",};WI.HTTPUtilities.RequestMethodsWithBody=new Set([WI.HTTPUtilities.RequestMethod.DELETE,WI.HTTPUtilities.RequestMethod.PATCH,WI.HTTPUtilities.RequestMethod.POST,WI.HTTPUtilities.RequestMethod.PUT,]);WI.ImageUtilities=class ImageUtilities{static useSVGSymbol(url,className,title)
{const svgNamespace="http://www.w3.org/2000/svg";const xlinkNamespace="http://www.w3.org/1999/xlink";let svgElement=document.createElementNS(svgNamespace,"svg");svgElement.style.width="100%";svgElement.style.height="100%";
if(!url.includes("#"))
url+="#root";let useElement=document.createElementNS(svgNamespace,"use");useElement.setAttributeNS(xlinkNamespace,"xlink:href",url);svgElement.appendChild(useElement);let wrapper=document.createElement("div");wrapper.appendChild(svgElement);if(className)
wrapper.className=className;if(title)
wrapper.title=title;return wrapper;}
static promisifyLoad(src)
{return new Promise((resolve,reject)=>{let image=new Image;let resolveWithImage=()=>{resolve(image);};image.addEventListener("load",resolveWithImage);image.addEventListener("error",resolveWithImage);image.src=src;});}
static scratchCanvasContext2D(callback)
{if(!WI.ImageUtilities._scratchContext2D)
WI.ImageUtilities._scratchContext2D=document.createElement("canvas").getContext("2d");let context=WI.ImageUtilities._scratchContext2D;context.clearRect(0,0,context.canvas.width,context.canvas.height);context.save();callback(context);context.restore();}
static imageFromImageBitmap(data)
{let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=data.width;context.canvas.height=data.height;context.drawImage(data,0,0);image=new Image;image.src=context.canvas.toDataURL();});return image;}
static imageFromImageData(data)
{let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=data.width;context.canvas.height=data.height;context.putImageData(data,0,0);image=new Image;image.src=context.canvas.toDataURL();});return image;}
static imageFromCanvasGradient(gradient,width,height)
{let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=width;context.canvas.height=height;context.fillStyle=gradient;context.fillRect(0,0,width,height);image=new Image;image.src=context.canvas.toDataURL();});return image;}
static supportsCanvasPathDebugging()
{return"getPath"in CanvasRenderingContext2D.prototype&&"setPath"in CanvasRenderingContext2D.prototype&&"currentX"in CanvasRenderingContext2D.prototype&&"currentY"in CanvasRenderingContext2D.prototype;}};WI.ImageUtilities._scratchContext2D=null;(function(){if(WI.dontLocalizeUserInterface)
return;let localizedStringsURL=InspectorFrontendHost.localizedStringsURL;if(localizedStringsURL)
document.write("<script src=\""+localizedStringsURL+"\"></script>");})();WI.unlocalizedString=function(string)
{
return string;};WI.UIString=function(string,key,comment)
{"use strict";if(WI.dontLocalizeUserInterface)
return string;if(arguments.length===2){comment=key;key=undefined;}
key=key||string;if(window.localizedStrings&&key in window.localizedStrings)
return window.localizedStrings[key];if(!window.localizedStrings)
console.error(`Attempted to load localized string "${key}" before localizedStrings was initialized.`,comment);if(!this._missingLocalizedStrings)
this._missingLocalizedStrings={};if(!(key in this._missingLocalizedStrings)){console.error(`Localized string "${key}" was not found.`,comment);this._missingLocalizedStrings[key]=true;}
return"LOCALIZED STRING NOT FOUND";};WI.repeatedUIString={};WI.repeatedUIString.timelineRecordLayout=function(){return WI.UIString("Layout","Layout @ Timeline record","Layout phase timeline records");};WI.repeatedUIString.timelineRecordPaint=function(){return WI.UIString("Paint","Paint @ Timeline record","Paint (render) phase timeline records");};WI.repeatedUIString.timelineRecordComposite=function(){return WI.UIString("Composite","Composite @ Timeline record","Composite phase timeline records, where graphic layers are combined");};WI.repeatedUIString.debuggerStatements=function(){return WI.UIString("Debugger Statements","Debugger Statements @ JavaScript Breakpoint","Break (pause) on debugger statements");};WI.repeatedUIString.allExceptions=function(){return WI.UIString("All Exceptions","All Exceptions @ JavaScript Breakpoint","Break (pause) on all exceptions");};WI.repeatedUIString.uncaughtExceptions=function(){return WI.UIString("Uncaught Exceptions","Uncaught Exceptions @ JavaScript Breakpoint","Break (pause) on uncaught (unhandled) exceptions");};WI.repeatedUIString.assertionFailures=function(){return WI.UIString("Assertion Failures","Assertion Failures @ JavaScript Breakpoint","Break (pause) when console.assert() fails");};WI.repeatedUIString.allMicrotasks=function(){return WI.UIString("All Microtasks","All Microtasks @ JavaScript Breakpoint","Break (pause) on all microtasks");};WI.repeatedUIString.allAnimationFrames=function(){return WI.UIString("All Animation Frames","All Animation Frames @ Event Breakpoint","Break (pause) on All animation frames");};WI.repeatedUIString.allIntervals=function(){return WI.UIString("All Intervals","All Intervals @ Event Breakpoint","Break (pause) on all intervals");};WI.repeatedUIString.allEvents=function(){return WI.UIString("All Events","All Events @ Event Breakpoint","Break (pause) on all events");};WI.repeatedUIString.allTimeouts=function(){return WI.UIString("All Timeouts","All Timeouts @ Event Breakpoint","Break (pause) on all timeouts");};WI.repeatedUIString.allRequests=function(){return WI.UIString("All Requests","A submenu item of 'Break on' that breaks (pauses) before all network requests");};WI.repeatedUIString.fetch=function(){return WI.UIString("Fetch","Resource loaded via 'fetch' method");};WI.repeatedUIString.revealInDOMTree=function(){return WI.UIString("Reveal in DOM Tree","Open Elements tab and select this node in DOM tree");};WI.repeatedUIString.showTransparencyGridTooltip=function(){return WI.UIString("Show transparency grid","Show transparency grid (tooltip)","Tooltip for showing the checkered transparency grid under images and canvases")};WI.fileExtensionForFilename=function(filename)
{if(!filename)
return null;let index=filename.lastIndexOf(".");if(index===-1)
return null;if(index===filename.length-1)
return null;return filename.substr(index+1);};WI.fileExtensionForURL=function(url)
{let lastPathComponent=parseURL(url).lastPathComponent;return WI.fileExtensionForFilename(lastPathComponent);};WI.mimeTypeForFileExtension=function(extension)
{const extensionToMIMEType={"html":"text/html","xhtml":"application/xhtml+xml","xml":"text/xml","js":"text/javascript","mjs":"text/javascript","json":"application/json","clj":"text/x-clojure","coffee":"text/x-coffeescript","ls":"text/x-livescript","ts":"text/typescript","ps":"application/postscript","jsx":"text/jsx","css":"text/css","less":"text/x-less","sass":"text/x-sass","scss":"text/x-scss","bmp":"image/bmp","gif":"image/gif","jpeg":"image/jpeg","jpg":"image/jpeg","pdf":"application/pdf","png":"image/png","tif":"image/tiff","tiff":"image/tiff","xbm":"image/x-xbitmap","webp":"image/webp","ico":"image/x-icon","ogx":"application/ogg","ogg":"audio/ogg","oga":"audio/ogg","ogv":"video/ogg","anx":"application/annodex","axa":"audio/annodex","axv":"video/annodex","spx":"audio/speex","webm":"video/webm","m1a":"audio/mpeg","m2a":"audio/mpeg","mpg":"video/mpeg","m15":"video/mpeg","m1s":"video/mpeg","m1v":"video/mpeg","m75":"video/mpeg","mpa":"video/mpeg","mpeg":"video/mpeg","mpm":"video/mpeg","mpv":"video/mpeg","m3u8":"application/x-mpegurl","m3url":"audio/x-mpegurl","m3u":"audio/x-mpegurl","m4v":"video/x-m4v","m4a":"audio/x-m4a","m4b":"audio/x-m4b","m4p":"audio/x-m4p","mp3":"audio/mp3","mp2":"video/x-mpeg2","vob":"video/mpeg2","mod":"video/mpeg2","m2ts":"video/m2ts","m2t":"video/x-m2ts","3gpp":"audio/3gpp","3g2":"audio/3gpp2","amc":"application/x-mpeg","aac":"audio/aac","adts":"audio/aac","m4r":"audio/x-aac","caf":"audio/x-caf","gsm":"audio/x-gsm","wav":"audio/x-wav","vtt":"text/vtt","woff":"font/woff","woff2":"font/woff2","otf":"font/otf","ttf":"font/ttf","sfnt":"font/sfnt","svg":"image/svg+xml","txt":"text/plain","xsl":"text/xsl"};return extensionToMIMEType[extension]||null;};WI.fileExtensionForMIMEType=function(mimeType)
{if(!mimeType)
return null;const mimeTypeToExtension={"text/html":"html","application/xhtml+xml":"xhtml","application/xml":"xml","text/xml":"xml","application/ecmascript":"js","application/javascript":"js","application/x-ecmascript":"js","application/x-javascript":"js","text/ecmascript":"js","text/javascript":"js","text/javascript1.0":"js","text/javascript1.1":"js","text/javascript1.2":"js","text/javascript1.3":"js","text/javascript1.4":"js","text/javascript1.5":"js","text/jscript":"js","text/x-ecmascript":"js","text/x-javascript":"js","application/json":"json","text/x-clojure":"clj","text/x-coffeescript":"coffee","text/livescript":"ls","text/x-livescript":"ls","text/typescript":"ts","application/postscript":"ps","text/jsx":"jsx","text/css":"css","text/x-less":"less","text/x-sass":"sass","text/x-scss":"scss","image/bmp":"bmp","image/gif":"gif","image/jp2":"jp2","image/jpeg":"jpg","application/pdf":"pdf","text/pdf":"pdf","image/png":"png","image/tiff":"tiff","image/x-xbitmap":"xbm","image/webp":"webp","image/vnd.microsoft.icon":"ico","image/x-icon":"ico","application/ogg":"ogx","audio/ogg":"ogg","application/annodex":"anx","audio/annodex":"axa","video/annodex":"axv","audio/speex":"spx","video/webm":"webm","audio/webm":"webm","video/mpeg":"mpeg","application/vnd.apple.mpegurl":"m3u8","application/mpegurl":"m3u8","application/x-mpegurl":"m3u8","audio/mpegurl":"m3u","audio/x-mpegurl":"m3u","video/x-m4v":"m4v","audio/x-m4a":"m4a","audio/x-m4b":"m4b","audio/x-m4p":"m4p","audio/mp4":"m4a","audio/mp3":"mp3","audio/x-mp3":"mp3","audio/x-mpeg":"mp3","video/x-mpeg2":"mp2","video/mpeg2":"vob","video/m2ts":"m2ts","video/x-m2ts":"m2t","audio/3gpp":"3gpp","audio/3gpp2":"3g2","application/x-mpeg":"amc","audio/aac":"aac","audio/x-aac":"m4r","audio/x-caf":"caf","audio/x-gsm":"gsm","audio/x-wav":"wav","audio/vnd.wave":"wav","text/vtt":"vtt","font/woff":"woff","font/woff2":"woff2","font/otf":"otf","font/ttf":"ttf","font/sfnt":"sfnt","image/svg+xml":"svg","text/plain":"txt","text/xsl":"xsl",};let extension=mimeTypeToExtension[mimeType];if(extension)
return extension;if(mimeType.endsWith("+json"))
return"json";if(mimeType.endsWith("+xml"))
return"xml";return null;};WI.shouldTreatMIMETypeAsText=function(mimeType)
{if(!mimeType)
return false;if(mimeType.startsWith("text/"))
return true;if(mimeType.endsWith("+json")||mimeType.endsWith("+xml"))
return true;let extension=WI.fileExtensionForMIMEType(mimeType);if(extension==="xml")
return true;if(extension==="js"||extension==="json")
return true;if(extension==="m3u8"||extension==="m3u")
return true;if(mimeType.startsWith("application/"))
return mimeType.endsWith("script")||mimeType.endsWith("json")||mimeType.endsWith("xml");return false;};WI.ObjectStore=class ObjectStore
{constructor(name,options={})
{this._name=name;this._options=options;} 
static supported()
{return(!window.InspectorTest||WI.ObjectStore.__testObjectStore)&&window.indexedDB;}
static async reset()
{if(WI.ObjectStore._database)
WI.ObjectStore._database.close();await window.indexedDB.deleteDatabase(ObjectStore._databaseName);}
static get _databaseName()
{let inspectionLevel=InspectorFrontendHost?InspectorFrontendHost.inspectionLevel:1;let levelString=(inspectionLevel>1)?"-"+inspectionLevel:"";return"com.apple.WebInspector"+levelString;}
static _open(callback)
{if(WI.ObjectStore._database){callback(WI.ObjectStore._database);return;}
if(Array.isArray(WI.ObjectStore._databaseCallbacks)){WI.ObjectStore._databaseCallbacks.push(callback);return;}
WI.ObjectStore._databaseCallbacks=[callback];const version=5;let databaseRequest=window.indexedDB.open(WI.ObjectStore._databaseName,version);databaseRequest.addEventListener("upgradeneeded",(event)=>{let database=databaseRequest.result;let objectStores=Object.values(WI.objectStores);if(WI.ObjectStore.__testObjectStore)
objectStores.push(WI.ObjectStore.__testObjectStore);let existingNames=new Set;for(let objectStore of objectStores){if(!database.objectStoreNames.contains(objectStore._name))
database.createObjectStore(objectStore._name,objectStore._options);existingNames.add(objectStore._name);}
for(let objectStoreName of database.objectStoreNames){if(!existingNames.has(objectStoreName))
database.deleteObjectStore(objectStoreName);}});databaseRequest.addEventListener("success",(successEvent)=>{WI.ObjectStore._database=databaseRequest.result;WI.ObjectStore._database.addEventListener("close",(closeEvent)=>{WI.ObjectStore._database=null;});for(let databaseCallback of WI.ObjectStore._databaseCallbacks)
databaseCallback(WI.ObjectStore._database);WI.ObjectStore._databaseCallbacks=null;});} 
get keyPath()
{return(this._options||{}).keyPath;}
associateObject(object,key,value)
{if(typeof value==="object")
value=this._resolveKeyPath(value,key).value;let resolved=this._resolveKeyPath(object,key);resolved.object[resolved.key]=value;}
async get(...args)
{if(!WI.ObjectStore.supported())
return undefined;return this._operation("readonly",(objectStore)=>objectStore.get(...args));}
async getAll(...args)
{if(!WI.ObjectStore.supported())
return[];return this._operation("readonly",(objectStore)=>objectStore.getAll(...args));}
async put(...args)
{if(!WI.ObjectStore.supported())
return undefined;return this._operation("readwrite",(objectStore)=>objectStore.put(...args));}
async putObject(object,...args)
{if(!WI.ObjectStore.supported())
return undefined;let result=await this.put(object.toJSON(WI.ObjectStore.toJSONSymbol),...args);this.associateObject(object,args[0],result);return result;}
async delete(...args)
{if(!WI.ObjectStore.supported())
return undefined;return this._operation("readwrite",(objectStore)=>objectStore.delete(...args));}
async deleteObject(object,...args)
{if(!WI.ObjectStore.supported())
return undefined;return this.delete(this._resolveKeyPath(object).value,...args);}
async clear(...args)
{if(!WI.ObjectStore.supported())
return undefined;return this._operation("readwrite",(objectStore)=>objectStore.clear(...args));} 
_resolveKeyPath(object,keyPath)
{keyPath=keyPath||this._options.keyPath||"";let parts=keyPath.split(".");let key=parts.splice(-1,1);while(parts.length){if(!object.hasOwnProperty(parts[0]))
break;object=object[parts.shift()];}
if(parts.length)
key=parts.join(".")+"."+key;return{object,key,value:object[key],};}
async _operation(mode,func)
{
return new Promise((resolve,reject)=>{WI.ObjectStore._open((database)=>{let transaction=database.transaction([this._name],mode);let objectStore=transaction.objectStore(this._name);let request=null;try{request=func(objectStore);}catch(e){reject(e);return;}
function listener(event){transaction.removeEventListener("complete",listener);transaction.removeEventListener("error",listener);request.removeEventListener("success",listener);request.removeEventListener("error",listener);if(request.error){reject(request.error);return;}
resolve(request.result);}
transaction.addEventListener("complete",listener,{once:true});transaction.addEventListener("error",listener,{once:true});request.addEventListener("success",listener,{once:true});request.addEventListener("error",listener,{once:true});});});}};WI.ObjectStore._database=null;WI.ObjectStore._databaseCallbacks=null;WI.ObjectStore.toJSONSymbol=Symbol("ObjectStore-toJSON");WI.objectStores={general:new WI.ObjectStore("general"),audits:new WI.ObjectStore("audit-manager-tests",{keyPath:"__id",autoIncrement:true}),breakpoints:new WI.ObjectStore("debugger-breakpoints",{keyPath:"__id"}),domBreakpoints:new WI.ObjectStore("dom-debugger-dom-breakpoints",{keyPath:"__id"}),eventBreakpoints:new WI.ObjectStore("dom-debugger-event-breakpoints",{keyPath:"__id"}),urlBreakpoints:new WI.ObjectStore("dom-debugger-url-breakpoints",{keyPath:"__id"}),localResourceOverrides:new WI.ObjectStore("local-resource-overrides",{keyPath:"__id"}),};function removeURLFragment(url)
{var hashIndex=url.indexOf("#");if(hashIndex>=0)
return url.substring(0,hashIndex);return url;}
function relativePath(path,basePath)
{var pathComponents=path.split("/");var baseComponents=basePath.replace(/\/$/,"").split("/");var finalComponents=[];var index=1;for(;index<pathComponents.length&&index<baseComponents.length;++index){if(pathComponents[index]!==baseComponents[index])
break;}
for(var i=index;i<baseComponents.length;++i)
finalComponents.push("..");for(var i=index;i<pathComponents.length;++i)
finalComponents.push(pathComponents[i]);return finalComponents.join("/");}
function parseSecurityOrigin(securityOrigin)
{securityOrigin=securityOrigin?securityOrigin.trim():"";let match=securityOrigin.match(/^(?<scheme>[^:]+):\/\/(?<host>[^\/:]*)(?::(?<port>[\d]+))?$/i);if(!match)
return{scheme:null,host:null,port:null};let scheme=match.groups.scheme.toLowerCase();let host=match.groups.host.toLowerCase();let port=Number(match.groups.port)||null;return{scheme,host,port};}
function parseDataURL(url)
{if(!url.startsWith("data:"))
return null;let match=url.match(/^data:(?<mime>[^;,]*)?(?:;charset=(?<charset>[^;,]*?))?(?<base64>;base64)?,(?<data>.*)$/);if(!match)
return null;let scheme="data";let mimeType=match.groups.mime||"text/plain";let charset=match.groups.charset||"US-ASCII";let base64=!!match.groups.base64;let data=decodeURIComponent(match.groups.data);return{scheme,mimeType,charset,base64,data};}
function parseURL(url)
{let result={scheme:null,userinfo:null,host:null,port:null,origin:null,path:null,queryString:null,fragment:null,lastPathComponent:null,};if(url&&url.startsWith("data:")){result.scheme="data";return result;}
if(isWebKitInternalScript(url))
return result;let parsed=null;try{parsed=new URL(url);}catch{return result;}
result.scheme=parsed.protocol.slice(0,-1);if(parsed.username)
result.userinfo=parsed.username;if(parsed.password)
result.userinfo=(result.userinfo||"")+":"+parsed.password;if(parsed.hostname)
result.host=parsed.hostname;if(parsed.port)
result.port=Number(parsed.port);if(parsed.origin&&parsed.origin!=="null")
result.origin=parsed.origin;else if(result.scheme&&result.host){result.origin=result.scheme+"://"+result.host;if(result.port)
result.origin+=":"+result.port;}
if(parsed.pathname)
result.path=parsed.pathname;if(parsed.search)
result.queryString=parsed.search.substring(1);if(parsed.hash)
result.fragment=parsed.hash.substring(1);if(result.path&&result.path!=="/"){let endOffset=result.path.endsWith("/")?1:0;let lastSlashIndex=result.path.lastIndexOf("/",result.path.length-1-endOffset);if(lastSlashIndex!==-1)
result.lastPathComponent=result.path.substring(lastSlashIndex+1,result.path.length-endOffset);}
return result;}
function absoluteURL(partialURL,baseURL)
{partialURL=partialURL?partialURL.trim():"";if(partialURL.startsWith("data:")||partialURL.startsWith("javascript:")||partialURL.startsWith("mailto:"))
return partialURL;if(parseURL(partialURL).scheme)
return partialURL;if(!partialURL)
return baseURL||null;var baseURLComponents=parseURL(baseURL);if(!baseURLComponents.scheme)
return null;if(partialURL[0]==="/"&&partialURL[1]==="/")
return baseURLComponents.scheme+":"+partialURL;if(!baseURLComponents.path)
baseURLComponents.path="/";var baseURLPrefix=baseURLComponents.scheme+"://"+baseURLComponents.host+(baseURLComponents.port?(":"+baseURLComponents.port):"");if(partialURL[0]==="?")
return baseURLPrefix+baseURLComponents.path+partialURL;if(partialURL[0]==="/")
return baseURLPrefix+resolveDotsInPath(partialURL);if(partialURL[0]==="#"){let queryStringComponent=baseURLComponents.queryString?"?"+baseURLComponents.queryString:"";return baseURLPrefix+baseURLComponents.path+queryStringComponent+partialURL;}
var basePath=baseURLComponents.path.substring(0,baseURLComponents.path.lastIndexOf("/"))+"/";return baseURLPrefix+resolveDotsInPath(basePath+partialURL);}
function parseQueryString(queryString,arrayResult)
{if(!queryString)
return arrayResult?[]:{};function decode(string)
{try{return decodeURIComponent(string.replace(/\+/g," "));}catch{return string;}}
var parameters=arrayResult?[]:{};for(let parameterString of queryString.split("&")){let index=parameterString.indexOf("=");if(index===-1)
index=parameterString.length;let name=decode(parameterString.substring(0,index));let value=decode(parameterString.substring(index+1));if(arrayResult)
parameters.push({name,value});else
parameters[name]=value;}
return parameters;}
WI.displayNameForURL=function(url,urlComponents,options={})
{if(url.startsWith("data:"))
return WI.truncateURL(url);if(!urlComponents)
urlComponents=parseURL(url);var displayName;try{displayName=decodeURIComponent(urlComponents.lastPathComponent||"");}catch{displayName=urlComponents.lastPathComponent;}
if(options.allowDirectoryAsName&&(urlComponents.path==="/"||(displayName&&urlComponents.path.endsWith(displayName+"/"))))
displayName="/";return displayName||WI.displayNameForHost(urlComponents.host)||url;};WI.truncateURL=function(url,multiline=false,dataURIMaxSize=6)
{if(!url.startsWith("data:"))
return url;const dataIndex=url.indexOf(",")+1;let header=url.slice(0,dataIndex);if(multiline)
header+="\n";const data=url.slice(dataIndex);if(data.length<dataURIMaxSize)
return header+data;const firstChunk=data.slice(0,Math.ceil(dataURIMaxSize/2));const ellipsis="\u2026";const middleChunk=multiline?`\n${ellipsis}\n`:ellipsis;const lastChunk=data.slice(-Math.floor(dataURIMaxSize/2));return header+firstChunk+middleChunk+lastChunk;};WI.urlWithoutFragment=function(urlString)
{try{let url=new URL(urlString);if(url.hash){url.hash="";return url.toString();}
let result=url.toString();if(result.endsWith("#"))
return result.substring(0,result.length-1);return result;}catch{}
return urlString;};WI.displayNameForHost=function(host)
{let extensionName=WI.browserManager.extensionNameForId(host);if(extensionName)
return extensionName;return host;};WI.h2Authority=function(components)
{let{scheme,userinfo,host,port}=components;let result=host||"";if(userinfo&&(scheme!=="http"&&scheme!=="https"))
result=userinfo+"@"+result;if(port)
result+=":"+port;return result;};WI.h2Path=function(components)
{let{scheme,path,queryString}=components;let result=path||"";


if(!path&&(scheme==="http"||scheme==="https"))
result="/";if(queryString)
result+="?"+queryString;return result;};var emDash="\u2014";var enDash="\u2013";var figureDash="\u2012";var ellipsis="\u2026";var zeroWidthSpace="\u200b";var multiplicationSign="\u00d7";function xor(a,b)
{if(a)
return b?false:a;return b||false;}
Object.defineProperty(Object,"shallowCopy",{value(object)
{var copy={};var keys=Object.keys(object);for(var i=0;i<keys.length;++i)
copy[keys[i]]=object[keys[i]];return copy;}});Object.defineProperty(Object,"shallowEqual",{value(a,b)
{if(!(a instanceof Object)||!(b instanceof Object))
return false;if(a===b)
return true;if(Array.shallowEqual(a,b))
return true;if(a.constructor!==b.constructor)
return false;let aKeys=Object.keys(a);let bKeys=Object.keys(b);if(aKeys.length!==bKeys.length)
return false;for(let aKey of aKeys){if(!(aKey in b))
return false;let aValue=a[aKey];let bValue=b[aKey];if(aValue!==bValue&&!Array.shallowEqual(aValue,bValue))
return false;}
return true;}});Object.defineProperty(Object,"filter",{value(object,callback)
{let filtered={};for(let key in object){if(callback(key,object[key]))
filtered[key]=object[key];}
return filtered;}});Object.defineProperty(Object.prototype,"valueForCaseInsensitiveKey",{value(key)
{if(this.hasOwnProperty(key))
return this[key];var lowerCaseKey=key.toLowerCase();for(var currentKey in this){if(currentKey.toLowerCase()===lowerCaseKey)
return this[currentKey];}
return undefined;}});Object.defineProperty(Map,"fromObject",{value(object)
{let map=new Map;for(let key in object)
map.set(key,object[key]);return map;}});Object.defineProperty(Map.prototype,"take",{value(key)
{let deletedValue=this.get(key);this.delete(key);return deletedValue;}});Object.defineProperty(Map.prototype,"getOrInitialize",{value(key,initialValue)
{let value=this.get(key);if(value)
return value;this.set(key,initialValue);return initialValue;}});Object.defineProperty(Set.prototype,"find",{value(predicate)
{for(let item of this){if(predicate(item,this))
return item;}
return undefined;},});Object.defineProperty(Set.prototype,"addAll",{value(iterable)
{for(let item of iterable)
this.add(item);},});Object.defineProperty(Set.prototype,"take",{value(key)
{if(this.has(key)){this.delete(key);return key;}
return undefined;}});Object.defineProperty(Set.prototype,"equals",{value(other)
{return this.size===other.size&&this.isSubsetOf(other);}});Object.defineProperty(Set.prototype,"difference",{value(other)
{if(other===this)
return new Set;let result=new Set;for(let item of this){if(!other.has(item))
result.add(item);}
return result;}});Object.defineProperty(Set.prototype,"firstValue",{get()
{return this.values().next().value;}});Object.defineProperty(Set.prototype,"lastValue",{get()
{return Array.from(this.values()).lastValue;}});Object.defineProperty(Set.prototype,"intersects",{value(other)
{if(!this.size||!other.size)
return false;for(let item of this){if(other.has(item))
return true;}
return false;}});Object.defineProperty(Set.prototype,"isSubsetOf",{value(other)
{for(let item of this){if(!other.has(item))
return false;}
return true;}});Object.defineProperty(Node.prototype,"traverseNextNode",{value(stayWithin)
{var node=this.firstChild;if(node)
return node;if(stayWithin&&this===stayWithin)
return null;node=this.nextSibling;if(node)
return node;node=this;while(node&&!node.nextSibling&&(!stayWithin||!node.parentNode||node.parentNode!==stayWithin))
node=node.parentNode;if(!node)
return null;return node.nextSibling;}});Object.defineProperty(Node.prototype,"traversePreviousNode",{value(stayWithin)
{if(stayWithin&&this===stayWithin)
return null;var node=this.previousSibling;while(node&&node.lastChild)
node=node.lastChild;if(node)
return node;return this.parentNode;}});Object.defineProperty(Node.prototype,"rangeOfWord",{value(offset,stopCharacters,stayWithinNode,direction)
{var startNode;var startOffset=0;var endNode;var endOffset=0;if(!stayWithinNode)
stayWithinNode=this;if(!direction||direction==="backward"||direction==="both"){var node=this;while(node){if(node===stayWithinNode){if(!startNode)
startNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){let start=node===this?(offset-1):(node.nodeValue.length-1);for(var 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"){node=this;while(node){if(node===stayWithinNode){if(!endNode)
endNode=stayWithinNode;break;}
if(node.nodeType===Node.TEXT_NODE){let start=node===this?offset:0;for(var 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;}
var result=this.ownerDocument.createRange();result.setStart(startNode,startOffset);result.setEnd(endNode,endOffset);return result;}});Object.defineProperty(Element.prototype,"realOffsetWidth",{get()
{return this.getBoundingClientRect().width;}});Object.defineProperty(Element.prototype,"realOffsetHeight",{get()
{return this.getBoundingClientRect().height;}});Object.defineProperty(Element.prototype,"totalOffsetLeft",{get()
{return this.getBoundingClientRect().left;}});Object.defineProperty(Element.prototype,"totalOffsetRight",{get()
{return this.getBoundingClientRect().right;}});Object.defineProperty(Element.prototype,"totalOffsetTop",{get()
{return this.getBoundingClientRect().top;}});Object.defineProperty(Element.prototype,"totalOffsetBottom",{get()
{return this.getBoundingClientRect().bottom;}});Object.defineProperty(Element.prototype,"removeChildren",{value()
{if(this.firstChild)
this.textContent="";}});Object.defineProperty(Element.prototype,"isInsertionCaretInside",{value()
{var selection=window.getSelection();if(!selection.rangeCount||!selection.isCollapsed)
return false;var selectionRange=selection.getRangeAt(0);return selectionRange.startContainer===this||this.contains(selectionRange.startContainer);}});Object.defineProperty(Element.prototype,"createChild",{value(elementName,className)
{var element=this.ownerDocument.createElement(elementName);if(className)
element.className=className;this.appendChild(element);return element;}});Object.defineProperty(Element.prototype,"isScrolledToBottom",{value()
{ return this.scrollTop+this.clientHeight===this.scrollHeight;}});Object.defineProperty(Element.prototype,"recalculateStyles",{value()
{this.ownerDocument.defaultView.getComputedStyle(this);}});Object.defineProperty(DocumentFragment.prototype,"createChild",{value:Element.prototype.createChild});(function(){const fontSymbol=Symbol("font");Object.defineProperty(HTMLInputElement.prototype,"autosize",{value(extra=0)
{extra+=6;if(this.type==="number")
extra+=13;extra+=2;WI.ImageUtilities.scratchCanvasContext2D((context)=>{this[fontSymbol]||=window.getComputedStyle(this).font;context.font=this[fontSymbol];let textMetrics=context.measureText(this.value||this.placeholder);this.style.setProperty("width",(textMetrics.width+extra)+"px");});},});})();Object.defineProperty(Event.prototype,"stop",{value()
{this.stopImmediatePropagation();this.preventDefault();}});Object.defineProperty(KeyboardEvent.prototype,"commandOrControlKey",{get()
{return WI.Platform.name==="mac"?this.metaKey:this.ctrlKey;}});Object.defineProperty(MouseEvent.prototype,"commandOrControlKey",{get()
{return WI.Platform.name==="mac"?this.metaKey:this.ctrlKey;}});Object.defineProperty(Array,"isTypedArray",{value(array)
{if(!array)
return false;let constructor=array.constructor;return constructor===Int8Array||constructor===Int16Array||constructor===Int32Array||constructor===Uint8Array||constructor===Uint8ClampedArray||constructor===Uint16Array||constructor===Uint32Array||constructor===Float32Array||constructor===Float64Array;}});Object.defineProperty(Array,"shallowEqual",{value(a,b)
{function isArrayLike(x){return Array.isArray(x)||Array.isTypedArray(x);}
if(!isArrayLike(a)||!isArrayLike(b))
return false;if(a===b)
return true;let length=a.length;if(length!==b.length)
return false;for(let i=0;i<length;++i){if(a[i]===b[i])
continue;if(!Object.shallowEqual(a[i],b[i]))
return false;}
return true;}});Object.defineProperty(Array,"diffArrays",{value(initialArray,currentArray,onEach,comparator)
{"use strict";function defaultComparator(initial,current){return initial===current;}
comparator=comparator||defaultComparator;
function findShortestEdit(){let deletionCount=initialArray.length;let additionCount=currentArray.length;let editCount=deletionCount+additionCount;for(let i=0;i<initialArray.length;++i){if(i>editCount){break;}
for(let j=0;j<currentArray.length;++j){let newEditCount=i+j;if(newEditCount>editCount){break;}
if(comparator(initialArray[i],currentArray[j])){if(newEditCount<editCount){editCount=newEditCount;deletionCount=i;additionCount=j;}
break;}}}
return[deletionCount,additionCount];}
function commonPrefixLength(listA,listB){let shorterListLength=Math.min(listA.length,listB.length);let i=0;while(i<shorterListLength){if(!comparator(listA[i],listB[i]))
break;++i;}
return i;}
function fireOnEach(count,diffAction,array){for(let i=0;i<count;++i)
onEach(array[i],diffAction);}
while(initialArray.length||currentArray.length){let prefixLength=commonPrefixLength(initialArray,currentArray);if(prefixLength){fireOnEach(prefixLength,0,currentArray);initialArray=initialArray.slice(prefixLength);currentArray=currentArray.slice(prefixLength);}
if(!initialArray.length&&!currentArray.length)
break;let[deletionCount,additionCount]=findShortestEdit();fireOnEach(deletionCount,-1,initialArray);fireOnEach(additionCount,1,currentArray);initialArray=initialArray.slice(deletionCount);currentArray=currentArray.slice(additionCount);}}});Object.defineProperty(Array.prototype,"lastValue",{get()
{if(!this.length)
return undefined;return this[this.length-1];}});Object.defineProperty(Array.prototype,"adjacencies",{value:function*(){for(let i=1;i<this.length;++i)
yield[this[i-1],this[i]];}});Object.defineProperty(Array.prototype,"remove",{value(value)
{for(let i=0;i<this.length;++i){if(this[i]===value){this.splice(i,1);return true;}}
return false;}});Object.defineProperty(Array.prototype,"removeAll",{value(value)
{for(let i=this.length-1;i>=0;--i){if(this[i]===value)
this.splice(i,1);}}});Object.defineProperty(Array.prototype,"toggleIncludes",{value(value,force)
{let exists=this.includes(value);if(exists===!!force)
return;if(exists)
this.remove(value);else
this.push(value);}});Object.defineProperty(Array.prototype,"insertAtIndex",{value(value,index)
{this.splice(index,0,value);}});Object.defineProperty(Array.prototype,"pushAll",{value(iterable)
{for(let item of iterable)
this.push(item);},});Object.defineProperty(Array.prototype,"partition",{value(callback)
{let positive=[];let negative=[];for(let i=0;i<this.length;++i){let value=this[i];if(callback(value))
positive.push(value);else
negative.push(value);}
return[positive,negative];}});Object.defineProperty(String.prototype,"isLowerCase",{value()
{return String(this)===this.toLowerCase();}});Object.defineProperty(String.prototype,"isUpperCase",{value()
{return String(this)===this.toUpperCase();}});Object.defineProperty(String.prototype,"isJSON",{value(predicate)
{try{let json=JSON.parse(this);return!predicate||predicate(json);}catch{}
return false;}});Object.defineProperty(String.prototype,"truncateStart",{value(maxLength)
{"use strict";if(this.length<=maxLength)
return this;return ellipsis+this.substr(this.length-maxLength+1);}});Object.defineProperty(String.prototype,"truncateMiddle",{value(maxLength)
{"use strict";if(this.length<=maxLength)
return this;var leftHalf=maxLength>>1;var rightHalf=maxLength-leftHalf-1;return this.substr(0,leftHalf)+ellipsis+this.substr(this.length-rightHalf,rightHalf);}});Object.defineProperty(String.prototype,"truncateEnd",{value(maxLength)
{"use strict";if(this.length<=maxLength)
return this;return this.substr(0,maxLength-1)+ellipsis;}});Object.defineProperty(String.prototype,"truncate",{value(maxLength)
{"use strict";if(this.length<=maxLength)
return this;let clipped=this.slice(0,maxLength);let indexOfLastWhitespace=clipped.search(/\s\S*$/);if(indexOfLastWhitespace>Math.floor(maxLength/2))
clipped=clipped.slice(0,indexOfLastWhitespace-1);return clipped+ellipsis;}});Object.defineProperty(String.prototype,"collapseWhitespace",{value()
{return this.replace(/[\s\xA0]+/g," ");}});Object.defineProperty(String.prototype,"removeWhitespace",{value()
{return this.replace(/[\s\xA0]+/g,"");}});Object.defineProperty(String.prototype,"escapeCharacters",{value(charactersToEscape)
{if(!charactersToEscape)
return this.valueOf();let charactersToEscapeSet=new Set(charactersToEscape);let foundCharacter=false;for(let c of this){if(!charactersToEscapeSet.has(c))
continue;foundCharacter=true;break;}
if(!foundCharacter)
return this.valueOf();let result="";for(let c of this){if(charactersToEscapeSet.has(c))
result+="\\";result+=c;}
return result.valueOf();}});Object.defineProperty(String.prototype,"escapeForRegExp",{value()
{return this.escapeCharacters("^[]{}()\\.$*+?|");}});Object.defineProperty(String.prototype,"capitalize",{value()
{return this.charAt(0).toUpperCase()+this.slice(1);}});Object.defineProperty(String.prototype,"extendedLocaleCompare",{value(other)
{return this.localeCompare(other,undefined,{numeric:true});}});Object.defineProperty(String,"tokenizeFormatString",{value(format)
{var tokens=[];var substitutionIndex=0;function addStringToken(str)
{tokens.push({type:"string",value:str});}
function addSpecifierToken(specifier,precision,substitutionIndex)
{tokens.push({type:"specifier",specifier,precision,substitutionIndex});}
var index=0;for(var precentIndex=format.indexOf("%",index);precentIndex!==-1;precentIndex=format.indexOf("%",index)){addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==="%"){addStringToken("%");++index;continue;}
if(!isNaN(format[index])){var number=parseInt(format.substring(index),10);while(!isNaN(format[index]))
++index;if(number>0&&format[index]==="$"){substitutionIndex=(number-1);++index;}}
const defaultPrecision=6;let precision=defaultPrecision;if(format[index]==="."){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision))
precision=defaultPrecision;while(!isNaN(format[index]))
++index;}
addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;}
addStringToken(format.substring(index));return tokens;}});Object.defineProperty(String.prototype,"lineCount",{get()
{"use strict";let lineCount=1;let index=0;while(true){index=this.indexOf("\n",index);if(index===-1)
return lineCount;index+="\n".length;lineCount++;}}});Object.defineProperty(String.prototype,"lastLine",{get()
{"use strict";let index=this.lastIndexOf("\n");if(index===-1)
return this;return this.slice(index+"\n".length);}});Object.defineProperty(String.prototype,"hash",{get()
{const stringHashingStartValue=0x9e3779b9;var result=stringHashingStartValue;var pendingCharacter=null;for(var i=0;i<this.length;++i){var currentCharacter=this[i].charCodeAt(0);if(pendingCharacter===null){pendingCharacter=currentCharacter;continue;}
result+=pendingCharacter;result=(result<<16)^((currentCharacter<<11)^result);result+=result>>11;pendingCharacter=null;}
if(pendingCharacter!==null){result+=pendingCharacter;result^=result<<11;result+=result>>17;}
result^=result<<3;result+=result>>5;result^=result<<2;result+=result>>15;result^=result<<10;return(0xffffffff+result+1).toString(36);}});Object.defineProperty(String,"standardFormatters",{value:{d:function(substitution)
{return parseInt(substitution).toLocaleString();},f:function(substitution,token)
{let value=parseFloat(substitution);if(isNaN(value))
return NaN;let options={minimumFractionDigits:token.precision,maximumFractionDigits:token.precision,useGrouping:false};return value.toLocaleString(undefined,options);},s:function(substitution)
{return substitution;}}});Object.defineProperty(String,"format",{value(format,substitutions,formatters,initialValue,append)
{if(!format||!substitutions||!substitutions.length)
return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName()
{return"String.format(\""+format+"\", \""+Array.from(substitutions).join("\", \"")+"\")";}
function warn(msg)
{console.warn(prettyFunctionName()+": "+msg);}
function error(msg)
{console.error(prettyFunctionName()+": "+msg);}
var result=initialValue;var tokens=String.tokenizeFormatString(format);var usedSubstitutionIndexes={};for(var i=0;i<tokens.length;++i){var 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));}
var unusedSubstitutions=[];for(var i=0;i<substitutions.length;++i){if(i in usedSubstitutionIndexes)
continue;unusedSubstitutions.push(substitutions[i]);}
return{formattedResult:result,unusedSubstitutions};}});Object.defineProperty(String.prototype,"format",{value()
{return String.format(this,arguments,String.standardFormatters,"",function(a,b){return a+b;}).formattedResult;}});Object.defineProperty(String.prototype,"insertWordBreakCharacters",{value()
{return this.replace(/([\/;:\)\]\}&?])/g,"$1\u200b");}});Object.defineProperty(String.prototype,"removeWordBreakCharacters",{value()
{return this.replace(/\u200b/g,"");}});Object.defineProperty(String.prototype,"levenshteinDistance",{value(s)
{var m=this.length;var n=s.length;var d=new Array(m+1);for(var i=0;i<=m;++i){d[i]=new Array(n+1);d[i][0]=i;}
for(var j=0;j<=n;++j)
d[0][j]=j;for(var j=1;j<=n;++j){for(var i=1;i<=m;++i){if(this[i-1]===s[j-1])
d[i][j]=d[i-1][j-1];else{var deletion=d[i-1][j]+1;var insertion=d[i][j-1]+1;var substitution=d[i-1][j-1]+1;d[i][j]=Math.min(deletion,insertion,substitution);}}}
return d[m][n];}});Object.defineProperty(String.prototype,"toCamelCase",{value()
{return this.toLowerCase().replace(/[^\w]+(\w)/g,(match,group)=>group.toUpperCase());}});Object.defineProperty(String.prototype,"hasMatchingEscapedQuotes",{value()
{return/^\"(?:[^\"\\]|\\.)*\"$/.test(this) || /^\'(?:[^\'\\]|\\.)*\'$/.test(this);
    }
});

Object.defineProperty(Math, "roundTo",
{
    value(num, step)
    {
        return Math.round(num / step) * step;
    }
});

// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web#Multiplying_a_matrix_and_a_point
Object.defineProperty(Math, "multiplyMatrixByVector",
{
    value(matrix, vector)
    {
        let height = matrix.length;
        let width = matrix[0].length;

        let result = Array(width).fill(0);
        for (let i = 0; i < width; ++i) {
            for (let rowIndex = 0; rowIndex < height; ++rowIndex)
                result[i] += vector[rowIndex] * matrix[i][rowIndex];
        }

        return result;
    }
});

Object.defineProperty(Number, "constrain",
{
    value(num, min, max)
    {
        if (isNaN(num) || max < min)
            return min;

        if (num < min)
            num = min;
        else if (num > max)
            num = max;
        return num;
    }
});

Object.defineProperty(Number, "percentageString",
{
    value(fraction, precision = 1)
    {
        return fraction.toLocaleString(undefined, {minimumFractionDigits: precision, style: "percent"});
    }
});

Object.defineProperty(Number, "secondsToMillisecondsString",
{
    value(seconds, higherResolution)
    {
        let ms = seconds * 1000;

        if (higherResolution)
            return WI.UIString("%.2fms").format(ms);
        return WI.UIString("%.1fms").format(ms);
    }
});

Object.defineProperty(Number, "secondsToString",
{
    value(seconds, higherResolution)
    {
        const epsilon = 0.0001;

        let ms = seconds * 1000;
        if (ms < epsilon)
            return WI.UIString("%.0fms").format(0);

        if (Math.abs(ms) < (10 + epsilon)) {
            if (higherResolution)
                return WI.UIString("%.3fms").format(ms);
            return WI.UIString("%.2fms").format(ms);
        }

        if (Math.abs(ms) < (100 + epsilon)) {
            if (higherResolution)
                return WI.UIString("%.2fms").format(ms);
            return WI.UIString("%.1fms").format(ms);
        }

        if (Math.abs(ms) < (1000 + epsilon)) {
            if (higherResolution)
                return WI.UIString("%.1fms").format(ms);
            return WI.UIString("%.0fms").format(ms);
        }

        // Do not go over seconds when in high resolution mode.
        if (higherResolution || Math.abs(seconds) < 60)
            return WI.UIString("%.2fs").format(seconds);

        let minutes = seconds / 60;
        if (Math.abs(minutes) < 60)
            return WI.UIString("%.1fmin").format(minutes);

        let hours = minutes / 60;
        if (Math.abs(hours) < 24)
            return WI.UIString("%.1fhrs").format(hours);

        let days = hours / 24;
        return WI.UIString("%.1f days").format(days);
    }
});

Object.defineProperty(Number, "bytesToString",
{
    value(bytes, higherResolution, bytesThreshold)
    {
        higherResolution ??= true;
        bytesThreshold ??= 1000;

        if (Math.abs(bytes) < bytesThreshold)
            return WI.UIString("%.0f B").format(bytes);

        let kilobytes = bytes / 1000;
        if (Math.abs(kilobytes) < 1000) {
            if (higherResolution || Math.abs(kilobytes) < 10)
                return WI.UIString("%.2f KB").format(kilobytes);
            return WI.UIString("%.1f KB").format(kilobytes);
        }

        let megabytes = kilobytes / 1000;
        if (Math.abs(megabytes) < 1000) {
            if (higherResolution || Math.abs(megabytes) < 10)
                return WI.UIString("%.2f MB").format(megabytes);
            return WI.UIString("%.1f MB").format(megabytes);
        }

        let gigabytes = megabytes / 1000;
        if (higherResolution || Math.abs(gigabytes) < 10)
            return WI.UIString("%.2f GB").format(gigabytes);
        return WI.UIString("%.1f GB").format(gigabytes);
    }
});

Object.defineProperty(Number, "abbreviate",
{
    value(num)
    {
        if (num < 1000)
            return num.toLocaleString();

        if (num < 1_000_000)
            return WI.UIString("%.1fK").format(Math.round(num / 100) / 10);

        if (num < 1_000_000_000)
            return WI.UIString("%.1fM").format(Math.round(num / 100_000) / 10);

        return WI.UIString("%.1fB").format(Math.round(num / 100_000_000) / 10);
    }
});

Object.defineProperty(Number, "zeroPad",
{
    value(num, length)
    {
        let string = num.toLocaleString();
        return string.padStart(length, "0");
    },
});

Object.defineProperty(Number, "countDigits",
{
    value(num)
    {
        if (num === 0)
            return 1;

        num = Math.abs(num);
        return Math.floor(Math.log(num) * Math.LOG10E) + 1;
    }
});

Object.defineProperty(Number.prototype, "maxDecimals",
{
    value(decimals)
    {
        let power = 10 ** decimals;
        return Math.round(this * power) / power;
    }
});

Object.defineProperty(Uint32Array, "isLittleEndian",
{
    value()
    {
        if ("_isLittleEndian" in this)
            return this._isLittleEndian;

        var buffer = new ArrayBuffer(4);
        var longData = new Uint32Array(buffer);
        var data = new Uint8Array(buffer);

        longData[0] = 0x0a0b0c0d;

        this._isLittleEndian = data[0] === 0x0d && data[1] === 0x0c && data[2] === 0x0b && data[3] === 0x0a;

        return this._isLittleEndian;
    }
});

function isEmptyObject(object)
{
    for (var property in object)
        return false;
    return true;
}

function isEnterKey(event)
{
    // Check if this is an IME event.
    return event.keyCode !== 229 && event.keyIdentifier === "Enter";
}

function resolveDotsInPath(path)
{
    if (!path)
        return path;

    if (path.indexOf("./") === -1)
        return path;


    var result = [];

    var components = path.split("/");
    for (var i = 0; i < components.length; ++i) {
        var component = components[i];

        // Skip over "./".
        if (component === ".")
            continue;

        // Rewind one component for "../".
        if (component === "..") {
            if (result.length === 1)
                continue;
            result.pop();
            continue;
        }

        result.push(component);
    }

    return result.join("/");
}

function parseMIMEType(fullMimeType)
{
    if (!fullMimeType)
        return {type: fullMimeType, boundary: null, encoding: null};

    var typeParts = fullMimeType.split(/\s*;\s*/);

    var type = typeParts[0];
    var boundary = null;
    var encoding = null;

    for (var i = 1; i < typeParts.length; ++i) {
        var subparts = typeParts[i].split(/\s*=\s*/);
        if (subparts.length !== 2)
            continue;

        if (subparts[0].toLowerCase() === "boundary")
            boundary = subparts[1];
        else if (subparts[0].toLowerCase() === "charset")
            encoding = subparts[1].replace("^\"|\"$","");}
return{type,boundary:boundary||null,encoding:encoding||null};}
function simpleGlobStringToRegExp(globString,regExpFlags)
{if(!globString)
return null;var regexString=globString.escapeCharacters("^[]{}()\\.$+?|");regexString=regexString.replace(/\\\\\*/g,"\\*");var unescapedAsteriskRegex=/(^|[^\\])\*+/g;if(unescapedAsteriskRegex.test(globString)){regexString=regexString.replace(unescapedAsteriskRegex,"$1.*");


regexString="\\b"+regexString+"\\b";}
return new RegExp(regexString,regExpFlags);}
Object.defineProperty(Array.prototype,"lowerBound",{

value(object,comparator)
{function defaultComparator(a,b)
{return a-b;}
comparator=comparator||defaultComparator;var l=0;var r=this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,"upperBound",{

value(object,comparator)
{function defaultComparator(a,b)
{return a-b;}
comparator=comparator||defaultComparator;var l=0;var r=this.length;while(l<r){var m=(l+r)>>1;if(comparator(object,this[m])>=0)
l=m+1;else
r=m;}
return r;}});Object.defineProperty(Array.prototype,"binaryIndexOf",{value(value,comparator)
{function defaultComparator(a,b)
{return a-b;}
comparator=comparator||defaultComparator;var index=this.lowerBound(value,comparator);return index<this.length&&comparator(value,this[index])===0?index:-1;}});Object.defineProperty(Array.prototype,"groupBy",{value(groupFunction,minGroupSize=1)
{let result=[];let startIndex=null;let flush=(endIndex)=>{if(startIndex===null)
return;let group=this.slice(startIndex,endIndex+1);let adjacentCount=(endIndex+1)-startIndex;if(adjacentCount>=minGroupSize)
result.push(group);else
result.pushAll(group);}
this.forEach((item,i)=>{if(groupFunction(item)){startIndex??=i;if(i===this.length-1)
flush(this.length-1);}else{flush(i-1);result.push(item);startIndex=null;}});return result;}});Object.defineProperty(Promise,"chain",{async value(callbacks,initialValue)
{let results=[];for(let i=0;i<callbacks.length;++i)
results.push(await callbacks[i](results.lastValue||initialValue||null,i));return results;}});Object.defineProperty(Promise,"delay",{value(delay)
{return new Promise((resolve)=>setTimeout(resolve,delay||0));}});function appendWebInspectorSourceURL(string)
{if(string.includes("//# sourceURL"))
return string;return"\n//# sourceURL=__WebInspectorInternal__\n"+string;}
function appendWebInspectorConsoleEvaluationSourceURL(string)
{if(string.includes("//# sourceURL"))
return string;return"\n//# sourceURL=__WebInspectorConsoleEvaluation__\n"+string;}
function isWebInspectorBootstrapScript(url)
{return url===WI.NetworkManager.bootstrapScriptURL;}
function isWebInspectorInternalScript(url)
{return url==="__WebInspectorInternal__";}
function isWebInspectorConsoleEvaluationScript(url)
{return url==="__WebInspectorConsoleEvaluation__";}
function isWebKitInjectedScript(url)
{return url&&url.startsWith("__InjectedScript_")&&url.endsWith(".js");}
function isWebKitInternalScript(url)
{if(isWebInspectorConsoleEvaluationScript(url))
return false;if(isWebKitInjectedScript(url))
return true;return url&&url.startsWith("__Web")&&url.endsWith("__");}
function isFunctionStringNativeCode(str)
{return str.endsWith("{\n    [native code]\n}");}
function whitespaceRatio(content,start,end)
{let whitespaceScore=0;let size=end-start;for(let i=start;i<end;i++){let char=content[i];if(char===" ")
whitespaceScore++;else if(char==="\t")
whitespaceScore+=4;else if(char==="\n")
whitespaceScore+=8;}
let ratio=whitespaceScore/size;return ratio;}
function isTextLikelyMinified(content)
{const autoFormatMaxCharactersToCheck=2500;const autoFormatWhitespaceRatio=0.2;if(content.length<=autoFormatMaxCharactersToCheck){let ratio=whitespaceRatio(content,0,content.length);return ratio<autoFormatWhitespaceRatio;}
let startRatio=whitespaceRatio(content,0,autoFormatMaxCharactersToCheck);if(startRatio<autoFormatWhitespaceRatio)
return true;let endRatio=whitespaceRatio(content,content.length-autoFormatMaxCharactersToCheck,content.length);if(endRatio<autoFormatWhitespaceRatio)
return true;return false;}
function doubleQuotedString(str)
{return JSON.stringify(str);}
function insertionIndexForObjectInListSortedByFunction(object,list,comparator,insertionIndexAfter)
{if(insertionIndexAfter){return list.upperBound(object,comparator);}else{return list.lowerBound(object,comparator);}}
function insertObjectIntoSortedArray(object,array,comparator)
{array.splice(insertionIndexForObjectInListSortedByFunction(object,array,comparator),0,object);}
WI.setReentrantCheck=function(object,key)
{key="__checkReentrant_"+key;object[key]=(object[key]||0)+1;return object[key]===1;};WI.clearReentrantCheck=function(object,key)
{key="__checkReentrant_"+key;object[key]=(object[key]||0)-1;return object[key]===0;};WI.SearchUtilities=class SearchUtilities{static get defaultSettings()
{return{caseSensitive:WI.settings.searchCaseSensitive,regularExpression:WI.settings.searchRegularExpression,};}
static createSettings(namePrefix)
{let settings={};for(let[key,defaultSetting]of Object.entries(WI.SearchUtilities.defaultSettings)){let setting=new WI.Setting(namePrefix+"-"+defaultSetting.name,defaultSetting.value);defaultSetting.addEventListener(WI.Setting.Event.Changed,function(event){this.value=defaultSetting.value;},setting);settings[key]=setting;}
return settings;}
static searchRegExpForString(query,settings={})
{return WI.SearchUtilities._regExpForString(query,settings,{global:true});}
static filterRegExpForString(query,settings={})
{return WI.SearchUtilities._regExpForString(query,settings);}
static createSettingsButton(settings)
{let button=document.createElement("button");button.classList.add("search-settings");button.tabIndex=-1;WI.addMouseDownContextMenuHandlers(button,(contextMenu)=>{if(settings.caseSensitive){contextMenu.appendCheckboxItem(WI.UIString("Case Sensitive","Case Sensitive @ Context Menu","Context menu label for whether searches should be case sensitive."),()=>{settings.caseSensitive.value=!settings.caseSensitive.value;},settings.caseSensitive.value);}
if(settings.regularExpression){contextMenu.appendCheckboxItem(WI.UIString("Regular Expression","Regular Expression @ Context Menu","Context menu label for whether searches should be treated as regular expressions."),()=>{settings.regularExpression.value=!settings.regularExpression.value;},settings.regularExpression.value);}});button.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Gear.svg","glyph"));function toggleActive(){button.classList.toggle("active",Object.values(settings).some((setting)=>!!setting.value));}
settings.caseSensitive.addEventListener(WI.Setting.Event.Changed,toggleActive,button);settings.regularExpression.addEventListener(WI.Setting.Event.Changed,toggleActive,button);toggleActive();return button;}
static _regExpForString(query,settings={},options={})
{function checkSetting(setting){return setting instanceof WI.Setting?setting.value:!!setting;}
if(!checkSetting(settings.regularExpression)){try{query=simpleGlobStringToRegExp(String(query));}catch{return null;}}
let flags="";if(options.global)
flags+="g"
if(!checkSetting(settings.caseSensitive))
flags+="i";try{return new RegExp(query,flags);}catch{return null;}}};WI.Setting=class Setting extends WI.Object
{constructor(name,defaultValue)
{super();this._name=name;this._defaultValue=defaultValue;} 
static migrateValue(key)
{let localStorageKey=WI.Setting._localStorageKeyPrefix+key;let value=undefined;if(!window.InspectorTest&&window.localStorage){let item=window.localStorage.getItem(localStorageKey);if(item!==null){try{value=JSON.parse(item);}catch{}
window.localStorage.removeItem(localStorageKey);}}
return value;}
static reset()
{let prefix=WI.Setting._localStorageKeyPrefix;let keysToRemove=[];for(let i=0;i<window.localStorage.length;++i){let key=window.localStorage.key(i);if(key.startsWith(prefix))
keysToRemove.push(key);}
for(let key of keysToRemove)
window.localStorage.removeItem(key);} 
get name(){return this._name;}
get defaultValue(){return this._defaultValue;}
get value()
{if("_value"in this)
return this._value;this._value=JSON.parse(JSON.stringify(this._defaultValue));if(!window.InspectorTest&&window.localStorage){let key=WI.Setting._localStorageKeyPrefix+this._name;let item=window.localStorage.getItem(key);if(item!==null){try{this._value=JSON.parse(item);}catch{window.localStorage.removeItem(key);}}}
return this._value;}
set value(value)
{if(this._value===value)
return;this._value=value;this.save();}
save()
{if(!window.InspectorTest&&window.localStorage){let key=WI.Setting._localStorageKeyPrefix+this._name;try{if(Object.shallowEqual(this._value,this._defaultValue))
window.localStorage.removeItem(key);else
window.localStorage.setItem(key,JSON.stringify(this._value));}catch{console.error("Error saving setting with name: "+this._name);}}
this.dispatchEventToListeners(WI.Setting.Event.Changed,this._value,{name:this._name});}
reset()
{this.value=JSON.parse(JSON.stringify(this._defaultValue));}};WI.Setting._localStorageKeyPrefix=(function(){let inspectionLevel=InspectorFrontendHost?InspectorFrontendHost.inspectionLevel:1;let levelString=inspectionLevel>1?"-"+inspectionLevel:"";return`com.apple.WebInspector${levelString}.`;})();WI.Setting.isFirstLaunch=!!window.InspectorTest||(window.localStorage&&Object.keys(window.localStorage).every((key)=>!key.startsWith(WI.Setting._localStorageKeyPrefix)));WI.Setting.Event={Changed:"setting-changed"};WI.EngineeringSetting=class EngineeringSetting extends WI.Setting
{get value()
{if(WI.isEngineeringBuild)
return super.value;return this.defaultValue;}
set value(value)
{if(WI.isEngineeringBuild)
super.value=value;}};WI.DebugSetting=class DebugSetting extends WI.Setting
{get value()
{if(WI.isDebugUIEnabled())
return super.value;return this.defaultValue;}
set value(value)
{if(WI.isDebugUIEnabled())
super.value=value;}};WI.settings={canvasRecordingAutoCaptureEnabled:new WI.Setting("canvas-recording-auto-capture-enabled",false),canvasRecordingAutoCaptureFrameCount:new WI.Setting("canvas-recording-auto-capture-frame-count",1),consoleAutoExpandTrace:new WI.Setting("console-auto-expand-trace",true),consoleSavedResultAlias:new WI.Setting("console-saved-result-alias",""),cssChangesPerNode:new WI.Setting("css-changes-per-node",false),clearLogOnNavigate:new WI.Setting("clear-log-on-navigate",true),clearNetworkOnNavigate:new WI.Setting("clear-network-on-navigate",true),cpuTimelineThreadDetailsExpanded:new WI.Setting("cpu-timeline-thread-details-expanded",false),emulateInUserGesture:new WI.Setting("emulate-in-user-gesture",false),enableControlFlowProfiler:new WI.Setting("enable-control-flow-profiler",false),enableElementsTabIndependentStylesDetailsSidebarPanel:new WI.Setting("elements-tab-independent-styles-details-panel",true),enableLineWrapping:new WI.Setting("enable-line-wrapping",true),frontendAppearance:new WI.Setting("frontend-appearance","system"),gridOverlayShowAreaNames:new WI.Setting("grid-overlay-show-area-names",false),gridOverlayShowExtendedGridLines:new WI.Setting("grid-overlay-show-extended-grid-lines",false),gridOverlayShowLineNames:new WI.Setting("grid-overlay-show-line-names",false),gridOverlayShowLineNumbers:new WI.Setting("grid-overlay-show-line-numbers",true),gridOverlayShowTrackSizes:new WI.Setting("grid-overlay-show-track-sizes",true),groupMediaRequestsByDOMNode:new WI.Setting("group-media-requests-by-dom-node",WI.Setting.migrateValue("group-by-dom-node")||false),indentUnit:new WI.Setting("indent-unit",4),indentWithTabs:new WI.Setting("indent-with-tabs",false),resourceCachingDisabled:new WI.Setting("disable-resource-caching",false),searchCaseSensitive:new WI.Setting("search-case-sensitive",false),searchFromSelection:new WI.Setting("search-from-selection",false),searchRegularExpression:new WI.Setting("search-regular-expression",false),selectedNetworkDetailContentViewIdentifier:new WI.Setting("network-detail-content-view-identifier","preview"),sourceMapsEnabled:new WI.Setting("source-maps-enabled",true),showCSSPropertySyntaxInDocumentationPopover:new WI.Setting("show-css-property-syntax-in-documentation-popover",false),showCanvasPath:new WI.Setting("show-canvas-path",false),showImageGrid:new WI.Setting("show-image-grid",true),showInvisibleCharacters:new WI.Setting("show-invisible-characters",!!WI.Setting.migrateValue("show-invalid-characters")),showJavaScriptTypeInformation:new WI.Setting("show-javascript-type-information",false),showRulers:new WI.Setting("show-rulers",false),showRulersDuringElementSelection:new WI.Setting("show-rulers-during-element-selection",true),showScopeChainOnPause:new WI.Setting("show-scope-chain-sidebar",true),showWhitespaceCharacters:new WI.Setting("show-whitespace-characters",false),tabSize:new WI.Setting("tab-size",4),timelinesAutoStop:new WI.Setting("timelines-auto-stop",true),timelineOverviewGroupBySourceCode:new WI.Setting("timeline-overview-group-by-source-code",true),zoomFactor:new WI.Setting("zoom-factor",1), experimentalEnablePreviewFeatures:new WI.Setting("experimental-enable-preview-features",true),experimentalEnableStylesJumpToEffective:new WI.Setting("experimental-styles-jump-to-effective",false),experimentalEnableStylesJumpToVariableDeclaration:new WI.Setting("experimental-styles-jump-to-variable-declaration",false),experimentalCollapseBlackboxedCallFrames:new WI.Setting("experimental-collapse-blackboxed-call-frames",false),experimentalAllowInspectingInspector:new WI.Setting("experimental-allow-inspecting-inspector",false), protocolLogAsText:new WI.Setting("protocol-log-as-text",false),protocolAutoLogMessages:new WI.Setting("protocol-auto-log-messages",false),protocolAutoLogTimeStats:new WI.Setting("protocol-auto-log-time-stats",false),protocolFilterMultiplexingBackendMessages:new WI.Setting("protocol-filter-multiplexing-backend-messages",true), engineeringShowInternalExecutionContexts:new WI.EngineeringSetting("engineering-show-internal-execution-contexts",false),engineeringShowInternalScripts:new WI.EngineeringSetting("engineering-show-internal-scripts",false),engineeringPauseForInternalScripts:new WI.EngineeringSetting("engineering-pause-for-internal-scripts",false),engineeringShowInternalObjectsInHeapSnapshot:new WI.EngineeringSetting("engineering-show-internal-objects-in-heap-snapshot",false),engineeringShowPrivateSymbolsInHeapSnapshot:new WI.EngineeringSetting("engineering-show-private-symbols-in-heap-snapshot",false),engineeringAllowEditingUserAgentShadowTrees:new WI.EngineeringSetting("engineering-allow-editing-user-agent-shadow-trees",false),engineeringShowMockWebExtensionTab:new WI.EngineeringSetting("engineering-show-mock-web-extension-tab",false), debugShowConsoleEvaluations:new WI.DebugSetting("debug-show-console-evaluations",false),debugOutlineFocusedElement:new WI.DebugSetting("debug-outline-focused-element",false),debugEnableLayoutFlashing:new WI.DebugSetting("debug-enable-layout-flashing",false),debugEnableStyleEditingDebugMode:new WI.DebugSetting("debug-enable-style-editing-debug-mode",false),debugEnableUncaughtExceptionReporter:new WI.DebugSetting("debug-enable-uncaught-exception-reporter",true),debugEnableDiagnosticLogging:new WI.DebugSetting("debug-enable-diagnostic-logging",true),debugAutoLogDiagnosticEvents:new WI.DebugSetting("debug-auto-log-diagnostic-events",false),debugLayoutDirection:new WI.DebugSetting("debug-layout-direction-override","system"),};WI.previewFeatures=[];WI.canShowPreviewFeatures=function()
{let hasPreviewFeatures=WI.previewFeatures.length>0;return hasPreviewFeatures&&WI.isExperimentalBuild;};WI.arePreviewFeaturesEnabled=function()
{return WI.canShowPreviewFeatures()&&WI.settings.experimentalEnablePreviewFeatures.value;};WI.YieldableTask=class YieldableTask
{constructor(delegate,items,options={})
{let{workInterval,idleInterval}=options;this._workInterval=workInterval||10;this._idleInterval=idleInterval||0;this._delegate=delegate;this._items=items;this._idleTimeoutIdentifier=undefined;this._processing=false;this._processing=false;this._cancelled=false;} 
get processing(){return this._processing;}
get cancelled(){return this._cancelled;}
get idleInterval(){return this._idleInterval;}
get workInterval(){return this._workInterval;}
start()
{if(this._processing)
return;if(this._cancelled)
return;function*createIteratorForProcessingItems()
{let startTime=Date.now();let processedItems=[];for(let item of this._items){if(this._cancelled)
break;this._delegate.yieldableTaskWillProcessItem(this,item);processedItems.push(item);if(this._cancelled)
break;let elapsedTime=Date.now()-startTime;if(elapsedTime>this._workInterval){let returnedItems=processedItems.slice();processedItems=[];this._willYield(returnedItems,elapsedTime);yield;startTime=Date.now();}}

if(processedItems.length)
this._willYield(processedItems,Date.now()-startTime);}
this._processing=true;this._pendingItemsIterator=createIteratorForProcessingItems.call(this);this._processPendingItems();}
cancel()
{if(!this._processing)
return;this._cancelled=true;} 
_processPendingItems()
{if(this._cancelled)
return;if(!this._pendingItemsIterator.next().done){this._idleTimeoutIdentifier=setTimeout(()=>{this._processPendingItems();},this._idleInterval);return;}
this._didFinish();}
_willYield(processedItems,elapsedTime)
{if(typeof this._delegate.yieldableTaskDidYield==="function")
this._delegate.yieldableTaskDidYield(this,processedItems,elapsedTime);}
_didFinish()
{this._processing=false;this._pendingItemsIterator=null;if(this._idleTimeoutIdentifier){clearTimeout(this._idleTimeoutIdentifier);this._idleTimeoutIdentifier=undefined;}
if(typeof this._delegate.yieldableTaskDidFinish==="function")
this._delegate.yieldableTaskDidFinish(this);}};WI.ProtocolTracer=class ProtocolTracer
{ logStarted()
{}
logFrontendException(connection,message,exception)
{}
logFrontendRequest(connection,message)
{}
logWillHandleResponse(connection,message)
{}
logDidHandleResponse(connection,message,timings=null)
{}
logWillHandleEvent(connection,message)
{}
logDidHandleEvent(connection,message,timings=null)
{}
logFinished()
{}};WI.LoggingProtocolTracer=class LoggingProtocolTracer extends WI.ProtocolTracer
{constructor()
{super();this._dumpMessagesToConsole=false;this._dumpTimingDataToConsole=false;this._filterMultiplexingBackend=true;this._logToConsole=window.InspectorTest?InspectorFrontendHost.unbufferedLog.bind(InspectorFrontendHost):console.log;} 
set dumpMessagesToConsole(value)
{this._dumpMessagesToConsole=!!value;}
get dumpMessagesToConsole()
{return this._dumpMessagesToConsole;}
set dumpTimingDataToConsole(value)
{this._dumpTimingDataToConsole=!!value;}
get dumpTimingDataToConsole()
{return this._dumpTimingDataToConsole;}
set filterMultiplexingBackend(value)
{this._filterMultiplexingBackend=!!value;}
get filterMultiplexingBackend()
{return this._filterMultiplexingBackend;}
logFrontendException(connection,message,exception)
{this._processEntry({type:"exception",connection,message,exception});}
logFrontendRequest(connection,message)
{this._processEntry({type:"request",connection,message});}
logWillHandleResponse(connection,message)
{let entry={type:"response",connection,message};this._processEntry(entry);}
logDidHandleResponse(connection,message,timings=null)
{let entry={type:"response",connection,message};if(timings)
entry.timings=Object.shallowCopy(timings);this._processEntry(entry);}
logWillHandleEvent(connection,message)
{let entry={type:"event",connection,message};this._processEntry(entry);}
logDidHandleEvent(connection,message,timings=null)
{let entry={type:"event",connection,message};if(timings)
entry.timings=Object.shallowCopy(timings);this._processEntry(entry);}
_processEntry(entry)
{if(this._dumpTimingDataToConsole&&entry.timings){if(entry.timings.rtt&&entry.timings.dispatch)
this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms; RTT: ${entry.timings.rtt}ms`);else if(entry.timings.dispatch)
this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms`);}else if(this._dumpMessagesToConsole&&!entry.timings){let connection=entry.connection;let targetId=connection&&connection.target?connection.target.identifier:"unknown";if(this._filterMultiplexingBackend&&targetId==="multi")
return;let prefix=`${entry.type} (${targetId})`;if(!window.InspectorTest&&InspectorFrontendHost.isBeingInspected()&&!WI.settings.protocolLogAsText.value){if(entry.type==="request"||entry.type==="exception")
console.trace(prefix,entry.message);else
this._logToConsole(prefix,entry.message);}else
this._logToConsole(`${prefix}: ${JSON.stringify(entry.message)}`);if(entry.exception){this._logToConsole(entry.exception);if(entry.exception.stack)
this._logToConsole(entry.exception.stack);}}}};InspectorBackendClass=class InspectorBackendClass
{constructor()
{this._registeredDomains={};this._activeDomains={};this._customTracer=null;this._defaultTracer=new WI.LoggingProtocolTracer;this._activeTracers=[this._defaultTracer]; this._supportedDomainsForTargetType=new Multimap;this._supportedCommandParameters=new Map;this._supportedEventParameters=new Map;WI.settings.protocolAutoLogMessages.addEventListener(WI.Setting.Event.Changed,this._startOrStopAutomaticTracing,this);WI.settings.protocolAutoLogTimeStats.addEventListener(WI.Setting.Event.Changed,this._startOrStopAutomaticTracing,this);this._startOrStopAutomaticTracing();this.currentDispatchState={event:null,request:null,response:null,};}

get Enum()
{return this._registeredDomains;}


set dumpInspectorProtocolMessages(value)
{WI.settings.protocolAutoLogMessages.value=value;this._defaultTracer.dumpMessagesToConsole=value;}
get dumpInspectorProtocolMessages()
{return WI.settings.protocolAutoLogMessages.value;}
set dumpInspectorTimeStats(value)
{WI.settings.protocolAutoLogTimeStats.value=value;if(!this.dumpInspectorProtocolMessages)
this.dumpInspectorProtocolMessages=true;this._defaultTracer.dumpTimingDataToConsole=value;}
get dumpInspectorTimeStats()
{return WI.settings.protocolAutoLogTimeStats.value;}
set filterMultiplexingBackendInspectorProtocolMessages(value)
{WI.settings.protocolFilterMultiplexingBackendMessages.value=value;this._defaultTracer.filterMultiplexingBackend=value;}
get filterMultiplexingBackendInspectorProtocolMessages()
{return WI.settings.protocolFilterMultiplexingBackendMessages.value;}
set customTracer(tracer)
{if(!tracer&&!this._customTracer)
return;if(tracer===this._customTracer)
return;if(tracer===this._defaultTracer)
return;if(this._customTracer)
this._customTracer.logFinished();this._customTracer=tracer;this._activeTracers=[this._defaultTracer];if(this._customTracer){this._customTracer.logStarted();this._activeTracers.push(this._customTracer);}}
get activeTracers()
{return this._activeTracers;}
registerDomain(domainName,targetTypes)
{targetTypes=targetTypes||WI.TargetType.all;for(let targetType of targetTypes)
this._supportedDomainsForTargetType.add(targetType,domainName);this._registeredDomains[domainName]=new InspectorBackend.Domain(domainName);}
registerVersion(domainName,version)
{let domain=this._registeredDomains[domainName];domain.VERSION=version;}
registerEnum(qualifiedName,enumValues)
{let[domainName,enumName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addEnum(enumName,enumValues);}
registerCommand(qualifiedName,targetTypes,callSignature,replySignature)
{let[domainName,commandName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addCommand(targetTypes,new InspectorBackend.Command(qualifiedName,commandName,callSignature,replySignature));}
registerEvent(qualifiedName,targetTypes,signature)
{let[domainName,eventName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addEvent(targetTypes,new InspectorBackend.Event(qualifiedName,eventName,signature));}
registerDispatcher(domainName,dispatcher)
{let domain=this._registeredDomains[domainName];domain._addDispatcher(dispatcher);}
activateDomain(domainName,debuggableTypes)
{

let currentDebuggableType=WI.sharedApp?.debuggableType||InspectorFrontendHost.debuggableInfo.debuggableType;if(debuggableTypes&&!debuggableTypes.includes(currentDebuggableType))
return;let domain=this._registeredDomains[domainName];this._activeDomains[domainName]=domain;let supportedTargetTypes=WI.DebuggableType.supportedTargetTypes(currentDebuggableType);for(let[targetType,command]of domain._supportedCommandsForTargetType){if(!supportedTargetTypes.has(targetType))
continue;let parameters=this._supportedCommandParameters.get(command._qualifiedName);if(!parameters){parameters=new Set;this._supportedCommandParameters.set(command._qualifiedName,parameters);}
parameters.addAll(command._callSignature.map((item)=>item.name));}
for(let[targetType,event]of domain._supportedEventsForTargetType){if(!supportedTargetTypes.has(targetType))
continue;let parameters=this._supportedEventParameters.get(event._qualifiedName);if(!parameters){parameters=new Set;this._supportedEventParameters.set(event._qualifiedName,parameters);}
parameters.addAll(event._parameterNames);}}
dispatch(message)
{InspectorBackend.backendConnection.dispatch(message);}
runAfterPendingDispatches(callback)
{if(!WI.mainTarget){callback();return;}
WI.mainTarget.connection.runAfterPendingDispatches(callback);}
supportedDomainsForTargetType(type)
{return this._supportedDomainsForTargetType.get(type)||new Set;}
hasDomain(domainName)
{return domainName in this._activeDomains;}
hasCommand(qualifiedName,parameterName)
{let parameters=this._supportedCommandParameters.get(qualifiedName);if(!parameters)
return false;return parameterName===undefined||parameters.has(parameterName);}
hasEvent(qualifiedName,parameterName)
{let parameters=this._supportedEventParameters.get(qualifiedName);if(!parameters)
return false;return parameterName===undefined||parameters.has(parameterName);}
getVersion(domainName)
{let domain=this._activeDomains[domainName];if(domain&&"VERSION"in domain)
return domain.VERSION;return-Infinity;}
invokeCommand(qualifiedName,targetType,connection,commandArguments,callback)
{let[domainName,commandName]=qualifiedName.split(".");let domain=this._activeDomains[domainName];return domain._invokeCommand(commandName,targetType,connection,commandArguments,callback);} 
_makeAgent(domainName,target)
{let domain=this._activeDomains[domainName];return domain._makeAgent(target);}
_startOrStopAutomaticTracing()
{this._defaultTracer.dumpMessagesToConsole=this.dumpInspectorProtocolMessages;this._defaultTracer.dumpTimingDataToConsole=this.dumpTimingDataToConsole;this._defaultTracer.filterMultiplexingBackend=this.filterMultiplexingBackendInspectorProtocolMessages;}};InspectorBackend=new InspectorBackendClass;InspectorBackend.Domain=class InspectorBackendDomain
{constructor(domainName)
{this._domainName=domainName;
this._dispatcher=null; this._supportedCommandsForTargetType=new Multimap;this._supportedEventsForTargetType=new Multimap;} 
_addEnum(enumName,enumValues)
{this[enumName]=enumValues;}
_addCommand(targetTypes,command)
{targetTypes=targetTypes||WI.TargetType.all;for(let type of targetTypes)
this._supportedCommandsForTargetType.add(type,command);}
_addEvent(targetTypes,event)
{targetTypes=targetTypes||WI.TargetType.all;for(let type of targetTypes)
this._supportedEventsForTargetType.add(type,event);}
_addDispatcher(dispatcher)
{this._dispatcher=dispatcher;}
_makeAgent(target)
{let commands=this._supportedCommandsForTargetType.get(target.type)||new Set;let events=this._supportedEventsForTargetType.get(target.type)||new Set;return new InspectorBackend.Agent(target,commands,events,this._dispatcher);}
_invokeCommand(commandName,targetType,connection,commandArguments,callback)
{let commands=this._supportedCommandsForTargetType.get(targetType);for(let command of commands){if(command._commandName===commandName)
return command._makeCallable(connection).invoke(commandArguments,callback);}}};InspectorBackend.Agent=class InspectorBackendAgent
{constructor(target,commands,events,dispatcher)
{
for(let command of commands){this[command._commandName]=command._makeCallable(target.connection);target._supportedCommandParameters.set(command._qualifiedName,command);}
this._events={};for(let event of events){this._events[event._eventName]=event;target._supportedEventParameters.set(event._qualifiedName,event);}
this._dispatcher=dispatcher?new dispatcher(target):null;}};InspectorBackend.Dispatcher=class InspectorBackendDispatcher
{constructor(target)
{this._target=target;}};InspectorBackend.Command=class InspectorBackendCommand
{constructor(qualifiedName,commandName,callSignature,replySignature)
{this._qualifiedName=qualifiedName;this._commandName=commandName;this._callSignature=callSignature||[];this._replySignature=replySignature||[];} 
_hasParameter(parameterName)
{return this._callSignature.some((item)=>item.name===parameterName);}
_makeCallable(connection)
{let instance=new InspectorBackend.Callable(this,connection);function callable(){return instance._invokeWithArguments.call(instance,Array.from(arguments));}
callable._instance=instance;Object.setPrototypeOf(callable,InspectorBackend.Callable.prototype);return callable;}};InspectorBackend.Event=class InspectorBackendEvent
{constructor(qualifiedName,eventName,parameterNames)
{this._qualifiedName=qualifiedName;this._eventName=eventName;this._parameterNames=parameterNames||[];} 
_hasParameter(parameterName)
{return this._parameterNames.includes(parameterName);}};InspectorBackend.Callable=function(command,connection)
{"use strict";this._command=command;this._connection=connection;this._instance=this;};InspectorBackend.Callable.prototype={__proto__:Function.prototype, invoke(commandArguments,callback)
{"use strict";let command=this._instance._command;let connection=this._instance._connection;function deliverFailure(message){console.error(`Protocol Error: ${message}`);if(callback)
setTimeout(callback.bind(null,message),0);else
return Promise.reject(new Error(message));}
if(typeof commandArguments!=="object")
return deliverFailure(`invoke expects an object for command arguments but its type is '${typeof commandArguments}'.`);let parameters={};for(let{name,type,optional}of command._callSignature){if(!(name in commandArguments)&&!optional)
return deliverFailure(`Missing argument '${name}' for command '${command._qualifiedName}'.`);let value=commandArguments[name];if(optional&&value===undefined)
continue;if(typeof value!==type)
return deliverFailure(`Invalid type of argument '${name}' for command '${command._qualifiedName}' call. It must be '${type}' but it is '${typeof value}'.`);parameters[name]=value;}
if(typeof callback==="function")
connection._sendCommandToBackendWithCallback(command,parameters,callback);else
return connection._sendCommandToBackendExpectingPromise(command,parameters);}, _invokeWithArguments(commandArguments)
{"use strict";let command=this._instance._command;let connection=this._instance._connection;let callback=typeof commandArguments.lastValue==="function"?commandArguments.pop():null;function deliverFailure(message){console.error(`Protocol Error: ${message}`);if(callback)
setTimeout(callback.bind(null,message),0);else
return Promise.reject(new Error(message));}
let parameters={};for(let{name,type,optional}of command._callSignature){if(!commandArguments.length&&!optional)
return deliverFailure(`Invalid number of arguments for command '${command._qualifiedName}'.`);let value=commandArguments.shift();if(optional&&value===undefined)
continue;if(typeof value!==type)
return deliverFailure(`Invalid type of argument '${name}' for command '${command._qualifiedName}' call. It must be '${type}' but it is '${typeof value}'.`);parameters[name]=value;}
if(!callback&&commandArguments.length===1&&commandArguments[0]!==undefined)
return deliverFailure(`Protocol Error: Optional callback argument for command '${command._qualifiedName}' call must be a function but its type is '${typeof commandArguments[0]}'.`);if(callback)
connection._sendCommandToBackendWithCallback(command,parameters,callback);else
return connection._sendCommandToBackendExpectingPromise(command,parameters);}};InspectorBackend.globalSequenceId=1;InspectorBackend.Connection=class InspectorBackendConnection
{constructor()
{this._pendingResponses=new Map;this._deferredCallbacks=[];this._target=null;this._provisionalMessages=[];} 
get target()
{return this._target;}
set target(target)
{this._target=target;}
addProvisionalMessage(message)
{this._provisionalMessages.push(message);}
dispatchProvisionalMessages()
{for(let message of this._provisionalMessages)
this.dispatch(message);this._provisionalMessages=[];}
dispatch(message)
{let messageObject=typeof message==="string"?JSON.parse(message):message;if("id"in messageObject)
this._dispatchResponse(messageObject);else
this._dispatchEvent(messageObject);}
runAfterPendingDispatches(callback)
{if(!this._pendingResponses.size)
callback.call(this);else
this._deferredCallbacks.push(callback);} 
sendMessageToBackend(message)
{throw new Error("Should be implemented by a InspectorBackend.Connection subclass");} 
_dispatchResponse(messageObject)
{if(messageObject.error&&messageObject.error.code!==-32_000)
console.error("Request with id = "+messageObject["id"]+" failed. "+JSON.stringify(messageObject.error));let sequenceId=messageObject["id"];let responseData=this._pendingResponses.take(sequenceId)||{};let{request,command,callback,promise}=responseData;let processingStartTimestamp=performance.now();for(let tracer of InspectorBackend.activeTracers)
tracer.logWillHandleResponse(this,messageObject);InspectorBackend.currentDispatchState.request=request;InspectorBackend.currentDispatchState.response=messageObject;if(typeof callback==="function")
this._dispatchResponseToCallback(command,request,messageObject,callback);else if(typeof promise==="object")
this._dispatchResponseToPromise(command,messageObject,promise);else
console.error("Received a command response without a corresponding callback or promise.",messageObject,command);InspectorBackend.currentDispatchState.request=null;InspectorBackend.currentDispatchState.response=null;let processingTime=(performance.now()-processingStartTimestamp).toFixed(3);let roundTripTime=(processingStartTimestamp-responseData.sendRequestTimestamp).toFixed(3);for(let tracer of InspectorBackend.activeTracers)
tracer.logDidHandleResponse(this,messageObject,{rtt:roundTripTime,dispatch:processingTime});if(this._deferredCallbacks.length&&!this._pendingResponses.size)
this._flushPendingScripts();}
_dispatchResponseToCallback(command,requestObject,responseObject,callback)
{let callbackArguments=[];callbackArguments.push(responseObject["error"]?responseObject["error"].message:null);if(responseObject["result"]){for(let parameterName of command._replySignature)
callbackArguments.push(responseObject["result"][parameterName]);}
try{callback.apply(null,callbackArguments);}catch(e){WI.reportInternalError(e,{"cause":`An uncaught exception was thrown while dispatching response callback for command ${command._qualifiedName}.`});}}
_dispatchResponseToPromise(command,messageObject,promise)
{let{resolve,reject}=promise;if(messageObject["error"])
reject(new Error(messageObject["error"].message));else
resolve(messageObject["result"]);}
_dispatchEvent(messageObject)
{let qualifiedName=messageObject.method;let[domainName,eventName]=qualifiedName.split(".");

if(!this._target&&this===InspectorBackend.backendConnection&&WI.sharedApp.debuggableType===WI.DebuggableType.WebPage&&qualifiedName==="Target.targetCreated")
WI.targetManager.createMultiplexingBackendTarget();let agent=this._target._agents[domainName];if(!agent){console.error(`Protocol Error: Attempted to dispatch method '${qualifiedName}' for non-existing domain '${domainName}'`,messageObject);return;}
let dispatcher=agent._dispatcher;if(!dispatcher){console.error(`Protocol Error: Missing dispatcher for domain '${domainName}', for event '${qualifiedName}'`,messageObject);return;}
let event=agent._events[eventName];if(!event){console.error(`Protocol Error: Attempted to dispatch an unspecified method '${qualifiedName}'`,messageObject);return;}
let handler=dispatcher[eventName];if(!handler){console.error(`Protocol Error: Attempted to dispatch an unimplemented method '${qualifiedName}'`,messageObject);return;}
let processingStartTimestamp=performance.now();for(let tracer of InspectorBackend.activeTracers)
tracer.logWillHandleEvent(this,messageObject);InspectorBackend.currentDispatchState.event=messageObject;try{let params=messageObject.params||{};handler.apply(dispatcher,event._parameterNames.map((name)=>params[name]));}catch(e){for(let tracer of InspectorBackend.activeTracers)
tracer.logFrontendException(this,messageObject,e);WI.reportInternalError(e,{"cause":`An uncaught exception was thrown while handling event: ${qualifiedName}`});}
InspectorBackend.currentDispatchState.event=null;let processingDuration=(performance.now()-processingStartTimestamp).toFixed(3);for(let tracer of InspectorBackend.activeTracers)
tracer.logDidHandleEvent(this,messageObject,{dispatch:processingDuration});}
_sendCommandToBackendWithCallback(command,parameters,callback)
{let sequenceId=InspectorBackend.globalSequenceId++;let messageObject={"id":sequenceId,"method":command._qualifiedName,};if(!isEmptyObject(parameters))
messageObject["params"]=parameters;let responseData={command,request:messageObject,callback};if(InspectorBackend.activeTracer)
responseData.sendRequestTimestamp=performance.now();this._pendingResponses.set(sequenceId,responseData);this._sendMessageToBackend(messageObject);}
_sendCommandToBackendExpectingPromise(command,parameters)
{let sequenceId=InspectorBackend.globalSequenceId++;let messageObject={"id":sequenceId,"method":command._qualifiedName,};if(!isEmptyObject(parameters))
messageObject["params"]=parameters;let responseData={command,request:messageObject};if(InspectorBackend.activeTracer)
responseData.sendRequestTimestamp=performance.now();let responsePromise=new Promise(function(resolve,reject){responseData.promise={resolve,reject};});this._pendingResponses.set(sequenceId,responseData);this._sendMessageToBackend(messageObject);return responsePromise;}
_sendMessageToBackend(messageObject)
{for(let tracer of InspectorBackend.activeTracers)
tracer.logFrontendRequest(this,messageObject);this.sendMessageToBackend(JSON.stringify(messageObject));}
_flushPendingScripts()
{let scriptsToRun=this._deferredCallbacks;this._deferredCallbacks=[];for(let script of scriptsToRun)
script.call(this);}};InspectorBackend.BackendConnection=class InspectorBackendBackendConnection extends InspectorBackend.Connection
{sendMessageToBackend(message)
{InspectorFrontendHost.sendMessageToBackend(message);}};InspectorBackend.WorkerConnection=class InspectorBackendWorkerConnection extends InspectorBackend.Connection
{sendMessageToBackend(message)
{let workerId=this.target.identifier;this.target.parentTarget.WorkerAgent.sendMessageToWorker(workerId,message).catch((error)=>{if(this.target.isDestroyed)
return;WI.reportInternalError(error);});}};InspectorBackend.TargetConnection=class InspectorBackendTargetConnection extends InspectorBackend.Connection
{sendMessageToBackend(message)
{let targetId=this.target.identifier;this.target.parentTarget.TargetAgent.sendMessageToTarget(targetId,message).catch((error)=>{if(this.target.isDestroyed)
return;WI.reportInternalError(error);});}};InspectorBackend.backendConnection=new InspectorBackend.BackendConnection;InspectorFrontendAPI={_loaded:false,_pendingCommands:[],savedURL:function(url)
{},appendedToURL:function(url)
{},isTimelineProfilingEnabled:function()
{return WI.timelineManager.isCapturing();},setTimelineProfilingEnabled:function(enabled)
{if(!WI.targetsAvailable()){WI.whenTargetsAvailable().then(()=>{InspectorFrontendAPI.setTimelineProfilingEnabled(enabled);});return;}
WI.showTimelineTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI});if(WI.timelineManager.isCapturing()===enabled)
return;if(enabled)
WI.timelineManager.startCapturing();else
WI.timelineManager.stopCapturing();},setElementSelectionEnabled:function(enabled)
{if(!WI.targetsAvailable()){WI.whenTargetsAvailable().then(()=>{InspectorFrontendAPI.setElementSelectionEnabled(enabled);});return;}
WI.domManager.inspectModeEnabled=enabled;},setDockingUnavailable:function(unavailable)
{WI.updateDockingAvailability(!unavailable);},setDockSide:function(side)
{WI.updateDockedState(side);},setIsVisible:function(visible)
{WI.updateVisibilityState(visible);},updateFindString:function(findString)
{WI.updateFindString(findString);},setDiagnosticLoggingAvailable:function(available)
{if(WI.diagnosticController)
WI.diagnosticController.diagnosticLoggingAvailable=available;},showConsole:function()
{const requestedScope=null;WI.showConsoleTab(requestedScope,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});WI.quickConsole.prompt.focus();if(document.readyState!=="complete")
document.addEventListener("readystatechange",this);if(document.visibilityState!=="visible")
document.addEventListener("visibilitychange",this);},handleEvent:function(event)
{if(document.readyState==="complete"&&document.visibilityState==="visible"){WI.quickConsole.prompt.focus();document.removeEventListener("readystatechange",this);document.removeEventListener("visibilitychange",this);}},showResources:function()
{WI.showSourcesTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});},showTimelines:function()
{WI.showTimelineTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI});},showMainResourceForFrame:function(frameIdentifier)
{WI.showSourceCodeForFrame(frameIdentifier,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});},contextMenuItemSelected:function(id)
{WI.ContextMenu.contextMenuItemSelected(id);},contextMenuCleared:function()
{WI.ContextMenu.contextMenuCleared();},dispatchMessageAsync:function(messageObject)
{WI.dispatchMessageFromBackend(messageObject);},dispatchMessage:function(messageObject)
{InspectorBackend.dispatch(messageObject);},dispatch:function(signature)
{if(!InspectorFrontendAPI._loaded){InspectorFrontendAPI._pendingCommands.push(signature);return null;}
var methodName=signature.shift();if(!InspectorFrontendAPI[methodName])
return null;return InspectorFrontendAPI[methodName].apply(InspectorFrontendAPI,signature);},loadCompleted:function()
{InspectorFrontendAPI._loaded=true;for(var i=0;i<InspectorFrontendAPI._pendingCommands.length;++i)
InspectorFrontendAPI.dispatch(InspectorFrontendAPI._pendingCommands[i]);delete InspectorFrontendAPI._pendingCommands;},registerExtension(extensionID,displayName)
{return WI.sharedApp.extensionController.registerExtension(extensionID,displayName);},unregisterExtension(extensionID)
{return WI.sharedApp.extensionController.unregisterExtension(extensionID);},
createTabForExtension(extensionID,tabName,tabIconURL,sourceURL)
{return WI.sharedApp.extensionController.createTabForExtension(extensionID,tabName,tabIconURL,sourceURL);},evaluateScriptForExtension(extensionID,scriptSource,{frameURL,contextSecurityOrigin,useContentScriptContext}={})
{return WI.sharedApp.extensionController.evaluateScriptForExtension(extensionID,scriptSource,{frameURL,contextSecurityOrigin,useContentScriptContext});},reloadForExtension(extensionID,{ignoreCache,userAgent,injectedScript}={})
{return WI.sharedApp.extensionController.reloadForExtension(extensionID,{ignoreCache,userAgent,injectedScript});},showExtensionTab(extensionTabID)
{return WI.sharedApp.extensionController.showExtensionTab(extensionTabID);},evaluateScriptInExtensionTab(extensionTabID,scriptSource)
{return WI.sharedApp.extensionController.evaluateScriptInExtensionTab(extensionTabID,scriptSource);},};(function(){let backendCommandsURL=InspectorFrontendHost.backendCommandsURL||"Protocol/InspectorBackendCommands.js";document.write("<script src=\""+backendCommandsURL+"\"></script>");})();WI._messagesToDispatch=[];WI.dispatchNextQueuedMessageFromBackend=function()
{const startCount=WI._messagesToDispatch.length;const startTimestamp=performance.now();const timeLimitPerRunLoop=10; let i=0;for(;i<WI._messagesToDispatch.length;++i){
if(performance.now()-startTimestamp>timeLimitPerRunLoop)
break;InspectorBackend.dispatch(WI._messagesToDispatch[i]);}
if(i===WI._messagesToDispatch.length){WI._messagesToDispatch=[];WI._dispatchTimeout=null;}else{WI._messagesToDispatch=WI._messagesToDispatch.slice(i);WI._dispatchTimeout=setTimeout(WI.dispatchNextQueuedMessageFromBackend,0);}
if(InspectorBackend.dumpInspectorTimeStats){let messageDuration=(performance.now()-startTimestamp).toFixed(3);let dispatchedCount=startCount-WI._messagesToDispatch.length;let remainingCount=WI._messagesToDispatch.length;console.log(`time-stats: --- RunLoop duration: ${messageDuration}ms; dispatched: ${dispatchedCount}; remaining: ${remainingCount}`);}};WI.dispatchMessageFromBackend=function(message)
{this._messagesToDispatch.push(message);
if(window.__uncaughtExceptions&&window.__uncaughtExceptions.length)
return;if(this._dispatchTimeout)
return;this._dispatchTimeout=setTimeout(this.dispatchNextQueuedMessageFromBackend,0);};WI.RemoteObject=class RemoteObject
{constructor(target,objectId,type,subtype,value,description,size,classPrototype,className,preview)
{this._target=target||WI.mainTarget;this._type=type;this._subtype=subtype;if(objectId){this._objectId=objectId;this._description=description||"";this._hasChildren=type!=="symbol";this._size=size;this._classPrototype=classPrototype;this._preview=preview;if(subtype==="class"){this._functionDescription=this._description;this._description="class "+className;}}else{this._description=description||(value+"");this._hasChildren=false;this._value=value;if(type==="bigint"){if(window.BigInt)
this._value=BigInt(description.substring(0,description.length-1));else
this._value=`${description} [BigInt Not Enabled in Web Inspector]`;}}} 
static createFakeRemoteObject()
{return new WI.RemoteObject(undefined,WI.RemoteObject.FakeRemoteObjectId,"object");}
static fromPrimitiveValue(value)
{return new WI.RemoteObject(undefined,undefined,typeof value,undefined,value,undefined,undefined,undefined,undefined);}
static createBigIntFromDescriptionString(description)
{return new WI.RemoteObject(undefined,undefined,"bigint",undefined,undefined,description,undefined,undefined,undefined);}
static fromPayload(payload,target)
{if(payload.classPrototype)
payload.classPrototype=WI.RemoteObject.fromPayload(payload.classPrototype,target);if(payload.preview)
payload.preview=WI.ObjectPreview.fromPayload(payload.preview);return new WI.RemoteObject(target,payload.objectId,payload.type,payload.subtype,payload.value,payload.description,payload.size,payload.classPrototype,payload.className,payload.preview);}
static createCallArgument(valueOrObject)
{if(valueOrObject instanceof WI.RemoteObject){if(valueOrObject.objectId)
return{objectId:valueOrObject.objectId};return{value:valueOrObject.value};}
return{value:valueOrObject};}
static resolveNode(node,objectGroup)
{if(node.destroyed)
return Promise.reject("ERROR: node is destroyed");let target=WI.assumingMainTarget();return target.DOMAgent.resolveNode(node.id,objectGroup).then(({object})=>WI.RemoteObject.fromPayload(object,WI.mainTarget));}
static resolveWebSocket(webSocketResource,objectGroup,callback)
{let target=WI.assumingMainTarget();target.NetworkAgent.resolveWebSocket(webSocketResource.requestIdentifier,objectGroup,(error,object)=>{if(error||!object)
callback(null);else
callback(WI.RemoteObject.fromPayload(object,webSocketResource.target));});}
static resolveCanvasContext(canvas,objectGroup,callback)
{function wrapCallback(error,object){if(error||!object)
callback(null);else
callback(WI.RemoteObject.fromPayload(object,WI.mainTarget));}
let target=WI.assumingMainTarget();if(!target.hasCommand("Canvas.resolveContext")){target.CanvasAgent.resolveCanvasContext(canvas.identifier,objectGroup,wrapCallback);return;}
target.CanvasAgent.resolveContext(canvas.identifier,objectGroup,wrapCallback);}
static resolveAnimation(animation,objectGroup,callback)
{function wrapCallback(error,object){if(error||!object)
callback(null);else
callback(WI.RemoteObject.fromPayload(object,WI.mainTarget));}
let target=WI.assumingMainTarget();target.AnimationAgent.resolveAnimation(animation.animationId,objectGroup,wrapCallback);} 
get target()
{return this._target;}
get objectId()
{return this._objectId;}
get type()
{return this._type;}
get subtype()
{return this._subtype;}
get description()
{return this._description;}
get functionDescription()
{return this._functionDescription||this._description;}
get hasChildren()
{return this._hasChildren;}
get value()
{return this._value;}
get size()
{return this._size||0;}
get classPrototype()
{return this._classPrototype;}
get preview()
{return this._preview;}
hasSize()
{return this.isArray()||this.isCollectionType();}
hasValue()
{return"_value"in this;}
canLoadPreview()
{if(this._failedToLoadPreview)
return false;if(this._type!=="object")
return false;if(!this._objectId||this._isSymbol()||this._isFakeObject())
return false;return true;}
updatePreview(callback)
{if(!this.canLoadPreview()){callback(null);return;}
if(!this._target.hasCommand("Runtime.getPreview")){this._failedToLoadPreview=true;callback(null);return;}
this._target.RuntimeAgent.getPreview(this._objectId,(error,payload)=>{if(error){this._failedToLoadPreview=true;callback(null);return;}
this._preview=WI.ObjectPreview.fromPayload(payload);callback(this._preview);});}
getPropertyDescriptors(callback,options={})
{if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback([]);return;}
this._getProperties(this._getPropertyDescriptorsResolver.bind(this,callback),options);}
getDisplayablePropertyDescriptors(callback,options={})
{if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback([]);return;}
this._getDisplayableProperties(this._getPropertyDescriptorsResolver.bind(this,callback),options);}
setPropertyValue(name,value,callback)
{if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback("Can't set a property of non-object.");return;}
this._target.RuntimeAgent.evaluate.invoke({expression:appendWebInspectorSourceURL(value),doNotPauseOnExceptionsAndMuteConsole:true},evaluatedCallback.bind(this));function evaluatedCallback(error,result,wasThrown)
{if(error||wasThrown){callback(error||result.description);return;}
function setPropertyValue(propertyName,propertyValue)
{this[propertyName]=propertyValue;}
delete result.description;this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(setPropertyValue.toString()),[{value:name},result],true,undefined,propertySetCallback.bind(this));if(result._objectId)
this._target.RuntimeAgent.releaseObject(result._objectId);}
function propertySetCallback(error,result,wasThrown)
{if(error||wasThrown){callback(error||result.description);return;}
callback();}}
isUndefined()
{return this._type==="undefined";}
isNode()
{return this._subtype==="node";}
isArray()
{return this._subtype==="array";}
isClass()
{return this._subtype==="class";}
isCollectionType()
{return this._subtype==="map"||this._subtype==="set"||this._subtype==="weakmap"||this._subtype==="weakset";}
isWeakCollection()
{return this._subtype==="weakmap"||this._subtype==="weakset";}
getCollectionEntries(callback,{fetchStart,fetchCount}={})
{let objectGroup=this.isWeakCollection()?this._weakCollectionObjectGroup():"";this._target.RuntimeAgent.getCollectionEntries(this._objectId,objectGroup,fetchStart,fetchCount,(error,entries)=>{callback(entries.map((x)=>WI.CollectionEntry.fromPayload(x,this._target)));});}
releaseWeakCollectionEntries()
{this._target.RuntimeAgent.releaseObjectGroup(this._weakCollectionObjectGroup());}
pushNodeToFrontend(callback)
{if(this._objectId&&InspectorBackend.hasCommand("DOM.requestNode"))
WI.domManager.pushNodeToFrontend(this._objectId,callback);else
callback(0);}
async fetchProperties(propertyNames,resultObject={})
{let seenPropertyNames=new Set;let requestedValues=[];for(let propertyName of propertyNames){if(typeof propertyName!=="string"&&typeof propertyName!=="number")
throw new Error(`Tried to get property using key is not a string or number: ${propertyName}`);if(seenPropertyNames.has(propertyName))
continue;seenPropertyNames.add(propertyName);requestedValues.push(this.getProperty(propertyName));}
function maybeUnwrapValue(remoteObject){return remoteObject.hasValue()?remoteObject.value:remoteObject;}

let fetchedKeys=Array.from(seenPropertyNames);let fetchedValues=await Promise.all(requestedValues);for(let i=0;i<fetchedKeys.length;++i)
resultObject[fetchedKeys[i]]=maybeUnwrapValue(fetchedValues[i]);return resultObject;}
getProperty(propertyName,callback=null)
{function inspectedPage_object_getProperty(property){if(typeof property!=="string"&&typeof property!=="number")
throw new Error(`Tried to get property using key is not a string or number: ${property}`);return this[property];}
if(callback&&typeof callback==="function")
this.callFunction(inspectedPage_object_getProperty,[propertyName],true,callback);else
return this.callFunction(inspectedPage_object_getProperty,[propertyName],true);}
callFunction(functionDeclaration,args,generatePreview,callback=null)
{let translateResult=(result)=>result?WI.RemoteObject.fromPayload(result,this._target):null;if(args)
args=args.map(WI.RemoteObject.createCallArgument);if(callback&&typeof callback==="function"){this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,undefined,!!generatePreview,(error,result,wasThrown)=>{callback(error,translateResult(result),wasThrown);});}else{return this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,undefined,!!generatePreview).then(({result,wasThrown})=>{result=translateResult(result);if(result&&wasThrown)
return Promise.reject(result);return Promise.resolve(result);});}}
callFunctionJSON(functionDeclaration,args,callback)
{function mycallback(error,result,wasThrown)
{callback((error||wasThrown)?null:result.value);}
this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,true,mycallback);}
invokeGetter(getterRemoteObject,callback)
{function backendInvokeGetter(getter)
{return getter?getter.call(this):undefined;}
this.callFunction(backendInvokeGetter,[getterRemoteObject],true,callback);}
getOwnPropertyDescriptor(propertyName,callback)
{function backendGetOwnPropertyDescriptor(propertyName)
{return this[propertyName];}
function wrappedCallback(error,result,wasThrown)
{if(error||wasThrown||!(result instanceof WI.RemoteObject)){callback(null);return;}
var fakeDescriptor={name:propertyName,value:result,writable:true,configurable:true};var fakePropertyDescriptor=new WI.PropertyDescriptor(fakeDescriptor,null,true,false,false,false);callback(fakePropertyDescriptor);}
this.callFunction(backendGetOwnPropertyDescriptor,[propertyName],false,wrappedCallback.bind(this));}
release()
{if(this._objectId&&!this._isFakeObject())
this._target.RuntimeAgent.releaseObject(this._objectId);}
arrayLength()
{if(this._subtype!=="array")
return 0;var matches=this._description.match(/\[([0-9]+)\]/);if(!matches)
return 0;return parseInt(matches[1],10);}
asCallArgument()
{return WI.RemoteObject.createCallArgument(this);}
findFunctionSourceCodeLocation()
{var result=new WI.WrappedPromise;if(!this._isFunction()||!this._objectId){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.MissingObjectId);return result.promise;}
this._target.DebuggerAgent.getFunctionDetails(this._objectId,(error,response)=>{if(error){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound);return;}
var location=response.location;var sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,this._target);if(!sourceCode||(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(sourceCode.sourceURL))){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound);return;}
var sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);result.resolve(sourceCodeLocation);});return result.promise;} 
_isFakeObject()
{return this._objectId===WI.RemoteObject.FakeRemoteObjectId;}
_isSymbol()
{return this._type==="symbol";}
_isFunction()
{return this._type==="function";}
_weakCollectionObjectGroup()
{return JSON.stringify(this._objectId)+"-"+this._subtype;}
_getProperties(callback,{ownProperties,fetchStart,fetchCount,generatePreview}={})
{this._target.RuntimeAgent.getProperties.invoke({objectId:this._objectId,ownProperties,fetchStart,fetchCount,generatePreview,},callback);}
_getDisplayableProperties(callback,{fetchStart,fetchCount,generatePreview}={})
{this._target.RuntimeAgent.getDisplayableProperties.invoke({objectId:this._objectId,fetchStart,fetchCount,generatePreview,},callback);}
_getPropertyDescriptorsResolver(callback,error,properties,internalProperties)
{if(error){callback(null);return;}
let descriptors=properties.map((payload)=>WI.PropertyDescriptor.fromPayload(payload,false,this._target));if(internalProperties){for(let payload of internalProperties)
descriptors.push(WI.PropertyDescriptor.fromPayload(payload,true,this._target));}
callback(descriptors);}};WI.RemoteObject.FakeRemoteObjectId="fake-remote-object";WI.RemoteObject.SourceCodeLocationPromise={NoSourceFound:"remote-object-source-code-location-promise-no-source-found",MissingObjectId:"remote-object-source-code-location-promise-missing-object-id"};WI.Target=class Target extends WI.Object
{constructor(parentTarget,identifier,name,type,connection,{isPaused,isProvisional}={})
{super();this._parentTarget=parentTarget;this._identifier=identifier;this._name=name;this._type=type;this._connection=connection;this._isPaused=!!isPaused;this._isProvisional=!!isProvisional;this._executionContext=null;this._mainResource=null;this._resourceCollection=new WI.ResourceCollection;this._extraScriptCollection=new WI.ScriptCollection;this._supportedCommandParameters=new Map;this._supportedEventParameters=new Map;
this._agents={};for(let domainName of InspectorBackend.supportedDomainsForTargetType(this._type))
this._agents[domainName]=InspectorBackend._makeAgent(domainName,this);this._connection.target=this;} 
initialize()
{if(this.hasDomain("Inspector"))
this.InspectorAgent.enable();for(let manager of WI.managers){if(manager.initializeTarget)
manager.initializeTarget(this);}
WI.initializeTarget(this);

this.ConsoleAgent.enable();setTimeout(()=>{
WI.performOneTimeFrontendInitializationsUsingTarget(this);});Promise.all(Target._initializationPromises).then(()=>{
if(this.hasDomain("Inspector"))
this.InspectorAgent.initialized();});this._resumeIfPaused();}
_resumeIfPaused()
{if(this._isPaused){this._parentTarget.TargetAgent.resume(this._identifier,(error)=>{if(error){if(!this.isDestroyed)
WI.reportInternalError(error);return;}
this._isPaused=false;});}}
activateExtraDomain(domainName)
{ this._agents[domainName]=InspectorBackend._makeAgent(domainName,this);} 
get AnimationAgent(){return this._agents.Animation;}
get ApplicationCacheAgent(){return this._agents.ApplicationCache;}
get AuditAgent(){return this._agents.Audit;}
get BrowserAgent(){return this._agents.Browser;}
get CPUProfilerAgent(){return this._agents.CPUProfiler;}
get CSSAgent(){return this._agents.CSS;}
get CanvasAgent(){return this._agents.Canvas;}
get ConsoleAgent(){return this._agents.Console;}
get DOMAgent(){return this._agents.DOM;}
get DOMDebuggerAgent(){return this._agents.DOMDebugger;}
get DOMStorageAgent(){return this._agents.DOMStorage;}
get DatabaseAgent(){return this._agents.Database;}
get DebuggerAgent(){return this._agents.Debugger;}
get HeapAgent(){return this._agents.Heap;}
get IndexedDBAgent(){return this._agents.IndexedDB;}
get InspectorAgent(){return this._agents.Inspector;}
get LayerTreeAgent(){return this._agents.LayerTree;}
get MemoryAgent(){return this._agents.Memory;}
get NetworkAgent(){return this._agents.Network;}
get PageAgent(){return this._agents.Page;}
get RecordingAgent(){return this._agents.Recording;}
get RuntimeAgent(){return this._agents.Runtime;}
get ScriptProfilerAgent(){return this._agents.ScriptProfiler;}
get ServiceWorkerAgent(){return this._agents.ServiceWorker;}
get TargetAgent(){return this._agents.Target;}
get TimelineAgent(){return this._agents.Timeline;}
get WorkerAgent(){return this._agents.Worker;} 
static registerInitializationPromise(promise)
{Target._initializationPromises.push(promise);promise.then(()=>{++Target._completedInitializationPromiseCount;Target._initializationPromises.remove(promise);});} 
get parentTarget(){return this._parentTarget;}
get rootTarget()
{if(this._type===WI.TargetType.Page)
return this;if(this._parentTarget)
return this._parentTarget.rootTarget;return this;}
get identifier(){return this._identifier;}
set identifier(identifier){this._identifier=identifier;}
get name(){return this._name;}
set name(name){this._name=name;}
get type(){return this._type;}
get connection(){return this._connection;}
get executionContext(){return this._executionContext;}
get resourceCollection(){return this._resourceCollection;}
get extraScriptCollection(){return this._extraScriptCollection;}
get isProvisional(){return this._isProvisional;}
get isPaused(){return this._isPaused;}
get isDestroyed(){return this._isDestroyed;}
get displayName(){return this._name;}
get mainResource()
{return this._mainResource;}
set mainResource(resource)
{this._mainResource=resource;this.dispatchEventToListeners(WI.Target.Event.MainResourceAdded,{resource});}
addResource(resource)
{this._resourceCollection.add(resource);this.dispatchEventToListeners(WI.Target.Event.ResourceAdded,{resource});}
adoptResource(resource)
{resource._target=this;this.addResource(resource);}
addScript(script)
{this._extraScriptCollection.add(script);this.dispatchEventToListeners(WI.Target.Event.ScriptAdded,{script});}
didCommitProvisionalTarget()
{this._isProvisional=false;}
destroy()
{this._isDestroyed=true;}
hasDomain(domainName)
{return domainName in this._agents;}
hasCommand(qualifiedName,parameterName)
{let command=this._supportedCommandParameters.get(qualifiedName);if(!command)
return false;return parameterName===undefined||command._hasParameter(parameterName);}
hasEvent(qualifiedName,parameterName)
{let event=this._supportedEventParameters.get(qualifiedName);if(!event)
return false;return parameterName===undefined||event._hasParameter(parameterName);}};WI.Target.Event={MainResourceAdded:"target-main-resource-added",ResourceAdded:"target-resource-added",ScriptAdded:"target-script-added",};WI.Target._initializationPromises=[];WI.Target._completedInitializationPromiseCount=0;WI.DirectBackendTarget=class DirectBackendTarget extends WI.Target
{constructor()
{const parentTarget=null;const targetId="direct";let{type,displayName}=DirectBackendTarget.connectionInfoForDebuggable();super(parentTarget,targetId,displayName,type,InspectorBackend.backendConnection);this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,displayName);this._mainResource=null;} 
static connectionInfoForDebuggable()
{switch(WI.sharedApp.debuggableType){case WI.DebuggableType.ITML:return{type:WI.TargetType.ITML,displayName:WI.UIString("ITML Context"),};case WI.DebuggableType.JavaScript:return{type:WI.TargetType.JavaScript,displayName:WI.UIString("JavaScript Context"),};case WI.DebuggableType.Page:return{type:WI.TargetType.Page,displayName:WI.UIString("Page"),};case WI.DebuggableType.ServiceWorker:return{type:WI.TargetType.ServiceWorker,displayName:WI.UIString("ServiceWorker"),};case WI.DebuggableType.WebPage:return{type:WI.TargetType.WebPage,displayName:WI.UIString("Page"),};default:console.error("Unexpected debuggable type: ",WI.sharedApp.debuggableType);return{type:WI.TargetType.JavaScript,displayName:WI.UIString("JavaScript Context"),};}}
get mainResource()
{if(this._mainResource)
return this._mainResource;let mainFrame=WI.networkManager.mainFrame;return mainFrame?mainFrame.mainResource:null;}
set mainResource(resource)
{this._mainResource=resource;}};WI.MultiplexingBackendTarget=class MultiplexingBackendTarget extends WI.Target
{constructor()
{const parentTarget=null;const targetId="multi";super(parentTarget,targetId,WI.UIString("Web Page"),WI.TargetType.WebPage,InspectorBackend.backendConnection);} 
initialize()
{WI.browserManager.initializeTarget(this);WI.targetManager.initializeTarget(this);}
get name()
{console.error("Called name on a MultiplexingBackendTarget");return WI.UIString("Page");}
get executionContext()
{console.error("Called executionContext on a MultiplexingBackendTarget");return null;}
get mainResource()
{console.error("Called mainResource on a MultiplexingBackendTarget");return null;}};WI.PageTarget=class PageTarget extends WI.Target
{constructor(parentTarget,targetId,name,connection,options={})
{super(parentTarget,targetId,name,WI.TargetType.Page,connection,options);this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,this.displayName);}};WI.WorkerTarget=class WorkerTarget extends WI.Target
{constructor(parentTarget,workerId,url,displayName,connection,options={})
{super(parentTarget,workerId,url,WI.TargetType.Worker,connection,options);this._displayName=displayName;this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,this.displayName);}
get customName()
{return this._displayName;}
get displayName()
{return this._displayName||this.displayURL;}
get displayURL()
{return WI.displayNameForURL(this._name);}};WI.AnimationObserver=class AnimationObserver extends InspectorBackend.Dispatcher
{animationCreated(animation)
{WI.animationManager.animationCreated(animation);}
nameChanged(animationId,name)
{WI.animationManager.nameChanged(animationId,name);}
effectChanged(animationId,effect)
{WI.animationManager.effectChanged(animationId,effect);}
targetChanged(animationId)
{WI.animationManager.targetChanged(animationId);}
animationDestroyed(animationId)
{WI.animationManager.animationDestroyed(animationId);}
trackingStart(timestamp)
{WI.timelineManager.animationTrackingStarted(timestamp);}
trackingUpdate(timestamp,event)
{WI.timelineManager.animationTrackingUpdated(timestamp,event);}
trackingComplete(timestamp)
{WI.timelineManager.animationTrackingCompleted(timestamp);}};WI.ApplicationCacheObserver=class ApplicationCacheObserver extends InspectorBackend.Dispatcher
{applicationCacheStatusUpdated(frameId,manifestURL,status)
{WI.applicationCacheManager.applicationCacheStatusUpdated(frameId,manifestURL,status);}
networkStateUpdated(isNowOnline)
{WI.applicationCacheManager.networkStateUpdated(isNowOnline);}};WI.BrowserObserver=class BrowserObserver extends InspectorBackend.Dispatcher
{extensionsEnabled(extensions)
{WI.browserManager.extensionsEnabled(extensions);}
extensionsDisabled(extensionIds)
{WI.browserManager.extensionsDisabled(extensionIds);}};WI.CPUProfilerObserver=class CPUProfilerObserver extends InspectorBackend.Dispatcher
{trackingStart(timestamp)
{WI.timelineManager.cpuProfilerTrackingStarted(timestamp);}
trackingUpdate(event)
{WI.timelineManager.cpuProfilerTrackingUpdated(event);}
trackingComplete(timestamp)
{WI.timelineManager.cpuProfilerTrackingCompleted(timestamp);}};WI.CSSObserver=class CSSObserver extends InspectorBackend.Dispatcher
{mediaQueryResultChanged()
{WI.cssManager.mediaQueryResultChanged();}
styleSheetChanged(styleSheetId)
{WI.cssManager.styleSheetChanged(styleSheetId);}
styleSheetAdded(styleSheetInfo)
{WI.cssManager.styleSheetAdded(styleSheetInfo);}
styleSheetRemoved(id)
{WI.cssManager.styleSheetRemoved(id);}
nodeLayoutContextTypeChanged(nodeId,layoutContextType)
{WI.domManager.nodeLayoutContextTypeChanged(nodeId,layoutContextType);}
namedFlowCreated(namedFlow)
{}
namedFlowRemoved(documentNodeId,flowName)
{}
regionOversetChanged(namedFlow)
{}
registeredNamedFlowContentElement(documentNodeId,flowName,contentNodeId,nextContentElementNodeId)
{}
unregisteredNamedFlowContentElement(documentNodeId,flowName,contentNodeId)
{}};WI.CanvasObserver=class CanvasObserver extends InspectorBackend.Dispatcher
{canvasAdded(canvas)
{WI.canvasManager.canvasAdded(canvas);}
canvasRemoved(canvasId)
{WI.canvasManager.canvasRemoved(canvasId);}
canvasMemoryChanged(canvasId,memoryCost)
{WI.canvasManager.canvasMemoryChanged(canvasId,memoryCost);}
clientNodesChanged(canvasId)
{WI.canvasManager.clientNodesChanged(canvasId);}
recordingStarted(canvasId,initiator)
{WI.canvasManager.recordingStarted(canvasId,initiator);}
recordingProgress(canvasId,frames,bufferUsed)
{WI.canvasManager.recordingProgress(canvasId,frames,bufferUsed);}
recordingFinished(canvasId,recording)
{WI.canvasManager.recordingFinished(canvasId,recording);}
extensionEnabled(canvasId,extension)
{WI.canvasManager.extensionEnabled(canvasId,extension);}
programCreated(shaderProgram)
{if(arguments.length===2){shaderProgram={canvasId:arguments[0],programId:arguments[1],};}
WI.canvasManager.programCreated(shaderProgram);}
programDeleted(programId)
{WI.canvasManager.programDeleted(programId);}
cssCanvasClientNodesChanged(canvasId)
{WI.canvasManager.clientNodesChanged(canvasId);}};WI.ConsoleObserver=class ConsoleObserver extends InspectorBackend.Dispatcher
{messageAdded(message)
{if(message.source==="console-api"&&message.type==="clear")
return;if(message.type==="assert"&&!message.text)
message.text=WI.UIString("Assertion");WI.consoleManager.messageWasAdded(this._target,message.source,message.level,message.text,message.type,message.url,message.line,message.column||0,message.repeatCount,message.parameters,message.stackTrace,message.networkRequestId);}
messageRepeatCountUpdated(count)
{WI.consoleManager.messageRepeatCountUpdated(count);}
messagesCleared()
{WI.consoleManager.messagesCleared();}
heapSnapshot(timestamp,snapshotStringData,title)
{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,title||null,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);});}};WI.DOMObserver=class DOMObserver extends InspectorBackend.Dispatcher
{documentUpdated()
{WI.domManager._documentUpdated();}
inspect(nodeId)
{WI.domManager.inspectElement(nodeId);}
setChildNodes(parentId,nodes)
{WI.domManager._setChildNodes(parentId,nodes);}
attributeModified(nodeId,name,value)
{WI.domManager._attributeModified(nodeId,name,value);}
attributeRemoved(nodeId,name)
{WI.domManager._attributeRemoved(nodeId,name);}
inlineStyleInvalidated(nodeIds)
{WI.domManager._inlineStyleInvalidated(nodeIds);}
characterDataModified(nodeId,characterData)
{WI.domManager._characterDataModified(nodeId,characterData);}
childNodeCountUpdated(nodeId,childNodeCount)
{WI.domManager._childNodeCountUpdated(nodeId,childNodeCount);}
childNodeInserted(parentNodeId,previousNodeId,node)
{WI.domManager._childNodeInserted(parentNodeId,previousNodeId,node);}
childNodeRemoved(parentNodeId,nodeId)
{WI.domManager._childNodeRemoved(parentNodeId,nodeId);}
willDestroyDOMNode(nodeId)
{WI.domManager.willDestroyDOMNode(nodeId);}
shadowRootPushed(hostId,root)
{WI.domManager._childNodeInserted(hostId,0,root);}
shadowRootPopped(hostId,rootId)
{WI.domManager._childNodeRemoved(hostId,rootId);}
customElementStateChanged(nodeId,customElementState)
{WI.domManager._customElementStateChanged(nodeId,customElementState);}
pseudoElementAdded(parentNodeId,pseudoElement)
{WI.domManager._pseudoElementAdded(parentNodeId,pseudoElement);}
pseudoElementRemoved(parentNodeId,pseudoElementId)
{WI.domManager._pseudoElementRemoved(parentNodeId,pseudoElementId);}
didAddEventListener(nodeId)
{WI.domManager.didAddEventListener(nodeId);}
willRemoveEventListener(nodeId)
{WI.domManager.willRemoveEventListener(nodeId);}
didFireEvent(nodeId,eventName,timestamp,data)
{WI.domManager.didFireEvent(nodeId,eventName,timestamp,data);}
videoLowPowerChanged(nodeId,timestamp,isLowPower)
{WI.domManager.powerEfficientPlaybackStateChanged(nodeId,timestamp,isLowPower);}
powerEfficientPlaybackStateChanged(nodeId,timestamp,isPowerEfficient)
{WI.domManager.powerEfficientPlaybackStateChanged(nodeId,timestamp,isPowerEfficient);}};WI.DOMStorageObserver=class DOMStorageObserver extends InspectorBackend.Dispatcher
{domStorageItemsCleared(storageId)
{WI.domStorageManager.itemsCleared(storageId);}
domStorageItemRemoved(storageId,key)
{WI.domStorageManager.itemRemoved(storageId,key);}
domStorageItemAdded(storageId,key,value)
{WI.domStorageManager.itemAdded(storageId,key,value);}
domStorageItemUpdated(storageId,key,oldValue,newValue)
{WI.domStorageManager.itemUpdated(storageId,key,oldValue,newValue);}};WI.DatabaseObserver=class DatabaseObserver extends InspectorBackend.Dispatcher
{addDatabase(database)
{WI.databaseManager.databaseWasAdded(database.id,database.domain,database.name,database.version);}};WI.DebuggerObserver=class DebuggerObserver extends InspectorBackend.Dispatcher
{constructor(target)
{super(target);this._legacyScriptParsed=this._target.hasEvent("Debugger.scriptParsed","hasSourceURL");}
globalObjectCleared()
{WI.debuggerManager.globalObjectCleared(this._target);}
scriptParsed(scriptId,url,startLine,startColumn,endLine,endColumn,isContentScript,sourceURL,sourceMapURL,isModule)
{WI.debuggerManager.scriptDidParse(this._target,scriptId,url,startLine,startColumn,endLine,endColumn,isModule,isContentScript,sourceURL,sourceMapURL);}
scriptFailedToParse(url,scriptSource,startLine,errorLine,errorMessage)
{WI.debuggerManager.scriptDidFail(this._target,url,scriptSource);}
breakpointResolved(breakpointId,location)
{WI.debuggerManager.breakpointResolved(this._target,breakpointId,location);}
paused(callFrames,reason,data,asyncStackTrace)
{WI.debuggerManager.debuggerDidPause(this._target,callFrames,reason,data,asyncStackTrace);}
resumed()
{WI.debuggerManager.debuggerDidResume(this._target);}
playBreakpointActionSound(breakpointActionIdentifier)
{WI.debuggerManager.playBreakpointActionSound(breakpointActionIdentifier);}
didSampleProbe(sample)
{WI.debuggerManager.didSampleProbe(this._target,sample);}};WI.HeapObserver=class HeapObserver extends InspectorBackend.Dispatcher
{garbageCollected(collection)
{WI.heapManager.garbageCollected(this._target,collection);}
trackingStart(timestamp,snapshotStringData)
{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapTrackingStarted(timestamp,snapshot);});}
trackingComplete(timestamp,snapshotStringData)
{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapTrackingCompleted(timestamp,snapshot);});}};WI.InspectorObserver=class InspectorObserver extends InspectorBackend.Dispatcher
{evaluateForTestInFrontend(script)
{if(!InspectorFrontendHost.isUnderTest())
return;InspectorBackend.runAfterPendingDispatches(function(){window.eval(script);});}
inspect(payload,hints)
{let remoteObject=WI.RemoteObject.fromPayload(payload,WI.mainTarget);if(remoteObject.subtype==="node"){WI.domManager.inspectNodeObject(remoteObject);return;}
if(remoteObject.type==="function"){remoteObject.findFunctionSourceCodeLocation().then((sourceCodeLocation)=>{if(sourceCodeLocation instanceof WI.SourceCodeLocation){WI.showSourceCodeLocation(sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});}});remoteObject.release();return;}
if(hints.databaseId)
WI.databaseManager.inspectDatabase(hints.databaseId);else if(hints.domStorageId)
WI.domStorageManager.inspectDOMStorage(hints.domStorageId);remoteObject.release();}
activateExtraDomains(domains)
{ WI.sharedApp.activateExtraDomains(domains);}};WI.LayerTreeObserver=class LayerTreeObserver extends InspectorBackend.Dispatcher
{layerTreeDidChange()
{WI.layerTreeManager.layerTreeDidChange();}};WI.MemoryObserver=class MemoryObserver extends InspectorBackend.Dispatcher
{memoryPressure(timestamp,severity)
{WI.memoryManager.memoryPressure(timestamp,severity);}
trackingStart(timestamp)
{WI.timelineManager.memoryTrackingStarted(timestamp);}
trackingUpdate(event)
{WI.timelineManager.memoryTrackingUpdated(event);}
trackingComplete(timestamp)
{WI.timelineManager.memoryTrackingCompleted(timestamp);}};WI.NetworkObserver=class NetworkObserver extends InspectorBackend.Dispatcher
{constructor(target)
{super(target);this._legacyRequestWillBeSent=!this._target.hasEvent("Network.requestWillBeSent","walltime");}
requestWillBeSent(requestId,frameId,loaderId,documentURL,request,timestamp,walltime,initiator,redirectResponse,type,targetId)
{if(this._legacyRequestWillBeSent){walltime=undefined;initiator=arguments[6];redirectResponse=arguments[7];type=arguments[8];targetId=arguments[9];}
WI.networkManager.resourceRequestWillBeSent(requestId,frameId,loaderId,request,type,redirectResponse,timestamp,walltime,initiator,targetId);}
requestServedFromCache(requestId)
{WI.networkManager.markResourceRequestAsServedFromMemoryCache(requestId);}
responseReceived(requestId,frameId,loaderId,timestamp,type,response)
{WI.networkManager.resourceRequestDidReceiveResponse(requestId,frameId,loaderId,type,response,timestamp);}
dataReceived(requestId,timestamp,dataLength,encodedDataLength)
{WI.networkManager.resourceRequestDidReceiveData(requestId,dataLength,encodedDataLength,timestamp);}
loadingFinished(requestId,timestamp,sourceMapURL,metrics)
{WI.networkManager.resourceRequestDidFinishLoading(requestId,timestamp,sourceMapURL,metrics);}
loadingFailed(requestId,timestamp,errorText,canceled)
{WI.networkManager.resourceRequestDidFailLoading(requestId,canceled,timestamp,errorText);}
requestServedFromMemoryCache(requestId,frameId,loaderId,documentURL,timestamp,initiator,resource)
{WI.networkManager.resourceRequestWasServedFromMemoryCache(requestId,frameId,loaderId,resource,timestamp,initiator);}
webSocketCreated(requestId,url)
{WI.networkManager.webSocketCreated(requestId,url);}
webSocketWillSendHandshakeRequest(requestId,timestamp,walltime,request)
{WI.networkManager.webSocketWillSendHandshakeRequest(requestId,timestamp,walltime,request);}
webSocketHandshakeResponseReceived(requestId,timestamp,response)
{WI.networkManager.webSocketHandshakeResponseReceived(requestId,timestamp,response);}
webSocketClosed(requestId,timestamp)
{WI.networkManager.webSocketClosed(requestId,timestamp);}
webSocketFrameReceived(requestId,timestamp,response)
{WI.networkManager.webSocketFrameReceived(requestId,timestamp,response);}
webSocketFrameSent(requestId,timestamp,response)
{WI.networkManager.webSocketFrameSent(requestId,timestamp,response);}
webSocketFrameError(requestId,timestamp,errorMessage)
{}
requestIntercepted(requestId,request)
{WI.networkManager.requestIntercepted(this._target,requestId,request);}
responseIntercepted(requestId,response)
{WI.networkManager.responseIntercepted(this._target,requestId,response);}};WI.PageObserver=class PageObserver extends InspectorBackend.Dispatcher
{domContentEventFired(timestamp)
{WI.timelineManager.pageDOMContentLoadedEventFired(timestamp);}
loadEventFired(timestamp)
{WI.timelineManager.pageLoadEventFired(timestamp);}
frameNavigated(frame,loaderId)
{WI.networkManager.frameDidNavigate(frame,loaderId);}
frameDetached(frameId)
{WI.networkManager.frameDidDetach(frameId);}
defaultAppearanceDidChange(appearance)
{WI.cssManager.defaultAppearanceDidChange(appearance);}
frameStartedLoading(frameId)
{}
frameStoppedLoading(frameId)
{}
frameScheduledNavigation(frameId,delay)
{}
frameClearedScheduledNavigation(frameId)
{}};WI.RuntimeObserver=class RuntimeObserver extends InspectorBackend.Dispatcher
{executionContextCreated(contextPayload)
{WI.networkManager.executionContextCreated(contextPayload);}};WI.ScriptProfilerObserver=class ScriptProfilerObserver extends InspectorBackend.Dispatcher
{trackingStart(timestamp)
{WI.timelineManager.scriptProfilerTrackingStarted(timestamp);}
trackingUpdate(event)
{WI.timelineManager.scriptProfilerTrackingUpdated(event);}
trackingComplete(timestamp,samples)
{WI.timelineManager.scriptProfilerTrackingCompleted(timestamp,samples);}
programmaticCaptureStarted()
{}
programmaticCaptureStopped()
{}};WI.TargetObserver=class TargetObserver extends InspectorBackend.Dispatcher
{targetCreated(targetInfo)
{WI.targetManager.targetCreated(this._target,targetInfo);}
didCommitProvisionalTarget(oldTargetId,newTargetId)
{WI.targetManager.didCommitProvisionalTarget(this._target,oldTargetId,newTargetId);}
targetDestroyed(targetId)
{WI.targetManager.targetDestroyed(targetId);}
dispatchMessageFromTarget(targetId,message)
{WI.targetManager.dispatchMessageFromTarget(targetId,message);}};WI.TimelineObserver=class TimelineObserver extends InspectorBackend.Dispatcher
{eventRecorded(record)
{WI.timelineManager.eventRecorded(record);}
recordingStarted(startTime)
{WI.timelineManager.capturingStarted(startTime);}
recordingStopped(endTime)
{WI.timelineManager.capturingStopped(endTime);}
autoCaptureStarted()
{WI.timelineManager.autoCaptureStarted();}
programmaticCaptureStarted()
{}
programmaticCaptureStopped()
{}};WI.WorkerObserver=class WorkerObserver extends InspectorBackend.Dispatcher
{workerCreated(workerId,url,name)
{WI.workerManager.workerCreated(this._target,workerId,url,name);}
workerTerminated(workerId)
{WI.workerManager.workerTerminated(workerId);}
dispatchMessageFromWorker(workerId,message)
{WI.workerManager.dispatchMessageFromWorker(workerId,message);}};WI.Breakpoint=class Breakpoint extends WI.Object
{constructor({disabled,condition,actions,ignoreCount,autoContinue}={})
{super();this._disabled=disabled||false;this._condition=condition||"";this._ignoreCount=ignoreCount||0;this._autoContinue=autoContinue||false;this._actions=actions||[];for(let action of this._actions)
action.addEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);} 
toJSON(key)
{let json={};if(this._disabled)
json.disabled=this._disabled;if(this.editable){if(this._condition)
json.condition=this._condition;if(this._ignoreCount)
json.ignoreCount=this._ignoreCount;if(this._actions.length)
json.actions=this._actions.map((action)=>action.toJSON());if(this._autoContinue)
json.autoContinue=this._autoContinue;}
return json;} 
get displayName()
{throw WI.NotImplementedError.subclassMustOverride();}
get special()
{return false;}
get removable()
{return true;}
get editable()
{return false;}
get resolved()
{return WI.debuggerManager.breakpointsEnabled;}
get disabled()
{return this._disabled;}
set disabled(disabled)
{if(this._disabled===disabled)
return;this._disabled=disabled||false;this.dispatchEventToListeners(WI.Breakpoint.Event.DisabledStateDidChange);}
get condition()
{return this._condition;}
set condition(condition)
{if(this._condition===condition)
return;this._condition=condition;this.dispatchEventToListeners(WI.Breakpoint.Event.ConditionDidChange);}
get ignoreCount()
{return this._ignoreCount;}
set ignoreCount(ignoreCount)
{if(ignoreCount<0)
return;if(this._ignoreCount===ignoreCount)
return;this._ignoreCount=ignoreCount;this.dispatchEventToListeners(WI.Breakpoint.Event.IgnoreCountDidChange);}
get autoContinue()
{return this._autoContinue;}
set autoContinue(cont)
{if(this._autoContinue===cont)
return;this._autoContinue=cont;this.dispatchEventToListeners(WI.Breakpoint.Event.AutoContinueDidChange);}
get actions()
{return this._actions;}
get probeActions()
{return this._actions.filter(function(action){return action.type===WI.BreakpointAction.Type.Probe;});}
cycleToNextMode()
{if(this.disabled){if(this.editable){this.autoContinue=false;}
this.disabled=false;return;}
if(this.editable){if(this.autoContinue){this.disabled=true;return;}
if(this.actions.length){this.autoContinue=true;return;}}
this.disabled=true;}
addAction(action,{precedingAction}={})
{action.addEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);if(!precedingAction)
this._actions.push(action);else{var index=this._actions.indexOf(precedingAction);if(index===-1)
this._actions.push(action);else
this._actions.splice(index+1,0,action);}
this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);}
removeAction(action)
{var index=this._actions.indexOf(action);if(index===-1)
return;this._actions.splice(index,1);action.removeEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);if(!this._actions.length)
this.autoContinue=false;this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);}
clearActions(type)
{if(!type)
this._actions=[];else
this._actions=this._actions.filter(function(action){return action.type!==type;});this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);}
reset()
{this.condition="";this.ignoreCount=0;this.autoContinue=false;this.clearActions();}
remove()
{}
optionsToProtocol()
{let payload={};if(this._condition)
payload.condition=this._condition;if(this._actions.length){payload.actions=this._actions.map((action)=>action.toProtocol()).filter((action)=>{if(action.type!==WI.BreakpointAction.Type.Log)
return true;if(!/\$\{.*?\}/.test(action.data))
return true;let lexer=new WI.BreakpointLogMessageLexer;let tokens=lexer.tokenize(action.data);if(!tokens)
return false;let templateLiteral=tokens.reduce((text,token)=>{if(token.type===WI.BreakpointLogMessageLexer.TokenType.PlainText)
return text+token.data.escapeCharacters("`\\");if(token.type===WI.BreakpointLogMessageLexer.TokenType.Expression)
return text+"${"+token.data+"}";return text;},"");action.data="console.log(`"+templateLiteral+"`)";action.type=WI.BreakpointAction.Type.Evaluate;return true;});}
if(this._autoContinue)
payload.autoContinue=this._autoContinue;if(this._ignoreCount)
payload.ignoreCount=this._ignoreCount;return!isEmptyObject(payload)?payload:undefined;} 
_handleBreakpointActionModified(event)
{this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);}};WI.Breakpoint.TypeIdentifier="breakpoint";WI.Breakpoint.Event={DisabledStateDidChange:"breakpoint-disabled-state-did-change",ConditionDidChange:"breakpoint-condition-did-change",IgnoreCountDidChange:"breakpoint-ignore-count-did-change",ActionsDidChange:"breakpoint-actions-did-change",AutoContinueDidChange:"breakpoint-auto-continue-did-change",};WI.BreakpointAction=class BreakpointAction extends WI.Object
{constructor(type,{data,emulateUserGesture}={})
{super();this._type=type;this._data=data||null;this._id=WI.debuggerManager.nextBreakpointActionIdentifier();this._emulateUserGesture=!!emulateUserGesture;} 
static supportsEmulateUserAction()
{return WI.sharedApp.isWebDebuggable()&&InspectorBackend.hasCommand("Debugger.setPauseOnExceptions","options");} 
static fromJSON(json)
{return new WI.BreakpointAction(json.type,{data:json.data,emulateUserGesture:json.emulateUserGesture,});}
toJSON()
{let json={type:this._type,};if(this._data)
json.data=this._data;if(this._emulateUserGesture)
json.emulateUserGesture=this._emulateUserGesture;return json;} 
get id(){return this._id;}
get type()
{return this._type;}
set type(type)
{if(type===this._type)
return;this._type=type;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);}
get data()
{return this._data;}
set data(data)
{if(this._data===data)
return;this._data=data;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);}
get emulateUserGesture()
{return this._emulateUserGesture;}
set emulateUserGesture(emulateUserGesture)
{if(this._emulateUserGesture===emulateUserGesture)
return;this._emulateUserGesture=emulateUserGesture;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);}
toProtocol()
{let json=this.toJSON();json.id=this._id;return json;}};WI.BreakpointAction.Type={Log:"log",Evaluate:"evaluate",Sound:"sound",Probe:"probe"};WI.BreakpointAction.Event={Modified:"breakpoint-action-modified",};WI.Collection=class Collection extends WI.Object
{constructor(items=[])
{super();this._items=new Set;for(let item of items)
this.add(item);} 
get size()
{return this._items.size;}
get displayName()
{throw WI.NotImplementedError.subclassMustOverride();}
objectIsRequiredType(object)
{throw WI.NotImplementedError.subclassMustOverride();}
add(item)
{let isValidType=this.objectIsRequiredType(item);if(!isValidType)
return;this._items.add(item);this.itemAdded(item);this.dispatchEventToListeners(WI.Collection.Event.ItemAdded,{item});}
remove(item)
{let wasRemoved=this._items.delete(item);this.itemRemoved(item);this.dispatchEventToListeners(WI.Collection.Event.ItemRemoved,{item});}
has(...args)
{return this._items.has(...args);}
clear()
{let items=new Set(this._items);this._items.clear();this.itemsCleared(items);for(let item of items)
this.dispatchEventToListeners(WI.Collection.Event.ItemRemoved,{item});}
toJSON()
{return Array.from(this);}
[Symbol.iterator]()
{return this._items[Symbol.iterator]();} 
itemAdded(item)
{}
itemRemoved(item)
{}
itemsCleared(items)
{}};WI.Collection.Event={ItemAdded:"collection-item-added",ItemRemoved:"collection-item-removed",};WI.ConsoleMessage=class ConsoleMessage
{constructor(target,source,level,message,type,url,line,column,repeatCount,parameters,callFrames,request)
{this._target=target;this._source=source;this._level=level;this._messageText=message;this._type=type||WI.ConsoleMessage.MessageType.Log;this._url=url||null;this._line=line||0;this._column=column||0;this._sourceCodeLocation=undefined;this._repeatCount=repeatCount||0;this._parameters=parameters;callFrames=callFrames||[];this._stackTrace=WI.StackTrace.fromPayload(this._target,{callFrames});this._request=request;} 
get target(){return this._target;}
get source(){return this._source;}
get level(){return this._level;}
get messageText(){return this._messageText;}
get type(){return this._type;}
get url(){return this._url;}
get line(){return this._line;}
get column(){return this._column;}
get repeatCount(){return this._repeatCount;}
get parameters(){return this._parameters;}
get stackTrace(){return this._stackTrace;}
get request(){return this._request;}
get sourceCodeLocation()
{if(this._sourceCodeLocation!==undefined)
return this._sourceCodeLocation;let topCallFrame=this._stackTrace.callFrames[0];if(topCallFrame&&topCallFrame.sourceCodeLocation){this._sourceCodeLocation=topCallFrame.sourceCodeLocation;return this._sourceCodeLocation;}
if(this._url&&this._url!=="undefined"){let sourceCode=WI.networkManager.resourcesForURL(this._url).firstValue;if(sourceCode){let lineNumber=this._line>0?this._line-1:0;let columnNumber=this._column>0?this._column-1:0;this._sourceCodeLocation=new WI.SourceCodeLocation(sourceCode,lineNumber,columnNumber);return this._sourceCodeLocation;}}
this._sourceCodeLocation=null;return this._sourceCodeLocation;}};WI.ConsoleMessage.MessageSource={HTML:"html",XML:"xml",JS:"javascript",Network:"network",ConsoleAPI:"console-api",Storage:"storage",Appcache:"appcache",Rendering:"rendering",CSS:"css",Security:"security",Media:"media",MediaSource:"mediasource",WebRTC:"webrtc",ITPDebug:"itp-debug",PrivateClickMeasurement:"private-click-measurement",PaymentRequest:"payment-request",Other:"other",AdClickAttribution:"ad-click-attribution",};WI.ConsoleMessage.MessageType={Log:"log",Dir:"dir",DirXML:"dirxml",Table:"table",Trace:"trace",StartGroup:"startGroup",StartGroupCollapsed:"startGroupCollapsed",EndGroup:"endGroup",Assert:"assert",Timing:"timing",Profile:"profile",ProfileEnd:"profileEnd",Image:"image",Result:"result",};WI.ConsoleMessage.MessageLevel={Log:"log",Info:"info",Warning:"warning",Error:"error",Debug:"debug",};WI.Instrument=class Instrument
{ static createForTimelineType(type)
{switch(type){case WI.TimelineRecord.Type.Network:return new WI.NetworkInstrument;case WI.TimelineRecord.Type.Layout:return new WI.LayoutInstrument;case WI.TimelineRecord.Type.Script:return new WI.ScriptInstrument;case WI.TimelineRecord.Type.RenderingFrame:return new WI.FPSInstrument;case WI.TimelineRecord.Type.CPU:return new WI.CPUInstrument;case WI.TimelineRecord.Type.Memory:return new WI.MemoryInstrument;case WI.TimelineRecord.Type.HeapAllocations:return new WI.HeapAllocationsInstrument;case WI.TimelineRecord.Type.Media:return new WI.MediaInstrument;default:console.error("Unknown TimelineRecord.Type: "+type);return null;}}
static startLegacyTimelineAgent(initiatedByBackend)
{if(WI.Instrument._legacyTimelineAgentStarted)
return;WI.Instrument._legacyTimelineAgentStarted=true;if(initiatedByBackend)
return;let target=WI.assumingMainTarget();target.TimelineAgent.start();}
static stopLegacyTimelineAgent(initiatedByBackend)
{if(!WI.Instrument._legacyTimelineAgentStarted)
return;WI.Instrument._legacyTimelineAgentStarted=false;if(initiatedByBackend)
return;let target=WI.assumingMainTarget();target.TimelineAgent.stop();} 
get timelineRecordType()
{return null;}
startInstrumentation(initiatedByBackend)
{WI.Instrument.startLegacyTimelineAgent(initiatedByBackend);}
stopInstrumentation(initiatedByBackend)
{WI.Instrument.stopLegacyTimelineAgent(initiatedByBackend);}};WI.Instrument._legacyTimelineAgentStarted=false;WI.SourceCode=class SourceCode extends WI.Object
{constructor(url)
{super();this._url=url;this._urlComponents=null;this._originalRevision=new WI.SourceCodeRevision(this);this._currentRevision=this._originalRevision;this._sourceMaps=null;this._formatterSourceMap=null;this._requestContentPromise=null;} 
static generateSpecialContentForURL(url)
{if(url==="about:blank"){return Promise.resolve({content:"",message:WI.unlocalizedString("about:blank")});}
return null;} 
get displayName()
{console.error("Needs to be implemented by a subclass.");return"";}
get originalRevision()
{return this._originalRevision;}
get currentRevision()
{return this._currentRevision;}
set currentRevision(revision)
{if(!(revision instanceof WI.SourceCodeRevision))
return;if(revision.sourceCode!==this)
return;this._currentRevision=revision;this.dispatchEventToListeners(WI.SourceCode.Event.ContentDidChange);}
get editableRevision()
{if(this._currentRevision===this._originalRevision)
this._currentRevision=this._originalRevision.copy();return this._currentRevision;}
get content()
{return this._currentRevision.content;}
get base64Encoded()
{return this._currentRevision.base64Encoded;}
get url()
{return this._url;}
get urlComponents()
{if(!this._urlComponents)
this._urlComponents=parseURL(this._url);return this._urlComponents;}
get contentIdentifier()
{
return this.url;}
get isScript()
{return false;}
get supportsScriptBlackboxing()
{if(!this.isScript)
return false;if(!WI.DebuggerManager.supportsBlackboxingScripts())
return false;let contentIdentifier=this.contentIdentifier;return contentIdentifier&&!isWebKitInjectedScript(contentIdentifier);}
get localResourceOverride()
{return null;}
get sourceMaps()
{return this._sourceMaps||[];}
addSourceMap(sourceMap)
{if(!this._sourceMaps)
this._sourceMaps=[];this._sourceMaps.push(sourceMap);this.dispatchEventToListeners(WI.SourceCode.Event.SourceMapAdded);}
get formatterSourceMap()
{return this._formatterSourceMap;}
set formatterSourceMap(formatterSourceMap)
{this._formatterSourceMap=formatterSourceMap;this.dispatchEventToListeners(WI.SourceCode.Event.FormatterDidChange);}
requestContent()
{this._requestContentPromise=this._requestContentPromise||this.requestContentFromBackend().then(this._processContent.bind(this));return this._requestContentPromise;}
createSourceCodeLocation(lineNumber,columnNumber)
{return new WI.SourceCodeLocation(this,lineNumber,columnNumber);}
createLazySourceCodeLocation(lineNumber,columnNumber)
{return new WI.LazySourceCodeLocation(this,lineNumber,columnNumber);}
createSourceCodeTextRange(textRange)
{return new WI.SourceCodeTextRange(this,textRange);} 
revisionContentDidChange(revision)
{if(this._ignoreRevisionContentDidChangeEvent)
return;if(revision!==this._currentRevision)
return;this.handleCurrentRevisionContentChange();this.dispatchEventToListeners(WI.SourceCode.Event.ContentDidChange);}
handleCurrentRevisionContentChange()
{}
get revisionForRequestedContent()
{return this._originalRevision;}
markContentAsStale()
{this._requestContentPromise=null;this._contentReceived=false;}
requestContentFromBackend()
{console.error("Needs to be implemented by a subclass.");return Promise.reject(new Error("Needs to be implemented by a subclass."));}
get mimeType()
{console.error("Needs to be implemented by a subclass.");} 
_processContent(parameters)
{let rawContent=parameters.content||parameters.body||parameters.text||parameters.scriptSource;let rawBase64Encoded=!!parameters.base64Encoded;let content=rawContent;let error=parameters.error;let message=parameters.message;if(parameters.base64Encoded)
content=content?WI.BlobUtilities.decodeBase64ToBlob(content,this.mimeType):"";let revision=this.revisionForRequestedContent;this._ignoreRevisionContentDidChangeEvent=true;revision.updateRevisionContent(rawContent,{base64Encoded:rawBase64Encoded,mimeType:this.mimeType,blobContent:content instanceof Blob?content:null,});this._ignoreRevisionContentDidChangeEvent=false;


return Promise.resolve({error,message,sourceCode:this,content,rawContent,rawBase64Encoded,});}};WI.SourceCode.Event={ContentDidChange:"source-code-content-did-change",SourceMapAdded:"source-code-source-map-added",FormatterDidChange:"source-code-formatter-did-change",LoadingDidFinish:"source-code-loading-did-finish",LoadingDidFail:"source-code-loading-did-fail"};WI.SourceCodeLocation=class SourceCodeLocation extends WI.Object
{constructor(sourceCode,lineNumber,columnNumber)
{super();this._sourceCode=sourceCode||null;this._lineNumber=lineNumber;this._columnNumber=columnNumber;this._resolveFormattedLocation();if(this._sourceCode){this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);}
this._resetMappedLocation();} 
static get specialBreakpointLocation()
{return new WI.SourceCodeLocation(null,Infinity,Infinity);} 
isEqual(other)
{if(!other)
return false;return this._sourceCode===other._sourceCode&&this._lineNumber===other._lineNumber&&this._columnNumber===other._columnNumber;}
get sourceCode()
{return this._sourceCode;}
set sourceCode(sourceCode)
{this.setSourceCode(sourceCode);}
get lineNumber()
{return this._lineNumber;}
get columnNumber()
{return this._columnNumber;}
position()
{return new WI.SourceCodePosition(this.lineNumber,this.columnNumber);}
get formattedLineNumber()
{return this._formattedLineNumber;}
get formattedColumnNumber()
{return this._formattedColumnNumber;}
formattedPosition()
{return new WI.SourceCodePosition(this.formattedLineNumber,this.formattedColumnNumber);}
get displaySourceCode()
{this.resolveMappedLocation();return this._mappedResource||this._sourceCode;}
get displayLineNumber()
{this.resolveMappedLocation();return isNaN(this._mappedLineNumber)?this._formattedLineNumber:this._mappedLineNumber;}
get displayColumnNumber()
{this.resolveMappedLocation();return isNaN(this._mappedColumnNumber)?this._formattedColumnNumber:this._mappedColumnNumber;}
displayPosition()
{return new WI.SourceCodePosition(this.displayLineNumber,this.displayColumnNumber);}
originalLocationString(columnStyle,nameStyle,prefix)
{return this._locationString(this.sourceCode,this.lineNumber,this.columnNumber,columnStyle,nameStyle,prefix);}
formattedLocationString(columnStyle,nameStyle,prefix)
{return this._locationString(this.sourceCode,this.formattedLineNumber,this.formattedColumn,columnStyle,nameStyle,prefix);}
displayLocationString(columnStyle,nameStyle,prefix)
{return this._locationString(this.displaySourceCode,this.displayLineNumber,this.displayColumnNumber,columnStyle,nameStyle,prefix);}
tooltipString()
{if(!this.hasDifferentDisplayLocation())
return this.originalLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full);var tooltip=WI.UIString("Located at %s").format(this.displayLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full));tooltip+="\n"+WI.UIString("Originally %s").format(this.originalLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full));return tooltip;}
hasMappedLocation()
{this.resolveMappedLocation();return this._mappedResource!==null;}
hasFormattedLocation()
{return this._formattedLineNumber!==this._lineNumber||this._formattedColumnNumber!==this._columnNumber;}
hasDifferentDisplayLocation()
{return this.hasMappedLocation()||this.hasFormattedLocation();}
update(sourceCode,lineNumber,columnNumber)
{if(sourceCode===this._sourceCode&&lineNumber===this._lineNumber&&columnNumber===this._columnNumber)
return;if(this._mappedResource&&sourceCode===this._mappedResource&&lineNumber===this._mappedLineNumber&&columnNumber===this._mappedColumnNumber)
return;var newSourceCodeLocation=sourceCode.createSourceCodeLocation(lineNumber,columnNumber);this._makeChangeAndDispatchChangeEventIfNeeded(function(){this._lineNumber=newSourceCodeLocation._lineNumber;this._columnNumber=newSourceCodeLocation._columnNumber;if(newSourceCodeLocation._mappedLocationIsResolved){this._mappedLocationIsResolved=true;this._mappedResource=newSourceCodeLocation._mappedResource;this._mappedLineNumber=newSourceCodeLocation._mappedLineNumber;this._mappedColumnNumber=newSourceCodeLocation._mappedColumnNumber;}});}
populateLiveDisplayLocationTooltip(element,prefix,suffix)
{prefix=prefix||"";suffix=suffix||"";element.title=prefix+this.tooltipString()+suffix;this.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,function(event){if(this.sourceCode)
element.title=prefix+this.tooltipString()+suffix;},this);}
populateLiveDisplayLocationString(element,propertyName,columnStyle,nameStyle,prefix)
{var currentDisplay;function updateDisplayString(showAlternativeLocation,forceUpdate)
{if(!forceUpdate&&currentDisplay===showAlternativeLocation)
return;currentDisplay=showAlternativeLocation;if(!showAlternativeLocation){element[propertyName]=this.displayLocationString(columnStyle,nameStyle,prefix);element.classList.toggle(WI.SourceCodeLocation.DisplayLocationClassName,this.hasDifferentDisplayLocation());}else if(this.hasDifferentDisplayLocation()){element[propertyName]=this.originalLocationString(columnStyle,nameStyle,prefix);element.classList.remove(WI.SourceCodeLocation.DisplayLocationClassName);}}
function mouseOverOrMove(event)
{updateDisplayString.call(this,event.metaKey&&!event.altKey&&!event.shiftKey);}
updateDisplayString.call(this,false);this.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,function(event){if(this.sourceCode)
updateDisplayString.call(this,currentDisplay,true);},this);var boundMouseOverOrMove=mouseOverOrMove.bind(this);element.addEventListener("mouseover",boundMouseOverOrMove);element.addEventListener("mousemove",boundMouseOverOrMove);element.addEventListener("mouseout",(event)=>{updateDisplayString.call(this,false);});} 
setSourceCode(sourceCode)
{if(sourceCode===this._sourceCode)
return;this._makeChangeAndDispatchChangeEventIfNeeded(function(){if(this._sourceCode){this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);}
this._sourceCode=sourceCode;if(this._sourceCode){this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);}});}
resolveMappedLocation()
{if(this._mappedLocationIsResolved)
return;this._mappedLocationIsResolved=true;if(!this._sourceCode)
return;var sourceMaps=this._sourceCode.sourceMaps;if(!sourceMaps.length)
return;for(var i=0;i<sourceMaps.length;++i){var sourceMap=sourceMaps[i];var entry=sourceMap.findEntry(this._lineNumber,this._columnNumber);if(!entry||entry.length===2)
continue;var url=entry[2];var sourceMapResource=sourceMap.resourceForURL(url);if(!sourceMapResource)
return;this._mappedResource=sourceMapResource;this._mappedLineNumber=entry[3];this._mappedColumnNumber=entry[4];return;}} 
_locationString(sourceCode,lineNumber,columnNumber,columnStyle,nameStyle,prefix)
{if(!sourceCode)
return"";columnStyle=columnStyle||WI.SourceCodeLocation.ColumnStyle.OnlyIfLarge;nameStyle=nameStyle||WI.SourceCodeLocation.NameStyle.Short;prefix=prefix||"";let lineString=lineNumber+1;if(columnStyle===WI.SourceCodeLocation.ColumnStyle.Shown&&columnNumber>0)
lineString+=":"+(columnNumber+1);else if(columnStyle===WI.SourceCodeLocation.ColumnStyle.OnlyIfLarge&&columnNumber>WI.SourceCodeLocation.LargeColumnNumber)
lineString+=":"+(columnNumber+1);else if(columnStyle===WI.SourceCodeLocation.ColumnStyle.Hidden)
lineString="";switch(nameStyle){case WI.SourceCodeLocation.NameStyle.None:return prefix+lineString;case WI.SourceCodeLocation.NameStyle.Short:case WI.SourceCodeLocation.NameStyle.Full:var displayURL=sourceCode.displayURL;var name=nameStyle===WI.SourceCodeLocation.NameStyle.Full&&displayURL?displayURL:sourceCode.displayName;if(columnStyle===WI.SourceCodeLocation.ColumnStyle.Hidden)
return prefix+name;var lineSuffix=displayURL?":"+lineString:WI.UIString(" (line %s)").format(lineString);return prefix+name+lineSuffix;default:console.error("Unknown nameStyle: "+nameStyle);return prefix+lineString;}}
_resetMappedLocation()
{this._mappedLocationIsResolved=false;this._mappedResource=null;this._mappedLineNumber=NaN;this._mappedColumnNumber=NaN;}
_setMappedLocation(mappedResource,mappedLineNumber,mappedColumnNumber)
{this._mappedLocationIsResolved=true;this._mappedResource=mappedResource;this._mappedLineNumber=mappedLineNumber;this._mappedColumnNumber=mappedColumnNumber;}
_resolveFormattedLocation()
{if(this._sourceCode&&this._sourceCode.formatterSourceMap){var formattedLocation=this._sourceCode.formatterSourceMap.originalToFormatted(this._lineNumber,this._columnNumber);this._formattedLineNumber=formattedLocation.lineNumber;this._formattedColumnNumber=formattedLocation.columnNumber;}else{this._formattedLineNumber=this._lineNumber;this._formattedColumnNumber=this._columnNumber;}}
_makeChangeAndDispatchChangeEventIfNeeded(changeFunction)
{var oldSourceCode=this._sourceCode;var oldLineNumber=this._lineNumber;var oldColumnNumber=this._columnNumber;var oldFormattedLineNumber=this._formattedLineNumber;var oldFormattedColumnNumber=this._formattedColumnNumber;var oldDisplaySourceCode=this.displaySourceCode;var oldDisplayLineNumber=this.displayLineNumber;var oldDisplayColumnNumber=this.displayColumnNumber;this._resetMappedLocation();if(changeFunction)
changeFunction.call(this);this.resolveMappedLocation();this._resolveFormattedLocation();var displayLocationChanged=false;var newDisplaySourceCode=this.displaySourceCode;if(oldDisplaySourceCode!==newDisplaySourceCode)
displayLocationChanged=true;else if(newDisplaySourceCode&&(oldDisplayLineNumber!==this.displayLineNumber||oldDisplayColumnNumber!==this.displayColumnNumber))
displayLocationChanged=true;var anyLocationChanged=false;if(displayLocationChanged)
anyLocationChanged=true;else if(oldSourceCode!==this._sourceCode)
anyLocationChanged=true;else if(this._sourceCode&&(oldLineNumber!==this._lineNumber||oldColumnNumber!==this._columnNumber))
anyLocationChanged=true;else if(this._sourceCode&&(oldFormattedLineNumber!==this._formattedLineNumber||oldFormattedColumnNumber!==this._formattedColumnNumber))
anyLocationChanged=true;if(displayLocationChanged||anyLocationChanged){var oldData={oldSourceCode,oldLineNumber,oldColumnNumber,oldFormattedLineNumber,oldFormattedColumnNumber,oldDisplaySourceCode,oldDisplayLineNumber,oldDisplayColumnNumber};if(displayLocationChanged)
this.dispatchEventToListeners(WI.SourceCodeLocation.Event.DisplayLocationChanged,oldData);if(anyLocationChanged)
this.dispatchEventToListeners(WI.SourceCodeLocation.Event.LocationChanged,oldData);}}
_sourceCodeSourceMapAdded()
{this._makeChangeAndDispatchChangeEventIfNeeded(null);}
_sourceCodeFormatterDidChange()
{this._makeChangeAndDispatchChangeEventIfNeeded(null);}};WI.SourceCodeLocation.DisplayLocationClassName="display-location";WI.SourceCodeLocation.LargeColumnNumber=80;WI.SourceCodeLocation.NameStyle={None:"none",Short:"short",Full:"full"};WI.SourceCodeLocation.ColumnStyle={Hidden:"hidden",OnlyIfLarge:"only-if-large",Shown:"shown"};WI.SourceCodeLocation.Event={LocationChanged:"source-code-location-location-changed",DisplayLocationChanged:"source-code-location-display-location-changed"};WI.Timeline=class Timeline extends WI.Object
{constructor(type)
{super();this._type=type;this.reset(true);} 
static create(type)
{if(type===WI.TimelineRecord.Type.Network)
return new WI.NetworkTimeline(type);if(type===WI.TimelineRecord.Type.CPU)
return new WI.CPUTimeline(type);if(type===WI.TimelineRecord.Type.Memory)
return new WI.MemoryTimeline(type);if(type===WI.TimelineRecord.Type.Media)
return new WI.MediaTimeline(type);return new WI.Timeline(type);} 
get type(){return this._type;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get records(){return this._records;}
reset(suppressEvents)
{this._records=[];this._startTime=NaN;this._endTime=NaN;if(!suppressEvents){this.dispatchEventToListeners(WI.Timeline.Event.TimesUpdated);this.dispatchEventToListeners(WI.Timeline.Event.Reset);}}
addRecord(record,options={})
{if(record.updatesDynamically)
record.addEventListener(WI.TimelineRecord.Event.Updated,this._recordUpdated,this);



this._tryInsertingRecordInSortedOrder(record);this._updateTimesIfNeeded(record);this.dispatchEventToListeners(WI.Timeline.Event.RecordAdded,{record});}
saveIdentityToCookie(cookie)
{cookie[WI.Timeline.TimelineTypeCookieKey]=this._type;}
refresh()
{this.dispatchEventToListeners(WI.Timeline.Event.Refreshed);}
closestRecordTo(timestamp)
{let lowerIndex=this._records.lowerBound(timestamp,(time,record)=>time-record.endTime);let recordBefore=this._records[lowerIndex-1];let recordAfter=this._records[lowerIndex];if(!recordBefore&&!recordAfter)
return null;if(!recordBefore&&recordAfter)
return recordAfter;if(!recordAfter&&recordBefore)
return recordBefore;let before=Math.abs(recordBefore.endTime-timestamp);let after=Math.abs(recordAfter.startTime-timestamp);return(before<after)?recordBefore:recordAfter;}
recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart,includeRecordAfterEnd}={})
{let lowerIndex=this._records.lowerBound(startTime,(time,record)=>time-record.endTime);if(includeRecordBeforeStart&&lowerIndex>0){lowerIndex--;let recordBefore=this._records[lowerIndex];if(recordBefore.parent&&recordBefore.parent.type===recordBefore.type){lowerIndex--;while(this._records[lowerIndex]!==recordBefore.parent)
lowerIndex--;}}
let upperIndex=this._records.upperBound(endTime,(time,record)=>time-record.startTime);if(includeRecordAfterEnd&&upperIndex<this._records.length)
++upperIndex;return this._records.slice(lowerIndex,upperIndex);} 
_updateTimesIfNeeded(record)
{let changed=false;


let recordStartTime=record.unadjustedStartTime;let recordEndTime=record.unadjustedEndTime;if(isNaN(this._startTime)||recordStartTime<this._startTime){this._startTime=recordStartTime;changed=true;}
if(isNaN(this._endTime)||this._endTime<recordEndTime){this._endTime=recordEndTime;changed=true;}
if(changed)
this.dispatchEventToListeners(WI.Timeline.Event.TimesUpdated);}
_recordUpdated(event)
{this._updateTimesIfNeeded(event.target);}
_tryInsertingRecordInSortedOrder(record)
{let lastValue=this._records.lastValue;if(!lastValue||lastValue.startTime<record.startTime||record.updatesDynamically){this._records.push(record);return;}
let start=this._records.length-2;let end=Math.max(this._records.length-20,0);for(let i=start;i>=end;--i){if(this._records[i].startTime<record.startTime){this._records.insertAtIndex(record,i+1);return;}}
this._records.push(record);}};WI.Timeline.Event={Reset:"timeline-reset",RecordAdded:"timeline-record-added",TimesUpdated:"timeline-times-updated",Refreshed:"timeline-refreshed",};WI.Timeline.TimelineTypeCookieKey="timeline-type";WI.TimelineRange=class TimelineRange
{constructor(startValue,endValue)
{this._startValue=startValue;this._endValue=endValue;}
get startValue(){return this._startValue;}
set startValue(x){this._startValue=x;}
get endValue(){return this._endValue;}
set endValue(x){this._endValue=x;}};WI.TimelineRecord=class TimelineRecord extends WI.Object
{constructor(type,startTime,endTime,callFrames,sourceCodeLocation)
{super();if(type in WI.TimelineRecord.Type)
type=WI.TimelineRecord.Type[type];this._type=type;this._startTime=startTime||NaN;this._endTime=endTime||NaN;this._callFrames=callFrames||null;this._sourceCodeLocation=sourceCodeLocation||null;this._children=[];} 
static async fromJSON(json)
{switch(json.type){case WI.TimelineRecord.Type.Network:return WI.ResourceTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.Layout:return WI.LayoutTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.Script:return WI.ScriptTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.RenderingFrame:return WI.RenderingFrameTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.CPU:return WI.CPUTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.Memory:return WI.MemoryTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.HeapAllocations:return WI.HeapAllocationsTimelineRecord.fromJSON(json);case WI.TimelineRecord.Type.Media:return WI.MediaTimelineRecord.fromJSON(json);default:console.error("Unknown TimelineRecord.Type: "+json.type,json);return null;}}
toJSON()
{throw WI.NotImplementedError.subclassMustOverride();} 
get type()
{return this._type;}
get startTime()
{return this._startTime;}
get activeStartTime()
{return this.startTime;}
get unadjustedStartTime()
{return this.startTime;}
get endTime()
{return this._endTime;}
get unadjustedEndTime()
{return this.endTime;}
get duration()
{return this.endTime-this.startTime;}
get inactiveDuration()
{return this.activeStartTime-this.startTime;}
get activeDuration()
{return this.endTime-this.activeStartTime;}
get updatesDynamically()
{return false;}
get usesActiveStartTime()
{return false;}
get callFrames()
{return this._callFrames;}
get initiatorCallFrame()
{if(!this._callFrames||!this._callFrames.length)
return null;for(let frame of this._callFrames){if(!frame.nativeCode)
return frame;}
return null;}
get sourceCodeLocation()
{return this._sourceCodeLocation;}
get parent()
{return this._parent;}
set parent(x)
{if(this._parent===x)
return;this._parent=x;}
get children()
{return this._children;}
saveIdentityToCookie(cookie)
{cookie[WI.TimelineRecord.SourceCodeURLCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.sourceCode.url?this._sourceCodeLocation.sourceCode.url.hash:null:null;cookie[WI.TimelineRecord.SourceCodeLocationLineCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:null;cookie[WI.TimelineRecord.SourceCodeLocationColumnCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:null;cookie[WI.TimelineRecord.TypeCookieKey]=this._type||null;}};WI.TimelineRecord.Event={Updated:"timeline-record-updated"};WI.TimelineRecord.Type={Network:"timeline-record-type-network",Layout:"timeline-record-type-layout",Script:"timeline-record-type-script",RenderingFrame:"timeline-record-type-rendering-frame",CPU:"timeline-record-type-cpu",Memory:"timeline-record-type-memory",HeapAllocations:"timeline-record-type-heap-allocations",Media:"timeline-record-type-media",};WI.TimelineRecord.TypeIdentifier="timeline-record";WI.TimelineRecord.SourceCodeURLCookieKey="timeline-record-source-code-url";WI.TimelineRecord.SourceCodeLocationLineCookieKey="timeline-record-source-code-location-line";WI.TimelineRecord.SourceCodeLocationColumnCookieKey="timeline-record-source-code-location-column";WI.TimelineRecord.TypeCookieKey="timeline-record-type";WI.Resource=class Resource extends WI.SourceCode
{constructor(url,{mimeType,type,loaderIdentifier,targetId,requestIdentifier,requestMethod,requestHeaders,requestData,requestSentTimestamp,requestSentWalltime,initiatorCallFrames,initiatorSourceCodeLocation,initiatorNode}={})
{super(url);if(type in WI.Resource.Type)
type=WI.Resource.Type[type];else if(type==="Stylesheet"){type=WI.Resource.Type.StyleSheet;}
this._mimeType=mimeType;this._mimeTypeComponents=null;this._type=Resource.resolvedType(type,mimeType);this._loaderIdentifier=loaderIdentifier||null;this._requestIdentifier=requestIdentifier||null;this._queryStringParameters=undefined;this._requestFormParameters=undefined;this._requestMethod=requestMethod||null;this._requestData=requestData||null;this._requestHeaders=requestHeaders||{};this._responseHeaders={};this._requestCookies=null;this._responseCookies=null;this._serverTimingEntries=null;this._parentFrame=null;this._initiatorCallFrames=initiatorCallFrames||null;this._initiatorSourceCodeLocation=initiatorSourceCodeLocation||null;this._initiatorNode=initiatorNode||null;this._initiatedResources=[];this._requestSentTimestamp=requestSentTimestamp||NaN;this._requestSentWalltime=requestSentWalltime||NaN;this._responseReceivedTimestamp=NaN;this._lastDataReceivedTimestamp=NaN;this._finishedOrFailedTimestamp=NaN;this._finishThenRequestContentPromise=null;this._statusCode=NaN;this._statusText=null;this._cached=false;this._canceled=false;this._finished=false;this._failed=false;this._failureReasonText=null;this._receivedNetworkLoadMetrics=false;this._responseSource=WI.Resource.ResponseSource.Unknown;this._security=null;this._timingData=new WI.ResourceTimingData(this);this._protocol=null;this._priority=WI.Resource.NetworkPriority.Unknown;this._remoteAddress=null;this._connectionIdentifier=null;this._target=targetId?WI.targetManager.targetForIdentifier(targetId):WI.mainTarget;this._redirects=[];this._requestHeadersTransferSize=NaN;this._requestBodyTransferSize=NaN;this._responseHeadersTransferSize=NaN;this._responseBodyTransferSize=NaN;this._responseBodySize=NaN;this._cachedResponseBodySize=NaN;this._estimatedSize=NaN;this._estimatedTransferSize=NaN;this._estimatedResponseHeadersSize=NaN;if(this._initiatorSourceCodeLocation&&this._initiatorSourceCodeLocation.sourceCode instanceof WI.Resource)
this._initiatorSourceCodeLocation.sourceCode.addInitiatedResource(this);} 
static resolvedType(type,mimeType)
{if(type&&type!==WI.Resource.Type.Other)
return type;return Resource.typeFromMIMEType(mimeType);}
static typeFromMIMEType(mimeType)
{if(!mimeType)
return WI.Resource.Type.Other;mimeType=parseMIMEType(mimeType).type;if(mimeType in WI.Resource._mimeTypeMap)
return WI.Resource._mimeTypeMap[mimeType];if(mimeType.startsWith("image/"))
return WI.Resource.Type.Image;if(mimeType.startsWith("font/"))
return WI.Resource.Type.Font;return WI.Resource.Type.Other;}
static displayNameForType(type,plural)
{switch(type){case WI.Resource.Type.Document:if(plural)
return WI.UIString("Documents");return WI.UIString("Document");case WI.Resource.Type.StyleSheet:if(plural)
return WI.UIString("Style Sheets");return WI.UIString("Style Sheet");case WI.Resource.Type.Image:if(plural)
return WI.UIString("Images");return WI.UIString("Image");case WI.Resource.Type.Font:if(plural)
return WI.UIString("Fonts");return WI.UIString("Font");case WI.Resource.Type.Script:if(plural)
return WI.UIString("Scripts");return WI.UIString("Script");case WI.Resource.Type.XHR:if(plural)
return WI.UIString("XHRs");return WI.UIString("XHR");case WI.Resource.Type.Fetch:if(plural)
return WI.UIString("Fetches","Resources loaded via 'fetch' method");return WI.repeatedUIString.fetch();case WI.Resource.Type.Ping:if(plural)
return WI.UIString("Pings");return WI.UIString("Ping");case WI.Resource.Type.Beacon:if(plural)
return WI.UIString("Beacons");return WI.UIString("Beacon");case WI.Resource.Type.WebSocket:if(plural)
return WI.UIString("Sockets");return WI.UIString("Socket");case WI.Resource.Type.Other:return WI.UIString("Other");default:console.error("Unknown resource type",type);return null;}}
static classNamesForResource(resource)
{let classes=[];let isOverride=!!resource.localResourceOverride;let wasOverridden=resource.responseSource===WI.Resource.ResponseSource.InspectorOverride;let shouldBeOverridden=resource.isLoading()&&WI.networkManager.localResourceOverridesForURL(resource.url).some((localResourceOverride)=>!localResourceOverride.disabled);if(isOverride||wasOverridden||shouldBeOverridden)
classes.push("override");if(resource.type===WI.Resource.Type.Other){if(resource.requestedByteRange)
classes.push("resource-type-range");}else
classes.push(resource.type);return classes;}
static displayNameForProtocol(protocol)
{switch(protocol){case"h2":return"HTTP/2";case"http/1.0":return"HTTP/1.0";case"http/1.1":return"HTTP/1.1";case"spdy/2":return"SPDY/2";case"spdy/3":return"SPDY/3";case"spdy/3.1":return"SPDY/3.1";default:return null;}}
static comparePriority(a,b)
{const map={[WI.Resource.NetworkPriority.Unknown]:0,[WI.Resource.NetworkPriority.Low]:1,[WI.Resource.NetworkPriority.Medium]:2,[WI.Resource.NetworkPriority.High]:3,};let aNum=map[a]||0;let bNum=map[b]||0;return aNum-bNum;}
static displayNameForPriority(priority)
{switch(priority){case WI.Resource.NetworkPriority.Low:return WI.UIString("Low","Low @ Network Priority","Low network request priority");case WI.Resource.NetworkPriority.Medium:return WI.UIString("Medium","Medium @ Network Priority","Medium network request priority");case WI.Resource.NetworkPriority.High:return WI.UIString("High","High @ Network Priority","High network request priority");default:return null;}}
static responseSourceFromPayload(source)
{if(!source)
return WI.Resource.ResponseSource.Unknown;switch(source){case InspectorBackend.Enum.Network.ResponseSource.Unknown:return WI.Resource.ResponseSource.Unknown;case InspectorBackend.Enum.Network.ResponseSource.Network:return WI.Resource.ResponseSource.Network;case InspectorBackend.Enum.Network.ResponseSource.MemoryCache:return WI.Resource.ResponseSource.MemoryCache;case InspectorBackend.Enum.Network.ResponseSource.DiskCache:return WI.Resource.ResponseSource.DiskCache;case InspectorBackend.Enum.Network.ResponseSource.ServiceWorker:return WI.Resource.ResponseSource.ServiceWorker;case InspectorBackend.Enum.Network.ResponseSource.InspectorOverride:return WI.Resource.ResponseSource.InspectorOverride;default:console.error("Unknown response source type",source);return WI.Resource.ResponseSource.Unknown;}}
static networkPriorityFromPayload(priority)
{switch(priority){case InspectorBackend.Enum.Network.MetricsPriority.Low:return WI.Resource.NetworkPriority.Low;case InspectorBackend.Enum.Network.MetricsPriority.Medium:return WI.Resource.NetworkPriority.Medium;case InspectorBackend.Enum.Network.MetricsPriority.High:return WI.Resource.NetworkPriority.High;default:console.error("Unknown metrics priority",priority);return WI.Resource.NetworkPriority.Unknown;}}
static connectionIdentifierFromPayload(connectionIdentifier)
{if(!WI.Resource.connectionIdentifierMap){WI.Resource.connectionIdentifierMap=new Map;WI.Resource.nextConnectionIdentifier=1;}
let id=WI.Resource.connectionIdentifierMap.get(connectionIdentifier);if(id)
return id;id=WI.Resource.nextConnectionIdentifier++;WI.Resource.connectionIdentifierMap.set(connectionIdentifier,id);return id;} 
get mimeType(){return this._mimeType;}
get target(){return this._target;}
get type(){return this._type;}
get loaderIdentifier(){return this._loaderIdentifier;}
get requestIdentifier(){return this._requestIdentifier;}
get requestMethod(){return this._requestMethod;}
get requestData(){return this._requestData;}
get initiatorCallFrames(){return this._initiatorCallFrames;}
get initiatorSourceCodeLocation(){return this._initiatorSourceCodeLocation;}
get initiatorNode(){return this._initiatorNode;}
get initiatedResources(){return this._initiatedResources;}
get statusCode(){return this._statusCode;}
get statusText(){return this._statusText;}
get responseSource(){return this._responseSource;}
get security(){return this._security;}
get timingData(){return this._timingData;}
get protocol(){return this._protocol;}
get priority(){return this._priority;}
get remoteAddress(){return this._remoteAddress;}
get connectionIdentifier(){return this._connectionIdentifier;}
get parentFrame(){return this._parentFrame;}
get finished(){return this._finished;}
get failed(){return this._failed;}
get canceled(){return this._canceled;}
get failureReasonText(){return this._failureReasonText;}
get requestHeaders(){return this._requestHeaders;}
get responseHeaders(){return this._responseHeaders;}
get requestSentTimestamp(){return this._requestSentTimestamp;}
get requestSentWalltime(){return this._requestSentWalltime;}
get responseReceivedTimestamp(){return this._responseReceivedTimestamp;}
get lastDataReceivedTimestamp(){return this._lastDataReceivedTimestamp;}
get finishedOrFailedTimestamp(){return this._finishedOrFailedTimestamp;}
get cached(){return this._cached;}
get requestHeadersTransferSize(){return this._requestHeadersTransferSize;}
get requestBodyTransferSize(){return this._requestBodyTransferSize;}
get responseHeadersTransferSize(){return this._responseHeadersTransferSize;}
get responseBodyTransferSize(){return this._responseBodyTransferSize;}
get cachedResponseBodySize(){return this._cachedResponseBodySize;}
get redirects(){return this._redirects;}
get loadedSecurely()
{if(this.urlComponents.scheme!=="https"&&this.urlComponents.scheme!=="wss"&&this.urlComponents.scheme!=="sftp")
return false;if(isNaN(this._timingData.secureConnectionStart)&&!isNaN(this._timingData.connectionStart))
return false;return true;}
get isScript()
{return this._type===Resource.Type.Script;}
get supportsScriptBlackboxing()
{if(this.localResourceOverride)
return false;if(!this.finished||this.failed)
return false;return super.supportsScriptBlackboxing;}
get displayName()
{return WI.displayNameForURL(this._url,this.urlComponents);}
get displayURL()
{const isMultiLine=true;const dataURIMaxSize=64;return WI.truncateURL(this._url,isMultiLine,dataURIMaxSize);}
get mimeTypeComponents()
{if(!this._mimeTypeComponents)
this._mimeTypeComponents=parseMIMEType(this._mimeType);return this._mimeTypeComponents;}
get syntheticMIMEType()
{
if(this._type===WI.Resource.typeFromMIMEType(this._mimeType))
return this._mimeType;
switch(this._type){case WI.Resource.Type.StyleSheet:return"text/css";case WI.Resource.Type.Script:return"text/javascript";}
return this._mimeType;}
createObjectURL()
{let revision=this.currentRevision;let blobContent=revision.blobContent;if(blobContent)
return URL.createObjectURL(blobContent)
return this._url;}
isMainResource()
{return this._parentFrame?this._parentFrame.mainResource===this:false;}
addInitiatedResource(resource)
{if(!(resource instanceof WI.Resource))
return;this._initiatedResources.push(resource);this.dispatchEventToListeners(WI.Resource.Event.InitiatedResourcesDidChange);}
get queryStringParameters()
{if(this._queryStringParameters===undefined)
this._queryStringParameters=parseQueryString(this.urlComponents.queryString,true);return this._queryStringParameters;}
get requestFormParameters()
{if(this._requestFormParameters===undefined)
this._requestFormParameters=this.hasRequestFormParameters()?parseQueryString(this.requestData,true):null;return this._requestFormParameters;}
get requestDataContentType()
{return this._requestHeaders.valueForCaseInsensitiveKey("Content-Type")||null;}
get requestCookies()
{if(!this._requestCookies)
this._requestCookies=WI.Cookie.parseCookieRequestHeader(this._requestHeaders.valueForCaseInsensitiveKey("Cookie"));return this._requestCookies;}
get responseCookies()
{if(!this._responseCookies){



let rawCombinedHeader=this._responseHeaders.valueForCaseInsensitiveKey("Set-Cookie")||"";let setCookieHeaders=rawCombinedHeader.split(/, (?![0-9])/);let cookies=[];for(let header of setCookieHeaders){let cookie=WI.Cookie.parseSetCookieResponseHeader(header);if(cookie)
cookies.push(cookie);}
this._responseCookies=cookies;}
return this._responseCookies;}
get requestSentDate()
{return isNaN(this._requestSentWalltime)?null:new Date(this._requestSentWalltime*1000);}
get lastRedirectReceivedTimestamp()
{return this._redirects.length?this._redirects.lastValue.timestamp:NaN;}
get firstTimestamp()
{return this.timingData.startTime||this.lastRedirectReceivedTimestamp||this.responseReceivedTimestamp||this.lastDataReceivedTimestamp||this.finishedOrFailedTimestamp;}
get lastTimestamp()
{return this.timingData.responseEnd||this.lastDataReceivedTimestamp||this.responseReceivedTimestamp||this.lastRedirectReceivedTimestamp||this.requestSentTimestamp;}
get latency()
{return this.timingData.responseStart-this.timingData.requestStart;}
get receiveDuration()
{return this.timingData.responseEnd-this.timingData.responseStart;}
get totalDuration()
{return this.timingData.responseEnd-this.timingData.startTime;}
get size()
{if(!isNaN(this._cachedResponseBodySize))
return this._cachedResponseBodySize;if(!isNaN(this._responseBodySize)&&this._responseBodySize!==0)
return this._responseBodySize;return this._estimatedSize;}
get networkEncodedSize()
{return this._responseBodyTransferSize;}
get networkDecodedSize()
{return this._responseBodySize;}
get networkTotalTransferSize()
{return this._responseHeadersTransferSize+this._responseBodyTransferSize;}
get estimatedNetworkEncodedSize()
{let exact=this.networkEncodedSize;if(!isNaN(exact))
return exact;if(this._cached)
return 0;


if(WI.Platform.name==="mac"){let contentLength=Number(this._responseHeaders.valueForCaseInsensitiveKey("Content-Length"));if(!isNaN(contentLength))
return contentLength;}
if(!isNaN(this._estimatedTransferSize))
return this._estimatedTransferSize;






return Number(this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")||this._estimatedSize);}
get estimatedTotalTransferSize()
{let exact=this.networkTotalTransferSize;if(!isNaN(exact))
return exact;if(this.statusCode===304) 
return this._estimatedResponseHeadersSize;if(this._cached)
return 0;return this._estimatedResponseHeadersSize+this.estimatedNetworkEncodedSize;}
get compressed()
{let contentEncoding=this._responseHeaders.valueForCaseInsensitiveKey("Content-Encoding");return!!(contentEncoding&&/\b(?:gzip|deflate|br)\b/.test(contentEncoding));}
get requestedByteRange()
{let range=this._requestHeaders.valueForCaseInsensitiveKey("Range");if(!range)
return null;let rangeValues=range.match(/bytes=(\d+)-(\d+)/);if(!rangeValues)
return null;let start=parseInt(rangeValues[1]);if(isNaN(start))
return null;let end=parseInt(rangeValues[2]);if(isNaN(end))
return null;return{start,end};}
get scripts()
{return this._scripts||[];}
get serverTiming()
{if(!this._serverTimingEntries)
this._serverTimingEntries=WI.ServerTimingEntry.parseHeaders(this._responseHeaders.valueForCaseInsensitiveKey("Server-Timing"));return this._serverTimingEntries;}
scriptForLocation(sourceCodeLocation)
{if(sourceCodeLocation.sourceCode!==this)
return null;var lineNumber=sourceCodeLocation.lineNumber;var columnNumber=sourceCodeLocation.columnNumber;for(var i=0;i<this._scripts.length;++i){var script=this._scripts[i];if(script.range.startLine<=lineNumber&&script.range.endLine>=lineNumber){if(script.range.startLine===lineNumber&&columnNumber<script.range.startColumn)
continue;if(script.range.endLine===lineNumber&&columnNumber>script.range.endColumn)
continue;return script;}}
return null;}
updateForRedirectResponse(request,response,elapsedTime,walltime)
{let oldURL=this._url;let oldHeaders=this._requestHeaders;let oldMethod=this._requestMethod;if(request.url)
this._url=request.url;this._requestHeaders=request.headers||{};this._requestCookies=null;this._requestMethod=request.method||null;this._redirects.push(new WI.Redirect(oldURL,oldMethod,oldHeaders,response.status,response.statusText,response.headers,elapsedTime));if(oldURL!==request.url){this._urlComponents=null;this.dispatchEventToListeners(WI.Resource.Event.URLDidChange,{oldURL});}
this.dispatchEventToListeners(WI.Resource.Event.RequestHeadersDidChange);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);}
hasResponse()
{return!isNaN(this._statusCode)||this._finished||this._failed;}
hasRequestFormParameters()
{let requestDataContentType=this.requestDataContentType;return requestDataContentType&&requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i);}
updateForResponse(url,mimeType,type,responseHeaders,statusCode,statusText,elapsedTime,timingData,source,security)
{let oldURL=this._url;let oldMIMEType=this._mimeType;let oldType=this._type;if(type in WI.Resource.Type)
type=WI.Resource.Type[type];else if(type==="Stylesheet"){type=WI.Resource.Type.StyleSheet;}
if(url)
this._url=url;this._mimeType=mimeType;this._type=Resource.resolvedType(type,mimeType);this._statusCode=statusCode;this._statusText=statusText;this._responseHeaders=responseHeaders||{};this._responseCookies=null;this._serverTimingEntries=null;this._responseReceivedTimestamp=elapsedTime||NaN;this._timingData=WI.ResourceTimingData.fromPayload(timingData,this);if(source)
this._responseSource=WI.Resource.responseSourceFromPayload(source);this._security=security||{};const headerBaseSize=12;const headerPad=4;this._estimatedResponseHeadersSize=String(this._statusCode).length+this._statusText.length+headerBaseSize;for(let name in this._responseHeaders)
this._estimatedResponseHeadersSize+=name.length+this._responseHeaders[name].length+headerPad;if(!this._cached){if(statusCode===304||(this._responseSource===WI.Resource.ResponseSource.MemoryCache||this._responseSource===WI.Resource.ResponseSource.DiskCache))
this.markAsCached();}
if(oldURL!==url){this._urlComponents=null;this.dispatchEventToListeners(WI.Resource.Event.URLDidChange,{oldURL});}
if(oldMIMEType!==mimeType){this._mimeTypeComponents=null;this.dispatchEventToListeners(WI.Resource.Event.MIMETypeDidChange,{oldMIMEType});}
if(oldType!==type)
this.dispatchEventToListeners(WI.Resource.Event.TypeDidChange,{oldType});
if(statusCode===304||this._responseHeaders.valueForCaseInsensitiveKey("Content-Length"))
this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);this.dispatchEventToListeners(WI.Resource.Event.ResponseReceived);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);}
updateWithMetrics(metrics)
{this._receivedNetworkLoadMetrics=true;if(metrics.protocol)
this._protocol=metrics.protocol;if(metrics.priority)
this._priority=WI.Resource.networkPriorityFromPayload(metrics.priority);if(metrics.remoteAddress)
this._remoteAddress=metrics.remoteAddress;if(metrics.connectionIdentifier)
this._connectionIdentifier=WI.Resource.connectionIdentifierFromPayload(metrics.connectionIdentifier);if(metrics.requestHeaders){this._requestHeaders=metrics.requestHeaders;this._requestCookies=null;this.dispatchEventToListeners(WI.Resource.Event.RequestHeadersDidChange);}
if("requestHeaderBytesSent"in metrics){this._requestHeadersTransferSize=metrics.requestHeaderBytesSent;this._requestBodyTransferSize=metrics.requestBodyBytesSent;this._responseHeadersTransferSize=metrics.responseHeaderBytesReceived;this._responseBodyTransferSize=metrics.responseBodyBytesReceived;this._responseBodySize=metrics.responseBodyDecodedSize;if(isNaN(this._estimatedSize))
this._estimatedSize=0;this.dispatchEventToListeners(WI.Resource.Event.SizeDidChange,{previousSize:this._estimatedSize});this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);}
if(metrics.securityConnection){if(!this._security)
this._security={};this._security.connection=metrics.securityConnection;}
this.dispatchEventToListeners(WI.Resource.Event.MetricsDidChange);}
setCachedResponseBodySize(size)
{this._cachedResponseBodySize=size;}
requestContentFromBackend()
{let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise)
return specialContentPromise;if(this._target.type===WI.TargetType.Worker){let scriptForTarget=this.scripts.find((script)=>script.target===this._target);if(scriptForTarget)
return scriptForTarget.requestContentFromBackend();}else{if(this._requestIdentifier)
return this._target.NetworkAgent.getResponseBody(this._requestIdentifier);if(this._parentFrame)
return this._target.PageAgent.getResourceContent(this._parentFrame.id,this._url);}
return Promise.reject(new Error("Content request failed."));}
increaseSize(dataLength,elapsedTime)
{if(isNaN(this._estimatedSize))
this._estimatedSize=0;let previousSize=this._estimatedSize;this._estimatedSize+=dataLength;this._lastDataReceivedTimestamp=elapsedTime||NaN;this.dispatchEventToListeners(WI.Resource.Event.SizeDidChange,{previousSize});if(isNaN(this._estimatedTransferSize)&&this._statusCode!==304&&!this._responseHeaders.valueForCaseInsensitiveKey("Content-Length"))
this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);}
increaseTransferSize(encodedDataLength)
{if(isNaN(this._estimatedTransferSize))
this._estimatedTransferSize=0;this._estimatedTransferSize+=encodedDataLength;this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);}
markAsCached()
{this._cached=true;this.dispatchEventToListeners(WI.Resource.Event.CacheStatusDidChange);if(this._statusCode!==304)
this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);}
markAsFinished(elapsedTime)
{this._finished=true;this._finishedOrFailedTimestamp=elapsedTime||NaN;this._timingData.markResponseEndTime(elapsedTime||NaN);if(this._finishThenRequestContentPromise)
this._finishThenRequestContentPromise=null;this.dispatchEventToListeners(WI.Resource.Event.LoadingDidFinish);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);}
markAsFailed(canceled,elapsedTime,errorText)
{this._failed=true;this._canceled=canceled;this._finishedOrFailedTimestamp=elapsedTime||NaN;if(!this._failureReasonText)
this._failureReasonText=errorText||null;this.dispatchEventToListeners(WI.Resource.Event.LoadingDidFail);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);}
revertMarkAsFinished()
{this._finished=false;this._finishedOrFailedTimestamp=NaN;}
legacyMarkServedFromMemoryCache()
{this._responseSource=WI.Resource.ResponseSource.MemoryCache;this.markAsCached();}
legacyMarkServedFromDiskCache()
{this._responseSource=WI.Resource.ResponseSource.DiskCache;this.markAsCached();}
isLoading()
{return!this._finished&&!this._failed;}
hadLoadingError()
{return this._failed||this._canceled||this._statusCode>=400;}
getImageSize(callback)
{if(this.type!==WI.Resource.Type.Image)
throw"Resource is not an image.";if(this._imageSize!==undefined){callback(this._imageSize);return;}
var objectURL=null;function imageDidLoad(){URL.revokeObjectURL(objectURL);this._imageSize={width:image.width,height:image.height};callback(this._imageSize);}
function requestContentFailure(){this._imageSize=null;callback(this._imageSize);}

var image=new Image;image.addEventListener("load",imageDidLoad.bind(this),false);this.requestContent().then((content)=>{objectURL=image.src=content.sourceCode.createObjectURL();if(!objectURL)
requestContentFailure.call(this);},requestContentFailure.bind(this));}
requestContent()
{if(this._finished)
return super.requestContent().catch(this._requestContentFailure.bind(this));if(this._failed)
return this._requestContentFailure();if(!this._finishThenRequestContentPromise){this._finishThenRequestContentPromise=new Promise((resolve,reject)=>{this.singleFireEventListener(WI.Resource.Event.LoadingDidFinish,resolve,this);this.singleFireEventListener(WI.Resource.Event.LoadingDidFail,reject,this);}).then(this.requestContent.bind(this));}
return this._finishThenRequestContentPromise;}
associateWithScript(script)
{if(!this._scripts)
this._scripts=[];this._scripts.push(script);if(this._type===WI.Resource.Type.Other||this._type===WI.Resource.Type.XHR){let oldType=this._type;this._type=WI.Resource.Type.Script;this.dispatchEventToListeners(WI.Resource.Event.TypeDidChange,{oldType});}}
saveIdentityToCookie(cookie)
{cookie[WI.Resource.URLCookieKey]=this.url.hash;cookie[WI.Resource.MainResourceCookieKey]=this.isMainResource();}
async createLocalResourceOverride(type,{mimeType,base64Encoded,content}={})
{let resourceData={requestURL:this.url,};switch(type){case WI.LocalResourceOverride.InterceptType.Request:resourceData.requestMethod=this.requestMethod??WI.HTTPUtilities.RequestMethod.GET;resourceData.requestHeaders=Object.shallowCopy(this.requestHeaders);resourceData.requestData=this.requestData??"";break;case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:resourceData.responseMIMEType=this.mimeType??WI.mimeTypeForFileExtension(WI.fileExtensionForFilename(this.urlComponents.lastPathComponent));resourceData.responseStatusCode=this.statusCode;resourceData.responseStatusText=this.statusText;if(!resourceData.responseStatusCode){resourceData.responseStatusCode=200;resourceData.responseStatusText=null;}
resourceData.responseStatusText||=WI.HTTPUtilities.statusTextForStatusCode(resourceData.responseStatusCode);if(base64Encoded===undefined||content===undefined){try{let{rawContent,rawBase64Encoded}=await this.requestContent();content??=rawContent;base64Encoded??=rawBase64Encoded;}catch{content??="";base64Encoded??=!WI.shouldTreatMIMETypeAsText(resourceData.mimeType);}}
resourceData.responseContent=content;resourceData.responseBase64Encoded=base64Encoded;resourceData.responseHeaders=Object.shallowCopy(this.responseHeaders);break;}
return WI.LocalResourceOverride.create(WI.urlWithoutFragment(this.url),type,resourceData);}
updateLocalResourceOverrideRequestData(data)
{if(data===this._requestData)
return;this._requestData=data;this.dispatchEventToListeners(WI.Resource.Event.RequestDataDidChange);}
generateCURLCommand()
{function escapeStringPosix(str){function escapeCharacter(x){let code=x.charCodeAt(0);let hex=code.toString(16);if(code<256)
return"\\x"+hex.padStart(2,"0");return"\\u"+hex.padStart(4,"0");}
if(/[^\x20-\x7E]|'/.test(str)){return"$'"+str.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/!/g,"\\041").replace(/[^\x20-\x7E]/g,escapeCharacter)+"'";}
return`'${str}'`;}
let command=["curl "+escapeStringPosix(this.url).replace(/[[{}\]]/g,"\\$&")];command.push("-X "+escapeStringPosix(this.requestMethod));for(let key in this.requestHeaders)
command.push("-H "+escapeStringPosix(`${key}: ${this.requestHeaders[key]}`));if(this.requestDataContentType&&this.requestMethod!=="GET"&&this.requestData){if(this.requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i))
command.push("--data "+escapeStringPosix(this.requestData));else
command.push("--data-binary "+escapeStringPosix(this.requestData));}
return command.join(" \\\n");}
stringifyHTTPRequest()
{let lines=[];let protocol=this.protocol||"";if(protocol==="h2"){ lines.push(`:method: ${this.requestMethod}`);lines.push(`:scheme: ${this.urlComponents.scheme}`);lines.push(`:authority: ${WI.h2Authority(this.urlComponents)}`);lines.push(`:path: ${WI.h2Path(this.urlComponents)}`);}else{ lines.push(`${this.requestMethod} ${this.urlComponents.path}${protocol ? " " + protocol.toUpperCase() : ""}`);}
for(let key in this.requestHeaders)
lines.push(`${key}: ${this.requestHeaders[key]}`);return lines.join("\n")+"\n";}
stringifyHTTPResponse()
{let lines=[];let protocol=this.protocol||"";if(protocol==="h2"){ lines.push(`:status: ${this.statusCode}`);}else{ lines.push(`${protocol ? protocol.toUpperCase() + " " : ""}${this.statusCode} ${this.statusText}`);}
for(let key in this.responseHeaders)
lines.push(`${key}: ${this.responseHeaders[key]}`);return lines.join("\n")+"\n";}
async showCertificate()
{let errorString=WI.UIString("Unable to show certificate for \u201C%s\u201D").format(this.url);try{let{serializedCertificate}=await this._target.NetworkAgent.getSerializedCertificate(this._requestIdentifier);if(InspectorFrontendHost.showCertificate(serializedCertificate))
return;}catch(e){console.error(e);throw errorString;}
let consoleMessage=new WI.ConsoleMessage(this._target,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,errorString);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);throw errorString;} 
_requestContentFailure(error)
{return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource."),reason:error?.message||this._failureReasonText,sourceCode:this,});}};WI.Resource.TypeIdentifier="resource";WI.Resource.URLCookieKey="resource-url";WI.Resource.MainResourceCookieKey="resource-is-main-resource";WI.Resource.Event={URLDidChange:"resource-url-did-change",MIMETypeDidChange:"resource-mime-type-did-change",TypeDidChange:"resource-type-did-change",RequestHeadersDidChange:"resource-request-headers-did-change",RequestDataDidChange:"resource-request-data-did-change",ResponseReceived:"resource-response-received",LoadingDidFinish:"resource-loading-did-finish",LoadingDidFail:"resource-loading-did-fail",TimestampsDidChange:"resource-timestamps-did-change",SizeDidChange:"resource-size-did-change",TransferSizeDidChange:"resource-transfer-size-did-change",CacheStatusDidChange:"resource-cached-did-change",MetricsDidChange:"resource-metrics-did-change",InitiatedResourcesDidChange:"resource-initiated-resources-did-change",};WI.Resource.Type={Document:"resource-type-document",StyleSheet:"resource-type-style-sheet",Image:"resource-type-image",Font:"resource-type-font",Script:"resource-type-script",XHR:"resource-type-xhr",Fetch:"resource-type-fetch",Ping:"resource-type-ping",Beacon:"resource-type-beacon",WebSocket:"resource-type-websocket",Other:"resource-type-other",};WI.Resource.ResponseSource={Unknown:Symbol("unknown"),Network:Symbol("network"),MemoryCache:Symbol("memory-cache"),DiskCache:Symbol("disk-cache"),ServiceWorker:Symbol("service-worker"),InspectorOverride:Symbol("inspector-override"),};WI.Resource.NetworkPriority={Unknown:Symbol("unknown"),Low:Symbol("low"),Medium:Symbol("medium"),High:Symbol("high"),};WI.Resource.GroupingMode={Path:"group-resource-by-path",Type:"group-resource-by-type",};WI.settings.resourceGroupingMode=new WI.Setting("resource-grouping-mode",WI.Resource.GroupingMode.Type);WI.Resource._mimeTypeMap={"text/html":WI.Resource.Type.Document,"text/xml":WI.Resource.Type.Document,"application/xhtml+xml":WI.Resource.Type.Document,"text/plain":WI.Resource.Type.Other,"text/css":WI.Resource.Type.StyleSheet,"text/xsl":WI.Resource.Type.StyleSheet,"text/x-less":WI.Resource.Type.StyleSheet,"text/x-sass":WI.Resource.Type.StyleSheet,"text/x-scss":WI.Resource.Type.StyleSheet,"application/pdf":WI.Resource.Type.Image,"image/svg+xml":WI.Resource.Type.Image,"application/x-font-type1":WI.Resource.Type.Font,"application/x-font-ttf":WI.Resource.Type.Font,"application/x-font-woff":WI.Resource.Type.Font,"application/x-truetype-font":WI.Resource.Type.Font,"text/javascript":WI.Resource.Type.Script,"text/ecmascript":WI.Resource.Type.Script,"application/javascript":WI.Resource.Type.Script,"application/ecmascript":WI.Resource.Type.Script,"application/x-javascript":WI.Resource.Type.Script,"application/json":WI.Resource.Type.Script,"application/x-json":WI.Resource.Type.Script,"text/x-javascript":WI.Resource.Type.Script,"text/x-json":WI.Resource.Type.Script,"text/javascript1.1":WI.Resource.Type.Script,"text/javascript1.2":WI.Resource.Type.Script,"text/javascript1.3":WI.Resource.Type.Script,"text/jscript":WI.Resource.Type.Script,"text/livescript":WI.Resource.Type.Script,"text/x-livescript":WI.Resource.Type.Script,"text/typescript":WI.Resource.Type.Script,"text/typescript-jsx":WI.Resource.Type.Script,"text/jsx":WI.Resource.Type.Script,"text/x-clojure":WI.Resource.Type.Script,"text/x-coffeescript":WI.Resource.Type.Script,};WI.Script=class Script extends WI.SourceCode
{constructor(target,id,range,url,sourceType,injected,sourceURL,sourceMapURL)
{super(url);this._target=target;this._id=id||null;this._range=range||null;this._sourceType=sourceType||WI.Script.SourceType.Program;this._sourceURL=sourceURL||null;this._sourceMappingURL=sourceMapURL||null;this._injected=injected||false;this._dynamicallyAddedScriptElement=false;this._scriptSyntaxTree=null;this._resource=this._resolveResource();
if(this._resource&&this._resource.type===WI.Resource.Type.Document&&!this._range.startLine&&!this._range.startColumn){let documentResource=this._resource;this._resource=null;this._dynamicallyAddedScriptElement=true;documentResource.parentFrame.addExtraScript(this);this._dynamicallyAddedScriptElementNumber=documentResource.parentFrame.extraScriptCollection.size;}else if(this._resource)
this._resource.associateWithScript(this);if(isWebInspectorConsoleEvaluationScript(this._sourceURL)){this._uniqueDisplayNameNumber=this._nextUniqueConsoleDisplayNameNumber();}
if(this._sourceMappingURL)
WI.networkManager.downloadSourceMap(this._sourceMappingURL,this._url,this);} 
static resetUniqueDisplayNameNumbers(target)
{if(WI.Script._uniqueDisplayNameNumbersForRootTargetMap)
WI.Script._uniqueDisplayNameNumbersForRootTargetMap.delete(target);} 
get target(){return this._target;}
get id(){return this._id;}
get range(){return this._range;}
get sourceType(){return this._sourceType;}
get sourceURL(){return this._sourceURL;}
get sourceMappingURL(){return this._sourceMappingURL;}
get injected(){return this._injected;}
get contentIdentifier()
{if(this._url)
return this._url;if(!this._sourceURL)
return null;



if(isWebInspectorConsoleEvaluationScript(this._sourceURL))
return null;if(isWebInspectorInternalScript(this._sourceURL))
return null;return this._sourceURL;}
get mimeType()
{return this._resource?this._resource.mimeType:"text/javascript";}
get isScript()
{return true;}
get displayName()
{if(isWebInspectorBootstrapScript(this._sourceURL||this._url)){return WI.UIString("Inspector Bootstrap Script");}
if(this._url&&!this._dynamicallyAddedScriptElement)
return WI.displayNameForURL(this._url,this.urlComponents);if(isWebInspectorConsoleEvaluationScript(this._sourceURL)){return WI.UIString("Console Evaluation %d").format(this._uniqueDisplayNameNumber);}
if(this._sourceURL){if(!this._sourceURLComponents)
this._sourceURLComponents=parseURL(this._sourceURL);return WI.displayNameForURL(this._sourceURL,this._sourceURLComponents);}
if(this._dynamicallyAddedScriptElement)
return WI.UIString("Script Element %d").format(this._dynamicallyAddedScriptElementNumber);if(!this._uniqueDisplayNameNumber)
this._uniqueDisplayNameNumber=this._nextUniqueDisplayNameNumber();return WI.UIString("Anonymous Script %d").format(this._uniqueDisplayNameNumber);}
get displayURL()
{if(isWebInspectorBootstrapScript(this._sourceURL||this._url)){return WI.UIString("Inspector Bootstrap Script");}
const isMultiLine=true;const dataURIMaxSize=64;if(this._url)
return WI.truncateURL(this._url,isMultiLine,dataURIMaxSize);if(this._sourceURL)
return WI.truncateURL(this._sourceURL,isMultiLine,dataURIMaxSize);return null;}
get dynamicallyAddedScriptElement()
{return this._dynamicallyAddedScriptElement;}
get anonymous()
{return!this._resource&&!this._url&&!this._sourceURL;}
get resource()
{return this._resource;}
get scriptSyntaxTree()
{return this._scriptSyntaxTree;}
isMainResource()
{return this._target&&this._target.mainResource===this;}
requestContentFromBackend()
{let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise)
return specialContentPromise;if(!this._id){
return Promise.reject(new Error("There is no identifier to request content with."));}
return this._target.DebuggerAgent.getScriptSource(this._id);}
saveIdentityToCookie(cookie)
{cookie[WI.Script.URLCookieKey]=this.url;cookie[WI.Script.DisplayNameCookieKey]=this.displayName;}
requestScriptSyntaxTree(callback)
{if(this._scriptSyntaxTree){setTimeout(()=>{callback(this._scriptSyntaxTree);},0);return;}
var makeSyntaxTreeAndCallCallback=(content)=>{this._makeSyntaxTree(content);callback(this._scriptSyntaxTree);};var content=this.content;if(!content&&this._resource&&this._resource.type===WI.Resource.Type.Script&&this._resource.finished)
content=this._resource.content;if(content){setTimeout(makeSyntaxTreeAndCallCallback,0,content);return;}
this.requestContent().then(function(parameters){makeSyntaxTreeAndCallCallback(parameters.sourceCode.content);}).catch(function(error){makeSyntaxTreeAndCallCallback(null);});} 
_nextUniqueDisplayNameNumber()
{let numbers=this._uniqueDisplayNameNumbersForRootTarget();return++numbers.lastUniqueDisplayNameNumber;}
_nextUniqueConsoleDisplayNameNumber()
{let numbers=this._uniqueDisplayNameNumbersForRootTarget();return++numbers.lastUniqueConsoleDisplayNameNumber;}
_uniqueDisplayNameNumbersForRootTarget()
{if(!WI.Script._uniqueDisplayNameNumbersForRootTargetMap)
WI.Script._uniqueDisplayNameNumbersForRootTargetMap=new WeakMap();let key=this._target.rootTarget;let numbers=WI.Script._uniqueDisplayNameNumbersForRootTargetMap.get(key);if(!numbers){numbers={lastUniqueDisplayNameNumber:0,lastUniqueConsoleDisplayNameNumber:0};WI.Script._uniqueDisplayNameNumbersForRootTargetMap.set(key,numbers);}
return numbers;}
_resolveResource()
{

if(!this._url)
return null;let resolver=WI.networkManager;if(this._target&&this._target!==WI.mainTarget)
resolver=this._target.resourceCollection;function isScriptResource(item){return item.type===WI.Resource.Type.Document||item.type===WI.Resource.Type.Script;}
try{let resource=resolver.resourcesForURL(this._url).find(isScriptResource);if(resource)
return resource;let decodedURL=decodeURI(this._url);if(decodedURL!==this._url){resource=resolver.resourcesForURL(decodedURL).find(isScriptResource);if(resource)
return resource;}
let urlWithoutFragment=removeURLFragment(this._url);if(urlWithoutFragment!==this._url){resource=resolver.resourcesForURL(urlWithoutFragment).find(isScriptResource);if(resource)
return resource;}
let decodedURLWithoutFragment=removeURLFragment(decodedURL);if(decodedURLWithoutFragment!==decodedURL){resource=resolver.resourcesForURL(decodedURLWithoutFragment).find(isScriptResource);if(resource)
return resource;}}catch{}
if(!this.isMainResource()){for(let frame of WI.networkManager.frames){if(frame.mainResource.type===WI.Resource.Type.Document&&frame.mainResource.url.startsWith(this._url))
return frame.mainResource;}}
return null;}
_makeSyntaxTree(sourceText)
{if(this._scriptSyntaxTree||!sourceText)
return;this._scriptSyntaxTree=new WI.ScriptSyntaxTree(sourceText,this);}};WI.Script.SourceType={Program:"script-source-type-program",Module:"script-source-type-module",};WI.Script.TypeIdentifier="script";WI.Script.URLCookieKey="script-url";WI.Script.DisplayNameCookieKey="script-display-name";WI.LocalScript=class LocalScript extends WI.Script
{constructor(target,url,sourceURL,sourceType,source,{injected,editable}={})
{const id=null;super(target,id,WI.TextRange.fromText(source),url,sourceType,injected,sourceURL);this._editable=!!editable;const base64Encoded=false;const mimeType="text/javascript";this._originalRevision=new WI.SourceCodeRevision(this,source,base64Encoded,mimeType);this._currentRevision=this._originalRevision;} 
get editable(){return this._editable;}
get supportsScriptBlackboxing()
{return false;}
requestContentFromBackend()
{return Promise.resolve({scriptSource:this._originalRevision.content,});} 
handleCurrentRevisionContentChange()
{super.handleCurrentRevisionContentChange();this._range=WI.TextRange.fromText(this._currentRevision.content);}};WI.Animation=class Animation extends WI.Object
{constructor(animationId,{name,cssAnimationName,cssTransitionProperty,effect,backtrace}={})
{super();this._animationId=animationId;this._name=name||null;this._cssAnimationName=cssAnimationName||null;this._cssTransitionProperty=cssTransitionProperty||null;this._updateEffect(effect);this._backtrace=backtrace||[];this._effectTarget=undefined;this._requestEffectTargetCallbacks=null;} 
static fromPayload(payload)
{return new WI.Animation(payload.animationId,{name:payload.name,cssAnimationName:payload.cssAnimationName,cssTransitionProperty:payload.cssTransitionProperty,effect:payload.effect,backtrace:Array.isArray(payload.backtrace)?payload.backtrace.map((item)=>WI.CallFrame.fromPayload(WI.mainTarget,item)):[],});}
static displayNameForAnimationType(animationType,plural)
{switch(animationType){case WI.Animation.Type.WebAnimation:return plural?WI.UIString("Web Animations"):WI.UIString("Web Animation");case WI.Animation.Type.CSSAnimation:return plural?WI.UIString("CSS Animations"):WI.UIString("CSS Animation");case WI.Animation.Type.CSSTransition:return plural?WI.UIString("CSS Transitions"):WI.UIString("CSS Transition");}
return null;}
static displayNameForPlaybackDirection(playbackDirection)
{switch(playbackDirection){case WI.Animation.PlaybackDirection.Normal:return WI.UIString("Normal","Web Animation Playback Direction Normal","Indicates that the playback direction of this web animation is normal (e.g. forwards)");case WI.Animation.PlaybackDirection.Reverse:return WI.UIString("Reverse","Web Animation Playback Direction Reverse","Indicates that the playback direction of this web animation is reversed (e.g. backwards)");case WI.Animation.PlaybackDirection.Alternate:return WI.UIString("Alternate","Web Animation Playback Direction Alternate","Indicates that the playback direction of this web animation alternates between normal and reversed on each iteration");case WI.Animation.PlaybackDirection.AlternateReverse:return WI.UIString("Alternate Reverse","Web Animation Playback Direction Alternate Reverse","Indicates that the playback direction of this web animation alternates between reversed and normal on each iteration");}
return null;}
static displayNameForFillMode(fillMode)
{switch(fillMode){case WI.Animation.FillMode.None:return WI.UIString("None","Web Animation Fill Mode None","Indicates that this web animation does not apply any styles before it begins and after it ends");case WI.Animation.FillMode.Forwards:return WI.UIString("Forwards","Web Animation Fill Mode Forwards","Indicates that this web animation also applies styles after it ends");case WI.Animation.FillMode.Backwards:return WI.UIString("Backwards","Web Animation Fill Mode Backwards","Indicates that this web animation also applies styles before it begins");case WI.Animation.FillMode.Both:return WI.UIString("Both","Web Animation Fill Mode Both","Indicates that this web animation also applies styles before it begins and after it ends");case WI.Animation.FillMode.Auto:return WI.UIString("Auto","Web Animation Fill Mode Auto","Indicates that this web animation either does not apply any styles before it begins and after it ends or that it applies to both, depending on it's configuration");}
return null;}
static resetUniqueDisplayNameNumbers()
{WI.Animation._nextUniqueDisplayNameNumber=1;} 
get animationId(){return this._animationId;}
get name(){return this._name;}
get cssAnimationName(){return this._cssAnimationName;}
get cssTransitionProperty(){return this._cssTransitionProperty;}
get backtrace(){return this._backtrace;}
get animationType()
{if(this._cssAnimationName)
return WI.Animation.Type.CSSAnimation;if(this._cssTransitionProperty)
return WI.Animation.Type.CSSTransition;return WI.Animation.Type.WebAnimation;}
get startDelay()
{return"startDelay"in this._effect?this._effect.startDelay:NaN;}
get endDelay()
{return"endDelay"in this._effect?this._effect.endDelay:NaN;}
get iterationCount()
{return"iterationCount"in this._effect?this._effect.iterationCount:NaN;}
get iterationStart()
{return"iterationStart"in this._effect?this._effect.iterationStart:NaN;}
get iterationDuration()
{return"iterationDuration"in this._effect?this._effect.iterationDuration:NaN;}
get timingFunction()
{return"timingFunction"in this._effect?this._effect.timingFunction:null;}
get playbackDirection()
{return"playbackDirection"in this._effect?this._effect.playbackDirection:null;}
get fillMode()
{return"fillMode"in this._effect?this._effect.fillMode:null;}
get keyframes()
{return"keyframes"in this._effect?this._effect.keyframes:[];}
get displayName()
{if(this._name)
return this._name;if(this._cssAnimationName)
return this._cssAnimationName;if(this._cssTransitionProperty)
return this._cssTransitionProperty;if(!this._uniqueDisplayNameNumber)
this._uniqueDisplayNameNumber=WI.Animation._nextUniqueDisplayNameNumber++;return WI.UIString("Animation %d").format(this._uniqueDisplayNameNumber);}
requestEffectTarget(callback)
{if(this._effectTarget!==undefined){callback(this._effectTarget);return;}
if(this._requestEffectTargetCallbacks){this._requestEffectTargetCallbacks.push(callback);return;}
this._requestEffectTargetCallbacks=[callback];WI.domManager.ensureDocument();let target=WI.assumingMainTarget();target.AnimationAgent.requestEffectTarget(this._animationId,(error,nodeId)=>{this._effectTarget=!error?WI.domManager.nodeForId(nodeId):null;for(let requestEffectTargetCallback of this._requestEffectTargetCallbacks)
requestEffectTargetCallback(this._effectTarget);this._requestEffectTargetCallbacks=null;});} 
nameChanged(name)
{this._name=name||null;this.dispatchEventToListeners(WI.Animation.Event.NameChanged);}
effectChanged(effect)
{this._updateEffect(effect);}
targetChanged()
{this._effectTarget=undefined;this.dispatchEventToListeners(WI.Animation.Event.TargetChanged);} 
_updateEffect(effect)
{this._effect=effect||{};if("iterationCount"in this._effect){if(this._effect.iterationCount===-1)
this._effect.iterationCount=Infinity;else if(this._effect.iterationCount===null){this._effect.iterationCount=Infinity;}}
if("timingFunction"in this._effect){let timingFunction=this._effect.timingFunction;this._effect.timingFunction=WI.CubicBezier.fromString(timingFunction)||WI.StepsFunction.fromString(timingFunction)||WI.Spring.fromString(timingFunction);}
if("keyframes"in this._effect){for(let keyframe of this._effect.keyframes){if(keyframe.easing){let easing=keyframe.easing;keyframe.easing=WI.CubicBezier.fromString(easing)||WI.StepsFunction.fromString(easing)||WI.Spring.fromString(easing);}
if(keyframe.style)
keyframe.style=keyframe.style.replaceAll(/;\s+/g,";\n");}}
this.dispatchEventToListeners(WI.Animation.Event.EffectChanged);}};WI.Animation._nextUniqueDisplayNameNumber=1;WI.Animation.Type={WebAnimation:"web-animation",CSSAnimation:"css-animation",CSSTransition:"css-transition",};WI.Animation.PlaybackDirection={Normal:"normal",Reverse:"reverse",Alternate:"alternate",AlternateReverse:"alternate-reverse",};WI.Animation.FillMode={None:"none",Forwards:"forwards",Backwards:"backwards",Both:"both",Auto:"auto",};WI.Animation.Event={NameChanged:"animation-name-changed",EffectChanged:"animation-effect-changed",TargetChanged:"animation-target-changed",};WI.AnimationCollection=class AnimationCollection extends WI.Collection
{constructor(animationType)
{super();this._animationType=animationType||null;if(!this._animationType)
this._animationCollectionForTypeMap=null;} 
get animationType(){return this._animationType;}
get displayName()
{if(this._animationType){const plural=true;return WI.Animation.displayNameForType(this._animationType,plural);}
return WI.UIString("Web Animations");}
objectIsRequiredType(object)
{if(!(object instanceof WI.Animation))
return false;return!this._animationType||object.animationType===this._animationType;}
animationCollectionForType(animationType)
{if(this._animationType){return this;}
if(!this._animationCollectionForTypeMap)
this._animationCollectionForTypeMap=new Map;let animationCollectionForType=this._animationCollectionForTypeMap.get(animationType);if(!animationCollectionForType){animationCollectionForType=new WI.AnimationCollection(animationType);this._animationCollectionForTypeMap.set(animationType,animationCollectionForType);}
return animationCollectionForType;} 
itemAdded(item)
{super.itemAdded(item);if(!this._animationType){let animationCollectionForType=this.animationCollectionForType(item.animationType);animationCollectionForType.add(item);}}
itemRemoved(item)
{if(!this._animationType){let animationCollectionForType=this.animationCollectionForType(item.animationType);animationCollectionForType.remove(item);}
super.itemRemoved(item);}
itemsCleared(items)
{if(this._animationCollectionForTypeMap){for(let animationCollectionForType of this._animationCollectionForTypeMap.values())
animationCollectionForType.clear();}
super.itemsCleared(items);}};WI.ApplicationCacheFrame=class ApplicationCacheFrame
{constructor(frame,manifest,status)
{this._frame=frame;this._manifest=manifest;this._status=status;} 
get frame(){return this._frame;}
get manifest(){return this._manifest;}
get status(){return this._status;}
set status(status){this._status=status;}
saveIdentityToCookie(cookie)
{cookie[WI.ApplicationCacheFrame.FrameURLCookieKey]=this.frame.url;cookie[WI.ApplicationCacheFrame.ManifestURLCookieKey]=this.manifest.manifestURL;}};WI.ApplicationCacheFrame.TypeIdentifier="application-cache-frame";WI.ApplicationCacheFrame.FrameURLCookieKey="application-cache-frame-url";WI.ApplicationCacheFrame.ManifestURLCookieKey="application-cache-frame-manifest-url";WI.ApplicationCacheManifest=class ApplicationCacheManifest
{constructor(manifestURL)
{this._manifestURL=manifestURL;} 
get manifestURL(){return this._manifestURL;}};WI.BackForwardEntry=class BackForwardEntry
{constructor(contentView,cookie)
{this._contentView=contentView;
this._tombstone=false;this._cookie=cookie||{};this._scrollPositions=[];contentView.saveToCookie(this._cookie);} 
makeCopy(newCookie)
{let copy=new WI.BackForwardEntry(this._contentView,newCookie||this.cookie);copy._tombstone=this._tombstone;copy._scrollPositions=this._scrollPositions.slice();return copy;}
get contentView()
{return this._contentView;}
get cookie()
{return Object.shallowCopy(this._cookie);}
get tombstone()
{return this._tombstone;}
set tombstone(tombstone)
{this._tombstone=tombstone;}
prepareToShow()
{this._restoreFromCookie();this.contentView.needsLayout();}
prepareToHide()
{this._saveScrollPositions();if(this._contentView.shouldSaveStateWhenHidden){this._cookie={};this._contentView.saveToCookie(this._cookie);}}
isEqual(other)
{if(!other)
return false;return this._contentView===other._contentView&&Object.shallowEqual(this._cookie,other._cookie);} 
_restoreFromCookie()
{this._restoreScrollPositions();this.contentView.restoreFromCookie(this.cookie);}
_restoreScrollPositions()
{if(!this._scrollPositions.length)
return;var scrollableElements=this.contentView.scrollableElements||[];for(var i=0;i<scrollableElements.length;++i){var position=this._scrollPositions[i];var element=scrollableElements[i];if(!element)
continue;element.scrollTop=position.isScrolledToBottom?element.scrollHeight:position.scrollTop;
element.scrollLeft=position.isScrolledToBottom?0:position.scrollLeft;}}
_saveScrollPositions()
{var scrollableElements=this.contentView.scrollableElements||[];var scrollPositions=[];for(var i=0;i<scrollableElements.length;++i){var element=scrollableElements[i];if(!element)
continue;let position={scrollTop:element.scrollTop,scrollLeft:element.scrollLeft};if(this.contentView.shouldKeepElementsScrolledToBottom)
position.isScrolledToBottom=element.isScrolledToBottom();scrollPositions.push(position);}
this._scrollPositions=scrollPositions;}};WI.BoxShadow=class BoxShadow
{constructor(offsetX,offsetY,blurRadius,spreadRadius,inset,color)
{this._offsetX=offsetX||null;this._offsetY=offsetY||null;this._blurRadius=blurRadius||null;this._spreadRadius=spreadRadius||null;this._inset=!!inset;this._color=color||null;} 
static fromString(cssString)
{if(cssString==="none")
return new WI.BoxShadow;let offsetX=null;let offsetY=null;let blurRadius=null;let spreadRadius=null;let inset=false;let color=null;let startIndex=0;let openParentheses=0;let numberComponentCount=0;for(let i=0;i<=cssString.length;++i){if(cssString[i]==="("){++openParentheses;continue;}
if(cssString[i]===")"){--openParentheses;continue;}
if((cssString[i]!==" "||openParentheses)&&i!==cssString.length)
continue;let component=cssString.substring(startIndex,i+1).trim();startIndex=i+1;if(!component.length)
continue;if(component==="inset"){if(inset)
return null;inset=true;continue;}
let possibleColor=WI.Color.fromString(component);if(possibleColor){if(color)
return null;color=possibleColor;continue;}
let numberComponent=WI.BoxShadow.parseNumberComponent(component);if(!numberComponent)
return null;switch(++numberComponentCount){case 1:offsetX=numberComponent;break;case 2:offsetY=numberComponent;break;case 3:blurRadius=numberComponent;if(blurRadius.value<0)
return null;break;case 4:spreadRadius=numberComponent;break;default:return null;}}
if(!offsetX||!offsetY)
return null;return new WI.BoxShadow(offsetX,offsetY,blurRadius,spreadRadius,inset,color);}
static parseNumberComponent(string)
{let value=parseFloat(string);if(isNaN(value))
return null;let unit=string.replace(value,"");if(!unit){if(value)
return null;unit="px";}else if(!WI.CSSCompletions.lengthUnits.has(unit))
return null;return{unit,value};} 
get offsetX(){return this._offsetX;}
get offsetY(){return this._offsetY;}
get blurRadius(){return this._blurRadius;}
get spreadRadius(){return this._spreadRadius;}
get inset(){return this._inset;}
get color(){return this._color;}
copy()
{return new WI.BoxShadow(this._offsetX,this._offsetY,this._blurRadius,this._spreadRadius,this._inset,this._color);}
toString()
{if(!this._offsetX||!this._offsetY)
return"none";function stringifyNumberComponent({value,unit}){return value+(value?unit:"");}
let values=[stringifyNumberComponent(this._offsetX),stringifyNumberComponent(this._offsetY),];if(this._blurRadius)
values.push(stringifyNumberComponent(this._blurRadius));if(this._spreadRadius)
values.push(stringifyNumberComponent(this._spreadRadius));if(this._color)
values.push(this._color.toString());if(this._inset)
values.push("inset");return values.join(" ");}};WI.CPUInstrument=class CPUInstrument extends WI.Instrument
{constructor()
{super();} 
static supported()
{return InspectorBackend.hasDomain("CPUProfiler");} 
get timelineRecordType()
{return WI.TimelineRecord.Type.CPU;}
startInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.CPUProfilerAgent.startTracking();}}
stopInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.CPUProfilerAgent.stopTracking();}}};WI.CPUTimeline=class CPUTimeline extends WI.Timeline
{ addRecord(record,options={})
{let lastRecord=this.records.lastValue;if(lastRecord){let startTime=lastRecord.endTime;if(options.discontinuity)
startTime=options.discontinuity.endTime;record.adjustStartTime(startTime);}
super.addRecord(record,options);}};WI.CPUTimelineRecord=class CPUTimelineRecord extends WI.TimelineRecord
{constructor({timestamp,usage,threads})
{super(WI.TimelineRecord.Type.CPU,timestamp-CPUTimelineRecord.samplingRatePerSecond,timestamp);this._timestamp=timestamp;this._usage=usage;this._threads=threads||[];this._mainThreadUsage=0;this._webkitThreadUsage=0;this._workerThreadUsage=0;this._unknownThreadUsage=0;this._workersData=null;for(let thread of this._threads){if(thread.type===InspectorBackend.Enum.CPUProfiler.ThreadInfoType.Main){this._mainThreadUsage+=thread.usage;continue;}
if(thread.type===InspectorBackend.Enum.CPUProfiler.ThreadInfoType.WebKit){if(thread.targetId){if(!this._workersData)
this._workersData=[];this._workersData.push(thread);this._workerThreadUsage+=thread.usage;continue;}
this._webkitThreadUsage+=thread.usage;continue;}
this._unknownThreadUsage+=thread.usage;}} 
static get samplingRatePerSecond()
{return 0.5;} 
static async fromJSON(json)
{return new WI.CPUTimelineRecord(json);}
toJSON()
{return{type:this.type,timestamp:this._timestamp,usage:this._usage,threads:this._threads,};} 
get timestamp(){return this._timestamp;}
get usage(){return this._usage;}
get unadjustedStartTime(){return this._timestamp;}
get mainThreadUsage(){return this._mainThreadUsage;}
get webkitThreadUsage(){return this._webkitThreadUsage;}
get workerThreadUsage(){return this._workerThreadUsage;}
get unknownThreadUsage(){return this._unknownThreadUsage;}
get workersData(){return this._workersData;}
adjustStartTime(startTime)
{this._startTime=startTime;}};WI.CSSCompletions=class CSSCompletions
{constructor(properties,acceptEmptyPrefix)
{this._values=[];if(properties.length&&typeof properties[0]==="string")
this._values.pushAll(properties);else{for(var property of properties){var propertyName=property.name;this._values.push(propertyName);let aliases=property.aliases;if(aliases)
this._values.pushAll(aliases);}}
this._values.sort();this._acceptEmptyPrefix=acceptEmptyPrefix;} 
static initializeCSSCompletions(target)
{if(WI.CSSCompletions.cssNameCompletions)
return;function propertiesCallback(error,cssProperties)
{if(error)
return;WI.CSSCompletions.cssNameCompletions=new WI.CSSCompletions(cssProperties,false);WI.CSSKeywordCompletions.addCustomCompletions(cssProperties);if(!window.CodeMirror)
return;var propertyNamesForCodeMirror={};var valueKeywordsForCodeMirror={"inherit":true,"initial":true,"unset":true,"revert":true,"var":true,"env":true};var colorKeywordsForCodeMirror={};function nameForCodeMirror(name)
{return name.replace(/^-[^-]+-/,"").replace(/\(\)$/,"").toLowerCase();}
function collectPropertyNameForCodeMirror(propertyName)
{var codeMirrorPropertyName=nameForCodeMirror(propertyName);propertyNamesForCodeMirror[codeMirrorPropertyName]=true;valueKeywordsForCodeMirror[codeMirrorPropertyName]=true;}
for(var property of cssProperties)
collectPropertyNameForCodeMirror(property.name);for(var propertyName in WI.CSSKeywordCompletions._propertyKeywordMap){var keywords=WI.CSSKeywordCompletions._propertyKeywordMap[propertyName];for(var i=0;i<keywords.length;++i){if(keywords[i]===WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder||!isNaN(Number(keywords[i])))
continue;valueKeywordsForCodeMirror[nameForCodeMirror(keywords[i])]=true;}}
WI.CSSKeywordCompletions._colors.forEach(function(colorName){colorKeywordsForCodeMirror[nameForCodeMirror(colorName)]=true;});function updateCodeMirrorCSSMode(mimeType)
{var modeSpec=CodeMirror.resolveMode(mimeType);modeSpec.propertyKeywords=propertyNamesForCodeMirror;modeSpec.valueKeywords=valueKeywordsForCodeMirror;modeSpec.colorKeywords=colorKeywordsForCodeMirror;CodeMirror.defineMIME(mimeType,modeSpec);}
updateCodeMirrorCSSMode("text/css");updateCodeMirrorCSSMode("text/x-scss");}
function fontFamilyNamesCallback(error,fontFamilyNames)
{if(error)
return;WI.CSSKeywordCompletions.addPropertyCompletionValues("font-family",fontFamilyNames);WI.CSSKeywordCompletions.addPropertyCompletionValues("font",fontFamilyNames);}
target.CSSAgent.getSupportedCSSProperties(propertiesCallback);if(target.hasCommand("CSS.getSupportedSystemFontFamilyNames"))
target.CSSAgent.getSupportedSystemFontFamilyNames(fontFamilyNamesCallback);}
static completeUnbalancedValue(value)
{const State={Data:0,SingleQuoteString:1,DoubleQuoteString:2,Comment:3};let state=State.Data;let unclosedParenthesisCount=0;let trailingBackslash=false;let length=value.length;for(let i=0;i<length;++i){switch(value[i]){case"'":if(state===State.Data)
state=State.SingleQuoteString;else if(state===State.SingleQuoteString)
state=State.Data;break;case"\"":if(state===State.Data)
state=State.DoubleQuoteString;else if(state===State.DoubleQuoteString)
state=State.Data;break;case"(":if(state===State.Data)
++unclosedParenthesisCount;break;case")":if(state===State.Data&&unclosedParenthesisCount)
--unclosedParenthesisCount;break;case"/":if(state===State.Data){if(value[i+1]==="*")
state=State.Comment;}
break;case"\\":if(i===length-1)
trailingBackslash=true;else
++i;break;case"*":if(state===State.Comment){if(value[i+1]==="/")
state=State.Data;}
break;}}
let suffix="";if(trailingBackslash)
suffix+="\\";switch(state){case State.SingleQuoteString:suffix+="'";break;case State.DoubleQuoteString:suffix+="\"";break;case State.Comment:suffix+="*/";break;}
suffix+=")".repeat(unclosedParenthesisCount);return suffix;} 
get values()
{return this._values;}
addValues(values)
{if(!values.length)
return;this._values.pushAll(values);this._values.sort();}
startsWith(prefix)
{if(!prefix)
return this._acceptEmptyPrefix?this._values.slice():[];let firstIndex=this._firstIndexOfPrefix(prefix);if(firstIndex===-1)
return[];let results=[];while(firstIndex<this._values.length&&this._values[firstIndex].startsWith(prefix))
results.push(this._values[firstIndex++]);return results;}
_firstIndexOfPrefix(prefix)
{if(!this._values.length)
return-1;if(!prefix)
return this._acceptEmptyPrefix?0:-1;var maxIndex=this._values.length-1;var minIndex=0;var foundIndex;do{var middleIndex=(maxIndex+minIndex)>>1;if(this._values[middleIndex].startsWith(prefix)){foundIndex=middleIndex;break;}
if(this._values[middleIndex]<prefix)
minIndex=middleIndex+1;else
maxIndex=middleIndex-1;}while(minIndex<=maxIndex);if(foundIndex===undefined)
return-1;while(foundIndex&&this._values[foundIndex-1].startsWith(prefix))
foundIndex--;return foundIndex;}
next(str,prefix)
{return this._closest(str,prefix,1);}
previous(str,prefix)
{return this._closest(str,prefix,-1);}
_closest(str,prefix,shift)
{if(!str)
return"";var index=this._values.indexOf(str);if(index===-1)
return"";if(!prefix){index=(index+this._values.length+shift)%this._values.length;return this._values[index];}
var propertiesWithPrefix=this.startsWith(prefix);var j=propertiesWithPrefix.indexOf(str);j=(j+propertiesWithPrefix.length+shift)%propertiesWithPrefix.length;return propertiesWithPrefix[j];}
isValidPropertyName(name)
{return this._values.includes(name);}};WI.CSSCompletions.cssNameCompletions=null;WI.CSSCompletions.lengthUnits=new Set(["ch","cm","dvh","dvmax","dvmin","dvw","em","ex","in","lvh","lvmax","lvmin","lvw","mm","pc","pt","px","q","rem","svh","svmax","svmin","svw","vh","vmax","vmin","vw",]);WI.CSSGrouping=class CSSGrouping
{constructor(type,text,sourceCodeLocation)
{this._type=type;this._text=text;this._sourceCodeLocation=sourceCodeLocation||null;} 
get type(){return this._type;}
get text(){return this._text;}
get sourceCodeLocation(){return this._sourceCodeLocation;}
get isMedia()
{return this._type===WI.CSSGrouping.Type.MediaRule||this._type===WI.CSSGrouping.Type.MediaImportRule||this._type===WI.CSSGrouping.Type.MediaLinkNode||this._type===WI.CSSGrouping.Type.MediaStyleNode;}
get isSupports()
{return this._type===WI.CSSGrouping.Type.SupportsRule;}
get prefix()
{if(this.isSupports)
return"@supports";return"@media";}};WI.CSSGrouping.Type={MediaRule:"media-rule",MediaImportRule:"media-import-rule",MediaLinkNode:"media-link-node",MediaStyleNode:"media-style-node",SupportsRule:"supports-rule",};WI.CSSKeywordCompletions={};WI.CSSKeywordCompletions.forPartialPropertyName=function(text,{caretPosition,allowEmptyPrefix}={})
{caretPosition??=text.length;allowEmptyPrefix??=false;if(caretPosition!==caretPosition)
return{prefix:text,completions:[]};if(!text.length&&allowEmptyPrefix)
return{prefix:text,completions:WI.CSSCompletions.cssNameCompletions.values};return{prefix:text,completions:WI.CSSCompletions.cssNameCompletions.startsWith(text)};};WI.CSSKeywordCompletions.forPartialPropertyValue=function(text,propertyName,{caretPosition,additionalFunctionValueCompletionsProvider}={})
{caretPosition??=text.length;if(caretPosition<0||caretPosition>text.length)
return{prefix:"",completions:[]};if(!text.length)
return{prefix:"",completions:WI.CSSKeywordCompletions.forProperty(propertyName).values};let tokens=WI.tokenizeCSSValue(text);let indexOfTokenAtCaret=-1;let passedCharacters=0;for(let i=0;i<tokens.length;++i){passedCharacters+=tokens[i].value.length;if(passedCharacters>=caretPosition){indexOfTokenAtCaret=i;break;}}
let tokenAtCaret=tokens[indexOfTokenAtCaret];if(!tokenAtCaret)
return{prefix:"",completions:[]};if(tokenAtCaret.type&&/\b(comment|string)\b/.test(tokenAtCaret.type))
return{prefix:"",completions:[]};let currentTokenValue=tokenAtCaret.value.trim();let caretIsInMiddleOfToken=caretPosition!==passedCharacters;let tokenAfterCaret=tokens[indexOfTokenAtCaret+1];if((caretIsInMiddleOfToken&&currentTokenValue.length)||(!caretIsInMiddleOfToken&&tokenAfterCaret&&/[a-zA-Z0-9-]/.test(tokenAfterCaret.value[0])))
return{prefix:"",completions:[]};if(currentTokenValue==="("||currentTokenValue===",")
currentTokenValue="";let functionName=null;let preceedingFunctionDepth=0;for(let i=indexOfTokenAtCaret;i>=0;--i){let value=tokens[i].value;if(value===")")
++preceedingFunctionDepth;else if(value==="("){if(preceedingFunctionDepth)
--preceedingFunctionDepth;else{functionName=tokens[i-1]?.value;break;}}}
if(functionName){let completions=WI.CSSKeywordCompletions.forFunction(functionName);let contextualValueCompletions=additionalFunctionValueCompletionsProvider?.(functionName)||[];completions.addValues(contextualValueCompletions);return{prefix:currentTokenValue,completions:completions.startsWith(currentTokenValue)};}
return{prefix:currentTokenValue,completions:WI.CSSKeywordCompletions.forProperty(propertyName).startsWith(currentTokenValue)};};WI.CSSKeywordCompletions.forProperty=function(propertyName)
{let acceptedKeywords=["initial","unset","revert","var()","env()"];function addKeywordsForName(name){let isNotPrefixed=name.charAt(0)!=="-";if(name in WI.CSSKeywordCompletions._propertyKeywordMap)
acceptedKeywords.pushAll(WI.CSSKeywordCompletions._propertyKeywordMap[name]);else if(isNotPrefixed&&("-webkit-"+name)in WI.CSSKeywordCompletions._propertyKeywordMap)
acceptedKeywords.pushAll(WI.CSSKeywordCompletions._propertyKeywordMap["-webkit-"+name]);if(WI.CSSKeywordCompletions.isColorAwareProperty(name))
acceptedKeywords.pushAll(WI.CSSKeywordCompletions._colors);if(WI.CSSKeywordCompletions.InheritedProperties.has(name))
acceptedKeywords.push("inherit");else if(isNotPrefixed&&WI.CSSKeywordCompletions.InheritedProperties.has("-webkit-"+name))
acceptedKeywords.push("inherit");}
addKeywordsForName(propertyName);let unaliasedName=WI.CSSKeywordCompletions.PropertyNameForAlias.get(propertyName);if(unaliasedName)
addKeywordsForName(unaliasedName);let longhandNames=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(propertyName);if(longhandNames){for(let longhandName of longhandNames)
addKeywordsForName(longhandName);}
if(acceptedKeywords.includes(WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder)&&WI.CSSCompletions.cssNameCompletions){acceptedKeywords.remove(WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder);acceptedKeywords.pushAll(WI.CSSCompletions.cssNameCompletions.values);}
return new WI.CSSCompletions(Array.from(new Set(acceptedKeywords)),true);};WI.CSSKeywordCompletions.isColorAwareProperty=function(name)
{if(WI.CSSKeywordCompletions._colorAwareProperties.has(name))
return true;let isNotPrefixed=name.charAt(0)!=="-";if(isNotPrefixed&&WI.CSSKeywordCompletions._colorAwareProperties.has("-webkit-"+name))
return true;if(name.endsWith("color"))
return true;return false;};WI.CSSKeywordCompletions.isTimingFunctionAwareProperty=function(name)
{if(WI.CSSKeywordCompletions._timingFunctionAwareProperties.has(name))
return true;let isNotPrefixed=name.charAt(0)!=="-";if(isNotPrefixed&&WI.CSSKeywordCompletions._timingFunctionAwareProperties.has("-webkit-"+name))
return true;return false;};WI.CSSKeywordCompletions.forFunction=function(functionName)
{let suggestions=["var()"];if(functionName==="var")
suggestions=[];else if(functionName==="calc"||functionName==="min"||functionName==="max")
suggestions.push("calc()","min()","max()");else if(functionName==="env")
suggestions.push("safe-area-inset-top","safe-area-inset-right","safe-area-inset-bottom","safe-area-inset-left");else if(functionName==="image-set")
suggestions.push("url()");else if(functionName==="repeat")
suggestions.push("auto","auto-fill","auto-fit","min-content","max-content");else if(functionName==="steps")
suggestions.push("jump-none","jump-start","jump-end","jump-both","start","end");else if(functionName.endsWith("gradient")){suggestions.push("to","left","right","top","bottom");suggestions.pushAll(WI.CSSKeywordCompletions._colors);}
return new WI.CSSCompletions(suggestions,true);};WI.CSSKeywordCompletions.addCustomCompletions=function(properties)
{for(var property of properties){if(property.aliases){for(let alias of property.aliases)
WI.CSSKeywordCompletions.PropertyNameForAlias.set(alias,property.name);}
if(property.values)
WI.CSSKeywordCompletions.addPropertyCompletionValues(property.name,property.values);if(property.inherited)
WI.CSSKeywordCompletions.InheritedProperties.add(property.name);if(property.longhands){WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.set(property.name,property.longhands);for(let longhand of property.longhands){let shorthands=WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty.getOrInitialize(longhand,[]);shorthands.push(property.name);}}}};WI.CSSKeywordCompletions.addPropertyCompletionValues=function(propertyName,newValues)
{var existingValues=WI.CSSKeywordCompletions._propertyKeywordMap[propertyName];if(!existingValues){WI.CSSKeywordCompletions._propertyKeywordMap[propertyName]=newValues;return;}
var union=new Set;for(var value of existingValues)
union.add(value);for(var value of newValues)
union.add(value);WI.CSSKeywordCompletions._propertyKeywordMap[propertyName]=[...union.values()];};WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder="__all-properties__";WI.CSSKeywordCompletions.PropertyNameForAlias=new Map;WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty=new Map;WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty=new Map;WI.CSSKeywordCompletions.InheritedProperties=new Set(["-apple-color-filter","-webkit-animation-trigger","-webkit-aspect-ratio","-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing","-webkit-box-direction","-webkit-cursor-visibility","-webkit-font-kerning","-webkit-font-smoothing","-webkit-hyphenate-character","-webkit-hyphenate-limit-after","-webkit-hyphenate-limit-before","-webkit-hyphenate-limit-lines","-webkit-hyphens","-webkit-line-align","-webkit-line-break","-webkit-line-box-contain","-webkit-line-grid","-webkit-line-snap","-webkit-locale","-webkit-nbsp-mode","-webkit-overflow-scrolling","-webkit-print-color-adjust","-webkit-rtl-ordering","-webkit-ruby-position","-webkit-text-align-last","-webkit-text-combine","-webkit-text-decoration-skip","-webkit-text-decorations-in-effect","-webkit-text-emphasis","-webkit-text-emphasis-color","-webkit-text-emphasis-position","-webkit-text-emphasis-style","-webkit-text-fill-color","-webkit-text-justify","-webkit-text-orientation","-webkit-text-security","-webkit-text-size-adjust","-webkit-text-stroke","-webkit-text-stroke-color","-webkit-text-stroke-width","-webkit-text-underline-position","-webkit-text-zoom","-webkit-touch-callout","-webkit-user-modify","-webkit-user-select","border-collapse","border-spacing","caption-side","caret-color","clip-rule","color","color-interpolation","color-interpolation-filters","color-rendering","cursor","direction","empty-cells","fill","fill-opacity","fill-rule","font","font-family","font-feature-settings","font-optical-sizing","font-size","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","glyph-orientation-horizontal","glyph-orientation-vertical","hanging-punctuation","image-orientation","image-rendering","image-resolution","kerning","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","marker","marker-end","marker-mid","marker-start","orphans","pointer-events","quotes","resize","shape-rendering","speak-as","stroke","stroke-color","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","text-align","text-anchor","text-indent","text-rendering","text-shadow","text-transform","visibility","white-space","widows","word-break","word-spacing","word-wrap","writing-mode",]);WI.CSSKeywordCompletions._colors=["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow","transparent","currentcolor","grey","aliceblue","antiquewhite","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","gainsboro","ghostwhite","gold","goldenrod","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","limegreen","linen","magenta","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","oldlace","olivedrab","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","thistle","tomato","turquoise","violet","wheat","whitesmoke","yellowgreen","rgb()","rgba()","hsl()","hsla()","color()","hwb()","lch()","lab()","color-mix()","color-contrast()",];WI.CSSKeywordCompletions._colorAwareProperties=new Set(["background","background-color","background-image","border","border-color","border-bottom","border-bottom-color","border-left","border-left-color","border-right","border-right-color","border-top","border-top-color","box-shadow","-webkit-box-shadow","color","column-rule","-webkit-column-rule","column-rule-color","-webkit-column-rule-color","fill","outline","outline-color","stroke","text-decoration-color","-webkit-text-decoration-color","text-emphasis","-webkit-text-emphasis","text-emphasis-color","-webkit-text-emphasis-color","text-line-through","text-line-through-color","text-overline","text-overline-color","text-shadow","text-underline","text-underline-color","-webkit-text-fill-color","-webkit-text-stroke","-webkit-text-stroke-color","-webkit-tap-highlight-color",]);WI.CSSKeywordCompletions._timingFunctionAwareProperties=new Set(["animation","-webkit-animation","animation-timing-function","-webkit-animation-timing-function","transition","-webkit-transition","transition-timing-function","-webkit-transition-timing-function",]);WI.CSSKeywordCompletions._propertyKeywordMap={"content":["list-item","close-quote","no-close-quote","no-open-quote","open-quote","attr()","counter()","counters()","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"list-style-image":["none","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"baseline-shift":["baseline","sub","super"],"block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"border-block-end-width":["medium","thick","thin","calc()",],"border-block-start-width":["medium","thick","thin","calc()",],"border-bottom-width":["medium","thick","thin","calc()"],"border-inline-end-width":["medium","thick","thin","calc()",],"border-inline-start-width":["medium","thick","thin","calc()",],"font-stretch":["normal","wider","narrower","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"],"border-left-width":["medium","thick","thin","calc()"],"border-top-width":["medium","thick","thin","calc()"],"outline-color":["invert","-webkit-focus-ring-color"],"cursor":["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","grab","grabbing","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","-webkit-grab","-webkit-grabbing","-webkit-zoom-in","-webkit-zoom-out","url()","image-set()"],"border-width":["medium","thick","thin","calc()"],"size":["a3","a4","a5","b4","b5","landscape","ledger","legal","letter","portrait"],"background":["none","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()","repeat","repeat-x","repeat-y","no-repeat","space","round","scroll","fixed","local","auto","contain","cover","top","right","left","bottom","center","border-box","padding-box","content-box"],"background-image":["none","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"background-size":["auto","contain","cover"],"background-attachment":["scroll","fixed","local"],"background-repeat":["repeat","repeat-x","repeat-y","no-repeat","space","round"],"background-blend-mode":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],"background-position":["top","right","left","bottom","center"],"background-origin":["border-box","padding-box","content-box"],"background-clip":["border-box","padding-box","content-box"],"enable-background":["accumulate","new"],"font-palette":["none","normal","light","dark"],"hanging-punctuation":["none","first","last","allow-end","force-end"],"inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"overflow":["hidden","auto","visible","scroll","marquee","-webkit-paged-x","-webkit-paged-y"],"-webkit-box-reflect":["none","left","right","above","below"],"margin-block":["auto",],"margin-block-end":["auto",],"margin-block-start":["auto",],"margin-bottom":["auto"],"margin-inline":["auto",],"margin-inline-end":["auto",],"margin-inline-start":["auto",],"font-weight":["normal","bold","bolder","lighter","100","200","300","400","500","600","700","800","900"],"font-synthesis":["none","weight","style"],"font-style":["italic","oblique","normal"],"outline":["none","hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"],"font":["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","-apple-system","-apple-system-headline","-apple-system-body","-apple-system-subheadline","-apple-system-footnote","-apple-system-caption1","-apple-system-caption2","-apple-system-short-headline","-apple-system-short-body","-apple-system-short-subheadline","-apple-system-short-footnote","-apple-system-short-caption1","-apple-system-tall-body","-apple-system-title0","-apple-system-title1","-apple-system-title2","-apple-system-title3","-apple-system-title4","system-ui"],"outline-width":["medium","thick","thin","calc()"],"box-shadow":["none"],"text-shadow":["none"],"-webkit-box-shadow":["none"],"border-right-width":["medium","thick","thin"],"line-height":["normal"],"counter-increment":["none"],"counter-reset":["none"],"page-break-after":["left","right","auto","always","avoid"],"page-break-before":["left","right","auto","always","avoid"],"page-break-inside":["auto","avoid"],"-webkit-column-break-after":["left","right","auto","always","avoid"],"-webkit-column-break-before":["left","right","auto","always","avoid"],"-webkit-column-break-inside":["auto","avoid"],"border-image":["repeat","stretch","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"border-image-repeat":["repeat","stretch","space","round"],"-webkit-mask-box-image-repeat":["repeat","stretch","space","round"],"font-family":["serif","sans-serif","cursive","fantasy","monospace","-webkit-body","-webkit-pictograph","-apple-system","-apple-system-headline","-apple-system-body","-apple-system-subheadline","-apple-system-footnote","-apple-system-caption1","-apple-system-caption2","-apple-system-short-headline","-apple-system-short-body","-apple-system-short-subheadline","-apple-system-short-footnote","-apple-system-short-caption1","-apple-system-tall-body","-apple-system-title0","-apple-system-title1","-apple-system-title2","-apple-system-title3","-apple-system-title4","system-ui"],"margin-left":["auto"],"margin-top":["auto"],"zoom":["normal","document","reset"],"z-index":["auto"],"width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"max-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"min-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"max-block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()",],"max-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"max-inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()",],"min-block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"min-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"min-inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"letter-spacing":["normal","calc()"],"word-spacing":["normal","calc()"],"border":["none","hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"],"font-size":["xx-small","x-small","small","medium","large","x-large","xx-large","-webkit-xxx-large","smaller","larger"],"font-variant":["small-caps","normal"],"font-variant-numeric":["normal","ordinal","slashed-zero","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions"],"vertical-align":["baseline","middle","sub","super","text-top","text-bottom","top","bottom","-webkit-baseline-middle"],"text-indent":["-webkit-each-line","-webkit-hanging"],"clip":["auto","rect()"],"clip-path":["none","url()","circle()","ellipse()","inset()","polygon()","margin-box","border-box","padding-box","content-box"],"shape-outside":["none","url()","circle()","ellipse()","inset()","polygon()","margin-box","border-box","padding-box","content-box"],"orphans":["auto"],"widows":["auto"],"margin":["auto"],"page":["auto"],"perspective":["none"],"perspective-origin":["none","left","right","bottom","top","center"],"margin-right":["auto"],"-webkit-text-emphasis":["circle","filled","open","dot","double-circle","triangle","sesame"],"-webkit-text-emphasis-style":["circle","filled","open","dot","double-circle","triangle","sesame"],"-webkit-text-emphasis-position":["over","under","left","right"],"transform":["none","scale()","scaleX()","scaleY()","scale3d()","rotate()","rotateX()","rotateY()","rotateZ()","rotate3d()","skew()","skewX()","skewY()","translate()","translateX()","translateY()","translateZ()","translate3d()","matrix()","matrix3d()","perspective()"],"text-decoration":["none","underline","overline","line-through","blink"],"-webkit-text-decorations-in-effect":["none","underline","overline","line-through","blink"],"-webkit-text-decoration-line":["none","underline","overline","line-through","blink"],"-webkit-text-decoration-skip":["auto","none","objects","ink"],"-webkit-text-underline-position":["auto","alphabetic","under"],"transition":["none","ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","spring()","all",WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder],"transition-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","spring()"],"transition-property":["all","none",WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder],"animation-direction":["normal","alternate","reverse","alternate-reverse"],"animation-fill-mode":["none","forwards","backwards","both"],"animation-iteration-count":["infinite"],"animation-play-state":["paused","running"],"animation-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","spring()"],"align-content":["auto","baseline","last-baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right","true","safe"],"justify-content":["auto","baseline","last-baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right","true","safe"],"align-items":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"align-self":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"justify-items":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"justify-self":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"flex-flow":["row","row-reverse","column","column-reverse","nowrap","wrap","wrap-reverse"],"flex":["none"],"flex-basis":["auto"],"grid":["none"],"grid-area":["auto"],"grid-auto-columns":["auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()",],"grid-auto-flow":["row","column","dense"],"grid-auto-rows":["auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()",],"grid-column":["auto"],"grid-column-start":["auto"],"grid-column-end":["auto"],"grid-row":["auto"],"grid-row-start":["auto"],"grid-row-end":["auto"],"grid-template":["none"],"grid-template-areas":["none"],"grid-template-columns":["none","auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()","repeat()"],"grid-template-rows":["none","auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()","repeat()"],"scroll-snap-align":["none","start","center","end"],"scroll-snap-type":["none","mandatory","proximity","x","y","inline","block","both"],"-webkit-background-composite":["clear","copy","source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","xor","plus-darker","plus-lighter"],"-webkit-mask-composite":["clear","copy","source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","xor","plus-darker","plus-lighter"],"-webkit-text-stroke-width":["medium","thick","thin","calc()"],"-webkit-aspect-ratio":["auto","from-dimensions","from-intrinsic","/"],"filter":["none","grayscale()","sepia()","saturate()","hue-rotate()","invert()","opacity()","brightness()","contrast()","blur()","drop-shadow()","custom()"],"-webkit-backdrop-filter":["none","grayscale()","sepia()","saturate()","hue-rotate()","invert()","opacity()","brightness()","contrast()","blur()","drop-shadow()","custom()"],"-webkit-hyphenate-character":["none"],"-webkit-hyphenate-limit-after":["auto"],"-webkit-hyphenate-limit-before":["auto"],"-webkit-hyphenate-limit-lines":["no-limit"],"-webkit-line-grid":["none"],"-webkit-locale":["auto"],"-webkit-line-box-contain":["block","inline","font","glyphs","replaced","inline-box","none"],"font-feature-settings":["normal"],"-webkit-animation-trigger":["auto","container-scroll()"],"-webkit-text-size-adjust":["none","auto"],"-apple-pay-button-style":["black","white","white-outline",],"-apple-pay-button-type":["plain","buy","set-up","donate","check-out","book","subscribe",],"-webkit-alt":["attr()",],"-webkit-animation-direction":["normal","alternate","reverse","alternate-reverse",],"-webkit-animation-fill-mode":["none","forwards","backwards","both",],"-webkit-animation-iteration-count":["infinite",],"-webkit-animation-play-state":["paused","running",],"-webkit-animation-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","spring()",],"-webkit-appearance":["none","checkbox","radio","push-button","square-button","button","button-bevel","default-button","inner-spin-button","listbox","listitem","media-controls-background","media-controls-dark-bar-background","media-controls-fullscreen-background","media-controls-light-bar-background","media-current-time-display","media-enter-fullscreen-button","media-exit-fullscreen-button","media-fullscreen-volume-slider","media-fullscreen-volume-slider-thumb","media-mute-button","media-overlay-play-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-toggle-closed-captions-button","media-volume-slider","media-volume-slider-container","media-volume-slider-mute-button","media-volume-sliderthumb","menulist","menulist-button","menulist-text","menulist-textfield","meter","progress-bar","progress-bar-value","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","caret","searchfield","searchfield-decoration","searchfield-results-decoration","searchfield-results-button","searchfield-cancel-button","snapshotted-plugin-overlay","textfield","relevancy-level-indicator","continuous-capacity-level-indicator","discrete-capacity-level-indicator","rating-level-indicator","-apple-pay-button","textarea","attachment","borderless-attachment","caps-lock-indicator",],"-webkit-backface-visibility":["hidden","visible",],"-webkit-border-after-width":["medium","thick","thin","calc()",],"-webkit-border-before-width":["medium","thick","thin","calc()",],"-webkit-border-end-width":["medium","thick","thin","calc()",],"-webkit-border-fit":["border","lines",],"-webkit-border-start-width":["medium","thick","thin","calc()",],"-webkit-box-align":["baseline","center","stretch","start","end",],"-webkit-box-decoration-break":["clone","slice",],"-webkit-box-direction":["normal","reverse",],"-webkit-box-lines":["single","multiple",],"-webkit-box-orient":["horizontal","vertical","inline-axis","block-axis",],"-webkit-box-pack":["center","justify","start","end",],"-webkit-column-axis":["auto","horizontal","vertical",],"-webkit-column-count":["auto","calc()",],"-webkit-column-fill":["auto","balance",],"-webkit-column-gap":["normal","calc()",],"-webkit-column-progression":["normal","reverse",],"-webkit-column-rule-width":["medium","thick","thin","calc()",],"-webkit-column-span":["all","none","calc()",],"-webkit-column-width":["auto","calc()",],"-webkit-cursor-visibility":["auto","auto-hide",],"-webkit-font-kerning":["none","normal","auto",],"-webkit-font-smoothing":["none","auto","antialiased","subpixel-antialiased",],"-webkit-hyphens":["none","auto","manual",],"-webkit-line-align":["none","edges",],"-webkit-line-break":["auto","loose","normal","strict","after-white-space",],"-webkit-line-snap":["none","baseline","contain",],"-webkit-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-margin-after-collapse":["collapse","separate","discard",],"-webkit-margin-before-collapse":["collapse","separate","discard",],"-webkit-margin-bottom-collapse":["collapse","separate","discard",],"-webkit-margin-top-collapse":["collapse","separate","discard",],"-webkit-max-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"-webkit-max-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"-webkit-min-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-min-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-nbsp-mode":["normal","space",],"-webkit-overflow-scrolling":["auto","touch",],"-webkit-print-color-adjust":["economy","exact",],"-webkit-rtl-ordering":["logical","visual",],"-webkit-ruby-position":["after","before","inter-character",],"-webkit-text-align-last":["auto","start","end","left","right","center","justify",],"-webkit-text-combine":["none","horizontal",],"-webkit-text-decoration-style":["dotted","dashed","solid","double","wavy",],"-webkit-text-justify":["auto","none","inter-word","inter-ideograph","inter-cluster","distribute","kashida",],"-webkit-text-orientation":["sideways","sideways-right","upright","mixed",],"-webkit-text-security":["none","disc","circle","square",],"-webkit-text-zoom":["normal","reset",],"-webkit-transform-style":["flat","preserve-3d",],"-webkit-user-drag":["none","auto","element",],"-webkit-user-modify":["read-only","read-write","read-write-plaintext-only",],"-webkit-user-select":["none","all","auto","text",],"-webkit-writing-mode":["lr","rl","tb","lr-tb","rl-tb","tb-rl","horizontal-tb","vertical-rl","vertical-lr","horizontal-bt",],"alignment-baseline":["baseline","middle","auto","alphabetic","before-edge","after-edge","central","text-before-edge","text-after-edge","ideographic","hanging","mathematical",],"border-block-end-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-block-start-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-bottom-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-collapse":["collapse","separate",],"border-inline-end-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-inline-start-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-left-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-right-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-top-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"box-sizing":["border-box","content-box",],"break-after":["left","right","auto","avoid","column","avoid-column","avoid-page","page","recto","verso",],"break-before":["left","right","auto","avoid","column","avoid-column","avoid-page","page","recto","verso",],"break-inside":["auto","avoid","avoid-column","avoid-page",],"buffered-rendering":["auto","static","dynamic",],"caption-side":["top","bottom","left","right",],"clear":["none","left","right","both",],"clip-rule":["nonzero","evenodd",],"color-interpolation":["auto","sRGB","linearRGB",],"color-interpolation-filters":["auto","sRGB","linearRGB",],"color-rendering":["auto","optimizeSpeed","optimizeQuality",],"column-fill":["auto","balance",],"column-rule-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"direction":["ltr","rtl",],"display":["none","inline","block","list-item","compact","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","-webkit-flex","inline-flex","-webkit-inline-flex","contents","grid","inline-grid",],"dominant-baseline":["middle","auto","alphabetic","central","text-before-edge","text-after-edge","ideographic","hanging","mathematical","use-script","no-change","reset-size",],"empty-cells":["hide","show",],"fill-rule":["nonzero","evenodd",],"flex-direction":["row","row-reverse","column","column-reverse",],"flex-wrap":["nowrap","wrap-reverse","wrap",],"float":["none","left","right",],"font-optical-sizing":["none","auto",],"font-variant-alternates":["historical-forms","normal",],"font-variant-caps":["small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","normal",],"font-variant-position":["normal","sub","super",],"image-rendering":["auto","optimizeSpeed","optimizeQuality","crisp-edges","pixelated","-webkit-crisp-edges","-webkit-optimize-contrast",],"image-resolution":["from-image","snap",],"isolation":["auto","isolate",],"line-break":["normal","auto","loose","strict","after-white-space",],"list-style-position":["outside","inside",],"list-style-type":["none","disc","circle","square","decimal","decimal-leading-zero","arabic-indic","binary","bengali","cambodian","khmer","devanagari","gujarati","gurmukhi","kannada","lower-hexadecimal","lao","malayalam","mongolian","myanmar","octal","oriya","persian","urdu","telugu","tibetan","thai","upper-hexadecimal","lower-roman","upper-roman","lower-greek","lower-alpha","lower-latin","upper-alpha","upper-latin","afar","ethiopic-halehame-aa-et","ethiopic-halehame-aa-er","amharic","ethiopic-halehame-am-et","amharic-abegede","ethiopic-abegede-am-et","cjk-earthly-branch","cjk-heavenly-stem","ethiopic","ethiopic-halehame-gez","ethiopic-abegede","ethiopic-abegede-gez","hangul-consonant","hangul","lower-norwegian","oromo","ethiopic-halehame-om-et","sidama","ethiopic-halehame-sid-et","somali","ethiopic-halehame-so-et","tigre","ethiopic-halehame-tig","tigrinya-er","ethiopic-halehame-ti-er","tigrinya-er-abegede","ethiopic-abegede-ti-er","tigrinya-et","ethiopic-halehame-ti-et","tigrinya-et-abegede","ethiopic-abegede-ti-et","upper-greek","upper-norwegian","asterisks","footnotes","hebrew","armenian","lower-armenian","upper-armenian","georgian","cjk-ideographic","hiragana","katakana","hiragana-iroha","katakana-iroha",],"mask-type":["alpha","luminance",],"max-zoom":["auto",],"min-zoom":["auto",],"mix-blend-mode":["normal","plus-darker","plus-lighter","overlay","multiply","screen","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity",],"object-fit":["none","contain","cover","fill","scale-down",],"orientation":["auto","portait","landscape",],"outline-style":["none","inset","groove","outset","ridge","dotted","dashed","solid","double","auto",],"overflow-wrap":["normal","break-word",],"overflow-x":["hidden","auto","visible","scroll",],"overflow-y":["hidden","auto","visible","scroll","-webkit-paged-x","-webkit-paged-y",],"pointer-events":["none","all","auto","visible","visiblePainted","visibleFill","visibleStroke","painted","fill","stroke",],"position":["absolute","fixed","relative","static","sticky","-webkit-sticky",],"resize":["none","auto","both","horizontal","vertical",],"shape-rendering":["auto","optimizeSpeed","geometricPrecision","crispedges",],"stroke-linecap":["square","round","butt",],"stroke-linejoin":["round","miter","bevel",],"table-layout":["auto","fixed",],"text-align":["-webkit-auto","left","right","center","justify","-webkit-left","-webkit-right","-webkit-center","-webkit-match-parent","start","end",],"text-anchor":["middle","start","end",],"text-line-through":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave","continuous","skip-white-space",],"text-line-through-mode":["continuous","skip-white-space",],"text-line-through-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-line-through-width":["normal","medium","auto","thick","thin",],"text-overflow":["clip","ellipsis",],"text-overline-mode":["continuous","skip-white-space",],"text-overline-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-overline-width":["normal","medium","auto","thick","thin","calc()",],"text-rendering":["auto","optimizeSpeed","optimizeLegibility","geometricPrecision",],"text-transform":["none","capitalize","uppercase","lowercase",],"text-underline":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-underline-mode":["continuous","skip-white-space",],"text-underline-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-underline-width":["normal","medium","auto","thick","thin","calc()",],"transform-style":["flat","preserve-3d",],"unicode-bidi":["normal","bidi-override","embed","isolate-override","plaintext","-webkit-isolate","-webkit-isolate-override","-webkit-plaintext","isolate",],"user-zoom":["zoom","fixed",],"vector-effect":["none",],"visibility":["hidden","visible","collapse",],"white-space":["normal","nowrap","pre","pre-line","pre-wrap",],"word-break":["normal","break-all","keep-all","break-word",],"word-wrap":["normal","break-word",],"writing-mode":["lr","rl","tb","lr-tb","rl-tb","tb-rl","horizontal-tb","vertical-rl","vertical-lr","horizontal-bt",],};WI.CSSProperty=class CSSProperty extends WI.Object
{constructor(index,text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange)
{super();this._ownerStyle=null;this._index=index;this._overridingProperty=null;this._initialState=null;this._modified=false;this._isUpdatingText=false;this.update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange,true);} 
static isInheritedPropertyName(name)
{if(WI.CSSKeywordCompletions.InheritedProperties.has(name))
return true;return name.startsWith("--");}
static findVariableNames(string)
{const prefix="var(--";let prefixCursor=0;let cursor=0;let nameStartIndex=0;let names=[];function isTerminatingChar(char){return char===")"||char===","||char===" "||char==="\n"||char==="\t";}
while(cursor<string.length){if(nameStartIndex&&isTerminatingChar(string.charAt(cursor))){names.push("--"+string.substring(nameStartIndex,cursor));nameStartIndex=0;}
if(prefixCursor===prefix.length){prefixCursor=0;nameStartIndex=cursor;}
if(string.charAt(cursor)===prefix.charAt(prefixCursor))
prefixCursor++;cursor++;}
return names;} 
get ownerStyle()
{return this._ownerStyle;}
set ownerStyle(ownerStyle)
{this._ownerStyle=ownerStyle||null;}
get index()
{return this._index;}
set index(index)
{this._index=index;}
update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange,dontFireEvents)
{if(this._ownerStyle&&this._ownerStyle.locked&&text!==this._text)
return;text=text||"";name=name||"";value=value||"";priority=priority||"";enabled=enabled||false;overridden=overridden||false;implicit=implicit||false;anonymous=anonymous||false;valid=valid||false;var changed=false;if(!dontFireEvents){changed=this._name!==name||this._rawValue!==value||this._priority!==priority||this._enabled!==enabled||this._implicit!==implicit||this._anonymous!==anonymous||this._valid!==valid;}

if(!dontFireEvents)
this.overridden=overridden;else
this._overridden=overridden;if(!overridden)
this._overridingProperty=null;this._text=text;this._name=name;this._rawValue=value;this._value=undefined;this._priority=priority;this._enabled=enabled;this._implicit=implicit;this._anonymous=anonymous;this._inherited=WI.CSSProperty.isInheritedPropertyName(name);this._valid=valid;this._isVariable=name.startsWith("--");this._styleSheetTextRange=styleSheetTextRange||null;this._rawValueNewlineIndent="";if(this._rawValue){let match=this._rawValue.match(/^[^\n]+\n(\s*)/);if(match)
this._rawValueNewlineIndent=match[1];}
this._rawValue=this._rawValue.replace(/\n\s+/g,"\n");this._isShorthand=undefined;this._shorthandPropertyNames=undefined;this._relatedShorthandProperty=null;this._relatedLonghandProperties=[];delete this._styleDeclarationTextRange;delete this._canonicalName;delete this._hasOtherVendorNameOrKeyword;if(changed)
this.dispatchEventToListeners(WI.CSSProperty.Event.Changed);}
remove()
{this._markModified();this._name="";const forceRemove=true;this._updateStyleText(forceRemove);}
commentOut(disabled)
{if(this._enabled===!disabled)
return;this._markModified();this._enabled=!disabled;if(disabled)
this.text="/* "+this._text+" */";else
this.text=this._text.slice(2,-2).trim();}
get text()
{return this._text;}
set text(newText)
{newText=newText.trim();if(this._text===newText)
return;this._markModified();this._text=newText;this._isUpdatingText=true;this._updateOwnerStyleText();this._isUpdatingText=false;}
get formattedText()
{if(this._isUpdatingText)
return this._text;if(!this._name)
return"";let text=`${this._name}: ${this._rawValue};`;if(!this._enabled)
text="/* "+text+" */";return text;}
get modified()
{return this._modified;}
set modified(value)
{if(this._modified===value)
return;this._modified=value;this.dispatchEventToListeners(WI.CSSProperty.Event.ModifiedChanged);}
get name()
{return this._name;}
set name(name)
{if(name===this._name)
return;this._markModified();this._name=name;this._updateStyleText();}
get canonicalName()
{if(this._canonicalName)
return this._canonicalName;this._canonicalName=WI.cssManager.canonicalNameForPropertyName(this.name);return this._canonicalName;}
get value()
{if(!this._value)
this._value=this._rawValue.replace(/\s*!important\s*$/,"");return this._value;}
get rawValue()
{return this._rawValue;}
set rawValue(value)
{if(value===this._rawValue)
return;this._markModified();let suffix=WI.CSSCompletions.completeUnbalancedValue(value);if(suffix)
value+=suffix;this._rawValue=value;this._value=undefined;this._updateStyleText();}
get important()
{return this.priority==="important";}
get priority(){return this._priority;}
get attached()
{return this._enabled&&this._ownerStyle&&(!isNaN(this._index)||this._ownerStyle.type===WI.CSSStyleDeclaration.Type.Computed);}
get enabled(){return this._enabled;}
get overridden(){return this._overridden;}
set overridden(overridden)
{overridden=overridden||false;if(this._overridden===overridden)
return;if(!overridden)
this._overridingProperty=null;var previousOverridden=this._overridden;this._overridden=overridden;if(this._overriddenStatusChangedTimeout)
return;function delayed()
{delete this._overriddenStatusChangedTimeout;if(this._overridden===previousOverridden)
return;this.dispatchEventToListeners(WI.CSSProperty.Event.OverriddenStatusChanged);}
this._overriddenStatusChangedTimeout=setTimeout(delayed.bind(this),0);}
get overridingProperty()
{return this._overridingProperty;}
set overridingProperty(effectiveProperty)
{if(!WI.settings.experimentalEnableStylesJumpToEffective.value)
return;this._overridingProperty=effectiveProperty||null;}
get implicit(){return this._implicit;}
set implicit(implicit){this._implicit=implicit;}
get anonymous(){return this._anonymous;}
get inherited(){return this._inherited;}
get valid(){return this._valid;}
get isVariable(){return this._isVariable;}
get styleSheetTextRange(){return this._styleSheetTextRange;}
get initialState()
{return this._initialState;}
get editable()
{return!!(this._styleSheetTextRange&&this._ownerStyle&&this._ownerStyle.styleSheetTextRange);}
get styleDeclarationTextRange()
{if("_styleDeclarationTextRange"in this)
return this._styleDeclarationTextRange;if(!this._ownerStyle||!this._styleSheetTextRange)
return null;var styleTextRange=this._ownerStyle.styleSheetTextRange;if(!styleTextRange)
return null;var startLine=this._styleSheetTextRange.startLine-styleTextRange.startLine;var endLine=this._styleSheetTextRange.endLine-styleTextRange.startLine;var startColumn=this._styleSheetTextRange.startColumn;if(!startLine)
startColumn-=styleTextRange.startColumn;var endColumn=this._styleSheetTextRange.endColumn;if(!endLine)
endColumn-=styleTextRange.startColumn;this._styleDeclarationTextRange=new WI.TextRange(startLine,startColumn,endLine,endColumn);return this._styleDeclarationTextRange;}
get relatedShorthandProperty(){return this._relatedShorthandProperty;}
set relatedShorthandProperty(property)
{this._relatedShorthandProperty=property||null;}
get relatedLonghandProperties(){return this._relatedLonghandProperties;}
addRelatedLonghandProperty(property)
{this._relatedLonghandProperties.push(property);}
clearRelatedLonghandProperties(property)
{this._relatedLonghandProperties=[];}
get isShorthand()
{if(this._isShorthand===undefined){this._isShorthand=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.has(this._name);if(this._isShorthand){let longhands=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(this._name);if(longhands&&longhands.length===1)
this._isShorthand=false;}}
return this._isShorthand;}
get shorthandPropertyNames()
{if(!this._shorthandPropertyNames){this._shorthandPropertyNames=WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty.get(this._name)||[];this._shorthandPropertyNames.remove("all");}
return this._shorthandPropertyNames;}
hasOtherVendorNameOrKeyword()
{if("_hasOtherVendorNameOrKeyword"in this)
return this._hasOtherVendorNameOrKeyword;this._hasOtherVendorNameOrKeyword=WI.cssManager.propertyNameHasOtherVendorPrefix(this.name)||WI.cssManager.propertyValueHasOtherVendorKeyword(this.value);return this._hasOtherVendorNameOrKeyword;}
equals(property)
{if(property===this)
return true;if(!property)
return false;return this._name===property.name&&this._rawValue===property.rawValue&&this._enabled===property.enabled;}
clone()
{let cssProperty=new WI.CSSProperty(this._index,this._text,this._name,this._rawValue,this._priority,this._enabled,this._overridden,this._implicit,this._anonymous,this._valid,this._styleSheetTextRange);cssProperty.ownerStyle=this._ownerStyle;return cssProperty;} 
_updateStyleText(forceRemove=false)
{let text="";if(this._name&&this._rawValue){let value=this._rawValue.replace(/\n/g,"\n"+this._rawValueNewlineIndent);text=this._name+": "+value+";";}
this._text=text;if(forceRemove)
this._ownerStyle.removeProperty(this);this._updateOwnerStyleText();}
_updateOwnerStyleText()
{if(!this._ownerStyle)
return;this._ownerStyle.text=this._ownerStyle.generateFormattedText({multiline:this._ownerStyle.type===WI.CSSStyleDeclaration.Type.Rule});this._ownerStyle.updatePropertiesModifiedState();}
_markModified()
{if(this._ownerStyle)
this._ownerStyle.markModified();}};WI.CSSProperty.Event={Changed:"css-property-changed",ModifiedChanged:"css-property-modified-changed",OverriddenStatusChanged:"css-property-overridden-status-changed"};WI.CSSRule=class CSSRule extends WI.Object
{constructor(nodeStyles,ownerStyleSheet,id,type,sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings)
{super();this._nodeStyles=nodeStyles;this._ownerStyleSheet=ownerStyleSheet||null;this._id=id||null;this._type=type||null;this._initialState=null;this.update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings,true);} 
get ownerStyleSheet(){return this._ownerStyleSheet;}
get id(){return this._id;}
get type(){return this._type;}
get initialState(){return this._initialState;}
get sourceCodeLocation(){return this._sourceCodeLocation;}
get selectors(){return this._selectors;}
get matchedSelectorIndices(){return this._matchedSelectorIndices;}
get style(){return this._style;}
get groupings(){return this._groupings;}
get editable()
{return!!this._id&&this._type!==WI.CSSStyleSheet.Type.UserAgent;}
get selectorText()
{return this._selectorText;}
setSelectorText(selectorText)
{if(!this.editable)
return Promise.reject();return this._nodeStyles.changeRuleSelector(this,selectorText).then(this._selectorResolved.bind(this));}
update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings)
{sourceCodeLocation=sourceCodeLocation||null;selectorText=selectorText||"";selectors=selectors||[];matchedSelectorIndices=matchedSelectorIndices||[];style=style||null;groupings=groupings||[];if(this._style)
this._style.ownerRule=null;this._sourceCodeLocation=sourceCodeLocation;this._selectorText=selectorText;this._selectors=selectors;this._matchedSelectorIndices=matchedSelectorIndices;this._style=style;this._groupings=groupings;if(this._style)
this._style.ownerRule=this;}
isEqualTo(rule)
{if(!rule)
return false;return Object.shallowEqual(this._id,rule.id);} 
get nodeStyles()
{return this._nodeStyles;}

_selectorResolved(rulePayload)
{if(!rulePayload)
return;let selectorText=rulePayload.selectorList.text;if(selectorText===this._selectorText)
return;let selectors=WI.DOMNodeStyles.parseSelectorListPayload(rulePayload.selectorList);let sourceCodeLocation=null;let sourceRange=rulePayload.selectorList.range;if(sourceRange){sourceCodeLocation=WI.DOMNodeStyles.createSourceCodeLocation(rulePayload.sourceURL,{line:sourceRange.startLine,column:sourceRange.startColumn,documentNode:this._nodeStyles.node.ownerDocument,});}
if(this._ownerStyleSheet){if(!sourceCodeLocation&&sourceRange)
sourceCodeLocation=this._ownerStyleSheet.createSourceCodeLocation(sourceRange.startLine,sourceRange.startColumn);sourceCodeLocation=this._ownerStyleSheet.offsetSourceCodeLocation(sourceCodeLocation);}
this.update(sourceCodeLocation,selectorText,selectors,[],this._style,this._groupings);}};WI.CSSSelector=class CSSSelector
{constructor(text,specificity,dynamic)
{this._text=text;this._specificity=specificity||null;this._dynamic=dynamic||false;} 
get text(){return this._text;}
get specificity(){return this._specificity;}
get dynamic(){return this._dynamic;}
isPseudoSelector()
{return Object.values(WI.CSSManager.PseudoSelectorNames).some((pseudoId)=>(new RegExp("(?:\\b|^):{1,2}(?:-webkit-)?"+pseudoId+"(?:\\b|$)")).test(this._text));}};WI.CSSStyleDeclaration=class CSSStyleDeclaration extends WI.Object
{constructor(nodeStyles,ownerStyleSheet,id,type,node,inherited,text,properties,styleSheetTextRange)
{super();this._nodeStyles=nodeStyles;this._ownerRule=null;this._ownerStyleSheet=ownerStyleSheet||null;this._id=id||null;this._type=type||null;this._node=node||null;this._inherited=inherited||false;this._initialState=null;this._updatesInProgressCount=0;this._pendingPropertiesChanged=false;this._locked=false;this._pendingProperties=[];this._propertyNameMap={};this._properties=[];this._enabledProperties=null;this._visibleProperties=null;this.update(text,properties,styleSheetTextRange,{dontFireEvents:true});} 
get initialState(){return this._initialState;}
get id()
{return this._id;}
get stringId()
{if(this._id)
return this._id.styleSheetId+"/"+this._id.ordinal;else
return"";}
get ownerStyleSheet()
{return this._ownerStyleSheet;}
get type()
{return this._type;}
get inherited()
{return this._inherited;}
get node()
{return this._node;}
get editable()
{if(!this._id)
return false;if(this._type===WI.CSSStyleDeclaration.Type.Rule)
return this._ownerRule&&this._ownerRule.editable;if(this._type===WI.CSSStyleDeclaration.Type.Inline)
return!this._node.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees();return false;}
get selectorEditable()
{return this._ownerRule&&this._ownerRule.editable&&InspectorBackend.hasCommand("CSS.setRuleSelector");}
get locked(){return this._locked;}
set locked(value){this._locked=value;}
update(text,properties,styleSheetTextRange,options={})
{let dontFireEvents=options.dontFireEvents||false;


 if(this._updatesInProgressCount>0&&!options.forceUpdate){if(WI.settings.debugEnableStyleEditingDebugMode.value&&text!==this._text)
console.warn("Style modified while editing:",text);return;}
if(this._locked&&!options.forceUpdate&&text!==this._text)
return;text=text||"";properties=properties||[];let oldProperties=this._properties||[];let oldText=this._text;this._text=text;this._properties=properties;this._styleSheetTextRange=styleSheetTextRange;this._propertyNameMap={};this._enabledProperties=null;this._visibleProperties=null;let editable=this.editable;for(let property of this._properties){property.ownerStyle=this;


if(!editable)
this._propertyNameMap[property.name]=property;else{this._pendingProperties.remove(property);}}
for(let oldProperty of oldProperties){if(this.enabledProperties.includes(oldProperty))
continue;oldProperty.index=NaN;
if(editable)
this._pendingProperties.push(oldProperty);}
if(dontFireEvents)
return;
if(oldText===this._text&&!this._pendingPropertiesChanged&&this._type!==WI.CSSStyleDeclaration.Type.Computed)
return;this._pendingPropertiesChanged=false;function delayed()
{this.dispatchEventToListeners(WI.CSSStyleDeclaration.Event.PropertiesChanged);}
setTimeout(delayed.bind(this),0);}
get ownerRule()
{return this._ownerRule;}
set ownerRule(rule)
{this._ownerRule=rule||null;}
get text()
{return this._text;}
set text(text)
{if(this._text===text)
return;let trimmedText=text.trim();if(this._text===trimmedText)
return;if(!trimmedText.length||this._type===WI.CSSStyleDeclaration.Type.Inline)
text=trimmedText;this._text=text;++this._updatesInProgressCount;let timeoutId=setTimeout(()=>{console.error("Timed out when setting style text:",text);styleTextDidChange();},2000);let styleTextDidChange=()=>{if(!timeoutId)
return;clearTimeout(timeoutId);timeoutId=null;this._updatesInProgressCount=Math.max(0,this._updatesInProgressCount-1);this._pendingPropertiesChanged=true;};this._nodeStyles.changeStyleText(this,text,styleTextDidChange);}
get enabledProperties()
{if(!this._enabledProperties)
this._enabledProperties=this._properties.filter((property)=>property.enabled);return this._enabledProperties;}
get properties()
{return this._properties;}
set properties(properties)
{if(properties===this._properties)
return;this._properties=properties;this._enabledProperties=null;this._visibleProperties=null;}
get visibleProperties()
{if(!this._visibleProperties)
this._visibleProperties=this._properties.filter((property)=>!!property.styleDeclarationTextRange);return this._visibleProperties;}
get pendingProperties()
{return this._pendingProperties;}
get styleSheetTextRange()
{return this._styleSheetTextRange;}
get groupings()
{if(this._ownerRule)
return this._ownerRule.groupings;return[];}
get selectorText()
{if(this._ownerRule)
return this._ownerRule.selectorText;return this._node.appropriateSelectorFor(true);}
propertyForName(name,dontCreateIfMissing)
{if(!name)
return null;if(!this.editable)
return this._propertyNameMap[name]||null;
function findMatch(properties)
{for(var i=0;i<properties.length;++i){var property=properties[i];if(property.canonicalName!==name&&property.name!==name)
continue;if(bestMatchProperty&&!bestMatchProperty.overridden&&property.overridden)
continue;bestMatchProperty=property;}}
var bestMatchProperty=null;findMatch(this.enabledProperties);if(bestMatchProperty)
return bestMatchProperty;if(dontCreateIfMissing||!this.editable)
return null;findMatch(this._pendingProperties,true);if(bestMatchProperty)
return bestMatchProperty;var newProperty=new WI.CSSProperty(NaN,null,name);newProperty.ownerStyle=this;this._pendingProperties.push(newProperty);return newProperty;}
resolveVariableValue(text)
{const invalid=Symbol("invalid");let checkTokens=(tokens)=>{let startIndex=NaN;let openParenthesis=0;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(token.value==="var"&&token.type&&token.type.includes("atom")){if(isNaN(startIndex)){startIndex=i;openParenthesis=0;}
continue;}
if(isNaN(startIndex))
continue;if(token.value==="("){++openParenthesis;continue;}
if(token.value===")"){--openParenthesis;if(openParenthesis>0)
continue;let variableTokens=tokens.slice(startIndex,i+1);startIndex=NaN;let variableNameIndex=variableTokens.findIndex((token)=>token.value.startsWith("--")&&/\bvariable-2\b/.test(token.type));if(variableNameIndex===-1)
continue;let variableProperty=this.propertyForName(variableTokens[variableNameIndex].value,true);if(variableProperty)
return variableProperty.value.trim();let fallbackStartIndex=variableTokens.findIndex((value,j)=>j>variableNameIndex+1&&/\bm-css\b/.test(value.type));if(fallbackStartIndex===-1)
return invalid;let fallbackTokens=variableTokens.slice(fallbackStartIndex,i);return checkTokens(fallbackTokens)||fallbackTokens.reduce((accumulator,token)=>accumulator+token.value,"").trim();}}
return null;};let resolved=checkTokens(WI.tokenizeCSSValue(text));return resolved===invalid?null:resolved;}
newBlankProperty(propertyIndex)
{let text,name,value,priority,overridden,implicit,anonymous;let enabled=true;let valid=false;let styleSheetTextRange=this._rangeAfterPropertyAtIndex(propertyIndex-1);this.markModified();let property=new WI.CSSProperty(propertyIndex,text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);this._properties.insertAtIndex(property,propertyIndex);for(let index=propertyIndex+1;index<this._properties.length;index++)
this._properties[index].index=index;this.update(this._text,this._properties,this._styleSheetTextRange,{dontFireEvents:true,forceUpdate:true});return property;}
markModified()
{if(!this._initialState){let visibleProperties=this.visibleProperties.map((property)=>{return property.clone();});this._initialState=new WI.CSSStyleDeclaration(this._nodeStyles,this._ownerStyleSheet,this._id,this._type,this._node,this._inherited,this._text,visibleProperties,this._styleSheetTextRange);}
WI.cssManager.addModifiedStyle(this);}
removeProperty(cssProperty)
{let realIndex=this._properties.indexOf(cssProperty);if(realIndex===-1)
return;this._properties.splice(realIndex,1);this._enabledProperties=null;this._visibleProperties=null;}
updatePropertiesModifiedState()
{if(!this._initialState)
return;if(this._type===WI.CSSStyleDeclaration.Type.Computed)
return;let initialCSSProperties=this._initialState.visibleProperties;let cssProperties=this.visibleProperties;let hasModified=false;function onEach(cssProperty,action){if(action!==0)
hasModified=true;cssProperty.modified=action===1;}
function comparator(a,b){return a.equals(b);}
Array.diffArrays(initialCSSProperties,cssProperties,onEach,comparator);if(!hasModified)
WI.cssManager.removeModifiedStyle(this);}
generateFormattedText(options={})
{let indentString=WI.indentString();let styleText="";let groupings=this.groupings.filter((grouping)=>grouping.text!=="all");let groupingsCount=groupings.length;if(options.includeGroupingsAndSelectors){for(let i=groupingsCount-1;i>=0;--i){if(options.multiline)
styleText+=indentString.repeat(groupingsCount-i-1);styleText+=groupings[i].prefix+" "+groupings[i].text+" {";if(options.multiline)
styleText+="\n";}
if(options.multiline)
styleText+=indentString.repeat(groupingsCount);styleText+=this.selectorText+" {";}
let properties=this._styleSheetTextRange?this.visibleProperties:this._properties;if(properties.length){if(options.multiline){let propertyIndent=indentString.repeat(groupingsCount+1);for(let property of properties)
styleText+="\n"+propertyIndent+property.formattedText;styleText+="\n";if(!options.includeGroupingsAndSelectors){styleText+=indentString.repeat(groupingsCount);}}else
styleText+=properties.map((property)=>property.formattedText).join(" ");}
if(options.includeGroupingsAndSelectors){for(let i=groupingsCount;i>0;--i){if(options.multiline)
styleText+=indentString.repeat(i);styleText+="}";if(options.multiline)
styleText+="\n";}
styleText+="}";}
return styleText;} 
get nodeStyles()
{return this._nodeStyles;} 
_rangeAfterPropertyAtIndex(index)
{if(index<0)
return this._styleSheetTextRange.collapseToStart();if(index>=this.visibleProperties.length)
return this._styleSheetTextRange.collapseToEnd();let property=this.visibleProperties[index];return property.styleSheetTextRange.collapseToEnd();}};WI.CSSStyleDeclaration.Event={PropertiesChanged:"css-style-declaration-properties-changed",};WI.CSSStyleDeclaration.Type={Rule:"css-style-declaration-type-rule",Inline:"css-style-declaration-type-inline",Attribute:"css-style-declaration-type-attribute",Computed:"css-style-declaration-type-computed"};WI.CSSStyleSheet=class CSSStyleSheet extends WI.SourceCode
{constructor(id)
{super();this._id=id||null;this._parentFrame=null;this._origin=null;this._startLineNumber=0;this._startColumnNumber=0;this._inlineStyleAttribute=false;this._inlineStyleTag=false;this._hasInfo=false;} 
static resetUniqueDisplayNameNumbers()
{WI.CSSStyleSheet._nextUniqueDisplayNameNumber=1;} 
get id()
{return this._id;}
get parentFrame()
{return this._parentFrame;}
get origin()
{return this._origin;}
get injected()
{return WI.browserManager.isExtensionScheme(this.urlComponents.scheme);}
get anonymous()
{return!this.isInspectorStyleSheet()&&!this._url;}
get mimeType()
{return"text/css";}
get displayName()
{if(this.isInspectorStyleSheet())
return WI.UIString("Inspector Style Sheet");if(this._url)
return WI.displayNameForURL(this._url,this.urlComponents);if(!this._uniqueDisplayNameNumber)
this._uniqueDisplayNameNumber=this.constructor._nextUniqueDisplayNameNumber++;return WI.UIString("Anonymous Style Sheet %d").format(this._uniqueDisplayNameNumber);}
get startLineNumber()
{return this._startLineNumber;}
get startColumnNumber()
{return this._startColumnNumber;}
hasInfo()
{return this._hasInfo;}
isInspectorStyleSheet()
{return this._origin===WI.CSSStyleSheet.Type.Inspector;}
isInlineStyleTag()
{return this._inlineStyleTag;}
isInlineStyleAttributeStyleSheet()
{return this._inlineStyleAttribute;}
markAsInlineStyleAttributeStyleSheet()
{this._inlineStyleAttribute=true;}
offsetSourceCodeLocation(sourceCodeLocation)
{if(!sourceCodeLocation)
return null;if(!this._hasInfo)
return sourceCodeLocation;let sourceCode=sourceCodeLocation.sourceCode;let lineNumber=this._startLineNumber+sourceCodeLocation.lineNumber;let columnNumber=this._startColumnNumber+sourceCodeLocation.columnNumber;return sourceCode.createSourceCodeLocation(lineNumber,columnNumber);} 
updateInfo(url,parentFrame,origin,inlineStyle,startLineNumber,startColumnNumber)
{this._hasInfo=true;this._url=url||null;this._urlComponents=undefined;this._parentFrame=parentFrame||null;this._origin=origin;this._inlineStyleTag=inlineStyle;this._startLineNumber=startLineNumber;this._startColumnNumber=startColumnNumber;}
get revisionForRequestedContent()
{return this.currentRevision;}
handleCurrentRevisionContentChange()
{if(!this._id)
return;let target=WI.assumingMainTarget();function contentDidChange(error)
{if(error)
return;if(target.hasCommand("DOM.markUndoableState"))
target.DOMAgent.markUndoableState();this.dispatchEventToListeners(WI.CSSStyleSheet.Event.ContentDidChange);}
this._ignoreNextContentDidChangeNotification=true;target.CSSAgent.setStyleSheetText(this._id,this.currentRevision.content,contentDidChange.bind(this));}
requestContentFromBackend()
{let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise)
return specialContentPromise;if(!this._id){
return Promise.reject(new Error("There is no identifier to request content with."));}
let target=WI.assumingMainTarget();return target.CSSAgent.getStyleSheetText(this._id);}
noteContentDidChange()
{if(this._ignoreNextContentDidChangeNotification){this._ignoreNextContentDidChangeNotification=false;return false;}
this.markContentAsStale();this.dispatchEventToListeners(WI.CSSStyleSheet.Event.ContentDidChange);return true;}};WI.CSSStyleSheet._nextUniqueDisplayNameNumber=1;WI.CSSStyleSheet.Event={ContentDidChange:"css-style-sheet-content-did-change"};WI.CSSStyleSheet.Type={Author:"css-style-sheet-type-author",User:"css-style-sheet-type-user",UserAgent:"css-style-sheet-type-user-agent",Inspector:"css-style-sheet-type-inspector"};WI.CallFrame=class CallFrame
{constructor(target,id,sourceCodeLocation,functionName,thisObject,scopeChain,nativeCode,programCode,isTailDeleted,blackboxed)
{this._isConsoleEvaluation=sourceCodeLocation&&isWebInspectorConsoleEvaluationScript(sourceCodeLocation.sourceCode.sourceURL);if(this._isConsoleEvaluation){functionName=WI.UIString("Console Evaluation");programCode=true;}
this._target=target;this._id=id||null;this._sourceCodeLocation=sourceCodeLocation||null;this._functionName=functionName||"";this._thisObject=thisObject||null;this._scopeChain=scopeChain||[];this._nativeCode=nativeCode||false;this._programCode=programCode||false;this._isTailDeleted=isTailDeleted||false;this._blackboxed=blackboxed||false;} 
get target(){return this._target;}
get id(){return this._id;}
get sourceCodeLocation(){return this._sourceCodeLocation;}
get functionName(){return this._functionName;}
get nativeCode(){return this._nativeCode;}
get programCode(){return this._programCode;}
get thisObject(){return this._thisObject;}
get scopeChain(){return this._scopeChain;}
get isTailDeleted(){return this._isTailDeleted;}
get blackboxed(){return this._blackboxed;}
get isConsoleEvaluation(){return this._isConsoleEvaluation;}
saveIdentityToCookie()
{
}
collectScopeChainVariableNames(callback)
{let result=["this","__proto__"];var pendingRequests=this._scopeChain.length;function propertiesCollected(properties)
{for(var i=0;properties&&i<properties.length;++i)
result.push(properties[i].name);if(--pendingRequests)
return;callback(result);}
for(var i=0;i<this._scopeChain.length;++i)
this._scopeChain[i].objects[0].getPropertyDescriptors(propertiesCollected);}
mergedScopeChain()
{let mergedScopes=[];
let scopes=this._scopeChain.slice();



 
let lastMarkedHash=null;function markAsBaseIfNeeded(scope){if(!scope.hash)
return false;if(scope.type!==WI.ScopeChainNode.Type.Closure)
return false;if(scope.hash===lastMarkedHash)
return false;lastMarkedHash=scope.hash;scope.__baseClosureScope=true;return true;}
function shouldMergeClosureScopes(youngScope,oldScope,lastMerge){if(!youngScope||!oldScope)
return false;if(!youngScope.hash||!oldScope.hash)
return false;if(youngScope.type!==WI.ScopeChainNode.Type.Closure)
return false;if(oldScope.type!==WI.ScopeChainNode.Type.Closure)
return false;if(youngScope.hash!==oldScope.hash)
return false;if(lastMerge&&youngScope.hash===lastMerge.hash)
return false;return true;}
let lastScope=null;let lastMerge=null;for(let i=scopes.length-1;i>=0;--i){let scope=scopes[i];markAsBaseIfNeeded(scope);if(shouldMergeClosureScopes(scope,lastScope,lastMerge)){let type=WI.ScopeChainNode.Type.Closure;let objects=lastScope.objects.concat(scope.objects);let merged=new WI.ScopeChainNode(type,objects,scope.name,scope.location);merged.__baseClosureScope=true;mergedScopes.pop();mergedScopes.push(merged);lastMerge=merged;lastScope=null;}else{mergedScopes.push(scope);lastMerge=null;lastScope=scope;}}
mergedScopes=mergedScopes.reverse();for(let scope of mergedScopes){if(scope.type===WI.ScopeChainNode.Type.Closure){if(scope.name===this._functionName)
scope.convertToLocalScope();break;}}
return mergedScopes;} 
static functionNameFromPayload(payload)
{let functionName=payload.functionName;if(functionName==="global code")
return WI.UIString("Global Code");if(functionName==="eval code")
return WI.UIString("Eval Code");if(functionName==="module code")
return WI.UIString("Module Code");return functionName;}
static programCodeFromPayload(payload)
{return payload.functionName.endsWith(" code");}
static fromDebuggerPayload(target,payload,scopeChain,sourceCodeLocation)
{let id=payload.callFrameId;let thisObject=WI.RemoteObject.fromPayload(payload.this,target);let functionName=WI.CallFrame.functionNameFromPayload(payload);let nativeCode=false;let programCode=WI.CallFrame.programCodeFromPayload(payload);let isTailDeleted=payload.isTailDeleted;let blackboxed=sourceCodeLocation&&!!WI.debuggerManager.blackboxDataForSourceCode(sourceCodeLocation.sourceCode);return new WI.CallFrame(target,id,sourceCodeLocation,functionName,thisObject,scopeChain,nativeCode,programCode,isTailDeleted,blackboxed);}
static fromPayload(target,payload)
{let{url,scriptId}=payload;let nativeCode=false;let sourceCodeLocation=null;let functionName=WI.CallFrame.functionNameFromPayload(payload);let programCode=WI.CallFrame.programCodeFromPayload(payload);if(url==="[native code]"){nativeCode=true;url=null;}else if(url||scriptId){let sourceCode=null;if(scriptId){sourceCode=WI.debuggerManager.scriptForIdentifier(scriptId,target);if(sourceCode&&sourceCode.resource)
sourceCode=sourceCode.resource;}
if(!sourceCode)
sourceCode=WI.networkManager.resourcesForURL(url).firstValue;if(!sourceCode)
sourceCode=WI.debuggerManager.scriptsForURL(url,target)[0];if(sourceCode){let lineNumber=payload.lineNumber-1;sourceCodeLocation=sourceCode.createLazySourceCodeLocation(lineNumber,payload.columnNumber);}else{nativeCode=true;url=null;}}
const id=null;const thisObject=null;const scopeChain=null;const isTailDeleted=false;let blackboxed=sourceCodeLocation&&!!WI.debuggerManager.blackboxDataForSourceCode(sourceCodeLocation.sourceCode);return new WI.CallFrame(target,id,sourceCodeLocation,functionName,thisObject,scopeChain,nativeCode,programCode,isTailDeleted,blackboxed);}};WI.CallingContextTree=class CallingContextTree
{constructor(type)
{this._type=type||WI.CallingContextTree.Type.TopDown;this.reset();} 
get type(){return this._type;}
get totalNumberOfSamples(){return this._totalNumberOfSamples;}
reset()
{this._root=new WI.CallingContextTreeNode(-1,-1,-1,"<root>",null);this._totalNumberOfSamples=0;}
totalDurationInTimeRange(startTime,endTime)
{return this._root.filteredTimestampsAndDuration(startTime,endTime).duration;}
updateTreeWithStackTrace({timestamp,stackFrames},duration)
{this._totalNumberOfSamples++;let node=this._root;node.addTimestampAndExpressionLocation(timestamp,duration,null);switch(this._type){case WI.CallingContextTree.Type.TopDown:for(let i=stackFrames.length;i--;){let stackFrame=stackFrames[i];node=node.findOrMakeChild(stackFrame);node.addTimestampAndExpressionLocation(timestamp,duration,stackFrame.expressionLocation||null,i===0);}
break;case WI.CallingContextTree.Type.BottomUp:for(let i=0;i<stackFrames.length;++i){let stackFrame=stackFrames[i];node=node.findOrMakeChild(stackFrame);node.addTimestampAndExpressionLocation(timestamp,duration,stackFrame.expressionLocation||null,i===0);}
break;case WI.CallingContextTree.Type.TopFunctionsTopDown:for(let i=stackFrames.length;i--;){node=this._root;for(let j=i+1;j--;){let stackFrame=stackFrames[j];node=node.findOrMakeChild(stackFrame);node.addTimestampAndExpressionLocation(timestamp,duration,stackFrame.expressionLocation||null,j===0);}}
break;case WI.CallingContextTree.Type.TopFunctionsBottomUp:for(let i=0;i<stackFrames.length;i++){node=this._root;for(let j=i;j<stackFrames.length;j++){let stackFrame=stackFrames[j];node=node.findOrMakeChild(stackFrame);node.addTimestampAndExpressionLocation(timestamp,duration,stackFrame.expressionLocation||null,j===0);}}
break;default:break;}}
toCPUProfilePayload(startTime,endTime)
{let cpuProfile={};let roots=[];let numSamplesInTimeRange=this._root.filteredTimestampsAndDuration(startTime,endTime).timestamps.length;this._root.forEachChild((child)=>{if(child.hasStackTraceInTimeRange(startTime,endTime))
roots.push(child.toCPUProfileNode(numSamplesInTimeRange,startTime,endTime));});cpuProfile.rootNodes=roots;return cpuProfile;}
forEachChild(callback)
{this._root.forEachChild(callback);}
forEachNode(callback)
{this._root.forEachNode(callback);}
static __test_makeTreeFromProtocolMessageObject(messageObject)
{let tree=new WI.CallingContextTree;let stackTraces=messageObject.params.samples.stackTraces;for(let i=0;i<stackTraces.length;i++)
tree.updateTreeWithStackTrace(stackTraces[i]);return tree;}
__test_matchesStackTrace(stackTrace)
{



let leaves=this.__test_buildLeafLinkedLists();outer:for(let node of leaves){for(let stackNode of stackTrace){for(let propertyName of Object.getOwnPropertyNames(stackNode)){if(stackNode[propertyName]!==node[propertyName])
continue outer;}
node=node.parent;}
return true;}
return false;}
__test_buildLeafLinkedLists()
{let result=[];let parent=null;this._root.__test_buildLeafLinkedLists(parent,result);return result;}};WI.CallingContextTree.Type={TopDown:Symbol("TopDown"),BottomUp:Symbol("BottomUp"),TopFunctionsTopDown:Symbol("TopFunctionsTopDown"),TopFunctionsBottomUp:Symbol("TopFunctionsBottomUp"),};WI.CallingContextTreeNode=class CallingContextTreeNode
{constructor(sourceID,line,column,name,url,hash)
{this._children={};this._sourceID=sourceID;this._line=line;this._column=column;this._name=name;this._url=url;this._uid=WI.CallingContextTreeNode.__uid++;this._timestamps=[];this._durations=[];this._leafTimestamps=[];this._leafDurations=[];this._expressionLocations={};this._hash=hash||WI.CallingContextTreeNode._hash(this);} 
static _hash(stackFrame)
{return stackFrame.name+":"+stackFrame.sourceID+":"+stackFrame.line+":"+stackFrame.column;} 
get sourceID(){return this._sourceID;}
get line(){return this._line;}
get column(){return this._column;}
get name(){return this._name;}
get uid(){return this._uid;}
get url(){return this._url;}
get hash(){return this._hash;}
hasChildrenInTimeRange(startTime,endTime)
{for(let propertyName of Object.getOwnPropertyNames(this._children)){let child=this._children[propertyName];if(child.hasStackTraceInTimeRange(startTime,endTime))
return true;}
return false;}
hasStackTraceInTimeRange(startTime,endTime)
{if(startTime>endTime)
return false;let timestamps=this._timestamps;let length=timestamps.length;if(!length)
return false;let index=timestamps.lowerBound(startTime);if(index===length)
return false;let hasTimestampInRange=timestamps[index]<=endTime;return hasTimestampInRange;}
filteredTimestampsAndDuration(startTime,endTime)
{let lowerIndex=this._timestamps.lowerBound(startTime);let upperIndex=this._timestamps.upperBound(endTime);let totalDuration=0;for(let i=lowerIndex;i<upperIndex;++i)
totalDuration+=this._durations[i];return{timestamps:this._timestamps.slice(lowerIndex,upperIndex),duration:totalDuration,};}
filteredLeafTimestampsAndDuration(startTime,endTime)
{let lowerIndex=this._leafTimestamps.lowerBound(startTime);let upperIndex=this._leafTimestamps.upperBound(endTime);let totalDuration=0;for(let i=lowerIndex;i<upperIndex;++i)
totalDuration+=this._leafDurations[i];return{leafTimestamps:this._leafTimestamps.slice(lowerIndex,upperIndex),leafDuration:totalDuration,};}
hasChildren()
{return!isEmptyObject(this._children);}
findOrMakeChild(stackFrame)
{let hash=WI.CallingContextTreeNode._hash(stackFrame);let node=this._children[hash];if(node)
return node;node=new WI.CallingContextTreeNode(stackFrame.sourceID,stackFrame.line,stackFrame.column,stackFrame.name,stackFrame.url,hash);this._children[hash]=node;return node;}
addTimestampAndExpressionLocation(timestamp,duration,expressionLocation,leaf)
{this._timestamps.push(timestamp);this._durations.push(duration);if(leaf){this._leafTimestamps.push(timestamp);this._leafDurations.push(duration);}
if(!expressionLocation)
return;let{line,column}=expressionLocation;let hashCons=line+":"+column;let timestamps=this._expressionLocations[hashCons];if(!timestamps){timestamps=[];this._expressionLocations[hashCons]=timestamps;}
timestamps.push(timestamp);}
forEachChild(callback)
{for(let propertyName of Object.getOwnPropertyNames(this._children))
callback(this._children[propertyName]);}
forEachNode(callback)
{callback(this);this.forEachChild(function(child){child.forEachNode(callback);});}
equals(other)
{return this._hash===other.hash;}
toCPUProfileNode(numSamples,startTime,endTime)
{let children=[];this.forEachChild((child)=>{if(child.hasStackTraceInTimeRange(startTime,endTime))
children.push(child.toCPUProfileNode(numSamples,startTime,endTime));});let cpuProfileNode={id:this._uid,functionName:this._name,url:this._url,lineNumber:this._line,columnNumber:this._column,children:children};let timestamps=[];let frameStartTime=Number.MAX_VALUE;let frameEndTime=Number.MIN_VALUE;for(let i=0;i<this._timestamps.length;i++){let timestamp=this._timestamps[i];if(startTime<=timestamp&&timestamp<=endTime){timestamps.push(timestamp);frameStartTime=Math.min(frameStartTime,timestamp);frameEndTime=Math.max(frameEndTime,timestamp);}}
cpuProfileNode.callInfo={callCount:timestamps.length,startTime:frameStartTime,endTime:frameEndTime,totalTime:(timestamps.length/numSamples)*(endTime-startTime)};return cpuProfileNode;}
__test_buildLeafLinkedLists(parent,result)
{let linkedListNode={name:this._name,url:this._url,parent:parent};if(this.hasChildren()){this.forEachChild((child)=>{child.__test_buildLeafLinkedLists(linkedListNode,result);});}else{result.push(linkedListNode);}}};WI.CallingContextTreeNode.__uid=0;WI.Canvas=class Canvas extends WI.Object
{constructor(identifier,contextType,{domNode,cssCanvasName,contextAttributes,memoryCost,backtrace}={})
{super();this._identifier=identifier;this._contextType=contextType;this._domNode=domNode||null;this._cssCanvasName=cssCanvasName||"";this._contextAttributes=contextAttributes||{};this._extensions=new Set;this._memoryCost=memoryCost||NaN;this._backtrace=backtrace||[];this._clientNodes=null;this._shaderProgramCollection=new WI.ShaderProgramCollection;this._recordingCollection=new WI.RecordingCollection;this._nextShaderProgramDisplayNumber=null;this._requestNodePromise=null;this._recordingState=WI.Canvas.RecordingState.Inactive;this._recordingFrames=[];this._recordingBufferUsed=0;} 
static fromPayload(payload)
{let contextType=null;switch(payload.contextType){case InspectorBackend.Enum.Canvas.ContextType.Canvas2D:contextType=WI.Canvas.ContextType.Canvas2D;break;case InspectorBackend.Enum.Canvas.ContextType.BitmapRenderer:contextType=WI.Canvas.ContextType.BitmapRenderer;break;case InspectorBackend.Enum.Canvas.ContextType.WebGL:contextType=WI.Canvas.ContextType.WebGL;break;case InspectorBackend.Enum.Canvas.ContextType.WebGL2:contextType=WI.Canvas.ContextType.WebGL2;break;case InspectorBackend.Enum.Canvas.ContextType.WebGPU:contextType=WI.Canvas.ContextType.WebGPU;break;case InspectorBackend.Enum.Canvas.ContextType.WebMetal:contextType=WI.Canvas.ContextType.WebMetal;break;default:console.error("Invalid canvas context type",payload.contextType);}
return new WI.Canvas(payload.canvasId,contextType,{domNode:payload.nodeId?WI.domManager.nodeForId(payload.nodeId):null,cssCanvasName:payload.cssCanvasName,contextAttributes:payload.contextAttributes,memoryCost:payload.memoryCost,backtrace:Array.isArray(payload.backtrace)?payload.backtrace.map((item)=>WI.CallFrame.fromPayload(WI.mainTarget,item)):[],});}
static displayNameForContextType(contextType)
{switch(contextType){case WI.Canvas.ContextType.Canvas2D:return WI.UIString("2D");case WI.Canvas.ContextType.BitmapRenderer:return WI.UIString("Bitmap Renderer","Canvas Context Type Bitmap Renderer","Bitmap Renderer is a type of rendering context associated with a <canvas> element");case WI.Canvas.ContextType.WebGL:return WI.unlocalizedString("WebGL");case WI.Canvas.ContextType.WebGL2:return WI.unlocalizedString("WebGL2");case WI.Canvas.ContextType.WebGPU:return WI.unlocalizedString("Web GPU");case WI.Canvas.ContextType.WebMetal:return WI.unlocalizedString("WebMetal");}
return null;}
static displayNameForColorSpace(colorSpace)
{switch(colorSpace){case WI.Canvas.ColorSpace.SRGB:return WI.unlocalizedString("sRGB");case WI.Canvas.ColorSpace.DisplayP3:return WI.unlocalizedString("Display P3");}
return null;}
static resetUniqueDisplayNameNumbers()
{Canvas._nextContextUniqueDisplayNameNumber=1;Canvas._nextDeviceUniqueDisplayNameNumber=1;}
static supportsRequestContentForContextType(contextType)
{switch(contextType){case Canvas.ContextType.WebGPU:case Canvas.ContextType.WebMetal:return false;}
return true;} 
get identifier(){return this._identifier;}
get contextType(){return this._contextType;}
get cssCanvasName(){return this._cssCanvasName;}
get contextAttributes(){return this._contextAttributes;}
get extensions(){return this._extensions;}
get backtrace(){return this._backtrace;}
get shaderProgramCollection(){return this._shaderProgramCollection;}
get recordingCollection(){return this._recordingCollection;}
get recordingFrameCount(){return this._recordingFrames.length;}
get recordingBufferUsed(){return this._recordingBufferUsed;}
get recordingActive()
{return this._recordingState!==WI.Canvas.RecordingState.Inactive;}
get memoryCost()
{return this._memoryCost;}
set memoryCost(memoryCost)
{if(memoryCost===this._memoryCost)
return;this._memoryCost=memoryCost;this.dispatchEventToListeners(WI.Canvas.Event.MemoryChanged);}
get displayName()
{if(this._cssCanvasName)
return WI.UIString("CSS canvas \u201C%s\u201D").format(this._cssCanvasName);if(this._domNode){let idSelector=this._domNode.escapedIdSelector;if(idSelector)
return WI.UIString("Canvas %s").format(idSelector);}
if(this._contextType===Canvas.ContextType.WebGPU){if(!this._uniqueDisplayNameNumber)
this._uniqueDisplayNameNumber=Canvas._nextDeviceUniqueDisplayNameNumber++;return WI.UIString("Device %d").format(this._uniqueDisplayNameNumber);}
if(!this._uniqueDisplayNameNumber)
this._uniqueDisplayNameNumber=Canvas._nextContextUniqueDisplayNameNumber++;return WI.UIString("Canvas %d").format(this._uniqueDisplayNameNumber);}
requestNode()
{if(!this._requestNodePromise){this._requestNodePromise=new Promise((resolve,reject)=>{WI.domManager.ensureDocument();let target=WI.assumingMainTarget();target.CanvasAgent.requestNode(this._identifier,(error,nodeId)=>{if(error){resolve(null);return;}
this._domNode=WI.domManager.nodeForId(nodeId);if(!this._domNode){resolve(null);return;}
resolve(this._domNode);});});}
return this._requestNodePromise;}
requestContent()
{if(!Canvas.supportsRequestContentForContextType(this._contextType))
return Promise.resolve(null);let target=WI.assumingMainTarget();return target.CanvasAgent.requestContent(this._identifier).then((result)=>result.content).catch((error)=>console.error(error));}
requestClientNodes(callback)
{if(this._clientNodes){callback(this._clientNodes);return;}
WI.domManager.ensureDocument();let wrappedCallback=(error,clientNodeIds)=>{if(error){callback([]);return;}
clientNodeIds=Array.isArray(clientNodeIds)?clientNodeIds:[];this._clientNodes=clientNodeIds.map((clientNodeId)=>WI.domManager.nodeForId(clientNodeId));callback(this._clientNodes);};let target=WI.assumingMainTarget();if(!target.hasCommand("Canvas.requestClientNodes")){target.CanvasAgent.requestCSSCanvasClientNodes(this._identifier,wrappedCallback);return;}
target.CanvasAgent.requestClientNodes(this._identifier,wrappedCallback);}
requestSize()
{function calculateSize(domNode){function getAttributeValue(name){let value=Number(domNode.getAttribute(name));if(!Number.isInteger(value)||value<0)
return NaN;return value;}
return{width:getAttributeValue("width"),height:getAttributeValue("height")};}
function getPropertyValue(remoteObject,name){return new Promise((resolve,reject)=>{remoteObject.getProperty(name,(error,result)=>{if(error){reject(error);return;}
resolve(result);});});}
return this.requestNode().then((domNode)=>{if(!domNode)
return null;let size=calculateSize(domNode);if(!isNaN(size.width)&&!isNaN(size.height))
return size;

 let remoteObject=null;return WI.RemoteObject.resolveNode(domNode).then((object)=>{remoteObject=object;return Promise.all([getPropertyValue(object,"width"),getPropertyValue(object,"height")]);}).then((values)=>{let width=values[0].value;let height=values[1].value;values[0].release();values[1].release();remoteObject.release();return{width,height};});});}
startRecording(singleFrame)
{let target=WI.assumingMainTarget();let handleStartRecording=(error)=>{if(error){console.error(error);return;}
this._recordingState=WI.Canvas.RecordingState.ActiveFrontend; if(target.hasEvent("Canvas.recordingStarted"))
return;this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStarted);};if(target.hasCommand("Canvas.startRecording","singleFrame")){target.CanvasAgent.startRecording(this._identifier,singleFrame,handleStartRecording);return;}
if(singleFrame){const frameCount=1;target.CanvasAgent.startRecording(this._identifier,frameCount,handleStartRecording);}else
target.CanvasAgent.startRecording(this._identifier,handleStartRecording);}
stopRecording()
{let target=WI.assumingMainTarget();target.CanvasAgent.stopRecording(this._identifier);}
saveIdentityToCookie(cookie)
{if(this._cssCanvasName)
cookie[WI.Canvas.CSSCanvasNameCookieKey]=this._cssCanvasName;else if(this._domNode)
cookie[WI.Canvas.NodePathCookieKey]=this._domNode.path;}
enableExtension(extension)
{this._extensions.add(extension);this.dispatchEventToListeners(WI.Canvas.Event.ExtensionEnabled,{extension});}
clientNodesChanged()
{this._clientNodes=null;this.dispatchEventToListeners(Canvas.Event.ClientNodesChanged);}
recordingStarted(initiator)
{if(initiator===InspectorBackend.Enum.Recording.Initiator.Console)
this._recordingState=WI.Canvas.RecordingState.ActiveConsole;else if(initiator===InspectorBackend.Enum.Recording.Initiator.AutoCapture)
this._recordingState=WI.Canvas.RecordingState.ActiveAutoCapture;else{this._recordingState=WI.Canvas.RecordingState.ActiveFrontend;}
this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStarted);}
recordingProgress(framesPayload,bufferUsed)
{this._recordingFrames.pushAll(framesPayload.map(WI.RecordingFrame.fromPayload));this._recordingBufferUsed=bufferUsed;this.dispatchEventToListeners(WI.Canvas.Event.RecordingProgress);}
recordingFinished(recordingPayload)
{let initiatedByUser=this._recordingState===WI.Canvas.RecordingState.ActiveFrontend; if(!initiatedByUser&&!InspectorBackend.hasEvent("Canvas.recordingStarted"))
initiatedByUser=!!this.recordingActive;let recording=recordingPayload?WI.Recording.fromPayload(recordingPayload,this._recordingFrames):null;if(recording){recording.source=this;recording.createDisplayName(recordingPayload.name);this._recordingCollection.add(recording);}
this._recordingState=WI.Canvas.RecordingState.Inactive;this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStopped,{recording,initiatedByUser});}
nextShaderProgramDisplayNumberForProgramType(programType)
{if(!this._nextShaderProgramDisplayNumber)
this._nextShaderProgramDisplayNumber={};this._nextShaderProgramDisplayNumber[programType]=(this._nextShaderProgramDisplayNumber[programType]||0)+1;return this._nextShaderProgramDisplayNumber[programType];}};WI.Canvas._nextContextUniqueDisplayNameNumber=1;WI.Canvas._nextDeviceUniqueDisplayNameNumber=1;WI.Canvas.FrameURLCookieKey="canvas-frame-url";WI.Canvas.CSSCanvasNameCookieKey="canvas-css-canvas-name";WI.Canvas.ContextType={Canvas2D:"canvas-2d",BitmapRenderer:"bitmaprenderer",WebGL:"webgl",WebGL2:"webgl2",WebGPU:"webgpu",WebMetal:"webmetal",};WI.Canvas.ColorSpace={SRGB:"srgb",DisplayP3:"display-p3",};WI.Canvas.RecordingState={Inactive:"canvas-recording-state-inactive",ActiveFrontend:"canvas-recording-state-active-frontend",ActiveConsole:"canvas-recording-state-active-console",ActiveAutoCapture:"canvas-recording-state-active-auto-capture",};WI.Canvas.Event={MemoryChanged:"canvas-memory-changed",ExtensionEnabled:"canvas-extension-enabled",ClientNodesChanged:"canvas-client-nodes-changed",RecordingStarted:"canvas-recording-started",RecordingProgress:"canvas-recording-progress",RecordingStopped:"canvas-recording-stopped",};WI.CollectionEntry=class CollectionEntry
{constructor(key,value)
{this._key=key;this._value=value;}

static fromPayload(payload,target)
{if(payload.key)
payload.key=WI.RemoteObject.fromPayload(payload.key,target);if(payload.value)
payload.value=WI.RemoteObject.fromPayload(payload.value,target);return new WI.CollectionEntry(payload.key,payload.value);} 
get key(){return this._key;}
get value(){return this._value;}};WI.CollectionEntryPreview=class CollectionEntryPreview
{constructor(keyPreview,valuePreview)
{this._key=keyPreview;this._value=valuePreview;}

static fromPayload(payload)
{if(payload.key)
payload.key=WI.ObjectPreview.fromPayload(payload.key);if(payload.value)
payload.value=WI.ObjectPreview.fromPayload(payload.value);return new WI.CollectionEntryPreview(payload.key,payload.value);} 
get keyPreview(){return this._key;}
get valuePreview(){return this._value;}};WI.FrameCollection=class FrameCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Frames");}
objectIsRequiredType(object)
{return object instanceof WI.Frame;}};WI.ScriptCollection=class ScriptCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Scripts");}
objectIsRequiredType(object)
{return object instanceof WI.Script;}};WI.CSSStyleSheetCollection=class CSSStyleSheetCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Style Sheets");}
objectIsRequiredType(object)
{return object instanceof WI.CSSStyleSheet;}};WI.CanvasCollection=class CanvasCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Canvases");}
objectIsRequiredType(object)
{return object instanceof WI.Canvas;}};WI.ShaderProgramCollection=class ShaderProgramCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Shader Programs");}
objectIsRequiredType(object)
{return object instanceof WI.ShaderProgram;}};WI.RecordingCollection=class RecordingCollection extends WI.Collection
{ get displayName()
{return WI.UIString("Recordings");}
objectIsRequiredType(object)
{return object instanceof WI.Recording;}};WI.Color=class Color
{constructor(format,components,gamut)
{this.format=format;this._gamut=gamut||WI.Color.Gamut.SRGB;this.alpha=components.length===4?components[3]:1;this._rgb=null;this._normalizedRGB=null;this._hsl=null;if(format===WI.Color.Format.HSL||format===WI.Color.Format.HSLA)
this._hsl=components.slice(0,3);else if(format===WI.Color.Format.ColorFunction)
this._normalizedRGB=components.slice(0,3);else
this._rgb=components.slice(0,3);this.valid=!components.some(isNaN);} 
static fromString(colorString)
{const matchRegExp=/^(?:#(?<hex>[0-9a-f]{3,8})|rgba?\((?<rgb>[^)]+)\)|(?<keyword>\w+)|color\((?<color>[^)]+)\)|hsla?\((?<hsl>[^)]+)\))$/i;let match=colorString.match(matchRegExp);if(!match)
return null;if(match.groups.hex){let hex=match.groups.hex.toUpperCase();switch(hex.length){case 3:return new WI.Color(WI.Color.Format.ShortHEX,[parseInt(hex.charAt(0)+hex.charAt(0),16),parseInt(hex.charAt(1)+hex.charAt(1),16),parseInt(hex.charAt(2)+hex.charAt(2),16),1]);case 6:return new WI.Color(WI.Color.Format.HEX,[parseInt(hex.substring(0,2),16),parseInt(hex.substring(2,4),16),parseInt(hex.substring(4,6),16),1]);case 4:return new WI.Color(WI.Color.Format.ShortHEXAlpha,[parseInt(hex.charAt(0)+hex.charAt(0),16),parseInt(hex.charAt(1)+hex.charAt(1),16),parseInt(hex.charAt(2)+hex.charAt(2),16),parseInt(hex.charAt(3)+hex.charAt(3),16)/255]);case 8:return new WI.Color(WI.Color.Format.HEXAlpha,[parseInt(hex.substring(0,2),16),parseInt(hex.substring(2,4),16),parseInt(hex.substring(4,6),16),parseInt(hex.substring(6,8),16)/255]);}
return null;}
if(match.groups.keyword){let keyword=match.groups.keyword.toLowerCase();if(!WI.Color.Keywords.hasOwnProperty(keyword))
return null;let color=new WI.Color(WI.Color.Format.Keyword,WI.Color.Keywords[keyword].slice());color.keyword=keyword;color.original=colorString;return color;}
function splitFunctionString(string){return string.trim().replace(/(\s*(,|\/)\s*|\s+)/g,"|").split("|");}
function parseFunctionAlpha(alpha){let value=parseFloat(alpha);if(alpha.includes("%"))
value/=100;return Number.constrain(value,0,1);}
if(match.groups.rgb){let rgb=splitFunctionString(match.groups.rgb);if(rgb.length!==3&&rgb.length!==4)
return null;function parseFunctionComponent(component){let value=parseFloat(component);if(component.includes("%"))
value=value*255/100;return Number.constrain(value,0,255);}
let alpha=1;if(rgb.length===4)
alpha=parseFunctionAlpha(rgb[3]);return new WI.Color(rgb.length===4?WI.Color.Format.RGBA:WI.Color.Format.RGB,[parseFunctionComponent(rgb[0]),parseFunctionComponent(rgb[1]),parseFunctionComponent(rgb[2]),alpha,]);}
if(match.groups.hsl){let hsl=splitFunctionString(match.groups.hsl);if(hsl.length!==3&&hsl.length!==4)
return null;let alpha=1;if(hsl.length===4)
alpha=parseFunctionAlpha(hsl[3]);function parseHueComponent(hue){let value=parseFloat(hue);if(/(\b|\d)rad\b/.test(hue))
value=value*180/Math.PI;else if(/(\b|\d)grad\b/.test(hue))
value=value*360/400;else if(/(\b|\d)turn\b/.test(hue))
value=value*360;return Number.constrain(value,0,360);}
function parsePercentageComponent(component){let value=parseFloat(component);return Number.constrain(value,0,100);}
return new WI.Color(hsl.length===4?WI.Color.Format.HSLA:WI.Color.Format.HSL,[parseHueComponent(hsl[0]),parsePercentageComponent(hsl[1]),parsePercentageComponent(hsl[2]),alpha,]);}
if(match.groups.color){let colorString=match.groups.color.trim();let components=splitFunctionString(colorString);if(components.length!==4&&components.length!==5)
return null;let gamut=components[0].toLowerCase();if(!Object.values(WI.Color.Gamut).includes(gamut))
return null;let alpha=1;if(components.length===5)
alpha=parseFunctionAlpha(components[4]);function parseFunctionComponent(component){let value=parseFloat(component);return Number.constrain(value,0,1);}
return new WI.Color(WI.Color.Format.ColorFunction,[parseFunctionComponent(components[1]),parseFunctionComponent(components[2]),parseFunctionComponent(components[3]),alpha,],gamut);}
return null;}
static rgb2hsl(r,g,b)
{r=WI.Color._eightBitChannel(r)/255;g=WI.Color._eightBitChannel(g)/255;b=WI.Color._eightBitChannel(b)/255;let min=Math.min(r,g,b);let max=Math.max(r,g,b);let delta=max-min;let h=0;let s=0;let l=(max+min)/2;if(delta===0)
h=0;else if(max===r)
h=(60*((g-b)/delta))%360;else if(max===g)
h=60*((b-r)/delta)+120;else if(max===b)
h=60*((r-g)/delta)+240;if(h<0)
h+=360; if(delta===0)
s=0;else
s=delta/(1-Math.abs((2*l)-1));return[h,s*100,l*100,];}
static hsl2rgb(h,s,l)
{h=Number.constrain(h,0,360)%360;s=Number.constrain(s,0,100)/100;l=Number.constrain(l,0,100)/100;let c=(1-Math.abs((2*l)-1))*s;let x=c*(1-Math.abs(((h/60)%2)-1));let m=l-(c/2);let r=0;let g=0;let b=0;if(h<60){r=c;g=x;}else if(h<120){r=x;g=c;}else if(h<180){g=c;b=x;}else if(h<240){g=x;b=c;}else if(h<300){r=x;b=c;}else if(h<360){r=c;b=x;}
return[(r+m)*255,(g+m)*255,(b+m)*255,];} 
static hsv2hsl(h,s,v)
{h=Number.constrain(h,0,360);s=Number.constrain(s,0,100)/100;v=Number.constrain(v,0,100)/100;let l=v-v*s/2;let saturation;if(l===0||l===1)
saturation=0;else
saturation=(v-l)/Math.min(l,1-l);return[h,saturation*100,l*100];} 
static rgb2hsv(r,g,b)
{r=Number.constrain(r,0,1);g=Number.constrain(g,0,1);b=Number.constrain(b,0,1);let max=Math.max(r,g,b);let min=Math.min(r,g,b);let h=0;let delta=max-min;let s=max===0?0:delta/max;let v=max;if(max===min)
h=0;else{switch(max){case r:h=((g-b)/delta)+((g<b)?6:0);break;case g:h=((b-r)/delta)+2;break;case b:h=((r-g)/delta)+4;break;}
h/=6;}
return[h*360,s*100,v*100];} 
static hsv2rgb(h,s,v)
{h=Number.constrain(h,0,360);s=Number.constrain(s,0,100)/100;v=Number.constrain(v,0,100)/100;function fraction(n){let k=(n+(h/60))%6;return v-(v*s*Math.max(Math.min(k,4-k,1),0));}
return[fraction(5),fraction(3),fraction(1)];} 
static displayP3toSRGB(r,g,b)
{r=Number.constrain(r,0,1);g=Number.constrain(g,0,1);b=Number.constrain(b,0,1);let linearP3=WI.Color._toLinearLight([r,g,b]);
 const rgbToXYZMatrix=[[0.4865709486482162,0.26566769316909306,0.1982172852343625],[0.2289745640697488,0.6917385218365064,0.079286914093745],[0.0000000000000000,0.04511338185890264,1.043944368900976],];let xyz=Math.multiplyMatrixByVector(rgbToXYZMatrix,linearP3);const xyzToLinearSRGBMatrix=[[3.2404542,-1.5371385,-0.4985314],[-0.9692660,1.8760108,0.0415560],[0.0556434,-0.2040259,1.0572252],];let linearSRGB=Math.multiplyMatrixByVector(xyzToLinearSRGBMatrix,xyz);let srgb=WI.Color._gammaCorrect(linearSRGB);return srgb.map((x)=>x.maxDecimals(4));} 
static srgbToDisplayP3(r,g,b)
{r=Number.constrain(r,0,1);g=Number.constrain(g,0,1);b=Number.constrain(b,0,1);let linearSRGB=WI.Color._toLinearLight([r,g,b]);
 
const linearSRGBtoXYZMatrix=[[0.4124564,0.3575761,0.1804375],[0.2126729,0.7151522,0.0721750],[0.0193339,0.1191920,0.9503041],];let xyz=Math.multiplyMatrixByVector(linearSRGBtoXYZMatrix,linearSRGB);const xyzToLinearP3Matrix=[[2.493496911941425,-0.9313836179191239,-0.40271078445071684],[-0.8294889695615747,1.7626640603183463,0.023624685841943577],[0.03584583024378447,-0.07617238926804182,0.9568845240076872],];let linearP3=Math.multiplyMatrixByVector(xyzToLinearP3Matrix,xyz);let p3=WI.Color._gammaCorrect(linearP3);return p3.map((x)=>x.maxDecimals(4));} 
static _toLinearLight(rgb)
{return rgb.map(function(value){if(value<0.04045)
return value/12.92;return Math.pow((value+0.055)/1.055,2.4);});} 
static _gammaCorrect(rgb)
{return rgb.map(function(value){if(value>0.0031308)
return 1.055*Math.pow(value,1/2.4)-0.055;return 12.92*value;});}
static cmyk2rgb(c,m,y,k)
{c=Number.constrain(c,0,1);m=Number.constrain(m,0,1);y=Number.constrain(y,0,1);k=Number.constrain(k,0,1);return[255*(1-c)*(1-k),255*(1-m)*(1-k),255*(1-y)*(1-k),];}
static normalized2rgb(r,g,b)
{return[WI.Color._eightBitChannel(r*255),WI.Color._eightBitChannel(g*255),WI.Color._eightBitChannel(b*255)];}
static _eightBitChannel(value)
{return Number.constrain(Math.round(value),0,255);} 
nextFormat(format)
{format=format||this.format;switch(format){case WI.Color.Format.Original:case WI.Color.Format.HEX:case WI.Color.Format.HEXAlpha:return this.simple?WI.Color.Format.RGB:WI.Color.Format.RGBA;case WI.Color.Format.RGB:case WI.Color.Format.RGBA:return WI.Color.Format.ColorFunction;case WI.Color.Format.ColorFunction:if(this.simple)
return WI.Color.Format.HSL;return WI.Color.Format.HSLA;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:if(this.isKeyword())
return WI.Color.Format.Keyword;if(this.simple)
return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEX:WI.Color.Format.HEX;return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEXAlpha:WI.Color.Format.HEXAlpha;case WI.Color.Format.ShortHEX:return WI.Color.Format.HEX;case WI.Color.Format.ShortHEXAlpha:return WI.Color.Format.HEXAlpha;case WI.Color.Format.Keyword:if(this.simple)
return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEX:WI.Color.Format.HEX;return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEXAlpha:WI.Color.Format.HEXAlpha;default:console.error("Unknown color format.");return null;}}
get simple()
{return this.alpha===1;}
get rgb()
{if(!this._rgb){if(this._hsl)
this._rgb=WI.Color.hsl2rgb(...this._hsl);else if(this._normalizedRGB)
this._rgb=this._normalizedRGB.map((component)=>WI.Color._eightBitChannel(component*255));}
return this._rgb;}
get hsl()
{if(!this._hsl)
this._hsl=WI.Color.rgb2hsl(...this.rgb);return this._hsl;}
get normalizedRGB()
{if(!this._normalizedRGB)
this._normalizedRGB=this.rgb.map((component)=>component/255);return this._normalizedRGB;}
get rgba()
{return[...this.rgb,this.alpha];}
get hsla()
{return[...this.hsl,this.alpha];}
get normalizedRGBA()
{return[...this.normalizedRGB,this.alpha];}
get gamut()
{return this._gamut;}
set gamut(gamut)
{if(this._gamut===WI.Color.Gamut.DisplayP3&&gamut===WI.Color.Gamut.SRGB){this._normalizedRGB=WI.Color.displayP3toSRGB(...this.normalizedRGB).map((x)=>Number.constrain(x,0,1));this._hsl=null;this._rgb=null;}else if(this._gamut===WI.Color.Gamut.SRGB&&gamut===WI.Color.Gamut.DisplayP3){this._normalizedRGB=WI.Color.srgbToDisplayP3(...this.normalizedRGB);this._hsl=null;this._rgb=null;this.format=WI.Color.Format.ColorFunction;}
this._gamut=gamut;}
copy()
{switch(this.format){case WI.Color.Format.RGB:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:case WI.Color.Format.RGBA:return new WI.Color(this.format,this.rgba,this._gamut);case WI.Color.Format.HSL:case WI.Color.Format.HSLA:return new WI.Color(this.format,this.hsla,this._gamut);case WI.Color.Format.ColorFunction:return new WI.Color(this.format,this.normalizedRGBA,this._gamut);}
console.error("Invalid color format: "+this.format);}
toString(format)
{if(!format)
format=this.format;switch(format){case WI.Color.Format.Original:return this._toOriginalString();case WI.Color.Format.RGB:return this._toRGBString();case WI.Color.Format.RGBA:return this._toRGBAString();case WI.Color.Format.ColorFunction:return this._toFunctionString();case WI.Color.Format.HSL:return this._toHSLString();case WI.Color.Format.HSLA:return this._toHSLAString();case WI.Color.Format.HEX:return this._toHEXString();case WI.Color.Format.ShortHEX:return this._toShortHEXString();case WI.Color.Format.HEXAlpha:return this._toHEXAlphaString();case WI.Color.Format.ShortHEXAlpha:return this._toShortHEXAlphaString();case WI.Color.Format.Keyword:return this._toKeywordString();}
console.error("Invalid color format: "+format);return"";}
toProtocol()
{let[r,g,b,a]=this.rgba;return{r,g,b,a};}
isKeyword()
{if(this.keyword)
return true;if(this._gamut!==WI.Color.Gamut.SRGB)
return false;if(!this.simple)
return Array.shallowEqual(this.rgba,[0,0,0,0]);return Object.keys(WI.Color.Keywords).some(key=>Array.shallowEqual(WI.Color.Keywords[key],this.rgb));}
isOutsideSRGB()
{if(this._gamut!==WI.Color.Gamut.DisplayP3)
return false;let rgb=WI.Color.displayP3toSRGB(...this.normalizedRGB);const epsilon=(1/255)/2;return rgb.some((x)=>x<=-epsilon||x>=1+epsilon);}
canBeSerializedAsShortHEX()
{let rgb=this.rgb;let r=this._componentToHexValue(rgb[0]);if(r[0]!==r[1])
return false;let g=this._componentToHexValue(rgb[1]);if(g[0]!==g[1])
return false;let b=this._componentToHexValue(rgb[2]);if(b[0]!==b[1])
return false;if(!this.simple){let a=this._componentToHexValue(Math.round(this.alpha*255));if(a[0]!==a[1])
return false;}
return true;} 
_toOriginalString()
{return this.original||this._toKeywordString();}
_toKeywordString()
{if(this.keyword)
return this.keyword;let rgba=this.rgba;if(!this.simple){if(Array.shallowEqual(rgba,[0,0,0,0]))
return"transparent";return this._toRGBAString();}
let keywords=WI.Color.Keywords;for(let keyword in keywords){if(!keywords.hasOwnProperty(keyword))
continue;let keywordRGB=keywords[keyword];if(keywordRGB[0]===rgba[0]&&keywordRGB[1]===rgba[1]&&keywordRGB[2]===rgba[2])
return keyword;}
return this._toRGBString();}
_toShortHEXString()
{if(!this.simple)
return this._toRGBAString();let[r,g,b]=this.rgb.map(this._componentToHexValue);if(r[0]===r[1]&&g[0]===g[1]&&b[0]===b[1])
return"#"+r[0]+g[0]+b[0];return"#"+r+g+b;}
_toHEXString()
{if(!this.simple)
return this._toRGBAString();let[r,g,b]=this.rgb.map(this._componentToHexValue);return"#"+r+g+b;}
_toShortHEXAlphaString()
{let[r,g,b]=this.rgb.map(this._componentToHexValue);let a=this._componentToHexValue(Math.round(this.alpha*255));if(r[0]===r[1]&&g[0]===g[1]&&b[0]===b[1]&&a[0]===a[1])
return"#"+r[0]+g[0]+b[0]+a[0];return"#"+r+g+b+a;}
_toHEXAlphaString()
{let[r,g,b]=this.rgb.map(this._componentToHexValue);let a=this._componentToHexValue(Math.round(this.alpha*255));return"#"+r+g+b+a;}
_toRGBString()
{if(!this.simple)
return this._toRGBAString();let[r,g,b]=this.rgb.map(WI.Color._eightBitChannel);return`rgb(${r}, ${g}, ${b})`;}
_toRGBAString()
{let[r,g,b]=this.rgb.map(WI.Color._eightBitChannel);return`rgba(${r}, ${g}, ${b}, ${this.alpha})`;}
_toFunctionString()
{let[r,g,b]=this.normalizedRGB.map((x)=>x.maxDecimals(4));if(this.alpha===1)
return`color(${this._gamut} ${r} ${g} ${b})`;return`color(${this._gamut} ${r} ${g} ${b} / ${this.alpha})`;}
_toHSLString()
{if(!this.simple)
return this._toHSLAString();let[h,s,l]=this.hsl.map((x)=>x.maxDecimals(2));return`hsl(${h}, ${s}%, ${l}%)`;}
_toHSLAString()
{let[h,s,l]=this.hsl.map((x)=>x.maxDecimals(2));return`hsla(${h}, ${s}%, ${l}%, ${this.alpha})`;}
_componentToHexValue(value)
{let hex=WI.Color._eightBitChannel(value).toString(16);if(hex.length===1)
hex="0"+hex;return hex;}};WI.Color.Format={Original:"color-format-original",Keyword:"color-format-keyword",HEX:"color-format-hex",ShortHEX:"color-format-short-hex",HEXAlpha:"color-format-hex-alpha",ShortHEXAlpha:"color-format-short-hex-alpha",RGB:"color-format-rgb",RGBA:"color-format-rgba",HSL:"color-format-hsl",HSLA:"color-format-hsla",ColorFunction:"color-format-color-function",};WI.Color.Gamut={SRGB:"srgb",DisplayP3:"display-p3",};WI.Color.FunctionNames=new Set(["rgb","rgba","hsl","hsla","color",]);WI.Color.Keywords={"aliceblue":[240,248,255,1],"antiquewhite":[250,235,215,1],"aqua":[0,255,255,1],"aquamarine":[127,255,212,1],"azure":[240,255,255,1],"beige":[245,245,220,1],"bisque":[255,228,196,1],"black":[0,0,0,1],"blanchedalmond":[255,235,205,1],"blue":[0,0,255,1],"blueviolet":[138,43,226,1],"brown":[165,42,42,1],"burlywood":[222,184,135,1],"cadetblue":[95,158,160,1],"chartreuse":[127,255,0,1],"chocolate":[210,105,30,1],"coral":[255,127,80,1],"cornflowerblue":[100,149,237,1],"cornsilk":[255,248,220,1],"crimson":[237,164,61,1],"cyan":[0,255,255,1],"darkblue":[0,0,139,1],"darkcyan":[0,139,139,1],"darkgoldenrod":[184,134,11,1],"darkgray":[169,169,169,1],"darkgreen":[0,100,0,1],"darkgrey":[169,169,169,1],"darkkhaki":[189,183,107,1],"darkmagenta":[139,0,139,1],"darkolivegreen":[85,107,47,1],"darkorange":[255,140,0,1],"darkorchid":[153,50,204,1],"darkred":[139,0,0,1],"darksalmon":[233,150,122,1],"darkseagreen":[143,188,143,1],"darkslateblue":[72,61,139,1],"darkslategray":[47,79,79,1],"darkslategrey":[47,79,79,1],"darkturquoise":[0,206,209,1],"darkviolet":[148,0,211,1],"deeppink":[255,20,147,1],"deepskyblue":[0,191,255,1],"dimgray":[105,105,105,1],"dimgrey":[105,105,105,1],"dodgerblue":[30,144,255,1],"firebrick":[178,34,34,1],"floralwhite":[255,250,240,1],"forestgreen":[34,139,34,1],"fuchsia":[255,0,255,1],"gainsboro":[220,220,220,1],"ghostwhite":[248,248,255,1],"gold":[255,215,0,1],"goldenrod":[218,165,32,1],"gray":[128,128,128,1],"green":[0,128,0,1],"greenyellow":[173,255,47,1],"grey":[128,128,128,1],"honeydew":[240,255,240,1],"hotpink":[255,105,180,1],"indianred":[205,92,92,1],"indigo":[75,0,130,1],"ivory":[255,255,240,1],"khaki":[240,230,140,1],"lavender":[230,230,250,1],"lavenderblush":[255,240,245,1],"lawngreen":[124,252,0,1],"lemonchiffon":[255,250,205,1],"lightblue":[173,216,230,1],"lightcoral":[240,128,128,1],"lightcyan":[224,255,255,1],"lightgoldenrodyellow":[250,250,210,1],"lightgray":[211,211,211,1],"lightgreen":[144,238,144,1],"lightgrey":[211,211,211,1],"lightpink":[255,182,193,1],"lightsalmon":[255,160,122,1],"lightseagreen":[32,178,170,1],"lightskyblue":[135,206,250,1],"lightslategray":[119,136,153,1],"lightslategrey":[119,136,153,1],"lightsteelblue":[176,196,222,1],"lightyellow":[255,255,224,1],"lime":[0,255,0,1],"limegreen":[50,205,50,1],"linen":[250,240,230,1],"magenta":[255,0,255,1],"maroon":[128,0,0,1],"mediumaquamarine":[102,205,170,1],"mediumblue":[0,0,205,1],"mediumorchid":[186,85,211,1],"mediumpurple":[147,112,219,1],"mediumseagreen":[60,179,113,1],"mediumslateblue":[123,104,238,1],"mediumspringgreen":[0,250,154,1],"mediumturquoise":[72,209,204,1],"mediumvioletred":[199,21,133,1],"midnightblue":[25,25,112,1],"mintcream":[245,255,250,1],"mistyrose":[255,228,225,1],"moccasin":[255,228,181,1],"navajowhite":[255,222,173,1],"navy":[0,0,128,1],"oldlace":[253,245,230,1],"olive":[128,128,0,1],"olivedrab":[107,142,35,1],"orange":[255,165,0,1],"orangered":[255,69,0,1],"orchid":[218,112,214,1],"palegoldenrod":[238,232,170,1],"palegreen":[152,251,152,1],"paleturquoise":[175,238,238,1],"palevioletred":[219,112,147,1],"papayawhip":[255,239,213,1],"peachpuff":[255,218,185,1],"peru":[205,133,63,1],"pink":[255,192,203,1],"plum":[221,160,221,1],"powderblue":[176,224,230,1],"purple":[128,0,128,1],"rebeccapurple":[102,51,153,1],"red":[255,0,0,1],"rosybrown":[188,143,143,1],"royalblue":[65,105,225,1],"saddlebrown":[139,69,19,1],"salmon":[250,128,114,1],"sandybrown":[244,164,96,1],"seagreen":[46,139,87,1],"seashell":[255,245,238,1],"sienna":[160,82,45,1],"silver":[192,192,192,1],"skyblue":[135,206,235,1],"slateblue":[106,90,205,1],"slategray":[112,128,144,1],"slategrey":[112,128,144,1],"snow":[255,250,250,1],"springgreen":[0,255,127,1],"steelblue":[70,130,180,1],"tan":[210,180,140,1],"teal":[0,128,128,1],"thistle":[216,191,216,1],"tomato":[255,99,71,1],"transparent":[0,0,0,0],"turquoise":[64,224,208,1],"violet":[238,130,238,1],"wheat":[245,222,179,1],"white":[255,255,255,1],"whitesmoke":[245,245,245,1],"yellow":[255,255,0,1],"yellowgreen":[154,205,50,1],};WI.ConsoleCommandResultMessage=class ConsoleCommandResult extends WI.ConsoleMessage
{constructor(target,result,wasThrown,savedResultIndex,shouldRevealConsole=true)
{let source=WI.ConsoleMessage.MessageSource.JS;let level=wasThrown?WI.ConsoleMessage.MessageLevel.Error:WI.ConsoleMessage.MessageLevel.Log;let type=WI.ConsoleMessage.MessageType.Result;super(target,source,level,"",type,undefined,undefined,undefined,0,[result],undefined,undefined);this._savedResultIndex=savedResultIndex;this._shouldRevealConsole=shouldRevealConsole;if(this._savedResultIndex&&this._savedResultIndex>WI.ConsoleCommandResultMessage.maximumSavedResultIndex)
WI.ConsoleCommandResultMessage.maximumSavedResultIndex=this._savedResultIndex;} 
static clearMaximumSavedResultIndex()
{WI.ConsoleCommandResultMessage.maximumSavedResultIndex=0;} 
get savedResultIndex()
{return this._savedResultIndex;}
get shouldRevealConsole()
{return this._shouldRevealConsole;}};WI.ConsoleCommandResultMessage.maximumSavedResultIndex=0;WI.Cookie=class Cookie
{constructor(type,name,value,{header,expires,session,maxAge,path,domain,secure,httpOnly,sameSite}={})
{this._type=type;this._name=name;this._value=value;this._size=this._name.length+this._value.length;if(this._type===WI.Cookie.Type.Response){this._header=header||"";this._expires=(!session&&expires)||null;this._session=session||false;this._maxAge=maxAge||null;this._path=path||null;this._domain=domain||null;this._secure=secure||false;this._httpOnly=httpOnly||false;this._sameSite=sameSite||WI.Cookie.SameSiteType.None;}} 
static fromPayload(payload)
{let{name,value,...options}=payload;options.expires=options.expires?new Date(options.expires.maxDecimals(-3)):null;return new WI.Cookie(WI.Cookie.Type.Response,name,value,options);} 
static parseCookieRequestHeader(header)
{if(!header)
return[];header=header.trim();if(!header)
return[];let cookies=[];let pairs=header.split(/; /);for(let pair of pairs){let match=pair.match(/^(?<name>[^\s=]+)[ \t]*=[ \t]*(?<value>.*)$/);if(!match){WI.reportInternalError("Failed to parse Cookie pair",{header,pair});continue;}
let{name,value}=match.groups;cookies.push(new WI.Cookie(WI.Cookie.Type.Request,name,value));}
return cookies;}
static displayNameForSameSiteType(sameSiteType)
{switch(sameSiteType){case WI.Cookie.SameSiteType.None:return WI.unlocalizedString("None");case WI.Cookie.SameSiteType.Lax:return WI.unlocalizedString("Lax");case WI.Cookie.SameSiteType.Strict:return WI.unlocalizedString("Strict");default:console.error("Invalid SameSite type",sameSiteType);return sameSiteType;}}
static parseSameSiteAttributeValue(attributeValue)
{if(!attributeValue)
return WI.Cookie.SameSiteType.None;switch(attributeValue.toLowerCase()){case"lax":return WI.Cookie.SameSiteType.Lax;case"strict":return WI.Cookie.SameSiteType.Strict;}
return WI.Cookie.SameSiteType.None;}
static parseSetCookieResponseHeader(header)
{if(!header)
return null;
let nameValueMatch=header.match(/^(?<name>[^\s=]+)[ \t]*=[ \t]*(?<value>[^;]*)/);if(!nameValueMatch){WI.reportInternalError("Failed to parse Set-Cookie header",{header});return null;}
let{name,value}=nameValueMatch.groups;let expires=null;let session=false;let maxAge=null;let path=null;let domain=null;let secure=false;let httpOnly=false;let sameSite=WI.Cookie.SameSiteType.None; let remaining=header.substr(nameValueMatch[0].length);let attributes=remaining.split(/; ?/);for(let attribute of attributes){if(!attribute)
continue;let match=attribute.match(/^(?<name>[^\s=]+)(?:=(?<value>.*))?$/);if(!match){console.error("Failed to parse Set-Cookie attribute:",attribute);continue;}
let attributeName=match.groups.name;let attributeValue=match.groups.value;switch(attributeName.toLowerCase()){case"expires":expires=new Date(attributeValue);if(isNaN(expires.getTime())){console.warn("Invalid Expires date:",attributeValue);expires=null;}
break;case"max-age":maxAge=parseInt(attributeValue,10);if(isNaN(maxAge)||!/^\d+$/.test(attributeValue)){console.warn("Invalid MaxAge value:",attributeValue);maxAge=null;}
break;case"path":path=attributeValue;break;case"domain":domain=attributeValue;break;case"secure":secure=true;break;case"httponly":httpOnly=true;break;case"samesite":sameSite=WI.Cookie.parseSameSiteAttributeValue(attributeValue);break;default:console.warn("Unknown Cookie attribute:",attribute);break;}}
if(!expires)
session=true;return new WI.Cookie(WI.Cookie.Type.Response,name,value,{header,expires,session,maxAge,path,domain,secure,httpOnly,sameSite});} 
get type(){return this._type;}
get name(){return this._name;}
get value(){return this._value;}
get header(){return this._header;}
get expires(){return this._expires;}
get session(){return this._session;}
get maxAge(){return this._maxAge;}
get path(){return this._path;}
get domain(){return this._domain;}
get secure(){return this._secure;}
get httpOnly(){return this._httpOnly;}
get sameSite(){return this._sameSite;}
get size(){return this._size;}
get url()
{let url=this._secure?"https://":"http://";url+=this._domain||"";url+=this._path||"";return url;}
expirationDate(requestSentDate)
{if(this._session)
return null;if(this._maxAge){let startDate=requestSentDate||new Date;return new Date(startDate.getTime()+(this._maxAge*1000));}
return this._expires;}
equals(other)
{return this._type===other.type&&this._name===other.name&&this._value===other.value&&this._header===other.header&&this._expires?.getTime()===other.expires?.getTime()&&this._session===other.session&&this._maxAge===other.maxAge&&this._path===other.path&&this._domain===other.domain&&this._secure===other.secure&&this._httpOnly===other.httpOnly&&this._sameSite===other.sameSite;}
toProtocol()
{if(typeof this._name!=="string")
return null;if(typeof this._value!=="string")
return null;if(typeof this._domain!=="string")
return null;if(typeof this._path!=="string")
return null;if(!this._session&&!this._expires)
return null;if(!Object.values(WI.Cookie.SameSiteType).includes(this._sameSite))
return null;let json={name:this._name,value:this._value,domain:this._domain,path:this._path,expires:this._expires?.getTime(),session:this._session,httpOnly:!!this._httpOnly,secure:!!this._secure,sameSite:this._sameSite,};return json;}};WI.Cookie.Type={Request:"request",Response:"response",};WI.Cookie.SameSiteType={None:"None",Lax:"Lax",Strict:"Strict",};WI.CookieStorageObject=class CookieStorageObject
{constructor(host)
{this._host=host;} 
static cookieMatchesResourceURL(cookie,resourceURL)
{var parsedURL=parseURL(resourceURL);if(!parsedURL||!WI.CookieStorageObject.cookieDomainMatchesResourceDomain(cookie.domain,parsedURL.host))
return false;return parsedURL.path.startsWith(cookie.path)&&(!cookie.port||parsedURL.port===cookie.port)&&(!cookie.secure||parsedURL.scheme==="https");}
static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain)
{if(cookieDomain.charAt(0)!==".")
return resourceDomain===cookieDomain;return!!resourceDomain.match(new RegExp("^(?:[^\\.]+\\.)*"+cookieDomain.substring(1).escapeForRegExp()+"$"),"i");} 
get host()
{return this._host;}
saveIdentityToCookie(cookie)
{cookie[WI.CookieStorageObject.CookieHostCookieKey]=this.host;}};WI.CookieStorageObject.TypeIdentifier="cookie-storage";WI.CookieStorageObject.CookieHostCookieKey="cookie-storage-host";WI.DOMBreakpoint=class DOMBreakpoint extends WI.Breakpoint
{constructor(domNodeOrInfo,type,{disabled,actions,condition,ignoreCount,autoContinue}={})
{super({disabled,actions,condition,ignoreCount,autoContinue});if(domNodeOrInfo instanceof WI.DOMNode){this._domNode=domNodeOrInfo;this._path=domNodeOrInfo.path();this._url=WI.networkManager.mainFrame.url;}else if(domNodeOrInfo&&typeof domNodeOrInfo==="object"){this._domNode=null;this._path=domNodeOrInfo.path;this._url=domNodeOrInfo.url;}
this._type=type;} 
static displayNameForType(type)
{switch(type){case WI.DOMBreakpoint.Type.SubtreeModified:return WI.UIString("Subtree Modified","Subtree Modified @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before child DOM node is modified");case WI.DOMBreakpoint.Type.AttributeModified:return WI.UIString("Attribute Modified","Attribute Modified @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before DOM attribute is modified");case WI.DOMBreakpoint.Type.NodeRemoved:return WI.UIString("Node Removed","Node Removed @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before DOM node is removed");}
return WI.UIString("DOM");}
static fromJSON(json)
{return new WI.DOMBreakpoint(json,json.type,{disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} 
get type(){return this._type;}
get url(){return this._url;}
get path(){return this._path;}
get displayName()
{return WI.DOMBreakpoint.displayNameForType(this._type);}
get editable()
{return InspectorBackend.hasCommand("DOMDebugger.setDOMBreakpoint","options");}
get domNode()
{return this._domNode;}
set domNode(domNode)
{if(!xor(domNode,this._domNode))
return;this.dispatchEventToListeners(WI.DOMBreakpoint.Event.DOMNodeWillChange);this._domNode=domNode;this.dispatchEventToListeners(WI.DOMBreakpoint.Event.DOMNodeDidChange);}
remove()
{super.remove();WI.domDebuggerManager.removeDOMBreakpoint(this);}
saveIdentityToCookie(cookie)
{cookie["dom-breakpoint-url"]=this._url;cookie["dom-breakpoint-path"]=this._path;cookie["dom-breakpoint-type"]=this._type;}
toJSON(key)
{let json=super.toJSON(key);json.url=this._url;json.path=this._path;json.type=this._type;if(key===WI.ObjectStore.toJSONSymbol)
json[WI.objectStores.domBreakpoints.keyPath]=this._url+":"+this._path+":"+this._type;return json;}};WI.DOMBreakpoint.Type={SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed",};WI.DOMBreakpoint.Event={DOMNodeDidChange:"dom-breakpoint-dom-node-did-change",DOMNodeWillChange:"dom-breakpoint-dom-node-will-change",};WI.DOMBreakpoint.ReferencePage=WI.ReferencePage.DOMBreakpoints;WI.DOMNode=class DOMNode extends WI.Object
{constructor(domManager,doc,isInShadowTree,payload)
{super();this._destroyed=false;this._domManager=domManager;this._isInShadowTree=isInShadowTree;this.id=payload.nodeId;this._domManager._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._computedRole=null;this._contentSecurityPolicyHash=payload.contentSecurityPolicyHash;this._layoutContextType=null;if(this._nodeType===Node.DOCUMENT_NODE)
this.ownerDocument=this;else
this.ownerDocument=doc;this._frame=null;if(InspectorBackend.hasDomain("Audit")){if(payload.frameId)
this._frame=WI.networkManager.frameForIdentifier(payload.frameId);}
if(!this._frame&&this.ownerDocument)
this._frame=WI.networkManager.frameForIdentifier(this.ownerDocument.frameIdentifier);this._attributes=[];this._attributesMap=new Map;if(payload.attributes)
this._setAttributesPayload(payload.attributes);this._childNodeCount=payload.childNodeCount;this._children=null;this._nextSibling=null;this._previousSibling=null;this.parentNode=null;this._enabledPseudoClasses=[];

this._shadowRoots=[];if(payload.shadowRoots){for(var i=0;i<payload.shadowRoots.length;++i){var root=payload.shadowRoots[i];var node=new WI.DOMNode(this._domManager,this.ownerDocument,true,root);node.parentNode=this;this._shadowRoots.push(node);}}
if(payload.children)
this._setChildrenPayload(payload.children);else if(this._shadowRoots.length&&!this._childNodeCount)
this._children=this._shadowRoots.slice();if(this._nodeType===Node.ELEMENT_NODE)
this._customElementState=payload.customElementState||WI.DOMNode.CustomElementState.Builtin;else
this._customElementState=null;if(payload.templateContent){this._templateContent=new WI.DOMNode(this._domManager,this.ownerDocument,false,payload.templateContent);this._templateContent.parentNode=this;}
this._pseudoElements=new Map;if(payload.pseudoElements){for(var i=0;i<payload.pseudoElements.length;++i){var node=new WI.DOMNode(this._domManager,this.ownerDocument,this._isInShadowTree,payload.pseudoElements[i]);node.parentNode=this;this._pseudoElements.set(node.pseudoType(),node);}}
if(payload.contentDocument){this._contentDocument=new WI.DOMNode(this._domManager,null,false,payload.contentDocument);this._children=[this._contentDocument];this._renumber();}
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;if(payload.documentURL)
this.documentURL=payload.documentURL;}else if(this._nodeType===Node.DOCUMENT_TYPE_NODE){this.publicId=payload.publicId;this.systemId=payload.systemId;}else if(this._nodeType===Node.DOCUMENT_NODE){this.documentURL=payload.documentURL;this.xmlVersion=payload.xmlVersion;}else if(this._nodeType===Node.ATTRIBUTE_NODE){this.name=payload.name;this.value=payload.value;}
this._domEvents=[];this._powerEfficientPlaybackRanges=[];if(this.isMediaElement())
WI.DOMNode.addEventListener(WI.DOMNode.Event.DidFireEvent,this._handleDOMNodeDidFireEvent,this);this.layoutContextType=payload.layoutContextType;} 
static getFullscreenDOMEvents(domEvents)
{return domEvents.reduce((accumulator,current)=>{if(current.eventName==="webkitfullscreenchange"&&current.data&&(!accumulator.length||accumulator.lastValue.data.enabled!==current.data.enabled))
accumulator.push(current);return accumulator;},[]);}
static isPlayEvent(eventName)
{return eventName==="play"||eventName==="playing";}
static isPauseEvent(eventName)
{return eventName==="pause"||eventName==="stall";}
static isStopEvent(eventName)
{return eventName==="emptied"||eventName==="ended"||eventName==="suspend";} 
get destroyed(){return this._destroyed;}
get frame(){return this._frame;}
get nextSibling(){return this._nextSibling;}
get previousSibling(){return this._previousSibling;}
get children(){return this._children;}
get domEvents(){return this._domEvents;}
get powerEfficientPlaybackRanges(){return this._powerEfficientPlaybackRanges;}
get attached()
{if(this._destroyed)
return false;for(let node=this;node;node=node.parentNode){if(node.ownerDocument===node)
return true;}
return false;}
get firstChild()
{var children=this.children;if(children&&children.length>0)
return children[0];return null;}
get lastChild()
{var children=this.children;if(children&&children.length>0)
return children.lastValue;return null;}
get childNodeCount()
{var children=this.children;if(children)
return children.length;return this._childNodeCount+this._shadowRoots.length;}
set childNodeCount(count)
{this._childNodeCount=count;}
get layoutContextType()
{return this._layoutContextType;}
set layoutContextType(layoutContextType)
{layoutContextType||=null;if(layoutContextType===this._layoutContextType)
return;this._layoutContextType=layoutContextType;this.dispatchEventToListeners(WI.DOMNode.Event.LayoutContextTypeChanged);}
markDestroyed()
{this._destroyed=true;this.layoutContextType=null;}
computedRole()
{return this._computedRole;}
contentSecurityPolicyHash()
{return this._contentSecurityPolicyHash;}
hasAttributes()
{return this._attributes.length>0;}
hasChildNodes()
{return this.childNodeCount>0;}
hasShadowRoots()
{return!!this._shadowRoots.length;}
isInShadowTree()
{return this._isInShadowTree;}
isInUserAgentShadowTree()
{return this._isInShadowTree&&this.ancestorShadowRoot().isUserAgentShadowRoot();}
isCustomElement()
{return this._customElementState===WI.DOMNode.CustomElementState.Custom;}
customElementState()
{return this._customElementState;}
isShadowRoot()
{return!!this._shadowRootType;}
isUserAgentShadowRoot()
{return this._shadowRootType===WI.DOMNode.ShadowRootType.UserAgent;}
ancestorShadowRoot()
{if(!this._isInShadowTree)
return null;let node=this;while(node&&!node.isShadowRoot())
node=node.parentNode;return node;}
ancestorShadowHost()
{let shadowRoot=this.ancestorShadowRoot();return shadowRoot?shadowRoot.parentNode:null;}
isPseudoElement()
{return this._pseudoType!==undefined;}
nodeType()
{return this._nodeType;}
nodeName()
{return this._nodeName;}
nodeNameInCorrectCase()
{return this.isXMLNode()?this.nodeName():this.nodeName().toLowerCase();}
setNodeName(name,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.setNodeName(this.id,name,this._makeUndoableCallback(callback));}
localName()
{return this._localName;}
templateContent()
{return this._templateContent||null;}
pseudoType()
{return this._pseudoType;}
hasPseudoElements()
{return this._pseudoElements.size>0;}
pseudoElements()
{return this._pseudoElements;}
beforePseudoElement()
{return this._pseudoElements.get(WI.DOMNode.PseudoElementType.Before)||null;}
afterPseudoElement()
{return this._pseudoElements.get(WI.DOMNode.PseudoElementType.After)||null;}
shadowRoots()
{return this._shadowRoots;}
shadowRootType()
{return this._shadowRootType;}
nodeValue()
{return this._nodeValue;}
setNodeValue(value,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.setNodeValue(this.id,value,this._makeUndoableCallback(callback));}
getAttribute(name)
{let attr=this._attributesMap.get(name);return attr?attr.value:undefined;}
setAttribute(name,text,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.setAttributesAsText(this.id,text,name,this._makeUndoableCallback(callback));}
setAttributeValue(name,value,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.setAttributeValue(this.id,name,value,this._makeUndoableCallback(callback));}
attributes()
{return this._attributes;}
removeAttribute(name,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
function mycallback(error,success)
{if(!error){this._attributesMap.delete(name);for(var i=0;i<this._attributes.length;++i){if(this._attributes[i].name===name){this._attributes.splice(i,1);break;}}}
this._makeUndoableCallback(callback)(error);}
let target=WI.assumingMainTarget();target.DOMAgent.removeAttribute(this.id,name,mycallback.bind(this));}
toggleClass(className,flag)
{if(!className||!className.length)
return;if(this.isPseudoElement()){this.parentNode.toggleClass(className,flag);return;}
if(this.nodeType()!==Node.ELEMENT_NODE)
return;WI.RemoteObject.resolveNode(this).then((object)=>{function inspectedPage_node_toggleClass(className,flag){this.classList.toggle(className,flag);}
object.callFunction(inspectedPage_node_toggleClass,[className,flag]);object.release();});}
querySelector(selector,callback)
{let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed)
return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.querySelector(this.id,selector).then(({nodeId})=>nodeId);}
if(this._destroyed){callback("ERROR: node is destroyed");return;}
target.DOMAgent.querySelector(this.id,selector,WI.DOMManager.wrapClientCallback(callback));}
querySelectorAll(selector,callback)
{let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed)
return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.querySelectorAll(this.id,selector).then(({nodeIds})=>nodeIds);}
if(this._destroyed){callback("ERROR: node is destroyed");return;}
target.DOMAgent.querySelectorAll(this.id,selector,WI.DOMManager.wrapClientCallback(callback));}
highlight(mode)
{if(this._destroyed)
return;if(this._hideDOMNodeHighlightTimeout){clearTimeout(this._hideDOMNodeHighlightTimeout);this._hideDOMNodeHighlightTimeout=undefined;}
let target=WI.assumingMainTarget();target.DOMAgent.highlightNode(WI.DOMManager.buildHighlightConfig(mode),this.id);}
scrollIntoView()
{WI.RemoteObject.resolveNode(this).then((object)=>{function inspectedPage_node_scrollIntoView(){this.scrollIntoViewIfNeeded(true);}
object.callFunction(inspectedPage_node_scrollIntoView);object.release();});}
getChildNodes(callback)
{if(this.children){if(callback)
callback(this.children);return;}
if(this._destroyed){callback(this.children);return;}
function mycallback(error){if(!error&&callback)
callback(this.children);}
let target=WI.assumingMainTarget();target.DOMAgent.requestChildNodes(this.id,mycallback.bind(this));}
getSubtree(depth,callback)
{if(this._destroyed){callback(this.children);return;}
function mycallback(error)
{if(callback)
callback(error?null:this.children);}
let target=WI.assumingMainTarget();target.DOMAgent.requestChildNodes(this.id,depth,mycallback.bind(this));}
getOuterHTML(callback)
{let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed)
return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.getOuterHTML(this.id).then(({outerHTML})=>outerHTML);}
if(this._destroyed){callback("ERROR: node is destroyed");return;}
target.DOMAgent.getOuterHTML(this.id,callback);}
setOuterHTML(html,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.setOuterHTML(this.id,html,this._makeUndoableCallback(callback));}
insertAdjacentHTML(position,html)
{if(this._destroyed)
return;if(this.nodeType()!==Node.ELEMENT_NODE)
return;let target=WI.assumingMainTarget();if(!target.hasCommand("DOM.insertAdjacentHTML")){WI.RemoteObject.resolveNode(this).then((object)=>{function inspectedPage_node_insertAdjacentHTML(position,html){this.insertAdjacentHTML(position,html);}
object.callFunction(inspectedPage_node_insertAdjacentHTML,[position,html]);object.release();});return;}
target.DOMAgent.insertAdjacentHTML(this.id,position,html,this._makeUndoableCallback());}
removeNode(callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.removeNode(this.id,this._makeUndoableCallback(callback));}
getEventListeners(callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.getEventListenersForNode(this.id,callback);}
accessibilityProperties(callback)
{if(this._destroyed){callback({});return;}
function accessibilityPropertiesCallback(error,accessibilityProperties)
{if(!error&&callback&&accessibilityProperties){this._computedRole=accessibilityProperties.role;callback({activeDescendantNodeId:accessibilityProperties.activeDescendantNodeId,busy:accessibilityProperties.busy,checked:accessibilityProperties.checked,childNodeIds:accessibilityProperties.childNodeIds,controlledNodeIds:accessibilityProperties.controlledNodeIds,current:accessibilityProperties.current,disabled:accessibilityProperties.disabled,exists:accessibilityProperties.exists,expanded:accessibilityProperties.expanded,flowedNodeIds:accessibilityProperties.flowedNodeIds,focused:accessibilityProperties.focused,ignored:accessibilityProperties.ignored,ignoredByDefault:accessibilityProperties.ignoredByDefault,invalid:accessibilityProperties.invalid,isPopupButton:accessibilityProperties.isPopUpButton,headingLevel:accessibilityProperties.headingLevel,hierarchyLevel:accessibilityProperties.hierarchyLevel,hidden:accessibilityProperties.hidden,label:accessibilityProperties.label,liveRegionAtomic:accessibilityProperties.liveRegionAtomic,liveRegionRelevant:accessibilityProperties.liveRegionRelevant,liveRegionStatus:accessibilityProperties.liveRegionStatus,mouseEventNodeId:accessibilityProperties.mouseEventNodeId,nodeId:accessibilityProperties.nodeId,ownedNodeIds:accessibilityProperties.ownedNodeIds,parentNodeId:accessibilityProperties.parentNodeId,pressed:accessibilityProperties.pressed,readonly:accessibilityProperties.readonly,required:accessibilityProperties.required,role:accessibilityProperties.role,selected:accessibilityProperties.selected,selectedChildNodeIds:accessibilityProperties.selectedChildNodeIds});}}
let target=WI.assumingMainTarget();target.DOMAgent.getAccessibilityPropertiesForNode(this.id,accessibilityPropertiesCallback.bind(this));}
path()
{var path=[];var node=this;while(node&&"index"in node&&node._nodeName.length){path.push([node.index,node._nodeName]);node=node.parentNode;}
path.reverse();return path.join(",");}
get escapedIdSelector()
{return this._idSelector(true);}
get escapedClassSelector()
{return this._classSelector(true);}
get displayName()
{if(this.isPseudoElement())
return"::"+this._pseudoType;return this.nodeNameInCorrectCase()+this.escapedIdSelector+this.escapedClassSelector;}
get unescapedSelector()
{if(this.isPseudoElement())
return"::"+this._pseudoType;const shouldEscape=false;return this.nodeNameInCorrectCase()+this._idSelector(shouldEscape)+this._classSelector(shouldEscape);}
appropriateSelectorFor(justSelector)
{if(this.isPseudoElement())
return this.parentNode.appropriateSelectorFor()+"::"+this._pseudoType;let lowerCaseName=this.localName()||this.nodeName().toLowerCase();let id=this.escapedIdSelector;if(id.length)
return justSelector?id:lowerCaseName+id;let classes=this.escapedClassSelector;if(classes.length)
return justSelector?classes:lowerCaseName+classes;if(lowerCaseName==="input"&&this.getAttribute("type"))
return lowerCaseName+"[type=\""+this.getAttribute("type")+"\"]";return lowerCaseName;}
isAncestor(node)
{if(!node)
return false;var currentNode=node.parentNode;while(currentNode){if(this===currentNode)
return true;currentNode=currentNode.parentNode;}
return false;}
isDescendant(descendant)
{return descendant!==null&&descendant.isAncestor(this);}
get ownerSVGElement()
{if(this._nodeName==="svg")
return this;if(!this.parentNode)
return null;return this.parentNode.ownerSVGElement;}
isSVGElement()
{return!!this.ownerSVGElement;}
isMediaElement()
{let lowerCaseName=this.localName()||this.nodeName().toLowerCase();return lowerCaseName==="video"||lowerCaseName==="audio";}
didFireEvent(eventName,timestamp,data)
{this._addDOMEvent({eventName,timestamp:WI.timelineManager.computeElapsedTime(timestamp),data,});}
powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient)
{let lastValue=this._powerEfficientPlaybackRanges.lastValue;if(isPowerEfficient){if(!lastValue||lastValue.endTimestamp)
this._powerEfficientPlaybackRanges.push({startTimestamp:timestamp});}else{if(!lastValue)
this._powerEfficientPlaybackRanges.push({endTimestamp:timestamp});else if(lastValue.startTimestamp)
lastValue.endTimestamp=timestamp;}
this.dispatchEventToListeners(DOMNode.Event.PowerEfficientPlaybackStateChanged,{isPowerEfficient,timestamp});}
canEnterPowerEfficientPlaybackState()
{return this.localName()==="video"||this.nodeName().toLowerCase()==="video";}
_handleDOMNodeDidFireEvent(event)
{if(event.target===this||!event.target.isAncestor(this))
return;let domEvent=Object.shallowCopy(event.data.domEvent);domEvent.originator=event.target;this._addDOMEvent(domEvent);}
_addDOMEvent(domEvent)
{this._domEvents.push(domEvent);this.dispatchEventToListeners(WI.DOMNode.Event.DidFireEvent,{domEvent});}
_setAttributesPayload(attrs)
{this._attributes=[];this._attributesMap=new Map;for(var i=0;i<attrs.length;i+=2)
this._addAttribute(attrs[i],attrs[i+1]);}
_insertChild(prev,payload)
{var node=new WI.DOMNode(this._domManager,this.ownerDocument,this._isInShadowTree,payload);if(!prev){if(!this._children){ this._children=this._shadowRoots.concat([node]);}else
this._children.unshift(node);}else
this._children.splice(this._children.indexOf(prev)+1,0,node);this._renumber();return node;}
_removeChild(node)
{if(node.isPseudoElement()){this._pseudoElements.delete(node.pseudoType());node.parentNode=null;}else{this._children.splice(this._children.indexOf(node),1);node.parentNode=null;this._renumber();}}
_setChildrenPayload(payloads)
{if(this._contentDocument)
return;this._children=this._shadowRoots.slice();for(var i=0;i<payloads.length;++i){var node=new WI.DOMNode(this._domManager,this.ownerDocument,this._isInShadowTree,payloads[i]);this._children.push(node);}
this._renumber();}
_renumber()
{var childNodeCount=this._children.length;if(childNodeCount===0)
return;for(var i=0;i<childNodeCount;++i){var child=this._children[i];child.index=i;child._nextSibling=i+1<childNodeCount?this._children[i+1]:null;child._previousSibling=i-1>=0?this._children[i-1]:null;child.parentNode=this;}}
_addAttribute(name,value)
{let attr={name,value,_node:this};this._attributesMap.set(name,attr);this._attributes.push(attr);}
_setAttribute(name,value)
{let attr=this._attributesMap.get(name);if(attr)
attr.value=value;else
this._addAttribute(name,value);}
_removeAttribute(name)
{let attr=this._attributesMap.get(name);if(attr){this._attributes.remove(attr);this._attributesMap.delete(name);}}
moveTo(targetNode,anchorNode,callback)
{if(this._destroyed){callback("ERROR: node is destroyed");return;}
let target=WI.assumingMainTarget();target.DOMAgent.moveTo(this.id,targetNode.id,anchorNode?anchorNode.id:undefined,this._makeUndoableCallback(callback));}
isXMLNode()
{return!!this.ownerDocument&&!!this.ownerDocument.xmlVersion;}
get enabledPseudoClasses()
{return this._enabledPseudoClasses;}
setPseudoClassEnabled(pseudoClass,enabled)
{var pseudoClasses=this._enabledPseudoClasses;if(enabled){if(pseudoClasses.includes(pseudoClass))
return;pseudoClasses.push(pseudoClass);}else{if(!pseudoClasses.includes(pseudoClass))
return;pseudoClasses.remove(pseudoClass);}
function changed(error)
{if(!error)
this.dispatchEventToListeners(WI.DOMNode.Event.EnabledPseudoClassesChanged);}
let target=WI.assumingMainTarget();target.CSSAgent.forcePseudoState(this.id,pseudoClasses,changed.bind(this));}
_makeUndoableCallback(callback)
{return(...args)=>{if(!args[0]){ let target=WI.assumingMainTarget();if(target.hasCommand("DOM.markUndoableState"))
target.DOMAgent.markUndoableState();}
if(callback)
callback.apply(null,args);};}
_idSelector(shouldEscape)
{let id=this.getAttribute("id");if(!id)
return"";id=id.trim();if(!id.length)
return"";if(shouldEscape)
id=CSS.escape(id);if(/[\s'"]/.test(id))
return`[id="${id}"]`;return`#${id}`;}
_classSelector(shouldEscape){let classes=this.getAttribute("class");if(!classes)
return"";classes=classes.trim();if(!classes.length)
return"";let foundClasses=new Set;return classes.split(/\s+/).reduce((selector,className)=>{if(!className.length||foundClasses.has(className))
return selector;foundClasses.add(className);return`${selector}.${(shouldEscape ? CSS.escape(className) : className)}`;},"");}};WI.DOMNode.Event={EnabledPseudoClassesChanged:"dom-node-enabled-pseudo-classes-did-change",AttributeModified:"dom-node-attribute-modified",AttributeRemoved:"dom-node-attribute-removed",EventListenersChanged:"dom-node-event-listeners-changed",DidFireEvent:"dom-node-did-fire-event",PowerEfficientPlaybackStateChanged:"dom-node-power-efficient-playback-state-changed",LayoutContextTypeChanged:"dom-node-layout-context-type-changed",};WI.DOMNode.PseudoElementType={Before:"before",After:"after",};WI.DOMNode.ShadowRootType={UserAgent:"user-agent",Closed:"closed",Open:"open",};WI.DOMNode.CustomElementState={Builtin:"builtin",Custom:"custom",Waiting:"waiting",Failed:"failed",};WI.DOMNode.LayoutContextType={Grid:"grid",};WI.DOMNodeStyles=class DOMNodeStyles extends WI.Object
{constructor(node)
{super();this._node=node||null;this._rulesMap=new Map;this._stylesMap=new Multimap;this._matchedRules=[];this._inheritedRules=[];this._pseudoElements=new Map;this._inlineStyle=null;this._attributesStyle=null;this._computedStyle=null;this._orderedStyles=[];this._computedPrimaryFont=null;this._propertyNameToEffectivePropertyMap={};this._usedCSSVariables=new Set;this._allCSSVariables=new Set;this._pendingRefreshTask=null;this.refresh();this._trackedStyleSheets=new WeakSet;WI.CSSStyleSheet.addEventListener(WI.CSSStyleSheet.Event.ContentDidChange,this._handleCSSStyleSheetContentDidChange,this);} 
static parseSelectorListPayload(selectorList)
{let selectors=selectorList.selectors;if(!selectors.length)
return[];return selectors.map(function(selectorPayload){return new WI.CSSSelector(selectorPayload.text,selectorPayload.specificity,selectorPayload.dynamic);});}
static createSourceCodeLocation(sourceURL,{line,column,documentNode}={})
{if(!sourceURL)
return null;let sourceCode=null;if(documentNode){let mainResource=WI.networkManager.resourcesForURL(documentNode.documentURL).firstValue;if(mainResource){let parentFrame=mainResource.parentFrame;sourceCode=parentFrame.resourcesForURL(sourceURL).firstValue;}}
if(!sourceCode)
sourceCode=WI.networkManager.resourcesForURL(sourceURL).firstValue;if(!sourceCode)
return null;return sourceCode.createSourceCodeLocation(line||0,column||0);}
static uniqueOrderedStyles(orderedStyles)
{let uniqueOrderedStyles=[];for(let style of orderedStyles){let rule=style.ownerRule;if(!rule){uniqueOrderedStyles.push(style);continue;}
let found=false;for(let existingStyle of uniqueOrderedStyles){if(rule.isEqualTo(existingStyle.ownerRule)){found=true;break;}}
if(!found)
uniqueOrderedStyles.push(style);}
return uniqueOrderedStyles;} 
get node(){return this._node;}
get matchedRules(){return this._matchedRules;}
get inheritedRules(){return this._inheritedRules;}
get inlineStyle(){return this._inlineStyle;}
get attributesStyle(){return this._attributesStyle;}
get pseudoElements(){return this._pseudoElements;}
get computedStyle(){return this._computedStyle;}
get orderedStyles(){return this._orderedStyles;}
get computedPrimaryFont(){return this._computedPrimaryFont;}
get usedCSSVariables(){return this._usedCSSVariables;}
get allCSSVariables(){return this._allCSSVariables;}
get needsRefresh()
{return this._pendingRefreshTask||this._needsRefresh;}
get uniqueOrderedStyles()
{return WI.DOMNodeStyles.uniqueOrderedStyles(this._orderedStyles);}
refreshIfNeeded()
{if(this._pendingRefreshTask)
return this._pendingRefreshTask;if(!this._needsRefresh)
return Promise.resolve(this);return this.refresh();}
refresh()
{if(this._pendingRefreshTask)
return this._pendingRefreshTask;this._needsRefresh=false;let fetchedMatchedStylesPromise=new WI.WrappedPromise;let fetchedInlineStylesPromise=new WI.WrappedPromise;let fetchedComputedStylesPromise=new WI.WrappedPromise;let fetchedFontDataPromise=new WI.WrappedPromise;function wrap(func,promise){return(...args)=>{try{func.apply(this,args);}catch(e){console.error(e);promise.resolve();}};}
let parseRuleMatchArrayPayload=(matchArray,node,inherited,pseudoId)=>{var result=[];var ruleOccurrences={};for(var i=matchArray.length-1;i>=0;--i){var rule=this._parseRulePayload(matchArray[i].rule,matchArray[i].matchingSelectors,node,inherited,pseudoId,ruleOccurrences);if(!rule)
continue;result.push(rule);}
return result;};function fetchedMatchedStyles(error,matchedRulesPayload,pseudoElementRulesPayload,inheritedRulesPayload)
{matchedRulesPayload=matchedRulesPayload||[];pseudoElementRulesPayload=pseudoElementRulesPayload||[];inheritedRulesPayload=inheritedRulesPayload||[];this._previousStylesMap=this._stylesMap;this._stylesMap=new Multimap;this._matchedRules=parseRuleMatchArrayPayload(matchedRulesPayload,this._node);this._pseudoElements.clear();for(let{pseudoId,matches}of pseudoElementRulesPayload){let pseudoElementRules=parseRuleMatchArrayPayload(matches,this._node,false,pseudoId);this._pseudoElements.set(pseudoId,{matchedRules:pseudoElementRules});}
this._inheritedRules=[];var i=0;var currentNode=this._node.parentNode;while(currentNode&&i<inheritedRulesPayload.length){var inheritedRulePayload=inheritedRulesPayload[i];var inheritedRuleInfo={node:currentNode};inheritedRuleInfo.inlineStyle=inheritedRulePayload.inlineStyle?this._parseStyleDeclarationPayload(inheritedRulePayload.inlineStyle,currentNode,true,null,WI.CSSStyleDeclaration.Type.Inline):null;inheritedRuleInfo.matchedRules=inheritedRulePayload.matchedCSSRules?parseRuleMatchArrayPayload(inheritedRulePayload.matchedCSSRules,currentNode,true):[];if(inheritedRuleInfo.inlineStyle||inheritedRuleInfo.matchedRules.length)
this._inheritedRules.push(inheritedRuleInfo);currentNode=currentNode.parentNode;++i;}
fetchedMatchedStylesPromise.resolve();}
function fetchedInlineStyles(error,inlineStylePayload,attributesStylePayload)
{this._inlineStyle=inlineStylePayload?this._parseStyleDeclarationPayload(inlineStylePayload,this._node,false,null,WI.CSSStyleDeclaration.Type.Inline):null;this._attributesStyle=attributesStylePayload?this._parseStyleDeclarationPayload(attributesStylePayload,this._node,false,null,WI.CSSStyleDeclaration.Type.Attribute):null;this._updateStyleCascade();fetchedInlineStylesPromise.resolve();}
function fetchedComputedStyle(error,computedPropertiesPayload)
{var properties=[];for(var i=0;computedPropertiesPayload&&i<computedPropertiesPayload.length;++i){var propertyPayload=computedPropertiesPayload[i];var canonicalName=WI.cssManager.canonicalNameForPropertyName(propertyPayload.name);propertyPayload.implicit=!this._propertyNameToEffectivePropertyMap[canonicalName];var property=this._parseStylePropertyPayload(propertyPayload,NaN,this._computedStyle);if(!property.implicit)
property.implicit=!this._isPropertyFoundInMatchingRules(property.name);properties.push(property);}
if(this._computedStyle)
this._computedStyle.update(null,properties);else
this._computedStyle=new WI.CSSStyleDeclaration(this,null,null,WI.CSSStyleDeclaration.Type.Computed,this._node,false,null,properties);let significantChange=false;for(let[key,styles]of this._stylesMap.sets()){let previousStyles=this._previousStylesMap.get(key);if(previousStyles){
let styleFound=false;for(let style of styles){if(previousStyles.has(style)){styleFound=true;break;}}
if(styleFound)
continue;}
if(!this._includeUserAgentRulesOnNextRefresh){let firstStyle=styles.firstValue;if(firstStyle&&firstStyle.ownerRule&&firstStyle.ownerRule.type===WI.CSSStyleSheet.Type.UserAgent){

 continue;}}
significantChange=true;break;}
if(!significantChange){for(let[key,previousStyles]of this._previousStylesMap.sets()){if(this._stylesMap.has(key))
continue;if(!this._includeUserAgentRulesOnNextRefresh){let firstStyle=previousStyles.firstValue;if(firstStyle&&firstStyle.ownerRule&&firstStyle.ownerRule.type===WI.CSSStyleSheet.Type.UserAgent)
continue;}
significantChange=true;break;}}
this._previousStylesMap=null;this._includeUserAgentRulesOnNextRefresh=false;fetchedComputedStylesPromise.resolve({significantChange});}
function fetchedFontData(error,fontDataPayload)
{if(fontDataPayload)
this._computedPrimaryFont=WI.Font.fromPayload(fontDataPayload);else
this._computedPrimaryFont=null;fetchedFontDataPromise.resolve();}
let target=WI.assumingMainTarget();target.CSSAgent.getMatchedStylesForNode.invoke({nodeId:this._node.id,includePseudo:true,includeInherited:true},wrap.call(this,fetchedMatchedStyles,fetchedMatchedStylesPromise));target.CSSAgent.getInlineStylesForNode.invoke({nodeId:this._node.id},wrap.call(this,fetchedInlineStyles,fetchedInlineStylesPromise));target.CSSAgent.getComputedStyleForNode.invoke({nodeId:this._node.id},wrap.call(this,fetchedComputedStyle,fetchedComputedStylesPromise));if(InspectorBackend.hasCommand("CSS.getFontDataForNode"))
target.CSSAgent.getFontDataForNode.invoke({nodeId:this._node.id},wrap.call(this,fetchedFontData,fetchedFontDataPromise));else
fetchedFontDataPromise.resolve();this._pendingRefreshTask=Promise.all([fetchedComputedStylesPromise.promise,fetchedMatchedStylesPromise.promise,fetchedInlineStylesPromise.promise,fetchedFontDataPromise.promise]).then(([fetchComputedStylesResult])=>{this._pendingRefreshTask=null;this.dispatchEventToListeners(WI.DOMNodeStyles.Event.Refreshed,{significantChange:fetchComputedStylesResult.significantChange,});return this;});return this._pendingRefreshTask;}
addRule(selector,text,styleSheetId)
{selector=selector||this._node.appropriateSelectorFor(true);let target=WI.assumingMainTarget();function completed()
{target.DOMAgent.markUndoableState();this.refresh();}
function styleChanged(error,stylePayload)
{if(error)
return;completed.call(this);}
function addedRule(error,rulePayload)
{if(error)
return;if(!text||!text.length){completed.call(this);return;}
target.CSSAgent.setStyleText(rulePayload.style.styleId,text,styleChanged.bind(this));}
function inspectorStyleSheetAvailable(styleSheet)
{if(!styleSheet)
return;target.CSSAgent.addRule(styleSheet.id,selector,addedRule.bind(this));}
if(styleSheetId)
inspectorStyleSheetAvailable.call(this,WI.cssManager.styleSheetForIdentifier(styleSheetId));else
WI.cssManager.preferredInspectorStyleSheetForFrame(this._node.frame,inspectorStyleSheetAvailable.bind(this));}
effectivePropertyForName(name)
{let property=this._propertyNameToEffectivePropertyMap[name];if(property)
return property;let canonicalName=WI.cssManager.canonicalNameForPropertyName(name);return this._propertyNameToEffectivePropertyMap[canonicalName]||null;} 
mediaQueryResultDidChange()
{this._markAsNeedsRefresh();}
pseudoClassesDidChange(node)
{this._includeUserAgentRulesOnNextRefresh=true;this._markAsNeedsRefresh();}
attributeDidChange(node,attributeName)
{this._markAsNeedsRefresh();}
changeRuleSelector(rule,selector)
{selector=selector||"";let result=new WI.WrappedPromise;let target=WI.assumingMainTarget();function ruleSelectorChanged(error,rulePayload)
{if(error){result.reject(error);return;}
target.DOMAgent.markUndoableState();
this.refresh().then(()=>{result.resolve(rulePayload);});}
this._needsRefresh=true;this._ignoreNextContentDidChangeForStyleSheet=rule.ownerStyleSheet;target.CSSAgent.setRuleSelector(rule.id,selector,ruleSelectorChanged.bind(this));return result.promise;}
changeStyleText(style,text,callback)
{if(!style.ownerStyleSheet||!style.styleSheetTextRange){callback();return;}
text=text||"";let didSetStyleText=(error,stylePayload)=>{if(error){callback(error);return;}
callback();if(style.ownerRule&&!style.ownerRule.matchedSelectorIndices.length)
this._parseStyleDeclarationPayload(stylePayload,this._node,false,null,style.type,style.ownerRule,false);this.refresh();};let target=WI.assumingMainTarget();target.CSSAgent.setStyleText(style.id,text,didSetStyleText);} 
_parseSourceRangePayload(payload)
{if(!payload)
return null;return new WI.TextRange(payload.startLine,payload.startColumn,payload.endLine,payload.endColumn);}
_parseStylePropertyPayload(payload,index,styleDeclaration)
{var text=payload.text||"";var name=payload.name;var value=payload.value||"";var priority=payload.priority||"";let range=payload.range||null;var enabled=true;var overridden=false;var implicit=payload.implicit||false;var anonymous=false;var valid="parsedOk"in payload?payload.parsedOk:true;switch(payload.status||"style"){case"active":enabled=true;break;case"inactive":overridden=true;enabled=true;break;case"disabled":enabled=false;break;case"style":anonymous=true;break;}
if(range){let rangeLineCount=1+range.endLine-range.startLine;if(rangeLineCount>1){let textLineCount=text.lineCount;if(textLineCount===rangeLineCount-1){range.endLine=range.startLine+(textLineCount-1);range.endColumn=range.startColumn+text.lastLine.length;}}}
var styleSheetTextRange=this._parseSourceRangePayload(payload.range);if(styleDeclaration){var property=isNaN(index)?styleDeclaration.propertyForName(name,true):styleDeclaration.enabledProperties[index];


if(property&&property.name===name&&(property.index===index||(isNaN(property.index)&&isNaN(index)))){property.update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);return property;}
var pendingProperties=styleDeclaration.pendingProperties;for(var i=0;i<pendingProperties.length;++i){var pendingProperty=pendingProperties[i];if(pendingProperty.name===name&&isNaN(pendingProperty.index)){pendingProperty.index=index;pendingProperty.update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);return pendingProperty;}}}
return new WI.CSSProperty(index,text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);}
_parseStyleDeclarationPayload(payload,node,inherited,pseudoId,type,rule,matchesNode=true)
{if(!payload)
return null;rule=rule||null;inherited=inherited||false;var id=payload.styleId;var mapKey=id?id.styleSheetId+":"+id.ordinal:null;if(pseudoId)
mapKey+=":"+pseudoId;if(type===WI.CSSStyleDeclaration.Type.Attribute)
mapKey+=":"+node.id+":attribute";let style=rule?rule.style:null;if(matchesNode){let existingStyles=this._previousStylesMap.get(mapKey);if(existingStyles&&!style){for(let existingStyle of existingStyles){if(existingStyle.node===node&&existingStyle.inherited===inherited){style=existingStyle;break;}}}
if(style)
this._stylesMap.add(mapKey,style);}
var inheritedPropertyCount=0;var properties=[];for(var i=0;payload.cssProperties&&i<payload.cssProperties.length;++i){var propertyPayload=payload.cssProperties[i];if(inherited&&WI.CSSProperty.isInheritedPropertyName(propertyPayload.name))
++inheritedPropertyCount;let property=this._parseStylePropertyPayload(propertyPayload,i,style);properties.push(property);}
let text=payload.cssText;var styleSheetTextRange=this._parseSourceRangePayload(payload.range);if(style){style.update(text,properties,styleSheetTextRange);return style;}
if(!matchesNode)
return null;var styleSheet=id?WI.cssManager.styleSheetForIdentifier(id.styleSheetId):null;if(styleSheet){if(type===WI.CSSStyleDeclaration.Type.Inline)
styleSheet.markAsInlineStyleAttributeStyleSheet();this._trackedStyleSheets.add(styleSheet);}
if(inherited&&!inheritedPropertyCount)
return null;style=new WI.CSSStyleDeclaration(this,styleSheet,id,type,node,inherited,text,properties,styleSheetTextRange);if(mapKey)
this._stylesMap.add(mapKey,style);return style;}
_parseRulePayload(payload,matchedSelectorIndices,node,inherited,pseudoId,ruleOccurrences)
{if(!payload)
return null;

var id=payload.ruleId||payload.style.styleId;var mapKey=id?id.styleSheetId+":"+id.ordinal+":"+(inherited?"I":"N")+":"+(pseudoId?pseudoId+":":"")+node.id:null;
var occurrence=0;if(mapKey){if(mapKey in ruleOccurrences)
occurrence=++ruleOccurrences[mapKey];else
ruleOccurrences[mapKey]=occurrence;mapKey+=":"+occurrence;}
let rule=this._rulesMap.get(mapKey);var style=this._parseStyleDeclarationPayload(payload.style,node,inherited,pseudoId,WI.CSSStyleDeclaration.Type.Rule,rule);if(!style)
return null;var styleSheet=id?WI.cssManager.styleSheetForIdentifier(id.styleSheetId):null;var selectorText=payload.selectorList.text;let selectors=DOMNodeStyles.parseSelectorListPayload(payload.selectorList);var type=WI.CSSManager.protocolStyleSheetOriginToEnum(payload.origin);var sourceCodeLocation=null;var sourceRange=payload.selectorList.range;if(sourceRange){sourceCodeLocation=DOMNodeStyles.createSourceCodeLocation(payload.sourceURL,{line:sourceRange.startLine,column:sourceRange.startColumn,documentNode:this._node.ownerDocument,});}else{sourceCodeLocation=DOMNodeStyles.createSourceCodeLocation(payload.sourceURL,{line:payload.sourceLine,documentNode:this._node.ownerDocument,});}
if(styleSheet){if(!sourceCodeLocation&&sourceRange)
sourceCodeLocation=styleSheet.createSourceCodeLocation(sourceRange.startLine,sourceRange.startColumn);sourceCodeLocation=styleSheet.offsetSourceCodeLocation(sourceCodeLocation);}
let groupings=(payload.groupings||payload.media||[]).map((grouping)=>{let groupingType=WI.CSSManager.protocolGroupingTypeToEnum(grouping.type||grouping.source);let groupingSourceCodeLocation=DOMNodeStyles.createSourceCodeLocation(grouping.sourceURL);if(styleSheet)
groupingSourceCodeLocation=styleSheet.offsetSourceCodeLocation(groupingSourceCodeLocation);return new WI.CSSGrouping(groupingType,grouping.text,groupingSourceCodeLocation);});if(rule){rule.update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings);return rule;}
if(styleSheet)
this._trackedStyleSheets.add(styleSheet);rule=new WI.CSSRule(this,styleSheet,id,type,sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings);if(mapKey)
this._rulesMap.set(mapKey,rule);return rule;}
_markAsNeedsRefresh()
{this._needsRefresh=true;this.dispatchEventToListeners(WI.DOMNodeStyles.Event.NeedsRefresh);}
_handleCSSStyleSheetContentDidChange(event)
{let styleSheet=event.target;if(!this._trackedStyleSheets.has(styleSheet))
return;if(styleSheet===this._ignoreNextContentDidChangeForStyleSheet){this._ignoreNextContentDidChangeForStyleSheet=null;return;}
this._markAsNeedsRefresh();}
_updateStyleCascade()
{var cascadeOrderedStyleDeclarations=this._collectStylesInCascadeOrder(this._matchedRules,this._inlineStyle,this._attributesStyle);for(var i=0;i<this._inheritedRules.length;++i){var inheritedStyleInfo=this._inheritedRules[i];var inheritedCascadeOrder=this._collectStylesInCascadeOrder(inheritedStyleInfo.matchedRules,inheritedStyleInfo.inlineStyle,null);cascadeOrderedStyleDeclarations.pushAll(inheritedCascadeOrder);}
this._orderedStyles=cascadeOrderedStyleDeclarations;this._propertyNameToEffectivePropertyMap={};this._associateRelatedProperties(cascadeOrderedStyleDeclarations,this._propertyNameToEffectivePropertyMap);this._markOverriddenProperties(cascadeOrderedStyleDeclarations,this._propertyNameToEffectivePropertyMap);this._collectCSSVariables(cascadeOrderedStyleDeclarations);for(let pseudoElementInfo of this._pseudoElements.values()){pseudoElementInfo.orderedStyles=this._collectStylesInCascadeOrder(pseudoElementInfo.matchedRules,null,null);this._associateRelatedProperties(pseudoElementInfo.orderedStyles);this._markOverriddenProperties(pseudoElementInfo.orderedStyles);}}
_collectStylesInCascadeOrder(matchedRules,inlineStyle,attributesStyle)
{var result=[];if(inlineStyle)
result.push(inlineStyle);var userAndUserAgentStyles=[];for(var i=0;i<matchedRules.length;++i){var rule=matchedRules[i];
switch(rule.type){case WI.CSSStyleSheet.Type.Inspector:case WI.CSSStyleSheet.Type.Author:result.push(rule.style);break;case WI.CSSStyleSheet.Type.User:case WI.CSSStyleSheet.Type.UserAgent:userAndUserAgentStyles.push(rule.style);break;}}
if(attributesStyle)
result.push(attributesStyle);result.pushAll(userAndUserAgentStyles);return result;}
_markOverriddenProperties(styles,propertyNameToEffectiveProperty)
{propertyNameToEffectiveProperty=propertyNameToEffectiveProperty||{};function isOverriddenByRelatedShorthand(property){let shorthand=property.relatedShorthandProperty;if(!shorthand)
return false;if(property.important&&!shorthand.important)
return false;if(!property.important&&shorthand.important)
return true;if(property.ownerStyle===shorthand.ownerStyle)
return shorthand.index>property.index;let propertyStyleIndex=styles.indexOf(property.ownerStyle);let shorthandStyleIndex=styles.indexOf(shorthand.ownerStyle);return shorthandStyleIndex>propertyStyleIndex;}
for(var i=0;i<styles.length;++i){var style=styles[i];var properties=style.enabledProperties;for(var j=0;j<properties.length;++j){var property=properties[j];if(!property.attached||!property.valid){property.overridden=false;continue;}
if(style.inherited&&!property.inherited){property.overridden=false;continue;}
var canonicalName=property.canonicalName;if(canonicalName in propertyNameToEffectiveProperty){var effectiveProperty=propertyNameToEffectiveProperty[canonicalName];if(effectiveProperty.ownerStyle===property.ownerStyle){if(effectiveProperty.important&&!property.important){property.overridden=true;property.overridingProperty=effectiveProperty;continue;}}else if(effectiveProperty.important||!property.important||effectiveProperty.ownerStyle.node!==property.ownerStyle.node){property.overridden=true;property.overridingProperty=effectiveProperty;continue;}
if(!property.anonymous){effectiveProperty.overridden=true;effectiveProperty.overridingProperty=property;}}
if(isOverriddenByRelatedShorthand(property)){property.overridden=true;property.overridingProperty=property.relatedShorthandProperty;}else
property.overridden=false;propertyNameToEffectiveProperty[canonicalName]=property;}}}
_associateRelatedProperties(styles,propertyNameToEffectiveProperty)
{for(var i=0;i<styles.length;++i){var properties=styles[i].enabledProperties;var knownShorthands={};for(var j=0;j<properties.length;++j){var property=properties[j];if(!property.valid)
continue;if(!WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.has(property.name))
continue;if(knownShorthands[property.canonicalName]&&!knownShorthands[property.canonicalName].overridden){continue;}
knownShorthands[property.canonicalName]=property;}
for(var j=0;j<properties.length;++j){var property=properties[j];if(!property.valid)
continue;var shorthandProperty=null;if(!isEmptyObject(knownShorthands)){var possibleShorthands=WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty.get(property.canonicalName)||[];for(var k=0;k<possibleShorthands.length;++k){if(possibleShorthands[k]in knownShorthands){shorthandProperty=knownShorthands[possibleShorthands[k]];break;}}}
if(!shorthandProperty||shorthandProperty.overridden!==property.overridden){property.relatedShorthandProperty=null;property.clearRelatedLonghandProperties();continue;}
shorthandProperty.addRelatedLonghandProperty(property);property.relatedShorthandProperty=shorthandProperty;if(propertyNameToEffectiveProperty&&propertyNameToEffectiveProperty[shorthandProperty.canonicalName]===shorthandProperty)
propertyNameToEffectiveProperty[property.canonicalName]=property;}}}
_collectCSSVariables(styles)
{this._allCSSVariables=new Set;this._usedCSSVariables=new Set;for(let style of styles){for(let property of style.enabledProperties){if(property.isVariable)
this._allCSSVariables.add(property.name);let variables=WI.CSSProperty.findVariableNames(property.value);if(!style.inherited){this._usedCSSVariables.addAll(variables);continue;}
if(WI.CSSKeywordCompletions.InheritedProperties.has(property.name)){this._usedCSSVariables.addAll(variables);continue;}

if(property.isVariable&&this._usedCSSVariables.has(property.name))
this._usedCSSVariables.addAll(variables);}}}
_isPropertyFoundInMatchingRules(propertyName)
{return this._orderedStyles.some((style)=>{return style.enabledProperties.some((property)=>property.name===propertyName);});}};WI.DOMNodeStyles.Event={NeedsRefresh:"dom-node-styles-needs-refresh",Refreshed:"dom-node-styles-refreshed"};WI.DOMSearchMatchObject=class DOMSearchMatchObject
{constructor(resource,domNode,title,searchTerm,textRange)
{this._resource=resource;this._domNode=domNode;this._title=title;this._searchTerm=searchTerm;this._sourceCodeTextRange=resource.createSourceCodeTextRange(textRange);} 
static titleForDOMNode(domNode)
{switch(domNode.nodeType()){case Node.ELEMENT_NODE:var title="<"+domNode.nodeNameInCorrectCase();for(var attribute of domNode.attributes()){title+=" "+attribute.name;if(attribute.value.length)
title+="=\""+attribute.value+"\"";}
return title+">";case Node.TEXT_NODE:return"\""+domNode.nodeValue()+"\"";case Node.COMMENT_NODE:return"<!--"+domNode.nodeValue()+"-->";case Node.DOCUMENT_TYPE_NODE:var title="<!DOCTYPE "+domNode.nodeName();if(domNode.publicId){title+=" PUBLIC \""+domNode.publicId+"\"";if(domNode.systemId)
title+=" \""+domNode.systemId+"\"";}else if(domNode.systemId)
title+=" SYSTEM \""+domNode.systemId+"\"";return title+">";case Node.CDATA_SECTION_NODE:return"<![CDATA["+domNode+"]]>";case Node.PROCESSING_INSTRUCTION_NODE:var data=domNode.nodeValue();var dataString=data.length?" "+data:"";var title="<?"+domNode.nodeNameInCorrectCase()+dataString+"?>";return title;default:console.error("Unknown DOM node type: ",domNode.nodeType());return domNode.nodeNameInCorrectCase();}} 
get resource()
{return this._resource;}
get domNode()
{return this._domNode;}
get title()
{return this._title;}
get className()
{if(!this._className)
this._className=this._generateClassName();return this._className;}
get searchTerm()
{return this._searchTerm;}
get sourceCodeTextRange()
{return this._sourceCodeTextRange;}
saveIdentityToCookie(cookie)
{cookie[WI.DOMSearchMatchObject.URLCookieKey]=this._resource.url.hash;cookie[WI.DOMSearchMatchObject.TitleKey]=this._title;var textRange=this._sourceCodeTextRange.textRange;cookie[WI.DOMSearchMatchObject.TextRangeKey]=[textRange.startLine,textRange.startColumn,textRange.endLine,textRange.endColumn].join();} 
_generateClassName()
{switch(this._domNode.nodeType()){case Node.ELEMENT_NODE:return WI.DOMSearchMatchObject.DOMMatchElementIconStyleClassName;case Node.TEXT_NODE:return WI.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName;case Node.COMMENT_NODE:return WI.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName;case Node.DOCUMENT_TYPE_NODE:return WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName;case Node.CDATA_SECTION_NODE:return WI.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName;case Node.PROCESSING_INSTRUCTION_NODE: return WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName;default:console.error("Unknown DOM node type: ",this._domNode.nodeType());return WI.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName;}}};WI.DOMSearchMatchObject.DOMMatchElementIconStyleClassName="dom-match-element-icon";WI.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName="dom-match-text-node-icon";WI.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName="dom-match-comment-icon";WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName="dom-match-document-type-icon";WI.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName="dom-match-character-data-icon";WI.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName="dom-match-node-icon";WI.DOMSearchMatchObject.TypeIdentifier="dom-search-match-object";WI.DOMSearchMatchObject.URLCookieKey="resource-url";WI.DOMSearchMatchObject.TitleKey="title";WI.DOMSearchMatchObject.TextRangeKey="text-range";WI.DOMStorageObject=class DOMStorageObject extends WI.Object
{constructor(id,host,isLocalStorage)
{super();this._id=id;this._host=host;this._isLocalStorage=isLocalStorage;this._entries=new Map;} 
get id(){return this._id;}
get host(){return this._host;}
get entries(){return this._entries;}
saveIdentityToCookie(cookie)
{cookie[WI.DOMStorageObject.HostCookieKey]=this.host;cookie[WI.DOMStorageObject.LocalStorageCookieKey]=this.isLocalStorage();}
isLocalStorage()
{return this._isLocalStorage;}
getEntries(callback)
{function innerCallback(error,entries)
{if(error)
return;for(let[key,value]of entries){if(!key||!value)
continue;this._entries.set(key,value);}
callback(error,entries);}
let target=WI.assumingMainTarget();target.DOMStorageAgent.getDOMStorageItems(this._id,innerCallback.bind(this));}
removeItem(key)
{let target=WI.assumingMainTarget();return target.DOMStorageAgent.removeDOMStorageItem(this._id,key);}
setItem(key,value)
{let target=WI.assumingMainTarget();return target.DOMStorageAgent.setDOMStorageItem(this._id,key,value);}
clear()
{let target=WI.assumingMainTarget();if(!target.hasCommand("DOMStorage.clearDOMStorageItems")){let promises=[];for(let key of this._entries.keys())
promises.push(this.removeItem(key));return Promise.all(promises);}
return target.DOMStorageAgent.clearDOMStorageItems(this._id);} 
itemsCleared()
{this._entries.clear();this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemsCleared);}
itemRemoved(key)
{let removed=this._entries.delete(key);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemRemoved,{key});}
itemAdded(key,value)
{this._entries.set(key,value);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemAdded,{key,value});}
itemUpdated(key,oldValue,newValue)
{this._entries.set(key,newValue);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemUpdated,{key,oldValue,newValue});}};WI.DOMStorageObject.TypeIdentifier="dom-storage";WI.DOMStorageObject.HostCookieKey="dom-storage-object-host";WI.DOMStorageObject.LocalStorageCookieKey="dom-storage-object-local-storage";WI.DOMStorageObject.Event={ItemsCleared:"dom-storage-object-items-cleared",ItemAdded:"dom-storage-object-item-added",ItemRemoved:"dom-storage-object-item-removed",ItemUpdated:"dom-storage-object-updated",};WI.DOMTree=class DOMTree extends WI.Object
{constructor(frame)
{super();this._frame=frame;this._rootDOMNode=null;this._requestIdentifier=0;this._frame.addEventListener(WI.Frame.Event.PageExecutionContextChanged,this._framePageExecutionContextChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);if(!this._frame.isMainFrame()){WI.domManager.addEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);this._frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._frameMainResourceDidChange,this);}} 
get frame(){return this._frame;}
disconnect()
{this._frame.removeEventListener(WI.Frame.Event.PageExecutionContextChanged,this._framePageExecutionContextChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);if(!this._frame.isMainFrame()){WI.domManager.removeEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);this._frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._frameMainResourceDidChange,this);}}
invalidate()
{this._rootDOMNode=null;
this._pendingRootDOMNodeRequests=null;if(this._invalidateTimeoutIdentifier)
return;function performInvalidate()
{this._invalidateTimeoutIdentifier=undefined;this.dispatchEventToListeners(WI.DOMTree.Event.RootDOMNodeInvalidated);}
this._invalidateTimeoutIdentifier=setTimeout(performInvalidate.bind(this),0);}
requestRootDOMNode(callback)
{if(typeof callback!=="function")
return;if(this._rootDOMNode){callback(this._rootDOMNode);return;}
if(!this._frame.isMainFrame()&&!this._frame.pageExecutionContext){this._rootDOMNodeRequestWaitingForExecutionContext=true;if(!this._pendingRootDOMNodeRequests)
this._pendingRootDOMNodeRequests=[];this._pendingRootDOMNodeRequests.push(callback);return;}
if(this._pendingRootDOMNodeRequests){this._pendingRootDOMNodeRequests.push(callback);return;}
this._pendingRootDOMNodeRequests=[callback];this._requestRootDOMNode();} 
_requestRootDOMNode()
{var requestIdentifier=++this._requestIdentifier;function rootObjectAvailable(error,result)
{if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier)
return;if(error){console.error(JSON.stringify(error));this._rootDOMNode=null;dispatchCallbacks.call(this);return;}
var remoteObject=WI.RemoteObject.fromPayload(result);remoteObject.pushNodeToFrontend(rootDOMNodeAvailable.bind(this,remoteObject));}
function rootDOMNodeAvailable(remoteObject,nodeId)
{remoteObject.release();if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier)
return;if(!nodeId){this._rootDOMNode=null;dispatchCallbacks.call(this);return;}
this._rootDOMNode=WI.domManager.nodeForId(nodeId);if(!this._rootDOMNode){dispatchCallbacks.call(this);return;}
this._rootDOMNode.getChildNodes(dispatchCallbacks.bind(this));}
function mainDocumentAvailable(document)
{this._rootDOMNode=document;dispatchCallbacks.call(this);}
function dispatchCallbacks()
{if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier)
return;for(var i=0;i<this._pendingRootDOMNodeRequests.length;++i)
this._pendingRootDOMNodeRequests[i](this._rootDOMNode);this._pendingRootDOMNodeRequests=null;}



if(this._frame.isMainFrame())
WI.domManager.requestDocument(mainDocumentAvailable.bind(this));else{let target=WI.assumingMainTarget();var contextId=this._frame.pageExecutionContext.id;target.RuntimeAgent.evaluate.invoke({expression:appendWebInspectorSourceURL("document"),objectGroup:"",includeCommandLineAPI:false,doNotPauseOnExceptionsAndMuteConsole:true,contextId,returnByValue:false,generatePreview:false},rootObjectAvailable.bind(this));}}
_nodeRemoved(event)
{if(event.data.node!==this._rootDOMNode)
return;this.invalidate();}
_documentUpdated(event)
{this.invalidate();}
_frameMainResourceDidChange(event)
{this.invalidate();}
_framePageExecutionContextChanged(event)
{if(this._rootDOMNodeRequestWaitingForExecutionContext){this._rootDOMNodeRequestWaitingForExecutionContext=false;this._requestRootDOMNode();}}};WI.DOMTree.Event={RootDOMNodeInvalidated:"dom-tree-root-dom-node-invalidated",};WI.DatabaseObject=class DatabaseObject
{constructor(id,host,name,version)
{this._id=id;this._host=host?host:WI.UIString("Local File");this._name=name;this._version=version;} 
get id(){return this._id;}
get host(){return this._host;}
get name(){return this._name;}
get version(){return this._version;}
saveIdentityToCookie(cookie)
{cookie[WI.DatabaseObject.HostCookieKey]=this.host;cookie[WI.DatabaseObject.NameCookieKey]=this.name;}
getTableNames(callback)
{function sortingCallback(error,names)
{if(!error)
callback(names.sort());}
let target=WI.assumingMainTarget();target.DatabaseAgent.getDatabaseTableNames(this._id,sortingCallback);}
executeSQL(query,successCallback,errorCallback)
{function queryCallback(error,columnNames,values,sqlError)
{if(error){errorCallback(WI.UIString("An unexpected error occurred."));return;}
if(sqlError){switch(sqlError.code){case SQLError.VERSION_ERR:errorCallback(WI.UIString("Database no longer has expected version."));break;case SQLError.TOO_LARGE_ERR:errorCallback(WI.UIString("Data returned from the database is too large."));break;default:errorCallback(WI.UIString("An unexpected error occurred."));break;}
return;}
successCallback(columnNames,values);}
let target=WI.assumingMainTarget();target.DatabaseAgent.executeSQL(this._id,query,queryCallback);}};WI.DatabaseObject.TypeIdentifier="database";WI.DatabaseObject.HostCookieKey="database-object-host";WI.DatabaseObject.NameCookieKey="database-object-name";WI.DatabaseTableObject=class DatabaseTableObject
{constructor(name,database)
{this._name=name;this._database=database;} 
get name(){return this._name;}
get database(){return this._database;}
saveIdentityToCookie(cookie)
{cookie[WI.DatabaseTableObject.NameCookieKey]=this.name;}};WI.DatabaseTableObject.TypeIdentifier="database-table";WI.DatabaseTableObject.NameCookieKey="database-table-object-name";WI.DebuggerData=class DebuggerData
{constructor(target)
{this._target=target;this._paused=false;this._pausing=false;this._pauseReason=null;this._pauseData=null;this._callFrames=[];this._asyncStackTrace=null;this._scriptIdMap=new Map;this._scriptContentIdentifierMap=new Map;this._makePausingAfterNextResume=false;} 
get target(){return this._target;}
get paused(){return this._paused;}
get pausing(){return this._pausing;}
get pauseReason(){return this._pauseReason;}
get pauseData(){return this._pauseData;}
get callFrames(){return this._callFrames;}
get asyncStackTrace(){return this._asyncStackTrace;}
get scripts()
{return Array.from(this._scriptIdMap.values());}
scriptForIdentifier(id)
{return this._scriptIdMap.get(id);}
scriptsForURL(url)
{return this._scriptContentIdentifierMap.get(url)||[];}
reset()
{this._scriptIdMap.clear();}
addScript(script)
{this._scriptIdMap.set(script.id,script);if(script.contentIdentifier){let scripts=this._scriptContentIdentifierMap.get(script.contentIdentifier);if(!scripts){scripts=[];this._scriptContentIdentifierMap.set(script.contentIdentifier,scripts);}
scripts.push(script);}}
pauseIfNeeded()
{if(this._paused||this._pausing)
return Promise.resolve();this._pausing=true;return this._target.DebuggerAgent.pause();}
resumeIfNeeded()
{if(!this._paused&&!this._pausing)
return Promise.resolve();this._pausing=false;return this._target.DebuggerAgent.resume();}
continueUntilNextRunLoop()
{if(!this._paused||this._pausing)
return Promise.resolve();
this._makePausingAfterNextResume=true;return this._target.DebuggerAgent.continueUntilNextRunLoop();}
updateForPause(callFrames,pauseReason,pauseData,asyncStackTrace)
{this._paused=true;this._pausing=false;this._pauseReason=pauseReason;this._pauseData=pauseData;this._callFrames=callFrames;this._asyncStackTrace=asyncStackTrace;this._makePausingAfterNextResume=false;}
updateForResume()
{this._paused=false;this._pausing=false;this._pauseReason=null;this._pauseData=null;this._callFrames=[];this._asyncStackTrace=null;if(this._makePausingAfterNextResume){this._makePausingAfterNextResume=false;this._pausing=true;}}};WI.EventBreakpoint=class EventBreakpoint extends WI.Breakpoint
{constructor(type,{eventName,eventListener,disabled,actions,condition,ignoreCount,autoContinue}={})
{if(type==="timer"){switch(eventName){case"setInterval":type=WI.EventBreakpoint.Type.Interval;break;case"setTimeout":type=WI.EventBreakpoint.Type.Timeout;break;}}
super({disabled,condition,actions,ignoreCount,autoContinue});this._type=type;this._eventName=eventName||null;this._eventListener=eventListener||null;} 
static get supportsEditing()
{return InspectorBackend.hasCommand("DOMDebugger.setEventBreakpoint","options");}
static fromJSON(json)
{return new WI.EventBreakpoint(json.type,{eventName:json.eventName,disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} 
get type(){return this._type;}
get eventName(){return this._eventName;}
get eventListener(){return this._eventListener;}
get displayName()
{switch(this){case WI.domDebuggerManager.allAnimationFramesBreakpoint:return WI.repeatedUIString.allAnimationFrames();case WI.domDebuggerManager.allIntervalsBreakpoint:return WI.repeatedUIString.allIntervals();case WI.domDebuggerManager.allListenersBreakpoint:return WI.repeatedUIString.allEvents();case WI.domDebuggerManager.allTimeoutsBreakpoint:return WI.repeatedUIString.allTimeouts();}
return this._eventName;}
get special()
{switch(this){case WI.domDebuggerManager.allAnimationFramesBreakpoint:case WI.domDebuggerManager.allIntervalsBreakpoint:case WI.domDebuggerManager.allListenersBreakpoint:case WI.domDebuggerManager.allTimeoutsBreakpoint:return true;}
return super.special;}
get editable()
{if(this._eventListener){return InspectorBackend.hasCommand("DOM.setBreakpointForEventListener","options");}
return WI.EventBreakpoint.supportsEditing||super.editable;}
remove()
{super.remove();if(this._eventListener)
WI.domManager.removeBreakpointForEventListener(this._eventListener);else
WI.domDebuggerManager.removeEventBreakpoint(this);}
saveIdentityToCookie(cookie)
{cookie["event-breakpoint-type"]=this._type;if(this._eventName)
cookie["event-breakpoint-event-name"]=this._eventName;if(this._eventListener)
cookie["event-breakpoint-event-listener"]=this._eventListener.eventListenerId;}
toJSON(key)
{let json=super.toJSON(key);json.type=this._type;if(this._eventName)
json.eventName=this._eventName;if(key===WI.ObjectStore.toJSONSymbol)
json[WI.objectStores.eventBreakpoints.keyPath]=this._type+(this._eventName?":"+this._eventName:"");return json;}};WI.EventBreakpoint.Type={AnimationFrame:"animation-frame",Interval:"interval",Listener:"listener",Timeout:"timeout",};WI.EventBreakpoint.ReferencePage=WI.ReferencePage.EventBreakpoints;WI.ExecutionContext=class ExecutionContext
{constructor(target,id,type,name,frame)
{this._target=target;this._id=id;this._type=type||WI.ExecutionContext.Type.Internal;this._name=name||"";this._frame=frame||null;} 
static typeFromPayload(payload)
{if(!("type"in payload))
return payload.isPageContext?WI.ExecutionContext.Type.Normal:WI.ExecutionContext.Type.Internal;switch(payload.type){case InspectorBackend.Enum.Runtime.ExecutionContextType.Normal:return WI.ExecutionContext.Type.Normal;case InspectorBackend.Enum.Runtime.ExecutionContextType.User:return WI.ExecutionContext.Type.User;case InspectorBackend.Enum.Runtime.ExecutionContextType.Internal:return WI.ExecutionContext.Type.Internal;}
return WI.ExecutionContext.Type.Internal;} 
get target(){return this._target;}
get id(){return this._id;}
get type(){return this._type;}
get name(){return this._name;}
get frame(){return this._frame;}};WI.ExecutionContext.Type={Normal:"normal",User:"user",Internal:"internal",};WI.ExecutionContextList=class ExecutionContextList
{constructor()
{this._contexts=[];this._pageExecutionContext=null;} 
get pageExecutionContext()
{return this._pageExecutionContext;}
get contexts()
{return this._contexts;}
add(context)
{if(context.type===WI.ExecutionContext.Type.Normal&&this._pageExecutionContext){return;}
this._contexts.push(context);if(context.type===WI.ExecutionContext.Type.Normal&&context.target.type===WI.TargetType.Page){this._pageExecutionContext=context;}}
clear()
{this._contexts=[];this._pageExecutionContext=null;}};WI.FPSInstrument=class FPSInstrument extends WI.Instrument
{ get timelineRecordType()
{return WI.TimelineRecord.Type.RenderingFrame;}};WI.Font=class Font
{constructor(name,variationAxes)
{this._name=name;this._variationAxes=variationAxes;} 
static fromPayload(payload)
{let variationAxes=payload.variationAxes.map((axisPayload)=>WI.FontVariationAxis.fromPayload(axisPayload));return new WI.Font(payload.displayName,variationAxes);} 
get name(){return this._name;}
get variationAxes(){return this._variationAxes;}
variationAxis(tag)
{return this._variationAxes.find((axis)=>axis.tag===tag);}
calculateFontProperties(domNodeStyle)
{let featuresMap=this._calculateFontFeatureAxes(domNodeStyle);let variationsMap=this._calculateFontVariationAxes(domNodeStyle);let propertiesMap=this._calculateProperties({domNodeStyle,featuresMap,variationsMap});return{propertiesMap,featuresMap,variationsMap};} 
_calculateProperties(style)
{let resultProperties=new Map;this._populateProperty("font-size",style,resultProperties,{keywordComputedReplacements:["larger","smaller","xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large"],});this._populateProperty("font-style",style,resultProperties,{variations:["ital","slnt"],keywordReplacements:new Map([["oblique","oblique 14deg"],]),});this._populateProperty("font-weight",style,resultProperties,{variations:["wght"],keywordComputedReplacements:["bolder","lighter"],keywordReplacements:new Map([["normal","400"],["bold","700"],]),});this._populateProperty("font-stretch",style,resultProperties,{variations:["wdth"],keywordReplacements:new Map([["ultra-condensed","50%"],["extra-condensed","62.5%"],["condensed","75%"],["semi-condensed","87.5%"],["normal","100%"],["semi-expanded","112.5%"],["expanded","125%"],["extra-expanded","150%"],["ultra-expanded","200%"],]),});this._populateProperty("font-variant-ligatures",style,resultProperties,{features:["liga","clig","dlig","hlig","calt"]});this._populateProperty("font-variant-position",style,resultProperties,{features:["subs","sups"]});this._populateProperty("font-variant-caps",style,resultProperties,{features:["smcp","c2sc","pcap","c2pc","unic","titl"]});this._populateProperty("font-variant-numeric",style,resultProperties,{features:["lnum","onum","pnum","tnum","frac","afrc","ordn","zero"]});this._populateProperty("font-variant-alternates",style,resultProperties,{features:["hist"]});this._populateProperty("font-variant-east-asian",style,resultProperties,{features:["jp78","jp83","jp90","jp04","smpl","trad","fwid","pwid","ruby"]});return resultProperties;}
_calculateFontFeatureAxes(domNodeStyle)
{return this._parseFontFeatureOrVariationSettings(domNodeStyle,"font-feature-settings");}
_calculateFontVariationAxes(domNodeStyle)
{let cssVariationSettings=this._parseFontFeatureOrVariationSettings(domNodeStyle,"font-variation-settings");let resultAxes=new Map;for(let axis of this._variationAxes){resultAxes.set(axis.tag,{name:axis.name,minimumValue:axis.minimumValue,maximumValue:axis.maximumValue,defaultValue:axis.defaultValue,value:cssVariationSettings.get(axis.tag),});}
return resultAxes;}
_parseFontFeatureOrVariationSettings(domNodeStyle,property)
{let cssSettings=new Map;let cssSettingsRawValue=this._computedPropertyValueForName(domNodeStyle,property);if(cssSettingsRawValue!=="normal"){for(let axis of cssSettingsRawValue.split(",")){let[tag,value]=axis.match(WI.Font.SettingPattern);tag=tag.replaceAll(/["']/g,"");if(!value||value==="on")
value=1;else if(value==="off")
value=0;cssSettings.set(tag,parseFloat(value));}}
return cssSettings;}
_populateProperty(name,style,resultProperties,{variations,features,keywordComputedReplacements,keywordReplacements})
{resultProperties.set(name,this._computeProperty(name,style,{variations,features,keywordComputedReplacements,keywordReplacements}));}
_computeProperty(name,style,{variations,features,keywordComputedReplacements,keywordReplacements})
{variations??=[];features??=[];keywordComputedReplacements??=[];keywordReplacements??=new Map;let resultProperties={};let value=this._effectivePropertyValueForName(style.domNodeStyle,name);if(!value||value==="inherit"||keywordComputedReplacements.includes(value))
value=this._computedPropertyValueForName(style.domNodeStyle,name);if(keywordReplacements.has(value))
value=keywordReplacements.get(value);resultProperties.value=value;for(let fontVariationSetting of variations){let variationSettingValue=style.variationsMap.get(fontVariationSetting);if(variationSettingValue){resultProperties.variations??=new Map;resultProperties.variations.set(fontVariationSetting,variationSettingValue);style.variationsMap.delete(fontVariationSetting);}}
for(let fontFeatureSetting of features){let featureSettingValue=style.featuresMap.get(fontFeatureSetting);if(featureSettingValue||featureSettingValue===0){resultProperties.features??=new Map;resultProperties.features.set(fontFeatureSetting,featureSettingValue);style.featuresMap.delete(fontFeatureSetting);}}
return resultProperties;}
_effectivePropertyValueForName(domNodeStyle,name)
{return domNodeStyle.effectivePropertyForName(name)?.value||"";}
_computedPropertyValueForName(domNodeStyle,name)
{const dontCreateIfMissing=true;return domNodeStyle.computedStyle?.propertyForName(name,dontCreateIfMissing)?.value||"";}};WI.Font.SettingPattern=/[^\s"']+|["']([^"']*)["']/g;WI.FontVariationAxis=class FontVariationAxis
{constructor(name,tag,minimumValue,maximumValue,defaultValue)
{this._name=name;this._tag=tag;this._minimumValue=minimumValue;this._maximumValue=maximumValue;this._defaultValue=defaultValue;} 
static fromPayload(payload)
{return new WI.FontVariationAxis(payload.name,payload.tag,payload.minimumValue,payload.maximumValue,payload.defaultValue);} 
get name(){return this._name;}
get tag(){return this._tag;}
get minimumValue(){return this._minimumValue;}
get maximumValue(){return this._maximumValue;}
get defaultValue(){return this._defaultValue;}};WI.Frame=class Frame extends WI.Object
{constructor(id,name,securityOrigin,loaderIdentifier,mainResource)
{super();this._id=id;this._name=null;this._securityOrigin=null;this._resourceCollection=new WI.ResourceCollection;this._provisionalResourceCollection=new WI.ResourceCollection;this._extraScriptCollection=new WI.ScriptCollection;this._childFrameCollection=new WI.FrameCollection;this._childFrameIdentifierMap=new Map;this._parentFrame=null;this._isMainFrame=false;this._domContentReadyEventTimestamp=NaN;this._loadEventTimestamp=NaN;this._executionContextList=new WI.ExecutionContextList;this.initialize(name,securityOrigin,loaderIdentifier,mainResource);} 
get resourceCollection(){return this._resourceCollection;}
get extraScriptCollection(){return this._extraScriptCollection;}
get childFrameCollection(){return this._childFrameCollection;}
initialize(name,securityOrigin,loaderIdentifier,mainResource)
{var oldName=this._name;var oldSecurityOrigin=this._securityOrigin;var oldMainResource=this._mainResource;this._name=name||null;this._securityOrigin=securityOrigin||null;this._loaderIdentifier=loaderIdentifier||null;this._mainResource=mainResource;this._mainResource._parentFrame=this;if(oldMainResource&&this._mainResource!==oldMainResource)
this._disassociateWithResource(oldMainResource);this.removeAllResources();this.removeAllChildFrames();this.clearExecutionContexts();this.clearProvisionalLoad();if(this._mainResource!==oldMainResource)
this._dispatchMainResourceDidChangeEvent(oldMainResource);if(this._securityOrigin!==oldSecurityOrigin)
this.dispatchEventToListeners(WI.Frame.Event.SecurityOriginDidChange,{oldSecurityOrigin});if(this._name!==oldName)
this.dispatchEventToListeners(WI.Frame.Event.NameDidChange,{oldName});}
startProvisionalLoad(provisionalMainResource)
{this._provisionalMainResource=provisionalMainResource;this._provisionalMainResource._parentFrame=this;this._provisionalLoaderIdentifier=provisionalMainResource.loaderIdentifier;this._provisionalResourceCollection.clear();this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadStarted);}
commitProvisionalLoad(securityOrigin)
{if(!this._provisionalLoaderIdentifier)
return;var oldSecurityOrigin=this._securityOrigin;var oldMainResource=this._mainResource;this._securityOrigin=securityOrigin||null;this._loaderIdentifier=this._provisionalLoaderIdentifier;this._mainResource=this._provisionalMainResource;this._domContentReadyEventTimestamp=NaN;this._loadEventTimestamp=NaN;if(oldMainResource&&this._mainResource!==oldMainResource)
this._disassociateWithResource(oldMainResource);this.removeAllResources();this._resourceCollection=this._provisionalResourceCollection;this._provisionalResourceCollection=new WI.ResourceCollection;this._extraScriptCollection.clear();this.clearExecutionContexts(true);this.clearProvisionalLoad(true);this.removeAllChildFrames();this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadCommitted);if(this._mainResource!==oldMainResource)
this._dispatchMainResourceDidChangeEvent(oldMainResource);if(this._securityOrigin!==oldSecurityOrigin)
this.dispatchEventToListeners(WI.Frame.Event.SecurityOriginDidChange,{oldSecurityOrigin});}
clearProvisionalLoad(skipProvisionalLoadClearedEvent)
{if(!this._provisionalLoaderIdentifier)
return;this._provisionalLoaderIdentifier=null;this._provisionalMainResource=null;this._provisionalResourceCollection.clear();if(!skipProvisionalLoadClearedEvent)
this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadCleared);}
get id()
{return this._id;}
get loaderIdentifier()
{return this._loaderIdentifier;}
get provisionalLoaderIdentifier()
{return this._provisionalLoaderIdentifier;}
get name()
{return this._name;}
get securityOrigin()
{return this._securityOrigin;}
get url()
{return this._mainResource.url;}
get urlComponents()
{return this._mainResource.urlComponents;}
get domTree()
{if(!this._domTree)
this._domTree=new WI.DOMTree(this);return this._domTree;}
get pageExecutionContext()
{return this._executionContextList.pageExecutionContext;}
get executionContextList()
{return this._executionContextList;}
clearExecutionContexts(committingProvisionalLoad)
{if(this._executionContextList.contexts.length){let contexts=this._executionContextList.contexts.slice();this._executionContextList.clear();this.dispatchEventToListeners(WI.Frame.Event.ExecutionContextsCleared,{committingProvisionalLoad:!!committingProvisionalLoad,contexts});}}
addExecutionContext(context)
{this._executionContextList.add(context);this.dispatchEventToListeners(WI.Frame.Event.ExecutionContextAdded,{context});if(this._executionContextList.pageExecutionContext===context)
this.dispatchEventToListeners(WI.Frame.Event.PageExecutionContextChanged);}
get mainResource()
{return this._mainResource;}
get provisionalMainResource()
{return this._provisionalMainResource;}
get parentFrame()
{return this._parentFrame;}
get domContentReadyEventTimestamp()
{return this._domContentReadyEventTimestamp;}
get loadEventTimestamp()
{return this._loadEventTimestamp;}
isMainFrame()
{return this._isMainFrame;}
markAsMainFrame()
{this._isMainFrame=true;}
unmarkAsMainFrame()
{this._isMainFrame=false;}
markDOMContentReadyEvent(timestamp)
{this._domContentReadyEventTimestamp=timestamp||NaN;}
markLoadEvent(timestamp)
{this._loadEventTimestamp=timestamp||NaN;}
isDetached()
{var frame=this;while(frame){if(frame.isMainFrame())
return false;frame=frame.parentFrame;}
return true;}
childFrameForIdentifier(frameId)
{return this._childFrameIdentifierMap.get(frameId)||null;}
addChildFrame(frame)
{if(!(frame instanceof WI.Frame))
return;if(frame._parentFrame===this)
return;if(frame._parentFrame)
frame._parentFrame.removeChildFrame(frame);this._childFrameCollection.add(frame);this._childFrameIdentifierMap.set(frame._id,frame);frame._parentFrame=this;this.dispatchEventToListeners(WI.Frame.Event.ChildFrameWasAdded,{childFrame:frame});}
removeChildFrame(frameOrFrameId)
{let childFrameId=frameOrFrameId;if(childFrameId instanceof WI.Frame)
childFrameId=frameOrFrameId._id;
let childFrame=this.childFrameForIdentifier(childFrameId);if(!(childFrame instanceof WI.Frame))
return;this._childFrameCollection.remove(childFrame);this._childFrameIdentifierMap.delete(childFrame._id);childFrame._detachFromParentFrame();this.dispatchEventToListeners(WI.Frame.Event.ChildFrameWasRemoved,{childFrame});}
removeAllChildFrames()
{this._detachFromParentFrame();for(let childFrame of this._childFrameCollection)
childFrame.removeAllChildFrames();this._childFrameCollection.clear();this._childFrameIdentifierMap.clear();this.dispatchEventToListeners(WI.Frame.Event.AllChildFramesRemoved);}
resourcesForURL(url,recursivelySearchChildFrames)
{let resources=this._resourceCollection.resourcesForURL(url);for(let childFrame of this._childFrameCollection){if(childFrame.mainResource.url===url)
resources.add(childFrame.mainResource);}
if(recursivelySearchChildFrames){for(let childFrame of this._childFrameCollection)
resources.addAll(childFrame.resourcesForURL(url,recursivelySearchChildFrames));}
return resources;}
resourceCollectionForType(type)
{return this._resourceCollection.resourceCollectionForType(type);}
addResource(resource)
{if(!(resource instanceof WI.Resource))
return;if(resource.parentFrame===this)
return;if(resource.parentFrame)
resource.parentFrame.remove(resource);this._associateWithResource(resource);if(this._isProvisionalResource(resource)){this._provisionalResourceCollection.add(resource);this.dispatchEventToListeners(WI.Frame.Event.ProvisionalResourceWasAdded,{resource});}else{this._resourceCollection.add(resource);this.dispatchEventToListeners(WI.Frame.Event.ResourceWasAdded,{resource});}}
removeResource(resource)
{this._resourceCollection.remove(resource);this._disassociateWithResource(resource);this.dispatchEventToListeners(WI.Frame.Event.ResourceWasRemoved,{resource});}
removeAllResources()
{if(!this._resourceCollection.size)
return;for(let resource of this._resourceCollection)
this._disassociateWithResource(resource);this._resourceCollection.clear();this.dispatchEventToListeners(WI.Frame.Event.AllResourcesRemoved);}
addExtraScript(script)
{this._extraScriptCollection.add(script);this.dispatchEventToListeners(WI.Frame.Event.ExtraScriptAdded,{script});}
saveIdentityToCookie(cookie)
{cookie[WI.Frame.MainResourceURLCookieKey]=this.mainResource.url.hash;cookie[WI.Frame.IsMainFrameCookieKey]=this._isMainFrame;} 
_detachFromParentFrame()
{if(this._domTree){this._domTree.disconnect();this._domTree=null;}
this._parentFrame=null;}
_isProvisionalResource(resource)
{return resource.loaderIdentifier&&this._provisionalLoaderIdentifier&&resource.loaderIdentifier===this._provisionalLoaderIdentifier;}
_associateWithResource(resource)
{if(resource._parentFrame)
return;resource._parentFrame=this;}
_disassociateWithResource(resource)
{if(resource.parentFrame!==this)
return;resource._parentFrame=null;}
_dispatchMainResourceDidChangeEvent(oldMainResource)
{this.dispatchEventToListeners(WI.Frame.Event.MainResourceDidChange,{oldMainResource});}};WI.Frame.Event={NameDidChange:"frame-name-did-change",SecurityOriginDidChange:"frame-security-origin-did-change",MainResourceDidChange:"frame-main-resource-did-change",ProvisionalLoadStarted:"frame-provisional-load-started",ProvisionalLoadCommitted:"frame-provisional-load-committed",ProvisionalLoadCleared:"frame-provisional-load-cleared",ProvisionalResourceWasAdded:"frame-provisional-resource-was-added",ResourceWasAdded:"frame-resource-was-added",ResourceWasRemoved:"frame-resource-was-removed",AllResourcesRemoved:"frame-all-resources-removed",ExtraScriptAdded:"frame-extra-script-added",ChildFrameWasAdded:"frame-child-frame-was-added",ChildFrameWasRemoved:"frame-child-frame-was-removed",AllChildFramesRemoved:"frame-all-child-frames-removed",PageExecutionContextChanged:"frame-page-execution-context-changed",ExecutionContextAdded:"frame-execution-context-added",ExecutionContextsCleared:"frame-execution-contexts-cleared"};WI.Frame.TypeIdentifier="Frame";WI.Frame.MainResourceURLCookieKey="frame-main-resource-url";WI.Frame.IsMainFrameCookieKey="frame-is-main-frame";WI.GarbageCollection=class GarbageCollection
{constructor(type,startTime,endTime)
{this._type=type;this._startTime=startTime;this._endTime=endTime;} 
static fromPayload(payload)
{let type=WI.GarbageCollection.Type.Full;if(payload.type===InspectorBackend.Enum.Heap.GarbageCollectionType.Partial)
type=WI.GarbageCollection.Type.Partial;return new WI.GarbageCollection(type,payload.startTime,payload.endTime);} 
static fromJSON(json)
{let{type,startTime,endTime}=json;return new WI.GarbageCollection(type,startTime,endTime);}
toJSON()
{return{__type:"GarbageCollection",type:this.type,startTime:this.startTime,endTime:this.endTime,};} 
get type(){return this._type;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get duration()
{return this._endTime-this._startTime;}};WI.GarbageCollection.Type={Partial:"partial",Full:"full",};WI.Point=class Point
{constructor(x,y)
{this.x=x||0;this.y=y||0;} 
static fromEvent(event)
{return new WI.Point(event.pageX,event.pageY);}
static fromEventInElement(event,element)
{let rect=element.getBoundingClientRect();return new WI.Point(event.pageX-rect.x,event.pageY-rect.y);} 
toString()
{return"WI.Point["+this.x+","+this.y+"]";}
copy()
{return new WI.Point(this.x,this.y);}
equals(anotherPoint)
{return this.x===anotherPoint.x&&this.y===anotherPoint.y;}
distance(anotherPoint)
{let dx=anotherPoint.x-this.x;let dy=anotherPoint.y-this.y;return Math.sqrt((dx*dx)+(dy*dy));}};WI.Size=class Size
{constructor(width,height)
{this.width=width||0;this.height=height||0;} 
toString()
{return"WI.Size["+this.width+","+this.height+"]";}
copy()
{return new WI.Size(this.width,this.height);}
equals(anotherSize)
{return this.width===anotherSize.width&&this.height===anotherSize.height;}};WI.Size.ZERO_SIZE=new WI.Size(0,0);WI.Rect=class Rect
{constructor(x,y,width,height)
{this.origin=new WI.Point(x||0,y||0);this.size=new WI.Size(width||0,height||0);} 
static rectFromClientRect(clientRect)
{return new WI.Rect(clientRect.left,clientRect.top,clientRect.width,clientRect.height);}
static unionOfRects(rects)
{var union=rects[0];for(var i=1;i<rects.length;++i)
union=union.unionWithRect(rects[i]);return union;} 
toString()
{return"WI.Rect["+[this.origin.x,this.origin.y,this.size.width,this.size.height].join(", ")+"]";}
copy()
{return new WI.Rect(this.origin.x,this.origin.y,this.size.width,this.size.height);}
equals(anotherRect)
{return this.origin.equals(anotherRect.origin)&&this.size.equals(anotherRect.size);}
inset(insets)
{return new WI.Rect(this.origin.x+insets.left,this.origin.y+insets.top,this.size.width-insets.left-insets.right,this.size.height-insets.top-insets.bottom);}
pad(padding)
{return new WI.Rect(this.origin.x-padding,this.origin.y-padding,this.size.width+padding*2,this.size.height+padding*2);}
minX()
{return this.origin.x;}
minY()
{return this.origin.y;}
midX()
{return this.origin.x+(this.size.width/2);}
midY()
{return this.origin.y+(this.size.height/2);}
maxX()
{return this.origin.x+this.size.width;}
maxY()
{return this.origin.y+this.size.height;}
intersectionWithRect(rect)
{var x1=Math.max(this.minX(),rect.minX());var x2=Math.min(this.maxX(),rect.maxX());if(x1>x2)
return WI.Rect.ZERO_RECT;var intersection=new WI.Rect;intersection.origin.x=x1;intersection.size.width=x2-x1;var y1=Math.max(this.minY(),rect.minY());var y2=Math.min(this.maxY(),rect.maxY());if(y1>y2)
return WI.Rect.ZERO_RECT;intersection.origin.y=y1;intersection.size.height=y2-y1;return intersection;}
unionWithRect(rect)
{var x=Math.min(this.minX(),rect.minX());var y=Math.min(this.minY(),rect.minY());var width=Math.max(this.maxX(),rect.maxX())-x;var height=Math.max(this.maxY(),rect.maxY())-y;return new WI.Rect(x,y,width,height);}
round()
{return new WI.Rect(Math.floor(this.origin.x),Math.floor(this.origin.y),Math.ceil(this.size.width),Math.ceil(this.size.height));}};WI.Rect.ZERO_RECT=new WI.Rect(0,0,0,0);WI.EdgeInsets=class EdgeInsets
{constructor(top,right,bottom,left)
{if(arguments.length===1){this.top=top;this.right=top;this.bottom=top;this.left=top;}else if(arguments.length===4){this.top=top;this.right=right;this.bottom=bottom;this.left=left;}} 
equals(anotherInset)
{return this.top===anotherInset.top&&this.right===anotherInset.right&&this.bottom===anotherInset.bottom&&this.left===anotherInset.left;}
copy()
{return new WI.EdgeInsets(this.top,this.right,this.bottom,this.left);}};WI.RectEdge={MIN_X:0,MIN_Y:1,MAX_X:2,MAX_Y:3};WI.Quad=class Quad
{constructor(quad)
{this.points=[new WI.Point(quad[0],quad[1]), new WI.Point(quad[2],quad[3]), new WI.Point(quad[4],quad[5]), new WI.Point(quad[6],quad[7])
];this.width=Math.round(Math.sqrt(Math.pow(quad[0]-quad[2],2)+Math.pow(quad[1]-quad[3],2)));this.height=Math.round(Math.sqrt(Math.pow(quad[0]-quad[6],2)+Math.pow(quad[1]-quad[7],2)));} 
static fromJSON(json)
{return new WI.Quad(json);}
toJSON()
{return this.toProtocol();} 
toProtocol()
{return[this.points[0].x,this.points[0].y,this.points[1].x,this.points[1].y,this.points[2].x,this.points[2].y,this.points[3].x,this.points[3].y];}};WI.Polygon=class Polygon
{constructor(points)
{this.points=points;} 
bounds()
{var minX=Number.MAX_VALUE;var minY=Number.MAX_VALUE;var maxX=-Number.MAX_VALUE;var maxY=-Number.MAX_VALUE;for(var point of this.points){minX=Math.min(minX,point.x);maxX=Math.max(maxX,point.x);minY=Math.min(minY,point.y);maxY=Math.max(maxY,point.y);}
return new WI.Rect(minX,minY,maxX-minX,maxY-minY);}};WI.CubicBezier=class CubicBezier
{constructor(x1,y1,x2,y2)
{this._inPoint=new WI.Point(x1,y1);this._outPoint=new WI.Point(x2,y2);this._curveInfo={x:{c:3.0*x1},y:{c:3.0*y1}};this._curveInfo.x.b=3.0*(x2-x1)-this._curveInfo.x.c;this._curveInfo.x.a=1.0-this._curveInfo.x.c-this._curveInfo.x.b;this._curveInfo.y.b=3.0*(y2-y1)-this._curveInfo.y.c;this._curveInfo.y.a=1.0-this._curveInfo.y.c-this._curveInfo.y.b;} 
static fromCoordinates(coordinates)
{if(!coordinates||coordinates.length<4)
return null;coordinates=coordinates.map(Number);if(coordinates.includes(NaN))
return null;return new WI.CubicBezier(coordinates[0],coordinates[1],coordinates[2],coordinates[3]);}
static fromString(text)
{if(!text||!text.length)
return null;var trimmedText=text.toLowerCase().replace(/\s/g,"");if(!trimmedText.length)
return null;if(Object.keys(WI.CubicBezier.keywordValues).includes(trimmedText))
return WI.CubicBezier.fromCoordinates(WI.CubicBezier.keywordValues[trimmedText]);var matches=trimmedText.match(/^cubic-bezier\(([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+)\)$/);if(!matches)
return null;matches.splice(0,1);return WI.CubicBezier.fromCoordinates(matches);} 
get inPoint()
{return this._inPoint;}
get outPoint()
{return this._outPoint;}
copy()
{return new WI.CubicBezier(this._inPoint.x,this._inPoint.y,this._outPoint.x,this._outPoint.y);}
toString()
{var values=[this._inPoint.x,this._inPoint.y,this._outPoint.x,this._outPoint.y];for(var key in WI.CubicBezier.keywordValues){if(Array.shallowEqual(WI.CubicBezier.keywordValues[key],values))
return key;}
return"cubic-bezier("+values.join(", ")+")";}
solve(x,epsilon)
{return this._sampleCurveY(this._solveCurveX(x,epsilon));} 
_sampleCurveX(t)
{return((this._curveInfo.x.a*t+this._curveInfo.x.b)*t+this._curveInfo.x.c)*t;}
_sampleCurveY(t)
{return((this._curveInfo.y.a*t+this._curveInfo.y.b)*t+this._curveInfo.y.c)*t;}
_sampleCurveDerivativeX(t)
{return(3.0*this._curveInfo.x.a*t+2.0*this._curveInfo.x.b)*t+this._curveInfo.x.c;}
_solveCurveX(x,epsilon)
{var t0,t1,t2,x2,d2,i;for(t2=x,i=0;i<8;i++){x2=this._sampleCurveX(t2)-x;if(Math.abs(x2)<epsilon)
return t2;d2=this._sampleCurveDerivativeX(t2);if(Math.abs(d2)<1e-6)
break;t2=t2-x2/d2;}
t0=0.0;t1=1.0;t2=x;if(t2<t0)
return t0;if(t2>t1)
return t1;while(t0<t1){x2=this._sampleCurveX(t2);if(Math.abs(x2-x)<epsilon)
return t2;if(x>x2)
t0=t2;else
t1=t2;t2=(t1-t0)*0.5+t0;}
return t2;}};WI.CubicBezier.keywordValues={"ease":[0.25,0.1,0.25,1],"ease-in":[0.42,0,1,1],"ease-out":[0,0,0.58,1],"ease-in-out":[0.42,0,0.58,1],"linear":[0,0,1,1]};WI.Spring=class Spring
{constructor(mass,stiffness,damping,initialVelocity)
{this.mass=Math.max(1,mass);this.stiffness=Math.max(1,stiffness);this.damping=Math.max(0,damping);this.initialVelocity=initialVelocity;} 
static fromValues(values)
{if(!values||values.length<4)
return null;values=values.map(Number);if(values.includes(NaN))
return null;return new WI.Spring(...values);}
static fromString(text)
{if(!text||!text.length)
return null;let trimmedText=text.toLowerCase().trim();if(!trimmedText.length)
return null;let matches=trimmedText.match(/^spring\(([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([-\d.]+)\)$/);if(!matches)
return null;return WI.Spring.fromValues(matches.slice(1));} 
copy()
{return new WI.Spring(this.mass,this.stiffness,this.damping,this.initialVelocity);}
toString()
{return`spring(${this.mass} ${this.stiffness} ${this.damping} ${this.initialVelocity})`;}
solve(t)
{let w0=Math.sqrt(this.stiffness/this.mass);let zeta=this.damping/(2*Math.sqrt(this.stiffness*this.mass));let wd=0;let A=1;let B=-this.initialVelocity+w0;if(zeta<1){wd=w0*Math.sqrt(1-zeta*zeta);A=1;B=(zeta*w0+-this.initialVelocity)/wd;}
if(zeta<1) 
t=Math.exp(-t*zeta*w0)*(A*Math.cos(wd*t)+B*Math.sin(wd*t));else
t=(A+B*t)*Math.exp(-t*w0);return 1-t;}
calculateDuration(epsilon)
{epsilon=epsilon||0.0001;let t=0;let current=0;let minimum=Number.POSITIVE_INFINITY;while(current>=epsilon||minimum>=epsilon){current=Math.abs(1-this.solve(t)); if(minimum<epsilon&&current>=epsilon)
minimum=Number.POSITIVE_INFINITY; else if(current<minimum)
minimum=current;t+=0.1;}
return t;}};WI.StepsFunction=class StepsFunction
{constructor(type,count)
{this._type=type;this._count=count;} 
static fromString(text)
{if(!text?.length)
return null;let trimmedText=text.toLowerCase().replace(/\s/g,"");if(!trimmedText.length)
return null;let keywordValue=WI.StepsFunction.keywordValues[trimmedText];if(keywordValue)
return new WI.StepsFunction(...keywordValue);let matches=trimmedText.match(/^steps\((\d+)(?:,([a-z-]+))?\)$/);if(!matches)
return null;let type=matches[2]||WI.StepsFunction.Type.JumpEnd;if(Object.values(WI.StepsFunction).includes(type))
return null;let count=Number(matches[1]);if(isNaN(count)||count<=0)
return null;return new WI.StepsFunction(type,count);} 
get type(){return this._type;}
get count(){return this._count;}
copy()
{return new WI.StepsFunction(this._type,this._count);}
toString()
{if(this._type===WI.StepsFunction.Type.JumpStart&&this._count===1)
return"step-start";if(this._type===WI.StepsFunction.Type.JumpEnd&&this._count===1)
return"step-end";return`steps(${this._count}, ${this._type})`;}};WI.StepsFunction.Type={JumpStart:"jump-start",JumpEnd:"jump-end",JumpNone:"jump-none",JumpBoth:"jump-both",Start:"start",End:"end",};WI.StepsFunction.keywordValues={"step-start":[WI.StepsFunction.Type.JumpStart,1],"step-end":[WI.StepsFunction.Type.JumpEnd,1],};WI.Gradient=class Gradient
{constructor(type,stops)
{this.type=type;this.stops=stops;} 
static fromString(cssString)
{var type;var openingParenthesisIndex=cssString.indexOf("(");var typeString=cssString.substring(0,openingParenthesisIndex);if(typeString.indexOf(WI.Gradient.Types.Linear)!==-1)
type=WI.Gradient.Types.Linear;else if(typeString.indexOf(WI.Gradient.Types.Radial)!==-1)
type=WI.Gradient.Types.Radial;else
return null;var components=[];var currentParams=[];var currentParam="";var openParentheses=0;var ch=openingParenthesisIndex+1;var c=null;while(c=cssString[ch]){if(c==="(")
openParentheses++;if(c===")")
openParentheses--;var isComma=c===",";var isSpace=/\s/.test(c);if(openParentheses===0){if(isSpace){if(currentParam!=="")
currentParams.push(currentParam);currentParam="";}else if(isComma){currentParams.push(currentParam);components.push(currentParams);currentParams=[];currentParam="";}}
if(openParentheses===-1){currentParams.push(currentParam);components.push(currentParams);break;}
if(openParentheses>0||(!isComma&&!isSpace))
currentParam+=c;ch++;}
if(openParentheses!==-1)
return null;var gradient;if(type===WI.Gradient.Types.Linear)
gradient=WI.LinearGradient.fromComponents(components);else
gradient=WI.RadialGradient.fromComponents(components);if(gradient)
gradient.repeats=typeString.startsWith("repeating");return gradient;}
static stopsWithComponents(components)
{var stops=components.map(function(component){while(component.length){var color=WI.Color.fromString(component.shift());if(!color)
continue;var stop={color};if(component.length&&component[0].substr(-1)==="%")
stop.offset=parseFloat(component.shift())/100;return stop;}});if(!stops.length)
return null;for(var i=0,count=stops.length;i<count;++i){var stop=stops[i];
if(!stop)
return null;if(!stop.offset)
stop.offset=i/(count-1);}
return stops;} 
stringFromStops(stops)
{var count=stops.length-1;return stops.map(function(stop,index){var str=stop.color;if(stop.offset!==index/count)
str+=" "+Math.round(stop.offset*10_000)/100+"%";return str;}).join(", ");} 
copy()
{}
toString()
{}};WI.Gradient.Types={Linear:"linear-gradient",Radial:"radial-gradient"};WI.LinearGradient=class LinearGradient extends WI.Gradient
{constructor(angle,stops)
{super(WI.Gradient.Types.Linear,stops);this._angle=angle;} 
static fromComponents(components)
{let angle={value:180,units:WI.LinearGradient.AngleUnits.DEG};if(components[0].length===1&&!WI.Color.fromString(components[0][0])){let match=components[0][0].match(/([-\d\.]+)(\w+)/);if(!match||!Object.values(WI.LinearGradient.AngleUnits).includes(match[2]))
return null;angle.value=parseFloat(match[1]);angle.units=match[2];components.shift();}else if(components[0][0]==="to"){components[0].shift();switch(components[0].sort().join(" ")){case"top":angle.value=0;break;case"right top":angle.value=45;break;case"right":angle.value=90;break;case"bottom right":angle.value=135;break;case"bottom":angle.value=180;break;case"bottom left":angle.value=225;break;case"left":angle.value=270;break;case"left top":angle.value=315;break;default:return null;}
components.shift();}else if(components[0].length!==1&&!WI.Color.fromString(components[0][0])){
return null;}
var stops=WI.Gradient.stopsWithComponents(components);if(!stops)
return null;return new WI.LinearGradient(angle,stops);} 
set angleValue(value){this._angle.value=value;}
get angleValue()
{return this._angle.value.maxDecimals(2);}
set angleUnits(units)
{if(units===this._angle.units)
return;this._angle.value=this._angleValueForUnits(units);this._angle.units=units;}
get angleUnits(){return this._angle.units;}
copy()
{return new WI.LinearGradient(this._angle,this.stops.concat());}
toString()
{let str="";let deg=this._angleValueForUnits(WI.LinearGradient.AngleUnits.DEG);if(deg===0)
str+="to top";else if(deg===45)
str+="to top right";else if(deg===90)
str+="to right";else if(deg===135)
str+="to bottom right";else if(deg===225)
str+="to bottom left";else if(deg===270)
str+="to left";else if(deg===315)
str+="to top left";else if(deg!==180)
str+=this.angleValue+this.angleUnits;if(str!=="")
str+=", ";str+=this.stringFromStops(this.stops);return(this.repeats?"repeating-":"")+this.type+"("+str+")";} 
_angleValueForUnits(units)
{if(units===this._angle.units)
return this._angle.value;let deg=0;switch(this._angle.units){case WI.LinearGradient.AngleUnits.DEG:deg=this._angle.value;break;case WI.LinearGradient.AngleUnits.RAD:deg=this._angle.value*180/Math.PI;break;case WI.LinearGradient.AngleUnits.GRAD:deg=this._angle.value/400*360;break;case WI.LinearGradient.AngleUnits.TURN:deg=this._angle.value*360;break;default:WI.reportInternalError(`Unknown angle units "${this._angle.units}"`);return 0;}
let value=0;switch(units){case WI.LinearGradient.AngleUnits.DEG:value=deg;break;case WI.LinearGradient.AngleUnits.RAD:value=deg*Math.PI/180;break;case WI.LinearGradient.AngleUnits.GRAD:value=deg/360*400;break;case WI.LinearGradient.AngleUnits.TURN:value=deg/360;break;}
return value;}};WI.LinearGradient.AngleUnits={DEG:"deg",RAD:"rad",GRAD:"grad",TURN:"turn",};WI.RadialGradient=class RadialGradient extends WI.Gradient
{constructor(sizing,stops)
{super(WI.Gradient.Types.Radial,stops);this.sizing=sizing;} 
static fromComponents(components)
{var sizing=!WI.Color.fromString(components[0].join(" "))?components.shift().join(" "):"";var stops=WI.Gradient.stopsWithComponents(components);if(!stops)
return null;return new WI.RadialGradient(sizing,stops);} 
copy()
{return new WI.RadialGradient(this.sizing,this.stops.concat());}
toString()
{var str=this.sizing;if(str!=="")
str+=", ";str+=this.stringFromStops(this.stops);return(this.repeats?"repeating-":"")+this.type+"("+str+")";}};WI.HeapAllocationsInstrument=class HeapAllocationsInstrument extends WI.Instrument
{constructor()
{super();this._snapshotIntervalIdentifier=undefined;} 
get timelineRecordType()
{return WI.TimelineRecord.Type.HeapAllocations;}
startInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.HeapAgent.startTracking();}
const snapshotInterval=10_000;this._snapshotIntervalIdentifier=setInterval(this._takeHeapSnapshot.bind(this),snapshotInterval);}
stopInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.HeapAgent.stopTracking();}
window.clearInterval(this._snapshotIntervalIdentifier);this._snapshotIntervalIdentifier=undefined;} 
_takeHeapSnapshot()
{WI.heapManager.snapshot((error,timestamp,snapshotStringData)=>{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);});});}};WI.HeapAllocationsTimelineRecord=class HeapAllocationsTimelineRecord extends WI.TimelineRecord
{constructor(timestamp,heapSnapshot)
{super(WI.TimelineRecord.Type.HeapAllocations,timestamp,timestamp);this._timestamp=timestamp;this._heapSnapshot=heapSnapshot;} 
static async fromJSON(json)
{

let{timestamp,title,snapshotStringData}=json;return await new Promise((resolve,reject)=>{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createImportedSnapshot(snapshotStringData,title,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;resolve(new WI.HeapAllocationsTimelineRecord(timestamp,snapshot));});});}
toJSON()
{return{type:this.type,timestamp:this._timestamp,title:WI.TimelineTabContentView.displayNameForRecord(this),snapshotStringData:this._heapSnapshot.snapshotStringData,};} 
get timestamp(){return this._timestamp;}
get heapSnapshot(){return this._heapSnapshot;}};WI.HeapSnapshotRootPath=class HeapSnapshotRootPath
{constructor(node,pathComponent,parent,isGlobalScope)
{this._node=node||null;this._parent=parent||null;this._pathComponent=typeof pathComponent==="string"?pathComponent:null;this._isGlobalScope=isGlobalScope||false;if(this._parent&&this._parent.isEmpty())
this._parent=null;} 
static emptyPath()
{return new WI.HeapSnapshotRootPath(null);}
static pathComponentForIndividualEdge(edge)
{switch(edge.type){case WI.HeapSnapshotEdgeProxy.EdgeType.Internal:return null;case WI.HeapSnapshotEdgeProxy.EdgeType.Index:return"["+edge.data+"]";case WI.HeapSnapshotEdgeProxy.EdgeType.Property:case WI.HeapSnapshotEdgeProxy.EdgeType.Variable:if(WI.HeapSnapshotRootPath.canPropertyNameBeDotAccess(edge.data))
return edge.data;return"["+doubleQuotedString(edge.data)+"]";}}
static canPropertyNameBeDotAccess(propertyName)
{return/^(?![0-9])\w+$/.test(propertyName);} 
get node(){return this._node;}
get parent(){return this._parent;}
get pathComponent(){return this._pathComponent;}
get rootNode()
{return this._parent?this._parent.rootNode:this._node;}
get fullPath()
{let components=[];for(let p=this;p&&p.pathComponent;p=p.parent)
components.push(p.pathComponent);components.reverse();return components.join("");}
isRoot()
{return!this._parent;}
isEmpty()
{return!this._node;}
isGlobalScope()
{return this._isGlobalScope;}
isPathComponentImpossible()
{return this._pathComponent&&this._pathComponent.startsWith("@");}
isFullPathImpossible()
{if(this.isEmpty())
return true;if(this.isPathComponentImpossible())
return true;if(this._parent)
return this._parent.isFullPathImpossible();return false;}
appendInternal(node)
{return new WI.HeapSnapshotRootPath(node,WI.HeapSnapshotRootPath.SpecialPathComponent.InternalPropertyName,this);}
appendArrayIndex(node,index)
{let component="["+index+"]";return new WI.HeapSnapshotRootPath(node,component,this);}
appendPropertyName(node,propertyName)
{let component=WI.HeapSnapshotRootPath.canPropertyNameBeDotAccess(propertyName)?"."+propertyName:"["+doubleQuotedString(propertyName)+"]";return new WI.HeapSnapshotRootPath(node,component,this);}
appendVariableName(node,variableName)
{if(this._isGlobalScope)
return this.appendPropertyName(node,variableName);return new WI.HeapSnapshotRootPath(node,variableName,this);}
appendGlobalScopeName(node,globalScopeName)
{return new WI.HeapSnapshotRootPath(node,globalScopeName,this,true);}
appendEdge(edge)
{switch(edge.type){case WI.HeapSnapshotEdgeProxy.EdgeType.Internal:return this.appendInternal(edge.to);case WI.HeapSnapshotEdgeProxy.EdgeType.Index:return this.appendArrayIndex(edge.to,edge.data);case WI.HeapSnapshotEdgeProxy.EdgeType.Property:return this.appendPropertyName(edge.to,edge.data);case WI.HeapSnapshotEdgeProxy.EdgeType.Variable:return this.appendVariableName(edge.to,edge.data);}
console.error("Unexpected edge type",edge.type);}};WI.HeapSnapshotRootPath.SpecialPathComponent={InternalPropertyName:"@internal",};WI.IndexedDatabase=class IndexedDatabase
{constructor(name,securityOrigin,version,objectStores)
{this._name=name;this._securityOrigin=securityOrigin;this._host=parseSecurityOrigin(securityOrigin).host;this._version=version;this._objectStores=objectStores||[];for(var objectStore of this._objectStores)
objectStore.establishRelationship(this);} 
get name(){return this._name;}
get securityOrigin(){return this._securityOrigin;}
get host(){return this._host;}
get version(){return this._version;}
get objectStores(){return this._objectStores;}
saveIdentityToCookie(cookie)
{cookie[WI.IndexedDatabase.NameCookieKey]=this._name;cookie[WI.IndexedDatabase.HostCookieKey]=this._host;}};WI.IndexedDatabase.TypeIdentifier="indexed-database";WI.IndexedDatabase.NameCookieKey="indexed-database-name";WI.IndexedDatabase.HostCookieKey="indexed-database-host";WI.IndexedDatabaseObjectStore=class IndexedDatabaseObjectStore
{constructor(name,keyPath,autoIncrement,indexes)
{this._name=name;this._keyPath=keyPath;this._autoIncrement=autoIncrement||false;this._indexes=indexes||[];this._parentDatabase=null;for(var index of this._indexes)
index.establishRelationship(this);} 
get name(){return this._name;}
get keyPath(){return this._keyPath;}
get autoIncrement(){return this._autoIncrement;}
get parentDatabase(){return this._parentDatabase;}
get indexes(){return this._indexes;}
saveIdentityToCookie(cookie)
{cookie[WI.IndexedDatabaseObjectStore.NameCookieKey]=this._name;cookie[WI.IndexedDatabaseObjectStore.KeyPathCookieKey]=this._keyPath;} 
establishRelationship(parentDatabase)
{this._parentDatabase=parentDatabase||null;}};WI.IndexedDatabaseObjectStore.TypeIdentifier="indexed-database-object-store";WI.IndexedDatabaseObjectStore.NameCookieKey="indexed-database-object-store-name";WI.IndexedDatabaseObjectStore.KeyPathCookieKey="indexed-database-object-store-key-path";WI.IndexedDatabaseObjectStoreIndex=class IndexedDatabaseObjectStoreIndex
{constructor(name,keyPath,unique,multiEntry)
{this._name=name;this._keyPath=keyPath;this._unique=unique||false;this._multiEntry=multiEntry||false;this._parentObjectStore=null;} 
get name(){return this._name;}
get keyPath(){return this._keyPath;}
get unique(){return this._unique;}
get multiEntry(){return this._multiEntry;}
get parentObjectStore(){return this._parentObjectStore;}
saveIdentityToCookie(cookie)
{cookie[WI.IndexedDatabaseObjectStoreIndex.NameCookieKey]=this._name;cookie[WI.IndexedDatabaseObjectStoreIndex.KeyPathCookieKey]=this._keyPath;} 
establishRelationship(parentObjectStore)
{this._parentObjectStore=parentObjectStore||null;}};WI.IndexedDatabaseObjectStoreIndex.TypeIdentifier="indexed-database-object-store-index";WI.IndexedDatabaseObjectStoreIndex.NameCookieKey="indexed-database-object-store-index-name";WI.IndexedDatabaseObjectStoreIndex.KeyPathCookieKey="indexed-database-object-store-index-key-path";WI.IssueMessage=class IssueMessage extends WI.Object
{constructor(consoleMessage)
{super();this._consoleMessage=consoleMessage;this._text=this._issueText();switch(this._consoleMessage.source){case WI.ConsoleMessage.MessageSource.JS:
var prefixRegex=/^([^:]+): (?:DOM Exception \d+: )?/;var match=prefixRegex.exec(this._text);if(match&&match[1]in WI.IssueMessage.Type._prefixTypeMap){this._type=WI.IssueMessage.Type._prefixTypeMap[match[1]];this._text=this._text.substring(match[0].length);}else
this._type=WI.IssueMessage.Type.OtherIssue;break;case WI.ConsoleMessage.MessageSource.CSS:case WI.ConsoleMessage.MessageSource.XML:this._type=WI.IssueMessage.Type.PageIssue;break;case WI.ConsoleMessage.MessageSource.Network:this._type=WI.IssueMessage.Type.NetworkIssue;break;case WI.ConsoleMessage.MessageSource.Security:this._type=WI.IssueMessage.Type.SecurityIssue;break;case WI.ConsoleMessage.MessageSource.ConsoleAPI:case WI.ConsoleMessage.MessageSource.Storage:case WI.ConsoleMessage.MessageSource.Appcache:case WI.ConsoleMessage.MessageSource.Rendering:case WI.ConsoleMessage.MessageSource.Media:case WI.ConsoleMessage.MessageSource.Mediasource:case WI.ConsoleMessage.MessageSource.WebRTC:case WI.ConsoleMessage.MessageSource.ITPDebug:case WI.ConsoleMessage.MessageSource.PrivateClickMeasurement:case WI.ConsoleMessage.MessageSource.PaymentRequest:case WI.ConsoleMessage.MessageSource.AdClickAttribution:case WI.ConsoleMessage.MessageSource.Other:this._type=WI.IssueMessage.Type.OtherIssue;break;default:console.error("Unknown issue source:",this._consoleMessage.source);this._type=WI.IssueMessage.Type.OtherIssue;}
this._sourceCodeLocation=consoleMessage.sourceCodeLocation;if(this._sourceCodeLocation)
this._sourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,this._sourceCodeLocationDisplayLocationChanged,this);} 
static displayName(type)
{switch(type){case WI.IssueMessage.Type.SemanticIssue:return WI.UIString("Semantic Issue");case WI.IssueMessage.Type.RangeIssue:return WI.UIString("Range Issue");case WI.IssueMessage.Type.ReferenceIssue:return WI.UIString("Reference Issue");case WI.IssueMessage.Type.TypeIssue:return WI.UIString("Type Issue");case WI.IssueMessage.Type.PageIssue:return WI.UIString("Page Issue");case WI.IssueMessage.Type.NetworkIssue:return WI.UIString("Network Issue");case WI.IssueMessage.Type.SecurityIssue:return WI.UIString("Security Issue");case WI.IssueMessage.Type.OtherIssue:return WI.UIString("Other Issue");default:console.error("Unknown issue message type:",type);return WI.UIString("Other Issue");}} 
get text(){return this._text;}
get type(){return this._type;}
get level(){return this._consoleMessage.level;}
get source(){return this._consoleMessage.source;}
get url(){return this._consoleMessage.url;}
get sourceCodeLocation(){return this._sourceCodeLocation;} 
saveIdentityToCookie(cookie)
{cookie[WI.IssueMessage.URLCookieKey]=this.url;cookie[WI.IssueMessage.LineNumberCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:0;cookie[WI.IssueMessage.ColumnNumberCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:0;} 
_issueText()
{let parameters=this._consoleMessage.parameters;if(!parameters)
return this._consoleMessage.messageText;if(parameters[0].type!=="string")
return this._consoleMessage.messageText;function valueFormatter(obj)
{return obj.description;}
let formatters={};formatters.o=valueFormatter;formatters.s=valueFormatter;formatters.f=valueFormatter;formatters.i=valueFormatter;formatters.d=valueFormatter;function append(a,b)
{a+=b;return a;}
let result=String.format(parameters[0].description,parameters.slice(1),formatters,"",append);let resultText=result.formattedResult;for(let i=0;i<result.unusedSubstitutions.length;++i)
resultText+=" "+result.unusedSubstitutions[i].description;return resultText;}
_sourceCodeLocationDisplayLocationChanged(event)
{this.dispatchEventToListeners(WI.IssueMessage.Event.DisplayLocationDidChange,event.data);}};WI.IssueMessage.Level={Error:"error",Warning:"warning"};WI.IssueMessage.Type={SemanticIssue:"issue-message-type-semantic-issue",RangeIssue:"issue-message-type-range-issue",ReferenceIssue:"issue-message-type-reference-issue",TypeIssue:"issue-message-type-type-issue",PageIssue:"issue-message-type-page-issue",NetworkIssue:"issue-message-type-network-issue",SecurityIssue:"issue-message-type-security-issue",OtherIssue:"issue-message-type-other-issue"};WI.IssueMessage.TypeIdentifier="issue-message";WI.IssueMessage.URLCookieKey="issue-message-url";WI.IssueMessage.LineNumberCookieKey="issue-message-line-number";WI.IssueMessage.ColumnNumberCookieKey="issue-message-column-number";WI.IssueMessage.Event={LocationDidChange:"issue-message-location-did-change",DisplayLocationDidChange:"issue-message-display-location-did-change"};WI.IssueMessage.Type._prefixTypeMap={"SyntaxError":WI.IssueMessage.Type.SemanticIssue,"URIError":WI.IssueMessage.Type.SemanticIssue,"AggregateError":WI.IssueMessage.Type.SemanticIssue,"EvalError":WI.IssueMessage.Type.SemanticIssue,"INVALID_CHARACTER_ERR":WI.IssueMessage.Type.SemanticIssue,"SYNTAX_ERR":WI.IssueMessage.Type.SemanticIssue,"RangeError":WI.IssueMessage.Type.RangeIssue,"INDEX_SIZE_ERR":WI.IssueMessage.Type.RangeIssue,"DOMSTRING_SIZE_ERR":WI.IssueMessage.Type.RangeIssue,"ReferenceError":WI.IssueMessage.Type.ReferenceIssue,"HIERARCHY_REQUEST_ERR":WI.IssueMessage.Type.ReferenceIssue,"INVALID_STATE_ERR":WI.IssueMessage.Type.ReferenceIssue,"NOT_FOUND_ERR":WI.IssueMessage.Type.ReferenceIssue,"WRONG_DOCUMENT_ERR":WI.IssueMessage.Type.ReferenceIssue,"TypeError":WI.IssueMessage.Type.TypeIssue,"INVALID_NODE_TYPE_ERR":WI.IssueMessage.Type.TypeIssue,"TYPE_MISMATCH_ERR":WI.IssueMessage.Type.TypeIssue,"SECURITY_ERR":WI.IssueMessage.Type.SecurityIssue,"NETWORK_ERR":WI.IssueMessage.Type.NetworkIssue,"ABORT_ERR":WI.IssueMessage.Type.OtherIssue,"DATA_CLONE_ERR":WI.IssueMessage.Type.OtherIssue,"INUSE_ATTRIBUTE_ERR":WI.IssueMessage.Type.OtherIssue,"INVALID_ACCESS_ERR":WI.IssueMessage.Type.OtherIssue,"INVALID_MODIFICATION_ERR":WI.IssueMessage.Type.OtherIssue,"NAMESPACE_ERR":WI.IssueMessage.Type.OtherIssue,"NOT_SUPPORTED_ERR":WI.IssueMessage.Type.OtherIssue,"NO_DATA_ALLOWED_ERR":WI.IssueMessage.Type.OtherIssue,"NO_MODIFICATION_ALLOWED_ERR":WI.IssueMessage.Type.OtherIssue,"QUOTA_EXCEEDED_ERR":WI.IssueMessage.Type.OtherIssue,"TIMEOUT_ERR":WI.IssueMessage.Type.OtherIssue,"URL_MISMATCH_ERR":WI.IssueMessage.Type.OtherIssue,"VALIDATION_ERR":WI.IssueMessage.Type.OtherIssue};WI.JavaScriptBreakpoint=class JavaScriptBreakpoint extends WI.Breakpoint
{constructor(sourceCodeLocation,{contentIdentifier,resolved,disabled,condition,actions,ignoreCount,autoContinue}={})
{super({disabled,condition,actions,ignoreCount,autoContinue});this._id=null;this._sourceCodeLocation=sourceCodeLocation;let sourceCode=this._sourceCodeLocation.sourceCode;if(sourceCode){this._contentIdentifier=sourceCode.contentIdentifier;}else
this._contentIdentifier=contentIdentifier||null;this._scriptIdentifier=sourceCode instanceof WI.Script?sourceCode.id:null;this._target=sourceCode instanceof WI.Script?sourceCode.target:null;this._resolved=!!resolved;this._sourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._sourceCodeLocationLocationChanged,this);this._sourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,this._sourceCodeLocationDisplayLocationChanged,this);} 
static supportsMicrotasks(parameter)
{return InspectorBackend.hasCommand("Debugger.setPauseOnMicrotasks",parameter);}
static supportsDebuggerStatements(parameter)
{return InspectorBackend.hasCommand("Debugger.setPauseOnDebuggerStatements",parameter);} 
static fromJSON(json)
{const sourceCode=null;return new WI.JavaScriptBreakpoint(new WI.SourceCodeLocation(sourceCode,json.lineNumber||0,json.columnNumber||0),{contentIdentifier:json.contentIdentifier||json.url,resolved:json.resolved,disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});}
toJSON(key)
{let json=super.toJSON(key);if(this._contentIdentifier)
json.contentIdentifier=this._contentIdentifier;if(isFinite(this._sourceCodeLocation.lineNumber))
json.lineNumber=this._sourceCodeLocation.lineNumber;if(isFinite(this._sourceCodeLocation.columnNumber))
json.columnNumber=this._sourceCodeLocation.columnNumber;if(key===WI.ObjectStore.toJSONSymbol)
json[WI.objectStores.breakpoints.keyPath]=this._contentIdentifier+":"+this._sourceCodeLocation.lineNumber+":"+this._sourceCodeLocation.columnNumber;return json;} 
get sourceCodeLocation(){return this._sourceCodeLocation;}
get contentIdentifier(){return this._contentIdentifier;}
get scriptIdentifier(){return this._scriptIdentifier;}
get target(){return this._target;}
get displayName()
{switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:return WI.repeatedUIString.debuggerStatements();case WI.debuggerManager.allExceptionsBreakpoint:return WI.repeatedUIString.allExceptions();case WI.debuggerManager.uncaughtExceptionsBreakpoint:return WI.repeatedUIString.uncaughtExceptions();case WI.debuggerManager.assertionFailuresBreakpoint:return WI.repeatedUIString.assertionFailures();case WI.debuggerManager.allMicrotasksBreakpoint:return WI.repeatedUIString.allMicrotasks();}
return this._sourceCodeLocation.displayLocationString()}
get special()
{switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:case WI.debuggerManager.assertionFailuresBreakpoint:case WI.debuggerManager.allMicrotasksBreakpoint:return true;}
if(this._isSpecial())
return true;return super.special;}
get removable()
{switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:return false;}
return super.removable;}
get editable()
{switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:return WI.JavaScriptBreakpoint.supportsDebuggerStatements("options");case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:return InspectorBackend.hasCommand("Debugger.setPauseOnExceptions","options");case WI.debuggerManager.assertionFailuresBreakpoint:return InspectorBackend.hasCommand("Debugger.setPauseOnAssertions","options");case WI.debuggerManager.allMicrotasksBreakpoint:return WI.JavaScriptBreakpoint.supportsMicrotasks("options");}
return true;}
get identifier()
{return this._id;}
set identifier(id)
{this._id=id||null;}
get resolved()
{return super.resolved&&this._resolved;}
set resolved(resolved)
{if(this._resolved===resolved)
return;this._resolved=resolved||false;this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange);}
remove()
{super.remove();WI.debuggerManager.removeBreakpoint(this);}
saveIdentityToCookie(cookie)
{cookie["javascript-breakpoint-content-identifier"]=this._contentIdentifier;cookie["javascript-breakpoint-line-number"]=this._sourceCodeLocation.lineNumber;cookie["javascript-breakpoint-column-number"]=this._sourceCodeLocation.columnNumber;} 
_isSpecial()
{return this._sourceCodeLocation.isEqual(WI.SourceCodeLocation.specialBreakpointLocation);}
_sourceCodeLocationLocationChanged(event)
{this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.LocationDidChange,event.data);}
_sourceCodeLocationDisplayLocationChanged(event)
{this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,event.data);}};WI.JavaScriptBreakpoint.TypeIdentifier="javascript-breakpoint";WI.JavaScriptBreakpoint.Event={ResolvedStateDidChange:"javascript-breakpoint-resolved-state-did-change",LocationDidChange:"javascript-breakpoint-location-did-change",DisplayLocationDidChange:"javascript-breakpoint-display-location-did-change",};WI.JavaScriptBreakpoint.ReferencePage=WI.ReferencePage.JavaScriptBreakpoints;WI.KeyboardShortcut=class KeyboardShortcut
{constructor(modifiers,key,callback,targetElement)
{if(typeof key==="string"){key=key[0].toUpperCase();key=new WI.Key(key.charCodeAt(0),key);}
if(callback&&!targetElement)
targetElement=document;this._modifiers=modifiers||WI.KeyboardShortcut.Modifier.None;this._key=key;this._targetElement=targetElement;this._callback=callback;this._disabled=false;this._implicitlyPreventsDefault=true;if(targetElement){var targetKeyboardShortcuts=targetElement._keyboardShortcuts;if(!targetKeyboardShortcuts)
targetKeyboardShortcuts=targetElement._keyboardShortcuts=[];targetKeyboardShortcuts.push(this);if(!WI.KeyboardShortcut._registeredKeyDownListener){WI.KeyboardShortcut._registeredKeyDownListener=true;window.addEventListener("keydown",WI.KeyboardShortcut._handleKeyDown);}}} 
static _handleKeyDown(event)
{if(event.defaultPrevented)
return;for(var targetElement=event.target;targetElement;targetElement=targetElement.parentNode){if(!targetElement._keyboardShortcuts)
continue;for(var i=0;i<targetElement._keyboardShortcuts.length;++i){var keyboardShortcut=targetElement._keyboardShortcuts[i];if(!keyboardShortcut.matchesEvent(event))
continue;if(!keyboardShortcut.callback)
continue;keyboardShortcut.callback(event,keyboardShortcut);if(keyboardShortcut.implicitlyPreventsDefault)
event.preventDefault();return;}}} 
get modifiers()
{return this._modifiers;}
get key()
{return this._key;}
get displayName()
{var result="";if(this._modifiers&WI.KeyboardShortcut.Modifier.Control)
result+="\u2303";if(this._modifiers&WI.KeyboardShortcut.Modifier.Option)
result+=WI.Platform.name==="mac"?"\u2325":"\u2387";if(this._modifiers&WI.KeyboardShortcut.Modifier.Shift)
result+="\u21e7";if(this._modifiers&WI.KeyboardShortcut.Modifier.Command)
result+="\u2318";result+=this._key.toString();return result;}
get callback()
{return this._callback;}
set callback(callback)
{this._callback=callback||null;}
get disabled()
{return this._disabled;}
set disabled(disabled)
{this._disabled=disabled||false;}
get implicitlyPreventsDefault()
{return this._implicitlyPreventsDefault;}
set implicitlyPreventsDefault(implicitly)
{this._implicitlyPreventsDefault=implicitly;}
unbind()
{this._disabled=true;if(!this._targetElement)
return;var targetKeyboardShortcuts=this._targetElement._keyboardShortcuts;if(!targetKeyboardShortcuts)
return;targetKeyboardShortcuts.remove(this);}
matchesEvent(event)
{if(this._disabled)
return false;if(this._key.keyCode!==event.keyCode)
return false;var eventModifiers=WI.KeyboardShortcut.Modifier.None;if(event.shiftKey)
eventModifiers|=WI.KeyboardShortcut.Modifier.Shift;if(event.ctrlKey)
eventModifiers|=WI.KeyboardShortcut.Modifier.Control;if(event.altKey)
eventModifiers|=WI.KeyboardShortcut.Modifier.Option;if(event.metaKey)
eventModifiers|=WI.KeyboardShortcut.Modifier.Command;return this._modifiers===eventModifiers;}};WI.Key=class Key
{constructor(keyCode,displayName)
{this._keyCode=keyCode;this._displayName=displayName;} 
get keyCode()
{return this._keyCode;}
get displayName()
{return this._displayName;}
toString()
{return this._displayName;}};WI.KeyboardShortcut.Modifier={None:0,Shift:1,Control:2,Option:4,Command:8,get CommandOrControl()
{return WI.Platform.name==="mac"?this.Command:this.Control;}};WI.KeyboardShortcut.Key={Backspace:new WI.Key(8,"\u232b"),Tab:new WI.Key(9,"\u21e5"),Enter:new WI.Key(13,"\u21a9"),Escape:new WI.Key(27,"\u238b"),Space:new WI.Key(32,"Space"),PageUp:new WI.Key(33,"\u21de"),PageDown:new WI.Key(34,"\u21df"),End:new WI.Key(35,"\u2198"),Home:new WI.Key(36,"\u2196"),Left:new WI.Key(37,"\u2190"),Up:new WI.Key(38,"\u2191"),Right:new WI.Key(39,"\u2192"),Down:new WI.Key(40,"\u2193"),Delete:new WI.Key(46,"\u2326"),Zero:new WI.Key(48,"0"),F1:new WI.Key(112,"F1"),F2:new WI.Key(113,"F2"),F3:new WI.Key(114,"F3"),F4:new WI.Key(115,"F4"),F5:new WI.Key(116,"F5"),F6:new WI.Key(117,"F6"),F7:new WI.Key(118,"F7"),F8:new WI.Key(119,"F8"),F9:new WI.Key(120,"F9"),F10:new WI.Key(121,"F10"),F11:new WI.Key(122,"F11"),F12:new WI.Key(123,"F12"),Semicolon:new WI.Key(186,";"),Plus:new WI.Key(187,"+"),Comma:new WI.Key(188,","),Minus:new WI.Key(189,"-"),Period:new WI.Key(190,"."),Slash:new WI.Key(191,"/"),Apostrophe:new WI.Key(192,"`"),LeftCurlyBrace:new WI.Key(219,"{"),Backslash:new WI.Key(220,"\\"),RightCurlyBrace:new WI.Key(221,"}"),SingleQuote:new WI.Key(222,"'")};WI.Layer=class Layer{constructor(layerId,nodeId,bounds,paintCount,memory,compositedBounds,isInShadowTree,isReflection,isGeneratedContent,isAnonymous,pseudoElementId,pseudoElement)
{this._layerId=layerId;this._nodeId=nodeId;this._bounds=bounds;this._paintCount=paintCount;this._memory=memory;this._compositedBounds=compositedBounds;this._isInShadowTree=isInShadowTree;this._isReflection=isReflection;this._isGeneratedContent=isGeneratedContent;this._isAnonymous=isAnonymous;this._pseudoElementId=pseudoElementId;this._pseudoElement=pseudoElement;this._compositedBounds.x=this._bounds.x;this._compositedBounds.y=this._bounds.y;} 
static fromPayload(payload)
{return new WI.Layer(payload.layerId,payload.nodeId,payload.bounds,payload.paintCount,payload.memory,payload.compositedBounds,payload.isInShadowTree,payload.isReflection,payload.isGeneratedContent,payload.isAnonymous,payload.pseudoElementId,payload.pseudoElement);} 
get layerId(){return this._layerId;}
get nodeId(){return this._nodeId;}
get bounds(){return this._bounds;}
get paintCount(){return this._paintCount;}
get memory(){return this._memory;}
get compositedBounds(){return this._compositedBounds;}
get isInShadowTree(){return this._isInShadowTree;}
get isReflection(){return this._isReflection;}
get isGeneratedContent(){return this._isGeneratedContent;}
get isAnonymous(){return this._isAnonymous;}
get pseudoElementId(){return this._pseudoElementId;}
get pseudoElement(){return this._pseudoElement;}};WI.LayoutInstrument=class LayoutInstrument extends WI.Instrument
{ get timelineRecordType()
{return WI.TimelineRecord.Type.Layout;}};WI.LayoutTimelineRecord=class LayoutTimelineRecord extends WI.TimelineRecord
{constructor(eventType,startTime,endTime,callFrames,sourceCodeLocation,quad)
{super(WI.TimelineRecord.Type.Layout,startTime,endTime,callFrames,sourceCodeLocation);if(eventType in WI.LayoutTimelineRecord.EventType)
eventType=WI.LayoutTimelineRecord.EventType[eventType];this._eventType=eventType;this._quad=quad||null;} 
static displayNameForEventType(eventType)
{switch(eventType){case WI.LayoutTimelineRecord.EventType.InvalidateStyles:return WI.UIString("Styles Invalidated");case WI.LayoutTimelineRecord.EventType.RecalculateStyles:return WI.UIString("Styles Recalculated");case WI.LayoutTimelineRecord.EventType.InvalidateLayout:return WI.UIString("Layout Invalidated");case WI.LayoutTimelineRecord.EventType.ForcedLayout:return WI.UIString("Forced Layout","Layout phase records that were imperative (forced)");case WI.LayoutTimelineRecord.EventType.Layout:return WI.repeatedUIString.timelineRecordLayout();case WI.LayoutTimelineRecord.EventType.Paint:return WI.repeatedUIString.timelineRecordPaint();case WI.LayoutTimelineRecord.EventType.Composite:return WI.repeatedUIString.timelineRecordComposite();}} 
static async fromJSON(json)
{let{eventType,startTime,endTime,callFrames,sourceCodeLocation,quad}=json;quad=quad?WI.Quad.fromJSON(quad):null;return new WI.LayoutTimelineRecord(eventType,startTime,endTime,callFrames,sourceCodeLocation,quad);}
toJSON()
{
 return{type:this.type,eventType:this._eventType,startTime:this.startTime,endTime:this.endTime,quad:this._quad||undefined,};} 
get eventType()
{return this._eventType;}
get width()
{return this._quad?this._quad.width:NaN;}
get height()
{return this._quad?this._quad.height:NaN;}
get area()
{return this.width*this.height;}
get quad()
{return this._quad;}
saveIdentityToCookie(cookie)
{super.saveIdentityToCookie(cookie);cookie[WI.LayoutTimelineRecord.EventTypeCookieKey]=this._eventType;}};WI.LayoutTimelineRecord.EventType={InvalidateStyles:"invalidate-styles",RecalculateStyles:"recalculate-styles",InvalidateLayout:"invalidate-layout",ForcedLayout:"forced-layout",Layout:"layout",Paint:"paint",Composite:"composite"};WI.LayoutTimelineRecord.TypeIdentifier="layout-timeline-record";WI.LayoutTimelineRecord.EventTypeCookieKey="layout-timeline-record-event-type";
WI.LazySourceCodeLocation=class LazySourceCodeLocation extends WI.SourceCodeLocation
{constructor(sourceCode,lineNumber,columnNumber)
{super(null,lineNumber,columnNumber);this._initialized=false;this._lazySourceCode=sourceCode;} 
isEqual(other)
{if(!other)
return false;return this._lazySourceCode===other._sourceCode&&this._lineNumber===other._lineNumber&&this._columnNumber===other._columnNumber;}
get sourceCode()
{return this._lazySourceCode;}
set sourceCode(sourceCode)
{this.setSourceCode(sourceCode);}
get formattedLineNumber()
{this._lazyInitialization();return this._formattedLineNumber;}
get formattedColumnNumber()
{this._lazyInitialization();return this._formattedColumnNumber;}
formattedPosition()
{this._lazyInitialization();return new WI.SourceCodePosition(this._formattedLineNumber,this._formattedColumnNumber);}
hasFormattedLocation()
{this._lazyInitialization();return super.hasFormattedLocation();}
hasDifferentDisplayLocation()
{this._lazyInitialization();return super.hasDifferentDisplayLocation();} 
resolveMappedLocation()
{this._lazyInitialization();super.resolveMappedLocation();} 
_lazyInitialization()
{if(!this._initialized){this._initialized=true;this.sourceCode=this._lazySourceCode;}}};WI.LineWidget=class LineWidget
{constructor(codeMirrorLineWidget,widgetElement)
{this._codeMirrorLineWidget=codeMirrorLineWidget;this._widgetElement=widgetElement;} 
get codeMirrorLineWidget()
{return this._codeMirrorLineWidget;}
get widgetElement()
{return this._widgetElement;}
clear()
{this._codeMirrorLineWidget.clear();}
update()
{if(this._codeMirrorLineWidget.update)
this._codeMirrorLineWidget.update();}};WI.LocalResourceOverride=class LocalResourceOverride extends WI.Object
{constructor(url,type,localResource,{isCaseSensitive,isRegex,disabled}={})
{super();this._url=url;this._urlComponents=null;this._type=type;this._localResource=localResource;this._isCaseSensitive=isCaseSensitive!==undefined?isCaseSensitive:true;this._isRegex=isRegex!==undefined?isRegex:false;this._disabled=disabled!==undefined?disabled:false;this._localResource._localResourceOverride=this;} 
static create(url,type,{requestURL,requestMethod,requestHeaders,requestData,responseMIMEType,responseContent,responseBase64Encoded,responseStatusCode,responseStatusText,responseHeaders,isCaseSensitive,isRegex,disabled}={})
{let localResource=new WI.LocalResource({request:{url:requestURL||"",method:requestMethod,headers:requestHeaders,data:requestData,},response:{headers:responseHeaders,mimeType:responseMIMEType,statusCode:responseStatusCode,statusText:responseStatusText,content:responseContent,base64Encoded:responseBase64Encoded,},});return new WI.LocalResourceOverride(url,type,localResource,{isCaseSensitive,isRegex,disabled});}
static displayNameForType(type)
{switch(type){case WI.LocalResourceOverride.InterceptType.Request:return WI.UIString("Request","Request @ Local Override Type","Text indicating that the local override intercepts the request phase of network activity.");case WI.LocalResourceOverride.InterceptType.Response:return WI.UIString("Response","Response @ Local Override Type","Text indicating that the local override intercepts the response phase of network activity.");case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:return WI.UIString("Response (skip network)","Response (skip network) @ Local Override Type","Text indicating that the local override will skip all network activity and instead immediately serve the response.");}
return"";} 
static fromJSON(json)
{let{url,type,localResource:localResourceJSON,isCaseSensitive,isRegex,disabled}=json;let localResource=WI.LocalResource.fromJSON(localResourceJSON);url??=localResource.url;type??=WI.LocalResourceOverride.InterceptType.Response;return new WI.LocalResourceOverride(url,type,localResource,{isCaseSensitive,isRegex,disabled});}
toJSON(key)
{let json={url:this._url,type:this._type,localResource:this._localResource.toJSON(key),isCaseSensitive:this._isCaseSensitive,isRegex:this._isRegex,disabled:this._disabled,};if(key===WI.ObjectStore.toJSONSymbol)
json[WI.objectStores.localResourceOverrides.keyPath]=this._url;return json;} 
get url(){return this._url;}
get type(){return this._type;}
get localResource(){return this._localResource;}
get isCaseSensitive(){return this._isCaseSensitive;}
get isRegex(){return this._isRegex;}
get urlComponents()
{if(!this._urlComponents)
this._urlComponents=parseURL(this._url);return this._urlComponents;}
get disabled()
{return this._disabled;}
set disabled(disabled)
{if(this._disabled===disabled)
return;this._disabled=!!disabled;this.dispatchEventToListeners(WI.LocalResourceOverride.Event.DisabledChanged);}
get displayName()
{return this.displayURL();}
displayURL({full}={})
{if(this._isRegex)
return"/"+this._url+"/"+(!this._isCaseSensitive?"i":"");let displayName=full?this._url:WI.displayNameForURL(this._url,this.urlComponents);if(!this._isCaseSensitive)
displayName=WI.UIString("%s (Case Insensitive)","%s (Case Insensitive) @ Local Override","Label for case-insensitive URL match pattern of a local override.").format(displayName);return displayName;}
matches(url)
{if(this._isRegex){let regex=new RegExp(this._url,!this._isCaseSensitive?"i":"");return regex.test(url);}
if(!this._isCaseSensitive)
return String(url).toLowerCase()===this._url.toLowerCase();return url===this._url;}
equals(localResourceOverrideOrSerializedData)
{return localResourceOverrideOrSerializedData.url===this._url&&localResourceOverrideOrSerializedData.isCaseSensitive===this._isCaseSensitive&&localResourceOverrideOrSerializedData.isRegex===this._isRegex;} 
saveIdentityToCookie(cookie)
{cookie["local-resource-override-url"]=this._url;cookie["local-resource-override-type"]=this._type;cookie["local-resource-override-is-case-sensitive"]=this._isCaseSensitive;cookie["local-resource-override-is-regex"]=this._isRegex;cookie["local-resource-override-disabled"]=this._disabled;}};WI.LocalResourceOverride.TypeIdentifier="local-resource-override";WI.LocalResourceOverride.InterceptType={Request:"request",Response:"response",ResponseSkippingNetwork:"response-skipping-network",};WI.LocalResourceOverride.Event={DisabledChanged:"local-resource-override-disabled-state-did-change",};WI.LogObject=class LogObject
{};WI.LoggingChannel=class LoggingChannel
{constructor(source,level)
{this._source=source;this._level=level;} 
static fromPayload(payload)
{return new WI.LoggingChannel(payload.source,payload.level);} 
get source(){return this._source;}
get level(){return this._level;}};WI.LoggingChannel.Level={Off:"off",Basic:"basic",Verbose:"verbose",};WI.MediaInstrument=class MediaInstrument extends WI.Instrument
{constructor()
{super();} 
static supported()
{return InspectorBackend.hasEvent("DOM.didFireEvent");} 
get timelineRecordType()
{return WI.TimelineRecord.Type.Media;}
startInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){if(InspectorBackend.hasDomain("Animation")){let target=WI.assumingMainTarget();target.AnimationAgent.startTracking();}}}
stopInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){if(InspectorBackend.hasDomain("Animation")){let target=WI.assumingMainTarget();target.AnimationAgent.stopTracking();}}}};WI.MediaTimeline=class MediaTimeline extends WI.Timeline
{ recordForTrackingAnimationId(trackingAnimationId)
{return this._trackingAnimationIdRecordMap.get(trackingAnimationId)||null;}
recordForMediaElementEvents(domNode)
{return this._mediaElementRecordMap.get(domNode)||null;}
reset(suppressEvents)
{this._trackingAnimationIdRecordMap=new Map;this._mediaElementRecordMap=new Map;super.reset(suppressEvents);}
addRecord(record,options={})
{if(record.trackingAnimationId){this._trackingAnimationIdRecordMap.set(record.trackingAnimationId,record);}
if(record.eventType===WI.MediaTimelineRecord.EventType.MediaElement){this._mediaElementRecordMap.set(record.domNode,record);}
super.addRecord(record,options);}};WI.MediaTimelineRecord=class MediaTimelineRecord extends WI.TimelineRecord
{constructor(eventType,domNodeOrInfo,{trackingAnimationId,animationName,transitionProperty}={})
{super(WI.TimelineRecord.Type.Media);this._eventType=eventType;this._domNode=domNodeOrInfo;this._domNodeDisplayName=domNodeOrInfo?.displayName;this._domNodeCSSPath=domNodeOrInfo instanceof WI.DOMNode?WI.cssPath(domNodeOrInfo,{full:true}):domNodeOrInfo?.cssPath; this._trackingAnimationId=trackingAnimationId||null; this._animationName=animationName||null;this._transitionProperty=transitionProperty||null;this._timestamps=[];this._activeStartTime=NaN;} 
static async fromJSON(json)
{let{eventType,domNodeDisplayName,domNodeCSSPath,animationName,transitionProperty,timestamps}=json;let documentNode=null;if(InspectorBackend.hasDomain("DOM"))
documentNode=await new Promise((resolve)=>WI.domManager.requestDocument(resolve));let domNode=null;if(documentNode&&domNodeCSSPath){try{let nodeId=await documentNode.querySelector(domNodeCSSPath);if(nodeId)
domNode=WI.domManager.nodeForId(nodeId);}catch{}}
if(!domNode){domNode={displayName:domNodeDisplayName,cssPath:domNodeCSSPath,};}
let record=new MediaTimelineRecord(eventType,domNode,{animationName,transitionProperty});if(Array.isArray(timestamps)&&timestamps.length){record._timestamps=[];for(let item of timestamps){if(item.type===MediaTimelineRecord.TimestampType.MediaElementDOMEvent){if(documentNode&&item.originatorCSSPath){try{let nodeId=await documentNode.querySelector(item.originatorCSSPath);if(nodeId)
item.originator=WI.domManager.nodeForId(nodeId);}catch{}
if(!item.originator){item.originator={displayName:item.originatorDisplayName,cssPath:item.originatorCSSPath,};}}}
record._timestamps.push(item);}}
return record;}
toJSON()
{let json={eventType:this._eventType,domNodeDisplayName:this._domNodeDisplayName,domNodeCSSPath:this._domNodeCSSPath,};if(this._animationName)
json.animationName=this._animationName;if(this._transitionProperty)
json.transitionProperty=this._transitionProperty;if(this._timestamps.length){json.timestamps=this._timestamps.map((item)=>{if(item.type===MediaTimelineRecord.TimestampType.MediaElementDOMEvent&&item.originator instanceof WI.DOMNode)
delete item.originator;return item;});}
return json;} 
get eventType(){return this._eventType;}
get domNode(){return this._domNode;}
get trackingAnimationId(){return this._trackingAnimationId;}
get timestamps(){return this._timestamps;}
get activeStartTime(){return this._activeStartTime;}
get updatesDynamically()
{return true;}
get usesActiveStartTime()
{return true;}
get displayName()
{switch(this._eventType){case MediaTimelineRecord.EventType.CSSAnimation:return this._animationName;case MediaTimelineRecord.EventType.CSSTransition:return this._transitionProperty;case MediaTimelineRecord.EventType.MediaElement:return WI.UIString("Media Element");}
console.error("Unknown media record event type: ",this._eventType,this);return WI.UIString("Media Event");}
get subtitle()
{switch(this._eventType){case MediaTimelineRecord.EventType.CSSAnimation:return WI.UIString("CSS Animation");case MediaTimelineRecord.EventType.CSSTransition:return WI.UIString("CSS Transition");}
return"";}
saveIdentityToCookie(cookie)
{super.saveIdentityToCookie(cookie);cookie["media-timeline-record-event-type"]=this._eventType;cookie["media-timeline-record-dom-node"]=this._domNode instanceof WI.DOMNode?this._domNode.path():this._domNode;if(this._animationName)
cookie["media-timeline-record-animation-name"]=this._animationName;if(this._transitionProperty)
cookie["media-timeline-record-transition-property"]=this._transitionProperty;} 
updateAnimationState(timestamp,animationState)
{let type;switch(animationState){case InspectorBackend.Enum.Animation.AnimationState.Ready:type=MediaTimelineRecord.TimestampType.CSSAnimationReady;break;case InspectorBackend.Enum.Animation.AnimationState.Delayed:type=MediaTimelineRecord.TimestampType.CSSAnimationDelay;break;case InspectorBackend.Enum.Animation.AnimationState.Active:type=MediaTimelineRecord.TimestampType.CSSAnimationActive;break;case InspectorBackend.Enum.Animation.AnimationState.Canceled:type=MediaTimelineRecord.TimestampType.CSSAnimationCancel;break;case InspectorBackend.Enum.Animation.AnimationState.Done:type=MediaTimelineRecord.TimestampType.CSSAnimationDone;break;}
this._timestamps.push({type,timestamp});this._updateTimes();}
addDOMEvent(timestamp,domEvent)
{let data={type:MediaTimelineRecord.TimestampType.MediaElementDOMEvent,timestamp,eventName:domEvent.eventName,};if(domEvent.originator instanceof WI.DOMNode){data.originator=domEvent.originator;data.originatorDisplayName=data.originator.displayName;data.originatorCSSPath=WI.cssPath(data.originator,{full:true});}
if(!isEmptyObject(domEvent.data))
data.data=domEvent.data;this._timestamps.push(data);this._updateTimes();}
powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient)
{this._timestamps.push({type:MediaTimelineRecord.TimestampType.MediaElementPowerEfficientPlaybackStateChange,timestamp,isPowerEfficient,});this._updateTimes();} 
_updateTimes()
{let oldStartTime=this.startTime;let oldEndTime=this.endTime;let firstItem=this._timestamps[0];let lastItem=this._timestamps.lastValue;if(isNaN(this._startTime))
this._startTime=firstItem.timestamp;if(isNaN(this._activeStartTime)){if(this._eventType===MediaTimelineRecord.EventType.MediaElement)
this._activeStartTime=firstItem.timestamp;else if(firstItem.type===MediaTimelineRecord.TimestampType.CSSAnimationActive)
this._activeStartTime=firstItem.timestamp;}
switch(lastItem.type){case MediaTimelineRecord.TimestampType.CSSAnimationCancel:case MediaTimelineRecord.TimestampType.CSSAnimationDone:this._endTime=lastItem.timestamp;break;case MediaTimelineRecord.TimestampType.MediaElementDOMEvent:if(WI.DOMNode.isPlayEvent(lastItem.eventName))
this._endTime=NaN;else if(!isNaN(this._endTime)||WI.DOMNode.isPauseEvent(lastItem.eventName)||WI.DOMNode.isStopEvent(lastItem.eventName))
this._endTime=lastItem.timestamp;break;}
if(this.startTime!==oldStartTime||this.endTime!==oldEndTime)
this.dispatchEventToListeners(WI.TimelineRecord.Event.Updated);}};WI.MediaTimelineRecord.EventType={CSSAnimation:"css-animation",CSSTransition:"css-transition",MediaElement:"media-element",};WI.MediaTimelineRecord.TimestampType={CSSAnimationReady:"css-animation-ready",CSSAnimationDelay:"css-animation-delay",CSSAnimationActive:"css-animation-active",CSSAnimationCancel:"css-animation-cancel",CSSAnimationDone:"css-animation-done",MediaElementDOMEvent:"media-element-dom-event",MediaElementPowerEfficientPlaybackStateChange:"media-element-power-efficient-playback-state-change",};WI.MemoryCategory=class MemoryCategory
{constructor(type,size)
{this.type=type;this.size=size;}};WI.MemoryCategory.Type={JavaScript:"javascript",Images:"images",Layers:"layers",Page:"page",};WI.MemoryInstrument=class MemoryInstrument extends WI.Instrument
{ get timelineRecordType()
{return WI.TimelineRecord.Type.Memory;}
startInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.MemoryAgent.startTracking();}}
stopInstrumentation(initiatedByBackend)
{if(!initiatedByBackend){let target=WI.assumingMainTarget();target.MemoryAgent.stopTracking();}}};WI.MemoryPressureEvent=class MemoryPressureEvent
{constructor(timestamp,severity)
{this._timestamp=timestamp;this._severity=severity;} 
static fromPayload(timestamp,protocolSeverity)
{let severity;switch(protocolSeverity){case InspectorBackend.Enum.Memory.MemoryPressureSeverity.Critical:severity=WI.MemoryPressureEvent.Severity.Critical;break;case InspectorBackend.Enum.Memory.MemoryPressureSeverity.NonCritical:severity=WI.MemoryPressureEvent.Severity.NonCritical;break;default:console.error("Unexpected memory pressure severity",protocolSeverity);severity=WI.MemoryPressureEvent.Severity.NonCritical;break;}
return new WI.MemoryPressureEvent(timestamp,severity);} 
static fromJSON(json)
{let{timestamp,severity}=json;return new WI.MemoryPressureEvent(timestamp,severity);}
toJSON()
{return{timestamp:this._timestamp,severity:this._severity,};} 
get timestamp(){return this._timestamp;}
get severity(){return this._severity;}};WI.MemoryPressureEvent.Severity={Critical:"critical",NonCritical:"non-critical",};WI.MemoryTimeline=class MemoryTimeline extends WI.Timeline
{ get memoryPressureEvents(){return this._pressureEvents;}
addMemoryPressureEvent(memoryPressureEvent)
{this._pressureEvents.push(memoryPressureEvent);this.dispatchEventToListeners(WI.MemoryTimeline.Event.MemoryPressureEventAdded,{memoryPressureEvent});} 
reset(suppressEvents)
{super.reset(suppressEvents);this._pressureEvents=[];}
addRecord(record,options={})
{let lastRecord=this.records.lastValue;if(lastRecord){let startTime=lastRecord.endTime;if(options.discontinuity)
startTime=options.discontinuity.endTime;record.adjustStartTime(startTime);}
super.addRecord(record,options);}};WI.MemoryTimeline.Event={MemoryPressureEventAdded:"memory-timeline-memory-pressure-event-added",};WI.MemoryTimelineRecord=class MemoryTimelineRecord extends WI.TimelineRecord
{constructor(timestamp,categories)
{super(WI.TimelineRecord.Type.Memory,timestamp-MemoryTimelineRecord.samplingRatePerSecond,timestamp);this._timestamp=timestamp;this._categories=WI.MemoryTimelineRecord.memoryCategoriesFromProtocol(categories);this._exportCategories=categories;this._totalSize=0;for(let{size}of categories)
this._totalSize+=size;} 
static get samplingRatePerSecond()
{return 0.5;}
static memoryCategoriesFromProtocol(categories)
{let javascriptSize=0;let imagesSize=0;let layersSize=0;let pageSize=0;for(let{type,size}of categories){switch(type){case InspectorBackend.Enum.Memory.CategoryDataType.JavaScript:case InspectorBackend.Enum.Memory.CategoryDataType.JIT:javascriptSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Images:imagesSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Layers:layersSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Page:case InspectorBackend.Enum.Memory.CategoryDataType.Other:pageSize+=size;break;default:console.warn("Unhandled Memory.CategoryDataType: "+type);break;}}
return[{type:WI.MemoryCategory.Type.JavaScript,size:javascriptSize},{type:WI.MemoryCategory.Type.Images,size:imagesSize},{type:WI.MemoryCategory.Type.Layers,size:layersSize},{type:WI.MemoryCategory.Type.Page,size:pageSize},];} 
static async fromJSON(json)
{let{timestamp,categories}=json;return new WI.MemoryTimelineRecord(timestamp,categories);}
toJSON()
{return{type:this.type,timestamp:this.startTime,categories:this._exportCategories,};} 
get timestamp(){return this._timestamp;}
get categories(){return this._categories;}
get totalSize(){return this._totalSize;}
get unadjustedStartTime(){return this._timestamp;}
adjustStartTime(startTime)
{this._startTime=startTime;}};WI.NativeConstructorFunctionParameters={Object:{assign:"target, ...sources",create:"prototype, [propertiesObject]",defineProperties:"object, properties",defineProperty:"object, propertyName, descriptor",freeze:"object",getOwnPropertyDescriptor:"object, propertyName",getOwnPropertyNames:"object",getOwnPropertySymbols:"object",getPrototypeOf:"object",is:"value1, value2",isExtensible:"object",isFrozen:"object",isSealed:"object",keys:"object",preventExtensions:"object",seal:"object",setPrototypeOf:"object, prototype",__proto__:null,},Array:{from:"arrayLike, [mapFunction], [thisArg]",isArray:"object",of:"[...values]",__proto__:null,},ArrayBuffer:{isView:"object",transfer:"oldBuffer, [newByteLength=length]",__proto__:null,},Number:{isFinite:"value",isInteger:"value",isNaN:"value",isSafeInteger:"value",parseFloat:"string",parseInt:"string, [radix]",__proto__:null,},Math:{abs:"x",acos:"x",acosh:"x",asin:"x",asinh:"x",atan2:"y, x",atan:"x",atanh:"x",cbrt:"x",ceil:"x",clz32:"x",cos:"x",cosh:"x",exp:"x",expm1:"x",floor:"x",fround:"x",hypot:"[...x]",imul:"x",log:"x",log1p:"x",log2:"x",log10:"x",max:"[...x]",min:"[...x]",pow:"x, y",round:"x",sign:"x",sin:"x",sinh:"x",sqrt:"x",tan:"x",tanh:"x",trunc:"x",__proto__:null,},JSON:{parse:"text, [reviver]",stringify:"value, [replacer], [space]",__proto__:null,},Date:{parse:"dateString",UTC:"year, [month], [day], [hour], [minute], [second], [ms]",__proto__:null,},Promise:{all:"iterable",race:"iterable",reject:"reason",resolve:"value",__proto__:null,},Reflect:{apply:"target, thisArgument, argumentsList",construct:"target, argumentsList, [newTarget=target]",defineProperty:"target, propertyKey, attributes",deleteProperty:"target, propertyKey",get:"target, propertyKey, [receiver]",getOwnPropertyDescriptor:"target, propertyKey",getPrototypeOf:"target",has:"target, propertyKey",isExtensible:"target",ownKeys:"target",preventExtensions:"target",set:"target, propertyKey, value, [receiver]",setPrototypeOf:"target, prototype",__proto__:null,},String:{fromCharCode:"...codeUnits",fromCodePoint:"...codePoints",raw:"template, ...substitutions",__proto__:null,},Symbol:{for:"key",keyFor:"symbol",__proto__:null,},Console:{assert:"condition, [message], [...values]",count:"label = \"default\"",countReset:"label = \"default\"",debug:"message, [...values]",dir:"object",dirxml:"object",error:"message, [...values]",group:"[name]",groupCollapsed:"[name]",groupEnd:"[name]",info:"message, [...values]",log:"message, [...values]",profile:"name",profileEnd:"name",record:"object, [options]",recordEnd:"object",screenshot:"[node]",table:"data, [columns]",takeHeapSnapshot:"[label]",time:"label = \"default\"",timeLog:"label = \"default\"",timeEnd:"label = \"default\"",timeStamp:"[label]",trace:"message, [...values]",warn:"message, [...values]",__proto__:null,},IDBKeyRangeConstructor:{bound:"lower, upper, [lowerOpen], [upperOpen]",lowerBound:"lower, [open]",only:"value",upperBound:"upper, [open]",__proto__:null,},MediaSourceConstructor:{isTypeSupported:"type",__proto__:null,},MediaStreamTrackConstructor:{getSources:"callback",__proto__:null,},NotificationConstructor:{requestPermission:"[callback]",__proto__:null,},URLConstructor:{createObjectURL:"blob",revokeObjectURL:"url",__proto__:null,},WebKitMediaKeysConstructor:{isTypeSupported:"keySystem, [type]",__proto__:null,},};WI.NativePrototypeFunctionParameters={Object:{__defineGetter__:"propertyName, getterFunction",__defineSetter__:"propertyName, setterFunction",__lookupGetter__:"propertyName",__lookupSetter__:"propertyName",hasOwnProperty:"propertyName",isPrototypeOf:"property",propertyIsEnumerable:"propertyName",__proto__:null,},Array:{concat:"value, ...",copyWithin:"targetIndex, startIndex, [endIndex=length]",every:"callback, [thisArg]",fill:"value, [startIndex=0], [endIndex=length]",filter:"callback, [thisArg]",find:"callback, [thisArg]",findIndex:"callback, [thisArg]",findLast:"callback, [thisArg]",findLastIndex:"callback, [thisArg]",forEach:"callback, [thisArg]",includes:"searchValue, [startIndex=0]",indexOf:"searchValue, [startIndex=0]",join:"[separator=\",\"]",lastIndexOf:"searchValue, [startIndex=length]",map:"callback, [thisArg]",push:"value, ...",reduce:"callback, [initialValue]",reduceRight:"callback, [initialValue]",slice:"[startIndex=0], [endIndex=length]",some:"callback, [thisArg]",sort:"[compareFunction]",splice:"startIndex, [deleteCount=0], ...itemsToAdd",__proto__:null,},ArrayBuffer:{slice:"startIndex, [endIndex=byteLength]",__proto__:null,},DataView:{setInt8:"byteOffset, value",setInt16:"byteOffset, value, [littleEndian=false]",setInt23:"byteOffset, value, [littleEndian=false]",setUint8:"byteOffset, value",setUint16:"byteOffset, value, [littleEndian=false]",setUint32:"byteOffset, value, [littleEndian=false]",setFloat32:"byteOffset, value, [littleEndian=false]",setFloat64:"byteOffset, value, [littleEndian=false]",getInt8:"byteOffset",getInt16:"byteOffset, [littleEndian=false]",getInt23:"byteOffset, [littleEndian=false]",getUint8:"byteOffset",getUint16:"byteOffset, [littleEndian=false]",getUint32:"byteOffset, [littleEndian=false]",getFloat32:"byteOffset, [littleEndian=false]",getFloat64:"byteOffset, [littleEndian=false]",__proto__:null,},Date:{setDate:"day",setFullYear:"year, [month=getMonth()], [day=getDate()]",setHours:"hours, [minutes=getMinutes()], [seconds=getSeconds()], [ms=getMilliseconds()]",setMilliseconds:"ms",setMinutes:"minutes, [seconds=getSeconds()], [ms=getMilliseconds()]",setMonth:"month, [day=getDate()]",setSeconds:"seconds, [ms=getMilliseconds()]",setTime:"time",setUTCDate:"day",setUTCFullYear:"year, [month=getUTCMonth()], [day=getUTCDate()]",setUTCHours:"hours, [minutes=getUTCMinutes()], [seconds=getUTCSeconds()], [ms=getUTCMilliseconds()]",setUTCMilliseconds:"ms",setUTCMinutes:"minutes, [seconds=getUTCSeconds()], [ms=getUTCMilliseconds()]",setUTCMonth:"month, [day=getUTCDate()]",setUTCSeconds:"seconds, [ms=getUTCMilliseconds()]",setUTCTime:"time",setYear:"year",__proto__:null,},Function:{apply:"thisObject, [argumentsArray]",bind:"thisObject, ...arguments",call:"thisObject, ...arguments",__proto__:null,},Map:{delete:"key",forEach:"callback, [thisArg]",get:"key",has:"key",set:"key, value",__proto__:null,},Number:{toExponential:"[digits]",toFixed:"[digits]",toPrecision:"[significantDigits]",toString:"[radix=10]",__proto__:null,},RegExp:{compile:"pattern, flags",exec:"string",test:"string",__proto__:null,},Set:{delete:"value",forEach:"callback, [thisArg]",has:"value",add:"value",__proto__:null,},String:{charAt:"index",charCodeAt:"index",codePoints:"index",concat:"string, ...",includes:"searchValue, [startIndex=0]",indexOf:"searchValue, [startIndex=0]",lastIndexOf:"searchValue, [startIndex=length]",localeCompare:"string",match:"regex",repeat:"count",replace:"regex|string, replaceString|replaceHandler, [flags]",search:"regex",slice:"startIndex, [endIndex=length]",split:"[separator], [limit]",substr:"startIndex, [numberOfCharacters]",substring:"startIndex, [endIndex=length]",__proto__:null,},WeakMap:{delete:"key",get:"key",has:"key",set:"key, value",__proto__:null,},WeakSet:{delete:"value",has:"value",add:"value",__proto__:null,},Promise:{catch:"rejectionHandler",then:"resolvedHandler, rejectionHandler",__proto__:null,},Generator:{next:"value",return:"value",throw:"exception",__proto__:null,},Element:{closest:"selectors",getAttribute:"attributeName",getAttributeNS:"namespace, attributeName",getAttributeNode:"attributeName",getAttributeNodeNS:"namespace, attributeName",hasAttribute:"attributeName",hasAttributeNS:"namespace, attributeName",matches:"selector",removeAttribute:"attributeName",removeAttributeNS:"namespace, attributeName",removeAttributeNode:"attributeName",scrollIntoView:"[alignWithTop]",scrollIntoViewIfNeeded:"[centerIfNeeded]",setAttribute:"name, value",setAttributeNS:"namespace, name, value",setAttributeNode:"attributeNode",setAttributeNodeNS:"namespace, attributeNode",webkitMatchesSelector:"selectors",__proto__:null,},Node:{appendChild:"child",cloneNode:"[deep]",compareDocumentPosition:"[node]",contains:"[node]",insertBefore:"insertElement, referenceElement",isDefaultNamespace:"[namespace]",isEqualNode:"[node]",lookupNamespaceURI:"prefix",removeChild:"node",replaceChild:"newChild, oldChild",__proto__:null,},Window:{alert:"[message]",atob:"encodedData",btoa:"stringToEncode",cancelAnimationFrame:"id",clearInterval:"intervalId",clearTimeout:"timeoutId",confirm:"[message]",find:"string, [caseSensitive], [backwards], [wrapAround]",getComputedStyle:"[element], [pseudoElement]",getMatchedCSSRules:"[element], [pseudoElement]",matchMedia:"mediaQueryString",moveBy:"[deltaX], [deltaY]",moveTo:"[screenX], [screenY]",open:"url, windowName, [featuresString]",openDatabase:"name, version, displayName, estimatedSize, [creationCallback]",postMessage:"message, targetOrigin, [...transferables]",prompt:"[message], [value]",requestAnimationFrame:"callback",resizeBy:"[deltaX], [deltaY]",resizeTo:"[width], [height]",scrollBy:"[deltaX], [deltaY]",scrollTo:"[x], [y]",setInterval:"func, [delay], [...params]",setTimeout:"func, [delay], [...params]",showModalDialog:"url, [arguments], [options]",__proto__:null,},Document:{adoptNode:"[node]",caretRangeFromPoint:"[x], [y]",createAttribute:"attributeName",createAttributeNS:"namespace, qualifiedName",createCDATASection:"data",createComment:"data",createElement:"tagName",createElementNS:"namespace, qualifiedName",createEntityReference:"name",createEvent:"type",createExpression:"xpath, resolver",createNSResolver:"node",createNodeIterator:"root, whatToShow, filter",createProcessingInstruction:"target, data",createTextNode:"data",createTreeWalker:"root, whatToShow, filter, entityReferenceExpansion",elementFromPoint:"x, y",evaluate:"xpath, contextNode, namespaceResolver, resultType, result",execCommand:"command, userInterface, value",getCSSCanvasContext:"contextId, name, width, height",getElementById:"id",getElementsByName:"name",importNode:"node, deep",queryCommandEnabled:"command",queryCommandIndeterm:"command",queryCommandState:"command",queryCommandSupported:"command",queryCommandValue:"command",__proto__:null,},ANGLEInstancedArrays:{drawArraysInstancedANGLE:"mode, first, count, primcount",drawElementsInstancedANGLE:"mode, count, type, offset, primcount",vertexAttribDivisorANGLE:"index, divisor",__proto__:null,},AnalyserNode:{getByteFrequencyData:"array",getByteTimeDomainData:"array",getFloatFrequencyData:"array",__proto__:null,},AudioBuffer:{getChannelData:"channelIndex",__proto__:null,},AudioBufferCallback:{handleEvent:"audioBuffer",__proto__:null,},AudioBufferSourceNode:{noteGrainOn:"when, grainOffset, grainDuration",noteOff:"when",noteOn:"when",start:"[when], [grainOffset], [grainDuration]",stop:"[when]",__proto__:null,},AudioListener:{setOrientation:"x, y, z, xUp, yUp, zUp",setPosition:"x, y, z",setVelocity:"x, y, z",__proto__:null,},AudioNode:{connect:"destination, [output], [input]",disconnect:"[output]",__proto__:null,},AudioParam:{cancelScheduledValues:"startTime",exponentialRampToValueAtTime:"value, time",linearRampToValueAtTime:"value, time",setTargetAtTime:"target, time, timeConstant",setTargetValueAtTime:"targetValue, time, timeConstant",setValueAtTime:"value, time",setValueCurveAtTime:"values, time, duration",__proto__:null,},AudioTrackList:{getTrackById:"id",item:"index",__proto__:null,},BiquadFilterNode:{getFrequencyResponse:"frequencyHz, magResponse, phaseResponse",__proto__:null,},Blob:{slice:"[start], [end], [contentType]",__proto__:null,},CSS:{supports:"property, value",__proto__:null,},CSSKeyframesRule:{appendRule:"[rule]",deleteRule:"[key]",findRule:"[key]",insertRule:"[rule]",__proto__:null,},CSSMediaRule:{deleteRule:"[index]",insertRule:"[rule], [index]",__proto__:null,},CSSPrimitiveValue:{getFloatValue:"[unitType]",setFloatValue:"[unitType], [floatValue]",setStringValue:"[stringType], [stringValue]",__proto__:null,},CSSRuleList:{item:"[index]",__proto__:null,},CSSStyleDeclaration:{getPropertyCSSValue:"[propertyName]",getPropertyPriority:"[propertyName]",getPropertyShorthand:"[propertyName]",getPropertyValue:"[propertyName]",isPropertyImplicit:"[propertyName]",item:"[index]",removeProperty:"[propertyName]",setProperty:"[propertyName], [value], [priority]",__proto__:null,},CSSStyleSheet:{addRule:"[selector], [style], [index]",deleteRule:"[index]",insertRule:"[rule], [index]",removeRule:"[index]",__proto__:null,},CSSSupportsRule:{deleteRule:"[index]",insertRule:"[rule], [index]",__proto__:null,},CSSValueList:{item:"[index]",__proto__:null,},CanvasGradient:{addColorStop:"[offset], [color]",__proto__:null,},CanvasRenderingContext2D:{arc:"x, y, radius, startAngle, endAngle, [anticlockwise]",arcTo:"x1, y1, x2, y2, radius",bezierCurveTo:"cp1x, cp1y, cp2x, cp2y, x, y",clearRect:"x, y, width, height",clip:"path, [winding]",createImageData:"imagedata",createConicGradient:"angle, x, y",createLinearGradient:"x0, y0, x1, y1",createPattern:"canvas, repetitionType",createRadialGradient:"x0, y0, r0, x1, y1, r1",drawFocusIfNeeded:"element",drawImage:"image, x, y",drawImageFromRect:"image, [sx], [sy], [sw], [sh], [dx], [dy], [dw], [dh], [compositeOperation]",ellipse:"x, y, radiusX, radiusY, rotation, startAngle, endAngle, [anticlockwise]",fill:"path, [winding]",fillRect:"x, y, width, height",fillText:"text, x, y, [maxWidth]",getImageData:"sx, sy, sw, sh",isPointInPath:"path, x, y, [winding]",isPointInStroke:"path, x, y",lineTo:"x, y",measureText:"text",moveTo:"x, y",putImageData:"imagedata, dx, dy",quadraticCurveTo:"cpx, cpy, x, y",rect:"x, y, width, height",rotate:"angle",scale:"sx, sy",setAlpha:"[alpha]",setCompositeOperation:"[compositeOperation]",setFillColor:"color, [alpha]",setLineCap:"[cap]",setLineDash:"dash",setLineJoin:"[join]",setLineWidth:"[width]",setMiterLimit:"[limit]",setShadow:"width, height, blur, [color], [alpha]",setStrokeColor:"color, [alpha]",setTransform:"m11, m12, m21, m22, dx, dy",stroke:"path",strokeRect:"x, y, width, height",strokeText:"text, x, y, [maxWidth]",transform:"m11, m12, m21, m22, dx, dy",translate:"tx, ty",__proto__:null,},CharacterData:{appendData:"[data]",deleteData:"[offset], [length]",insertData:"[offset], [data]",replaceData:"[offset], [length], [data]",substringData:"[offset], [length]",__proto__:null,},CommandLineAPIHost:{copyText:"text",databaseId:"database",getEventListeners:"target",inspect:"objectId, hints",storageId:"storage",__proto__:null,},CompositionEvent:{initCompositionEvent:"[typeArg], [canBubbleArg], [cancelableArg], [viewArg], [dataArg]",__proto__:null,},Crypto:{getRandomValues:"array",__proto__:null,},CustomElementRegistry:{define:"name, constructor",get:"name",whenDefined:"name",__proto__:null,},CustomEvent:{initCustomEvent:"type, [bubbles], [cancelable], [detail]",__proto__:null,},DOMApplicationCache:{__proto__:null,},DOMImplementation:{createCSSStyleSheet:"[title], [media]",createDocument:"[namespaceURI], [qualifiedName], [doctype]",createDocumentType:"[qualifiedName], [publicId], [systemId]",createHTMLDocument:"[title]",hasFeature:"[feature], [version]",__proto__:null,},DOMParser:{parseFromString:"[str], [contentType]",__proto__:null,},DOMStringList:{contains:"[string]",item:"[index]",__proto__:null,},DOMTokenList:{add:"tokens...",contains:"token",item:"index",remove:"tokens...",toggle:"token, [force]",__proto__:null,},DataTransfer:{clearData:"[type]",getData:"type",setData:"type, data",setDragImage:"image, x, y",__proto__:null,},DataTransferItem:{getAsString:"[callback]",__proto__:null,},DataTransferItemList:{add:"file",item:"[index]",__proto__:null,},Database:{changeVersion:"oldVersion, newVersion, [callback], [errorCallback], [successCallback]",readTransaction:"callback, [errorCallback], [successCallback]",transaction:"callback, [errorCallback], [successCallback]",__proto__:null,},DatabaseCallback:{handleEvent:"database",__proto__:null,},DedicatedWorkerGlobalScope:{postMessage:"message, [messagePorts]",__proto__:null,},DeviceMotionEvent:{initDeviceMotionEvent:"[type], [bubbles], [cancelable], [acceleration], [accelerationIncludingGravity], [rotationRate], [interval]",__proto__:null,},DeviceOrientationEvent:{initDeviceOrientationEvent:"[type], [bubbles], [cancelable], [alpha], [beta], [gamma], [absolute]",__proto__:null,},DocumentFragment:{getElementById:"id",querySelector:"selectors",querySelectorAll:"selectors",__proto__:null,},Event:{initEvent:"type, [bubbles], [cancelable]",__proto__:null,},FileList:{item:"index",__proto__:null,},FileReader:{readAsArrayBuffer:"blob",readAsBinaryString:"blob",readAsDataURL:"blob",readAsText:"blob, [encoding]",__proto__:null,},FileReaderSync:{readAsArrayBuffer:"blob",readAsBinaryString:"blob",readAsDataURL:"blob",readAsText:"blob, [encoding]",__proto__:null,},FontFaceSet:{add:"font",check:"font, [text=\" \"]",delete:"font",load:"font, [text=\" \"]",__proto__:null,},FormData:{append:"[name], [value], [filename]",__proto__:null,},Geolocation:{clearWatch:"watchID",getCurrentPosition:"successCallback, [errorCallback], [options]",watchPosition:"successCallback, [errorCallback], [options]",__proto__:null,},HTMLAllCollection:{item:"[index]",namedItem:"name",tags:"name",__proto__:null,},HTMLButtonElement:{setCustomValidity:"error",__proto__:null,},HTMLCanvasElement:{getContext:"contextId",toDataURL:"[type]",__proto__:null,},HTMLCollection:{item:"[index]",namedItem:"[name]",__proto__:null,},HTMLDocument:{write:"[html]",writeln:"[html]",__proto__:null,},HTMLElement:{insertAdjacentElement:"[position], [element]",insertAdjacentHTML:"[position], [html]",insertAdjacentText:"[position], [text]",__proto__:null,},HTMLFieldSetElement:{setCustomValidity:"error",__proto__:null,},HTMLFormControlsCollection:{namedItem:"[name]",__proto__:null,},HTMLInputElement:{setCustomValidity:"error",setRangeText:"replacement",setSelectionRange:"start, end, [direction]",stepDown:"[n]",stepUp:"[n]",__proto__:null,},HTMLKeygenElement:{setCustomValidity:"error",__proto__:null,},HTMLMediaElement:{addTextTrack:"kind, [label], [language]",canPlayType:"[type], [keySystem]",fastSeek:"time",webkitAddKey:"keySystem, key, [initData], [sessionId]",webkitCancelKeyRequest:"keySystem, [sessionId]",webkitGenerateKeyRequest:"keySystem, [initData]",webkitSetMediaKeys:"mediaKeys",__proto__:null,},HTMLObjectElement:{setCustomValidity:"error",__proto__:null,},HTMLOptionsCollection:{add:"element, [before]",namedItem:"[name]",remove:"[index]",__proto__:null,},HTMLOutputElement:{setCustomValidity:"error",__proto__:null,},HTMLSelectElement:{add:"element, [before]",item:"index",namedItem:"[name]",setCustomValidity:"error",__proto__:null,},HTMLSlotElement:{assignedNodes:"[options]",__proto__:null,},HTMLTableElement:{deleteRow:"index",insertRow:"[index]",__proto__:null,},HTMLTableRowElement:{deleteCell:"index",insertCell:"[index]",__proto__:null,},HTMLTableSectionElement:{deleteRow:"index",insertRow:"[index]",__proto__:null,},HTMLTextAreaElement:{setCustomValidity:"error",setRangeText:"replacement",setSelectionRange:"[start], [end], [direction]",__proto__:null,},HTMLVideoElement:{webkitSetPresentationMode:"mode",webkitSupportsPresentationMode:"mode",__proto__:null,},HashChangeEvent:{initHashChangeEvent:"[type], [canBubble], [cancelable], [oldURL], [newURL]",__proto__:null,},History:{go:"[distance]",pushState:"data, title, [url]",replaceState:"data, title, [url]",__proto__:null,},IDBCursor:{advance:"count",continue:"[key]",update:"value",__proto__:null,},IDBDatabase:{createObjectStore:"name, [options]",deleteObjectStore:"name",transaction:"storeName, [mode]",__proto__:null,},IDBFactory:{cmp:"first, second",deleteDatabase:"name",open:"name, [version]",__proto__:null,},IDBIndex:{count:"[range]",get:"key",getKey:"key",openCursor:"[range], [direction]",openKeyCursor:"[range], [direction]",__proto__:null,},IDBObjectStore:{add:"value, [key]",count:"[range]",createIndex:"name, keyPath, [options]",delete:"keyRange",deleteIndex:"name",get:"key",index:"name",openCursor:"[range], [direction]",put:"value, [key]",__proto__:null,},IDBTransaction:{objectStore:"name",__proto__:null,},ImageBitmapRenderingContext:{transferFromImageBitmap:"[bitmap]",__proto__:null,},KeyboardEvent:{initKeyboardEvent:"[type], [canBubble], [cancelable], [view], [keyIdentifier], [location], [ctrlKey], [altKey], [shiftKey], [metaKey], [altGraphKey]",__proto__:null,},Location:{assign:"[url]",reload:"[force=false]",replace:"[url]",__proto__:null,},MediaController:{__proto__:null,},MediaControlsHost:{displayNameForTrack:"track",mediaUIImageData:"partID",setSelectedTextTrack:"track",sortedTrackListForMenu:"trackList",__proto__:null,},MediaList:{appendMedium:"[newMedium]",deleteMedium:"[oldMedium]",item:"[index]",__proto__:null,},MediaQueryList:{addListener:"[listener]",removeListener:"[listener]",__proto__:null,},MediaSource:{addSourceBuffer:"type",endOfStream:"[error]",removeSourceBuffer:"buffer",__proto__:null,},MediaStreamTrack:{applyConstraints:"constraints",__proto__:null,},MediaStreamTrackSourcesCallback:{handleEvent:"sources",__proto__:null,},MessageEvent:{initMessageEvent:"type, [bubbles], [cancelable], [data], [origin], [lastEventId], [source], [messagePorts]",__proto__:null,},MessagePort:{__proto__:null,},MimeTypeArray:{item:"[index]",namedItem:"[name]",__proto__:null,},MouseEvent:{initMouseEvent:"[type], [canBubble], [cancelable], [view], [detail], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey], [button], [relatedTarget]",__proto__:null,},MutationEvent:{initMutationEvent:"[type], [canBubble], [cancelable], [relatedNode], [prevValue], [newValue], [attrName], [attrChange]",__proto__:null,},MutationObserver:{observe:"target, options",__proto__:null,},NamedNodeMap:{getNamedItem:"[name]",getNamedItemNS:"[namespaceURI], [localName]",item:"[index]",removeNamedItem:"[name]",removeNamedItemNS:"[namespaceURI], [localName]",setNamedItem:"[node]",setNamedItemNS:"[node]",__proto__:null,},Navigator:{getUserMedia:"options, successCallback, errorCallback",__proto__:null,},NavigatorUserMediaErrorCallback:{handleEvent:"error",__proto__:null,},NavigatorUserMediaSuccessCallback:{handleEvent:"stream",__proto__:null,},NodeFilter:{acceptNode:"[n]",__proto__:null,},NodeList:{item:"index",__proto__:null,},Notification:{__proto__:null,},NotificationCenter:{createNotification:"iconUrl, title, body",requestPermission:"[callback]",__proto__:null,},NotificationPermissionCallback:{handleEvent:"permission",__proto__:null,},OESVertexArrayObject:{bindVertexArrayOES:"[arrayObject]",deleteVertexArrayOES:"[arrayObject]",isVertexArrayOES:"[arrayObject]",__proto__:null,},OscillatorNode:{noteOff:"when",noteOn:"when",setPeriodicWave:"wave",start:"[when]",stop:"[when]",__proto__:null,},Path2D:{addPath:"path, [transform]",arc:"[x], [y], [radius], [startAngle], [endAngle], [anticlockwise]",arcTo:"[x1], [y1], [x2], [y2], [radius]",bezierCurveTo:"[cp1x], [cp1y], [cp2x], [cp2y], [x], [y]",ellipse:"x, y, radiusX, radiusY, rotation, startAngle, endAngle, [anticlockwise]",lineTo:"[x], [y]",moveTo:"[x], [y]",quadraticCurveTo:"[cpx], [cpy], [x], [y]",rect:"[x], [y], [width], [height]",__proto__:null,},Performance:{clearMarks:"[name]",clearMeasures:"name",getEntriesByName:"name, [type]",getEntriesByType:"type",mark:"name",measure:"name, [startMark], [endMark]",__proto__:null,},PerformanceObserver:{observe:"options",__proto__:null,},PerformanceObserverEntryList:{getEntriesByName:"name, [type]",getEntriesByType:"type",__proto__:null,},Plugin:{item:"[index]",namedItem:"[name]",__proto__:null,},PluginArray:{item:"[index]",namedItem:"[name]",refresh:"[reload]",__proto__:null,},PositionCallback:{handleEvent:"position",__proto__:null,},PositionErrorCallback:{handleEvent:"error",__proto__:null,},RTCDTMFSender:{insertDTMF:"tones, [duration], [interToneGap]",__proto__:null,},RTCDataChannel:{send:"data",__proto__:null,},RTCPeerConnectionErrorCallback:{handleEvent:"error",__proto__:null,},RTCSessionDescriptionCallback:{handleEvent:"sdp",__proto__:null,},RTCStatsCallback:{handleEvent:"response",__proto__:null,},RTCStatsReport:{stat:"name",__proto__:null,},RTCStatsResponse:{namedItem:"[name]",__proto__:null,},Range:{collapse:"[toStart]",compareBoundaryPoints:"[how], [sourceRange]",compareNode:"[refNode]",comparePoint:"[refNode], [offset]",createContextualFragment:"[html]",expand:"[unit]",insertNode:"[newNode]",intersectsNode:"[refNode]",isPointInRange:"[refNode], [offset]",selectNode:"[refNode]",selectNodeContents:"[refNode]",setEnd:"[refNode], [offset]",setEndAfter:"[refNode]",setEndBefore:"[refNode]",setStart:"[refNode], [offset]",setStartAfter:"[refNode]",setStartBefore:"[refNode]",surroundContents:"[newParent]",__proto__:null,},ReadableStream:{cancel:"reason",pipeThrough:"dest, options",pipeTo:"streams, options",__proto__:null,},WritableStream:{abort:"reason",close:"",write:"chunk",__proto__:null,},RequestAnimationFrameCallback:{handleEvent:"highResTime",__proto__:null,},SQLResultSetRowList:{item:"index",__proto__:null,},SQLStatementCallback:{handleEvent:"transaction, resultSet",__proto__:null,},SQLStatementErrorCallback:{handleEvent:"transaction, error",__proto__:null,},SQLTransaction:{executeSql:"sqlStatement, arguments, [callback], [errorCallback]",__proto__:null,},SQLTransactionCallback:{handleEvent:"transaction",__proto__:null,},SQLTransactionErrorCallback:{handleEvent:"error",__proto__:null,},SVGAngle:{convertToSpecifiedUnits:"unitType",newValueSpecifiedUnits:"unitType, valueInSpecifiedUnits",__proto__:null,},SVGAnimationElement:{beginElementAt:"[offset]",endElementAt:"[offset]",hasExtension:"[extension]",__proto__:null,},SVGColor:{setColor:"colorType, rgbColor, iccColor",setRGBColor:"rgbColor",setRGBColorICCColor:"rgbColor, iccColor",__proto__:null,},SVGCursorElement:{hasExtension:"[extension]",__proto__:null,},SVGDocument:{createEvent:"[eventType]",__proto__:null,},SVGElement:{getPresentationAttribute:"[name]",__proto__:null,},SVGFEDropShadowElement:{setStdDeviation:"[stdDeviationX], [stdDeviationY]",__proto__:null,},SVGFEGaussianBlurElement:{setStdDeviation:"[stdDeviationX], [stdDeviationY]",__proto__:null,},SVGFEMorphologyElement:{setRadius:"[radiusX], [radiusY]",__proto__:null,},SVGFilterElement:{setFilterRes:"[filterResX], [filterResY]",__proto__:null,},SVGGraphicsElement:{getTransformToElement:"[element]",hasExtension:"[extension]",__proto__:null,},SVGLength:{convertToSpecifiedUnits:"unitType",newValueSpecifiedUnits:"unitType, valueInSpecifiedUnits",__proto__:null,},SVGLengthList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGMarkerElement:{setOrientToAngle:"[angle]",__proto__:null,},SVGMaskElement:{hasExtension:"[extension]",__proto__:null,},SVGMatrix:{multiply:"secondMatrix",rotate:"angle",rotateFromVector:"x, y",scale:"scaleFactor",scaleNonUniform:"scaleFactorX, scaleFactorY",skewX:"angle",skewY:"angle",translate:"x, y",__proto__:null,},SVGNumberList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGPaint:{setPaint:"paintType, uri, rgbColor, iccColor",setUri:"uri",__proto__:null,},SVGPathElement:{createSVGPathSegArcAbs:"[x], [y], [r1], [r2], [angle], [largeArcFlag], [sweepFlag]",createSVGPathSegArcRel:"[x], [y], [r1], [r2], [angle], [largeArcFlag], [sweepFlag]",createSVGPathSegCurvetoCubicAbs:"[x], [y], [x1], [y1], [x2], [y2]",createSVGPathSegCurvetoCubicRel:"[x], [y], [x1], [y1], [x2], [y2]",createSVGPathSegCurvetoCubicSmoothAbs:"[x], [y], [x2], [y2]",createSVGPathSegCurvetoCubicSmoothRel:"[x], [y], [x2], [y2]",createSVGPathSegCurvetoQuadraticAbs:"[x], [y], [x1], [y1]",createSVGPathSegCurvetoQuadraticRel:"[x], [y], [x1], [y1]",createSVGPathSegCurvetoQuadraticSmoothAbs:"[x], [y]",createSVGPathSegCurvetoQuadraticSmoothRel:"[x], [y]",createSVGPathSegLinetoAbs:"[x], [y]",createSVGPathSegLinetoHorizontalAbs:"[x]",createSVGPathSegLinetoHorizontalRel:"[x]",createSVGPathSegLinetoRel:"[x], [y]",createSVGPathSegLinetoVerticalAbs:"[y]",createSVGPathSegLinetoVerticalRel:"[y]",createSVGPathSegMovetoAbs:"[x], [y]",createSVGPathSegMovetoRel:"[x], [y]",getPathSegAtLength:"[distance]",getPointAtLength:"[distance]",__proto__:null,},SVGPathSegList:{appendItem:"newItem",getItem:"index",initialize:"newItem",insertItemBefore:"newItem, index",removeItem:"index",replaceItem:"newItem, index",__proto__:null,},SVGPatternElement:{hasExtension:"[extension]",__proto__:null,},SVGPoint:{matrixTransform:"matrix",__proto__:null,},SVGPointList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGSVGElement:{checkEnclosure:"[element], [rect]",checkIntersection:"[element], [rect]",createSVGTransformFromMatrix:"[matrix]",getElementById:"[elementId]",getEnclosureList:"[rect], [referenceElement]",getIntersectionList:"[rect], [referenceElement]",setCurrentTime:"[seconds]",suspendRedraw:"[maxWaitMilliseconds]",unsuspendRedraw:"[suspendHandleId]",__proto__:null,},SVGStringList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGTextContentElement:{getCharNumAtPosition:"[point]",getEndPositionOfChar:"[offset]",getExtentOfChar:"[offset]",getRotationOfChar:"[offset]",getStartPositionOfChar:"[offset]",getSubStringLength:"[offset], [length]",selectSubString:"[offset], [length]",__proto__:null,},SVGTransform:{setMatrix:"matrix",setRotate:"angle, cx, cy",setScale:"sx, sy",setSkewX:"angle",setSkewY:"angle",setTranslate:"tx, ty",__proto__:null,},SVGTransformList:{appendItem:"item",createSVGTransformFromMatrix:"matrix",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SecurityPolicy:{allowsConnectionTo:"url",allowsFontFrom:"url",allowsFormAction:"url",allowsFrameFrom:"url",allowsImageFrom:"url",allowsMediaFrom:"url",allowsObjectFrom:"url",allowsPluginType:"type",allowsScriptFrom:"url",allowsStyleFrom:"url",__proto__:null,},Selection:{addRange:"[range]",collapse:"[node], [index]",containsNode:"[node], [allowPartial]",extend:"[node], [offset]",getRangeAt:"[index]",modify:"[alter], [direction], [granularity]",selectAllChildren:"[node]",setBaseAndExtent:"[baseNode], [baseOffset], [extentNode], [extentOffset]",setPosition:"[node], [offset]",__proto__:null,},SourceBuffer:{appendBuffer:"data",remove:"start, end",__proto__:null,},SourceBufferList:{item:"index",__proto__:null,},SpeechSynthesis:{speak:"utterance",__proto__:null,},SpeechSynthesisUtterance:{__proto__:null,},Storage:{getItem:"key",key:"index",removeItem:"key",setItem:"key, data",__proto__:null,},StorageErrorCallback:{handleEvent:"error",__proto__:null,},StorageEvent:{initStorageEvent:"[typeArg], [canBubbleArg], [cancelableArg], [keyArg], [oldValueArg], [newValueArg], [urlArg], [storageAreaArg]",__proto__:null,},StorageInfo:{queryUsageAndQuota:"storageType, [usageCallback], [errorCallback]",requestQuota:"storageType, newQuotaInBytes, [quotaCallback], [errorCallback]",__proto__:null,},StorageQuota:{queryUsageAndQuota:"usageCallback, [errorCallback]",requestQuota:"newQuotaInBytes, [quotaCallback], [errorCallback]",__proto__:null,},StorageQuotaCallback:{handleEvent:"grantedQuotaInBytes",__proto__:null,},StorageUsageCallback:{handleEvent:"currentUsageInBytes, currentQuotaInBytes",__proto__:null,},StringCallback:{handleEvent:"data",__proto__:null,},StyleMedia:{matchMedium:"[mediaquery]",__proto__:null,},StyleSheetList:{item:"[index]",__proto__:null,},Text:{replaceWholeText:"[content]",splitText:"offset",__proto__:null,},TextEvent:{initTextEvent:"[typeArg], [canBubbleArg], [cancelableArg], [viewArg], [dataArg]",__proto__:null,},TextTrack:{addCue:"cue",addRegion:"region",removeCue:"cue",removeRegion:"region",__proto__:null,},TextTrackCue:{__proto__:null,},TextTrackCueList:{getCueById:"id",item:"index",__proto__:null,},TextTrackList:{getTrackById:"id",item:"index",__proto__:null,},TimeRanges:{end:"index",start:"index",__proto__:null,},TouchEvent:{initTouchEvent:"[touches], [targetTouches], [changedTouches], [type], [view], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey]",__proto__:null,},TouchList:{item:"index",__proto__:null,},UIEvent:{initUIEvent:"[type], [canBubble], [cancelable], [view], [detail]",__proto__:null,},UserMessageHandler:{postMessage:"message",__proto__:null,},VTTRegionList:{getRegionById:"id",item:"index",__proto__:null,},VideoTrackList:{getTrackById:"id",item:"index",__proto__:null,},WebGL2RenderingContext:{beginQuery:"target, query",beginTransformFeedback:"primitiveMode",bindBufferBase:"target, index, buffer",bindBufferRange:"target, index, buffer, offset, size",bindSampler:"unit, sampler",bindTransformFeedback:"target, id",bindVertexArray:"vertexArray",blitFramebuffer:"srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter",clearBufferfi:"buffer, drawbuffer, depth, stencil",clearBufferfv:"buffer, drawbuffer, value",clearBufferiv:"buffer, drawbuffer, value",clearBufferuiv:"buffer, drawbuffer, value",clientWaitSync:"sync, flags, timeout",compressedTexImage3D:"target, level, internalformat, width, height, depth, border, imageSize, data",compressedTexSubImage3D:"target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data",copyBufferSubData:"readTarget, writeTarget, readOffset, writeOffset, size",copyTexSubImage3D:"target, level, xoffset, yoffset, zoffset, x, y, width, height",deleteQuery:"query",deleteSampler:"sampler",deleteSync:"sync",deleteTransformFeedback:"id",deleteVertexArray:"vertexArray",drawArraysInstanced:"mode, first, count, instanceCount",drawBuffers:"buffers",drawElementsInstanced:"mode, count, type, offset, instanceCount",drawRangeElements:"mode, start, end, count, type, offset",endQuery:"target",fenceSync:"condition, flags",framebufferTextureLayer:"target, attachment, texture, level, layer",getActiveUniformBlockName:"program, uniformBlockIndex",getActiveUniformBlockParameter:"program, uniformBlockIndex, pname",getActiveUniforms:"program, uniformIndices, pname",getBufferSubData:"target, offset, returnedData",getFragDataLocation:"program, name",getIndexedParameter:"target, index",getInternalformatParameter:"target, internalformat, pname",getQuery:"target, pname",getQueryParameter:"query, pname",getSamplerParameter:"sampler, pname",getSyncParameter:"sync, pname",getTransformFeedbackVarying:"program, index",getUniformBlockIndex:"program, uniformBlockName",getUniformIndices:"program, uniformNames",invalidateFramebuffer:"target, attachments",invalidateSubFramebuffer:"target, attachments, x, y, width, height",isQuery:"query",isSampler:"sampler",isSync:"sync",isTransformFeedback:"id",isVertexArray:"vertexArray",readBuffer:"src",renderbufferStorageMultisample:"target, samples, internalformat, width, height",samplerParameterf:"sampler, pname, param",samplerParameteri:"sampler, pname, param",texImage3D:"target, level, internalformat, width, height, depth, border, format, type, pixels",texStorage2D:"target, levels, internalformat, width, height",texStorage3D:"target, levels, internalformat, width, height, depth",texSubImage3D:"target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels",transformFeedbackVaryings:"program, varyings, bufferMode",uniform1ui:"location, v0",uniform1uiv:"location, value",uniform2ui:"location, v0, v1",uniform2uiv:"location, value",uniform3ui:"location, v0, v1, v2",uniform3uiv:"location, value",uniform4ui:"location, v0, v1, v2, v3",uniform4uiv:"location, value",uniformBlockBinding:"program, uniformBlockIndex, uniformBlockBinding",uniformMatrix2x3fv:"location, transpose, value",uniformMatrix2x4fv:"location, transpose, value",uniformMatrix3x2fv:"location, transpose, value",uniformMatrix3x4fv:"location, transpose, value",uniformMatrix4x2fv:"location, transpose, value",uniformMatrix4x3fv:"location, transpose, value",vertexAttribDivisor:"index, divisor",vertexAttribI4i:"index, x, y, z, w",vertexAttribI4iv:"index, v",vertexAttribI4ui:"index, x, y, z, w",vertexAttribI4uiv:"index, v",vertexAttribIPointer:"index, size, type, stride, offset",waitSync:"sync, flags, timeout",__proto__:null,},WebGLDebugShaders:{getTranslatedShaderSource:"shader",__proto__:null,},WebGLDrawBuffers:{drawBuffersWEBGL:"buffers",__proto__:null,},WebGLMultiDraw:{multiDrawArraysWebGL:"mode, firstsList, firstsOffset, countsList, countsOffset, drawcount",multiDrawArraysInstancedWebGL:"mode, firstsList, firstsOffset, countsList, countsOffset, instanceCountsList, instanceCountsOffset, drawcount",multiDrawElementsWebGL:"mode, countsList, countsOffset, type, offsetsList, offsetsOffset, drawcount",multiDrawElementsInstancedWebGL:"mode, countsList, countsOffset, type, offsetsList, offsetsOffset, instanceCountsList, instanceCountsOffset, drawcount",__proto__:null,},WebGLRenderingContextBase:{activeTexture:"texture",attachShader:"program, shader",bindAttribLocation:"program, index, name",bindBuffer:"target, buffer",bindFramebuffer:"target, framebuffer",bindRenderbuffer:"target, renderbuffer",bindTexture:"target, texture",blendColor:"red, green, blue, alpha",blendEquation:"mode",blendEquationSeparate:"modeRGB, modeAlpha",blendFunc:"sfactor, dfactor",blendFuncSeparate:"srcRGB, dstRGB, srcAlpha, dstAlpha",bufferData:"target, data, usage",bufferSubData:"target, offset, data",checkFramebufferStatus:"target",clear:"mask",clearColor:"red, green, blue, alpha",clearDepth:"depth",clearStencil:"s",colorMask:"red, green, blue, alpha",compileShader:"shader",compressedTexImage2D:"target, level, internalformat, width, height, border, data",compressedTexSubImage2D:"target, level, xoffset, yoffset, width, height, format, data",copyTexImage2D:"target, level, internalformat, x, y, width, height, border",copyTexSubImage2D:"target, level, xoffset, yoffset, x, y, width, height",createShader:"type",cullFace:"mode",deleteBuffer:"buffer",deleteFramebuffer:"framebuffer",deleteProgram:"program",deleteRenderbuffer:"renderbuffer",deleteShader:"shader",deleteTexture:"texture",depthFunc:"func",depthMask:"flag",depthRange:"zNear, zFar",detachShader:"program, shader",disable:"cap",disableVertexAttribArray:"index",drawArrays:"mode, first, count",drawElements:"mode, count, type, offset",enable:"cap",enableVertexAttribArray:"index",framebufferRenderbuffer:"target, attachment, renderbuffertarget, renderbuffer",framebufferTexture2D:"target, attachment, textarget, texture, level",frontFace:"mode",generateMipmap:"target",getActiveAttrib:"program, index",getActiveUniform:"program, index",getAttachedShaders:"program",getAttribLocation:"program, name",getBufferParameter:"target, pname",getExtension:"name",getFramebufferAttachmentParameter:"target, attachment, pname",getParameter:"pname",getProgramInfoLog:"program",getProgramParameter:"program, pname",getRenderbufferParameter:"target, pname",getShaderInfoLog:"shader",getShaderParameter:"shader, pname",getShaderPrecisionFormat:"shadertype, precisiontype",getShaderSource:"shader",getTexParameter:"target, pname",getUniform:"program, location",getUniformLocation:"program, name",getVertexAttrib:"index, pname",getVertexAttribOffset:"index, pname",hint:"target, mode",isBuffer:"buffer",isEnabled:"cap",isFramebuffer:"framebuffer",isProgram:"program",isRenderbuffer:"renderbuffer",isShader:"shader",isTexture:"texture",lineWidth:"width",linkProgram:"program",pixelStorei:"pname, param",polygonOffset:"factor, units",readPixels:"x, y, width, height, format, type, pixels",renderbufferStorage:"target, internalformat, width, height",sampleCoverage:"value, invert",scissor:"x, y, width, height",shaderSource:"shader, string",stencilFunc:"func, ref, mask",stencilFuncSeparate:"face, func, ref, mask",stencilMask:"mask",stencilMaskSeparate:"face, mask",stencilOp:"fail, zfail, zpass",stencilOpSeparate:"face, fail, zfail, zpass",texImage2D:"target, level, internalformat, width, height, border, format, type, pixels",texParameterf:"target, pname, param",texParameteri:"target, pname, param",texSubImage2D:"target, level, xoffset, yoffset, width, height, format, type, pixels",uniform1f:"location, x",uniform1fv:"location, v",uniform1i:"location, x",uniform1iv:"location, v",uniform2f:"location, x, y",uniform2fv:"location, v",uniform2i:"location, x, y",uniform2iv:"location, v",uniform3f:"location, x, y, z",uniform3fv:"location, v",uniform3i:"location, x, y, z",uniform3iv:"location, v",uniform4f:"location, x, y, z, w",uniform4fv:"location, v",uniform4i:"location, x, y, z, w",uniform4iv:"location, v",uniformMatrix2fv:"location, transpose, array",uniformMatrix3fv:"location, transpose, array",uniformMatrix4fv:"location, transpose, array",useProgram:"program",validateProgram:"program",vertexAttrib1f:"indx, x",vertexAttrib1fv:"indx, values",vertexAttrib2f:"indx, x, y",vertexAttrib2fv:"indx, values",vertexAttrib3f:"indx, x, y, z",vertexAttrib3fv:"indx, values",vertexAttrib4f:"indx, x, y, z, w",vertexAttrib4fv:"indx, values",vertexAttribPointer:"indx, size, type, normalized, stride, offset",viewport:"x, y, width, height",__proto__:null,},WebKitCSSMatrix:{multiply:"[secondMatrix]",rotate:"[rotX], [rotY], [rotZ]",rotateAxisAngle:"[x], [y], [z], [angle]",scale:"[scaleX], [scaleY], [scaleZ]",setMatrixValue:"[string]",skewX:"[angle]",skewY:"[angle]",translate:"[x], [y], [z]",__proto__:null,},WebKitMediaKeySession:{update:"key",__proto__:null,},WebKitMediaKeys:{createSession:"[type], [initData]",__proto__:null,},WebKitNamedFlow:{getRegionsByContent:"contentNode",__proto__:null,},WebKitNamedFlowCollection:{item:"index",namedItem:"name",__proto__:null,},WebKitSubtleCrypto:{decrypt:"algorithm, key, data",digest:"algorithm, data",encrypt:"algorithm, key, data",exportKey:"format, key",generateKey:"algorithm, [extractable], [keyUsages]",importKey:"format, keyData, algorithm, [extractable], [keyUsages]",sign:"algorithm, key, data",unwrapKey:"format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, [extractable], [keyUsages]",verify:"algorithm, key, signature, data",wrapKey:"format, key, wrappingKey, wrapAlgorithm",__proto__:null,},WebSocket:{close:"[code], [reason]",send:"data",__proto__:null,},WheelEvent:{initWebKitWheelEvent:"[wheelDeltaX], [wheelDeltaY], [view], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey]",__proto__:null,},Worker:{postMessage:"message, [messagePorts]",__proto__:null,},WorkerGlobalScope:{clearInterval:"[handle]",clearTimeout:"[handle]",setInterval:"handler, [timeout]",setTimeout:"handler, [timeout]",__proto__:null,},XMLHttpRequest:{getResponseHeader:"header",open:"method, url, [async], [user], [password]",overrideMimeType:"override",setRequestHeader:"header, value",__proto__:null,},XMLHttpRequestUpload:{__proto__:null,},XMLSerializer:{serializeToString:"[node]",__proto__:null,},XPathEvaluator:{createExpression:"[expression], [resolver]",createNSResolver:"[nodeResolver]",evaluate:"[expression], [contextNode], [resolver], [type], [inResult]",__proto__:null,},XPathExpression:{evaluate:"[contextNode], [type], [inResult]",__proto__:null,},XPathNSResolver:{lookupNamespaceURI:"[prefix]",__proto__:null,},XPathResult:{snapshotItem:"[index]",__proto__:null,},XSLTProcessor:{getParameter:"namespaceURI, localName",importStylesheet:"[stylesheet]",removeParameter:"namespaceURI, localName",setParameter:"namespaceURI, localName, value",transformToDocument:"[source]",transformToFragment:"[source], [docVal]",__proto__:null,},webkitAudioContext:{createBuffer:"numberOfChannels, numberOfFrames, sampleRate",createChannelMerger:"[numberOfInputs]",createChannelSplitter:"[numberOfOutputs]",createDelay:"[maxDelayTime]",createDelayNode:"[maxDelayTime]",createJavaScriptNode:"bufferSize, [numberOfInputChannels], [numberOfOutputChannels]",createMediaElementSource:"mediaElement",createPeriodicWave:"real, imag",createScriptProcessor:"bufferSize, [numberOfInputChannels], [numberOfOutputChannels]",decodeAudioData:"audioData, successCallback, [errorCallback]",__proto__:null,},webkitAudioPannerNode:{setOrientation:"x, y, z",setPosition:"x, y, z",setVelocity:"x, y, z",__proto__:null,},webkitMediaStream:{addTrack:"track",getTrackById:"trackId",removeTrack:"track",__proto__:null,},webkitRTCPeerConnection:{addIceCandidate:"candidate, successCallback, failureCallback",addStream:"stream",createAnswer:"successCallback, failureCallback, [answerOptions]",createDTMFSender:"track",createDataChannel:"label, [options]",createOffer:"successCallback, failureCallback, [offerOptions]",getStats:"successCallback, failureCallback, [selector]",getStreamById:"streamId",removeStream:"stream",setLocalDescription:"description, successCallback, failureCallback",setRemoteDescription:"description, successCallback, failureCallback",updateIce:"configuration",__proto__:null,},EventTarget:{addEventListener:"type, listener, [useCapture=false]",removeEventListener:"type, listener, [useCapture=false]",dispatchEvent:"event",__proto__:null,},};(function(){var ElementQueries={getElementsByClassName:"classNames",getElementsByTagName:"tagName",getElementsByTagNameNS:"namespace, localName",querySelector:"selectors",querySelectorAll:"selectors",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ElementQueries);Object.assign(WI.NativePrototypeFunctionParameters.Document,ElementQueries);var ChildNode={after:"[node|string]...",before:"[node|string]...",replaceWith:"[node|string]...",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ChildNode);Object.assign(WI.NativePrototypeFunctionParameters.CharacterData,ChildNode);var ParentNode={append:"[node|string]...",prepend:"[node|string]...",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ParentNode);Object.assign(WI.NativePrototypeFunctionParameters.Document,ParentNode);Object.assign(WI.NativePrototypeFunctionParameters.DocumentFragment,ParentNode);})();WI.NetworkInstrument=class NetworkInstrument extends WI.Instrument
{ get timelineRecordType()
{return WI.TimelineRecord.Type.Network;}
startInstrumentation(initiatedByBackend)
{}
stopInstrumentation(initiatedByBackend)
{}};WI.NetworkTimeline=class NetworkTimeline extends WI.Timeline
{ recordForResource(resource)
{return this._resourceRecordMap.get(resource)||null;}
reset(suppressEvents)
{this._resourceRecordMap=new Map;super.reset(suppressEvents);}
addRecord(record,options={})
{if(this._resourceRecordMap.has(record.resource))
return;this._resourceRecordMap.set(record.resource,record);super.addRecord(record,options);}};WI.ObjectPreview=class ObjectPreview
{constructor(type,subtype,description,lossless,overflow,properties,entries,size)
{this._type=type;this._subtype=subtype;this._description=description||"";this._lossless=lossless;this._overflow=overflow||false;this._size=size;this._properties=properties||null;this._entries=entries||null;}

static fromPayload(payload)
{if(payload.properties)
payload.properties=payload.properties.map(WI.PropertyPreview.fromPayload);if(payload.entries)
payload.entries=payload.entries.map(WI.CollectionEntryPreview.fromPayload);return new WI.ObjectPreview(payload.type,payload.subtype,payload.description,payload.lossless,payload.overflow,payload.properties,payload.entries,payload.size);} 
get type(){return this._type;}
get subtype(){return this._subtype;}
get description(){return this._description;}
get lossless(){return this._lossless;}
get overflow(){return this._overflow;}
get propertyPreviews(){return this._properties;}
get collectionEntryPreviews(){return this._entries;}
get size(){return this._size;}
hasSize()
{return this._size!==undefined&&(this._subtype==="array"||this._subtype==="set"||this._subtype==="map"||this._subtype==="weakmap"||this._subtype==="weakset");}};WI.ProbeSample=class ProbeSample
{constructor(sampleId,batchId,elapsedTime,object)
{this.sampleId=sampleId;this.batchId=batchId;this.timestamp=elapsedTime;this.object=object;}};WI.Probe=class Probe extends WI.Object
{constructor(id,breakpoint,expression)
{super();this._id=id;this._breakpoint=breakpoint;this._expression=expression;this._samples=[];} 
get id()
{return this._id;}
get breakpoint()
{return this._breakpoint;}
get expression()
{return this._expression;}
set expression(value)
{if(this._expression===value)
return;var data={oldValue:this._expression,newValue:value};this._expression=value;this.clearSamples();this.dispatchEventToListeners(WI.Probe.Event.ExpressionChanged,data);}
get samples()
{return this._samples.slice();}
clearSamples()
{this._samples=[];this.dispatchEventToListeners(WI.Probe.Event.SamplesCleared);}
addSample(sample)
{this._samples.push(sample);this.dispatchEventToListeners(WI.Probe.Event.SampleAdded,sample);}};WI.Probe.Event={ExpressionChanged:"probe-object-expression-changed",SampleAdded:"probe-object-sample-added",SamplesCleared:"probe-object-samples-cleared"};WI.ProbeSet=class ProbeSet extends WI.Object
{constructor(breakpoint)
{super();this._breakpoint=breakpoint;this._probes=[];this._probesByIdentifier=new Map;this._createDataTable();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceChanged,this);WI.Probe.addEventListener(WI.Probe.Event.SampleAdded,this._sampleCollected,this);} 
get breakpoint(){return this._breakpoint;}
get probes(){return this._probes.slice();}
get dataTable(){return this._dataTable;}
clear()
{this._breakpoint.clearActions(WI.BreakpointAction.Type.Probe);}
clearSamples()
{for(var probe of this._probes)
probe.clearSamples();var oldTable=this._dataTable;this._createDataTable();this.dispatchEventToListeners(WI.ProbeSet.Event.SamplesCleared,{oldTable});}
createProbe(expression)
{this._breakpoint.addAction(new WI.BreakpointAction(WI.BreakpointAction.Type.Probe,{data:expression}));}
addProbe(probe)
{this._probes.push(probe);this._probesByIdentifier.set(probe.id,probe);this.dataTable.addProbe(probe);this.dispatchEventToListeners(WI.ProbeSet.Event.ProbeAdded,probe);}
removeProbe(probe)
{this._probes.splice(this._probes.indexOf(probe),1);this._probesByIdentifier.delete(probe.id);this.dataTable.removeProbe(probe);this.dispatchEventToListeners(WI.ProbeSet.Event.ProbeRemoved,probe);}
willRemove()
{WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceChanged,this);WI.Probe.removeEventListener(WI.Probe.Event.SampleAdded,this._sampleCollected,this);} 
_mainResourceChanged()
{this.dataTable.mainResourceChanged();}
_createDataTable()
{if(this.dataTable)
this.dataTable.willRemove();this._dataTable=new WI.ProbeSetDataTable(this);}
_sampleCollected(event)
{var sample=event.data;var probe=event.target;if(!this._probesByIdentifier.has(probe.id))
return;this.dataTable.addSampleForProbe(probe,sample);this.dispatchEventToListeners(WI.ProbeSet.Event.SampleAdded,{probe,sample});}};WI.ProbeSet.Event={ProbeAdded:"probe-set-probe-added",ProbeRemoved:"probe-set-probe-removed",SampleAdded:"probe-set-sample-added",SamplesCleared:"probe-set-samples-cleared",};WI.ProbeSetDataFrame=class ProbeSetDataFrame
{constructor(index)
{this._count=0;this._index=index;this._separator=false;} 
static compare(a,b)
{return a.index-b.index;} 
get key()
{return String(this._index);}
get count()
{return this._count;}
get index()
{return this._index;}
get isSeparator()
{return this._separator;}
set isSeparator(value)
{this._separator=!!value;}
addSampleForProbe(probe,sample)
{this[probe.id]=sample;this._count++;}
missingKeys(probeSet)
{return probeSet.probes.filter(function(probe){return!this.hasOwnProperty(probe.id);},this);}
isComplete(probeSet)
{return!this.missingKeys(probeSet).length;}
fillMissingValues(probeSet)
{for(var key of this.missingKeys(probeSet))
this[key]=WI.ProbeSetDataFrame.MissingValue;}};WI.ProbeSetDataFrame.MissingValue="?";WI.ProbeSetDataTable=class ProbeSetDataTable extends WI.Object
{constructor(probeSet)
{super();this._probeSet=probeSet;this._frames=[];this._previousBatchIdentifier=WI.ProbeSetDataTable.SentinelValue;} 
get frames()
{return this._frames.slice();}
get separators()
{return this._frames.filter(function(frame){return frame.isSeparator;});}
willRemove()
{this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.WillRemove);this._frames=[];delete this._probeSet;}
mainResourceChanged()
{this.addSeparator();}
addSampleForProbe(probe,sample)
{if(sample.batchId!==this._previousBatchIdentifier){if(this._openFrame){this._openFrame.fillMissingValues(this._probeSet);this.addFrame(this._openFrame);}
this._openFrame=this.createFrame();this._previousBatchIdentifier=sample.batchId;}
this._openFrame.addSampleForProbe(probe,sample);if(this._openFrame.count===this._probeSet.probes.length){this.addFrame(this._openFrame);this._openFrame=null;}}
addProbe(probe)
{for(var frame of this.frames)
if(!frame[probe.id])
frame[probe.id]=WI.ProbeSetDataTable.UnknownValue;}
removeProbe(probe)
{for(var frame of this.frames)
delete frame[probe.id];}
createFrame()
{return new WI.ProbeSetDataFrame(this._frames.length);}
addFrame(frame)
{this._frames.push(frame);this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.FrameInserted,frame);}
addSeparator()
{if(!this._frames.length)
return;var previousFrame=this._frames.lastValue;if(previousFrame.isSeparator)
return;previousFrame.isSeparator=true;this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.SeparatorInserted,previousFrame);}};WI.ProbeSetDataTable.Event={FrameInserted:"probe-set-data-table-frame-inserted",SeparatorInserted:"probe-set-data-table-separator-inserted",WillRemove:"probe-set-data-table-will-remove"};WI.ProbeSetDataTable.SentinelValue=-1;WI.ProbeSetDataTable.UnknownValue="?";WI.Profile=class Profile
{constructor(topDownRootNodes)
{topDownRootNodes=topDownRootNodes||[];this._topDownRootNodes=topDownRootNodes;} 
get topDownRootNodes()
{return this._topDownRootNodes;}
get bottomUpRootNodes()
{return[];}};WI.ProfileNode=class ProfileNode
{constructor(id,type,functionName,sourceCodeLocation,callInfo,childNodes)
{childNodes=childNodes||[];this._id=id;this._type=type||WI.ProfileNode.Type.Function;this._functionName=functionName||null;this._sourceCodeLocation=sourceCodeLocation||null;this._callInfo=callInfo;this._childNodes=childNodes;this._parentNode=null;this._previousSibling=null;this._nextSibling=null;this._computedTotalTimes=false;this._startTime=this._callInfo.startTime;this._endTime=this._callInfo.endTime;this._totalTime=this._callInfo.totalTime;this._callCount=this._callInfo.callCount;for(var i=0;i<this._childNodes.length;++i)
this._childNodes[i].establishRelationships(this,this._childNodes[i-1],this._childNodes[i+1]);} 
get id(){return this._id;}
get type(){return this._type;}
get functionName(){return this._functionName;}
get sourceCodeLocation(){return this._sourceCodeLocation;}
get callInfo(){return this._callInfo;}
get previousSibling(){return this._previousSibling;}
get nextSibling(){return this._nextSibling;}
get parentNode(){return this._parentNode;}
get childNodes(){return this._childNodes;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get selfTime()
{this._computeTotalTimesIfNeeded();return this._selfTime;}
get totalTime()
{this._computeTotalTimesIfNeeded();return this._totalTime;}
computeCallInfoForTimeRange(rangeStartTime,rangeEndTime)
{

if(this._selfTime===undefined){var childNodesTotalTime=0;for(var childNode of this._childNodes)
childNodesTotalTime+=childNode.totalTime;this._selfTime=this._totalTime-childNodesTotalTime;if(this._selfTime<0.0001)
this._selfTime=0.0;}
return{callCount:this._callCount,startTime:this._startTime,endTime:this._endTime,selfTime:this._selfTime,totalTime:this._totalTime,averageTime:this._selfTime/this._callCount,};}
traverseNextProfileNode(stayWithin)
{var profileNode=this._childNodes[0];if(profileNode)
return profileNode;if(this===stayWithin)
return null;profileNode=this._nextSibling;if(profileNode)
return profileNode;profileNode=this;while(profileNode&&!profileNode.nextSibling&&profileNode.parentNode!==stayWithin)
profileNode=profileNode.parentNode;if(!profileNode)
return null;return profileNode.nextSibling;}
saveIdentityToCookie(cookie)
{cookie[WI.ProfileNode.TypeCookieKey]=this._type||null;cookie[WI.ProfileNode.FunctionNameCookieKey]=this._functionName||null;cookie[WI.ProfileNode.SourceCodeURLCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.sourceCode.url?this._sourceCodeLocation.sourceCode.url.hash:null:null;cookie[WI.ProfileNode.SourceCodeLocationLineCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:null;cookie[WI.ProfileNode.SourceCodeLocationColumnCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:null;} 
establishRelationships(parentNode,previousSibling,nextSibling)
{this._parentNode=parentNode||null;this._previousSibling=previousSibling||null;this._nextSibling=nextSibling||null;} 
_computeTotalTimesIfNeeded()
{if(this._computedTotalTimes)
return;this._computedTotalTimes=true;var info=this.computeCallInfoForTimeRange(0,Infinity);this._startTime=info.startTime;this._endTime=info.endTime;this._selfTime=info.selfTime;this._totalTime=info.totalTime;}};WI.ProfileNode.Type={Function:"profile-node-type-function",Program:"profile-node-type-program"};WI.ProfileNode.TypeIdentifier="profile-node";WI.ProfileNode.TypeCookieKey="profile-node-type";WI.ProfileNode.FunctionNameCookieKey="profile-node-function-name";WI.ProfileNode.SourceCodeURLCookieKey="profile-node-source-code-url";WI.ProfileNode.SourceCodeLocationLineCookieKey="profile-node-source-code-location-line";WI.ProfileNode.SourceCodeLocationColumnCookieKey="profile-node-source-code-location-column";WI.ProfileNodeCall=class ProfileNodeCall
{constructor(startTime,totalTime)
{this._startTime=startTime;this._totalTime=totalTime||0;this._parentNode=null;this._previousSibling=null;this._nextSibling=null;} 
get startTime()
{return this._startTime;}
get totalTime()
{return this._totalTime;}
get endTime()
{return this._startTime+this._totalTime;} 
establishRelationships(parentNode,previousSibling,nextSibling)
{this._parentNode=parentNode||null;this._previousSibling=previousSibling||null;this._nextSibling=nextSibling||null;}};WI.PropertyDescriptor=class PropertyDescriptor
{constructor(descriptor,symbol,isOwnProperty,wasThrown,nativeGetter,isInternalProperty)
{this._name=descriptor.name;this._value=descriptor.value;this._hasValue="value"in descriptor;this._get=descriptor.get;this._set=descriptor.set;this._symbol=symbol;this._writable=descriptor.writable||false;this._configurable=descriptor.configurable||false;this._enumerable=descriptor.enumerable||false;this._own=isOwnProperty||false;this._wasThrown=wasThrown||false;this._nativeGetterValue=nativeGetter||false;this._internal=isInternalProperty||false;}

static fromPayload(payload,internal,target)
{if(payload.value)
payload.value=WI.RemoteObject.fromPayload(payload.value,target);if(payload.get)
payload.get=WI.RemoteObject.fromPayload(payload.get,target);if(payload.set)
payload.set=WI.RemoteObject.fromPayload(payload.set,target);if(payload.symbol)
payload.symbol=WI.RemoteObject.fromPayload(payload.symbol,target);if(internal){payload.writable=payload.configurable=payload.enumerable=false;payload.isOwn=true;}
return new WI.PropertyDescriptor(payload,payload.symbol,payload.isOwn,payload.wasThrown,payload.nativeGetter,internal);} 
get name(){return this._name;}
get value(){return this._value;}
get get(){return this._get;}
get set(){return this._set;}
get writable(){return this._writable;}
get configurable(){return this._configurable;}
get enumerable(){return this._enumerable;}
get symbol(){return this._symbol;}
get isOwnProperty(){return this._own;}
get wasThrown(){return this._wasThrown;}
get nativeGetter(){return this._nativeGetterValue;}
get isInternalProperty(){return this._internal;}
hasValue()
{return this._hasValue;}
hasGetter()
{return this._get&&this._get.type==="function";}
hasSetter()
{return this._set&&this._set.type==="function";}
isIndexProperty()
{return!isNaN(Number(this._name));}
isSymbolProperty()
{return!!this._symbol;}};WI.PropertyPath=class PropertyPath
{constructor(object,pathComponent,parent,isPrototype)
{if(parent&&!parent.object)
throw new Error("Attempted to append to a PropertyPath with null object.");this._object=object;this._pathComponent=typeof pathComponent==="string"?pathComponent:null;this._parent=parent||null;this._isPrototype=isPrototype||false;} 
static emptyPropertyPathForScope(object)
{return new WI.PropertyPath(object,WI.PropertyPath.SpecialPathComponent.EmptyPathComponentForScope);} 
get object(){return this._object;}
get parent(){return this._parent;}
get isPrototype(){return this._isPrototype;}
get pathComponent(){return this._pathComponent;}
set pathComponent(pathComponent){this._pathComponent=pathComponent;}
get rootObject()
{return this._parent?this._parent.rootObject:this._object;}
get lastNonPrototypeObject()
{if(!this._parent)
return this._object;var p=this._parent;while(p){if(!p.isPrototype)
break;if(!p.parent)
break;p=p.parent;}
return p.object;}
get fullPath()
{var components=[];for(var p=this;p&&p.pathComponent;p=p.parent)
components.push(p.pathComponent);components.reverse();return components.join("");}
get reducedPath()
{var components=[];var p=this;for(;p&&p.isPrototype;p=p.parent)
components.push(p.pathComponent);for(;p&&p.pathComponent;p=p.parent){if(p.isPrototype)
continue;components.push(p.pathComponent);}
components.reverse();return components.join("");}
displayPath(type)
{return type===WI.PropertyPath.Type.Value?this.reducedPath:this.fullPath;}
isRoot()
{return!this._parent;}
isScope()
{return this._pathComponent===WI.PropertyPath.SpecialPathComponent.EmptyPathComponentForScope;}
isPathComponentImpossible()
{return this._pathComponent&&this._pathComponent.startsWith("@");}
isFullPathImpossible()
{if(this.isPathComponentImpossible())
return true;if(this._parent)
return this._parent.isFullPathImpossible();return false;}
appendPropertyName(object,propertyName)
{var isPrototype=propertyName==="__proto__";if(this.isScope())
return new WI.PropertyPath(object,propertyName,this,isPrototype);var component=this._canPropertyNameBeDotAccess(propertyName)?"."+propertyName:"["+doubleQuotedString(propertyName)+"]";return new WI.PropertyPath(object,component,this,isPrototype);}
appendPropertySymbol(object,symbolName)
{var component=WI.PropertyPath.SpecialPathComponent.SymbolPropertyName+(symbolName.length?"("+symbolName+")":"");return new WI.PropertyPath(object,component,this);}
appendInternalPropertyName(object,propertyName)
{var component=WI.PropertyPath.SpecialPathComponent.InternalPropertyName+"["+propertyName+"]";return new WI.PropertyPath(object,component,this);}
appendGetterPropertyName(object,propertyName)
{var component=".__lookupGetter__("+doubleQuotedString(propertyName)+")";return new WI.PropertyPath(object,component,this);}
appendSetterPropertyName(object,propertyName)
{var component=".__lookupSetter__("+doubleQuotedString(propertyName)+")";return new WI.PropertyPath(object,component,this);}
appendArrayIndex(object,indexString)
{var component="["+indexString+"]";return new WI.PropertyPath(object,component,this);}
appendMapKey(object)
{var component=WI.PropertyPath.SpecialPathComponent.MapKey;return new WI.PropertyPath(object,component,this);}
appendMapValue(object,keyObject)
{if(keyObject&&keyObject.hasValue()){if(keyObject.type==="string"){var component=".get("+doubleQuotedString(keyObject.description)+")";return new WI.PropertyPath(object,component,this);}
var component=".get("+keyObject.description+")";return new WI.PropertyPath(object,component,this);}
var component=WI.PropertyPath.SpecialPathComponent.MapValue;return new WI.PropertyPath(object,component,this);}
appendSetIndex(object)
{var component=WI.PropertyPath.SpecialPathComponent.SetIndex;return new WI.PropertyPath(object,component,this);}
appendSymbolProperty(object)
{var component=WI.PropertyPath.SpecialPathComponent.SymbolPropertyName;return new WI.PropertyPath(object,component,this);}
appendPropertyDescriptor(object,descriptor,type)
{if(descriptor.isInternalProperty)
return this.appendInternalPropertyName(object,descriptor.name);if(descriptor.symbol)
return this.appendSymbolProperty(object);if(type===WI.PropertyPath.Type.Getter)
return this.appendGetterPropertyName(object,descriptor.name);if(type===WI.PropertyPath.Type.Setter)
return this.appendSetterPropertyName(object,descriptor.name);if(this._object.subtype==="array"&&!isNaN(parseInt(descriptor.name)))
return this.appendArrayIndex(object,descriptor.name);return this.appendPropertyName(object,descriptor.name);} 
_canPropertyNameBeDotAccess(propertyName)
{return/^(?![0-9])\w+$/.test(propertyName);}};WI.PropertyPath.SpecialPathComponent={InternalPropertyName:"@internal",SymbolPropertyName:"@symbol",MapKey:"@mapkey",MapValue:"@mapvalue",SetIndex:"@setindex",EmptyPathComponentForScope:"",};WI.PropertyPath.Type={Value:"value",Getter:"getter",Setter:"setter",};WI.PropertyPreview=class PropertyPreview
{constructor(name,type,subtype,value,valuePreview,isInternalProperty)
{this._name=name;this._type=type;this._subtype=subtype;this._value=value;this._valuePreview=valuePreview;this._internal=isInternalProperty;}

static fromPayload(payload)
{if(payload.valuePreview)
payload.valuePreview=WI.ObjectPreview.fromPayload(payload.valuePreview);return new WI.PropertyPreview(payload.name,payload.type,payload.subtype,payload.value,payload.valuePreview,payload.internal);} 
get name(){return this._name;}
get type(){return this._type;}
get subtype(){return this._subtype;}
get value(){return this._value;}
get valuePreview(){return this._valuePreview;}
get internal(){return this._internal;}};WI.Recording=class Recording extends WI.Object
{constructor(version,type,initialState,frames,data)
{super();this._version=version;this._type=type;this._initialState=initialState;this._frames=frames;this._data=data;this._displayName=WI.UIString("Recording");this._swizzle=null;this._actions=[new WI.RecordingInitialStateAction].concat(...this._frames.map((frame)=>frame.actions));this._visualActionIndexes=[];this._source=null;this._processContext=null;this._processStates=[];this._processing=false;}
static fromPayload(payload,frames)
{if(typeof payload!=="object"||payload===null)
return null;if(typeof payload.version!=="number"){WI.Recording.synthesizeError(WI.UIString("non-number %s").format(WI.unlocalizedString("version")));return null;}
if(payload.version<1||payload.version>WI.Recording.Version){WI.Recording.synthesizeError(WI.UIString("unsupported %s").format(WI.unlocalizedString("version")));return null;}
if(parseInt(payload.version)!==payload.version){WI.Recording.synthesizeWarning(WI.UIString("non-integer %s").format(WI.unlocalizedString("version")));payload.version=parseInt(payload.version);}
let type=null;switch(payload.type){case InspectorBackend.Enum.Recording.Type.Canvas2D:type=WI.Recording.Type.Canvas2D;break;case InspectorBackend.Enum.Recording.Type.CanvasBitmapRenderer:type=WI.Recording.Type.CanvasBitmapRenderer;break;case InspectorBackend.Enum.Recording.Type.CanvasWebGL:type=WI.Recording.Type.CanvasWebGL;break;case InspectorBackend.Enum.Recording.Type.CanvasWebGL2:type=WI.Recording.Type.CanvasWebGL2;break;default:WI.Recording.synthesizeWarning(WI.UIString("unknown %s \u0022%s\u0022").format(WI.unlocalizedString("type"),payload.type));type=String(payload.type);break;}
if(typeof payload.initialState!=="object"||payload.initialState===null){if("initialState"in payload)
WI.Recording.synthesizeWarning(WI.UIString("non-object %s").format(WI.unlocalizedString("initialState")));payload.initialState={};}
if(typeof payload.initialState.attributes!=="object"||payload.initialState.attributes===null){if("attributes"in payload.initialState)
WI.Recording.synthesizeWarning(WI.UIString("non-object %s").format(WI.unlocalizedString("initialState.attributes")));payload.initialState.attributes={};}
if(!Array.isArray(payload.initialState.states)||payload.initialState.states.some((item)=>typeof item!=="object"||item===null)){if("states"in payload.initialState)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("initialState.states")));payload.initialState.states=[]; if(!isEmptyObject(payload.initialState.attributes)){let{width,height,...state}=payload.initialState.attributes;if(!isEmptyObject(state))
payload.initialState.states.push(state);}}
if(!Array.isArray(payload.initialState.parameters)){if("parameters"in payload.initialState)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("initialState.attributes")));payload.initialState.parameters=[];}
if(typeof payload.initialState.content!=="string"){if("content"in payload.initialState)
WI.Recording.synthesizeWarning(WI.UIString("non-string %s").format(WI.unlocalizedString("initialState.content")));payload.initialState.content="";}
if(!Array.isArray(payload.frames)){if("frames"in payload)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("frames")));payload.frames=[];}
if(!Array.isArray(payload.data)){if("data"in payload)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("data")));payload.data=[];}
if(!frames)
frames=payload.frames.map(WI.RecordingFrame.fromPayload)
return new WI.Recording(payload.version,type,payload.initialState,frames,payload.data);}
static displayNameForRecordingType(recordingType)
{switch(recordingType){case Recording.Type.Canvas2D:return WI.UIString("2D");case Recording.Type.CanvasBitmapRenderer:return WI.UIString("Bitmap Renderer","Recording Type Canvas Bitmap Renderer","A type of canvas recording in the Graphics Tab");case Recording.Type.CanvasWebGL:return WI.unlocalizedString("WebGL");case Recording.Type.CanvasWebGL2:return WI.unlocalizedString("WebGL2");}
return null;}
static displayNameForSwizzleType(swizzleType)
{switch(swizzleType){case WI.Recording.Swizzle.None:return WI.unlocalizedString("None");case WI.Recording.Swizzle.Number:return WI.unlocalizedString("Number");case WI.Recording.Swizzle.Boolean:return WI.unlocalizedString("Boolean");case WI.Recording.Swizzle.String:return WI.unlocalizedString("String");case WI.Recording.Swizzle.Array:return WI.unlocalizedString("Array");case WI.Recording.Swizzle.TypedArray:return WI.unlocalizedString("TypedArray");case WI.Recording.Swizzle.Image:return WI.unlocalizedString("Image");case WI.Recording.Swizzle.ImageData:return WI.unlocalizedString("ImageData");case WI.Recording.Swizzle.DOMMatrix:return WI.unlocalizedString("DOMMatrix");case WI.Recording.Swizzle.Path2D:return WI.unlocalizedString("Path2D");case WI.Recording.Swizzle.CanvasGradient:return WI.unlocalizedString("CanvasGradient");case WI.Recording.Swizzle.CanvasPattern:return WI.unlocalizedString("CanvasPattern");case WI.Recording.Swizzle.WebGLBuffer:return WI.unlocalizedString("WebGLBuffer");case WI.Recording.Swizzle.WebGLFramebuffer:return WI.unlocalizedString("WebGLFramebuffer");case WI.Recording.Swizzle.WebGLRenderbuffer:return WI.unlocalizedString("WebGLRenderbuffer");case WI.Recording.Swizzle.WebGLTexture:return WI.unlocalizedString("WebGLTexture");case WI.Recording.Swizzle.WebGLShader:return WI.unlocalizedString("WebGLShader");case WI.Recording.Swizzle.WebGLProgram:return WI.unlocalizedString("WebGLProgram");case WI.Recording.Swizzle.WebGLUniformLocation:return WI.unlocalizedString("WebGLUniformLocation");case WI.Recording.Swizzle.ImageBitmap:return WI.unlocalizedString("ImageBitmap");case WI.Recording.Swizzle.WebGLQuery:return WI.unlocalizedString("WebGLQuery");case WI.Recording.Swizzle.WebGLSampler:return WI.unlocalizedString("WebGLSampler");case WI.Recording.Swizzle.WebGLSync:return WI.unlocalizedString("WebGLSync");case WI.Recording.Swizzle.WebGLTransformFeedback:return WI.unlocalizedString("WebGLTransformFeedback");case WI.Recording.Swizzle.WebGLVertexArrayObject:return WI.unlocalizedString("WebGLVertexArrayObject");default:console.error("Unknown swizzle type",swizzleType);return null;}}
static synthesizeWarning(message)
{message=WI.UIString("Recording Warning: %s").format(message);if(window.InspectorTest){console.warn(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Warning,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);}
static synthesizeError(message)
{message=WI.UIString("Recording Error: %s").format(message);if(window.InspectorTest){console.error(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} 
get displayName(){return this._displayName;}
get type(){return this._type;}
get initialState(){return this._initialState;}
get frames(){return this._frames;}
get data(){return this._data;}
get actions(){return this._actions;}
get visualActionIndexes(){return this._visualActionIndexes;}
get source(){return this._source;}
set source(source){this._source=source;}
get processing(){return this._processing;}
get ready()
{return this._actions.lastValue.ready;}
startProcessing()
{if(this._processing||this.ready)
return;this._processing=true;this._process();}
stopProcessing()
{if(!this._processing||this.ready)
return;this._processing=false;}
createDisplayName(suggestedName)
{let recordingNameSet;if(this._source){recordingNameSet=this._source[WI.Recording.CanvasRecordingNamesSymbol];if(!recordingNameSet)
this._source[WI.Recording.CanvasRecordingNamesSymbol]=recordingNameSet=new Set;}else
recordingNameSet=WI.Recording._importedRecordingNameSet;let name;if(suggestedName){name=suggestedName;let duplicateNumber=2;while(recordingNameSet.has(name))
name=`${suggestedName} (${duplicateNumber++})`;}else{let recordingNumber=1;do{name=WI.UIString("Recording %d").format(recordingNumber++);}while(recordingNameSet.has(name));}
recordingNameSet.add(name);this._displayName=name;}
async swizzle(index,type)
{if(!this._swizzle)
this._swizzle={};if(typeof this._swizzle[index]!=="object")
this._swizzle[index]={};if(type===WI.Recording.Swizzle.Number)
return parseFloat(index);if(type===WI.Recording.Swizzle.Boolean)
return!!index;if(type===WI.Recording.Swizzle.Array)
return Array.isArray(index)?index:[];if(type===WI.Recording.Swizzle.DOMMatrix)
return new DOMMatrix(index); if(type===WI.Recording.Swizzle.TypedArray||type===WI.Recording.Swizzle.WebGLBuffer||type===WI.Recording.Swizzle.WebGLFramebuffer||type===WI.Recording.Swizzle.WebGLRenderbuffer||type===WI.Recording.Swizzle.WebGLTexture||type===WI.Recording.Swizzle.WebGLShader||type===WI.Recording.Swizzle.WebGLProgram||type===WI.Recording.Swizzle.WebGLUniformLocation||type===WI.Recording.Swizzle.WebGLQuery||type===WI.Recording.Swizzle.WebGLSampler||type===WI.Recording.Swizzle.WebGLSync||type===WI.Recording.Swizzle.WebGLTransformFeedback||type===WI.Recording.Swizzle.WebGLVertexArrayObject){return index;}
if(!(type in this._swizzle[index])){try{let data=this._data[index];switch(type){case WI.Recording.Swizzle.None:this._swizzle[index][type]=data;break;case WI.Recording.Swizzle.String:if(Array.isArray(data))
this._swizzle[index][type]=await Promise.all(data.map((item)=>this.swizzle(item,WI.Recording.Swizzle.String)));else
this._swizzle[index][type]=String(data);break;case WI.Recording.Swizzle.Image:this._swizzle[index][type]=await WI.ImageUtilities.promisifyLoad(data);this._swizzle[index][type].__data=data;break;case WI.Recording.Swizzle.ImageData:{let[object,width,height]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.Array),this.swizzle(data[1],WI.Recording.Swizzle.Number),this.swizzle(data[2],WI.Recording.Swizzle.Number),]);object=await Promise.all(object.map((item)=>this.swizzle(item,WI.Recording.Swizzle.Number)));this._swizzle[index][type]=new ImageData(new Uint8ClampedArray(object),width,height);this._swizzle[index][type].__data={data:object,width,height};break;}
case WI.Recording.Swizzle.Path2D:this._swizzle[index][type]=new Path2D(data);this._swizzle[index][type].__data=data;break;case WI.Recording.Swizzle.CanvasGradient:{let[gradientType,points]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.String),this.swizzle(data[1],WI.Recording.Swizzle.Array),]);points=await Promise.all(points.map((item)=>this.swizzle(item,WI.Recording.Swizzle.Number)));WI.ImageUtilities.scratchCanvasContext2D((context)=>{if(gradientType=="radial-gradient")
this._swizzle[index][type]=context.createRadialGradient(...points);else if(gradientType=="linear-gradient")
this._swizzle[index][type]=context.createLinearGradient(...points);else
this._swizzle[index][type]=context.createConicGradient(...points);});let stops=[];for(let stop of data[2]){let[offset,color]=await Promise.all([this.swizzle(stop[0],WI.Recording.Swizzle.Number),this.swizzle(stop[1],WI.Recording.Swizzle.String),]);this._swizzle[index][type].addColorStop(offset,color);stops.push({offset,color});}
this._swizzle[index][type].__data={type:gradientType,points,stops};break;}
case WI.Recording.Swizzle.CanvasPattern:{let[image,repeat]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.Image),this.swizzle(data[1],WI.Recording.Swizzle.String),]);WI.ImageUtilities.scratchCanvasContext2D((context)=>{this._swizzle[index][type]=context.createPattern(image,repeat);this._swizzle[index][type].__image=image;});this._swizzle[index][type].__data={image:image.__data,repeat};break;}
case WI.Recording.Swizzle.ImageBitmap:{let image=await this.swizzle(index,WI.Recording.Swizzle.Image);this._swizzle[index][type]=await createImageBitmap(image);this._swizzle[index][type].__data=data;break;}
case WI.Recording.Swizzle.CallStack:{let array=await this.swizzle(data,WI.Recording.Swizzle.Array);this._swizzle[index][type]=await Promise.all(array.map((item)=>this.swizzle(item,WI.Recording.Swizzle.CallFrame)));break;}
case WI.Recording.Swizzle.CallFrame:{let array=await this.swizzle(data,WI.Recording.Swizzle.Array);let[functionName,url]=await Promise.all([this.swizzle(array[0],WI.Recording.Swizzle.String),this.swizzle(array[1],WI.Recording.Swizzle.String),]);this._swizzle[index][type]=WI.CallFrame.fromPayload(WI.assumingMainTarget(),{functionName,url,lineNumber:array[2],columnNumber:array[3],});break;}}}catch{}}
return this._swizzle[index][type];}
createContext()
{let createCanvasContext=(type)=>{let canvas=document.createElement("canvas");if("width"in this._initialState.attributes)
canvas.width=this._initialState.attributes.width;if("height"in this._initialState.attributes)
canvas.height=this._initialState.attributes.height;return canvas.getContext(type,...this._initialState.parameters);};if(this._type===WI.Recording.Type.Canvas2D)
return createCanvasContext("2d");if(this._type===WI.Recording.Type.CanvasBitmapRenderer)
return createCanvasContext("bitmaprenderer");if(this._type===WI.Recording.Type.CanvasWebGL)
return createCanvasContext("webgl");if(this._type===WI.Recording.Type.CanvasWebGL2)
return createCanvasContext("webgl2");console.error("Unknown recording type",this._type);return null;}
toJSON()
{let initialState={};if(!isEmptyObject(this._initialState.attributes))
initialState.attributes=this._initialState.attributes;if(this._initialState.states.length)
initialState.states=this._initialState.states;if(this._initialState.parameters.length)
initialState.parameters=this._initialState.parameters;if(this._initialState.content&&this._initialState.content.length)
initialState.content=this._initialState.content;return{version:this._version,type:this._type,initialState,frames:this._frames.map((frame)=>frame.toJSON()),data:this._data,};}
toHTML()
{let lines=[];let objects=[];function processObject(object){objects.push({object,index:objects.length});return`objects[${objects.length - 1}]`;}
function processValue(value){if(typeof value==="object"&&!Array.isArray(value))
return processObject(value);return JSON.stringify(value);}
function escapeHTML(s){return s.replace(/[^0-9A-Za-z ]/g,(c)=>{return`&#${c.charCodeAt(0)};`;});}
lines.push(`<!DOCTYPE html>`);lines.push(`<head>`);lines.push(`<title>${escapeHTML(this._displayName)}</title>`);lines.push(`<style>`);lines.push(`    body {`);lines.push(`        margin: 0;`);lines.push(`    }`);lines.push(`    canvas {`);lines.push(`        max-width: calc(100% - 40px);`);lines.push(`        max-height: calc(100% - 40px);`);lines.push(`        padding: 20px;`);lines.push(`    }`);lines.push(`</style>`);lines.push(`</head>`);lines.push(`<body>`);lines.push(`<script>`);lines.push(`"use strict";`);lines.push(``);lines.push(`let promises = [];`);lines.push(`let objects = {};`);lines.push(``);lines.push(`let canvas = document.body.appendChild(document.createElement("canvas"));`);for(let[attribute,value]of Object.entries(this._initialState.attributes))
lines.push(`canvas.${attribute} = ${JSON.stringify(value)};`);lines.push(``);let parametersString=this._initialState.parameters.map(processValue).join(`, `);lines.push(`let context = canvas.getContext("2d"${parametersString ? ", " + parametersString : ""});`);lines.push(``);lines.push(`let frames = [`);lines.push(`    function initialState() {`);if(this._initialState.content){let image=new Image;image.__data=this._initialState.content;lines.push(`        context.drawImage(${processObject(image)}, 0, 0);`);lines.push(``);}
for(let state of this._actions[0].states){for(let[name,value]of state){if(name==="getPath"||name==="currentX"||name==="currentY")
continue;let contextString=`context`;if(name==="setPath"){lines.push(`        if (${JSON.stringify(name)} in context)`);contextString=`    `+contextString;}
let callString=``;if(WI.RecordingAction.isFunctionForType(this._type,name))
callString=`(`+value.map(processValue).join(`, `)+`)`;else
callString=` = ${processValue(value)}`;lines.push(`        ${contextString}.${name}${callString};`);}
if(state!==this._actions[0].states.lastValue){lines.push(`        context.save();`);lines.push(``);}}
lines.push(`    },`);lines.push(`    function startRecording() {`);lines.push(`        if (typeof console.record === "function")`);lines.push(`            console.record(context, {name: ${JSON.stringify(this._displayName)}});`);lines.push(`    },`);for(let i=0;i<this._frames.length;++i){lines.push(`    function frame${i + 1}() {`);for(let action of this._frames[i].actions){let contextString=`context`;if(action.contextReplacer)
contextString+=`.${action.contextReplacer}`;if(!action.valid)
contextString=`// `+contextString;let callString=``;if(action.isFunction)
callString+=`(`+action.parameters.map(processValue).join(`, `)+`)`;else if(!action.isGetter)
callString+=` = `+processValue(action.parameters[0]);lines.push(`        ${contextString}.${action.name}${callString};`);}
lines.push(`    },`);}
lines.push(`    function stopRecording() {`);lines.push(`        if (typeof console.recordEnd === "function")`);lines.push(`            console.recordEnd(context);`);lines.push(`    },`);lines.push(`];`);lines.push(``);if(objects.length){if(objects.some(({object})=>object instanceof CanvasGradient)){lines.push(`function rebuildCanvasGradient(key, data) {`);lines.push(`    let gradient = null;`);lines.push(`    if (data.type === "radial-gradient")`);lines.push(`        gradient = context.createRadialGradient(data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]);`);lines.push(`    else if (data.type === "linear-gradient")`);lines.push(`        gradient = context.createLinearGradient(data.points[0], data.points[1], data.points[2], data.points[3]);`);lines.push(`    else`);lines.push(`        gradient = context.createConicGradient(data.points[0], data.points[1], data.points[2]);`);lines.push(`    for (let stop of data.stops)`);lines.push(`        gradient.addColorStop(stop.offset, stop.color);`);lines.push(`    objects[key] = gradient;`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof CanvasPattern)){lines.push(`function rebuildCanvasPattern(key, data) {`);lines.push(`    promises.push(new Promise(function(resolve, reject) {`);lines.push(`        let image = new Image;`);lines.push(`        function resolveWithImage(event) {`);lines.push(`            objects[key] = context.createPattern(image, data.repeat);`);lines.push(`            resolve();`);lines.push(`        }`);lines.push(`        image.addEventListener("load", resolveWithImage);`);lines.push(`        image.addEventListener("error", resolveWithImage);`);lines.push(`        image.src = data.image;`);lines.push(`    }));`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof DOMMatrix)){lines.push(`function rebuildDOMMatrix(key, data) {`);lines.push(`    objects[key] = new DOMMatrix(data);`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof Image)){lines.push(`function rebuildImage(key, data) {`);lines.push(`    promises.push(new Promise(function(resolve, reject) {`);lines.push(`        let image = new Image;`);lines.push(`        function resolveWithImage(event) {`);lines.push(`            objects[key] = image;`);lines.push(`            resolve();`);lines.push(`        }`);lines.push(`        image.addEventListener("load", resolveWithImage);`);lines.push(`        image.addEventListener("error", resolveWithImage);`);lines.push(`        image.src = data;`);lines.push(`    }));`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof ImageBitmap)){lines.push(`function rebuildImageBitmap(key, data) {`);lines.push(`    promises.push(new Promise(function(resolve, reject) {`);lines.push(`        let image = new Image;`);lines.push(`        function resolveWithImage(event) {`);lines.push(`            createImageBitmap(image).then(function(imageBitmap) {`);lines.push(`                objects[key] = imageBitmap;`);lines.push(`                resolve();`);lines.push(`            });`);lines.push(`        }`);lines.push(`        image.addEventListener("load", resolveWithImage);`);lines.push(`        image.addEventListener("error", resolveWithImage);`);lines.push(`        image.src = data;`);lines.push(`    }));`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof ImageData)){lines.push(`function rebuildImageData(key, data) {`);lines.push(`    objects[key] = new ImageData(new Uint8ClampedArray(data.data), parseInt(data.width), parseInt(data.height));`);lines.push(`}`);}
if(objects.some(({object})=>object instanceof Path2D)){lines.push(`function rebuildPath2D(key, data) {`);lines.push(`    objects[key] = new Path2D(data);`);lines.push(`}`);}
lines.push(``);for(let{object,index}of objects){if(object instanceof CanvasGradient){lines.push(`rebuildCanvasGradient(${index}, ${JSON.stringify(object.__data)});`);continue;}
if(object instanceof CanvasPattern){lines.push(`rebuildCanvasPattern(${index}, ${JSON.stringify(object.__data)});`);continue;}
if(object instanceof DOMMatrix){lines.push(`rebuildDOMMatrix(${index}, ${JSON.stringify(object.toString())});`)
continue;}
if(object instanceof Image){lines.push(`rebuildImage(${index}, ${JSON.stringify(object.__data)});`)
continue;}
if(object instanceof ImageBitmap){lines.push(`rebuildImageBitmap(${index}, ${JSON.stringify(object.__data)});`)
continue;}
if(object instanceof ImageData){lines.push(`rebuildImageData(${index}, ${JSON.stringify(object.__data)});`);continue;}
if(object instanceof Path2D){lines.push(`rebuildPath2D(${index}, ${JSON.stringify(object.__data || "")});`)
continue;}}
lines.push(``);}
lines.push(`Promise.all(promises).then(function() {`);lines.push(`    window.requestAnimationFrame(function executeFrame() {`);lines.push(`        frames.shift()();`);lines.push(`        if (frames.length)`);lines.push(`            window.requestAnimationFrame(executeFrame);`);lines.push(`    });`);lines.push(`});`);lines.push(`</script>`);lines.push(`</body>`);return lines.join(`\n`);} 
async _process()
{if(!this._processContext){this._processContext=this.createContext();if(this._type===WI.Recording.Type.Canvas2D){let initialContent=await WI.ImageUtilities.promisifyLoad(this._initialState.content);this._processContext.drawImage(initialContent,0,0);for(let initialState of this._initialState.states){let state=await WI.RecordingState.swizzleInitialState(this,initialState);state.apply(this._type,this._processContext);if(initialState!==this._initialState.states.lastValue){this._processContext.save();this._processStates.push(WI.RecordingState.fromContext(this._type,this._processContext));}}}}
if(!this._actions[0].ready){this._actions[0].process(this,this._processContext,this._processStates);this.dispatchEventToListeners(WI.Recording.Event.ProcessedAction,{action:this._actions[0],index:0});}
const workInterval=10;let startTime=Date.now();let cumulativeActionIndex=0;let lastAction=this._actions[cumulativeActionIndex];for(let frameIndex=0;frameIndex<this._frames.length;++frameIndex){let frame=this._frames[frameIndex];if(frame.actions.lastValue.ready){cumulativeActionIndex+=frame.actions.length;lastAction=frame.actions.lastValue;continue;}
for(let actionIndex=0;actionIndex<frame.actions.length;++actionIndex){++cumulativeActionIndex;let action=frame.actions[actionIndex];if(action.ready){lastAction=action;continue;}
await action.swizzle(this);action.process(this,this._processContext,this._processStates,{lastAction});if(action.isVisual)
this._visualActionIndexes.push(cumulativeActionIndex);if(!actionIndex)
this.dispatchEventToListeners(WI.Recording.Event.StartProcessingFrame,{frame,index:frameIndex});this.dispatchEventToListeners(WI.Recording.Event.ProcessedAction,{action,index:cumulativeActionIndex});if(Date.now()-startTime>workInterval){await Promise.delay(); startTime=Date.now();}
lastAction=action;if(!this._processing)
return;}
if(!this._processing)
return;}
this._swizzle=null;this._processContext=null;this._processing=false;}};WI.Recording.Version=1;WI.Recording.Event={ProcessedAction:"recording-processed-action",StartProcessingFrame:"recording-start-processing-frame",};WI.Recording._importedRecordingNameSet=new Set;WI.Recording.CanvasRecordingNamesSymbol=Symbol("canvas-recording-names");WI.Recording.Type={Canvas2D:"canvas-2d",CanvasBitmapRenderer:"canvas-bitmaprenderer",CanvasWebGL:"canvas-webgl",CanvasWebGL2:"canvas-webgl2",};WI.Recording.Swizzle={None:0,Number:1,Boolean:2,String:3,Array:4,TypedArray:5,Image:6,ImageData:7,DOMMatrix:8,Path2D:9,CanvasGradient:10,CanvasPattern:11,WebGLBuffer:12,WebGLFramebuffer:13,WebGLRenderbuffer:14,WebGLTexture:15,WebGLShader:16,WebGLProgram:17,WebGLUniformLocation:18,ImageBitmap:19,WebGLQuery:20,WebGLSampler:21,WebGLSync:22,WebGLTransformFeedback:23,WebGLVertexArrayObject:24,CallStack:Symbol("CallStack"),CallFrame:Symbol("CallFrame"),};WI.RecordingAction=class RecordingAction extends WI.Object
{constructor(name,parameters,swizzleTypes,trace,snapshot)
{super();this._payloadName=name;this._payloadParameters=parameters;this._payloadSwizzleTypes=swizzleTypes;this._payloadTrace=trace;this._payloadSnapshot=snapshot??-1;this._name="";this._parameters=[];this._trace=[];this._snapshot="";this._valid=true;this._isFunction=false;this._isGetter=false;this._isVisual=false;this._contextReplacer=null;this._states=[];this._stateModifiers=new Set;this._warning=null;this._swizzled=false;this._processed=false;}

static fromPayload(payload)
{if(!Array.isArray(payload))
payload=[];if(typeof payload[0]!=="number"){if(payload.length>0)
WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("name")));payload[0]=-1;}
if(!Array.isArray(payload[1])){if(payload.length>1)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("parameters")));payload[1]=[];}
if(!Array.isArray(payload[2])){if(payload.length>2)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("swizzleTypes")));payload[2]=[];}
if(typeof payload[3]!=="number"||isNaN(payload[3])||(!payload[3]&&payload[3]!==0)){ if(!Array.isArray(payload[3])){if(payload.length>3)
WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("trace")));payload[3]=[];}}
if(typeof payload[4]!=="number"||isNaN(payload[4])){if(payload.length>4)
WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("snapshot")));payload[4]=-1;}
return new WI.RecordingAction(...payload);}
static isFunctionForType(type,name)
{let prototype=WI.RecordingAction._prototypeForType(type);if(!prototype)
return false;let propertyDescriptor=Object.getOwnPropertyDescriptor(prototype,name);if(!propertyDescriptor)
return false;return typeof propertyDescriptor.value==="function";}
static constantNameForParameter(type,name,value,index,count)
{let indexesForType=WI.RecordingAction._constantIndexes[type];if(!indexesForType)
return null;let indexesForAction=indexesForType[name];if(!indexesForAction)
return null;if(Array.isArray(indexesForAction)&&!indexesForAction.includes(index))
return null;if(typeof indexesForAction==="object"){let indexesForActionVariant=indexesForAction[count];if(!indexesForActionVariant)
return null;if(Array.isArray(indexesForActionVariant)&&!indexesForActionVariant.includes(index))
return null;}
if(value===0&&(type===WI.Recording.Type.CanvasWebGL||type===WI.Recording.Type.CanvasWebGL2)){if(name==="blendFunc"||name==="blendFuncSeparate")
return"ZERO";if(index===0){if(name==="drawArrays"||name==="drawElements")
return"POINTS";if(name==="pixelStorei")
return"NONE";}}
let prototype=WI.RecordingAction._prototypeForType(type);if(prototype){for(let key in prototype){let descriptor=Object.getOwnPropertyDescriptor(prototype,key);if(descriptor&&descriptor.value===value)
return key;}}
return null;}
static _prototypeForType(type)
{switch(type){case WI.Recording.Type.Canvas2D:return CanvasRenderingContext2D.prototype;case WI.Recording.Type.CanvasBitmapRenderer:if(window.ImageBitmapRenderingContext)
return ImageBitmapRenderingContext.prototype;break;case WI.Recording.Type.CanvasWebGL:if(window.WebGLRenderingContext)
return WebGLRenderingContext.prototype;break;case WI.Recording.Type.CanvasWebGL2:if(window.WebGL2RenderingContext)
return WebGL2RenderingContext.prototype;break;}
WI.reportInternalError("Unknown recording type: "+type);return null;} 
get name(){return this._name;}
get parameters(){return this._parameters;}
get swizzleTypes(){return this._payloadSwizzleTypes;}
get trace(){return this._trace;}
get snapshot(){return this._snapshot;}
get valid(){return this._valid;}
get isFunction(){return this._isFunction;}
get isGetter(){return this._isGetter;}
get isVisual(){return this._isVisual;}
get contextReplacer(){return this._contextReplacer;}
get states(){return this._states;}
get stateModifiers(){return this._stateModifiers;}
get warning(){return this._warning;}
get ready()
{return this._swizzled&&this._processed;}
process(recording,context,states,{lastAction}={})
{this._processed=true;if(recording.type===WI.Recording.Type.CanvasWebGL||recording.type===WI.Recording.Type.CanvasWebGL2){if(this._valid&&this._isVisual){let contentBefore=recording.visualActionIndexes.length?recording.actions[recording.visualActionIndexes.lastValue].snapshot:recording.initialState.content;if(this._snapshot===contentBefore)
this._warning=WI.UIString("This action causes no visual change");}
return;}
function getContent(){if(context instanceof CanvasRenderingContext2D)
return context.getImageData(0,0,context.canvas.width,context.canvas.height).data;if((window.WebGLRenderingContext&&context instanceof WebGLRenderingContext)||(window.WebGL2RenderingContext&&context instanceof WebGL2RenderingContext)){let pixels=new Uint8Array(context.drawingBufferWidth*context.drawingBufferHeight*4);context.readPixels(0,0,context.canvas.width,context.canvas.height,context.RGBA,context.UNSIGNED_BYTE,pixels);return pixels;}
if(context.canvas instanceof HTMLCanvasElement)
return[context.canvas.toDataURL()];return[];}
let contentBefore=null;let shouldCheckHasVisualEffect=this._valid&&this._isVisual;if(shouldCheckHasVisualEffect)
contentBefore=getContent();this.apply(context);if(shouldCheckHasVisualEffect){let contentAfter=getContent();if(Array.shallowEqual(contentBefore,contentAfter))
this._warning=WI.UIString("This action causes no visual change");}
if(recording.type===WI.Recording.Type.Canvas2D){let currentState=WI.RecordingState.fromContext(recording.type,context,{source:this});if(this.name==="save")
states.push(currentState);else if(this.name==="restore")
states.pop();this._states=states.slice();this._states.push(currentState);let lastState=null;if(lastAction){lastState=lastAction.states.lastValue;for(let[name,value]of currentState){let previousValue=lastState.get(name);if(value!==previousValue&&!Object.shallowEqual(value,previousValue))
this._stateModifiers.add(name);}}
if(WI.ImageUtilities.supportsCanvasPathDebugging()){let currentX=currentState.get("currentX");let invalidX=(currentX<0||currentX>=context.canvas.width)&&(!lastState||currentX!==lastState.get("currentX"));let currentY=currentState.get("currentY");let invalidY=(currentY<0||currentY>=context.canvas.height)&&(!lastState||currentY!==lastState.get("currentY"));if(invalidX||invalidY)
this._warning=WI.UIString("This action moves the path outside the visible area");}}}
async swizzle(recording,lastAction)
{if(!this._valid){this._swizzled=true;return;}
let swizzleParameter=(item,index)=>{return recording.swizzle(item,this._payloadSwizzleTypes[index]);};let swizzlePromises=[recording.swizzle(this._payloadName,WI.Recording.Swizzle.String),Promise.all(this._payloadParameters.map(swizzleParameter)),];if(!isNaN(this._payloadTrace))
swizzlePromises.push(recording.swizzle(this._payloadTrace,WI.Recording.Swizzle.CallStack))
else{ swizzlePromises.push(Promise.all(this._payloadTrace.map((item)=>recording.swizzle(item,WI.Recording.Swizzle.CallFrame))));}
if(this._payloadSnapshot>=0)
swizzlePromises.push(recording.swizzle(this._payloadSnapshot,WI.Recording.Swizzle.String));let[name,parameters,callFrames,snapshot]=await Promise.all(swizzlePromises);this._name=name;this._parameters=parameters;this._trace=callFrames;if(this._payloadSnapshot>=0)
this._snapshot=snapshot;if(recording.type===WI.Recording.Type.Canvas2D||recording.type===WI.Recording.Type.CanvasBitmapRenderer||recording.type===WI.Recording.Type.CanvasWebGL||recording.type===WI.Recording.Type.CanvasWebGL2){if(this._name==="width"||this._name==="height"){this._contextReplacer="canvas";this._isFunction=false;this._isGetter=!this._parameters.length;this._isVisual=!this._isGetter;}
}
if(!this._contextReplacer){this._isFunction=WI.RecordingAction.isFunctionForType(recording.type,this._name);this._isGetter=!this._isFunction&&!this._parameters.length;if(this._snapshot)
this._isVisual=true;else{let visualNames=WI.RecordingAction._visualNames[recording.type];this._isVisual=visualNames?visualNames.has(this._name):false;}
if(this._valid){let prototype=WI.RecordingAction._prototypeForType(recording.type);if(prototype&&!(name in prototype)){this.markInvalid();WI.Recording.synthesizeWarning(WI.UIString("\u0022%s\u0022 is not valid for %s").format(name,prototype.constructor.name));}}}
if(this._valid){let parametersSpecified=this._parameters.every((parameter)=>parameter!==undefined);let parametersCanBeSwizzled=this._payloadSwizzleTypes.every((swizzleType)=>swizzleType!==WI.Recording.Swizzle.None);if(!parametersSpecified||!parametersCanBeSwizzled)
this.markInvalid();}
if(this._valid){let stateModifiers=WI.RecordingAction._stateModifiers[recording.type];if(stateModifiers){this._stateModifiers.add(this._name);let modifiedByAction=stateModifiers[this._name]||[];for(let item of modifiedByAction)
this._stateModifiers.add(item);}}
this._swizzled=true;}
apply(context,options={})
{if(!this.valid)
return;try{let name=options.nameOverride||this._name;if(this._contextReplacer)
context=context[this._contextReplacer];if(this.isFunction)
context[name](...this._parameters);else{if(this.isGetter)
context[name];else
context[name]=this._parameters[0];}}catch{this.markInvalid();WI.Recording.synthesizeWarning(WI.UIString("\u0022%s\u0022 threw an error").format(this._name));}}
markInvalid()
{if(!this._valid)
return;this._valid=false;this.dispatchEventToListeners(WI.RecordingAction.Event.ValidityChanged);}
getColorParameters()
{switch(this._name){ case"fillStyle":case"strokeStyle":case"shadowColor":case"setFillColor":case"setStrokeColor": case"blendColor":case"clearColor":case"colorMask":return this._parameters;case"setShadow":return this._parameters.slice(3);}
return[];}
getImageParameters()
{switch(this._name){ case"createImageData":case"createPattern":case"drawImage":case"fillStyle":case"putImageData":case"strokeStyle":case"drawImageFromRect": case"transferFromImageBitmap":return this._parameters.slice(0,1); case"texImage2D":case"texSubImage2D":case"compressedTexImage2D":return[this._parameters.lastValue];}
return[];}
toJSON()
{let json=[this._payloadName,this._payloadParameters,this._payloadSwizzleTypes,this._payloadTrace];if(this._payloadSnapshot>=0)
json.push(this._payloadSnapshot);return json;}};WI.RecordingAction.Event={ValidityChanged:"recording-action-marked-invalid",};WI.RecordingAction._constantIndexes={[WI.Recording.Type.CanvasWebGL]:{"activeTexture":true,"bindBuffer":true,"bindFramebuffer":true,"bindRenderbuffer":true,"bindTexture":true,"blendEquation":true,"blendEquationSeparate":true,"blendFunc":true,"blendFuncSeparate":true,"bufferData":[0,2],"bufferSubData":[0],"checkFramebufferStatus":true,"compressedTexImage2D":[0,2],"compressedTexSubImage2D":[0],"copyTexImage2D":[0,2],"copyTexSubImage2D":[0],"createShader":true,"cullFace":true,"depthFunc":true,"disable":true,"drawArrays":[0],"drawElements":[0,2],"enable":true,"framebufferRenderbuffer":true,"framebufferTexture2D":[0,1,2],"frontFace":true,"generateMipmap":true,"getBufferParameter":true,"getFramebufferAttachmentParameter":true,"getParameter":true,"getProgramParameter":true,"getRenderbufferParameter":true,"getShaderParameter":true,"getShaderPrecisionFormat":true,"getTexParameter":true,"getVertexAttrib":[1],"getVertexAttribOffset":[1],"hint":true,"isEnabled":true,"pixelStorei":[0],"readPixels":[4,5],"renderbufferStorage":[0,1],"stencilFunc":[0],"stencilFuncSeparate":[0,1],"stencilMaskSeparate":[0],"stencilOp":true,"stencilOpSeparate":true,"texImage2D":{5:[0,2,3,4],6:[0,2,3,4],8:[0,2,6,7],9:[0,2,6,7],},"texParameterf":[0,1],"texParameteri":[0,1],"texSubImage2D":{6:[0,4,5],7:[0,4,5],8:[0,6,7],9:[0,6,7],},"vertexAttribPointer":[2],},[WI.Recording.Type.CanvasWebGL2]:{"activeTexture":true,"beginQuery":[0],"beginTransformFeedback":true,"bindBuffer":true,"bindBufferBase":[0],"bindBufferRange":[0],"bindFramebuffer":true,"bindRenderbuffer":true,"bindTexture":true,"bindTransformFeedback":[0],"blendEquation":true,"blendEquationSeparate":true,"blendFunc":true,"blendFuncSeparate":true,"blitFramebuffer":[10],"bufferData":[0,2],"bufferSubData":[0],"checkFramebufferStatus":true,"clearBufferfi":[0],"clearBufferfv":[0],"clearBufferiv":[0],"clearBufferuiv":[0],"compressedTexImage2D":[0,2],"compressedTexSubImage2D":[0],"compressedTexSubImage3D":[0],"copyBufferSubData":[0,1],"copyTexImage2D":[0,2],"copyTexSubImage2D":[0],"copyTexSubImage3D":[0],"createShader":true,"cullFace":true,"depthFunc":true,"disable":true,"drawArrays":[0],"drawArraysInstanced":[0],"drawBuffers":true,"drawElements":[0,2],"drawElementsInstanced":[0,2],"drawRangeElements":[0,4],"enable":true,"endQuery":true,"fenceSync":[0],"framebufferRenderbuffer":true,"framebufferTexture2D":[0,1,2],"framebufferTextureLayer":[0,1],"frontFace":true,"generateMipmap":true,"getActiveUniformBlockParameter":[2],"getActiveUniforms":[2],"getBufferParameter":true,"getBufferSubData":[0],"getFramebufferAttachmentParameter":true,"getIndexedParameter":[0],"getInternalformatParameter":true,"getParameter":true,"getProgramParameter":true,"getQuery":true,"getQueryParameter":[1],"getRenderbufferParameter":true,"getSamplerParameter":[1],"getShaderParameter":true,"getShaderPrecisionFormat":true,"getSyncParameter":[1],"getTexParameter":true,"getVertexAttrib":[1],"getVertexAttribOffset":[1],"hint":true,"invalidateFramebuffer":[0,1],"invalidateSubFramebuffer":[0,1],"isEnabled":true,"pixelStorei":[0],"readBuffer":true,"readPixels":[4,5],"renderbufferStorage":[0,1],"renderbufferStorageMultisample":[0,2],"samplerParameterf":[1],"samplerParameteri":[1],"stencilFunc":[0],"stencilFuncSeparate":[0,1],"stencilMaskSeparate":[0],"stencilOp":true,"stencilOpSeparate":true,"texImage2D":{5:[0,2,3,4],6:[0,2,3,4],8:[0,2,6,7],9:[0,2,6,7],10:[0,2,6,7],11:[0,2,7,8],},"texParameterf":[0,1],"texParameteri":[0,1],"texStorage2D":[0,2],"texSubImage2D":{6:[0,4,5],7:[0,4,5],8:[0,6,7],9:[0,6,7],10:[0,6,7],11:[0,8,9],12:[0,8,9],},"transformFeedbackVaryings":[2],"vertexAttribIPointer":[2],"vertexAttribPointer":[2],},};WI.RecordingAction._visualNames={[WI.Recording.Type.Canvas2D]:new Set(["clearRect","drawFocusIfNeeded","drawImage","drawImageFromRect","fill","fillRect","fillText","putImageData","stroke","strokeRect","strokeText",]),[WI.Recording.Type.CanvasBitmapRenderer]:new Set(["transferFromImageBitmap",]),[WI.Recording.Type.CanvasWebGL]:new Set(["clear","drawArrays","drawElements",]),[WI.Recording.Type.CanvasWebGL2]:new Set(["clear","drawArrays","drawArraysInstanced","drawElements","drawElementsInstanced",]),};WI.RecordingAction._stateModifiers={[WI.Recording.Type.Canvas2D]:{arc:["currentX","currentY"],arcTo:["currentX","currentY"],beginPath:["currentX","currentY"],bezierCurveTo:["currentX","currentY"],clearShadow:["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"],closePath:["currentX","currentY"],ellipse:["currentX","currentY"],lineTo:["currentX","currentY"],moveTo:["currentX","currentY"],quadraticCurveTo:["currentX","currentY"],rect:["currentX","currentY"],resetTransform:["transform"],rotate:["transform"],scale:["transform"],setAlpha:["globalAlpha"],setCompositeOperation:["globalCompositeOperation"],setFillColor:["fillStyle"],setLineCap:["lineCap"],setLineJoin:["lineJoin"],setLineWidth:["lineWidth"],setMiterLimit:["miterLimit"],setShadow:["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"],setStrokeColor:["strokeStyle"],setTransform:["transform"],translate:["transform"],},};WI.RecordingFrame=class RecordingFrame
{constructor(actions,{duration,incomplete}={})
{this._actions=actions;this._duration=duration||NaN;this._incomplete=incomplete||false;} 
static fromPayload(payload)
{if(typeof payload!=="object"||payload===null)
payload={};if(!Array.isArray(payload.actions)){if("actions"in payload)
WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("actions")));payload.actions=[];}
let actions=payload.actions.map(WI.RecordingAction.fromPayload);return new WI.RecordingFrame(actions,{duration:payload.duration||NaN,incomplete:!!payload.incomplete,});} 
get actions(){return this._actions;}
get duration(){return this._duration;}
get incomplete(){return this._incomplete;}
toJSON()
{let json={actions:this._actions.map((action)=>action.toJSON()),};if(!isNaN(this._duration))
json.duration=this._duration;if(this._incomplete)
json.incomplete=this._incomplete;return json;}};WI.RecordingInitialStateAction=class RecordingInitialStateAction extends WI.RecordingAction
{constructor()
{super();this._name=WI.UIString("Initial State");this._valid=false;this._swizzled=true;}};WI.RecordingState=class RecordingState
{constructor(data,{source}={})
{this._data=data;this._source=source||null;} 
static fromContext(type,context,options={})
{if(type!==WI.Recording.Type.Canvas2D)
return null;let matrix=context.getTransform();let data={};if(WI.ImageUtilities.supportsCanvasPathDebugging()){data.currentX=context.currentX;data.currentY=context.currentY;}
data.direction=context.direction;data.fillStyle=context.fillStyle;data.font=context.font;data.globalAlpha=context.globalAlpha;data.globalCompositeOperation=context.globalCompositeOperation;data.imageSmoothingEnabled=context.imageSmoothingEnabled;data.imageSmoothingQuality=context.imageSmoothingQuality;data.lineCap=context.lineCap;data.lineDash=context.getLineDash();data.lineDashOffset=context.lineDashOffset;data.lineJoin=context.lineJoin;data.lineWidth=context.lineWidth;data.miterLimit=context.miterLimit;data.shadowBlur=context.shadowBlur;data.shadowColor=context.shadowColor;data.shadowOffsetX=context.shadowOffsetX;data.shadowOffsetY=context.shadowOffsetY;data.strokeStyle=context.strokeStyle;data.textAlign=context.textAlign;data.textBaseline=context.textBaseline;data.transform=[matrix.a,matrix.b,matrix.c,matrix.d,matrix.e,matrix.f];data.webkitImageSmoothingEnabled=context.webkitImageSmoothingEnabled;data.webkitLineDash=context.webkitLineDash;data.webkitLineDashOffset=context.webkitLineDashOffset;if(WI.ImageUtilities.supportsCanvasPathDebugging())
data.setPath=[context.getPath()];return new WI.RecordingState(data,options);}
static async swizzleInitialState(recording,initialState)
{if(recording.type===WI.Recording.Type.Canvas2D){let swizzledState={};for(let[name,value]of Object.entries(initialState)){ let nameIndex=parseInt(name);if(!isNaN(nameIndex))
name=await recording.swizzle(nameIndex,WI.Recording.Swizzle.String);switch(name){case"setTransform":value=[await recording.swizzle(value,WI.Recording.Swizzle.DOMMatrix)];break;case"fillStyle":case"strokeStyle":var[gradient,pattern,string]=await Promise.all([recording.swizzle(value,WI.Recording.Swizzle.CanvasGradient),recording.swizzle(value,WI.Recording.Swizzle.CanvasPattern),recording.swizzle(value,WI.Recording.Swizzle.String),]);if(gradient&&!pattern)
value=gradient;else if(pattern&&!gradient)
value=pattern;else
value=string;break;case"direction":case"font":case"globalCompositeOperation":case"imageSmoothingQuality":case"lineCap":case"lineJoin":case"shadowColor":case"textAlign":case"textBaseline":value=await recording.swizzle(value,WI.Recording.Swizzle.String);break;case"globalAlpha":case"lineWidth":case"miterLimit":case"shadowOffsetX":case"shadowOffsetY":case"shadowBlur":case"lineDashOffset":value=await recording.swizzle(value,WI.Recording.Swizzle.Number);break;case"setPath":value=[await recording.swizzle(value[0],WI.Recording.Swizzle.Path2D)];break;}
if(value===undefined||(Array.isArray(value)&&value.includes(undefined)))
continue;swizzledState[name]=value;}
return new WI.RecordingState(swizzledState);}
return null;} 
get source(){return this._source;}
has(name)
{return name in this._data;}
get(name)
{return this._data[name];}
apply(type,context)
{for(let[name,value]of this){if(!(name in context))
continue;if(name==="currentX"||name==="currentY")
continue;try{if(WI.RecordingAction.isFunctionForType(type,name))
context[name](...value);else
context[name]=value;}catch{}}}
toJSON()
{return this._data;}
[Symbol.iterator]()
{return Object.entries(this._data)[Symbol.iterator]();}};WI.Redirect=class Redirect
{constructor(url,requestMethod,requestHeaders,responseStatusCode,responseStatusText,responseHeaders,timestamp)
{this._url=url;this._urlComponents=null;this._requestMethod=requestMethod;this._requestHeaders=requestHeaders;this._responseStatusCode=responseStatusCode;this._responseStatusText=responseStatusText;this._responseHeaders=responseHeaders;this._timestamp=timestamp;} 
get url(){return this._url;}
get requestMethod(){return this._requestMethod;}
get requestHeaders(){return this._requestHeaders;}
get responseStatusCode(){return this._responseStatusCode;}
get responseStatusText(){return this._responseStatusText;}
get responseHeaders(){return this._responseHeaders;}
get timestamp(){return this._timestamp;}
get urlComponents()
{if(!this._urlComponents)
this._urlComponents=parseURL(this._url);return this._urlComponents;}};WI.RenderingFrameTimelineRecord=class RenderingFrameTimelineRecord extends WI.TimelineRecord
{constructor(startTime,endTime,name)
{super(WI.TimelineRecord.Type.RenderingFrame,startTime,endTime);this._name=name||"";this._durationByTaskType=new Map;this._frameIndex=-1;} 
static resetFrameIndex()
{WI.RenderingFrameTimelineRecord._nextFrameIndex=0;}
static displayNameForTaskType(taskType)
{switch(taskType){case WI.RenderingFrameTimelineRecord.TaskType.Script:return WI.UIString("Script");case WI.RenderingFrameTimelineRecord.TaskType.Layout:return WI.repeatedUIString.timelineRecordLayout();case WI.RenderingFrameTimelineRecord.TaskType.Paint:return WI.repeatedUIString.timelineRecordPaint();case WI.RenderingFrameTimelineRecord.TaskType.Other:return WI.UIString("Other");}}
static taskTypeForTimelineRecord(record)
{switch(record.type){case WI.TimelineRecord.Type.Script:return WI.RenderingFrameTimelineRecord.TaskType.Script;case WI.TimelineRecord.Type.Layout:if(record.eventType===WI.LayoutTimelineRecord.EventType.Paint||record.eventType===WI.LayoutTimelineRecord.EventType.Composite)
return WI.RenderingFrameTimelineRecord.TaskType.Paint;return WI.RenderingFrameTimelineRecord.TaskType.Layout;default:console.error("Unsupported timeline record type: "+record.type);return null;}} 
static async fromJSON(json)
{let{startTime,endTime}=json;let record=new WI.RenderingFrameTimelineRecord(startTime,endTime);record.setupFrameIndex();return record;}
toJSON()
{return{type:this.type,startTime:this.startTime,endTime:this.endTime,};} 
get frameIndex()
{return this._frameIndex;}
get frameNumber()
{return this._frameIndex+1;}
get name()
{return this._name;}
setupFrameIndex()
{if(this._frameIndex>=0)
return;this._frameIndex=WI.RenderingFrameTimelineRecord._nextFrameIndex++;}
durationForTask(taskType)
{if(this._durationByTaskType.has(taskType))
return this._durationByTaskType.get(taskType);var duration;if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Other)
duration=this._calculateDurationRemainder();else{duration=this.children.reduce(function(previousValue,currentValue){if(taskType!==WI.RenderingFrameTimelineRecord.taskTypeForTimelineRecord(currentValue))
return previousValue;var currentDuration=currentValue.duration;if(currentValue.usesActiveStartTime)
currentDuration-=currentValue.inactiveDuration;return previousValue+currentDuration;},0);if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Script){
duration-=this.children.reduce(function(previousValue,currentValue){if(currentValue.type===WI.TimelineRecord.Type.Layout&&(currentValue.sourceCodeLocation||currentValue.callFrames))
return previousValue+currentValue.duration;return previousValue;},0);}}
this._durationByTaskType.set(taskType,duration);return duration;} 
_calculateDurationRemainder()
{return Object.keys(WI.RenderingFrameTimelineRecord.TaskType).reduce((previousValue,key)=>{let taskType=WI.RenderingFrameTimelineRecord.TaskType[key];if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Other)
return previousValue;return previousValue-this.durationForTask(taskType);},this.duration);}};WI.RenderingFrameTimelineRecord.TaskType={Script:"rendering-frame-timeline-record-script",Layout:"rendering-frame-timeline-record-layout",Paint:"rendering-frame-timeline-record-paint",Other:"rendering-frame-timeline-record-other"};WI.RenderingFrameTimelineRecord.TypeIdentifier="rendering-frame-timeline-record";WI.RenderingFrameTimelineRecord._nextFrameIndex=0;WI.ResourceCollection=class ResourceCollection extends WI.Collection
{constructor(resourceType)
{super();this._resourceType=resourceType||null;this._resourceURLMap=new Multimap;this._resourcesTypeMap=new Map;} 
get resourceType(){return this._resourceType;}
get displayName()
{const plural=true;return this._resourceType?WI.Resource.displayNameForType(this._resourceType,plural):WI.UIString("Resources");}
objectIsRequiredType(object)
{if(this._resourceType===WI.Resource.Type.StyleSheet&&object instanceof WI.CSSStyleSheet)
return true;if(!(object instanceof WI.Resource))
return false;if(!this._resourceType)
return true;return object.type===this._resourceType;}
resourcesForURL(url)
{return this._resourceURLMap.get(url)||new Set;}
resourceCollectionForType(type)
{if(this._resourceType){return this;}
let resourcesCollectionForType=this._resourcesTypeMap.get(type);if(!resourcesCollectionForType){resourcesCollectionForType=new WI.ResourceCollection(type);this._resourcesTypeMap.set(type,resourcesCollectionForType);}
return resourcesCollectionForType;}
clear()
{super.clear();this._resourceURLMap.clear();if(!this._resourceType)
this._resourcesTypeMap.clear();} 
itemAdded(item)
{this._associateWithResource(item);}
itemRemoved(item)
{this._disassociateWithResource(item);}
itemsCleared(items)
{const skipRemoval=true;for(let item of items)
this._disassociateWithResource(item,skipRemoval);} 
_associateWithResource(resource)
{this._resourceURLMap.add(resource.url,resource);if(!this._resourceType){let resourcesCollectionForType=this.resourceCollectionForType(resource.type);resourcesCollectionForType.add(resource);}
resource.addEventListener(WI.Resource.Event.URLDidChange,this._resourceURLDidChange,this);resource.addEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);}
_disassociateWithResource(resource,skipRemoval)
{resource.removeEventListener(WI.Resource.Event.URLDidChange,this._resourceURLDidChange,this);resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);if(skipRemoval)
return;if(!this._resourceType){let resourcesCollectionForType=this.resourceCollectionForType(resource.type);resourcesCollectionForType.remove(resource);}
this._resourceURLMap.delete(resource.url,resource);}
_resourceURLDidChange(event)
{let resource=event.target;if(!(resource instanceof WI.Resource))
return;let oldURL=event.data.oldURL;if(!oldURL)
return;this._resourceURLMap.add(resource.url,resource);this._resourceURLMap.delete(oldURL,resource);}
_resourceTypeDidChange(event)
{let resource=event.target;if(!(resource instanceof WI.Resource))
return;if(this._resourceType){this.remove(resource);return;}
let resourcesWithNewType=this.resourceCollectionForType(resource.type);resourcesWithNewType.add(resource);

}};WI.ResourceQueryMatch=class ResourceQueryMatch
{constructor(type,index,queryIndex)
{this._type=type;this._index=index;this._queryIndex=queryIndex;} 
get type(){return this._type;}
get index(){return this._index;}
get queryIndex(){return this._queryIndex;}};WI.ResourceQueryMatch.Type={Normal:Symbol("normal"),Special:Symbol("special")};WI.ResourceQueryResult=class ResourceQueryResult
{constructor(resource,matches,cookie)
{this._resource=resource;this._matches=matches;this._cookie=cookie||null;} 
get resource(){return this._resource;}
get cookie(){return this._cookie;}
get rank()
{if(this._rank===undefined)
this._calculateRank();return this._rank;}
get matchingTextRanges()
{if(!this._matchingTextRanges)
this._matchingTextRanges=this._createMatchingTextRanges();return this._matchingTextRanges;} 
_calculateRank()
{const normalWeight=10;const consecutiveWeight=5;const specialMultiplier=5;function getMultiplier(match){if(match.type===WI.ResourceQueryMatch.Type.Special)
return specialMultiplier;return 1;}
this._rank=0;let previousMatch=null;let consecutiveMatchStart=null;for(let match of this._matches){this._rank+=normalWeight*getMultiplier(match);let consecutive=previousMatch&&previousMatch.index===match.index-1;if(consecutive){if(!consecutiveMatchStart)
consecutiveMatchStart=previousMatch;


this._rank+=consecutiveWeight*getMultiplier(consecutiveMatchStart)*(match.index-consecutiveMatchStart.index);}else if(consecutiveMatchStart)
consecutiveMatchStart=null;previousMatch=match;

if(!consecutive)
this._rank-=match.index*getMultiplier(match);}}
_createMatchingTextRanges()
{if(!this._matches.length)
return[];let ranges=[];let startIndex=this._matches[0].index;let endIndex=startIndex;for(let i=1;i<this._matches.length;++i){let match=this._matches[i];if(match.index===endIndex+1){endIndex++;continue;}
ranges.push(new WI.TextRange(0,startIndex,0,endIndex+1));startIndex=match.index;endIndex=startIndex;}
ranges.push(new WI.TextRange(0,startIndex,0,endIndex+1));return ranges;} 
__test_createMatchesMask()
{let filename=this._resource.displayName;let lastIndex=-1;let result="";for(let match of this._matches){let gap=" ".repeat(match.index-lastIndex-1);result+=gap;result+=filename[match.index];lastIndex=match.index;}
return result;}};WI.ResourceTimelineRecord=class ResourceTimelineRecord extends WI.TimelineRecord
{constructor(resource)
{super(WI.TimelineRecord.Type.Network);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.TimestampsDidChange,this._dispatchUpdatedEvent,this);} 
static async fromJSON(json)
{let{entry,archiveStartTime}=json;let localResource=WI.LocalResource.fromHAREntry(entry,archiveStartTime);return new WI.ResourceTimelineRecord(localResource);}
toJSON()
{const content="";return{type:this.type,archiveStartTime:this._resource.requestSentWalltime-this.startTime,entry:WI.HARBuilder.entry(this._resource,content),};} 
get resource()
{return this._resource;}
get updatesDynamically()
{return true;}
get usesActiveStartTime()
{return true;}
get startTime()
{return this._resource.timingData.startTime;}
get activeStartTime()
{return this._resource.timingData.responseStart;}
get endTime()
{return this._resource.timingData.responseEnd;} 
_dispatchUpdatedEvent()
{this.dispatchEventToListeners(WI.TimelineRecord.Event.Updated);}};WI.ResourceTimingData=class ResourceTimingData
{constructor(resource,data)
{data=data||{};this._resource=resource;this._startTime=data.startTime||NaN;this._redirectStart=data.redirectStart||NaN;this._redirectEnd=data.redirectEnd||NaN;this._fetchStart=data.fetchStart||NaN;this._domainLookupStart=data.domainLookupStart||NaN;this._domainLookupEnd=data.domainLookupEnd||NaN;this._connectStart=data.connectStart||NaN;this._connectEnd=data.connectEnd||NaN;this._secureConnectionStart=data.secureConnectionStart||NaN;this._requestStart=data.requestStart||NaN;this._responseStart=data.responseStart||NaN;this._responseEnd=data.responseEnd||NaN;if(this._domainLookupStart>=this._domainLookupEnd)
this._domainLookupStart=this._domainLookupEnd=NaN;if(this._connectStart>=this._connectEnd)
this._connectStart=this._connectEnd=NaN;} 
static fromPayload(payload,resource)
{payload=payload||{};let startTime=payload.startTime;let fetchStart=payload.fetchStart;let redirectStart=payload.redirectStart;let redirectEnd=payload.redirectEnd;if(isNaN(fetchStart)||fetchStart<startTime)
fetchStart=startTime;if(redirectStart<startTime||redirectStart>fetchStart||redirectStart>redirectEnd)
redirectStart=NaN;if(redirectEnd<startTime||redirectEnd>fetchStart||redirectEnd<redirectStart)
redirectEnd=NaN;function offsetToTimestamp(offset){return offset>0?fetchStart+(offset/1000):NaN;}
let data={startTime,redirectStart,redirectEnd,fetchStart,domainLookupStart:offsetToTimestamp(payload.domainLookupStart),domainLookupEnd:offsetToTimestamp(payload.domainLookupEnd),connectStart:offsetToTimestamp(payload.connectStart),connectEnd:offsetToTimestamp(payload.connectEnd),secureConnectionStart:offsetToTimestamp(payload.secureConnectionStart),requestStart:offsetToTimestamp(payload.requestStart),responseStart:offsetToTimestamp(payload.responseStart),responseEnd:offsetToTimestamp(payload.responseEnd)};return new WI.ResourceTimingData(resource,data);} 
get startTime(){return this._startTime||this._resource.requestSentTimestamp;}
get redirectStart(){return this._redirectStart;}
get redirectEnd(){return this._redirectEnd;}
get fetchStart(){return this._fetchStart||this._resource.requestSentTimestamp;}
get domainLookupStart(){return this._domainLookupStart;}
get domainLookupEnd(){return this._domainLookupEnd;}
get connectStart(){return this._connectStart;}
get connectEnd(){return this._connectEnd;}
get secureConnectionStart(){return this._secureConnectionStart;}
get requestStart(){return this._requestStart||this._startTime||this._resource.requestSentTimestamp;}
get responseStart(){return this._responseStart||this._startTime||this._resource.responseReceivedTimestamp||this._resource.finishedOrFailedTimestamp;}
get responseEnd(){return this._responseEnd||this._resource.finishedOrFailedTimestamp;}
markResponseEndTime(responseEnd)
{this._responseEnd=responseEnd;}};WI.Revision=class Revision
{ apply()
{console.error("Needs to be implemented by a subclass.");}
revert()
{console.error("Needs to be implemented by a subclass.");}
copy()
{return this;}};WI.ScopeChainNode=class ScopeChainNode
{constructor(type,objects,name,location,empty)
{if(type in WI.ScopeChainNode.Type)
type=WI.ScopeChainNode.Type[type];this._type=type||null;this._objects=objects||[];this._name=name||"";this._location=location||null;this._empty=empty||false;} 
get type(){return this._type;}
get objects(){return this._objects;}
get name(){return this._name;}
get location(){return this._location;}
get empty(){return this._empty;}
get hash()
{if(this._hash)
return this._hash;this._hash=this._name;if(this._location)
this._hash+=`:${this._location.scriptId}:${this._location.lineNumber}:${this._location.columnNumber}`;return this._hash;}
convertToLocalScope()
{this._type=WI.ScopeChainNode.Type.Local;}};WI.ScopeChainNode.Type={Local:"scope-chain-type-local",Global:"scope-chain-type-global",GlobalLexicalEnvironment:"scope-chain-type-global-lexical-environment",With:"scope-chain-type-with",Closure:"scope-chain-type-closure",Catch:"scope-chain-type-catch",FunctionName:"scope-chain-type-function-name",Block:"scope-chain-type-block",};WI.ScriptInstrument=class ScriptInstrument extends WI.Instrument
{ get timelineRecordType()
{return WI.TimelineRecord.Type.Script;}
startInstrumentation(initiatedByBackend)
{let target=WI.assumingMainTarget();const includeSamples=true;if(!initiatedByBackend)
target.ScriptProfilerAgent.startTracking(includeSamples);}
stopInstrumentation(initiatedByBackend)
{let target=WI.assumingMainTarget();if(!initiatedByBackend)
target.ScriptProfilerAgent.stopTracking();}};WI.ScriptSyntaxTree=class ScriptSyntaxTree
{constructor(sourceText,script)
{this._script=script;try{let sourceType=this._script.sourceType===WI.Script.SourceType.Module?"module":"script";let esprimaSyntaxTree=esprima.parse(sourceText,{loc:true,range:true,sourceType});this._syntaxTree=this._createInternalSyntaxTree(esprimaSyntaxTree);this._parsedSuccessfully=true;}catch(error){this._parsedSuccessfully=false;this._syntaxTree=null;console.error("Couldn't parse JavaScript File: "+script.url,error);}} 
get parsedSuccessfully()
{return this._parsedSuccessfully;}
forEachNode(callback)
{if(!this._parsedSuccessfully)
return;this._recurse(this._syntaxTree,callback,this._defaultParserState());}
filter(predicate,startNode)
{if(!this._parsedSuccessfully)
return[];var nodes=[];function filter(node,state)
{if(predicate(node))
nodes.push(node);else
state.skipChildNodes=true;}
this._recurse(startNode,filter,this._defaultParserState());return nodes;}
containersOfPosition(position)
{if(!this._parsedSuccessfully)
return[];let allNodes=[];this.forEachNode((node,state)=>{if(node.endPosition.isBefore(position))
state.skipChildNodes=true;else if(node.startPosition.isAfter(position))
state.shouldStopEarly=true;else
allNodes.push(node);});return allNodes;}
filterByRange(startPosition,endPosition)
{if(!this._parsedSuccessfully)
return[];var allNodes=[];function filterForNodesInRange(node,state)
{


if(node.endPosition.isBefore(startPosition)){state.skipChildNodes=true;return;}
if(node.startPosition.isWithin(startPosition,endPosition)){allNodes.push(node);return;}


if(node.startPosition.isAfter(endPosition))
state.shouldStopEarly=true;}
this.forEachNode(filterForNodesInRange);return allNodes;}
containsNonEmptyReturnStatement(startNode)
{if(!this._parsedSuccessfully)
return false;if(startNode.attachments._hasNonEmptyReturnStatement!==undefined)
return startNode.attachments._hasNonEmptyReturnStatement;function removeFunctionsFilter(node)
{return node.type!==WI.ScriptSyntaxTree.NodeType.FunctionExpression&&node.type!==WI.ScriptSyntaxTree.NodeType.FunctionDeclaration&&node.type!==WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression;}
var nodes=this.filter(removeFunctionsFilter,startNode);var hasNonEmptyReturnStatement=false;var returnStatementType=WI.ScriptSyntaxTree.NodeType.ReturnStatement;for(var node of nodes){if(node.type===returnStatementType&&node.argument){hasNonEmptyReturnStatement=true;break;}}
startNode.attachments._hasNonEmptyReturnStatement=hasNonEmptyReturnStatement;return hasNonEmptyReturnStatement;}
static functionReturnDivot(node)
{return node.typeProfilingReturnDivot;}
updateTypes(nodesToUpdate,callback)
{if(!this._parsedSuccessfully)
return;var allRequests=[];var allRequestNodes=[];var sourceID=this._script.id;for(var node of nodesToUpdate){switch(node.type){case WI.ScriptSyntaxTree.NodeType.FunctionDeclaration:case WI.ScriptSyntaxTree.NodeType.FunctionExpression:case WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression:for(var param of node.params){for(var identifier of this._gatherIdentifiersInDeclaration(param)){allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:identifier.range[0]});allRequestNodes.push(identifier);}}
allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.FunctionReturn,sourceID,divot:WI.ScriptSyntaxTree.functionReturnDivot(node)});allRequestNodes.push(node);break;case WI.ScriptSyntaxTree.NodeType.VariableDeclarator:for(var identifier of this._gatherIdentifiersInDeclaration(node.id)){allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:identifier.range[0]});allRequestNodes.push(identifier);}
break;}}
function handleTypes(error,typeInformationArray)
{if(error)
return;for(var i=0;i<typeInformationArray.length;i++){var node=allRequestNodes[i];var typeInformation=WI.TypeDescription.fromPayload(typeInformationArray[i]);if(allRequests[i].typeInformationDescriptor===WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.FunctionReturn)
node.attachments.returnTypes=typeInformation;else
node.attachments.types=typeInformation;}
callback(allRequestNodes);}
this._script.target.RuntimeAgent.getRuntimeTypesForVariablesAtOffsets(allRequests,handleTypes);} 
_gatherIdentifiersInDeclaration(node)
{function gatherIdentifiers(node)
{switch(node.type){case WI.ScriptSyntaxTree.NodeType.Identifier:return[node];case WI.ScriptSyntaxTree.NodeType.Property:return gatherIdentifiers(node.value);case WI.ScriptSyntaxTree.NodeType.ObjectPattern:var identifiers=[];for(var property of node.properties){for(var identifier of gatherIdentifiers(property))
identifiers.push(identifier);}
return identifiers;case WI.ScriptSyntaxTree.NodeType.ArrayPattern:var identifiers=[];for(var element of node.elements){for(var identifier of gatherIdentifiers(element))
identifiers.push(identifier);}
return identifiers;case WI.ScriptSyntaxTree.NodeType.AssignmentPattern:return gatherIdentifiers(node.left);case WI.ScriptSyntaxTree.NodeType.RestElement:return gatherIdentifiers(node.argument);default:return[];}}
return gatherIdentifiers(node);}
_defaultParserState()
{return{shouldStopEarly:false,skipChildNodes:false};}
_recurse(node,callback,state)
{if(!node)
return;if(state.shouldStopEarly||state.skipChildNodes)
return;callback(node,state);switch(node.type){case WI.ScriptSyntaxTree.NodeType.AssignmentExpression:this._recurse(node.left,callback,state);this._recurse(node.right,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ArrayExpression:case WI.ScriptSyntaxTree.NodeType.ArrayPattern:this._recurseArray(node.elements,callback,state);break;case WI.ScriptSyntaxTree.NodeType.AssignmentPattern:this._recurse(node.left,callback,state);this._recurse(node.right,callback,state);break;case WI.ScriptSyntaxTree.NodeType.AwaitExpression:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.BlockStatement:this._recurseArray(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.BinaryExpression:this._recurse(node.left,callback,state);this._recurse(node.right,callback,state);break;case WI.ScriptSyntaxTree.NodeType.BreakStatement:this._recurse(node.label,callback,state);break;case WI.ScriptSyntaxTree.NodeType.CatchClause:this._recurse(node.param,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.CallExpression:this._recurse(node.callee,callback,state);this._recurseArray(node.arguments,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ClassBody:this._recurseArray(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ClassDeclaration:case WI.ScriptSyntaxTree.NodeType.ClassExpression:this._recurse(node.id,callback,state);this._recurse(node.superClass,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ContinueStatement:this._recurse(node.label,callback,state);break;case WI.ScriptSyntaxTree.NodeType.DoWhileStatement:this._recurse(node.body,callback,state);this._recurse(node.test,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ExpressionStatement:this._recurse(node.expression,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ForStatement:this._recurse(node.init,callback,state);this._recurse(node.test,callback,state);this._recurse(node.update,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ForInStatement:case WI.ScriptSyntaxTree.NodeType.ForOfStatement:this._recurse(node.left,callback,state);this._recurse(node.right,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.FunctionDeclaration:case WI.ScriptSyntaxTree.NodeType.FunctionExpression:case WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression:this._recurse(node.id,callback,state);this._recurseArray(node.params,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.IfStatement:this._recurse(node.test,callback,state);this._recurse(node.consequent,callback,state);this._recurse(node.alternate,callback,state);break;case WI.ScriptSyntaxTree.NodeType.LabeledStatement:this._recurse(node.label,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.LogicalExpression:this._recurse(node.left,callback,state);this._recurse(node.right,callback,state);break;case WI.ScriptSyntaxTree.NodeType.MemberExpression:this._recurse(node.object,callback,state);this._recurse(node.property,callback,state);break;case WI.ScriptSyntaxTree.NodeType.MethodDefinition:this._recurse(node.key,callback,state);this._recurse(node.value,callback,state);break;case WI.ScriptSyntaxTree.NodeType.NewExpression:this._recurse(node.callee,callback,state);this._recurseArray(node.arguments,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ObjectExpression:case WI.ScriptSyntaxTree.NodeType.ObjectPattern:this._recurseArray(node.properties,callback,state);break;case WI.ScriptSyntaxTree.NodeType.Program:this._recurseArray(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.Property:this._recurse(node.key,callback,state);this._recurse(node.value,callback,state);break;case WI.ScriptSyntaxTree.NodeType.RestElement:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ReturnStatement:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.SequenceExpression:this._recurseArray(node.expressions,callback,state);break;case WI.ScriptSyntaxTree.NodeType.SpreadElement:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.SwitchStatement:this._recurse(node.discriminant,callback,state);this._recurseArray(node.cases,callback,state);break;case WI.ScriptSyntaxTree.NodeType.SwitchCase:this._recurse(node.test,callback,state);this._recurseArray(node.consequent,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ConditionalExpression:this._recurse(node.test,callback,state);this._recurse(node.consequent,callback,state);this._recurse(node.alternate,callback,state);break;case WI.ScriptSyntaxTree.NodeType.TaggedTemplateExpression:this._recurse(node.tag,callback,state);this._recurse(node.quasi,callback,state);break;case WI.ScriptSyntaxTree.NodeType.TemplateLiteral:this._recurseArray(node.quasis,callback,state);this._recurseArray(node.expressions,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ThrowStatement:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.TryStatement:this._recurse(node.block,callback,state);this._recurse(node.handler,callback,state);this._recurse(node.finalizer,callback,state);break;case WI.ScriptSyntaxTree.NodeType.UnaryExpression:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.UpdateExpression:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.VariableDeclaration:this._recurseArray(node.declarations,callback,state);break;case WI.ScriptSyntaxTree.NodeType.VariableDeclarator:this._recurse(node.id,callback,state);this._recurse(node.init,callback,state);break;case WI.ScriptSyntaxTree.NodeType.WhileStatement:this._recurse(node.test,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.WithStatement:this._recurse(node.object,callback,state);this._recurse(node.body,callback,state);break;case WI.ScriptSyntaxTree.NodeType.YieldExpression:this._recurse(node.argument,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ExportAllDeclaration:this._recurse(node.source,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ExportNamedDeclaration:this._recurse(node.declaration,callback,state);this._recurseArray(node.specifiers,callback,state);this._recurse(node.source,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ExportDefaultDeclaration:this._recurse(node.declaration,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ExportSpecifier:this._recurse(node.local,callback,state);this._recurse(node.exported,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ImportDeclaration:this._recurseArray(node.specifiers,callback,state);this._recurse(node.source,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ImportDefaultSpecifier:this._recurse(node.local,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ImportNamespaceSpecifier:this._recurse(node.local,callback,state);break;case WI.ScriptSyntaxTree.NodeType.ImportSpecifier:this._recurse(node.imported,callback,state);this._recurse(node.local,callback,state);break;case WI.ScriptSyntaxTree.NodeType.DebuggerStatement:case WI.ScriptSyntaxTree.NodeType.EmptyStatement:case WI.ScriptSyntaxTree.NodeType.Identifier:case WI.ScriptSyntaxTree.NodeType.Import:case WI.ScriptSyntaxTree.NodeType.Literal:case WI.ScriptSyntaxTree.NodeType.MetaProperty:case WI.ScriptSyntaxTree.NodeType.Super:case WI.ScriptSyntaxTree.NodeType.ThisExpression:case WI.ScriptSyntaxTree.NodeType.TemplateElement:break;}
state.skipChildNodes=false;}
_recurseArray(array,callback,state)
{for(var node of array)
this._recurse(node,callback,state);} 
_createInternalSyntaxTree(node)
{if(!node)
return null;var result=null;switch(node.type){case"ArrayExpression":result={type:WI.ScriptSyntaxTree.NodeType.ArrayExpression,elements:node.elements.map(this._createInternalSyntaxTree,this)};break;case"ArrayPattern":result={type:WI.ScriptSyntaxTree.NodeType.ArrayPattern,elements:node.elements.map(this._createInternalSyntaxTree,this)};break;case"ArrowFunctionExpression":result={type:WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression,id:this._createInternalSyntaxTree(node.id),params:node.params.map(this._createInternalSyntaxTree,this),body:this._createInternalSyntaxTree(node.body),generator:node.generator,expression:node.expression,async:node.async,typeProfilingReturnDivot:node.range[0]};break;case"AssignmentExpression":result={type:WI.ScriptSyntaxTree.NodeType.AssignmentExpression,operator:node.operator,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right)};break;case"AssignmentPattern":result={type:WI.ScriptSyntaxTree.NodeType.AssignmentPattern,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right),};break;case"AwaitExpression":result={type:WI.ScriptSyntaxTree.NodeType.AwaitExpression,argument:this._createInternalSyntaxTree(node.argument),};break;case"BlockStatement":result={type:WI.ScriptSyntaxTree.NodeType.BlockStatement,body:node.body.map(this._createInternalSyntaxTree,this)};break;case"BinaryExpression":result={type:WI.ScriptSyntaxTree.NodeType.BinaryExpression,operator:node.operator,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right)};break;case"BreakStatement":result={type:WI.ScriptSyntaxTree.NodeType.BreakStatement,label:this._createInternalSyntaxTree(node.label)};break;case"CallExpression":result={type:WI.ScriptSyntaxTree.NodeType.CallExpression,callee:this._createInternalSyntaxTree(node.callee),arguments:node.arguments.map(this._createInternalSyntaxTree,this)};break;case"CatchClause":result={type:WI.ScriptSyntaxTree.NodeType.CatchClause,param:this._createInternalSyntaxTree(node.param),body:this._createInternalSyntaxTree(node.body)};break;case"ClassBody":result={type:WI.ScriptSyntaxTree.NodeType.ClassBody,body:node.body.map(this._createInternalSyntaxTree,this)};break;case"ClassDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.ClassDeclaration,id:this._createInternalSyntaxTree(node.id),superClass:this._createInternalSyntaxTree(node.superClass),body:this._createInternalSyntaxTree(node.body),};break;case"ClassExpression":result={type:WI.ScriptSyntaxTree.NodeType.ClassExpression,id:this._createInternalSyntaxTree(node.id),superClass:this._createInternalSyntaxTree(node.superClass),body:this._createInternalSyntaxTree(node.body),};break;case"ConditionalExpression":result={type:WI.ScriptSyntaxTree.NodeType.ConditionalExpression,test:this._createInternalSyntaxTree(node.test),consequent:this._createInternalSyntaxTree(node.consequent),alternate:this._createInternalSyntaxTree(node.alternate)};break;case"ContinueStatement":result={type:WI.ScriptSyntaxTree.NodeType.ContinueStatement,label:this._createInternalSyntaxTree(node.label)};break;case"DoWhileStatement":result={type:WI.ScriptSyntaxTree.NodeType.DoWhileStatement,body:this._createInternalSyntaxTree(node.body),test:this._createInternalSyntaxTree(node.test)};break;case"DebuggerStatement":result={type:WI.ScriptSyntaxTree.NodeType.DebuggerStatement};break;case"EmptyStatement":result={type:WI.ScriptSyntaxTree.NodeType.EmptyStatement};break;case"ExpressionStatement":result={type:WI.ScriptSyntaxTree.NodeType.ExpressionStatement,expression:this._createInternalSyntaxTree(node.expression)};break;case"ForStatement":result={type:WI.ScriptSyntaxTree.NodeType.ForStatement,init:this._createInternalSyntaxTree(node.init),test:this._createInternalSyntaxTree(node.test),update:this._createInternalSyntaxTree(node.update),body:this._createInternalSyntaxTree(node.body)};break;case"ForInStatement":result={type:WI.ScriptSyntaxTree.NodeType.ForInStatement,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right),body:this._createInternalSyntaxTree(node.body)};break;case"ForOfStatement":result={type:WI.ScriptSyntaxTree.NodeType.ForOfStatement,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right),body:this._createInternalSyntaxTree(node.body),await:node.await};break;case"FunctionDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.FunctionDeclaration,id:this._createInternalSyntaxTree(node.id),params:node.params.map(this._createInternalSyntaxTree,this),body:this._createInternalSyntaxTree(node.body),generator:node.generator,async:node.async,typeProfilingReturnDivot:node.range[0]};break;case"FunctionExpression":result={type:WI.ScriptSyntaxTree.NodeType.FunctionExpression,id:this._createInternalSyntaxTree(node.id),params:node.params.map(this._createInternalSyntaxTree,this),body:this._createInternalSyntaxTree(node.body),generator:node.generator,async:node.async,typeProfilingReturnDivot:node.range[0]
};break;case"Identifier":result={type:WI.ScriptSyntaxTree.NodeType.Identifier,name:node.name};break;case"IfStatement":result={type:WI.ScriptSyntaxTree.NodeType.IfStatement,test:this._createInternalSyntaxTree(node.test),consequent:this._createInternalSyntaxTree(node.consequent),alternate:this._createInternalSyntaxTree(node.alternate)};break;case"Literal":result={type:WI.ScriptSyntaxTree.NodeType.Literal,value:node.value,raw:node.raw};break;case"LabeledStatement":result={type:WI.ScriptSyntaxTree.NodeType.LabeledStatement,label:this._createInternalSyntaxTree(node.label),body:this._createInternalSyntaxTree(node.body)};break;case"LogicalExpression":result={type:WI.ScriptSyntaxTree.NodeType.LogicalExpression,left:this._createInternalSyntaxTree(node.left),right:this._createInternalSyntaxTree(node.right),operator:node.operator};break;case"MemberExpression":result={type:WI.ScriptSyntaxTree.NodeType.MemberExpression,object:this._createInternalSyntaxTree(node.object),property:this._createInternalSyntaxTree(node.property),computed:node.computed};break;case"MetaProperty":result={type:WI.ScriptSyntaxTree.NodeType.MetaProperty,meta:this._createInternalSyntaxTree(node.meta),property:this._createInternalSyntaxTree(node.property),};break;case"MethodDefinition":result={type:WI.ScriptSyntaxTree.NodeType.MethodDefinition,key:this._createInternalSyntaxTree(node.key),value:this._createInternalSyntaxTree(node.value),computed:node.computed,kind:node.kind,static:node.static};result.value.typeProfilingReturnDivot=node.range[0];break;case"NewExpression":result={type:WI.ScriptSyntaxTree.NodeType.NewExpression,callee:this._createInternalSyntaxTree(node.callee),arguments:node.arguments.map(this._createInternalSyntaxTree,this)};break;case"ObjectExpression":result={type:WI.ScriptSyntaxTree.NodeType.ObjectExpression,properties:node.properties.map(this._createInternalSyntaxTree,this)};break;case"ObjectPattern":result={type:WI.ScriptSyntaxTree.NodeType.ObjectPattern,properties:node.properties.map(this._createInternalSyntaxTree,this)};break;case"Program":result={type:WI.ScriptSyntaxTree.NodeType.Program,sourceType:node.sourceType,body:node.body.map(this._createInternalSyntaxTree,this)};break;case"Property":result={type:WI.ScriptSyntaxTree.NodeType.Property,key:this._createInternalSyntaxTree(node.key),value:this._createInternalSyntaxTree(node.value),kind:node.kind,method:node.method,computed:node.computed};if(result.kind==="get"||result.kind==="set"||result.method)
result.value.typeProfilingReturnDivot=node.range[0];break;case"RestElement":result={type:WI.ScriptSyntaxTree.NodeType.RestElement,argument:this._createInternalSyntaxTree(node.argument)};break;case"ReturnStatement":result={type:WI.ScriptSyntaxTree.NodeType.ReturnStatement,argument:this._createInternalSyntaxTree(node.argument)};break;case"SequenceExpression":result={type:WI.ScriptSyntaxTree.NodeType.SequenceExpression,expressions:node.expressions.map(this._createInternalSyntaxTree,this)};break;case"SpreadElement":result={type:WI.ScriptSyntaxTree.NodeType.SpreadElement,argument:this._createInternalSyntaxTree(node.argument),};break;case"Super":result={type:WI.ScriptSyntaxTree.NodeType.Super};break;case"SwitchStatement":result={type:WI.ScriptSyntaxTree.NodeType.SwitchStatement,discriminant:this._createInternalSyntaxTree(node.discriminant),cases:node.cases.map(this._createInternalSyntaxTree,this)};break;case"SwitchCase":result={type:WI.ScriptSyntaxTree.NodeType.SwitchCase,test:this._createInternalSyntaxTree(node.test),consequent:node.consequent.map(this._createInternalSyntaxTree,this)};break;case"TaggedTemplateExpression":result={type:WI.ScriptSyntaxTree.NodeType.TaggedTemplateExpression,tag:this._createInternalSyntaxTree(node.tag),quasi:this._createInternalSyntaxTree(node.quasi)};break;case"TemplateElement":result={type:WI.ScriptSyntaxTree.NodeType.TemplateElement,value:node.value,tail:node.tail};break;case"TemplateLiteral":result={type:WI.ScriptSyntaxTree.NodeType.TemplateLiteral,quasis:node.quasis.map(this._createInternalSyntaxTree,this),expressions:node.expressions.map(this._createInternalSyntaxTree,this)};break;case"ThisExpression":result={type:WI.ScriptSyntaxTree.NodeType.ThisExpression};break;case"ThrowStatement":result={type:WI.ScriptSyntaxTree.NodeType.ThrowStatement,argument:this._createInternalSyntaxTree(node.argument)};break;case"TryStatement":result={type:WI.ScriptSyntaxTree.NodeType.TryStatement,block:this._createInternalSyntaxTree(node.block),handler:this._createInternalSyntaxTree(node.handler),finalizer:this._createInternalSyntaxTree(node.finalizer)};break;case"UnaryExpression":result={type:WI.ScriptSyntaxTree.NodeType.UnaryExpression,operator:node.operator,argument:this._createInternalSyntaxTree(node.argument)};break;case"UpdateExpression":result={type:WI.ScriptSyntaxTree.NodeType.UpdateExpression,operator:node.operator,prefix:node.prefix,argument:this._createInternalSyntaxTree(node.argument)};break;case"VariableDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.VariableDeclaration,declarations:node.declarations.map(this._createInternalSyntaxTree,this),kind:node.kind};break;case"VariableDeclarator":result={type:WI.ScriptSyntaxTree.NodeType.VariableDeclarator,id:this._createInternalSyntaxTree(node.id),init:this._createInternalSyntaxTree(node.init)};break;case"WhileStatement":result={type:WI.ScriptSyntaxTree.NodeType.WhileStatement,test:this._createInternalSyntaxTree(node.test),body:this._createInternalSyntaxTree(node.body)};break;case"WithStatement":result={type:WI.ScriptSyntaxTree.NodeType.WithStatement,object:this._createInternalSyntaxTree(node.object),body:this._createInternalSyntaxTree(node.body)};break;case"YieldExpression":result={type:WI.ScriptSyntaxTree.NodeType.YieldExpression,argument:this._createInternalSyntaxTree(node.argument),delegate:node.delegate};break;case"ExportAllDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.ExportAllDeclaration,source:this._createInternalSyntaxTree(node.source),};break;case"ExportNamedDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.ExportNamedDeclaration,declaration:this._createInternalSyntaxTree(node.declaration),specifiers:node.specifiers.map(this._createInternalSyntaxTree,this),source:this._createInternalSyntaxTree(node.source),};break;case"ExportDefaultDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.ExportDefaultDeclaration,declaration:this._createInternalSyntaxTree(node.declaration),};break;case"ExportSpecifier":result={type:WI.ScriptSyntaxTree.NodeType.ExportSpecifier,local:this._createInternalSyntaxTree(node.local),exported:this._createInternalSyntaxTree(node.exported),};break;case"Import":result={type:WI.ScriptSyntaxTree.NodeType.Import,};break;case"ImportDeclaration":result={type:WI.ScriptSyntaxTree.NodeType.ImportDeclaration,specifiers:node.specifiers.map(this._createInternalSyntaxTree,this),source:this._createInternalSyntaxTree(node.source),};break;case"ImportDefaultSpecifier":result={type:WI.ScriptSyntaxTree.NodeType.ImportDefaultSpecifier,local:this._createInternalSyntaxTree(node.local),};break;case"ImportNamespaceSpecifier":result={type:WI.ScriptSyntaxTree.NodeType.ImportNamespaceSpecifier,local:this._createInternalSyntaxTree(node.local),};break;case"ImportSpecifier":result={type:WI.ScriptSyntaxTree.NodeType.ImportSpecifier,imported:this._createInternalSyntaxTree(node.imported),local:this._createInternalSyntaxTree(node.local),};break;default:console.error("Unsupported Syntax Tree Node: "+node.type,node);return null;}
let{start,end}=node.loc;result.startPosition=new WI.SourceCodePosition(start.line-1,start.column);result.endPosition=new WI.SourceCodePosition(end.line-1,end.column);result.range=node.range;result.attachments={};return result;}};WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor={NormalExpression:1,FunctionReturn:2};WI.ScriptSyntaxTree.NodeType={ArrayExpression:Symbol("array-expression"),ArrayPattern:Symbol("array-pattern"),ArrowFunctionExpression:Symbol("arrow-function-expression"),AssignmentExpression:Symbol("assignment-expression"),AssignmentPattern:Symbol("assignment-pattern"),AwaitExpression:Symbol("await-expression"),BinaryExpression:Symbol("binary-expression"),BlockStatement:Symbol("block-statement"),BreakStatement:Symbol("break-statement"),CallExpression:Symbol("call-expression"),CatchClause:Symbol("catch-clause"),ClassBody:Symbol("class-body"),ClassDeclaration:Symbol("class-declaration"),ClassExpression:Symbol("class-expression"),ConditionalExpression:Symbol("conditional-expression"),ContinueStatement:Symbol("continue-statement"),DebuggerStatement:Symbol("debugger-statement"),DoWhileStatement:Symbol("do-while-statement"),EmptyStatement:Symbol("empty-statement"),ExportAllDeclaration:Symbol("export-all-declaration"),ExportDefaultDeclaration:Symbol("export-default-declaration"),ExportNamedDeclaration:Symbol("export-named-declaration"),ExportSpecifier:Symbol("export-specifier"),ExpressionStatement:Symbol("expression-statement"),ForInStatement:Symbol("for-in-statement"),ForOfStatement:Symbol("for-of-statement"),ForStatement:Symbol("for-statement"),FunctionDeclaration:Symbol("function-declaration"),FunctionExpression:Symbol("function-expression"),Identifier:Symbol("identifier"),IfStatement:Symbol("if-statement"),Import:Symbol("import"),ImportDeclaration:Symbol("import-declaration"),ImportDefaultSpecifier:Symbol("import-default-specifier"),ImportNamespaceSpecifier:Symbol("import-namespace-specifier"),ImportSpecifier:Symbol("import-specifier"),LabeledStatement:Symbol("labeled-statement"),Literal:Symbol("literal"),LogicalExpression:Symbol("logical-expression"),MemberExpression:Symbol("member-expression"),MetaProperty:Symbol("meta-property"),MethodDefinition:Symbol("method-definition"),NewExpression:Symbol("new-expression"),ObjectExpression:Symbol("object-expression"),ObjectPattern:Symbol("object-pattern"),Program:Symbol("program"),Property:Symbol("property"),RestElement:Symbol("rest-element"),ReturnStatement:Symbol("return-statement"),SequenceExpression:Symbol("sequence-expression"),SpreadElement:Symbol("spread-element"),Super:Symbol("super"),SwitchCase:Symbol("switch-case"),SwitchStatement:Symbol("switch-statement"),TaggedTemplateExpression:Symbol("tagged-template-expression"),TemplateElement:Symbol("template-element"),TemplateLiteral:Symbol("template-literal"),ThisExpression:Symbol("this-expression"),ThrowStatement:Symbol("throw-statement"),TryStatement:Symbol("try-statement"),UnaryExpression:Symbol("unary-expression"),UpdateExpression:Symbol("update-expression"),VariableDeclaration:Symbol("variable-declaration"),VariableDeclarator:Symbol("variable-declarator"),WhileStatement:Symbol("while-statement"),WithStatement:Symbol("with-statement"),YieldExpression:Symbol("yield-expression"),};WI.ScriptTimelineRecord=class ScriptTimelineRecord extends WI.TimelineRecord
{constructor(eventType,startTime,endTime,callFrames,sourceCodeLocation,details,profilePayload,extraDetails)
{super(WI.TimelineRecord.Type.Script,startTime,endTime,callFrames,sourceCodeLocation);if(eventType in WI.ScriptTimelineRecord.EventType)
eventType=WI.ScriptTimelineRecord.EventType[eventType];this._eventType=eventType;this._details=details||"";this._profilePayload=profilePayload||null;this._profile=null;this._extraDetails=extraDetails||null;this._callCountOrSamples=0;} 
static async fromJSON(json)
{let{eventType,startTime,endTime,callFrames,sourceCodeLocation,details,profilePayload,extraDetails}=json;if(typeof details==="object"&&details.__type==="GarbageCollection")
details=WI.GarbageCollection.fromJSON(details);return new WI.ScriptTimelineRecord(eventType,startTime,endTime,callFrames,sourceCodeLocation,details,profilePayload,extraDetails);}
toJSON()
{

 return{type:this.type,eventType:this._eventType,startTime:this.startTime,endTime:this.endTime,details:this._details,extraDetails:this._extraDetails,};} 
get eventType(){return this._eventType;}
get details(){return this._details;}
get extraDetails(){return this._extraDetails;}
get callCountOrSamples(){return this._callCountOrSamples;}
get profile()
{this._initializeProfileFromPayload();return this._profile;}
isGarbageCollection()
{return this._eventType===WI.ScriptTimelineRecord.EventType.GarbageCollected;}
saveIdentityToCookie(cookie)
{super.saveIdentityToCookie(cookie);cookie[WI.ScriptTimelineRecord.EventTypeCookieKey]=this._eventType;cookie[WI.ScriptTimelineRecord.DetailsCookieKey]=this._details;}
get profilePayload()
{return this._profilePayload;}
set profilePayload(payload)
{this._profilePayload=payload;} 
_initializeProfileFromPayload(payload)
{if(this._profile||!this._profilePayload)
return;var payload=this._profilePayload;this._profilePayload=undefined;function profileNodeFromPayload(nodePayload)
{if(nodePayload.url){let sourceCode=WI.networkManager.resourcesForURL(nodePayload.url).firstValue;if(!sourceCode)
sourceCode=WI.debuggerManager.scriptsForURL(nodePayload.url,WI.assumingMainTarget())[0];var lineNumber=nodePayload.lineNumber-1;var sourceCodeLocation=sourceCode?sourceCode.createLazySourceCodeLocation(lineNumber,nodePayload.columnNumber):null;}
var isProgramCode=nodePayload.functionName==="(program)";var isAnonymousFunction=nodePayload.functionName==="(anonymous function)";var type=isProgramCode?WI.ProfileNode.Type.Program:WI.ProfileNode.Type.Function;var functionName=!isProgramCode&&!isAnonymousFunction&&nodePayload.functionName!=="(unknown)"?nodePayload.functionName:null;return new WI.ProfileNode(nodePayload.id,type,functionName,sourceCodeLocation,nodePayload.callInfo,nodePayload.children);}
function profileNodeCallFromPayload(nodeCallPayload)
{var startTime=WI.timelineManager.computeElapsedTime(nodeCallPayload.startTime);return new WI.ProfileNodeCall(startTime,nodeCallPayload.totalTime);}
var rootNodes=payload.rootNodes;var stack=[{parent:{children:rootNodes},index:0,root:true}];while(stack.length){var entry=stack.lastValue;if(entry.index<entry.parent.children.length){var childNodePayload=entry.parent.children[entry.index];if(childNodePayload.children&&childNodePayload.children.length)
stack.push({parent:childNodePayload,index:0});++entry.index;}else{if(!entry.root)
entry.parent.children=entry.parent.children.map(profileNodeFromPayload);else
rootNodes=rootNodes.map(profileNodeFromPayload);stack.pop();}}
for(let rootNode of rootNodes)
this._callCountOrSamples+=rootNode.callInfo.callCount;this._profile=new WI.Profile(rootNodes);}};WI.ScriptTimelineRecord.EventType={ScriptEvaluated:"script-evaluated",APIScriptEvaluated:"api-script-evaluated",MicrotaskDispatched:"microtask-dispatched",EventDispatched:"event-dispatched",ProbeSampleRecorded:"probe-sample-recorded",TimerFired:"timer-fired",TimerInstalled:"timer-installed",TimerRemoved:"timer-removed",AnimationFrameFired:"animation-frame-fired",AnimationFrameRequested:"animation-frame-requested",AnimationFrameCanceled:"animation-frame-canceled",ObserverCallback:"observer-callback",ConsoleProfileRecorded:"console-profile-recorded",GarbageCollected:"garbage-collected",};WI.ScriptTimelineRecord.EventType.displayName=function(eventType,details,includeDetailsInMainTitle)
{if(details&&!WI.ScriptTimelineRecord._eventDisplayNames){
var nameMap=new Map;nameMap.set("DOMActivate","DOM Activate");nameMap.set("DOMCharacterDataModified","DOM Character Data Modified");nameMap.set("DOMContentLoaded","DOM Content Loaded");nameMap.set("DOMFocusIn","DOM Focus In");nameMap.set("DOMFocusOut","DOM Focus Out");nameMap.set("DOMNodeInserted","DOM Node Inserted");nameMap.set("DOMNodeInsertedIntoDocument","DOM Node Inserted Into Document");nameMap.set("DOMNodeRemoved","DOM Node Removed");nameMap.set("DOMNodeRemovedFromDocument","DOM Node Removed From Document");nameMap.set("DOMSubtreeModified","DOM Sub-Tree Modified");nameMap.set("addsourcebuffer","Add Source Buffer");nameMap.set("addstream","Add Stream");nameMap.set("addtrack","Add Track");nameMap.set("animationend","Animation End");nameMap.set("animationiteration","Animation Iteration");nameMap.set("animationstart","Animation Start");nameMap.set("audioend","Audio End");nameMap.set("audioprocess","Audio Process");nameMap.set("audiostart","Audio Start");nameMap.set("beforecopy","Before Copy");nameMap.set("beforecut","Before Cut");nameMap.set("beforeload","Before Load");nameMap.set("beforepaste","Before Paste");nameMap.set("beforeunload","Before Unload");nameMap.set("canplay","Can Play");nameMap.set("canplaythrough","Can Play Through");nameMap.set("chargingchange","Charging Change");nameMap.set("chargingtimechange","Charging Time Change");nameMap.set("compositionend","Composition End");nameMap.set("compositionstart","Composition Start");nameMap.set("compositionupdate","Composition Update");nameMap.set("contextmenu","Context Menu");nameMap.set("cuechange","Cue Change");nameMap.set("datachannel","Data Channel");nameMap.set("dblclick","Double Click");nameMap.set("devicemotion","Device Motion");nameMap.set("deviceorientation","Device Orientation");nameMap.set("dischargingtimechange","Discharging Time Change");nameMap.set("dragend","Drag End");nameMap.set("dragenter","Drag Enter");nameMap.set("dragleave","Drag Leave");nameMap.set("dragover","Drag Over");nameMap.set("dragstart","Drag Start");nameMap.set("durationchange","Duration Change");nameMap.set("focusin","Focus In");nameMap.set("focusout","Focus Out");nameMap.set("formdata","Form submission or invocation of FormData()");nameMap.set("gesturechange","Gesture Change");nameMap.set("gestureend","Gesture End");nameMap.set("gesturescrollend","Gesture Scroll End");nameMap.set("gesturescrollstart","Gesture Scroll Start");nameMap.set("gesturescrollupdate","Gesture Scroll Update");nameMap.set("gesturestart","Gesture Start");nameMap.set("gesturetap","Gesture Tap");nameMap.set("gesturetapdown","Gesture Tap Down");nameMap.set("hashchange","Hash Change");nameMap.set("icecandidate","ICE Candidate");nameMap.set("iceconnectionstatechange","ICE Connection State Change");nameMap.set("keydown","Key Down");nameMap.set("keypress","Key Press");nameMap.set("keyup","Key Up");nameMap.set("levelchange","Level Change");nameMap.set("loadeddata","Loaded Data");nameMap.set("loadedmetadata","Loaded Metadata");nameMap.set("loadend","Load End");nameMap.set("loadingdone","Loading Done");nameMap.set("loadstart","Load Start");nameMap.set("mousedown","Mouse Down");nameMap.set("mouseenter","Mouse Enter");nameMap.set("mouseleave","Mouse Leave");nameMap.set("mousemove","Mouse Move");nameMap.set("mouseout","Mouse Out");nameMap.set("mouseover","Mouse Over");nameMap.set("mouseup","Mouse Up");nameMap.set("mousewheel","Mouse Wheel");nameMap.set("negotiationneeded","Negotiation Needed");nameMap.set("nomatch","No Match");nameMap.set("noupdate","No Update");nameMap.set("orientationchange","Orientation Change");nameMap.set("overflowchanged","Overflow Changed");nameMap.set("pagehide","Page Hide");nameMap.set("pageshow","Page Show");nameMap.set("popstate","Pop State");nameMap.set("ratechange","Rate Change");nameMap.set("readystatechange","Ready State Change");nameMap.set("removesourcebuffer","Remove Source Buffer");nameMap.set("removestream","Remove Stream");nameMap.set("removetrack","Remove Track");nameMap.set("resize","Resize");nameMap.set("securitypolicyviolation","Security Policy Violation");nameMap.set("selectionchange","Selection Change");nameMap.set("selectstart","Select Start");nameMap.set("signalingstatechange","Signaling State Change");nameMap.set("soundend","Sound End");nameMap.set("soundstart","Sound Start");nameMap.set("sourceclose","Source Close");nameMap.set("sourceended","Source Ended");nameMap.set("sourceopen","Source Open");nameMap.set("speechend","Speech End");nameMap.set("speechstart","Speech Start");nameMap.set("textInput","Text Input");nameMap.set("timeupdate","Time Update");nameMap.set("tonechange","Tone Change");nameMap.set("touchcancel","Touch Cancel");nameMap.set("touchend","Touch End");nameMap.set("touchmove","Touch Move");nameMap.set("touchstart","Touch Start");nameMap.set("transitionend","Transition End");nameMap.set("updateend","Update End");nameMap.set("updateready","Update Ready");nameMap.set("updatestart","Update Start");nameMap.set("upgradeneeded","Upgrade Needed");nameMap.set("versionchange","Version Change");nameMap.set("visibilitychange","Visibility Change");nameMap.set("volumechange","Volume Change");nameMap.set("webglcontextcreationerror","WebGL Context Creation Error");nameMap.set("webglcontextlost","WebGL Context Lost");nameMap.set("webglcontextrestored","WebGL Context Restored");nameMap.set("webkitAnimationEnd","Animation End");nameMap.set("webkitAnimationIteration","Animation Iteration");nameMap.set("webkitAnimationStart","Animation Start");nameMap.set("webkitBeforeTextInserted","Before Text Inserted");nameMap.set("webkitEditableContentChanged","Editable Content Changed");nameMap.set("webkitTransitionEnd","Transition End");nameMap.set("webkitaddsourcebuffer","Add Source Buffer");nameMap.set("webkitbeginfullscreen","Begin Full-Screen");nameMap.set("webkitcurrentplaybacktargetiswirelesschanged","Current Playback Target Is Wireless Changed");nameMap.set("webkitendfullscreen","End Full-Screen");nameMap.set("webkitfullscreenchange","Full-Screen Change");nameMap.set("webkitfullscreenerror","Full-Screen Error");nameMap.set("webkitkeyadded","Key Added");nameMap.set("webkitkeyerror","Key Error");nameMap.set("webkitkeymessage","Key Message");nameMap.set("webkitneedkey","Need Key");nameMap.set("webkitnetworkinfochange","Network Info Change");nameMap.set("webkitplaybacktargetavailabilitychanged","Playback Target Availability Changed");nameMap.set("webkitpointerlockchange","Pointer Lock Change");nameMap.set("webkitpointerlockerror","Pointer Lock Error");nameMap.set("webkitregionoversetchange","Region Overset Change");nameMap.set("webkitremovesourcebuffer","Remove Source Buffer");nameMap.set("webkitresourcetimingbufferfull","Resource Timing Buffer Full");nameMap.set("webkitsourceclose","Source Close");nameMap.set("webkitsourceended","Source Ended");nameMap.set("webkitsourceopen","Source Open");nameMap.set("webkitspeechchange","Speech Change");nameMap.set("writeend","Write End");nameMap.set("writestart","Write Start");WI.ScriptTimelineRecord._eventDisplayNames=nameMap;}
switch(eventType){case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:return WI.UIString("Script Evaluated");case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:return WI.UIString("Microtask Dispatched");case WI.ScriptTimelineRecord.EventType.EventDispatched:if(details&&(details instanceof String||typeof details==="string")){var eventDisplayName=WI.ScriptTimelineRecord._eventDisplayNames.get(details)||details.capitalize();return WI.UIString("%s Event Dispatched").format(eventDisplayName);}
return WI.UIString("Event Dispatched");case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:return WI.UIString("Probe Sample Recorded");case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:if(details&&(details instanceof String||typeof details==="string"))
return WI.UIString("\u201C%s\u201D Profile Recorded").format(details);return WI.UIString("Console Profile Recorded");case WI.ScriptTimelineRecord.EventType.GarbageCollected:if(details&&(details instanceof WI.GarbageCollection)&&includeDetailsInMainTitle){switch(details.type){case WI.GarbageCollection.Type.Partial:return WI.UIString("Partial Garbage Collection");case WI.GarbageCollection.Type.Full:return WI.UIString("Full Garbage Collection");}}
return WI.UIString("Garbage Collection");case WI.ScriptTimelineRecord.EventType.TimerFired:if(details&&includeDetailsInMainTitle)
return WI.UIString("Timer %d Fired").format(details);return WI.UIString("Timer Fired");case WI.ScriptTimelineRecord.EventType.TimerInstalled:if(details&&includeDetailsInMainTitle)
return WI.UIString("Timer %d Installed").format(details.timerId);return WI.UIString("Timer Installed");case WI.ScriptTimelineRecord.EventType.TimerRemoved:if(details&&includeDetailsInMainTitle)
return WI.UIString("Timer %d Removed").format(details);return WI.UIString("Timer Removed");case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:if(details&&includeDetailsInMainTitle)
return WI.UIString("Animation Frame %d Fired").format(details);return WI.UIString("Animation Frame Fired");case WI.ScriptTimelineRecord.EventType.ObserverCallback:if(details&&(details instanceof String||typeof details==="string"))
return WI.UIString("%s Callback").format(details);return WI.UIString("Observer Callback");case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:if(details&&includeDetailsInMainTitle)
return WI.UIString("Animation Frame %d Requested").format(details);return WI.UIString("Animation Frame Requested");case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:if(details&&includeDetailsInMainTitle)
return WI.UIString("Animation Frame %d Canceled").format(details);return WI.UIString("Animation Frame Canceled");}};WI.ScriptTimelineRecord.TypeIdentifier="script-timeline-record";WI.ScriptTimelineRecord.EventTypeCookieKey="script-timeline-record-event-type";WI.ScriptTimelineRecord.DetailsCookieKey="script-timeline-record-details";WI.ServerTimingEntry=class ServerTimingEntry
{constructor(name)
{this._name=name;this._duration=undefined;this._description=undefined;} 
static parseHeaders(valueString="")
{ function trimLeadingWhiteSpace(){valueString=valueString.trimStart();}
function consumeDelimiter(char){trimLeadingWhiteSpace();if(valueString.charAt(0)!==char)
return false;valueString=valueString.substring(1);return true;}
function consumeToken(){ let 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(){
valueString=valueString.substring(1);let unescapedValueString="";for(let i=0;i<valueString.length;++i){let char=valueString.charAt(i);switch(char){case"\\":++i;if(i<valueString.length){unescapedValueString+=valueString.charAt(i);}
break;case"\"":valueString=valueString.substring(i+1);return unescapedValueString;default:unescapedValueString+=char;break;}}
valueString="";return null;}
function consumeExtraneous(){let result=/([,;].*)/.exec(valueString);if(result)
valueString=result[1];}
function getParserForParameter(paramName){switch(paramName){case"dur":return function(paramValue,entry){if(paramValue!==null){let duration=parseFloat(paramValue);if(!isNaN(duration)){entry.duration=duration;return;}}
entry.duration=0;};case"desc":return function(paramValue,entry){entry.description=paramValue||"";};default:return null;}}
let entries=[];let name;while((name=consumeToken())!==null){let entry=new WI.ServerTimingEntry(name);while(consumeDelimiter(";")){let paramName;if((paramName=consumeToken())===null)
continue;paramName=paramName.toLowerCase();let parseParameter=getParserForParameter(paramName);let paramValue=null;if(consumeDelimiter("=")){paramValue=consumeTokenOrQuotedString();consumeExtraneous();}
if(parseParameter)
parseParameter(paramValue,entry);else
console.warn("Unknown Server-Timing parameter:",paramName,paramValue);}
entries.push(entry);if(!consumeDelimiter(","))
break;}
return entries;} 
get name(){return this._name;}
get duration(){return this._duration;}
get description(){return this._description;}
set duration(duration)
{if(this._duration!==undefined){console.warn("Ignoring redundant duration.");return;}
this._duration=duration;}
set description(description)
{if(this._description!==undefined){console.warn("Ignoring redundant description.");return;}
this._description=description;}};WI.ShaderProgram=class ShaderProgram extends WI.Object
{constructor(identifier,programType,canvas,{sharesVertexFragmentShader}={})
{super();this._identifier=identifier;this._programType=programType;this._canvas=canvas;this._sharesVertexFragmentShader=!!sharesVertexFragmentShader;this._disabled=false;} 
static contextTypeSupportsProgramType(contextType,programType)
{switch(contextType){case WI.Canvas.ContextType.WebGL:case WI.Canvas.ContextType.WebGL2:return programType===ShaderProgram.ProgramType.Render;case WI.Canvas.ContextType.WebGPU:return programType===ShaderProgram.ProgramType.Compute||programType===ShaderProgram.ProgramType.Render;}
return false;}
static programTypeSupportsShaderType(programType,shaderType)
{switch(programType){case ShaderProgram.ProgramType.Compute:return shaderType===ShaderProgram.ShaderType.Compute;case ShaderProgram.ProgramType.Render:return shaderType===ShaderProgram.ShaderType.Fragment||shaderType===ShaderProgram.ShaderType.Vertex;}
return false;} 
get identifier(){return this._identifier;}
get programType(){return this._programType;}
get canvas(){return this._canvas;}
get sharesVertexFragmentShader(){return this._sharesVertexFragmentShader;}
get displayName()
{let format=null;switch(this._canvas.contextType){case WI.Canvas.ContextType.WebGL:case WI.Canvas.ContextType.WebGL2:format=WI.UIString("Program %d");break;case WI.Canvas.ContextType.WebGPU:switch(this._programType){case ShaderProgram.ProgramType.Compute:format=WI.UIString("Compute Pipeline %d");break;case ShaderProgram.ProgramType.Render:format=WI.UIString("Render Pipeline %d");break;}
break;}
if(!this._uniqueDisplayNumber)
this._uniqueDisplayNumber=this._canvas.nextShaderProgramDisplayNumberForProgramType(this._programType);return format.format(this._uniqueDisplayNumber);}
get disabled()
{return this._disabled;}
set disabled(disabled)
{if(this._canvas.contextType===WI.Canvas.ContextType.WebGPU)
return;if(this._disabled===disabled)
return;this._disabled=disabled;let target=WI.assumingMainTarget();target.CanvasAgent.setShaderProgramDisabled(this._identifier,disabled);this.dispatchEventToListeners(ShaderProgram.Event.DisabledChanged);}
requestShaderSource(shaderType,callback)
{let target=WI.assumingMainTarget();target.CanvasAgent.requestShaderSource(this._identifier,shaderType,(error,source)=>{if(error){WI.reportInternalError(error);callback(null);return;}
callback(source);});}
updateShader(shaderType,source)
{let target=WI.assumingMainTarget();target.CanvasAgent.updateShader(this._identifier,shaderType,source);}
showHighlight()
{let target=WI.assumingMainTarget();target.CanvasAgent.setShaderProgramHighlighted(this._identifier,true);}
hideHighlight()
{let target=WI.assumingMainTarget();target.CanvasAgent.setShaderProgramHighlighted(this._identifier,false);}};WI.ShaderProgram.ProgramType={Compute:"compute",Render:"render",};WI.ShaderProgram.ShaderType={Compute:"compute",Fragment:"fragment",Vertex:"vertex",};WI.ShaderProgram.Event={DisabledChanged:"shader-program-disabled-changed",};WI.SourceCodePosition=class SourceCodePosition
{constructor(lineNumber,columNumber)
{this._lineNumber=lineNumber||0;this._columnNumber=columNumber||0;} 
get lineNumber(){return this._lineNumber;}
get columnNumber(){return this._columnNumber;}
offsetColumn(delta)
{return new WI.SourceCodePosition(this._lineNumber,this._columnNumber+delta);}
equals(position)
{return this._lineNumber===position.lineNumber&&this._columnNumber===position.columnNumber;}
isBefore(position)
{if(this._lineNumber<position.lineNumber)
return true;if(this._lineNumber===position.lineNumber&&this._columnNumber<position.columnNumber)
return true;return false;}
isAfter(position)
{if(this._lineNumber>position.lineNumber)
return true;if(this._lineNumber===position.lineNumber&&this._columnNumber>position.columnNumber)
return true;return false;}
isWithin(startPosition,endPosition)
{if(this.equals(startPosition)||this.equals(endPosition))
return true;if(this.isAfter(startPosition)&&this.isBefore(endPosition))
return true;return false;}
toCodeMirror()
{return{line:this._lineNumber,ch:this._columnNumber};}};WI.SourceCodeRevision=class SourceCodeRevision extends WI.Revision
{constructor(sourceCode,content,base64Encoded,mimeType)
{super();this._sourceCode=sourceCode;this._content=content||"";this._base64Encoded=!!base64Encoded;this._mimeType=mimeType;this._blobContent=null;} 
get sourceCode(){return this._sourceCode;}
get content(){return this._content;}
get base64Encoded(){return this._base64Encoded;}
get mimeType(){return this._mimeType;}
get blobContent()
{if(!this._blobContent&&this._content)
this._blobContent=WI.BlobUtilities.blobForContent(this._content,this._base64Encoded,this._mimeType);return this._blobContent;}
updateRevisionContent(content,{base64Encoded,mimeType,blobContent}={})
{this._content=content||"";if(base64Encoded!==undefined){this._base64Encoded=!!base64Encoded;}
if(mimeType!==undefined){this._mimeType=mimeType;}
this._blobContent=blobContent!==undefined?blobContent:null;this._sourceCode.revisionContentDidChange(this);}
apply()
{this._sourceCode.currentRevision=this;}
revert()
{this._sourceCode.currentRevision=this._sourceCode.originalRevision;}
copy()
{return new WI.SourceCodeRevision(this._sourceCode,this._content,this._base64Encoded,this._mimeType);}};WI.SourceCodeSearchMatchObject=class SourceCodeSearchMatchObject
{constructor(sourceCode,lineText,searchTerm,textRange)
{this._sourceCode=sourceCode;this._lineText=lineText;this._searchTerm=searchTerm;this._sourceCodeTextRange=sourceCode.createSourceCodeTextRange(textRange);} 
get sourceCode(){return this._sourceCode;}
get title(){return this._lineText;}
get searchTerm(){return this._searchTerm;}
get sourceCodeTextRange(){return this._sourceCodeTextRange;}
get className()
{return"source-code-match";}
saveIdentityToCookie(cookie)
{if(this._sourceCode.url)
cookie[WI.SourceCodeSearchMatchObject.URLCookieKey]=this._sourceCode.url.hash;var textRange=this._sourceCodeTextRange.textRange;cookie[WI.SourceCodeSearchMatchObject.TextRangeKey]=[textRange.startLine,textRange.startColumn,textRange.endLine,textRange.endColumn].join();}};WI.SourceCodeSearchMatchObject.TypeIdentifier="source-code-search-match-object";WI.SourceCodeSearchMatchObject.URLCookieKey="source-code-url";WI.SourceCodeSearchMatchObject.TextRangeKey="text-range";WI.SourceCodeTextRange=class SourceCodeTextRange extends WI.Object
{constructor(sourceCode){super();this._sourceCode=sourceCode;if(arguments.length===2){var textRange=arguments[1];this._startLocation=sourceCode.createSourceCodeLocation(textRange.startLine,textRange.startColumn);this._endLocation=sourceCode.createSourceCodeLocation(textRange.endLine,textRange.endColumn);}else{this._startLocation=arguments[1];this._endLocation=arguments[2];}
this._startLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._sourceCodeLocationChanged,this);this._endLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._sourceCodeLocationChanged,this);} 
get sourceCode()
{return this._sourceCode;}
get textRange()
{var startLine=this._startLocation.lineNumber;var startColumn=this._startLocation.columnNumber;var endLine=this._endLocation.lineNumber;var endColumn=this._endLocation.columnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);}
get formattedTextRange()
{var startLine=this._startLocation.formattedLineNumber;var startColumn=this._startLocation.formattedColumnNumber;var endLine=this._endLocation.formattedLineNumber;var endColumn=this._endLocation.formattedColumnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);}

get displaySourceCode()
{if(!this._startAndEndLocationsInSameMappedResource())
return this._sourceCode;return this._startLocation.displaySourceCode;}
get displayTextRange()
{if(!this._startAndEndLocationsInSameMappedResource())
return this.formattedTextRange;var startLine=this._startLocation.displayLineNumber;var startColumn=this._startLocation.displayColumnNumber;var endLine=this._endLocation.displayLineNumber;var endColumn=this._endLocation.displayColumnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);}
get synthesizedTextValue()
{return this._sourceCode.url+":"+(this._startLocation.lineNumber+1);} 
_startAndEndLocationsInSameMappedResource()
{return this._startLocation.hasMappedLocation()&&this._endLocation.hasMappedLocation()&&this._startLocation.displaySourceCode===this._endLocation.displaySourceCode;}
_sourceCodeLocationChanged(event)
{this.dispatchEventToListeners(WI.SourceCodeLocation.Event.RangeChanged);}};WI.SourceCodeTextRange.Event={RangeChanged:"source-code-text-range-range-changed"};WI.SourceCodeTimeline=class SourceCodeTimeline extends WI.Timeline
{constructor(sourceCode,sourceCodeLocation,recordType,recordEventType)
{super();this._sourceCode=sourceCode;this._sourceCodeLocation=sourceCodeLocation||null;this._recordType=recordType;this._recordEventType=recordEventType||null;} 
get sourceCode(){return this._sourceCode;}
get sourceCodeLocation(){return this._sourceCodeLocation;}
get recordType(){return this._recordType;}
get recordEventType(){return this._recordEventType;}
saveIdentityToCookie(cookie)
{cookie[WI.SourceCodeTimeline.SourceCodeURLCookieKey]=this._sourceCode.url?this._sourceCode.url.hash:null;cookie[WI.SourceCodeTimeline.SourceCodeLocationLineCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:null;cookie[WI.SourceCodeTimeline.SourceCodeLocationColumnCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:null;cookie[WI.SourceCodeTimeline.RecordTypeCookieKey]=this._recordType||null;cookie[WI.SourceCodeTimeline.RecordEventTypeCookieKey]=this._recordEventType||null;}};WI.SourceCodeTimeline.TypeIdentifier="source-code-timeline";WI.SourceCodeTimeline.SourceCodeURLCookieKey="source-code-timeline-source-code-url";WI.SourceCodeTimeline.SourceCodeLocationLineCookieKey="source-code-timeline-source-code-location-line";WI.SourceCodeTimeline.SourceCodeLocationColumnCookieKey="source-code-timeline-source-code-location-column";WI.SourceCodeTimeline.SourceCodeURLCookieKey="source-code-timeline-source-code-url";WI.SourceCodeTimeline.RecordTypeCookieKey="source-code-timeline-record-type";WI.SourceCodeTimeline.RecordEventTypeCookieKey="source-code-timeline-record-event-type";WI.SourceMap=class SourceMap
{constructor(sourceMappingURL,payload,originalSourceCode)
{if(!WI.SourceMap._base64Map){var base64Digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";WI.SourceMap._base64Map={};for(var i=0;i<base64Digits.length;++i)
WI.SourceMap._base64Map[base64Digits.charAt(i)]=i;}
this._originalSourceCode=originalSourceCode||null;this._sourceMapResources={};this._sourceMapResourcesList=[];this._sourceMappingURL=sourceMappingURL;this._reverseMappingsBySourceURL={};this._mappings=[];this._sources={};this._sourceRoot=null;this._sourceContentByURL={};this._parseMappingPayload(payload);} 
get originalSourceCode()
{return this._originalSourceCode;}
get sourceMappingBasePathURLComponents()
{if(this._sourceMappingURLBasePathComponents)
return this._sourceMappingURLBasePathComponents;if(this._sourceRoot){var baseURLPath=absoluteURL(this._sourceRoot,this._sourceMappingURL);if(baseURLPath){var urlComponents=parseURL(baseURLPath);if(!/\/$/.test(urlComponents.path))
urlComponents.path+="/";this._sourceMappingURLBasePathComponents=urlComponents;return this._sourceMappingURLBasePathComponents;}}
var urlComponents=parseURL(this._sourceMappingURL);if(!urlComponents.path)
urlComponents.path=this._sourceMappingURL||"";urlComponents.path=urlComponents.path.substr(0,urlComponents.path.lastIndexOf(urlComponents.lastPathComponent));urlComponents.lastPathComponent=null;this._sourceMappingURLBasePathComponents=urlComponents;return this._sourceMappingURLBasePathComponents;}
get resources()
{return this._sourceMapResourcesList;}
addResource(resource)
{this._sourceMapResources[resource.url]=resource;this._sourceMapResourcesList.push(resource);}
resourceForURL(url)
{return this._sourceMapResources[url];}
sources()
{return Object.keys(this._sources);}
sourceContent(sourceURL)
{return this._sourceContentByURL[sourceURL];}
_parseMappingPayload(mappingPayload)
{if(mappingPayload.sections)
this._parseSections(mappingPayload.sections);else
this._parseMap(mappingPayload,0,0);}
_parseSections(sections)
{for(var i=0;i<sections.length;++i){var section=sections[i];this._parseMap(section.map,section.offset.line,section.offset.column);}}
findEntry(lineNumber,columnNumber)
{var first=0;var count=this._mappings.length;while(count>1){var step=count>>1;var middle=first+step;var mapping=this._mappings[middle];if(lineNumber<mapping[0]||(lineNumber===mapping[0]&&columnNumber<mapping[1]))
count=step;else{first=middle;count-=step;}}
var entry=this._mappings[first];if(!first&&entry&&(lineNumber<entry[0]||(lineNumber===entry[0]&&columnNumber<entry[1])))
return null;return entry;}
findEntryReversed(sourceURL,lineNumber)
{var mappings=this._reverseMappingsBySourceURL[sourceURL];for(;lineNumber<mappings.length;++lineNumber){var mapping=mappings[lineNumber];if(mapping)
return mapping;}
return this._mappings[0];}
_parseMap(map,lineNumber,columnNumber)
{var sourceIndex=0;var sourceLineNumber=0;var sourceColumnNumber=0;var nameIndex=0;var sources=[];var originalToCanonicalURLMap={};for(var i=0;i<map.sources.length;++i){var originalSourceURL=map.sources[i];var href=originalSourceURL;if(map.sourceRoot&&href.charAt(0)!=="/")
href=map.sourceRoot.replace(/\/+$/,"")+"/"+href;var url=absoluteURL(href,this._sourceMappingURL)||href;originalToCanonicalURLMap[originalSourceURL]=url;sources.push(url);this._sources[url]=true;if(map.sourcesContent&&map.sourcesContent[i])
this._sourceContentByURL[url]=map.sourcesContent[i];}
this._sourceRoot=map.sourceRoot||null;var stringCharIterator=new WI.SourceMap.StringCharIterator(map.mappings);var 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(this._isSeparator(stringCharIterator.peek())){this._mappings.push([lineNumber,columnNumber]);continue;}
var sourceIndexDelta=this._decodeVLQ(stringCharIterator);if(sourceIndexDelta){sourceIndex+=sourceIndexDelta;sourceURL=sources[sourceIndex];}
sourceLineNumber+=this._decodeVLQ(stringCharIterator);sourceColumnNumber+=this._decodeVLQ(stringCharIterator);if(!this._isSeparator(stringCharIterator.peek()))
nameIndex+=this._decodeVLQ(stringCharIterator);this._mappings.push([lineNumber,columnNumber,sourceURL,sourceLineNumber,sourceColumnNumber]);}
for(var i=0;i<this._mappings.length;++i){var mapping=this._mappings[i];var url=mapping[2];if(!url)
continue;if(!this._reverseMappingsBySourceURL[url])
this._reverseMappingsBySourceURL[url]=[];var reverseMappings=this._reverseMappingsBySourceURL[url];var sourceLine=mapping[3];if(!reverseMappings[sourceLine])
reverseMappings[sourceLine]=[mapping[0],mapping[1]];}}
_isSeparator(char)
{return char===","||char===";";}
_decodeVLQ(stringCharIterator)
{var result=0;var shift=0;do{var digit=WI.SourceMap._base64Map[stringCharIterator.next()];result+=(digit&WI.SourceMap.VLQ_BASE_MASK)<<shift;shift+=WI.SourceMap.VLQ_BASE_SHIFT;}while(digit&WI.SourceMap.VLQ_CONTINUATION_MASK);var negative=result&1;result>>=1;return negative?-result:result;}};WI.SourceMap.VLQ_BASE_SHIFT=5;WI.SourceMap.VLQ_BASE_MASK=(1<<5)-1;WI.SourceMap.VLQ_CONTINUATION_MASK=1<<5;WI.SourceMap.StringCharIterator=class StringCharIterator
{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;}};WI.StackTrace=class StackTrace
{constructor(callFrames,topCallFrameIsBoundary,truncated,parentStackTrace)
{this._callFrames=callFrames;this._topCallFrameIsBoundary=topCallFrameIsBoundary||false;this._truncated=truncated||false;this._parentStackTrace=parentStackTrace||null;} 
static fromPayload(target,payload)
{let result=null;let previousStackTrace=null;while(payload){let callFrames=payload.callFrames.map((x)=>WI.CallFrame.fromPayload(target,x));let stackTrace=new WI.StackTrace(callFrames,payload.topCallFrameIsBoundary,payload.truncated);if(!result)
result=stackTrace;if(previousStackTrace)
previousStackTrace._parentStackTrace=stackTrace;previousStackTrace=stackTrace;payload=payload.parentStackTrace;}
return result;}
static fromString(target,stack)
{let callFrames=WI.StackTrace._parseStackTrace(stack);return WI.StackTrace.fromPayload(target,{callFrames});}
static isLikelyStackTrace(stack)
{const smallestPossibleStackTraceLength="http://a.bc/:9:1".length;if(stack.length<smallestPossibleStackTraceLength.length*2)
return false;const approximateStackLengthOf50Items=5000;if(stack.length>approximateStackLengthOf50Items)
return false;if(/^[^a-z$_@]/i.test(stack[0]))
return false;if(!WI.StackTrace._likelyStackTraceRegex){const reasonablyLongProtocolLength=10;const reasonablyLongLineLength=500;const reasonablyLongNativeMethodLength=120;const stackTraceLine=`(global code|eval code|module code|\\w+)?([^:]{1,${reasonablyLongProtocolLength}}://[^:]{1,${reasonablyLongLineLength}}:\\d+:\\d+|[^@]{1,${reasonablyLongNativeMethodLength}}@\\[native code\\])`;WI.StackTrace._likelyStackTraceRegex=new RegExp(`^${stackTraceLine}([\\n\\r]${stackTraceLine})+$`);}
WI.StackTrace._likelyStackTraceRegex.lastIndex=0;return WI.StackTrace._likelyStackTraceRegex.test(stack);}
static _parseStackTrace(stack)
{var lines=stack.split(/\n/g);var result=[];for(var line of lines){var functionName="";var url="";var lineNumber=0;var columnNumber=0;var atIndex=line.indexOf("@");if(atIndex!==-1){functionName=line.slice(0,atIndex);({url,lineNumber,columnNumber}=WI.StackTrace._parseLocation(line.slice(atIndex+1)));}else if(line.includes("/"))
({url,lineNumber,columnNumber}=WI.StackTrace._parseLocation(line));else
functionName=line;result.push({functionName,url,lineNumber,columnNumber});}
return result;}
static _parseLocation(locationString)
{var result={url:"",lineNumber:0,columnNumber:0};var locationRegEx=/(.+?)(?::(\d+)(?::(\d+))?)?$/;var matched=locationString.match(locationRegEx);if(!matched)
return result;result.url=matched[1];if(matched[2])
result.lineNumber=parseInt(matched[2]);if(matched[3])
result.columnNumber=parseInt(matched[3]);return result;} 
get callFrames(){return this._callFrames;}
get topCallFrameIsBoundary(){return this._topCallFrameIsBoundary;}
get truncated(){return this._truncated;}
get parentStackTrace(){return this._parentStackTrace;}
get firstNonNativeNonAnonymousNotBlackboxedCallFrame()
{let firstNonNativeNonAnonymousCallFrame=null;for(let frame of this._callFrames){if(frame.nativeCode)
continue;if(frame.sourceCodeLocation){let sourceCode=frame.sourceCodeLocation.sourceCode;if(sourceCode instanceof WI.Script&&sourceCode.anonymous)
continue;
firstNonNativeNonAnonymousCallFrame=frame;if(WI.debuggerManager.blackboxDataForSourceCode(sourceCode))
continue;}
return frame;}
return firstNonNativeNonAnonymousCallFrame;}};WI.StructureDescription=class StructureDescription
{constructor(fields,optionalFields,constructorName,prototypeStructure,imprecise)
{this._fields=fields||null;this._optionalFields=optionalFields||null;this._constructorName=constructorName||"";this._prototypeStructure=prototypeStructure||null;this._imprecise=imprecise||false;}

static fromPayload(payload)
{if(payload.prototypeStructure)
payload.prototypeStructure=WI.StructureDescription.fromPayload(payload.prototypeStructure);return new WI.StructureDescription(payload.fields,payload.optionalFields,payload.constructorName,payload.prototypeStructure,payload.imprecise);} 
get fields(){return this._fields;}
get optionalFields(){return this._optionalFields;}
get constructorName(){return this._constructorName;}
get prototypeStructure(){return this._prototypeStructure;}
get imprecise(){return this._imprecise;}};WI.TextMarker=class TextMarker
{constructor(codeMirrorTextMarker,type)
{this._codeMirrorTextMarker=codeMirrorTextMarker;codeMirrorTextMarker.__webInspectorTextMarker=this;this._type=type||WI.TextMarker.Type.Plain;} 
static textMarkerForCodeMirrorTextMarker(codeMirrorTextMarker)
{return codeMirrorTextMarker.__webInspectorTextMarker||new WI.TextMarker(codeMirrorTextMarker);} 
get codeMirrorTextMarker()
{return this._codeMirrorTextMarker;}
get type()
{return this._type;}
get range()
{var range=this._codeMirrorTextMarker.find();if(!range)
return null;return new WI.TextRange(range.from.line,range.from.ch,range.to.line,range.to.ch);}
get rects()
{var range=this._codeMirrorTextMarker.find();if(!range)
return WI.Rect.ZERO_RECT;return this._codeMirrorTextMarker.doc.cm.rectsForRange({start:range.from,end:range.to});}
clear()
{this._codeMirrorTextMarker.clear();}};WI.TextMarker.Type={Color:"text-marker-type-color",Gradient:"text-marker-type-gradient",Plain:"text-marker-type-plain",CubicBezier:"text-marker-type-cubic-bezier",Spring:"text-marker-type-spring",Variable:"text-marker-type-variable",};WI.TextRange=class TextRange
{constructor(startLineOrStartOffset,startColumnOrEndOffset,endLine,endColumn)
{if(arguments.length===4){this._startLine=typeof startLineOrStartOffset==="number"?startLineOrStartOffset:NaN;this._startColumn=typeof startColumnOrEndOffset==="number"?startColumnOrEndOffset:NaN;this._endLine=typeof endLine==="number"?endLine:NaN;this._endColumn=typeof endColumn==="number"?endColumn:NaN;this._startOffset=NaN;this._endOffset=NaN;}else if(arguments.length===2){this._startOffset=typeof startLineOrStartOffset==="number"?startLineOrStartOffset:NaN;this._endOffset=typeof startColumnOrEndOffset==="number"?startColumnOrEndOffset:NaN;this._startLine=NaN;this._startColumn=NaN;this._endLine=NaN;this._endColumn=NaN;}} 
static fromText(text)
{let lines=text.split("\n");return new WI.TextRange(0,0,lines.length-1,lines.lastValue.length);} 
get startLine(){return this._startLine;}
get startColumn(){return this._startColumn;}
get endLine(){return this._endLine;}
get endColumn(){return this._endColumn;}
get startOffset(){return this._startOffset;}
get endOffset(){return this._endOffset;}
startPosition()
{return new WI.SourceCodePosition(this._startLine,this._startColumn);}
endPosition()
{return new WI.SourceCodePosition(this._endLine,this._endColumn);}
resolveOffsets(text)
{if(typeof text!=="string")
return;if(isNaN(this._startLine)||isNaN(this._startColumn)||isNaN(this._endLine)||isNaN(this._endColumn))
return;var lastNewLineOffset=0;for(var i=0;i<this._startLine;++i)
lastNewLineOffset=text.indexOf("\n",lastNewLineOffset)+1;this._startOffset=lastNewLineOffset+this._startColumn;for(var i=this._startLine;i<this._endLine;++i)
lastNewLineOffset=text.indexOf("\n",lastNewLineOffset)+1;this._endOffset=lastNewLineOffset+this._endColumn;}
contains(line,column)
{if(line<this._startLine||line>this._endLine)
return false;if(line===this._startLine&&column<this._startColumn)
return false;if(line===this._endLine&&column>this._endColumn)
return false;return true;}
clone()
{return new WI.TextRange(this._startLine,this._startColumn,this._endLine,this._endColumn);}
cloneAndModify(deltaStartLine,deltaStartColumn,deltaEndLine,deltaEndColumn)
{let startLine=this._startLine+deltaStartLine;let startColumn=this._startColumn+deltaStartColumn;let endLine=this._endLine+deltaEndLine;let endColumn=this._endColumn+deltaEndColumn;return new WI.TextRange(startLine,startColumn,endLine,endColumn);}
collapseToStart()
{return new WI.TextRange(this._startLine,this._startColumn,this._startLine,this._startColumn);}
collapseToEnd()
{return new WI.TextRange(this._endLine,this._endColumn,this._endLine,this._endColumn);}
relativeTo(line,column)
{let deltaStartColumn=0;if(this._startLine===line)
deltaStartColumn=-column;let deltaEndColumn=0;if(this._endLine===line)
deltaEndColumn=-column;return this.cloneAndModify(-line,deltaStartColumn,-line,deltaEndColumn);}};WI.TimelineMarker=class TimelineMarker extends WI.Object
{constructor(time,type,details)
{super();this._time=time||0;this._type=type;this._details=details||null;} 
static fromJSON(json)
{let{time,type,details}=json;return new WI.TimelineMarker(time,type,details);}
toJSON()
{return{time:this._time,type:this._type,details:this._details||undefined,};} 
get type(){return this._type;}
get details(){return this._details;}
get time()
{return this._time;}
set time(x)
{x=x||0;if(this._time===x)
return;this._time=x;this.dispatchEventToListeners(WI.TimelineMarker.Event.TimeChanged);}};WI.TimelineMarker.Event={TimeChanged:"timeline-marker-time-changed"};WI.TimelineMarker.Type={CurrentTime:"current-time",LoadEvent:"load-event",DOMContentEvent:"dom-content-event",TimeStamp:"timestamp",Scanner:"scanner",};WI.TimelineRecording=class TimelineRecording extends WI.Object
{constructor(identifier,displayName,instruments)
{super();this._identifier=identifier;this._timelines=new Map;this._displayName=displayName;this._capturing=false;this._readonly=false;this._imported=false;this._instruments=instruments||[];this._startTime=NaN;this._endTime=NaN;this._discontinuityStartTime=NaN;this._discontinuities=null;this._firstRecordOfTypeAfterDiscontinuity=new Set;this._exportDataRecords=null;this._exportDataMarkers=null;this._exportDataMemoryPressureEvents=null;this._exportDataSampleStackTraces=null;this._exportDataSampleDurations=null;this._topDownCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopDown);this._bottomUpCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.BottomUp);this._topFunctionsTopDownCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopFunctionsTopDown);this._topFunctionsBottomUpCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopFunctionsBottomUp);for(let type of WI.TimelineManager.availableTimelineTypes()){let timeline=WI.Timeline.create(type);this._timelines.set(type,timeline);timeline.addEventListener(WI.Timeline.Event.TimesUpdated,this._timelineTimesUpdated,this);}
this.reset(true);} 
static sourceCodeTimelinesSupported()
{return WI.sharedApp.isWebDebuggable();} 
static async import(identifier,json,displayName)
{let{startTime,endTime,discontinuities,instrumentTypes,records,markers,memoryPressureEvents,sampleStackTraces,sampleDurations}=json;let importedDisplayName=WI.UIString("Imported - %s").format(displayName);let instruments=instrumentTypes.map((type)=>WI.Instrument.createForTimelineType(type));let recording=new WI.TimelineRecording(identifier,importedDisplayName,instruments);recording._readonly=true;recording._imported=true;recording._startTime=startTime;recording._endTime=endTime;recording._discontinuities=discontinuities;recording.initializeCallingContextTrees(sampleStackTraces,sampleDurations);for(let recordJSON of records){let record=await WI.TimelineRecord.fromJSON(recordJSON);if(record){recording.addRecord(record);if(record instanceof WI.ScriptTimelineRecord)
record.profilePayload=recording._topDownCallingContextTree.toCPUProfilePayload(record.startTime,record.endTime);}}
for(let memoryPressureJSON of memoryPressureEvents){let memoryPressureEvent=WI.MemoryPressureEvent.fromJSON(memoryPressureJSON);if(memoryPressureEvent)
recording.addMemoryPressureEvent(memoryPressureEvent);}
setTimeout(()=>{recording.__importing=true;for(let markerJSON of markers){let marker=WI.TimelineMarker.fromJSON(markerJSON);if(marker)
recording.addEventMarker(marker);}
recording.__importing=false;});return recording;}
exportData()
{return{displayName:this._displayName,startTime:this._startTime,endTime:this._endTime,discontinuities:this._discontinuities,instrumentTypes:this._instruments.map((instrument)=>instrument.timelineRecordType),records:this._exportDataRecords,markers:this._exportDataMarkers,memoryPressureEvents:this._exportDataMemoryPressureEvents,sampleStackTraces:this._exportDataSampleStackTraces,sampleDurations:this._exportDataSampleDurations,};} 
get displayName(){return this._displayName;}
get identifier(){return this._identifier;}
get timelines(){return this._timelines;}
get instruments(){return this._instruments;}
get capturing(){return this._capturing;}
get readonly(){return this._readonly;}
get imported(){return this._imported;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get topDownCallingContextTree(){return this._topDownCallingContextTree;}
get bottomUpCallingContextTree(){return this._bottomUpCallingContextTree;}
get topFunctionsTopDownCallingContextTree(){return this._topFunctionsTopDownCallingContextTree;}
get topFunctionsBottomUpCallingContextTree(){return this._topFunctionsBottomUpCallingContextTree;}
start(initiatedByBackend)
{this._capturing=true;for(let instrument of this._instruments)
instrument.startInstrumentation(initiatedByBackend);if(!isNaN(this._discontinuityStartTime)){for(let instrument of this._instruments)
this._firstRecordOfTypeAfterDiscontinuity.add(instrument.timelineRecordType);}}
stop(initiatedByBackend)
{this._capturing=false;for(let instrument of this._instruments)
instrument.stopInstrumentation(initiatedByBackend);}
capturingStarted(startTime)
{

if(!isNaN(this._discontinuityStartTime)){this._discontinuities.push({startTime:this._discontinuityStartTime,endTime:startTime,});this._discontinuityStartTime=NaN;}}
capturingStopped(endTime)
{this._discontinuityStartTime=endTime;}
saveIdentityToCookie()
{
}
isEmpty()
{for(var timeline of this._timelines.values()){if(timeline.records.length)
return false;}
return true;}
unloaded(importing)
{this._readonly=true;this.dispatchEventToListeners(WI.TimelineRecording.Event.Unloaded);}
reset(suppressEvents)
{this._sourceCodeTimelinesMap=new Map;this._startTime=NaN;this._endTime=NaN;this._discontinuityStartTime=NaN;this._discontinuities=[];this._firstRecordOfTypeAfterDiscontinuity.clear();this._exportDataRecords=[];this._exportDataMarkers=[];this._exportDataMemoryPressureEvents=[];this._exportDataSampleStackTraces=[];this._exportDataSampleDurations=[];this._topDownCallingContextTree.reset();this._bottomUpCallingContextTree.reset();this._topFunctionsTopDownCallingContextTree.reset();this._topFunctionsBottomUpCallingContextTree.reset();for(var timeline of this._timelines.values())
timeline.reset(suppressEvents);WI.RenderingFrameTimelineRecord.resetFrameIndex();if(!suppressEvents){this.dispatchEventToListeners(WI.TimelineRecording.Event.Reset);this.dispatchEventToListeners(WI.TimelineRecording.Event.TimesUpdated);}}
get sourceCodeTimelines()
{let timelines=[];for(let timelinesForSourceCode of this._sourceCodeTimelinesMap.values())
timelines.pushAll(timelinesForSourceCode.values());return timelines;}
timelineForInstrument(instrument)
{return this._timelines.get(instrument.timelineRecordType);}
instrumentForTimeline(timeline)
{return this._instruments.find((instrument)=>instrument.timelineRecordType===timeline.type);}
timelineForRecordType(recordType)
{return this._timelines.get(recordType);}
addInstrument(instrument)
{this._instruments.push(instrument);this.dispatchEventToListeners(WI.TimelineRecording.Event.InstrumentAdded,{instrument});}
removeInstrument(instrument)
{this._instruments.remove(instrument);this.dispatchEventToListeners(WI.TimelineRecording.Event.InstrumentRemoved,{instrument});}
addEventMarker(marker)
{this._exportDataMarkers.push(marker);if(!this._capturing&&!this.__importing)
return;this.dispatchEventToListeners(WI.TimelineRecording.Event.MarkerAdded,{marker});}
addRecord(record)
{this._exportDataRecords.push(record);let timeline=this._timelines.get(record.type);if(!timeline)
return;let discontinuity=null;if(this._firstRecordOfTypeAfterDiscontinuity.take(record.type))
discontinuity=this._discontinuities.lastValue;timeline.addRecord(record,{discontinuity});if(record.type===WI.TimelineRecord.Type.Network||record.type===WI.TimelineRecord.Type.RenderingFrame||record.type===WI.TimelineRecord.Type.CPU||record.type===WI.TimelineRecord.Type.Memory||record.type===WI.TimelineRecord.Type.HeapAllocations)
return;if(!WI.TimelineRecording.sourceCodeTimelinesSupported())
return;let sourceCode=null;if(record.sourceCodeLocation)
sourceCode=record.sourceCodeLocation.sourceCode;else if(record.type===WI.TimelineRecord.Type.Media){if(record.domNode&&record.domNode.frame)
sourceCode=record.domNode.frame.mainResource;}
if(!sourceCode)
sourceCode=WI.networkManager.mainFrame.provisionalMainResource||WI.networkManager.mainFrame.mainResource;var sourceCodeTimelines=this._sourceCodeTimelinesMap.get(sourceCode);if(!sourceCodeTimelines){sourceCodeTimelines=new Map;this._sourceCodeTimelinesMap.set(sourceCode,sourceCodeTimelines);}
var newTimeline=false;var key=this._keyForRecord(record);var sourceCodeTimeline=sourceCodeTimelines.get(key);if(!sourceCodeTimeline){sourceCodeTimeline=new WI.SourceCodeTimeline(sourceCode,record.sourceCodeLocation,record.type,record.eventType);sourceCodeTimelines.set(key,sourceCodeTimeline);newTimeline=true;}
sourceCodeTimeline.addRecord(record);if(newTimeline)
this.dispatchEventToListeners(WI.TimelineRecording.Event.SourceCodeTimelineAdded,{sourceCodeTimeline});}
addMemoryPressureEvent(memoryPressureEvent)
{this._exportDataMemoryPressureEvents.push(memoryPressureEvent);let memoryTimeline=this._timelines.get(WI.TimelineRecord.Type.Memory);if(!memoryTimeline)
return;memoryTimeline.addMemoryPressureEvent(memoryPressureEvent);}
discontinuitiesInTimeRange(startTime,endTime)
{return this._discontinuities.filter((item)=>item.startTime<=endTime&&item.endTime>=startTime);}
addScriptInstrumentForProgrammaticCapture()
{for(let instrument of this._instruments){if(instrument instanceof WI.ScriptInstrument)
return;}
this.addInstrument(new WI.ScriptInstrument);let instrumentTypes=this._instruments.map((instrument)=>instrument.timelineRecordType);WI.timelineManager.enabledTimelineTypes=instrumentTypes;}
computeElapsedTime(timestamp)
{if(!timestamp||isNaN(timestamp))
return NaN;return timestamp;}
initializeTimeBoundsIfNecessary(timestamp)
{if(isNaN(this._startTime)){this._startTime=timestamp;this._endTime=timestamp;this.dispatchEventToListeners(WI.TimelineRecording.Event.TimesUpdated);}}
initializeCallingContextTrees(stackTraces,sampleDurations)
{this._exportDataSampleStackTraces.pushAll(stackTraces);this._exportDataSampleDurations.pushAll(sampleDurations);for(let i=0;i<stackTraces.length;i++){this._topDownCallingContextTree.updateTreeWithStackTrace(stackTraces[i],sampleDurations[i]);this._bottomUpCallingContextTree.updateTreeWithStackTrace(stackTraces[i],sampleDurations[i]);this._topFunctionsTopDownCallingContextTree.updateTreeWithStackTrace(stackTraces[i],sampleDurations[i]);this._topFunctionsBottomUpCallingContextTree.updateTreeWithStackTrace(stackTraces[i],sampleDurations[i]);}}
canExport()
{if(this._capturing)
return false;if(isNaN(this._startTime))
return false;return true;} 
_keyForRecord(record)
{var key=record.type;if(record instanceof WI.ScriptTimelineRecord||record instanceof WI.LayoutTimelineRecord)
key+=":"+record.eventType;if(record instanceof WI.ScriptTimelineRecord&&record.eventType===WI.ScriptTimelineRecord.EventType.EventDispatched)
key+=":"+record.details;if(record instanceof WI.MediaTimelineRecord){key+=":"+record.eventType;if(record.eventType===WI.MediaTimelineRecord.EventType.DOMEvent){if(record.domEvent&&record.domEvent.eventName)
key+=":"+record.domEvent.eventName;}else if(record.eventType===WI.MediaTimelineRecord.EventType.PowerEfficientPlaybackStateChanged)
key+=":"+(record.isPowerEfficient?"enabled":"disabled");}
if(record.sourceCodeLocation)
key+=":"+record.sourceCodeLocation.lineNumber+":"+record.sourceCodeLocation.columnNumber;return key;}
_timelineTimesUpdated(event)
{var timeline=event.target;var changed=false;if(isNaN(this._startTime)||timeline.startTime<this._startTime){this._startTime=timeline.startTime;changed=true;}
if(isNaN(this._endTime)||this._endTime<timeline.endTime){this._endTime=timeline.endTime;changed=true;}
if(changed)
this.dispatchEventToListeners(WI.TimelineRecording.Event.TimesUpdated);}};WI.TimelineRecording.Event={Reset:"timeline-recording-reset",Unloaded:"timeline-recording-unloaded",SourceCodeTimelineAdded:"timeline-recording-source-code-timeline-added",InstrumentAdded:"timeline-recording-instrument-added",InstrumentRemoved:"timeline-recording-instrument-removed",TimesUpdated:"timeline-recording-times-updated",MarkerAdded:"timeline-recording-marker-added",};WI.TimelineRecording.SerializationVersion=1;WI.TypeDescription=class TypeDescription
{constructor(leastCommonAncestor,typeSet,structures,valid,truncated)
{this._leastCommonAncestor=leastCommonAncestor||null;this._typeSet=typeSet||null;this._structures=structures||null;this._valid=valid||false;this._truncated=truncated||false;}

static fromPayload(payload)
{var typeSet=undefined;if(payload.typeSet)
typeSet=WI.TypeSet.fromPayload(payload.typeSet);var structures=undefined;if(payload.structures)
structures=payload.structures.map(WI.StructureDescription.fromPayload);return new WI.TypeDescription(payload.leastCommonAncestor,typeSet,structures,payload.isValid,payload.isTruncated);} 
get leastCommonAncestor(){return this._leastCommonAncestor;}
get typeSet(){return this._typeSet;}
get structures(){return this._structures;}
get valid(){return this._valid;}
get truncated(){return this._truncated;}};WI.TypeSet=class TypeSet
{constructor(typeSet)
{var bitString=0x0;if(typeSet.isFunction)
bitString|=WI.TypeSet.TypeBit.Function;if(typeSet.isUndefined)
bitString|=WI.TypeSet.TypeBit.Undefined;if(typeSet.isNull)
bitString|=WI.TypeSet.TypeBit.Null;if(typeSet.isBoolean)
bitString|=WI.TypeSet.TypeBit.Boolean;if(typeSet.isInteger)
bitString|=WI.TypeSet.TypeBit.Integer;if(typeSet.isNumber)
bitString|=WI.TypeSet.TypeBit.Number;if(typeSet.isString)
bitString|=WI.TypeSet.TypeBit.String;if(typeSet.isObject)
bitString|=WI.TypeSet.TypeBit.Object;if(typeSet.isSymbol)
bitString|=WI.TypeSet.TypeBit.Symbol;if(typeSet.isBigInt)
bitString|=WI.TypeSet.TypeBit.BigInt;this._typeSet=typeSet;this._bitString=bitString;this._primitiveTypeNames=null;} 
static fromPayload(payload)
{return new WI.TypeSet(payload);} 
isContainedIn(test)
{
 
return this._bitString&&(this._bitString&test)===this._bitString;}
get primitiveTypeNames()
{if(this._primitiveTypeNames)
return this._primitiveTypeNames;this._primitiveTypeNames=[];var typeSet=this._typeSet;if(typeSet.isUndefined)
this._primitiveTypeNames.push("Undefined");if(typeSet.isNull)
this._primitiveTypeNames.push("Null");if(typeSet.isBoolean)
this._primitiveTypeNames.push("Boolean");if(typeSet.isString)
this._primitiveTypeNames.push("String");if(typeSet.isSymbol)
this._primitiveTypeNames.push("Symbol");if(typeSet.isBigInt)
this._primitiveTypeNames.push("BigInt");

if(typeSet.isNumber)
this._primitiveTypeNames.push("Number");else if(typeSet.isInteger)
this._primitiveTypeNames.push("Integer");return this._primitiveTypeNames;}};WI.TypeSet.TypeBit={"Function":0x1,"Undefined":0x2,"Null":0x4,"Boolean":0x8,"Integer":0x10,"Number":0x20,"String":0x40,"Object":0x80,"Symbol":0x100,"BigInt":0x200,};WI.TypeSet.NullOrUndefinedTypeBits=WI.TypeSet.TypeBit.Null|WI.TypeSet.TypeBit.Undefined;WI.URLBreakpoint=class URLBreakpoint extends WI.Breakpoint
{constructor(type,url,{disabled,actions,condition,ignoreCount,autoContinue}={})
{super({disabled,actions,condition,ignoreCount,autoContinue});this._type=type;this._url=url;} 
static get supportsEditing()
{return InspectorBackend.hasCommand("DOMDebugger.setURLBreakpoint","options");}
static fromJSON(json)
{return new WI.URLBreakpoint(json.type,json.url,{disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} 
get type(){return this._type;}
get url(){return this._url;}
get displayName()
{if(this===WI.domDebuggerManager.allRequestsBreakpoint)
return WI.repeatedUIString.allRequests();switch(this._type){case WI.URLBreakpoint.Type.Text:return doubleQuotedString(this._url);case WI.URLBreakpoint.Type.RegularExpression:return"/"+this._url+"/";}
return WI.UIString("URL");}
get special()
{return this===WI.domDebuggerManager.allRequestsBreakpoint||super.special;}
get editable()
{return WI.URLBreakpoint.supportsEditing||super.editable;}
remove()
{super.remove();WI.domDebuggerManager.removeURLBreakpoint(this);}
saveIdentityToCookie(cookie)
{cookie["url-breakpoint-type"]=this._type;cookie["url-breakpoint-url"]=this._url;}
toJSON(key)
{let json=super.toJSON(key);json.type=this._type;json.url=this._url;if(key===WI.ObjectStore.toJSONSymbol)
json[WI.objectStores.urlBreakpoints.keyPath]=this._type+":"+this._url;return json;}};WI.URLBreakpoint.Type={Text:"text",RegularExpression:"regex",};WI.URLBreakpoint.ReferencePage=WI.ReferencePage.URLBreakpoints;WI.WebInspectorExtension=class WebInspectorExtension
{constructor(extensionID,displayName)
{this._extensionID=extensionID;this._displayName=displayName;} 
get extensionID(){return this._extensionID;}
get displayName(){return this._displayName;}};WI.WebInspectorExtension.ErrorCode={ContextDestroyed:"ContextDestroyed",InternalError:"InternalError",InvalidRequest:"InvalidRequest",RegistrationFailed:"RegistrationFailed",NotImplemented:"NotImplemented",};WI.WebSocketResource=class WebSocketResource extends WI.Resource
{constructor(url,{loaderIdentifier,requestIdentifier,requestHeaders,timestamp,walltime,requestSentTimestamp}={})
{super(url,{type:WI.Resource.Type.WebSocket,loaderIdentifier,requestIdentifier,requestMethod:"GET",requestHeaders,requestSentTimestamp,});this._timestamp=timestamp;this._walltime=walltime;this._readyState=WI.WebSocketResource.ReadyState.Connecting;this._frames=[];} 
get frames(){return this._frames;}
get walltime(){return this._walltime;}
get readyState()
{return this._readyState;}
set readyState(state)
{if(state===this._readyState)
return;let previousState=this._readyState;this._readyState=state;this.dispatchEventToListeners(WI.WebSocketResource.Event.ReadyStateChanged,{previousState,state});}
addFrame(data,payloadLength,isOutgoing,opcode,timestamp,elapsedTime)
{let frameData;if(opcode===WI.WebSocketResource.OpCodes.BinaryFrame)
frameData=null;else
frameData=data;let frame={data:frameData,isOutgoing,opcode,walltime:this._walltimeForWebSocketTimestamp(timestamp)};this._frames.push(frame);if(InspectorFrontendHost.isUnderTest())
frame.dataForTest=data;if(payloadLength===undefined)
payloadLength=new TextEncoder("utf-8").encode(data).length;this.increaseSize(payloadLength,elapsedTime);this.dispatchEventToListeners(WI.WebSocketResource.Event.FrameAdded,frame);} 
requestContentFromBackend()
{return super.requestContentFromBackend();} 
_walltimeForWebSocketTimestamp(timestamp)
{return this._walltime+(timestamp-this._timestamp);}};WI.WebSocketResource.Event={FrameAdded:"web-socket-frame-added",ReadyStateChanged:"web-socket-resource-ready-state-changed",};WI.WebSocketResource.ReadyState={Closed:Symbol("closed"),Connecting:Symbol("connecting"),Open:Symbol("open"),};WI.WebSocketResource.OpCodes={ContinuationFrame:0,TextFrame:1,BinaryFrame:2,ConnectionCloseFrame:8,PingFrame:9,PongFrame:10,};WI.WrappedPromise=class WrappedPromise
{constructor(work)
{this._settled=false;this._promise=new Promise((resolve,reject)=>{this._resolveCallback=resolve;this._rejectCallback=reject;
if(work&&typeof work==="function")
return work(this.resolve.bind(this),this.reject.bind(this));});} 
get settled()
{return this._settled;}
get promise()
{return this._promise;}
resolve(value)
{if(this._settled)
throw new Error("Promise is already settled, cannot call resolve().");this._settled=true;this._resolveCallback(value);}
reject(value)
{if(this._settled)
throw new Error("Promise is already settled, cannot call reject().");this._settled=true;this._rejectCallback(value);}};


WI.LocalResource=class LocalResource extends WI.Resource
{constructor({request,response,metrics,timing})
{metrics=metrics||{};timing=timing||{};super(request.url,{mimeType:response.mimeType||(response.headers||{}).valueForCaseInsensitiveKey("Content-Type")||null,requestMethod:request.method,requestHeaders:request.headers,requestData:request.data,requestSentTimestamp:request.timestamp,requestSentWalltime:request.walltime,});this._finishedOrFailedTimestamp=request.finishedTimestamp||NaN;this._statusCode=response.statusCode||NaN;this._statusText=response.statusText||null;this._responseHeaders=response.headers||{};this._failureReasonText=response.failureReasonText||null;this._timingData=new WI.ResourceTimingData(this,timing);this._responseSource=metrics.responseSource||WI.Resource.ResponseSource.Unknown;this._protocol=metrics.protocol||null;this._priority=metrics.priority||WI.Resource.NetworkPriority.Unknown;this._remoteAddress=metrics.remoteAddress||null;this._connectionIdentifier=metrics.connectionIdentifier||null;this._requestHeadersTransferSize=!isNaN(metrics.requestHeaderBytesSent)?metrics.requestHeaderBytesSent:NaN;this._requestBodyTransferSize=!isNaN(metrics.requestBodyBytesSent)?metrics.requestBodyBytesSent:NaN;this._responseHeadersTransferSize=!isNaN(metrics.responseHeaderBytesReceived)?metrics.responseHeaderBytesReceived:NaN;this._responseBodyTransferSize=!isNaN(metrics.responseBodyBytesReceived)?metrics.responseBodyBytesReceived:NaN;this._responseBodySize=!isNaN(metrics.responseBodyDecodedSize)?metrics.responseBodyDecodedSize:NaN;this._localResourceOverride=null;this._finished=true;this._failed=false;this._cached=false;let content=response.content||"";let base64Encoded=response.base64Encoded||false;this._originalRevision=new WI.SourceCodeRevision(this,content,base64Encoded,this._mimeType);this._currentRevision=this._originalRevision;} 
static headersArrayToHeadersObject(headers)
{let result={};if(headers){for(let{name,value}of headers)
result[name]=value;}
return result;}
static fromHAREntry(entry,archiveStartWalltime)
{ let{request,response,startedDateTime,timings}=entry;let requestSentWalltime=WI.HARBuilder.dateFromHARDate(startedDateTime)/1000;let requestSentTimestamp=requestSentWalltime-archiveStartWalltime;let finishedTimestamp=NaN;let timing={startTime:NaN,domainLookupStart:NaN,domainLookupEnd:NaN,connectStart:NaN,connectEnd:NaN,secureConnectionStart:NaN,requestStart:NaN,responseStart:NaN,responseEnd:NaN,};if(!isNaN(requestSentWalltime)&&!isNaN(archiveStartWalltime)){let hasBlocked=timings.blocked!==-1;let hasDNS=timings.dns!==-1;let hasConnect=timings.connect!==-1;let hasSecureConnect=timings.ssl!==-1; timing.startTime=requestSentTimestamp||Number.EPSILON;timing.fetchStart=timing.startTime;let accumulation=timing.startTime;if(hasBlocked)
accumulation+=(timings.blocked/1000);if(hasDNS){timing.domainLookupStart=accumulation;accumulation+=(timings.dns/1000);timing.domainLookupEnd=accumulation;}
if(hasConnect){timing.connectStart=accumulation;accumulation+=(timings.connect/1000);timing.connectEnd=accumulation;if(hasSecureConnect)
timing.secureConnectionStart=timing.connectEnd-(timings.ssl/1000);}
accumulation+=(timings.send/1000);timing.requestStart=accumulation;accumulation+=(timings.wait/1000);timing.responseStart=accumulation;accumulation+=(timings.receive/1000);timing.responseEnd=accumulation;finishedTimestamp=timing.responseEnd;}
let serverAddress=entry.serverIPAddress||null;if(serverAddress&&typeof entry._serverPort==="number")
serverAddress+=":"+entry._serverPort;return new WI.LocalResource({request:{url:request.url,method:request.method,headers:LocalResource.headersArrayToHeadersObject(request.headers),timestamp:requestSentTimestamp,walltime:requestSentWalltime,finishedTimestamp:finishedTimestamp,data:request.postData?request.postData.text:null,},response:{headers:LocalResource.headersArrayToHeadersObject(response.headers),mimeType:response.content.mimeType,statusCode:response.status,statusText:response.statusText,failureReasonText:response._error||null,content:response.content.text,base64Encoded:response.content.encoding==="base64",},metrics:{responseSource:WI.HARBuilder.responseSourceFromHARFetchType(entry._fetchType),protocol:WI.HARBuilder.protocolFromHARProtocol(response.httpVersion),priority:WI.HARBuilder.networkPriorityFromHARPriority(entry._priority),remoteAddress:serverAddress,connectionIdentifier:entry.connection?parseInt(entry.connection):null,requestHeaderBytesSent:request.headersSize>=0?request.headersSize:NaN,requestBodyBytesSent:request.bodySize>=0?request.bodySize:NaN,responseHeaderBytesReceived:response.headersSize>=0?response.headersSize:NaN,responseBodyBytesReceived:response.bodySize>=0?response.bodySize:NaN,responseBodyDecodedSize:response.content.size||NaN,},timing,});} 
static fromJSON(json)
{return new WI.LocalResource(json);}
toJSON(key)
{return{request:{url:this.url,method:this.requestMethod,headers:this.requestHeaders,data:this.requestData,},response:{headers:this.responseHeaders,mimeType:this.mimeType,statusCode:this.statusCode,statusText:this.statusText,content:this.currentRevision.content,base64Encoded:this.currentRevision.base64Encoded,},};} 
get localResourceOverride(){return this._localResourceOverride;} 
requestContentFromBackend()
{return Promise.resolve({content:this._originalRevision.content,base64Encoded:this._originalRevision.base64Encoded,});}
handleCurrentRevisionContentChange()
{if(this._mimeType!==this.currentRevision.mimeType){let oldMIMEType=this._mimeType;this._mimeType=this.currentRevision.mimeType;this.dispatchEventToListeners(WI.Resource.Event.MIMETypeDidChange,{oldMIMEType});}}};WI.SourceMapResource=class SourceMapResource extends WI.Resource
{constructor(url,sourceMap)
{super(url);this._sourceMap=sourceMap;var inheritedMIMEType=this._sourceMap.originalSourceCode instanceof WI.Resource?this._sourceMap.originalSourceCode.syntheticMIMEType:null;let fileExtension=WI.fileExtensionForURL(url)||"";let fileExtensionMIMEType=fileExtension==="js"?"text/jsx":WI.mimeTypeForFileExtension(fileExtension,true);
this._mimeType=fileExtensionMIMEType||inheritedMIMEType||"text/javascript";this._type=WI.Resource.typeFromMIMEType(this._mimeType);this.markAsFinished();} 
get sourceMap(){return this._sourceMap;}
get sourceMapDisplaySubpath()
{var sourceMappingBasePathURLComponents=this._sourceMap.sourceMappingBasePathURLComponents;var resourceURLComponents=this.urlComponents;if(!resourceURLComponents.path)
resourceURLComponents.path=this.url;if(resourceURLComponents.scheme!==sourceMappingBasePathURLComponents.scheme||resourceURLComponents.host!==sourceMappingBasePathURLComponents.host){let subpath="";if(resourceURLComponents.host){subpath+=resourceURLComponents.host;if(resourceURLComponents.port)
subpath+=":"+resourceURLComponents.port;subpath+=resourceURLComponents.path;}else{subpath+=resourceURLComponents.path.substring(1);}
return subpath;}
if(!resourceURLComponents.path.startsWith(sourceMappingBasePathURLComponents.path))
return relativePath(resourceURLComponents.path,sourceMappingBasePathURLComponents.path);return resourceURLComponents.path.substring(sourceMappingBasePathURLComponents.path.length,resourceURLComponents.length);}
get supportsScriptBlackboxing()
{return false;}
requestContentFromBackend()
{this.revertMarkAsFinished();var inlineContent=this._sourceMap.sourceContent(this.url);if(inlineContent){return Promise.resolve().then(sourceMapResourceLoaded.bind(this,{content:inlineContent,mimeType:this.mimeType,statusCode:200}));}
function sourceMapResourceNotAvailable(error,content,mimeType,statusCode)
{this.markAsFailed();return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource."),content,mimeType,statusCode});}
function sourceMapResourceLoadError(error)
{console.error(error||"There was an unknown error calling Network.loadResource.");this.markAsFailed();return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource.")});}
function sourceMapResourceLoaded(parameters)
{var{error,content,mimeType,statusCode}=parameters;var base64encoded=false;if(statusCode>=400||error)
return sourceMapResourceNotAvailable(error,content,mimeType,statusCode);this.markAsFinished();return Promise.resolve({content,mimeType,base64encoded,statusCode});}
if(!this._target.hasCommand("Network.loadResource"))
return sourceMapResourceLoadError.call(this);var frameIdentifier=null;if(this._sourceMap.originalSourceCode instanceof WI.Resource&&this._sourceMap.originalSourceCode.parentFrame)
frameIdentifier=this._sourceMap.originalSourceCode.parentFrame.id;if(!frameIdentifier)
frameIdentifier=WI.networkManager.mainFrame?WI.networkManager.mainFrame.id:"";return this._target.NetworkAgent.loadResource(frameIdentifier,this.url).then(sourceMapResourceLoaded.bind(this)).catch(sourceMapResourceLoadError.bind(this));}
createSourceCodeLocation(lineNumber,columnNumber)
{var entry=this._sourceMap.findEntryReversed(this.url,lineNumber);var rawLineNumber=entry[0];var rawColumnNumber=entry[1];var originalSourceCode=this._sourceMap.originalSourceCode;if(originalSourceCode instanceof WI.Script){if(rawLineNumber===0)
rawColumnNumber+=originalSourceCode.range.startColumn;rawLineNumber+=originalSourceCode.range.startLine;}
var location=originalSourceCode.createSourceCodeLocation(rawLineNumber,rawColumnNumber);location._setMappedLocation(this,lineNumber,columnNumber);return location;}
createSourceCodeTextRange(textRange)
{var startSourceCodeLocation=this.createSourceCodeLocation(textRange.startLine,textRange.startColumn);var endSourceCodeLocation=this.createSourceCodeLocation(textRange.endLine,textRange.endColumn);return new WI.SourceCodeTextRange(this._sourceMap.originalSourceCode,startSourceCodeLocation,endSourceCodeLocation);}};WI.AuditTestBase=class AuditTestBase extends WI.Object
{constructor(name,{description,supports,setup,disabled}={})
{super();this._name=name;this._description=description||"";this._supports=supports??NaN;this._setup=setup||"";this.determineIfSupported({warn:true});this._runningState=disabled?WI.AuditManager.RunningState.Disabled:WI.AuditManager.RunningState.Inactive;this._result=null;this._parent=null;this._default=false;} 
get runningState(){return this._runningState;}
get result(){return this._result;}
get supported(){return this._supported;}
get name()
{return this._name;}
set name(name)
{if(name===this._name)
return;let oldName=this._name;this._name=name;this.dispatchEventToListeners(WI.AuditTestBase.Event.NameChanged,{oldName});}
get description()
{return this._description;}
set description(description)
{if(description===this._description)
return;this._description=description;}
get supports()
{return this._supports;}
set supports(supports)
{if(supports===this._supports)
return;this._supports=supports;this.determineIfSupported();}
get setup()
{return this._setup;}
set setup(setup)
{if(setup===this._setup)
return;this._setup=setup;this.clearResult();}
get disabled()
{return this._runningState===WI.AuditManager.RunningState.Disabled;}
set disabled(disabled)
{this.updateDisabled(disabled);}
get editable()
{return!this._default;}
get default()
{return this._default;}
markAsDefault()
{this._default=true;}
get topLevelTest()
{let test=this;while(test._parent)
test=test._parent;return test;}
async runSetup()
{if(!this._setup)
return;let target=WI.assumingMainTarget();let agentCommandFunction=null;let agentCommandArguments={};if(target.hasDomain("Audit")){agentCommandFunction=target.AuditAgent.run;agentCommandArguments.test=this._setup;}else{agentCommandFunction=target.RuntimeAgent.evaluate;agentCommandArguments.expression=`(function() { "use strict"; return eval(\`(${this._setup.replace(/`/g,"\\`")})\`)(); })()`;agentCommandArguments.objectGroup=AuditTestBase.ObjectGroup;agentCommandArguments.doNotPauseOnExceptionsAndMuteConsole=true;}
try{let response=await agentCommandFunction.invoke(agentCommandArguments);if(response.result.type==="object"&&response.result.className==="Promise"){if(WI.RuntimeManager.supportsAwaitPromise())
response=await target.RuntimeAgent.awaitPromise(response.result.objectId);else{response=null;WI.AuditManager.synthesizeError(WI.UIString("Async audits are not supported."));}}
if(response){let remoteObject=WI.RemoteObject.fromPayload(response.result,WI.mainTarget);if(response.wasThrown||(remoteObject.type==="object"&&remoteObject.subtype==="error"))
WI.AuditManager.synthesizeError(remoteObject.description);}}catch(error){WI.AuditManager.synthesizeError(error.message);}}
async start()
{if(!this._supported||this.disabled)
return;if(this._runningState!==WI.AuditManager.RunningState.Inactive)
return;this._runningState=WI.AuditManager.RunningState.Active;this.dispatchEventToListeners(WI.AuditTestBase.Event.Scheduled);await this.run();this._runningState=WI.AuditManager.RunningState.Inactive;this.dispatchEventToListeners(WI.AuditTestBase.Event.Completed);}
stop()
{if(!this._supported||this.disabled)
return;if(this._runningState!==WI.AuditManager.RunningState.Active)
return;this._runningState=WI.AuditManager.RunningState.Stopping;this.dispatchEventToListeners(WI.AuditTestBase.Event.Stopping);}
clearResult(options={})
{if(!this._result)
return false;this._result=null;if(!options.suppressResultChangedEvent)
this.dispatchEventToListeners(WI.AuditTestBase.Event.ResultChanged);return true;}
async clone()
{return this.constructor.fromPayload(this.toJSON());}
remove()
{if(!this._parent||this._default){WI.auditManager.removeTest(this);return;}
this._parent.removeTest(this);}
saveIdentityToCookie(cookie)
{let path=[];let test=this;while(test){path.push(test.name);test=test._parent;}
path.reverse();cookie["audit-path"]=path.join(",");}
toJSON(key)
{let json={type:this.constructor.TypeIdentifier,name:this._name,};if(this._description)
json.description=this._description;if(!isNaN(this._supports))
json.supports=Number.isFinite(this._supports)?this._supports:WI.AuditTestBase.Version+1;if(this._setup)
json.setup=this._setup;if(key===WI.ObjectStore.toJSONSymbol)
json.disabled=this.disabled;return json;} 
async run()
{throw WI.NotImplementedError.subclassMustOverride();}
determineIfSupported(options={})
{let supportedBefore=this._supported;if(this._supports>WI.AuditTestBase.Version){this.updateSupported(false,options);if(options.warn&&supportedBefore!==this._supported&&Number.isFinite(this._supports))
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 is too new to run in this Web Inspector").format(this.name));}else if(InspectorBackend.hasDomain("Audit")&&this._supports>InspectorBackend.getVersion("Audit")){this.updateSupported(false,options);if(options.warn&&supportedBefore!==this._supported&&Number.isFinite(this._supports))
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 is too new to run in the inspected page").format(this.name));}else
this.updateSupported(true,options);return this._supported;}
updateSupported(supported,options={})
{if(supported===this._supported)
return;this._supported=supported;if(!options.silent)
this.dispatchEventToListeners(WI.AuditTestBase.Event.SupportedChanged);if(!this._supported)
this.clearResult();}
updateDisabled(disabled,options={})
{if(this._runningState!==WI.AuditManager.RunningState.Disabled&&this._runningState!==WI.AuditManager.RunningState.Inactive)
return;let runningState=disabled?WI.AuditManager.RunningState.Disabled:WI.AuditManager.RunningState.Inactive;if(runningState===this._runningState)
return;this._runningState=runningState;if(!options.silent)
this.dispatchEventToListeners(WI.AuditTestBase.Event.DisabledChanged);if(this.disabled)
this.clearResult();}
updateResult(result)
{this._result=result;this.dispatchEventToListeners(WI.AuditTestBase.Event.ResultChanged);}};WI.AuditTestBase.Version=3;WI.AuditTestBase.ObjectGroup="audit";WI.AuditTestBase.Event={Completed:"audit-test-base-completed",DisabledChanged:"audit-test-base-disabled-changed",NameChanged:"audit-test-base-name-changed",Progress:"audit-test-base-progress",ResultChanged:"audit-test-base-result-changed",Scheduled:"audit-test-base-scheduled",Stopping:"audit-test-base-stopping",SupportedChanged:"audit-test-base-supported-changed",TestChanged:"audit-test-base-test-changed",};WI.AuditTestCase=class AuditTestCase extends WI.AuditTestBase
{constructor(name,test,options={})
{super(name,options);this._test=test;} 
static async fromPayload(payload)
{if(typeof payload!=="object"||payload===null)
return null;if(payload.type!==WI.AuditTestCase.TypeIdentifier)
return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;}
if(typeof payload.test!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("test")));return null;}
let options={};if(typeof payload.description==="string")
options.description=payload.description;else if("description"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(typeof payload.supports==="number")
options.supports=payload.supports;else if("supports"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-number \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("supports")));if(typeof payload.setup==="string")
options.setup=payload.setup;else if("setup"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("setup")));if(typeof payload.disabled==="boolean")
options.disabled=payload.disabled;return new WI.AuditTestCase(payload.name,payload.test,options);} 
get test()
{return this._test;}
set test(test)
{if(test===this._test)
return;this._test=test;this.clearResult();this.dispatchEventToListeners(WI.AuditTestBase.Event.TestChanged);}
toJSON(key)
{let json=super.toJSON(key);json.test=this._test;return json;} 
async run()
{const levelStrings=Object.values(WI.AuditTestCaseResult.Level);let level=null;let data={};let metadata={url:WI.networkManager.mainFrame.url,startTimestamp:null,endTimestamp:null,};let resolvedDOMNodes=null;function setLevel(newLevel){let newLevelIndex=levelStrings.indexOf(newLevel);if(newLevelIndex<0){addError(WI.UIString("Return string must be one of %s").format(JSON.stringify(levelStrings)));return;}
if(newLevelIndex<=levelStrings.indexOf(level))
return;level=newLevel;}
function addError(value){setLevel(WI.AuditTestCaseResult.Level.Error);if(!data.errors)
data.errors=[];data.errors.push(value);}
async function parseResponse(response){let remoteObject=WI.RemoteObject.fromPayload(response.result,WI.mainTarget);if(response.wasThrown||(remoteObject.type==="object"&&remoteObject.subtype==="error")){addError(remoteObject.description);return;}
if(remoteObject.type==="boolean"){setLevel(remoteObject.value?WI.AuditTestCaseResult.Level.Pass:WI.AuditTestCaseResult.Level.Fail);return;}
if(remoteObject.type==="string"){setLevel(remoteObject.value.trim().toLowerCase());return;}
if(remoteObject.type!=="object"||remoteObject.subtype){addError(WI.UIString("Return value is not an object, string, or boolean"));return;}
const options={ownProperties:true,};function checkResultProperty(key,value,type,subtype){function addErrorForValueType(valueType){let errorString=null;if(valueType==="object"||valueType==="array")
errorString=WI.UIString("\u0022%s\u0022 must be an %s");else
errorString=WI.UIString("\u0022%s\u0022 must be a %s");addError(errorString.format(key,valueType));}
if(value.subtype!==subtype){addErrorForValueType(subtype);return null;}
if(value.type!==type){addErrorForValueType(type);return null;}
if(type==="boolean"||type==="string")
return value.value;return value;}
async function resultArrayForEach(key,value,callback){let array=checkResultProperty(key,value,"object","array");if(!array)
return;let arrayProperties=await new Promise((resolve,reject)=>array.getPropertyDescriptors(resolve,options));for(let i=0;i<array.size;++i){let arrayPropertyForIndex=arrayProperties.find((arrayProperty)=>arrayProperty.name===String(i));if(arrayPropertyForIndex)
await callback(arrayPropertyForIndex);}}
let properties=await new Promise((resolve,reject)=>remoteObject.getPropertyDescriptors(resolve,options));for(let property of properties){let key=property.name;if(key==="__proto__")
continue;let value=property.value;switch(key){case"level":{let levelString=checkResultProperty(key,value,"string");if(levelString)
setLevel(levelString.trim().toLowerCase());break;}
case"pass":if(checkResultProperty(key,value,"boolean"))
setLevel(WI.AuditTestCaseResult.Level.Pass);break;case"warn":if(checkResultProperty(key,value,"boolean"))
setLevel(WI.AuditTestCaseResult.Level.Warn);break;case"fail":if(checkResultProperty(key,value,"boolean"))
setLevel(WI.AuditTestCaseResult.Level.Fail);break;case"error":if(checkResultProperty(key,value,"boolean"))
setLevel(WI.AuditTestCaseResult.Level.Error);break;case"unsupported":if(checkResultProperty(key,value,"boolean"))
setLevel(WI.AuditTestCaseResult.Level.Unsupported);break;case"domNodes":await resultArrayForEach(key,value,async(item)=>{if(!item||!item.value||item.value.type!=="object"||item.value.subtype!=="node"){addError(WI.UIString("All items in \u0022%s\u0022 must be valid DOM nodes").format(WI.unlocalizedString("domNodes")));return;}
let domNodeId=await new Promise((resolve,reject)=>item.value.pushNodeToFrontend(resolve));let domNode=WI.domManager.nodeForId(domNodeId);if(!domNode)
return;if(!data.domNodes)
data.domNodes=[];data.domNodes.push(WI.cssPath(domNode,{full:true}));if(!resolvedDOMNodes)
resolvedDOMNodes=[];resolvedDOMNodes.push(domNode);});break;case"domAttributes":await resultArrayForEach(key,value,(item)=>{if(!item||!item.value||item.value.type!=="string"||!item.value.value.length){addError(WI.UIString("All items in \u0022%s\u0022 must be non-empty strings").format(WI.unlocalizedString("domAttributes")));return;}
if(!data.domAttributes)
data.domAttributes=[];data.domAttributes.push(item.value.value);});break;case"errors":await resultArrayForEach(key,value,(item)=>{if(!item||!item.value||item.value.type!=="object"||item.value.subtype!=="error"){addError(WI.UIString("All items in \u0022%s\u0022 must be error objects").format(WI.unlocalizedString("errors")));return;}
addError(item.value.description);});break;default:if(value.objectId){try{function inspectedPage_stringify(){return JSON.stringify(this);}
let stringifiedValue=await value.callFunction(inspectedPage_stringify);data[key]=JSON.parse(stringifiedValue.value);}catch{addError(WI.UIString("\u0022%s\u0022 is not JSON serializable").format(key));}}else
data[key]=value.value;break;}}}
let target=WI.assumingMainTarget();let agentCommandFunction=null;let agentCommandArguments={};if(target.hasDomain("Audit")){agentCommandFunction=target.AuditAgent.run;agentCommandArguments.test=this._test;}else{agentCommandFunction=target.RuntimeAgent.evaluate;agentCommandArguments.expression=`(function() { "use strict"; return eval(\`(${this._test.replace(/`/g,"\\`")})\`)(); })()`;agentCommandArguments.objectGroup=WI.AuditTestCase.ObjectGroup;agentCommandArguments.doNotPauseOnExceptionsAndMuteConsole=true;}
try{metadata.startTimestamp=new Date;let response=await agentCommandFunction.invoke(agentCommandArguments);metadata.endTimestamp=new Date;if(response.result.type==="object"&&response.result.className==="Promise"){if(WI.RuntimeManager.supportsAwaitPromise()){metadata.asyncTimestamp=metadata.endTimestamp;response=await target.RuntimeAgent.awaitPromise(response.result.objectId);metadata.endTimestamp=new Date;}else{response=null;addError(WI.UIString("Async audits are not supported."));setLevel(WI.AuditTestCaseResult.Level.Unsupported);}}
if(response)
await parseResponse(response);}catch(error){metadata.endTimestamp=new Date;addError(error.message);}
if(!level)
addError(WI.UIString("Missing result level"));let options={description:this.description,metadata,};if(!isEmptyObject(data))
options.data=data;if(resolvedDOMNodes)
options.resolvedDOMNodes=resolvedDOMNodes;this.updateResult(new WI.AuditTestCaseResult(this.name,level,options));}};WI.AuditTestCase.TypeIdentifier="test-case";WI.AuditTestGroup=class AuditTestGroup extends WI.AuditTestBase
{constructor(name,tests,options={})
{let disabled=options.disabled;options.disabled=false;super(name,options);this._tests=[];for(let test of tests)
this.addTest(test);if(disabled)
this.updateDisabled(true);} 
static async fromPayload(payload)
{if(typeof payload!=="object"||payload===null)
return null;if(payload.type!==WI.AuditTestGroup.TypeIdentifier)
return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;}
if(!Array.isArray(payload.tests)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("tests")));return null;}
let tests=await Promise.all(payload.tests.map(async(test)=>{let testCase=await WI.AuditTestCase.fromPayload(test);if(testCase)
return testCase;let testGroup=await WI.AuditTestGroup.fromPayload(test);if(testGroup)
return testGroup;return null;}));tests=tests.filter((test)=>!!test);if(!tests.length)
return null;let options={};if(typeof payload.description==="string")
options.description=payload.description;else if("description"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(typeof payload.supports==="number")
options.supports=payload.supports;else if("supports"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-number \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("supports")));if(typeof payload.setup==="string")
options.setup=payload.setup;else if("setup"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("setup")));if(typeof payload.disabled==="boolean")
options.disabled=payload.disabled;return new WI.AuditTestGroup(payload.name,tests,options);} 
get tests(){return this._tests;}
addTest(test)
{this._tests.push(test);test._parent=this;test.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCompleted,this);test.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);test.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestProgress,this);if(this.editable){test.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);test.addEventListener(WI.AuditTestBase.Event.TestChanged,this._handleTestChanged,this);}
this.dispatchEventToListeners(WI.AuditTestGroup.Event.TestAdded,{test});this.determineIfSupported();if(this._checkDisabled(test))
test.updateDisabled(true,{silent:true});}
removeTest(test)
{test.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCompleted,this);test.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);test.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestProgress,this);test.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);test.removeEventListener(WI.AuditTestBase.Event.TestChanged,this._handleTestChanged,this);this._tests.remove(test);test._parent=null;this.dispatchEventToListeners(WI.AuditTestGroup.Event.TestRemoved,{test});this.determineIfSupported();this._checkDisabled();}
stop()
{for(let test of this._tests)
test.stop();super.stop();}
clearResult(options={})
{let cleared=!!this.result;if(!options.excludeTests&&this._tests){for(let test of this._tests){if(test.clearResult(options))
cleared=true;}}
return super.clearResult({...options,suppressResultChangedEvent:!cleared,});}
toJSON(key)
{let json=super.toJSON(key);json.tests=this._tests.map((testCase)=>testCase.toJSON(key));return json;} 
async run()
{let count=this._tests.length;for(let index=0;index<count&&this._runningState===WI.AuditManager.RunningState.Active;++index){let test=this._tests[index];if(test.disabled||!test.supported)
continue;await test.start();if(test instanceof WI.AuditTestCase)
this.dispatchEventToListeners(WI.AuditTestBase.Event.Progress,{index,count});}
this.updateResult();}
determineIfSupported(options={})
{if(this._tests){for(let test of this._tests)
test.determineIfSupported({...options,warn:false,silent:true});}
return super.determineIfSupported(options);}
updateSupported(supported,options={})
{if(this._tests&&(!supported||this._tests.every((test)=>!test.supported))){supported=false;for(let test of this._tests)
test.updateSupported(supported,{silent:true});}
super.updateSupported(supported,options);}
updateDisabled(disabled,options={})
{if(!options.excludeTests&&this._tests){for(let test of this._tests)
test.updateDisabled(disabled,options);}
super.updateDisabled(disabled,options);}
updateResult()
{let results=this._tests.map((test)=>test.result).filter((result)=>!!result);if(!results.length)
return;super.updateResult(new WI.AuditTestGroupResult(this.name,results,{description:this.description,}));} 
_checkDisabled(test)
{let testDisabled=!test||!test.supported||test.disabled;let enabledTestCount=this._tests.filter((existing)=>existing.supported&&!existing.disabled).length;if(testDisabled&&!enabledTestCount)
this.updateDisabled(true);else if(!testDisabled&&enabledTestCount===1)
this.updateDisabled(false,{excludeTests:true});else{this.dispatchEventToListeners(WI.AuditTestBase.Event.DisabledChanged);}
return this.disabled;}
_handleTestCompleted(event)
{if(this._runningState===WI.AuditManager.RunningState.Active)
return;this.updateResult();this.dispatchEventToListeners(WI.AuditTestBase.Event.Completed);}
_handleTestDisabledChanged(event)
{this._checkDisabled(event.target);}
_handleTestProgress(event)
{if(this._runningState!==WI.AuditManager.RunningState.Active)
return;let walk=(tests)=>{let count=0;for(let test of tests){if(test.disabled||!test.supported)
continue;if(test instanceof WI.AuditTestCase)
++count;else if(test instanceof WI.AuditTestGroup)
count+=walk(test.tests);}
return count;};this.dispatchEventToListeners(WI.AuditTestBase.Event.Progress,{index:event.data.index+walk(this._tests.slice(0,this._tests.indexOf(event.target))),count:walk(this._tests),});}
_handleTestSupportedChanged(event)
{this.determineIfSupported();}
_handleTestChanged(event)
{this.clearResult({excludeTests:true});this.dispatchEventToListeners(WI.AuditTestBase.Event.TestChanged);}};WI.AuditTestGroup.TypeIdentifier="test-group";WI.AuditTestGroup.Event={TestAdded:"audit-test-group-test-added",TestRemoved:"audit-test-group-test-removed",};WI.AuditTestResultBase=class AuditTestResultBase
{constructor(name,{description}={})
{this._name=name;this._description=description||null;} 
get name(){return this._name;}
get description(){return this._description;}
get result()
{return this;}
get didPass()
{throw WI.NotImplementedError.subclassMustOverride();}
get didWarn()
{throw WI.NotImplementedError.subclassMustOverride();}
get didFail()
{throw WI.NotImplementedError.subclassMustOverride();}
get didError()
{throw WI.NotImplementedError.subclassMustOverride();}
get unsupported()
{throw WI.NotImplementedError.subclassMustOverride();}
get disabled()
{return false;}
get editable()
{return false;}
saveIdentityToCookie(cookie)
{cookie["audit-"+this.constructor.TypeIdentifier+"-name"]=this._name;}
toJSON()
{let json={type:this.constructor.TypeIdentifier,name:this._name,};if(this._description)
json.description=this._description;return json;}};WI.AuditTestCaseResult=class AuditTestCaseResult extends WI.AuditTestResultBase
{constructor(name,level,{description,data,metadata,resolvedDOMNodes}={})
{super(name,{description});this._level=level;this._data=data||{};this._metadata=metadata||{};this._resolvedDOMNodes=resolvedDOMNodes||[];} 
static async fromPayload(payload)
{if(typeof payload!=="object"||payload===null)
return null;if(payload.type!==WI.AuditTestCaseResult.TypeIdentifier)
return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;}
if(!Object.values(WI.AuditTestCaseResult.Level).includes(payload.level)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has an invalid \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("level")));return null;}
if(typeof payload.data!=="object"||payload.data===null){if("data"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("data")));payload.data={};}else{function checkArray(key){if(!(key in payload.data))
return;if(!Array.isArray(payload.data[key])){WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("data.%s").format(key)));payload.data[key]=[];}
payload.data[key]=payload.data[key].filter((item)=>typeof item==="string");}
checkArray("domNodes");checkArray("domAttributes");checkArray("errors");}
if(typeof payload.metadata!=="object"||payload.metadata===null){if("metadata"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata")));payload.metadata={};}else{if(typeof payload.metadata.startTimestamp==="string")
payload.metadata.startTimestamp=new Date(payload.metadata.startTimestamp);else{if("startTimestamp"in payload.metadata)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.startTimestamp")));payload.metadata.startTimestamp=null;}
if(typeof payload.metadata.asyncTimestamp==="string")
payload.metadata.asyncTimestamp=new Date(payload.metadata.asyncTimestamp);else{if("asyncTimestamp"in payload.metadata)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.asyncTimestamp")));payload.metadata.asyncTimestamp=null;}
if(typeof payload.metadata.endTimestamp==="string")
payload.metadata.endTimestamp=new Date(payload.metadata.endTimestamp);else{if("endTimestamp"in payload.metadata)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.endTimestamp")));payload.metadata.endTimestamp=null;}
if(typeof payload.metadata.url!=="string"){if("url"in payload.metadata)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.url")));payload.metadata.url=null;}}
let options={};if(typeof payload.description==="string")
options.description=payload.description;else if("description"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(!isEmptyObject(payload.data)){options.data={};for(let key in payload.data){if(key==="domNodes"||key==="domAttributes"||key==="errors"){if(!payload.data[key].length)
continue;}
if(key==="domNodes"){if(InspectorBackend.hasDomain("DOM")&&(!payload.metadata.url||payload.metadata.url===WI.networkManager.mainFrame.url)){let documentNode=await new Promise((resolve)=>WI.domManager.requestDocument(resolve));options.resolvedDOMNodes=await Promise.all(payload.data.domNodes.map(async(domNodeString)=>{let nodeId=0;try{nodeId=await documentNode.querySelector(domNodeString);}catch{}
return WI.domManager.nodeForId(nodeId);}));}}
options.data[key]=payload.data[key];}}
if(!isEmptyObject(payload.metadata)){options.metadata={};if(payload.metadata.startTimestamp&&!isNaN(payload.metadata.startTimestamp))
options.metadata.startTimestamp=payload.metadata.startTimestamp;if(payload.metadata.asyncTimestamp&&!isNaN(payload.metadata.asyncTimestamp))
options.metadata.asyncTimestamp=payload.metadata.asyncTimestamp;if(payload.metadata.endTimestamp&&!isNaN(payload.metadata.endTimestamp))
options.metadata.endTimestamp=payload.metadata.endTimestamp;if(payload.metadata.url)
options.metadata.url=payload.metadata.url;}
return new WI.AuditTestCaseResult(payload.name,payload.level,options);} 
get level(){return this._level;}
get data(){return this._data;}
get metadata(){return this._metadata;}
get resolvedDOMNodes(){return this._resolvedDOMNodes;}
get result()
{return this;}
get didPass()
{return this._level===WI.AuditTestCaseResult.Level.Pass;}
get didWarn()
{return this._level===WI.AuditTestCaseResult.Level.Warn;}
get didFail()
{return this._level===WI.AuditTestCaseResult.Level.Fail;}
get didError()
{return this._level===WI.AuditTestCaseResult.Level.Error;}
get unsupported()
{return this._level===WI.AuditTestCaseResult.Level.Unsupported;}
toJSON()
{let json=super.toJSON();json.level=this._level;let data={};for(let key in this._data){if(key==="domNodes"||key==="domAttributes"||key==="errors"){if(!this._data[key].length)
continue;}
data[key]=this._data[key];}
if(!isEmptyObject(data))
json.data=data;let metadata={};if(this._metadata.startTimestamp&&!isNaN(this._metadata.startTimestamp))
metadata.startTimestamp=this._metadata.startTimestamp;if(this._metadata.asyncTimestamp&&!isNaN(this._metadata.asyncTimestamp))
metadata.asyncTimestamp=this._metadata.asyncTimestamp;if(this._metadata.endTimestamp&&!isNaN(this._metadata.endTimestamp))
metadata.endTimestamp=this._metadata.endTimestamp;if(this._metadata.url)
metadata.url=this._metadata.url;if(!isEmptyObject(metadata))
json.metadata=metadata;return json;}};WI.AuditTestCaseResult.TypeIdentifier="test-case-result";WI.AuditTestCaseResult.Level={Pass:"pass",Warn:"warn",Fail:"fail",Error:"error",Unsupported:"unsupported",};WI.AuditTestGroupResult=class AuditTestGroupResult extends WI.AuditTestResultBase
{constructor(name,results,{description}={})
{super(name,{description});this._results=results;} 
static async fromPayload(payload)
{if(typeof payload!=="object"||payload===null)
return null;if(payload.type!==WI.AuditTestGroupResult.TypeIdentifier)
return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;}
if(!Array.isArray(payload.results)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("results")));return null;}
let results=await Promise.all(payload.results.map(async(test)=>{let testCaseResult=await WI.AuditTestCaseResult.fromPayload(test);if(testCaseResult)
return testCaseResult;let testGroupResult=await WI.AuditTestGroupResult.fromPayload(test);if(testGroupResult)
return testGroupResult;return null;}));results=results.filter((result)=>!!result);if(!results.length)
return null;let options={};if(typeof payload.description==="string")
options.description=payload.description;else if("description"in payload)
WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));return new WI.AuditTestGroupResult(payload.name,results,options);} 
get results(){return this._results;}
get levelCounts()
{let counts={};for(let level of Object.values(WI.AuditTestCaseResult.Level))
counts[level]=0;for(let result of this._results){if(result instanceof WI.AuditTestCaseResult)
++counts[result.level];else if(result instanceof WI.AuditTestGroupResult){for(let[level,count]of Object.entries(result.levelCounts))
counts[level]+=count;}}
return counts;}
get didPass()
{return this._results.some((result)=>result.didPass);}
get didWarn()
{return this._results.some((result)=>result.didWarn);}
get didFail()
{return this._results.some((result)=>result.didFail);}
get didError()
{return this._results.some((result)=>result.didError);}
get unsupported()
{return this._results.some((result)=>result.unsupported);}
toJSON()
{let json=super.toJSON();json.results=this._results.map((result)=>result.toJSON());return json;}};WI.AuditTestGroupResult.TypeIdentifier="test-group-result";WI.FormatterWorkerProxy=class FormatterWorkerProxy
{constructor()
{this._formatterWorker=new Worker("Workers/Formatter/FormatterWorker.js");this._formatterWorker.addEventListener("message",this._handleMessage.bind(this));this._nextCallId=1;this._callbacks=new Map;} 
static singleton()
{if(!FormatterWorkerProxy.instance)
FormatterWorkerProxy.instance=new FormatterWorkerProxy;return FormatterWorkerProxy.instance;} 
formatJavaScript(sourceText,isModule,indentString,includeSourceMapData)
{this.performAction("formatJavaScript",...arguments);}
formatCSS(sourceText,indentString,includeSourceMapData)
{this.performAction("formatCSS",...arguments);}
formatHTML(sourceText,indentString,includeSourceMapData)
{this.performAction("formatHTML",...arguments);}
formatXML(sourceText,indentString,includeSourceMapData)
{this.performAction("formatXML",...arguments);} 
performAction(actionName)
{let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let actionArguments=Array.prototype.slice.call(arguments,1,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,actionName,actionArguments});} 
_postMessage()
{this._formatterWorker.postMessage(...arguments);}
_handleMessage(event)
{let data=event.data;if(data.callId){let callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);return;}
console.error("Unexpected FormatterWorker message",data);}};WI.HeapSnapshotDiffProxy=class HeapSnapshotDiffProxy extends WI.Object
{constructor(snapshotDiffObjectId,snapshot1,snapshot2,totalSize,totalObjectCount,categories)
{super();this._proxyObjectId=snapshotDiffObjectId;this._snapshot1=snapshot1;this._snapshot2=snapshot2;this._totalSize=totalSize;this._totalObjectCount=totalObjectCount;this._categories=Map.fromObject(categories);} 
static deserialize(objectId,serializedSnapshotDiff)
{let{snapshot1:serializedSnapshot1,snapshot2:serializedSnapshot2,totalSize,totalObjectCount,categories}=serializedSnapshotDiff;
let snapshot1=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot1);let snapshot2=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot2);return new WI.HeapSnapshotDiffProxy(objectId,snapshot1,snapshot2,totalSize,totalObjectCount,categories);} 
get snapshot1(){return this._snapshot1;}
get snapshot2(){return this._snapshot2;}
get totalSize(){return this._totalSize;}
get totalObjectCount(){return this._totalObjectCount;}
get categories(){return this._categories;}
get invalid(){return this._snapshot1.invalid||this._snapshot2.invalid;}
updateForCollectionEvent(event)
{if(!event.data.affectedSnapshots.includes(this._snapshot2._identifier))
return;this.update(()=>{this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.CollectedNodes,event.data);});}
allocationBucketCounts(bucketSizes,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"allocationBucketCounts",bucketSizes,callback);}
instancesWithClassName(className,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"instancesWithClassName",className,(serializedNodes)=>{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});}
update(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"update",({liveSize,categories})=>{this._categories=Map.fromObject(categories);callback();});}
nodeWithIdentifier(nodeIdentifier,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"nodeWithIdentifier",nodeIdentifier,(serializedNode)=>{callback(WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,serializedNode));});}};WI.HeapSnapshotEdgeProxy=class HeapSnapshotEdgeProxy
{constructor(objectId,fromIdentifier,toIdentifier,type,data)
{this._proxyObjectId=objectId;this.fromIdentifier=fromIdentifier;this.toIdentifier=toIdentifier;this.type=type;this.data=data;this.from=null;this.to=null;}
isPrivateSymbol()
{if(WI.settings.engineeringShowPrivateSymbolsInHeapSnapshot.value)
return false;return typeof this.data==="string"&&this.data.startsWith("PrivateSymbol");} 
static deserialize(objectId,serializedEdge)
{let{from,to,type,data}=serializedEdge;return new WI.HeapSnapshotEdgeProxy(objectId,from,to,type,data);}};WI.HeapSnapshotEdgeProxy.EdgeType={Internal:"Internal",Property:"Property",Index:"Index",Variable:"Variable",};WI.HeapSnapshotNodeProxy=class HeapSnapshotNodeProxy
{constructor(snapshotObjectId,{id,className,size,retainedSize,internal,isObjectType,gcRoot,dead,dominatorNodeIdentifier,hasChildren})
{this._proxyObjectId=snapshotObjectId;this.id=id;this.className=className;this.size=size;this.retainedSize=retainedSize;this.internal=internal;this.isObjectType=isObjectType;this.gcRoot=gcRoot;this.dead=dead;this.dominatorNodeIdentifier=dominatorNodeIdentifier;this.hasChildren=hasChildren;} 
static deserialize(objectId,serializedNode)
{return new WI.HeapSnapshotNodeProxy(objectId,serializedNode);} 
shortestGCRootPath(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"shortestGCRootPath",this.id,(serializedPath)=>{let isNode=false;let path=serializedPath.map((component)=>{isNode=!isNode;if(isNode)
return WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,component);return WI.HeapSnapshotEdgeProxy.deserialize(this._proxyObjectId,component);});for(let i=1;i<path.length;i+=2){let edge=path[i];edge.from=path[i-1];edge.to=path[i+1];}
callback(path);});}
dominatedNodes(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"dominatedNodes",this.id,(serializedNodes)=>{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});}
retainedNodes(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"retainedNodes",this.id,({retainedNodes:serializedNodes,edges:serializedEdges})=>{let deserializedNodes=serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId));let deserializedEdges=serializedEdges.map(WI.HeapSnapshotEdgeProxy.deserialize.bind(null,this._proxyObjectId));callback(deserializedNodes,deserializedEdges);});}
retainers(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"retainers",this.id,({retainers:serializedNodes,edges:serializedEdges})=>{let deserializedNodes=serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId));let deserializedEdges=serializedEdges.map(WI.HeapSnapshotEdgeProxy.deserialize.bind(null,this._proxyObjectId));callback(deserializedNodes,deserializedEdges);});}};WI.HeapSnapshotProxy=class HeapSnapshotProxy extends WI.Object
{constructor(snapshotObjectId,identifier,title,totalSize,totalObjectCount,liveSize,categories,imported)
{super();this._proxyObjectId=snapshotObjectId;this._identifier=identifier;this._title=title;this._totalSize=totalSize;this._totalObjectCount=totalObjectCount;this._liveSize=liveSize;this._categories=Map.fromObject(categories);this._imported=imported;this._snapshotStringData=null;if(!WI.HeapSnapshotProxy.ValidSnapshotProxies)
WI.HeapSnapshotProxy.ValidSnapshotProxies=[];WI.HeapSnapshotProxy.ValidSnapshotProxies.push(this);} 
static deserialize(objectId,serializedSnapshot)
{let{identifier,title,totalSize,totalObjectCount,liveSize,categories,imported}=serializedSnapshot;return new WI.HeapSnapshotProxy(objectId,identifier,title,totalSize,totalObjectCount,liveSize,categories,imported);}
static invalidateSnapshotProxies()
{if(!WI.HeapSnapshotProxy.ValidSnapshotProxies)
return;for(let snapshotProxy of WI.HeapSnapshotProxy.ValidSnapshotProxies)
snapshotProxy._invalidate();WI.HeapSnapshotProxy.ValidSnapshotProxies=null;} 
get proxyObjectId(){return this._proxyObjectId;}
get identifier(){return this._identifier;}
get title(){return this._title;}
get totalSize(){return this._totalSize;}
get totalObjectCount(){return this._totalObjectCount;}
get liveSize(){return this._liveSize;}
get categories(){return this._categories;}
get imported(){return this._imported;}
get invalid(){return this._proxyObjectId===0;}
get snapshotStringData()
{return this._snapshotStringData;}
set snapshotStringData(data)
{this._snapshotStringData=data;}
updateForCollectionEvent(event)
{if(!event.data.affectedSnapshots.includes(this._identifier))
return;this.update(()=>{this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.CollectedNodes,event.data);});}
allocationBucketCounts(bucketSizes,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"allocationBucketCounts",bucketSizes,callback);}
instancesWithClassName(className,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"instancesWithClassName",className,(serializedNodes)=>{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});}
update(callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"update",({liveSize,categories})=>{this._liveSize=liveSize;this._categories=Map.fromObject(categories);callback();});}
nodeWithIdentifier(nodeIdentifier,callback)
{WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"nodeWithIdentifier",nodeIdentifier,(serializedNode)=>{callback(WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,serializedNode));});} 
_invalidate()
{this._proxyObjectId=0;this._liveSize=0;this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.Invalidated);}};WI.HeapSnapshotProxy.Event={CollectedNodes:"heap-snapshot-proxy-collected-nodes",Invalidated:"heap-snapshot-proxy-invalidated",};WI.HeapSnapshotWorkerProxy=class HeapSnapshotWorkerProxy extends WI.Object
{constructor()
{super();this._heapSnapshotWorker=new Worker("Workers/HeapSnapshot/HeapSnapshotWorker.js");this._heapSnapshotWorker.addEventListener("message",this._handleMessage.bind(this));this._nextCallId=1;this._callbacks=new Map;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} 
static singleton()
{if(!HeapSnapshotWorkerProxy.instance)
HeapSnapshotWorkerProxy.instance=new HeapSnapshotWorkerProxy;return HeapSnapshotWorkerProxy.instance;} 
clearSnapshots(callback)
{this.performAction("clearSnapshots",callback);}
createSnapshot(snapshotStringData,callback)
{this.performAction("createSnapshot",...arguments);}
createSnapshotDiff(objectId1,objectId2,callback)
{this.performAction("createSnapshotDiff",...arguments);}
createImportedSnapshot(snapshotStringData,title,callback)
{const imported=true;this.performAction("createSnapshot",snapshotStringData,title,imported,callback);} 
performAction(actionName)
{let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let actionArguments=Array.prototype.slice.call(arguments,1,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,actionName,actionArguments});}
callMethod(objectId,methodName)
{let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let methodArguments=Array.prototype.slice.call(arguments,2,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,objectId,methodName,methodArguments});} 
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this.clearSnapshots(()=>{WI.HeapSnapshotProxy.invalidateSnapshotProxies();});}
_postMessage()
{this._heapSnapshotWorker.postMessage(...arguments);}
_handleMessage(event)
{let data=event.data;if(data.error){this._callbacks.delete(data.callId);return;}
if(data.eventName){this.dispatchEventToListeners(data.eventName,data.eventData);return;}
if(data.callId){let callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);return;}
console.error("Unexpected HeapSnapshotWorker message",data);}};WI.HeapSnapshotWorkerProxy.Event={Collection:"heap-snapshot-collection",};WI.View=class View extends WI.Object
{constructor(element)
{super();this._element=element||document.createElement("div");this._element.__view=this;this._parentView=null;this._subviews=[];this._dirty=false;this._dirtyDescendantsCount=0;this._isAttachedToRoot=false;this._layoutReason=null;this._didInitialLayout=false;} 
static fromElement(element)
{if(!element||!(element instanceof HTMLElement))
return null;if(element.__view instanceof WI.View)
return element.__view;return null;}
static rootView()
{if(!WI.View._rootView){
WI.View._rootView=new WI.View(document.body);WI.View._rootView._isAttachedToRoot=true;}
return WI.View._rootView;} 
get element(){return this._element;}
get layoutPending(){return this._dirty;}
get parentView(){return this._parentView;}
get subviews(){return this._subviews;}
get isAttached(){return this._isAttachedToRoot;}
isDescendantOf(view)
{let parentView=this._parentView;while(parentView){if(parentView===view)
return true;parentView=parentView.parentView;}
return false;}
addSubview(view)
{this.insertSubviewBefore(view,null);}
insertSubviewBefore(view,referenceView)
{if(this._subviews.includes(view)){return;}
const beforeIndex=referenceView?this._subviews.indexOf(referenceView):this._subviews.length;if(beforeIndex===-1){return;}
this._subviews.insertAtIndex(view,beforeIndex);if(!view.element.parentNode)
this._element.insertBefore(view.element,referenceView?referenceView.element:null);view._didMoveToParent(this);}
removeSubview(view)
{let index=this._subviews.lastIndexOf(view);if(index===-1){return;}
view._didMoveToParent(null);this._subviews.splice(index,1);view.element.remove();}
removeAllSubviews()
{for(let subview of this._subviews)
subview._didMoveToParent(null);this._subviews=[];this._element.removeChildren();}
replaceSubview(oldView,newView)
{if(oldView===newView)
return;this.insertSubviewBefore(newView,oldView);this.removeSubview(oldView);}
updateLayout(layoutReason)
{this.cancelLayout();this._setLayoutReason(layoutReason);this._layoutSubtree();}
updateLayoutIfNeeded(layoutReason)
{if(!this._dirty&&this._didInitialLayout)
return;this.updateLayout(layoutReason);}
needsLayout(layoutReason)
{this._setLayoutReason(layoutReason);if(this._dirty)
return;WI.View._scheduleLayoutForView(this);}
cancelLayout()
{WI.View._cancelScheduledLayoutForView(this);} 
get layoutReason(){return this._layoutReason;}
get didInitialLayout(){return this._didInitialLayout;}
attached()
{}
detached()
{}
initialLayout()
{
}
layout()
{}
didLayoutSubtree()
{}
sizeDidChange()
{} 
_didMoveToParent(parentView)
{this._parentView=parentView;let isAttachedToRoot=this.isDescendantOf(WI.View._rootView);this._didMoveToWindow(isAttachedToRoot);if(!this._parentView)
return;let pendingLayoutsCount=this._dirtyDescendantsCount;if(this._dirty)
pendingLayoutsCount++;let view=this._parentView;while(view){view._dirtyDescendantsCount+=pendingLayoutsCount;view=view.parentView;}}
_didMoveToWindow(isAttachedToRoot)
{if(this._isAttachedToRoot===isAttachedToRoot)
return;this._isAttachedToRoot=isAttachedToRoot;if(this._isAttachedToRoot){WI.View._scheduleLayoutForView(this);this.attached();}else{if(this._dirty)
this.cancelLayout();this.detached();}
for(let view of this._subviews)
view._didMoveToWindow(isAttachedToRoot);}
_layoutSubtree()
{this._dirty=false;this._dirtyDescendantsCount=0;let isInitialLayout=!this._didInitialLayout;if(isInitialLayout){this.initialLayout();this._didInitialLayout=true;}
if(this._layoutReason===WI.View.LayoutReason.Resize||isInitialLayout){this.sizeDidChange();}
let savedLayoutReason=this._layoutReason;if(isInitialLayout){this._setLayoutReason();}
this.layout();this._layoutReason=savedLayoutReason;if(WI.settings.debugEnableLayoutFlashing.value)
this._drawLayoutFlashingOutline(isInitialLayout);for(let view of this._subviews){view._setLayoutReason(this._layoutReason);view._layoutSubtree();}
this._layoutReason=null;this.didLayoutSubtree();}
_setLayoutReason(layoutReason)
{this._layoutReason=layoutReason||WI.View.LayoutReason.Dirty;}
_drawLayoutFlashingOutline(isInitialLayout)
{if(this._layoutFlashingTimeout)
clearTimeout(this._layoutFlashingTimeout);else
this._layoutFlashingPreviousOutline=this._element.style.outline;let hue=isInitialLayout?20:40;this._element.style.outline=`1px solid hsla(${hue}, 100%, 51%, 0.8)`;this._layoutFlashingTimeout=setTimeout(()=>{if(this._element)
this._element.style.outline=this._layoutFlashingPreviousOutline;this._layoutFlashingTimeout=undefined;this._layoutFlashingPreviousOutline=null;},500);} 
static _scheduleLayoutForView(view)
{view._dirty=true;let parentView=view.parentView;while(parentView){parentView._dirtyDescendantsCount++;parentView=parentView.parentView;}
if(!view._isAttachedToRoot)
return;if(WI.View._scheduledLayoutUpdateIdentifier)
return;WI.View._scheduledLayoutUpdateIdentifier=requestAnimationFrame(WI.View._visitViewTreeForLayout);}
static _cancelScheduledLayoutForView(view)
{let cancelledLayoutsCount=view._dirtyDescendantsCount;if(view.layoutPending)
cancelledLayoutsCount++;let parentView=view.parentView;while(parentView){parentView._dirtyDescendantsCount=Math.max(0,parentView._dirtyDescendantsCount-cancelledLayoutsCount);parentView=parentView.parentView;}
view._dirty=false;if(!WI.View._scheduledLayoutUpdateIdentifier)
return;let rootView=WI.View._rootView;if(!rootView||rootView._dirtyDescendantsCount)
return;cancelAnimationFrame(WI.View._scheduledLayoutUpdateIdentifier);WI.View._scheduledLayoutUpdateIdentifier=undefined;}
static _visitViewTreeForLayout()
{WI.View._scheduledLayoutUpdateIdentifier=undefined;let views=[WI.View._rootView];while(views.length){let view=views.shift();if(view.layoutPending)
view._layoutSubtree();else if(view._dirtyDescendantsCount){views.pushAll(view.subviews);view._dirtyDescendantsCount=0;}}}};WI.View.LayoutReason={Dirty:Symbol("layout-reason-dirty"),Resize:Symbol("layout-reason-resize")};WI.View._rootView=null;WI.View._scheduledLayoutUpdateIdentifier=undefined;WI.SelectionController=class SelectionController extends WI.Object
{constructor(delegate,comparator)
{super();this._delegate=delegate;this._comparator=comparator;this._allowsEmptySelection=true;this._allowsMultipleSelection=false;this._lastSelectedItem=null;this._shiftAnchorItem=null;this._selectedItems=new Set;this._suppressSelectionDidChange=false;} 
static createTreeComparator(itemForRepresentedObject)
{return(a,b)=>{a=itemForRepresentedObject(a);b=itemForRepresentedObject(b);if(!a||!b)
return 0;let getLevel=(item)=>{let level=0;while(item=item.parent)
level++;return level;};let compareSiblings=(s,t)=>{return s.parent.children.indexOf(s)-s.parent.children.indexOf(t);};if(a.parent===b.parent)
return compareSiblings(a,b);let aLevel=getLevel(a);let bLevel=getLevel(b);while(aLevel>bLevel){if(a.parent===b)
return 1;a=a.parent;aLevel--;}
while(bLevel>aLevel){if(b.parent===a)
return-1;b=b.parent;bLevel--;}
while(a.parent!==b.parent){a=a.parent;b=b.parent;}
return compareSiblings(a,b);};}
static createListComparator(indexForRepresentedObject)
{return(a,b)=>{return indexForRepresentedObject(a)-indexForRepresentedObject(b);};} 
get delegate(){return this._delegate;}
get lastSelectedItem(){return this._lastSelectedItem;}
get selectedItems(){return this._selectedItems;}
get allowsEmptySelection(){return this._allowsEmptySelection;}
set allowsEmptySelection(flag){this._allowsEmptySelection=flag;}
get allowsMultipleSelection()
{return this._allowsMultipleSelection;}
set allowsMultipleSelection(flag)
{if(this._allowsMultipleSelection===flag)
return;this._allowsMultipleSelection=flag;if(this._allowsMultipleSelection)
return;if(this._selectedItems.size>1)
this._updateSelectedItems(new Set([this._lastSelectedItem]));}
hasSelectedItem(item)
{return this._selectedItems.has(item);}
selectItem(item,extendSelection=false)
{if(!this._allowsMultipleSelection)
extendSelection=false;this._lastSelectedItem=item;this._shiftAnchorItem=null;let newItems=new Set(extendSelection?this._selectedItems:null);newItems.add(item);this._updateSelectedItems(newItems);}
selectItems(items)
{if(!this._allowsMultipleSelection)
return;if(!this._lastSelectedItem||!items.has(this._lastSelectedItem))
this._lastSelectedItem=items.lastValue;if(!this._shiftAnchorItem||!items.has(this._shiftAnchorItem))
this._shiftAnchorItem=this._lastSelectedItem;this._updateSelectedItems(items);}
deselectItem(item)
{if(!this.hasSelectedItem(item))
return;if(!this._allowsEmptySelection&&this._selectedItems.size===1)
return;let newItems=new Set(this._selectedItems);newItems.delete(item);if(this._lastSelectedItem===item){this._lastSelectedItem=null;if(newItems.size){const operation=WI.SelectionController.Operation.Extend;let previous=item;let next=item;while(!this._lastSelectedItem&&previous&&next){previous=this._previousSelectableItem(previous,operation);if(this.hasSelectedItem(previous)){this._lastSelectedItem=previous;break;}
next=this._nextSelectableItem(next,operation);if(this.hasSelectedItem(next)){this._lastSelectedItem=next;break;}}}}
if(this._shiftAnchorItem===item)
this._shiftAnchorItem=null;this._updateSelectedItems(newItems);}
selectAll()
{if(!this._allowsMultipleSelection)
return;const operation=WI.SelectionController.Operation.Extend;let newItems=new Set;this._addRange(newItems,this._firstSelectableItem(operation),this._lastSelectableItem(operation));this.selectItems(newItems);}
deselectAll()
{this._deselectAllAndSelect(null);}
removeSelectedItems()
{if(!this._selectedItems.size)
return;let operation=this._allowsMultipleSelection?WI.SelectionController.Operation.Extend:WI.SelectionController.Operation.Direct;let orderedSelection=Array.from(this._selectedItems).sort(this._comparator);let firstSelectedItem=orderedSelection[0];let itemToSelect=this._previousSelectableItem(firstSelectedItem,operation);if(!itemToSelect){
itemToSelect=firstSelectedItem;while(itemToSelect&&this.hasSelectedItem(itemToSelect))
itemToSelect=this._nextSelectableItem(itemToSelect,operation);if(!itemToSelect||this.hasSelectedItem(itemToSelect)){
itemToSelect=this._nextSelectableItem(orderedSelection.lastValue,operation);}}
this._deselectAllAndSelect(itemToSelect);}
reset()
{this._lastSelectedItem=null;this._shiftAnchorItem=null;this._selectedItems.clear();}
didRemoveItems(items)
{if(!items.size||!this._selectedItems.size)
return;this._updateSelectedItems(this._selectedItems.difference(items));}
handleKeyDown(event)
{if(event.key==="a"&&event.commandOrControlKey){this.selectAll();return true;}
if(event.metaKey||event.ctrlKey)
return false;if(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"){this._selectItemsFromArrowKey(event.keyIdentifier==="Up",event.shiftKey);event.preventDefault();event.stopPropagation();return true;}
return false;}
handleItemMouseDown(item,event)
{if(event.button!==0||event.ctrlKey)
return;
if(event.commandOrControlKey){if(this.hasSelectedItem(item))
this.deselectItem(item);else
this.selectItem(item,this._allowsMultipleSelection);return;}
let shiftExtendSelection=this._allowsMultipleSelection&&event.shiftKey;if(!shiftExtendSelection){this.selectItem(item);return;}
let newItems=new Set(this._selectedItems);
if(!newItems.size){this._lastSelectedItem=item;this._shiftAnchorItem=this._firstSelectableItem(WI.SelectionController.Operation.Extend);this._addRange(newItems,this._shiftAnchorItem,this._lastSelectedItem);this._updateSelectedItems(newItems);return;}
if(!this._shiftAnchorItem)
this._shiftAnchorItem=this._lastSelectedItem;

let sortItemPair=(a,b)=>{return[a,b].sort(this._comparator);};if(this._shiftAnchorItem!==this._lastSelectedItem){let[startItem,endItem]=sortItemPair(this._shiftAnchorItem,this._lastSelectedItem);this._deleteRange(newItems,startItem,endItem);}
let[startItem,endItem]=sortItemPair(this._shiftAnchorItem,item);this._addRange(newItems,startItem,endItem);this._lastSelectedItem=item;this._updateSelectedItems(newItems);} 
_deselectAllAndSelect(item)
{if(!this._selectedItems.size&&!item)
return;if(this._selectedItems.size===1&&this.hasSelectedItem(item))
return;this._lastSelectedItem=item;this._shiftAnchorItem=null;let newItems=new Set;if(item)
newItems.add(item);this._updateSelectedItems(newItems);}
_selectItemsFromArrowKey(goingUp,shiftKey)
{let extendSelection=shiftKey&&this._allowsMultipleSelection;let operation=extendSelection?WI.SelectionController.Operation.Extend:WI.SelectionController.Operation.Direct;if(!this._selectedItems.size){this.selectItem(goingUp?this._lastSelectableItem(operation):this._firstSelectableItem(operation));return;}
let item=goingUp?this._previousSelectableItem(this._lastSelectedItem,operation):this._nextSelectableItem(this._lastSelectedItem,operation);if(!item)
return;if(!extendSelection||!this.hasSelectedItem(item)){this.selectItem(item,extendSelection);return;}


let priorItem=goingUp?this._nextSelectableItem(this._lastSelectedItem,operation):this._previousSelectableItem(this._lastSelectedItem,operation);if(!priorItem||!this.hasSelectedItem(priorItem)){this.deselectItem(this._lastSelectedItem);return;}


while(item){if(!this.hasSelectedItem(item)){this.selectItem(item,extendSelection);break;}
this._lastSelectedItem=item;item=goingUp?this._previousSelectableItem(item,operation):this._nextSelectableItem(item,operation);}}
_firstSelectableItem(operation)
{return this._delegate.selectionControllerFirstSelectableItem(this,operation);}
_lastSelectableItem(operation)
{return this._delegate.selectionControllerLastSelectableItem(this,operation);}
_previousSelectableItem(item,operation)
{return this._delegate.selectionControllerPreviousSelectableItem(this,item,operation);}
_nextSelectableItem(item,operation)
{return this._delegate.selectionControllerNextSelectableItem(this,item,operation);}
_updateSelectedItems(items)
{let oldSelectedItems=this._selectedItems;this._selectedItems=items;if(this._suppressSelectionDidChange||!this._delegate.selectionControllerSelectionDidChange)
return;let deselectedItems=oldSelectedItems.difference(items);let selectedItems=items.difference(oldSelectedItems);if(deselectedItems.size||selectedItems.size)
this._delegate.selectionControllerSelectionDidChange(this,deselectedItems,selectedItems);}
_addRange(items,firstItem,lastItem)
{const operation=WI.SelectionController.Operation.Extend;let current=firstItem;while(current){items.add(current);if(current===lastItem)
break;current=this._nextSelectableItem(current,operation);}}
_deleteRange(items,firstItem,lastItem)
{const operation=WI.SelectionController.Operation.Extend;let current=firstItem;while(current){items.delete(current);if(current===lastItem)
break;current=this._nextSelectableItem(current,operation);}}};WI.SelectionController.Operation={Direct:Symbol("selection-operation-direct"),Extend:Symbol("selection-operation-extend"),};WI.ConsoleCommandView=class ConsoleCommandView
{constructor(commandText,className)
{this._commandText=commandText;this._className=className||"";} 
render()
{this._element=document.createElement("div");this._element.classList.add("console-user-command");this._element.dir="ltr";this._element.setAttribute("data-labelprefix",WI.UIString("Input: "));if(this._className)
this._element.classList.add(this._className);this._formattedCommandElement=this._element.appendChild(document.createElement("span"));this._formattedCommandElement.classList.add("console-message-body");this._formattedCommandElement.textContent=this._commandText; this._element.__commandView=this;}
get element()
{return this._element;}
get commandText()
{return this._commandText;}
toClipboardString(isPrefixOptional)
{return(isPrefixOptional?"":"> ")+this._commandText.removeWordBreakCharacters();}};WI.ConsoleMessageView=class ConsoleMessageView extends WI.Object
{constructor(message)
{super();this._message=message;this._expandable=false;this._repeatCount=message._repeatCount||0;this._extraParameters=message.parameters;} 
render()
{this._element=document.createElement("div");this._element.classList.add("console-message");this._element.dir="ltr"; this._element.__message=this._message;this._element.__messageView=this;if(this._message.type===WI.ConsoleMessage.MessageType.Result){this._element.classList.add("console-user-command-result");this._element.setAttribute("data-labelprefix",WI.UIString("Output: "));}else if(this._message.type===WI.ConsoleMessage.MessageType.StartGroup||this._message.type===WI.ConsoleMessage.MessageType.StartGroupCollapsed)
this._element.classList.add("console-group-title");switch(this._message.level){case WI.ConsoleMessage.MessageLevel.Log:this._element.classList.add("console-log-level");this._element.setAttribute("data-labelprefix",WI.UIString("Log: "));break;case WI.ConsoleMessage.MessageLevel.Info:this._element.classList.add("console-info-level");this._element.setAttribute("data-labelprefix",WI.UIString("Info: "));break;case WI.ConsoleMessage.MessageLevel.Debug:this._element.classList.add("console-debug-level");this._element.setAttribute("data-labelprefix",WI.UIString("Debug: "));break;case WI.ConsoleMessage.MessageLevel.Warning:this._element.classList.add("console-warning-level");this._element.setAttribute("data-labelprefix",WI.UIString("Warning: "));break;case WI.ConsoleMessage.MessageLevel.Error:this._element.classList.add("console-error-level");this._element.setAttribute("data-labelprefix",WI.UIString("Error: "));break;}
this._appendLocationLink();this._messageBodyElement=this._element.appendChild(document.createElement("span"));this._messageBodyElement.classList.add("console-top-level-message","console-message-body");this._appendMessageTextAndArguments(this._messageBodyElement);this._appendSavedResultIndex();this._appendExtraParameters();this._appendStackTrace();this._renderRepeatCount();if(this._message.type===WI.ConsoleMessage.MessageType.Dir)
this.expand();else if(this._message.type===WI.ConsoleMessage.MessageType.Image){this._element.classList.add("console-image");this._element.addEventListener("contextmenu",this._handleContextMenu.bind(this));}
WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._handleDebuggerBlackboxChanged,this);}
get element()
{return this._element;}
get message()
{return this._message;}
get repeatCount()
{return this._repeatCount;}
set repeatCount(count)
{if(this._repeatCount===count)
return;this._repeatCount=count;if(this._element)
this._renderRepeatCount();}
_renderRepeatCount()
{let count=this._repeatCount;if(count<=1){if(this._repeatCountElement){this._repeatCountElement.remove();this._repeatCountElement=null;}
return;}
if(!this._repeatCountElement){this._repeatCountElement=document.createElement("span");this._repeatCountElement.classList.add("repeat-count");this._element.insertBefore(this._repeatCountElement,this._element.firstChild);}
this._repeatCountElement.textContent=Number.abbreviate(count);}
get expandable()
{if(this._expandable)
return true;if(this._objectTree)
return true;return false;}
expand()
{if(this._expandable)
this._element.classList.add("expanded");if(this._objectTree&&this._message.type!==WI.ConsoleMessage.MessageType.Trace){if(!this._extraParameters||this._extraParameters.length<=1)
this._objectTree.expand();}}
collapse()
{if(this._expandable)
this._element.classList.remove("expanded");if(this._objectTree){if(!this._extraParameters||this._extraParameters.length<=1)
this._objectTree.collapse();}}
toggle()
{if(this._element.classList.contains("expanded"))
this.collapse();else
this.expand();}
toClipboardString(isPrefixOptional)
{let clipboardString=this._messageBodyElement.innerText.removeWordBreakCharacters();if(this._message.savedResultIndex){let escapedSavedResultPrefix=WI.RuntimeManager.preferredSavedResultPrefix().escapeForRegExp();clipboardString=clipboardString.replace(new RegExp(`\\s*=\\s*${escapedSavedResultPrefix}\\d+\\s*$`),"");}
let hasStackTrace=this._shouldShowStackTrace();if(!hasStackTrace){let repeatString=this.repeatCount>1?"x"+this.repeatCount:"";let urlLine="";if(this._message.url){let components=[WI.displayNameForURL(this._message.url),"line "+this._message.line];if(repeatString)
components.push(repeatString);urlLine=" ("+components.join(", ")+")";}else if(repeatString)
urlLine=" ("+repeatString+")";if(urlLine){let lines=clipboardString.split("\n");lines[0]+=urlLine;clipboardString=lines.join("\n");}}
if(this._extraElementsList)
clipboardString+="\n"+this._extraElementsList.innerText.removeWordBreakCharacters().trim();if(hasStackTrace){this._message.stackTrace.callFrames.forEach(function(frame){clipboardString+="\n\t"+(frame.functionName||WI.UIString("(anonymous function)"));if(frame.sourceCodeLocation)
clipboardString+=" ("+frame.sourceCodeLocation.originalLocationString()+")";});}
if(!isPrefixOptional||this._enforcesClipboardPrefixString())
return this._clipboardPrefixString()+clipboardString;return clipboardString;}
clearSessionState()
{for(let node of this._messageBodyElement.querySelectorAll(".console-saved-variable"))
node.remove();if(this._objectTree instanceof WI.ObjectTreeView)
this._objectTree.resetPropertyPath();WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._handleDebuggerBlackboxChanged,this);} 
_appendMessageTextAndArguments(element)
{if(this._message.source===WI.ConsoleMessage.MessageSource.ConsoleAPI){switch(this._message.type){case WI.ConsoleMessage.MessageType.Trace:var args=[WI.UIString("Trace")];if(this._message.parameters){if(this._message.parameters[0].type==="string"){var prefixedFormatString=WI.UIString("Trace: %s").format(this._message.parameters[0].description);args=[prefixedFormatString].concat(this._message.parameters.slice(1));}else
args.pushAll(this._message.parameters);}
this._appendFormattedArguments(element,args);return;case WI.ConsoleMessage.MessageType.Assert:var args=[WI.UIString("Assertion Failed")];if(this._message.parameters){if(this._message.parameters[0].type==="string"){var prefixedFormatString=WI.UIString("Assertion Failed: %s").format(this._message.parameters[0].description);args=[prefixedFormatString].concat(this._message.parameters.slice(1));}else
args.pushAll(this._message.parameters);}
this._appendFormattedArguments(element,args);return;case WI.ConsoleMessage.MessageType.Dir:var obj=this._message.parameters?this._message.parameters[0]:undefined;this._appendFormattedArguments(element,["%O",obj]);return;case WI.ConsoleMessage.MessageType.Table:var args=this._message.parameters;element.appendChild(this._formatParameterAsTable(args));this._extraParameters=null;return;case WI.ConsoleMessage.MessageType.StartGroup:case WI.ConsoleMessage.MessageType.StartGroupCollapsed:var args=this._message.parameters||[this._message.messageText||WI.UIString("Group")];this._formatWithSubstitutionString(args,element);this._extraParameters=null;return;case WI.ConsoleMessage.MessageType.Timing:{let args=[this._message.messageText];if(this._extraParameters)
args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);return;}
case WI.ConsoleMessage.MessageType.Image:{if(this._message.level===WI.ConsoleMessage.MessageLevel.Log){let divider=null;if(this._message.parameters.length>1){this._appendFormattedArguments(element,this._message.parameters.slice(1));divider=element.appendChild(document.createElement("hr"));}
let target=this._message.parameters[0];if(target==="Viewport")
target=WI.UIString("Viewport");this._appendFormattedArguments(element,[target]);if(this._message.messageText){let img=document.createElement("img");img.classList.add("show-grid");img.src=this._message.messageText;img.setAttribute("filename",WI.FileUtilities.screenshotString()+".png");img.addEventListener("load",(event)=>{if(img.width>=img.height)
img.width=img.width/window.devicePixelRatio;else
img.height=img.height/window.devicePixelRatio;element.appendChild(img);});img.addEventListener("error",(event)=>{this._element.setAttribute("data-labelprefix",WI.UIString("Error: "));this._element.classList.add("console-error-level");this._element.classList.remove("console-log-level");if(divider){while(divider.nextSibling)
divider.nextSibling.remove();}else
element.removeChildren();let args=[WI.UIString("Could not capture screenshot"),this._message.messageText];if(this._extraParameters)
args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);});}
return;}
if(this._message.level===WI.ConsoleMessage.MessageLevel.Error){let args=[];if(this._message.messageText==="Could not capture screenshot")
args.push(WI.UIString("Could not capture screenshot"));else
args.push(this._message.messageText);if(this._extraParameters)
args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);return;}
break;}}}
var args=this._message.parameters||[this._message.messageText];this._appendFormattedArguments(element,args);}
_appendSavedResultIndex(element)
{let savedResultIndex=this._message.savedResultIndex;if(!savedResultIndex)
return;var savedVariableElement=document.createElement("span");savedVariableElement.classList.add("console-saved-variable"); function updateSavedVariableText(){savedVariableElement.textContent=" = "+WI.RuntimeManager.preferredSavedResultPrefix()+savedResultIndex;}
WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,updateSavedVariableText,savedVariableElement);updateSavedVariableText();if(this._objectTree)
this._objectTree.appendTitleSuffix(savedVariableElement);else
this._messageBodyElement.appendChild(savedVariableElement);}
_appendLocationLink()
{if(this._message.source===WI.ConsoleMessage.MessageSource.Network){if(this._message.url){var anchor=WI.linkifyURLAsNode(this._message.url,this._message.url,"console-message-url");anchor.classList.add("console-message-location");this._element.appendChild(anchor);}
return;}
var callFrame;let firstNonNativeNonAnonymousNotBlackboxedCallFrame=this._message.stackTrace.firstNonNativeNonAnonymousNotBlackboxedCallFrame;if(firstNonNativeNonAnonymousNotBlackboxedCallFrame){callFrame=firstNonNativeNonAnonymousNotBlackboxedCallFrame;}else if(this._message.url&&!this._shouldHideURL(this._message.url)){callFrame=WI.CallFrame.fromPayload(this._message.target,{functionName:"",url:this._message.url,lineNumber:this._message.line,columnNumber:this._message.column});}
if(callFrame&&(!callFrame.isConsoleEvaluation||WI.settings.debugShowConsoleEvaluations.value)){let existingCallFrameView=this._callFrameView;this._callFrameView=new WI.CallFrameView(callFrame,{showFunctionName:!!callFrame.functionName});this._callFrameView.classList.add("console-message-location");if(existingCallFrameView)
this._element.replaceChild(this._callFrameView,existingCallFrameView);else
this._element.appendChild(this._callFrameView);return;}
if(this._message.parameters&&this._message.parameters.length===1){var parameter=this._createRemoteObjectIfNeeded(this._message.parameters[0]);parameter.findFunctionSourceCodeLocation().then((result)=>{if(result===WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound||result===WI.RemoteObject.SourceCodeLocationPromise.MissingObjectId)
return;let link=WI.linkifySourceCode(result.sourceCode,new WI.SourceCodePosition(result.lineNumber,result.columnNumber),{className:"console-message-url",ignoreNetworkTab:true,ignoreSearchTab:true,});link.classList.add("console-message-location");if(this._element.hasChildNodes())
this._element.insertBefore(link,this._element.firstChild);else
this._element.appendChild(link);});}}
_appendExtraParameters()
{if(!this._extraParameters||!this._extraParameters.length)
return;this._makeExpandable();if(this._extraParameters.length>1)
this.expand();this._extraElementsList=this._element.appendChild(document.createElement("ol"));this._extraElementsList.classList.add("console-message-extra-parameters-container");for(var parameter of this._extraParameters){var listItemElement=this._extraElementsList.appendChild(document.createElement("li"));const forceObjectFormat=parameter.type==="object"&&(parameter.subtype!=="null"&&parameter.subtype!=="regexp"&&parameter.subtype!=="node"&&parameter.subtype!=="error");listItemElement.classList.add("console-message-extra-parameter");listItemElement.appendChild(this._formatParameter(parameter,forceObjectFormat));}}
_appendStackTrace()
{if(!this._shouldShowStackTrace())
return;this._makeExpandable();if(this._message.type===WI.ConsoleMessage.MessageType.Trace&&WI.settings.consoleAutoExpandTrace.value)
this.expand();this._stackTraceElement=this._element.appendChild(document.createElement("div"));this._stackTraceElement.classList.add("console-message-body","console-message-stack-trace-container");var callFramesElement=new WI.StackTraceView(this._message.stackTrace).element;this._stackTraceElement.appendChild(callFramesElement);}
_createRemoteObjectIfNeeded(parameter)
{if(parameter instanceof WI.RemoteObject)
return parameter;if(typeof parameter==="object")
return WI.RemoteObject.fromPayload(parameter,this._message.target);return WI.RemoteObject.fromPrimitiveValue(parameter);}
_appendFormattedArguments(element,parameters)
{if(!parameters.length)
return;for(let i=0;i<parameters.length;++i)
parameters[i]=this._createRemoteObjectIfNeeded(parameters[i]);let builderElement=element.appendChild(document.createElement("span"));let shouldFormatWithStringSubstitution=parameters[0].type==="string"&&this._message.type!==WI.ConsoleMessage.MessageType.Result;if(parameters.length===1&&!shouldFormatWithStringSubstitution){this._extraParameters=null;builderElement.appendChild(this._formatParameter(parameters[0],false));return;}
if(shouldFormatWithStringSubstitution&&this._isStackTrace(parameters[0]))
shouldFormatWithStringSubstitution=false;let needsDivider=false;function appendDividerIfNeeded(){if(!needsDivider)
return null;let element=builderElement.appendChild(document.createElement("span"));element.classList.add("console-message-preview-divider");element.textContent=` ${enDash} `;return element;}
if(shouldFormatWithStringSubstitution){let result=this._formatWithSubstitutionString(parameters,builderElement);parameters=result.unusedSubstitutions;this._extraParameters=parameters;needsDivider=true;}
if(parameters.length){let simpleParametersCount=0;for(let parameter of parameters){if(!this._hasSimpleDisplay(parameter))
break;simpleParametersCount++;}
if(simpleParametersCount){let simpleParameters=parameters.splice(0,simpleParametersCount);this._extraParameters=parameters;for(let parameter of simpleParameters){let dividerElement=appendDividerIfNeeded();if(dividerElement)
dividerElement.classList.add("inline-lossless");let previewContainer=builderElement.appendChild(document.createElement("span"));previewContainer.classList.add("inline-lossless");let preview=WI.FormattedValue.createObjectPreviewOrFormattedValueForRemoteObject(parameter,WI.ObjectPreviewView.Mode.Brief);let isPreviewView=preview instanceof WI.ObjectPreviewView;if(isPreviewView)
preview.setOriginatingObjectInfo(parameter,null);let previewElement=isPreviewView?preview.element:preview;previewContainer.appendChild(previewElement);needsDivider=true;}}
if(parameters.length===1&&!this._isStackTrace(parameters[0])){let parameter=parameters[0];let dividerElement=appendDividerIfNeeded();let previewContainer=builderElement.appendChild(document.createElement("span"));previewContainer.classList.add("console-message-preview");let preview=WI.FormattedValue.createObjectPreviewOrFormattedValueForRemoteObject(parameter,WI.ObjectPreviewView.Mode.Brief);let isPreviewView=preview instanceof WI.ObjectPreviewView;if(isPreviewView)
preview.setOriginatingObjectInfo(parameter,null);let previewElement=isPreviewView?preview.element:preview;previewContainer.appendChild(previewElement);needsDivider=true;if((isPreviewView&&preview.lossless)||(!isPreviewView&&this._shouldConsiderObjectLossless(parameter))){this._extraParameters=null;if(dividerElement)
dividerElement.classList.add("inline-lossless");previewContainer.classList.add("inline-lossless");}}else if(parameters.length){let enclosedElement=document.createElement("span");builderElement.append(" ",enclosedElement);enclosedElement.classList.add("console-message-enclosed");enclosedElement.textContent="("+parameters.length+")";}}}
_hasSimpleDisplay(parameter)
{return WI.FormattedValue.hasSimpleDisplay(parameter)&&!this._isStackTrace(parameter);}
_isStackTrace(parameter)
{return parameter.type==="string"&&WI.StackTrace.isLikelyStackTrace(parameter.description);}
_shouldConsiderObjectLossless(object)
{if(object.type==="string")
return WI.FormattedValue.isSimpleString(object.description);return object.type!=="object"||object.subtype==="null"||object.subtype==="regexp";}
_formatParameter(parameter,forceObjectFormat)
{var type;if(forceObjectFormat)
type="object";else if(parameter instanceof WI.RemoteObject)
type=parameter.subtype||parameter.type;else{type=typeof parameter;}
var formatters={"object":this._formatParameterAsObject,"error":this._formatParameterAsError,"map":this._formatParameterAsObject,"set":this._formatParameterAsObject,"weakmap":this._formatParameterAsObject,"weakset":this._formatParameterAsObject,"iterator":this._formatParameterAsObject,"class":this._formatParameterAsObject,"proxy":this._formatParameterAsObject,"array":this._formatParameterAsArray,"node":this._formatParameterAsNode,"string":this._formatParameterAsString,};var formatter=formatters[type]||this._formatParameterAsValue;const fragment=document.createDocumentFragment();formatter.call(this,parameter,fragment,forceObjectFormat);return fragment;}
_formatParameterAsValue(value,fragment)
{fragment.appendChild(WI.FormattedValue.createElementForRemoteObject(value));}
_formatParameterAsString(object,fragment)
{if(this._isStackTrace(object)){let stackTrace=WI.StackTrace.fromString(this._message.target,object.description);if(stackTrace.callFrames.length){let stackView=new WI.StackTraceView(stackTrace);fragment.appendChild(stackView.element);return;}}
fragment.appendChild(WI.FormattedValue.createLinkifiedElementString(object.description));}
_formatParameterAsNode(object,fragment)
{fragment.appendChild(WI.FormattedValue.createElementForNode(object));}
_formatParameterAsObject(object,fragment,forceExpansion)
{this._objectTree=new WI.ObjectTreeView(object,null,this._rootPropertyPathForObject(object),forceExpansion);fragment.appendChild(this._objectTree.element);}
_formatParameterAsError(object,fragment)
{this._objectTree=new WI.ErrorObjectView(object);fragment.appendChild(this._objectTree.element);}
_formatParameterAsArray(array,fragment)
{this._objectTree=new WI.ObjectTreeView(array,WI.ObjectTreeView.Mode.Properties,this._rootPropertyPathForObject(array));fragment.appendChild(this._objectTree.element);}
_rootPropertyPathForObject(object)
{let savedResultIndex=this._message.savedResultIndex;if(!savedResultIndex)
return null;function prefixSavedResultIndex(){return WI.RuntimeManager.preferredSavedResultPrefix()+savedResultIndex;}
let propertyPath=new WI.PropertyPath(object,prefixSavedResultIndex());WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,function(event){this.pathComponent=prefixSavedResultIndex();},propertyPath);return propertyPath;}
_formatWithSubstitutionString(parameters,formattedResult)
{function parameterFormatter(force,obj)
{return this._formatParameter(obj,force);}
function stringFormatter(obj)
{return obj.description;}
function floatFormatter(obj,token)
{let value=typeof obj.value==="number"?obj.value:obj.description;return String.standardFormatters.f(value,token);}
function integerFormatter(obj)
{let value=typeof obj.value==="number"?obj.value:obj.description;return String.standardFormatters.d(value);}
var currentStyle=null;function styleFormatter(obj)
{currentStyle={};var buffer=document.createElement("span");buffer.setAttribute("style",obj.description);for(var i=0;i<buffer.style.length;i++){var property=buffer.style[i];if(isAllowedProperty(property))
currentStyle[property]=buffer.style[property];}}
function isAllowedProperty(property)
{for(var prefix of["background","border","color","font","line","margin","padding","text"]){if(property.startsWith(prefix)||property.startsWith("-webkit-"+prefix))
return true;}
return false;}
var formatters={};formatters.o=parameterFormatter.bind(this,false);formatters.s=stringFormatter;formatters.f=floatFormatter;formatters.i=integerFormatter;formatters.d=integerFormatter;formatters.c=styleFormatter;formatters.O=parameterFormatter.bind(this,true);function append(a,b)
{if(b instanceof Node)
a.appendChild(b);else if(b!==undefined){var toAppend=WI.linkifyStringAsFragment(b.toString());if(currentStyle){var wrapper=document.createElement("span");for(var key in currentStyle)
wrapper.style[key]=currentStyle[key];wrapper.appendChild(toAppend);toAppend=wrapper;}
a.appendChild(toAppend);}
return a;}
return String.format(parameters[0].description,parameters.slice(1),formatters,formattedResult,append);}
_shouldShowStackTrace()
{if(!this._message.stackTrace.callFrames.length)
return false;return this._message.source===WI.ConsoleMessage.MessageSource.Network||this._message.level===WI.ConsoleMessage.MessageLevel.Error||this._message.type===WI.ConsoleMessage.MessageType.Trace;}
_shouldHideURL(url)
{return url==="undefined"||url==="[native code]";}
_userProvidedColumnNames(columnNamesArgument)
{if(!columnNamesArgument)
return null;if(columnNamesArgument.type==="string"||columnNamesArgument.type==="number")
return[String(columnNamesArgument.value)];if(columnNamesArgument.type!=="object"||columnNamesArgument.subtype!=="array"||!columnNamesArgument.preview||!columnNamesArgument.preview.propertyPreviews)
return null;var extractedColumnNames=[];for(var propertyPreview of columnNamesArgument.preview.propertyPreviews){if(propertyPreview.type==="string"||propertyPreview.type==="number")
extractedColumnNames.push(String(propertyPreview.value));}
return extractedColumnNames.length?extractedColumnNames:null;}
_formatParameterAsTable(parameters)
{var element=document.createElement("span");var table=parameters[0];if(!table||!table.preview)
return element;var rows=[];var columnNames=[];var flatValues=[];var preview=table.preview;var userProvidedColumnNames=false;var extractedColumnNames=this._userProvidedColumnNames(parameters[1]);if(extractedColumnNames){userProvidedColumnNames=true;columnNames=extractedColumnNames;}
if(preview.propertyPreviews){for(var i=0;i<preview.propertyPreviews.length;++i){var rowProperty=preview.propertyPreviews[i];var rowPreview=rowProperty.valuePreview;if(!rowPreview||!rowPreview.propertyPreviews)
continue;var rowValue={};var maxColumnsToRender=15;for(var j=0;j<rowPreview.propertyPreviews.length;++j){var cellProperty=rowPreview.propertyPreviews[j];var columnRendered=columnNames.includes(cellProperty.name);if(!columnRendered){if(userProvidedColumnNames||columnNames.length===maxColumnsToRender)
continue;columnRendered=true;columnNames.push(cellProperty.name);}
rowValue[cellProperty.name]=WI.FormattedValue.createElementForPropertyPreview(cellProperty);}
rows.push([rowProperty.name,rowValue]);}}
if(rows.length){columnNames.unshift(WI.UIString("(Index)"));for(var i=0;i<rows.length;++i){var rowName=rows[i][0];var rowValue=rows[i][1];flatValues.push(rowName);for(var j=1;j<columnNames.length;++j){var columnName=columnNames[j];if(!(columnName in rowValue))
flatValues.push(emDash);else
flatValues.push(rowValue[columnName]);}}}
if(!flatValues.length&&preview.propertyPreviews){for(var i=0;i<preview.propertyPreviews.length;++i){var rowProperty=preview.propertyPreviews[i];if(!("value"in rowProperty))
continue;if(!columnNames.length){columnNames.push(WI.UIString("Index"));columnNames.push(WI.UIString("Value"));}
flatValues.push(rowProperty.name);flatValues.push(WI.FormattedValue.createElementForPropertyPreview(rowProperty));}}
if(!flatValues.length)
return element;var dataGrid=WI.DataGrid.createSortableDataGrid(columnNames,flatValues);dataGrid.inline=true;dataGrid.variableHeightRows=true;element.appendChild(dataGrid.element);dataGrid.updateLayoutIfNeeded();return element;}
_levelString()
{switch(this._message.level){case WI.ConsoleMessage.MessageLevel.Log:return"Log";case WI.ConsoleMessage.MessageLevel.Info:return"Info";case WI.ConsoleMessage.MessageLevel.Warning:return"Warning";case WI.ConsoleMessage.MessageLevel.Debug:return"Debug";case WI.ConsoleMessage.MessageLevel.Error:return"Error";}}
_enforcesClipboardPrefixString()
{return this._message.type!==WI.ConsoleMessage.MessageType.Result;}
_clipboardPrefixString()
{if(this._message.type===WI.ConsoleMessage.MessageType.Result)
return"< ";return"["+this._levelString()+"] ";}
_makeExpandable()
{if(this._expandable)
return;this._expandable=true;this._element.classList.add("expandable");this._boundClickHandler=this.toggle.bind(this);this._messageBodyElement.addEventListener("click",this._boundClickHandler);}
_handleContextMenu(event)
{let image=event.target.closest(".console-image > .console-message-body > img");if(!image)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.appendItem(WI.UIString("Save Image"),()=>{const forceSaveAs=true;WI.FileUtilities.save({content:parseDataURL(this._message.messageText).data,base64Encoded:true,suggestedName:image.getAttribute("filename"),},forceSaveAs);});contextMenu.appendSeparator();}
_handleDebuggerBlackboxChanged(event)
{if(this._callFrameView)
this._appendLocationLink();}};WI.ContentBrowser=class ContentBrowser extends WI.View
{constructor(element,delegate,{hideBackForwardButtons,disableBackForwardNavigation,disableFindBanner,flexibleNavigationItem,contentViewNavigationItemGroup}={})
{super(element);this.element.classList.add("content-browser");this._navigationBar=new WI.NavigationBar;this.addSubview(this._navigationBar);this._contentViewContainer=new WI.ContentViewContainer({disableBackForwardNavigation});this._contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);this.addSubview(this._contentViewContainer);if(!hideBackForwardButtons){let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let goBack=()=>{this.goBack();};let goForward=()=>{this.goForward();};let backShortcutKey=isRTL?WI.KeyboardShortcut.Key.Right:WI.KeyboardShortcut.Key.Left;let forwardShortcutKey=isRTL?WI.KeyboardShortcut.Key.Left:WI.KeyboardShortcut.Key.Right;this._backKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Control,backShortcutKey,goBack,this.element);this._forwardKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Control,forwardShortcutKey,goForward,this.element);let leftArrow="Images/BackForwardArrows.svg#left-arrow-mask";let rightArrow="Images/BackForwardArrows.svg#right-arrow-mask";let backButtonImage=isRTL?rightArrow:leftArrow;let forwardButtonImage=isRTL?leftArrow:rightArrow;this._backNavigationItem=new WI.ButtonNavigationItem("back",WI.UIString("Back (%s)").format(this._backKeyboardShortcut.displayName),backButtonImage,8,13);this._backNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,goBack,this);this._backNavigationItem.enabled=false;this._forwardNavigationItem=new WI.ButtonNavigationItem("forward",WI.UIString("Forward (%s)").format(this._forwardKeyboardShortcut.displayName),forwardButtonImage,8,13);this._forwardNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,goForward,this);this._forwardNavigationItem.enabled=false;let navigationButtonsGroup=new WI.GroupNavigationItem([this._backNavigationItem,this._forwardNavigationItem]);this._navigationBar.addNavigationItem(navigationButtonsGroup);}
if(!disableFindBanner){this._findBanner=new WI.FindBanner(this);this._findBanner.addEventListener(WI.FindBanner.Event.DidShow,this._findBannerDidShow,this);this._findBanner.addEventListener(WI.FindBanner.Event.DidHide,this._findBannerDidHide,this);}
this._hierarchicalPathNavigationItem=new WI.HierarchicalPathNavigationItem;this._hierarchicalPathNavigationItem.addEventListener(WI.HierarchicalPathNavigationItem.Event.PathComponentWasSelected,this._hierarchicalPathComponentWasSelected,this);this._navigationBar.addNavigationItem(this._hierarchicalPathNavigationItem);this._contentViewSelectionPathNavigationItem=new WI.HierarchicalPathNavigationItem;this._flexibleNavigationItem=flexibleNavigationItem||new WI.FlexibleSpaceNavigationItem;this._navigationBar.addNavigationItem(this._flexibleNavigationItem);this._currentContentViewNavigationItemsGroup=contentViewNavigationItemGroup||null;WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._contentViewNavigationItemsDidChange,this);this._delegate=delegate||null;this._currentContentViewNavigationItems=[];this._dispatchCurrentRepresentedObjectsDidChangeDebouncer=new Debouncer(()=>{this.dispatchEventToListeners(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange);});} 
get navigationBar()
{return this._navigationBar;}
get contentViewContainer()
{return this._contentViewContainer;}
get delegate()
{return this._delegate;}
set delegate(newDelegate)
{this._delegate=newDelegate||null;}
get currentContentView()
{return this._contentViewContainer.currentContentView;}
get currentRepresentedObjects()
{var representedObjects=[];var lastComponent=this._hierarchicalPathNavigationItem.lastComponent;if(lastComponent&&lastComponent.representedObject)
representedObjects.push(lastComponent.representedObject);lastComponent=this._contentViewSelectionPathNavigationItem.lastComponent;if(lastComponent&&lastComponent.representedObject)
representedObjects.push(lastComponent.representedObject);var currentContentView=this.currentContentView;if(currentContentView){var supplementalRepresentedObjects=currentContentView.supplementalRepresentedObjects;if(supplementalRepresentedObjects&&supplementalRepresentedObjects.length)
representedObjects.pushAll(supplementalRepresentedObjects);}
return representedObjects;}
showContentViewForRepresentedObject(representedObject,cookie,extraArguments)
{var contentView=this.contentViewForRepresentedObject(representedObject,false,extraArguments);return this._contentViewContainer.showContentView(contentView,cookie);}
showContentView(contentView,cookie)
{return this._contentViewContainer.showContentView(contentView,cookie);}
contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments)
{return this._contentViewContainer.contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments);}
updateHierarchicalPathForCurrentContentView()
{var currentContentView=this.currentContentView;this._updateHierarchicalPathNavigationItem(currentContentView?currentContentView.representedObject:null);}
canGoBack()
{var currentContentView=this.currentContentView;if(currentContentView&&currentContentView.canGoBack())
return true;return this._contentViewContainer.canGoBack();}
canGoForward()
{var currentContentView=this.currentContentView;if(currentContentView&&currentContentView.canGoForward())
return true;return this._contentViewContainer.canGoForward();}
goBack()
{var currentContentView=this.currentContentView;if(currentContentView&&currentContentView.canGoBack()){currentContentView.goBack();this._updateBackForwardButtons();return;}
this._contentViewContainer.goBack();}
goForward()
{var currentContentView=this.currentContentView;if(currentContentView&&currentContentView.canGoForward()){currentContentView.goForward();this._updateBackForwardButtons();return;}
this._contentViewContainer.goForward();}
showFindBanner()
{if(!this._findBanner)
return;var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;if(currentContentView.supportsCustomFindBanner){currentContentView.showCustomFindBanner();return;}
this._findBanner.show();}
attached()
{super.attached();this._updateContentViewSelectionPathNavigationItem(this.currentContentView);this.updateHierarchicalPathForCurrentContentView();} 
handlePopulateFindShortcut()
{let currentContentView=this.currentContentView;if(!currentContentView?.supportsSearch)
return;if(!WI.updateFindString(currentContentView.searchQueryWithSelection()))
return;this._findBanner.searchQuery=WI.findString;currentContentView.performSearch(this._findBanner.searchQuery);}
async handleFindNextShortcut()
{if(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString){let searchQuery=WI.findString;this._findBanner.searchQuery=searchQuery;let currentContentView=this.currentContentView;if(currentContentView?.supportsSearch){currentContentView.performSearch(this._findBanner.searchQuery);await currentContentView.awaitEvent(WI.ContentView.Event.NumberOfSearchResultsDidChange,this);if(this._findBanner.searchQuery!==searchQuery||this.currentContentView!==currentContentView)
return;}}
this.findBannerRevealNextResult(this._findBanner);}
async handleFindPreviousShortcut()
{if(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString){let searchQuery=WI.findString;this._findBanner.searchQuery=searchQuery;let currentContentView=this.currentContentView;if(currentContentView?.supportsSearch){currentContentView.performSearch(this._findBanner.searchQuery);await currentContentView.awaitEvent(WI.ContentView.Event.NumberOfSearchResultsDidChange,this);if(this._findBanner.searchQuery!==searchQuery||this.currentContentView!==currentContentView)
return;}}
this.findBannerRevealPreviousResult(this._findBanner);} 
findBannerPerformSearch(findBanner,query)
{let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.performSearch(query);}
findBannerSearchCleared(findBanner)
{let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.searchCleared();}
findBannerRevealPreviousResult(findBanner)
{let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.revealPreviousSearchResult(!findBanner.showing);}
findBannerRevealNextResult(findBanner)
{let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.revealNextSearchResult(!findBanner.showing);} 
_findBannerDidShow(event)
{var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.automaticallyRevealFirstSearchResult=true;if(this._findBanner.searchQuery!=="")
currentContentView.performSearch(this._findBanner.searchQuery);}
_findBannerDidHide(event)
{var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.automaticallyRevealFirstSearchResult=false;currentContentView.searchHidden();}
_contentViewNumberOfSearchResultsDidChange(event)
{if(!this._findBanner)
return;if(event.target!==this.currentContentView)
return;this._findBanner.numberOfResults=this.currentContentView.numberOfSearchResults;}
_updateHierarchicalPathNavigationItem(representedObject)
{if(!this.delegate||typeof this.delegate.contentBrowserTreeElementForRepresentedObject!=="function")
return;var treeElement=representedObject?this.delegate.contentBrowserTreeElementForRepresentedObject(this,representedObject):null;var pathComponents=[];while(treeElement&&!treeElement.root){var pathComponent=new WI.GeneralTreeElementPathComponent(treeElement);pathComponents.unshift(pathComponent);treeElement=treeElement.parent;}
this._hierarchicalPathNavigationItem.components=pathComponents;}
_updateContentViewSelectionPathNavigationItem(contentView)
{var selectionPathComponents=contentView?contentView.selectionPathComponents||[]:[];this._contentViewSelectionPathNavigationItem.components=selectionPathComponents;if(this._currentContentViewNavigationItemsGroup)
return;if(!selectionPathComponents.length){this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator=false;this._navigationBar.removeNavigationItem(this._contentViewSelectionPathNavigationItem);return;}
if(!this._navigationBar.navigationItems.includes(this._contentViewSelectionPathNavigationItem)){var hierarchicalPathItemIndex=this._navigationBar.navigationItems.indexOf(this._hierarchicalPathNavigationItem);this._navigationBar.insertNavigationItem(this._contentViewSelectionPathNavigationItem,hierarchicalPathItemIndex+1);this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator=true;}}
_updateBackForwardButtons()
{if(!this._backNavigationItem||!this._forwardNavigationItem)
return;this._backNavigationItem.enabled=this.canGoBack();this._forwardNavigationItem.enabled=this.canGoForward();}
_updateContentViewNavigationItems(forceUpdate)
{let currentContentView=this.currentContentView;if(!currentContentView){this._removeAllNavigationItems();this._currentContentViewNavigationItems=[];if(this._currentContentViewNavigationItemsGroup)
this._currentContentViewNavigationItems.push(this._contentViewSelectionPathNavigationItem);return;}
if(currentContentView.parentContainer!==this._contentViewContainer)
return;if(!forceUpdate){let previousItems=this._currentContentViewNavigationItems.filter((item)=>!(item instanceof WI.DividerNavigationItem));let isUnchanged=Array.shallowEqual(previousItems,currentContentView.navigationItems);if(isUnchanged)
return;}
this._removeAllNavigationItems();let navigationBar=this.navigationBar;let insertionIndex=navigationBar.navigationItems.indexOf(this._flexibleNavigationItem)+1;let newNavigationItems=[];let shouldInsert=!this._currentContentViewNavigationItemsGroup;currentContentView.navigationItems.forEach(function(navigationItem,index){if(shouldInsert)
navigationBar.insertNavigationItem(navigationItem,insertionIndex++);newNavigationItems.push(navigationItem);});if(this._currentContentViewNavigationItemsGroup)
this._currentContentViewNavigationItemsGroup.navigationItems=[this._contentViewSelectionPathNavigationItem].concat(newNavigationItems);
this._currentContentViewNavigationItems=newNavigationItems;}
_removeAllNavigationItems()
{if(this._currentContentViewNavigationItemsGroup)
this._currentContentViewNavigationItemsGroup.navigationItems=[];else{for(let navigationItem of this._currentContentViewNavigationItems){if(navigationItem.parentNavigationBar)
navigationItem.parentNavigationBar.removeNavigationItem(navigationItem);}}}
_updateFindBanner(currentContentView)
{if(!this._findBanner)
return;if(!currentContentView){this._findBanner.targetElement=null;this._findBanner.numberOfResults=null;return;}
this._findBanner.targetElement=currentContentView.element;this._findBanner.numberOfResults=currentContentView.hasPerformedSearch?currentContentView.numberOfSearchResults:null;if(currentContentView.supportsSearch&&this._findBanner.searchQuery){currentContentView.automaticallyRevealFirstSearchResult=this._findBanner.showing;currentContentView.performSearch(this._findBanner.searchQuery);}}
_contentViewSelectionPathComponentDidChange(event)
{if(event.target!==this.currentContentView)
return;if(event.target.parentContainer!==this._contentViewContainer)
return;this._updateContentViewSelectionPathNavigationItem(event.target);this._updateBackForwardButtons();this._updateContentViewNavigationItems();this._navigationBar.needsLayout();this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.delayForTime(0);}
_contentViewSupplementalRepresentedObjectsDidChange(event)
{if(event.target!==this.currentContentView)
return;if(event.target.parentContainer!==this._contentViewContainer)
return;this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.delayForTime(0);}
_currentContentViewDidChange(event)
{var currentContentView=this.currentContentView;this._updateHierarchicalPathNavigationItem(currentContentView?currentContentView.representedObject:null);this._updateContentViewSelectionPathNavigationItem(currentContentView);this._updateBackForwardButtons();this._updateContentViewNavigationItems();this._updateFindBanner(currentContentView);this._navigationBar.needsLayout();this.dispatchEventToListeners(WI.ContentBrowser.Event.CurrentContentViewDidChange);this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.force();}
_contentViewNavigationItemsDidChange(event)
{if(event.target!==this.currentContentView)
return;if(event.target.parentContainer!==this._contentViewContainer)
return;const forceUpdate=true;this._updateContentViewNavigationItems(forceUpdate);this._navigationBar.needsLayout();}
_hierarchicalPathComponentWasSelected(event)
{var treeElement=event.data.pathComponent.generalTreeElement;var originalTreeElement=treeElement;while(treeElement&&!WI.ContentView.isViewable(treeElement.representedObject))
treeElement=treeElement.traverseNextTreeElement(false,originalTreeElement,false);if(!treeElement)
return;treeElement.revealAndSelect();}};WI.ContentBrowser.Event={CurrentRepresentedObjectsDidChange:"content-browser-current-represented-objects-did-change",CurrentContentViewDidChange:"content-browser-current-content-view-did-change"};WI.ContentView=class ContentView extends WI.View
{constructor(representedObject,extraArguments)
{super();this._representedObject=representedObject;this.element.classList.add("content-view");this._parentContainer=null;this._isClosed=false;this._visible=false;} 
static shouldNotRemoveFromDOMWhenHidden()
{return false;}
static createFromRepresentedObject(representedObject,extraArguments)
{if(representedObject instanceof WI.Frame)
return new WI.ResourceClusterContentView(representedObject.mainResource,extraArguments);if(representedObject instanceof WI.Resource)
return new WI.ResourceClusterContentView(representedObject,extraArguments);if(representedObject instanceof WI.Script)
return new WI.ScriptContentView(representedObject,extraArguments);if(representedObject instanceof WI.CSSStyleSheet)
return new WI.TextResourceContentView(representedObject,extraArguments);if(representedObject instanceof WI.Canvas)
return new WI.CanvasContentView(representedObject,extraArguments);if(representedObject instanceof WI.ShaderProgram)
return new WI.ShaderProgramContentView(representedObject,extraArguments);if(representedObject instanceof WI.TimelineRecording)
return new WI.TimelineRecordingContentView(representedObject,extraArguments);if(representedObject instanceof WI.Timeline){var timelineType=representedObject.type;if(timelineType===WI.TimelineRecord.Type.Network)
return new WI.NetworkTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Layout)
return new WI.LayoutTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Script)
return new WI.ScriptClusterTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.RenderingFrame)
return new WI.RenderingFrameTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.CPU)
return new WI.CPUTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Memory)
return new WI.MemoryTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.HeapAllocations)
return new WI.HeapAllocationsTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Media)
return new WI.MediaTimelineView(representedObject,extraArguments);}
if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage){if(representedObject.sourceCodeLocation)
return WI.ContentView.createFromRepresentedObject(representedObject.sourceCodeLocation.displaySourceCode,extraArguments);}
if(representedObject instanceof WI.LocalResourceOverride){if(representedObject.type===WI.LocalResourceOverride.InterceptType.Request)
return new WI.LocalResourceOverrideRequestContentView(representedObject);return WI.ContentView.createFromRepresentedObject(representedObject.localResource);}
if(representedObject instanceof WI.DOMStorageObject)
return new WI.DOMStorageContentView(representedObject,extraArguments);if(representedObject instanceof WI.CookieStorageObject)
return new WI.CookieStorageContentView(representedObject,extraArguments);if(representedObject instanceof WI.DatabaseTableObject)
return new WI.DatabaseTableContentView(representedObject,extraArguments);if(representedObject instanceof WI.DatabaseObject)
return new WI.DatabaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabase)
return new WI.IndexedDatabaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabaseObjectStore)
return new WI.IndexedDatabaseObjectStoreContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
return new WI.IndexedDatabaseObjectStoreContentView(representedObject,extraArguments);if(representedObject instanceof WI.ApplicationCacheFrame)
return new WI.ApplicationCacheFrameContentView(representedObject,extraArguments);if(representedObject instanceof WI.DOMTree)
return new WI.FrameDOMTreeContentView(representedObject,extraArguments);if(representedObject instanceof WI.DOMSearchMatchObject){var resultView=new WI.FrameDOMTreeContentView(WI.networkManager.mainFrame.domTree,extraArguments);resultView.restoreFromCookie({nodeToSelect:representedObject.domNode});return resultView;}
if(representedObject instanceof WI.DOMNode){if(representedObject.frame){let resultView=WI.ContentView.createFromRepresentedObject(representedObject.frame,extraArguments);resultView.restoreFromCookie({nodeToSelect:representedObject});return resultView;}}
if(representedObject instanceof WI.SourceCodeSearchMatchObject){var resultView;if(representedObject.sourceCode instanceof WI.Resource)
resultView=new WI.ResourceClusterContentView(representedObject.sourceCode,extraArguments);else if(representedObject.sourceCode instanceof WI.Script)
resultView=new WI.ScriptContentView(representedObject.sourceCode,extraArguments);else
console.error("Unknown SourceCode",representedObject.sourceCode);var textRangeToSelect=representedObject.sourceCodeTextRange.formattedTextRange;var startPosition=textRangeToSelect.startPosition();resultView.restoreFromCookie({lineNumber:startPosition.lineNumber,columnNumber:startPosition.columnNumber});return resultView;}
if(representedObject instanceof WI.LogObject)
return new WI.LogContentView(representedObject,extraArguments);if(representedObject instanceof WI.CallingContextTree)
return new WI.ProfileView(representedObject,extraArguments);if(representedObject instanceof WI.HeapSnapshotProxy||representedObject instanceof WI.HeapSnapshotDiffProxy)
return new WI.HeapSnapshotClusterContentView(representedObject,extraArguments);if(representedObject instanceof WI.Recording)
return new WI.RecordingContentView(representedObject,extraArguments);if(representedObject instanceof WI.ResourceCollection)
return new WI.ResourceCollectionContentView(representedObject,extraArguments);if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestCaseResult)
return new WI.AuditTestCaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestGroupResult)
return new WI.AuditTestGroupContentView(representedObject,extraArguments);if(representedObject instanceof WI.Animation)
return new WI.AnimationContentView(representedObject,extraArguments);if(representedObject instanceof WI.Collection)
return new WI.CollectionContentView(representedObject,extraArguments);if(typeof representedObject==="string"||representedObject instanceof String)
return new WI.TextContentView(representedObject,extraArguments);throw new Error("Can't make a ContentView for an unknown representedObject of type: "+representedObject.constructor.name);}
static contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments)
{let resolvedRepresentedObject=WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject);if(!resolvedRepresentedObject)
return null;let existingContentView=resolvedRepresentedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol];if(existingContentView)
return existingContentView;if(onlyExisting)
return null;let newContentView=WI.ContentView.createFromRepresentedObject(representedObject,extraArguments);if(!newContentView)
return null;if(typeof resolvedRepresentedObject==="object")
newContentView.representedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol]=newContentView;return newContentView;}
static closedContentViewForRepresentedObject(representedObject)
{let resolvedRepresentedObject=WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject);if(typeof resolvedRepresentedObject==="object")
resolvedRepresentedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol]=null;}
static resolvedRepresentedObjectForRepresentedObject(representedObject)
{if(representedObject instanceof WI.Frame)
return representedObject.mainResource;if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage){if(representedObject.sourceCodeLocation)
return representedObject.sourceCodeLocation.displaySourceCode;return representedObject;}
if(representedObject instanceof WI.DOMBreakpoint){if(representedObject.domNode)
return WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject.domNode);return representedObject;}
if(representedObject instanceof WI.DOMNode){if(representedObject.frame)
return WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject.frame);return representedObject;}
if(representedObject instanceof WI.DOMSearchMatchObject)
return WI.networkManager.mainFrame.domTree;if(representedObject instanceof WI.SourceCodeSearchMatchObject)
return representedObject.sourceCode;if(representedObject instanceof WI.LocalResourceOverride){if(representedObject.type!==WI.LocalResourceOverride.InterceptType.Request)
return representedObject.localResource;return representedObject;}
return representedObject;}
static isViewable(representedObject)
{if(representedObject instanceof WI.Frame)
return true;if(representedObject instanceof WI.Resource)
return true;if(representedObject instanceof WI.Script)
return true;if(representedObject instanceof WI.CSSStyleSheet)
return true;if(representedObject instanceof WI.Canvas)
return true;if(representedObject instanceof WI.ShaderProgram)
return true;if(representedObject instanceof WI.TimelineRecording)
return true;if(representedObject instanceof WI.Timeline)
return true;if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage)
return representedObject.sourceCodeLocation;if(representedObject instanceof WI.LocalResourceOverride)
return true;if(representedObject instanceof WI.DOMStorageObject)
return true;if(representedObject instanceof WI.CookieStorageObject)
return true;if(representedObject instanceof WI.DatabaseTableObject)
return true;if(representedObject instanceof WI.DatabaseObject)
return true;if(representedObject instanceof WI.IndexedDatabase)
return true;if(representedObject instanceof WI.IndexedDatabaseObjectStore)
return true;if(representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
return true;if(representedObject instanceof WI.ApplicationCacheFrame)
return true;if(representedObject instanceof WI.DOMTree)
return true;if(representedObject instanceof WI.DOMSearchMatchObject)
return true;if(representedObject instanceof WI.SourceCodeSearchMatchObject)
return true;if(representedObject instanceof WI.LogObject)
return true;if(representedObject instanceof WI.CallingContextTree)
return true;if(representedObject instanceof WI.HeapSnapshotProxy||representedObject instanceof WI.HeapSnapshotDiffProxy)
return true;if(representedObject instanceof WI.Recording)
return true;if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult)
return true;if(representedObject instanceof WI.Animation)
return true;if(representedObject instanceof WI.Collection)
return true;if(typeof representedObject==="string"||representedObject instanceof String)
return true;if(representedObject[WI.ContentView.isViewableSymbol])
return true;return false;} 
get isClosed(){return this._isClosed;}
get visible()
{return!this.isClosed&&this._visible;}
set visible(value)
{this._visible=!!value;this.element.classList.toggle("not-visible",!this._visible);}
get representedObject()
{return this._representedObject;}
get navigationItems()
{return[];}
get parentContainer()
{return this._parentContainer;}
get scrollableElements()
{return[];}
get shouldKeepElementsScrolledToBottom()
{return false;}
get shouldSaveStateWhenHidden()
{return false;}
get selectionPathComponents()
{return[];}
get supplementalRepresentedObjects()
{return[];}
get supportsSplitContentBrowser()
{return WI.dockedConfigurationSupportsSplitContentBrowser();}
closed()
{this._isClosed=true;}
saveToCookie(cookie)
{}
restoreFromCookie(cookie)
{}
canGoBack()
{return false;}
canGoForward()
{return false;}
goBack()
{}
goForward()
{}
get supportsSearch()
{return false;}
get supportsCustomFindBanner()
{return false;}
showCustomFindBanner()
{}
get numberOfSearchResults()
{return null;}
get hasPerformedSearch()
{return false;}
set automaticallyRevealFirstSearchResult(reveal)
{}
performSearch(query)
{}
searchHidden()
{}
searchCleared()
{}
searchQueryWithSelection()
{let selection=window.getSelection();if(selection.isCollapsed)
return null;return selection.toString().removeWordBreakCharacters();}
revealPreviousSearchResult(changeFocus)
{}
revealNextSearchResult(changeFocus)
{}};WI.ContentView.Event={SelectionPathComponentsDidChange:"content-view-selection-path-components-did-change",SupplementalRepresentedObjectsDidChange:"content-view-supplemental-represented-objects-did-change",NumberOfSearchResultsDidChange:"content-view-number-of-search-results-did-change",NavigationItemsDidChange:"content-view-navigation-items-did-change"};WI.ContentView.isViewableSymbol=Symbol("is-viewable");WI.ContentView.ContentViewForRepresentedObjectSymbol=Symbol("content-view-for-represented-object");WI.DataGrid=class DataGrid extends WI.View
{constructor(columnsData,{editCallback,copyCallback,deleteCallback,preferredColumnOrder}={})
{super();this.columns=new Map;this.orderedColumns=[];this._settingsIdentifier=null;this._sortColumnIdentifier=null;this._sortColumnIdentifierSetting=null;this._sortOrder=WI.DataGrid.SortOrder.Indeterminate;this._sortOrderSetting=null;this._columnVisibilitySetting=null;this._columnChooserEnabled=false;this._headerVisible=true;this._rows=[];this.children=[];this.expandNodesWhenArrowing=false;this.root=true;this.hasChildren=false;this.expanded=true;this.revealed=true;this.selected=false;this.dataGrid=this;this.indentWidth=15;this.rowHeight=20;this.resizers=[];this._columnWidthsInitialized=false;this._scrollbarWidth=0;this._cachedScrollTop=NaN;this._cachedScrollableOffsetHeight=NaN;this._previousRevealedRowCount=NaN;this._topDataTableMarginHeight=NaN;this._bottomDataTableMarginHeight=NaN;this._filterText="";this._filterDelegate=null;this._filterDidModifyNodeWhileProcessingItems=false;let itemForRepresentedObject=this.dataGridNodeForSelectionItem.bind(this);let selectionComparator=WI.SelectionController.createTreeComparator(itemForRepresentedObject);this._selectionController=new WI.SelectionController(this,selectionComparator);this._processingSelectionChange=false;this._suppressNextSelectionDidChangeEvent=false;this.element.className="data-grid";this.element.tabIndex=0;this.element.addEventListener("keydown",this._keyDown.bind(this),false);this.element.copyHandler=this;this._headerWrapperElement=document.createElement("div");this._headerWrapperElement.classList.add("header-wrapper");this._headerTableElement=document.createElement("table");this._headerTableElement.className="header";this._headerWrapperElement.appendChild(this._headerTableElement);this._headerTableColumnGroupElement=this._headerTableElement.createChild("colgroup");this._headerTableBodyElement=this._headerTableElement.createChild("tbody");this._headerTableRowElement=this._headerTableBodyElement.createChild("tr");this._headerTableRowElement.addEventListener("contextmenu",this._contextMenuInHeader.bind(this),true);this._headerTableCellElements=new Map;this._scrollContainerElement=document.createElement("div");this._scrollContainerElement.className="data-container";this._scrollListener=()=>this._noteScrollPositionChanged();this._updateScrollListeners();this._topDataTableMarginElement=this._scrollContainerElement.createChild("div");this._dataTableElement=this._scrollContainerElement.createChild("table","data");this._bottomDataTableMarginElement=this._scrollContainerElement.createChild("div");this._dataTableElement.addEventListener("mousedown",this._mouseDownInDataTable.bind(this));this._dataTableElement.addEventListener("click",this._clickInDataTable.bind(this));this._dataTableElement.addEventListener("contextmenu",this._contextMenuInDataTable.bind(this),true);
if(editCallback){this._dataTableElement.addEventListener("dblclick",this._ondblclick.bind(this),false);this._editCallback=editCallback;}
if(copyCallback)
this._copyCallback=copyCallback;if(deleteCallback)
this._deleteCallback=deleteCallback;this._dataTableColumnGroupElement=this._headerTableColumnGroupElement.cloneNode(true);this._dataTableElement.appendChild(this._dataTableColumnGroupElement);this.dataTableBodyElement=this._dataTableElement.createChild("tbody");this._fillerRowElement=this.dataTableBodyElement.createChild("tr","filler");this.element.appendChild(this._headerWrapperElement);this.element.appendChild(this._scrollContainerElement);if(preferredColumnOrder){for(var columnIdentifier of preferredColumnOrder)
this.insertColumn(columnIdentifier,columnsData[columnIdentifier]);}else{for(var columnIdentifier in columnsData)
this.insertColumn(columnIdentifier,columnsData[columnIdentifier]);}
this._updateScrollbarPadding();this._copyTextDelimiter="\t";}
_updateScrollbarPadding()
{if(this._inline)
return;let scrollbarWidth=this._scrollContainerElement.offsetWidth-this._scrollContainerElement.scrollWidth;if(this._scrollbarWidth===scrollbarWidth)
return;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
this._headerWrapperElement.style.setProperty("padding-left",`${scrollbarWidth}px`);else
this._headerWrapperElement.style.setProperty("padding-right",`${scrollbarWidth}px`);this._scrollbarWidth=scrollbarWidth;}
static createSortableDataGrid(columnNames,values)
{var numColumns=columnNames.length;if(!numColumns)
return null;var columnsData={};for(var columnName of columnNames){columnsData[columnName]={width:columnName.length,title:columnName,sortable:true,};}
let dataGrid=new WI.DataGrid(columnsData,{preferredColumnOrder:columnNames});for(var i=0;i<values.length/numColumns;++i){var data={};for(var j=0;j<columnNames.length;++j)
data[columnNames[j]]=values[numColumns*i+j];var node=new WI.DataGridNode(data);dataGrid.appendChild(node);}
function sortDataGrid()
{var sortColumnIdentifier=dataGrid.sortColumnIdentifier;var columnIsNumeric=true;for(var node of dataGrid.children){var value=dataGrid.textForDataGridNodeColumn(node,sortColumnIdentifier);if(isNaN(Number(value)))
columnIsNumeric=false;}
function comparator(dataGridNode1,dataGridNode2)
{var item1=dataGrid.textForDataGridNodeColumn(dataGridNode1,sortColumnIdentifier);var item2=dataGrid.textForDataGridNodeColumn(dataGridNode2,sortColumnIdentifier);var comparison;if(columnIsNumeric){var number1=parseFloat(item1);var number2=parseFloat(item2);comparison=number1<number2?-1:(number1>number2?1:0);}else
comparison=item1<item2?-1:(item1>item2?1:0);return comparison;}
dataGrid.sortNodes(comparator);}
dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,sortDataGrid,this);dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;dataGrid.sortColumnIdentifier=columnNames[0];return dataGrid;}
get headerVisible(){return this._headerVisible;}
set headerVisible(x)
{if(x===this._headerVisible)
return;this._headerVisible=x;this.element.classList.toggle("no-header",!this._headerVisible);}
get columnChooserEnabled(){return this._columnChooserEnabled;}
set columnChooserEnabled(x){this._columnChooserEnabled=x;}
get copyTextDelimiter(){return this._copyTextDelimiter;}
set copyTextDelimiter(x){this._copyTextDelimiter=x;}
get refreshCallback()
{return this._refreshCallback;}
set refreshCallback(refreshCallback)
{this._refreshCallback=refreshCallback;}
get sortOrder()
{return this._sortOrder;}
set sortOrder(order)
{if(!order||order===this._sortOrder)
return;this._sortOrder=order;if(this._sortOrderSetting)
this._sortOrderSetting.value=this._sortOrder;if(!this._sortColumnIdentifier)
return;var sortHeaderCellElement=this._headerTableCellElements.get(this._sortColumnIdentifier);sortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnAscendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Ascending);sortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnDescendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Descending);this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);}
get sortColumnIdentifier()
{return this._sortColumnIdentifier;}
set sortColumnIdentifier(columnIdentifier)
{if(this._sortColumnIdentifier===columnIdentifier)
return;let oldSortColumnIdentifier=this._sortColumnIdentifier;this._sortColumnIdentifier=columnIdentifier;this._updateSortedColumn(oldSortColumnIdentifier);}
get inline(){return this._inline;}
set inline(x)
{if(this._inline===x)
return;this._inline=x||false;this._element.classList.toggle("inline",this._inline);this._updateScrollListeners();}
get variableHeightRows(){return this._variableHeightRows;}
set variableHeightRows(x)
{if(this._variableHeightRows===x)
return;this._variableHeightRows=x||false;this._element.classList.toggle("variable-height-rows",this._variableHeightRows);this._updateScrollListeners();}
get allowsMultipleSelection()
{return this._selectionController.allowsMultipleSelection;}
set allowsMultipleSelection(flag)
{this._selectionController.allowsMultipleSelection=flag;}
get selectedNode()
{return this.dataGridNodeForSelectionItem(this._selectionController.lastSelectedItem);}
set selectedNode(dataGridNode)
{if(dataGridNode)
this._selectionController.selectItem(this.selectionItemForDataGridNode(dataGridNode));else
this._selectionController.deselectAll();}
get selectedDataGridNodes()
{if(this.allowsMultipleSelection){let selectedDataGridNodes=[];for(let item of this._selectionController.selectedItems)
selectedDataGridNodes.push(this.dataGridNodeForSelectionItem(item));return selectedDataGridNodes;}
let selectedNode=this.selectedNode;if(selectedNode)
return[selectedNode];return[];}
get filterText(){return this._filterText;}
set filterText(x)
{if(this._filterText===x)
return;this._filterText=x;this.filterDidChange();}
get filterDelegate(){return this._filterDelegate;}
set filterDelegate(delegate)
{this._filterDelegate=delegate;this.filterDidChange();}
filterDidChange()
{if(this._scheduledFilterUpdateIdentifier)
return;if(this._applyFilterToNodesTask){this._applyFilterToNodesTask.cancel();this._applyFilterToNodesTask=null;}
this._scheduledFilterUpdateIdentifier=requestAnimationFrame(this._updateFilter.bind(this));}
hasFilters()
{return this._textFilterRegex||this._hasFilterDelegate();}
matchNodeAgainstCustomFilters(node)
{if(!this._hasFilterDelegate())
return true;return this._filterDelegate.dataGridMatchNodeAgainstCustomFilters(node);}
createSettings(identifier)
{if(this._settingsIdentifier===identifier)
return;this._settingsIdentifier=identifier;this._sortColumnIdentifierSetting=new WI.Setting(this._settingsIdentifier+"-sort",this._sortColumnIdentifier);this._sortOrderSetting=new WI.Setting(this._settingsIdentifier+"-sort-order",this._sortOrder);this._columnVisibilitySetting=new WI.Setting(this._settingsIdentifier+"-column-visibility",{});if(!this.columns)
return;if(this._sortColumnIdentifierSetting.value){this.sortColumnIdentifier=this._sortColumnIdentifierSetting.value;this.sortOrder=this._sortOrderSetting.value;}
let visibilitySettings=this._columnVisibilitySetting.value;for(let columnIdentifier in visibilitySettings){let visible=visibilitySettings[columnIdentifier];this.setColumnVisible(columnIdentifier,visible);}}
startEditingNode(node)
{if(this._editing||this._editingNode)
return;this._startEditingNodeAtColumnIndex(node,0);}
_updateScrollListeners()
{if(this._inline||this._variableHeightRows){this._scrollContainerElement.removeEventListener("scroll",this._scrollListener);this._scrollContainerElement.removeEventListener("mousewheel",this._scrollListener);}else{this._scrollContainerElement.addEventListener("scroll",this._scrollListener);this._scrollContainerElement.addEventListener("mousewheel",this._scrollListener);}}
_applyFiltersToNodeAndDispatchEvent(node)
{const nodeWasHidden=node.hidden;this._applyFiltersToNode(node);if(nodeWasHidden!==node.hidden)
this.dispatchEventToListeners(WI.DataGrid.Event.NodeWasFiltered,{node});return nodeWasHidden!==node.hidden;}
_applyFiltersToNode(node)
{if(!this.hasFilters()){node.hidden=false;if(node.expanded&&node[WI.DataGrid.WasExpandedDuringFilteringSymbol]){node[WI.DataGrid.WasExpandedDuringFilteringSymbol]=false;node.collapse();}
return;}
let filterableData=node.filterableData||[];let flags={expandNode:false};let filterRegex=this._textFilterRegex;function matchTextFilter()
{if(!filterableData.length||!filterRegex)
return true;if(filterableData.some((value)=>filterRegex.test(value))){flags.expandNode=true;return true;}
return false;}
function makeVisible()
{node.hidden=false;let currentAncestor=node.parent;while(currentAncestor&&!currentAncestor.root){currentAncestor.hidden=false;if(flags.expandNode&&!currentAncestor.expanded){currentAncestor[WI.DataGrid.WasExpandedDuringFilteringSymbol]=true;currentAncestor.expand();}
currentAncestor=currentAncestor.parent;}}
if(matchTextFilter()&&this.matchNodeAgainstCustomFilters(node)){makeVisible();if(!flags.expandNode&&node.expanded&&node[WI.DataGrid.WasExpandedDuringFilteringSymbol]){node[WI.DataGrid.WasExpandedDuringFilteringSymbol]=false;node.collapse();}
return;}
node.hidden=true;}
_updateSortedColumn(oldSortColumnIdentifier)
{if(this._sortColumnIdentifierSetting)
this._sortColumnIdentifierSetting.value=this._sortColumnIdentifier;if(oldSortColumnIdentifier){let oldSortHeaderCellElement=this._headerTableCellElements.get(oldSortColumnIdentifier);oldSortHeaderCellElement.classList.remove(WI.DataGrid.SortColumnAscendingStyleClassName);oldSortHeaderCellElement.classList.remove(WI.DataGrid.SortColumnDescendingStyleClassName);}
if(this._sortColumnIdentifier){let newSortHeaderCellElement=this._headerTableCellElements.get(this._sortColumnIdentifier);newSortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnAscendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Ascending);newSortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnDescendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Descending);}
this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);}
_hasFilterDelegate()
{return this._filterDelegate&&typeof this._filterDelegate.dataGridMatchNodeAgainstCustomFilters==="function";}
_ondblclick(event)
{if(this._editing||this._editingNode)
return;this._startEditing(event.target);}
_startEditingNodeAtColumnIndex(node,columnIndex)
{this.updateLayoutIfNeeded();this._editing=true;this._editingNode=node;this._editingNode.select();var element=this._editingNode.element.children[columnIndex];WI.startEditing(element,this._startEditingConfig(element));window.getSelection().setBaseAndExtent(element,0,element,1);}
_startEditing(target)
{let element=target.closest("td");if(!element)
return;let node=this.dataGridNodeFromNode(target);if(!node.editable)
return;this._editingNode=node;if(!this._editingNode){if(!this.placeholderNode)
return;this._editingNode=this.placeholderNode;} 
if(this._editingNode.isPlaceholderNode)
return this._startEditingNodeAtColumnIndex(this._editingNode,0);this._editing=true;WI.startEditing(element,this._startEditingConfig(element));window.getSelection().setBaseAndExtent(element,0,element,1);}
_startEditingConfig(element)
{return new WI.EditingConfig(this._editingCommitted.bind(this),this._editingCancelled.bind(this),element.textContent);}
_editingCommitted(element,newText,oldText,context,moveDirection)
{var columnIdentifier=element.__columnIdentifier;var columnIndex=this.orderedColumns.indexOf(columnIdentifier);var textBeforeEditing=this._editingNode.data[columnIdentifier]||"";var currentEditingNode=this._editingNode;currentEditingNode.data[columnIdentifier]=newText.trim();

function determineNextCell(valueDidChange){if(moveDirection==="forward"){if(columnIndex<this.orderedColumns.length-1)
return{shouldSort:false,editingNode:currentEditingNode,columnIndex:columnIndex+1};var nextDataGridNode=currentEditingNode.traverseNextNode(true,null,true);return{shouldSort:true,editingNode:nextDataGridNode||currentEditingNode,columnIndex:0};}
if(moveDirection==="backward"){if(columnIndex>0)
return{shouldSort:false,editingNode:currentEditingNode,columnIndex:columnIndex-1};var previousDataGridNode=currentEditingNode.traversePreviousNode(true,null,true);return{shouldSort:true,editingNode:previousDataGridNode||currentEditingNode,columnIndex:this.orderedColumns.length-1};}
return{shouldSort:true};}
function moveToNextCell(valueDidChange){var moveCommand=determineNextCell.call(this,valueDidChange);if(moveCommand.shouldSort&&this._sortAfterEditingCallback){this._sortAfterEditingCallback();this._sortAfterEditingCallback=null;}
if(moveCommand.editingNode)
this._startEditingNodeAtColumnIndex(moveCommand.editingNode,moveCommand.columnIndex);}
this._editingCancelled(element);this._editCallback(currentEditingNode,columnIdentifier,textBeforeEditing,newText,moveDirection);var textDidChange=textBeforeEditing.trim()!==newText.trim();moveToNextCell.call(this,textDidChange);}
_editingCancelled(element)
{this._editingNode.refresh();this._editing=false;this._editingNode=null;}
autoSizeColumns(minPercent,maxPercent,maxDescentLevel)
{if(minPercent)
minPercent=Math.min(minPercent,Math.floor(100/this.orderedColumns.length));var widths={};for(var[identifier,column]of this.columns)
widths[identifier]=(column["title"]||"").length;var children=maxDescentLevel?this._enumerateChildren(this,[],maxDescentLevel+1):this.children;for(var node of children){for(var identifier of this.columns.keys()){var text=this.textForDataGridNodeColumn(node,identifier);if(text.length>widths[identifier])
widths[identifier]=text.length;}}
var totalColumnWidths=0;for(var identifier of this.columns.keys())
totalColumnWidths+=widths[identifier];var recoupPercent=0;for(var identifier of this.columns.keys()){var width=Math.round(100*widths[identifier]/totalColumnWidths);if(minPercent&&width<minPercent){recoupPercent+=minPercent-width;width=minPercent;}else if(maxPercent&&width>maxPercent){recoupPercent-=width-maxPercent;width=maxPercent;}
widths[identifier]=width;}
while(minPercent&&recoupPercent>0){for(var identifier of this.columns.keys()){if(widths[identifier]>minPercent){--widths[identifier];--recoupPercent;if(!recoupPercent)
break;}}}
while(maxPercent&&recoupPercent<0){for(var identifier of this.columns.keys()){if(widths[identifier]<maxPercent){++widths[identifier];++recoupPercent;if(!recoupPercent)
break;}}}
for(var[identifier,column]of this.columns){column["element"].style.width=widths[identifier]+"%";column["bodyElement"].style.width=widths[identifier]+"%";}
this._columnWidthsInitialized=false;this.needsLayout();}
insertColumn(columnIdentifier,columnData,insertionIndex)
{if(insertionIndex===undefined)
insertionIndex=this.orderedColumns.length;insertionIndex=Number.constrain(insertionIndex,0,this.orderedColumns.length);var column=Object.shallowCopy(columnData);column["ordinal"]=insertionIndex;column["columnIdentifier"]=columnIdentifier;this.orderedColumns.splice(insertionIndex,0,columnIdentifier);for(var[identifier,existingColumn]of this.columns){var ordinal=existingColumn["ordinal"];if(ordinal>=insertionIndex)
existingColumn["ordinal"]=ordinal+1;}
this.columns.set(columnIdentifier,column);if(column["disclosure"])
this.disclosureColumnIdentifier=columnIdentifier;var headerColumnElement=document.createElement("col");if(column["width"])
headerColumnElement.style.width=column["width"];column["element"]=headerColumnElement;var referenceElement=this._headerTableColumnGroupElement.children[insertionIndex];this._headerTableColumnGroupElement.insertBefore(headerColumnElement,referenceElement);var headerCellElement=document.createElement("th");headerCellElement.className=columnIdentifier+"-column";headerCellElement.columnIdentifier=columnIdentifier;if(column["aligned"])
headerCellElement.classList.add(column["aligned"]);this._headerTableCellElements.set(columnIdentifier,headerCellElement);var referenceElement=this._headerTableRowElement.children[insertionIndex];this._headerTableRowElement.insertBefore(headerCellElement,referenceElement);if(column["headerView"]){let headerView=column["headerView"];headerView.element.classList.add("header-cell-content");headerCellElement.appendChild(headerView.element);this.addSubview(headerView);}else{let titleElement=headerCellElement.createChild("div","header-cell-content");if(column["titleDOMFragment"])
titleElement.appendChild(column["titleDOMFragment"]);else
titleElement.textContent=column["title"]||"";}
if(column["sortable"]){headerCellElement.addEventListener("click",this._headerCellClicked.bind(this));headerCellElement.classList.add(WI.DataGrid.SortableColumnStyleClassName);}
if(column["group"])
headerCellElement.classList.add("column-group-"+column["group"]);if(column["tooltip"])
headerCellElement.title=column["tooltip"];if(column["collapsesGroup"]){headerCellElement.createChild("div","divider");var collapseDiv=headerCellElement.createChild("div","collapser-button");collapseDiv.title=this._collapserButtonCollapseColumnsToolTip();collapseDiv.addEventListener("mouseover",this._mouseoverColumnCollapser.bind(this));collapseDiv.addEventListener("mouseout",this._mouseoutColumnCollapser.bind(this));collapseDiv.addEventListener("click",this._clickInColumnCollapser.bind(this));headerCellElement.collapsesGroup=column["collapsesGroup"];headerCellElement.classList.add("collapser");}
this._headerTableColumnGroupElement.span=this.orderedColumns.length;var dataColumnElement=headerColumnElement.cloneNode();var referenceElement=this._dataTableColumnGroupElement.children[insertionIndex];this._dataTableColumnGroupElement.insertBefore(dataColumnElement,referenceElement);column["bodyElement"]=dataColumnElement;var fillerCellElement=document.createElement("td");fillerCellElement.className=columnIdentifier+"-column";fillerCellElement.__columnIdentifier=columnIdentifier;if(column["group"])
fillerCellElement.classList.add("column-group-"+column["group"]);var referenceElement=this._fillerRowElement.children[insertionIndex];this._fillerRowElement.insertBefore(fillerCellElement,referenceElement);this.setColumnVisible(columnIdentifier,!column.hidden);}
removeColumn(columnIdentifier)
{var removedColumn=this.columns.get(columnIdentifier);this.columns.delete(columnIdentifier);this.orderedColumns.splice(this.orderedColumns.indexOf(columnIdentifier),1);var removedOrdinal=removedColumn["ordinal"];for(var[identifier,column]of this.columns){var ordinal=column["ordinal"];if(ordinal>removedOrdinal)
column["ordinal"]=ordinal-1;}
if(removedColumn["disclosure"])
this.disclosureColumnIdentifier=undefined;if(this.sortColumnIdentifier===columnIdentifier)
this.sortColumnIdentifier=null;this._headerTableCellElements.delete(columnIdentifier);this._headerTableRowElement.children[removedOrdinal].remove();this._headerTableColumnGroupElement.children[removedOrdinal].remove();this._dataTableColumnGroupElement.children[removedOrdinal].remove();this._fillerRowElement.children[removedOrdinal].remove();this._headerTableColumnGroupElement.span=this.orderedColumns.length;for(var child of this.children)
child.refresh();}
_enumerateChildren(rootNode,result,maxLevel)
{if(!rootNode.root)
result.push(rootNode);if(!maxLevel)
return;for(var i=0;i<rootNode.children.length;++i)
this._enumerateChildren(rootNode.children[i],result,maxLevel-1);return result;}





layout()
{if(!this._columnWidthsInitialized&&this.element.offsetWidth){

let headerTableColumnElements=this._headerTableColumnGroupElement.children;let tableWidth=this._dataTableElement.offsetWidth;let numColumns=headerTableColumnElements.length;let cells=this._headerTableBodyElement.rows[0].cells;let columnWidths=[];for(let i=0;i<numColumns;++i){let headerCellElement=cells[i];if(this.isColumnVisible(headerCellElement.columnIdentifier)){let columnWidth=headerCellElement.offsetWidth;let percentWidth=((columnWidth/tableWidth)*100)+"%";columnWidths.push(percentWidth);}else
columnWidths.push(0);}
for(let i=0;i<numColumns;i++){let percentWidth=columnWidths[i];this._headerTableColumnGroupElement.children[i].style.width=percentWidth;this._dataTableColumnGroupElement.children[i].style.width=percentWidth;}
this._columnWidthsInitialized=true;this._updateHeaderAndScrollbar();}
this.updateVisibleRows();}
sizeDidChange()
{this._updateHeaderAndScrollbar();}
_updateHeaderAndScrollbar()
{this._positionResizerElements();this._positionHeaderViews();this._updateScrollbarPadding();this._cachedScrollTop=NaN;this._cachedScrollableOffsetHeight=NaN;}
isColumnVisible(columnIdentifier)
{return!this.columns.get(columnIdentifier)["hidden"];}
setColumnVisible(columnIdentifier,visible)
{let column=this.columns.get(columnIdentifier);if(!column||visible===!column.hidden)
return;column.element.style.width=visible?column.width:0;column.hidden=!visible;if(this._columnVisibilitySetting){if(this._columnVisibilitySetting.value[columnIdentifier]!==visible){let copy=Object.shallowCopy(this._columnVisibilitySetting.value);copy[columnIdentifier]=visible;this._columnVisibilitySetting.value=copy;}}
this._columnWidthsInitialized=false;this.updateLayout();}
get scrollContainer()
{return this._scrollContainerElement;}
isScrolledToLastRow()
{return this._scrollContainerElement.isScrolledToBottom();}
scrollToLastRow()
{this._scrollContainerElement.scrollTop=this._scrollContainerElement.scrollHeight-this._scrollContainerElement.offsetHeight;}
_positionResizerElements()
{let leadingOffset=0;var previousResizer=null;var numResizers=this.orderedColumns.length-1;

var cells=this._headerTableBodyElement.rows[0].cells;var columnWidths=[];for(var i=0;i<numResizers;++i){leadingOffset+=cells[i].getBoundingClientRect().width;columnWidths.push(leadingOffset);}
for(var i=0;i<numResizers;++i){var resizer=this.resizers[i];if(!resizer){resizer=this.resizers[i]=new WI.Resizer(WI.Resizer.RuleOrientation.Vertical,this);this.element.appendChild(resizer.element);}
leadingOffset=columnWidths[i];if(this.isColumnVisible(this.orderedColumns[i])){resizer.element.style.removeProperty("display");resizer.element.style.setProperty(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left",`${leadingOffset}px`);resizer[WI.DataGrid.PreviousColumnOrdinalSymbol]=i;if(previousResizer)
previousResizer[WI.DataGrid.NextColumnOrdinalSymbol]=i;previousResizer=resizer;}else{resizer.element.style.setProperty("display","none");resizer[WI.DataGrid.PreviousColumnOrdinalSymbol]=0;resizer[WI.DataGrid.NextColumnOrdinalSymbol]=0;}}
if(previousResizer)
previousResizer[WI.DataGrid.NextColumnOrdinalSymbol]=this.orderedColumns.length-1;}
_positionHeaderViews()
{let leadingOffset=0;let headerViews=[];let offsets=[];let columnWidths=[];for(let columnIdentifier of this.orderedColumns){let column=this.columns.get(columnIdentifier);if(!column)
continue;let columnWidth=this._headerTableCellElements.get(columnIdentifier).offsetWidth;let headerView=column["headerView"];if(headerView){headerViews.push(headerView);offsets.push(leadingOffset);columnWidths.push(columnWidth);}
leadingOffset+=columnWidth;}
for(let i=0;i<headerViews.length;++i){let headerView=headerViews[i];headerView.element.style.setProperty(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left",`${offsets[i]}px`);headerView.element.style.width=columnWidths[i]+"px";headerView.updateLayout(WI.View.LayoutReason.Resize);}}
_noteRowsChanged()
{this._previousRevealedRowCount=NaN;this.needsLayout();}
_noteRowRemoved(dataGridNode)
{if(this._inline||this._variableHeightRows){
if(dataGridNode.element&&dataGridNode.element.parentNode)
dataGridNode.element.parentNode.removeChild(dataGridNode.element);return;}
this._noteRowsChanged();}
_noteScrollPositionChanged()
{this._cachedScrollTop=NaN;this.needsLayout();}
updateVisibleRows(focusedDataGridNode)
{if(this._inline||this._variableHeightRows){


let nextElement=this.dataTableBodyElement.lastChild;for(let i=this._rows.length-1;i>=0;--i){let rowElement=this._rows[i].element;if(rowElement.nextSibling!==nextElement)
this.dataTableBodyElement.insertBefore(rowElement,nextElement);nextElement=rowElement;}
if(focusedDataGridNode)
focusedDataGridNode.element.scrollIntoViewIfNeeded(false);return;}
let rowHeight=this.rowHeight;let updateOffsetThreshold=rowHeight*5;let overflowPadding=updateOffsetThreshold*3;if(isNaN(this._cachedScrollTop))
this._cachedScrollTop=this._scrollContainerElement.scrollTop;if(isNaN(this._cachedScrollableOffsetHeight))
this._cachedScrollableOffsetHeight=this._scrollContainerElement.offsetHeight;let visibleRowCount=Math.ceil((this._cachedScrollableOffsetHeight+(overflowPadding*2))/rowHeight);if(!focusedDataGridNode){let currentTopMargin=this._topDataTableMarginHeight;let currentBottomMargin=this._bottomDataTableMarginHeight;let currentTableBottom=currentTopMargin+(visibleRowCount*rowHeight);let belowTopThreshold=!currentTopMargin||this._cachedScrollTop>currentTopMargin+updateOffsetThreshold;let aboveBottomThreshold=!currentBottomMargin||this._cachedScrollTop+this._cachedScrollableOffsetHeight<currentTableBottom-updateOffsetThreshold;if(belowTopThreshold&&aboveBottomThreshold&&!isNaN(this._previousRevealedRowCount))
return;}
let revealedRows=this._rows.filter((row)=>row.revealed&&!row.hidden);this._previousRevealedRowCount=revealedRows.length;if(focusedDataGridNode){let focusedIndex=revealedRows.indexOf(focusedDataGridNode);let firstVisibleRowIndex=this._cachedScrollTop/rowHeight;if(focusedIndex<firstVisibleRowIndex||focusedIndex>firstVisibleRowIndex+visibleRowCount)
this._scrollContainerElement.scrollTop=this._cachedScrollTop=(focusedIndex*rowHeight)-(this._cachedScrollableOffsetHeight/2)+(rowHeight/2);}
let topHiddenRowCount=Math.max(0,Math.floor((this._cachedScrollTop-overflowPadding)/rowHeight));let bottomHiddenRowCount=Math.max(0,this._previousRevealedRowCount-topHiddenRowCount-visibleRowCount);let marginTop=topHiddenRowCount*rowHeight;let marginBottom=bottomHiddenRowCount*rowHeight;if(this._topDataTableMarginHeight!==marginTop){this._topDataTableMarginHeight=marginTop;this._topDataTableMarginElement.style.height=marginTop+"px";}
if(this._bottomDataTableMarginElement!==marginBottom){this._bottomDataTableMarginHeight=marginBottom;this._bottomDataTableMarginElement.style.height=marginBottom+"px";}
this._dataTableElement.classList.toggle("even-first-zebra-stripe",!!(topHiddenRowCount%2));this.dataTableBodyElement.removeChildren();for(let i=topHiddenRowCount;i<topHiddenRowCount+visibleRowCount;++i){let rowDataGridNode=revealedRows[i];if(!rowDataGridNode)
continue;this.dataTableBodyElement.appendChild(rowDataGridNode.element);}
this.dataTableBodyElement.appendChild(this._fillerRowElement);}
addPlaceholderNode()
{if(this.placeholderNode)
this.placeholderNode.makeNormal();var emptyData={};for(var identifier of this.columns.keys())
emptyData[identifier]="";this.placeholderNode=new WI.PlaceholderDataGridNode(emptyData);this.appendChild(this.placeholderNode);}
appendChild(child)
{this.insertChild(child,this.children.length);}
insertChild(child,index)
{if(!child)
return;if(child.parent===this)
return;if(child.parent)
child.parent.removeChild(child);this.children.splice(index,0,child);this.hasChildren=true;child.parent=this;child.dataGrid=this.dataGrid;child._recalculateSiblings(index);delete child._depth;delete child._revealed;delete child._attached;delete child._leftPadding;child._shouldRefreshChildren=true;var current=child.children[0];while(current){current.dataGrid=this.dataGrid;delete current._depth;delete current._revealed;delete current._attached;delete current._leftPadding;current._shouldRefreshChildren=true;current=current.traverseNextNode(false,child,true);}
if(this.expanded)
child._attach();if(!this.dataGrid.hasFilters())
return;this.dataGrid._applyFiltersToNodeAndDispatchEvent(child);}
removeChild(child)
{if(!child)
return;if(child.parent!==this)
return;let wasSelected=this.selectedNode===child||child.selected;child.deselect();child._detach();this.children.remove(child,true);if(child.previousSibling)
child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling)
child.nextSibling.previousSibling=child.previousSibling;let nextChildToSelect=wasSelected?(child.nextSibling||child.previousSibling):null;child.dataGrid=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;if(this.children.length<=0)
this.hasChildren=false;else if(nextChildToSelect)
nextChildToSelect.select();}
removeChildren()
{for(var i=0;i<this.children.length;++i){var child=this.children[i];child.deselect();child._detach();child.dataGrid=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;}
this.children=[];this.hasChildren=false;}
findNode(comparator,skipHidden,stayWithin,dontPopulate)
{let currentNode=this._rows[0];while(currentNode&&!currentNode.root){if(!currentNode.isPlaceholderNode&&!(skipHidden&&currentNode.hidden)){if(comparator(currentNode))
return currentNode;}
currentNode=currentNode.traverseNextNode(skipHidden,stayWithin,dontPopulate);}
return null;}
sortNodes(comparator)
{this._sortNodesComparator=comparator;if(this._sortNodesRequestId)
return;this._sortNodesRequestId=window.requestAnimationFrame(()=>{if(this._sortNodesComparator)
this._sortNodesCallback(this._sortNodesComparator);});}
sortNodesImmediately(comparator)
{this._sortNodesCallback(comparator);}
_sortNodesCallback(comparator)
{function comparatorWrapper(aNode,bNode)
{if(aNode.isPlaceholderNode)
return 1;if(bNode.isPlaceholderNode)
return-1;var reverseFactor=this.sortOrder!==WI.DataGrid.SortOrder.Ascending?-1:1;return reverseFactor*comparator(aNode,bNode);}
this._sortNodesRequestId=undefined;this._sortNodesComparator=null;if(this._editing){this._sortAfterEditingCallback=this.sortNodes.bind(this,comparator);return;}
this._rows.sort(comparatorWrapper.bind(this));this._noteRowsChanged();let previousSiblingNode=null;for(let node of this._rows){node.previousSibling=previousSiblingNode;if(previousSiblingNode)
previousSiblingNode.nextSibling=node;previousSiblingNode=node;}
if(previousSiblingNode)
previousSiblingNode.nextSibling=null;if(!this.parentView)
this.updateLayoutIfNeeded();}
_toggledSortOrder()
{return this._sortOrder!==WI.DataGrid.SortOrder.Descending?WI.DataGrid.SortOrder.Descending:WI.DataGrid.SortOrder.Ascending;}
_selectSortColumnAndSetOrder(columnIdentifier,sortOrder)
{this.sortColumnIdentifier=columnIdentifier;this.sortOrder=sortOrder;}
_keyDown(event)
{if(this._editing)
return;let isRTL=WI.resolveLayoutDirectionForElement(this.element)===WI.LayoutDirection.RTL;let expandKeyIdentifier=isRTL?"Left":"Right";let collapseKeyIdentifier=isRTL?"Right":"Left";var handled=false;var nextSelectedNode;if(this.selectedNode){if(event.keyIdentifier===collapseKeyIdentifier){if(this.selectedNode.expanded){if(event.altKey)
this.selectedNode.collapseRecursively();else
this.selectedNode.collapse();handled=true;}else if(this.selectedNode.parent&&!this.selectedNode.parent.root){handled=true;if(this.selectedNode.parent.selectable){nextSelectedNode=this.selectedNode.parent;while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.parent;handled=!!nextSelectedNode;}else if(this.selectedNode.parent)
this.selectedNode.parent.collapse();}}else if(event.keyIdentifier===expandKeyIdentifier){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];while(nextSelectedNode&&!nextSelectedNode.selectable)
nextSelectedNode=nextSelectedNode.nextSibling;handled=!!nextSelectedNode;}else{if(event.altKey)
this.selectedNode.expandRecursively();else
this.selectedNode.expand();}}}else if(event.keyCode===8||event.keyCode===46){if(this._deleteCallback){handled=true;this._deleteCallback(this.selectedNode);}}else if(isEnterKey(event)){if(this._editCallback){handled=true;this._startEditing(this.selectedNode.element.children[0]);}}}
if(!handled){handled=this._selectionController.handleKeyDown(event);if(handled)
nextSelectedNode=this.selectedNode;}
if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();}
if(handled){event.preventDefault();event.stopPropagation();}}
closed()
{}
expand()
{}
collapse()
{}
reveal()
{}
revealAndSelect()
{}
selectNodes(nodes)
{if(!nodes.length)
return;if(nodes.length===1){this.selectedNode=nodes[0];return;}
if(!this.allowsMultipleSelection)
return;let selectableObjects=nodes.map((node)=>this.selectionItemForDataGridNode(node));this._selectionController.selectItems(new Set(selectableObjects));}
dataGridNodeFromNode(target)
{var rowElement=target.closest("tr");return rowElement&&rowElement._dataGridNode;}
dataGridNodeFromPoint(x,y)
{var node=this._dataTableElement.ownerDocument.elementFromPoint(x,y);var rowElement=node.closest("tr");return rowElement&&rowElement._dataGridNode;}
_headerCellClicked(event)
{let cell=event.target.closest("th");if(!cell||!cell.columnIdentifier||!cell.classList.contains(WI.DataGrid.SortableColumnStyleClassName))
return;let sortOrder=this._sortColumnIdentifier===cell.columnIdentifier?this._toggledSortOrder():this.sortOrder;this._selectSortColumnAndSetOrder(cell.columnIdentifier,sortOrder);}
_mouseoverColumnCollapser(event)
{var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup)
return;cell.classList.add("mouse-over-collapser");}
_mouseoutColumnCollapser(event)
{var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup)
return;cell.classList.remove("mouse-over-collapser");}
_clickInColumnCollapser(event)
{var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup)
return;this._collapseColumnGroupWithCell(cell);event.stopPropagation();event.preventDefault();}
collapseColumnGroup(columnGroup)
{var collapserColumnIdentifier=null;for(var[identifier,column]of this.columns){if(column["collapsesGroup"]===columnGroup){collapserColumnIdentifier=identifier;break;}}
if(!collapserColumnIdentifier)
return;var cell=this._headerTableCellElements.get(collapserColumnIdentifier);this._collapseColumnGroupWithCell(cell);}
_collapseColumnGroupWithCell(cell)
{var columnsWillCollapse=cell.classList.toggle("collapsed");this.willToggleColumnGroup(cell.collapsesGroup,columnsWillCollapse);for(var[identifier,column]of this.columns){if(column["group"]===cell.collapsesGroup)
this.setColumnVisible(identifier,!columnsWillCollapse);}
var collapserButton=cell.querySelector(".collapser-button");if(collapserButton)
collapserButton.title=columnsWillCollapse?this._collapserButtonExpandColumnsToolTip():this._collapserButtonCollapseColumnsToolTip();this.didToggleColumnGroup(cell.collapsesGroup,columnsWillCollapse);}
_collapserButtonCollapseColumnsToolTip()
{return WI.UIString("Collapse columns");}
_collapserButtonExpandColumnsToolTip()
{return WI.UIString("Expand columns");}
willToggleColumnGroup(columnGroup,willCollapse)
{}
didToggleColumnGroup(columnGroup,didCollapse)
{}
headerTableHeader(columnIdentifier)
{return this._headerTableCellElements.get(columnIdentifier);}
_mouseDownInDataTable(event)
{let dataGridNode=this.dataGridNodeFromNode(event.target);if(!dataGridNode){this._selectionController.deselectAll();return;}
if(!dataGridNode.selectable||dataGridNode.isEventWithinDisclosureTriangle(event))
return;this._selectionController.handleItemMouseDown(this.selectionItemForDataGridNode(dataGridNode),event);}
_contextMenuInHeader(event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);if(this._hasCopyableData())
contextMenu.appendItem(WI.UIString("Copy Table"),this._copyTable.bind(this));let headerCellElement=event.target.closest("th");if(!headerCellElement)
return;let columnIdentifier=headerCellElement.columnIdentifier;let column=this.columns.get(columnIdentifier);if(!column)
return;if(column.sortable){contextMenu.appendSeparator();if(this.sortColumnIdentifier!==columnIdentifier||this.sortOrder!==WI.DataGrid.SortOrder.Ascending){contextMenu.appendItem(WI.UIString("Sort Ascending"),()=>{this._selectSortColumnAndSetOrder(columnIdentifier,WI.DataGrid.SortOrder.Ascending);});}
if(this.sortColumnIdentifier!==columnIdentifier||this.sortOrder!==WI.DataGrid.SortOrder.Descending){contextMenu.appendItem(WI.UIString("Sort Descending"),()=>{this._selectSortColumnAndSetOrder(columnIdentifier,WI.DataGrid.SortOrder.Descending);});}}
if(this._columnChooserEnabled){let didAddSeparator=false;for(let[identifier,columnInfo]of this.columns){if(columnInfo.locked)
continue;if(!didAddSeparator){contextMenu.appendSeparator();didAddSeparator=true;const disabled=true;contextMenu.appendItem(WI.UIString("Displayed Columns"),()=>{},disabled);}
contextMenu.appendCheckboxItem(columnInfo.title,()=>{this.setColumnVisible(identifier,!!columnInfo.hidden);},!columnInfo.hidden);}}}
_contextMenuInDataTable(event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);let gridNode=this.dataGridNodeFromNode(event.target);if(gridNode)
gridNode.appendContextMenuItems(contextMenu);if(this.dataGrid._refreshCallback&&(!gridNode||gridNode!==this.placeholderNode))
contextMenu.appendItem(WI.UIString("Refresh"),this._refreshCallback.bind(this));if(gridNode){if(gridNode.selectable&&gridNode.copyable&&!gridNode.isEventWithinDisclosureTriangle(event)){contextMenu.appendItem(WI.UIString("Copy Row"),this._copyRow.bind(this,gridNode));contextMenu.appendItem(WI.UIString("Copy Table"),this._copyTable.bind(this));if(this.dataGrid._editCallback){if(gridNode===this.placeholderNode)
contextMenu.appendItem(WI.UIString("Add New"),this._startEditing.bind(this,event.target));else if(gridNode.editable){let element=event.target.closest("td");let columnIdentifier=element.__columnIdentifier;let columnTitle=this.dataGrid.columns.get(columnIdentifier)["title"];contextMenu.appendItem(WI.UIString("Edit %s").format(columnTitle),this._startEditing.bind(this,event.target));}}
if(this.dataGrid._deleteCallback&&gridNode!==this.placeholderNode&&gridNode.editable)
contextMenu.appendItem(WI.UIString("Delete"),this._deleteCallback.bind(this,gridNode));}
if(gridNode.children.some((child)=>child.hasChildren)||(gridNode.hasChildren&&!gridNode.children.length)){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Expand All"),gridNode.expandRecursively.bind(gridNode));contextMenu.appendItem(WI.UIString("Collapse All"),gridNode.collapseRecursively.bind(gridNode));}}}
_clickInDataTable(event)
{var gridNode=this.dataGridNodeFromNode(event.target);if(!gridNode||!gridNode.hasChildren)
return;if(!gridNode.isEventWithinDisclosureTriangle(event))
return;if(gridNode.expanded){if(event.altKey)
gridNode.collapseRecursively();else
gridNode.collapse();}else{if(event.altKey)
gridNode.expandRecursively();else
gridNode.expand();}}
textForDataGridNodeColumn(node,columnIdentifier)
{var data=node.data[columnIdentifier];return(data instanceof Node?data.textContent:data)||"";}
_copyTextForDataGridNode(node)
{let fields=node.dataGrid.orderedColumns.map((identifier)=>{let text=this.textForDataGridNodeColumn(node,identifier);if(this._copyCallback)
text=this._copyCallback(node,identifier,text);return text;});return fields.join(this._copyTextDelimiter);}
_copyTextForDataGridHeaders()
{let fields=this.orderedColumns.map((identifier)=>this.headerTableHeader(identifier).textContent);return fields.join(this._copyTextDelimiter);}
handleBeforeCopyEvent(event)
{if(this.selectedNode&&window.getSelection().isCollapsed)
event.preventDefault();}
handleCopyEvent(event)
{if(!window.getSelection().isCollapsed)
return;let copyData=[];for(let dataGridNode of this.selectedDataGridNodes){if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode)
continue;copyData.push(this._copyTextForDataGridNode(dataGridNode));}
if(!copyData.length)
return;event.clipboardData.setData("text/plain",copyData.join("\n"));event.stopPropagation();event.preventDefault();}
_copyRow(dataGridNode)
{if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode)
return;let copyText=this._copyTextForDataGridNode(dataGridNode);InspectorFrontendHost.copyText(copyText);}
_copyTable()
{let copyData=[];copyData.push(this._copyTextForDataGridHeaders());for(let dataGridNode of this._rows){if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode)
continue;copyData.push(this._copyTextForDataGridNode(dataGridNode));}
if(!copyData.length)
return;InspectorFrontendHost.copyText(copyData.join("\n"));}
_hasCopyableData()
{const skipHidden=true;const stayWithin=null;const dontPopulate=true;let dataGridNode=this._rows[0];while(dataGridNode&&(!dataGridNode.selectable||!dataGridNode.copyable||dataGridNode.isPlaceholderNode))
dataGridNode=dataGridNode.traverseNextNode(skipHidden,stayWithin,dontPopulate);return!!dataGridNode;}
resizerDragStarted(resizer)
{if(!resizer[WI.DataGrid.NextColumnOrdinalSymbol])
return true;this._currentResizer=resizer;}
resizerDragging(resizer,positionDelta)
{if(resizer!==this._currentResizer)
return;let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;if(isRTL)
positionDelta*=-1;let dragPoint=0;if(isRTL)
dragPoint+=this.element.totalOffsetRight-resizer.initialPosition-positionDelta;else
dragPoint+=resizer.initialPosition-this.element.totalOffsetLeft-positionDelta;
var leftColumnIndex=resizer[WI.DataGrid.PreviousColumnOrdinalSymbol];var rightColumnIndex=resizer[WI.DataGrid.NextColumnOrdinalSymbol];var firstRowCells=this._headerTableBodyElement.rows[0].cells;let leadingEdgeOfPreviousColumn=0;for(let i=0;i<leftColumnIndex;++i)
leadingEdgeOfPreviousColumn+=firstRowCells[i].offsetWidth;let trailingEdgeOfNextColumn=leadingEdgeOfPreviousColumn+firstRowCells[leftColumnIndex].offsetWidth+firstRowCells[rightColumnIndex].offsetWidth;let leftMinimum=leadingEdgeOfPreviousColumn+WI.DataGrid.ColumnResizePadding;let rightMaximum=trailingEdgeOfNextColumn-WI.DataGrid.ColumnResizePadding;dragPoint=Number.constrain(dragPoint,leftMinimum,rightMaximum);resizer.element.style.setProperty(isRTL?"right":"left",`${dragPoint - this.CenterResizerOverBorderAdjustment}px`);let percentLeftColumn=(((dragPoint-leadingEdgeOfPreviousColumn)/this._dataTableElement.offsetWidth)*100)+"%";this._headerTableColumnGroupElement.children[leftColumnIndex].style.width=percentLeftColumn;this._dataTableColumnGroupElement.children[leftColumnIndex].style.width=percentLeftColumn;let percentRightColumn=(((trailingEdgeOfNextColumn-dragPoint)/this._dataTableElement.offsetWidth)*100)+"%";this._headerTableColumnGroupElement.children[rightColumnIndex].style.width=percentRightColumn;this._dataTableColumnGroupElement.children[rightColumnIndex].style.width=percentRightColumn;this._positionResizerElements();this._positionHeaderViews();const skipHidden=true;const dontPopulate=true;let leftColumnIdentifier=this.orderedColumns[leftColumnIndex];let rightColumnIdentifier=this.orderedColumns[rightColumnIndex];let child=this.children[0];while(child){child.didResizeColumn(leftColumnIdentifier);child.didResizeColumn(rightColumnIdentifier);child=child.traverseNextNode(skipHidden,this,dontPopulate);}
event.preventDefault();}
resizerDragEnded(resizer)
{if(resizer!==this._currentResizer)
return;this._currentResizer=null;}
_updateFilter()
{if(this._scheduledFilterUpdateIdentifier){cancelAnimationFrame(this._scheduledFilterUpdateIdentifier);this._scheduledFilterUpdateIdentifier=undefined;}
if(!this._rows.length)
return;this._textFilterRegex=this._filterText?WI.SearchUtilities.filterRegExpForString(this._filterText,WI.SearchUtilities.defaultSettings):null;if(this._applyFilterToNodesTask&&this._applyFilterToNodesTask.processing)
this._applyFilterToNodesTask.cancel();function*createIteratorForNodesToBeFiltered()
{let hasFilters=this.hasFilters();let currentNode=this._rows[0];while(currentNode&&!currentNode.root){yield currentNode;let dontPopulate=!hasFilters;if(hasFilters&&this._filterDelegate&&this._filterDelegate.dataGridMatchShouldPopulateWhenFilteringNode)
dontPopulate=this._filterDelegate.dataGridMatchShouldPopulateWhenFilteringNode(currentNode);currentNode=currentNode.traverseNextNode(false,null,dontPopulate);}}
let items=createIteratorForNodesToBeFiltered.call(this);this._applyFilterToNodesTask=new WI.YieldableTask(this,items,{workInterval:100});this._filterDidModifyNodeWhileProcessingItems=false;this._applyFilterToNodesTask.start();}
selectDataGridNodeInternal(dataGridNode,suppressSelectedEvent)
{if(this._processingSelectionChange)
return;this._suppressNextSelectionDidChangeEvent=suppressSelectedEvent;this._selectionController.selectItem(this.selectionItemForDataGridNode(dataGridNode));}
deselectDataGridNodeInternal(dataGridNode,suppressDeselectedEvent)
{if(this._processingSelectionChange)
return;this._suppressNextSelectionDidChangeEvent=suppressDeselectedEvent;this._selectionController.deselectItem(this.selectionItemForDataGridNode(dataGridNode));}
_dispatchSelectedNodeChangedEvent()
{if(this._suppressNextSelectionDidChangeEvent){this._suppressNextSelectionDidChangeEvent=false;return;}
this.dispatchEventToListeners(WI.DataGrid.Event.SelectedNodeChanged);} 
yieldableTaskWillProcessItem(task,node)
{let nodeWasModified=this._applyFiltersToNodeAndDispatchEvent(node);if(nodeWasModified)
this._filterDidModifyNodeWhileProcessingItems=true;}
yieldableTaskDidYield(task,processedItems,elapsedTime)
{if(!this._filterDidModifyNodeWhileProcessingItems)
return;this._filterDidModifyNodeWhileProcessingItems=false;this.dispatchEventToListeners(WI.DataGrid.Event.FilterDidChange);}
yieldableTaskDidFinish(task)
{this._applyFilterToNodesTask=null;} 
dataGridNodeForSelectionItem(item)
{return item;}
selectionItemForDataGridNode(dataGridNode)
{return dataGridNode;}
selectionControllerSelectionDidChange(selectionController,deselectedItems,selectedItems)
{this._processingSelectionChange=true;for(let item of deselectedItems){let dataGridNode=this.dataGridNodeForSelectionItem(item);dataGridNode?.deselect();}
for(let item of selectedItems){let dataGridNode=this.dataGridNodeForSelectionItem(item);dataGridNode?.select();}
this._dispatchSelectedNodeChangedEvent();this._processingSelectionChange=false;}
selectionControllerFirstSelectableItem(controller,operation)
{let firstChild=this._rows[0];let item=this.selectionItemForDataGridNode(firstChild);if(firstChild.selectable&&(!firstChild.isPlaceholderNode||operation===WI.SelectionController.Operation.Direct))
return item;return this.selectionControllerNextSelectableItem(controller,item,operation);}
selectionControllerLastSelectableItem(controller,operation)
{let lastChild=this._rows.lastValue;while(lastChild.expanded&&lastChild.children.length)
lastChild=lastChild.children.lastValue;let item=this.selectionItemForDataGridNode(lastChild);if(lastChild.selectable&&(!lastChild.isPlaceholderNode||operation===WI.SelectionController.Operation.Direct))
return item;return this.selectionControllerPreviousSelectableItem(controller,item,operation);}
selectionControllerPreviousSelectableItem(controller,item,operation)
{let dataGridNode=this.dataGridNodeForSelectionItem(item);if(!dataGridNode)
return null;const skipUnrevealed=true;const dontPopulate=true;while(dataGridNode=dataGridNode.traversePreviousNode(skipUnrevealed,dontPopulate)){if(dataGridNode.selectable&&(!dataGridNode.isPlaceholderNode||operation===WI.SelectionController.Operation.Direct))
return this.selectionItemForDataGridNode(dataGridNode);}
return null;}
selectionControllerNextSelectableItem(controller,item,operation)
{let dataGridNode=this.dataGridNodeForSelectionItem(item);if(!dataGridNode)
return null;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(dataGridNode=dataGridNode.traverseNextNode(skipUnrevealed,stayWithin,dontPopulate)){if(dataGridNode.selectable&&(!dataGridNode.isPlaceholderNode||operation===WI.SelectionController.Operation.Direct))
return this.selectionItemForDataGridNode(dataGridNode);}
return null;}};WI.DataGrid.Event={SortChanged:"datagrid-sort-changed",SelectedNodeChanged:"datagrid-selected-node-changed",ExpandedNode:"datagrid-expanded-node",CollapsedNode:"datagrid-collapsed-node",FilterDidChange:"datagrid-filter-did-change",NodeWasFiltered:"datagrid-node-was-filtered"};WI.DataGrid.SortOrder={Indeterminate:"data-grid-sort-order-indeterminate",Ascending:"data-grid-sort-order-ascending",Descending:"data-grid-sort-order-descending"};WI.DataGrid.PreviousColumnOrdinalSymbol=Symbol("previous-column-ordinal");WI.DataGrid.NextColumnOrdinalSymbol=Symbol("next-column-ordinal");WI.DataGrid.WasExpandedDuringFilteringSymbol=Symbol("was-expanded-during-filtering");WI.DataGrid.ColumnResizePadding=10;WI.DataGrid.CenterResizerOverBorderAdjustment=3;WI.DataGrid.SortColumnAscendingStyleClassName="sort-ascending";WI.DataGrid.SortColumnDescendingStyleClassName="sort-descending";WI.DataGrid.SortableColumnStyleClassName="sortable";WI.DataGridNode=class DataGridNode extends WI.Object
{constructor(data,{selectable,copyable,editable,hasChildren,classNames}={})
{super();this._expanded=false;this._hidden=false;this._selected=false;this._selectable=selectable!==undefined?selectable:true;this._copyable=copyable!==undefined?copyable:true;this._editable=editable!==undefined?editable:true;this._shouldRefreshChildren=true;this._data=data||{};this.hasChildren=hasChildren||false;this.children=[];this.dataGrid=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this.disclosureToggleWidth=10;this._classNames=classNames||[];}
get hidden()
{return this._hidden;}
set hidden(x)
{x=!!x;if(this._hidden===x)
return;this._hidden=x;if(this._element)
this._element.classList.toggle("hidden",this._hidden);if(this.dataGrid)
this.dataGrid._noteRowsChanged();}
get selectable()
{return this._element&&!this._hidden&&this._selectable;}
get copyable()
{return this._copyable;}
set copyable(x)
{this._copyable=x;}
get editable()
{return this._editable;}
set editable(x)
{this._editable=x;}
get element()
{if(this._element)
return this._element;if(!this.dataGrid)
return null;this._element=document.createElement("tr");this._element._dataGridNode=this;if(this.hasChildren)
this._element.classList.add("parent");if(this.expanded)
this._element.classList.add("expanded");if(this.selected)
this._element.classList.add("selected");if(this.revealed)
this._element.classList.add("revealed");if(this._hidden)
this._element.classList.add("hidden");this._element.classList.add(...this._classNames);this.createCells();return this._element;}
createCells()
{for(var columnIdentifier of this.dataGrid.orderedColumns)
this._element.appendChild(this.createCell(columnIdentifier));}
refreshIfNeeded()
{if(!this._needsRefresh)
return;this._needsRefresh=false;this.refresh();}
needsRefresh()
{this._needsRefresh=true;if(!this._revealed)
return;if(this._scheduledRefreshIdentifier)
return;this._scheduledRefreshIdentifier=requestAnimationFrame(this.refresh.bind(this));}
get data()
{return this._data;}
set data(x)
{x=x||{};if(Object.shallowEqual(this._data,x))
return;this._data=x;this.needsRefresh();}
get filterableData()
{if(this._cachedFilterableData)
return this._cachedFilterableData;this._cachedFilterableData=[];for(let column of this.dataGrid.columns.values()){if(column.hidden)
continue;let value=this.filterableDataForColumn(column.columnIdentifier);if(!value)
continue;if(!(value instanceof Array))
value=[value];if(!value.length)
continue;this._cachedFilterableData.pushAll(value);}
return this._cachedFilterableData;}
get revealed()
{if("_revealed"in this)
return this._revealed;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded){this._revealed=false;return false;}
currentAncestor=currentAncestor.parent;}
this._revealed=true;return true;}
set hasChildren(x)
{if(this._hasChildren===x)
return;this._hasChildren=x;if(!this._element)
return;if(this._hasChildren){this._element.classList.add("parent");if(this.expanded)
this._element.classList.add("expanded");}else
this._element.classList.remove("parent","expanded");}
get hasChildren()
{return this._hasChildren;}
set revealed(x)
{if(this._revealed===x)
return;this._revealed=x;if(this._element){if(this._revealed)
this._element.classList.add("revealed");else
this._element.classList.remove("revealed");}
this.refreshIfNeeded();for(var i=0;i<this.children.length;++i)
this.children[i].revealed=x&&this.expanded;}
get depth()
{if("_depth"in this)
return this._depth;if(this.parent&&!this.parent.root)
this._depth=this.parent.depth+1;else
this._depth=0;return this._depth;}
get indentPadding()
{if(typeof this._indentPadding==="number")
return this._indentPadding;this._indentPadding=this.depth*this.dataGrid.indentWidth;return this._indentPadding;}
get shouldRefreshChildren()
{return this._shouldRefreshChildren;}
set shouldRefreshChildren(x)
{this._shouldRefreshChildren=x;if(x&&this.expanded)
this.expand();}
get selected()
{return this._selected;}
set selected(x)
{if(x)
this.select();else
this.deselect();}
get expanded()
{return this._expanded;}
set expanded(x)
{if(x)
this.expand();else
this.collapse();}
hasAncestor(ancestor)
{if(!ancestor)
return false;let currentAncestor=this.parent;while(currentAncestor){if(ancestor===currentAncestor)
return true;currentAncestor=currentAncestor.parent;}
return false;}
refresh()
{if(!this._element||!this.dataGrid)
return;if(this._scheduledRefreshIdentifier){cancelAnimationFrame(this._scheduledRefreshIdentifier);this._scheduledRefreshIdentifier=undefined;}
this._cachedFilterableData=null;this._needsRefresh=false;this._element.removeChildren();this.createCells();}
refreshRecursively()
{this.refresh();this.forEachChildInSubtree((node)=>node.refresh());}
updateLayout()
{}
createCell(columnIdentifier)
{var cellElement=document.createElement("td");cellElement.className=columnIdentifier+"-column";cellElement.__columnIdentifier=columnIdentifier;var div=cellElement.createChild("div","cell-content");var content=this.createCellContent(columnIdentifier,cellElement);div.append(content);let column=this.dataGrid.columns.get(columnIdentifier);if(column){if(column["aligned"])
cellElement.classList.add(column["aligned"]);if(column["group"])
cellElement.classList.add("column-group-"+column["group"]);if(column["icon"]){let iconElement=document.createElement("div");iconElement.classList.add("icon");iconElement.title=this.generateIconTitle(columnIdentifier);div.insertBefore(iconElement,div.firstChild);}}
if(columnIdentifier===this.dataGrid.disclosureColumnIdentifier){cellElement.classList.add("disclosure");if(this.indentPadding){if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
cellElement.style.setProperty("padding-right",`${this.indentPadding}px`);else
cellElement.style.setProperty("padding-left",`${this.indentPadding}px`);}}
return cellElement;}
createCellContent(columnIdentifier)
{if(!(columnIdentifier in this.data))
return zeroWidthSpace;let data=this.data[columnIdentifier];return typeof data==="number"?data.maxDecimals(2).toLocaleString():data;}
generateIconTitle(columnIdentifier)
{return"";}
elementWithColumnIdentifier(columnIdentifier)
{if(!this.dataGrid)
return null;let index=this.dataGrid.orderedColumns.indexOf(columnIdentifier);if(index===-1)
return null;return this.element.children[index];}
appendChild(){return WI.DataGrid.prototype.appendChild.apply(this,arguments);}
insertChild(){return WI.DataGrid.prototype.insertChild.apply(this,arguments);}
removeChild(){return WI.DataGrid.prototype.removeChild.apply(this,arguments);}
removeChildren(){return WI.DataGrid.prototype.removeChildren.apply(this,arguments);}
_recalculateSiblings(myIndex)
{if(!this.parent)
return;var previousChild=myIndex>0?this.parent.children[myIndex-1]:null;if(previousChild){previousChild.nextSibling=this;this.previousSibling=previousChild;}else
this.previousSibling=null;var nextChild=this.parent.children[myIndex+1];if(nextChild){nextChild.previousSibling=this;this.nextSibling=nextChild;}else
this.nextSibling=null;}
collapse()
{if(this._element)
this._element.classList.remove("expanded");this._expanded=false;for(var i=0;i<this.children.length;++i)
this.children[i].revealed=false;if(this.dataGrid){this.dataGrid.dispatchEventToListeners(WI.DataGrid.Event.CollapsedNode,{dataGridNode:this});this.dataGrid._noteRowsChanged();}}
collapseRecursively()
{var item=this;while(item){if(item.expanded)
item.collapse();item=item.traverseNextNode(false,this,true);}}
expand()
{if(!this.hasChildren||this.expanded)
return;if(this.revealed&&!this._shouldRefreshChildren)
for(var i=0;i<this.children.length;++i)
this.children[i].revealed=true;if(this._shouldRefreshChildren){for(var i=0;i<this.children.length;++i)
this.children[i]._detach();this.dispatchEventToListeners(DataGridNode.Event.Populate);if(this._attached){for(var i=0;i<this.children.length;++i){var child=this.children[i];if(this.revealed)
child.revealed=true;child._attach();}}
this._shouldRefreshChildren=false;}
if(this._element)
this._element.classList.add("expanded");this._expanded=true;if(this.dataGrid){this.dataGrid.dispatchEventToListeners(WI.DataGrid.Event.ExpandedNode,{dataGridNode:this});this.dataGrid._noteRowsChanged();}}
expandRecursively()
{var item=this;while(item){item.expand();item=item.traverseNextNode(false,this);}}
forEachImmediateChild(callback)
{for(let node of this.children)
callback(node);}
forEachChildInSubtree(callback)
{let node=this.traverseNextNode(false,this,true);while(node){callback(node);node=node.traverseNextNode(false,this,true);}}
isInSubtreeOfNode(baseNode)
{let node=baseNode;while(node){if(node===this)
return true;node=node.traverseNextNode(false,baseNode,true);}
return false;}
reveal()
{var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
currentAncestor.expand();currentAncestor=currentAncestor.parent;}
this.dataGrid.updateVisibleRows(this);}
select(suppressSelectedEvent)
{if(!this.dataGrid||!this.selectable||this.selected)
return;this._selected=true;this._element?.classList.add("selected");this.dataGrid.selectDataGridNodeInternal(this,suppressSelectedEvent);}
revealAndSelect(suppressSelectedEvent)
{this.reveal();this.select(suppressSelectedEvent);}
deselect(suppressDeselectedEvent)
{if(!this.dataGrid||!this.selectable||!this.selected)
return;this._selected=false;this._element?.classList.remove("selected");this.dataGrid.deselectDataGridNodeInternal(this,suppressDeselectedEvent);}
traverseNextNode(skipHidden,stayWithin,dontPopulate,info)
{if(!dontPopulate&&this.hasChildren)
this.dispatchEventToListeners(DataGridNode.Event.Populate);if(info)
info.depthChange=0;var node=(!skipHidden||this.revealed)?this.children[0]:null;if(node&&(!skipHidden||this.expanded)){if(info)
info.depthChange=1;return node;}
if(this===stayWithin)
return null;node=(!skipHidden||this.revealed)?this.nextSibling:null;if(node)
return node;node=this;while(node&&!node.root&&!((!skipHidden||node.revealed)?node.nextSibling:null)&&node.parent!==stayWithin){if(info)
info.depthChange-=1;node=node.parent;}
if(!node)
return null;return(!skipHidden||node.revealed)?node.nextSibling:null;}
traversePreviousNode(skipHidden,dontPopulate)
{var node=(!skipHidden||this.revealed)?this.previousSibling:null;if(!dontPopulate&&node&&node.hasChildren)
node.dispatchEventToListeners(DataGridNode.Event.Populate);while(node&&((!skipHidden||(node.revealed&&node.expanded))?node.children.lastValue:null)){if(!dontPopulate&&node.hasChildren)
node.dispatchEventToListeners(DataGridNode.Event.Populate);node=(!skipHidden||(node.revealed&&node.expanded))?node.children.lastValue:null;}
if(node)
return node;if(!this.parent||this.parent.root)
return null;return this.parent;}
isEventWithinDisclosureTriangle(event)
{if(!this.hasChildren)
return false;let cell=event.target.closest("td");if(!cell||!cell.classList.contains("disclosure"))
return false;let computedStyle=window.getComputedStyle(cell);let start=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
start+=cell.totalOffsetRight-computedStyle.getPropertyCSSValue("padding-right").getFloatValue(CSSPrimitiveValue.CSS_PX)-this.disclosureToggleWidth;else
start+=cell.totalOffsetLeft+computedStyle.getPropertyCSSValue("padding-left").getFloatValue(CSSPrimitiveValue.CSS_PX);return event.pageX>=start&&event.pageX<=start+this.disclosureToggleWidth;}
_attach()
{if(!this.dataGrid||this._attached)
return;this._attached=true;let insertionIndex=-1;if(!this.isPlaceholderNode){var previousGridNode=this.traversePreviousNode(true,true);insertionIndex=this.dataGrid._rows.indexOf(previousGridNode);if(insertionIndex===-1)
insertionIndex=0;else
insertionIndex++;}
if(insertionIndex===-1)
this.dataGrid._rows.push(this);else
this.dataGrid._rows.insertAtIndex(this,insertionIndex);this.dataGrid._noteRowsChanged();if(this.expanded){for(var i=0;i<this.children.length;++i)
this.children[i]._attach();}}
_detach()
{if(!this._attached)
return;this._attached=false;this.dataGrid._rows.remove(this,true);this.dataGrid._noteRowRemoved(this);for(var i=0;i<this.children.length;++i)
this.children[i]._detach();}
savePosition()
{if(this._savedPosition)
return;if(!this.parent)
return;this._savedPosition={parent:this.parent,index:this.parent.children.indexOf(this)};}
restorePosition()
{if(!this._savedPosition)
return;if(this.parent!==this._savedPosition.parent)
this._savedPosition.parent.insertChild(this,this._savedPosition.index);this._savedPosition=null;}
appendContextMenuItems(contextMenu)
{ return null;} 
filterableDataForColumn(columnIdentifier)
{let value=this.data[columnIdentifier];return typeof value==="string"?value:null;}
didResizeColumn(columnIdentifier)
{}};WI.DataGridNode.Event={Populate:"data-grid-node-populate",};WI.PlaceholderDataGridNode=class PlaceholderDataGridNode extends WI.DataGridNode
{constructor(data)
{super(data);this.isPlaceholderNode=true;}
makeNormal()
{this.isPlaceholderNode=false;}};WI.DetailsSectionRow=class DetailsSectionRow extends WI.Object
{constructor(emptyMessage)
{super();this._element=document.createElement("div");this._element.className="row";this._emptyMessage=emptyMessage||"";} 
get element()
{return this._element;}
get emptyMessage()
{return this._emptyMessage;}
set emptyMessage(emptyMessage)
{this._emptyMessage=emptyMessage||"";if(!this._element.childNodes.length)
this.showEmptyMessage();}
showEmptyMessage()
{this.element.classList.add(WI.DetailsSectionRow.EmptyStyleClassName);if(this._emptyMessage instanceof Node){this.element.removeChildren();this.element.appendChild(this._emptyMessage);}else
this.element.textContent=this._emptyMessage;}
hideEmptyMessage()
{this.element.classList.remove(WI.DetailsSectionRow.EmptyStyleClassName);this.element.removeChildren();}};WI.DetailsSectionRow.EmptyStyleClassName="empty";WI.Dialog=class Dialog extends WI.View
{constructor(delegate)
{super();this._delegate=delegate;this._dismissing=false;this._representedObject=null;this._cookie=null;this._visible=false;} 
get visible(){return this._visible;}
get delegate(){return this._delegate;}
get representedObject(){return this._representedObject;}
get cookie(){return this._cookie;}
present(parentElement)
{parentElement.appendChild(this.element);this._visible=true;this.didPresentDialog();}
dismiss(representedObject,cookie)
{if(this._dismissing)
return;let parent=this.element.parentNode;if(!parent)
return;this._dismissing=true;this._representedObject=representedObject||null;this._cookie=cookie||null;this._visible=false;this.element.remove();if(this.representedObjectIsValid(this._representedObject)){if(this._delegate&&typeof this._delegate.dialogWasDismissedWithRepresentedObject==="function")
this._delegate.dialogWasDismissedWithRepresentedObject(this,this._representedObject);}
this._dismissing=false;this.didDismissDialog();} 
didDismissDialog()
{}
didPresetDialog()
{}
representedObjectIsValid(value)
{if(this.delegate&&typeof this.delegate.isDialogRepresentedObjectValid==="function")
return this.delegate.isDialogRepresentedObjectValid(this,value);return true;}};WI.HierarchicalPathComponent=class HierarchicalPathComponent extends WI.Object
{constructor(displayName,styleClassNames,representedObject,textOnly,showSelectorArrows)
{super();this._representedObject=representedObject||null;this._element=document.createElement("div");this._element.className="hierarchical-path-component";if(!Array.isArray(styleClassNames))
styleClassNames=[styleClassNames];this._element.classList.add(...styleClassNames);if(!textOnly){this._iconElement=document.createElement("img");this._iconElement.className="icon";this._element.appendChild(this._iconElement);}else
this._element.classList.add("text-only");this._titleElement=document.createElement("div");this._titleElement.className="title";this._titleElement.setAttribute("dir","auto");this._element.appendChild(this._titleElement);this._titleContentElement=document.createElement("div");this._titleContentElement.className="content";this._titleElement.appendChild(this._titleContentElement);this._separatorElement=document.createElement("div");this._separatorElement.className="separator";this._element.appendChild(this._separatorElement);this._selectElement=document.createElement("select");this._selectElement.setAttribute("dir","auto");this._selectElement.addEventListener("mouseover",this._selectElementMouseOver.bind(this));this._selectElement.addEventListener("mouseout",this._selectElementMouseOut.bind(this));this._selectElement.addEventListener("mousedown",this._selectElementMouseDown.bind(this));this._selectElement.addEventListener("mouseup",this._selectElementMouseUp.bind(this));this._selectElement.addEventListener("change",this._selectElementSelectionChanged.bind(this));this._element.appendChild(this._selectElement);this._previousSibling=null;this._nextSibling=null;this._truncatedDisplayNameLength=0;this._collapsed=false;this._hidden=false;this._selectorArrows=false;this.displayName=displayName;this.tooltip=displayName;this.selectorArrows=showSelectorArrows;} 
get selectedPathComponent()
{let selectedOption=this._selectElement[this._selectElement.selectedIndex];if(!selectedOption&&this._selectElement.options.length===1)
selectedOption=this._selectElement.options[0];return selectedOption&&selectedOption._pathComponent||null;}
get element(){return this._element;}
get representedObject(){return this._representedObject;}
get displayName()
{return this._displayName;}
set displayName(newDisplayName)
{if(newDisplayName===this._displayName)
return;this._displayName=newDisplayName;this._updateElementTitleAndText();}
get truncatedDisplayNameLength()
{return this._truncatedDisplayNameLength;}
set truncatedDisplayNameLength(truncatedDisplayNameLength)
{truncatedDisplayNameLength=truncatedDisplayNameLength||0;if(truncatedDisplayNameLength===this._truncatedDisplayNameLength)
return;this._truncatedDisplayNameLength=truncatedDisplayNameLength;this._updateElementTitleAndText();}
get minimumWidth()
{if(this._collapsed)
return WI.HierarchicalPathComponent.MinimumWidthCollapsed;if(this._selectorArrows)
return WI.HierarchicalPathComponent.MinimumWidth+WI.HierarchicalPathComponent.SelectorArrowsWidth;return WI.HierarchicalPathComponent.MinimumWidth;}
get forcedWidth()
{let maxWidth=this._element.style.getProperty("width");if(typeof maxWidth==="string")
return parseInt(maxWidth);return null;}
set forcedWidth(width)
{if(typeof width==="number"){let minimumWidthForOneCharacterTruncatedTitle=WI.HierarchicalPathComponent.MinimumWidthForOneCharacterTruncatedTitle;if(this.selectorArrows)
minimumWidthForOneCharacterTruncatedTitle+=WI.HierarchicalPathComponent.SelectorArrowsWidth;
if(width<minimumWidthForOneCharacterTruncatedTitle)
width=0;
this._element.style.setProperty("width",Math.max(1,width)+"px");}else
this._element.style.removeProperty("width");}
get hidden()
{return this._hidden;}
set hidden(flag)
{if(this._hidden===flag)
return;this._hidden=flag;this._element.classList.toggle("hidden",this._hidden);}
get collapsed()
{return this._collapsed;}
set collapsed(flag)
{if(this._collapsed===flag)
return;this._collapsed=flag;this._element.classList.toggle("collapsed",this._collapsed);}
get selectorArrows()
{return this._selectorArrows;}
set selectorArrows(flag)
{if(this._selectorArrows===flag)
return;this._selectorArrows=flag;if(this._selectorArrows){this._selectorArrowsElement=WI.ImageUtilities.useSVGSymbol("Images/UpDownArrows.svg","selector-arrows");this._element.insertBefore(this._selectorArrowsElement,this._separatorElement);}else if(this._selectorArrowsElement){this._selectorArrowsElement.remove();this._selectorArrowsElement=null;}
this._element.classList.toggle("show-selector-arrows",!!this._selectorArrows);}
get tooltip()
{return this._tooltip;}
set tooltip(x)
{if(x===this._tooltip)
return;this._tooltip=x;this._updateElementTitleAndText();}
get hideTooltip()
{return this._hideTooltip;}
set hideTooltip(hide)
{this._hideTooltip=hide;this._updateElementTitleAndText();}
get previousSibling(){return this._previousSibling;}
set previousSibling(newSlibling){this._previousSibling=newSlibling||null;}
get nextSibling(){return this._nextSibling;}
set nextSibling(newSlibling){this._nextSibling=newSlibling||null;} 
_updateElementTitleAndText()
{let truncatedDisplayName=this._displayName;if(this._truncatedDisplayNameLength&&truncatedDisplayName.length>this._truncatedDisplayNameLength)
truncatedDisplayName=truncatedDisplayName.substring(0,this._truncatedDisplayNameLength)+ellipsis;this._titleContentElement.textContent=truncatedDisplayName;if(this.hideTooltip)
this._element.title="";else
this._element.title=this._tooltip;}
_updateSelectElement()
{this._selectElement.removeChildren();function createOption(component)
{let optionElement=document.createElement("option");let maxPopupMenuLength=130; optionElement.textContent=component.displayName.length<=maxPopupMenuLength?component.displayName:component.displayName.substring(0,maxPopupMenuLength)+ellipsis;optionElement._pathComponent=component;return optionElement;}
let previousSiblingCount=0;let sibling=this.previousSibling;while(sibling){this._selectElement.insertBefore(createOption(sibling),this._selectElement.firstChild);sibling=sibling.previousSibling;++previousSiblingCount;}
this._selectElement.appendChild(createOption(this));sibling=this.nextSibling;while(sibling){this._selectElement.appendChild(createOption(sibling));sibling=sibling.nextSibling;}
this._selectElement.selectedIndex=previousSiblingCount;}
_selectElementMouseOver(event)
{if(typeof this.mouseOver==="function")
this.mouseOver();}
_selectElementMouseOut(event)
{if(typeof this.mouseOut==="function")
this.mouseOut();}
_selectElementMouseDown(event)
{this._updateSelectElement();if(this._selectElement.options.length===1){event.preventDefault();this._selectElementSelectionChanged();}}
_selectElementMouseUp(event)
{this.dispatchEventToListeners(WI.HierarchicalPathComponent.Event.Clicked,{pathComponent:this.selectedPathComponent});}
_selectElementSelectionChanged(event)
{this.dispatchEventToListeners(WI.HierarchicalPathComponent.Event.SiblingWasSelected,{pathComponent:this.selectedPathComponent});}};WI.HierarchicalPathComponent.MinimumWidth=32;WI.HierarchicalPathComponent.MinimumWidthCollapsed=24;WI.HierarchicalPathComponent.MinimumWidthForOneCharacterTruncatedTitle=54;WI.HierarchicalPathComponent.SelectorArrowsWidth=12;WI.HierarchicalPathComponent.Event={SiblingWasSelected:"hierarchical-path-component-sibling-was-selected",Clicked:"hierarchical-path-component-clicked"};WI.NavigationItem=class NavigationItem extends WI.Object
{constructor(identifier,role,label)
{super();this._identifier=identifier||null;this._element=document.createElement("div");this._hidden=false;this._parentNavigationBar=null;this._visibilityPriority=WI.NavigationItem.VisibilityPriority.Normal;this._cachedWidth=NaN;if(label)
this._element.setAttribute("aria-label",label);this._element.classList.add(...this._classNames);this._element.role=role;this._element.navigationItem=this;} 
get identifier(){return this._identifier;}
get element(){return this._element;}
get minimumWidth(){return this.width;}
get parentNavigationBar(){return this._parentNavigationBar;}
get width()
{if(isNaN(this._cachedWidth))
this._cachedWidth=this._element.realOffsetWidth+this.totalMargin;return this._cachedWidth;}
get visibilityPriority(){return this._visibilityPriority;}
set visibilityPriority(priority){this._visibilityPriority=priority;}
update(options={})
{this._cachedWidth=NaN;}
get hidden()
{return this._hidden;}
set hidden(flag)
{if(this._hidden===flag)
return;this._hidden=flag;this._element.classList.toggle("hidden",flag);if(this._parentNavigationBar)
this._parentNavigationBar.needsLayout();}
get tooltip()
{return this.element.title;}
set tooltip(x)
{this.element.title=x;} 
get totalMargin()
{return 0;}
didAttach(navigationBar)
{this._parentNavigationBar=navigationBar;}
didDetach()
{this._cachedWidth=NaN;this._parentNavigationBar=null;} 
get _classNames()
{var classNames=["item"];if(this._identifier)
classNames.push(this._identifier);if(Array.isArray(this.additionalClassNames))
classNames.pushAll(this.additionalClassNames);return classNames;}};WI.NavigationItem.VisibilityPriority={Low:-100,Normal:0,High:100,};WI.Popover=class Popover extends WI.Object
{constructor(delegate)
{super();this.delegate=delegate;this._edge=null;this._frame=new WI.Rect;this._content=null;this._targetFrame=new WI.Rect;this._anchorPoint=new WI.Point;this._preferredEdges=null;this._resizeHandler=null;this._contentNeedsUpdate=false;this._dismissing=false;this._element=document.createElement("div");this._element.className="popover";this._element.addEventListener("transitionend",this,true);this._container=this._element.appendChild(document.createElement("div"));this._container.className="container";this._drawBackgroundAnimationIdentifier=undefined;} 
get element(){return this._element;}
get visible()
{return this._element.parentNode===document.body&&!this._element.classList.contains(WI.Popover.FadeOutClassName);}
get frame()
{return this._frame;}
set frame(frame)
{this._element.style.left=frame.minX()+"px";this._element.style.top=frame.minY()+"px";this._element.style.width=frame.size.width+"px";this._element.style.height=frame.size.height+"px";this._element.style.backgroundSize=frame.size.width+"px "+frame.size.height+"px";this._frame=frame;}
set content(content)
{if(content===this._content)
return;this._content=content;this._contentNeedsUpdate=true;if(this.visible)
this._update(true);}
set windowResizeHandler(resizeHandler)
{this._resizeHandler=resizeHandler;}
resize()
{if(this.visible&&this._resizeHandler)
this._resizeHandler();}
update(shouldAnimate=true)
{if(!this.visible)
return;var previouslyFocusedElement=document.activeElement;this._contentNeedsUpdate=true;this._update(shouldAnimate);if(previouslyFocusedElement)
previouslyFocusedElement.focus();}
present(targetFrame,preferredEdges)
{this._targetFrame=targetFrame;this._preferredEdges=preferredEdges;if(!this._content)
return;this._addListenersIfNeeded();this._update();}
presentNewContentWithFrame(content,targetFrame,preferredEdges)
{this._content=content;this._contentNeedsUpdate=true;this._targetFrame=targetFrame;this._preferredEdges=preferredEdges;this._addListenersIfNeeded();var shouldAnimate=this.visible;this._update(shouldAnimate);}
dismiss()
{if(this._dismissing||this._element.parentNode!==document.body)
return;this._dismissing=true;this._isListeningForPopoverEvents=false;window.removeEventListener("mousedown",this,true);window.removeEventListener("scroll",this,true);window.removeEventListener("resize",this,true);window.removeEventListener("keypress",this,true);this._prefersDarkColorSchemeMediaQueryList.removeListener(this._boundUpdate);WI.quickConsole.keyboardShortcutDisabled=false;this._element.classList.add(WI.Popover.FadeOutClassName);if(this.delegate&&typeof this.delegate.willDismissPopover==="function")
this.delegate.willDismissPopover(this);}
handleEvent(event)
{switch(event.type){case"mousedown":case"scroll":if(!this._element.contains(event.target)&&!event.target.closest("."+WI.Popover.IgnoreAutoDismissClassName)&&!event[WI.Popover.EventPreventDismissSymbol]){this.dismiss();}
break;case"resize":this.resize();break;case"keypress":if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode)
this.dismiss();break;case"transitionend":if(event.target===this._element){document.body.removeChild(this._element);this._element.classList.remove(WI.Popover.FadeOutClassName);this._container.textContent="";if(this.delegate&&typeof this.delegate.didDismissPopover==="function")
this.delegate.didDismissPopover(this);this._dismissing=false;break;}
break;}} 
_update(shouldAnimate)
{if(shouldAnimate)
var previousEdge=this._edge;var targetFrame=this._targetFrame;var preferredEdges=this._preferredEdges;
if(this._element.parentNode!==document.body)
document.body.appendChild(this._element);else
this._element.classList.remove(WI.Popover.FadeOutClassName);this._dismissing=false;if(this._edge!==null)
this._element.classList.remove(this._cssClassNameForEdge());if(this._contentNeedsUpdate){this._element.style.removeProperty("left");this._element.style.removeProperty("top");this._element.style.removeProperty("width");this._element.style.removeProperty("height");this._container.replaceWith(this._content);var popoverBounds=this._element.getBoundingClientRect();this._preferredSize=new WI.Size(Math.ceil(popoverBounds.width),Math.ceil(popoverBounds.height));}
var titleBarOffset=WI.undockedTitleAreaHeight();var containerFrame=new WI.Rect(0,titleBarOffset,window.innerWidth,window.innerHeight-titleBarOffset);containerFrame=containerFrame.inset(WI.Popover.ShadowEdgeInsets);var metrics=new Array(preferredEdges.length);for(var edgeName in WI.RectEdge){var edge=WI.RectEdge[edgeName];var item={edge,metrics:this._bestMetricsForEdge(this._preferredSize,targetFrame,containerFrame,edge)};var preferredIndex=preferredEdges.indexOf(edge);if(preferredIndex!==-1)
metrics[preferredIndex]=item;else
metrics.push(item);}
function area(size)
{return Math.max(0,size.width)*Math.max(0,size.height);}
var bestEdge=metrics[0].edge;var bestMetrics=metrics[0].metrics;for(var i=1;i<metrics.length;i++){var itemMetrics=metrics[i].metrics;if(area(itemMetrics.contentSize)>area(bestMetrics.contentSize)){bestEdge=metrics[i].edge;bestMetrics=itemMetrics;}}
var anchorPoint;var bestFrame=bestMetrics.frame.round();this._edge=bestEdge;if(bestFrame===WI.Rect.ZERO_RECT){this.dismiss();}else{switch(bestEdge){case WI.RectEdge.MIN_X:anchorPoint=new WI.Point(bestFrame.size.width-WI.Popover.ShadowPadding,targetFrame.midY()-bestFrame.minY());break;case WI.RectEdge.MAX_X:anchorPoint=new WI.Point(WI.Popover.ShadowPadding,targetFrame.midY()-bestFrame.minY());break;case WI.RectEdge.MIN_Y:anchorPoint=new WI.Point(targetFrame.midX()-bestFrame.minX(),bestFrame.size.height-WI.Popover.ShadowPadding);break;case WI.RectEdge.MAX_Y:anchorPoint=new WI.Point(targetFrame.midX()-bestFrame.minX(),WI.Popover.ShadowPadding);break;}
this._element.classList.add(this._cssClassNameForEdge());if(shouldAnimate&&this._edge===previousEdge)
this._animateFrame(bestFrame,anchorPoint);else{this.frame=bestFrame;this._setAnchorPoint(anchorPoint);this._drawBackground();}
if(this._preferredSize.width<WI.Popover.MinWidth||this._preferredSize.height<WI.Popover.MinHeight)
this._container.classList.add("center");else
this._container.classList.remove("center");}
if(this._contentNeedsUpdate){this._container.textContent="";this._content.replaceWith(this._container);this._container.appendChild(this._content);}
this._contentNeedsUpdate=false;}
_cssClassNameForEdge()
{switch(this._edge){case WI.RectEdge.MIN_X:return"arrow-right";case WI.RectEdge.MAX_X:return"arrow-left";case WI.RectEdge.MIN_Y:return"arrow-down";case WI.RectEdge.MAX_Y:return"arrow-up";}
console.error("Unknown edge.");return"arrow-up";}
_setAnchorPoint(anchorPoint)
{anchorPoint.x=Math.floor(anchorPoint.x);anchorPoint.y=Math.floor(anchorPoint.y);this._anchorPoint=anchorPoint;}
_animateFrame(toFrame,toAnchor)
{var startTime=Date.now();var duration=350;var epsilon=1/(200*duration);var spline=new WI.CubicBezier(0.25,0.1,0.25,1);var fromFrame=this._frame.copy();var fromAnchor=this._anchorPoint.copy();function animatedValue(from,to,progress)
{return from+(to-from)*progress;}
function drawBackground()
{var progress=spline.solve(Math.min((Date.now()-startTime)/duration,1),epsilon);this.frame=new WI.Rect(animatedValue(fromFrame.minX(),toFrame.minX(),progress),animatedValue(fromFrame.minY(),toFrame.minY(),progress),animatedValue(fromFrame.size.width,toFrame.size.width,progress),animatedValue(fromFrame.size.height,toFrame.size.height,progress)).round();this._setAnchorPoint(new WI.Point(animatedValue(fromAnchor.x,toAnchor.x,progress),animatedValue(fromAnchor.y,toAnchor.y,progress)));this._drawBackground();if(progress<1)
this._drawBackgroundAnimationIdentifier=requestAnimationFrame(drawBackground.bind(this));}
drawBackground.call(this);}
_drawBackground()
{if(this._drawBackgroundAnimationIdentifier){cancelAnimationFrame(this._drawBackgroundAnimationIdentifier);this._drawBackgroundAnimationIdentifier=undefined;}
let scaleFactor=window.devicePixelRatio;let width=this._frame.size.width;let height=this._frame.size.height;let scaledWidth=width*scaleFactor;let scaledHeight=height*scaleFactor;
let bounds;switch(this._edge){case WI.RectEdge.MIN_X:bounds=new WI.Rect(0,0,width-WI.Popover.AnchorSize,height);break;case WI.RectEdge.MAX_X:bounds=new WI.Rect(WI.Popover.AnchorSize,0,width-WI.Popover.AnchorSize,height);break;case WI.RectEdge.MIN_Y:bounds=new WI.Rect(0,0,width,height-WI.Popover.AnchorSize);break;case WI.RectEdge.MAX_Y:bounds=new WI.Rect(0,WI.Popover.AnchorSize,width,height-WI.Popover.AnchorSize);break;}
bounds=bounds.inset(WI.Popover.ShadowEdgeInsets);let computedStyle=window.getComputedStyle(this._element,null);let context=document.getCSSCanvasContext("2d","popover",scaledWidth,scaledHeight);context.clearRect(0,0,scaledWidth,scaledHeight);function isolate(callback){context.save();callback();context.restore();}
isolate(()=>{context.scale(scaleFactor,scaleFactor);this._drawFrame(context,bounds,this._edge,this._anchorPoint);isolate(()=>{context.shadowBlur=4;context.shadowColor=computedStyle.getPropertyValue("--popover-shadow-color").trim();context.strokeStyle=computedStyle.getPropertyValue("--popover-border-color").trim();context.lineWidth=2;context.stroke();});isolate(()=>{context.fillStyle=computedStyle.getPropertyValue("--popover-background-color").trim();context.fill();});});}
_bestMetricsForEdge(preferredSize,targetFrame,containerFrame,edge)
{var x,y;var width=preferredSize.width+(WI.Popover.ShadowPadding*2)+(WI.Popover.ContentPadding*2);var height=preferredSize.height+(WI.Popover.ShadowPadding*2)+(WI.Popover.ContentPadding*2);switch(edge){case WI.RectEdge.MIN_X:width+=WI.Popover.AnchorSize;x=targetFrame.origin.x-width+WI.Popover.ShadowPadding;y=targetFrame.origin.y-(height-targetFrame.size.height)/2;break;case WI.RectEdge.MAX_X:width+=WI.Popover.AnchorSize;x=targetFrame.origin.x+targetFrame.size.width-WI.Popover.ShadowPadding;y=targetFrame.origin.y-(height-targetFrame.size.height)/2;break;case WI.RectEdge.MIN_Y:height+=WI.Popover.AnchorSize;x=targetFrame.origin.x-(width-targetFrame.size.width)/2;y=targetFrame.origin.y-height+WI.Popover.ShadowPadding;break;case WI.RectEdge.MAX_Y:height+=WI.Popover.AnchorSize;x=targetFrame.origin.x-(width-targetFrame.size.width)/2;y=targetFrame.origin.y+targetFrame.size.height-WI.Popover.ShadowPadding;break;}
if(edge!==WI.RectEdge.MIN_X&&x<containerFrame.minX())
x=containerFrame.minX();if(edge!==WI.RectEdge.MAX_X&&x+width>containerFrame.maxX())
x=containerFrame.maxX()-width;if(edge!==WI.RectEdge.MIN_Y&&y<containerFrame.minY())
y=containerFrame.minY();if(edge!==WI.RectEdge.MAX_Y&&y+height>containerFrame.maxY())
y=containerFrame.maxY()-height;var preferredFrame=new WI.Rect(x,y,width,height);var bestFrame=preferredFrame.intersectionWithRect(containerFrame);width=bestFrame.size.width-(WI.Popover.ShadowPadding*2);height=bestFrame.size.height-(WI.Popover.ShadowPadding*2);switch(edge){case WI.RectEdge.MIN_X:case WI.RectEdge.MAX_X:width-=WI.Popover.AnchorSize;break;case WI.RectEdge.MIN_Y:case WI.RectEdge.MAX_Y:height-=WI.Popover.AnchorSize;break;}
return{frame:bestFrame,contentSize:new WI.Size(width,height)};}
_drawFrame(ctx,bounds,anchorEdge)
{let cornerRadius=WI.Popover.CornerRadius;let anchorPoint=this._anchorPoint;let arrowPadding=cornerRadius+WI.Popover.AnchorSize;if(anchorEdge===WI.RectEdge.MIN_Y||anchorEdge===WI.RectEdge.MAX_Y)
anchorPoint.x=Number.constrain(anchorPoint.x,bounds.minX()+arrowPadding,bounds.maxX()-arrowPadding);else
anchorPoint.y=Number.constrain(anchorPoint.y,bounds.minY()+arrowPadding,bounds.maxY()-arrowPadding);ctx.beginPath();switch(anchorEdge){case WI.RectEdge.MIN_X:ctx.moveTo(bounds.maxX(),bounds.minY()+cornerRadius);ctx.lineTo(bounds.maxX(),anchorPoint.y-WI.Popover.AnchorSize);ctx.lineTo(anchorPoint.x,anchorPoint.y);ctx.lineTo(bounds.maxX(),anchorPoint.y+WI.Popover.AnchorSize);ctx.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);break;case WI.RectEdge.MAX_X:ctx.moveTo(bounds.minX(),bounds.maxY()-cornerRadius);ctx.lineTo(bounds.minX(),anchorPoint.y+WI.Popover.AnchorSize);ctx.lineTo(anchorPoint.x,anchorPoint.y);ctx.lineTo(bounds.minX(),anchorPoint.y-WI.Popover.AnchorSize);ctx.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);break;case WI.RectEdge.MIN_Y:ctx.moveTo(bounds.maxX()-cornerRadius,bounds.maxY());ctx.lineTo(anchorPoint.x+WI.Popover.AnchorSize,bounds.maxY());ctx.lineTo(anchorPoint.x,anchorPoint.y);ctx.lineTo(anchorPoint.x-WI.Popover.AnchorSize,bounds.maxY());ctx.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);break;case WI.RectEdge.MAX_Y:ctx.moveTo(bounds.minX()+cornerRadius,bounds.minY());ctx.lineTo(anchorPoint.x-WI.Popover.AnchorSize,bounds.minY());ctx.lineTo(anchorPoint.x,anchorPoint.y);ctx.lineTo(anchorPoint.x+WI.Popover.AnchorSize,bounds.minY());ctx.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);ctx.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);break;}
ctx.closePath();}
_addListenersIfNeeded()
{if(!this._isListeningForPopoverEvents){this._isListeningForPopoverEvents=true;window.addEventListener("mousedown",this,true);window.addEventListener("scroll",this,true);window.addEventListener("resize",this,true);window.addEventListener("keypress",this,true);if(!this._boundUpdate)
this._boundUpdate=this._update.bind(this);if(!this._prefersDarkColorSchemeMediaQueryList)
this._prefersDarkColorSchemeMediaQueryList=window.matchMedia("(prefers-color-scheme: dark)");this._prefersDarkColorSchemeMediaQueryList.addListener(this._boundUpdate);WI.quickConsole.keyboardShortcutDisabled=true;}}};WI.Popover.FadeOutClassName="fade-out";WI.Popover.CornerRadius=5;WI.Popover.MinWidth=40;WI.Popover.MinHeight=40;WI.Popover.ShadowPadding=5;WI.Popover.ContentPadding=5;WI.Popover.AnchorSize=11;WI.Popover.ShadowEdgeInsets=new WI.EdgeInsets(WI.Popover.ShadowPadding);WI.Popover.IgnoreAutoDismissClassName="popover-ignore-auto-dismiss";WI.Popover.EventPreventDismissSymbol=Symbol("popover-event-prevent-dismiss");WI.Sidebar=class Sidebar extends WI.View
{constructor(element,side,label)
{super(element);this._side=side;this._collapsed=true;this._collapsable=true;this.element.classList.add("sidebar",this._side,WI.Sidebar.CollapsedStyleClassName);this.element.setAttribute("role","group");if(label)
this.element.setAttribute("aria-label",label);this._sidebarPanels=[];this._selectedSidebarPanel=null;} 
get sidebarPanels(){return this._sidebarPanels;}
get side(){return this._side;}
addSidebarPanel(sidebarPanel)
{this.insertSidebarPanel(sidebarPanel,this.sidebarPanels.length);}
insertSidebarPanel(sidebarPanel,index)
{if(!(sidebarPanel instanceof WI.SidebarPanel))
return;if(!this.shouldInsertSidebarPanel(sidebarPanel,index))
return;this._sidebarPanels.splice(index,0,sidebarPanel);this.didInsertSidebarPanel(sidebarPanel,index);}
removeSidebarPanel(sidebarPanelOrIdentifierOrIndex)
{let sidebarPanel=this._findSidebarPanel(sidebarPanelOrIdentifierOrIndex);if(!sidebarPanel)
return;this._sidebarPanels.remove(sidebarPanel);if(this.selectedSidebarPanel===sidebarPanel)
this.selectedSidebarPanel=0;this.didRemoveSidebarPanel(sidebarPanel);}
get selectedSidebarPanel()
{return this._selectedSidebarPanel;}
set selectedSidebarPanel(sidebarPanelOrIdentifierOrIndex)
{let sidebarPanel=this._findSidebarPanel(sidebarPanelOrIdentifierOrIndex);if(!sidebarPanel)
sidebarPanel=this._findSidebarPanel(0);if(this._selectedSidebarPanel===sidebarPanel)
return;this.willSetSelectedSidebarPanel(sidebarPanel);this._selectedSidebarPanel=sidebarPanel;this.didSetSelectedSidebarPanel(sidebarPanel);this.dispatchEventToListeners(WI.Sidebar.Event.SidebarPanelSelected);}
get collapsed()
{return this._collapsed;}
set collapsed(flag)
{if(flag===this._collapsed)
return;if(flag&&!this._collapsable)
return;this._collapsed=flag||false;this.element.classList.toggle(WI.Sidebar.CollapsedStyleClassName);this.didSetCollapsed();this.dispatchEventToListeners(WI.Sidebar.Event.CollapsedStateDidChange);}
get collapsable()
{return this._collapsable;}
set collapsable(allow){if(allow===this._collapsable)
return;this._collapsable=!!allow;if(!allow&&this.collapsed)
this.collapsed=false;}
get minimumWidth()
{let minimumWidth=WI.Sidebar.AbsoluteMinimumWidth;if(this.selectedSidebarPanel)
minimumWidth=Math.max(minimumWidth,this.selectedSidebarPanel.minimumWidth);return minimumWidth;}
get maximumWidth()
{return WI.getMaximumSidebarWidth(this);} 
shouldInsertSidebarPanel(sidebarPanel,index)
{return true;}
didInsertSidebarPanel(sidebarPanel,index)
{}
didRemoveSidebarPanel(sidebarPanel)
{}
willSetSelectedSidebarPanel(sidebarPanel)
{}
didSetSelectedSidebarPanel(sidebarPanel)
{}
didSetCollapsed(flag)
{} 
_findSidebarPanel(sidebarPanelOrIdentifierOrIndex)
{let sidebarPanel=null;if(sidebarPanelOrIdentifierOrIndex instanceof WI.SidebarPanel){if(this._sidebarPanels.includes(sidebarPanelOrIdentifierOrIndex))
sidebarPanel=sidebarPanelOrIdentifierOrIndex;}else if(typeof sidebarPanelOrIdentifierOrIndex==="number"){sidebarPanel=this._sidebarPanels[sidebarPanelOrIdentifierOrIndex];}else if(typeof sidebarPanelOrIdentifierOrIndex==="string"){sidebarPanel=this._sidebarPanels.find((existingSidebarPanel)=>existingSidebarPanel.identifier===sidebarPanelOrIdentifierOrIndex)||null;}
return sidebarPanel;}};WI.Sidebar.CollapsedStyleClassName="collapsed";WI.Sidebar.AbsoluteMinimumWidth=250;WI.Sidebar.Sides={Leading:"leading",Trailing:"trailing",};WI.Sidebar.Event={SidebarPanelSelected:"sidebar-panel-selected",CollapsedStateDidChange:"sidebar-collapsed-state-did-change",WidthDidChange:"sidebar-width-did-change",};WI.SidebarPanel=class SidebarPanel extends WI.View
{constructor(identifier,displayName)
{super();this._identifier=identifier;this._displayName=displayName;this._selected=false;this._exclusive=false;this._savedScrollPosition=0;this.element.classList.add("panel",identifier);this.element.setAttribute("role","group");this.element.setAttribute("aria-label",displayName);this._contentView=new WI.View;this._contentView.element.classList.add("content");this.addSubview(this._contentView);} 
get identifier()
{return this._identifier;}
get contentView()
{return this._contentView;}
get displayName()
{return this._displayName;}
get visible()
{return this.selected&&this.parentSidebar&&!this.parentSidebar.collapsed;}
get selected()
{return this._selected;}
set selected(flag)
{if(flag===this._selected)
return;this._selected=flag||false;this.element.classList.toggle("selected",this._selected);}
get parentSidebar()
{return this.parentView;}
get minimumWidth()
{return 0;}
get exclusive()
{return this._exclusive;}
set exclusive(exclusive)
{if(exclusive===this._exclusive)
return;this._exclusive=!!exclusive;this.element.classList.toggle("exclusive-presentation",this._exclusive);}
get allowExclusivePresentation()
{return false;}
attached()
{super.attached();this.scrollElement.scrollTop=this._savedScrollPosition;}
detached()
{this._savedScrollPosition=this.scrollElement.scrollTop;super.detached();} 
get scrollElement()
{return this.contentView.element;}};WI.TabBar=class TabBar extends WI.View
{constructor(element)
{super(element);this.element.classList.add("tab-bar");this.element.addEventListener("mousedown",this._handleMouseDown.bind(this));this.element.createChild("div","border top");const navigationBarBeforeElement=null;this._navigationBarBefore=new WI.NavigationBar(navigationBarBeforeElement,{sizesToFit:true});this.addSubview(this._navigationBarBefore);this._tabContainer=this.element.appendChild(document.createElement("div"));this._tabContainer.className="tabs";this._tabContainer.setAttribute("role","tablist");this._tabContainer.addEventListener("mousedown",this._handleTabContainerMouseDown.bind(this));this._tabContainer.addEventListener("mouseleave",this._handleTabContainerMouseLeave.bind(this));this._tabContainer.addEventListener("contextmenu",this._handleTabContainerContextMenu.bind(this));const navigationBarAfterElement=null;this._navigationBarAfter=new WI.NavigationBar(navigationBarAfterElement,{sizesToFit:true});this.addSubview(this._navigationBarAfter);this.element.createChild("div","border bottom");this._tabBarItems=[];this._hiddenTabBarItems=[];const showHiddenTabsRepresentedObject=null;const showHiddenTabsDisplayName=null;this._showHiddenTabsTabBarItem=new WI.PinnedTabBarItem(showHiddenTabsRepresentedObject,"Images/Overflow.svg",showHiddenTabsDisplayName,WI.UIString("Show hidden tabs\u2026"));this._showHiddenTabsTabBarItem.hidden=true;this.addTabBarItem(this._showHiddenTabsTabBarItem,{suppressAnimations:true});const openClosedTabsRepresentedObject=null;const openClosedTabsDisplayName=null;this._openClosedTabsTabBarItem=new WI.PinnedTabBarItem(openClosedTabsRepresentedObject,"Images/Plus15.svg",openClosedTabsDisplayName,WI.UIString("Open closed tabs\u2026"));this._openClosedTabsTabBarItem.hidden=true;this.addTabBarItem(this._openClosedTabsTabBarItem,{suppressAnimations:true});this._mouseDownPageX=NaN;this._isDragging=false;} 
addNavigationItemBefore(navigationItem)
{this._navigationBarBefore.addNavigationItem(navigationItem);this.needsLayout();}
addNavigationItemAfter(navigationItem)
{this._navigationBarAfter.addNavigationItem(navigationItem);this.needsLayout();}
addTabBarItem(tabBarItem,options={})
{return this.insertTabBarItem(tabBarItem,this._tabBarItems.length,options);}
insertTabBarItem(tabBarItem,index,options={})
{if(!(tabBarItem instanceof WI.TabBarItem))
return null;if(tabBarItem.parentTabBar===this)
return null;if(this._tabAnimatedClosedSinceMouseEnter){this._finishExpandingTabsAfterClose().then(()=>{this.insertTabBarItem(tabBarItem,index,options);});return null;}
if(tabBarItem.parentTabBar)
tabBarItem.parentTabBar.removeTabBarItem(tabBarItem);tabBarItem.parentTabBar=this;if(tabBarItem instanceof WI.GeneralTabBarItem)
index=Number.constrain(index,0,this.normalTabCount);else
index=Number.constrain(index,this.normalTabCount,this._tabBarItems.length);if(this._tabContainer.classList.contains("animating")){requestAnimationFrame(removeStyles.bind(this));options.suppressAnimations=true;}
var beforeTabSizesAndPositions;if(!options.suppressAnimations)
beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._tabBarItems.splice(index,0,tabBarItem);let nextSibling=this._tabBarItems[index+1]||this._tabBarItems.lastValue;if(this._tabContainer.contains(nextSibling.element)){if(!(tabBarItem instanceof WI.PinnedTabBarItem)&&nextSibling instanceof WI.PinnedTabBarItem)
this._tabContainer.insertBefore(tabBarItem.element,this._pinnedButtons()[0].element);else
this._tabContainer.insertBefore(tabBarItem.element,nextSibling.element);}else{if(tabBarItem instanceof WI.PinnedTabBarItem)
this._tabContainer.appendChild(tabBarItem.element);else
this._tabContainer.insertBefore(tabBarItem.element,this._pinnedButtons()[0].element);}
tabBarItem.element.style.left=null;tabBarItem.element.style.width=null;function animateTabs()
{this._tabContainer.classList.add("animating");this._tabContainer.classList.add("inserting-tab");this._applyTabBarItemSizesAndPositions(afterTabSizesAndPositions);this._tabContainer.addEventListener("webkitTransitionEnd",removeStylesListener);}
function removeStyles()
{this._tabContainer.classList.remove("static-layout");this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("inserting-tab");tabBarItem.element.classList.remove("being-inserted");this._clearTabBarItemSizesAndPositions();this._tabContainer.removeEventListener("webkitTransitionEnd",removeStylesListener);}
if(!options.suppressAnimations){var afterTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this.updateLayout();let tabBarItems=this._tabBarItemsFromLeftToRight();let previousTabBarItem=tabBarItems[tabBarItems.indexOf(tabBarItem)-1]||null;let previousTabBarItemSizeAndPosition=previousTabBarItem?beforeTabSizesAndPositions.get(previousTabBarItem):null;if(previousTabBarItemSizeAndPosition)
beforeTabSizesAndPositions.set(tabBarItem,{left:previousTabBarItemSizeAndPosition.left+previousTabBarItemSizeAndPosition.width,width:0});else
beforeTabSizesAndPositions.set(tabBarItem,{left:0,width:0});this._tabContainer.classList.add("static-layout");tabBarItem.element.classList.add("being-inserted");this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}else
this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemAdded,{tabBarItem});return tabBarItem;}
removeTabBarItem(tabBarItemOrIndex,options={})
{let tabBarItem=this._findTabBarItem(tabBarItemOrIndex);if(!tabBarItem||tabBarItem instanceof WI.PinnedTabBarItem)
return null;if(this.normalTabCount===1)
return null;tabBarItem.parentTabBar=null;if(this._selectedTabBarItem===tabBarItem){var index=this._tabBarItems.indexOf(tabBarItem);var nextTabBarItem=this._tabBarItems[index+1];if(!nextTabBarItem||nextTabBarItem instanceof WI.PinnedTabBarItem)
nextTabBarItem=this._tabBarItems[index-1];this.selectedTabBarItem=nextTabBarItem;}
if(this._tabContainer.classList.contains("animating")){requestAnimationFrame(removeStyles.bind(this));options.suppressAnimations=true;}
var beforeTabSizesAndPositions;if(!options.suppressAnimations)
beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();let wasLastNormalTab=this._tabBarItems.indexOf(tabBarItem)===this.normalTabCount-1;this._tabBarItems.remove(tabBarItem);tabBarItem.element.remove();this._openClosedTabsTabBarItem.hidden=!this._closedTabClasses().length;if(!this._hasMoreThanOneNormalTab()||wasLastNormalTab||!options.suppressExpansion){if(!options.suppressAnimations){this._tabAnimatedClosedSinceMouseEnter=true;this._finishExpandingTabsAfterClose(beforeTabSizesAndPositions);}else
this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemRemoved,{tabBarItem});return tabBarItem;}
var lastNormalTabBarItem;function animateTabs()
{this._tabContainer.classList.add("animating");this._tabContainer.classList.add("closing-tab");
let extraSpaceBetweenNormalAndPinnedTabs=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL){extraSpaceBetweenNormalAndPinnedTabs=this._tabContainer.getBoundingClientRect().width;for(let currentTabBarItem of this._tabBarItemsFromLeftToRight())
extraSpaceBetweenNormalAndPinnedTabs-=currentTabBarItem.element.getBoundingClientRect().width;}
let left=0;for(let currentTabBarItem of this._tabBarItemsFromLeftToRight()){let sizeAndPosition=beforeTabSizesAndPositions.get(currentTabBarItem);if(!(currentTabBarItem instanceof WI.PinnedTabBarItem)){currentTabBarItem.element.style.left=extraSpaceBetweenNormalAndPinnedTabs+left+"px";left+=sizeAndPosition.width;lastNormalTabBarItem=currentTabBarItem;}else
left=sizeAndPosition.left+sizeAndPosition.width;}
if(this._selectedTabBarItem)
this._selectedTabBarItem.element.style.width=(parseFloat(this._selectedTabBarItem.element.style.width)+1)+"px";if(lastNormalTabBarItem!==this._selectedTabBarItem)
lastNormalTabBarItem.element.style.width=(parseFloat(lastNormalTabBarItem.element.style.width)+1)+"px";this._tabContainer.addEventListener("webkitTransitionEnd",removeStylesListener);}
function removeStyles()
{if(this._selectedTabBarItem&&this._selectedTabBarItem!==lastNormalTabBarItem)
this._selectedTabBarItem.element.style.width=(parseFloat(this._selectedTabBarItem.element.style.width)-1)+"px";this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("closing-tab");this.updateLayout();this._tabContainer.removeEventListener("webkitTransitionEnd",removeStylesListener);}
if(!options.suppressAnimations){this._tabContainer.classList.add("static-layout");this._tabAnimatedClosedSinceMouseEnter=true;this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}else
this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemRemoved,{tabBarItem});return tabBarItem;}
selectPreviousTab()
{if(this._tabBarItems.length<=1)
return;var startIndex=this._tabBarItems.indexOf(this._selectedTabBarItem);var newIndex=startIndex;do{if(newIndex===0)
newIndex=this._tabBarItems.length-1;else
newIndex--;if(!(this._tabBarItems[newIndex]instanceof WI.PinnedTabBarItem))
break;}while(newIndex!==startIndex);if(newIndex===startIndex)
return;this.selectedTabBarItem=this._tabBarItems[newIndex];}
selectNextTab()
{if(this._tabBarItems.length<=1)
return;var startIndex=this._tabBarItems.indexOf(this._selectedTabBarItem);var newIndex=startIndex;do{if(newIndex===this._tabBarItems.length-1)
newIndex=0;else
newIndex++;if(!(this._tabBarItems[newIndex]instanceof WI.PinnedTabBarItem))
break;}while(newIndex!==startIndex);if(newIndex===startIndex)
return;this.selectedTabBarItem=this._tabBarItems[newIndex];}
get selectedTabBarItem()
{return this._selectedTabBarItem;}
set selectedTabBarItem(tabBarItemOrIndex)
{this.selectTabBarItem(tabBarItemOrIndex);}
selectTabBarItem(tabBarItemOrIndex,options={})
{let tabBarItem=this._findTabBarItem(tabBarItemOrIndex);if(this._pinnedButtons().includes(tabBarItem)){tabBarItem=this._tabBarItems[this.normalTabCount-1];}
if(this._selectedTabBarItem===tabBarItem)
return;let previousTabBarItem=this._selectedTabBarItem;if(this._selectedTabBarItem)
this._selectedTabBarItem.selected=false;this._selectedTabBarItem=tabBarItem||null;if(this._selectedTabBarItem){this._selectedTabBarItem.selected=true;if(this._selectedTabBarItem.hidden)
this.needsLayout();}
let initiatorHint=options.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Unknown;this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemSelected,{previousTabBarItem,initiatorHint});}
get tabBarItems()
{return this._tabBarItems;}
get tabCount()
{return this._tabBarItems.filter((item)=>item.representedObject instanceof WI.TabContentView).length;}
get normalTabCount()
{return this._tabBarItems.filter((item)=>!(item instanceof WI.PinnedTabBarItem)).length;}
resetCachedWidths()
{for(let tabBarItem of this._tabBarItems)
tabBarItem[WI.TabBar.CachedWidthSymbol]=0;} 
layout()
{if(this._tabContainer.classList.contains("static-layout"))
return;let undocked=WI.dockConfiguration===WI.DockConfiguration.Undocked;function measureWidth(tabBarItem){if(!tabBarItem[WI.TabBar.CachedWidthSymbol])
tabBarItem[WI.TabBar.CachedWidthSymbol]=tabBarItem.element.realOffsetWidth;return tabBarItem[WI.TabBar.CachedWidthSymbol];}
let availableSpace=this._tabContainer.realOffsetWidth;this._tabContainer.classList.add("calculate-width");this._hiddenTabBarItems=[];let normalTabBarItems=[];for(let tabBarItem of this._tabBarItemsFromLeftToRight()){switch(tabBarItem){case this._showHiddenTabsTabBarItem:tabBarItem.hidden=true;continue;case this._openClosedTabsTabBarItem:tabBarItem.hidden=!this._closedTabClasses().length;if(tabBarItem.hidden)
continue;else
break;}
tabBarItem.hidden=false;if(tabBarItem instanceof WI.PinnedTabBarItem){availableSpace-=measureWidth(tabBarItem);continue;}
normalTabBarItems.push(tabBarItem);
if(undocked)
tabBarItem[WI.TabBar.CachedWidthSymbol]=0;}
let normalTabBarItemsWidth=normalTabBarItems.reduce((accumulator,tabBarItem)=>accumulator+measureWidth(tabBarItem),0);if(Math.round(normalTabBarItemsWidth)>=Math.floor(availableSpace)){this._showHiddenTabsTabBarItem.hidden=false;availableSpace-=measureWidth(this._showHiddenTabsTabBarItem);let index=normalTabBarItems.length-1;do{let tabBarItem=normalTabBarItems[index];if(tabBarItem===this._selectedTabBarItem)
continue;normalTabBarItemsWidth-=measureWidth(tabBarItem);tabBarItem.hidden=true;this._hiddenTabBarItems.push(tabBarItem);}while(normalTabBarItemsWidth>=availableSpace&&--index>=0);}

this._hiddenTabBarItems.reverse();this._tabContainer.classList.remove("calculate-width");}
didLayoutSubtree()
{super.didLayoutSubtree();this._tabContainer.classList.toggle("hide-border-start",this._navigationBarBefore.navigationItems.every((item)=>item.hidden));this._tabContainer.classList.toggle("hide-border-end",this._navigationBarAfter.navigationItems.every((item)=>item.hidden));} 
_pinnedButtons()
{return[this._showHiddenTabsTabBarItem,this._openClosedTabsTabBarItem];}
_tabBarItemsFromLeftToRight()
{return WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR?this._tabBarItems:this._tabBarItems.slice().reverse();}
_closedTabClasses()
{return Array.from(WI.knownTabClasses()).filter((tabClass)=>WI.isNewTabWithTypeAllowed(tabClass.Type));}
_findTabBarItem(tabBarItemOrIndex)
{if(typeof tabBarItemOrIndex==="number")
return this._tabBarItems[tabBarItemOrIndex]||null;if(tabBarItemOrIndex instanceof WI.TabBarItem){if(this._tabBarItems.includes(tabBarItemOrIndex))
return tabBarItemOrIndex;}
return null;}
_hasMoreThanOneNormalTab()
{let normalTabCount=0;for(let tabBarItem of this._tabBarItems){if(tabBarItem instanceof WI.PinnedTabBarItem)
continue;++normalTabCount;if(normalTabCount>=2)
return true;}
return false;}
_recordTabBarItemSizesAndPositions()
{var tabBarItemSizesAndPositions=new Map;let barRect=this._tabContainer.getBoundingClientRect();for(let tabBarItem of this._tabBarItems){if(tabBarItem.hidden)
continue;let boundingRect=tabBarItem.element.getBoundingClientRect();tabBarItemSizesAndPositions.set(tabBarItem,{left:boundingRect.left-barRect.left,width:boundingRect.width,});}
return tabBarItemSizesAndPositions;}
_applyTabBarItemSizesAndPositions(tabBarItemSizesAndPositions,skipTabBarItem)
{for(var[tabBarItem,sizeAndPosition]of tabBarItemSizesAndPositions){if(skipTabBarItem&&tabBarItem===skipTabBarItem)
continue;tabBarItem.element.style.left=sizeAndPosition.left+"px";tabBarItem.element.style.width=sizeAndPosition.width+"px";}}
_clearTabBarItemSizesAndPositions(skipTabBarItem)
{for(var tabBarItem of this._tabBarItems){if(skipTabBarItem&&tabBarItem===skipTabBarItem)
continue;tabBarItem.element.style.left=null;tabBarItem.element.style.width=null;}}
_finishExpandingTabsAfterClose(beforeTabSizesAndPositions)
{return new Promise(function(resolve,reject){this._tabAnimatedClosedSinceMouseEnter=false;if(!beforeTabSizesAndPositions)
beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._tabContainer.classList.remove("static-layout");this._clearTabBarItemSizesAndPositions();var afterTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);this._tabContainer.classList.add("static-layout");function animateTabs()
{this._tabContainer.classList.add("static-layout");this._tabContainer.classList.add("animating");this._tabContainer.classList.add("expanding-tabs");this._applyTabBarItemSizesAndPositions(afterTabSizesAndPositions);this._tabContainer.addEventListener("webkitTransitionEnd",removeStylesListener);}
function removeStyles()
{this._tabContainer.classList.remove("static-layout");this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("expanding-tabs");this._clearTabBarItemSizesAndPositions();this.updateLayout();this._tabContainer.removeEventListener("webkitTransitionEnd",removeStylesListener);resolve();}
var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}.bind(this));}
_handleMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;if(event.target!==this.element)
return;switch(WI.dockConfiguration){case WI.DockConfiguration.Bottom:WI.resizeDockedFrameMouseDown(event);break;case WI.DockConfiguration.Undocked:WI.moveUndockedWindowMouseDown(event);break;}}
_handleTabContainerMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;let itemElement=event.target.closest("."+WI.TabBarItem.StyleClassName);if(!itemElement)
return;let tabBarItem=itemElement[WI.TabBarItem.ElementReferenceSymbol];if(!tabBarItem)
return;if(tabBarItem.disabled)
return;switch(tabBarItem){case this._showHiddenTabsTabBarItem:this._handleShowHiddenTabsTabBarItemMouseDown(event);return;case this._openClosedTabsTabBarItem:this._handleAddClosedTabsTabBarItemMouseDown(event);return;}
this.selectTabBarItem(tabBarItem,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.TabClick});if(tabBarItem instanceof WI.PinnedTabBarItem||!this._hasMoreThanOneNormalTab())
return;this._firstNormalTabItemIndex=0;for(let i=0;i<this._tabBarItems.length;++i){if(this._tabBarItems[i]instanceof WI.PinnedTabBarItem)
continue;this._firstNormalTabItemIndex=i;break;}
this._mouseDownPageX=event.pageX;this._mouseMovedEventListener=this._handleMouseMoved.bind(this);this._mouseUpEventListener=this._handleMouseUp.bind(this);document.addEventListener("mousemove",this._mouseMovedEventListener,true);document.addEventListener("mouseup",this._mouseUpEventListener,true);event.preventDefault();event.stopPropagation();}
_handleShowHiddenTabsTabBarItemMouseDown(event)
{if(!this._hiddenTabBarItems.length)
return;if(this._ignoreShowHiddenTabsTabBarItemMouseDown)
return;this._ignoreShowHiddenTabsTabBarItemMouseDown=true;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.addBeforeShowCallback(()=>{this._ignoreShowHiddenTabsTabBarItemMouseDown=false;});for(let item of this._hiddenTabBarItems){contextMenu.appendItem(item.displayName,()=>{this.selectTabBarItem(item,{initiator:WI.TabBrowser.TabNavigationInitiator.ContextMenu});});}
contextMenu.show();}
_handleAddClosedTabsTabBarItemMouseDown(event)
{let closedTabClasses=this._closedTabClasses();if(!closedTabClasses.length)
return;if(this._ignoreAddClosedTabsTabBarItemMouseDown)
return;this._ignoreAddClosedTabsTabBarItemMouseDown=true;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.addBeforeShowCallback(()=>{this._ignoreAddClosedTabsTabBarItemMouseDown=false;});for(let closedTabClass of closedTabClasses){if(!closedTabClass.shouldSaveTab())
continue;contextMenu.appendItem(closedTabClass.tabInfo().displayName,()=>{WI.createNewTabWithType(closedTabClass.Type,{shouldShowNewTab:true});});}
WI.sharedApp.extensionController.addContextMenuItemsForClosedExtensionTabs(contextMenu);contextMenu.show();}
_handleMouseMoved(event)
{if(isNaN(this._mouseDownPageX))
return;if(!this._selectedTabBarItem)
return;if(this._mouseOffset===undefined)
this._mouseOffset=event.pageX-this._selectedTabBarItem.element.totalOffsetLeft;if(!this._isDragging){const dragThreshold=12;if(Math.abs(this._mouseDownPageX-event.pageX)<dragThreshold)
return;this._isDragging=true;}
event.preventDefault();event.stopPropagation();if(!this._tabContainer.classList.contains("static-layout")){this._applyTabBarItemSizesAndPositions(this._recordTabBarItemSizesAndPositions());this._tabContainer.classList.add("static-layout");this._tabContainer.classList.add("dragging-tab");}
let containerOffset=this._tabContainer.totalOffsetLeft;let tabBarMouseOffset=event.pageX-containerOffset;var newLeft=tabBarMouseOffset-this._mouseOffset;this._selectedTabBarItem.element.style.left=newLeft+"px";let selectedTabMidX=containerOffset+newLeft+(this._selectedTabBarItem.element.realOffsetWidth/2);var currentIndex=this._tabBarItems.indexOf(this._selectedTabBarItem);var newIndex=currentIndex;for(let tabBarItem of this._tabBarItems){if(tabBarItem.hidden)
continue;if(tabBarItem===this._selectedTabBarItem)
continue;var tabBarItemRect=tabBarItem.element.getBoundingClientRect();if(selectedTabMidX<tabBarItemRect.left||selectedTabMidX>tabBarItemRect.right)
continue;newIndex=this._tabBarItems.indexOf(tabBarItem);break;}
newIndex=Number.constrain(newIndex,this._firstNormalTabItemIndex,this.normalTabCount-1);if(currentIndex===newIndex)
return;this._tabBarItems.splice(currentIndex,1);this._tabBarItems.splice(newIndex,0,this._selectedTabBarItem);let nextSibling=this._tabBarItems[newIndex+1];let nextSiblingElement=nextSibling?nextSibling.element:null;this._tabContainer.insertBefore(this._selectedTabBarItem.element,nextSiblingElement);function inlineStyleValue(element,property){return element.style.getPropertyCSSValue(property).getFloatValue(CSSPrimitiveValue.CSS_PX)||0;}
let accumulatedLeft=0;for(let tabBarItem of this._tabBarItemsFromLeftToRight()){if(tabBarItem.hidden)
continue;if(tabBarItem!==this._selectedTabBarItem&&inlineStyleValue(tabBarItem.element,"left")!==accumulatedLeft)
tabBarItem.element.style.left=accumulatedLeft+"px";accumulatedLeft+=inlineStyleValue(tabBarItem.element,"width");}}
_handleMouseUp(event)
{if(isNaN(this._mouseDownPageX))
return;this._tabContainer.classList.remove("dragging-tab");if(!this._tabAnimatedClosedSinceMouseEnter){this._tabContainer.classList.remove("static-layout");this._clearTabBarItemSizesAndPositions();}else{let left=0;for(let tabBarItem of this._tabBarItemsFromLeftToRight()){if(tabBarItem===this._selectedTabBarItem)
tabBarItem.element.style.left=left+"px";left+=parseFloat(tabBarItem.element.style.width);}}
this._isDragging=false;this._mouseDownPageX=NaN;this._mouseOffset=undefined;document.removeEventListener("mousemove",this._mouseMovedEventListener,true);document.removeEventListener("mouseup",this._mouseUpEventListener,true);this._mouseMovedEventListener=null;this._mouseUpEventListener=null;event.preventDefault();event.stopPropagation();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemsReordered);}
_handleTabContainerMouseLeave(event)
{if(!isNaN(this._mouseDownPageX)||!this._tabAnimatedClosedSinceMouseEnter||!this._tabContainer.classList.contains("static-layout")||this._tabContainer.classList.contains("animating"))
return;let barRect=this._tabContainer.getBoundingClientRect();if(event.pageY>barRect.top&&event.pageY<barRect.bottom&&event.pageX>barRect.left&&event.pageX<barRect.right)
return;this._finishExpandingTabsAfterClose();}
_handleTabContainerContextMenu(event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);for(let tabClass of WI.knownTabClasses()){if(!tabClass.isTabAllowed()||!tabClass.shouldSaveTab())
continue;let openTabBarItem=null;for(let tabBarItem of this._tabBarItems){let tabContentView=tabBarItem.representedObject;if(!(tabContentView instanceof WI.TabContentView))
continue;if(tabContentView.type===tabClass.Type){openTabBarItem=tabBarItem;break;}}
let checked=!!openTabBarItem;let disabled=checked&&this.normalTabCount===1;contextMenu.appendCheckboxItem(tabClass.tabInfo().displayName,()=>{if(openTabBarItem)
this.removeTabBarItem(openTabBarItem);else
WI.createNewTabWithType(tabClass.Type,{shouldShowNewTab:true});},checked,disabled);}
WI.sharedApp.extensionController.addContextMenuItemsForAllExtensionTabs(contextMenu);}};WI.TabBar.CachedWidthSymbol=Symbol("cached-width");WI.TabBar.Event={TabBarItemSelected:"tab-bar-tab-bar-item-selected",TabBarItemAdded:"tab-bar-tab-bar-item-added",TabBarItemRemoved:"tab-bar-tab-bar-item-removed",TabBarItemsReordered:"tab-bar-tab-bar-items-reordered",};WI.TabBarItem=class TabBarItem
{constructor(representedObject,image,displayName,title)
{this._representedObject=representedObject||null;this._parentTabBar=null;this._element=document.createElement("div");this._element.classList.add(WI.TabBarItem.StyleClassName);this._element.setAttribute("role","tab");this._element.tabIndex=0;this._element[WI.TabBarItem.ElementReferenceSymbol]=this;this._element.createChild("div","flex-space");this._iconElement=document.createElement("img");this._iconElement.classList.add("icon");this._element.appendChild(this._iconElement);this._element.createChild("div","flex-space");this.displayName=displayName;this.title=title;this.image=image;} 
get element(){return this._element;}
get representedObject(){return this._representedObject;}
get parentTabBar(){return this._parentTabBar;}
set parentTabBar(tabBar){this._parentTabBar=tabBar||null;}
get selected()
{return this._element.classList.contains("selected");}
set selected(selected)
{this._element.classList.toggle("selected",selected);if(selected)
this._element.setAttribute("aria-selected","true");else
this._element.removeAttribute("aria-selected");}
get disabled()
{return this._element.classList.contains("disabled");}
set disabled(disabled)
{this._element.classList.toggle("disabled",!!disabled);}
get hidden()
{return this._element.classList.contains("hidden");}
set hidden(hidden)
{this._element.classList.toggle("hidden",!!hidden);}
get image(){return this._iconElement.src;}
set image(url){this._iconElement.src=url||"";}
get displayName()
{return this._displayName;}
set displayName(displayName)
{displayName=displayName||"";if(this._displayName===displayName)
return;this._displayName=displayName;}
get title()
{return this._title;}
set title(title)
{title=title||"";if(this._title===title)
return;this._title=title;if(!this._title)
this._element.removeAttribute("title");else
this._element.title=this._title;}};WI.TabBarItem.StyleClassName="item";WI.TabBarItem.ElementReferenceSymbol=Symbol("tab-bar-item");WI.TabBrowser=class TabBrowser extends WI.View
{constructor(element,tabBar,navigationSidebar,detailsSidebar)
{super(element);this.element.classList.add("tab-browser");this._tabBar=tabBar;this._navigationSidebar=navigationSidebar||null;this._detailsSidebar=detailsSidebar||null;if(this._navigationSidebar){this._navigationSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);this._navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarWidthDidChange,this);}
if(this._detailsSidebar){this._detailsSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarWidthDidChange,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._handleSidebarPanelSelected,this);this._detailsSidebar.addEventListener(WI.MultiSidebar.Event.SidebarAdded,this._handleMultiSidebarSidebarAdded,this);}
this._contentViewContainer=new WI.ContentViewContainer;this.addSubview(this._contentViewContainer);let showNextTab=()=>{this._showNextTab();};let showPreviousTab=()=>{this._showPreviousTab();};let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let nextKey1=isRTL?WI.KeyboardShortcut.Key.LeftCurlyBrace:WI.KeyboardShortcut.Key.RightCurlyBrace;let previousKey1=isRTL?WI.KeyboardShortcut.Key.RightCurlyBrace:WI.KeyboardShortcut.Key.LeftCurlyBrace;this._showNextTabKeyboardShortcut1=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,nextKey1,showNextTab);this._showPreviousTabKeyboardShortcut1=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,previousKey1,showPreviousTab);let nextModifier2=isRTL?WI.KeyboardShortcut.Modifier.Shift:0;let previousModifier2=isRTL?0:WI.KeyboardShortcut.Modifier.Shift;this._showNextTabKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control|nextModifier2,WI.KeyboardShortcut.Key.Tab,showNextTab);this._showPreviousTabKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control|previousModifier2,WI.KeyboardShortcut.Key.Tab,showPreviousTab);let previousTabKey=isRTL?WI.KeyboardShortcut.Key.Right:WI.KeyboardShortcut.Key.Left;let nextTabKey=isRTL?WI.KeyboardShortcut.Key.Left:WI.KeyboardShortcut.Key.Right;this._previousTabKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,previousTabKey,this._showPreviousTabCheckingForEditableField.bind(this));this._previousTabKeyboardShortcut.implicitlyPreventsDefault=false;this._nextTabKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,nextTabKey,this._showNextTabCheckingForEditableField.bind(this));this._nextTabKeyboardShortcut.implicitlyPreventsDefault=false;this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemSelected,this._tabBarItemSelected,this);this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded,this._tabBarItemAdded,this);this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved,this._tabBarItemRemoved,this);this._recentTabContentViews=[];this._closedTabClasses=new Set;} 
get tabBar()
{return this._tabBar;}
get navigationSidebar()
{return this._navigationSidebar;}
get detailsSidebar()
{return this._detailsSidebar;}
get selectedTabContentView()
{return this._contentViewContainer.currentContentView;}
bestTabContentViewForClass(constructor)
{for(var tabContentView of this._recentTabContentViews){if(tabContentView instanceof constructor)
return tabContentView;}
return null;}
bestTabContentViewForRepresentedObject(representedObject,options={})
{let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();let tabContentView=this._recentTabContentViews.find((tabContentView)=>tabContentView.type===options.preferredTabType);if(tabContentView&&tabContentView.canShowRepresentedObject(representedObject))
return tabContentView;for(let tabContentView of this._recentTabContentViews){if(options.ignoreSearchTab&&tabContentView instanceof WI.SearchTabContentView)
continue;if(options.ignoreNetworkTab&&tabContentView instanceof WI.NetworkTabContentView)
continue;if(tabContentView.canShowRepresentedObject(representedObject))
return tabContentView;}
return null;}
addTabForContentView(tabContentView,options={})
{if(!(tabContentView instanceof WI.TabContentView))
return false;let tabBarItem=tabContentView.tabBarItem;if(!(tabBarItem instanceof WI.TabBarItem))
return false;if(tabBarItem.representedObject!==tabContentView)
tabBarItem.representedObject=tabContentView;if(tabBarItem.parentTabBar===this._tabBar)
return true;
if(this._recentTabContentViews.length&&this.selectedTabContentView)
this._recentTabContentViews.splice(1,0,tabContentView);else
this._recentTabContentViews.push(tabContentView);if(typeof options.insertionIndex==="number")
this._tabBar.insertTabBarItem(tabBarItem,options.insertionIndex,options);else
this._tabBar.addTabBarItem(tabBarItem,options);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();return true;}
showTabForContentView(tabContentView,options={})
{if(!this.addTabForContentView(tabContentView,options))
return false;this._tabBar.selectTabBarItem(tabContentView.tabBarItem,options);



this.needsLayout();return true;}
closeTabForContentView(tabContentView,options={})
{if(!(tabContentView instanceof WI.TabContentView))
return false;if(!(tabContentView.tabBarItem instanceof WI.TabBarItem))
return false;if(tabContentView.tabBarItem.parentTabBar!==this._tabBar)
return false;this._tabBar.removeTabBarItem(tabContentView.tabBarItem,options);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();return true;} 
sizeDidChange()
{super.sizeDidChange();for(let tabContentView of this._recentTabContentViews)
tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]=tabContentView!==this.selectedTabContentView;} 
_tabBarItemSelected(event)
{this._saveFocusedNodeForTabContentView(event.data.previousTabBarItem?event.data.previousTabBarItem.representedObject:null);let tabContentView=this._tabBar.selectedTabBarItem?this._tabBar.selectedTabBarItem.representedObject:null;if(tabContentView){let tabClass=tabContentView.constructor;let shouldSaveTab=tabClass.shouldSaveTab()||tabClass.shouldPinTab();if(shouldSaveTab){this._recentTabContentViews.remove(tabContentView);this._recentTabContentViews.unshift(tabContentView);}
this._contentViewContainer.showContentView(tabContentView);}else{this._contentViewContainer.closeAllContentViews();}
this._showNavigationSidebarPanelForTabContentView(tabContentView);this._showDetailsSidebarPanelsForTabContentView(tabContentView);if(tabContentView&&tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]){tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]=false;tabContentView.updateLayout(WI.View.LayoutReason.Resize);}
let outgoingTab=event.data.previousTabBarItem?event.data.previousTabBarItem.representedObject:null;let incomingTab=tabContentView;let initiator=event.data.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Unknown;this.dispatchEventToListeners(WI.TabBrowser.Event.SelectedTabContentViewDidChange,{outgoingTab,incomingTab,initiator});this._restoreFocusedNodeForTabContentView(tabContentView);}
_tabBarItemAdded(event)
{let tabContentView=event.data.tabBarItem.representedObject;if(!tabContentView)
return;this._closedTabClasses.delete(tabContentView.constructor);}
_tabBarItemRemoved(event)
{let tabContentView=event.data.tabBarItem.representedObject;if(!tabContentView)
return;this._recentTabContentViews.remove(tabContentView);if(tabContentView.constructor.shouldSaveTab())
this._closedTabClasses.add(tabContentView.constructor);this._contentViewContainer.closeContentView(tabContentView);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();}
_handleSidebarPanelSelected(event)
{if(this._ignoreSidebarEvents)
return;var tabContentView=this.selectedTabContentView;if(!tabContentView)
return;if(tabContentView.managesDetailsSidebarPanels)
return;var selectedSidebarPanel=this._detailsSidebar.selectedSidebarPanel;tabContentView.detailsSidebarSelectedPanelSetting.value=selectedSidebarPanel?.identifier??null;}
_handleSidebarCollapsedStateDidChange(event)
{if(this._ignoreSidebarEvents)
return;var tabContentView=this.selectedTabContentView;if(!tabContentView)
return;if(event.target===this._navigationSidebar&&!tabContentView.managesNavigationSidebarPanel)
tabContentView.navigationSidebarCollapsedSetting.value=this._navigationSidebar.collapsed;else if(event.target===this._detailsSidebar&&!tabContentView.managesDetailsSidebarPanels)
tabContentView.detailsSidebarCollapsedSetting.value=this._detailsSidebar.collapsed;}
_handleSidebarWidthDidChange(event)
{if(this._ignoreSidebarEvents||!event.data)
return;let tabContentView=this.selectedTabContentView;if(!tabContentView)
return;switch(event.target){case this._navigationSidebar:tabContentView.navigationSidebarWidthSetting.value=event.data.newWidth;break;case this._detailsSidebar:if(event.data.sidebar&&event.data.newWidth){let identifier=event.data.sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(event.data.sidebar.sidebarPanels[0]?.identifier||null);if(identifier){tabContentView.detailsSidebarWidthSetting.value[identifier]=event.data.newWidth;tabContentView.detailsSidebarWidthSetting.save();}}
break;}}
_handleMultiSidebarSidebarAdded(event)
{let tabContentView=this.selectedTabContentView;if(!tabContentView)
return;if(event.target!==this._detailsSidebar)
return;let sidebar=event.data.sidebar;let identifier=event.data.sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(event.data.sidebar.sidebarPanels[0]?.identifier||null);sidebar.width=tabContentView.detailsSidebarWidthSetting.value[identifier]||WI.TabContentView.DefaultSidebarWidth;}
_saveFocusedNodeForTabContentView(tabContentView)
{if(!tabContentView)
return;if(!WI.isContentAreaFocused())
return;tabContentView[WI.TabBrowser.FocusedNodeSymbol]=document.activeElement;}
_restoreFocusedNodeForTabContentView(tabContentView)
{if(!tabContentView)
return;let node=tabContentView[WI.TabBrowser.FocusedNodeSymbol];if(node&&!WI.isContentAreaFocused())
node.focus();tabContentView[WI.TabBrowser.FocusedNodeSymbol]=null;}
_showNavigationSidebarPanelForTabContentView(tabContentView)
{if(!this._navigationSidebar)
return;this._ignoreSidebarEvents=true;this._navigationSidebar.removeSidebarPanel(0);if(!tabContentView){this._ignoreSidebarEvents=false;return;}
if(tabContentView.navigationSidebarWidthSetting.value)
this._navigationSidebar.width=tabContentView.navigationSidebarWidthSetting.value;var navigationSidebarPanel=tabContentView.navigationSidebarPanel;if(!navigationSidebarPanel){this._navigationSidebar.collapsed=true;this._ignoreSidebarEvents=false;return;}
if(tabContentView.managesNavigationSidebarPanel){tabContentView.showNavigationSidebarPanel();this._ignoreSidebarEvents=false;return;}
this._navigationSidebar.addSidebarPanel(navigationSidebarPanel);this._navigationSidebar.selectedSidebarPanel=navigationSidebarPanel;this._navigationSidebar.collapsed=tabContentView.navigationSidebarCollapsedSetting.value;this._ignoreSidebarEvents=false;}
_showDetailsSidebarPanelsForTabContentView(tabContentView)
{if(!this._detailsSidebar)
return;this._ignoreSidebarEvents=true;for(var i=this._detailsSidebar.sidebarPanels.length-1;i>=0;--i)
this._detailsSidebar.removeSidebarPanel(i);if(!tabContentView){this._ignoreSidebarEvents=false;return;}
for(let sidebar of this._detailsSidebar.sidebars){let identifier=sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(sidebar.sidebarPanels[0]?.identifier||null);sidebar.width=tabContentView.detailsSidebarWidthSetting.value[identifier]||WI.TabContentView.DefaultSidebarWidth;}
this._detailsSidebar.allowMultipleSidebars=tabContentView.allowMultipleDetailSidebars;if(tabContentView.managesDetailsSidebarPanels){tabContentView.showDetailsSidebarPanels();this._ignoreSidebarEvents=false;return;}
var detailsSidebarPanels=tabContentView.detailsSidebarPanels;if(!detailsSidebarPanels){this._detailsSidebar.collapsed=true;this._ignoreSidebarEvents=false;return;}
for(var detailsSidebarPanel of detailsSidebarPanels)
this._detailsSidebar.addSidebarPanel(detailsSidebarPanel);this._detailsSidebar.selectedSidebarPanel=tabContentView.detailsSidebarSelectedPanelSetting.value||detailsSidebarPanels[0];this._detailsSidebar.collapsed=tabContentView.detailsSidebarCollapsedSetting.value||!detailsSidebarPanels.length;this._ignoreSidebarEvents=false;}
_showPreviousTab(event)
{this._tabBar.selectPreviousTab();}
_showNextTab(event)
{this._tabBar.selectNextTab();}
_showNextTabCheckingForEditableField(event)
{if(WI.isEventTargetAnEditableField(event))
return;this._showNextTab(event);event.preventDefault();}
_showPreviousTabCheckingForEditableField(event)
{if(WI.isEventTargetAnEditableField(event))
return;this._showPreviousTab(event);event.preventDefault();}};WI.TabBrowser.NeedsResizeLayoutSymbol=Symbol("needs-resize-layout");WI.TabBrowser.FocusedNodeSymbol=Symbol("focused-node");WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier="primary-sidebar";WI.TabBrowser.TabNavigationInitiator={TabClick:"tab-browser-tab-navigation-initiator-tab-click",LinkClick:"tab-browser-tab-navigation-initiator-link-click",ButtonClick:"tab-browser-tab-navigation-initiator-button-click",ContextMenu:"tab-browser-tab-navigation-initiator-context-menu",Dashboard:"tab-browser-tab-navigation-initiator-dashboard",Breakpoint:"tab-browser-tab-navigation-initiator-breakpoint",Inspect:"tab-browser-tab-navigation-initiator-inspect",KeyboardShortcut:"tab-browser-tab-navigation-initiator-keyboard-shortcut",FrontendAPI:"tab-browser-tab-navigation-initiator-frontend-api",Unknown:"tab-browser-tab-navigation-initiator-unknown"}
WI.TabBrowser.Event={SelectedTabContentViewDidChange:"tab-browser-selected-tab-content-view-did-change"};WI.Table=class Table extends WI.View
{constructor(identifier,dataSource,delegate,rowHeight)
{super();this._identifier=identifier;this._dataSource=dataSource;this._delegate=delegate;this._rowHeight=rowHeight;
this.element.classList.add("table",identifier);this.element.tabIndex=0;this.element.addEventListener("keydown",this._handleKeyDown.bind(this));this._headerElement=this.element.appendChild(document.createElement("div"));this._headerElement.className="header";let scrollHandler=this._handleScroll.bind(this);this._scrollContainerElement=this.element.appendChild(document.createElement("div"));this._scrollContainerElement.className="data-container";this._scrollContainerElement.addEventListener("scroll",scrollHandler);this._scrollContainerElement.addEventListener("mousewheel",scrollHandler);this._scrollContainerElement.addEventListener("mousedown",this._handleMouseDown.bind(this));if(this._delegate.tableCellContextMenuClicked)
this._scrollContainerElement.addEventListener("contextmenu",this._handleContextMenu.bind(this));this._topSpacerElement=this._scrollContainerElement.appendChild(document.createElement("div"));this._topSpacerElement.className="spacer";this._listElement=this._scrollContainerElement.appendChild(document.createElement("ul"));this._listElement.className="data-list";this._bottomSpacerElement=this._scrollContainerElement.appendChild(document.createElement("div"));this._bottomSpacerElement.className="spacer";this._fillerRow=this._listElement.appendChild(document.createElement("li"));this._fillerRow.className="filler";this._resizersElement=this._element.appendChild(document.createElement("div"));this._resizersElement.className="resizers";this._cachedRows=new Map;this._columnSpecs=new Map;this._columnOrder=[];this._visibleColumns=[];this._hiddenColumns=[];this._widthGeneration=1;this._columnWidths=null;this._fillerHeight=0;let selectionComparator=WI.SelectionController.createListComparator(this._indexForRepresentedObject.bind(this));this._selectionController=new WI.SelectionController(this,selectionComparator);this._resizers=[];this._currentResizer=null;this._resizeLeftColumns=null;this._resizeRightColumns=null;this._resizeOriginalColumnWidths=null;this._lastColumnIndexToAcceptRemainderPixel=0;this._sortOrderSetting=new WI.Setting(this._identifier+"-sort-order",WI.Table.SortOrder.Indeterminate);this._sortColumnIdentifierSetting=new WI.Setting(this._identifier+"-sort",null);this._columnVisibilitySetting=new WI.Setting(this._identifier+"-column-visibility",{});this._sortOrder=this._sortOrderSetting.value;this._sortColumnIdentifier=this._sortColumnIdentifierSetting.value;this._cachedWidth=NaN;this._cachedHeight=NaN;this._cachedScrollTop=NaN;this._previousCachedWidth=NaN;this._previousRevealedRowCount=NaN;this._topSpacerHeight=NaN;this._bottomSpacerHeight=NaN;this._visibleRowIndexStart=NaN;this._visibleRowIndexEnd=NaN;} 
get identifier(){return this._identifier;}
get dataSource(){return this._dataSource;}
get delegate(){return this._delegate;}
get rowHeight(){return this._rowHeight;}
get selectedRow()
{let item=this._selectionController.lastSelectedItem;let index=this._indexForRepresentedObject(item);return index>=0?index:NaN;}
get selectedRows()
{let rowIndexes=[];for(let item of this._selectionController.selectedItems)
rowIndexes.push(this._indexForRepresentedObject(item));return rowIndexes;}
get scrollContainer(){return this._scrollContainerElement;}
get numberOfRows()
{return this._dataSource.tableNumberOfRows(this);}
get sortOrder()
{return this._sortOrder;}
set sortOrder(sortOrder)
{if(sortOrder===this._sortOrder&&this.didInitialLayout)
return;this._sortOrder=sortOrder;this._sortOrderSetting.value=sortOrder;if(this._sortColumnIdentifier){let column=this._columnSpecs.get(this._sortColumnIdentifier);let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex!==-1){let headerCell=this._headerElement.children[columnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);}
if(this._dataSource.tableSortChanged)
this._dataSource.tableSortChanged(this);}}
get sortColumnIdentifier()
{return this._sortColumnIdentifier;}
set sortColumnIdentifier(columnIdentifier)
{if(columnIdentifier===this._sortColumnIdentifier&&this.didInitialLayout)
return;let column=this._columnSpecs.get(columnIdentifier);if(!column)
return;if(!column.sortable)
return;let oldSortColumnIdentifier=this._sortColumnIdentifier;this._sortColumnIdentifier=columnIdentifier;this._sortColumnIdentifierSetting.value=columnIdentifier;if(oldSortColumnIdentifier){let oldColumn=this._columnSpecs.get(oldSortColumnIdentifier);let oldColumnIndex=this._visibleColumns.indexOf(oldColumn);if(oldColumnIndex!==-1){let headerCell=this._headerElement.children[oldColumnIndex];headerCell.classList.remove("sort-ascending","sort-descending");}}
if(this._sortColumnIdentifier){let newColumnIndex=this._visibleColumns.indexOf(column);if(newColumnIndex!==-1){let headerCell=this._headerElement.children[newColumnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);}else
this._sortColumnIdentifier=null;}
if(this._dataSource.tableSortChanged)
this._dataSource.tableSortChanged(this);}
get allowsMultipleSelection()
{return this._selectionController.allowsMultipleSelection;}
set allowsMultipleSelection(flag)
{this._selectionController.allowsMultipleSelection=flag;}
get columns()
{return Array.from(this._columnSpecs.values());}
isRowSelected(rowIndex)
{return this._selectionController.hasSelectedItem(this._representedObjectForIndex(rowIndex));}
reloadData()
{this._cachedRows.clear();this._selectionController.reset();this._previousRevealedRowCount=NaN;this.needsLayout();}
reloadDataAddedToEndOnly()
{this._previousRevealedRowCount=NaN;this.needsLayout();}
reloadRow(rowIndex)
{if(this._isRowVisible(rowIndex)){let row=this._cachedRows.get(rowIndex);if(!row)
return;this._populateRow(row);return;}
this._cachedRows.delete(rowIndex);}
reloadVisibleColumnCells(column)
{let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex===-1)
return;let numberOfRows=Math.min(this._visibleRowIndexEnd,this.numberOfRows);for(let rowIndex=this._visibleRowIndexStart;rowIndex<numberOfRows;++rowIndex){let row=this._cachedRows.get(rowIndex);if(!row)
continue;let cell=row.children[columnIndex];if(!cell)
continue;this._delegate.tablePopulateCell(this,cell,column,rowIndex);}}
reloadCell(rowIndex,columnIdentifier)
{let column=this._columnSpecs.get(columnIdentifier);let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex===-1)
return;if(this._isRowVisible(rowIndex)){let row=this._cachedRows.get(rowIndex);if(!row)
return;let cell=row.children[columnIndex];if(!cell)
return;this._delegate.tablePopulateCell(this,cell,column,rowIndex);return;}
this._cachedRows.delete(rowIndex);}
selectRow(rowIndex,extendSelection=false)
{this._selectionController.selectItem(this._representedObjectForIndex(rowIndex),extendSelection);}
deselectRow(rowIndex)
{this._selectionController.deselectItem(this._representedObjectForIndex(rowIndex));}
selectAll()
{this._selectionController.selectAll();}
deselectAll()
{this._selectionController.deselectAll();}
removeRow(rowIndex)
{if(this.isRowSelected(rowIndex))
this.deselectRow(rowIndex);this._removeRows(new Set([this._representedObjectForIndex(rowIndex)]));}
removeSelectedRows()
{let selectedItems=this._selectionController.selectedItems;if(!selectedItems.size)
return;
this._selectionController.removeSelectedItems();this._removeRows(selectedItems);}
revealRow(rowIndex)
{if(rowIndex<0||rowIndex>=this.numberOfRows)
return;if(this._isRowVisible(rowIndex)){let row=this._cachedRows.get(rowIndex);if(row){row.scrollIntoViewIfNeeded(false);this._cachedScrollTop=NaN;this.needsLayout();}}else{let rowPosition=rowIndex*this._rowHeight;let scrollableOffsetHeight=this._calculateOffsetHeight();let scrollTop=this._calculateScrollTop();let newScrollTop=NaN;if(rowPosition+this._rowHeight<scrollTop)
newScrollTop=rowPosition;else if(rowPosition>scrollTop+scrollableOffsetHeight)
newScrollTop=scrollTop+scrollableOffsetHeight-this._rowHeight;if(!isNaN(newScrollTop)){this._scrollContainerElement.scrollTop=newScrollTop;this.updateLayout();}}}
columnWithIdentifier(identifier)
{return this._columnSpecs.get(identifier);}
cellForRowAndColumn(rowIndex,column)
{if(!this._isRowVisible(rowIndex))
return null;let row=this._cachedRows.get(rowIndex);if(!row)
return null;let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex===-1)
return null;return row.children[columnIndex];}
addColumn(column)
{this._columnSpecs.set(column.identifier,column);this._columnOrder.push(column.identifier);if(column.hidden){this._hiddenColumns.push(column);column.width=NaN;}else{this._visibleColumns.push(column);this._headerElement.appendChild(this._createHeaderCell(column));this._fillerRow.appendChild(this._createFillerCell(column));if(column.headerView)
this.addSubview(column.headerView);}
let savedColumnVisibility=this._columnVisibilitySetting.value;if(column.identifier in savedColumnVisibility){let visible=savedColumnVisibility[column.identifier];if(visible)
this.showColumn(column);else
this.hideColumn(column);}
this.reloadData();}
showColumn(column)
{if(column.locked)
return;if(!column.hidden)
return;column.hidden=false;let columnIndex=this._hiddenColumns.indexOf(column);this._hiddenColumns.splice(columnIndex,1);let newColumnIndex=this._indexToInsertColumn(column);this._visibleColumns.insertAtIndex(column,newColumnIndex);let savedColumnVisibility=this._columnVisibilitySetting.value;if(savedColumnVisibility[column.identifier]!==true){let copy=Object.shallowCopy(savedColumnVisibility);if(column.defaultHidden)
copy[column.identifier]=true;else
delete copy[column.identifier];this._columnVisibilitySetting.value=copy;}
this._headerElement.insertBefore(this._createHeaderCell(column),this._headerElement.children[newColumnIndex]);this._fillerRow.insertBefore(this._createFillerCell(column),this._fillerRow.children[newColumnIndex]);if(column.headerView)
this.addSubview(column.headerView);if(this._sortColumnIdentifier===column.identifier){let headerCell=this._headerElement.children[newColumnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);}
if(!this._columnWidths)
return;
let cellsToPopulate=[];for(let row of this._listElement.children){if(row!==this._fillerRow){let unpopulatedCell=this._createCell(column,newColumnIndex);cellsToPopulate.push(unpopulatedCell);row.insertBefore(unpopulatedCell,row.children[newColumnIndex]);}}
this._widthGeneration++;this._columnWidths=null;this._resizeColumnsAndFiller();for(let cell of cellsToPopulate)
this._delegate.tablePopulateCell(this,cell,column,cell.parentElement.__index);for(let visibleColumn of this._visibleColumns){if(visibleColumn!==column){if(visibleColumn.needsReloadOnResize)
this.reloadVisibleColumnCells(visibleColumn);}}}
hideColumn(column)
{if(column.locked)
return;if(!column.hideable)
return;if(column.hidden)
return;column.hidden=true;this._hiddenColumns.push(column);let columnIndex=this._visibleColumns.indexOf(column);this._visibleColumns.splice(columnIndex,1);let savedColumnVisibility=this._columnVisibilitySetting.value;if(savedColumnVisibility[column.identifier]!==false){let copy=Object.shallowCopy(savedColumnVisibility);if(column.defaultHidden)
delete copy[column.identifier];else
copy[column.identifier]=false;this._columnVisibilitySetting.value=copy;}
this._headerElement.removeChild(this._headerElement.children[columnIndex]);this._fillerRow.removeChild(this._fillerRow.children[columnIndex]);if(column.headerView)
this.removeSubview(column.headerView);if(!this._columnWidths)
return;for(let row of this._listElement.children){if(row!==this._fillerRow)
row.removeChild(row.children[columnIndex]);}
this._widthGeneration++;this._columnWidths=null;this._resizeColumnsAndFiller();for(let visibleColumn of this._visibleColumns){if(visibleColumn.needsReloadOnResize)
this.reloadVisibleColumnCells(visibleColumn);}} 
attached()
{super.attached();if(this._cachedScrollTop&&!this._scrollContainerElement.scrollTop)
this._scrollContainerElement.scrollTop=this._cachedScrollTop;}
initialLayout()
{this.sortOrder=this._sortOrderSetting.value;let restoreSortColumnIdentifier=this._sortColumnIdentifierSetting.value;if(!this._columnSpecs.has(restoreSortColumnIdentifier))
this._sortColumnIdentifierSetting.value=null;else
this.sortColumnIdentifier=restoreSortColumnIdentifier;}
layout()
{this._updateVisibleRows();this._resizeColumnsAndFiller();}
sizeDidChange()
{super.sizeDidChange();this._previousCachedWidth=this._cachedWidth;this._cachedWidth=NaN;this._cachedHeight=NaN;} 
selectionControllerSelectionDidChange(controller,deselectedItems,selectedItems)
{for(let item of deselectedItems){let rowIndex=this._indexForRepresentedObject(item);let row=this._cachedRows.get(rowIndex);if(row)
row.classList.toggle("selected",false);}
for(let item of selectedItems){let rowIndex=this._indexForRepresentedObject(item);let row=this._cachedRows.get(rowIndex);if(row)
row.classList.toggle("selected",true);}
if(this._selectionController.lastSelectedItem){let rowIndex=this._indexForRepresentedObject(this._selectionController.lastSelectedItem);this.revealRow(rowIndex);}
if(this._delegate.tableSelectionDidChange)
this._delegate.tableSelectionDidChange(this);}
selectionControllerFirstSelectableItem(controller)
{return this._representedObjectForIndex(0);}
selectionControllerLastSelectableItem(controller)
{return this._representedObjectForIndex(this.numberOfRows-1);}
selectionControllerPreviousSelectableItem(controller,item)
{let index=this._indexForRepresentedObject(item);return index>0?this._representedObjectForIndex(index-1):null;}
selectionControllerNextSelectableItem(controller,item)
{let index=this._indexForRepresentedObject(item);return index<this.numberOfRows-1?this._representedObjectForIndex(index+1):null;} 
resizerDragStarted(resizer)
{let resizerIndex=this._resizers.indexOf(resizer);this._currentResizer=resizer;this._resizeLeftColumns=this._visibleColumns.slice(0,resizerIndex+1).reverse();this._resizeRightColumns=this._visibleColumns.slice(resizerIndex+1);this._resizeOriginalColumnWidths=[].concat(this._columnWidths);}
resizerDragging(resizer,positionDelta)
{if(resizer!==this._currentResizer)
return;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
positionDelta=-positionDelta;this._columnWidths=[].concat(this._resizeOriginalColumnWidths);if(!positionDelta){this._applyColumnWidths();return;}
let delta=Math.abs(positionDelta);let leftDirection=positionDelta>0;let rightDirection=!leftDirection;let columnWidths=this._columnWidths;let visibleColumns=this._visibleColumns;function growableSize(column){let width=columnWidths[visibleColumns.indexOf(column)];if(column.maxWidth)
return column.maxWidth-width;return Infinity;}
function shrinkableSize(column){let width=columnWidths[visibleColumns.indexOf(column)];if(column.minWidth)
return width-column.minWidth;return width;}
function canGrow(column){return growableSize(column)>0;}
function canShrink(column){return shrinkableSize(column)>0;}
function columnToResize(columns,isShrinking){for(let column of columns){if(!column.flexible)
continue;if(isShrinking?canShrink(column):canGrow(column))
return column;}
let immediateColumn=columns[0];if((isShrinking&&canShrink(immediateColumn))||(!isShrinking&&canGrow(immediateColumn)))
return immediateColumn;return null;}
while(delta>0){let leftColumn=columnToResize(this._resizeLeftColumns,leftDirection);let rightColumn=columnToResize(this._resizeRightColumns,rightDirection);if(!leftColumn||!rightColumn){break;}
let incrementalDelta=Math.min(delta,leftDirection?shrinkableSize(leftColumn):shrinkableSize(rightColumn),leftDirection?growableSize(rightColumn):growableSize(leftColumn));let leftIndex=this._visibleColumns.indexOf(leftColumn);let rightIndex=this._visibleColumns.indexOf(rightColumn);if(leftDirection){this._columnWidths[leftIndex]-=incrementalDelta;this._columnWidths[rightIndex]+=incrementalDelta;}else{this._columnWidths[leftIndex]+=incrementalDelta;this._columnWidths[rightIndex]-=incrementalDelta;}
delta-=incrementalDelta;}
this._widthGeneration++;this._applyColumnWidths();this._positionHeaderViews();}
resizerDragEnded(resizer)
{if(resizer!==this._currentResizer)
return;this._currentResizer=null;this._resizeLeftColumns=null;this._resizeRightColumns=null;this._resizeOriginalColumnWidths=null;this._positionResizerElements();this._positionHeaderViews();} 
_createHeaderCell(column)
{let cell=document.createElement("span");cell.classList.add("cell",column.identifier);cell.textContent=column.name;if(column.align)
cell.classList.add("align-"+column.align);if(column.sortable){cell.classList.add("sortable");cell.addEventListener("click",this._handleHeaderCellClicked.bind(this,column));}
cell.addEventListener("contextmenu",this._handleHeaderContextMenu.bind(this,column));return cell;}
_createFillerCell(column)
{let cell=document.createElement("span");cell.classList.add("cell",column.identifier);return cell;}
_createCell(column,columnIndex)
{let cell=document.createElement("span");cell.classList.add("cell",column.identifier);if(column.align)
cell.classList.add("align-"+column.align);if(this._columnWidths)
cell.style.width=this._columnWidths[columnIndex]+"px";return cell;}
_getOrCreateRow(rowIndex)
{let cachedRow=this._cachedRows.get(rowIndex);if(cachedRow)
return cachedRow;let row=document.createElement("li");row.__index=rowIndex;row.__widthGeneration=0;if(this.isRowSelected(rowIndex))
row.classList.add("selected");this._cachedRows.set(rowIndex,row);return row;}
_populatedCellForColumnAndRow(column,columnIndex,rowIndex)
{let cell=this._createCell(column,columnIndex);this._delegate.tablePopulateCell(this,cell,column,rowIndex);return cell;}
_populateRow(row)
{row.removeChildren();let rowIndex=row.__index;for(let i=0;i<this._visibleColumns.length;++i){let column=this._visibleColumns[i];let cell=this._populatedCellForColumnAndRow(column,i,rowIndex);row.appendChild(cell);}}
_resizeColumnsAndFiller()
{if(isNaN(this._cachedWidth)||!this._cachedWidth)
this._cachedWidth=this._scrollContainerElement.realOffsetWidth;if(!this._cachedWidth)
return;let availableWidth=this._cachedWidth;let availableHeight=this._cachedHeight;let contentHeight=this.numberOfRows*this._rowHeight;this._fillerHeight=Math.max(availableHeight-contentHeight,0);if(this._columnWidths&&this._cachedWidth===this._previousCachedWidth){this._updateFillerRowWithNewHeight();this._applyColumnWidthsToColumnsIfNeeded();return;}
this._previousCachedWidth=this._cachedWidth;let lockedWidth=0;let lockedColumnCount=0;let totalMinimumWidth=0;for(let column of this._visibleColumns){if(column.locked){lockedWidth+=column.width;lockedColumnCount++;totalMinimumWidth+=column.width;}else if(column.minWidth)
totalMinimumWidth+=column.minWidth;}
let flexibleWidth=availableWidth-lockedWidth;let flexibleColumnCount=this._visibleColumns.length-lockedColumnCount;



function distributeRemainingPixels(remainder,shrinking){if(!remainder)
return;let indexToStartAddingRemainderPixels=(this._lastColumnIndexToAcceptRemainderPixel+1)%this._visibleColumns.length;

let ignoreConstraints=false;while(remainder>0){let initialRemainder=remainder;for(let i=indexToStartAddingRemainderPixels;i<this._columnWidths.length;++i){let column=this._visibleColumns[i];if(column.locked)
continue;if(shrinking){if(ignoreConstraints||(column.minWidth&&this._columnWidths[i]>column.minWidth)){this._columnWidths[i]--;remainder--;}}else{if(ignoreConstraints||(column.maxWidth&&this._columnWidths[i]<column.maxWidth)){this._columnWidths[i]++;remainder--;}else if(!column.maxWidth){this._columnWidths[i]++;remainder--;}}
if(!remainder){this._lastColumnIndexToAcceptRemainderPixel=i;break;}}
if(remainder===initialRemainder&&!indexToStartAddingRemainderPixels){if(ignoreConstraints)
break;ignoreConstraints=true;}
indexToStartAddingRemainderPixels=0;}}
if(!this._columnWidths){this._columnWidths=[];this._lastColumnIndexToAcceptRemainderPixel=0;let bestFitWidth=0;let bestFitColumnCount=0;function bestFit(callback){while(true){let remainingFlexibleColumnCount=flexibleColumnCount-bestFitColumnCount;if(!remainingFlexibleColumnCount)
return;let remainingFlexibleWidth=flexibleWidth-bestFitWidth;let flexWidth=Math.floor(remainingFlexibleWidth/remainingFlexibleColumnCount);let didPerformBestFit=false;for(let i=0;i<this._visibleColumns.length;++i){if(this._columnWidths[i])
continue;let column=this._visibleColumns[i];let bestWidth=callback(column,flexWidth);if(bestWidth===-1)
continue;this._columnWidths[i]=bestWidth;bestFitWidth+=bestWidth;bestFitColumnCount++;didPerformBestFit=true;}
if(!didPerformBestFit)
return;}}
for(let i=0;i<this._visibleColumns.length;++i){let column=this._visibleColumns[i];if(column.locked)
this._columnWidths[i]=column.width;}
bestFit.call(this,(column,width)=>{if(!column.preferredInitialWidth||width<=column.preferredInitialWidth)
return-1;return column.preferredInitialWidth;});bestFit.call(this,(column,width)=>{if(!column.maxWidth||width<=column.maxWidth)
return-1;return column.maxWidth;});bestFit.call(this,(column,width)=>{if(!column.minWidth||width>=column.minWidth)
return-1;return column.minWidth;});bestFit.call(this,(column,width)=>width);let remainder=availableWidth-(lockedWidth+bestFitWidth);let shrinking=remainder<0;distributeRemainingPixels.call(this,Math.abs(remainder),shrinking);}else{let originalTotalColumnWidth=0;for(let width of this._columnWidths)
originalTotalColumnWidth+=width;let remainder=Math.abs(availableWidth-originalTotalColumnWidth);let shrinking=availableWidth<originalTotalColumnWidth;distributeRemainingPixels.call(this,remainder,shrinking);}
this._widthGeneration++;this._updateFillerRowWithNewHeight();this._applyColumnWidths();this._positionResizerElements();this._positionHeaderViews();}
_updateVisibleRows()
{let rowHeight=this._rowHeight;let updateOffsetThreshold=rowHeight*10;let overflowPadding=updateOffsetThreshold*3;let scrollTop=this._calculateScrollTop();let scrollableOffsetHeight=this._calculateOffsetHeight();let visibleRowCount=Math.ceil((scrollableOffsetHeight+(overflowPadding*2))/rowHeight);let currentTopMargin=this._topSpacerHeight;let currentBottomMargin=this._bottomSpacerHeight;let currentTableBottom=currentTopMargin+(visibleRowCount*rowHeight);let belowTopThreshold=!currentTopMargin||scrollTop>currentTopMargin+updateOffsetThreshold;let aboveBottomThreshold=!currentBottomMargin||scrollTop+scrollableOffsetHeight<currentTableBottom-updateOffsetThreshold;if(belowTopThreshold&&aboveBottomThreshold&&!isNaN(this._previousRevealedRowCount))
return;let numberOfRows=this.numberOfRows;this._previousRevealedRowCount=numberOfRows;

if(scrollTop){let rowsThatCanFitOnScreen=Math.ceil(scrollableOffsetHeight/rowHeight);if(numberOfRows>=rowsThatCanFitOnScreen){let maximumScrollTop=Math.max(0,(numberOfRows*rowHeight)-scrollableOffsetHeight);if(scrollTop>maximumScrollTop){this._scrollContainerElement.scrollTop=maximumScrollTop;this._cachedScrollTop=maximumScrollTop;}}}
let topHiddenRowCount=Math.max(0,Math.floor((scrollTop-overflowPadding)/rowHeight));let bottomHiddenRowCount=Math.max(0,this._previousRevealedRowCount-topHiddenRowCount-visibleRowCount);let marginTop=topHiddenRowCount*rowHeight;let marginBottom=bottomHiddenRowCount*rowHeight;if(this._topSpacerHeight!==marginTop){this._topSpacerHeight=marginTop;this._topSpacerElement.style.height=marginTop+"px";}
if(this._bottomDataTableMarginElement!==marginBottom){this._bottomSpacerHeight=marginBottom;this._bottomSpacerElement.style.height=marginBottom+"px";}
this._visibleRowIndexStart=topHiddenRowCount;this._visibleRowIndexEnd=this._visibleRowIndexStart+visibleRowCount;this._listElement.removeChildren();this._listElement.classList.toggle("even-first-zebra-stripe",!!(topHiddenRowCount%2));for(let i=this._visibleRowIndexStart;i<this._visibleRowIndexEnd&&i<numberOfRows;++i){let row=this._getOrCreateRow(i);this._listElement.appendChild(row);}
this._listElement.appendChild(this._fillerRow);}
_updateFillerRowWithNewHeight()
{if(!this._fillerHeight){this._scrollContainerElement.classList.remove("not-scrollable");this._fillerRow.remove();return;}
this._scrollContainerElement.classList.add("not-scrollable");
if(this._cachedScrollTop){this._scrollContainerElement.scrollTop=0;this._cachedScrollTop=0;}
const paddingPastTheEdge=200;this._fillerHeight+=paddingPastTheEdge;for(let cell of this._fillerRow.children)
cell.style.height=this._fillerHeight+"px";if(!this._fillerRow.parentElement)
this._listElement.appendChild(this._fillerRow);}
_applyColumnWidths()
{for(let i=0;i<this._headerElement.children.length;++i)
this._headerElement.children[i].style.width=this._columnWidths[i]+"px";for(let row of this._listElement.children){for(let i=0;i<row.children.length;++i)
row.children[i].style.width=this._columnWidths[i]+"px";row.__widthGeneration=this._widthGeneration;}
for(let i=0;i<this._visibleColumns.length;++i)
this._visibleColumns[i].width=this._columnWidths[i];for(let row of this._listElement.children){if(row!==this._fillerRow){if(row.children.length!==this._visibleColumns.length)
this._populateRow(row);}}}
_applyColumnWidthsToColumnsIfNeeded()
{for(let row of this._listElement.children){if(row.__widthGeneration!==this._widthGeneration){for(let i=0;i<row.children.length;++i)
row.children[i].style.width=this._columnWidths[i]+"px";if(row!==this._fillerRow){if(row.children.length!==this._visibleColumns.length)
this._populateRow(row);}
row.__widthGeneration=this._widthGeneration;}}}
_positionResizerElements()
{let resizersNeededCount=this._visibleColumns.length-1;if(this._resizers.length!==resizersNeededCount){if(this._resizers.length<resizersNeededCount){do{let resizer=new WI.Resizer(WI.Resizer.RuleOrientation.Vertical,this);this._resizers.push(resizer);this._resizersElement.appendChild(resizer.element);}while(this._resizers.length<resizersNeededCount);}else{do{let resizer=this._resizers.pop();this._resizersElement.removeChild(resizer.element);}while(this._resizers.length>resizersNeededCount);}}
const columnResizerAdjustment=3;let positionAttribute=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";let totalWidth=0;for(let i=0;i<resizersNeededCount;++i){totalWidth+=this._columnWidths[i];this._resizers[i].element.style[positionAttribute]=(totalWidth-columnResizerAdjustment)+"px";}}
_positionHeaderViews()
{if(!this.subviews.length)
return;let offset=0;let updates=[];for(let i=0;i<this._visibleColumns.length;++i){let column=this._visibleColumns[i];let width=this._columnWidths[i];if(column.headerView)
updates.push({headerView:column.headerView,offset,width});offset+=width;}
let styleProperty=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";for(let{headerView,offset,width}of updates){headerView.element.style.setProperty(styleProperty,offset+"px");headerView.element.style.width=width+"px";headerView.updateLayout(WI.View.LayoutReason.Resize);}}
_isRowVisible(rowIndex)
{if(!this._previousRevealedRowCount)
return false;return rowIndex>=this._visibleRowIndexStart&&rowIndex<=this._visibleRowIndexEnd;}
_indexToInsertColumn(column)
{let currentVisibleColumnIndex=0;for(let columnIdentifier of this._columnOrder){if(columnIdentifier===column.identifier)
return currentVisibleColumnIndex;if(columnIdentifier===this._visibleColumns[currentVisibleColumnIndex].identifier){currentVisibleColumnIndex++;if(currentVisibleColumnIndex>=this._visibleColumns.length)
break;}}
return currentVisibleColumnIndex;}
_handleScroll(event)
{if(event.type==="mousewheel"&&!event.wheelDeltaY)
return;this._cachedScrollTop=NaN;this.needsLayout();}
_handleKeyDown(event)
{this._selectionController.handleKeyDown(event);}
_handleMouseDown(event)
{let cell=event.target.closest(".cell");if(!cell)
return;let row=cell.parentElement;if(row===this._fillerRow)
return;let rowIndex=row.__index;
if(!this.isRowSelected(rowIndex)&&this._delegate.tableShouldSelectRow){let columnIndex=Array.from(row.children).indexOf(cell);let column=this._visibleColumns[columnIndex];if(!this._delegate.tableShouldSelectRow(this,cell,column,rowIndex))
return;}
this._selectionController.handleItemMouseDown(this._representedObjectForIndex(rowIndex),event);}
_handleContextMenu(event)
{let cell=event.target.closest(".cell");if(!cell)
return;let row=cell.parentElement;if(row===this._fillerRow)
return;let columnIndex=Array.from(row.children).indexOf(cell);let column=this._visibleColumns[columnIndex];let rowIndex=row.__index;this._delegate.tableCellContextMenuClicked(this,cell,column,rowIndex,event);}
_handleHeaderCellClicked(column,event)
{let sortOrder=this._sortOrder;if(sortOrder===WI.Table.SortOrder.Indeterminate)
sortOrder=WI.Table.SortOrder.Descending;else if(this._sortColumnIdentifier===column.identifier)
sortOrder=sortOrder===WI.Table.SortOrder.Ascending?WI.Table.SortOrder.Descending:WI.Table.SortOrder.Ascending;this.sortColumnIdentifier=column.identifier;this.sortOrder=sortOrder;}
_handleHeaderContextMenu(column,event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);if(column.sortable){if(this.sortColumnIdentifier!==column.identifier||this.sortOrder!==WI.Table.SortOrder.Ascending){contextMenu.appendItem(WI.UIString("Sort Ascending"),()=>{this.sortColumnIdentifier=column.identifier;this.sortOrder=WI.Table.SortOrder.Ascending;});}
if(this.sortColumnIdentifier!==column.identifier||this.sortOrder!==WI.Table.SortOrder.Descending){contextMenu.appendItem(WI.UIString("Sort Descending"),()=>{this.sortColumnIdentifier=column.identifier;this.sortOrder=WI.Table.SortOrder.Descending;});}}
contextMenu.appendSeparator();let didAppendHeaderItem=false;for(let[columnIdentifier,column]of this._columnSpecs){if(column.locked)
continue;if(!column.hideable)
continue;if(!didAppendHeaderItem){const disabled=true;contextMenu.appendItem(WI.UIString("Displayed Columns"),()=>{},disabled);didAppendHeaderItem=true;}
let checked=!column.hidden;contextMenu.appendCheckboxItem(column.name,()=>{if(column.hidden)
this.showColumn(column);else
this.hideColumn(column);},checked);}}
_removeRows(representedObjects)
{let removed=0;let adjustRowAtIndex=(index)=>{let row=this._cachedRows.get(index);if(row){this._cachedRows.delete(index);row.__index-=removed;this._cachedRows.set(row.__index,row);}};let rowIndexes=[];for(let object of representedObjects)
rowIndexes.push(this._indexForRepresentedObject(object));rowIndexes.sort((a,b)=>a-b);let lastIndex=rowIndexes.lastValue;for(let index=rowIndexes[0];index<=lastIndex;++index){if(rowIndexes.binaryIndexOf(index)>=0){let row=this._cachedRows.get(index);if(row){this._cachedRows.delete(index);row.remove();}
removed++;continue;}
if(removed)
adjustRowAtIndex(index);}
if(!removed)
return;for(let index=lastIndex+1;index<this.numberOfRows;++index)
adjustRowAtIndex(index);this._selectionController.didRemoveItems(representedObjects);if(this._delegate.tableDidRemoveRows)
this._delegate.tableDidRemoveRows(this,rowIndexes);}
_indexForRepresentedObject(object)
{return this.dataSource.tableIndexForRepresentedObject(this,object);}
_representedObjectForIndex(index)
{return this.dataSource.tableRepresentedObjectForIndex(this,index);}
_calculateOffsetHeight()
{if(isNaN(this._cachedHeight))
this._cachedHeight=this._scrollContainerElement.realOffsetHeight;return this._cachedHeight;}
_calculateScrollTop()
{if(isNaN(this._cachedScrollTop))
this._cachedScrollTop=this._scrollContainerElement.scrollTop;return this._cachedScrollTop;}};WI.Table.SortOrder={Indeterminate:"table-sort-order-indeterminate",Ascending:"table-sort-order-ascending",Descending:"table-sort-order-descending",};WI.TableColumn=class TableColumn extends WI.Object
{constructor(identifier,name,{initialWidth,minWidth,maxWidth,hidden,sortable,hideable,align,resizeType,headerView,needsReloadOnResize}={})
{super();this._identifier=identifier;this._name=name;this._width=initialWidth||NaN;this._minWidth=minWidth||50;this._maxWidth=maxWidth||0;this._initialWidth=initialWidth||NaN;this._hidden=hidden||false;this._defaultHidden=hidden||false;this._sortable=typeof sortable==="boolean"?sortable:true;this._hideable=typeof hideable==="boolean"?hideable:true;this._align=align||null;this._resizeType=resizeType||TableColumn.ResizeType.Auto;this._headerView=headerView||null;this._needsReloadOnResize=needsReloadOnResize||false;}
get identifier(){return this._identifier;}
get name(){return this._name;}
get minWidth(){return this._minWidth;}
get maxWidth(){return this._maxWidth;}
get preferredInitialWidth(){return this._initialWidth;}
get defaultHidden(){return this._defaultHidden;}
get sortable(){return this._sortable;}
get hideable(){return this._hideable;}
get align(){return this._align;}
get headerView(){return this._headerView;}
get needsReloadOnResize(){return this._needsReloadOnResize;}
get locked(){return this._resizeType===TableColumn.ResizeType.Locked;}
get flexible(){return this._resizeType===TableColumn.ResizeType.Auto;}
get width()
{return this._width;}
set width(width)
{if(this._width===width)
return;this._width=width;this.dispatchEventToListeners(WI.TableColumn.Event.WidthDidChange);}
get hidden()
{return this._hidden;}
set hidden(x)
{this._hidden=x;}};WI.TableColumn.ResizeType={Auto:"auto",Locked:"locked",};WI.TableColumn.Event={WidthDidChange:"table-column-width-did-change",};WI.TextEditor=class TextEditor extends WI.View
{constructor(element,mimeType,delegate)
{super(element);this.element.classList.add("text-editor",WI.SyntaxHighlightedStyleClassName);this._codeMirror=WI.CodeMirrorEditor.create(this.element,{readOnly:true,lineNumbers:true,matchBrackets:true,autoCloseBrackets:true,styleSelectedText:true,});this._codeMirror.on("focus",this._editorFocused.bind(this));this._codeMirror.on("change",this._contentChanged.bind(this));this._codeMirror.on("gutterClick",this._gutterMouseDown.bind(this));this._codeMirror.on("gutterContextMenu",this._gutterContextMenu.bind(this));this._codeMirror.getScrollerElement().addEventListener("click",this._openClickedLinks.bind(this),true);this._completionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.Basic,this._codeMirror,this);this._tokenTrackingController=new WI.CodeMirrorTokenTrackingController(this._codeMirror,this);this._initialStringNotSet=true;this.mimeType=mimeType;this._breakpoints={};this._executionLineNumber=NaN;this._executionColumnNumber=NaN;this._executionLineHandle=null;this._executionMultilineHandles=[];this._executionRangeHighlightMarker=null;this._searchQuery=null;this._searchResults=[];this._currentSearchResultIndex=-1;this._ignoreCodeMirrorContentDidChangeEvent=0;this._formatted=false;this._formattingPromise=null;this._formatterSourceMap=null;this._deferReveal=false;this._repeatReveal=false;this._delegate=delegate||null;} 
get string()
{return this._codeMirror.getValue();}
set string(newString)
{let previousSelectedTextRange=this._repeatReveal?this.selectedTextRange:null;function update()
{if(this._initialStringNotSet)
this._codeMirror.removeLineClass(0,"wrap");if(this._codeMirror.getValue()!==newString)
this._codeMirror.setValue(newString);else{this.layout();}
if(this._initialStringNotSet){this._codeMirror.clearHistory();this._codeMirror.markClean();this._initialStringNotSet=false;if(this._searchQuery){let query=this._searchQuery;this._searchQuery=null;this.performSearch(query);}
if(this._codeMirror.getMode().name==="null"){

this._attemptToDetermineMIMEType();}}
this._updateExecutionLine();this._updateExecutionRangeHighlight();for(var lineNumber in this._breakpoints)
this._setBreakpointStylesOnLine(lineNumber);this._revealPendingPositionIfPossible();if(previousSelectedTextRange){this.selectedTextRange=previousSelectedTextRange;let position=this._codeMirrorPositionFromTextRange(previousSelectedTextRange);this._scrollIntoViewCentered(position.start);}}
this._ignoreCodeMirrorContentDidChangeEvent++;this._codeMirror.operation(update.bind(this));this._ignoreCodeMirrorContentDidChangeEvent--;}
get readOnly()
{return this._codeMirror.getOption("readOnly")||false;}
set readOnly(readOnly)
{this._codeMirror.setOption("readOnly",readOnly);this._codeMirror.getWrapperElement().classList.toggle("read-only",!!readOnly);}
get formatted()
{return this._formatted;}
get hasModified()
{let historySize=this._codeMirror.historySize().undo;if(this._formatted)
historySize--;return historySize>0;}
updateFormattedState(formatted)
{return this._format(formatted);}
hasFormatter()
{let mode=this._codeMirror.getMode().name;return mode==="javascript"||mode==="css"||mode==="htmlmixed"||mode==="xml";}
canBeFormatted()
{return this.hasFormatter();}
canShowTypeAnnotations()
{return false;}
canShowCoverageHints()
{return false;}
get selectedTextRange()
{var start=this._codeMirror.getCursor(true);var end=this._codeMirror.getCursor(false);return this._textRangeFromCodeMirrorPosition(start,end);}
set selectedTextRange(textRange)
{if(document.activeElement===document.body)
this.focus();var position=this._codeMirrorPositionFromTextRange(textRange);this._codeMirror.setSelection(position.start,position.end);}
get mimeType()
{return this._mimeType;}
set mimeType(newMIMEType)
{newMIMEType=parseMIMEType(newMIMEType).type;this._mimeType=newMIMEType;this._codeMirror.setOption("mode",{name:newMIMEType,globalVars:true});this.dispatchEventToListeners(WI.TextEditor.Event.MIMETypeChanged);}
get executionLineNumber()
{return this._executionLineNumber;}
get executionColumnNumber()
{return this._executionColumnNumber;}
get formatterSourceMap()
{return this._formatterSourceMap;}
get tokenTrackingController()
{return this._tokenTrackingController;}
get delegate()
{return this._delegate;}
set delegate(newDelegate)
{this._delegate=newDelegate||null;}
get numberOfSearchResults()
{return this._searchResults.length;}
get currentSearchQuery()
{return this._searchQuery;}
set automaticallyRevealFirstSearchResult(reveal)
{this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0){if(this._currentSearchResultIndex===-1)
this._revealFirstSearchResultAfterCursor();}}
set deferReveal(defer)
{this._deferReveal=defer;}
set repeatReveal(repeat)
{this._repeatReveal=repeat;}
performSearch(query)
{if(this._searchQuery===query)
return;this.searchCleared();this._searchQuery=query;if(this._initialStringNotSet)
return;if(typeof this.customPerformSearch==="function"&&!this.formatted){if(this.customPerformSearch(query))
return;}
let queryRegex=WI.SearchUtilities.searchRegExpForString(query,WI.SearchUtilities.defaultSettings);if(!queryRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;}
var searchCursor=this._codeMirror.getSearchCursor(queryRegex,{line:0,ch:0},false);var boundBatchSearch=batchSearch.bind(this);var numberOfSearchResultsDidChangeTimeout=null;function reportNumberOfSearchResultsDidChange()
{if(numberOfSearchResultsDidChangeTimeout){clearTimeout(numberOfSearchResultsDidChangeTimeout);numberOfSearchResultsDidChangeTimeout=null;}
this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);}
function batchSearch()
{if(this._searchQuery!==query)
return;var newSearchResults=[];var foundResult=false;for(var i=0;i<WI.TextEditor.NumberOfFindsPerSearchBatch&&(foundResult=searchCursor.findNext());++i){var textRange=this._textRangeFromCodeMirrorPosition(searchCursor.from(),searchCursor.to());newSearchResults.push(textRange);}
this.addSearchResults(newSearchResults);if(!numberOfSearchResultsDidChangeTimeout)
numberOfSearchResultsDidChangeTimeout=setTimeout(reportNumberOfSearchResultsDidChange.bind(this),500);if(foundResult){setTimeout(boundBatchSearch,50);}else{reportNumberOfSearchResultsDidChange.call(this);}}
boundBatchSearch();}
setExecutionLineAndColumn(lineNumber,columnNumber)
{if(!this._executionLineHandle&&isNaN(lineNumber))
return;this._executionLineNumber=lineNumber;this._executionColumnNumber=columnNumber;if(!this._initialStringNotSet){this._updateExecutionLine();this._updateExecutionRangeHighlight();}

this.dispatchEventToListeners(WI.TextEditor.Event.ExecutionLineNumberDidChange);}
addSearchResults(textRanges)
{if(!textRanges||!textRanges.length)
return;function markRanges()
{for(var i=0;i<textRanges.length;++i){var position=this._codeMirrorPositionFromTextRange(textRanges[i]);var mark=this._codeMirror.markText(position.start,position.end,{className:WI.TextEditor.SearchResultStyleClassName});this._searchResults.push(mark);}
if(this._automaticallyRevealFirstSearchResult){if(this._currentSearchResultIndex===-1)
this._revealFirstSearchResultAfterCursor();}}
this._codeMirror.operation(markRanges.bind(this));}
searchCleared()
{this._codeMirror.operation(()=>{for(let searchResult of this._searchResults)
searchResult.clear();});this._searchQuery=null;this._searchResults=[];this._currentSearchResultIndex=-1;}
searchQueryWithSelection()
{if(!this._codeMirror.somethingSelected())
return null;return this._codeMirror.getSelection();}
revealPreviousSearchResult(changeFocus)
{if(!this._searchResults.length)
return;if(this._currentSearchResultIndex===-1||this._cursorDoesNotMatchLastRevealedSearchResult()){this._revealFirstSearchResultBeforeCursor(changeFocus);return;}
if(this._currentSearchResultIndex>0)
--this._currentSearchResultIndex;else
this._currentSearchResultIndex=this._searchResults.length-1;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,-1);}
revealNextSearchResult(changeFocus)
{if(!this._searchResults.length)
return;if(this._currentSearchResultIndex===-1||this._cursorDoesNotMatchLastRevealedSearchResult()){this._revealFirstSearchResultAfterCursor(changeFocus);return;}
if(this._currentSearchResultIndex+1<this._searchResults.length)
++this._currentSearchResultIndex;else
this._currentSearchResultIndex=0;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,1);}
line(lineNumber)
{return this._codeMirror.getLine(lineNumber);}
getTextInRange(startPosition,endPosition)
{return this._codeMirror.getRange(startPosition.toCodeMirror(),endPosition.toCodeMirror());}
addStyleToTextRange(startPosition,endPosition,styleClassName)
{endPosition=endPosition.offsetColumn(1);return this._codeMirror.getDoc().markText(startPosition.toCodeMirror(),endPosition.toCodeMirror(),{className:styleClassName,inclusiveLeft:true,inclusiveRight:true});}
revealPosition(position,textRangeToSelect,forceUnformatted,noHighlight)
{if(!(position instanceof WI.SourceCodePosition))
return;if(!this.isAttached||this._initialStringNotSet||this._deferReveal){this._positionToReveal=position;this._textRangeToSelect=textRangeToSelect;this._forceUnformatted=forceUnformatted;return;}
delete this._positionToReveal;delete this._textRangeToSelect;delete this._forceUnformatted;if(this._formatted&&forceUnformatted){this.updateFormattedState(false).then(()=>{setTimeout(this.revealPosition.bind(this),0,position,textRangeToSelect);});return;}
let line=Number.constrain(position.lineNumber,0,this._codeMirror.lineCount()-1);let lineHandle=this._codeMirror.getLineHandle(line);if(!textRangeToSelect){let column=Number.constrain(position.columnNumber,0,this._codeMirror.getLine(line).length);textRangeToSelect=new WI.TextRange(line,column,line,column);}
function removeStyleClass()
{this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName);}
function revealAndHighlightLine()
{var position=this._codeMirrorPositionFromTextRange(textRangeToSelect);if(!this._isPositionVisible(position.start))
this._scrollIntoViewCentered(position.start);this.selectedTextRange=textRangeToSelect;if(noHighlight)
return;if(WI.debuggerManager.paused&&line===this._executionLineNumber)
return;this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName);

setTimeout(removeStyleClass.bind(this),WI.TextEditor.HighlightAnimationDuration);}
this._codeMirror.operation(revealAndHighlightLine.bind(this));}
attached()
{super.attached();this._codeMirror.refresh();
this._revealPendingPositionIfPossible();}
setBreakpointInfoForLineAndColumn(lineNumber,columnNumber,breakpointInfo)
{if(this._ignoreSetBreakpointInfoCalls)
return;if(breakpointInfo)
this._addBreakpointToLineAndColumnWithInfo(lineNumber,columnNumber,breakpointInfo);else
this._removeBreakpointFromLineAndColumn(lineNumber,columnNumber);}
updateBreakpointLineAndColumn(oldLineNumber,oldColumnNumber,newLineNumber,newColumnNumber)
{if(!this._breakpoints[oldLineNumber])
return;if(!this._breakpoints[oldLineNumber][oldColumnNumber])
return;var breakpointInfo=this._breakpoints[oldLineNumber][oldColumnNumber];this._removeBreakpointFromLineAndColumn(oldLineNumber,oldColumnNumber);this._addBreakpointToLineAndColumnWithInfo(newLineNumber,newColumnNumber,breakpointInfo);}
addStyleClassToLine(lineNumber,styleClassName)
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return null;return this._codeMirror.addLineClass(lineHandle,"wrap",styleClassName);}
removeStyleClassFromLine(lineNumber,styleClassName)
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return null;return this._codeMirror.removeLineClass(lineHandle,"wrap",styleClassName);}
toggleStyleClassForLine(lineNumber,styleClassName)
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return false;return this._codeMirror.toggleLineClass(lineHandle,"wrap",styleClassName);}
createWidgetForLine(lineNumber)
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return null;var widgetElement=document.createElement("div");var lineWidget=this._codeMirror.addLineWidget(lineHandle,widgetElement,{coverGutter:false,noHScroll:true});return new WI.LineWidget(lineWidget,widgetElement);}
get lineCount()
{return this._codeMirror.lineCount();}
focus()
{this._codeMirror.focus();}
contentDidChange(replacedRanges,newRanges)
{}
rectsForRange(range)
{return this._codeMirror.rectsForRange(range);}
get markers()
{return this._codeMirror.getAllMarks().map(WI.TextMarker.textMarkerForCodeMirrorTextMarker);}
markersAtPosition(position)
{return this._codeMirror.findMarksAt(position).map(WI.TextMarker.textMarkerForCodeMirrorTextMarker);}
createColorMarkers(range)
{return createCodeMirrorColorTextMarkers(this._codeMirror,range);}
createGradientMarkers(range)
{return createCodeMirrorGradientTextMarkers(this._codeMirror,range);}
createCubicBezierMarkers(range)
{return createCodeMirrorCubicBezierTextMarkers(this._codeMirror,range);}
createSpringMarkers(range)
{return createCodeMirrorSpringTextMarkers(this._codeMirror,range);}
editingControllerForMarker(editableMarker)
{switch(editableMarker.type){case WI.TextMarker.Type.Color:return new WI.CodeMirrorColorEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.Gradient:return new WI.CodeMirrorGradientEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.CubicBezier:return new WI.CodeMirrorBezierEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.Spring:return new WI.CodeMirrorSpringEditingController(this._codeMirror,editableMarker);default:return new WI.CodeMirrorEditingController(this._codeMirror,editableMarker);}}
visibleRangeOffsets()
{var startOffset=null;var endOffset=null;var visibleRange=this._codeMirror.getViewport();if(this._formatterSourceMap){startOffset=this._formatterSourceMap.formattedToOriginalOffset(Math.max(visibleRange.from-1,0),0);endOffset=this._formatterSourceMap.formattedToOriginalOffset(visibleRange.to-1,0);}else{startOffset=this._codeMirror.getDoc().indexFromPos({line:visibleRange.from,ch:0});endOffset=this._codeMirror.getDoc().indexFromPos({line:visibleRange.to,ch:0});}
return{startOffset,endOffset};}
visibleRangePositions()
{let visibleRange=this._codeMirror.getViewport();let startLine;let endLine;if(this._formatterSourceMap){startLine=this._formatterSourceMap.formattedToOriginal(Math.max(visibleRange.from-1,0),0).lineNumber;endLine=this._formatterSourceMap.formattedToOriginal(visibleRange.to-1,0).lineNumber;}else{startLine=visibleRange.from;endLine=visibleRange.to;}
return{startPosition:new WI.SourceCodePosition(startLine,0),endPosition:new WI.SourceCodePosition(endLine,0)};}
originalPositionToCurrentPosition(position)
{if(!this._formatterSourceMap)
return position;let{lineNumber,columnNumber}=this._formatterSourceMap.originalToFormatted(position.lineNumber,position.columnNumber);return new WI.SourceCodePosition(lineNumber,columnNumber);}
originalOffsetToCurrentPosition(offset)
{var position=null;if(this._formatterSourceMap){var location=this._formatterSourceMap.originalPositionToFormatted(offset);position={line:location.lineNumber,ch:location.columnNumber};}else
position=this._codeMirror.getDoc().posFromIndex(offset);return position;}
currentOffsetToCurrentPosition(offset)
{let pos=this._codeMirror.getDoc().posFromIndex(offset);return new WI.SourceCodePosition(pos.line,pos.ch);}
currentPositionToOriginalOffset(position)
{let offset=null;if(this._formatterSourceMap)
offset=this._formatterSourceMap.formattedToOriginalOffset(position.line,position.ch);else
offset=this._codeMirror.getDoc().indexFromPos(position);return offset;}
currentPositionToOriginalPosition(position)
{if(!this._formatterSourceMap)
return position;let location=this._formatterSourceMap.formattedToOriginal(position.lineNumber,position.columnNumber);return new WI.SourceCodePosition(location.lineNumber,location.columnNumber);}
currentPositionToCurrentOffset(position)
{return this._codeMirror.getDoc().indexFromPos(position.toCodeMirror());}
setInlineWidget(position,inlineElement)
{return this._codeMirror.setUniqueBookmark(position.toCodeMirror(),{widget:inlineElement});}
addScrollHandler(handler)
{this._codeMirror.on("scroll",handler);}
removeScrollHandler(handler)
{this._codeMirror.off("scroll",handler);} 
layout()
{super.layout();this._codeMirror.refresh();}
_format(formatted)
{if(this._formatted===formatted)
return Promise.resolve(this._formatted);if(formatted&&!this.canBeFormatted())
return Promise.resolve(this._formatted);if(this._formattingPromise)
return this._formattingPromise;this._ignoreCodeMirrorContentDidChangeEvent++;this._formattingPromise=this.prettyPrint(formatted).then(()=>{this._ignoreCodeMirrorContentDidChangeEvent--;this._formattingPromise=null;let originalFormatted=this._formatted;this._formatted=!!this._formatterSourceMap;if(this._formatted!==originalFormatted)
this.dispatchEventToListeners(WI.TextEditor.Event.FormattingDidChange);return this._formatted;});return this._formattingPromise;}
prettyPrint(pretty)
{return new Promise((resolve,reject)=>{let beforePrettyPrintState={selectionAnchor:this._codeMirror.getCursor("anchor"),selectionHead:this._codeMirror.getCursor("head"),};if(!pretty)
this._undoFormatting(beforePrettyPrintState,resolve);else
this._startWorkerPrettyPrint(beforePrettyPrintState,resolve);});}
_attemptToDetermineMIMEType()
{let startTime=Date.now();const isModule=false;const includeSourceMapData=false;let workerProxy=WI.FormatterWorkerProxy.singleton();workerProxy.formatJavaScript(this.string,isModule,WI.indentString(),includeSourceMapData,({formattedText})=>{if(!formattedText)
return;this.mimeType="text/javascript";if(Date.now()-startTime<100)
this.updateFormattedState(true);});}
_startWorkerPrettyPrint(beforePrettyPrintState,callback)
{let workerProxy=WI.FormatterWorkerProxy.singleton();let sourceText=this._codeMirror.getValue();let indentString=WI.indentString();const includeSourceMapData=true;let formatCallback=({formattedText,sourceMapData})=>{if(formattedText===null){callback();return;}
this._finishPrettyPrint(beforePrettyPrintState,formattedText,sourceMapData,callback);};let mode=this._codeMirror.getMode().name;switch(mode){case"javascript":{let sourceType=this._delegate?this._delegate.textEditorScriptSourceType(this):WI.Script.SourceType.Program;const isModule=sourceType===WI.Script.SourceType.Module;workerProxy.formatJavaScript(sourceText,isModule,indentString,includeSourceMapData,formatCallback);break;}
case"css":workerProxy.formatCSS(sourceText,indentString,includeSourceMapData,formatCallback);break;case"htmlmixed":workerProxy.formatHTML(sourceText,indentString,includeSourceMapData,formatCallback);break;case"xml":workerProxy.formatXML(sourceText,indentString,includeSourceMapData,formatCallback);break;default:break;}}
_finishPrettyPrint(beforePrettyPrintState,formattedText,sourceMapData,callback)
{this._codeMirror.operation(()=>{this._formatterSourceMap=WI.FormatterSourceMap.fromSourceMapData(sourceMapData);this._codeMirror.setValue(formattedText);this._updateAfterFormatting(true,beforePrettyPrintState);});callback();}
_undoFormatting(beforePrettyPrintState,callback)
{this._codeMirror.operation(()=>{this._codeMirror.undo();this._updateAfterFormatting(false,beforePrettyPrintState);});callback();}
_updateAfterFormatting(pretty,beforePrettyPrintState)
{let oldSelectionAnchor=beforePrettyPrintState.selectionAnchor;let oldSelectionHead=beforePrettyPrintState.selectionHead;let newSelectionAnchor,newSelectionHead;let newExecutionLocation=null;if(pretty){if(this._positionToReveal){let newRevealPosition=this._formatterSourceMap.originalToFormatted(this._positionToReveal.lineNumber,this._positionToReveal.columnNumber);this._positionToReveal=new WI.SourceCodePosition(newRevealPosition.lineNumber,newRevealPosition.columnNumber);}
if(this._textRangeToSelect){let mappedRevealSelectionStart=this._formatterSourceMap.originalToFormatted(this._textRangeToSelect.startLine,this._textRangeToSelect.startColumn);let mappedRevealSelectionEnd=this._formatterSourceMap.originalToFormatted(this._textRangeToSelect.endLine,this._textRangeToSelect.endColumn);this._textRangeToSelect=new WI.TextRange(mappedRevealSelectionStart.lineNumber,mappedRevealSelectionStart.columnNumber,mappedRevealSelectionEnd.lineNumber,mappedRevealSelectionEnd.columnNumber);}
if(!isNaN(this._executionLineNumber)){newExecutionLocation=this._formatterSourceMap.originalToFormatted(this._executionLineNumber,this._executionColumnNumber);}
let mappedAnchorLocation=this._formatterSourceMap.originalToFormatted(oldSelectionAnchor.line,oldSelectionAnchor.ch);let mappedHeadLocation=this._formatterSourceMap.originalToFormatted(oldSelectionHead.line,oldSelectionHead.ch);newSelectionAnchor={line:mappedAnchorLocation.lineNumber,ch:mappedAnchorLocation.columnNumber};newSelectionHead={line:mappedHeadLocation.lineNumber,ch:mappedHeadLocation.columnNumber};}else{if(this._positionToReveal){let newRevealPosition=this._formatterSourceMap.formattedToOriginal(this._positionToReveal.lineNumber,this._positionToReveal.columnNumber);this._positionToReveal=new WI.SourceCodePosition(newRevealPosition.lineNumber,newRevealPosition.columnNumber);}
if(this._textRangeToSelect){let mappedRevealSelectionStart=this._formatterSourceMap.formattedToOriginal(this._textRangeToSelect.startLine,this._textRangeToSelect.startColumn);let mappedRevealSelectionEnd=this._formatterSourceMap.formattedToOriginal(this._textRangeToSelect.endLine,this._textRangeToSelect.endColumn);this._textRangeToSelect=new WI.TextRange(mappedRevealSelectionStart.lineNumber,mappedRevealSelectionStart.columnNumber,mappedRevealSelectionEnd.lineNumber,mappedRevealSelectionEnd.columnNumber);}
if(!isNaN(this._executionLineNumber)){newExecutionLocation=this._formatterSourceMap.formattedToOriginal(this._executionLineNumber,this._executionColumnNumber);}
let mappedAnchorLocation=this._formatterSourceMap.formattedToOriginal(oldSelectionAnchor.line,oldSelectionAnchor.ch);let mappedHeadLocation=this._formatterSourceMap.formattedToOriginal(oldSelectionHead.line,oldSelectionHead.ch);newSelectionAnchor={line:mappedAnchorLocation.lineNumber,ch:mappedAnchorLocation.columnNumber};newSelectionHead={line:mappedHeadLocation.lineNumber,ch:mappedHeadLocation.columnNumber};this._formatterSourceMap=null;}
this._scrollIntoViewCentered(newSelectionAnchor);this._codeMirror.setSelection(newSelectionAnchor,newSelectionHead);if(newExecutionLocation){this._executionLineHandle=null;this._executionMultilineHandles=[];this.setExecutionLineAndColumn(newExecutionLocation.lineNumber,newExecutionLocation.columnNumber);}
if(this.currentSearchQuery){let searchQuery=this.currentSearchQuery;this.searchCleared();setTimeout(()=>{this.performSearch(searchQuery);},0);}
if(this._delegate&&typeof this._delegate.textEditorUpdatedFormatting==="function")
this._delegate.textEditorUpdatedFormatting(this);} 
hasEdits()
{return!this._codeMirror.isClean();}
_editorFocused(codeMirror)
{this.dispatchEventToListeners(WI.TextEditor.Event.Focused);}
_contentChanged(codeMirror,change)
{if(this._ignoreCodeMirrorContentDidChangeEvent>0)
return;var replacedRanges=[];var newRanges=[];while(change){replacedRanges.push(new WI.TextRange(change.from.line,change.from.ch,change.to.line,change.to.ch));newRanges.push(new WI.TextRange(change.from.line,change.from.ch,change.from.line+change.text.length-1,change.text.length===1?change.from.ch+change.text[0].length:change.text.lastValue.length));change=change.next;}
this.contentDidChange(replacedRanges,newRanges);if(this._formatted){this._formatterSourceMap=null;this._formatted=false;if(this._delegate&&typeof this._delegate.textEditorUpdatedFormatting==="function")
this._delegate.textEditorUpdatedFormatting(this);this.dispatchEventToListeners(WI.TextEditor.Event.FormattingDidChange);}
this.dispatchEventToListeners(WI.TextEditor.Event.ContentDidChange);}
_textRangeFromCodeMirrorPosition(start,end)
{return new WI.TextRange(start.line,start.ch,end.line,end.ch);}
_codeMirrorPositionFromTextRange(textRange)
{var start={line:textRange.startLine,ch:textRange.startColumn};var end={line:textRange.endLine,ch:textRange.endColumn};return{start,end};}
_revealPendingPositionIfPossible()
{if(!this._positionToReveal)
return;if(!this.isAttached)
return;this.revealPosition(this._positionToReveal,this._textRangeToSelect,this._forceUnformatted);}
_revealSearchResult(result,changeFocus,directionInCaseOfRevalidation)
{let position=result.find();if(!position){this._revalidateSearchResults(directionInCaseOfRevalidation);return;}
if(!this._isPositionVisible(position.from))
this._scrollIntoViewCentered(position.from);this.selectedTextRange=this._textRangeFromCodeMirrorPosition(position.from,position.to);this._automaticallyRevealFirstSearchResult=false;if(changeFocus)
this._codeMirror.focus();let highlightEditorPosition=this._codeMirror.getCursor("start");let textContent=this._codeMirror.getSelection();
this._removeBouncyHighlightElementIfNeeded();this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className=WI.TextEditor.BouncyHighlightStyleClassName;this._bouncyHighlightElement.textContent=textContent;function positionBouncyHighlight(){let coordinates=this._codeMirror.cursorCoords(highlightEditorPosition,"page");let textEditorRect=this.element.getBoundingClientRect();coordinates.top-=textEditorRect.top;coordinates.left-=textEditorRect.left;this._bouncyHighlightElement.style.top=coordinates.top+"px";this._bouncyHighlightElement.style.left=coordinates.left+"px";}
positionBouncyHighlight.call(this);this.element.appendChild(this._bouncyHighlightElement);this._bouncyHighlightScrollHandler=()=>{positionBouncyHighlight.call(this);};this.addScrollHandler(this._bouncyHighlightScrollHandler);this._bouncyHighlightElement.addEventListener("animationend",()=>{this._removeBouncyHighlightElementIfNeeded();});}
_removeBouncyHighlightElementIfNeeded()
{if(!this._bouncyHighlightElement)
return;this.removeScrollHandler(this._bouncyHighlightScrollHandler);this._bouncyHighlightScrollHandler=null;this._bouncyHighlightElement.remove();this._bouncyHighlightElement=null;}
_binarySearchInsertionIndexInSearchResults(object,comparator)
{
var array=this._searchResults;var first=0;var last=array.length-1;while(first<=last){var mid=(first+last)>>1;var c=comparator(object,array[mid]);if(c===null)
return null;if(c>0)
first=mid+1;else if(c<0)
last=mid-1;else
return mid;}
return first-1;}
_revealFirstSearchResultBeforeCursor(changeFocus)
{var currentCursorPosition=this._codeMirror.getCursor("start");if(currentCursorPosition.line===0&&currentCursorPosition.ch===0){this._currentSearchResultIndex=this._searchResults.length-1;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,-1);return;}
var index=this._binarySearchInsertionIndexInSearchResults(currentCursorPosition,function(current,searchResult){var searchResultMarker=searchResult.find();if(!searchResultMarker)
return null;return WI.compareCodeMirrorPositions(current,searchResultMarker.from);});if(index===null){this._revalidateSearchResults(-1);return;}
this._currentSearchResultIndex=index;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus);}
_revealFirstSearchResultAfterCursor(changeFocus)
{var currentCursorPosition=this._codeMirror.getCursor("start");if(currentCursorPosition.line===0&&currentCursorPosition.ch===0){this._currentSearchResultIndex=0;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,1);return;}
var index=this._binarySearchInsertionIndexInSearchResults(currentCursorPosition,function(current,searchResult){var searchResultMarker=searchResult.find();if(!searchResultMarker)
return null;return WI.compareCodeMirrorPositions(current,searchResultMarker.from);});if(index===null){this._revalidateSearchResults(1);return;}
if(index+1<this._searchResults.length)
++index;else
index=0;this._currentSearchResultIndex=index;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus);}
_cursorDoesNotMatchLastRevealedSearchResult()
{var lastRevealedSearchResultMarker=this._searchResults[this._currentSearchResultIndex].find();if(!lastRevealedSearchResultMarker)
return true;var currentCursorPosition=this._codeMirror.getCursor("start");var lastRevealedSearchResultPosition=lastRevealedSearchResultMarker.from;return WI.compareCodeMirrorPositions(currentCursorPosition,lastRevealedSearchResultPosition)!==0;}
_revalidateSearchResults(direction)
{this._currentSearchResultIndex=-1;var updatedSearchResults=[];for(var i=0;i<this._searchResults.length;++i){if(this._searchResults[i].find())
updatedSearchResults.push(this._searchResults[i]);}
this._searchResults=updatedSearchResults;this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);if(this._searchResults.length){if(direction>0)
this._revealFirstSearchResultAfterCursor();else
this._revealFirstSearchResultBeforeCursor();}}
_clearMultilineExecutionLineHighlights()
{if(this._executionMultilineHandles.length){for(let lineHandle of this._executionMultilineHandles)
this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._executionMultilineHandles=[];}}
_updateExecutionLine()
{this._codeMirror.operation(()=>{if(this._executionLineHandle){this._codeMirror.removeLineClass(this._executionLineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._codeMirror.removeLineClass(this._executionLineHandle,"wrap","primary");}
this._clearMultilineExecutionLineHighlights();this._executionLineHandle=!isNaN(this._executionLineNumber)?this._codeMirror.getLineHandle(this._executionLineNumber):null;if(this._executionLineHandle){this._codeMirror.addLineClass(this._executionLineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._codeMirror.addLineClass(this._executionLineHandle,"wrap","primary");this._codeMirror.removeLineClass(this._executionLineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName);}});}
_updateExecutionRangeHighlight()
{if(this._executionRangeHighlightMarker){this._executionRangeHighlightMarker.clear();this._executionRangeHighlightMarker=null;}
if(isNaN(this._executionLineNumber))
return;let currentPosition=new WI.SourceCodePosition(this._executionLineNumber,this._executionColumnNumber);this._delegate.textEditorExecutionHighlightRange(currentPosition,(range)=>{let start,end;if(!range){start={line:this._executionLineNumber,ch:this._executionColumnNumber};end={line:this._executionLineNumber};}else{start=range.startPosition.toCodeMirror();end=range.endPosition.toCodeMirror();}
if(this._executionRangeHighlightMarker){this._executionRangeHighlightMarker.clear();this._executionRangeHighlightMarker=null;}
let text=this._codeMirror.getRange(start,end);let trailingWhitespace=text.match(/\s+$/);if(trailingWhitespace)
end.ch=Math.max(0,end.ch-trailingWhitespace[0].length);this._clearMultilineExecutionLineHighlights();if(start.line!==end.line){for(let line=start.line;line<end.line;++line){let lineHandle=this._codeMirror.getLineHandle(line);this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._executionMultilineHandles.push(lineHandle);}}
this._executionRangeHighlightMarker=this._codeMirror.markText(start,end,{className:"execution-range-highlight"});});}
_setBreakpointStylesOnLine(lineNumber)
{var columnBreakpoints=this._breakpoints[lineNumber];if(!columnBreakpoints)
return;var allDisabled=true;var allResolved=true;var allAutoContinue=true;var multiple=Object.keys(columnBreakpoints).length>1;for(var columnNumber in columnBreakpoints){var breakpointInfo=columnBreakpoints[columnNumber];if(!breakpointInfo.disabled)
allDisabled=false;if(!breakpointInfo.resolved)
allResolved=false;if(!breakpointInfo.autoContinue)
allAutoContinue=false;}
allResolved=allResolved&&WI.debuggerManager.breakpointsEnabled;function updateStyles()
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return;this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.HasBreakpointStyleClassName);if(allResolved)
this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);else
this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);if(allDisabled)
this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);else
this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);if(allAutoContinue)
this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);else
this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);if(multiple)
this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);else
this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);}
this._codeMirror.operation(updateStyles.bind(this));}
_addBreakpointToLineAndColumnWithInfo(lineNumber,columnNumber,breakpointInfo)
{if(!this._breakpoints[lineNumber])
this._breakpoints[lineNumber]={};this._breakpoints[lineNumber][columnNumber]=breakpointInfo;this._setBreakpointStylesOnLine(lineNumber);}
_removeBreakpointFromLineAndColumn(lineNumber,columnNumber)
{delete this._breakpoints[lineNumber][columnNumber];if(!isEmptyObject(this._breakpoints[lineNumber])){this._setBreakpointStylesOnLine(lineNumber);return;}
delete this._breakpoints[lineNumber];function updateStyles()
{var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle)
return;this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.HasBreakpointStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);}
this._codeMirror.operation(updateStyles.bind(this));}
_allColumnBreakpointInfoForLine(lineNumber)
{return this._breakpoints[lineNumber];}
_setColumnBreakpointInfoForLine(lineNumber,columnBreakpointInfo)
{this._breakpoints[lineNumber]=columnBreakpointInfo;this._setBreakpointStylesOnLine(lineNumber);}
_gutterMouseDown(codeMirror,lineNumber,gutterElement,event)
{if(event.button!==0||event.ctrlKey)
return;if(!this._codeMirror.hasLineClass(lineNumber,"wrap",WI.TextEditor.HasBreakpointStyleClassName)){if(this._delegate&&typeof this._delegate.textEditorBreakpointAdded==="function"){var data=this._delegate.textEditorBreakpointAdded(this,lineNumber,0);if(data){var breakpointInfo=data.breakpointInfo;if(breakpointInfo)
this._addBreakpointToLineAndColumnWithInfo(data.lineNumber,data.columnNumber,breakpointInfo);}}
return;}
if(this._codeMirror.hasLineClass(lineNumber,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName)){return;}
var columnNumber=Object.keys(this._breakpoints[lineNumber])[0];this._draggingBreakpointInfo=this._breakpoints[lineNumber][columnNumber];this._lineNumberWithMousedDownBreakpoint=lineNumber;this._lineNumberWithDraggedBreakpoint=lineNumber;this._columnNumberWithMousedDownBreakpoint=columnNumber;this._columnNumberWithDraggedBreakpoint=columnNumber;this._documentMouseMovedEventListener=this._documentMouseMoved.bind(this);this._documentMouseUpEventListener=this._documentMouseUp.bind(this);document.addEventListener("mousemove",this._documentMouseMovedEventListener,true);document.addEventListener("mouseup",this._documentMouseUpEventListener,true);}
_gutterContextMenu(codeMirror,lineNumber,gutterElement,event)
{if(this._delegate&&typeof this._delegate.textEditorGutterContextMenu==="function"){var breakpoints=[];for(var columnNumber in this._breakpoints[lineNumber])
breakpoints.push({lineNumber,columnNumber});this._delegate.textEditorGutterContextMenu(this,lineNumber,0,breakpoints,event);}}
_documentMouseMoved(event)
{if(!("_lineNumberWithMousedDownBreakpoint"in this))
return;event.preventDefault();var lineNumber;var position=this._codeMirror.coordsChar({left:event.pageX,top:event.pageY});
var gutterBounds=this._codeMirror.getGutterElement().getBoundingClientRect();if(event.pageX<gutterBounds.left||event.pageX>gutterBounds.right||event.pageY<gutterBounds.top||event.pageY>gutterBounds.bottom)
position=null;if(position&&"line"in position)
lineNumber=position.line;
if(lineNumber===this._lineNumberWithDraggedBreakpoint)
return;
this._mouseDragged=true;if("_lineNumberWithDraggedBreakpoint"in this){
if(this._previousColumnBreakpointInfo)
this._setColumnBreakpointInfoForLine(this._lineNumberWithDraggedBreakpoint,this._previousColumnBreakpointInfo);else
this._removeBreakpointFromLineAndColumn(this._lineNumberWithDraggedBreakpoint,this._columnNumberWithDraggedBreakpoint);delete this._previousColumnBreakpointInfo;delete this._lineNumberWithDraggedBreakpoint;delete this._columnNumberWithDraggedBreakpoint;}
if(lineNumber!==undefined){var newColumnBreakpoints={};var columnNumber=lineNumber===this._lineNumberWithMousedDownBreakpoint?this._columnNumberWithDraggedBreakpoint:0;newColumnBreakpoints[columnNumber]=this._draggingBreakpointInfo;this._previousColumnBreakpointInfo=this._allColumnBreakpointInfoForLine(lineNumber);this._setColumnBreakpointInfoForLine(lineNumber,newColumnBreakpoints);this._lineNumberWithDraggedBreakpoint=lineNumber;this._columnNumberWithDraggedBreakpoint=columnNumber;}}
_documentMouseUp(event)
{if(!("_lineNumberWithMousedDownBreakpoint"in this))
return;event.preventDefault();document.removeEventListener("mousemove",this._documentMouseMovedEventListener,true);document.removeEventListener("mouseup",this._documentMouseUpEventListener,true);var delegateImplementsBreakpointClicked=this._delegate&&typeof this._delegate.textEditorBreakpointClicked==="function";var delegateImplementsBreakpointRemoved=this._delegate&&typeof this._delegate.textEditorBreakpointRemoved==="function";var delegateImplementsBreakpointMoved=this._delegate&&typeof this._delegate.textEditorBreakpointMoved==="function";if(this._mouseDragged){if(!("_lineNumberWithDraggedBreakpoint"in this)){if(delegateImplementsBreakpointRemoved){this._ignoreSetBreakpointInfoCalls=true;this._delegate.textEditorBreakpointRemoved(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint);delete this._ignoreSetBreakpointInfoCalls;}}else if(this._lineNumberWithMousedDownBreakpoint!==this._lineNumberWithDraggedBreakpoint){
if(this._previousColumnBreakpointInfo&&delegateImplementsBreakpointRemoved){this._ignoreSetBreakpointInfoCalls=true;for(var columnNumber in this._previousColumnBreakpointInfo)
this._delegate.textEditorBreakpointRemoved(this,this._lineNumberWithDraggedBreakpoint,columnNumber);delete this._ignoreSetBreakpointInfoCalls;}
if(delegateImplementsBreakpointMoved){this._ignoreSetBreakpointInfoCalls=true;this._delegate.textEditorBreakpointMoved(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint,this._lineNumberWithDraggedBreakpoint,this._columnNumberWithDraggedBreakpoint);delete this._ignoreSetBreakpointInfoCalls;}}}else{if(this._lineNumberWithMousedDownBreakpoint in this._breakpoints&&this._columnNumberWithMousedDownBreakpoint in this._breakpoints[this._lineNumberWithMousedDownBreakpoint]&&delegateImplementsBreakpointClicked)
this._delegate.textEditorBreakpointClicked(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint);}
delete this._documentMouseMovedEventListener;delete this._documentMouseUpEventListener;delete this._lineNumberWithMousedDownBreakpoint;delete this._lineNumberWithDraggedBreakpoint;delete this._columnNumberWithMousedDownBreakpoint;delete this._columnNumberWithDraggedBreakpoint;delete this._previousColumnBreakpointInfo;delete this._mouseDragged;}
_openClickedLinks(event)
{if(!this.readOnly&&!event.commandOrControlKey)
return;var position=this._codeMirror.coordsChar({left:event.pageX,top:event.pageY});var tokenInfo=this._codeMirror.getTokenAt(position);if(!tokenInfo||!tokenInfo.type||!tokenInfo.string)
return;if(!/\blink\b/.test(tokenInfo.type))
return;var url=tokenInfo.string;var baseURL="";if(this._delegate&&typeof this._delegate.textEditorBaseURL==="function")
baseURL=this._delegate.textEditorBaseURL(this);WI.openURL(absoluteURL(url,baseURL));event.preventDefault();event.stopPropagation();}
_isPositionVisible(position)
{var scrollInfo=this._codeMirror.getScrollInfo();var visibleRangeStart=scrollInfo.top;var visibleRangeEnd=visibleRangeStart+scrollInfo.clientHeight;var coords=this._codeMirror.charCoords(position,"local");return coords.top>=visibleRangeStart&&coords.bottom<=visibleRangeEnd;}
_scrollIntoViewCentered(position)
{var scrollInfo=this._codeMirror.getScrollInfo();var lineHeight=Math.ceil(this._codeMirror.defaultTextHeight());var margin=Math.floor((scrollInfo.clientHeight-lineHeight)/2);this._codeMirror.scrollIntoView(position,margin);}};WI.TextEditor.HighlightedStyleClassName="highlighted";WI.TextEditor.SearchResultStyleClassName="search-result";WI.TextEditor.HasBreakpointStyleClassName="has-breakpoint";WI.TextEditor.BreakpointResolvedStyleClassName="breakpoint-resolved";WI.TextEditor.BreakpointAutoContinueStyleClassName="breakpoint-auto-continue";WI.TextEditor.BreakpointDisabledStyleClassName="breakpoint-disabled";WI.TextEditor.MultipleBreakpointsStyleClassName="multiple-breakpoints";WI.TextEditor.ExecutionLineStyleClassName="execution-line";WI.TextEditor.BouncyHighlightStyleClassName="bouncy-highlight";WI.TextEditor.NumberOfFindsPerSearchBatch=10;WI.TextEditor.HighlightAnimationDuration=2000;WI.TextEditor.Event={Focused:"text-editor-focused",ExecutionLineNumberDidChange:"text-editor-execution-line-number-did-change",NumberOfSearchResultsDidChange:"text-editor-number-of-search-results-did-change",ContentDidChange:"text-editor-content-did-change",FormattingDidChange:"text-editor-formatting-did-change",MIMETypeChanged:"text-editor-mime-type-changed",};WI.TimelineOverviewGraph=class TimelineOverviewGraph extends WI.View
{constructor(timelineOverview)
{super();this.element.classList.add("timeline-overview-graph");this._zeroTime=0;this._startTime=0;this._endTime=5;this._currentTime=0;this._timelineOverview=timelineOverview;this._selectedRecord=null;this._selectedRecordBar=null;this._scheduledSelectedRecordLayoutUpdateIdentifier=undefined;this._selected=false;this._hidden=false;} 
static createForTimeline(timeline,timelineOverview)
{var timelineType=timeline.type;if(timelineType===WI.TimelineRecord.Type.Network)
return new WI.NetworkTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Layout)
return new WI.LayoutTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Script)
return new WI.ScriptTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.RenderingFrame)
return new WI.RenderingFrameTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.CPU)
return new WI.CPUTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Memory)
return new WI.MemoryTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.HeapAllocations)
return new WI.HeapAllocationsTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Media)
return new WI.MediaTimelineOverviewGraph(timeline,timelineOverview);throw new Error("Can't make a graph for an unknown timeline.");}
get zeroTime()
{return this._zeroTime;}
set zeroTime(x)
{x=x||0;if(this._zeroTime===x)
return;this._zeroTime=x;this.needsLayout();}
get startTime()
{return this._startTime;}
set startTime(x)
{x=x||0;if(this._startTime===x)
return;this._startTime=x;this.needsLayout();}
get endTime()
{return this._endTime;}
set endTime(x)
{x=x||0;if(this._endTime===x)
return;this._endTime=x;this.needsLayout();}
get currentTime()
{return this._currentTime;}
set currentTime(x)
{x=x||0;if(this._currentTime===x)
return;let oldCurrentTime=this._currentTime;this._currentTime=x;if((this._startTime<=oldCurrentTime&&oldCurrentTime<=this._endTime)||(this._startTime<=this._currentTime&&this._currentTime<=this._endTime))
this.needsLayout();}
get timelineOverview()
{return this._timelineOverview;}
get secondsPerPixel(){return this._timelineOverview.secondsPerPixel;}
get hidden()
{return this._hidden;}
set hidden(hidden)
{if(!xor(hidden,this._hidden))
return;this._hidden=hidden;this.element.classList.toggle("hidden",this._hidden);if(!this._hidden)
this.updateLayout();}
get selectedRecord()
{return this._selectedRecord;}
set selectedRecord(x)
{if(this._selectedRecord===x)
return;this._selectedRecord=x;this._needsSelectedRecordLayout();}
get selectedRecordBar()
{return this._selectedRecordBar;}
set selectedRecordBar(recordBar)
{if(this._selectedRecordBar===recordBar)
return;if(this._selectedRecordBar)
this._selectedRecordBar.selected=false;this._selectedRecordBar=recordBar;if(this._selectedRecordBar){this._selectedRecordBar.selected=true;}}
get height()
{return 36;}
get selected()
{return this._selected;}
set selected(x)
{if(this._selected===x)
return;this._selected=x;this.element.classList.toggle("selected",this._selected);}
reset()
{}
recordWasFiltered(record,filtered)
{}
needsLayout()
{if(this._hidden)
return;super.needsLayout();}
didLayoutSubtree()
{super.didLayoutSubtree();this.updateSelectedRecord();} 
timelineRecordBarClicked(timelineRecordBar)
{this.selectedRecord=timelineRecordBar.records[0];} 
updateSelectedRecord()
{} 
_needsSelectedRecordLayout()
{if(this.layoutPending)
return;if(this._scheduledSelectedRecordLayoutUpdateIdentifier)
return;this._scheduledSelectedRecordLayoutUpdateIdentifier=requestAnimationFrame(()=>{this._scheduledSelectedRecordLayoutUpdateIdentifier=undefined;this.updateSelectedRecord();this.dispatchEventToListeners(WI.TimelineOverviewGraph.Event.RecordSelected,{record:this.selectedRecord,recordBar:this.selectedRecordBar});});}};WI.TimelineOverviewGraph.Event={RecordSelected:"timeline-overview-graph-record-selected"};WI.TimelineView=class TimelineView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("timeline-view");this._zeroTime=0;this._startTime=0;this._endTime=5;this._currentTime=0;} 
get scrollableElements()
{if(!this._timelineDataGrid)
return[];return[this._timelineDataGrid.scrollContainer];}
get showsLiveRecordingData()
{return true;}
get showsImportedRecordingMessage()
{return false;}
get showsFilterBar()
{return true;}
get navigationItems()
{return this._scopeBar?[this._scopeBar]:[];}
get selectionPathComponents()
{return null;}
get zeroTime()
{return this._zeroTime;}
set zeroTime(x)
{x=x||0;if(this._zeroTime===x)
return;this._zeroTime=x;this._timesDidChange();}
get startTime()
{return this._startTime;}
set startTime(x)
{x=x||0;if(this._startTime===x)
return;this._startTime=x;this._timesDidChange();this._scheduleFilterDidChange();}
get endTime()
{return this._endTime;}
set endTime(x)
{x=x||0;if(this._endTime===x)
return;this._endTime=x;this._timesDidChange();this._scheduleFilterDidChange();}
get currentTime()
{return this._currentTime;}
set currentTime(x)
{x=x||0;if(this._currentTime===x)
return;let oldCurrentTime=this._currentTime;this._currentTime=x;function checkIfLayoutIsNeeded(currentTime)
{const wiggleTime=0.05; return this._startTime-wiggleTime<=currentTime&&currentTime<=this._endTime+wiggleTime;}
if(checkIfLayoutIsNeeded.call(this,oldCurrentTime)||checkIfLayoutIsNeeded.call(this,this._currentTime))
this._timesDidChange();}
get filterStartTime()
{return this.startTime;}
get filterEndTime()
{return this.endTime;}
setupDataGrid(dataGrid)
{if(this._timelineDataGrid){this._timelineDataGrid.filterDelegate=null;this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._timelineDataGridSelectedNodeChanged,this);this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.NodeWasFiltered,this._timelineDataGridNodeWasFiltered,this);this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.FilterDidChange,this.filterDidChange,this);}
this._timelineDataGrid=dataGrid;this._timelineDataGrid.filterDelegate=this;this._timelineDataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._timelineDataGridSelectedNodeChanged,this);this._timelineDataGrid.addEventListener(WI.DataGrid.Event.NodeWasFiltered,this._timelineDataGridNodeWasFiltered,this);this._timelineDataGrid.addEventListener(WI.DataGrid.Event.FilterDidChange,this.filterDidChange,this);}
selectRecord(record)
{if(!this._timelineDataGrid)
return;let selectedDataGridNode=this._timelineDataGrid.selectedNode;if(!record){if(selectedDataGridNode)
selectedDataGridNode.deselect();return;}
let dataGridNode=this._timelineDataGrid.findNode((node)=>node.record===record);if(!dataGridNode||dataGridNode.selected)
return;if(selectedDataGridNode&&selectedDataGridNode.hasAncestor(dataGridNode))
return;dataGridNode.revealAndSelect();}
reset()
{}
updateFilter(filters)
{if(!this._timelineDataGrid)
return;this._timelineDataGrid.filterText=filters?filters.text:"";}
matchDataGridNodeAgainstCustomFilters(node)
{return true;} 
dataGridMatchNodeAgainstCustomFilters(node)
{if(!this.matchDataGridNodeAgainstCustomFilters(node))
return false;let startTime=this.filterStartTime;let endTime=this.filterEndTime;let currentTime=this.currentTime;function checkTimeBounds(itemStartTime,itemEndTime)
{itemStartTime=itemStartTime||currentTime;itemEndTime=itemEndTime||currentTime;return startTime<=itemEndTime&&itemStartTime<=endTime;}
if(node instanceof WI.ResourceTimelineDataGridNode){let resource=node.resource;return checkTimeBounds(resource.requestSentTimestamp,resource.finishedOrFailedTimestamp);}
if(node instanceof WI.SourceCodeTimelineTimelineDataGridNode){let sourceCodeTimeline=node.sourceCodeTimeline;if(!checkTimeBounds(sourceCodeTimeline.startTime,sourceCodeTimeline.endTime))
return false;for(let record of sourceCodeTimeline.records){if(checkTimeBounds(record.startTime,record.endTime))
return true;}
return false;}
if(node instanceof WI.ProfileNodeDataGridNode){let profileNode=node.profileNode;if(checkTimeBounds(profileNode.startTime,profileNode.endTime))
return true;return false;}
if(node instanceof WI.TimelineDataGridNode){let record=node.record;return checkTimeBounds(record.startTime,record.endTime);}
if(node instanceof WI.ProfileDataGridNode)
return node.callingContextTreeNode.hasStackTraceInTimeRange(startTime,endTime);console.error("Unknown DataGridNode, can't filter by time.");return true;} 
filterDidChange()
{} 
_timelineDataGridSelectedNodeChanged(event)
{this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_timelineDataGridNodeWasFiltered(event)
{let node=event.data.node;if(!(node instanceof WI.TimelineDataGridNode))
return;this.dispatchEventToListeners(WI.TimelineView.Event.RecordWasFiltered,{record:node.record,filtered:node.hidden});}
_timesDidChange()
{if(!WI.timelineManager.isCapturing()||this.showsLiveRecordingData)
this.needsLayout();}
_scheduleFilterDidChange()
{if(!this._timelineDataGrid||this._updateFilterTimeout)
return;this._updateFilterTimeout=setTimeout(()=>{this._updateFilterTimeout=undefined;this._timelineDataGrid.filterDidChange();},0);}};WI.TimelineView.Event={RecordWasFiltered:"timeline-view-record-was-filtered",RecordWasSelected:"timeline-view-record-was-selected",ScannerShow:"timeline-view-scanner-show",ScannerHide:"timeline-view-scanner-hide",NeedsEntireSelectedRange:"timeline-view-needs-entire-selected-range",NeedsFiltersCleared:"timeline-view-needs-filters-cleared",};WI.TreeElement=class TreeElement extends WI.Object
{constructor(title,representedObject,options={})
{super();this._title=title;this.representedObject=representedObject||{};if(this.representedObject.__treeElementIdentifier)
this.identifier=this.representedObject.__treeElementIdentifier;else{this.identifier=WI.TreeOutline._knownTreeElementNextIdentifier++;this.representedObject.__treeElementIdentifier=this.identifier;}
this._hidden=false;this._selectable=true;this.expanded=false;this.selected=false;this.hasChildren=options.hasChildren;this.children=[];this.treeOutline=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this._listItemNode=null;} 
appendChild(){return WI.TreeOutline.prototype.appendChild.apply(this,arguments);}
insertChild(){return WI.TreeOutline.prototype.insertChild.apply(this,arguments);}
removeChild(){return WI.TreeOutline.prototype.removeChild.apply(this,arguments);}
removeChildAtIndex(){return WI.TreeOutline.prototype.removeChildAtIndex.apply(this,arguments);}
removeChildren(){return WI.TreeOutline.prototype.removeChildren.apply(this,arguments);}
selfOrDescendant(){return WI.TreeOutline.prototype.selfOrDescendant.apply(this,arguments);}
get arrowToggleWidth()
{return 10;}
get selectable()
{if(this._hidden)
return false;return this._selectable;}
set selectable(x)
{this._selectable=x;}
get listItemElement()
{return this._listItemNode;}
get title()
{return this._title;}
set title(x)
{this._title=x;this._setListItemNodeContent();this.didChange();}
get titleHTML()
{return this._titleHTML;}
set titleHTML(x)
{this._titleHTML=x;this._setListItemNodeContent();this.didChange();}
get tooltip()
{return this._tooltip;}
set tooltip(x)
{this._tooltip=x;if(this._listItemNode)
this._listItemNode.title=x?x:"";}
get hasChildren()
{return this._hasChildren;}
set hasChildren(x)
{if(this._hasChildren===x)
return;this._hasChildren=x;if(!this._listItemNode)
return;if(x)
this._listItemNode.classList.add("parent");else{this._listItemNode.classList.remove("parent");this.collapse();}
this.didChange();}
get hidden()
{return this._hidden;}
set hidden(x)
{if(this._hidden===x)
return;this._hidden=x;if(this._listItemNode)
this._listItemNode.hidden=this._hidden;if(this._childrenListNode)
this._childrenListNode.hidden=this._hidden;if(this.treeOutline){if(this.treeOutline.virtualized)
this.treeOutline.updateVirtualizedElementsDebouncer.delayForFrame();this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementVisibilityDidChange,{element:this});}}
get shouldRefreshChildren()
{return this._shouldRefreshChildren;}
set shouldRefreshChildren(x)
{this._shouldRefreshChildren=x;if(x&&this.expanded)
this.expand();}
get previousSelectableSibling()
{let treeElement=this.previousSibling;while(treeElement&&!treeElement.selectable)
treeElement=treeElement.previousSibling;return treeElement;}
get nextSelectableSibling()
{let treeElement=this.nextSibling;while(treeElement&&!treeElement.selectable)
treeElement=treeElement.nextSibling;return treeElement;}
canSelectOnMouseDown(event)
{return true;}
_fireDidChange()
{if(this.treeOutline)
this.treeOutline._treeElementDidChange(this);}
didChange()
{if(!this.treeOutline)
return;if(!this._fireDidChangeDebouncer){this._fireDidChangeDebouncer=new Debouncer(()=>{this._fireDidChange();});}
this._fireDidChangeDebouncer.delayForFrame();}
_setListItemNodeContent()
{if(!this._listItemNode)
return;if(!this._titleHTML&&!this._title)
this._listItemNode.removeChildren();else if(typeof this._titleHTML==="string")
this._listItemNode.innerHTML=this._titleHTML;else if(typeof this._title==="string")
this._listItemNode.textContent=this._title;else{this._listItemNode.removeChildren();if(this._title.parentNode)
this._title.parentNode.removeChild(this._title);this._listItemNode.appendChild(this._title);}}
_attach()
{if(!this._listItemNode||this.parent._shouldRefreshChildren){if(this.parent._shouldRefreshChildren)
this._detach();this._listItemNode=this.treeOutline._childrenListNode.ownerDocument.createElement("li");this._listItemNode.treeElement=this;this._setListItemNodeContent();this._listItemNode.title=this._tooltip?this._tooltip:"";this._listItemNode.hidden=this.hidden;this._listItemNode.role="treeitem";if(this.hasChildren)
this._listItemNode.classList.add("parent");if(this.expanded)
this._listItemNode.classList.add("expanded");if(this.selected)
this._listItemNode.classList.add("selected");this._listItemNode.addEventListener("click",WI.TreeElement.treeElementToggled);this._listItemNode.addEventListener("dblclick",WI.TreeElement.treeElementDoubleClicked);if(this.onattach)
this.onattach(this);}
var nextSibling=null;if(this.nextSibling&&this.nextSibling._listItemNode&&this.nextSibling._listItemNode.parentNode===this.parent._childrenListNode)
nextSibling=this.nextSibling._listItemNode;if(!this.treeOutline||!this.treeOutline.virtualized){this.parent._childrenListNode.insertBefore(this._listItemNode,nextSibling);if(this._childrenListNode)
this.parent._childrenListNode.insertBefore(this._childrenListNode,this._listItemNode.nextSibling);}
if(this.selected)
this.select();if(this.expanded)
this.expand();}
_detach()
{if(this.ondetach&&this._listItemNode)
this.ondetach(this);if(this._listItemNode&&this._listItemNode.parentNode)
this._listItemNode.parentNode.removeChild(this._listItemNode);if(this._childrenListNode&&this._childrenListNode.parentNode)
this._childrenListNode.parentNode.removeChild(this._childrenListNode);}
static treeElementToggled(event)
{let element=event.currentTarget;if(!element)
return;let treeElement=element.treeElement;if(!treeElement)
return;let toggleOnClick=treeElement.toggleOnClick&&!treeElement.selectable;if(toggleOnClick||treeElement.isEventWithinDisclosureTriangle(event)){if(treeElement.expanded){if(event.altKey)
treeElement.collapseRecursively();else
treeElement.collapse();}else{if(event.altKey)
treeElement.expandRecursively();else
treeElement.expand();}
event.stopPropagation();}
if(treeElement.treeOutline&&!treeElement.treeOutline.selectable)
treeElement.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementClicked,{treeElement});}
static treeElementDoubleClicked(event)
{var element=event.currentTarget;if(!element||!element.treeElement)
return;if(element.treeElement.isEventWithinDisclosureTriangle(event))
return;if(element.treeElement.dispatchEventToListeners(WI.TreeElement.Event.DoubleClick))
return;if(element.treeElement.ondblclick)
element.treeElement.ondblclick.call(element.treeElement,event);else if(element.treeElement.hasChildren&&!element.treeElement.expanded)
element.treeElement.expand();}
collapse()
{if(this._listItemNode){this._listItemNode.classList.remove("expanded");this._listItemNode.ariaExpanded=false;}
if(this._childrenListNode){this._childrenListNode.classList.remove("expanded");this._childrenListNode.ariaExpanded=false;}
this.expanded=false;if(this.treeOutline)
this.treeOutline._treeElementsExpandedState[this.identifier]=false;if(this.oncollapse)
this.oncollapse(this);if(this.treeOutline){if(this.treeOutline.virtualized)
this.treeOutline.updateVirtualizedElementsDebouncer.delayForFrame();this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementDisclosureDidChanged,{element:this});}}
collapseRecursively()
{var item=this;while(item){if(item.expanded)
item.collapse();item=item.traverseNextTreeElement(false,this,true);}}
expand()
{if(this.expanded&&!this._shouldRefreshChildren&&this._childrenListNode)
return;
this.expanded=true;if(this.treeOutline)
this.treeOutline._treeElementsExpandedState[this.identifier]=true;if(!this.hasChildren)
return;if(this.treeOutline&&(!this._childrenListNode||this._shouldRefreshChildren)){if(this._childrenListNode&&this._childrenListNode.parentNode)
this._childrenListNode.parentNode.removeChild(this._childrenListNode);this._childrenListNode=this.treeOutline._childrenListNode.ownerDocument.createElement("ol");this._childrenListNode.parentTreeElement=this;this._childrenListNode.classList.add("children");this._childrenListNode.hidden=this.hidden;this._childrenListNode.role="group";this.onpopulate();
this.expanded=true;for(var i=0;i<this.children.length;++i)
this.children[i]._attach();this._shouldRefreshChildren=false;}
if(this._listItemNode){this._listItemNode.classList.add("expanded");this._listItemNode.ariaExpanded=true;if(this._childrenListNode&&this._childrenListNode.parentNode!==this._listItemNode.parentNode)
this.parent._childrenListNode.insertBefore(this._childrenListNode,this._listItemNode.nextSibling);}
if(this._childrenListNode){this._childrenListNode.classList.add("expanded");this._childrenListNode.ariaExpanded=true;}
if(this.onexpand)
this.onexpand(this);if(this.treeOutline){if(this.treeOutline.virtualized)
this.treeOutline.updateVirtualizedElementsDebouncer.delayForFrame();this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementDisclosureDidChanged,{element:this});}}
expandRecursively(maxDepth)
{var item=this;var info={};var depth=0;
if(maxDepth===undefined)
maxDepth=3;while(item){if(depth<maxDepth)
item.expand();item=item.traverseNextTreeElement(false,this,depth>=maxDepth,info);depth+=info.depthChange;}}
hasAncestor(ancestor)
{if(!ancestor)
return false;var currentNode=this.parent;while(currentNode){if(ancestor===currentNode)
return true;currentNode=currentNode.parent;}
return false;}
reveal()
{var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
currentAncestor.expand();currentAncestor=currentAncestor.parent;}

if(this.treeOutline&&this.treeOutline.virtualized)
this.treeOutline.updateVirtualizedElementsDebouncer.force(this);if(this.onreveal)
this.onreveal(this);if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRevealed,{element:this});}
revealed(ignoreHidden)
{if(!ignoreHidden&&this.hidden)
return false;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded)
return false;if(!ignoreHidden&&currentAncestor.hidden)
return false;currentAncestor=currentAncestor.parent;}
return true;}
select(omitFocus,selectedByUser,suppressNotification)
{let treeOutline=this.treeOutline;if(!treeOutline||!this.selectable)
return;if(!omitFocus)
this.focus();else if(treeOutline.element.contains(document.activeElement)){this.focus();}
if(this.selected&&!this.treeOutline.allowsRepeatSelection)
return;treeOutline=this.treeOutline;if(!treeOutline)
return;this.selected=true;treeOutline.selectTreeElementInternal(this,suppressNotification,selectedByUser);if(this._listItemNode)
this._listItemNode.ariaSelected=true;}
revealAndSelect(omitFocus,selectedByUser,suppressNotification)
{this.reveal();this.select(omitFocus,selectedByUser,suppressNotification);}
deselect(suppressNotification)
{if(!this.treeOutline||!this.selected)
return false;this.selected=false;this.treeOutline.selectTreeElementInternal(null,suppressNotification);if(this._listItemNode){this.unfocus();this._listItemNode.ariaSelected=false;}
return true;}
focus()
{if(!this._listItemNode)
return;this._listItemNode.tabIndex=0;this._listItemNode.focus();}
unfocus()
{if(!this._listItemNode)
return;this._listItemNode.removeAttribute("tabIndex");}
onpopulate()
{}
traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate,info)
{function shouldSkip(element){return skipUnrevealed&&!element.revealed(true);}
var depthChange=0;var element=this;if(!dontPopulate)
element.onpopulate();do{if(element.hasChildren&&element.children[0]&&(!skipUnrevealed||element.expanded)){element=element.children[0];depthChange+=1;}else{while(element&&!element.nextSibling&&element.parent&&!element.parent.root&&element.parent!==stayWithin){element=element.parent;depthChange-=1;}
if(element)
element=element.nextSibling;}}while(element&&shouldSkip(element));if(info)
info.depthChange=depthChange;return element;}
traversePreviousTreeElement(skipUnrevealed,dontPopulate)
{function shouldSkip(element){return skipUnrevealed&&!element.revealed(true);}
var element=this;do{if(element.previousSibling){element=element.previousSibling;while(element&&element.hasChildren&&element.expanded&&!shouldSkip(element)){if(!dontPopulate)
element.onpopulate();element=element.children.lastValue;}}else
element=element.parent&&element.parent.root?null:element.parent;}while(element&&shouldSkip(element));return element;}
isEventWithinDisclosureTriangle(event)
{if(!document.contains(this._listItemNode))
return false;let computedStyle=window.getComputedStyle(this._listItemNode);let start=0;if(computedStyle.direction===WI.LayoutDirection.RTL)
start+=this._listItemNode.totalOffsetRight-computedStyle.getPropertyCSSValue("padding-right").getFloatValue(CSSPrimitiveValue.CSS_PX)-this.arrowToggleWidth;else
start+=this._listItemNode.totalOffsetLeft+computedStyle.getPropertyCSSValue("padding-left").getFloatValue(CSSPrimitiveValue.CSS_PX);return event.pageX>=start&&event.pageX<=start+this.arrowToggleWidth&&this.hasChildren;}
populateContextMenu(contextMenu,event)
{if(this.children.some((child)=>child.hasChildren)||(this.hasChildren&&!this.children.length)){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Expand All"),this.expandRecursively.bind(this));contextMenu.appendItem(WI.UIString("Collapse All"),this.collapseRecursively.bind(this));}}};WI.TreeElement.Event={DoubleClick:"tree-element-double-click",};WI.TreeOutline=class TreeOutline extends WI.Object
{constructor(selectable=true)
{super();this.element=document.createElement("ol");this.element.classList.add(WI.TreeOutline.ElementStyleClassName);this.element.role="tree";this.element.addEventListener("contextmenu",this._handleContextmenu.bind(this));this.children=[];this._childrenListNode=this.element;this._childrenListNode.removeChildren();this._knownTreeElements=[];this._treeElementsExpandedState=[];this.allowsRepeatSelection=false;this.root=true;this.hasChildren=false;this.expanded=true;this.selected=false;this.treeOutline=this;this._hidden=false;this._compact=false;this._large=false;this._disclosureButtons=true;this._customIndent=false;this._selectable=selectable;this._cachedNumberOfDescendants=0;let itemForRepresentedObject=this.getCachedTreeElement.bind(this);let selectionComparator=WI.SelectionController.createTreeComparator(itemForRepresentedObject);this._selectionController=new WI.SelectionController(this,selectionComparator);this._itemWasSelectedByUser=false;this._processingSelectionChange=false;this._suppressNextSelectionDidChangeEvent=false;this._virtualizedDebouncer=null;this._virtualizedVisibleTreeElements=null;this._virtualizedAttachedTreeElements=null;this._virtualizedScrollContainer=null;this._virtualizedTreeItemHeight=NaN;this._virtualizedTopSpacer=null;this._virtualizedBottomSpacer=null;this._childrenListNode.tabIndex=0;this._childrenListNode.addEventListener("keydown",this._treeKeyDown.bind(this),true);this._childrenListNode.addEventListener("mousedown",this._handleMouseDown.bind(this));WI.TreeOutline._generateStyleRulesIfNeeded();if(!this._selectable)
this.element.classList.add("non-selectable");} 
get allowsEmptySelection()
{return this._selectionController.allowsEmptySelection;}
set allowsEmptySelection(flag)
{this._selectionController.allowsEmptySelection=flag;}
get allowsMultipleSelection()
{return this._selectionController.allowsMultipleSelection;}
set allowsMultipleSelection(flag)
{this._selectionController.allowsMultipleSelection=flag;}
get selectedTreeElement()
{return this.getCachedTreeElement(this._selectionController.lastSelectedItem);}
set selectedTreeElement(treeElement)
{if(treeElement)
this._selectionController.selectItem(this.objectForSelection(treeElement));else
this._selectionController.deselectAll();}
get selectedTreeElements()
{if(this.allowsMultipleSelection){let treeElements=[];for(let representedObject of this._selectionController.selectedItems)
treeElements.push(this.getCachedTreeElement(representedObject));return treeElements;}
let selectedTreeElement=this.selectedTreeElement;if(selectedTreeElement)
return[selectedTreeElement];return[];}
get processingSelectionChange(){return this._processingSelectionChange;}
get hidden()
{return this._hidden;}
set hidden(x)
{if(this._hidden===x)
return;this._hidden=x;this.element.hidden=this._hidden;}
get compact()
{return this._compact;}
set compact(x)
{if(this._compact===x)
return;this._compact=x;if(this._compact)
this.large=false;this.element.classList.toggle("compact",this._compact);}
get large()
{return this._large;}
set large(x)
{if(this._large===x)
return;this._large=x;if(this._large)
this.compact=false;this.element.classList.toggle("large",this._large);}
get disclosureButtons()
{return this._disclosureButtons;}
set disclosureButtons(x)
{if(this._disclosureButtons===x)
return;this._disclosureButtons=x;this.element.classList.toggle("hide-disclosure-buttons",!this._disclosureButtons);}
get customIndent()
{return this._customIndent;}
set customIndent(x)
{if(this._customIndent===x)
return;this._customIndent=x;this.element.classList.toggle(WI.TreeOutline.CustomIndentStyleClassName,this._customIndent);}
get selectable(){return this._selectable;}
appendChild(child)
{if(!child)
return;var lastChild=this.children[this.children.length-1];if(lastChild){lastChild.nextSibling=child;child.previousSibling=lastChild;}else{child.previousSibling=null;child.nextSibling=null;}
var isFirstChild=!this.children.length;this.children.push(child);this.hasChildren=true;child.parent=this;child.treeOutline=this.treeOutline;child.treeOutline._rememberTreeElement(child);var current=child.children[0];while(current){current.treeOutline=this.treeOutline;current.treeOutline._rememberTreeElement(current);current=current.traverseNextTreeElement(false,child,true);}
if(child.hasChildren&&child.treeOutline._treeElementsExpandedState[child.identifier]!==undefined)
child.expanded=child.treeOutline._treeElementsExpandedState[child.identifier];if(this._childrenListNode)
child._attach();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementAdded,{element:child});if(isFirstChild&&this.expanded)
this.expand();}
insertChild(child,index)
{if(!child)
return;var previousChild=index>0?this.children[index-1]:null;if(previousChild){previousChild.nextSibling=child;child.previousSibling=previousChild;}else{child.previousSibling=null;}
var nextChild=this.children[index];if(nextChild){nextChild.previousSibling=child;child.nextSibling=nextChild;}else{child.nextSibling=null;}
var isFirstChild=!this.children.length;this.children.splice(index,0,child);this.hasChildren=true;child.parent=this;child.treeOutline=this.treeOutline;child.treeOutline._rememberTreeElement(child);var current=child.children[0];while(current){current.treeOutline=this.treeOutline;current.treeOutline._rememberTreeElement(current);current=current.traverseNextTreeElement(false,child,true);}
if(child.hasChildren&&child.treeOutline._treeElementsExpandedState[child.identifier]!==undefined)
child.expanded=child.treeOutline._treeElementsExpandedState[child.identifier];if(this._childrenListNode)
child._attach();if(this.treeOutline)
this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementAdded,{element:child});if(isFirstChild&&this.expanded)
this.expand();}
removeChildAtIndex(childIndex,suppressOnDeselect,suppressSelectSibling)
{if(childIndex<0||childIndex>=this.children.length)
return;let child=this.children[childIndex];let parent=child.parent;if(child.deselect(suppressOnDeselect)&&!suppressSelectSibling){if(child.previousSibling)
child.previousSibling.select(true,false);else if(child.nextSibling)
child.nextSibling.select(true,false);else
parent.select(true,false);}
let treeOutline=child.treeOutline;if(treeOutline){treeOutline._forgetTreeElement(child);treeOutline._forgetChildrenRecursive(child);}
if(child.previousSibling)
child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling)
child.nextSibling.previousSibling=child.previousSibling;this.children.splice(childIndex,1);child._detach();child.treeOutline=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;if(treeOutline)
treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRemoved,{element:child});}
removeChild(child,suppressOnDeselect,suppressSelectSibling)
{if(!child)
return;var childIndex=this.children.indexOf(child);if(childIndex===-1)
return;this.removeChildAtIndex(childIndex,suppressOnDeselect,suppressSelectSibling);if(!this.children.length){if(this._listItemNode)
this._listItemNode.classList.remove("parent");this.hasChildren=false;}}
removeChildren(suppressOnDeselect)
{for(let child of this.children){child.deselect(suppressOnDeselect);let treeOutline=child.treeOutline;if(treeOutline){treeOutline._forgetTreeElement(child);treeOutline._forgetChildrenRecursive(child);}
child._detach();child.treeOutline=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;if(treeOutline)
treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRemoved,{element:child});}
this.children=[];}
_rememberTreeElement(element)
{if(!this._knownTreeElements[element.identifier])
this._knownTreeElements[element.identifier]=[];var elements=this._knownTreeElements[element.identifier];if(!elements.includes(element)){elements.push(element);this._cachedNumberOfDescendants++;}
if(this.virtualized)
this._virtualizedDebouncer.delayForFrame();}
_forgetTreeElement(element)
{if(this.selectedTreeElement===element){element.deselect(true);this.selectedTreeElement=null;}
if(this._knownTreeElements[element.identifier]){if(this._knownTreeElements[element.identifier].remove(element))
this._cachedNumberOfDescendants--;}
if(this.virtualized)
this._virtualizedDebouncer.delayForFrame();}
_forgetChildrenRecursive(parentElement)
{var child=parentElement.children[0];while(child){this._forgetTreeElement(child);child=child.traverseNextTreeElement(false,parentElement,true);}}
getCachedTreeElement(representedObject)
{if(!representedObject)
return null;

if(representedObject.__proxyObjectTreeElement)
return representedObject.__proxyObjectTreeElement;if(representedObject.__treeElementIdentifier){
var elements=this._knownTreeElements[representedObject.__treeElementIdentifier];if(elements){for(var i=0;i<elements.length;++i)
if(elements[i].representedObject===representedObject)
return elements[i];}}
return null;}
selfOrDescendant(predicate)
{let treeElements=[this];while(treeElements.length){let treeElement=treeElements.shift();if(predicate(treeElement))
return treeElement;treeElements.pushAll(treeElement.children);}
return false;}
findTreeElement(representedObject,isAncestor,getParent)
{if(!representedObject)
return null;var cachedElement=this.getCachedTreeElement(representedObject);if(cachedElement)
return cachedElement;
var item;var found=false;for(var i=0;i<this.children.length;++i){item=this.children[i];if(item.representedObject===representedObject||(isAncestor&&isAncestor(item.representedObject,representedObject))){found=true;break;}}
if(!found)
return null;var ancestors=[];var currentObject=representedObject;while(currentObject){ancestors.unshift(currentObject);if(currentObject===item.representedObject)
break;currentObject=getParent(currentObject);}
for(var i=0;i<ancestors.length;++i){
if(ancestors[i]===representedObject)
continue;
item=this.findTreeElement(ancestors[i],isAncestor,getParent);if(!item)
return null;item.onpopulate();}
return this.getCachedTreeElement(representedObject);}
_treeElementDidChange(treeElement)
{if(treeElement.treeOutline!==this)
return;this.dispatchEventToListeners(WI.TreeOutline.Event.ElementDidChange,{element:treeElement});}
treeElementFromNode(node)
{var listNode=node.closest("ol, li");if(listNode)
return listNode.parentTreeElement||listNode.treeElement;return null;}
treeElementFromPoint(x,y)
{var node=this._childrenListNode.ownerDocument.elementFromPoint(x,y);if(!node)
return null;return this.treeElementFromNode(node);}
_treeKeyDown(event)
{if(WI.isBeingEdited(event.target))
return;if(event.target!==this._childrenListNode&&event.target.closest("."+WI.TreeOutline.ElementStyleClassName)!==this._childrenListNode)
return;let isRTL=WI.resolveLayoutDirectionForElement(this.element)===WI.LayoutDirection.RTL;let expandKeyIdentifier=isRTL?"Left":"Right";let collapseKeyIdentifier=isRTL?"Right":"Left";var handled=false;var nextSelectedElement;if(this.selectedTreeElement){if(event.keyIdentifier===collapseKeyIdentifier){if(this.selectedTreeElement.expanded){if(event.altKey)
this.selectedTreeElement.collapseRecursively();else
this.selectedTreeElement.collapse();handled=true;}else if(this.selectedTreeElement.parent&&!this.selectedTreeElement.parent.root){handled=true;if(this.selectedTreeElement.parent.selectable){nextSelectedElement=this.selectedTreeElement.parent;while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.parent;handled=nextSelectedElement?true:false;}else if(this.selectedTreeElement.parent)
this.selectedTreeElement.parent.collapse();}}else if(event.keyIdentifier===expandKeyIdentifier){if(!this.selectedTreeElement.revealed()){this.selectedTreeElement.reveal();handled=true;}else if(this.selectedTreeElement.hasChildren){handled=true;if(this.selectedTreeElement.expanded){nextSelectedElement=this.selectedTreeElement.children[0];while(nextSelectedElement&&!nextSelectedElement.selectable)
nextSelectedElement=nextSelectedElement.nextSibling;handled=nextSelectedElement?true:false;}else{if(event.altKey)
this.selectedTreeElement.expandRecursively();else
this.selectedTreeElement.expand();}}}else if(event.keyCode===8||event.keyCode===46){for(let treeElement of this.selectedTreeElements){if(treeElement.ondelete&&treeElement.ondelete())
handled=true;}
if(!handled&&this.treeOutline.ondelete)
handled=this.treeOutline.ondelete(this.selectedTreeElement);}else if(isEnterKey(event)){if(this.selectedTreeElement.onenter)
handled=this.selectedTreeElement.onenter();if(!handled&&this.treeOutline.onenter)
handled=this.treeOutline.onenter(this.selectedTreeElement);}else if(event.keyIdentifier==="U+0020"){if(this.selectedTreeElement.onspace)
handled=this.selectedTreeElement.onspace();if(!handled&&this.treeOutline.onspace)
handled=this.treeOutline.onspace(this.selectedTreeElement);}}
if(!handled){this._itemWasSelectedByUser=true;handled=this._selectionController.handleKeyDown(event);this._itemWasSelectedByUser=false;if(handled)
nextSelectedElement=this.selectedTreeElement;}
if(nextSelectedElement){nextSelectedElement.reveal();nextSelectedElement.select(false,true);}
if(handled){event.preventDefault();event.stopPropagation();}}
expand()
{}
collapse()
{}
revealed()
{return true;}
reveal()
{}
select()
{}
revealAndSelect(omitFocus)
{}
selectTreeElements(treeElements)
{if(!treeElements.length)
return;if(treeElements.length===1){this.selectedTreeElement=treeElements[0];return;}
if(!this.allowsMultipleSelection)
return;let selectableObjects=treeElements.map((treeElement)=>this.objectForSelection(treeElement));this._selectionController.selectItems(new Set(selectableObjects));}
get virtualized()
{return this._virtualizedScrollContainer&&!isNaN(this._virtualizedTreeItemHeight);}
registerScrollVirtualizer(scrollContainer,treeItemHeight)
{let boundUpdateVirtualizedElements=(focusedTreeElement)=>{this._updateVirtualizedElements(focusedTreeElement);};this._virtualizedDebouncer=new Debouncer(boundUpdateVirtualizedElements);this._virtualizedVisibleTreeElements=new Set;this._virtualizedAttachedTreeElements=new Set;this._virtualizedScrollContainer=scrollContainer;this._virtualizedTreeItemHeight=treeItemHeight;this._virtualizedTopSpacer=document.createElement("div");this._virtualizedBottomSpacer=document.createElement("div");let throttler=new Throttler(boundUpdateVirtualizedElements,1000/16);this._virtualizedScrollContainer.addEventListener("scroll",(event)=>{throttler.fire();});this._updateVirtualizedElements();}
get updateVirtualizedElementsDebouncer()
{return this._virtualizedDebouncer;} 
selectionControllerSelectionDidChange(controller,deselectedItems,selectedItems)
{this._processingSelectionChange=true;for(let representedObject of deselectedItems){let treeElement=this.getCachedTreeElement(representedObject);if(!treeElement)
continue;if(treeElement.listItemElement)
treeElement.listItemElement.classList.remove("selected");treeElement.deselect();}
for(let representedObject of selectedItems){let treeElement=this.getCachedTreeElement(representedObject);if(!treeElement)
continue;if(treeElement.listItemElement)
treeElement.listItemElement.classList.add("selected");const omitFocus=true;treeElement.select(omitFocus);}
this._dispatchSelectionDidChangeEvent();this._processingSelectionChange=false;}
selectionControllerFirstSelectableItem(controller)
{let firstChild=this.children[0];if(firstChild.selectable)
return firstChild.representedObject;return this.selectionControllerNextSelectableItem(controller,firstChild.representedObject);}
selectionControllerLastSelectableItem(controller)
{let treeElement=this.children.lastValue;while(treeElement.expanded&&treeElement.children.length)
treeElement=treeElement.children.lastValue;let item=this.objectForSelection(treeElement);if(this.canSelectTreeElement(treeElement))
return item;return this.selectionControllerPreviousSelectableItem(controller,item);}
selectionControllerPreviousSelectableItem(controller,item)
{let treeElement=this.getCachedTreeElement(item);if(!treeElement)
return null;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(treeElement=treeElement.traversePreviousTreeElement(skipUnrevealed,stayWithin,dontPopulate)){if(this.canSelectTreeElement(treeElement))
return this.objectForSelection(treeElement);}
return null;}
selectionControllerNextSelectableItem(controller,item)
{let treeElement=this.getCachedTreeElement(item);if(!treeElement)
return null;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate)){if(this.canSelectTreeElement(treeElement))
return this.objectForSelection(treeElement);}
return null;} 
canSelectTreeElement(treeElement)
{return treeElement.selectable;}
objectForSelection(treeElement)
{return treeElement.representedObject;}
selectTreeElementInternal(treeElement,suppressNotification=false,selectedByUser=false)
{if(this._processingSelectionChange)
return;this._itemWasSelectedByUser=selectedByUser;this._suppressNextSelectionDidChangeEvent=suppressNotification;if(this.allowsRepeatSelection&&this.selectedTreeElement===treeElement){this._dispatchSelectionDidChangeEvent();return;}
this.selectedTreeElement=treeElement;}
treeElementFromEvent(event)
{



let scrollContainer=this.element.parentElement;if(scrollContainer.offsetWidth>this.element.offsetWidth)
scrollContainer=this.element;




let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let trailingEdgeOffset=isRTL?36:(scrollContainer.offsetWidth-36);let x=scrollContainer.totalOffsetLeft+trailingEdgeOffset;let y=event.pageY;

let elementUnderMouse=this.treeElementFromPoint(x,y);let elementAboveMouse=this.treeElementFromPoint(x,y-2);let element=null;if(elementUnderMouse===elementAboveMouse)
element=elementUnderMouse;else
element=this.treeElementFromPoint(x,y+2);return element;}
populateContextMenu(contextMenu,event,treeElement)
{treeElement.populateContextMenu(contextMenu,event);} 
static _generateStyleRulesIfNeeded()
{if(WI.TreeOutline._styleElement)
return;WI.TreeOutline._styleElement=document.createElement("style");let maximumTreeDepth=32;let depthPadding=10;let styleText="";let childrenSubstring="";for(let i=1;i<=maximumTreeDepth;++i){childrenSubstring+=i===maximumTreeDepth?" .children":" > .children";styleText+=`.${WI.TreeOutline.ElementStyleClassName}:not(.${WI.TreeOutline.CustomIndentStyleClassName})${childrenSubstring} > .item { `;styleText+=`padding-inline-start: calc(var(--tree-outline-item-padding) + ${depthPadding * i}px);`;styleText+=` }\n`;}
WI.TreeOutline._styleElement.textContent=styleText;document.head.appendChild(WI.TreeOutline._styleElement);}
_updateVirtualizedElements(focusedTreeElement)
{this._virtualizedDebouncer.cancel();function walk(parent,callback,count=0){let shouldReturn=false;for(let child of parent.children){if(!child.revealed(false))
continue;shouldReturn=callback(child,count);if(shouldReturn)
break;++count;if(child.expanded){let result=walk(child,callback,count);count=result.count;if(result.shouldReturn)
break;}}
return{count,shouldReturn};}
function calculateOffsetFromContainer(node,target){let top=0;while(node!==target){top+=node.offsetTop;node=node.offsetParent;if(!node)
return 0;}
return top;}
let offsetFromContainer=calculateOffsetFromContainer(this._virtualizedTopSpacer.parentNode?this._virtualizedTopSpacer:this.element,this._virtualizedScrollContainer);let numberVisible=Math.ceil(Math.max(0,this._virtualizedScrollContainer.offsetHeight-offsetFromContainer)/this._virtualizedTreeItemHeight);let extraRows=Math.max(numberVisible*5,50);let firstItem=Math.floor((this._virtualizedScrollContainer.scrollTop-offsetFromContainer)/this._virtualizedTreeItemHeight)-extraRows;let lastItem=firstItem+numberVisible+(extraRows*2);let shouldScroll=false;if(focusedTreeElement&&focusedTreeElement.revealed(false)){let index=walk(this,(treeElement)=>treeElement===focusedTreeElement).count;if(index<firstItem){firstItem=index-extraRows;lastItem=index+numberVisible+extraRows;}else if(index>lastItem){firstItem=index-numberVisible-extraRows;lastItem=index+extraRows;}

shouldScroll=(index<firstItem+extraRows)||(index>lastItem-extraRows);}
let visibleTreeElements=new Set;let treeElementsToAttach=new Set;let treeElementsToDetach=new Set;let totalItems=walk(this,(treeElement,count)=>{if(count>=firstItem&&count<=lastItem){treeElementsToAttach.add(treeElement);if(count>=firstItem+extraRows&&count<=lastItem-extraRows)
visibleTreeElements.add(treeElement);}else if(treeElement._listItemNode.parentNode)
treeElementsToDetach.add(treeElement);return false;}).count;if(!shouldScroll){if(visibleTreeElements.size===this._virtualizedVisibleTreeElements.size){if(visibleTreeElements.intersects(this._virtualizedVisibleTreeElements)){if(visibleTreeElements.isSubsetOf(this._virtualizedAttachedTreeElements))
return;}}}
this._virtualizedVisibleTreeElements=visibleTreeElements;this._virtualizedAttachedTreeElements=treeElementsToAttach;for(let treeElement of treeElementsToDetach)
treeElement._listItemNode.remove();for(let treeElement of treeElementsToAttach){treeElement.parent._childrenListNode.appendChild(treeElement._listItemNode);if(treeElement._childrenListNode)
treeElement.parent._childrenListNode.appendChild(treeElement._childrenListNode);}
this._virtualizedTopSpacer.style.height=(Number.constrain(firstItem,0,totalItems)*this._virtualizedTreeItemHeight)+"px";if(this.element.previousElementSibling!==this._virtualizedTopSpacer)
this.element.parentNode.insertBefore(this._virtualizedTopSpacer,this.element);this._virtualizedBottomSpacer.style.height=(Number.constrain(totalItems-lastItem,0,totalItems)*this._virtualizedTreeItemHeight)+"px";if(this.element.nextElementSibling!==this._virtualizedBottomSpacer)
this.element.parentNode.insertBefore(this._virtualizedBottomSpacer,this.element.nextElementSibling);if(shouldScroll)
this._virtualizedScrollContainer.scrollTop=offsetFromContainer+((firstItem+extraRows)*this._virtualizedTreeItemHeight);}
_handleContextmenu(event)
{let treeElement=this.treeElementFromEvent(event);if(!treeElement)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);this.populateContextMenu(contextMenu,event,treeElement);}
_handleMouseDown(event)
{let treeElement=this.treeElementFromEvent(event);if(!treeElement||!treeElement.selectable)
return;if(treeElement.isEventWithinDisclosureTriangle(event)){event.preventDefault();return;}
if(!treeElement.canSelectOnMouseDown(event))
return;if(this.allowsRepeatSelection&&treeElement.selected&&this._selectionController.selectedItems.size===1){
this._itemWasSelectedByUser=true;this._dispatchSelectionDidChangeEvent();return;}
this._itemWasSelectedByUser=true;this._selectionController.handleItemMouseDown(this.objectForSelection(treeElement),event);this._itemWasSelectedByUser=false;treeElement.focus();}
_dispatchSelectionDidChangeEvent()
{let selectedByUser=this._itemWasSelectedByUser;this._itemWasSelectedByUser=false;if(this._suppressNextSelectionDidChangeEvent){this._suppressNextSelectionDidChangeEvent=false;return;}
this.dispatchEventToListeners(WI.TreeOutline.Event.SelectionDidChange,{selectedByUser});}};WI.TreeOutline._styleElement=null;WI.TreeOutline.ElementStyleClassName="tree-outline";WI.TreeOutline.CustomIndentStyleClassName="custom-indent";WI.TreeOutline.Event={ElementAdded:"element-added",ElementDidChange:"element-did-change",ElementRemoved:"element-removed",ElementRevealed:"element-revealed",ElementClicked:"element-clicked",ElementDisclosureDidChanged:"element-disclosure-did-change",ElementVisibilityDidChange:"element-visbility-did-change",SelectionDidChange:"selection-did-change",};WI.TreeOutline._knownTreeElementNextIdentifier=1;WI.TreeOutlineGroup=class TreeOutlineGroup extends WI.Collection
{ objectIsRequiredType(object)
{return object instanceof WI.TreeOutline;}
get selectedTreeElement()
{for(let treeOutline of this){if(treeOutline.selectedTreeElement)
return treeOutline.selectedTreeElement;}
return null;} 
itemAdded(treeOutline)
{if(treeOutline.selectedTreeElement)
this._removeConflictingTreeSelections(treeOutline);treeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeOutlineSelectionDidChange,this);}
itemRemoved(treeOutline)
{treeOutline.removeEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeOutlineSelectionDidChange,this);} 
_removeConflictingTreeSelections(selectedTreeOutline)
{for(let treeOutline of this){if(selectedTreeOutline===treeOutline)
continue;treeOutline.selectedTreeElement=null;}}
_treeOutlineSelectionDidChange(event)
{let treeOutline=event.target;if(!treeOutline.selectedTreeElement)
return;this._removeConflictingTreeSelections(treeOutline);}};WI.ButtonNavigationItem=class ButtonNavigationItem extends WI.NavigationItem
{constructor(identifier,toolTipOrLabel,image,imageWidth,imageHeight,role,label)
{role=role||"button";super(identifier,role);this._enabled=true;this.element.addEventListener("click",this._mouseClicked.bind(this));this.element.addEventListener("mousedown",this._handleMouseDown.bind(this),true);this._role=role;if(this._role==="button")
this.element.addEventListener("keydown",this._handleKeyDown.bind(this));if(label)
this.element.setAttribute("aria-label",label);this._buttonStyle=null;this._disabled=false;this._image=image||null;this._imageWidth=imageWidth||16;this._imageHeight=imageHeight||16;this._label=toolTipOrLabel;this._updateTabIndex();this.buttonStyle=this._image?WI.ButtonNavigationItem.Style.Image:WI.ButtonNavigationItem.Style.Text;this.imageType=this._image?WI.ButtonNavigationItem.ImageType.SVG:null;if(this.buttonStyle===WI.ButtonNavigationItem.Style.Image)
this.tooltip=toolTipOrLabel;} 
get label()
{return this._label;}
set label(newLabel)
{newLabel=newLabel||"";if(this._label===newLabel)
return;this._label=newLabel;this._update();if(this.parentNavigationBar)
this.parentNavigationBar.needsLayout();}
get image()
{return this._image;}
set image(newImage)
{newImage=newImage||null;if(this._image===newImage)
return;this._image=newImage;this._update();}
get enabled()
{return this._enabled;}
set enabled(flag)
{flag=!!flag;if(this._enabled===flag)
return;this._enabled=flag;this.element.classList.toggle("disabled",!this._enabled);this.element.ariaDisabled=!this._enabled;this._updateTabIndex();}
get buttonStyle()
{return this._buttonStyle;}
set buttonStyle(newButtonStyle)
{newButtonStyle=newButtonStyle||WI.ButtonNavigationItem.Style.Image;if(this._buttonStyle===newButtonStyle)
return;this.element.classList.remove(...Object.values(WI.ButtonNavigationItem.Style));this.element.classList.add(newButtonStyle);this._buttonStyle=newButtonStyle;this._update();if(this.parentNavigationBar)
this.parentNavigationBar.needsLayout();}
get imageType()
{return this._imageType;}
set imageType(imageType)
{if(this._imageType===imageType)
return;this._imageType=imageType;this._update();if(this.parentNavigationBar)
this.parentNavigationBar.needsLayout();} 
get totalMargin()
{let totalMargin=super.totalMargin;if(this._buttonStyle===ButtonNavigationItem.Style.Text)
return totalMargin+4;return totalMargin;}
get additionalClassNames()
{return["button"];}
get tabbable()
{return this._role==="button";} 
_mouseClicked(event)
{this._buttonPressed(event);}
_handleMouseDown(event)
{event.preventDefault();}
_handleKeyDown(event)
{if(event.code==="Enter"||event.code==="Space"){event.stop();this._buttonPressed(event);}}
_buttonPressed(event)
{if(!this.enabled)
return;this.dispatchEventToListeners(WI.ButtonNavigationItem.Event.Clicked,{nativeEvent:event});}
_update()
{this.element.removeChildren();if(this._buttonStyle===WI.ButtonNavigationItem.Style.Text)
this.element.textContent=this._label;else{switch(this._imageType){case null:case WI.ButtonNavigationItem.ImageType.SVG:{let glyphElement=WI.ImageUtilities.useSVGSymbol(this._image,"glyph");glyphElement.style.width=this._imageWidth+"px";glyphElement.style.height=this._imageHeight+"px";this.element.appendChild(glyphElement);break;}
case WI.ButtonNavigationItem.ImageType.IMG:{let img=this.element.appendChild(document.createElement("img"));img.src=this._image;break;}}
if(this._buttonStyle===WI.ButtonNavigationItem.Style.ImageAndText){let labelElement=this.element.appendChild(document.createElement("span"));labelElement.textContent=this._label;}}}
_updateTabIndex()
{if(!this._enabled){this.element.tabIndex=-1;return;}
this.element.tabIndex=this.tabbable?0:-1;}};WI.ButtonNavigationItem.Event={Clicked:"button-navigation-item-clicked"};WI.ButtonNavigationItem.Style={Image:"image-only",Text:"text-only",ImageAndText:"image-and-text",};WI.ButtonNavigationItem.ImageType={SVG:"image-type-svg",IMG:"image-type-img",};WI.DatabaseUserQueryViewBase=class DatabaseUserQueryViewBase extends WI.View
{constructor(query)
{super();this.element.className="database-user-query";let commandTextElement=document.createElement("span");commandTextElement.className="database-query-text";commandTextElement.textContent=query;this.element.appendChild(commandTextElement);this._resultElement=document.createElement("div");this._resultElement.className="database-query-result";this.element.appendChild(this._resultElement);} 
get resultElement()
{return this._resultElement;}};WI.DatabaseUserQueryErrorView=class DatabaseUserQueryErrorView extends WI.DatabaseUserQueryViewBase
{constructor(query,message)
{super(query);this.resultElement.classList.add("error");this.resultElement.textContent=message;}};WI.DatabaseUserQuerySuccessView=class DatabaseUserQuerySuccessView extends WI.DatabaseUserQueryViewBase
{constructor(query,columnNames,values)
{super(query);this._dataGrid=WI.DataGrid.createSortableDataGrid(columnNames,values);if(this._dataGrid){this._dataGrid.inline=true;this.resultElement.appendChild(this._dataGrid.element);this._dataGrid.updateLayoutIfNeeded();}else{this.resultElement.classList.add("no-results");this.resultElement.textContent=WI.UIString("Query returned no results.");}} 
get dataGrid()
{return this._dataGrid;} 
layout()
{if(this._dataGrid)
this._dataGrid.updateLayout();}};WI.DOMTreeContentView=class DOMTreeContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);WI.settings.showRulers.addEventListener(WI.Setting.Event.Changed,this._showRulersChanged,this);this._showRulersButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-rulers",WI.UIString("Show rulers"),WI.UIString("Hide rulers"),"Images/Rulers.svg",16,16);this._showRulersButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleShowRulers,this);this._showRulersButtonNavigationItem.enabled=InspectorBackend.hasCommand("Page.setShowRulers");this._showRulersButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showRulersChanged();this._showPrintStylesButtonNavigationItem=new WI.ActivateButtonNavigationItem("print-styles",WI.UIString("Force print media styles"),WI.UIString("Use default media styles"),"Images/Printer.svg",16,16);this._showPrintStylesButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrintStyles,this);this._showPrintStylesButtonNavigationItem.enabled=InspectorBackend.hasCommand("Page.setEmulatedMedia");this._showPrintStylesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showPrintStylesChanged();this._forceAppearanceButtonNavigationItem=new WI.ActivateButtonNavigationItem("appearance",WI.UIString("Force Dark Appearance"),WI.UIString("Use Default Appearance"),"Images/Appearance.svg",16,16);this._forceAppearanceButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleAppearance,this);this._forceAppearanceButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._forceAppearanceButtonNavigationItem.enabled=WI.cssManager.canForceAppearance();this._compositingBordersButtonNavigationItem=new WI.ActivateButtonNavigationItem("layer-borders",WI.UIString("Show compositing borders"),WI.UIString("Hide compositing borders"),"Images/LayerBorders.svg",13,13);this._compositingBordersButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCompositingBordersButtonClicked,this);this._compositingBordersButtonNavigationItem.enabled=WI.LayerTreeManager.supportsVisibleCompositingBorders();this._compositingBordersButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._paintFlashingButtonNavigationItem=new WI.ActivateButtonNavigationItem("paint-flashing",WI.UIString("Enable paint flashing"),WI.UIString("Disable paint flashing"),"Images/Paint.svg",16,16);this._paintFlashingButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handlePaingFlashingButtonClicked,this);this._paintFlashingButtonNavigationItem.enabled=WI.LayerTreeManager.supportsShowingPaintRects();this._paintFlashingButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this.element.classList.add("dom-tree");this.element.addEventListener("click",this._mouseWasClicked.bind(this),false);this._domTreeOutline=new WI.DOMTreeOutline({omitRootDOMNode:true,excludeRevealElementContextMenu:true,showInspectedNode:true});this._domTreeOutline.allowsEmptySelection=false;this._domTreeOutline.allowsMultipleSelection=true;this._domTreeOutline.addEventListener(WI.TreeOutline.Event.ElementAdded,this._domTreeElementAdded,this);this._domTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._domTreeSelectionDidChange,this);this._domTreeOutline.addEventListener(WI.DOMTreeOutline.Event.SelectedNodeChanged,this._selectedNodeDidChange,this);this._domTreeOutline.wireToDomAgent();this._domTreeOutline.editable=true;this.element.appendChild(this._domTreeOutline.element);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeModified,this._domNodeChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeRemoved,this._domNodeChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.CharacterDataModified,this._domNodeChanged,this);WI.cssManager.addEventListener(WI.CSSManager.Event.DefaultAppearanceDidChange,this._defaultAppearanceDidChange,this);this._lastSelectedNodePathSetting=new WI.Setting("last-selected-node-path",null);this._lastKnownDefaultAppearance=null;this._numberOfSearchResults=null;this._breakpointGutterEnabled=false;this._pendingBreakpointNodes=new Set;this._defaultAppearanceDidChange();if(WI.domDebuggerManager.supported){WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._domBreakpointAddedOrRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._domBreakpointAddedOrRemoved,this);WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleDOMBreakpointDisabledStateChanged,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);this._breakpointsEnabledDidChange();}} 
get navigationItems()
{return[this._showRulersButtonNavigationItem,this._showPrintStylesButtonNavigationItem,this._forceAppearanceButtonNavigationItem,this._compositingBordersButtonNavigationItem,this._paintFlashingButtonNavigationItem,];}
get domTreeOutline()
{return this._domTreeOutline;}
get scrollableElements()
{return[this.element];}
get breakpointGutterEnabled()
{return this._breakpointGutterEnabled;}
set breakpointGutterEnabled(flag)
{if(this._breakpointGutterEnabled===flag)
return;this._breakpointGutterEnabled=flag;this.element.classList.toggle("show-gutter",this._breakpointGutterEnabled);}
closed()
{super.closed();WI.settings.showRulers.removeEventListener(WI.Setting.Event.Changed,this._showRulersChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeModified,this._domNodeChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeRemoved,this._domNodeChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CharacterDataModified,this._domNodeChanged,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.DefaultAppearanceDidChange,this._defaultAppearanceDidChange,this);if(WI.domDebuggerManager.supported){WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._domBreakpointAddedOrRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._domBreakpointAddedOrRemoved,this);WI.DOMBreakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleDOMBreakpointDisabledStateChanged,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);}
this._domTreeOutline.close();this._pendingBreakpointNodes.clear();}
get selectionPathComponents()
{var treeElement=this._domTreeOutline.selectedTreeElement;var pathComponents=[];while(treeElement&&!treeElement.root){
if(treeElement.isCloseTag()){treeElement=treeElement.parent;continue;}
var pathComponent=new WI.DOMTreeElementPathComponent(treeElement,treeElement.representedObject);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.Clicked,this._handlePathComponentSelected,this);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._handlePathComponentSelected,this);pathComponents.unshift(pathComponent);treeElement=treeElement.parent;}
return pathComponents;}
restoreFromCookie(cookie)
{if(!cookie||!cookie.nodeToSelect)
return;this.selectAndRevealDOMNode(cookie.nodeToSelect);
cookie.nodeToSelect=undefined;}
selectAndRevealDOMNode(domNode,preventFocusChange)
{this._domTreeOutline.selectDOMNode(domNode,!preventFocusChange);}
async handleCopyEvent(event)
{let promises=[];for(let treeElement of this._domTreeOutline.selectedTreeElements){if(treeElement.representedObject instanceof WI.DOMNode)
promises.push(treeElement.representedObject.getOuterHTML());}
if(!promises.length)
return;event.clipboardData.clearData();event.preventDefault();let outerHTMLs=await Promise.all(promises);InspectorFrontendHost.copyText(outerHTMLs.join("\n"));}
handlePasteEvent(event)
{let selectedDOMNode=this._domTreeOutline.selectedDOMNode();if(!selectedDOMNode)
return;let text=event.clipboardData.getData("text/plain");if(!text)
return;selectedDOMNode.insertAdjacentHTML("afterend",text);}
get supportsSave()
{return WI.canArchiveMainFrame();}
get saveData()
{return{customSaveHandler:()=>{WI.archiveMainFrame();}};}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._numberOfSearchResults;}
get hasPerformedSearch()
{return this._numberOfSearchResults!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this._numberOfSearchResults>0){if(this._currentSearchResultIndex===-1)
this.revealNextSearchResult();}}
performSearch(query)
{if(this._searchQuery===query)
return;let target=WI.assumingMainTarget();if(this._searchIdentifier){target.DOMAgent.discardSearchResults(this._searchIdentifier);this._hideSearchHighlights();}
this._searchQuery=query;this._searchIdentifier=null;this._numberOfSearchResults=null;this._currentSearchResultIndex=-1;function searchResultsReady(error,searchIdentifier,resultsCount)
{if(error)
return;this._searchIdentifier=searchIdentifier;this._numberOfSearchResults=resultsCount;this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);this._showSearchHighlights();if(this._automaticallyRevealFirstSearchResult)
this.revealNextSearchResult();}
function contextNodesReady(nodeIds)
{if(this._searchQuery!==query)
return;let commandArguments={query:this._searchQuery,nodeIds,caseSensitive:WI.SearchUtilities.defaultSettings.caseSensitive.value,};target.DOMAgent.performSearch.invoke(commandArguments,searchResultsReady.bind(this));}
this.getSearchContextNodes(contextNodesReady.bind(this));}
getSearchContextNodes(callback)
{callback(undefined);}
searchCleared()
{if(this._searchIdentifier){let target=WI.assumingMainTarget();target.DOMAgent.discardSearchResults(this._searchIdentifier);this._hideSearchHighlights();}
this._searchQuery=null;this._searchIdentifier=null;this._numberOfSearchResults=null;this._currentSearchResultIndex=-1;}
revealPreviousSearchResult(changeFocus)
{if(!this._numberOfSearchResults)
return;if(this._currentSearchResultIndex>0)
--this._currentSearchResultIndex;else
this._currentSearchResultIndex=this._numberOfSearchResults-1;this._revealSearchResult(this._currentSearchResultIndex,changeFocus);}
revealNextSearchResult(changeFocus)
{if(!this._numberOfSearchResults)
return;if(this._currentSearchResultIndex+1<this._numberOfSearchResults)
++this._currentSearchResultIndex;else
this._currentSearchResultIndex=0;this._revealSearchResult(this._currentSearchResultIndex,changeFocus);} 
attached()
{super.attached();this._domTreeOutline.setVisible(true,WI.isConsoleFocused());if(this._domTreeOutline.rootDOMNode)
this._restoreBreakpointsAfterUpdate();WI.layerTreeManager.updateCompositingBordersVisibleFromPageIfNeeded();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.CompositingBordersVisibleChanged,this._handleCompositingBordersVisibleChanged,this);this._handleCompositingBordersVisibleChanged();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.ShowPaintRectsChanged,this._handleShowPaintRectsChanged,this);this._handleShowPaintRectsChanged();}
detached()
{WI.domManager.hideDOMNodeHighlight();this._domTreeOutline.setVisible(false);WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.ShowPaintRectsChanged,this._handleShowPaintRectsChanged,this);WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.CompositingBordersVisibleChanged,this._handleCompositingBordersVisibleChanged,this);super.detached();}
sizeDidChange()
{super.sizeDidChange();this._domTreeOutline.selectDOMNode(this._domTreeOutline.selectedDOMNode());}
layout()
{super.layout();this._domTreeOutline.updateSelectionArea();} 
_revealSearchResult(index,changeFocus)
{var searchIdentifier=this._searchIdentifier;function revealResult(error,nodeIdentifiers)
{if(error)
return;if(this._searchIdentifier!==searchIdentifier)
return;var domNode=WI.domManager.nodeForId(nodeIdentifiers[0]);if(!domNode)
return;this._domTreeOutline.selectDOMNode(domNode,changeFocus);var selectedTreeElement=this._domTreeOutline.selectedTreeElement;if(selectedTreeElement)
selectedTreeElement.emphasizeSearchHighlight();}
let target=WI.assumingMainTarget();target.DOMAgent.getSearchResults(this._searchIdentifier,index,index+1,revealResult.bind(this));}
_restoreSelectedNodeAfterUpdate(documentURL,defaultNode)
{if(!WI.domManager.restoreSelectedNodeIsAllowed)
return;function selectNode(lastSelectedNode)
{var nodeToFocus=lastSelectedNode;if(!nodeToFocus)
nodeToFocus=defaultNode;if(!nodeToFocus)
return;this._dontSetLastSelectedNodePath=true;this.selectAndRevealDOMNode(nodeToFocus,WI.isConsoleFocused());this._dontSetLastSelectedNodePath=false;if(!lastSelectedNode&&this._domTreeOutline.selectedTreeElement)
this._domTreeOutline.selectedTreeElement.expand();}
function selectLastSelectedNode(nodeId)
{if(!WI.domManager.restoreSelectedNodeIsAllowed)
return;selectNode.call(this,WI.domManager.nodeForId(nodeId));}
if(InspectorBackend.hasCommand("DOM.pushNodeByPathToFrontend")&&documentURL&&this._lastSelectedNodePathSetting.value&&this._lastSelectedNodePathSetting.value.path&&this._lastSelectedNodePathSetting.value.url===documentURL.hash)
WI.domManager.pushNodeByPathToFrontend(this._lastSelectedNodePathSetting.value.path,selectLastSelectedNode.bind(this));else
selectNode.call(this);}
_domTreeElementAdded(event)
{if(!this._pendingBreakpointNodes.size)
return;let treeElement=event.data.element;let node=treeElement.representedObject;if(!(node instanceof WI.DOMNode))
return;if(!this._pendingBreakpointNodes.delete(node))
return;this._updateBreakpointStatus(node);}
_domTreeSelectionDidChange(event)
{let treeElement=this._domTreeOutline.selectedTreeElement;let domNode=treeElement?treeElement.representedObject:null;let selectedByUser=event.data.selectedByUser;this._domTreeOutline.suppressRevealAndSelect=true;this._domTreeOutline.selectDOMNode(domNode,selectedByUser);if(domNode&&selectedByUser)
domNode.highlight();this._domTreeOutline.updateSelectionArea();this._domTreeOutline.suppressRevealAndSelect=false;}
_selectedNodeDidChange(event)
{var selectedDOMNode=this._domTreeOutline.selectedDOMNode();if(selectedDOMNode&&!this._dontSetLastSelectedNodePath)
this._lastSelectedNodePathSetting.value={url:WI.networkManager.mainFrame.url.hash,path:selectedDOMNode.path()};if(selectedDOMNode)
WI.domManager.setInspectedNode(selectedDOMNode);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_handlePathComponentSelected(event)
{if(!event.data.pathComponent)
return;this._domTreeOutline.selectDOMNode(event.data.pathComponent.domTreeElement.representedObject,true);}
_domNodeChanged(event)
{var selectedDOMNode=this._domTreeOutline.selectedDOMNode();if(selectedDOMNode!==event.data.node)
return;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_mouseWasClicked(event)
{var anchorElement=event.target.closest("a");if(!anchorElement||!anchorElement.href)
return;event.preventDefault();event.stopPropagation();if(WI.isBeingEdited(anchorElement)){return;}
if(this._followLinkTimeoutIdentifier){clearTimeout(this._followLinkTimeoutIdentifier);delete this._followLinkTimeoutIdentifier;}
if(event.detail>1)
return;function followLink()
{

const options={alwaysOpenExternally:event?event.metaKey:false,lineNumber:anchorElement.lineNumber,ignoreNetworkTab:true,ignoreSearchTab:true,};WI.openURL(anchorElement.href,this._frame,options);}
this._followLinkTimeoutIdentifier=setTimeout(followLink.bind(this),333);}
_handleCompositingBordersVisibleChanged(event)
{this._compositingBordersButtonNavigationItem.activated=WI.layerTreeManager.compositingBordersVisible;}
_handleCompositingBordersButtonClicked(event)
{WI.layerTreeManager.compositingBordersVisible=!WI.layerTreeManager.compositingBordersVisible;}
_handleShowPaintRectsChanged(event)
{this._paintFlashingButtonNavigationItem.activated=WI.layerTreeManager.showPaintRects;}
_handlePaingFlashingButtonClicked(event)
{WI.layerTreeManager.showPaintRects=!WI.layerTreeManager.showPaintRects;}
_showPrintStylesChanged()
{this._showPrintStylesButtonNavigationItem.activated=WI.printStylesEnabled;let mediaType=WI.printStylesEnabled?"print":"";for(let target of WI.targets){if(target.hasCommand("Page.setEmulatedMedia"))
target.PageAgent.setEmulatedMedia(mediaType);}
WI.cssManager.mediaTypeChanged();}
_togglePrintStyles(event)
{WI.printStylesEnabled=!WI.printStylesEnabled;this._showPrintStylesChanged();}
_defaultAppearanceDidChange()
{if(WI.cssManager.forcedAppearance)
return;let defaultAppearance=WI.cssManager.defaultAppearance;switch(defaultAppearance){case WI.CSSManager.Appearance.Light:case null: this._forceAppearanceButtonNavigationItem.defaultToolTip=WI.UIString("Force Dark Appearance");break;case WI.CSSManager.Appearance.Dark:this._forceAppearanceButtonNavigationItem.defaultToolTip=WI.UIString("Force Light Appearance");break;}
this._lastKnownDefaultAppearance=defaultAppearance;this._forceAppearanceButtonNavigationItem.activated=!!WI.cssManager.forcedAppearance;}
_toggleAppearance(event)
{let appearanceToForce=null;switch(this._lastKnownDefaultAppearance){case WI.CSSManager.Appearance.Light:case null:appearanceToForce=WI.CSSManager.Appearance.Dark;break;case WI.CSSManager.Appearance.Dark:appearanceToForce=WI.CSSManager.Appearance.Light;break;}
WI.cssManager.forcedAppearance=WI.cssManager.forcedAppearance===appearanceToForce?null:appearanceToForce;
if(!WI.cssManager.forcedAppearance&&this._lastKnownDefaultAppearance!==WI.cssManager.defaultAppearance)
this._defaultAppearanceDidChange();else
this._forceAppearanceButtonNavigationItem.activated=!!WI.cssManager.forcedAppearance;}
_showRulersChanged()
{let activated=WI.settings.showRulers.value;this._showRulersButtonNavigationItem.activated=activated;for(let target of WI.targets){if(target.hasCommand("Page.setShowRulers"))
target.PageAgent.setShowRulers(activated);}}
_toggleShowRulers(event)
{WI.settings.showRulers.value=!WI.settings.showRulers.value;this._showRulersChanged();}
_showSearchHighlights()
{this._searchResultNodes=[];var searchIdentifier=this._searchIdentifier;let target=WI.assumingMainTarget();target.DOMAgent.getSearchResults(this._searchIdentifier,0,this._numberOfSearchResults,function(error,nodeIdentifiers){if(error)
return;if(this._searchIdentifier!==searchIdentifier)
return;for(var i=0;i<nodeIdentifiers.length;++i){var domNode=WI.domManager.nodeForId(nodeIdentifiers[i]);if(!domNode)
continue;this._searchResultNodes.push(domNode);var treeElement=this._domTreeOutline.findTreeElement(domNode);if(treeElement)
treeElement.highlightSearchResults(this._searchQuery);}}.bind(this));}
_hideSearchHighlights()
{if(!this._searchResultNodes)
return;for(var domNode of this._searchResultNodes){var treeElement=this._domTreeOutline.findTreeElement(domNode);if(treeElement)
treeElement.hideSearchHighlights();}
delete this._searchResultNodes;}
_domBreakpointAddedOrRemoved(event)
{let breakpoint=event.data.breakpoint;this._updateBreakpointStatus(breakpoint.domNode);}
_handleDOMBreakpointDisabledStateChanged(event)
{let breakpoint=event.target;this._updateBreakpointStatus(breakpoint.domNode);}
_handleDOMBreakpointDOMNodeWillChange(event)
{let breakpoint=event.target;this._updateBreakpointStatus(breakpoint.domNode);}
_handleDOMBreakpointDOMNodeDidChange(event)
{let breakpoint=event.target;this._updateBreakpointStatus(breakpoint.domNode);}
_updateBreakpointStatus(domNode)
{if(!domNode)
return;let treeElement=this._domTreeOutline.findTreeElement(domNode);if(!treeElement){this._pendingBreakpointNodes.add(domNode);return;}
let breakpoints=WI.domDebuggerManager.domBreakpointsForNode(domNode);if(breakpoints.length){if(breakpoints.some((item)=>item.disabled))
treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.DisabledBreakpoint;else
treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.Breakpoint;}else
treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.None;this.breakpointGutterEnabled=this._domTreeOutline.children.some((child)=>child.hasBreakpoint);}
_restoreBreakpointsAfterUpdate()
{this._pendingBreakpointNodes.clear();this.breakpointGutterEnabled=false;let updatedNodes=new Set;for(let breakpoint of WI.domDebuggerManager.domBreakpoints){if(updatedNodes.has(breakpoint.domNode))
continue;this._updateBreakpointStatus(breakpoint.domNode);}}
_breakpointsEnabledDidChange(event)
{this._domTreeOutline.element.classList.toggle("breakpoints-disabled",!WI.debuggerManager.breakpointsEnabled);}};WI.DetailsSidebarPanel=class DetailsSidebarPanel extends WI.SidebarPanel
{constructor(identifier,displayName,dontCreateNavigationItem)
{super(identifier,displayName);this.element.classList.add("details");if(!dontCreateNavigationItem)
this._navigationItem=new WI.RadioButtonNavigationItem(identifier,displayName);} 
get navigationItem()
{return this._navigationItem;}
inspect(objects)
{return false;}};WI.GeneralTabBarItem=class GeneralTabBarItem extends WI.TabBarItem
{ static fromTabContentView(tabContentView)
{let{image,displayName,title}=tabContentView.tabInfo();return new WI.GeneralTabBarItem(tabContentView,image,displayName,title);} 
get displayName()
{return super.displayName;}
set displayName(displayName)
{if(displayName){this._displayNameElement=document.createElement("span");this._displayNameElement.className="name";let displayNameContentElement=this._displayNameElement.appendChild(document.createElement("span"));displayNameContentElement.className="content";displayNameContentElement.textContent=displayName;this.element.insertBefore(this._displayNameElement,this.element.lastChild);}else{if(this._displayNameElement)
this._displayNameElement.remove();this._displayNameElement=null;}
super.displayName=displayName;}};WI.GeneralTreeElement=class GeneralTreeElement extends WI.TreeElement
{constructor(classNames,title,subtitle,representedObject,options)
{super("",representedObject,options);this.classNames=classNames;this._tooltipHandledSeparately=false;this._mainTitle=title||"";this._subtitle=subtitle||"";this._status="";} 
get element()
{return this._listItemNode;}
get iconElement()
{this._createElementsIfNeeded();return this._iconElement;}
get statusElement()
{return this._statusElement;}
get titlesElement()
{this._createElementsIfNeeded();return this._titlesElement;}
get mainTitleElement()
{this._createElementsIfNeeded();return this._mainTitleElement;}
get subtitleElement()
{this._createElementsIfNeeded();this._createSubtitleElementIfNeeded();return this._subtitleElement;}
get classNames()
{return this._classNames;}
set classNames(x)
{x=x||[];if(typeof x==="string")
x=[x];if(Array.shallowEqual(this._classNames,x))
return;if(this._listItemNode&&this._classNames)
this._listItemNode.classList.remove(...this._classNames);this._classNames=x;if(this._listItemNode)
this._listItemNode.classList.add(...this._classNames);}
addClassName(className)
{if(this._classNames.includes(className))
return;this._classNames.push(className);if(this._listItemNode)
this._listItemNode.classList.add(className);}
removeClassName(className)
{if(!this._classNames.includes(className))
return;this._classNames.remove(className);if(this._listItemNode)
this._listItemNode.classList.remove(className);}
get mainTitle()
{return this._mainTitle;}
set mainTitle(x)
{x=x||"";if(this._mainTitle===x)
return;this._mainTitle=x;this._updateTitleElements();this.didChange();this.dispatchEventToListeners(WI.GeneralTreeElement.Event.MainTitleDidChange);}
get subtitle()
{return this._subtitle;}
set subtitle(x)
{x=x||"";if(this._subtitle===x)
return;this._subtitle=x;this._updateTitleElements();this.didChange();}
get status()
{return this._status;}
set status(x)
{x=x||"";if(this._status===x)
return;if(!this._statusElement){this._statusElement=document.createElement("div");this._statusElement.className=WI.GeneralTreeElement.StatusElementStyleClassName;}
this._status=x;this._updateStatusElement();}
get filterableData()
{return{text:[this.mainTitle,this.subtitle]};}
get tooltipHandledSeparately()
{return this._tooltipHandledSeparately;}
set tooltipHandledSeparately(x)
{this._tooltipHandledSeparately=!!x;}
createFoldersAsNeededForSubpath(subpath,comparator)
{if(!subpath)
return this;let components=subpath.split("/");if(components.length===1)
return this;if(!this._subpathFolderTreeElementMap)
this._subpathFolderTreeElementMap=new Map;let currentPath="";let currentFolderTreeElement=this;for(let component of components){if(component===components.lastValue)
break;if(currentPath)
currentPath+="/";currentPath+=component;let cachedFolder=this._subpathFolderTreeElementMap.get(currentPath);if(cachedFolder){currentFolderTreeElement=cachedFolder;continue;}
let newFolder=new WI.FolderTreeElement(component);this._subpathFolderTreeElementMap.set(currentPath,newFolder);let index=insertionIndexForObjectInListSortedByFunction(newFolder,currentFolderTreeElement.children,comparator||WI.ResourceTreeElement.compareFolderAndResourceTreeElements);currentFolderTreeElement.insertChild(newFolder,index);currentFolderTreeElement=newFolder;}
return currentFolderTreeElement;}
isEventWithinDisclosureTriangle(event)
{return event.target===this._disclosureButton;}
onattach()
{this._createElementsIfNeeded();this._updateTitleElements();this._listItemNode.classList.add("item");if(this._classNames)
this._listItemNode.classList.add(...this._classNames);this._listItemNode.appendChild(this._disclosureButton);this._listItemNode.appendChild(this._iconElement);if(this._statusElement)
this._listItemNode.appendChild(this._statusElement);this._listItemNode.appendChild(this._titlesElement);}
ondetach()
{}
onreveal()
{if(this._listItemNode)
this._listItemNode.scrollIntoViewIfNeeded(false);} 
callFirstAncestorFunction(functionName,args)
{var currentNode=this.parent;while(currentNode){if(typeof currentNode[functionName]==="function"){currentNode[functionName].apply(currentNode,args);break;}
currentNode=currentNode.parent;}}
customTitleTooltip()
{} 
_createElementsIfNeeded()
{if(this._createdElements)
return;this._disclosureButton=document.createElement("button");this._disclosureButton.className=WI.GeneralTreeElement.DisclosureButtonStyleClassName;
this._disclosureButton.tabIndex=-1;this._iconElement=document.createElement("img");this._iconElement.className=WI.GeneralTreeElement.IconElementStyleClassName;this._titlesElement=document.createElement("div");this._titlesElement.className=WI.GeneralTreeElement.TitlesElementStyleClassName;this._mainTitleElement=document.createElement("span");this._mainTitleElement.className=WI.GeneralTreeElement.MainTitleElementStyleClassName;this._titlesElement.appendChild(this._mainTitleElement);this._createdElements=true;}
_createSubtitleElementIfNeeded()
{if(this._subtitleElement)
return;this._subtitleElement=document.createElement("span");this._subtitleElement.className=WI.GeneralTreeElement.SubtitleElementStyleClassName;this._titlesElement.appendChild(this._subtitleElement);}
_updateTitleElements()
{if(!this._createdElements)
return;if(typeof this._mainTitle==="string"){if(this._mainTitleElement.textContent!==this._mainTitle)
this._mainTitleElement.textContent=this._mainTitle;}else if(this._mainTitle instanceof Node){this._mainTitleElement.removeChildren();this._mainTitleElement.appendChild(this._mainTitle);if(this._mainTitle instanceof DocumentFragment)
this._mainTitle=this._mainTitleElement.textContent;}
if(typeof this._subtitle==="string"&&this._subtitle){this._createSubtitleElementIfNeeded();if(this._subtitleElement.textContent!==this._subtitle)
this._subtitleElement.textContent=this._subtitle;this._titlesElement.classList.remove(WI.GeneralTreeElement.NoSubtitleStyleClassName);}else if(this._subtitle instanceof Node){this._createSubtitleElementIfNeeded();this._subtitleElement.removeChildren();this._subtitleElement.appendChild(this._subtitle);if(this._subtitle instanceof DocumentFragment)
this._subtitle=this._subtitleElement.textContent;this._titlesElement.classList.remove(WI.GeneralTreeElement.NoSubtitleStyleClassName);}else{if(this._subtitleElement)
this._subtitleElement.textContent="";this._titlesElement.classList.add(WI.GeneralTreeElement.NoSubtitleStyleClassName);}
if(!this.tooltip&&!this._tooltipHandledSeparately)
this._updateTitleTooltip();}
_updateTitleTooltip()
{if(!this._listItemNode)
return;let tooltip=this.customTitleTooltip();if(!tooltip){let mainTitleText=this._mainTitleElement.textContent;let subtitleText=this._subtitleElement?this._subtitleElement.textContent:"";let large=this.treeOutline&&this.treeOutline.large;if(mainTitleText&&subtitleText)
tooltip=mainTitleText+(large?"\n":" \u2014 ")+subtitleText;else if(mainTitleText)
tooltip=mainTitleText;else
tooltip=subtitleText;}
this._listItemNode.title=tooltip;}
_updateStatusElement()
{if(!this._statusElement)
return;if(!this._statusElement.parentNode&&this._listItemNode)
this._listItemNode.insertBefore(this._statusElement,this._titlesElement);if(this._status instanceof Node){this._statusElement.removeChildren();this._statusElement.appendChild(this._status);}else
this._statusElement.textContent=this._status;}};WI.GeneralTreeElement.DisclosureButtonStyleClassName="disclosure-button";WI.GeneralTreeElement.IconElementStyleClassName="icon";WI.GeneralTreeElement.StatusElementStyleClassName="status";WI.GeneralTreeElement.TitlesElementStyleClassName="titles";WI.GeneralTreeElement.MainTitleElementStyleClassName="title";WI.GeneralTreeElement.SubtitleElementStyleClassName="subtitle";WI.GeneralTreeElement.NoSubtitleStyleClassName="no-subtitle";WI.GeneralTreeElement.Event={MainTitleDidChange:"general-tree-element-main-title-did-change"};WI.GroupNavigationItem=class GroupNavigationItem extends WI.NavigationItem
{constructor(navigationItems)
{super();this._needsUpdate=false;this.navigationItems=navigationItems||[];} 
get navigationItems()
{return this._navigationItems;}
set navigationItems(items)
{this._navigationItems=items;this._needsUpdate=true;}
get hidden()
{return super.hidden||this._navigationItems.every((item)=>item.hidden);}
set hidden(flag)
{super.hidden=flag;}
get width()
{this._updateItems();return super.width;}
get minimumWidth()
{this._updateItems();return this._navigationItems.reduce((total,item)=>total+item.minimumWidth,0);} 
get additionalClassNames()
{return["group"];}
update(options={})
{super.update(options);this._updateItems();for(let item of this._navigationItems)
item.update(options);}
didAttach(navigationBar)
{super.didAttach(navigationBar);this._updateItems();for(let item of this._navigationItems)
item.didAttach(navigationBar);}
didDetach()
{for(let item of this._navigationItems)
item.didDetach();super.didDetach();} 
_updateItems()
{if(!this._needsUpdate)
return;this._needsUpdate=false;this.element.removeChildren();for(let item of this._navigationItems){this.element.appendChild(item.element);}}};WI.NavigationSidebarPanel=class NavigationSidebarPanel extends WI.SidebarPanel
{constructor(identifier,displayName,shouldAutoPruneStaleTopLevelResourceTreeElements,wantsTopOverflowShadow)
{super(identifier,displayName);this.element.classList.add("navigation");this._updateContentOverflowShadowVisibilityDebouncer=new Debouncer(()=>{this._updateContentOverflowShadowVisibility();});this._boundUpdateContentOverflowShadowVisibilitySoon=(event)=>{this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);};this.contentView.element.addEventListener("scroll",this._boundUpdateContentOverflowShadowVisibilitySoon);this._contentTreeOutlineGroup=new WI.TreeOutlineGroup;this._contentTreeOutline=this.createContentTreeOutline();this._filterBar=new WI.FilterBar;this._filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._filterDidChange,this);this.element.appendChild(this._filterBar.element);this._bottomOverflowShadowElement=document.createElement("div");this._bottomOverflowShadowElement.className=WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName;this.element.appendChild(this._bottomOverflowShadowElement);if(wantsTopOverflowShadow){this._topOverflowShadowElement=this.element.appendChild(document.createElement("div"));this._topOverflowShadowElement.classList.add(WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName,"top");}
window.addEventListener("resize",this._boundUpdateContentOverflowShadowVisibilitySoon);this._filtersSetting=new WI.Setting(identifier+"-navigation-sidebar-filters",{});this._filterBar.filters=this._filtersSetting.value;this._emptyContentPlaceholderElements=new Map;this._emptyFilterResults=new Set;this._shouldAutoPruneStaleTopLevelResourceTreeElements=shouldAutoPruneStaleTopLevelResourceTreeElements||false;if(this._shouldAutoPruneStaleTopLevelResourceTreeElements){WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._checkForStaleResources,this);WI.Frame.addEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._checkForStaleResources,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasRemoved,this._checkForStaleResources,this);}
this._pendingViewStateCookie=null;this._restoringState=false;} 
get filterBar(){return this._filterBar;}
get hasActiveFilters(){return this._filterBar.hasActiveFilters();}
closed()
{window.removeEventListener("resize",this._boundUpdateContentOverflowShadowVisibilitySoon);if(this._shouldAutoPruneStaleTopLevelResourceTreeElements){WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._checkForStaleResources,this);WI.Frame.removeEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._checkForStaleResources,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasRemoved,this._checkForStaleResources,this);}}
get contentBrowser()
{return this._contentBrowser;}
set contentBrowser(contentBrowser)
{this._contentBrowser=contentBrowser||null;}
get contentTreeOutline()
{return this._contentTreeOutline;}
get contentTreeOutlines()
{return Array.from(this._contentTreeOutlineGroup);}
get currentRepresentedObject()
{if(!this._contentBrowser)
return null;return this._contentBrowser.currentRepresentedObjects[0]||null;}
get restoringState()
{return this._restoringState;}
cancelRestoringState()
{this._pendingViewStateCookie=null;if(!this._finalAttemptToRestoreViewStateTimeout)
return;clearTimeout(this._finalAttemptToRestoreViewStateTimeout);this._finalAttemptToRestoreViewStateTimeout=undefined;}
createContentTreeOutline({ignoreCookieRestoration,suppressFiltering}={})
{let contentTreeOutline=new WI.TreeOutline;contentTreeOutline.allowsRepeatSelection=true;contentTreeOutline.element.classList.add(WI.NavigationSidebarPanel.ContentTreeOutlineElementStyleClassName);this._contentTreeOutlineGroup.add(contentTreeOutline);this.contentView.element.appendChild(contentTreeOutline.element);if(!suppressFiltering){contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementAdded,this._treeElementAddedOrChanged,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementDidChange,this._treeElementAddedOrChanged,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementDisclosureDidChanged,this._treeElementDisclosureDidChange,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementRemoved,this._handleTreeElementRemoved,this);}
contentTreeOutline[WI.NavigationSidebarPanel.IgnoreCookieRestoration]=ignoreCookieRestoration;contentTreeOutline[WI.NavigationSidebarPanel.SuppressFilteringSymbol]=suppressFiltering;return contentTreeOutline;}
suppressFilteringOnTreeElements(treeElements)
{for(let treeElement of treeElements)
treeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]=true;this.updateFilter();}
treeElementForRepresentedObject(representedObject)
{let treeElement=null;for(let treeOutline of this.contentTreeOutlines){treeElement=treeOutline.getCachedTreeElement(representedObject);if(treeElement)
break;}
return treeElement;}
showDefaultContentView()
{}
showDefaultContentViewForTreeElement(treeElement)
{if(!treeElement||!treeElement.representedObject)
return false;
if(!this.selected){let contentView=this.contentBrowser.contentViewForRepresentedObject(treeElement.representedObject);if(contentView&&contentView.parentContainer&&contentView.parentContainer!==this.contentBrowser.contentViewContainer)
return false;let selectedTabContentView=WI.tabBrowser.selectedTabContentView;if(selectedTabContentView&&selectedTabContentView.contentBrowser!==this.contentBrowser)
return false;}
let contentView=this.contentBrowser.showContentViewForRepresentedObject(treeElement.representedObject);if(!contentView)
return false;treeElement.revealAndSelect(true,false,true);return true;}
canShowRepresentedObject(representedObject)
{let selectedTabContentView=WI.tabBrowser.selectedTabContentView;return selectedTabContentView&&selectedTabContentView.canShowRepresentedObject(representedObject);}
saveStateToCookie(cookie)
{if(!this._contentBrowser)
return;let representedObject=this.currentRepresentedObject;if(!representedObject)
return;cookie[WI.TypeIdentifierCookieKey]=representedObject.constructor.TypeIdentifier;if(representedObject.saveIdentityToCookie){representedObject.saveIdentityToCookie(cookie);return;}
console.error("NavigationSidebarPanel representedObject is missing a saveIdentityToCookie implementation.",representedObject);}
restoreStateFromCookie(cookie,relaxedMatchDelay)
{this._pendingViewStateCookie=cookie;this._restoringState=true;this._checkOutlinesForPendingViewStateCookie();if(this._finalAttemptToRestoreViewStateTimeout)
clearTimeout(this._finalAttemptToRestoreViewStateTimeout);if(relaxedMatchDelay===0)
return;function finalAttemptToRestoreViewStateFromCookie()
{this._finalAttemptToRestoreViewStateTimeout=undefined;this._checkOutlinesForPendingViewStateCookie(true);this._pendingViewStateCookie=null;this._restoringState=false;}

this._finalAttemptToRestoreViewStateTimeout=setTimeout(finalAttemptToRestoreViewStateFromCookie.bind(this),relaxedMatchDelay);}
showEmptyContentPlaceholder(message,treeOutline)
{treeOutline=treeOutline||this._contentTreeOutline;let emptyContentPlaceholderElement=this._emptyContentPlaceholderElements.get(treeOutline);if(emptyContentPlaceholderElement)
emptyContentPlaceholderElement.remove();emptyContentPlaceholderElement=message instanceof Node?message:WI.createMessageTextView(message);this._emptyContentPlaceholderElements.set(treeOutline,emptyContentPlaceholderElement);let emptyContentPlaceholderParentElement=treeOutline.element.parentNode;emptyContentPlaceholderParentElement.appendChild(emptyContentPlaceholderElement);this._updateContentOverflowShadowVisibilityDebouncer.force();return emptyContentPlaceholderElement;}
hideEmptyContentPlaceholder(treeOutline)
{treeOutline=treeOutline||this._contentTreeOutline;let emptyContentPlaceholderElement=this._emptyContentPlaceholderElements.get(treeOutline);if(!emptyContentPlaceholderElement||!emptyContentPlaceholderElement.parentNode)
return;emptyContentPlaceholderElement.remove();this._emptyContentPlaceholderElements.delete(treeOutline);this._updateContentOverflowShadowVisibilityDebouncer.force();}
updateEmptyContentPlaceholder(message,treeOutline)
{treeOutline=treeOutline||this._contentTreeOutline;if(!treeOutline.children.length){this.showEmptyContentPlaceholder(message,treeOutline);}else if(!this._emptyFilterResults.has(treeOutline)){this.hideEmptyContentPlaceholder(treeOutline);}}
updateFilter()
{let filters=this._filterBar.filters;this._textFilterRegex=filters.text?WI.SearchUtilities.filterRegExpForString(filters.text,WI.SearchUtilities.defaultSettings):null;this._filtersSetting.value=filters;this._filterFunctions=filters.functions;this._filterBar.invalid=filters.text&&!this._textFilterRegex;let dontPopulate=!this._filterBar.hasActiveFilters()&&!this.shouldFilterPopulate();for(let treeOutline of this.contentTreeOutlines){if(treeOutline.hidden||treeOutline[WI.NavigationSidebarPanel.SuppressFilteringSymbol])
continue;let currentTreeElement=treeOutline.children[0];while(currentTreeElement&&!currentTreeElement.root){if(!currentTreeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]){const currentTreeElementWasHidden=currentTreeElement.hidden;this.applyFiltersToTreeElement(currentTreeElement);if(currentTreeElementWasHidden!==currentTreeElement.hidden)
this._treeElementWasFiltered(currentTreeElement);}
currentTreeElement=currentTreeElement.traverseNextTreeElement(false,null,dontPopulate);}
this._checkForEmptyFilterResults(treeOutline);}
this._updateContentOverflowShadowVisibilityDebouncer.force();}
resetFilter()
{this._filterBar.clear();}
shouldFilterPopulate()
{return this.hasCustomFilters();}
hasCustomFilters()
{return false;}
matchTreeElementAgainstCustomFilters(treeElement)
{return true;}
matchTreeElementAgainstFilterFunctions(treeElement)
{if(!this._filterFunctions||!this._filterFunctions.length)
return true;for(var filterFunction of this._filterFunctions){if(filterFunction(treeElement))
return true;}
return false;}
applyFiltersToTreeElement(treeElement)
{if(!this._filterBar.hasActiveFilters()&&!this.hasCustomFilters()){treeElement.hidden=false;if(treeElement.expanded&&treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]){treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]=false;treeElement.collapse();}
return;}
var filterableData=treeElement.filterableData||{};var flags={expandTreeElement:false};var filterRegex=this._textFilterRegex;function matchTextFilter(inputs)
{if(!inputs||!filterRegex)
return true;for(var input of inputs){if(!input)
continue;if(filterRegex.test(input)){flags.expandTreeElement=true;return true;}}
return false;}
function makeVisible()
{treeElement.hidden=false;var currentAncestor=treeElement.parent;while(currentAncestor&&!currentAncestor.root){currentAncestor.hidden=false;if(flags.expandTreeElement&&!currentAncestor.expanded){currentAncestor.__wasExpandedDuringFiltering=true;currentAncestor.expand();}
currentAncestor=currentAncestor.parent;}}
let suppressFiltering=treeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol];if(suppressFiltering||(matchTextFilter(filterableData.text)&&this.matchTreeElementAgainstFilterFunctions(treeElement,flags)&&this.matchTreeElementAgainstCustomFilters(treeElement,flags))){makeVisible();if(!flags.expandTreeElement&&treeElement.expanded&&treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]){treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]=false;treeElement.collapse();}
return;}
treeElement.hidden=true;}
attached()
{super.attached();this._updateContentOverflowShadowVisibilityDebouncer.force();if(this._contentBrowser&&!this._contentBrowser.currentContentView)
this.showDefaultContentView();} 
pruneStaleResourceTreeElements()
{if(this._checkForStaleResourcesTimeoutIdentifier){clearTimeout(this._checkForStaleResourcesTimeoutIdentifier);this._checkForStaleResourcesTimeoutIdentifier=undefined;}
for(let contentTreeOutline of this.contentTreeOutlines){
for(let i=contentTreeOutline.children.length-1;i>=0;--i){let treeElement=contentTreeOutline.children[i];if(!(treeElement instanceof WI.ResourceTreeElement))
continue;let resource=treeElement.resource;if(resource.localResourceOverride)
continue;if(!resource.parentFrame||resource.parentFrame.isDetached())
contentTreeOutline.removeChildAtIndex(i,true,true);}}} 
_updateContentOverflowShadowVisibility()
{if(!this.visible)
return;let scrollHeight=this.contentView.element.scrollHeight;let offsetHeight=this.contentView.element.offsetHeight;if(scrollHeight<offsetHeight){if(this._topOverflowShadowElement)
this._topOverflowShadowElement.style.opacity=0;this._bottomOverflowShadowElement.style.opacity=0;return;}
let edgeThreshold=1;let scrollTop=this.contentView.element.scrollTop;let topCoverage=Math.min(scrollTop,edgeThreshold);let bottomCoverage=Math.max(0,(offsetHeight+scrollTop)-(scrollHeight-edgeThreshold));if(this._topOverflowShadowElement)
this._topOverflowShadowElement.style.opacity=(topCoverage/edgeThreshold).toFixed(1);this._bottomOverflowShadowElement.style.opacity=(1-(bottomCoverage/edgeThreshold)).toFixed(1);}
_checkForEmptyFilterResults(treeOutline)
{if(treeOutline[WI.NavigationSidebarPanel.SuppressFilteringSymbol])
return;if(!treeOutline.children.length)
return;let filterableTreeElementFound=false;let unfilteredTreeElementFound=false;let currentTreeElement=treeOutline.children[0];while(currentTreeElement){let suppressFilteringForTreeElement=currentTreeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol];if(!suppressFilteringForTreeElement){filterableTreeElementFound=true;if(!currentTreeElement.hidden){unfilteredTreeElementFound=true;break;}}
currentTreeElement=currentTreeElement.nextSibling;}
if(unfilteredTreeElementFound||!filterableTreeElementFound){this.hideEmptyContentPlaceholder(treeOutline);this._emptyFilterResults.delete(treeOutline);return;}
let message=WI.createMessageTextView(WI.UIString("No Filter Results"));let buttonElement=message.appendChild(document.createElement("button"));buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",()=>{this.resetFilter();});this.showEmptyContentPlaceholder(message,treeOutline);this._emptyFilterResults.add(treeOutline);}
_filterDidChange()
{this.updateFilter();}
_treeElementAddedOrChanged(event)
{var dontPopulate=!this._filterBar.hasActiveFilters()&&!this.shouldFilterPopulate();let treeElement=event.data.element;let currentTreeElement=treeElement;while(currentTreeElement&&!currentTreeElement.root){if(!currentTreeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]){const currentTreeElementWasHidden=currentTreeElement.hidden;this.applyFiltersToTreeElement(currentTreeElement);if(currentTreeElementWasHidden!==currentTreeElement.hidden)
this._treeElementWasFiltered(currentTreeElement);}
currentTreeElement=currentTreeElement.traverseNextTreeElement(false,treeElement,dontPopulate);}
this._checkForEmptyFilterResults(event.target);if(this.visible)
this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);if(this.selected&&!treeElement.treeOutline[WI.NavigationSidebarPanel.IgnoreCookieRestoration])
this._checkElementsForPendingViewStateCookie([treeElement]);}
_treeElementDisclosureDidChange(event)
{this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);}
_handleTreeElementRemoved(event)
{this._checkForEmptyFilterResults(event.target);if(this.visible)
this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);}
_checkForStaleResourcesIfNeeded()
{if(!this._checkForStaleResourcesTimeoutIdentifier||!this._shouldAutoPruneStaleTopLevelResourceTreeElements)
return;this.pruneStaleResourceTreeElements();}
_checkForStaleResources(event)
{if(this._checkForStaleResourcesTimeoutIdentifier)
return;this._checkForStaleResourcesTimeoutIdentifier=setTimeout(this.pruneStaleResourceTreeElements.bind(this));}
_isTreeElementWithoutRepresentedObject(treeElement)
{return treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.DatabaseHostTreeElement||treeElement instanceof WI.IndexedDatabaseHostTreeElement||treeElement instanceof WI.ApplicationCacheManifestTreeElement||treeElement instanceof WI.ThreadTreeElement||treeElement instanceof WI.IdleTreeElement||treeElement instanceof WI.DOMBreakpointTreeElement||treeElement instanceof WI.EventBreakpointTreeElement||treeElement instanceof WI.URLBreakpointTreeElement||treeElement instanceof WI.CSSStyleSheetTreeElement||typeof treeElement.representedObject==="string"||treeElement.representedObject instanceof String;}
_checkOutlinesForPendingViewStateCookie(matchTypeOnly)
{if(!this._pendingViewStateCookie)
return;this._checkForStaleResourcesIfNeeded();var visibleTreeElements=[];this.contentTreeOutlines.forEach(function(outline){if(outline[WI.NavigationSidebarPanel.IgnoreCookieRestoration])
return;var currentTreeElement=outline.hasChildren?outline.children[0]:null;while(currentTreeElement){visibleTreeElements.push(currentTreeElement);currentTreeElement=currentTreeElement.traverseNextTreeElement(false,null,false);}});this._checkElementsForPendingViewStateCookie(visibleTreeElements,matchTypeOnly);}
_checkElementsForPendingViewStateCookie(treeElements,matchTypeOnly)
{if(!this._pendingViewStateCookie)
return;var cookie=this._pendingViewStateCookie;function treeElementMatchesCookie(treeElement)
{if(this._isTreeElementWithoutRepresentedObject(treeElement))
return false;var representedObject=treeElement.representedObject;if(!representedObject)
return false;var typeIdentifier=cookie[WI.TypeIdentifierCookieKey];if(typeIdentifier!==representedObject.constructor.TypeIdentifier)
return false;if(matchTypeOnly)
return!!typeIdentifier;var candidateObjectCookie={};if(representedObject.saveIdentityToCookie)
representedObject.saveIdentityToCookie(candidateObjectCookie);var candidateCookieKeys=Object.keys(candidateObjectCookie);return candidateCookieKeys.length&&candidateCookieKeys.every((key)=>candidateObjectCookie[key]===cookie[key]);}
var matchedElement=null;treeElements.some((element)=>{if(treeElementMatchesCookie.call(this,element)){matchedElement=element;return true;}
return false;});if(matchedElement){let didShowContentView=this.showDefaultContentViewForTreeElement(matchedElement);if(!didShowContentView)
return;this._pendingViewStateCookie=null;
setTimeout(()=>{this._restoringState=false;},0);if(this._finalAttemptToRestoreViewStateTimeout){clearTimeout(this._finalAttemptToRestoreViewStateTimeout);this._finalAttemptToRestoreViewStateTimeout=undefined;}}}
_treeElementWasFiltered(treeElement)
{if(treeElement.selected||treeElement.hidden)
return;let representedObject=this.currentRepresentedObject;if(!representedObject||treeElement.representedObject!==representedObject)
return;const omitFocus=true;const selectedByUser=false;const suppressNotification=true;treeElement.revealAndSelect(omitFocus,selectedByUser,suppressNotification);}};WI.NavigationSidebarPanel.IgnoreCookieRestoration=Symbol("ignore-cookie-restoration");WI.NavigationSidebarPanel.SuppressFilteringSymbol=Symbol("suppress-filtering");WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol=Symbol("was-expanded-during-filtering");WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName="overflow-shadow";WI.NavigationSidebarPanel.ContentTreeOutlineElementStyleClassName="navigation-sidebar-panel-content-tree-outline";WI.PinnedTabBarItem=class PinnedTabBarItem extends WI.TabBarItem
{constructor(representedObject,image,displayName,title)
{super(representedObject,image,displayName,title);this.element.classList.add("pinned");} 
static fromTabContentView(tabContentView)
{let{image,displayName,title}=tabContentView.tabInfo();return new WI.PinnedTabBarItem(tabContentView,image,displayName,title);}};WI.ResourceContentView=class ResourceContentView extends WI.ContentView
{constructor(resource,styleClassName)
{super(resource);this._resource=resource;this.element.classList.add(styleClassName,"resource");this._spinnerTimeout=setTimeout(()=>{
let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._spinnerTimeout=undefined;},100);this.element.addEventListener("click",this._mouseWasClicked.bind(this),false);resource.requestContent().then(this._contentAvailable.bind(this)).catch(this.showGenericErrorMessage.bind(this));if(!this.managesOwnIssues){WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);var issues=WI.consoleManager.issuesForSourceCode(resource);for(var i=0;i<issues.length;++i)
this.addIssue(issues[i]);}
if(WI.NetworkManager.supportsOverridingResponses()){if(resource.localResourceOverride){this._localResourceOverrideBannerView=new WI.LocalResourceOverrideLabelView(resource.localResourceOverride);this._importLocalResourceOverrideButtonNavigationItem=new WI.ButtonNavigationItem("import-local-resource-override",WI.UIString("Import"),"Images/Import.svg",15,15);this._importLocalResourceOverrideButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._importLocalResourceOverrideButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._importLocalResourceOverrideButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportLocalResourceOverride,this);this._removeLocalResourceOverrideButtonNavigationItem=new WI.ButtonNavigationItem("remove-local-resource-override",WI.UIString("Delete Local Override"),"Images/NavigationItemTrash.svg",15,15);this._removeLocalResourceOverrideButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleRemoveLocalResourceOverride,this);this._removeLocalResourceOverrideButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;}else{this._localResourceOverrideBannerView=new WI.LocalResourceOverrideWarningView(resource);this._createLocalResourceOverrideButtonNavigationItem=new WI.ButtonNavigationItem("create-local-resource-override",this.createLocalResourceOverrideTooltip,"Images/NavigationItemNetworkOverride.svg",13,14);this._createLocalResourceOverrideButtonNavigationItem.enabled=false;this._createLocalResourceOverrideButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;if(WI.NetworkManager.supportsOverridingRequests())
WI.addMouseDownContextMenuHandlers(this._createLocalResourceOverrideButtonNavigationItem.element,this._populateCreateLocalResourceOverrideContextMenu.bind(this));else
this._createLocalResourceOverrideButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCreateLocalResourceOverride,this);}
WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideChanged,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideChanged,this);}} 
get resource(){return this._resource;}
get navigationItems()
{let items=[];if(this._importLocalResourceOverrideButtonNavigationItem)
items.push(this._importLocalResourceOverrideButtonNavigationItem,new WI.DividerNavigationItem);if(this._removeLocalResourceOverrideButtonNavigationItem)
items.push(this._removeLocalResourceOverrideButtonNavigationItem);if(this._createLocalResourceOverrideButtonNavigationItem)
items.push(this._createLocalResourceOverrideButtonNavigationItem);return items;}
get supportsSave()
{return this._resource.finished;}
get saveData()
{let saveData={url:this._resource.url,content:this._resource.content,};if(this._resource.urlComponents.path==="/"){let extension=WI.fileExtensionForMIMEType(this._resource.mimeType);if(extension)
saveData.suggestedName=`index.${extension}`;}
return saveData;}
contentAvailable(content,base64Encoded)
{throw WI.NotImplementedError.subclassMustOverride();}
get createLocalResourceOverrideTooltip()
{return WI.UIString("Click to import a file and create a Local Override\nShift-click to create a Local Override from this content");}
requestLocalResourceOverrideInitialContent()
{return new Promise((resolve,reject)=>{WI.FileUtilities.import(async(fileList)=>{this._getContentForLocalResourceOverrideFromFile(fileList[0],({mimeType,base64Encoded,content})=>{resolve({mimeType,base64Encoded,content});});});});}
showGenericNoContentMessage()
{this.showMessage(WI.UIString("Resource has no content."));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);}
showNoCachedContentMessage()
{this.showMessage(WI.UIString("Resource has no cached content.","Resource has no cached content. @ Resource Preview","An error message shown when there is no cached content for a HTTP 304 Not Modified resource response."));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);}
showGenericErrorMessage()
{this._contentError(WI.UIString("An error occurred trying to load the resource."));}
showMessage(message)
{this.element.removeChildren();this.element.appendChild(WI.createMessageTextView(message));}
addIssue(issue)
{this.element.removeChildren();this.element.appendChild(WI.createMessageTextView(issue.text,issue.level===WI.IssueMessage.Level.Error));}
closed()
{super.closed();if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideChanged,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideChanged,this);}
if(!this.managesOwnIssues)
WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);} 
removeLoadingIndicator()
{if(this._spinnerTimeout){clearTimeout(this._spinnerTimeout);this._spinnerTimeout=undefined;}
this.removeAllSubviews();if(this._localResourceOverrideBannerView)
this.addSubview(this._localResourceOverrideBannerView);} 
_contentAvailable(parameters)
{if(parameters.error){if(parameters.sourceCode.statusCode==304&&parameters.reason==="Missing content of resource for given requestId"){this.showNoCachedContentMessage();return;}
this._contentError(parameters.error);return;}
if(parameters.message){this.showMessage(parameters.message);return;}

if(this._hasContent())
return;if(!parameters.sourceCode.content&&!parameters.sourceCode.mimeType){this.showGenericNoContentMessage();return;}
this.contentAvailable(parameters.sourceCode.content,parameters.base64Encoded);if(this._createLocalResourceOverrideButtonNavigationItem)
this._createLocalResourceOverrideButtonNavigationItem.enabled=WI.networkManager.canBeOverridden(this._resource);}
_contentError(error)
{if(this._hasContent())
return;this.removeLoadingIndicator();this.element.appendChild(WI.createMessageTextView(error,true));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);}
_hasContent()
{return this.element.hasChildNodes()&&!this.element.querySelector(".indeterminate-progress-spinner");}
_issueWasAdded(event)
{var issue=event.data.issue;if(!WI.ConsoleManager.issueMatchSourceCode(issue,this._resource))
return;this.addIssue(issue);}
async _getContentForLocalResourceOverrideFromFile(file,callback)
{let mimeType=file.type||WI.mimeTypeForFileExtension(WI.fileExtensionForFilename(file.name));if(WI.shouldTreatMIMETypeAsText(mimeType)){await WI.FileUtilities.readText(file,async({text})=>{await callback({mimeType,base64Encoded:false,content:text,});});}else{await WI.FileUtilities.readData(file,async({mimeType,base64Encoded,content})=>{await callback({mimeType,base64Encoded,content});});}}
async _createAndShowLocalResourceOverride(type,{requestInitialContent}={})
{let initialContent=requestInitialContent?await this.requestLocalResourceOverrideInitialContent():{};let localResourceOverride=await this._resource.createLocalResourceOverride(type,initialContent);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride);}
_populateCreateLocalResourceOverrideContextMenu(contextMenu,event)
{if(!this._createLocalResourceOverrideButtonNavigationItem.enabled)
return;contextMenu.appendItem(WI.UIString("Create Request Local Override"),()=>{this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Request);});contextMenu.appendItem(WI.UIString("Create Response Local Override"),()=>{this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response,{requestInitialContent:!event.shiftKey,});});}
_handleCreateLocalResourceOverride(event)
{let{nativeEvent}=event.data;this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response,{requestInitialContent:!nativeEvent.shiftKey,});}
_handleImportLocalResourceOverride(event)
{let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this.resource.url)[0];WI.FileUtilities.import(async(fileList)=>{await this._getContentForLocalResourceOverrideFromFile(fileList[0],({mimeType,base64Encoded,content})=>{let revision=localResourceOverride.localResource.editableRevision;revision.updateRevisionContent(content,{base64Encoded,mimeType});});if(!this._resource.localResourceOverride)
WI.showLocalResourceOverride(localResourceOverride);});}
_handleRemoveLocalResourceOverride(event)
{let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this._resource.url)[0];WI.networkManager.removeLocalResourceOverride(localResourceOverride);}
_handleLocalResourceOverrideChanged(event)
{let{localResourceOverride}=event.data;if(!localResourceOverride.matches(this._resource.url))
return;if(this._createLocalResourceOverrideButtonNavigationItem)
this._createLocalResourceOverrideButtonNavigationItem.enabled=WI.networkManager.canBeOverridden(this._resource);}
_mouseWasClicked(event)
{WI.handlePossibleLinkClick(event,this._resource.parentFrame);}};WI.ResourceContentView.Event={ContentError:"resource-content-view-content-error",};WI.TabContentView=class TabContentView extends WI.ContentView
{constructor(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors}={})
{super(null);this._identifier=tabInfo.identifier;this._navigationSidebarPanelConstructor=navigationSidebarPanelConstructor||null;this._detailsSidebarPanelConstructors=detailsSidebarPanelConstructors||[];this._navigationSidebarCollapsedSetting=new WI.Setting(this._identifier+"-navigation-sidebar-collapsed",false);this._navigationSidebarWidthSetting=new WI.Setting(this._identifier+"-navigation-sidebar-width",WI.TabContentView.DefaultSidebarWidth);this._detailsSidebarCollapsedSetting=new WI.Setting(this._identifier+"-details-sidebar-collapsed",!this.detailsSidebarExpandedByDefault);this._detailsSidebarSelectedPanelSetting=new WI.Setting(this._identifier+"-details-sidebar-selected-panel",null);this._detailsSidebarWidthSetting=new WI.Setting(this._identifier+"-details-sidebar-widths",{});this._cookieSetting=new WI.Setting(this._identifier+"-tab-cookie",{});this.element.classList.add("tab",this._identifier);}
static isTabAllowed()
{return true;}
static shouldPinTab()
{return false;}
static shouldSaveTab()
{return true;} 
get type()
{return null;}
get identifier()
{return this._identifier;}
get tabBarItem()
{if(!this._tabBarItem)
this._tabBarItem=this.constructor.shouldPinTab()?WI.PinnedTabBarItem.fromTabContentView(this):WI.GeneralTabBarItem.fromTabContentView(this);return this._tabBarItem;}
get managesNavigationSidebarPanel()
{return false;}
get managesDetailsSidebarPanels()
{return false;}
get detailsSidebarExpandedByDefault()
{return false;}
showDetailsSidebarPanels()
{}
showRepresentedObject(representedObject,cookie)
{}
canShowRepresentedObject(representedObject)
{return false;}
get allowMultipleDetailSidebars()
{return false;}
tabInfo()
{return this.constructor.tabInfo();}
attached()
{super.attached();if(this._shouldRestoreStateWhenShown)
this.restoreStateFromCookie(WI.StateRestorationType.Delayed);}
restoreStateFromCookie(restorationType)
{if(!this.isAttached){this._shouldRestoreStateWhenShown=true;return;}
this._shouldRestoreStateWhenShown=false;var relaxMatchDelay=0;if(restorationType===WI.StateRestorationType.Load)
relaxMatchDelay=1000;else if(restorationType===WI.StateRestorationType.Navigation)
relaxMatchDelay=2000;let cookie=this._cookieSetting.value||{};if(this.navigationSidebarPanel)
this.navigationSidebarPanel.restoreStateFromCookie(cookie,relaxMatchDelay);this.restoreFromCookie(cookie);}
saveStateToCookie(cookie)
{if(this._shouldRestoreStateWhenShown)
return;cookie=cookie||{};if(this.navigationSidebarPanel)
this.navigationSidebarPanel.saveStateToCookie(cookie);this.saveToCookie(cookie);this._cookieSetting.value=cookie;}
get navigationSidebarPanel()
{if(!this._navigationSidebarPanelConstructor)
return null;if(!this._navigationSidebarPanel)
this._navigationSidebarPanel=new this._navigationSidebarPanelConstructor;return this._navigationSidebarPanel;}
get navigationSidebarCollapsedSetting(){return this._navigationSidebarCollapsedSetting;}
get navigationSidebarWidthSetting(){return this._navigationSidebarWidthSetting;}
get detailsSidebarPanels()
{if(!this._detailsSidebarPanels)
this._detailsSidebarPanels=this._detailsSidebarPanelConstructors.map((constructor)=>new constructor);return this._detailsSidebarPanels;}
get detailsSidebarCollapsedSetting(){return this._detailsSidebarCollapsedSetting;}
get detailsSidebarSelectedPanelSetting(){return this._detailsSidebarSelectedPanelSetting;}
get detailsSidebarWidthSetting(){return this._detailsSidebarWidthSetting;}};WI.TabContentView.DefaultSidebarWidth=300;WI.TextContentView=class TextContentView extends WI.ContentView
{constructor(string,mimeType,representedObject)
{super(representedObject||string);this.element.classList.add("text");this._textEditor=new WI.TextEditor;this._textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.FormattingDidChange,this._textEditorFormattingDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.MIMETypeChanged,this._handleTextEditorMIMETypeChanged,this);this.addSubview(this._textEditor);var toolTip=WI.UIString("Pretty print");var activatedToolTip=WI.UIString("Original formatting");this._prettyPrintButtonNavigationItem=new WI.ActivateButtonNavigationItem("pretty-print",toolTip,activatedToolTip,"Images/NavigationItemCurleyBraces.svg",13,13);this._prettyPrintButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrettyPrint,this);this._prettyPrintButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;var toolTipTypes=WI.UIString("Show type information");var activatedToolTipTypes=WI.UIString("Hide type information");this._showTypesButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-types",toolTipTypes,activatedToolTipTypes,"Images/NavigationItemTypes.svg",13,14);this._showTypesButtonNavigationItem.enabled=false;this._showTypesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;let toolTipCodeCoverage=WI.UIString("Fade unexecuted code");let activatedToolTipCodeCoverage=WI.UIString("Do not fade unexecuted code");this._codeCoverageButtonNavigationItem=new WI.ActivateButtonNavigationItem("code-coverage",toolTipCodeCoverage,activatedToolTipCodeCoverage,"Images/NavigationItemCodeCoverage.svg",13,14);this._codeCoverageButtonNavigationItem.enabled=false;this._codeCoverageButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._textEditor.readOnly=true;this._textEditor.mimeType=mimeType;this._textEditor.string=string;this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();} 
get textEditor()
{return this._textEditor;}
get navigationItems()
{return[this._prettyPrintButtonNavigationItem,this._showTypesButtonNavigationItem,this._codeCoverageButtonNavigationItem];}
revealPosition(position,textRangeToSelect,forceUnformatted)
{this._textEditor.revealPosition(position,textRangeToSelect,forceUnformatted);}
get supportsSave()
{return true;}
get saveData()
{return{content:this._textEditor.string,suggestedName:WI.UIString("Untitled")+".txt",forceSaveAs:true,};}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._textEditor.numberOfSearchResults;}
get hasPerformedSearch()
{return this._textEditor.currentSearchQuery!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._textEditor.automaticallyRevealFirstSearchResult=reveal;}
performSearch(query)
{this._textEditor.performSearch(query);}
searchCleared()
{this._textEditor.searchCleared();}
searchQueryWithSelection()
{return this._textEditor.searchQueryWithSelection();}
revealPreviousSearchResult(changeFocus)
{this._textEditor.revealPreviousSearchResult(changeFocus);}
revealNextSearchResult(changeFocus)
{this._textEditor.revealNextSearchResult(changeFocus);} 
_togglePrettyPrint(event)
{var activated=!this._prettyPrintButtonNavigationItem.activated;this._textEditor.updateFormattedState(activated);}
_textEditorFormattingDidChange(event)
{this._prettyPrintButtonNavigationItem.activated=this._textEditor.formatted;}
_handleTextEditorMIMETypeChanged(event)
{this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();}
_numberOfSearchResultsDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};WI.TimelineDataGrid=class TimelineDataGrid extends WI.DataGrid
{constructor(columns)
{super(columns);this.element.classList.add("timeline");this._sortDelegate=null;this._scopeBarColumns=[];for(var[identifier,column]of this.columns){var scopeBar=column.scopeBar;if(!scopeBar)
continue;this._scopeBarColumns.push(identifier);scopeBar.columnIdentifier=identifier;scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectedItemsDidChange,this);}
if(this._scopeBarColumns.length>1){console.error("Creating a TimelineDataGrid with more than one filterable column is not yet supported.");return;}
this.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridSelectedNodeChanged,this);this.addEventListener(WI.DataGrid.Event.SortChanged,this._sort,this);this.columnChooserEnabled=true;}
static createColumnScopeBar(prefix,map)
{prefix=prefix+"-timeline-data-grid-";var scopeBarItems=[];for(var[key,value]of map){var id=prefix+key;var item=new WI.ScopeBarItem(id,value);item.value=key;scopeBarItems.push(item);}
var allItem=new WI.ScopeBarItem(prefix+"type-all",WI.UIString("All"));scopeBarItems.unshift(allItem);return new WI.ScopeBar(prefix+"scope-bar",scopeBarItems,allItem,true);} 
get sortDelegate()
{return this._sortDelegate;}
set sortDelegate(delegate)
{delegate=delegate||null;if(this._sortDelegate===delegate)
return;this._sortDelegate=delegate;if(this.sortOrder!==WI.DataGrid.SortOrder.Indeterminate)
this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);}
reset()
{this.removeChildren();this._hidePopover();}
detached()
{this._hidePopover();super.detached();}
callFramePopoverAnchorElement()
{return null;}
shouldShowCallFramePopover()
{return false;}
addRowInSortOrder(dataGridNode,parentDataGridNode)
{parentDataGridNode=parentDataGridNode||this;if(this.sortColumnIdentifier){let insertionIndex=insertionIndexForObjectInListSortedByFunction(dataGridNode,parentDataGridNode.children,this._sortComparator.bind(this));parentDataGridNode.insertChild(dataGridNode,insertionIndex);}else
parentDataGridNode.appendChild(dataGridNode);}
shouldIgnoreSelectionEvent()
{return this._ignoreSelectionEvent||false;} 
dataGridNodeNeedsRefresh(dataGridNode)
{if(!this._dirtyDataGridNodes)
this._dirtyDataGridNodes=new Set;this._dirtyDataGridNodes.add(dataGridNode);if(this._scheduledDataGridNodeRefreshIdentifier)
return;this._scheduledDataGridNodeRefreshIdentifier=requestAnimationFrame(this._refreshDirtyDataGridNodes.bind(this));}
hasCustomFilters()
{return true;}
matchNodeAgainstCustomFilters(node)
{if(!super.matchNodeAgainstCustomFilters(node))
return false;for(let identifier of this._scopeBarColumns){let scopeBar=this.columns.get(identifier).scopeBar;if(!scopeBar||scopeBar.defaultItem.selected)
continue;let value=node.data[identifier];if(!scopeBar.selectedItems.some((scopeBarItem)=>scopeBarItem.value===value))
return false;}
return true;} 
_refreshDirtyDataGridNodes()
{if(this._scheduledDataGridNodeRefreshIdentifier){cancelAnimationFrame(this._scheduledDataGridNodeRefreshIdentifier);this._scheduledDataGridNodeRefreshIdentifier=undefined;}
if(!this._dirtyDataGridNodes)
return;let selectedNode=this.selectedNode;let sortComparator=this._sortComparator.bind(this);for(let dataGridNode of this._dirtyDataGridNodes){dataGridNode.refresh();if(!this.sortColumnIdentifier)
continue;if(dataGridNode===selectedNode)
this._ignoreSelectionEvent=true;if(dataGridNode.parent===this)
this.removeChild(dataGridNode);let insertionIndex=insertionIndexForObjectInListSortedByFunction(dataGridNode,this.children,sortComparator);this.insertChild(dataGridNode,insertionIndex);if(dataGridNode===selectedNode){selectedNode.revealAndSelect();this._ignoreSelectionEvent=false;}}
this._dirtyDataGridNodes=null;}
_sort()
{if(!this.children.length)
return;let sortColumnIdentifier=this.sortColumnIdentifier;if(!sortColumnIdentifier)
return;let selectedNode=this.selectedNode;this._ignoreSelectionEvent=true;
let parentDataGridNodes=[this];let currentDataGridNode=this.children[0];while(currentDataGridNode){if(currentDataGridNode.children.length)
parentDataGridNodes.push(currentDataGridNode);currentDataGridNode=currentDataGridNode.traverseNextNode(false,null,true);}
for(let parentDataGridNode of parentDataGridNodes){let childDataGridNodes=parentDataGridNode.children.slice();parentDataGridNode.removeChildren();childDataGridNodes.sort(this._sortComparator.bind(this));for(let dataGridNode of childDataGridNodes)
parentDataGridNode.appendChild(dataGridNode);}
if(selectedNode)
selectedNode.revealAndSelect();this._ignoreSelectionEvent=false;}
_sortComparator(node1,node2)
{var sortColumnIdentifier=this.sortColumnIdentifier;if(!sortColumnIdentifier)
return 0;var sortDirection=this.sortOrder===WI.DataGrid.SortOrder.Ascending?1:-1;if(this._sortDelegate&&typeof this._sortDelegate.dataGridSortComparator==="function"){let result=this._sortDelegate.dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2);if(typeof result==="number")
return result;}
var value1=node1.data[sortColumnIdentifier];var value2=node2.data[sortColumnIdentifier];if(typeof value1==="number"&&typeof value2==="number"){if(isNaN(value1)&&isNaN(value2))
return 0;if(isNaN(value1))
return-sortDirection;if(isNaN(value2))
return sortDirection;return(value1-value2)*sortDirection;}
if(typeof value1==="string"&&typeof value2==="string")
return value1.extendedLocaleCompare(value2)*sortDirection;if(value1 instanceof WI.CallFrame||value2 instanceof WI.CallFrame){value1=value1&&value1.functionName?value1.functionName:(value1&&value1.sourceCodeLocation?value1.sourceCodeLocation.sourceCode:"");value2=value2&&value2.functionName?value2.functionName:(value2&&value2.sourceCodeLocation?value2.sourceCodeLocation.sourceCode:"");}
if(value1 instanceof WI.SourceCode||value2 instanceof WI.SourceCode){value1=value1?value1.displayName||"":"";value2=value2?value2.displayName||"":"";}
if(value1 instanceof WI.SourceCodeLocation||value2 instanceof WI.SourceCodeLocation){value1=value1?value1.displayLocationString()||"":"";value2=value2?value2.displayLocationString()||"":"";}
return(value1<value2?-1:(value1>value2?1:0))*sortDirection;}
_scopeBarSelectedItemsDidChange(event)
{this.filterDidChange();}
_dataGridSelectedNodeChanged(event)
{if(!this.selectedNode){this._hidePopover();return;}
var record=this.selectedNode.record;if(!record||!record.callFrames||!record.callFrames.length){this._hidePopover();return;}
if(this.shouldShowCallFramePopover())
this._showPopoverForSelectedNodeSoon();}
_showPopoverForSelectedNodeSoon()
{if(this._showPopoverTimeout)
return;this._showPopoverTimeout=setTimeout(()=>{if(!this._popover){this._popover=new WI.Popover;this._popover.windowResizeHandler=()=>{this._updatePopoverForSelectedNode(false);};}
this._updatePopoverForSelectedNode(true);this._showPopoverTimeout=undefined;},WI.TimelineDataGrid.DelayedPopoverShowTimeout);}
_hidePopover()
{if(this._showPopoverTimeout){clearTimeout(this._showPopoverTimeout);this._showPopoverTimeout=undefined;}
if(this._popover)
this._popover.dismiss();if(this._hidePopoverContentClearTimeout)
clearTimeout(this._hidePopoverContentClearTimeout);this._hidePopoverContentClearTimeout=setTimeout(()=>{if(this._popoverCallStackTreeOutline)
this._popoverCallStackTreeOutline.removeChildren();},WI.TimelineDataGrid.DelayedPopoverHideContentClearTimeout);}
_updatePopoverForSelectedNode(updateContent)
{if(!this._popover||!this.selectedNode)
return;let targetPopoverElement=this.callFramePopoverAnchorElement();if(!targetPopoverElement)
return;let rect=WI.Rect.rectFromClientRect(targetPopoverElement.getBoundingClientRect());if(!rect.size.width&&!rect.size.height)
return;if(this._hidePopoverContentClearTimeout){clearTimeout(this._hidePopoverContentClearTimeout);this._hidePopoverContentClearTimeout=undefined;}
let targetFrame=rect.pad(2);let preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X];if(updateContent)
this._popover.presentNewContentWithFrame(this._createPopoverContent(),targetFrame,preferredEdges);else
this._popover.present(targetFrame,preferredEdges);}
_createPopoverContent()
{if(!this._popoverCallStackTreeOutline){this._popoverCallStackTreeOutline=new WI.TreeOutline;this._popoverCallStackTreeOutline.disclosureButtons=false;this._popoverCallStackTreeOutline.element.classList.add("timeline-data-grid");this._popoverCallStackTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._popoverCallStackTreeSelectionDidChange,this);}else
this._popoverCallStackTreeOutline.removeChildren();var callFrames=this.selectedNode.record.callFrames;for(var i=0;i<callFrames.length;++i){var callFrameTreeElement=new WI.CallFrameTreeElement(callFrames[i]);this._popoverCallStackTreeOutline.appendChild(callFrameTreeElement);}
let content=document.createElement("div");content.appendChild(this._popoverCallStackTreeOutline.element);return content;}
_popoverCallStackTreeSelectionDidChange(event)
{let treeElement=this._popoverCallStackTreeOutline.selectedTreeElement;if(!treeElement)
return;this._popover.dismiss();var callFrame=treeElement.callFrame;if(!callFrame.sourceCodeLocation)
return;WI.showSourceCodeLocation(callFrame.sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});}};WI.TimelineDataGrid.HasNonDefaultFilterStyleClassName="has-non-default-filter";WI.TimelineDataGrid.DelayedPopoverShowTimeout=250;WI.TimelineDataGrid.DelayedPopoverHideContentClearTimeout=500;WI.TimelineDataGridNode=class TimelineDataGridNode extends WI.DataGridNode
{constructor(records,{hasChildren,includesGraph,graphDataSource}={})
{super({},{hasChildren,copyable:false});this._records=records;this._includesGraph=includesGraph||false;this._graphDataSource=graphDataSource||null;this._cachedData=null;if(this._graphDataSource){this._graphContainerElement=document.createElement("div");this._timelineRecordBars=[];}} 
get records(){return this._records;}
get record()
{return this.records&&this.records.length?this.records[0]:null;}
get graphDataSource()
{return this._graphDataSource;}
get data()
{if(!this._graphDataSource)
return{};return{graph:this.record?this.record.startTime:0,};}
collapse()
{super.collapse();if(!this._graphDataSource||!this.revealed)
return;this.refreshGraph();}
expand()
{super.expand();if(!this._graphDataSource||!this.revealed)
return;this.refreshGraph();var childNode=this.children[0];while(childNode){if(childNode instanceof WI.TimelineDataGridNode)
childNode.refreshGraph();childNode=childNode.traverseNextNode(true,this);}}
createCellContent(columnIdentifier,cell)
{if(columnIdentifier==="graph"&&this._graphDataSource){this.needsGraphRefresh();return this._graphContainerElement;}
var value=this.data[columnIdentifier];if(!value)
return emDash;const options={useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};if(value instanceof WI.SourceCodeLocation){if(value.sourceCode instanceof WI.Resource){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(value.sourceCode));}else if(value.sourceCode instanceof WI.Script){if(value.sourceCode.url){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName);cell.classList.add(WI.Resource.Type.Script);}else
cell.classList.add(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);}else
console.error("Unknown SourceCode subclass.");value.populateLiveDisplayLocationTooltip(cell);var fragment=document.createDocumentFragment();fragment.appendChild(WI.createSourceCodeLocationLink(value,options));var titleElement=document.createElement("span");value.populateLiveDisplayLocationString(titleElement,"textContent");fragment.appendChild(titleElement);return fragment;}
if(value instanceof WI.CallFrame){var callFrame=value;var isAnonymousFunction=false;var functionName=callFrame.functionName;if(!functionName){functionName=WI.UIString("(anonymous function)");isAnonymousFunction=true;}
cell.classList.add(WI.CallFrameView.FunctionIconStyleClassName);var fragment=document.createDocumentFragment();let iconElement=document.createElement("div");iconElement.classList.add("icon");let sourceCode=callFrame.sourceCodeLocation?.sourceCode;if(sourceCode){callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(cell);fragment.appendChild(WI.createSourceCodeLocationLink(callFrame.sourceCodeLocation,options));if(isAnonymousFunction){if(sourceCode instanceof WI.Resource){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(sourceCode));if(sourceCode.responseSource===WI.Resource.ResponseSource.InspectorOverride)
iconElement.title=WI.UIString("This resource was loaded from a local override");}else if(sourceCode instanceof WI.Script){if(sourceCode.url){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName);cell.classList.add(WI.Resource.Type.Script);}else
cell.classList.add(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);}else
console.error("Unknown SourceCode subclass.");var titleElement=document.createElement("span");callFrame.sourceCodeLocation.populateLiveDisplayLocationString(titleElement,"textContent");fragment.appendChild(titleElement);}else{cell.classList.add(WI.CallFrameView.FunctionIconStyleClassName);fragment.append(functionName);var subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");callFrame.sourceCodeLocation.populateLiveDisplayLocationString(subtitleElement,"textContent");fragment.appendChild(subtitleElement);}
return fragment;}
fragment.append(iconElement,functionName);return fragment;}
if(value instanceof WI.DOMNode){cell.classList.add(WI.DOMTreeElementPathComponent.iconClassNameForNode(value));return WI.linkifyNodeReference(value);}
return super.createCellContent(columnIdentifier,cell);}
generateIconTitle(columnIdentifier)
{let value=this.data[columnIdentifier];if(value instanceof WI.SourceCodeLocation&&value.sourceCode instanceof WI.Resource&&value.sourceCode.responseSource===WI.Resource.ResponseSource.InspectorOverride)
return WI.UIString("This resource was loaded from a local override");return super.generateIconTitle(columnIdentifier);}
refresh()
{this._cachedData=null;if(this._graphDataSource&&this._includesGraph)
this.needsGraphRefresh();super.refresh();}
refreshGraph()
{if(!this._graphDataSource)
return;if(this._scheduledGraphRefreshIdentifier){cancelAnimationFrame(this._scheduledGraphRefreshIdentifier);this._scheduledGraphRefreshIdentifier=undefined;}
if(!this.revealed)
return;let secondsPerPixel=this._graphDataSource.secondsPerPixel;if(isNaN(secondsPerPixel))
return;var recordBarIndex=0;function createBar(records,renderMode)
{var timelineRecordBar=this._timelineRecordBars[recordBarIndex];if(!timelineRecordBar)
timelineRecordBar=this._timelineRecordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;}
timelineRecordBar.refresh(this._graphDataSource);if(!timelineRecordBar.element.parentNode){this._graphContainerElement.appendChild(timelineRecordBar.element);this.didAddRecordBar(timelineRecordBar);}
++recordBarIndex;}
function collectRecordsByType(records,recordsByTypeMap)
{for(var record of records){var typedRecords=recordsByTypeMap.get(record.type);if(!typedRecords){typedRecords=[];recordsByTypeMap.set(record.type,typedRecords);}
typedRecords.push(record);}}
var boundCreateBar=createBar.bind(this);if(this.expanded){WI.TimelineRecordBar.createCombinedBars(this.records,secondsPerPixel,this._graphDataSource,boundCreateBar);}else{var recordTypeMap=new Map;collectRecordsByType(this.records,recordTypeMap);var childNode=this.children[0];while(childNode){if(childNode instanceof WI.TimelineDataGridNode)
collectRecordsByType(childNode.records,recordTypeMap);childNode=childNode.traverseNextNode(false,this);}
for(var records of recordTypeMap.values())
WI.TimelineRecordBar.createCombinedBars(records,secondsPerPixel,this._graphDataSource,boundCreateBar);}
for(;recordBarIndex<this._timelineRecordBars.length;++recordBarIndex){this._timelineRecordBars[recordBarIndex].element.remove();this.didRemoveRecordBar(this._timelineRecordBars[recordBarIndex]);this._timelineRecordBars[recordBarIndex].records=null;}}
needsGraphRefresh()
{if(!this.revealed){var ancestor=this;while(ancestor&&!ancestor.root){if(ancestor.revealed&&ancestor instanceof WI.TimelineDataGridNode){ancestor.needsGraphRefresh();return;}
ancestor=ancestor.parent;}
return;}
if(!this._graphDataSource||this._scheduledGraphRefreshIdentifier)
return;this._scheduledGraphRefreshIdentifier=requestAnimationFrame(this.refreshGraph.bind(this));}
displayName()
{const includeDetailsInMainTitle=true;return WI.TimelineTabContentView.displayNameForRecord(this.record,includeDetailsInMainTitle);}
iconClassNames()
{return[WI.TimelineTabContentView.iconClassNameForRecord(this.record)];} 
createGoToArrowButton(cellElement,callback)
{function buttonClicked(event)
{if(this.hidden||!this.revealed)
return;event.stopPropagation();callback(this,cellElement.__columnIdentifier);}
let button=WI.createGoToArrowButton();button.addEventListener("click",buttonClicked.bind(this));let contentElement=cellElement.firstChild;contentElement.appendChild(button);}
isRecordVisible(record)
{if(!this._graphDataSource)
return false;if(isNaN(record.startTime))
return false;if(record.endTime<this.graphDataSource.startTime)
return false;if(record.startTime>this.graphDataSource.currentTime||record.startTime>this.graphDataSource.endTime)
return false;return true;}
filterableDataForColumn(columnIdentifier)
{let value=this.data[columnIdentifier];if(value instanceof WI.SourceCodeLocation)
return value.displayLocationString();if(value instanceof WI.CallFrame)
return[value.functionName,value.sourceCodeLocation.displayLocationString()];return super.filterableDataForColumn(columnIdentifier);}
didAddRecordBar(recordBar)
{}
didRemoveRecordBar(recordBar)
{}
didResizeColumn(columnIdentifier)
{if(columnIdentifier!=="graph")
return;this.needsGraphRefresh();}};WI.ContentBrowserTabContentView=class ContentBrowserTabContentView extends WI.TabContentView
{constructor(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors,hideBackForwardButtons,disableBackForwardNavigation,flexibleNavigationItem}={})
{super(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors});const contentBrowserElement=null;const disableFindBanner=false;this._contentBrowser=new WI.ContentBrowser(contentBrowserElement,this,{hideBackForwardButtons,disableBackForwardNavigation,flexibleNavigationItem});this._ignoreNavigationSidebarPanelCollapsedEvent=false;this._ignoreDetailsSidebarPanelCollapsedEvent=false;this._ignoreDetailsSidebarPanelSelectedEvent=false;this._lastSelectedDetailsSidebarPanelSetting=new WI.Setting(this._identifier+"-last-selected-details-sidebar-panel",null);this._contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this._contentBrowserCurrentRepresentedObjectsDidChange,this);this._contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentContentViewDidChange,this._contentBrowserCurrentContentViewDidChange,this);this._contentBrowser.updateHierarchicalPathForCurrentContentView();if(this._navigationSidebarPanelConstructor){let showToolTip=WI.UIString("Show the navigation sidebar (%s)").format(WI.navigationSidebarKeyboardShortcut.displayName);let hideToolTip=WI.UIString("Hide the navigation sidebar (%s)").format(WI.navigationSidebarKeyboardShortcut.displayName);let image=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"Images/ToggleRightSidebar.svg":"Images/ToggleLeftSidebar.svg";this._showNavigationSidebarItem=new WI.ActivateButtonNavigationItem("toggle-navigation-sidebar",showToolTip,hideToolTip,image,16,16);this._showNavigationSidebarItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.toggleNavigationSidebar,this);this._showNavigationSidebarItem.activated=!WI.navigationSidebar.collapsed;this._showNavigationSidebarItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._contentBrowser.navigationBar.insertNavigationItem(this._showNavigationSidebarItem,0);this._contentBrowser.navigationBar.insertNavigationItem(new WI.DividerNavigationItem,1);WI.navigationSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._navigationSidebarCollapsedStateDidChange,this);}
if(this._detailsSidebarPanelConstructors.length){let showToolTip=WI.UIString("Show the details sidebar (%s)").format(WI.detailsSidebarKeyboardShortcut.displayName);let hideToolTip=WI.UIString("Hide the details sidebar (%s)").format(WI.detailsSidebarKeyboardShortcut.displayName);let image=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"Images/ToggleLeftSidebar.svg":"Images/ToggleRightSidebar.svg";this._showDetailsSidebarItem=new WI.ActivateButtonNavigationItem("toggle-details-sidebar",showToolTip,hideToolTip,image,16,16);this._showDetailsSidebarItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.toggleDetailsSidebar,this);this._showDetailsSidebarItem.activated=!WI.detailsSidebar.collapsed;this._showDetailsSidebarItem.enabled=false;this._showDetailsSidebarItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._contentBrowser.navigationBar.addNavigationItem(new WI.DividerNavigationItem);this._contentBrowser.navigationBar.addNavigationItem(this._showDetailsSidebarItem);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._detailsSidebarCollapsedStateDidChange,this);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._detailsSidebarPanelSelected,this);}
this.element.classList.add("content-browser");this.addSubview(this._contentBrowser);} 
get contentBrowser()
{return this._contentBrowser;}
attached()
{if(this.navigationSidebarPanel&&!this.navigationSidebarPanel.contentBrowser)
this.navigationSidebarPanel.contentBrowser=this._contentBrowser;super.attached();}
closed()
{super.closed();if(this._navigationSidebarPanelConstructor)
WI.navigationSidebar.removeEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._navigationSidebarCollapsedStateDidChange,this);if(this._detailsSidebarPanelConstructors.length){WI.detailsSidebar.removeEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._detailsSidebarCollapsedStateDidChange,this);WI.detailsSidebar.removeEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._detailsSidebarPanelSelected,this);}
if(this.navigationSidebarPanel&&typeof this.navigationSidebarPanel.closed==="function")
this.navigationSidebarPanel.closed();this._contentBrowser.contentViewContainer.closeAllContentViews();}
get managesDetailsSidebarPanels()
{return true;}
showNavigationSidebarPanel()
{if(!this.isAttached)
return;if(!this.navigationSidebarPanel)
return;this._ignoreNavigationSidebarPanelCollapsedEvent=true;let currentRepresentedObjects=this._contentBrowser.currentRepresentedObjects;let shouldShowSidebar=currentRepresentedObjects.some((object)=>this.navigationSidebarPanel.canShowRepresentedObject(object));if(shouldShowSidebar){if(!this.navigationSidebarPanel.parentSidebar)
WI.navigationSidebar.addSidebarPanel(this.navigationSidebarPanel);WI.navigationSidebar.collapsed=this.navigationSidebarCollapsedSetting.value;WI.navigationSidebar.selectedSidebarPanel=this.navigationSidebarPanel;}else{if(this.navigationSidebarPanel.parentSidebar)
WI.navigationSidebar.removeSidebarPanel(this.navigationSidebarPanel);WI.navigationSidebar.collapsed=true;}
this._ignoreNavigationSidebarPanelCollapsedEvent=false;this._showNavigationSidebarItem.enabled=!!this.navigationSidebarPanel.parentSidebar;}
showDetailsSidebarPanels()
{if(!this.isAttached)
return;var currentRepresentedObjects=this._contentBrowser.currentRepresentedObjects;var wasSidebarEmpty=!WI.detailsSidebar.sidebarPanels.length;
this._ignoreDetailsSidebarPanelSelectedEvent=true;this._ignoreDetailsSidebarPanelCollapsedEvent=true;let hiddenSidebarPanels=0;let sidebarPanelToSelect=null;for(var i=0;i<this.detailsSidebarPanels.length;++i){var sidebarPanel=this.detailsSidebarPanels[i];if(sidebarPanel.inspect(currentRepresentedObjects)){if(WI.detailsSidebar.sidebarPanels.includes(sidebarPanel)){continue;}
let index=i-hiddenSidebarPanels;WI.detailsSidebar.insertSidebarPanel(sidebarPanel,index);if(this._lastSelectedDetailsSidebarPanelSetting.value===sidebarPanel.identifier){sidebarPanelToSelect=sidebarPanel;}}else{WI.detailsSidebar.removeSidebarPanel(sidebarPanel);hiddenSidebarPanels++;}}
if(!WI.detailsSidebar.sidebarPanels.length)
WI.detailsSidebar.collapsed=true;else if(wasSidebarEmpty)
WI.detailsSidebar.collapsed=this.detailsSidebarCollapsedSetting.value;if(sidebarPanelToSelect)
WI.detailsSidebar.selectedSidebarPanel=sidebarPanelToSelect;else if(!WI.detailsSidebar.selectedSidebarPanel&&WI.detailsSidebar.sidebarPanels.length)
WI.detailsSidebar.selectedSidebarPanel=WI.detailsSidebar.sidebarPanels[0];this._ignoreDetailsSidebarPanelCollapsedEvent=false;this._ignoreDetailsSidebarPanelSelectedEvent=false;if(!this.detailsSidebarPanels.length)
return;this._showDetailsSidebarItem.enabled=WI.detailsSidebar.sidebarPanels.length;}
showRepresentedObject(representedObject,cookie)
{if(this.navigationSidebarPanel)
this.navigationSidebarPanel.cancelRestoringState();this.contentBrowser.showContentViewForRepresentedObject(representedObject,cookie);} 
contentBrowserTreeElementForRepresentedObject(contentBrowser,representedObject)
{return this.treeElementForRepresentedObject(representedObject);} 
treeElementForRepresentedObject(representedObject)
{if(!this.navigationSidebarPanel)
return null;return this.navigationSidebarPanel.treeElementForRepresentedObject(representedObject);} 
_navigationSidebarCollapsedStateDidChange(event)
{if(!this.isAttached)
return;this._showNavigationSidebarItem.activated=!WI.navigationSidebar.collapsed;if(this._ignoreNavigationSidebarPanelCollapsedEvent)
return;this.navigationSidebarCollapsedSetting.value=WI.navigationSidebar.collapsed;}
_detailsSidebarCollapsedStateDidChange(event)
{if(!this.isAttached)
return;this._showDetailsSidebarItem.activated=!WI.detailsSidebar.collapsed;this._showDetailsSidebarItem.enabled=WI.detailsSidebar.sidebarPanels.length;if(this._ignoreDetailsSidebarPanelCollapsedEvent)
return;this.detailsSidebarCollapsedSetting.value=WI.detailsSidebar.collapsed;}
_detailsSidebarPanelSelected(event)
{if(!this.isAttached)
return;this._showDetailsSidebarItem.activated=!WI.detailsSidebar.collapsed;this._showDetailsSidebarItem.enabled=WI.detailsSidebar.sidebarPanels.length;if(!WI.detailsSidebar.selectedSidebarPanel||this._ignoreDetailsSidebarPanelSelectedEvent)
return;this._lastSelectedDetailsSidebarPanelSetting.value=WI.detailsSidebar.selectedSidebarPanel.identifier;}
_contentBrowserCurrentContentViewDidChange(event)
{let currentContentView=this._contentBrowser.currentContentView;if(!currentContentView)
return;this._revealAndSelectRepresentedObject(currentContentView.representedObject);}
_revealAndSelectRepresentedObject(representedObject)
{if(this.navigationSidebarPanel){

for(let contentTreeOutline of this.navigationSidebarPanel.contentTreeOutlines){if(contentTreeOutline.processingSelectionChange)
return;}}
let treeElement=this.treeElementForRepresentedObject(representedObject);if(treeElement)
treeElement.revealAndSelect();else if(this.navigationSidebarPanel&&this.navigationSidebarPanel.contentTreeOutline.selectedTreeElement)
this.navigationSidebarPanel.contentTreeOutline.selectedTreeElement.deselect(true);}
_contentBrowserCurrentRepresentedObjectsDidChange()
{if(this.managesNavigationSidebarPanel)
this.showNavigationSidebarPanel();this.showDetailsSidebarPanels();}};WI.DOMDetailsSidebarPanel=class DOMDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor(identifier,displayName,dontCreateNavigationItem)
{super(identifier,displayName,dontCreateNavigationItem);this.element.addEventListener("click",this._mouseWasClicked.bind(this),true);this._domNode=null;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];var nodeToInspect=null;for(var i=0;i<objects.length;++i){if(objects[i]instanceof WI.DOMNode){nodeToInspect=objects[i];break;}}
if(nodeToInspect&&!this.supportsDOMNode(nodeToInspect))
nodeToInspect=null;this.domNode=nodeToInspect;return!!this._domNode;}
get domNode()
{return this._domNode;}
set domNode(domNode)
{if(domNode===this._domNode)
return;if(this._domNode)
this.removeEventListeners();this._domNode=domNode;if(this._domNode)
this.addEventListeners();this.needsLayout();}
supportsDOMNode(nodeToInspect)
{return true;}
addEventListeners()
{}
removeEventListeners()
{} 
_mouseWasClicked(event)
{let parentFrame=null;if(this._domNode&&this._domNode.ownerDocument){let mainResource=WI.networkManager.resourcesForURL(this._domNode.ownerDocument.documentURL).firstValue;if(mainResource)
parentFrame=mainResource.parentFrame;}
const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.handlePossibleLinkClick(event,parentFrame,options);}};WI.FolderTreeElement=class FolderTreeElement extends WI.GeneralTreeElement
{constructor(title,representedObject)
{const classNames=[WI.FolderTreeElement.FolderIconStyleClassName];const subtitle=null;super(classNames,title,subtitle,representedObject,{hasChildren:true});}};WI.FolderTreeElement.FolderIconStyleClassName="folder-icon";WI.FolderizedTreeElement=class FolderizedTreeElement extends WI.GeneralTreeElement
{constructor(classNames,title,subtitle,representedObject)
{super(classNames,title,subtitle,representedObject);this.shouldRefreshChildren=true;this._folderExpandedSettingMap=new Map;this._folderSettingsKey="";this._folderTypeMap=new Map;this._folderizeSettingsMap=new Map;this._groupedIntoFolders=false;this._clearNewChildQueue();} 
get groupedIntoFolders()
{return this._groupedIntoFolders;}
set folderSettingsKey(x)
{this._folderSettingsKey=x;}
registerFolderizeSettings(type,displayName,representedObject,treeElementConstructor)
{let settings={type,displayName,topLevel:displayName===null,representedObject,treeElementConstructor,};this._folderizeSettingsMap.set(type,settings);}
removeChildren()
{super.removeChildren();this._clearNewChildQueue();this._folderExpandedSettingMap.clear();this._folderTypeMap.clear();this._groupedIntoFolders=false;} 
addChildForRepresentedObject(representedObject)
{var settings=this._settingsForRepresentedObject(representedObject);if(!settings){console.error("No settings for represented object",representedObject);return;}
if(!this.treeOutline){this.shouldRefreshChildren=true;return;}
var childTreeElement=this.treeOutline.getCachedTreeElement(representedObject);if(!childTreeElement)
childTreeElement=new settings.treeElementConstructor(representedObject);this._addTreeElement(childTreeElement);}
addRepresentedObjectToNewChildQueue(representedObject)
{this._newChildQueue.push(representedObject);if(!this._newChildQueueTimeoutIdentifier)
this._newChildQueueTimeoutIdentifier=setTimeout(this._populateFromNewChildQueue.bind(this),WI.FolderizedTreeElement.NewChildQueueUpdateInterval);}
removeChildForRepresentedObject(representedObject)
{this._removeRepresentedObjectFromNewChildQueue(representedObject);this.updateParentStatus();if(!this.treeOutline){this.shouldRefreshChildren=true;return;}

var childTreeElement=this.treeOutline.getCachedTreeElement(representedObject);if(!childTreeElement||!childTreeElement.parent)
return;this._removeTreeElement(childTreeElement);}
compareChildTreeElements(a,b)
{return this._compareTreeElementsByMainTitle(a,b);}
updateParentStatus()
{let hasChildren=false;for(let settings of this._folderizeSettingsMap.values()){if(settings.representedObject.size){hasChildren=true;break;}}
this.hasChildren=hasChildren;if(!this.hasChildren)
this.removeChildren();}
prepareToPopulate()
{if(!this._groupedIntoFolders&&this._shouldGroupIntoFolders()){this._groupedIntoFolders=true;return true;}
return false;} 
_clearNewChildQueue()
{this._newChildQueue=[];if(this._newChildQueueTimeoutIdentifier){clearTimeout(this._newChildQueueTimeoutIdentifier);this._newChildQueueTimeoutIdentifier=null;}}
_populateFromNewChildQueue()
{if(!this.children.length){this.updateParentStatus();this.shouldRefreshChildren=true;return;}
if(this.prepareToPopulate()){this._clearNewChildQueue();this.shouldRefreshChildren=true;return;}
for(var i=0;i<this._newChildQueue.length;++i)
this.addChildForRepresentedObject(this._newChildQueue[i]);this._clearNewChildQueue();}
_removeRepresentedObjectFromNewChildQueue(representedObject)
{this._newChildQueue.remove(representedObject);}
_addTreeElement(childTreeElement)
{if(!childTreeElement)
return;var wasSelected=childTreeElement.selected;this._removeTreeElement(childTreeElement,true,true);var parentTreeElement=this._parentTreeElementForRepresentedObject(childTreeElement.representedObject);if(parentTreeElement!==this&&!parentTreeElement.parent)
this._insertFolderTreeElement(parentTreeElement);this._insertChildTreeElement(parentTreeElement,childTreeElement);if(wasSelected)
childTreeElement.revealAndSelect(true,false,true);}
_compareTreeElementsByMainTitle(a,b)
{let aIsFolder=a instanceof WI.FolderTreeElement;let bIsFolder=b instanceof WI.FolderTreeElement;if(aIsFolder&&!bIsFolder)
return-1;if(bIsFolder&&!aIsFolder)
return 1;return a.mainTitle.extendedLocaleCompare(b.mainTitle);}
_insertFolderTreeElement(folderTreeElement)
{this.insertChild(folderTreeElement,insertionIndexForObjectInListSortedByFunction(folderTreeElement,this.children,this._compareTreeElementsByMainTitle));}
_insertChildTreeElement(parentTreeElement,childTreeElement)
{parentTreeElement.insertChild(childTreeElement,insertionIndexForObjectInListSortedByFunction(childTreeElement,parentTreeElement.children,this.compareChildTreeElements.bind(this)));}
_removeTreeElement(childTreeElement,suppressOnDeselect,suppressSelectSibling)
{var oldParent=childTreeElement.parent;if(!oldParent)
return;oldParent.removeChild(childTreeElement,suppressOnDeselect,suppressSelectSibling);if(oldParent===this)
return;if(!(oldParent instanceof WI.FolderTreeElement))
return;if(!oldParent.children.length)
oldParent.parent.removeChild(oldParent);}
_parentTreeElementForRepresentedObject(representedObject)
{if(!this._groupedIntoFolders)
return this;function createFolderTreeElement(settings)
{let folderTreeElement=new WI.FolderTreeElement(settings.displayName,settings.representedObject);let folderExpandedSetting=new WI.Setting(settings.type+"-folder-expanded-"+this._folderSettingsKey,false);this._folderExpandedSettingMap.set(folderTreeElement,folderExpandedSetting);if(folderExpandedSetting.value)
folderTreeElement.expand();folderTreeElement.onexpand=this._folderTreeElementExpandedStateChange.bind(this);folderTreeElement.oncollapse=this._folderTreeElementExpandedStateChange.bind(this);return folderTreeElement;}
var settings=this._settingsForRepresentedObject(representedObject);if(!settings){console.error("Unknown representedObject",representedObject);return this;}
if(settings.topLevel)
return this;var folder=this._folderTypeMap.get(settings.type);if(folder)
return folder;folder=createFolderTreeElement.call(this,settings);this._folderTypeMap.set(settings.type,folder);return folder;}
_folderTreeElementExpandedStateChange(folderTreeElement)
{let expandedSetting=this._folderExpandedSettingMap.get(folderTreeElement);if(!expandedSetting)
return;expandedSetting.value=folderTreeElement.expanded;}
_settingsForRepresentedObject(representedObject)
{for(let settings of this._folderizeSettingsMap.values()){if(settings.representedObject.objectIsRequiredType(representedObject))
return settings;}
return null;}
_shouldGroupIntoFolders()
{if(this._groupedIntoFolders)
return true;
var numberOfSmallCategories=0;var numberOfMediumCategories=0;var foundLargeCategory=false;function pushCategory(childCount)
{if(!childCount)
return false;if(foundLargeCategory)
return true;if(childCount>=WI.FolderizedTreeElement.LargeChildCountThreshold){if(numberOfSmallCategories||numberOfMediumCategories)
return true;foundLargeCategory=true;return false;}
if(childCount>=WI.FolderizedTreeElement.MediumChildCountThreshold){return++numberOfMediumCategories>=WI.FolderizedTreeElement.NumberOfMediumCategoriesThreshold;}
++numberOfSmallCategories;return false;}
for(var settings of this._folderizeSettingsMap.values()){if(pushCategory(settings.representedObject.size))
return true;}
return false;}};WI.FolderizedTreeElement.MediumChildCountThreshold=5;WI.FolderizedTreeElement.LargeChildCountThreshold=15;WI.FolderizedTreeElement.NumberOfMediumCategoriesThreshold=2;WI.FolderizedTreeElement.NewChildQueueUpdateInterval=500;WI.NetworkDetailView=class NetworkDetailView extends WI.View
{constructor(representedObject,delegate)
{super();this._representedObject=representedObject;this._delegate=delegate||null;this.element.classList.add("network-detail");this._contentBrowser=null;this._detailNavigationItemMap=new Map;this._contentViewCookie=null;} 
get representedObject(){return this._representedObject;}
attached()
{super.attached();if(!this._contentBrowser)
return;this._showPreferredContentView();if(this._contentViewCookie){this._contentBrowser.showContentView(this._contentBrowser.currentContentView,this._contentViewCookie);this._contentViewCookie=null;}}
dispose()
{this._delegate=null;this._contentBrowser.contentViewContainer.closeAllContentViews();}
willShowWithCookie(cookie)
{this._contentViewCookie=cookie;} 
initialLayout()
{let closeNavigationItem=new WI.ButtonNavigationItem("close",WI.UIString("Close detail view"),"Images/CloseLarge.svg",16,16);closeNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCloseButton,this);closeNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;let contentViewNavigationItemGroup=new WI.GroupNavigationItem;let flexibleNavigationItem=new WI.FlexibleSpaceNavigationItem(contentViewNavigationItemGroup,WI.FlexibleSpaceNavigationItem.Align.End);flexibleNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;const element=null;this._contentBrowser=new WI.ContentBrowser(element,this,{hideBackForwardButtons:true,flexibleNavigationItem,contentViewNavigationItemGroup});let index=0;this._contentBrowser.navigationBar.insertNavigationItem(closeNavigationItem,index++);for(let detailNavigationItem of this._detailNavigationItemMap.values())
this._contentBrowser.navigationBar.insertNavigationItem(detailNavigationItem,index++);this._contentBrowser.navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._navigationItemSelected,this);this.addSubview(this._contentBrowser);this._showPreferredContentView();}
createDetailNavigationItem(identifier,toolTip)
{this._detailNavigationItemMap.set(identifier,new WI.RadioButtonNavigationItem(identifier,toolTip));}
detailNavigationItemForIdentifier(identifier)
{return this._detailNavigationItemMap.get(identifier);}
showContentViewForIdentifier(identifier)
{} 
_showPreferredContentView()
{let detailNavigationItems=Array.from(this._detailNavigationItemMap.values());let firstNavigationItem=null;let defaultIdentifier=WI.settings.selectedNetworkDetailContentViewIdentifier.value;for(let navigationItem of this._contentBrowser.navigationBar.navigationItems){if(!(navigationItem instanceof WI.RadioButtonNavigationItem))
continue;if(!detailNavigationItems.includes(navigationItem))
continue;if(!firstNavigationItem)
firstNavigationItem=navigationItem;if(navigationItem.identifier===defaultIdentifier){this._contentBrowser.navigationBar.selectedNavigationItem=navigationItem;return;}}
this._contentBrowser.navigationBar.selectedNavigationItem=firstNavigationItem;}
_navigationItemSelected(event)
{let navigationItem=event.target.selectedNavigationItem;if(!(navigationItem instanceof WI.RadioButtonNavigationItem))
return;this.showContentViewForIdentifier(navigationItem.identifier);WI.settings.selectedNetworkDetailContentViewIdentifier.value=navigationItem.identifier;}
_handleCloseButton(event)
{if(this._delegate&&this._delegate.networkDetailViewClose)
this._delegate.networkDetailViewClose(this);}};WI.NetworkTabContentView=class NetworkTabContentView extends WI.TabContentView
{constructor()
{super(NetworkTabContentView.tabInfo());this._networkTableContentView=new WI.NetworkTableContentView;this._contentBrowser=new WI.ContentBrowser(null,this,{hideBackForwardButtons:true,disableFindBanner:true});this._contentBrowser.showContentView(this._networkTableContentView);let filterNavigationItems=this._networkTableContentView.filterNavigationItems;for(let i=0;i<filterNavigationItems.length;++i)
this._contentBrowser.navigationBar.insertNavigationItem(filterNavigationItems[i],i);this.addSubview(this._contentBrowser);} 
static tabInfo()
{return{identifier:NetworkTabContentView.Type,image:"Images/Network.svg",displayName:WI.UIString("Network","Network Tab Name","Name of Network Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("Network");} 
closed()
{this._contentBrowser.contentViewContainer.closeAllContentViews();super.closed();}
initialLayout()
{super.initialLayout();let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import HAR");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);}
get canHandleFindEvent()
{return this._networkTableContentView.canFocusFilterBar;}
handleFindEvent()
{this._networkTableContentView.focusFilterBar();} 
get contentBrowser(){return this._contentBrowser;}
get type()
{return WI.NetworkTabContentView.Type;}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.Resource;}
showRepresentedObject(representedObject,cookie)
{this._networkTableContentView.showRepresentedObject(representedObject,cookie);}
get supportsSplitContentBrowser()
{return true;} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{return event.dataTransfer.types.includes("Files");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readJSON(files,(result)=>this._networkTableContentView.processHAR(result));}};WI.NetworkTabContentView.Type="network";WI.ObjectTreeBaseTreeElement=class ObjectTreeBaseTreeElement extends WI.GeneralTreeElement
{constructor(representedObject,propertyPath,property)
{const classNames=null;const title=null;const subtitle=null;super(classNames,title,subtitle,representedObject);this._property=property;this._propertyPath=propertyPath;this.toggleOnClick=true;this.selectable=false;this.tooltipHandledSeparately=true;} 
get property()
{return this._property;}
get propertyPath()
{return this._propertyPath;} 
resolvedValue()
{if(this._getterValue)
return this._getterValue;if(this._property.hasValue())
return this._property.value;return null;}
resolvedValuePropertyPath()
{if(this._getterValue)
return this._propertyPath.appendPropertyDescriptor(this._getterValue,this._property,WI.PropertyPath.Type.Value);if(this._property.hasValue())
return this._propertyPath.appendPropertyDescriptor(this._property.value,this._property,WI.PropertyPath.Type.Value);return null;}
thisPropertyPath()
{return this._propertyPath.appendPropertyDescriptor(null,this._property,this.propertyPathType());}
hadError()
{return this._property.wasThrown||this._getterHadError;}
propertyPathType()
{if(this._getterValue||this._property.hasValue())
return WI.PropertyPath.Type.Value;if(this._property.hasGetter())
return WI.PropertyPath.Type.Getter;if(this._property.hasSetter())
return WI.PropertyPath.Type.Setter;return WI.PropertyPath.Type.Value;}
propertyPathString(propertyPath)
{if(propertyPath.isFullPathImpossible())
return WI.UIString("Unable to determine path to property from root");return propertyPath.displayPath(this.propertyPathType());}
createGetterElement(interactive)
{var getterElement=document.createElement("img");getterElement.className="getter";if(!interactive){getterElement.classList.add("disabled");getterElement.title=WI.UIString("Getter");return getterElement;}
getterElement.title=WI.UIString("Invoke getter");getterElement.addEventListener("click",(event)=>{event.stopPropagation();var lastNonPrototypeObject=this._propertyPath.lastNonPrototypeObject;var getterObject=this._property.get;lastNonPrototypeObject.invokeGetter(getterObject,(error,result,wasThrown)=>{this._getterHadError=!!(error||wasThrown);this._getterValue=result;if(this.invokedGetter&&typeof this.invokedGetter==="function")
this.invokedGetter();});});return getterElement;}
createSetterElement(interactive)
{var setterElement=document.createElement("img");setterElement.className="setter";setterElement.title=WI.UIString("Setter");if(!interactive)
setterElement.classList.add("disabled");return setterElement;}
populateContextMenu(contextMenu,event)
{if(event.__addedObjectPreviewContextMenuItems)
return;if(event.__addedObjectTreeContextMenuItems)
return;event.__addedObjectTreeContextMenuItems=true;if(typeof this.treeOutline.objectTreeElementAddContextMenuItems==="function"){this.treeOutline.objectTreeElementAddContextMenuItems(this,contextMenu);if(!contextMenu.isEmpty())
contextMenu.appendSeparator();}
let resolvedValue=this.resolvedValue();if(!resolvedValue)
return;if(this._property&&this._property.symbol)
contextMenu.appendItem(WI.UIString("Log Symbol"),this._logSymbolProperty.bind(this));contextMenu.appendItem(WI.UIString("Log Value"),this._logValue.bind(this));let propertyPath=this.resolvedValuePropertyPath();if(propertyPath&&!propertyPath.isFullPathImpossible()){contextMenu.appendItem(WI.UIString("Copy Path to Property"),()=>{InspectorFrontendHost.copyText(propertyPath.displayPath(WI.PropertyPath.Type.Value));});}
contextMenu.appendSeparator();this._appendMenusItemsForObject(contextMenu,resolvedValue);super.populateContextMenu(contextMenu,event);} 
_logSymbolProperty()
{var symbol=this._property.symbol;if(!symbol)
return;var text=WI.UIString("Selected Symbol");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,symbol,true);}
_logValue(value)
{var resolvedValue=value||this.resolvedValue();if(!resolvedValue)
return;var propertyPath=this.resolvedValuePropertyPath();var isImpossible=propertyPath.isFullPathImpossible();var text=isImpossible?WI.UIString("Selected Value"):propertyPath.displayPath(this.propertyPathType());if(!isImpossible)
WI.quickConsole.prompt.pushHistoryItem(text);WI.consoleLogViewController.appendImmediateExecutionWithResult(text,resolvedValue,isImpossible);}
_appendMenusItemsForObject(contextMenu,resolvedValue)
{if(resolvedValue.type==="function"){if(!isFunctionStringNativeCode(resolvedValue.description)){contextMenu.appendItem(WI.UIString("Jump to Definition"),function(){resolvedValue.target.DebuggerAgent.getFunctionDetails(resolvedValue.objectId,function(error,response){if(error)
return;let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,resolvedValue.target);if(!sourceCode)
return;let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.showSourceCodeLocation(sourceCodeLocation,options);});});}
return;}}};WI.SourceCodeTreeElement=class SourceCodeTreeElement extends WI.FolderizedTreeElement
{constructor(sourceCode,classNames,title,subtitle,representedObject)
{super(classNames,title,subtitle,representedObject||sourceCode);this._updateSourceCode(sourceCode);} 
updateSourceMapResources()
{if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren)
return;this.hasChildren=!!this._sourceCode.sourceMaps.length;this.shouldRefreshChildren=this.hasChildren;if(!this.hasChildren)
this.removeChildren();} 
onattach()
{super.onattach();this.updateSourceMapResources();}
onpopulate()
{if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren)
return;if(!this.hasChildren||!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();function combineFolderChain(topFolder,bottomFolder)
{var components=[];for(var currentFolder=bottomFolder;currentFolder!==topFolder;currentFolder=currentFolder.parent)
components.push(currentFolder.mainTitle);components.push(topFolder.mainTitle);var folderName=components.reverse().join("/");var newFolder=new WI.FolderTreeElement(folderName);var folderIndex=topFolder.parent.children.indexOf(topFolder);topFolder.parent.insertChild(newFolder,folderIndex);topFolder.parent.removeChild(topFolder);var children=bottomFolder.children;bottomFolder.removeChildren();for(var i=0;i<children.length;++i)
newFolder.appendChild(children[i]);}
function findAndCombineFolderChains(treeElement,previousSingleTreeElement)
{if(!(treeElement instanceof WI.FolderTreeElement)){if(previousSingleTreeElement&&previousSingleTreeElement!==treeElement.parent)
combineFolderChain(previousSingleTreeElement,treeElement.parent);return;}
if(previousSingleTreeElement&&treeElement.children.length!==1){combineFolderChain(previousSingleTreeElement,treeElement);previousSingleTreeElement=null;}
if(!previousSingleTreeElement&&treeElement.children.length===1)
previousSingleTreeElement=treeElement;for(var i=0;i<treeElement.children.length;++i)
findAndCombineFolderChains(treeElement.children[i],previousSingleTreeElement);}
var sourceMaps=this._sourceCode.sourceMaps;for(var i=0;i<sourceMaps.length;++i){var sourceMap=sourceMaps[i];for(var j=0;j<sourceMap.resources.length;++j){var sourceMapResource=sourceMap.resources[j];var relativeSubpath=sourceMapResource.sourceMapDisplaySubpath;var folderTreeElement=this.createFoldersAsNeededForSubpath(relativeSubpath);var sourceMapTreeElement=new WI.SourceMapResourceTreeElement(sourceMapResource);folderTreeElement.insertChild(sourceMapTreeElement,insertionIndexForObjectInListSortedByFunction(sourceMapTreeElement,folderTreeElement.children,WI.ResourceTreeElement.compareFolderAndResourceTreeElements));}}
if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Type){for(let child of this.children)
findAndCombineFolderChains(child);}}
canSelectOnMouseDown(event)
{if(this._toggleBlackboxedImageElement&&this._toggleBlackboxedImageElement.contains(event.target))
return false;return super.canSelectOnMouseDown(event);} 
descendantResourceTreeElementTypeDidChange(childTreeElement,oldType)
{let parentTreeElement=childTreeElement.parent;let wasParentExpanded=parentTreeElement.expanded;let wasSelected=childTreeElement.selected;parentTreeElement.removeChild(childTreeElement,true,true);parentTreeElement.insertChild(childTreeElement,insertionIndexForObjectInListSortedByFunction(childTreeElement,parentTreeElement.children,WI.ResourceTreeElement.compareFolderAndResourceTreeElements));if(wasParentExpanded)
parentTreeElement.expand();if(wasSelected)
childTreeElement.revealAndSelect(true,false,true);}
updateStatus()
{if(this._sourceCode.supportsScriptBlackboxing){if(!this._toggleBlackboxedImageElement){this._toggleBlackboxedImageElement=document.createElement("img");this._toggleBlackboxedImageElement.classList.add("toggle-script-blackbox");this._toggleBlackboxedImageElement.addEventListener("click",this._handleToggleBlackboxedImageElementClicked.bind(this));}
this.status=this._toggleBlackboxedImageElement;this._updateToggleBlackboxImageElementState();}else if(this.status===this._toggleBlackboxedImageElement)
this.status=null;}
_updateSourceCode(sourceCode)
{if(this._sourceCode===sourceCode)
return;let oldSupportsScriptBlackboxing=false;if(this._sourceCode){oldSupportsScriptBlackboxing=this._sourceCode.supportsScriptBlackboxing;this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this.updateSourceMapResources,this);}
this._sourceCode=sourceCode;this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this.updateSourceMapResources,this);let newSupportsScriptBlackboxing=this._sourceCode.supportsScriptBlackboxing;if(oldSupportsScriptBlackboxing!==newSupportsScriptBlackboxing){if(newSupportsScriptBlackboxing)
WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._updateToggleBlackboxImageElementState,this);else if(oldSupportsScriptBlackboxing)
WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._updateToggleBlackboxImageElementState,this);}
this.updateSourceMapResources();this.updateStatus();} 
_updateToggleBlackboxImageElementState()
{let blackboxData=WI.debuggerManager.blackboxDataForSourceCode(this._sourceCode);this._toggleBlackboxedImageElement.classList.toggle("pattern-blackboxed",blackboxData&&blackboxData.type===WI.DebuggerManager.BlackboxType.Pattern);this._toggleBlackboxedImageElement.classList.toggle("url-blackboxed",blackboxData&&blackboxData.type===WI.DebuggerManager.BlackboxType.URL);if(blackboxData){switch(blackboxData.type){case WI.DebuggerManager.BlackboxType.Pattern:this._toggleBlackboxedImageElement.title=WI.UIString("Script ignored when debugging due to URL pattern blackbox");break;case WI.DebuggerManager.BlackboxType.URL:this._toggleBlackboxedImageElement.title=WI.UIString("Unblackbox script to include it when debugging");break;}}else
this._toggleBlackboxedImageElement.title=WI.UIString("Blackbox script to ignore it when debugging");}
_handleToggleBlackboxedImageElementClicked(event)
{let blackboxData=WI.debuggerManager.blackboxDataForSourceCode(this._sourceCode);if(blackboxData&&blackboxData.type===WI.DebuggerManager.BlackboxType.Pattern){WI.showSettingsTab({blackboxPatternToSelect:blackboxData.regex,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});return;}
WI.debuggerManager.setShouldBlackboxScript(this._sourceCode,!blackboxData);this._updateToggleBlackboxImageElementState();}};WI.StorageTreeElement=class StorageTreeElement extends WI.GeneralTreeElement
{constructor(classNames,title,representedObject)
{const subtitle=null;super(classNames,title,subtitle,representedObject);this.flattened=false;this.tooltipHandledSeparately=true;} 
get flattened()
{return this._flattened;}
set flattened(flattened)
{if(this._flattened===flattened)
return;this._flattened=flattened;if(!this._flattened){this.mainTitle=this.name;this.subtitle=this.secondaryName;this._updateChildrenTitles();return;}
this.mainTitle=this.categoryName;this.subtitle=this.name;this._updateChildrenTitles();} 
_updateChildrenTitles()
{for(var i=0;i<this.children.length;++i){if(typeof this.children[i].updateTitles==="function")
this.children[i].updateTitles();}}};WI.TimelineDataGridNodePathComponent=class TimelineDataGridNodePathComponent extends WI.HierarchicalPathComponent
{constructor(timelineDataGridNode,representedObject)
{super(timelineDataGridNode.displayName(),timelineDataGridNode.iconClassNames(),representedObject||timelineDataGridNode.record);this._timelineDataGridNode=timelineDataGridNode;} 
get timelineDataGridNode()
{return this._timelineDataGridNode;}
get previousSibling()
{let previousSibling=this._timelineDataGridNode.previousSibling;while(previousSibling&&previousSibling.hidden)
previousSibling=previousSibling.previousSibling;if(!previousSibling)
return null;return new WI.TimelineDataGridNodePathComponent(previousSibling);}
get nextSibling()
{let nextSibling=this._timelineDataGridNode.nextSibling;while(nextSibling&&nextSibling.hidden)
nextSibling=nextSibling.nextSibling;if(!nextSibling)
return null;return new WI.TimelineDataGridNodePathComponent(nextSibling);}};WI.TimelineOverview=class TimelineOverview extends WI.View
{constructor(timelineRecording)
{super();this._timelinesViewModeSettings=this._createViewModeSettings(WI.TimelineOverview.ViewMode.Timelines,WI.TimelineOverview.MinimumDurationPerPixel,WI.TimelineOverview.MaximumDurationPerPixel,0.01,0,15);this._instrumentTypes=WI.TimelineManager.availableTimelineTypes();let minimumDurationPerPixel=1/WI.TimelineRecordFrame.MaximumWidthPixels;let maximumDurationPerPixel=1/WI.TimelineRecordFrame.MinimumWidthPixels;this._renderingFramesViewModeSettings=this._createViewModeSettings(WI.TimelineOverview.ViewMode.RenderingFrames,minimumDurationPerPixel,maximumDurationPerPixel,minimumDurationPerPixel,0,100);this._recording=timelineRecording;this._recording.addEventListener(WI.TimelineRecording.Event.InstrumentAdded,this._instrumentAdded,this);this._recording.addEventListener(WI.TimelineRecording.Event.InstrumentRemoved,this._instrumentRemoved,this);this._recording.addEventListener(WI.TimelineRecording.Event.MarkerAdded,this._markerAdded,this);this._recording.addEventListener(WI.TimelineRecording.Event.Reset,this._recordingReset,this);this.element.classList.add("timeline-overview");this._updateWheelAndGestureHandlers();this._graphsContainerView=new WI.View;this._graphsContainerView.element.classList.add("graphs-container");this._graphsContainerView.element.addEventListener("click",this._handleGraphsContainerClick.bind(this));this.addSubview(this._graphsContainerView);this._selectedTimelineRecord=null;this._overviewGraphsByTypeMap=new Map;this._editInstrumentsButton=new WI.ActivateButtonNavigationItem("toggle-edit-instruments",WI.UIString("Edit configuration"),WI.UIString("Save configuration"));this._editInstrumentsButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleEditingInstruments,this);this._editingInstruments=false;this._updateEditInstrumentsButton();let instrumentsNavigationBar=new WI.NavigationBar;instrumentsNavigationBar.element.classList.add("timelines");instrumentsNavigationBar.addNavigationItem(new WI.FlexibleSpaceNavigationItem);instrumentsNavigationBar.addNavigationItem(this._editInstrumentsButton);this.addSubview(instrumentsNavigationBar);this._timelinesTreeOutline=new WI.TreeOutline;this._timelinesTreeOutline.element.classList.add("timelines");this._timelinesTreeOutline.disclosureButtons=false;this._timelinesTreeOutline.large=true;this._timelinesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._timelinesTreeSelectionDidChange,this);this.element.appendChild(this._timelinesTreeOutline.element);this._treeElementsByTypeMap=new Map;this._timelineRuler=new WI.TimelineRuler;this._timelineRuler.allowsClippedLabels=true;this._timelineRuler.allowsTimeRangeSelection=true;this._timelineRuler.element.addEventListener("mousedown",this._timelineRulerMouseDown.bind(this));this._timelineRuler.element.addEventListener("click",this._timelineRulerMouseClicked.bind(this));this._timelineRuler.addEventListener(WI.TimelineRuler.Event.TimeRangeSelectionChanged,this._timeRangeSelectionChanged,this);this.addSubview(this._timelineRuler);this._currentTimeMarker=new WI.TimelineMarker(0,WI.TimelineMarker.Type.CurrentTime);this._timelineRuler.addMarker(this._currentTimeMarker);this._scrollContainerElement=document.createElement("div");this._scrollContainerElement.classList.add("scroll-container");this._scrollContainerElement.addEventListener("scroll",this._handleScrollEvent.bind(this));this.element.appendChild(this._scrollContainerElement);this._scrollWidthSizer=document.createElement("div");this._scrollWidthSizer.classList.add("scroll-width-sizer");this._scrollContainerElement.appendChild(this._scrollWidthSizer);this._startTime=0;this._currentTime=0;this._revealCurrentTime=false;this._endTime=0;this._pixelAlignDuration=false;this._mouseWheelDelta=0;this._cachedScrollContainerWidth=NaN;this._timelineRulerSelectionChanged=false;this._viewMode=WI.TimelineOverview.ViewMode.Timelines;this._selectedTimeline=null;for(let instrument of this._recording.instruments)
this._instrumentAdded(instrument);if(!WI.timelineManager.isCapturingPageReload())
this._resetSelection();this._viewModeDidChange();WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.RecordingImported,this._recordingImported,this);} 
exportData()
{let json={secondsPerPixel:this.secondsPerPixel,scrollStartTime:this.scrollStartTime,selectionStartTime:this.selectionStartTime,selectionDuration:this.selectionDuration,};if(this._selectedTimeline)
json.selectedTimelineType=this._selectedTimeline.type;return json;} 
get selectedTimeline()
{return this._selectedTimeline;}
set selectedTimeline(x)
{if(this._editingInstruments)
return;if(this._selectedTimeline===x)
return;this._selectedTimeline=x;if(this._selectedTimeline){let treeElement=this._treeElementsByTypeMap.get(this._selectedTimeline.type);let omitFocus=true;let wasSelectedByUser=false;treeElement.select(omitFocus,wasSelectedByUser);}else if(this._timelinesTreeOutline.selectedTreeElement)
this._timelinesTreeOutline.selectedTreeElement.deselect();}
get editingInstruments()
{return this._editingInstruments;}
get viewMode()
{return this._viewMode;}
set viewMode(x)
{if(this._editingInstruments)
return;if(this._viewMode===x)
return;this._viewMode=x;this._viewModeDidChange();}
get startTime()
{return this._startTime;}
set startTime(x)
{x=x||0;if(this._startTime===x)
return;if(this._viewMode!==WI.TimelineOverview.ViewMode.RenderingFrames){let selectionOffset=this.selectionStartTime-this._startTime;this.selectionStartTime=selectionOffset+x;}
this._startTime=x;this.needsLayout();}
get currentTime()
{return this._currentTime;}
set currentTime(x)
{x=x||0;if(this._currentTime===x)
return;this._currentTime=x;this._revealCurrentTime=true;this.needsLayout();}
get secondsPerPixel()
{return this._currentSettings.durationPerPixelSetting.value;}
set secondsPerPixel(x)
{x=Math.min(this._currentSettings.maximumDurationPerPixel,Math.max(this._currentSettings.minimumDurationPerPixel,x));if(this.secondsPerPixel===x)
return;if(this._pixelAlignDuration){x=1/Math.round(1/x);if(this.secondsPerPixel===x)
return;}
this._currentSettings.durationPerPixelSetting.value=x;this.needsLayout();}
get pixelAlignDuration()
{return this._pixelAlignDuration;}
set pixelAlignDuration(x)
{if(this._pixelAlignDuration===x)
return;this._mouseWheelDelta=0;this._pixelAlignDuration=x;if(this._pixelAlignDuration)
this.secondsPerPixel=1/Math.round(1/this.secondsPerPixel);}
get endTime()
{return this._endTime;}
set endTime(x)
{x=x||0;if(this._endTime===x)
return;this._endTime=x;this.needsLayout();}
get scrollStartTime()
{return this._currentSettings.scrollStartTime;}
set scrollStartTime(x)
{x=x||0;if(this.scrollStartTime===x)
return;this._currentSettings.scrollStartTime=x;this.needsLayout();}
get scrollContainerWidth()
{return this._cachedScrollContainerWidth;}
get visibleDuration()
{if(isNaN(this._cachedScrollContainerWidth)){this._cachedScrollContainerWidth=this._scrollContainerElement.offsetWidth;if(!this._cachedScrollContainerWidth)
this._cachedScrollContainerWidth=NaN;}
return this._cachedScrollContainerWidth*this.secondsPerPixel;}
get selectionStartTime()
{return this._timelineRuler.selectionStartTime;}
set selectionStartTime(x)
{x=x||0;if(this._timelineRuler.selectionStartTime===x)
return;let selectionDuration=this.selectionDuration;this._timelineRuler.selectionStartTime=x;this._timelineRuler.selectionEndTime=x+selectionDuration;}
get selectionDuration()
{return this._timelineRuler.selectionEndTime-this._timelineRuler.selectionStartTime;}
set selectionDuration(x)
{x=Math.max(this._timelineRuler.minimumSelectionDuration,x);this._timelineRuler.selectionEndTime=this._timelineRuler.selectionStartTime+x;}
get height()
{let height=0;for(let overviewGraph of this._overviewGraphsByTypeMap.values()){if(!overviewGraph.hidden)
height+=overviewGraph.height;}
return height;}
attached()
{super.attached();for(let[type,overviewGraph]of this._overviewGraphsByTypeMap){if(this._canShowTimelineType(type))
overviewGraph.hidden=false;}
this.needsLayout(WI.View.LayoutReason.Resize);}
detached()
{for(let overviewGraph of this._overviewGraphsByTypeMap.values())
overviewGraph.hidden=true;this.hideScanner();super.detached();}
closed()
{WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.RecordingImported,this._recordingImported,this);super.closed();}
reset()
{this._selectedTimelineRecord=null;for(let overviewGraph of this._overviewGraphsByTypeMap.values())
overviewGraph.reset();this._mouseWheelDelta=0;this._resetSelection();}
revealMarker(marker)
{this.scrollStartTime=marker.time-(this.visibleDuration/2);}
recordWasFiltered(timeline,record,filtered)
{let overviewGraph=this._overviewGraphsByTypeMap.get(timeline.type);if(!overviewGraph)
return;overviewGraph.recordWasFiltered(record,filtered);}
selectRecord(timeline,record)
{let overviewGraph=this._overviewGraphsByTypeMap.get(timeline.type);if(!overviewGraph)
return;overviewGraph.selectedRecord=record;}
showScanner(time)
{this._timelineRuler.showScanner(time);}
hideScanner()
{this._timelineRuler.hideScanner();}
updateLayoutIfNeeded(layoutReason)
{if(this.layoutPending){super.updateLayoutIfNeeded(layoutReason);return;}
this._timelineRuler.updateLayoutIfNeeded(layoutReason);for(let overviewGraph of this._overviewGraphsByTypeMap.values()){if(!overviewGraph.hidden)
overviewGraph.updateLayoutIfNeeded(layoutReason);}}
discontinuitiesInTimeRange(startTime,endTime)
{return this._recording.discontinuitiesInTimeRange(startTime,endTime);} 
get timelineRuler()
{return this._timelineRuler;}
layout()
{let startTime=this._startTime;let endTime=this._endTime;let currentTime=this._currentTime;if(this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames){let renderingFramesTimeline=this._recording.timelines.get(WI.TimelineRecord.Type.RenderingFrame);startTime=0;endTime=renderingFramesTimeline.records.length;currentTime=endTime;}
let duration=endTime-startTime;let newWidth=Math.ceil(duration/this.secondsPerPixel);this._updateElementWidth(this._scrollWidthSizer,newWidth);this._currentTimeMarker.time=currentTime;if(this._revealCurrentTime){this.revealMarker(this._currentTimeMarker);this._revealCurrentTime=false;}
const visibleDuration=this.visibleDuration;let scrollStartTime=Math.min(this.scrollStartTime,endTime-visibleDuration);scrollStartTime=Math.max(startTime,scrollStartTime);this._timelineRuler.zeroTime=startTime;this._timelineRuler.startTime=scrollStartTime;this._timelineRuler.secondsPerPixel=this.secondsPerPixel;if(!this._dontUpdateScrollLeft){this._ignoreNextScrollEvent=true;let scrollLeft=Math.ceil((scrollStartTime-startTime)/this.secondsPerPixel);if(scrollLeft)
this._scrollContainerElement.scrollLeft=scrollLeft;}
for(let overviewGraph of this._overviewGraphsByTypeMap.values()){if(overviewGraph.hidden)
continue;overviewGraph.zeroTime=startTime;overviewGraph.startTime=scrollStartTime;overviewGraph.currentTime=currentTime;overviewGraph.endTime=scrollStartTime+visibleDuration;}}
sizeDidChange()
{this._cachedScrollContainerWidth=NaN;} 
_updateElementWidth(element,newWidth)
{var currentWidth=parseInt(element.style.width);if(currentWidth!==newWidth)
element.style.width=newWidth+"px";}
_handleScrollEvent(event)
{if(this._ignoreNextScrollEvent){this._ignoreNextScrollEvent=false;return;}
this._dontUpdateScrollLeft=true;let scrollOffset=this._scrollContainerElement.scrollLeft;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
this.scrollStartTime=this._startTime-(scrollOffset*this.secondsPerPixel);else
this.scrollStartTime=this._startTime+(scrollOffset*this.secondsPerPixel);this.updateLayoutIfNeeded();this._dontUpdateScrollLeft=false;this.element.classList.toggle("has-scrollbar",this._scrollContainerElement.clientHeight<=1);}
_handleWheelEvent(event)
{if(event.__cloned)
return;if(this._handlingGesture)
return;
if(Math.abs(event.deltaX)>=Math.abs(event.deltaY)*0.5){let newWheelEvent=new event.constructor(event.type,event);newWheelEvent.__cloned=true;this._scrollContainerElement.dispatchEvent(newWheelEvent);return;}
let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let mousePositionTime=this._currentSettings.scrollStartTime+(mouseOffset*this.secondsPerPixel);let deviceDirection=event.webkitDirectionInvertedFromDevice?1:-1;let delta=event.deltaY*(this.secondsPerPixel/WI.TimelineOverview.ScrollDeltaDenominator)*deviceDirection;if(this._pixelAlignDuration&&(delta<0&&this._mouseWheelDelta>=0||delta>=0&&this._mouseWheelDelta<0))
this._mouseWheelDelta=0;let previousDurationPerPixel=this.secondsPerPixel;this._mouseWheelDelta+=delta;this.secondsPerPixel+=this._mouseWheelDelta;if(this.secondsPerPixel===this._currentSettings.minimumDurationPerPixel&&delta<0||this.secondsPerPixel===this._currentSettings.maximumDurationPerPixel&&delta>=0)
this._mouseWheelDelta=0;else
this._mouseWheelDelta=previousDurationPerPixel+this._mouseWheelDelta-this.secondsPerPixel;this.scrollStartTime=mousePositionTime-(mouseOffset*this.secondsPerPixel);this.element.classList.toggle("has-scrollbar",this._scrollContainerElement.clientHeight<=1);event.preventDefault();event.stopPropagation();}
_handleGestureStart(event)
{if(this._handlingGesture){ return;}
let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let mousePositionTime=this._currentSettings.scrollStartTime+(mouseOffset*this.secondsPerPixel);this._handlingGesture=true;this._gestureStartStartTime=mousePositionTime;this._gestureStartDurationPerPixel=this.secondsPerPixel;this.element.classList.toggle("has-scrollbar",this._scrollContainerElement.clientHeight<=1);event.preventDefault();event.stopPropagation();}
_handleGestureChange(event)
{let scale=Math.max(1/5,event.scale);let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let newSecondsPerPixel=this._gestureStartDurationPerPixel/scale;this.secondsPerPixel=newSecondsPerPixel;this.scrollStartTime=this._gestureStartStartTime-(mouseOffset*this.secondsPerPixel);event.preventDefault();event.stopPropagation();}
_handleGestureEnd(event)
{this._handlingGesture=false;this._gestureStartStartTime=NaN;this._gestureStartDurationPerPixel=NaN;}
_instrumentAdded(instrumentOrEvent)
{let instrument=instrumentOrEvent instanceof WI.Instrument?instrumentOrEvent:instrumentOrEvent.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);let treeElement=new WI.TimelineTreeElement(timeline);let insertionIndex=insertionIndexForObjectInListSortedByFunction(treeElement,this._timelinesTreeOutline.children,this._compareTimelineTreeElements.bind(this));this._timelinesTreeOutline.insertChild(treeElement,insertionIndex);this._treeElementsByTypeMap.set(timeline.type,treeElement);let overviewGraph=WI.TimelineOverviewGraph.createForTimeline(timeline,this);overviewGraph.addEventListener(WI.TimelineOverviewGraph.Event.RecordSelected,this._handleOverviewGraphRecordSelected,this);this._overviewGraphsByTypeMap.set(timeline.type,overviewGraph);this._graphsContainerView.insertSubviewBefore(overviewGraph,this._graphsContainerView.subviews[insertionIndex]);treeElement.element.style.height=overviewGraph.height+"px";if(!this._canShowTimelineType(timeline.type)){overviewGraph.hidden=true;treeElement.hidden=true;}
this.needsLayout();}
_instrumentRemoved(event)
{let instrument=event.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);let overviewGraph=this._overviewGraphsByTypeMap.get(timeline.type);let treeElement=this._treeElementsByTypeMap.get(timeline.type);let shouldSuppressOnDeselect=false;let shouldSuppressSelectSibling=true;this._timelinesTreeOutline.removeChild(treeElement,shouldSuppressOnDeselect,shouldSuppressSelectSibling);overviewGraph.removeEventListener(WI.TimelineOverviewGraph.Event.RecordSelected,this._handleOverviewGraphRecordSelected,this);this._graphsContainerView.removeSubview(overviewGraph);this._overviewGraphsByTypeMap.delete(timeline.type);this._treeElementsByTypeMap.delete(timeline.type);}
_markerAdded(event)
{this._timelineRuler.addMarker(event.data.marker);}
_handleGraphsContainerClick(event)
{if(event.__timelineRecordClickEventHandled)
return;this._recordSelected(null,null);}
_timelineRulerMouseDown(event)
{this._timelineRulerSelectionChanged=false;}
_timelineRulerMouseClicked(event)
{if(this._timelineRulerSelectionChanged)
return;for(let overviewGraph of this._overviewGraphsByTypeMap.values()){if(overviewGraph.hidden)
continue;let graphRect=overviewGraph.element.getBoundingClientRect();if(!(event.pageX>=graphRect.left&&event.pageX<=graphRect.right&&event.pageY>=graphRect.top&&event.pageY<=graphRect.bottom))
continue;let newClickEvent=new event.constructor(event.type,event);overviewGraph.element.dispatchEvent(newClickEvent);return;}}
_timeRangeSelectionChanged(event)
{this._timelineRulerSelectionChanged=true;let startTime=this._viewMode===WI.TimelineOverview.ViewMode.Timelines?this._startTime:0;this._currentSettings.selectionStartValueSetting.value=this.selectionStartTime-startTime;this._currentSettings.selectionDurationSetting.value=this.selectionDuration;this.dispatchEventToListeners(WI.TimelineOverview.Event.TimeRangeSelectionChanged);}
_handleOverviewGraphRecordSelected(event)
{let{record,recordBar}=event.data;if(!record)
return;this._recordSelected(record,recordBar);}
_recordSelected(record,recordBar)
{if(record===this._selectedTimelineRecord)
return;if(this._selectedTimelineRecord&&(!record||this._selectedTimelineRecord.type!==record.type)){let timelineOverviewGraph=this._overviewGraphsByTypeMap.get(this._selectedTimelineRecord.type);if(timelineOverviewGraph)
timelineOverviewGraph.selectedRecord=null;}
this._selectedTimelineRecord=record;if(this._selectedTimelineRecord){let firstRecord=this._selectedTimelineRecord;let lastRecord=this._selectedTimelineRecord;if(recordBar){firstRecord=recordBar.records[0];lastRecord=recordBar.records.lastValue;}
let startTime=firstRecord instanceof WI.RenderingFrameTimelineRecord?firstRecord.frameIndex:firstRecord.startTime;let endTime=lastRecord instanceof WI.RenderingFrameTimelineRecord?lastRecord.frameIndex:lastRecord.endTime;if(startTime<this.selectionStartTime||(endTime>this.selectionStartTime+this.selectionDuration)||firstRecord instanceof WI.CPUTimelineRecord){let selectionPadding=this.secondsPerPixel*10;this.selectionStartTime=startTime-selectionPadding;this.selectionDuration=endTime-startTime+(selectionPadding*2);}}
this.dispatchEventToListeners(WI.TimelineOverview.Event.RecordSelected,{record:this._selectedTimelineRecord});}
_resetSelection()
{function reset(settings)
{settings.durationPerPixelSetting.reset();settings.selectionStartValueSetting.reset();settings.selectionDurationSetting.reset();}
reset(this._timelinesViewModeSettings);if(this._renderingFramesViewModeSettings)
reset(this._renderingFramesViewModeSettings);this.secondsPerPixel=this._currentSettings.durationPerPixelSetting.value;this.selectionStartTime=this._currentSettings.selectionStartValueSetting.value;this.selectionDuration=this._currentSettings.selectionDurationSetting.value;}
_recordingReset(event)
{this._timelineRuler.clearMarkers();this._timelineRuler.addMarker(this._currentTimeMarker);}
_canShowTimelineType(type)
{let timelineViewMode=WI.TimelineOverview.ViewMode.Timelines;if(type===WI.TimelineRecord.Type.RenderingFrame)
timelineViewMode=WI.TimelineOverview.ViewMode.RenderingFrames;return timelineViewMode===this._viewMode;}
_viewModeDidChange()
{let startTime=0;let isRenderingFramesMode=this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames;if(isRenderingFramesMode){this._timelineRuler.minimumSelectionDuration=1;this._timelineRuler.snapInterval=1;this._timelineRuler.formatLabelCallback=(value)=>value.maxDecimals(0).toLocaleString();}else{this._timelineRuler.minimumSelectionDuration=0.01;this._timelineRuler.snapInterval=NaN;this._timelineRuler.formatLabelCallback=null;startTime=this._startTime;}
this.pixelAlignDuration=isRenderingFramesMode;this.selectionStartTime=this._currentSettings.selectionStartValueSetting.value+startTime;this.selectionDuration=this._currentSettings.selectionDurationSetting.value;for(let[type,overviewGraph]of this._overviewGraphsByTypeMap){let treeElement=this._treeElementsByTypeMap.get(type);let hidden=!this._canShowTimelineType(type);treeElement.hidden=hidden;overviewGraph.hidden=hidden;}
this.element.classList.toggle("frames",isRenderingFramesMode);if(this.didInitialLayout)
this.updateLayout(WI.View.LayoutReason.Resize);}
_createViewModeSettings(viewMode,minimumDurationPerPixel,maximumDurationPerPixel,durationPerPixel,selectionStartValue,selectionDuration)
{durationPerPixel=Math.min(maximumDurationPerPixel,Math.max(minimumDurationPerPixel,durationPerPixel));let durationPerPixelSetting=new WI.Setting(viewMode+"-duration-per-pixel",durationPerPixel);let selectionStartValueSetting=new WI.Setting(viewMode+"-selection-start-value",selectionStartValue);let selectionDurationSetting=new WI.Setting(viewMode+"-selection-duration",selectionDuration);return{scrollStartTime:0,minimumDurationPerPixel,maximumDurationPerPixel,durationPerPixelSetting,selectionStartValueSetting,selectionDurationSetting};}
get _currentSettings()
{return this._viewMode===WI.TimelineOverview.ViewMode.Timelines?this._timelinesViewModeSettings:this._renderingFramesViewModeSettings;}
_timelinesTreeSelectionDidChange(event)
{let timeline=null;let selectedTreeElement=this._timelinesTreeOutline.selectedTreeElement;if(selectedTreeElement){timeline=selectedTreeElement.representedObject;for(let[type,overviewGraph]of this._overviewGraphsByTypeMap)
overviewGraph.selected=type===timeline.type;}
this._selectedTimeline=timeline;this.dispatchEventToListeners(WI.TimelineOverview.Event.TimelineSelected);}
_toggleEditingInstruments(event)
{if(this._editingInstruments)
this._stopEditingInstruments();else
this._startEditingInstruments();}
_editingInstrumentsDidChange()
{this.element.classList.toggle(WI.TimelineOverview.EditInstrumentsStyleClassName,this._editingInstruments);this._timelineRuler.enabled=!this._editingInstruments;this._updateWheelAndGestureHandlers();this._updateEditInstrumentsButton();this.dispatchEventToListeners(WI.TimelineOverview.Event.EditingInstrumentsDidChange);}
_updateEditInstrumentsButton()
{let newLabel=this._editingInstruments?WI.UIString("Done"):WI.UIString("Edit");this._editInstrumentsButton.label=newLabel;this._editInstrumentsButton.activated=this._editingInstruments;this._editInstrumentsButton.enabled=!WI.timelineManager.isCapturing();}
_updateWheelAndGestureHandlers()
{if(this._editingInstruments){this.element.removeEventListener("wheel",this._handleWheelEventListener);this.element.removeEventListener("gesturestart",this._handleGestureStartEventListener);this.element.removeEventListener("gesturechange",this._handleGestureChangeEventListener);this.element.removeEventListener("gestureend",this._handleGestureEndEventListener);this._handleWheelEventListener=null;this._handleGestureStartEventListener=null;this._handleGestureChangeEventListener=null;this._handleGestureEndEventListener=null;}else{this._handleWheelEventListener=this._handleWheelEvent.bind(this);this._handleGestureStartEventListener=this._handleGestureStart.bind(this);this._handleGestureChangeEventListener=this._handleGestureChange.bind(this);this._handleGestureEndEventListener=this._handleGestureEnd.bind(this);this.element.addEventListener("wheel",this._handleWheelEventListener);this.element.addEventListener("gesturestart",this._handleGestureStartEventListener);this.element.addEventListener("gesturechange",this._handleGestureChangeEventListener);this.element.addEventListener("gestureend",this._handleGestureEndEventListener);}}
_startEditingInstruments()
{if(this._editingInstruments)
return;this._editingInstruments=true;for(let type of this._instrumentTypes){let treeElement=this._treeElementsByTypeMap.get(type);if(!treeElement){let timeline=this._recording.timelines.get(type);const placeholder=true;treeElement=new WI.TimelineTreeElement(timeline,placeholder);let insertionIndex=insertionIndexForObjectInListSortedByFunction(treeElement,this._timelinesTreeOutline.children,this._compareTimelineTreeElements.bind(this));this._timelinesTreeOutline.insertChild(treeElement,insertionIndex);let placeholderGraph=new WI.View;placeholderGraph.element.classList.add("timeline-overview-graph");treeElement[WI.TimelineOverview.PlaceholderOverviewGraph]=placeholderGraph;this._graphsContainerView.insertSubviewBefore(placeholderGraph,this._graphsContainerView.subviews[insertionIndex]);}
treeElement.editing=true;treeElement.addEventListener(WI.TimelineTreeElement.Event.EnabledDidChange,this._timelineTreeElementEnabledDidChange,this);}
this._editingInstrumentsDidChange();}
_stopEditingInstruments()
{if(!this._editingInstruments)
return;this._editingInstruments=false;let instruments=this._recording.instruments;for(let treeElement of this._treeElementsByTypeMap.values()){if(treeElement.status.checked){treeElement.editing=false;treeElement.removeEventListener(WI.TimelineTreeElement.Event.EnabledDidChange,this._timelineTreeElementEnabledDidChange,this);continue;}
let timelineInstrument=instruments.find((instrument)=>instrument.timelineRecordType===treeElement.representedObject.type);this._recording.removeInstrument(timelineInstrument);}
let placeholderTreeElements=this._timelinesTreeOutline.children.filter((treeElement)=>treeElement.placeholder);for(let treeElement of placeholderTreeElements){this._timelinesTreeOutline.removeChild(treeElement);let placeholderGraph=treeElement[WI.TimelineOverview.PlaceholderOverviewGraph];this._graphsContainerView.removeSubview(placeholderGraph);if(treeElement.status.checked){let instrument=WI.Instrument.createForTimelineType(treeElement.representedObject.type);this._recording.addInstrument(instrument);}}
let instrumentTypes=instruments.map((instrument)=>instrument.timelineRecordType);WI.timelineManager.enabledTimelineTypes=instrumentTypes;this._editingInstrumentsDidChange();}
_handleTimelineCapturingStateChanged(event)
{switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Active:this._editInstrumentsButton.enabled=false;this._stopEditingInstruments();break;case WI.TimelineManager.CapturingState.Inactive:this._editInstrumentsButton.enabled=true;break;}}
_recordingImported(event)
{let{overviewData}=event.data;if(overviewData.secondsPerPixel!==undefined)
this.secondsPerPixel=overviewData.secondsPerPixel;if(overviewData.scrollStartTime!==undefined)
this.scrollStartTime=overviewData.scrollStartTime;if(overviewData.selectionStartTime!==undefined)
this.selectionStartTime=overviewData.selectionStartTime;if(overviewData.selectionDuration!==undefined){if(overviewData.selectionDuration===Number.MAX_VALUE)
this._timelineRuler.selectEntireRange();else
this.selectionDuration=overviewData.selectionDuration;}
if(overviewData.selectedTimelineType!==undefined){let timeline=this._recording.timelineForRecordType(overviewData.selectedTimelineType);if(timeline)
this.selectedTimeline=timeline;}}
_compareTimelineTreeElements(a,b)
{let aTimelineType=a.representedObject.type;let bTimelineType=b.representedObject.type;if(aTimelineType===WI.TimelineRecord.Type.RenderingFrame)
return 1;if(bTimelineType===WI.TimelineRecord.Type.RenderingFrame)
return-1;if(a.placeholder!==b.placeholder)
return a.placeholder?1:-1;let aTimelineIndex=this._instrumentTypes.indexOf(aTimelineType);let bTimelineIndex=this._instrumentTypes.indexOf(bTimelineType);return aTimelineIndex-bTimelineIndex;}
_timelineTreeElementEnabledDidChange(event)
{let enabled=this._timelinesTreeOutline.children.some((treeElement)=>{let timelineType=treeElement.representedObject.type;return this._canShowTimelineType(timelineType)&&treeElement.status.checked;});this._editInstrumentsButton.enabled=enabled;}};WI.TimelineOverview.PlaceholderOverviewGraph=Symbol("placeholder-overview-graph");WI.TimelineOverview.ScrollDeltaDenominator=500;WI.TimelineOverview.EditInstrumentsStyleClassName="edit-instruments";WI.TimelineOverview.MinimumDurationPerPixel=0.0001;WI.TimelineOverview.MaximumDurationPerPixel=60;WI.TimelineOverview.ViewMode={Timelines:"timeline-overview-view-mode-timelines",RenderingFrames:"timeline-overview-view-mode-rendering-frames"};WI.TimelineOverview.Event={EditingInstrumentsDidChange:"editing-instruments-did-change",RecordSelected:"timeline-overview-record-selected",TimelineSelected:"timeline-overview-timeline-selected",TimeRangeSelectionChanged:"timeline-overview-time-range-selection-changed"};WI.TimelineRecordTreeElement=class TimelineRecordTreeElement extends WI.GeneralTreeElement
{constructor(timelineRecord,subtitleNameStyle,includeDetailsInMainTitle,sourceCodeLocation,representedObject)
{sourceCodeLocation=sourceCodeLocation||timelineRecord.sourceCodeLocation||null;let alternateSubtitle=null;if(includeDetailsInMainTitle&&timelineRecord.type===WI.TimelineRecord.Type.Script&&timelineRecord.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled){let timeoutString=Number.secondsToString(timelineRecord.details.timeout/1000);alternateSubtitle=document.createElement("span");alternateSubtitle.classList.add("alternate-subtitle");if(timelineRecord.details.repeating)
alternateSubtitle.textContent=WI.UIString("%s interval").format(timeoutString);else
alternateSubtitle.textContent=WI.UIString("%s delay").format(timeoutString);}
let subtitle=null;if(sourceCodeLocation){subtitle=document.createElement("span");if(subtitleNameStyle!==WI.SourceCodeLocation.NameStyle.None)
sourceCodeLocation.populateLiveDisplayLocationString(subtitle,"textContent",null,subtitleNameStyle);else
sourceCodeLocation.populateLiveDisplayLocationString(subtitle,"textContent",null,WI.SourceCodeLocation.NameStyle.None,WI.UIString("line "));}
let iconStyleClass=WI.TimelineTabContentView.iconClassNameForRecord(timelineRecord);let title=WI.TimelineTabContentView.displayNameForRecord(timelineRecord);super([iconStyleClass],title,subtitle,representedObject||timelineRecord);this._record=timelineRecord;this._sourceCodeLocation=sourceCodeLocation;if(this._sourceCodeLocation)
this.tooltipHandledSeparately=true;if(alternateSubtitle)
this.titlesElement.appendChild(alternateSubtitle);} 
get record()
{return this._record;}
get filterableData()
{var url=this._sourceCodeLocation?this._sourceCodeLocation.sourceCode.url:"";return{text:[this.mainTitle,url||"",this._record.details||""]};}
get sourceCodeLocation()
{return this._sourceCodeLocation;} 
onattach()
{super.onattach();if(!this.tooltipHandledSeparately)
return;var tooltipPrefix=this.mainTitle+"\n";this._sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element,tooltipPrefix);}};WI.TimelineRecordTreeElement.StyleRecordIconStyleClass="style-record";WI.TimelineRecordTreeElement.LayoutRecordIconStyleClass="layout-record";WI.TimelineRecordTreeElement.PaintRecordIconStyleClass="paint-record";WI.TimelineRecordTreeElement.CompositeRecordIconStyleClass="composite-record";WI.TimelineRecordTreeElement.RenderingFrameRecordIconStyleClass="rendering-frame-record";WI.TimelineRecordTreeElement.APIRecordIconStyleClass="api-record";WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass="evaluated-record";WI.TimelineRecordTreeElement.EventRecordIconStyleClass="event-record";WI.TimelineRecordTreeElement.TimerRecordIconStyleClass="timer-record";WI.TimelineRecordTreeElement.ProbeRecordIconStyleClass="probe-record";WI.TimelineRecordTreeElement.ConsoleProfileIconStyleClass="console-profile-record";WI.TimelineRecordTreeElement.GarbageCollectionIconStyleClass="garbage-collection-profile-record";WI.TimelineTreeElement=class TimelineTreeElement extends WI.GeneralTreeElement
{constructor(timeline,placeholder)
{let displayName=WI.TimelineTabContentView.displayNameForTimelineType(timeline.type);let iconClassName=WI.TimelineTabContentView.iconClassNameForTimelineType(timeline.type);let genericClassName=WI.TimelineTabContentView.genericClassNameForTimelineType(timeline.type);super([iconClassName,genericClassName],displayName,"",timeline);this._placeholder=placeholder||false;this.editing=this._placeholder;this.tooltipHandledSeparately=true;} 
get placeholder()
{return this._placeholder;}
get editing()
{return this._editing;}
set editing(x)
{if(this._editing===x)
return;this._editing=x;this.selectable=!this._editing;this._updateStatusButton();} 
onattach()
{super.onattach();this.listItemElement.addEventListener("click",this._clickHandler.bind(this));} 
_showCloseButton()
{let tooltip=WI.UIString("Close %s timeline view").format(this.mainTitle);let button=new WI.TreeElementStatusButton(WI.ImageUtilities.useSVGSymbol("Images/CloseLarge.svg","close-button",tooltip));button.addEventListener(WI.TreeElementStatusButton.Event.Clicked,function(event){this.deselect();},this);this.status=button.element;}
_showCheckbox()
{let checkboxElement=document.createElement("input");checkboxElement.type="checkbox";checkboxElement.checked=!this._placeholder;let button=new WI.TreeElementStatusButton(checkboxElement);checkboxElement.addEventListener("change",()=>{this._dispatchEnabledDidChangeEvent();});this.status=checkboxElement;}
_updateStatusButton()
{if(this._editing)
this._showCheckbox();else
this._showCloseButton();}
_clickHandler()
{if(!this._editing)
return;this.status.checked=!this.status.checked;this._dispatchEnabledDidChangeEvent();}
_dispatchEnabledDidChangeEvent()
{this.dispatchEventToListeners(WI.TimelineTreeElement.Event.EnabledDidChange);}};WI.TimelineTreeElement.Event={EnabledDidChange:"timeline-tree-element-enabled-did-change"};WI.GeneralStyleDetailsSidebarPanel=class GeneralStyleDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel
{constructor(identifier,displayName,panelConstructor)
{super(identifier,displayName);this.element.classList.add("css-style");this._panel=new panelConstructor(this);this._panel.addEventListener(WI.StyleDetailsPanel.Event.NodeChanged,this._handleNodeChanged,this);this._classListContainerToggledSetting=new WI.Setting("class-list-container-toggled",false);this._forcedPseudoClassCheckboxes={};} 
get panel(){return this._panel;}
get minimumWidth()
{let minimumWidth=Math.max(super.minimumWidth,this._panel.minimumWidth||0);if(this._forcedPseudoClassContainer&&this.exclusive){let pseudoClassMinimumWidth=0;for(let child of this._forcedPseudoClassContainer.children)
pseudoClassMinimumWidth+=child.offsetWidth;minimumWidth=Math.max(minimumWidth,pseudoClassMinimumWidth);}
return minimumWidth;}
supportsDOMNode(nodeToInspect)
{return nodeToInspect.nodeType()===Node.ELEMENT_NODE;}
attached()
{super.attached();if(!this._panel)
return;this._updateNoForcedPseudoClassesScrollOffset();this._panel.markAsNeedsRefresh(this.domNode);} 
styleDetailsPanelFocusLastPseudoClassCheckbox(styleDetailsPanel)
{this._forcedPseudoClassCheckboxes[WI.CSSManager.ForceablePseudoClasses.lastValue].focus();}
styleDetailsPanelFocusFilterBar(styleDetailsPanel)
{if(this._filterBar)
this._filterBar.inputField.focus();} 
layout()
{let domNode=this.domNode;if(!domNode||domNode.destroyed)
return;this.contentView.element.scrollTop=this._initialScrollOffset;this._panel.markAsNeedsRefresh(domNode);this._updatePseudoClassCheckboxes();this._populateClassToggles();}
addEventListeners()
{let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode)
return;effectiveDOMNode.addEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassCheckboxes,this);effectiveDOMNode.addEventListener(WI.DOMNode.Event.AttributeModified,this._handleNodeAttributeModified,this);effectiveDOMNode.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._handleNodeAttributeRemoved,this);}
removeEventListeners()
{let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode)
return;effectiveDOMNode.removeEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassCheckboxes,this);effectiveDOMNode.removeEventListener(WI.DOMNode.Event.AttributeModified,this._handleNodeAttributeModified,this);effectiveDOMNode.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._handleNodeAttributeRemoved,this);}
initialLayout()
{if(WI.cssManager.canForcePseudoClasses()){this._forcedPseudoClassContainer=document.createElement("div");this._forcedPseudoClassContainer.className="pseudo-classes";let groupElement=null;WI.CSSManager.ForceablePseudoClasses.forEach(function(pseudoClass){let label=pseudoClass.capitalize();let labelElement=document.createElement("label");let checkboxElement=document.createElement("input");checkboxElement.addEventListener("keydown",this._handleForcedPseudoClassCheckboxKeydown.bind(this,pseudoClass));checkboxElement.addEventListener("change",this._forcedPseudoClassCheckboxChanged.bind(this,pseudoClass));checkboxElement.type="checkbox";this._forcedPseudoClassCheckboxes[pseudoClass]=checkboxElement;labelElement.appendChild(checkboxElement);labelElement.append(label);if(!groupElement||groupElement.children.length===2){groupElement=document.createElement("div");groupElement.className="group";this._forcedPseudoClassContainer.appendChild(groupElement);}
groupElement.appendChild(labelElement);},this);this.contentView.element.appendChild(this._forcedPseudoClassContainer);}
this._showPanel(this._panel);if(InspectorBackend.hasCommand("DOM.resolveNode")){this._classListContainer=this.element.createChild("div","class-list-container");this._classListContainer.hidden=true;this._addClassContainer=this._classListContainer.createChild("div","new-class");this._addClassContainer.title=WI.UIString("Add a Class");this._addClassContainer.addEventListener("click",this._addClassContainerClicked.bind(this));this._addClassInput=this._addClassContainer.createChild("input","class-name-input");this._addClassInput.spellcheck=false;this._addClassInput.setAttribute("placeholder",WI.UIString("Add New Class"));this._addClassInput.addEventListener("keypress",this._addClassInputKeyPressed.bind(this));this._addClassInput.addEventListener("blur",this._addClassInputBlur.bind(this));}
let optionsContainer=this.element.createChild("div","options-container");let newRuleButton=optionsContainer.createChild("img","new-rule");newRuleButton.title=WI.UIString("Add new rule");newRuleButton.addEventListener("click",this._newRuleButtonClicked.bind(this));newRuleButton.addEventListener("contextmenu",this._newRuleButtonContextMenu.bind(this));if(typeof this._panel.filterDidChange==="function"){this._filterBar=new WI.FilterBar;this._filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._filterDidChange,this);this._filterBar.inputField.addEventListener("keydown",this._handleFilterBarInputFieldKeyDown.bind(this));optionsContainer.appendChild(this._filterBar.element);}
if(this._classListContainer){this._classToggleButton=optionsContainer.createChild("button","toggle-class-toggle");this._classToggleButton.textContent=WI.UIString("Classes");this._classToggleButton.title=WI.UIString("Toggle Classes");this._classToggleButton.addEventListener("click",this._classToggleButtonClicked.bind(this));if(this._classListContainerToggledSetting.value)
this._classToggleButtonClicked();}
WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._styleSheetAddedOrRemoved,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._styleSheetAddedOrRemoved,this);}
sizeDidChange()
{super.sizeDidChange();this._updateNoForcedPseudoClassesScrollOffset();if(this._panel)
this._panel.sizeDidChange();} 
get _initialScrollOffset()
{if(!WI.cssManager.canForcePseudoClasses())
return 0;return this.domNode&&this.domNode.enabledPseudoClasses.length?0:WI.GeneralStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset;}
_updateNoForcedPseudoClassesScrollOffset()
{if(this._forcedPseudoClassContainer)
WI.GeneralStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset=this._forcedPseudoClassContainer.offsetHeight;}
_showPanel()
{this.contentView.addSubview(this._panel);this.contentView.element.classList.toggle("has-filter-bar",this._filterBar);if(this._filterBar)
this.contentView.element.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterInProgressClassName,this._filterBar.hasActiveFilters());}
_handleNodeChanged(event)
{this.contentView.element.classList.toggle("supports-new-rule",this._panel.supportsNewRule);this.contentView.element.classList.toggle("supports-toggle-css-class",this._panel.supportsToggleCSSClass);}
_handleForcedPseudoClassCheckboxKeydown(pseudoClass,event)
{if(event.key!=="Tab"||event.shiftKey)
return;if(WI.CSSManager.ForceablePseudoClasses.lastValue===pseudoClass){if(this._panel.focusFirstSection){this._panel.focusFirstSection();event.preventDefault();}}}
_forcedPseudoClassCheckboxChanged(pseudoClass,event)
{if(!this.domNode)
return;let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode)
return;effectiveDOMNode.setPseudoClassEnabled(pseudoClass,event.target.checked);this._forcedPseudoClassCheckboxes[pseudoClass].focus();}
_updatePseudoClassCheckboxes()
{if(!this.domNode)
return;let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode)
return;let enabledPseudoClasses=effectiveDOMNode.enabledPseudoClasses;for(let pseudoClass in this._forcedPseudoClassCheckboxes){let checkboxElement=this._forcedPseudoClassCheckboxes[pseudoClass];checkboxElement.checked=enabledPseudoClasses.includes(pseudoClass);}}
_handleNodeAttributeModified(event)
{if(event&&event.data&&event.data.name==="class")
this._populateClassToggles();}
_handleNodeAttributeRemoved(event)
{if(event&&event.data&&event.data.name==="class")
this._populateClassToggles();}
_newRuleButtonClicked()
{if(this._panel&&typeof this._panel.newRuleButtonClicked==="function")
this._panel.newRuleButtonClicked();}
_newRuleButtonContextMenu(event)
{if(this._panel&&typeof this._panel.newRuleButtonContextMenu==="function")
this._panel.newRuleButtonContextMenu(event);}
_classToggleButtonClicked(event)
{this._classToggleButton.classList.toggle("selected");this._classListContainer.hidden=!this._classListContainer.hidden;this._classListContainerToggledSetting.value=!this._classListContainer.hidden;this._populateClassToggles();}
_addClassContainerClicked(event)
{this._addClassContainer.classList.add("active");this._addClassInput.focus();}
_addClassInputKeyPressed(event)
{if(event.keyCode!==WI.KeyboardShortcut.Key.Enter.keyCode)
return;this._addClassFromInput();}
_addClassInputBlur(event)
{this._addClassFromInput();this._addClassContainer.classList.remove("active");}
_addClassFromInput()
{this.domNode.toggleClass(this._addClassInput.value,true);this._addClassInput.value=null;}
_populateClassToggles()
{if(!this._classListContainer||this._classListContainer.hidden)
return;while(this._classListContainer.children.length>1)
this._classListContainer.children[1].remove();let classes=this.domNode.getAttribute("class")||[];let classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol];if(!classToggledMap)
classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol]=new Map;if(classes&&classes.length){for(let className of classes.split(/\s+/))
classToggledMap.set(className,true);}
for(let[className,toggled]of classToggledMap){if((toggled&&!classes.includes(className))||(!toggled&&classes.includes(className))){toggled=!toggled;classToggledMap.set(className,toggled);}
this._createToggleForClassName(className);}}
_createToggleForClassName(className)
{if(!className||!className.length)
return;let classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol];if(!classToggledMap)
return;if(!classToggledMap.has(className))
classToggledMap.set(className,true);let toggled=classToggledMap.get(className);let classNameContainer=document.createElement("div");classNameContainer.classList.add("class-toggle");let classNameToggle=classNameContainer.createChild("input");classNameToggle.type="checkbox";classNameToggle.checked=toggled;let classNameTitle=classNameContainer.createChild("span");classNameTitle.textContent=className;classNameTitle.draggable=true;classNameTitle.addEventListener("dragstart",(event)=>{event.dataTransfer.setData(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType,className);event.dataTransfer.effectAllowed="copy";});let classNameToggleChanged=(event)=>{this.domNode.toggleClass(className,classNameToggle.checked);classToggledMap.set(className,classNameToggle.checked);};classNameToggle.addEventListener("click",classNameToggleChanged);classNameTitle.addEventListener("click",(event)=>{classNameToggle.checked=!classNameToggle.checked;classNameToggleChanged();});this._classListContainer.appendChild(classNameContainer);}
_filterDidChange()
{if(!this._filterBar)
return;this.contentView.element.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterInProgressClassName,this._filterBar.hasActiveFilters());this._panel.filterDidChange(this._filterBar);}
_handleFilterBarInputFieldKeyDown(event)
{if(event.key!=="Tab"||!event.shiftKey)
return;if(this._panel.focusLastSection){this._panel.focusLastSection();event.preventDefault();}}
_styleSheetAddedOrRemoved()
{this.needsLayout();}};WI.GeneralStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset=30;WI.GeneralStyleDetailsSidebarPanel.FilterInProgressClassName="filter-in-progress";WI.GeneralStyleDetailsSidebarPanel.FilterMatchingSectionHasLabelClassName="filter-section-has-label";WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName="filter-matching";WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName="filter-section-non-matching";WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInPropertyClassName="filter-property-non-matching";WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol=Symbol("css-style-details-sidebar-panel-toggled-classes-symbol");WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType="web-inspector/css-class";WI.RulesStyleDetailsSidebarPanel=class RulesStyleDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel
{constructor()
{super("style-rules",WI.UIString("Styles"),WI.SpreadsheetRulesStyleDetailsPanel);} 
get allowExclusivePresentation()
{return WI.settings.enableElementsTabIndependentStylesDetailsSidebarPanel.value;}};WI.ComputedStyleDetailsSidebarPanel=class ComputedStyleDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel
{constructor()
{super("style-computed",WI.UIString("Computed"),WI.ComputedStyleDetailsPanel);} 
computedStyleDetailsPanelShowProperty(property)
{let styleRulesPanel=WI.detailsSidebar.sidebarPanels.find((panel)=>panel instanceof WI.RulesStyleDetailsSidebarPanel);if(!styleRulesPanel)
return;WI.detailsSidebar.selectedSidebarPanel=styleRulesPanel;styleRulesPanel.panel.scrollToSectionAndHighlightProperty(property);}};WI.StyleDetailsPanel=class StyleDetailsPanel extends WI.View
{constructor(delegate,className,identifier,label)
{super();this._delegate=delegate||null;this.element.classList.add(className);this._navigationInfo={identifier,label};this._nodeStyles=null;} 
get navigationInfo()
{return this._navigationInfo;}
get nodeStyles()
{return this._nodeStyles;}
get supportsNewRule()
{return false;}
get supportsToggleCSSClass()
{return true;}
attached()
{super.attached();this._refreshNodeStyles();}
markAsNeedsRefresh(domNode)
{if(!domNode)
return;if(!this._nodeStyles||this._nodeStyles.node!==domNode){if(this._nodeStyles){this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.Refreshed,this.nodeStylesRefreshed,this);this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);}
this._nodeStyles=WI.cssManager.stylesForNode(domNode);this.dispatchEventToListeners(WI.StyleDetailsPanel.Event.NodeChanged);if(!this._nodeStyles)
return;this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.Refreshed,this.nodeStylesRefreshed,this);this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);this._forceSignificantChange=true;}
if(this.isAttached)
this._refreshNodeStyles();}
refresh(significantChange)
{} 
nodeStylesRefreshed(event)
{if(this.isAttached)
this._refreshPreservingScrollPosition(event.data.significantChange);} 
get _initialScrollOffset()
{if(!WI.cssManager.canForcePseudoClasses())
return 0;return this.nodeStyles.node.enabledPseudoClasses.length?0:WI.GeneralStyleDetailsSidebarPanel.NoForcedPseudoClassesScrollOffset;}
_refreshNodeStyles()
{if(!this._nodeStyles)
return;this._nodeStyles.refresh();}
_refreshPreservingScrollPosition(significantChange)
{significantChange=this._forceSignificantChange||significantChange||false;var previousScrollTop=this._initialScrollOffset;if(this.element.parentNode&&this._previousRefreshNodeIdentifier===this._nodeStyles.node.id)
previousScrollTop=this.element.parentNode.scrollTop;this.refresh(significantChange);this._previousRefreshNodeIdentifier=this._nodeStyles.node.id;if(this.element.parentNode)
this.element.parentNode.scrollTop=previousScrollTop;this._forceSignificantChange=false;}
_nodeStylesNeedsRefreshed(event)
{if(this.isAttached)
this._refreshNodeStyles();}};WI.StyleDetailsPanel.Event={NodeChanged:"style-details-panel-node-changed",};WI.AuditTabContentView=class AuditTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(AuditTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.AuditNavigationSidebarPanel,hideBackForwardButtons:true,});this._startStopShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._startStopShortcut.implicitlyPreventsDefault=false;this._startStopShortcut.disabled=true;} 
static tabInfo()
{return{identifier:AuditTabContentView.Type,image:"Images/Audit.svg",displayName:WI.UIString("Audit","Audit Tab Name","Name of Audit Tab"),};}
static isTabAllowed()
{return WI.sharedApp.isWebDebuggable();} 
get type()
{return WI.AuditTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult;}
attached()
{super.attached();this._startStopShortcut.disabled=false;}
detached()
{this._startStopShortcut.disabled=true;super.detached();} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{return event.dataTransfer.types.includes("Files");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readJSON(files,(result)=>WI.auditManager.processJSON(result));} 
initialLayout()
{super.initialLayout();let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Audit or Result");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);WI.auditManager.loadStoredTests();} 
_handleSpace(event)
{if(WI.isEventTargetAnEditableField(event))
return;if(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive)
WI.auditManager.start(this.contentBrowser.currentRepresentedObjects);else if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active)
WI.auditManager.stop();else
return;event.preventDefault();}};WI.AuditTabContentView.Type="audit";WI.ConsoleTabContentView=class ConsoleTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(ConsoleTabContentView.tabInfo(),{hideBackForwardButtons:true,disableBackForwardNavigation:true});this._wasShowingSplitConsole=false;}
static tabInfo()
{return{identifier:ConsoleTabContentView.Type,image:"Images/Console.svg",displayName:WI.UIString("Console","Console Tab Name","Name of Console Tab"),};} 
get type()
{return WI.ConsoleTabContentView.Type;}
attached()
{super.attached();this._wasShowingSplitConsole=WI.isShowingSplitConsole();if(this._wasShowingSplitConsole)
WI.hideSplitConsole();this.contentBrowser.showContentView(WI.consoleContentView);WI.consoleContentView.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);WI.consoleContentView.prompt.focus();}
detached()
{super.detached();if(this._wasShowingSplitConsole)
WI.showSplitConsole();}
showRepresentedObject(representedObject,cookie)
{

}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.LogObject;}
get supportsSplitContentBrowser()
{return false;}};WI.ConsoleTabContentView.Type="console";WI.ElementsTabContentView=class ElementsTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{let detailsSidebarPanelConstructors=[WI.RulesStyleDetailsSidebarPanel,WI.ComputedStyleDetailsSidebarPanel,];if(InspectorBackend.hasCommand("DOM.showGridOverlay"))
detailsSidebarPanelConstructors.push(WI.LayoutDetailsSidebarPanel);if(InspectorBackend.hasCommand("CSS.getFontDataForNode"))
detailsSidebarPanelConstructors.push(WI.FontDetailsSidebarPanel);detailsSidebarPanelConstructors.push(WI.ChangesDetailsSidebarPanel,WI.DOMNodeDetailsSidebarPanel);if(InspectorBackend.hasDomain("LayerTree"))
detailsSidebarPanelConstructors.push(WI.LayerTreeDetailsSidebarPanel);super(ElementsTabContentView.tabInfo(),{detailsSidebarPanelConstructors,hideBackForwardButtons:true,disableBackForwardNavigation:true});}
static tabInfo()
{return{identifier:ElementsTabContentView.Type,image:"Images/Elements.svg",displayName:WI.UIString("Elements","Elements Tab Name","Name of Elements Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("DOM");} 
get type()
{return WI.ElementsTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
get detailsSidebarExpandedByDefault()
{return true;}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.DOMTree;}
showRepresentedObject(representedObject,cookie)
{this._showDOMTreeContentViewIfNeeded();if(!cookie||!cookie.nodeToSelect)
return;let domTreeContentView=this.contentBrowser.currentContentView;domTreeContentView.selectAndRevealDOMNode(cookie.nodeToSelect);
cookie.nodeToSelect=undefined;}
attached()
{super.attached();WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._showDOMTreeContentViewIfNeeded();}
detached()
{WI.networkManager.removeEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);super.detached();}
closed()
{super.closed();WI.networkManager.removeEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);}
get allowMultipleDetailSidebars()
{return true;} 
_showDOMTreeContentViewIfNeeded()
{let mainDOMTree=WI.networkManager.mainFrame?.domTree;if(!mainDOMTree)
return;if(this.contentBrowser.currentContentView?.representedObject===mainDOMTree)
return;this.contentBrowser.showContentViewForRepresentedObject(mainDOMTree);}
_mainFrameDidChange(event)
{this._showDOMTreeContentViewIfNeeded();}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._showDOMTreeContentViewIfNeeded();}};WI.ElementsTabContentView.Type="elements";WI.GraphicsTabContentView=class GraphicsTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(GraphicsTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.CanvasSidebarPanel,detailsSidebarPanelConstructors:[WI.RecordingStateDetailsSidebarPanel,WI.RecordingTraceDetailsSidebarPanel,WI.CanvasDetailsSidebarPanel,WI.AnimationDetailsSidebarPanel,],hideBackForwardButtons:true,});this._canvasesTreeOutline=new WI.TreeOutline;this._canvasesTreeOutline.allowsRepeatSelection=true;this._canvasesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleOverviewTreeOutlineSelectionDidChange,this);this._canvasesTreeElement=new WI.GeneralTreeElement("canvas-overview",WI.UIString("Overview"),null,{[WI.ContentView.isViewableSymbol]:true});this._canvasesTreeOutline.appendChild(this._canvasesTreeElement);this._savedCanvasRecordingsTreeElement=new WI.FolderTreeElement(WI.UIString("Saved Recordings"));this._savedCanvasRecordingsTreeElement.hidden=true;this._canvasesTreeElement.appendChild(this._savedCanvasRecordingsTreeElement);this._recordShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._recordShortcut.implicitlyPreventsDefault=false;this._recordShortcut.disabled=true;this._recordSingleFrameShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._recordSingleFrameShortcut.implicitlyPreventsDefault=false;this._recordSingleFrameShortcut.disabled=true;WI.canvasManager.enable();WI.animationManager.enable();}
static tabInfo()
{return{identifier:GraphicsTabContentView.Type,image:"Images/Graphics.svg",displayName:WI.UIString("Graphics","Graphics Tab Name","Name of Graphics Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("Canvas")||InspectorBackend.hasDomain("Animation");} 
treeElementForRepresentedObject(representedObject)
{return this._canvasesTreeOutline.findTreeElement(representedObject);}
get type()
{return WI.GraphicsTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
get managesNavigationSidebarPanel()
{return true;}
showRepresentedObject(representedObject,cookie)
{if(representedObject instanceof WI.Collection){this.contentBrowser.showContentView(this._overviewContentView);return;}
super.showRepresentedObject(representedObject,cookie);}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.CanvasCollection||representedObject instanceof WI.Canvas||representedObject instanceof WI.Recording||representedObject instanceof WI.ShaderProgram||representedObject instanceof WI.AnimationCollection||representedObject instanceof WI.Animation;}
closed()
{WI.animationManager.disable();WI.canvasManager.disable();super.closed();}
restoreStateFromCookie(cookie)
{}
saveStateToCookie(cookie)
{} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{return event.dataTransfer.types.includes("Files");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readJSON(files,(result)=>WI.canvasManager.processJSON(result));} 
attached()
{super.attached();WI.canvasManager.canvasCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleCanvasAdded,this);WI.canvasManager.canvasCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleCanvasRemoved,this);WI.canvasManager.addEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSavedOrStopped,this);WI.Canvas.addEventListener(WI.Canvas.Event.RecordingStopped,this._handleRecordingSavedOrStopped,this);for(let child of this._canvasesTreeElement.children){let canvas=child.representedObject;if(canvas instanceof WI.Canvas&&!WI.canvasManager.canvasCollection.has(canvas))
this._removeCanvas(canvas);}
for(let canvas of WI.canvasManager.canvasCollection){if(!this._canvasesTreeOutline.findTreeElement(canvas))
this._addCanvas(canvas);}
for(let recording of WI.canvasManager.savedRecordings){if(!this._canvasesTreeOutline.findTreeElement(recording))
this._addRecording(recording,{suppressShowRecording:true});}
this._recordShortcut.disabled=false;this._recordSingleFrameShortcut.disabled=false;}
detached()
{this._recordShortcut.disabled=true;this._recordSingleFrameShortcut.disabled=true;WI.Canvas.removeEventListener(WI.Canvas.Event.RecordingStopped,this._handleRecordingSavedOrStopped,this);WI.canvasManager.removeEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSavedOrStopped,this);WI.canvasManager.canvasCollection.removeEventListener(WI.Collection.Event.ItemAdded,this._handleCanvasAdded,this);WI.canvasManager.canvasCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this._handleCanvasRemoved,this);super.detached();}
initialLayout()
{super.initialLayout();this._overviewContentView=new WI.GraphicsOverviewContentView;setTimeout(()=>{this.contentBrowser.showContentView(this._overviewContentView);});let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Recording");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);} 
_addCanvas(canvas)
{this._canvasesTreeElement.appendChild(new WI.CanvasTreeElement(canvas));const options={suppressShowRecording:true,};for(let recording of canvas.recordingCollection)
this._addRecording(recording,options);}
_removeCanvas(canvas)
{let treeElement=this._canvasesTreeOutline.findTreeElement(canvas);const suppressNotification=true;treeElement.deselect(suppressNotification);this._canvasesTreeElement.removeChild(treeElement);let currentContentView=this.contentBrowser.currentContentView;if(currentContentView instanceof WI.CanvasContentView&&canvas===currentContentView.representedObject)
WI.showRepresentedObject(WI.canvasManager.canvasCollection);else if(currentContentView instanceof WI.ShaderProgramContentView&&canvas===currentContentView.representedObject.canvas)
WI.showRepresentedObject(WI.canvasManager.canvasCollection);else if(currentContentView instanceof WI.RecordingContentView&&canvas.recordingCollection.has(currentContentView.representedObject))
this.contentBrowser.updateHierarchicalPathForCurrentContentView();let navigationSidebarPanel=this.navigationSidebarPanel;if(navigationSidebarPanel instanceof WI.CanvasSidebarPanel&&navigationSidebarPanel.visible)
navigationSidebarPanel.updateRepresentedObjects();this.showDetailsSidebarPanels();}
_addRecording(recording,options={})
{if(!recording.source){const subtitle=null;let recordingTreeElement=new WI.GeneralTreeElement(["recording"],recording.displayName,subtitle,recording);this._savedCanvasRecordingsTreeElement.hidden=false;this._savedCanvasRecordingsTreeElement.appendChild(recordingTreeElement);}
if(!options.suppressShowRecording)
this.showRepresentedObject(recording);}
_handleCanvasAdded(event)
{this._addCanvas(event.data.item);}
_handleCanvasRemoved(event)
{this._removeCanvas(event.data.item);}
_handleOverviewTreeOutlineSelectionDidChange(event)
{let selectedElement=this._canvasesTreeOutline.selectedTreeElement;if(!selectedElement)
return;switch(selectedElement){case this._canvasesTreeElement:case this._savedCanvasRecordingsTreeElement:this.contentBrowser.showContentView(this._overviewContentView);return;}
let representedObject=selectedElement.representedObject;if(!this.canShowRepresentedObject(representedObject)){return;}
this.showRepresentedObject(representedObject);}
_handleRecordingSavedOrStopped(event)
{let{recording,initiatedByUser,imported}=event.data;if(!recording)
return;let options={};if(recording.source||!imported)
options.suppressShowRecording=!initiatedByUser||this.contentBrowser.currentRepresentedObjects.some((representedObject)=>representedObject instanceof WI.Recording);this._addRecording(recording,options);}
_handleSpace(event)
{if(WI.isEventTargetAnEditableField(event))
return;if(!this.navigationSidebarPanel)
return;let canvas=this.navigationSidebarPanel.canvas;if(!canvas)
return;if(canvas.recordingActive)
canvas.stopRecording();else{let singleFrame=!!event.shiftKey;canvas.startRecording(singleFrame);}
event.preventDefault();}};WI.GraphicsTabContentView.Type="graphics";WI.LayersTabContentView=class LayersTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(LayersTabContentView.tabInfo(),{detailsSidebarPanelConstructors:[WI.LayerDetailsSidebarPanel],hideBackForwardButtons:true,disableBackForwardNavigation:true,});this._layerDetailsSidebarPanel=this.detailsSidebarPanels[0];this._layerDetailsSidebarPanel.addEventListener(WI.LayerDetailsSidebarPanel.Event.SelectedLayerChanged,this._detailsSidebarSelectedLayerChanged,this);this._layers3DContentView=new WI.Layers3DContentView;this._layers3DContentView.addEventListener(WI.Layers3DContentView.Event.SelectedLayerChanged,this._contentViewSelectedLayerChanged,this);} 
static tabInfo()
{return{identifier:LayersTabContentView.Type,image:"Images/Layers.svg",displayName:WI.UIString("Layers","Layers Tab Name","Name of Layers Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("LayerTree");} 
get type(){return WI.LayersTabContentView.Type;}
get supportsSplitContentBrowser(){return false;}
selectLayerForNode(node)
{this._layers3DContentView.selectLayerForNode(node);}
attached()
{super.attached();this.contentBrowser.showContentView(this._layers3DContentView);} 
_detailsSidebarSelectedLayerChanged(event)
{this._layers3DContentView.selectLayerById(event.data.layerId);}
_contentViewSelectedLayerChanged(event)
{this._layerDetailsSidebarPanel.selectNodeByLayerId(event.data.layerId);}};WI.LayersTabContentView.Type="layers";WI.ResourceTreeElement=class ResourceTreeElement extends WI.SourceCodeTreeElement
{constructor(resource,representedObject,{allowDirectoryAsName,hideOrigin}={})
{const title=null;const subtitle=null;let styleClassNames=["resource",WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(resource)];super(resource,styleClassNames,title,subtitle,representedObject||resource);if(allowDirectoryAsName)
this._allowDirectoryAsName=allowDirectoryAsName;if(hideOrigin)
this._hideOrigin=hideOrigin;this._updateResource(resource);} 
static compareResourceTreeElements(a,b)
{let resourceA=a.resource||a.representedObject;let resourceB=b.resource||b.representedObject;function resolvedType(resource){if(resource instanceof WI.Resource)
return resource.type;if(resource instanceof WI.CSSStyleSheet)
return WI.Resource.Type.StyleSheet;if(resource instanceof WI.Script)
return WI.Resource.Type.Script;return WI.Resource.Type.Other;}
let typeA=resolvedType(resourceA);let typeB=resolvedType(resourceB);var comparisonResult=typeA.extendedLocaleCompare(typeB);if(comparisonResult!==0)
return comparisonResult;if(typeA===WI.Resource.Type.XHR||typeA===WI.Resource.Type.Fetch||typeA===WI.Resource.Type.WebSocket)
return resourceA.firstTimestamp-resourceB.firstTimestamp||0;


comparisonResult=a.subtitle.extendedLocaleCompare(b.subtitle);if(comparisonResult!==0)
return comparisonResult;return a.mainTitle.extendedLocaleCompare(b.mainTitle);}
static compareFolderAndResourceTreeElements(a,b)
{var aIsFolder=a instanceof WI.FolderTreeElement;var bIsFolder=b instanceof WI.FolderTreeElement;if(aIsFolder&&!bIsFolder)
return-1;if(!aIsFolder&&bIsFolder)
return 1;if(aIsFolder&&bIsFolder)
return a.mainTitle.extendedLocaleCompare(b.mainTitle);return WI.ResourceTreeElement.compareResourceTreeElements(a,b);} 
get resource()
{return this._resource;}
get filterableData()
{let urlComponents=this._resource.urlComponents;return{text:[urlComponents.lastPathComponent,urlComponents.path,this._resource.url]};}
ondblclick()
{if(this._resource.type===WI.Resource.Type.WebSocket)
return;WI.openURL(this._resource.url);}
_updateResource(resource)
{
if(this._resource){this._resource.removeEventListener(WI.Resource.Event.URLDidChange,this._urlDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._typeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFinish,this.updateStatus,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFail,this.updateStatus,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._responseReceived,this);}
this._updateSourceCode(resource);this._resource=resource;resource.addEventListener(WI.Resource.Event.URLDidChange,this._urlDidChange,this);resource.addEventListener(WI.Resource.Event.TypeDidChange,this._typeDidChange,this);resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this.updateStatus,this);resource.addEventListener(WI.Resource.Event.LoadingDidFail,this.updateStatus,this);resource.addEventListener(WI.Resource.Event.ResponseReceived,this._responseReceived,this);this._updateTitles();this.updateStatus();this._updateToolTip();this._updateIcon();} 
get mainTitleText()
{return WI.displayNameForURL(this._resource.url,this._resource.urlComponents,{allowDirectoryAsName:this._allowDirectoryAsName,});}
_updateTitles()
{var frame=this._resource.parentFrame;var target=this._resource.target;var isMainResource=this._resource.isMainResource();var parentResourceHost=target.mainResource?target.mainResource.urlComponents.host:null;if(isMainResource&&frame){parentResourceHost=frame.parentFrame?frame.parentFrame.mainResource.urlComponents.host:null;}else if(frame){parentResourceHost=frame.mainResource.urlComponents.host;}
var urlComponents=this._resource.urlComponents;var oldMainTitle=this.mainTitle;this.mainTitle=this.mainTitleText;if(!this._hideOrigin){if(this._resource.localResourceOverride){if(WI.NetworkManager.supportsOverridingRequests())
this.subtitle=WI.LocalResourceOverride.displayNameForType(this._resource.localResourceOverride.type);else{let localResourceOverrideHost=urlComponents.host;let mainFrameHost=(WI.networkManager.mainFrame&&WI.networkManager.mainFrame.mainResource)?WI.networkManager.mainFrame.mainResource.urlComponents.host:null;let subtitle=localResourceOverrideHost!==mainFrameHost?localResourceOverrideHost:null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;}}else{let subtitle=(parentResourceHost!==urlComponents.host||(frame&&frame.isMainFrame()&&isMainResource))?WI.displayNameForHost(urlComponents.host):null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;}}
if(oldMainTitle!==this.mainTitle)
this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange",[this,oldMainTitle]);}
updateStatus()
{super.updateStatus();if(!this._resource)
return;if(this._resource.hadLoadingError())
this.addClassName(WI.ResourceTreeElement.FailedStyleClassName);else
this.removeClassName(WI.ResourceTreeElement.FailedStyleClassName);if(this._resource.isLoading()){if(!this.status||!this.status[WI.ResourceTreeElement.SpinnerSymbol]){let spinner=new WI.IndeterminateProgressSpinner;if(this.status)
this.statusElement.insertAdjacentElement("afterbegin",spinner.element);else
this.status=spinner.element;this.status[WI.ResourceTreeElement.SpinnerSymbol]=spinner.element;}}else{if(this.status&&this.status[WI.ResourceTreeElement.SpinnerSymbol]){if(this.status===this.status[WI.ResourceTreeElement.SpinnerSymbol])
this.status=null;else{this.status[WI.ResourceTreeElement.SpinnerSymbol].remove();this.status[WI.ResourceTreeElement.SpinnerSymbol]=null;}}}}
populateContextMenu(contextMenu,event)
{WI.appendContextMenuItemsForSourceCode(contextMenu,this._resource);super.populateContextMenu(contextMenu,event);} 
_updateToolTip()
{this.tooltip=this._resource.displayURL;}
_updateIcon()
{let isOverride=!!this._resource.localResourceOverride;let wasOverridden=this._resource.responseSource===WI.Resource.ResponseSource.InspectorOverride;if(isOverride||wasOverridden)
this.addClassName("override");else
this.removeClassName("override");this.iconElement.title=wasOverridden?WI.UIString("This resource was loaded from a local override"):"";}
_urlDidChange(event)
{this._updateTitles();this._updateToolTip();}
_typeDidChange(event)
{this.removeClassName(event.data.oldType);this.addClassName(this._resource.type);this.callFirstAncestorFunction("descendantResourceTreeElementTypeDidChange",[this,event.data.oldType]);}
_responseReceived(event)
{this._updateIcon();}};WI.ResourceTreeElement.ResourceIconStyleClassName="resource-icon";WI.ResourceTreeElement.FailedStyleClassName="failed";WI.ResourceTreeElement.SpinnerSymbol=Symbol("spinner");WI.ScriptTreeElement=class ScriptTreeElement extends WI.SourceCodeTreeElement
{constructor(script,options={})
{let scriptDisplayName=script.displayName;let title=options.mainTitle||scriptDisplayName;let subtitle=null;let tooltip=null;let classNames=["script"];if(script.url&&!script.dynamicallyAddedScriptElement){if(script.urlComponents.scheme!=="web-inspector"){let host=WI.displayNameForHost(script.urlComponents.host);if(host&&title!==host)
subtitle=host;else if(scriptDisplayName&&title!==scriptDisplayName)
subtitle=scriptDisplayName;tooltip=script.url;}
classNames.push(WI.ResourceTreeElement.ResourceIconStyleClassName);classNames.push(WI.Resource.Type.Script);}else
classNames.push(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);if(script.isMainResource()){classNames.push("worker-icon");}
super(script,classNames,title,subtitle);this._script=script;if(tooltip)
this.tooltip=tooltip;} 
get script()
{return this._script;}};WI.ScriptTreeElement.AnonymousScriptIconStyleClassName="anonymous-script-icon";WI.SearchTabContentView=class SearchTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{let detailsSidebarPanelConstructors=[WI.ResourceDetailsSidebarPanel,WI.ProbeDetailsSidebarPanel,WI.DOMNodeDetailsSidebarPanel,WI.ComputedStyleDetailsSidebarPanel,WI.RulesStyleDetailsSidebarPanel,];if(InspectorBackend.hasDomain("LayerTree"))
detailsSidebarPanelConstructors.push(WI.LayerTreeDetailsSidebarPanel);super(SearchTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.SearchSidebarPanel,detailsSidebarPanelConstructors,});this._forcePerformSearch=false;}
static tabInfo()
{return{identifier:SearchTabContentView.Type,image:"Images/Search.svg",displayName:WI.UIString("Search","Search Tab Name","Name of Search Tab"),title:WI.UIString("Search (%s)","Search Tab Title","Title of Search Tab with keyboard shortcut").format(WI.searchKeyboardShortcut.displayName),};}
static shouldPinTab()
{return true;}
static shouldSaveTab()
{return false;} 
get type()
{return WI.SearchTabContentView.Type;}
attached()
{super.attached();setTimeout(this.focusSearchField.bind(this));}
canShowRepresentedObject(representedObject)
{if(representedObject instanceof WI.DOMTree)
return true;if(!(representedObject instanceof WI.Resource)&&!(representedObject instanceof WI.Script))
return false;return!!this.navigationSidebarPanel.contentTreeOutline.getCachedTreeElement(representedObject);}
focusSearchField()
{this.navigationSidebarPanel.focusSearchField(this._forcePerformSearch);this._forcePerformSearch=false;}
performSearch(searchQuery)
{this.navigationSidebarPanel.performSearch(searchQuery);this._forcePerformSearch=false;}
handleCopyEvent(event)
{let contentTreeOutline=this.navigationSidebarPanel.contentTreeOutline;if(contentTreeOutline.element!==document.activeElement)
return;let selectedTreeElement=contentTreeOutline.selectedTreeElement;if(!selectedTreeElement)
return;event.clipboardData.setData("text/plain",selectedTreeElement.synthesizedTextValue);event.stopPropagation();event.preventDefault();} 
initialLayout()
{super.initialLayout();this._forcePerformSearch=true;}};WI.SearchTabContentView.Type="search";WI.SettingsTabContentView=class SettingsTabContentView extends WI.TabContentView
{constructor()
{super(SettingsTabContentView.tabInfo());this._selectedSettingsView=null;this._settingsViews=[];}
static tabInfo()
{return{identifier:SettingsTabContentView.Type,image:"Images/Gear.svg",displayName:WI.UIString("Settings","Settings Tab Name","Name of Settings Tab"),title:WI.UIString("Settings (%s)","Settings Tab Title","Title of Settings Tab with keyboard shortcut").format(WI.settingsKeyboardShortcut.displayName),};}
static shouldPinTab()
{return true;}
static shouldSaveTab()
{return false;} 
get type(){return WI.SettingsTabContentView.Type;}
get supportsSplitContentBrowser()
{return false;}
get selectedSettingsView()
{return this._selectedSettingsView;}
set selectedSettingsView(settingsView)
{if(this._selectedSettingsView===settingsView)
return;if(this._selectedSettingsView)
this.replaceSubview(this._selectedSettingsView,settingsView);else
this.addSubview(settingsView);this._selectedSettingsView=settingsView;this._selectedSettingsView.updateLayout();let navigationItem=this._navigationBar.findNavigationItem(settingsView.identifier);if(!navigationItem)
return;this._navigationBar.selectedNavigationItem=navigationItem;}
addSettingsView(settingsView)
{if(this._settingsViews.includes(settingsView)){return;}
this._settingsViews.push(settingsView);this._navigationBar.addNavigationItem(new WI.RadioButtonNavigationItem(settingsView.identifier,settingsView.displayName));this._updateNavigationBarVisibility();}
setSettingsViewVisible(settingsView,visible)
{let navigationItem=this._navigationBar.findNavigationItem(settingsView.identifier);if(!navigationItem)
return;if(navigationItem.hidden===!visible)
return;navigationItem.hidden=!visible;settingsView.element.classList.toggle("hidden",!visible);this._updateNavigationBarVisibility();if(!this.selectedSettingsView){if(visible)
this.selectedSettingsView=settingsView;return;}
if(this.selectedSettingsView!==settingsView)
return;let index=this._settingsViews.indexOf(settingsView);if(index===-1)
return;let previousIndex=index;while(--previousIndex>=0){let previousNavigationItem=this._navigationBar.navigationItems[previousIndex];if(!previousNavigationItem||previousNavigationItem.hidden)
continue;this.selectedSettingsView=this._settingsViews[previousIndex];return;}
let nextIndex=index;while(++nextIndex<this._settingsViews.length){let nextNavigationItem=this._navigationBar.navigationItems[nextIndex];if(!nextNavigationItem||nextNavigationItem.hidden)
continue;this.selectedSettingsView=this._settingsViews[nextIndex];return;}}
selectBlackboxPattern(regex)
{this.selectedSettingsView=this._blackboxSettingsView;this._blackboxSettingsView.selectBlackboxPattern(regex);} 
initialLayout()
{super.initialLayout();this._navigationBar=new WI.NavigationBar;this._navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._navigationItemSelected,this);this.addSubview(this._navigationBar);this._createGeneralSettingsView();this._createElementsSettingsView();this._createSourcesSettingsView();this._createConsoleSettingsView();if(WI.DebuggerManager.supportsBlackboxingScripts()){this._blackboxSettingsView=new WI.BlackboxSettingsView;this._createReferenceLink(this._blackboxSettingsView);this.addSettingsView(this._blackboxSettingsView);}
this._createExperimentalSettingsView();if(WI.isEngineeringBuild){this._createEngineeringSettingsView();WI.showDebugUISetting.addEventListener(WI.Setting.Event.Changed,this._updateDebugSettingsViewVisibility,this);this._updateDebugSettingsViewVisibility();}
this.selectedSettingsView=this._settingsViews[0];} 
_createGeneralSettingsView()
{let generalSettingsView=new WI.SettingsView("general",WI.UIString("General"));if(CSS.supports("color-scheme","light")&&CSS.supports("color-scheme","dark")){const appearanceValues=[["system",WI.UIString("System","System @ Settings General Appearance","Label of dropdown item used for forcing Web Inspector to be shown using the system's theme")],[WI.SettingEditor.SelectSpacerKey,null],["light",WI.UIString("Light","Light @ Settings General Appearance","Label of dropdown item used for forcing Web Inspector to be shown using a light theme")],["dark",WI.UIString("Dark","Dark @ Settings General Appearance","Label of dropdown item used for forcing Web Inspector to be shown using a dark theme")],];let appearanceEditor=generalSettingsView.addGroupWithCustomSetting(WI.UIString("Appearance:"),WI.SettingEditor.Type.Select,{values:appearanceValues});appearanceEditor.value=WI.settings.frontendAppearance.value;appearanceEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.settings.frontendAppearance.value=this.value;},appearanceEditor);generalSettingsView.addSeparator();}
const indentValues=[WI.UIString("Tabs"),WI.UIString("Spaces")];let indentEditor=generalSettingsView.addGroupWithCustomSetting(WI.UIString("Prefer indent using:"),WI.SettingEditor.Type.Select,{values:indentValues});indentEditor.value=indentValues[WI.settings.indentWithTabs.value?0:1];indentEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.settings.indentWithTabs.value=this.value===indentValues[0];},indentEditor);function addSpacesSetting(title,setting){let editor=generalSettingsView.addSetting(title,setting,WI.UIString("spaces"),{min:1});function updateLabel(){editor.label=setting.value===1?WI.UIString("space"):WI.UIString("spaces");}
setting.addEventListener(WI.Setting.Event.Changed,function(event){updateLabel();},editor);updateLabel();}
addSpacesSetting(WI.UIString("Tab width:"),WI.settings.tabSize);addSpacesSetting(WI.UIString("Indent width:"),WI.settings.indentUnit);generalSettingsView.addSetting(WI.UIString("Line wrapping:"),WI.settings.enableLineWrapping,WI.UIString("Wrap lines to editor width"));let showGroup=generalSettingsView.addGroup(WI.UIString("Show:"));showGroup.addSetting(WI.settings.showWhitespaceCharacters,WI.UIString("Whitespace characters"));showGroup.addSetting(WI.settings.showInvisibleCharacters,WI.UIString("Invisible characters"));generalSettingsView.addSeparator();let searchGroup=generalSettingsView.addGroup(WI.UIString("Search:","Search: @ Settings","Settings tab label for search related settings"));searchGroup.addSetting(WI.settings.searchCaseSensitive,WI.UIString("Case Sensitive","Case Sensitive @ Settings","Settings tab checkbox label for whether searches should be case sensitive."));searchGroup.addSetting(WI.settings.searchRegularExpression,WI.UIString("Regular Expression","Regular Expression @ Settings","Settings tab checkbox label for whether searches should be treated as regular expressions."));searchGroup.addSetting(WI.settings.searchFromSelection,WI.UIString("%s from selection","Global Search From Selection @ Settings","Settings tab checkbox label for whether the global search should populate from the current selection.").format(WI.searchKeyboardShortcut.displayName));generalSettingsView.addSeparator();const zoomLevels=[0.6,0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4];const zoomValues=zoomLevels.map((level)=>[level,Number.percentageString(level,0)]);let zoomEditor=generalSettingsView.addGroupWithCustomSetting(WI.UIString("Zoom:"),WI.SettingEditor.Type.Select,{values:zoomValues});zoomEditor.value=WI.getZoomFactor();zoomEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.setZoomFactor(this.value);},zoomEditor);WI.settings.zoomFactor.addEventListener(WI.Setting.Event.Changed,function(event){this.value=WI.getZoomFactor().maxDecimals(2);},zoomEditor);this._createReferenceLink(generalSettingsView);this.addSettingsView(generalSettingsView);}
_createElementsSettingsView()
{if(!InspectorBackend.hasDomain("DOM"))
return;let elementsSettingsView=new WI.SettingsView("elements",WI.UIString("Elements"));if(InspectorBackend.hasCommand("DOM.setInspectModeEnabled","showRulers")){elementsSettingsView.addSetting(WI.UIString("Element Selection:"),WI.settings.showRulersDuringElementSelection,WI.UIString("Show page rulers and node border lines"));elementsSettingsView.addSeparator();}
elementsSettingsView.addSetting(WI.UIString("Details Sidebars:","Details Sidebars: @ Settings Elements Pane","Category label for detail sidebar settings."),WI.settings.enableElementsTabIndependentStylesDetailsSidebarPanel,WI.UIString("Show independent Styles sidebar","Show independent Styles sidebar @ Settings Elements Pane","Settings tab checkbox label for whether the independent styles sidebar should be shown"));elementsSettingsView.addSeparator();let cssGroup=elementsSettingsView.addGroup(WI.UIString("CSS:"));cssGroup.addSetting(WI.settings.cssChangesPerNode,WI.UIString("Show changes only for selected node"));cssGroup.addSetting(WI.settings.showCSSPropertySyntaxInDocumentationPopover,WI.UIString("Show property syntax in documentation popover"));this._createReferenceLink(elementsSettingsView);this.addSettingsView(elementsSettingsView);}
_createSourcesSettingsView()
{let sourcesSettingsView=new WI.SettingsView("sources",WI.UIString("Sources"));sourcesSettingsView.addSetting(WI.UIString("Debugging:"),WI.settings.showScopeChainOnPause,WI.UIString("Show Scope Chain on pause"));sourcesSettingsView.addSeparator();sourcesSettingsView.addSetting(WI.UIString("Source Maps:"),WI.settings.sourceMapsEnabled,WI.UIString("Enable source maps"));sourcesSettingsView.addSeparator();sourcesSettingsView.addSetting(WI.UIString("Images:"),WI.settings.showImageGrid,WI.UIString("Show transparency grid","Show transparency grid (settings label)","Settings tab checkbox label for whether the transparency grid is shown by default"));this._createReferenceLink(sourcesSettingsView);this.addSettingsView(sourcesSettingsView);}
_createConsoleSettingsView()
{let consoleSettingsView=new WI.SettingsView("console",WI.UIString("Console"));if(InspectorBackend.hasCommand("Runtime.setSavedResultAlias")){let consoleSavedResultAliasEditor=consoleSettingsView.addGroupWithCustomEditor(WI.UIString("Saved Result Alias:"));let consoleSavedResultAliasInput=consoleSavedResultAliasEditor.appendChild(document.createElement("input"));consoleSavedResultAliasInput.spellcheck=false;consoleSavedResultAliasInput.value=WI.settings.consoleSavedResultAlias.value;consoleSavedResultAliasInput.placeholder=WI.unlocalizedString("$");consoleSavedResultAliasInput.addEventListener("keydown",(event)=>{if(!/[a-zA-Z0-9_$]/.test(event.key)||(consoleSavedResultAliasInput.selectionStart===0&&/[0-9]/.test(event.key))){event.preventDefault();InspectorFrontendHost.beep();}});consoleSavedResultAliasInput.addEventListener("input",(event)=>{let savedResultAlias=consoleSavedResultAliasInput.value;if(savedResultAlias==="$")
savedResultAlias="";WI.settings.consoleSavedResultAlias.value=savedResultAlias;});consoleSettingsView.addSeparator();}
consoleSettingsView.addSetting(WI.UIString("Traces:"),WI.settings.consoleAutoExpandTrace,WI.UIString("Auto-expand"));if(WI.ConsoleManager.supportsLogChannels()){consoleSettingsView.addSeparator();const logLevels=[[WI.LoggingChannel.Level.Off,WI.UIString("Off")],[WI.LoggingChannel.Level.Basic,WI.UIString("Basic")],[WI.LoggingChannel.Level.Verbose,WI.UIString("Verbose")],];const editorLabels={[WI.ConsoleMessage.MessageSource.Media]:WI.UIString("Media Logging:"),[WI.ConsoleMessage.MessageSource.MediaSource]:WI.UIString("MSE Logging:"),[WI.ConsoleMessage.MessageSource.WebRTC]:WI.UIString("WebRTC Logging:"),};let channels=WI.consoleManager.customLoggingChannels;for(let channel of channels){let label=editorLabels[channel.source];if(!label)
continue;let logEditor=consoleSettingsView.addGroupWithCustomSetting(label,WI.SettingEditor.Type.Select,{values:logLevels});logEditor.value=channel.level;logEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){for(let target of WI.targets)
target.ConsoleAgent.setLoggingChannelLevel(channel.source,this.value);},logEditor);}}
this._createReferenceLink(consoleSettingsView);this.addSettingsView(consoleSettingsView);}
_createExperimentalSettingsView()
{let experimentalSettingsView=new WI.SettingsView("experimental",WI.UIString("Experimental"));let initialValues=new Map;let canShowPreviewFeatures=WI.canShowPreviewFeatures();if(canShowPreviewFeatures){experimentalSettingsView.addSetting(WI.UIString("Staging:"),WI.settings.experimentalEnablePreviewFeatures,WI.UIString("Enable Preview Features"));experimentalSettingsView.addSeparator();}
let hasCSSDomain=InspectorBackend.hasDomain("CSS");if(hasCSSDomain){let stylesGroup=experimentalSettingsView.addGroup(WI.UIString("Styles:"));stylesGroup.addSetting(WI.settings.experimentalEnableStylesJumpToEffective,WI.UIString("Show jump to effective property button"));stylesGroup.addSetting(WI.settings.experimentalEnableStylesJumpToVariableDeclaration,WI.UIString("Show jump to variable declaration button"));experimentalSettingsView.addSeparator();}
let supportsBlackboxingScripts=WI.DebuggerManager.supportsBlackboxingScripts();if(supportsBlackboxingScripts){experimentalSettingsView.addSetting(WI.UIString("Debugging:","Debugging: @ Experimental Settings","Category label for experimental settings related to debugging."),WI.settings.experimentalCollapseBlackboxedCallFrames,WI.UIString("Collapse blackboxed call frames","Collapse blackboxed call frames @ Experimental Settings","Setting to collapse blackboxed call frames in the debugger."));experimentalSettingsView.addSeparator();}
let diagnosticsGroup=experimentalSettingsView.addGroup(WI.UIString("Diagnostics:","Diagnostics: @ Experimental Settings","Category label for experimental settings related to Web Inspector diagnostics."));diagnosticsGroup.addSetting(WI.settings.experimentalAllowInspectingInspector,WI.UIString("Allow Inspecting Web Inspector","Allow Inspecting Web Inspector @ Experimental Settings","Label for setting that allows the user to inspect the Web Inspector user interface."));experimentalSettingsView.addSeparator();let reloadInspectorButton=document.createElement("button");reloadInspectorButton.textContent=WI.UIString("Reload Web Inspector");reloadInspectorButton.addEventListener("click",(event)=>{InspectorFrontendHost.reopen();});let reloadInspectorContainerElement=experimentalSettingsView.addCenteredContainer(reloadInspectorButton,WI.UIString("for changes to take effect"));reloadInspectorContainerElement.classList.add("hidden");function listenForChange(setting){initialValues.set(setting,setting.value);setting.addEventListener(WI.Setting.Event.Changed,function(event){this.classList.toggle("hidden",Array.from(initialValues).every(([setting,initialValue])=>setting.value===initialValue));},reloadInspectorContainerElement);}
if(canShowPreviewFeatures)
listenForChange(WI.settings.experimentalEnablePreviewFeatures);if(hasCSSDomain){listenForChange(WI.settings.experimentalEnableStylesJumpToEffective);listenForChange(WI.settings.experimentalEnableStylesJumpToVariableDeclaration);}
if(supportsBlackboxingScripts)
listenForChange(WI.settings.experimentalCollapseBlackboxedCallFrames);this._createReferenceLink(experimentalSettingsView);this.addSettingsView(experimentalSettingsView);}
_createEngineeringSettingsView()
{let engineeringSettingsView=new WI.SettingsView("engineering",WI.unlocalizedString("Engineering"));let elementsGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Elements:"));elementsGroup.addSetting(WI.settings.engineeringAllowEditingUserAgentShadowTrees,WI.unlocalizedString("Allow editing UserAgent shadow trees"));engineeringSettingsView.addSeparator();let debuggingGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Debugging:"));debuggingGroup.addSetting(WI.settings.engineeringShowInternalExecutionContexts,WI.unlocalizedString("Show WebKit-internal execution contexts"));debuggingGroup.addSetting(WI.settings.engineeringShowInternalScripts,WI.unlocalizedString("Show WebKit-internal scripts"));debuggingGroup.addSetting(WI.settings.engineeringPauseForInternalScripts,WI.unlocalizedString("Pause in WebKit-internal scripts"));engineeringSettingsView.addSeparator();let heapSnapshotGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Heap Snapshot:"));heapSnapshotGroup.addSetting(WI.settings.engineeringShowInternalObjectsInHeapSnapshot,WI.unlocalizedString("Show Internal Objects"));heapSnapshotGroup.addSetting(WI.settings.engineeringShowPrivateSymbolsInHeapSnapshot,WI.unlocalizedString("Show Private Symbols"));let extensionsGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Web Extensions:"));extensionsGroup.addSetting(WI.settings.engineeringShowMockWebExtensionTab,WI.unlocalizedString("Show Mock Web Extension tab"));this.addSettingsView(engineeringSettingsView);}
_createDebugSettingsView()
{if(this._debugSettingsView)
return;this._debugSettingsView=new WI.SettingsView("debug",WI.unlocalizedString("Debug"));let protocolMessagesGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Protocol Logging:"));let protocolAutoLogMessagesEditor=protocolMessagesGroup.addSetting(WI.settings.protocolAutoLogMessages,WI.unlocalizedString("Messages"));WI.settings.protocolAutoLogMessages.addEventListener(WI.Setting.Event.Changed,function(event){this.value=InspectorBackend.dumpInspectorProtocolMessages;},protocolAutoLogMessagesEditor);protocolMessagesGroup.addSetting(WI.settings.protocolAutoLogTimeStats,WI.unlocalizedString("Time Stats"));protocolMessagesGroup.addSetting(WI.settings.protocolLogAsText,WI.unlocalizedString("Log as Text"));this._debugSettingsView.addSeparator();let debuggingGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Debugging:"));debuggingGroup.addSetting(WI.settings.debugShowConsoleEvaluations,WI.unlocalizedString("Show Console Evaluations"));debuggingGroup.addSetting(WI.settings.debugOutlineFocusedElement,WI.unlocalizedString("Outline focused element"));this._debugSettingsView.addSeparator();this._debugSettingsView.addSetting(WI.unlocalizedString("Layout Flashing:"),WI.settings.debugEnableLayoutFlashing,WI.unlocalizedString("Draw borders when a view performs a layout"));this._debugSettingsView.addSeparator();this._debugSettingsView.addSetting(WI.unlocalizedString("Styles:"),WI.settings.debugEnableStyleEditingDebugMode,WI.unlocalizedString("Enable style editing debug mode"));this._debugSettingsView.addSeparator();let diagnosticsGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Diagnostics:"));diagnosticsGroup.addSetting(WI.settings.debugEnableUncaughtExceptionReporter,WI.unlocalizedString("Report Uncaught Exceptions"));diagnosticsGroup.addSetting(WI.settings.debugEnableDiagnosticLogging,WI.unlocalizedString("Enable Diagnostic Logging"));diagnosticsGroup.addSetting(WI.settings.debugAutoLogDiagnosticEvents,WI.unlocalizedString("Show Diagnostic Events in Console"));this._debugSettingsView.addSeparator();const layoutDirectionValues=[[WI.LayoutDirection.System,WI.unlocalizedString("System Default")],[WI.LayoutDirection.LTR,WI.unlocalizedString("Left to Right (LTR)")],[WI.LayoutDirection.RTL,WI.unlocalizedString("Right to Left (RTL)")],];let layoutDirectionEditor=this._debugSettingsView.addGroupWithCustomSetting(WI.unlocalizedString("Layout Direction:"),WI.SettingEditor.Type.Select,{values:layoutDirectionValues});layoutDirectionEditor.value=WI.settings.debugLayoutDirection.value;layoutDirectionEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.setLayoutDirection(this.value);},layoutDirectionEditor);this._debugSettingsView.addSeparator();let resetInspectorButton=document.createElement("button");resetInspectorButton.textContent=WI.unlocalizedString("Reset Web Inspector");resetInspectorButton.addEventListener("click",(event)=>{WI.reset();});this._debugSettingsView.addCenteredContainer(resetInspectorButton);this.addSettingsView(this._debugSettingsView);}
_createReferenceLink(settingsView)
{let link=document.createElement("a");link.href=link.title="https://webkit.org/web-inspector/web-inspector-settings/#"+settingsView.identifier;link.textContent=WI.UIString("Web Inspector Reference");link.appendChild(WI.createGoToArrowButton());let container=settingsView.addCenteredContainer(link);container.classList.add("reference");}
_updateNavigationBarVisibility()
{let visibleItems=0;for(let item of this._navigationBar.navigationItems){if(!item.hidden&&++visibleItems>1){this._navigationBar.element.classList.remove("invisible");return;}}
this._navigationBar.element.classList.add("invisible");}
_navigationItemSelected(event)
{let navigationItem=event.target.selectedNavigationItem;if(!navigationItem)
return;let settingsView=this._settingsViews.find((view)=>view.identifier===navigationItem.identifier);if(!settingsView)
return;this.selectedSettingsView=settingsView;}
_updateDebugSettingsViewVisibility()
{if(WI.isDebugUIEnabled())
this._createDebugSettingsView();if(!this._debugSettingsView)
return;this.setSettingsViewVisible(this._debugSettingsView,WI.isDebugUIEnabled());this.needsLayout();}};WI.SettingsTabContentView.Type="settings";WI.SourcesTabContentView=class SourcesTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(SourcesTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.SourcesNavigationSidebarPanel,detailsSidebarPanelConstructors:[WI.ResourceDetailsSidebarPanel,WI.ScopeChainDetailsSidebarPanel,WI.ProbeDetailsSidebarPanel,],});this._showScopeChainDetailsSidebarPanel=false;WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);}
static tabInfo()
{return{identifier:SourcesTabContentView.Type,image:WI.debuggerManager.paused?"Images/SourcesPaused.svg":"Images/Sources.svg",displayName:WI.UIString("Sources","Sources Tab Name","Name of Sources Tab"),};} 
get type()
{return WI.SourcesTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.Frame||representedObject instanceof WI.FrameCollection||representedObject instanceof WI.Resource||representedObject instanceof WI.ResourceCollection||representedObject instanceof WI.Script||representedObject instanceof WI.ScriptCollection||representedObject instanceof WI.CSSStyleSheet||representedObject instanceof WI.CSSStyleSheetCollection||representedObject instanceof WI.LocalResourceOverride||super.canShowRepresentedObject(representedObject);}
showDetailsSidebarPanels()
{super.showDetailsSidebarPanels();if(!this._showScopeChainDetailsSidebarPanel)
return;let scopeChainDetailsSidebarPanel=this.detailsSidebarPanels.find((item)=>item instanceof WI.ScopeChainDetailsSidebarPanel);if(!scopeChainDetailsSidebarPanel)
return;WI.detailsSidebar.selectedSidebarPanel=scopeChainDetailsSidebarPanel;WI.detailsSidebar.collapsed=false;this._showScopeChainDetailsSidebarPanel=false;}
showScopeChainDetailsSidebarPanel()
{this._showScopeChainDetailsSidebarPanel=true;}
revealAndSelectRepresentedObject(representedObject)
{let treeElement=this.navigationSidebarPanel.treeElementForRepresentedObject(representedObject);if(treeElement){const omitFocus=false;const selectedByUser=true;treeElement.revealAndSelect(omitFocus,selectedByUser);}}
handleCopyEvent(event)
{if(this.navigationSidebarPanel.element.contains(WI.currentFocusElement))
this.navigationSidebarPanel.handleCopyEvent(event);} 
_handleDebuggerPaused(event)
{this.tabBarItem.image="Images/SourcesPaused.svg";}
_handleDebuggerResumed(event)
{this.tabBarItem.image="Images/Sources.svg";}};WI.SourcesTabContentView.Type="sources";WI.StorageTabContentView=class StorageTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(StorageTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.StorageSidebarPanel,detailsSidebarPanelConstructors:[WI.ApplicationCacheDetailsSidebarPanel,WI.IndexedDatabaseDetailsSidebarPanel,],});WI.applicationCacheManager.enable();WI.databaseManager.enable();WI.domStorageManager.enable();WI.indexedDBManager.enable();}
static tabInfo()
{return{identifier:StorageTabContentView.Type,image:"Images/Storage.svg",displayName:WI.UIString("Storage","Storage Tab Name","Name of Storage Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("ApplicationCache")||InspectorBackend.hasDomain("DOMStorage")||InspectorBackend.hasDomain("Database")||InspectorBackend.hasDomain("IndexedDB");} 
get type()
{return WI.StorageTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.ApplicationCacheFrame||representedObject instanceof WI.CookieStorageObject||representedObject instanceof WI.DOMStorageObject||representedObject instanceof WI.DatabaseObject||representedObject instanceof WI.DatabaseTableObject||representedObject instanceof WI.IndexedDatabase||representedObject instanceof WI.IndexedDatabaseObjectStore||representedObject instanceof WI.IndexedDatabaseObjectStoreIndex;}
get canHandleFindEvent()
{return this.contentBrowser.currentContentView.canFocusFilterBar;}
handleFindEvent(event)
{this.contentBrowser.currentContentView.focusFilterBar();}
closed()
{WI.applicationCacheManager.disable();WI.databaseManager.disable();WI.domStorageManager.disable();WI.indexedDBManager.disable();super.closed();}};WI.StorageTabContentView.Type="storage";WI.TimelineTabContentView=class TimelineTabContentView extends WI.ContentBrowserTabContentView
{constructor()
{super(TimelineTabContentView.tabInfo());this._recordingTreeElementMap=new Map;this._recordingsTreeOutline=new WI.TreeOutline;this._recordingsTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._recordingsTreeSelectionDidChange,this);this._toggleRecordingShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._toggleRecordingOnSpacebar.bind(this));this._toggleRecordingShortcut.implicitlyPreventsDefault=false;this._toggleRecordingShortcut.disabled=true;this._toggleNewRecordingShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Space,this._toggleNewRecordingOnSpacebar.bind(this));this._toggleNewRecordingShortcut.implicitlyPreventsDefault=false;this._toggleNewRecordingShortcut.disabled=true;let toolTip=WI.UIString("Start recording (%s)\nCreate new recording (%s)").format(this._toggleRecordingShortcut.displayName,this._toggleNewRecordingShortcut.displayName);let altToolTip=WI.UIString("Stop recording (%s)").format(this._toggleRecordingShortcut.displayName);this._recordButton=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._recordButtonClicked,this);this._recordStoppingSpinner=new WI.IndeterminateProgressSpinnerNavigationItem("record-stopping",WI.UIString("Stopping recording"));this._recordStoppingSpinner.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordStoppingSpinner.hidden=true;this._continueButton=new WI.ButtonNavigationItem("record-continue",WI.UIString("Continue without automatically stopping"),"Images/Resume.svg",13,13);this._continueButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._continueButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._continueButtonClicked,this);this._continueButton.hidden=true;this.contentBrowser.navigationBar.insertNavigationItem(this._recordButton,0);this.contentBrowser.navigationBar.insertNavigationItem(this._recordStoppingSpinner,1);this.contentBrowser.navigationBar.insertNavigationItem(this._continueButton,2);if(WI.sharedApp.isWebDebuggable()){let timelinesNavigationItem=new WI.RadioButtonNavigationItem(WI.TimelineOverview.ViewMode.Timelines,WI.UIString("Events"));let renderingFramesNavigationItem=new WI.RadioButtonNavigationItem(WI.TimelineOverview.ViewMode.RenderingFrames,WI.UIString("Frames"));let viewModeGroup=new WI.GroupNavigationItem([timelinesNavigationItem,renderingFramesNavigationItem]);viewModeGroup.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this.contentBrowser.navigationBar.insertNavigationItem(viewModeGroup,3);this.contentBrowser.navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._viewModeSelected,this);}
WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.RecordingCreated,this._recordingCreated,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.RecordingLoaded,this._recordingLoaded,this);WI.notifications.addEventListener(WI.Notification.VisibilityStateDidChange,this._inspectorVisibilityChanged,this);WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._globalModifierKeysDidChange,this);this._displayedRecording=null;this._displayedContentView=null;this._viewMode=null;this._previousSelectedTimelineType=null;const selectedByUser=false;this._changeViewMode(WI.TimelineOverview.ViewMode.Timelines,selectedByUser);WI.heapManager.enable();WI.memoryManager.enable();WI.timelineManager.enable();} 
static tabInfo()
{return{identifier:TimelineTabContentView.Type,image:"Images/Timeline.svg",displayName:WI.UIString("Timelines","Timelines Tab Name","Name of Timelines Tab"),};}
static isTabAllowed()
{return InspectorBackend.hasDomain("Timeline")||InspectorBackend.hasDomain("ScriptProfiler");}
static displayNameForTimelineType(timelineType)
{switch(timelineType){case WI.TimelineRecord.Type.Network:return WI.UIString("Network Requests");case WI.TimelineRecord.Type.Layout:return WI.UIString("Layout & Rendering");case WI.TimelineRecord.Type.Script:return WI.UIString("JavaScript & Events");case WI.TimelineRecord.Type.RenderingFrame:return WI.UIString("Rendering Frames");case WI.TimelineRecord.Type.CPU:return WI.UIString("CPU");case WI.TimelineRecord.Type.Memory:return WI.UIString("Memory");case WI.TimelineRecord.Type.HeapAllocations:return WI.UIString("JavaScript Allocations");case WI.TimelineRecord.Type.Media:if(InspectorBackend.hasDomain("Animation"))
return WI.UIString("Media & Animations");return WI.UIString("Media");default:console.error("Unknown Timeline type:",timelineType);}
return null;}
static iconClassNameForTimelineType(timelineType)
{switch(timelineType){case WI.TimelineRecord.Type.Network:return"network-icon";case WI.TimelineRecord.Type.Layout:return"layout-icon";case WI.TimelineRecord.Type.CPU:return"cpu-icon";case WI.TimelineRecord.Type.Memory:return"memory-icon";case WI.TimelineRecord.Type.HeapAllocations:return"heap-allocations-icon";case WI.TimelineRecord.Type.Script:return"script-icon";case WI.TimelineRecord.Type.RenderingFrame:return"rendering-frame-icon";case WI.TimelineRecord.Type.Media:return"media-icon";default:console.error("Unknown Timeline type:",timelineType);}
return null;}
static genericClassNameForTimelineType(timelineType)
{switch(timelineType){case WI.TimelineRecord.Type.Network:return"network";case WI.TimelineRecord.Type.Layout:return"colors";case WI.TimelineRecord.Type.CPU:return"cpu";case WI.TimelineRecord.Type.Memory:return"memory";case WI.TimelineRecord.Type.HeapAllocations:return"heap-allocations";case WI.TimelineRecord.Type.Script:return"script";case WI.TimelineRecord.Type.RenderingFrame:return"rendering-frame";case WI.TimelineRecord.Type.Media:return"media";default:console.error("Unknown Timeline type:",timelineType);}
return null;}
static iconClassNameForRecord(timelineRecord)
{switch(timelineRecord.type){case WI.TimelineRecord.Type.Layout:switch(timelineRecord.eventType){case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.RecalculateStyles:return WI.TimelineRecordTreeElement.StyleRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.InvalidateLayout:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:return WI.TimelineRecordTreeElement.LayoutRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.Paint:return WI.TimelineRecordTreeElement.PaintRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.Composite:return WI.TimelineRecordTreeElement.CompositeRecordIconStyleClass;default:console.error("Unknown LayoutTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);}
break;case WI.TimelineRecord.Type.Script:switch(timelineRecord.eventType){case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:return WI.TimelineRecordTreeElement.APIRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:return WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:case WI.ScriptTimelineRecord.EventType.EventDispatched:case WI.ScriptTimelineRecord.EventType.ObserverCallback:return WI.TimelineRecordTreeElement.EventRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:return WI.TimelineRecordTreeElement.ProbeRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:return WI.TimelineRecordTreeElement.ConsoleProfileIconStyleClass;case WI.ScriptTimelineRecord.EventType.GarbageCollected:return WI.TimelineRecordTreeElement.GarbageCollectionIconStyleClass;case WI.ScriptTimelineRecord.EventType.TimerInstalled:return WI.TimelineRecordTreeElement.TimerRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.TimerFired:case WI.ScriptTimelineRecord.EventType.TimerRemoved:return WI.TimelineRecordTreeElement.TimerRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:return"animation-frame-record";default:console.error("Unknown ScriptTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);}
break;case WI.TimelineRecord.Type.RenderingFrame:return WI.TimelineRecordTreeElement.RenderingFrameRecordIconStyleClass;case WI.TimelineRecord.Type.HeapAllocations:return"heap-snapshot-record";case WI.TimelineRecord.Type.Media:switch(timelineRecord.eventType){case WI.MediaTimelineRecord.EventType.CSSAnimation:return"css-animation-record";case WI.MediaTimelineRecord.EventType.CSSTransition:return"css-transition-record";case WI.MediaTimelineRecord.EventType.MediaElement:return"media-element-record";default:console.error("Unknown MediaTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);}
break;case WI.TimelineRecord.Type.CPU:case WI.TimelineRecord.Type.Memory:default:console.error("Unknown TimelineRecord type: "+timelineRecord.type,timelineRecord);}
return null;}
static displayNameForRecord(timelineRecord,includeDetailsInMainTitle)
{switch(timelineRecord.type){case WI.TimelineRecord.Type.Network:return WI.displayNameForURL(timelineRecord.resource.url,timelineRecord.resource.urlComponents);case WI.TimelineRecord.Type.Layout:return WI.LayoutTimelineRecord.displayNameForEventType(timelineRecord.eventType);case WI.TimelineRecord.Type.Script:return WI.ScriptTimelineRecord.EventType.displayName(timelineRecord.eventType,timelineRecord.details,includeDetailsInMainTitle);case WI.TimelineRecord.Type.RenderingFrame:if(timelineRecord.name)
return WI.UIString("Frame %d \u2014 %s").format(timelineRecord.frameNumber,timelineRecord.name);return WI.UIString("Frame %d").format(timelineRecord.frameNumber);case WI.TimelineRecord.Type.HeapAllocations:if(timelineRecord.heapSnapshot.imported)
return WI.UIString("Imported \u2014 %s").format(timelineRecord.heapSnapshot.title);if(timelineRecord.heapSnapshot.title)
return WI.UIString("Snapshot %d \u2014 %s").format(timelineRecord.heapSnapshot.identifier,timelineRecord.heapSnapshot.title);return WI.UIString("Snapshot %d").format(timelineRecord.heapSnapshot.identifier);case WI.TimelineRecord.Type.Media:if(includeDetailsInMainTitle&&timelineRecord.subtitle)
return timelineRecord.subtitle;return timelineRecord.displayName;case WI.TimelineRecord.Type.CPU:case WI.TimelineRecord.Type.Memory:default:console.error("Unknown TimelineRecord type: "+timelineRecord.type,timelineRecord);}
return null;} 
get type()
{return WI.TimelineTabContentView.Type;}
attached()
{super.attached();this._toggleRecordingShortcut.disabled=false;this._toggleNewRecordingShortcut.disabled=false;if(WI.visible)
WI.timelineManager.autoCaptureOnPageLoad=true;}
detached()
{this._toggleRecordingShortcut.disabled=true;this._toggleNewRecordingShortcut.disabled=true;WI.timelineManager.autoCaptureOnPageLoad=false;super.detached();}
closed()
{WI.timelineManager.disable();WI.memoryManager.disable();WI.heapManager.disable();if(WI.sharedApp.isWebDebuggable())
this.contentBrowser.navigationBar.removeEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._viewModeSelected,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.RecordingCreated,this._recordingCreated,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.RecordingLoaded,this._recordingLoaded,this);WI.notifications.removeEventListener(WI.Notification.VisibilityStateDidChange,this._inspectorVisibilityChanged,this);WI.notifications.removeEventListener(WI.Notification.GlobalModifierKeysDidChange,this._globalModifierKeysDidChange,this);super.closed();}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.TimelineRecording;}
get canHandleFindEvent()
{return this._displayedContentView.canFocusFilterBar;}
handleFindEvent(event)
{this._displayedContentView.focusFilterBar();} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{return event.dataTransfer.types.includes("Files");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readJSON(files,(result)=>WI.timelineManager.processJSON(result));} 
initialLayout()
{super.initialLayout();let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Recording");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);}
restoreFromCookie(cookie)
{this._restoredShowingTimelineRecordingContentView=cookie[WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey];if(!this._restoredShowingTimelineRecordingContentView){if(!this.contentBrowser.currentContentView){if(!this._displayedRecording&&WI.timelineManager.activeRecording)
this._recordingLoaded();this._showTimelineViewForType(WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue);}
return;}
let selectedTimelineViewIdentifier=cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey];this._showTimelineViewForType(selectedTimelineViewIdentifier);super.restoreFromCookie(cookie);}
saveToCookie(cookie)
{cookie[WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey]=this.contentBrowser.currentContentView instanceof WI.TimelineRecordingContentView;if(this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames)
cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=WI.TimelineRecord.Type.RenderingFrame;else{let selectedTimeline=this._getTimelineForCurrentContentView();if(selectedTimeline)
cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=selectedTimeline.type;else
cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue;}
super.saveToCookie(cookie);}
treeElementForRepresentedObject(representedObject)
{if(!this._recordingTreeElementMap)
return null;if(representedObject instanceof WI.TimelineRecording)
return this._recordingTreeElementMap.get(representedObject);return null;} 
_showRecordButton()
{this._recordButton.hidden=false;this._recordStoppingSpinner.hidden=true;this._continueButton.hidden=true;}
_showRecordStoppingSpinner()
{this._recordButton.hidden=true;this._recordStoppingSpinner.hidden=false;this._continueButton.hidden=true;}
_showContinueButton()
{this._recordButton.hidden=true;this._recordStoppingSpinner.hidden=true;this._continueButton.hidden=false;}
_updateNavigationBarButtons()
{if(WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Stopping)
this._showRecordStoppingSpinner();else if(!WI.modifierKeys.altKey||!WI.timelineManager.willAutoStop())
this._showRecordButton();else
this._showContinueButton();}
_handleTimelineCapturingStateChanged(event)
{let enabled=WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Active||WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Inactive;let stopping=WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Stopping;this._toggleRecordingShortcut.disabled=!enabled||stopping;this._toggleNewRecordingShortcut.disabled=!enabled||stopping;this._recordButton.toggled=WI.timelineManager.isCapturing();this._recordButton.enabled=enabled;this._updateNavigationBarButtons();}
_inspectorVisibilityChanged(event)
{WI.timelineManager.autoCaptureOnPageLoad=!!this.isAttached&&!!WI.visible;}
_globalModifierKeysDidChange(event)
{this._updateNavigationBarButtons();}
_toggleRecordingOnSpacebar(event)
{if(WI.timelineManager.activeRecording.readonly)
return;if(WI.isEventTargetAnEditableField(event))
return;this._toggleRecording();event.preventDefault();}
_toggleNewRecordingOnSpacebar(event)
{if(WI.isEventTargetAnEditableField(event))
return;this._toggleRecording(true);event.preventDefault();}
_toggleRecording(shouldCreateRecording)
{let isCapturing=WI.timelineManager.isCapturing();this._recordButton.toggled=isCapturing;if(isCapturing)
WI.timelineManager.stopCapturing();else{WI.timelineManager.startCapturing(shouldCreateRecording);this._recordingLoaded();}}
_recordButtonClicked(event)
{let shouldCreateNewRecording=window.event?window.event.shiftKey:false;if(WI.timelineManager.activeRecording.readonly)
shouldCreateNewRecording=true;this._recordButton.toggled=!WI.timelineManager.isCapturing();this._toggleRecording(shouldCreateNewRecording);}
_continueButtonClicked(event)
{WI.timelineManager.relaxAutoStop();this._updateNavigationBarButtons();}
_recordingsTreeSelectionDidChange(event)
{let treeElement=this._recordingsTreeOutline.selectedTreeElement;if(!treeElement)
return;this._recordingSelected(treeElement.representedObject);}
_recordingCreated(event)
{this._addRecording(event.data.recording);this._recordingCountChanged();}
_addRecording(recording)
{let recordingTreeElement=new WI.GeneralTreeElement(WI.TimelineTabContentView.StopwatchIconStyleClass,recording.displayName,null,recording);this._recordingTreeElementMap.set(recording,recordingTreeElement);this._recordingsTreeOutline.appendChild(recordingTreeElement);}
_recordingCountChanged()
{let previousTreeElement=null;for(let treeElement of this._recordingTreeElementMap.values()){if(previousTreeElement){previousTreeElement.nextSibling=treeElement;treeElement.previousSibling=previousTreeElement;}
previousTreeElement=treeElement;}}
_recordingSelected(recording)
{this._displayedRecording=recording;let cookie={};this.saveToCookie(cookie);if(this._displayedContentView)
this._displayedContentView.removeEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);let onlyExisting=true;this._displayedContentView=this.contentBrowser.contentViewForRepresentedObject(this._displayedRecording,onlyExisting);if(this._displayedContentView){this._displayedContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);let currentTimelineView=this._displayedContentView.currentTimelineView;let timelineType=currentTimelineView&&currentTimelineView.representedObject instanceof WI.Timeline?currentTimelineView.representedObject.type:null;this._showTimelineViewForType(timelineType);return;}
onlyExisting=false;this._displayedContentView=this.contentBrowser.contentViewForRepresentedObject(this._displayedRecording,onlyExisting);if(this._displayedContentView)
this._displayedContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);this.restoreFromCookie(cookie);}
_recordingLoaded(event)
{this._recordingSelected(WI.timelineManager.activeRecording);}
_viewModeSelected(event)
{let selectedNavigationItem=event.target.selectedNavigationItem;if(!selectedNavigationItem)
return;const selectedByUser=true;this._changeViewMode(selectedNavigationItem.identifier,selectedByUser);}
_changeViewMode(mode,selectedByUser)
{if(this._viewMode===mode)
return;let navigationItemForViewMode=this.contentBrowser.navigationBar.findNavigationItem(mode);if(!navigationItemForViewMode)
return;this._viewMode=mode;this.contentBrowser.navigationBar.selectedNavigationItem=navigationItemForViewMode;if(!selectedByUser)
return;let timelineType=this._previousSelectedTimelineType;if(this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames){let timeline=this._getTimelineForCurrentContentView();this._previousSelectedTimelineType=timeline?timeline.type:null;timelineType=WI.TimelineRecord.Type.RenderingFrame;}
this._showTimelineViewForType(timelineType);}
_showTimelineViewForType(timelineType)
{let timeline=timelineType?this._displayedRecording.timelines.get(timelineType):null;if(timeline)
this._displayedContentView.showTimelineViewForTimeline(timeline);else
this._displayedContentView.showOverviewTimelineView();if(this.contentBrowser.currentContentView!==this._displayedContentView)
this.contentBrowser.showContentView(this._displayedContentView);}
_displayedContentViewNavigationItemsDidChange(event)
{let timeline=this._getTimelineForCurrentContentView();let newViewMode=WI.TimelineOverview.ViewMode.Timelines;if(timeline&&timeline.type===WI.TimelineRecord.Type.RenderingFrame)
newViewMode=WI.TimelineOverview.ViewMode.RenderingFrames;const selectedByUser=false;this._changeViewMode(newViewMode,selectedByUser);}
_getTimelineForCurrentContentView()
{let currentContentView=this.contentBrowser.currentContentView;if(!(currentContentView instanceof WI.TimelineRecordingContentView))
return null;let timelineView=currentContentView.currentTimelineView;return(timelineView&&timelineView.representedObject instanceof WI.Timeline)?timelineView.representedObject:null;}};WI.TimelineTabContentView.Type="timeline";WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey="timeline-sidebar-panel-showing-timeline-recording-content-view";WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey="timeline-sidebar-panel-selected-timeline-view-identifier";WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue="overview";WI.TimelineTabContentView.StopwatchIconStyleClass="stopwatch-icon";WI.WebInspectorExtensionTabContentView=class WebInspectorExtensionTabContentView extends WI.TabContentView
{constructor(extension,extensionTabID,tabLabel,iconURL,sourceURL)
{let tabInfo={identifier:WI.WebInspectorExtensionTabContentView.Type,image:iconURL,displayName:tabLabel,title:tabLabel,};super(tabInfo);this._extension=extension;this._extensionTabID=extensionTabID;this._tabInfo=tabInfo;this._sourceURL=sourceURL;this._iframeElement=this.element.appendChild(document.createElement("iframe"));this._iframeElement.addEventListener("load",this._extensionFrameDidLoad.bind(this));this._iframeElement.src=this._sourceURL;this._frameContentDidLoad=false;} 
static shouldSaveTab(){return false;}
static shouldNotRemoveFromDOMWhenHidden(){return true;}
static isTabAllowed()
{return InspectorFrontendHost.supportsWebExtensions;} 
get extensionTabID(){return this._extensionTabID;}
get iframeElement(){return this._iframeElement;}
get type()
{return WI.WebInspectorExtensionTabContentView.Type;}
get supportsSplitContentBrowser()
{return true;}
attached()
{super.attached();this._maybeDispatchDidShowExtensionTab();}
detached()
{if(InspectorFrontendHost.supportsWebExtensions)
InspectorFrontendHost.didHideExtensionTab(this._extension.extensionID,this._extensionTabID);super.detached();}
dispose()
{this.element?.remove();}
tabInfo()
{return this._tabInfo;}
static shouldSaveTab(){return false;}
static shouldNotRemoveFromDOMWhenHidden(){return true;} 
_extensionFrameDidLoad()
{this._frameContentDidLoad=true;this._maybeDispatchDidShowExtensionTab();}
_maybeDispatchDidShowExtensionTab()
{if(!this._frameContentDidLoad||!this.element.isConnected)
return;if(InspectorFrontendHost.supportsWebExtensions)
InspectorFrontendHost.didShowExtensionTab(this._extension.extensionID,this._extensionTabID);}};WI.WebInspectorExtensionTabContentView.Type="web-inspector-extension";WI.DetailsSection=class DetailsSection extends WI.Object
{constructor(identifier,title,groups,optionsElement,defaultCollapsedSettingValue)
{super();this._element=document.createElement("div");this._element.classList.add(identifier,"details-section");this._headerElement=document.createElement("div");this._headerElement.addEventListener("mousedown",this._headerElementMouseDown.bind(this));this._headerElement.addEventListener("click",this._headerElementClicked.bind(this));this._headerElement.addEventListener("keydown",this._handleHeaderElementKeyDown.bind(this));this._headerElement.className="header";this._headerElement.tabIndex=0;this._element.appendChild(this._headerElement);if(optionsElement instanceof HTMLElement){this._optionsElement=optionsElement;this._optionsElement.classList.add("options");this._optionsElement.addEventListener("mousedown",this._optionsElementMouseDown.bind(this));this._optionsElement.addEventListener("mouseup",this._optionsElementMouseUp.bind(this));this._headerElement.appendChild(this._optionsElement);}
this._titleElement=document.createElement("span");this._headerElement.appendChild(this._titleElement);this._contentElement=document.createElement("div");this._contentElement.className="content";this._element.appendChild(this._contentElement);this._identifier=identifier;this.title=title;this.groups=groups||[new WI.DetailsSectionGroup];this._collapsedSetting=new WI.Setting(identifier+"-details-section-collapsed",!!defaultCollapsedSettingValue);this.collapsed=this._collapsedSetting.value;} 
get element(){return this._element;}
get headerElement(){return this._headerElement;}
get identifier(){return this._identifier;}
get title()
{return this._titleElement.textContent;}
set title(title)
{this._titleElement.textContent=title;}
get titleElement()
{return this._titleElement;}
set titleElement(element)
{this._headerElement.replaceChild(element,this._titleElement);this._titleElement=element;}
get collapsed()
{return this._element.classList.contains(WI.DetailsSection.CollapsedStyleClassName);}
set collapsed(flag)
{if(flag)
this._element.classList.add(WI.DetailsSection.CollapsedStyleClassName);else
this._element.classList.remove(WI.DetailsSection.CollapsedStyleClassName);this._collapsedSetting.value=flag||false;this.dispatchEventToListeners(WI.DetailsSection.Event.CollapsedStateChanged,{collapsed:this._collapsedSetting.value});}
get groups()
{return this._groups;}
set groups(groups)
{this._contentElement.removeChildren();this._groups=groups||[];for(var i=0;i<this._groups.length;++i)
this._contentElement.appendChild(this._groups[i].element);} 
_headerElementMouseDown(event)
{if(this._optionsElement?.contains(event.target))
return;if(document.activeElement===this._headerElement)
return;event.preventDefault();}
_headerElementClicked(event)
{if(this._optionsElement?.contains(event.target))
return;let collapsed=this.collapsed;this.collapsed=!collapsed;this._element.scrollIntoViewIfNeeded(false);}
_handleHeaderElementKeyDown(event)
{let isSpaceOrEnterKey=event.code==="Space"||event.code==="Enter";if(!isSpaceOrEnterKey&&event.code!=="ArrowLeft"&&event.code!=="ArrowRight")
return;if(this._optionsElement?.contains(event.target))
return;event.preventDefault();if(isSpaceOrEnterKey){this.collapsed=!this.collapsed;return;}
let collapsed=event.code==="ArrowLeft";if(WI.resolveLayoutDirectionForElement(this._headerElement)===WI.LayoutDirection.RTL)
collapsed=!collapsed;this.collapsed=collapsed;}
_optionsElementMouseDown(event)
{this._headerElement.classList.add(WI.DetailsSection.MouseOverOptionsElementStyleClassName);}
_optionsElementMouseUp(event)
{this._headerElement.classList.remove(WI.DetailsSection.MouseOverOptionsElementStyleClassName);}};WI.DetailsSection.CollapsedStyleClassName="collapsed";WI.DetailsSection.MouseOverOptionsElementStyleClassName="mouse-over-options-element";WI.DetailsSection.Event={CollapsedStateChanged:"details-section-collapsed-state-changed"};WI.DetailsSectionDataGridRow=class DetailsSectionDataGridRow extends WI.DetailsSectionRow
{constructor(dataGrid,emptyMessage)
{super(emptyMessage);this.element.classList.add("data-grid");this.dataGrid=dataGrid;} 
get dataGrid()
{return this._dataGrid;}
set dataGrid(dataGrid)
{if(this._dataGrid===dataGrid)
return;this._dataGrid=dataGrid||null;if(dataGrid){dataGrid.inline=true;dataGrid.variableHeightRows=true;this.hideEmptyMessage();this.element.appendChild(dataGrid.element);dataGrid.updateLayoutIfNeeded();}else
this.showEmptyMessage();}
sizeDidChange()
{ if(this._dataGrid)
this._dataGrid.sizeDidChange();}};WI.DetailsSectionGroup=class DetailsSectionGroup extends WI.Object
{constructor(rows)
{super();this._element=document.createElement("div");this._element.className="group";this.rows=rows||[];} 
get element()
{return this._element;}
get rows()
{return this._rows;}
set rows(rows)
{this._element.removeChildren();this._rows=rows||[];for(var i=0;i<this._rows.length;++i)
this._element.appendChild(this._rows[i].element);}};WI.DetailsSectionSimpleRow=class DetailsSectionSimpleRow extends WI.DetailsSectionRow
{constructor(label,value)
{super();this.element.classList.add("simple");this._labelElement=document.createElement("div");this._labelElement.className="label";this.element.appendChild(this._labelElement);this._valueElement=document.createElement("div");this._valueElement.className="value";this.element.appendChild(this._valueElement);

var valueElementClicked=function(event){event.stopPropagation();if(event.detail<3)
return;var currentSelection=window.getSelection();if(!currentSelection)
return;var currentRange=currentSelection.getRangeAt(0);if(!currentRange||currentRange.startContainer===currentRange.endContainer)
return;var correctedRange=document.createRange();correctedRange.selectNodeContents(event.currentTarget);currentSelection.removeAllRanges();currentSelection.addRange(correctedRange);};this._valueElement.addEventListener("click",valueElementClicked);this.label=label;this.value=value;} 
get label()
{return this._label;}
set label(label)
{this._label=label||"";if(this._label instanceof Node){this._labelElement.removeChildren();this._labelElement.appendChild(this._label);}else
this._labelElement.textContent=this._label;}
get value()
{return this._value;}
set value(value)
{this._value=value||"";if(this._value||this._value===0){this.element.classList.remove(WI.DetailsSectionSimpleRow.EmptyStyleClassName);if(/[\s\u200b]/.test(this._value))
this.element.classList.remove(WI.DetailsSectionSimpleRow.DataStyleClassName);else
this.element.classList.add(WI.DetailsSectionSimpleRow.DataStyleClassName);}else{this.element.classList.add(WI.DetailsSectionSimpleRow.EmptyStyleClassName);this.element.classList.remove(WI.DetailsSectionSimpleRow.DataStyleClassName);}
if(value instanceof Node){this._valueElement.removeChildren();this._valueElement.appendChild(this._value);}else
this._valueElement.textContent=this._value;}
get tooltip()
{return this._valueElement.title;}
set tooltip(x)
{this._valueElement.title=x;}};WI.DetailsSectionSimpleRow.DataStyleClassName="data";WI.DetailsSectionSimpleRow.EmptyStyleClassName="empty";WI.DetailsSectionTextRow=class DetailsSectionTextRow extends WI.DetailsSectionRow
{constructor(text)
{super();this.element.classList.add("text");this.element.textContent=text;} 
get text()
{return this.element.textContent;}
set text(text)
{this.element.textContent=text;}};WI.SettingEditor=class SettingEditor extends WI.Object
{constructor(type,label,options)
{super();this._type=type;this._value=null;this._editorElement=this._createEditorElement(options);this._element=document.createElement("div");this._element.classList.add("setting-editor");this._element.append(this._editorElement);this.label=label;}
static createForSetting(setting,label,options)
{let type;if(typeof setting.value==="boolean")
type=WI.SettingEditor.Type.Checkbox;else if(typeof setting.value==="number")
type=WI.SettingEditor.Type.Numeric;if(!type)
return null;let editor=new WI.SettingEditor(type,label,options);editor.value=setting.value;editor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){this.value=editor.value;},setting);setting.addEventListener(WI.Setting.Event.Changed,function(event){this.value=setting.value;},editor);return editor;} 
get element(){return this._element;}
get type(){return this._type;}
get label()
{return this._label;}
set label(label)
{if(label===this._label)
return;this._label=label;if(!this._label){if(this._labelElement)
this._labelElement.remove();this._editorElement.removeAttribute("id");this._labelElement=null;return;}
if(!this._labelElement){this._editorElement.id="setting-editor-"+WI.SettingEditor._nextEditorIdentifier++;this._labelElement=this._element.appendChild(document.createElement("label"));this._labelElement.setAttribute("for",this._editorElement.id);}
this._labelElement.textContent=this._label;}
get value()
{return this._value;}
set value(value)
{if(this._value===value)
return;let oldValue=this._value;this._value=value;if(this._type===WI.SettingEditor.Type.Checkbox)
this._editorElement.checked=!!this._value;else
this._editorElement.value=this._value;this.dispatchEventToListeners(WI.SettingEditor.Event.ValueDidChange,{oldValue});} 
_createEditorElement(options)
{let editorElement;switch(this._type){case WI.SettingEditor.Type.Checkbox:editorElement=document.createElement("input");editorElement.type="checkbox";editorElement.addEventListener("change",(event)=>{this.value=event.target.checked;});break;case WI.SettingEditor.Type.Numeric:editorElement=document.createElement("input");editorElement.type="number";if(options.min!==undefined)
editorElement.min=options.min;if(options.max!==undefined)
editorElement.max=options.max;editorElement.addEventListener("change",(event)=>{let currentValue=this._value;let newValue=parseInt(event.target.value);this.value=isNaN(newValue)?currentValue:newValue;});break;case WI.SettingEditor.Type.Select:editorElement=document.createElement("select");var keyValuePairs=[];if(Array.isArray(options.values[0]))
keyValuePairs=options.values;else
keyValuePairs=options.values.map((value)=>[value,value]);for(let[key,value]of keyValuePairs){if(key===WI.SettingEditor.SelectSpacerKey){editorElement.appendChild(document.createElement("hr"));continue;}
let optionElement=editorElement.appendChild(document.createElement("option"));optionElement.value=key;optionElement.textContent=value;}
editorElement.addEventListener("change",(event)=>{this.value=event.target.value;});break;default:console.error("Unknown editor type: "+this._type);}
return editorElement;}};WI.SettingEditor._nextEditorIdentifier=1;WI.SettingEditor.Type={Checkbox:"setting-editor-type-checkbox",Numeric:"setting-editor-type-numeric",Select:"setting-editor-type-select",};WI.SettingEditor.SelectSpacerKey=Symbol("setting-editor-select-spacer-key");WI.SettingEditor.Event={ValueDidChange:"value-did-change",};WI.SettingsGroup=class SettingsGroup extends WI.Object
{constructor(title)
{super();this._element=document.createElement("div");this._element.classList.add("container");let titleElement=this._element.appendChild(document.createElement("div"));titleElement.classList.add("title");titleElement.textContent=title;this._editorGroupElement=this._element.appendChild(document.createElement("div"));this._editorGroupElement.classList.add("editor-group");} 
get element(){return this._element;}
addSetting(setting,label,options)
{let editor=WI.SettingEditor.createForSetting(setting,label,options);if(!editor)
return null;this._editorGroupElement.append(editor.element);return editor;}
addCustomSetting(editorType,options)
{let editor=new WI.SettingEditor(editorType,options.label,options);if(!editor)
return null;this._editorGroupElement.append(editor.element);return editor;}
addCustomEditor()
{let element=this._editorGroupElement.appendChild(document.createElement("div"));element.classList.add("editor");return element;}};WI.SettingsView=class SettingsView extends WI.View
{constructor(identifier,displayName)
{super();this._identifier=identifier;this._displayName=displayName;this.element.classList.add("settings-view",identifier);} 
get identifier(){return this._identifier;}
get displayName(){return this._displayName;}
addSetting(title,setting,label,options)
{let settingsGroup=this.addGroup(title);return settingsGroup.addSetting(setting,label,options);}
addGroupWithCustomSetting(title,editorType,options)
{let settingsGroup=this.addGroup(title);return settingsGroup.addCustomSetting(editorType,options);}
addGroupWithCustomEditor(title,element)
{let settingsGroup=this.addGroup(title);return settingsGroup.addCustomEditor();}
addGroup(title)
{let settingsGroup=new WI.SettingsGroup(title);this.element.append(settingsGroup.element);return settingsGroup;}
addSeparator()
{if(this.element.lastChild&&this.element.lastChild.classList.contains("separator"))
return;let separatorElement=this.element.appendChild(document.createElement("div"));separatorElement.classList.add("separator");}
addCenteredContainer(...nodes)
{let containerElement=document.createElement("div");containerElement.append(...nodes);containerElement.classList.add("container","container-centered");this.element.append(containerElement);return containerElement;}};WI.SettingsView.EditorType={Checkbox:"settings-view-editor-type-checkbox",Numeric:"settings-view-editor-type-numeric",Select:"settings-view-editor-type-select",};WI.AuditTestContentView=class AuditTestContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("audit-test");if(this.representedObject.editable)
this.element.classList.add("editable");if(this.representedObject instanceof WI.AuditTestBase){this._exportTestButtonNavigationItem=new WI.ButtonNavigationItem("audit-export-test",WI.UIString("Export Audit"),"Images/Export.svg",15,15);this._exportTestButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportTestButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportTestButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportTestButtonNavigationItemClicked,this);}
this._exportResultButtonNavigationItem=new WI.ButtonNavigationItem("audit-export-result",WI.UIString("Export Result"),"Images/Export.svg",15,15);this._exportResultButtonNavigationItem.tooltip=WI.UIString("Export result (%s)","Export result (%s) @ Audit Tab","Tooltip for button that exports the most recent result after running an audit.").format(WI.saveKeyboardShortcut.displayName);this._exportResultButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportResultButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportResultButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportResultButtonNavigationItemClicked,this);this._updateExportNavigationItems();this._headerView=new WI.View(document.createElement("header"));this._contentView=new WI.View(document.createElement("section"));this._placeholderElement=null;this._cachedName=this.representedObject.name;this._nameElement=null;this._descriptionElement=null;this._supportsInputElement=null;this._supportsWarningElement=null;this._shownResult=null;} 
get navigationItems()
{let navigationItems=[];if(this._exportTestButtonNavigationItem)
navigationItems.push(this._exportTestButtonNavigationItem);navigationItems.push(this._exportResultButtonNavigationItem);return navigationItems;} 
get headerView(){return this._headerView;}
get contentView(){return this._contentView;}
get supportsSave()
{return!WI.auditManager.editing&&!!this.representedObject.result;}
get saveData()
{return{customSaveHandler:()=>{this._exportResult();}};}
get result()
{if(this.representedObject instanceof WI.AuditTestBase)
return this.representedObject;return this.representedObject.result;}
createNameElement(tagName)
{this._nameElement=document.createElement(tagName);this._nameElement.textContent=this.representedObject.name;this._nameElement.className="name";if(this.representedObject.editable){this._nameElement.spellcheck=false;this._nameElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._descriptionElement);});this._nameElement.addEventListener("input",(event)=>{let name=this._nameElement.textContent;if(!name.trim()){name=this._cachedName;this._nameElement.removeChildren();}
this.representedObject.name=name;});}
return this._nameElement;}
createDescriptionElement(tagName)
{this._descriptionElement=document.createElement(tagName);this._descriptionElement.textContent=this.representedObject.description;this._descriptionElement.className="description";if(this.representedObject.editable){this._descriptionElement.spellcheck=false;this._descriptionElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._supportsInputElement);});this._descriptionElement.addEventListener("input",(event)=>{let description=this._descriptionElement.textContent;if(!description.trim()){description="";this._descriptionElement.removeChildren();}
this.representedObject.description=description;});}
return this._descriptionElement;}
createControlsTableElement()
{let controlsTableElement=document.createElement("table");controlsTableElement.className="controls";let supportsRowElement=controlsTableElement.appendChild(document.createElement("tr"));supportsRowElement.className="supports";let supportsHeaderElement=supportsRowElement.appendChild(document.createElement("th"));supportsHeaderElement.textContent=WI.unlocalizedString("supports");let supportsDataElement=supportsRowElement.appendChild(document.createElement("td"));this._supportsInputElement=supportsDataElement.appendChild(document.createElement("input"));this._supportsInputElement.type="number";this._supportsInputElement.disabled=!this.representedObject.editable;this._supportsInputElement.min=0;this._supportsInputElement.placeholder=Math.min(WI.AuditTestBase.Version,InspectorBackend.hasDomain("Audit")?InspectorBackend.getVersion("Audit"):Infinity);if(!isNaN(this.representedObject.supports))
this._supportsInputElement.value=this.representedObject.supports;if(this.representedObject.editable){this._supportsInputElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._setupEditorElement);});}
this._supportsWarningElement=supportsDataElement.appendChild(document.createElement("span"));this._supportsWarningElement.className="warning";if(this.representedObject.topLevelTest===this.representedObject){let setupRowElement=controlsTableElement.appendChild(document.createElement("tr"));setupRowElement.className="setup";let setupHeaderElement=setupRowElement.appendChild(document.createElement("th"));setupHeaderElement.textContent=WI.unlocalizedString("setup");let setupDataElement=setupRowElement.appendChild(document.createElement("td"));this._setupEditorElement=setupDataElement.appendChild(document.createElement("div"));}
if(this.representedObject.editable){this._supportsInputElement.addEventListener("input",(event)=>{this.representedObject.supports=parseInt(this._supportsInputElement.value);this._updateSupportsInputState();});}
return controlsTableElement;}
initialLayout()
{super.initialLayout();this.addSubview(this._headerView);this.addSubview(this._contentView);}
layout()
{super.layout();if(this.representedObject instanceof WI.AuditTestBase){this.element.classList.toggle("unsupported",!this.representedObject.supported);this.element.classList.toggle("disabled",this.representedObject.disabled);this.element.classList.toggle("manager-editing",WI.auditManager.editing);if(this.representedObject.editable){let contentEditable=WI.auditManager.editing?"plaintext-only":"inherit";this._nameElement.contentEditable=contentEditable;this._descriptionElement.contentEditable=contentEditable;}
if(WI.auditManager.editing){this._cachedName=this.representedObject.name;this._nameElement.dataset.name=this._cachedName;this._updateSupportsInputState();this._createSetupEditor();}else{this._nameElement.textContent||=this._cachedName;this._setupEditorElement?.removeChildren();}}
this.hidePlaceholder();this._updateExportNavigationItems();}
attached()
{super.attached();if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.ResultChanged,this.handleResultChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Stopping,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleEditingChanged,this);}}
detached()
{if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.ResultChanged,this.handleResultChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Stopping,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleEditingChanged,this);if(this.representedObject.editable&&WI.auditManager.editing)
this.saveEditedData();}
super.detached();}
handleResultChanged(event)
{if(!WI.auditManager.editing)
this.needsLayout();}
get placeholderElement()
{return this._placeholderElement;}
set placeholderElement(placeholderElement)
{this.hidePlaceholder();this._placeholderElement=placeholderElement;}
saveEditedData()
{if(this._setupCodeMirror)
this.representedObject.setup=this._setupCodeMirror.getValue().trim();}
showRunningPlaceholder()
{this._showPlaceholder();}
showStoppingPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderStopping){this.placeholderElement=WI.createMessageTextView(WI.UIString("Stopping the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderStopping=true;let spinner=new WI.IndeterminateProgressSpinner;this.placeholderElement.appendChild(spinner.element);this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
this._showPlaceholder();}
showNoResultPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderNoResult){this.placeholderElement=WI.createMessageTextView(WI.UIString("No Result"));this.placeholderElement.__placeholderNoResult=true;let startNavigationItem=new WI.ButtonNavigationItem("run-audit",WI.UIString("Start"),"Images/AuditStart.svg",15,15);startNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;startNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.start([this.representedObject]);},this);let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to start running the audit."),startNavigationItem);this.placeholderElement.appendChild(importHelpElement);this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
this._showPlaceholder();}
showNoResultDataPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderNoResultData){let result=this.representedObject.result;if(!result){this.showNoResultPlaceholder();return;}
let message=null;if(result.didError)
message=WI.UIString("The \u201C%s\u201D audit threw an error");else if(result.didFail)
message=WI.UIString("The \u201C%s\u201D audit failed");else if(result.didWarn)
message=WI.UIString("The \u201C%s\u201D audit resulted in a warning");else if(result.didPass)
message=WI.UIString("The \u201C%s\u201D audit passed");else if(result.unsupported)
message=WI.UIString("The \u201C%s\u201D audit is unsupported");else{console.error("Unknown result",result);return;}
this.placeholderElement=WI.createMessageTextView(message.format(this.representedObject.name),result.didError);this.placeholderElement.__placeholderNoResultData=true;this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
this._showPlaceholder();}
showFilteredPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderFiltered){this.placeholderElement=WI.createMessageTextView(WI.UIString("No Filter Results"));this.placeholderElement.__placeholderFiltered=true;let buttonElement=this.placeholderElement.appendChild(document.createElement("button"));buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",()=>{this.resetFilter();this.needsLayout();});this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
this._showPlaceholder();}
hidePlaceholder()
{this.element.classList.remove("showing-placeholder");if(this.placeholderElement)
this.placeholderElement.remove();}
applyFilter(levels)
{let hasMatch=false;for(let view of this.contentView.subviews){let matches=view.applyFilter(levels);view.element.classList.toggle("filtered",!matches);if(matches)
hasMatch=true;}
this.element.classList.toggle("no-matches",!hasMatch);if(!Array.isArray(levels))
return true;let result=this.representedObject.result;if(!result)
return false;if((levels.includes(WI.AuditTestCaseResult.Level.Error)&&result.didError)||(levels.includes(WI.AuditTestCaseResult.Level.Fail)&&result.didFail)||(levels.includes(WI.AuditTestCaseResult.Level.Warn)&&result.didWarn)||(levels.includes(WI.AuditTestCaseResult.Level.Pass)&&result.didPass)||(levels.includes(WI.AuditTestCaseResult.Level.Unsupported)&&result.unsupported)){return true;}
return false;}
resetFilter()
{for(let view of this.contentView.subviews)
view.element.classList.remove("filtered");this.element.classList.remove("no-matches");} 
_exportResult()
{WI.auditManager.export(this.representedObject.result);}
_updateExportNavigationItems()
{if(this._exportTestButtonNavigationItem)
this._exportTestButtonNavigationItem.enabled=!WI.auditManager.editing;this._exportResultButtonNavigationItem.enabled=!WI.auditManager.editing&&this.representedObject.result;}
_updateSupportsInputState()
{this._supportsInputElement.autosize(4);this._supportsWarningElement.removeChildren();if(this.representedObject.supports>WI.AuditTestBase.Version)
this._supportsWarningElement.textContent=WI.UIString("too new to run in this Web Inspector","too new to run in this Web Inspector @ Audit Tab","Warning text shown if the version number in the 'supports' input is too new.");else if(InspectorBackend.hasDomain("Audit")&&this._supports>InspectorBackend.getVersion("Audit"))
this._supportsWarningElement.textContent=WI.UIString("too new to run in the inspected page","too new to run in the inspected page @ Audit Tab","Warning text shown if the version number in the 'supports' input is too new.");}
_createSetupEditor()
{if(!this._setupEditorElement)
return;let setupEditorElement=document.createElement(this._setupEditorElement.nodeName);setupEditorElement.className="editor";setTimeout(()=>{this._setupCodeMirror=WI.CodeMirrorEditor.create(setupEditorElement,{autoCloseBrackets:true,lineNumbers:true,lineWrapping:true,matchBrackets:true,mode:"text/javascript",readOnly:this.representedObject.editable?false:"nocursor",styleSelectedText:true,value:this.representedObject.setup,});});this._setupEditorElement.parentNode.replaceChild(setupEditorElement,this._setupEditorElement);this._setupEditorElement=setupEditorElement;}
_showPlaceholder()
{this.element.classList.add("showing-placeholder");this.contentView.element.appendChild(this.placeholderElement);}
_handleEditorKeydown(event,nextEditor)
{switch(event.keyCode){case WI.KeyboardShortcut.Key.Enter.keyCode:if(nextEditor){nextEditor.focus();break;} 
case WI.KeyboardShortcut.Key.Escape.keyCode:event.target.blur();break;default:return;}
event.preventDefault();}
_handleExportTestButtonNavigationItemClicked(event)
{WI.auditManager.export(this.representedObject);}
_handleExportResultButtonNavigationItemClicked(event)
{this._exportResult();}
_handleTestChanged(event)
{this.needsLayout();}
_handleTestDisabledChanged(event)
{this.element.classList.toggle("disabled",this.representedObject.disabled);}
_handleTestSupportedChanged(event)
{this.element.classList.toggle("unsupported",!this.representedObject.supported);}
_handleEditingChanged(event)
{this.needsLayout();if(!WI.auditManager.editing&&this.representedObject.editable)
this.saveEditedData();this._updateExportNavigationItems();}};WI.CollectionContentView=class CollectionContentView extends WI.ContentView
{constructor(collection,contentViewConstructor,contentPlaceholder)
{super(collection);this.element.classList.add("collection");this._contentPlaceholder=contentPlaceholder||collection.displayName;this._contentPlaceholderElement=null;this._contentViewConstructor=contentViewConstructor;this._contentViewMap=new Map;this._selectedItem=null;this._selectionEnabled=false;} 
get supplementalRepresentedObjects()
{if(this._selectedItem)
return[this._selectedItem];return[];}
get selectionEnabled()
{return this._selectionEnabled;}
set selectionEnabled(value)
{if(this._selectionEnabled===value)
return;this._selectionEnabled=value;if(!this._selectionEnabled)
this._selectItem(null);}
get selectedItem()
{return this._selectedItem;}
set selectedItem(item)
{if(!this._selectionEnabled)
return;this._selectItem(item);if(item){let contentView=this._contentViewMap.get(item);if(contentView)
contentView.element.scrollIntoViewIfNeeded();}} 
get contentViewConstructorOptions()
{return{};}
addContentViewForItem(item)
{if(!this._contentViewConstructor)
return;if(this._contentViewMap.has(item)){return;}
this.hideContentPlaceholder();let contentView=new this._contentViewConstructor(item,this.contentViewConstructorOptions);this._contentViewMap.set(item,contentView);this.addSubview(contentView);this.contentViewAdded(contentView);}
removeContentViewForItem(item)
{if(!this._contentViewConstructor)
return;let contentView=this._contentViewMap.get(item);if(!contentView)
return;if(this._selectedItem===item)
this._selectItem(null);this.removeSubview(contentView);this._contentViewMap.delete(item);this.contentViewRemoved(contentView);if(!this.subviews.length)
this.showContentPlaceholder();}
contentViewAdded(contentView)
{}
contentViewRemoved(contentView)
{}
showContentPlaceholder()
{if(!this._contentPlaceholderElement){if(typeof this._contentPlaceholder==="string")
this._contentPlaceholderElement=WI.createMessageTextView(this._contentPlaceholder);else if(this._contentPlaceholder instanceof HTMLElement)
this._contentPlaceholderElement=this._contentPlaceholder;}
this._contentPlaceholderElement.classList.add("placeholder");if(!this._contentPlaceholderElement.parentNode)
this.element.appendChild(this._contentPlaceholderElement);}
hideContentPlaceholder()
{if(this._contentPlaceholderElement)
this._contentPlaceholderElement.remove();}
initialLayout()
{if(this._contentViewConstructor)
this.element.addEventListener("click",this._handleClick.bind(this));if(!this.representedObject.size||!this._contentViewConstructor)
this.showContentPlaceholder();}
attached()
{super.attached();this.representedObject.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);for(let item of this._contentViewMap.keys()){if(this.representedObject.has(item))
continue;this.removeContentViewForItem(item);if(this._selectedItem===item)
this._selectItem(null);}
for(let item of this.representedObject){if(!this._contentViewMap.has(item))
this.addContentViewForItem(item);}}
detached()
{this.representedObject.removeEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.removeEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);super.detached();} 
_handleItemAdded(event)
{let item=event.data.item;if(!item)
return;this.addContentViewForItem(item);}
_handleItemRemoved(event)
{let item=event.data.item;if(!item)
return;this.removeContentViewForItem(item);}
_handleContentError(event)
{if(event&&event.target)
this._removeContentViewForItem(event.target.representedObject);}
_selectItem(item)
{if(this._selectedItem===item)
return;if(this._selectedItem){let contentView=this._contentViewMap.get(this._selectedItem);contentView.element.classList.remove("selected");}
this._selectedItem=item;if(this._selectedItem){let selectedContentView=this._contentViewMap.get(this._selectedItem);selectedContentView.element.classList.add("selected");}
this.dispatchEventToListeners(WI.CollectionContentView.Event.SelectedItemChanged);this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_handleClick(event)
{if(event.button!==0||event.ctrlKey)
return;for(let[item,contentView]of this._contentViewMap){if(contentView.element.contains(event.target)){if(this._selectionEnabled)
this._selectItem(item);else
WI.showRepresentedObject(item);return;}}
if(this._selectionEnabled)
this._selectItem(null);}};WI.CollectionContentView.Event={SelectedItemChanged:"collection-content-view-selected-item-changed",};WI.LocalRemoteObjectContentView=class LocalRemoteObjectContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this._remoteObject=null;this._spinnerTimeout=undefined;this.element.classList.add("local-remote-object");} 
get expression()
{throw WI.NotImplementedError.subclassMustOverride();}
renderRemoteObject(remoteObject)
{throw WI.NotImplementedError.subclassMustOverride();}
initialLayout()
{super.initialLayout();let target=WI.assumingMainTarget();let options={expression:"("+this.expression+")",doNotPauseOnExceptionsAndMuteConsole:true,generatePreview:true,};target.RuntimeAgent.evaluate.invoke(options,(error,result,wasThrown)=>{this._remoteObject=WI.RemoteObject.fromPayload(result);if(this._spinnerTimeout){clearTimeout(this._spinnerTimeout);this._spinnerTimeout=undefined;}
this.element.removeChildren();this.renderRemoteObject(this._remoteObject);});}
attached()
{super.attached();if(this._spinnerTimeout||this._remoteObject)
return;this._spinnerTimeout=setTimeout(()=>{let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._spinnerTimeout=undefined;},100);}
closed()
{super.closed();if(this._remoteObject){this._remoteObject.release();this._remoteObject=null;}}};WI.ActivateButtonNavigationItem=class ActivateButtonNavigationItem extends WI.ButtonNavigationItem
{constructor(identifier,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight,role)
{super(identifier,defaultToolTip,image,imageWidth,imageHeight,role);this._defaultToolTip=defaultToolTip;this._activatedToolTip=activatedToolTip||defaultToolTip;} 
get defaultToolTip()
{return this._defaultToolTip;}
set defaultToolTip(defaultToolTip)
{this._defaultToolTip=defaultToolTip;if(!this.activated)
this.tooltip=this._defaultToolTip;}
get activatedToolTip()
{return this._activatedToolTip;}
set activatedToolTip(activatedToolTip)
{this._activatedToolTip=activatedToolTip;if(this.activated)
this.tooltip=this._activatedToolTip;}
get activated()
{return this.element.classList.contains(WI.ActivateButtonNavigationItem.ActivatedStyleClassName);}
set activated(flag)
{flag=!!flag;this.element.classList.toggle(WI.ActivateButtonNavigationItem.ActivatedStyleClassName,flag);this.tooltip=flag?this._activatedToolTip:this._defaultToolTip;this.element.ariaPressed=flag;this.element.ariaLabel=this.tooltip;} 
get additionalClassNames()
{return["activate","button"];}};WI.ActivateButtonNavigationItem.ActivatedStyleClassName="activated";WI.AnimationCollectionContentView=class AnimationCollectionContentView extends WI.CollectionContentView
{constructor(representedObject)
{let contentPlaceholder=document.createElement("div");let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";switch(representedObject.animationType){case WI.Animation.Type.WebAnimation:descriptionElement.textContent=WI.UIString("Waiting for animations created by JavaScript.");break;case WI.Animation.Type.CSSAnimation:descriptionElement.textContent=WI.UIString("Waiting for animations created by CSS.");break;case WI.Animation.Type.CSSTransition:descriptionElement.textContent=WI.UIString("Waiting for transitions created by CSS.");break;}
super(representedObject,WI.AnimationContentView,contentPlaceholder);this.selectionEnabled=true;this.element.classList.add("animation-collection");} 
handleRefreshButtonClicked()
{for(let subview of this.subviews){if(subview instanceof WI.AnimationContentView)
subview.handleRefreshButtonClicked();}} 
contentViewAdded(contentView)
{contentView.element.addEventListener("mouseenter",this._handleContentViewMouseEnter);contentView.element.addEventListener("mouseleave",this._handleContentViewMouseLeave);}
contentViewRemoved(contentView)
{contentView.element.removeEventListener("mouseenter",this._handleContentViewMouseEnter);contentView.element.removeEventListener("mouseleave",this._handleContentViewMouseLeave);}
detached()
{WI.domManager.hideDOMNodeHighlight();super.detached();} 
_handleContentViewMouseEnter(event)
{let contentView=WI.View.fromElement(event.target);if(!(contentView instanceof WI.AnimationContentView))
return;let animation=contentView.representedObject;animation.requestEffectTarget((node)=>{if(!node||!node.ownerDocument)
return;node.highlight();});}
_handleContentViewMouseLeave(event)
{WI.domManager.hideDOMNodeHighlight();}};WI.AnimationContentView=class AnimationContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this._animationTargetDOMNode=null;this._cachedWidth=NaN;this.element.classList.add("animation");} 
static get previewHeight()
{return 40;} 
handleRefreshButtonClicked()
{this._refreshSubtitle();} 
initialLayout()
{super.initialLayout();let headerElement=this.element.appendChild(document.createElement("header"));let titlesContainer=headerElement.appendChild(document.createElement("div"));titlesContainer.className="titles";this._titleElement=titlesContainer.appendChild(document.createElement("span"));this._titleElement.className="title";this._subtitleElement=titlesContainer.appendChild(document.createElement("span"));this._subtitleElement.className="subtitle";let navigationBar=new WI.NavigationBar;let animationTargetButtonNavigationItem=new WI.ButtonNavigationItem("animation-target",WI.UIString("Animation Target"),"Images/Markup.svg",16,16);animationTargetButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.addMouseDownContextMenuHandlers(animationTargetButtonNavigationItem.element,this._populateAnimationTargetButtonContextMenu.bind(this));navigationBar.addNavigationItem(animationTargetButtonNavigationItem);headerElement.append(navigationBar.element);this.addSubview(navigationBar);this._previewContainer=this.element.appendChild(document.createElement("div"));this._previewContainer.className="preview";}
layout()
{super.layout();this._refreshTitle();this._refreshSubtitle();this._refreshPreview();}
sizeDidChange()
{super.sizeDidChange();this._cachedWidth=this.element.realOffsetWidth;}
attached()
{super.attached();this.representedObject.addEventListener(WI.Animation.Event.NameChanged,this._handleNameChanged,this);this.representedObject.addEventListener(WI.Animation.Event.EffectChanged,this._handleEffectChanged,this);this.representedObject.addEventListener(WI.Animation.Event.TargetChanged,this._handleTargetChanged,this);}
detached()
{this.representedObject.removeEventListener(WI.Animation.Event.TargetChanged,this._handleTargetChanged,this);this.representedObject.removeEventListener(WI.Animation.Event.EffectChanged,this._handleEffectChanged,this);this.representedObject.removeEventListener(WI.Animation.Event.NameChanged,this._handleNameChanged,this);super.detached();} 
_refreshTitle()
{this._titleElement.removeChildren();let displayName=this.representedObject.displayName;let showIdentifierIfDifferent=(cssName)=>{let formatString="";let substitutions=[];if(cssName===displayName)
formatString=WI.UIString("(%s)");else{formatString=WI.UIString("%s (%s)");substitutions.push(displayName);}
let cssNameWrapper=document.createElement("code");cssNameWrapper.textContent=cssName;substitutions.push(cssNameWrapper);String.format(formatString,substitutions,String.standardFormatters,this._titleElement,function(a,b){a.append(b);return a;});};switch(this.representedObject.animationType){case WI.Animation.Type.WebAnimation:this._titleElement.textContent=this.representedObject.name||WI.UIString("(%s)").format(displayName);break;case WI.Animation.Type.CSSAnimation:showIdentifierIfDifferent(this.representedObject.cssAnimationName);break;case WI.Animation.Type.CSSTransition:showIdentifierIfDifferent(this.representedObject.cssTransitionProperty);break;}}
_refreshSubtitle()
{this.representedObject.requestEffectTarget((domNode)=>{this._animationTargetDOMNode=domNode;this._subtitleElement.removeChildren();if(domNode)
this._subtitleElement.appendChild(WI.linkifyNodeReference(domNode));});}
_refreshPreview()
{this._previewContainer.removeChildren();let keyframes=this.representedObject.keyframes;if(!keyframes.length){let span=this._previewContainer.appendChild(document.createElement("span"));span.textContent=WI.UIString("This animation has no keyframes.");return;}
let startDelay=this.representedObject.startDelay||0;let iterationDuration=this.representedObject.iterationDuration||0;let endDelay=this.representedObject.endDelay||0;let totalDuration=startDelay+iterationDuration+endDelay;if(totalDuration===0){let span=this._previewContainer.appendChild(document.createElement("span"));span.textContent=WI.UIString("This animation has no duration.");return;}
const previewHeight=WI.AnimationContentView.previewHeight;const markerHeadRadius=4;const markerHeadPadding=2;const squeezeXStart=(iterationDuration&&startDelay)?0:markerHeadRadius+markerHeadPadding;const squeezeXEnd=(iterationDuration&&endDelay)?0:markerHeadRadius+markerHeadPadding;const squeezeYStart=markerHeadRadius+(markerHeadPadding*2);const adjustEasingHeight=-1;const adjustEasingBottomY=0.5;let secondsPerPixel=this._cachedWidth/totalDuration;startDelay*=secondsPerPixel;iterationDuration=(iterationDuration*secondsPerPixel)-squeezeXStart-squeezeXEnd;endDelay*=secondsPerPixel;let svg=this._previewContainer.appendChild(createSVGElement("svg"));svg.setAttribute("viewBox",`0 0 ${this._cachedWidth} ${previewHeight}`);function addTitle(parent,title){let titleElement=parent.appendChild(createSVGElement("title"));titleElement.textContent=title;}
if(startDelay){let startDelayContainer=svg.appendChild(createSVGElement("g"));startDelayContainer.classList.add("delay","start");let startDelayLine=startDelayContainer.appendChild(createSVGElement("line"));startDelayLine.setAttribute("y1",(previewHeight+squeezeYStart)/2);startDelayLine.setAttribute("x2",startDelay);startDelayLine.setAttribute("y2",(previewHeight+squeezeYStart)/2);let startDelayElement=startDelayContainer.appendChild(createSVGElement("rect"));startDelayElement.setAttribute("width",startDelay);startDelayElement.setAttribute("height",previewHeight);const startDelayTitleFormat=WI.UIString("Start Delay %s","Web Animation Start Delay Tooltip","Tooltip for section of graph representing delay before a web animation begins applying styles");addTitle(startDelayElement,startDelayTitleFormat.format(Number.secondsToString(this.representedObject.startDelay/1000)));}
if(endDelay){let endDelayContainer=svg.appendChild(createSVGElement("g"));endDelayContainer.setAttribute("transform",`translate(${startDelay + iterationDuration + squeezeXStart}, 0)`);endDelayContainer.classList.add("delay","end");let endDelayLine=endDelayContainer.appendChild(createSVGElement("line"));endDelayLine.setAttribute("y1",(previewHeight+squeezeYStart)/2);endDelayLine.setAttribute("x2",endDelay);endDelayLine.setAttribute("y2",(previewHeight+squeezeYStart)/2);let endDelayElement=endDelayContainer.appendChild(createSVGElement("rect"));endDelayElement.setAttribute("width",startDelay+iterationDuration+endDelay);endDelayElement.setAttribute("height",previewHeight);const endDelayTitleFormat=WI.UIString("End Delay %s","Web Animation End Delay Tooltip","Tooltip for section of graph representing delay after a web animation finishes applying styles");addTitle(endDelayElement,endDelayTitleFormat.format(Number.secondsToString(this.representedObject.endDelay/1000)));}
if(iterationDuration){let timingFunction=this.representedObject.timingFunction;let activeDurationContainer=svg.appendChild(createSVGElement("g"));activeDurationContainer.classList.add("active");activeDurationContainer.setAttribute("transform",`translate(${startDelay + squeezeXStart}, ${squeezeYStart})`);const startY=0;const endY=previewHeight-squeezeYStart;const height=endY-startY;for(let[keyframeA,keyframeB]of keyframes.adjacencies()){let startX=iterationDuration*keyframeA.offset;let endX=iterationDuration*keyframeB.offset;let width=endX-startX;let easing=keyframeA.easing||timingFunction;let easingContainer=activeDurationContainer.appendChild(createSVGElement("g"));easingContainer.classList.add("easing");easingContainer.setAttribute("transform",`translate(${startX}, ${startY})`);let easingPath=easingContainer.appendChild(createSVGElement("path"));let pathSteps=[];if(easing instanceof WI.CubicBezier){pathSteps.push("C");pathSteps.push(easing.inPoint.x*width); pathSteps.push((1-easing.inPoint.y)*(height+adjustEasingHeight)); pathSteps.push(easing.outPoint.x*width); pathSteps.push((1-easing.outPoint.y)*(height+adjustEasingHeight)); pathSteps.push(width); pathSteps.push(0);}else if(easing instanceof WI.StepsFunction){let goUpFirst=false;let stepStartAdjust=0;let stepCountAdjust=0;switch(easing.type){case WI.StepsFunction.Type.JumpStart:case WI.StepsFunction.Type.Start:goUpFirst=true;break;case WI.StepsFunction.Type.JumpNone:--stepCountAdjust;break;case WI.StepsFunction.Type.JumpBoth:++stepStartAdjust;++stepCountAdjust;break;}
let stepCount=easing.count+stepCountAdjust;let stepX=width/easing.count;let stepY=(height+adjustEasingHeight)/stepCount;for(let i=stepStartAdjust;i<=stepCount;++i){let x=stepX*(i-stepStartAdjust);let y=height+adjustEasingHeight-(stepY*i);if(goUpFirst){if(i)
pathSteps.push("H",x);if(i<stepCount)
pathSteps.push("V",y-stepY);}else{pathSteps.push("V",y);if(i<stepCount||stepCountAdjust<0)
pathSteps.push("H",x+stepX);}}}else if(easing instanceof WI.Spring){let duration=easing.calculateDuration();for(let i=0;i<width;i+=1/window.devicePixelRatio)
pathSteps.push("L",i,easing.solve(duration*i/width)*(height+adjustEasingHeight));}
easingPath.setAttribute("d",`M 0 ${height + adjustEasingBottomY} ${pathSteps.join(" ")} V ${height + adjustEasingBottomY} Z`);let titleRect=easingContainer.appendChild(createSVGElement("rect"));titleRect.setAttribute("width",width);titleRect.setAttribute("height",height);addTitle(titleRect,easing.toString());}
for(let keyframe of keyframes){let x=iterationDuration*keyframe.offset;let keyframeContainer=activeDurationContainer.appendChild(createSVGElement("g"));keyframeContainer.classList.add("keyframe");keyframeContainer.setAttribute("transform",`translate(${x}, ${startY})`);let keyframeMarkerHead=keyframeContainer.appendChild(createSVGElement("circle"));keyframeMarkerHead.setAttribute("r",markerHeadRadius);let keyframeMarkerLine=keyframeContainer.appendChild(createSVGElement("line"));keyframeMarkerLine.setAttribute("y1",height);let titleRect=keyframeContainer.appendChild(createSVGElement("rect"));titleRect.setAttribute("x",-1*(markerHeadRadius+markerHeadPadding));titleRect.setAttribute("y",-1*squeezeYStart);titleRect.setAttribute("width",(markerHeadRadius+markerHeadPadding)*2);titleRect.setAttribute("height",height+squeezeYStart);addTitle(titleRect,keyframe.style);}}}
_handleNameChanged(event)
{if(!this.didInitialLayout)
return;this._refreshTitle();}
_handleEffectChanged(event)
{this._refreshPreview();}
_handleTargetChanged(event)
{this._refreshSubtitle();}
_populateAnimationTargetButtonContextMenu(contextMenu)
{contextMenu.appendItem(WI.UIString("Log Animation"),()=>{WI.RemoteObject.resolveAnimation(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject)
return;const text=WI.UIString("Selected Animation","Appears as a label when a given web animation is logged to the Console");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);});});contextMenu.appendSeparator();if(this._animationTargetDOMNode)
WI.appendContextMenuItemsForDOMNode(contextMenu,this._animationTargetDOMNode);}};WI.AnimationDetailsSidebarPanel=class AnimationDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("animation",WI.UIString("Animation"));this._animation=null;this._codeMirrorSectionMap=new Map;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];this.animation=objects.find((object)=>object instanceof WI.Animation);return!!this.animation;}
get animation()
{return this._animation;}
set animation(animation)
{if(animation===this._animation)
return;if(this._animation){this._animation.removeEventListener(WI.Animation.Event.TargetChanged,this._handleAnimationTargetChanged,this);this._animation.removeEventListener(WI.Animation.Event.EffectChanged,this._handleAnimationEffectChanged,this);this._animation.removeEventListener(WI.Animation.Event.NameChanged,this._handleAnimationNameChanged,this);}
this._animation=animation||null;if(this._animation){this._animation.addEventListener(WI.Animation.Event.NameChanged,this._handleAnimationNameChanged,this);this._animation.addEventListener(WI.Animation.Event.EffectChanged,this._handleAnimationEffectChanged,this);this._animation.addEventListener(WI.Animation.Event.TargetChanged,this._handleAnimationTargetChanged,this);}
this.needsLayout();} 
initialLayout()
{super.initialLayout();this._idRow=new WI.DetailsSectionSimpleRow(WI.UIString("Identifier"));this._typeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._cssAnimationNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._cssTransitionPropertyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Property"));this._targetRow=new WI.DetailsSectionSimpleRow(WI.UIString("Target","Web Animation Target Label","Label for the current DOM node target of a web animation"));const identitySectionTitle=WI.UIString("Identity","Web Animation Identity Title","Section title for information about a web animation");let identitySection=new WI.DetailsSection("animation-identity",identitySectionTitle,[new WI.DetailsSectionGroup([this._idRow,this._typeRow,this._cssAnimationNameRow,this._cssTransitionPropertyRow,this._targetRow])]);this.contentView.element.appendChild(identitySection.element);this._iterationCountRow=new WI.DetailsSectionSimpleRow(WI.UIString("Iterations","Web Animation Iteration Count Label","Label for the number of iterations of a web animation"));this._iterationStartRow=new WI.DetailsSectionSimpleRow(WI.UIString("Start","Web Animation Iteration Start Label","Label for the number describing which iteration a web animation should start at"));this._iterationDurationRow=new WI.DetailsSectionSimpleRow(WI.UIString("Duration","Web Animation Iteration Duration Label","Label for the time duration of each iteration of a web animation"));let iterationsGroup=new WI.DetailsSectionGroup([this._iterationCountRow,this._iterationStartRow,this._iterationDurationRow]);this._startDelayRow=new WI.DetailsSectionSimpleRow(WI.UIString("Start Delay","Web Animation Start Delay Label","Label for the start delay time of a web animation "));this._endDelayRow=new WI.DetailsSectionSimpleRow(WI.UIString("End Delay","Web Animation End Delay Label","Label for the end delay time of a web animation "));this._timingFunctionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Easing","Web Animation Easing Label","Label for the cubic-bezier timing function of a web animation"));let timingGroup=new WI.DetailsSectionGroup([this._startDelayRow,this._endDelayRow,this._timingFunctionRow]);this._playbackDirectionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Direction","Web Animation Playback Direction Label","Label for the playback direction of a web animation"));this._fillModeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Fill","Web Animation Fill Mode Label","Label for the fill mode of a web animation"));let fillDirectionGroup=new WI.DetailsSectionGroup([this._playbackDirectionRow,this._fillModeRow]);const effectSectionTitle=WI.UIString("Effect","Web Animation Effect Title","Section title for information about the effect of a web animation");let effectSection=new WI.DetailsSection("animation-effect",effectSectionTitle,[iterationsGroup,timingGroup,fillDirectionGroup]);this.contentView.element.appendChild(effectSection.element);this._keyframesGroup=new WI.DetailsSectionGroup;const keyframesSectionTitle=WI.UIString("Keyframes","Web Animation Keyframes Title","Section title for information about the keyframes of a web animation");let keyframesSection=new WI.DetailsSection("animation-keyframes",keyframesSectionTitle,[this._keyframesGroup]);this.contentView.element.appendChild(keyframesSection.element);const selectable=false;let backtraceTreeOutline=new WI.TreeOutline(selectable);backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.CallFrameTreeController(backtraceTreeOutline);let backtraceRow=new WI.DetailsSectionRow;backtraceRow.element.appendChild(backtraceTreeOutline.element);const backtraceSectionTitle=WI.UIString("Backtrace","Web Animation Backtrace Title","Section title for the JavaScript backtrace of the creation of a web animation");this._backtraceSection=new WI.DetailsSection("animation-backtrace",backtraceSectionTitle,[new WI.DetailsSectionGroup([backtraceRow])]);this._backtraceSection.element.hidden=true;this.contentView.element.appendChild(this._backtraceSection.element);}
layout()
{super.layout();if(!this._animation)
return;this._refreshIdentitySection();this._refreshEffectSection();this._refreshBacktraceSection();for(let codeMirror of this._codeMirrorSectionMap.values())
codeMirror.refresh();}
attached()
{super.attached();for(let codeMirror of this._codeMirrorSectionMap.values())
codeMirror.refresh();} 
_refreshIdentitySection()
{let animationType=this._animation.animationType;let displayName=this._animation.displayName;let cssAnimationName=this._animation.cssAnimationName;let cssTransitionProperty=this._animation.cssTransitionProperty;switch(animationType){case WI.Animation.Type.WebAnimation:this._idRow.value=this._animation.name;break;case WI.Animation.Type.CSSAnimation:this._idRow.value=cssAnimationName!==displayName?displayName:null;break;case WI.Animation.Type.CSSTransition:this._idRow.value=cssTransitionProperty!==displayName?displayName:null;break;}
this._typeRow.value=WI.Animation.displayNameForAnimationType(animationType);this._cssAnimationNameRow.value=cssAnimationName;this._cssTransitionPropertyRow.value=cssTransitionProperty;this._targetRow.value=null;this._animation.requestEffectTarget((domNode)=>{this._targetRow.value=domNode?WI.linkifyNodeReference(domNode):null;});}
_refreshEffectSection()
{for(let section of this._codeMirrorSectionMap.keys())
section.removeEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);this._codeMirrorSectionMap.clear();const precision=0;const readOnly=true;this._iterationCountRow.value=!isNaN(this._animation.iterationCount)?this._animation.iterationCount.toLocaleString():null;this._iterationStartRow.value=!isNaN(this._animation.iterationStart)?this._animation.iterationStart.toLocaleString():null;this._iterationDurationRow.value=!isNaN(this._animation.iterationDuration)?Number.secondsToString(this._animation.iterationDuration/1000):null;this._startDelayRow.value=this._animation.startDelay?Number.secondsToString(this._animation.startDelay/1000):null;this._endDelayRow.value=this._animation.endDelay?Number.secondsToString(this._animation.endDelay/1000):null;this._timingFunctionRow.value=this._animation.timingFunction?this._animation.timingFunction.toString():null;this._playbackDirectionRow.value=this._animation.playbackDirection?WI.Animation.displayNameForPlaybackDirection(this._animation.playbackDirection):null;this._fillModeRow.value=this._animation.fillMode?WI.Animation.displayNameForFillMode(this._animation.fillMode):null;let keyframeSections=[];for(let keyframe of this._animation.keyframes){let rows=[];let keyframeSection=new WI.DetailsSection("animation-keyframe-offset-"+keyframe.offset,Number.percentageString(keyframe.offset,precision));keyframeSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);keyframeSections.push(keyframeSection);if(keyframe.easing){let subtitle=keyframeSection.headerElement.appendChild(document.createElement("span"));subtitle.className="subtitle";subtitle.textContent=` ${emDash} ${keyframe.easing.toString()}`;}
if(keyframe.style){let codeMirrorElement=document.createElement("div");let codeMirror=WI.CodeMirrorEditor.create(codeMirrorElement,{mode:"css",readOnly:"nocursor",lineWrapping:true,});codeMirror.setValue(keyframe.style);const range=null;function optionsForType(type){return{allowedTokens:/\btag\b/,callback(marker,valueObject,valueString){let swatch=new WI.InlineSwatch(type,valueObject,readOnly);codeMirror.setUniqueBookmark(marker.range.startPosition().toCodeMirror(),swatch.element);}};}
createCodeMirrorColorTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Color));createCodeMirrorGradientTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Gradient));createCodeMirrorCubicBezierTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Bezier));createCodeMirrorSpringTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Spring));let row=new WI.DetailsSectionRow;row.element.classList.add("styles");row.element.appendChild(codeMirrorElement);rows.push(row);this._codeMirrorSectionMap.set(keyframeSection,codeMirror);}
if(!rows.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Styles"));emptyRow.showEmptyMessage();rows.push(emptyRow);}
keyframeSection.groups=[new WI.DetailsSectionGroup(rows)];}
if(!keyframeSections.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Keyframes"));emptyRow.showEmptyMessage();keyframeSections.push(emptyRow);}
this._keyframesGroup.rows=keyframeSections;}
_refreshBacktraceSection()
{let callFrames=this._animation.backtrace;this._backtraceTreeController.callFrames=callFrames;this._backtraceSection.element.hidden=!callFrames.length;}
_handleAnimationNameChanged(event)
{this._refreshIdentitySection();}
_handleAnimationEffectChanged(event)
{this._refreshEffectSection();}
_handleAnimationTargetChanged(event)
{this._refreshIdentitySection();}
_handleDetailsSectionCollapsedStateChanged(event)
{let codeMirror=this._codeMirrorSectionMap.get(event.target);codeMirror.refresh();}};WI.ApplicationCacheDetailsSidebarPanel=class ApplicationCacheDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("application-cache-details",WI.UIString("Storage"));this.element.classList.add("application-cache");this._applicationCacheFrame=null;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];var applicationCacheFrameToInspect=null;for(var i=0;i<objects.length;++i){if(objects[i]instanceof WI.ApplicationCacheFrame){applicationCacheFrameToInspect=objects[i];break;}}
this.applicationCacheFrame=applicationCacheFrameToInspect;return!!this.applicationCacheFrame;}
get applicationCacheFrame()
{return this._applicationCacheFrame;}
set applicationCacheFrame(applicationCacheFrame)
{if(this._applicationCacheFrame===applicationCacheFrame)
return;this._applicationCacheFrame=applicationCacheFrame;this.needsLayout();}
closed()
{if(this.didInitialLayout){WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.NetworkStateUpdated,this._networkStateUpdated,this);WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.FrameManifestStatusChanged,this._frameManifestStatusChanged,this);}
super.closed();} 
initialLayout()
{super.initialLayout();this._locationManifestURLRow=new WI.DetailsSectionSimpleRow(WI.UIString("Manifest URL"));this._locationFrameURLRow=new WI.DetailsSectionSimpleRow(WI.UIString("Frame URL"));let locationGroup=new WI.DetailsSectionGroup([this._locationManifestURLRow,this._locationFrameURLRow]);let locationSection=new WI.DetailsSection("application-cache-location",WI.UIString("Location"),[locationGroup]);this._onlineRow=new WI.DetailsSectionSimpleRow(WI.UIString("Online"));this._statusRow=new WI.DetailsSectionSimpleRow(WI.UIString("Status"));let statusGroup=new WI.DetailsSectionGroup([this._onlineRow,this._statusRow]);let statusSection=new WI.DetailsSection("application-cache-status",WI.UIString("Status"),[statusGroup]);this.contentView.element.appendChild(locationSection.element);this.contentView.element.appendChild(statusSection.element);WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.NetworkStateUpdated,this._networkStateUpdated,this);WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.FrameManifestStatusChanged,this._frameManifestStatusChanged,this);}
layout()
{super.layout();if(!this.applicationCacheFrame)
return;this._locationFrameURLRow.value=this.applicationCacheFrame.frame.url;this._locationManifestURLRow.value=this.applicationCacheFrame.manifest.manifestURL;this._refreshOnlineRow();this._refreshStatusRow();} 
_networkStateUpdated(event)
{if(!this.applicationCacheFrame)
return;this._refreshOnlineRow();}
_frameManifestStatusChanged(event)
{if(!this.applicationCacheFrame)
return;if(event.data.frameManifest!==this.applicationCacheFrame)
return;this._refreshStatusRow();}
_refreshOnlineRow()
{this._onlineRow.value=WI.applicationCacheManager.online?WI.UIString("Yes"):WI.UIString("No");}
_refreshStatusRow()
{this._statusRow.value=WI.ApplicationCacheDetailsSidebarPanel.Status[this.applicationCacheFrame.status];}};WI.ApplicationCacheDetailsSidebarPanel.Status={0:"Uncached",1:"Idle",2:"Checking",3:"Downloading",4:"UpdateReady",5:"Obsolete"};WI.ApplicationCacheFrameContentView=class ApplicationCacheFrameContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("application-cache-frame");this._frame=representedObject.frame;this._emptyView=WI.createMessageTextView(WI.UIString("No Application Cache information available"),false);this._emptyView.classList.add("hidden");this.element.appendChild(this._emptyView);}
attached()
{super.attached();WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.FrameManifestStatusChanged,this._handleFrameManifestStatusChanged,this);this.updateStatus(this.representedObject.status);}
detached()
{WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.FrameManifestStatusChanged,this._handleFrameManifestStatusChanged,this);super.detached();}
layout()
{super.layout();this.updateStatus();}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.ApplicationCache;cookie.frame=this.representedObject.frame.url;cookie.manifest=this.representedObject.manifest.manifestURL;}
get scrollableElements()
{if(!this._dataGrid)
return[];return[this._dataGrid.scrollContainer];}
_handleFrameManifestStatusChanged(event)
{var frameManifest=event.data.frameManifest;if(frameManifest!==this.representedObject)
return;this.updateStatus(frameManifest.status);}
updateStatus(status)
{var oldStatus=this._status;this._status=status;if(this._status===WI.ApplicationCacheManager.Status.Idle&&(oldStatus===WI.ApplicationCacheManager.Status.UpdateReady||!this._resources))
WI.applicationCacheManager.requestApplicationCache(this._frame,this._updateCallback.bind(this));}
_updateCallback(applicationCache)
{if(!applicationCache||!applicationCache.manifestURL){delete this._manifest;delete this._creationTime;delete this._updateTime;delete this._size;delete this._resources;this._emptyView.classList.remove("hidden");if(this._dataGrid)
this._dataGrid.element.classList.add("hidden");return;}
this._manifest=applicationCache.manifestURL;this._creationTime=applicationCache.creationTime;this._updateTime=applicationCache.updateTime;this._size=applicationCache.size;this._resources=applicationCache.resources;if(!this._dataGrid)
this._createDataGrid();this._populateDataGrid();this._dataGrid.autoSizeColumns(20,80);this._dataGrid.element.classList.remove("hidden");this._emptyView.classList.add("hidden");}
_createDataGrid()
{var columns={url:{},type:{},size:{}};columns.url.title=WI.UIString("Resource");columns.url.sortable=true;columns.type.title=WI.UIString("Type");columns.type.sortable=true;columns.size.title=WI.UIString("Size");columns.size.aligned="right";columns.size.sortable=true;this._dataGrid=new WI.DataGrid(columns);this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);this._dataGrid.sortColumnIdentifier="url";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("application-cache-frame-content-view");this.addSubview(this._dataGrid);this._dataGrid.updateLayout();}
_sortDataGrid()
{function numberCompare(columnIdentifier,nodeA,nodeB)
{return nodeA.data[columnIdentifier]-nodeB.data[columnIdentifier];}
function localeCompare(columnIdentifier,nodeA,nodeB)
{return(nodeA.data[columnIdentifier]+"").extendedLocaleCompare(nodeB.data[columnIdentifier]+"");}
var comparator;switch(this._dataGrid.sortColumnIdentifier){case"type":comparator=localeCompare.bind(this,"type");break;case"size":comparator=numberCompare.bind(this,"sizeNumber");break;case"url":default:comparator=localeCompare.bind(this,"url");break;}
this._dataGrid.sortNodes(comparator);}
_populateDataGrid()
{this._dataGrid.removeChildren();for(var resource of this._resources){var data={url:resource.url,type:resource.type,size:Number.bytesToString(resource.size),sizeNumber:resource.size,};var node=new WI.DataGridNode(data);this._dataGrid.appendChild(node);}}
_deleteButtonClicked(event)
{if(!this._dataGrid||!this._dataGrid.selectedNode)
return;this._deleteCallback(this._dataGrid.selectedNode);}
_deleteCallback(node)
{
}};WI.ApplicationCacheFrameTreeElement=class ApplicationCacheFrameTreeElement extends WI.GeneralTreeElement
{constructor(representedObject)
{const title=null;const subtitle=null;super("application-cache-frame",title,subtitle,representedObject);this.updateTitles();}
updateTitles()
{var url=this.representedObject.frame.url;var parsedURL=parseURL(url);this.mainTitle=WI.displayNameForURL(url,parsedURL);var subtitle=WI.displayNameForHost(parsedURL.host);var manifestTreeElement=null;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(currentAncestor instanceof WI.ApplicationCacheManifestTreeElement){manifestTreeElement=currentAncestor;break;}
currentAncestor=currentAncestor.parent;}
var subtitleIsDuplicate=subtitle===this._mainTitle||(manifestTreeElement&&manifestTreeElement.subtitle===subtitle);this.subtitle=subtitleIsDuplicate?null:subtitle;}};WI.ApplicationCacheManifestTreeElement=class ApplicationCacheManifestTreeElement extends WI.StorageTreeElement
{constructor(representedObject)
{super("application-cache-manifest","",representedObject);this.hasChildren=true;this.expanded=true;} 
get name()
{if(!this._name)
this._generateTitles();return this._name;}
get secondaryName()
{if(!this._secondaryName)
this._generateTitles();return this._secondaryName;}
get categoryName()
{return WI.UIString("Application Cache");}
_generateTitles()
{var parsedURL=parseURL(this.representedObject.manifestURL);this._name=WI.displayNameForURL(this.representedObject.manifestURL,parsedURL);var secondaryName=WI.displayNameForHost(parsedURL.host);this._secondaryName=this._name!==secondaryName?secondaryName:null;}};

WI.AreaChart=class AreaChart extends WI.View
{constructor()
{super();this.element.classList.add("area-chart");this._chartElement=this.element.appendChild(createSVGElement("svg"));this._chartElement.setAttribute("preserveAspectRatio","none");this._pathElement=this._chartElement.appendChild(createSVGElement("path"));this._circleElements=[];this._points=[];this._markers=[];this._size=null;} 
get size()
{return this._size;}
set size(size)
{if(this._size&&this._size.equals(size))
return;this._size=size;this._chartElement.setAttribute("viewBox",`0 0 ${size.width} ${size.height}`);this.needsLayout();}
addPoint(x,y)
{this._points.push({x,y});}
clearPoints()
{this._points=[];}
addPointMarker(x,y)
{this._markers.push({x,y});}
clearPointMarkers()
{this._markers=[];}
clear()
{this.clearPoints();this.clearPointMarkers();} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;if(!this._size)
return;let pathComponents=[];pathComponents.push(`M 0 ${this._size.height}`);for(let point of this._points)
pathComponents.push(`L ${point.x} ${point.y}`);let lastX=this._points.length?this._points.lastValue.x:0;pathComponents.push(`L ${lastX} ${this._size.height}`);pathComponents.push("Z");let pathString=pathComponents.join(" ");this._pathElement.setAttribute("d",pathString);if(this._circleElements.length){for(let circle of this._circleElements)
circle.remove();this._circleElements=[];}
if(this._markers.length){for(let{x,y}of this._markers){let circle=this._chartElement.appendChild(createSVGElement("circle"));this._circleElements.push(circle);circle.setAttribute("cx",x);circle.setAttribute("cy",y);}}}};WI.AuditNavigationSidebarPanel=class AuditNavigationSidebarPanel extends WI.NavigationSidebarPanel
{constructor()
{super("audit",WI.UIString("Audits"));} 
static _createNavigationItemTitle()
{return WI.UIString("Create","Create @ Audit Tab Navigation Sidebar","Title of button that creates a new audit.");} 
showDefaultContentView()
{let contentView=new WI.ContentView;if(WI.auditManager.editing){let contentPlaceholder=WI.createMessageTextView(WI.UIString("Editing audits"));contentView.element.appendChild(contentPlaceholder);let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";descriptionElement.textContent=WI.UIString("Select an audit in the navigation sidebar to edit it.");let createAuditNavigationItem=new WI.ButtonNavigationItem("create-audit",WI.AuditNavigationSidebarPanel._createNavigationItemTitle(),"Images/Plus15.svg",15,15);createAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;createAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCreateButtonNavigationItemClicked,this);let createAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to create a new audit."),createAuditNavigationItem);createAuditHelpElement.classList.add("create-audit");contentPlaceholder.appendChild(createAuditHelpElement);let stopEditingAuditsNavigationItem=new WI.ButtonNavigationItem("stop-editing-audits",WI.UIString("Done"));stopEditingAuditsNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleEditButtonNavigationItemClicked,this);let stopEditingAuditsHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to stop editing audits."),stopEditingAuditsNavigationItem);stopEditingAuditsHelpElement.classList.add("stop-editing-audits");contentPlaceholder.appendChild(stopEditingAuditsHelpElement);}else{let hasEnabledAudit=WI.auditManager.tests.length&&WI.auditManager.tests.some((test)=>!test.disabled&&test.supported);let contentPlaceholder=WI.createMessageTextView(WI.UIString("No audit selected"));contentView.element.appendChild(contentPlaceholder);if(hasEnabledAudit){let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";descriptionElement.textContent=WI.UIString("Select an audit in the navigation sidebar to view its results.");}
let importAuditNavigationItem=new WI.ButtonNavigationItem("import-audit",WI.UIString("Import"),"Images/Import.svg",15,15);importAuditNavigationItem.title=WI.UIString("Import audit or result");importAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);let importAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to import an audit or a result."),importAuditNavigationItem);importAuditHelpElement.classList.add("import-audit");contentPlaceholder.appendChild(importAuditHelpElement);let startEditingAuditsNavigationItem=new WI.ButtonNavigationItem("start-editing-audits",WI.UIString("Edit"));startEditingAuditsNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleEditButtonNavigationItemClicked,this);let startEditingAuditsHelpElement=WI.createNavigationItemHelp(hasEnabledAudit?WI.UIString("Press %s to start editing audits."):WI.UIString("Press %s to enable audits."),startEditingAuditsNavigationItem);startEditingAuditsHelpElement.classList.add("start-editing-audits");contentPlaceholder.appendChild(startEditingAuditsHelpElement);}
let versionContainer=contentView.element.appendChild(document.createElement("div"));versionContainer.classList.add("audit-version");let version=WI.AuditTestBase.Version;if(InspectorBackend.hasDomain("Audit"))
version=Math.min(version,InspectorBackend.getVersion("Audit"));versionContainer.textContent=WI.UIString("Audit version: %s").format(version);versionContainer.appendChild(WI.createReferencePageLink("audit-tab"));this.contentBrowser.showContentView(contentView);} 
willDismissPopover(popover)
{let audit=popover.audit;if(!audit){InspectorFrontendHost.beep();return;}
WI.auditManager.addTest(audit,{save:true});WI.showRepresentedObject(audit);} 
initialLayout()
{super.initialLayout();this.contentTreeOutline.allowsRepeatSelection=false;let controlsNavigationBar=new WI.NavigationBar;this._startStopButtonNavigationItem=new WI.ToggleButtonNavigationItem("start-stop-audit",WI.UIString("Start"),WI.UIString("Stop"),"Images/AuditStart.svg","Images/AuditStop.svg",13,13);this._startStopButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._startStopButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleStartStopButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(this._startStopButtonNavigationItem);this._createButtonNavigationItem=new WI.ButtonNavigationItem("create-audit",WI.AuditNavigationSidebarPanel._createNavigationItemTitle(),"Images/Plus15.svg",15,15);this._createButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._createButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCreateButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(this._createButtonNavigationItem);controlsNavigationBar.addNavigationItem(new WI.DividerNavigationItem);let importButtonNavigationItem=new WI.ButtonNavigationItem("import-audit",WI.UIString("Import"),"Images/Import.svg",15,15);importButtonNavigationItem.title=WI.UIString("Import audit or result");importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(importButtonNavigationItem);this.addSubview(controlsNavigationBar);this._editButtonNavigationItem=new WI.ActivateButtonNavigationItem("edit-audits",WI.UIString("Edit"),WI.UIString("Done"));this._editButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleEditButtonNavigationItemClicked,this);this.filterBar.addFilterNavigationItem(this._editButtonNavigationItem);for(let test of WI.auditManager.tests)
this._addTest(test);WI.auditManager.results.forEach((result,i)=>{this._addResult(result,i);});this._updateControlNavigationItems();this._updateEditNavigationItems();this._updateNoAuditsPlaceholder();WI.AuditTestGroup.addEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleAuditManagerEditingChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.RunningStateChanged,this._handleAuditManagerRunningStateChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestAdded,this._handleAuditTestAdded,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditTestCompleted,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditTestScheduled,this);this.contentTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);}
closed()
{super.closed();if(this.didInitialLayout){WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleAuditManagerEditingChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.RunningStateChanged,this._handleAuditManagerRunningStateChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestAdded,this._handleAuditTestAdded,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditTestCompleted,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditTestScheduled,this);}}
updateFilter()
{super.updateFilter();if(!this.hasActiveFilters)
this._updateNoAuditsPlaceholder();}
hasCustomFilters()
{return true;}
matchTreeElementAgainstCustomFilters(treeElement,flags)
{if(WI.auditManager.editing){if(treeElement.representedObject instanceof WI.AuditTestResultBase||treeElement.hasAncestor(this._resultsFolderTreeElement)||treeElement===this._resultsFolderTreeElement)
return false;}else{if(treeElement.representedObject instanceof WI.AuditTestBase&&(treeElement.representedObject.disabled||!treeElement.representedObject.supported))
return false;}
return super.matchTreeElementAgainstCustomFilters(treeElement,flags);} 
_addTest(test)
{let treeElement=new WI.AuditTreeElement(test);if(this._resultsFolderTreeElement){this.contentTreeOutline.insertChild(treeElement,this.contentTreeOutline.children.indexOf(this._resultsFolderTreeElement));this._resultsFolderTreeElement.hidden=!this._resultsFolderTreeElement.children.length||WI.auditManager.editing;}else
this.contentTreeOutline.appendChild(treeElement);}
_addResult(result,index)
{this.element.classList.add("has-results");if(!this._resultsFolderTreeElement){this._resultsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Results"));this.contentTreeOutline.appendChild(this._resultsFolderTreeElement);}
this._resultsFolderTreeElement.expand();let resultFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Run %d").format(index+1));if(result instanceof WI.AuditTestResultBase){resultFolderTreeElement.subtitle=WI.UIString("Imported");result=[result];}
this._resultsFolderTreeElement.appendChild(resultFolderTreeElement);for(let resultItem of result)
resultFolderTreeElement.appendChild(new WI.AuditTreeElement(resultItem));}
_updateControlNavigationItems()
{this._startStopButtonNavigationItem.toggled=WI.auditManager.runningState===WI.AuditManager.RunningState.Active||WI.auditManager.runningState===WI.AuditManager.RunningState.Stopping;this._startStopButtonNavigationItem.enabled=WI.auditManager.tests.some((test)=>!test.disabled&&test.supported)&&(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive||WI.auditManager.runningState===WI.AuditManager.RunningState.Active);this._startStopButtonNavigationItem.hidden=WI.auditManager.editing;this._createButtonNavigationItem.hidden=!WI.auditManager.editing;}
_updateEditNavigationItems()
{this._editButtonNavigationItem.label=WI.auditManager.editing?this._editButtonNavigationItem.activatedToolTip:this._editButtonNavigationItem.defaultToolTip;this._editButtonNavigationItem.activated=WI.auditManager.editing;this._editButtonNavigationItem.enabled=WI.auditManager.editing||WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive;}
_updateNoAuditsPlaceholder()
{if(WI.auditManager.editing||WI.auditManager.tests.some((test)=>!test.disabled&&test.supported)){if(!this.hasActiveFilters)
this.hideEmptyContentPlaceholder();return;}
let contentPlaceholder=this.showEmptyContentPlaceholder(WI.UIString("No Enabled Audits"));contentPlaceholder.classList.add("no-enabled-audits");if(WI.auditManager.results.length){
this.contentView.element.insertBefore(contentPlaceholder,this.contentView.element.firstChild);}}
_handleAuditManagerEditingChanged(event)
{let previousSelectedTreeElement=this.contentTreeOutline.selectedTreeElement;if(previousSelectedTreeElement){if(WI.auditManager.editing){if(!(previousSelectedTreeElement.representedObject instanceof WI.AuditTestBase))
previousSelectedTreeElement.deselect();}else{if(previousSelectedTreeElement.representedObject.disabled||!previousSelectedTreeElement.representedObject.supported)
previousSelectedTreeElement.deselect();}}
this.updateFilter();if(!this.contentTreeOutline.selectedTreeElement)
this.showDefaultContentView();this._updateControlNavigationItems();this._updateEditNavigationItems();this._updateNoAuditsPlaceholder();}
_handleAuditManagerRunningStateChanged(event)
{this._updateControlNavigationItems();this._updateEditNavigationItems();}
_handleAuditTestAdded(event)
{let{test}=event.data;this._addTest(test);this._updateControlNavigationItems();this._updateNoAuditsPlaceholder();}
_handleAuditTestCompleted(event)
{let{result,index}=event.data;this._addResult(result,index);this._updateControlNavigationItems();this._updateEditNavigationItems();}
_handleAuditTestRemoved(event)
{let{test}=event.data;let treeElement=this.treeElementForRepresentedObject(test);treeElement.parent.removeChild(treeElement);this._updateControlNavigationItems();}
_handleAuditTestScheduled(event)
{this._updateControlNavigationItems();this._updateEditNavigationItems();}
_treeSelectionDidChange(event)
{if(!this.selected)
return;let treeElement=this.contentTreeOutline.selectedTreeElement;if(!treeElement||treeElement instanceof WI.FolderTreeElement){this.showDefaultContentView();return;}
let representedObject=treeElement.representedObject;if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult){WI.showRepresentedObject(representedObject);return;}
console.error("Unknown tree element",treeElement);}
_handleStartStopButtonNavigationItemClicked(event)
{if(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive)
WI.auditManager.start();else if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active)
WI.auditManager.stop();}
_handleCreateButtonNavigationItemClicked(event)
{let popover=new WI.CreateAuditPopover(this);popover.show(event.target.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X,WI.RectEdge.MIN_X]);}
_handleImportButtonNavigationItemClicked(event)
{WI.FileUtilities.importJSON((result)=>WI.auditManager.processJSON(result),{multiple:true});}
_handleEditButtonNavigationItemClicked(event)
{WI.auditManager.editing=!WI.auditManager.editing;}};WI.AuditTestCaseContentView=class AuditTestCaseContentView extends WI.AuditTestContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("audit-test-case");this._resultDataGeneralContainer=null;this._resultDataDOMNodesContainer=null;this._resultDataErrorsContainer=null;} 
initialLayout()
{super.initialLayout();let informationContainer=this.headerView.element.appendChild(document.createElement("div"));informationContainer.classList.add("information");let nameContainer=informationContainer.appendChild(document.createElement("h1"));this._resultImageElement=nameContainer.appendChild(document.createElement("img"));nameContainer.appendChild(this.createNameElement("span"));informationContainer.appendChild(this.createDescriptionElement("p"));if(this.representedObject instanceof WI.AuditTestCase)
informationContainer.appendChild(this.createControlsTableElement());this._metadataElement=this.headerView.element.appendChild(document.createElement("div"));this._metadataElement.classList.add("metadata");}
layout()
{if(this.layoutReason!==WI.View.LayoutReason.Dirty)
return;super.layout();this._metadataElement.removeChildren();this.contentView.element.removeChildren();if(WI.auditManager.editing){this._resultImageElement.src="Images/Pencil.svg";this._resultImageElement.title=WI.UIString("Editing audit","Editing Audit @ Audit Tab - Test Case","Title of icon indiciating that the selected audit is being edited.");let testEditorElement=this.contentView.element.appendChild(document.createElement("div"));testEditorElement.className="editor";setTimeout(()=>{this._testCodeMirror=WI.CodeMirrorEditor.create(testEditorElement,{autoCloseBrackets:true,lineNumbers:true,lineWrapping:true,matchBrackets:true,mode:"text/javascript",readOnly:this.representedObject.editable?false:"nocursor",styleSelectedText:true,value:this.representedObject.test,});});return;}
this._resultImageElement.src="Images/AuditTestNoResult.svg";this._resultImageElement.title=WI.UIString("Not yet run","Not yet run @ Audit Tab - Test Case","Title of icon indicating that the selected audit has not been run yet.");let result=this.representedObject.result;if(!result){if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive)
this.showNoResultPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Active)
this.showRunningPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Stopping)
this.showStoppingPlaceholder();return;}
if(result.didError){this._resultImageElement.src="Images/AuditTestError.svg";this._resultImageElement.title=WI.UIString("Error","Error @ Audit Tab - Test Case","Title of icon indicating that the selected audit threw an error.");}else if(result.didFail){this._resultImageElement.src="Images/AuditTestFail.svg";this._resultImageElement.title=WI.UIString("Fail","Fail @ Audit Tab - Test Case","Title of icon indicating that the selected audit failed.");}else if(result.didWarn){this._resultImageElement.src="Images/AuditTestWarn.svg";this._resultImageElement.title=WI.UIString("Warn","Warn @ Audit Tab - Test Case","Title of icon indicating that the selected audit passed with issues (i.e. warnings).");}else if(result.didPass){this._resultImageElement.src="Images/AuditTestPass.svg";this._resultImageElement.title=WI.UIString("Pass","Pass @ Audit Tab - Test Case","Title of icon indicating that the selected audit passed with no issues.");}else if(result.unsupported){this._resultImageElement.src="Images/AuditTestUnsupported.svg";this._resultImageElement.title=WI.UIString("Unsupported","Unsupported @ Audit Tab - Test Case","Title of icon indicating that the selected audit is not able to be run (i.e. unsupported).");}
let metadata=result.metadata;if(metadata){let sourceContainer=this._metadataElement.appendChild(document.createElement("div"));sourceContainer.classList.add("source");if(metadata.startTimestamp){let timeElement=sourceContainer.appendChild(document.createElement("time"));timeElement.datetime=metadata.startTimestamp.toISOString();timeElement.textContent=metadata.startTimestamp.toLocaleString();if(metadata.endTimestamp){let totalDuration=Number.secondsToString((metadata.endTimestamp-metadata.startTimestamp)/1000);let durationElement=this._metadataElement.appendChild(document.createElement("span"));durationElement.classList.add("duration");durationElement.textContent=totalDuration;if(metadata.asyncTimestamp){let evalDuration=Number.secondsToString((metadata.asyncTimestamp-metadata.startTimestamp)/1000);let asyncDuration=Number.secondsToString((metadata.endTimestamp-metadata.asyncTimestamp)/1000);durationElement.classList.add("async");durationElement.title=WI.UIString("%s eval\n%s async").format(evalDuration,asyncDuration);}}}
if(metadata.url&&(metadata.url!==WI.networkManager.mainFrame.url||this.representedObject instanceof WI.AuditTestResultBase)){let url=new URL(metadata.url);let origin=url.origin;if(url.pathname.startsWith("/"))
origin+="/";let linkElement=WI.linkifyURLAsNode(url.href,origin+url.href.substring(origin.length).truncateStart(20));linkElement.title=url.href;sourceContainer.appendChild(linkElement);}}
let resultData=result.data;if(!this._resultDataGeneralContainer){let nonSpecialData=Object.filter(resultData,(key)=>key!=="domNodes"&&key!=="errors");if(!isEmptyObject(nonSpecialData)){this._resultDataGeneralContainer=document.createElement("div");let expression="("+JSON.stringify(nonSpecialData)+")";const options={objectGroup:WI.AuditTestBase.ObjectGroup,doNotPauseOnExceptionsAndMuteConsole:true,};WI.runtimeManager.evaluateInInspectedWindow(expression,options,(nonSpecialDataRemoteObject,wasThrown)=>{if(!nonSpecialDataRemoteObject)
return;if(!this.representedObject.result||this.representedObject.result.data!==resultData)
return;const propertyPath=null;const forceExpanding=true;let element=WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(nonSpecialDataRemoteObject,propertyPath,forceExpanding);let objectTree=element.__objectTree;if(objectTree){objectTree.showOnlyJSON();objectTree.expand();}
this._resultDataGeneralContainer.appendChild(element);this.hidePlaceholder();});}}
if(this._resultDataGeneralContainer)
this.contentView.element.appendChild(this._resultDataGeneralContainer);if(!this._resultDataDOMNodesContainer&&resultData.domNodes&&resultData.domNodes.length){this._resultDataDOMNodesContainer=document.createElement("div");this._resultDataDOMNodesContainer.classList.add("dom-nodes");let domNodeText=this._resultDataDOMNodesContainer.appendChild(document.createElement("h1"));domNodeText.textContent=WI.UIString("DOM Nodes:");let tableContainer=this._resultDataDOMNodesContainer.appendChild(document.createElement("table"));resultData.domNodes.forEach((domNode,index)=>{domNode=result.resolvedDOMNodes[index]||domNode;let rowElement=tableContainer.appendChild(document.createElement("tr"));let indexElement=rowElement.appendChild(document.createElement("td"));indexElement.textContent=index+1;let dataElement=rowElement.appendChild(document.createElement("td"));if(domNode instanceof WI.DOMNode){let treeOutline=new WI.DOMTreeOutline({selectable:false});treeOutline.setVisible(true);treeOutline.rootDOMNode=domNode;let rootTreeElement=treeOutline.children[0];rootTreeElement.showGoToArrow=true;if(!rootTreeElement.hasChildren)
treeOutline.element.classList.add("single-node");if(resultData.domAttributes){for(let domAttribute of resultData.domAttributes){rootTreeElement.highlightAttribute(domAttribute);rootTreeElement.updateTitle();}}
dataElement.appendChild(treeOutline.element);}else if(typeof domNode==="string"){let codeMirror=WI.CodeMirrorEditor.create(dataElement.appendChild(document.createElement("code")),{mode:"css",readOnly:true,lineWrapping:true,styleSelectedText:true,});codeMirror.setValue(domNode);if(resultData.domAttributes){for(let domAttribute of resultData.domAttributes){let regex=null;if(domAttribute==="id")
regex=/(\#[^\#|\.|\[|\s|$]+)/g;else if(domAttribute==="class")
regex=/(\.[^\#|\.|\[|\s|$]+)/g;else
regex=new RegExp(`\\[\\s*(${domAttribute})\\s*=`,"g");while(true){let match=regex.exec(domNode);if(!match)
break;let start=match.index+match[0].indexOf(match[1]);codeMirror.markText({line:0,ch:start},{line:0,ch:start+match[1].length},{className:"mark"});}}}
setTimeout(()=>{codeMirror.refresh();});}});}
if(this._resultDataDOMNodesContainer)
this.contentView.element.appendChild(this._resultDataDOMNodesContainer);if(!this._resultDataErrorsContainer&&resultData.errors&&resultData.errors.length){this._resultDataErrorsContainer=document.createElement("div");this._resultDataErrorsContainer.classList.add("errors");let errorText=this._resultDataErrorsContainer.appendChild(document.createElement("h1"));errorText.textContent=WI.UIString("Errors:");let tableContainer=this._resultDataErrorsContainer.appendChild(document.createElement("table"));resultData.errors.forEach((error,index)=>{let rowElement=tableContainer.appendChild(document.createElement("tr"));let indexElement=rowElement.appendChild(document.createElement("td"));indexElement.textContent=index+1;let dataElement=rowElement.appendChild(document.createElement("td"));let errorElement=dataElement.appendChild(document.createElement("div"));errorElement.classList.add("error");errorElement.textContent=error;});}
if(this._resultDataErrorsContainer)
this.contentView.element.appendChild(this._resultDataErrorsContainer);if(!this.contentView.element.children.length)
this.showNoResultDataPlaceholder();}
handleResultChanged(event)
{super.handleResultChanged(event);this._resultDataGeneralContainer=null;this._resultDataDOMNodesContainer=null;this._resultDataErrorsContainer=null;}
saveEditedData()
{super.saveEditedData();this.representedObject.test=this._testCodeMirror.getValue().trim();}
showRunningPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderRunning){this.placeholderElement=WI.createMessageTextView(WI.UIString("Running the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderRunning=true;let spinner=new WI.IndeterminateProgressSpinner;this.placeholderElement.appendChild(spinner.element);let stopAuditNavigationItem=new WI.ButtonNavigationItem("stop-audit",WI.UIString("Stop"),"Images/AuditStop.svg",13,13);stopAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;stopAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.stop();},stopAuditNavigationItem);let stopAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to stop running."),stopAuditNavigationItem);this.placeholderElement.appendChild(stopAuditHelpElement);this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
super.showRunningPlaceholder();}};WI.AuditTestGroupContentView=class AuditTestGroupContentView extends WI.AuditTestContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("audit-test-group");this._levelScopeBar=null;this._viewForSubobject=new Map;} 
willDismissPopover(popover)
{let audit=popover.audit;if(!audit){InspectorFrontendHost.beep();return;}
this.representedObject.addTest(audit);} 
createControlsTableElement()
{let controlsTableElement=super.createControlsTableElement();let actionsRowElement=controlsTableElement.appendChild(document.createElement("tr"));actionsRowElement.className="actions";let actionsHeaderElement=controlsTableElement.appendChild(document.createElement("th"));let actionsDataElement=controlsTableElement.appendChild(document.createElement("td"));let addTestCaseButtonElement=actionsDataElement.appendChild(document.createElement("button"));addTestCaseButtonElement.disabled=!this.representedObject.editable;addTestCaseButtonElement.textContent=WI.UIString("Add Test Case","Add Test Case @ Audit Tab - Group","Text of button to add a new audit test case to the currently shown audit group.");addTestCaseButtonElement.addEventListener("click",(event)=>{let popover=new WI.CreateAuditPopover(this);popover.show(addTestCaseButtonElement,[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X,WI.RectEdge.MIN_X]);});return controlsTableElement;}
initialLayout()
{super.initialLayout();let informationContainer=this.headerView.element.appendChild(document.createElement("div"));informationContainer.classList.add("information");let nameContainer=informationContainer.appendChild(document.createElement("h1"));nameContainer.appendChild(this.createNameElement("span"));informationContainer.appendChild(this.createDescriptionElement("p"));if(this.representedObject instanceof WI.AuditTestGroup)
informationContainer.appendChild(this.createControlsTableElement());this._levelNavigationBar=new WI.NavigationBar(document.createElement("nav"));this.headerView.addSubview(this._levelNavigationBar);this._percentageContainer=this.headerView.element.appendChild(document.createElement("div"));this._percentageContainer.classList.add("percentage-pass");this._percentageContainer.hidden=true;this._percentageTextElement=document.createElement("span");const format=WI.UIString("%s%%","Percentage (of audits)","The number of tests that passed expressed as a percentage, followed by a literal %.");String.format(format,[this._percentageTextElement],String.standardFormatters,this._percentageContainer,(a,b)=>{a.append(b);return a;});this._updateClassList();}
layout()
{if(this.layoutReason!==WI.View.LayoutReason.Dirty)
return;super.layout();if(WI.auditManager.editing){if(this._levelScopeBar){this._levelNavigationBar.removeNavigationItem(this._levelScopeBar);this._levelScopeBar=null;}
this._percentageContainer.hidden=true;this.resetFilter();return;}
let result=this.representedObject.result;if(!result){if(this._levelScopeBar){this._levelNavigationBar.removeNavigationItem(this._levelScopeBar);this._levelScopeBar=null;}
this._percentageContainer.hidden=true;this._percentageTextElement.textContent="";if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive)
this.showNoResultPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Active)
this.showRunningPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Stopping)
this.showStoppingPlaceholder();return;}
let levelCounts=result.levelCounts;let totalCount=Object.values(levelCounts).reduce((accumulator,current)=>accumulator+current);this._percentageTextElement.textContent=Math.floor(100*levelCounts[WI.AuditTestCaseResult.Level.Pass]/totalCount);this._percentageContainer.hidden=false;if(!this._levelScopeBar){let scopeBarItems=[];let addScopeBarItem=(level,labelSingular,labelPlural)=>{let count=levelCounts[level];if(isNaN(count)||count<=0)
return;let label=(labelPlural&&count!==1)?labelPlural:labelSingular;let scopeBarItem=new WI.ScopeBarItem(level,label.format(count),{className:level,exclusive:false,independent:true,});scopeBarItem.selected=true;scopeBarItem.element.insertBefore(document.createElement("img"),scopeBarItem.element.firstChild);scopeBarItems.push(scopeBarItem);};addScopeBarItem(WI.AuditTestCaseResult.Level.Pass,WI.UIString("%d Passed","%d Passed (singular)",""),WI.UIString("%d Passed","%d Passed (plural)",""));addScopeBarItem(WI.AuditTestCaseResult.Level.Warn,WI.UIString("%d Warning"),WI.UIString("%d Warnings"));addScopeBarItem(WI.AuditTestCaseResult.Level.Fail,WI.UIString("%d Failed","%d Failed (singular)",""),WI.UIString("%d Failed","%d Failed (plural)",""));addScopeBarItem(WI.AuditTestCaseResult.Level.Error,WI.UIString("%d Error"),WI.UIString("%d Errors"));addScopeBarItem(WI.AuditTestCaseResult.Level.Unsupported,WI.UIString("%d Unsupported","%d Unsupported (singular)",""),WI.UIString("%d Unsupported","%d Unsupported (plural)",""));this._levelScopeBar=new WI.ScopeBar(null,scopeBarItems);this._levelScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleLevelScopeBarSelectionChanged,this);this._levelNavigationBar.addNavigationItem(this._levelScopeBar);}
if(this.applyFilter())
this.hidePlaceholder();else
this.showFilteredPlaceholder();}
attached()
{super.attached();if(this.representedObject instanceof WI.AuditTestGroup){this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleTestGroupTestRemoved,this);}}
for(let subobject of this._subobjects())
this._addTest(subobject);}
detached()
{if(this.representedObject instanceof WI.AuditTestGroup){this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleTestGroupTestRemoved,this);}}
this.contentView.removeAllSubviews();this._viewForSubobject.clear();super.detached();}
applyFilter(levels)
{if(this._levelScopeBar&&!levels)
levels=this._levelScopeBar.selectedItems.map((item)=>item.id);this._updateLevelScopeBar(levels);return super.applyFilter(levels);}
resetFilter()
{this._updateLevelScopeBar(Object.values(WI.AuditTestCaseResult.Level));super.resetFilter();}
showRunningPlaceholder()
{if(!this.placeholderElement||!this.placeholderElement.__placeholderRunning){this.placeholderElement=WI.createMessageTextView(WI.UIString("Running the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderRunning=true;this.placeholderElement.__progress=document.createElement("progress");this.placeholderElement.__progress.value=0;this.placeholderElement.appendChild(this.placeholderElement.__progress);let stopAuditNavigationItem=new WI.ButtonNavigationItem("stop-audit",WI.UIString("Stop"),"Images/AuditStop.svg",13,13);stopAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;stopAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.stop();},stopAuditNavigationItem);let stopAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to stop running."),stopAuditNavigationItem);this.placeholderElement.appendChild(stopAuditHelpElement);this.placeholderElement.appendChild(WI.createReferencePageLink("audit-tab"));}
super.showRunningPlaceholder();} 
_subobjects()
{if(this.representedObject instanceof WI.AuditTestGroup)
return this.representedObject.tests;if(this.representedObject instanceof WI.AuditTestGroupResult)
return this.representedObject.results;console.error("Unknown representedObject",this.representedObject);return[];}
_updateClassList()
{let subobjects=this._subobjects();let containsTestGroup=subobjects.some((test)=>test instanceof WI.AuditTestGroup||test instanceof WI.AuditTestGroupResult);this.element.classList.toggle("contains-test-group",containsTestGroup);this.element.classList.toggle("contains-test-case",!containsTestGroup&&subobjects.some((test)=>test instanceof WI.AuditTestCase||test instanceof WI.AuditTestCaseResult));}
_updateLevelScopeBar(levels)
{if(!this._levelScopeBar)
return;for(let item of this._levelScopeBar.items)
item.selected=levels.includes(item.id);for(let view of this._viewForSubobject.values()){if(view instanceof WI.AuditTestGroupContentView)
view._updateLevelScopeBar(levels);}}
_addTest(test)
{let view=WI.ContentView.contentViewForRepresentedObject(test);this.contentView.addSubview(view);this._viewForSubobject.set(test,view);}
_handleTestGroupProgress(event)
{let{index,count}=event.data;if(this.placeholderElement&&this.placeholderElement.__progress)
this.placeholderElement.__progress.value=(index+1)/count;}
_handleTestGroupScheduled(event)
{if(this.placeholderElement&&this.placeholderElement.__progress)
this.placeholderElement.__progress.value=0;}
_handleTestGroupTestAdded(event)
{let{test}=event.data;this._addTest(test);this._updateClassList();}
_handleTestGroupTestRemoved(event)
{let{test}=event.data;let view=this._viewForSubobject.get(test);this.contentView.removeSubview(view);this._updateClassList();}
_handleLevelScopeBarSelectionChanged(event)
{this.needsLayout();}};WI.AuditTreeElement=class AuditTreeElement extends WI.GeneralTreeElement
{constructor(representedObject)
{let isTestCase=representedObject instanceof WI.AuditTestCase;let isTestGroup=representedObject instanceof WI.AuditTestGroup;let isTestCaseResult=representedObject instanceof WI.AuditTestCaseResult;let isTestGroupResult=representedObject instanceof WI.AuditTestGroupResult;let classNames=["audit"];if(isTestCase)
classNames.push("test-case");else if(isTestGroup)
classNames.push("test-group");else if(isTestCaseResult)
classNames.push("test-case-result");else if(isTestGroupResult)
classNames.push("test-group-result");let options={hasChildren:isTestGroup||isTestGroupResult,};const subtitle=null;super(classNames,representedObject.name,subtitle,representedObject,options);if(isTestGroup)
this._expandedSetting=new WI.Setting(WI.AuditTreeElement.expandedSettingKey(this.representedObject.name),false);} 
static expandedSettingKey(name)
{return`audit-tree-element-${name}-expanded`;} 
onattach()
{super.onattach();if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.ResultChanged,this._handleTestResultChanged,this);if(this.representedObject instanceof WI.AuditTestCase)
this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestCaseScheduled,this);else if(this.representedObject instanceof WI.AuditTestGroup)
this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.addEventListener(WI.AuditTestBase.Event.NameChanged,this._handleTestNameChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);if(this.representedObject instanceof WI.AuditTestGroup)
this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);}
WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleManagerEditingChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);}
if(this.representedObject.supported&&this._expandedSetting&&this._expandedSetting.value)
this.expand();this._updateStatus();}
ondetach()
{if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.ResultChanged,this._handleTestResultChanged,this);if(this.representedObject instanceof WI.AuditTestCase)
this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestCaseScheduled,this);else if(this.representedObject instanceof WI.AuditTestGroup)
this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.removeEventListener(WI.AuditTestBase.Event.NameChanged,this._handleTestNameChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);if(this.representedObject instanceof WI.AuditTestGroup)
this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);}
WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleManagerEditingChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);}
super.ondetach();}
onpopulate()
{super.onpopulate();if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();if(this.representedObject instanceof WI.AuditTestGroup){for(let test of this.representedObject.tests)
this.appendChild(new WI.AuditTreeElement(test));}else if(this.representedObject instanceof WI.AuditTestGroupResult){for(let result of this.representedObject.results)
this.appendChild(new WI.AuditTreeElement(result));}}
onexpand()
{if(this._expandedSetting)
this._expandedSetting.value=this.expanded;}
oncollapse()
{if(this._expandedSetting)
this._expandedSetting.value=this.expanded;}
ondelete()
{if(!(this.representedObject instanceof WI.AuditTestBase))
return false;if(!WI.auditManager.editing)
return false;this.representedObject.remove();return true;}
canSelectOnMouseDown(event)
{if(this.representedObject instanceof WI.AuditTestBase&&this.representedObject.supported&&this.status.contains(event.target))
return false;return super.canSelectOnMouseDown(event);}
populateContextMenu(contextMenu,event)
{let isTest=this.representedObject instanceof WI.AuditTestBase;contextMenu.appendSeparator();if(WI.auditManager.editing){if(isTest){if(this.representedObject.supported){contextMenu.appendItem(this.representedObject.disabled?WI.UIString("Enable Audit"):WI.UIString("Disable Audit"),()=>{this.representedObject.disabled=!this.representedObject.disabled;});}
contextMenu.appendItem(WI.UIString("Duplicate Audit"),async()=>{let audit=await this.representedObject.clone();WI.auditManager.addTest(audit,{save:true});});if(this.representedObject.editable){contextMenu.appendItem(WI.UIString("Delete Audit"),()=>{this.representedObject.remove();});}}}else{if(isTest){contextMenu.appendItem(WI.UIString("Start Audit"),()=>{this._start();},WI.auditManager.runningState!==WI.AuditManager.RunningState.Inactive);contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Export Audit"),()=>{WI.auditManager.export(this.representedObject);});}
contextMenu.appendItem(WI.UIString("Export Result"),()=>{WI.auditManager.export(this.representedObject.result);},!this.representedObject.result);if(isTest&&this.representedObject.editable){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Edit Audit"),()=>{WI.auditManager.editing=true;WI.showRepresentedObject(this.representedObject);});}}
contextMenu.appendSeparator();super.populateContextMenu(contextMenu,event);} 
_start()
{if(WI.auditManager.runningState!==WI.AuditManager.RunningState.Inactive)
return;WI.auditManager.start([this.representedObject]);}
_updateStatus()
{if(this.representedObject instanceof WI.AuditTestBase&&!this.representedObject.supported){this.status=document.createElement("img");this.status.title=WI.UIString("This audit is not supported");this.addClassName("unsupported");return;}
if(WI.auditManager.editing){this.status=document.createElement("input");this.status.type="checkbox";this._updateTestGroupDisabled();this.status.addEventListener("change",()=>{this.representedObject.disabled=!this.representedObject.disabled;});this.addClassName("editing-audits");return;}
let className="";let result=this.representedObject.result;if(result){if(result.didError)
className=WI.AuditTestCaseResult.Level.Error;else if(result.didFail)
className=WI.AuditTestCaseResult.Level.Fail;else if(result.didWarn)
className=WI.AuditTestCaseResult.Level.Warn;else if(result.didPass)
className=WI.AuditTestCaseResult.Level.Pass;else if(result.unsupported)
className=WI.AuditTestCaseResult.Level.Unsupported;}
this.status=document.createElement("img");if(this.representedObject instanceof WI.AuditTestBase){this.status.title=WI.UIString("Start");this.status.addEventListener("click",this._handleStatusClick.bind(this));if(!className)
className="show-on-hover";}
this.status.classList.add(className);this.removeClassName("editing-audits");}
_showRunningSpinner()
{if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive){this._updateStatus();return;}
if(!this.status||!this.status.__spinner){let spinner=new WI.IndeterminateProgressSpinner;this.status=spinner.element;this.status.__spinner=true;}}
_showRunningProgress(progress)
{if(!this.representedObject.runningState===WI.AuditManager.RunningState.Inactive){this._updateStatus();return;}
if(!this.status||!this.status.__progress){this.status=document.createElement("progress");this.status.__progress=true;}
this.status.value=progress||0;}
_updateTestGroupDisabled()
{this.status.checked=!this.representedObject.disabled;if(this.representedObject instanceof WI.AuditTestGroup){let firstSupportedTest=this.representedObject.tests.find((test)=>test.supported);this.status.indeterminate=this.representedObject.tests.some((test)=>test.supported&&test.disabled!==firstSupportedTest.disabled);}}
_handleTestCaseCompleted(event)
{this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCaseCompleted,this);this._updateStatus();}
_handleTestDisabledChanged(event)
{if(this.status instanceof HTMLInputElement&&this.status.type==="checkbox")
this._updateTestGroupDisabled();}
_handleTestResultChanged(event)
{this._updateStatus();}
_handleTestCaseScheduled(event)
{this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCaseCompleted,this);this._showRunningSpinner();}
_handleTestGroupCompleted(event)
{this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestGroupCompleted,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this._updateStatus();}
_handleTestGroupProgress(event)
{let{index,count}=event.data;this._showRunningProgress((index+1)/count);}
_handleTestGroupScheduled(event)
{this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestGroupCompleted,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this._showRunningProgress();}
_handleTestNameChanged(event)
{this.mainTitle=this.representedObject.name;if(this.representedObject instanceof WI.AuditTestGroup)
this._expandedSetting=new WI.Setting(WI.AuditTreeElement.expandedSettingKey(this.representedObject.name),!!WI.Setting.migrateValue(WI.AuditTreeElement.expandedSettingKey(event.data.oldName)));}
_handleTestSupportedChanged(event)
{this._updateStatus();}
_handleTestGroupTestAdded(event)
{let{test}=event.data;this.appendChild(new WI.AuditTreeElement(test));}
_handleManagerEditingChanged(event)
{this._updateStatus();}
_handleAuditManagerTestScheduled(event)
{this.addClassName("manager-active");}
_handleAuditManagerTestCompleted(event)
{this.removeClassName("manager-active");}
_handleStatusClick(event)
{this._start();}};WI.BannerView=class BannerView extends WI.View
{constructor(message,{actionButtonMessage,showDismissButton}={})
{super();this.element.classList.add("banner-view");this.element.appendChild(document.createTextNode(message));if(actionButtonMessage){let actionButtonElement=this.element.appendChild(document.createElement("button"));actionButtonElement.textContent=actionButtonMessage;actionButtonElement.addEventListener("click",this._handleActionButtonClicked.bind(this));}
if(showDismissButton){let dismissButtonElement=this.element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Close.svg","dismiss",WI.UIString("Dismiss","Dismiss @ Banner View","Tooltip for the dismiss button in banner views.")));dismissButtonElement.addEventListener("click",this._handleDismissButtonClicked.bind(this));}} 
_handleActionButtonClicked(event)
{this.dispatchEventToListeners(WI.BannerView.Event.ActionButtonClicked);}
_handleDismissButtonClicked(event)
{this.dispatchEventToListeners(WI.BannerView.Event.DismissButtonClicked);}};WI.BannerView.Event={ActionButtonClicked:"banner-view-action-button-clicked",DismissButtonClicked:"banner-view-dismiss-button-clicked",};WI.BezierEditor=class BezierEditor extends WI.Object
{constructor()
{super();this._element=document.createElement("div");this._element.classList.add("bezier-editor");this._element.dir="ltr";var editorWidth=184;var editorHeight=200;this._padding=25;this._controlHandleRadius=7;this._bezierWidth=editorWidth-(this._controlHandleRadius*2);this._bezierHeight=editorHeight-(this._controlHandleRadius*2)-(this._padding*2);this._bezierPreviewContainer=this._element.createChild("div","bezier-preview");this._bezierPreviewContainer.title=WI.UIString("Restart animation");this._bezierPreviewContainer.addEventListener("mousedown",this._resetPreviewAnimation.bind(this));this._bezierPreview=this._bezierPreviewContainer.createChild("div");this._bezierPreviewTiming=this._element.createChild("div","bezier-preview-timing");this._bezierContainer=this._element.appendChild(createSVGElement("svg"));this._bezierContainer.setAttribute("width",editorWidth);this._bezierContainer.setAttribute("height",editorHeight);this._bezierContainer.classList.add("bezier-container");let svgGroup=this._bezierContainer.appendChild(createSVGElement("g"));svgGroup.setAttribute("transform","translate(0, "+this._padding+")");let linearCurve=svgGroup.appendChild(createSVGElement("line"));linearCurve.classList.add("linear-curve");linearCurve.setAttribute("x1",this._controlHandleRadius);linearCurve.setAttribute("y1",this._bezierHeight+this._controlHandleRadius);linearCurve.setAttribute("x2",this._bezierWidth+this._controlHandleRadius);linearCurve.setAttribute("y2",this._controlHandleRadius);this._bezierCurve=svgGroup.appendChild(createSVGElement("path"));this._bezierCurve.classList.add("bezier-curve");function createControl(x1,y1)
{x1+=this._controlHandleRadius;y1+=this._controlHandleRadius;let line=svgGroup.appendChild(createSVGElement("line"));line.classList.add("control-line");line.setAttribute("x1",x1);line.setAttribute("y1",y1);line.setAttribute("x2",x1);line.setAttribute("y2",y1);let handle=svgGroup.appendChild(createSVGElement("circle"));handle.classList.add("control-handle");return{point:null,line,handle};}
this._inControl=createControl.call(this,0,this._bezierHeight);this._outControl=createControl.call(this,this._bezierWidth,0);this._numberInputContainer=this._element.createChild("div","number-input-container");function createBezierInput(id,{min,max}={})
{let key="_bezier"+id+"Input";this[key]=this._numberInputContainer.createChild("input");this[key].type="number";this[key].step=0.01;if(!isNaN(min))
this[key].min=min;if(!isNaN(max))
this[key].max=max;this[key].addEventListener("input",this._handleNumberInputInput.bind(this));this[key].addEventListener("keydown",this._handleNumberInputKeydown.bind(this));}
createBezierInput.call(this,"InX",{min:0,max:1});createBezierInput.call(this,"InY");createBezierInput.call(this,"OutX",{min:0,max:1});createBezierInput.call(this,"OutY");this._selectedControl=null;this._mouseDownPosition=null;this._bezierContainer.addEventListener("mousedown",this);WI.addWindowKeydownListener(this);} 
get element()
{return this._element;}
set bezier(bezier)
{if(!bezier)
return;var isCubicBezier=bezier instanceof WI.CubicBezier;if(!isCubicBezier)
return;this._bezier=bezier;this._updateBezierPreview();}
get bezier()
{return this._bezier;}
removeListeners()
{WI.removeWindowKeydownListener(this);} 
handleEvent(event)
{switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}}
handleKeydownEvent(event)
{if(!this._selectedControl||!this._element.parentNode)
return false;let horizontal=0;let vertical=0;switch(event.keyCode){case WI.KeyboardShortcut.Key.Up.keyCode:vertical=-1;break;case WI.KeyboardShortcut.Key.Right.keyCode:horizontal=1;break;case WI.KeyboardShortcut.Key.Down.keyCode:vertical=1;break;case WI.KeyboardShortcut.Key.Left.keyCode:horizontal=-1;break;default:return false;}
if(event.shiftKey){horizontal*=10;vertical*=10;}
vertical*=this._bezierWidth/100;horizontal*=this._bezierHeight/100;this._selectedControl.point.x=Number.constrain(this._selectedControl.point.x+horizontal,0,this._bezierWidth);this._selectedControl.point.y+=vertical;this._updateControl(this._selectedControl);this._updateValue();return true;} 
_handleMousedown(event)
{if(event.button!==0)
return;event.stop();window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._bezierPreviewContainer.classList.remove("animate");this._bezierPreviewTiming.classList.remove("animate");this._updateControlPointsForMouseEvent(event,true);}
_handleMousemove(event)
{this._updateControlPointsForMouseEvent(event);}
_handleMouseup(event)
{this._selectedControl.handle.classList.remove("selected");this._mouseDownPosition=null;this._triggerPreviewAnimation();window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);}
_updateControlPointsForMouseEvent(event,calculateSelectedControlPoint)
{var point=WI.Point.fromEventInElement(event,this._bezierContainer);point.x=Number.constrain(point.x-this._controlHandleRadius,0,this._bezierWidth);point.y-=this._controlHandleRadius+this._padding;if(calculateSelectedControlPoint){this._mouseDownPosition=point;if(this._inControl.point.distance(point)<this._outControl.point.distance(point))
this._selectedControl=this._inControl;else
this._selectedControl=this._outControl;}
if(event.shiftKey&&this._mouseDownPosition){if(Math.abs(this._mouseDownPosition.x-point.x)>Math.abs(this._mouseDownPosition.y-point.y))
point.y=this._mouseDownPosition.y;else
point.x=this._mouseDownPosition.x;}
this._selectedControl.point=point;this._selectedControl.handle.classList.add("selected");this._updateValue();}
_updateValue()
{function round(num)
{return Math.round(num*100)/100;}
var inValueX=round(this._inControl.point.x/this._bezierWidth);var inValueY=round(1-(this._inControl.point.y/this._bezierHeight));var outValueX=round(this._outControl.point.x/this._bezierWidth);var outValueY=round(1-(this._outControl.point.y/this._bezierHeight));this._bezier=new WI.CubicBezier(inValueX,inValueY,outValueX,outValueY);this._updateBezier();this.dispatchEventToListeners(WI.BezierEditor.Event.BezierChanged,{bezier:this._bezier});}
_updateBezier()
{var r=this._controlHandleRadius;var inControlX=this._inControl.point.x+r;var inControlY=this._inControl.point.y+r;var outControlX=this._outControl.point.x+r;var outControlY=this._outControl.point.y+r;var path=`M ${r} ${this._bezierHeight + r} C ${inControlX} ${inControlY} ${outControlX} ${outControlY} ${this._bezierWidth + r} ${r}`;this._bezierCurve.setAttribute("d",path);this._updateControl(this._inControl);this._updateControl(this._outControl);this._bezierInXInput.value=this._bezier.inPoint.x;this._bezierInYInput.value=this._bezier.inPoint.y;this._bezierOutXInput.value=this._bezier.outPoint.x;this._bezierOutYInput.value=this._bezier.outPoint.y;}
_updateControl(control)
{control.handle.setAttribute("cx",control.point.x+this._controlHandleRadius);control.handle.setAttribute("cy",control.point.y+this._controlHandleRadius);control.line.setAttribute("x2",control.point.x+this._controlHandleRadius);control.line.setAttribute("y2",control.point.y+this._controlHandleRadius);}
_updateBezierPreview()
{this._inControl.point=new WI.Point(this._bezier.inPoint.x*this._bezierWidth,(1-this._bezier.inPoint.y)*this._bezierHeight);this._outControl.point=new WI.Point(this._bezier.outPoint.x*this._bezierWidth,(1-this._bezier.outPoint.y)*this._bezierHeight);this._updateBezier();this._triggerPreviewAnimation();}
_triggerPreviewAnimation()
{this._bezierPreview.style.animationTimingFunction=this._bezier.toString();this._bezierPreviewContainer.classList.add("animate");this._bezierPreviewTiming.classList.add("animate");}
_resetPreviewAnimation()
{var parent=this._bezierPreview.parentNode;parent.removeChild(this._bezierPreview);parent.appendChild(this._bezierPreview);this._element.removeChild(this._bezierPreviewTiming);this._element.appendChild(this._bezierPreviewTiming);}
_handleNumberInputInput(event)
{this._changeBezierForInput(event.target,event.target.value);}
_handleNumberInputKeydown(event)
{let shift=0;if(event.keyIdentifier==="Up")
shift=0.01;else if(event.keyIdentifier==="Down")
shift=-0.01;if(!shift)
return;if(event.shiftKey)
shift*=10;event.preventDefault();this._changeBezierForInput(event.target,parseFloat(event.target.value)+shift);}
_changeBezierForInput(target,value)
{value=Math.round(value*100)/100;switch(target){case this._bezierInXInput:this._bezier.inPoint.x=Number.constrain(value,0,1);break;case this._bezierInYInput:this._bezier.inPoint.y=value;break;case this._bezierOutXInput:this._bezier.outPoint.x=Number.constrain(value,0,1);break;case this._bezierOutYInput:this._bezier.outPoint.y=value;break;default:return;}
this._updateBezierPreview();this.dispatchEventToListeners(WI.BezierEditor.Event.BezierChanged,{bezier:this._bezier});}};WI.BezierEditor.Event={BezierChanged:"bezier-editor-bezier-changed"};WI.BlackboxSettingsView=class BlackboxSettingsView extends WI.SettingsView
{constructor()
{super("blackbox",WI.UIString("Blackbox"));this._blackboxPatternCodeMirrorMap=new Map;} 
selectBlackboxPattern(regex)
{let codeMirror=this._blackboxPatternCodeMirrorMap.get(regex);if(!codeMirror)
return;codeMirror.focus();} 
initialLayout()
{super.initialLayout();let patternBlackboxExplanationElement=this.element.insertBefore(document.createElement("p"),this.element.lastChild);patternBlackboxExplanationElement.textContent=WI.UIString("If the URL of any script matches one of the regular expression patterns below, any pauses that would have happened in that script will be deferred until execution has continued to outside of that script.");let table=this.element.insertBefore(document.createElement("table"),this.element.lastChild);let tableHead=table.appendChild(document.createElement("thead"));let tableHeadRow=tableHead.appendChild(document.createElement("tr"));let urlHeaderCell=tableHeadRow.appendChild(document.createElement("th"));urlHeaderCell.classList.add("url");urlHeaderCell.textContent=WI.UIString("URL Pattern");let caseSensitiveHeaderCell=tableHeadRow.appendChild(document.createElement("th"));caseSensitiveHeaderCell.classList.add("case-sensitive");caseSensitiveHeaderCell.textContent=WI.UIString("Case Sensitive");let removeBlackboxHeaderCell=tableHeadRow.appendChild(document.createElement("th"));removeBlackboxHeaderCell.classList.add("remove-blackbox");this._tableBody=table.appendChild(document.createElement("tbody"));for(let regex of WI.debuggerManager.blackboxPatterns)
this._addRow(regex);if(!this._tableBody.children.length)
this._addRow(null);let tableFoot=table.appendChild(document.createElement("tfoot"));let tableFooterRow=tableFoot.appendChild(document.createElement("tr"));let addBlackboxCell=tableFooterRow.appendChild(document.createElement("td"));let addBlackboxButton=addBlackboxCell.appendChild(document.createElement("button"));addBlackboxButton.textContent=WI.UIString("Add Pattern");addBlackboxButton.addEventListener("click",(event)=>{for(let[regex,codeMirror]of this._blackboxPatternCodeMirrorMap){if(!regex){codeMirror.focus();return;}}
this._addRow(null);});let individualBlackboxExplanationElement=this.element.insertBefore(document.createElement("p"),this.element.lastChild);let blackboxIconElement=WI.ImageUtilities.useSVGSymbol("Images/Hide.svg#currentColor","toggle-script-blackbox",WI.UIString("Ignore script when debugging"));String.format(WI.UIString("Scripts can also be individually blackboxed by clicking on the %s icon that is shown on hover."),[blackboxIconElement],String.standardFormatters,individualBlackboxExplanationElement,(a,b)=>{a.append(b);return a;});} 
_addRow(regex)
{let tableBodyRow=this._tableBody.appendChild(document.createElement("tr"));let urlBodyCell=tableBodyRow.appendChild(document.createElement("td"));urlBodyCell.classList.add("url");let urlCodeMirror=WI.CodeMirrorEditor.create(urlBodyCell,{extraKeys:{"Tab":false,"Shift-Tab":false},lineWrapping:false,matchBrackets:false,mode:"text/x-regex",placeholder:WI.UIString("Regular Expression"),scrollbarStyle:null,value:regex?regex.source:"",});this._blackboxPatternCodeMirrorMap.set(regex,urlCodeMirror);this.needsLayout();let caseSensitiveBodyCell=tableBodyRow.appendChild(document.createElement("td"));caseSensitiveBodyCell.classList.add("case-sensitive");let caseSensitiveCheckbox=caseSensitiveBodyCell.appendChild(document.createElement("input"));caseSensitiveCheckbox.type="checkbox";caseSensitiveCheckbox.checked=regex?!regex.ignoreCase:true;let removeBlackboxBodyCell=tableBodyRow.appendChild(document.createElement("td"));removeBlackboxBodyCell.classList.add("remove-blackbox");let removeBlackboxButton=removeBlackboxBodyCell.appendChild(WI.ImageUtilities.useSVGSymbol("Images/NavigationItemTrash.svg","remove-blackbox-button",WI.UIString("Delete Blackbox")));removeBlackboxButton.addEventListener("click",(event)=>{if(regex)
WI.debuggerManager.setShouldBlackboxPattern(regex,false);regex=null;this._blackboxPatternCodeMirrorMap.delete(regex);tableBodyRow.remove();if(!this._tableBody.children.length)
this._addRow(null);});let update=()=>{let url=urlCodeMirror.getValue();if(regex){if(regex.source===url&&regex.ignoreCase!==caseSensitiveCheckbox.checked)
return;WI.debuggerManager.setShouldBlackboxPattern(regex,false);}
this._blackboxPatternCodeMirrorMap.delete(regex);regex=url?new RegExp(url,!caseSensitiveCheckbox.checked?"i":""):null;if(regex)
WI.debuggerManager.setShouldBlackboxPattern(regex,true);this._blackboxPatternCodeMirrorMap.set(regex,urlCodeMirror);};urlCodeMirror.addKeyMap({"Enter":update,"Esc":update,});urlCodeMirror.on("blur",update);caseSensitiveCheckbox.addEventListener("change",update);if(!regex)
urlCodeMirror.focus();}};WI.BlackboxedGroupTreeElement=class BlackboxedGroupTreeElement extends WI.GeneralTreeElement
{constructor(callFrames)
{const classNames=["blackboxed-group"];const title=WI.UIString("Blackboxed","Blackboxed @ Debugger Call Stack","Part of the 'Blackboxed - %d call frames' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.");let subtitle;if(callFrames.length===1)
subtitle=WI.UIString("%d call frame","call frame @ Debugger Call Stack","Part of the 'Blackboxed - %d call frame' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);else
subtitle=WI.UIString("%d call frames","call frames @ Debugger Call Stack","Part of the 'Blackboxed - %d call frames' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);super(classNames,title,subtitle);this.selectable=false;this.toggleOnClick=true;this._callFrames=callFrames;} 
expand()
{let index=this.parent.children.indexOf(this);for(let i=this._callFrames.length-1;i>=0;--i)
this.parent.insertChild(new WI.CallFrameTreeElement(this._callFrames[i]),index);this.parent.removeChild(this);}};WI.BootstrapScriptTreeElement=class BootstrapScriptTreeElement extends WI.ScriptTreeElement
{constructor(bootstrapScript)
{super(bootstrapScript);this.addClassName("bootstrap");} 
onattach()
{super.onattach();WI.NetworkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptEnabledChanged,this._handleNetworkManagerBootstrapScriptEnabledChanged,this);this.status=document.createElement("input");this.status.type="checkbox";this.status.checked=WI.networkManager.bootstrapScriptEnabled;this.status.addEventListener("change",(event)=>{WI.networkManager.bootstrapScriptEnabled=event.target.checked;});}
ondetach()
{WI.NetworkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptEnabledChanged,this._handleNetworkManagerBootstrapScriptEnabledChanged,this);super.ondetach();}
ondelete()
{WI.networkManager.destroyBootstrapScript();return true;}
onspace()
{WI.networkManager.bootstrapScriptEnabled=!WI.networkManager.bootstrapScriptEnabled;return true;}
canSelectOnMouseDown(event)
{if(this.status.contains(event.target))
return false;return super.canSelectOnMouseDown(event);}
populateContextMenu(contextMenu,event)
{let toggleEnabledString=WI.networkManager.bootstrapScriptEnabled?WI.UIString("Disable Inspector Bootstrap Script"):WI.UIString("Enable Inspector Bootstrap Script");contextMenu.appendItem(toggleEnabledString,()=>{WI.networkManager.bootstrapScriptEnabled=!WI.networkManager.bootstrapScriptEnabled;});contextMenu.appendItem(WI.UIString("Delete Inspector Bootstrap Script"),()=>{WI.networkManager.destroyBootstrapScript();});super.populateContextMenu(contextMenu,event);}
updateStatus()
{} 
_handleNetworkManagerBootstrapScriptEnabledChanged(event)
{this.status.checked=WI.networkManager.bootstrapScriptEnabled;}};WI.BoxModelDetailsSectionRow=class BoxModelDetailsSectionRow extends WI.DetailsSectionRow
{constructor()
{super(WI.UIString("No Box Model Information"));this.element.classList.add("box-model");this._nodeStyles=null;this._outermostBox=null;this._outermostBoxWidth=NaN;} 
get nodeStyles()
{return this._nodeStyles;}
set nodeStyles(nodeStyles)
{if(this._nodeStyles&&this._nodeStyles.computedStyle)
this._nodeStyles.computedStyle.removeEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._refresh,this);this._nodeStyles=nodeStyles;if(this._nodeStyles&&this._nodeStyles.computedStyle)
this._nodeStyles.computedStyle.addEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._refresh,this);this.element.classList.remove("hovered");this._refresh();}
get minimumWidth()
{if(isNaN(this._outermostBoxWidth)&&this._outermostBox){const margin=6;this._outermostBoxWidth=this._outermostBox.realOffsetWidth+margin;}
return this._outermostBoxWidth||0;} 
_refresh()
{if(this._ignoreNextRefresh){this._ignoreNextRefresh=false;return;}
this._updateMetrics();}
_getPropertyValue(style,propertyName)
{const dontCreateIfMissing=true;let property=style.propertyForName(propertyName,dontCreateIfMissing);if(!property)
return null;return property.value;}
_getPropertyValueAsPx(style,propertyName)
{let value=this._getPropertyValue(style,propertyName);if(!value)
return 0;return Number(value.replace(/px$/,"")||0);}
_getBox(computedStyle,componentName)
{let prefix=this._getComponentPrefix(componentName);let suffix=this._getComponentSuffix(componentName);let left=this._getPropertyValueAsPx(computedStyle,prefix+"-left"+suffix);let top=this._getPropertyValueAsPx(computedStyle,prefix+"-top"+suffix);let right=this._getPropertyValueAsPx(computedStyle,prefix+"-right"+suffix);let bottom=this._getPropertyValueAsPx(computedStyle,prefix+"-bottom"+suffix);return{left,top,right,bottom};}
_getComponentPrefix(componentName)
{return componentName==="border-radius"?"border":componentName;}
_getComponentSuffix(componentName)
{switch(componentName){case"border":return"-width";case"border-radius":return"-radius";}
return"";}
_highlightDOMNode(showHighlight,mode,event)
{event.stopPropagation();let node=showHighlight?this.nodeStyles.node:null;if(node){if(this._highlightMode===mode)
return;this._highlightMode=mode;node.highlight(this._highlightMode);}else{this._highlightMode=null;WI.domManager.hideDOMNodeHighlight();}
for(var i=0;this._boxElements&&i<this._boxElements.length;++i){var element=this._boxElements[i];if(node&&(mode==="all"||element._name===mode))
element.classList.add("active");else
element.classList.remove("active");}
this.element.classList.toggle("hovered",showHighlight);}
_updateMetrics()
{var metricsElement=document.createElement("div");var style=this._nodeStyles.computedStyle;function createValueElement(type,value,name,propertyName)
{let floatValue=parseFloat(value);let shouldRoundValue=!isNaN(floatValue)&&(floatValue%1!==0);if(isNaN(floatValue))
value=figureDash;let element=document.createElement(type);element.textContent=shouldRoundValue?("~"+Math.round(floatValue*100)/100):value;if(shouldRoundValue)
element.title=value;element.addEventListener("dblclick",this._startEditing.bind(this,element,name,propertyName,style),false);return element;}
function createBoxPartElement(name,side)
{let prefix=this._getComponentPrefix(name);let suffix=this._getComponentSuffix(name);let propertyName=(prefix!=="position"?prefix+"-":"")+side+suffix;let value=this._getPropertyValue(style,propertyName);if(value){if(prefix==="position"&&value==="auto")
value="";else if(prefix!=="position"&&value==="0px")
value="";else
value=value.replace(/px$/,"");}else
value="";let element=createValueElement.call(this,"div",value,name,propertyName);element.className=side;return element;}
function createContentAreaElement(name)
{let size=this._getPropertyValueAsPx(style,name);if(this._getPropertyValue(style,"box-sizing")==="border-box"){let borderBox=this._getBox(style,"border");let paddingBox=this._getBox(style,"padding");let[side,oppositeSide]=name==="width"?["left","right"]:["top","bottom"];size=size-borderBox[side]-borderBox[oppositeSide]-paddingBox[side]-paddingBox[oppositeSide];}
return createValueElement.call(this,"span",size,name,name);}
var noMarginDisplayType={"table-cell":true,"table-column":true,"table-column-group":true,"table-footer-group":true,"table-header-group":true,"table-row":true,"table-row-group":true};var noPaddingDisplayType={"table-column":true,"table-column-group":true,"table-footer-group":true,"table-header-group":true,"table-row":true,"table-row-group":true};var noPositionType={"static":true};this._boxElements=[];if(style.enabledProperties.length===0){this.showEmptyMessage();return;}
let displayProperty=this._getPropertyValue(style,"display");let positionProperty=this._getPropertyValue(style,"position");if(!displayProperty||!positionProperty){this.showEmptyMessage();return;}
this._outermostBox=null;this._outermostBoxWidth=NaN;for(let name of["content","padding","border","margin","position"]){if(name==="margin"&&noMarginDisplayType[displayProperty.value])
continue;if(name==="padding"&&noPaddingDisplayType[displayProperty.value])
continue;if(name==="position"&&noPositionType[positionProperty.value])
continue;let boxElement=document.createElement("div");boxElement.classList.add("box",name);boxElement._name=name;boxElement.addEventListener("mouseover",this._highlightDOMNode.bind(this,true,name==="position"?"all":name),false);this._boxElements.push(boxElement);if(name==="content"){let widthElement=createContentAreaElement.call(this,"width");let heightElement=createContentAreaElement.call(this,"height");if(!widthElement||!heightElement){this.showEmptyMessage();return;}
boxElement.append(widthElement," \u00D7 ",heightElement);}else{let borderTopLeftRadiusElement=null;let borderTopRightRadiusElement=null;let borderBottomRightRadiusElement=null;let borderBottomLeftRadiusElement=null;if(name==="border"){for(let corner of["top-left","top-right","bottom-right","bottom-left"]){let cornerValue=this._getPropertyValue(style,"border-"+corner+"-radius");if(cornerValue&&cornerValue!=="0px")
boxElement.classList.add("has-"+corner+"-radius");}
borderTopLeftRadiusElement=createBoxPartElement.call(this,"border-radius","top-left");borderTopRightRadiusElement=createBoxPartElement.call(this,"border-radius","top-right");borderBottomRightRadiusElement=createBoxPartElement.call(this,"border-radius","bottom-right");borderBottomLeftRadiusElement=createBoxPartElement.call(this,"border-radius","bottom-left");}
let topElement=createBoxPartElement.call(this,name,"top");let leftElement=createBoxPartElement.call(this,name,"left");let rightElement=createBoxPartElement.call(this,name,"right");let bottomElement=createBoxPartElement.call(this,name,"bottom");if(!topElement||!leftElement||!rightElement||!bottomElement){this.showEmptyMessage();return;}
let labelElement=document.createElement("div");labelElement.className="label";labelElement.textContent=name;boxElement.appendChild(labelElement);if(borderTopLeftRadiusElement)
boxElement.appendChild(borderTopLeftRadiusElement);boxElement.appendChild(topElement);if(borderTopRightRadiusElement)
boxElement.appendChild(borderTopRightRadiusElement);boxElement.appendChild(document.createElement("br"));boxElement.appendChild(leftElement);if(this._outermostBox)
boxElement.appendChild(this._outermostBox);boxElement.appendChild(rightElement);boxElement.appendChild(document.createElement("br"));if(borderBottomLeftRadiusElement)
boxElement.appendChild(borderBottomLeftRadiusElement);boxElement.appendChild(bottomElement);if(borderBottomRightRadiusElement)
boxElement.appendChild(borderBottomRightRadiusElement);}
this._outermostBox=boxElement;}
metricsElement.appendChild(this._outermostBox);metricsElement.addEventListener("mouseover",this._highlightDOMNode.bind(this,false,""),false);this.hideEmptyMessage();this.element.appendChild(metricsElement);}
_startEditing(targetElement,box,styleProperty,computedStyle)
{if(WI.isBeingEdited(targetElement))
return;
if(targetElement.title)
targetElement.textContent=targetElement.title;var context={box,styleProperty};var boundKeyDown=this._handleKeyDown.bind(this,context,styleProperty);context.keyDownHandler=boundKeyDown;targetElement.addEventListener("keydown",boundKeyDown,false);this._isEditingMetrics=true;var config=new WI.EditingConfig(this._editingCommitted.bind(this),this._editingCancelled.bind(this),context);WI.startEditing(targetElement,config);window.getSelection().setBaseAndExtent(targetElement,0,targetElement,1);}
_alteredFloatNumber(number,event)
{var arrowKeyPressed=event.keyIdentifier==="Up"||event.keyIdentifier==="Down";var changeAmount=1;if(event.shiftKey&&!arrowKeyPressed)
changeAmount=100;else if(event.shiftKey||!arrowKeyPressed)
changeAmount=10;else if(event.altKey)
changeAmount=0.1;if(event.keyIdentifier==="Down"||event.keyIdentifier==="PageDown")
changeAmount*=-1;var result=Number((number+changeAmount).toFixed(6));if(!String(result).match(WI.EditingSupport.NumberRegex))
return null;return result;}
_handleKeyDown(context,styleProperty,event)
{if(!/^(?:Page)?(?:Up|Down)$/.test(event.keyIdentifier))
return;var element=event.currentTarget;var selection=window.getSelection();if(!selection.rangeCount)
return;var selectionRange=selection.getRangeAt(0);if(!element.contains(selectionRange.commonAncestorContainer))
return;var originalValue=element.textContent;var wordRange=selectionRange.startContainer.rangeOfWord(selectionRange.startOffset,WI.EditingSupport.StyleValueDelimiters,element);var wordString=wordRange.toString();var matches=WI.EditingSupport.NumberRegex.exec(wordString);var replacementString;if(matches&&matches.length){var prefix=matches[1];var suffix=matches[3];var number=this._alteredFloatNumber(parseFloat(matches[2]),event);if(number===null){return;}
if(styleProperty!=="margin"&&number<0)
number=0;replacementString=prefix+number+suffix;}
if(!replacementString)
return;var replacementTextNode=document.createTextNode(replacementString);wordRange.deleteContents();wordRange.insertNode(replacementTextNode);var finalSelectionRange=document.createRange();finalSelectionRange.setStart(replacementTextNode,0);finalSelectionRange.setEnd(replacementTextNode,replacementString.length);selection.removeAllRanges();selection.addRange(finalSelectionRange);event.handled=true;event.preventDefault();this._ignoreNextRefresh=true;this._applyUserInput(element,replacementString,originalValue,context,false);}
_editingEnded(element,context)
{element.removeEventListener("keydown",context.keyDownHandler,false);this._isEditingMetrics=false;}
_editingCancelled(element,context)
{this._editingEnded(element,context);this._refresh();}
_applyUserInput(element,userInput,previousContent,context,commitEditor)
{if(commitEditor&&userInput===previousContent){this._editingCancelled(element,context);return;}
if(context.box!=="position"&&(!userInput||userInput===figureDash))
userInput="0px";else if(context.box==="position"&&(!userInput||userInput===figureDash))
userInput="auto";userInput=userInput.toLowerCase();if(/^-?(?:\d+(?:\.\d+)?|\.\d+)$/.test(userInput))
userInput+="px";var styleProperty=context.styleProperty;var computedStyle=this._nodeStyles.computedStyle;if(this._getPropertyValue(computedStyle,"box-sizing")==="border-box"&&(styleProperty==="width"||styleProperty==="height")){if(!userInput.match(/px$/)){console.error("For elements with box-sizing: border-box, only absolute content area dimensions can be applied");return;}
var borderBox=this._getBox(computedStyle,"border");var paddingBox=this._getBox(computedStyle,"padding");var userValuePx=Number(userInput.replace(/px$/,""));if(isNaN(userValuePx))
return;if(styleProperty==="width")
userValuePx+=borderBox.left+borderBox.right+paddingBox.left+paddingBox.right;else
userValuePx+=borderBox.top+borderBox.bottom+paddingBox.top+paddingBox.bottom;userInput=userValuePx+"px";}
let setBorderStyleProperty=null;if(context.box==="border"){let borderStyleProperty=styleProperty.replace("-width","-style");if(this._getPropertyValue(computedStyle,borderStyleProperty)==="none")
setBorderStyleProperty=borderStyleProperty;}
WI.RemoteObject.resolveNode(this._nodeStyles.node).then((object)=>{function inspectedPage_node_toggleInlineStyleProperty(styleProperty,userInput,setBorderStyleProperty){if(setBorderStyleProperty)
this.style.setProperty(setBorderStyleProperty,"solid","important");this.style.setProperty(styleProperty,userInput,"important");}
let didToggle=()=>{this._nodeStyles.refresh();};object.callFunction(inspectedPage_node_toggleInlineStyleProperty,[styleProperty,userInput,setBorderStyleProperty],false,didToggle);object.release();});}
_editingCommitted(element,userInput,previousContent,context)
{this._editingEnded(element,context);this._applyUserInput(element,userInput,previousContent,context,true);}};WI.BoxShadowEditor=class BoxShadowEditor extends WI.Object
{constructor()
{super();this._element=document.createElement("div");this._element.classList.add("box-shadow-editor");let tableElement=this._element.appendChild(document.createElement("table"));function createInputRow(identifier,label){let id=`box-shadow-editor-${identifier}-input`;let rowElement=tableElement.appendChild(document.createElement("tr"));rowElement.className=identifier;let headerElement=rowElement.appendChild(document.createElement("th"));let labelElement=headerElement.appendChild(document.createElement("label"));labelElement.setAttribute("for",id);labelElement.textContent=label;let dataElement=rowElement.appendChild(document.createElement("td"));let inputElement=dataElement.appendChild(document.createElement("input"));inputElement.type="text";inputElement.id=id;return{rowElement,inputElement};}
function createSlider(rowElement,min,max){let dataElement=rowElement.appendChild(document.createElement("td"));let rangeElement=dataElement.appendChild(document.createElement("input"));rangeElement.type="range";rangeElement.min=min;rangeElement.max=max;return rangeElement;}
let offsetXRow=createInputRow("offset-x",WI.UIString("Offset X","Offset X @ Box Shadow Editor","Input label for the x-axis of the offset of a CSS box shadow"));this._offsetXInput=offsetXRow.inputElement;this._offsetXInput.spellcheck=false;this._offsetXInput.addEventListener("input",this._handleOffsetXInputInput.bind(this));this._offsetXInput.addEventListener("keydown",this._handleOffsetXInputKeyDown.bind(this));let offsetSliderDataElement=offsetXRow.rowElement.appendChild(document.createElement("td"));offsetSliderDataElement.setAttribute("rowspan",3);this._offsetSliderKnobRadius=5;this._offsetSliderAreaSize=100;const offsetSliderContainerSize=this._offsetSliderAreaSize+(this._offsetSliderKnobRadius*2);this._offsetSliderSVG=offsetSliderDataElement.appendChild(createSVGElement("svg"));this._offsetSliderSVG.setAttribute("tabindex",0);this._offsetSliderSVG.setAttribute("width",offsetSliderContainerSize);this._offsetSliderSVG.setAttribute("height",offsetSliderContainerSize);this._offsetSliderSVG.addEventListener("mousedown",this);this._offsetSliderSVG.addEventListener("keydown",this);this._offsetSliderSVGMouseDownPoint=null;let offsetSliderGroup=this._offsetSliderSVG.appendChild(createSVGElement("g"));offsetSliderGroup.setAttribute("transform",`translate(${this._offsetSliderKnobRadius}, ${this._offsetSliderKnobRadius})`);let offsetSliderXAxisLine=offsetSliderGroup.appendChild(createSVGElement("line"));offsetSliderXAxisLine.classList.add("axis");offsetSliderXAxisLine.setAttribute("x1",this._offsetSliderAreaSize/2);offsetSliderXAxisLine.setAttribute("y1",0);offsetSliderXAxisLine.setAttribute("x2",this._offsetSliderAreaSize/2);offsetSliderXAxisLine.setAttribute("y2",this._offsetSliderAreaSize);let offsetSliderYAxisLine=offsetSliderGroup.appendChild(createSVGElement("line"));offsetSliderYAxisLine.classList.add("axis");offsetSliderYAxisLine.setAttribute("x1",0);offsetSliderYAxisLine.setAttribute("y1",this._offsetSliderAreaSize/2);offsetSliderYAxisLine.setAttribute("x2",this._offsetSliderAreaSize);offsetSliderYAxisLine.setAttribute("y2",this._offsetSliderAreaSize/2);this._offsetSliderLine=offsetSliderGroup.appendChild(createSVGElement("line"));this._offsetSliderLine.setAttribute("x1",this._offsetSliderAreaSize/2);this._offsetSliderLine.setAttribute("y1",this._offsetSliderAreaSize/2);this._offsetSliderKnob=offsetSliderGroup.appendChild(createSVGElement("circle"));let offsetYRow=createInputRow("offset-y",WI.UIString("Offset Y","Offset Y @ Box Shadow Editor","Input label for the y-axis of the offset of a CSS box shadow"));this._offsetYInput=offsetYRow.inputElement;this._offsetYInput.spellcheck=false;this._offsetYInput.addEventListener("input",this._handleOffsetYInputInput.bind(this));this._offsetYInput.addEventListener("keydown",this._handleOffsetYInputKeyDown.bind(this));let insetRow=createInputRow("inset",WI.UIString("Inset","Inset @ Box Shadow Editor","Checkbox label for the inset of a CSS box shadow."));this._insetCheckbox=insetRow.inputElement;this._insetCheckbox.type="checkbox";this._insetCheckbox.addEventListener("change",this._handleInsetCheckboxChange.bind(this));let blurRadiusRow=createInputRow("blur-radius",WI.UIString("Blur","Blur @ Box Shadow Editor","Input label for the blur radius of a CSS box shadow"));this._blurRadiusInput=blurRadiusRow.inputElement;this._blurRadiusInput.spellcheck=false;this._blurRadiusInput.addEventListener("input",this._handleBlurRadiusInputInput.bind(this));this._blurRadiusInput.addEventListener("keydown",this._handleBlurRadiusInputKeyDown.bind(this));this._blurRadiusInput.min=0;this._blurRadiusSlider=createSlider(blurRadiusRow.rowElement,0,100);this._blurRadiusSlider.addEventListener("input",this._handleBlurRadiusSliderInput.bind(this));let spreadRadiusRow=createInputRow("spread-radius",WI.UIString("Spread","Spread @ Box Shadow Editor","Input label for the spread radius of a CSS box shadow"));this._spreadRadiusInput=spreadRadiusRow.inputElement;this._spreadRadiusInput.spellcheck=false;this._spreadRadiusInput.addEventListener("input",this._handleSpreadRadiusInputInput.bind(this));this._spreadRadiusInput.addEventListener("keydown",this._handleSpreadRadiusInputKeyDown.bind(this));this._spreadRadiusSlider=createSlider(spreadRadiusRow.rowElement,-50,50);this._spreadRadiusSlider.addEventListener("input",this._handleSpreadRadiusSliderInput.bind(this));this._colorPicker=new WI.ColorPicker;this._colorPicker.addEventListener(WI.ColorPicker.Event.ColorChanged,this._handleColorChanged,this);this._element.appendChild(this._colorPicker.element);this.boxShadow=new WI.BoxShadow;WI.addWindowKeydownListener(this);} 
get element(){return this._element;}
get boxShadow()
{return this._boxShadow;}
set boxShadow(boxShadow)
{this._boxShadow=boxShadow;let offsetX=this._boxShadow?.offsetX||{value:0,unit:""};let offsetY=this._boxShadow?.offsetY||{value:0,unit:""};this._offsetXInput.value=offsetX.value+offsetX.unit;this._offsetYInput.value=offsetY.value+offsetY.unit;let offsetSliderCenter=this._offsetSliderAreaSize/2;let offsetSliderX=Number.constrain(offsetX.value+offsetSliderCenter,0,this._offsetSliderAreaSize);let offsetSliderY=Number.constrain(offsetY.value+offsetSliderCenter,0,this._offsetSliderAreaSize);this._offsetSliderLine.setAttribute("x2",offsetSliderX);this._offsetSliderKnob.setAttribute("cx",offsetSliderX);this._offsetSliderLine.setAttribute("y2",offsetSliderY);this._offsetSliderKnob.setAttribute("cy",offsetSliderY);let blurRadius=this._boxShadow?.blurRadius||{value:0,unit:""};this._blurRadiusInput.value=blurRadius.value+blurRadius.unit;this._blurRadiusSlider.value=blurRadius.value;let spreadRadius=this._boxShadow?.spreadRadius||{value:0,unit:""};this._spreadRadiusInput.value=spreadRadius.value+spreadRadius.unit;this._spreadRadiusSlider.value=spreadRadius.value;let inset=this._boxShadow?.inset||false;this._insetCheckbox.checked=inset;let color=this._boxShadow?.color||WI.Color.fromString("transparent");this._colorPicker.color=color;} 
handleEvent(event)
{switch(event.type){case"keydown":this._handleOffsetSliderSVGKeyDown(event);return;case"mousedown":this._handleOffsetSliderSVGMouseDown(event);return;case"mousemove":this._handleWindowMouseMove(event);return;case"mouseup":this._handleWindowMouseUp(event);return;}} 
_updateBoxShadow({offsetX,offsetY,blurRadius,spreadRadius,inset,color})
{let change=false;if(!offsetX)
offsetX=this._boxShadow.offsetX;else if(!Object.shallowEqual(offsetX,this._boxShadow.offsetX))
change=true;if(!offsetY)
offsetY=this._boxShadow.offsetY;else if(!Object.shallowEqual(offsetY,this._boxShadow.offsetY))
change=true;if(!blurRadius)
blurRadius=this._boxShadow.blurRadius;else if(!Object.shallowEqual(blurRadius,this._boxShadow.blurRadius))
change=true;if(!spreadRadius)
spreadRadius=this._boxShadow.spreadRadius;else if(!Object.shallowEqual(spreadRadius,this._boxShadow.spreadRadius))
change=true;if(inset===undefined)
inset=this._boxShadow.inset;else if(inset!==this._boxShadow.inset)
change=true;if(!color)
color=this._boxShadow.color;else if(color.toString()!==this._boxShadow.color?.toString())
change=true;if(!change)
return;this.boxShadow=new WI.BoxShadow(offsetX,offsetY,blurRadius,spreadRadius,inset,color);this.dispatchEventToListeners(WI.BoxShadowEditor.Event.BoxShadowChanged,{boxShadow:this._boxShadow});}
_updateBoxShadowOffsetFromSliderMouseEvent(event,saveMouseDownPoint)
{let point=WI.Point.fromEventInElement(event,this._offsetSliderSVG);point.x=Number.constrain(point.x-this._offsetSliderKnobRadius,0,this._offsetSliderAreaSize);point.y=Number.constrain(point.y-this._offsetSliderKnobRadius,0,this._offsetSliderAreaSize);if(saveMouseDownPoint)
this._offsetSliderSVGMouseDownPoint=point;if(event.shiftKey&&this._offsetSliderSVGMouseDownPoint){if(Math.abs(this._offsetSliderSVGMouseDownPoint.x-point.x)>Math.abs(this._offsetSliderSVGMouseDownPoint.y-point.y))
point.y=this._offsetSliderSVGMouseDownPoint.y;else
point.x=this._offsetSliderSVGMouseDownPoint.x;}
let offsetSliderCenter=this._offsetSliderAreaSize/2;this._updateBoxShadow({offsetX:{value:point.x-offsetSliderCenter,unit:this._boxShadow.offsetX.unit,},offsetY:{value:point.y-offsetSliderCenter,unit:this._boxShadow.offsetY.unit,},});}
_determineShiftForEvent(event)
{let shift=0;if(event.key==="ArrowUp")
shift=1;else if(event.key==="ArrowDown")
shift=-1;if(!shift)
return NaN;if(event.metaKey)
shift*=100;else if(event.shiftKey)
shift*=10;else if(event.altKey)
shift/=10;event.preventDefault();return shift;}
_handleOffsetSliderSVGKeyDown(event){let shiftX=0;let shiftY=0;switch(event.keyCode){case WI.KeyboardShortcut.Key.Up.keyCode:shiftY=-1;break;case WI.KeyboardShortcut.Key.Right.keyCode:shiftX=1;break;case WI.KeyboardShortcut.Key.Down.keyCode:shiftY=1;break;case WI.KeyboardShortcut.Key.Left.keyCode:shiftX=-1;break;}
if(!shiftX&&!shiftY)
return false;let multiplier=1;if(event.shiftKey)
multiplier=10;else if(event.altKey)
multiplier=0.1;shiftX*=multiplier;shiftY*=multiplier;let offsetValueLimit=this._offsetSliderAreaSize/2;this._updateBoxShadow({offsetX:{value:Number.constrain(this._boxShadow.offsetX.value+shiftX,-1*offsetValueLimit,offsetValueLimit).maxDecimals(1),unit:this._boxShadow.offsetX.unit,},offsetY:{value:Number.constrain(this._boxShadow.offsetY.value+shiftY,-1*offsetValueLimit,offsetValueLimit).maxDecimals(1),unit:this._boxShadow.offsetY.unit,},});}
_handleOffsetSliderSVGMouseDown(event)
{if(event.button!==0)
return;event.stop();this._offsetSliderSVG.focus();window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._updateBoxShadowOffsetFromSliderMouseEvent(event,true);}
_handleWindowMouseMove(event)
{this._updateBoxShadowOffsetFromSliderMouseEvent(event);}
_handleWindowMouseUp(event)
{this._offsetSliderSVGMouseDownPoint=null;window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);}
_handleOffsetXInputInput(event)
{this._updateBoxShadow({offsetX:WI.BoxShadow.parseNumberComponent(this._offsetXInput.value),});}
_handleOffsetXInputKeyDown(event)
{let shift=this._determineShiftForEvent(event);if(isNaN(shift))
return;this._updateBoxShadow({offsetX:{value:(this._boxShadow.offsetX.value+shift).maxDecimals(1),unit:this._boxShadow.offsetX.unit,},});}
_handleOffsetYInputInput(event)
{this._updateBoxShadow({offsetY:WI.BoxShadow.parseNumberComponent(this._offsetYInput.value),});}
_handleOffsetYInputKeyDown(event)
{let shift=this._determineShiftForEvent(event);if(isNaN(shift))
return;this._updateBoxShadow({offsetY:{value:(this._boxShadow.offsetY.value+shift).maxDecimals(1),unit:this._boxShadow.offsetY.unit,},});}
_handleBlurRadiusInputInput(event)
{this._updateBoxShadow({blurRadius:WI.BoxShadow.parseNumberComponent(this._blurRadiusInput.value),});}
_handleBlurRadiusInputKeyDown(event)
{let shift=this._determineShiftForEvent(event);if(isNaN(shift))
return;this._updateBoxShadow({blurRadius:{value:(this._boxShadow.blurRadius.value+shift).maxDecimals(1),unit:this._boxShadow.blurRadius.unit,}});}
_handleBlurRadiusSliderInput(event)
{this._updateBoxShadow({blurRadius:{value:this._blurRadiusSlider.valueAsNumber,unit:this._boxShadow.blurRadius.unit,}});}
_handleSpreadRadiusInputInput(event)
{this._updateBoxShadow({spreadRadius:WI.BoxShadow.parseNumberComponent(this._spreadRadiusInput.value),});}
_handleSpreadRadiusInputKeyDown(event)
{let shift=this._determineShiftForEvent(event);if(isNaN(shift))
return;this._updateBoxShadow({spreadRadius:{value:(this._boxShadow.spreadRadius.value+shift).maxDecimals(1),unit:this._boxShadow.spreadRadius.unit,}});}
_handleSpreadRadiusSliderInput(event)
{this._updateBoxShadow({spreadRadius:{value:this._spreadRadiusSlider.valueAsNumber,unit:this._boxShadow.spreadRadius.unit,}});}
_handleInsetCheckboxChange(event)
{this._updateBoxShadow({inset:!!this._insetCheckbox.checked,});}
_handleColorChanged(event)
{this._updateBoxShadow({color:this._colorPicker.color,});}};WI.BoxShadowEditor.Event={BoxShadowChanged:"box-shadow-editor-box-shadow-changed"};WI.BreakpointActionView=class BreakpointActionView extends WI.Object
{constructor(action,delegate,{omitFocus}={})
{super();this._action=action;this._delegate=delegate;this._element=document.createElement("div");this._element.className="breakpoint-action-block";var header=this._element.appendChild(document.createElement("div"));header.className="breakpoint-action-block-header";var picker=header.appendChild(document.createElement("select"));picker.addEventListener("change",this._pickerChanged.bind(this));for(var key in WI.BreakpointAction.Type){var type=WI.BreakpointAction.Type[key];var option=document.createElement("option");option.textContent=WI.BreakpointActionView.displayStringForType(type);option.selected=this._action.type===type;option.value=type;picker.add(option);}
let buttonContainerElement=header.appendChild(document.createElement("div"));buttonContainerElement.classList.add("breakpoint-action-button-container");let appendActionButton=buttonContainerElement.appendChild(document.createElement("button"));appendActionButton.className="breakpoint-action-append-button";appendActionButton.addEventListener("click",this._appendActionButtonClicked.bind(this));appendActionButton.title=WI.UIString("Add new breakpoint action after this action");let removeActionButton=buttonContainerElement.appendChild(document.createElement("button"));removeActionButton.className="breakpoint-action-remove-button";removeActionButton.addEventListener("click",this._removeAction.bind(this));removeActionButton.title=WI.UIString("Delete this breakpoint action");this._bodyElement=this._element.appendChild(document.createElement("div"));this._bodyElement.className="breakpoint-action-block-body";this._updateBody(omitFocus);} 
static displayStringForType(type)
{switch(type){case WI.BreakpointAction.Type.Log:return WI.UIString("Log Message");case WI.BreakpointAction.Type.Evaluate:return WI.UIString("Evaluate JavaScript");case WI.BreakpointAction.Type.Sound:return WI.UIString("Play Sound");case WI.BreakpointAction.Type.Probe:return WI.UIString("Probe Expression");default:return"";}} 
get action()
{return this._action;}
get element()
{return this._element;} 
_pickerChanged(event)
{this._action.type=event.target.value;this._updateBody();this._delegate.breakpointActionViewResized(this);}
_appendActionButtonClicked(event)
{this._delegate.breakpointActionViewAppendActionView(this,new WI.BreakpointAction(this._action.type));}
_removeAction()
{this._delegate.breakpointActionViewRemoveActionView(this);}
_updateBody(omitFocus)
{this._bodyElement.removeChildren();let createOptionsElements=()=>{let optionsElement=document.createElement("div");let emulateUserGestureLabel=optionsElement.appendChild(document.createElement("label"));this._emulateUserGestureCheckbox=emulateUserGestureLabel.appendChild(document.createElement("input"));this._emulateUserGestureCheckbox.type="checkbox";this._emulateUserGestureCheckbox.checked=this._action.emulateUserGesture;this._emulateUserGestureCheckbox.addEventListener("change",this._handleEmulateUserGestureCheckboxChange.bind(this));emulateUserGestureLabel.appendChild(document.createTextNode(WI.UIString("Emulate User Gesture","Emulate User Gesture @ breakpoint action configuration","Checkbox shown when configuring log/evaluate/probe breakpoint actions to cause it to be evaluated as though it was in response to user interaction.")));return optionsElement;};switch(this._action.type){case WI.BreakpointAction.Type.Log:this._bodyElement.hidden=false;var input=this._bodyElement.appendChild(document.createElement("input"));input.placeholder=WI.UIString("Message");input.addEventListener("input",this._handleLogInputInput.bind(this));input.value=this._action.data||"";input.spellcheck=false;if(!omitFocus)
setTimeout(function(){input.focus();},0);var flexWrapper=this._bodyElement.appendChild(document.createElement("div"));flexWrapper.className="flex";if(WI.BreakpointAction.supportsEmulateUserAction())
flexWrapper.appendChild(createOptionsElements());var descriptionElement=flexWrapper.appendChild(document.createElement("div"));descriptionElement.classList.add("description");descriptionElement.setAttribute("dir","ltr");descriptionElement.textContent=WI.UIString("${expr} = expression");break;case WI.BreakpointAction.Type.Evaluate:case WI.BreakpointAction.Type.Probe:this._bodyElement.hidden=false;var editorElement=this._bodyElement.appendChild(document.createElement("div"));editorElement.classList.add("breakpoint-action-eval-editor");editorElement.classList.add(WI.SyntaxHighlightedStyleClassName);this._codeMirror=WI.CodeMirrorEditor.create(editorElement,{lineWrapping:true,mode:"text/javascript",matchBrackets:true,value:this._action.data||"",});this._codeMirror.on("viewportChange",this._codeMirrorViewportChanged.bind(this));this._codeMirror.on("change",this._handleJavaScriptCodeMirrorChange.bind(this));this._codeMirrorViewport={from:null,to:null};var completionController=new WI.CodeMirrorCompletionController(this._delegate.breakpointActionViewCodeMirrorCompletionControllerMode(this,this._codeMirror),this._codeMirror);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);if(WI.BreakpointAction.supportsEmulateUserAction())
this._bodyElement.appendChild(createOptionsElements());setTimeout(()=>{this._codeMirror.refresh();if(!omitFocus)
this._codeMirror.focus();},0);break;case WI.BreakpointAction.Type.Sound:this._bodyElement.hidden=true;break;default:this._bodyElement.hidden=true;break;}}
_handleLogInputInput(event)
{this._action.data=event.target.value;}
_handleJavaScriptCodeMirrorChange(event)
{this._action.data=this._codeMirror.getValue().trim();}
_codeMirrorViewportChanged(event,from,to)
{if(this._codeMirrorViewport.from===from&&this._codeMirrorViewport.to===to)
return;this._codeMirrorViewport.from=from;this._codeMirrorViewport.to=to;this._delegate.breakpointActionViewResized(this);}
_handleEmulateUserGestureCheckboxChange(event)
{this._action.emulateUserGesture=this._emulateUserGestureCheckbox.checked;}};WI.BreakpointPopover=class BreakpointPopover extends WI.Popover
{constructor(delegate,breakpoint)
{super(delegate);this._breakpoint=breakpoint||null;this._contentElement=null;this._conditionCodeMirror=null;this._ignoreCountInputElement=null;this._actionsContainerElement=null;this._actionViews=[];this._optionsRowElement=null;this._autoContinueCheckboxElement=null;this._targetElement=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} 
static appendContextMenuItems(contextMenu,breakpoint,targetElement)
{if(breakpoint.editable&&targetElement){contextMenu.appendItem(WI.UIString("Edit Breakpoint\u2026"),()=>{const delegate=null;let popover;if(breakpoint instanceof WI.EventBreakpoint)
popover=new WI.EventBreakpointPopover(delegate,breakpoint);else if(breakpoint instanceof WI.URLBreakpoint)
popover=new WI.URLBreakpointPopover(delegate,breakpoint);else
popover=new WI.BreakpointPopover(delegate,breakpoint);popover.show(targetElement);});}
if(!breakpoint.disabled){contextMenu.appendItem(WI.UIString("Disable Breakpoint"),()=>{breakpoint.disabled=!breakpoint.disabled;});if(breakpoint.editable&&breakpoint.autoContinue){contextMenu.appendItem(WI.UIString("Cancel Automatic Continue"),()=>{breakpoint.autoContinue=!breakpoint.autoContinue;});}}else{contextMenu.appendItem(WI.UIString("Enable Breakpoint"),()=>{breakpoint.disabled=!breakpoint.disabled;});}
if(breakpoint.editable&&!breakpoint.autoContinue&&!breakpoint.disabled&&breakpoint.actions.length){contextMenu.appendItem(WI.UIString("Set to Automatically Continue"),()=>{breakpoint.autoContinue=!breakpoint.autoContinue;});}
if(breakpoint.removable){contextMenu.appendItem(WI.UIString("Delete Breakpoint"),()=>{breakpoint.remove();});}else{contextMenu.appendItem(WI.UIString("Reset Breakpoint","Reset Breakpoint @ Breakpoint Context Menu","Context menu action for resetting the breakpoint to its initial configuration."),()=>{breakpoint.reset();});}
if(breakpoint instanceof WI.JavaScriptBreakpoint&&breakpoint.sourceCodeLocation.hasMappedLocation()){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal in Original Resource"),()=>{const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.showOriginalOrFormattedSourceCodeLocation(breakpoint.sourceCodeLocation,options);});}} 
get breakpoint(){return this._breakpoint;}
show(targetElement)
{this._targetElement=targetElement;this._contentElement=document.createElement("div");this._contentElement.classList.add("edit-breakpoint-popover-content");if(this._breakpoint){let toggleLabelElement=this._contentElement.appendChild(document.createElement("label"));toggleLabelElement.className="toggle";let toggleCheckboxElement=toggleLabelElement.appendChild(document.createElement("input"));toggleCheckboxElement.type="checkbox";toggleCheckboxElement.checked=!this._breakpoint.disabled;toggleCheckboxElement.addEventListener("change",this._handleEnabledCheckboxChange.bind(this));toggleLabelElement.appendChild(document.createTextNode(this._breakpoint.displayName));}
this._tableElement=this._contentElement.appendChild(document.createElement("table"));if(!this._breakpoint)
this.populateContent();if(this._breakpoint?.editable||this.constructor.supportsEditing){let conditionLabelElement=document.createElement("label");conditionLabelElement.textContent=WI.UIString("Condition");let conditionEditorElement=document.createElement("div");conditionEditorElement.classList.add("editor",WI.SyntaxHighlightedStyleClassName);this._conditionCodeMirror=WI.CodeMirrorEditor.create(conditionEditorElement,{extraKeys:{Tab:false},lineWrapping:false,mode:"text/javascript",matchBrackets:true,placeholder:WI.UIString("Conditional expression"),scrollbarStyle:null,value:this._breakpoint?.condition||"",});let conditionCodeMirrorInputField=this._conditionCodeMirror.getInputField();conditionCodeMirrorInputField.id="edit-breakpoint-popover-content-condition";conditionLabelElement.setAttribute("for",conditionCodeMirrorInputField.id);this.addRow("condition",conditionLabelElement,conditionEditorElement);this._conditionCodeMirror.addKeyMap({"Enter":()=>{this.dismiss();},"Esc":()=>{this.dismiss();},});this._conditionCodeMirror.on("beforeChange",this._handleConditionCodeMirrorBeforeChange.bind(this));if(this._breakpoint)
this._conditionCodeMirror.on("change",this._handleConditionCodeMirrorChange.bind(this));let completionController=new WI.CodeMirrorCompletionController(this.codeMirrorCompletionControllerMode,this._conditionCodeMirror,this);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let ignoreCountLabelElement=document.createElement("label");ignoreCountLabelElement.textContent=WI.UIString("Ignore");let ignoreCountContentFragment=document.createDocumentFragment();this._ignoreCountInputElement=ignoreCountContentFragment.appendChild(document.createElement("input"));this._ignoreCountInputElement.id="edit-breakpoint-popover-ignore-count";this._ignoreCountInputElement.type="number";this._ignoreCountInputElement.min=0;this._ignoreCountInputElement.value=this._breakpoint?.ignoreCount||0;this._ignoreCountInputElement.addEventListener("change",this._handleIgnoreCountInputChange.bind(this));this._ignoreCountText=ignoreCountContentFragment.appendChild(document.createElement("label"));this._updateIgnoreCountText();ignoreCountLabelElement.setAttribute("for",this._ignoreCountInputElement.id);this._ignoreCountText.setAttribute("for",this._ignoreCountInputElement.id);this.addRow("ignore-count",ignoreCountLabelElement,ignoreCountContentFragment);let actionsLabelElement=document.createElement("label");actionsLabelElement.textContent=WI.UIString("Action");this._actionsContainerElement=document.createElement("div");if(!this._breakpoint?.actions.length)
this._createAddActionButton();else{this._contentElement.classList.add("wide");for(let i=0;i<this._breakpoint.actions.length;++i){let breakpointActionView=new WI.BreakpointActionView(this._breakpoint.actions[i],this,{omitFocus:true});this._insertBreakpointActionView(breakpointActionView);}}
this.addRow("actions",actionsLabelElement,this._actionsContainerElement);let optionsLabelElement=document.createElement("label");optionsLabelElement.textContent=WI.UIString("Options");let optionsDocumentFragment=document.createDocumentFragment();this._autoContinueCheckboxElement=optionsDocumentFragment.appendChild(document.createElement("input"));this._autoContinueCheckboxElement.id="edit-breakpoint-popover-auto-continue";this._autoContinueCheckboxElement.type="checkbox";this._autoContinueCheckboxElement.checked=this._breakpoint?.autoContinue||false;this._autoContinueCheckboxElement.addEventListener("change",this._handleAutoContinueCheckboxChange.bind(this));let optionsCheckboxLabel=optionsDocumentFragment.appendChild(document.createElement("label"));optionsCheckboxLabel.textContent=WI.UIString("Automatically continue after evaluating");optionsLabelElement.setAttribute("for",this._autoContinueCheckboxElement.id);optionsCheckboxLabel.setAttribute("for",this._autoContinueCheckboxElement.id);this._optionsRowElement=this.addRow("options",optionsLabelElement,optionsDocumentFragment);if(!this._breakpoint?.actions.length)
this._optionsRowElement.classList.add("hidden");setTimeout(()=>{this._conditionCodeMirror.refresh();if(this._breakpoint)
this._conditionCodeMirror.focus();this.update();});}
this._contentElement.appendChild(WI.createReferencePageLink(this._breakpoint?.constructor.ReferencePage||this.constructor.ReferencePage,this._breakpoint?"configuration":""));this.content=this._contentElement;this._presentOverTargetElement();}
dismiss()
{this._breakpoint??=this.createBreakpoint({condition:this._conditionCodeMirror?this._conditionCodeMirror.getValue().trim():"",actions:this._actionViews.map((breakpointActionView)=>breakpointActionView.action),ignoreCount:this._ignoreCountInputElement?this._parseIgnoreCountNumber():0,autoContinue:this._autoContinueCheckboxElement?this._autoContinueCheckboxElement.checked:false,});let emptyActions=this._breakpoint?.actions.filter(function(action){if(action.type===WI.BreakpointAction.Type.Sound)
return false;return!action.data?.trim();})||[];for(let action of emptyActions)
this._breakpoint.removeAction(action);super.dismiss();} 
completionControllerShouldAllowEscapeCompletion()
{return false;} 
breakpointActionViewCodeMirrorCompletionControllerMode(breakpointActionView,codeMirror)
{return this.codeMirrorCompletionControllerMode;}
breakpointActionViewAppendActionView(breakpointActionView,newBreakpointAction)
{this._breakpoint?.addAction(newBreakpointAction,{precedingAction:breakpointActionView.action});let newBreakpointActionView=new WI.BreakpointActionView(newBreakpointAction,this);let index=this._actionViews.indexOf(breakpointActionView)+1;this._insertBreakpointActionView(newBreakpointActionView,index);this._optionsRowElement.classList.remove("hidden");this.update();}
breakpointActionViewRemoveActionView(breakpointActionView)
{this._breakpoint?.removeAction(breakpointActionView.action);breakpointActionView.element.remove();this._actionViews.remove(breakpointActionView);if(!this._actionViews.length){this._createAddActionButton();this._optionsRowElement.classList.add("hidden");this._autoContinueCheckboxElement.checked=false;}
this.update();}
breakpointActionViewResized(breakpointActionView)
{this.update();} 
get codeMirrorCompletionControllerMode()
{if(this._breakpoint===WI.debuggerManager.allExceptionsBreakpoint||this._breakpoint===WI.debuggerManager.uncaughtExceptionsBreakpoint)
return WI.CodeMirrorCompletionController.Mode.ExceptionBreakpoint;return WI.CodeMirrorCompletionController.Mode.Basic;}
populateContent()
{throw WI.NotImplementedError.subclassMustOverride();}
addRow(className,label,content)
{let rowElement=this._tableElement.appendChild(document.createElement("tr"));rowElement.className=className;let headerElement=rowElement.appendChild(document.createElement("th"));headerElement.append(label);let dataElement=rowElement.appendChild(document.createElement("td"));dataElement.append(content);return rowElement;}
createBreakpoint(options={})
{throw WI.NotImplementedError.subclassMustOverride();} 
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);}
_parseIgnoreCountNumber()
{let ignoreCount=0;if(this._ignoreCountInputElement.value){ignoreCount=parseInt(this._ignoreCountInputElement.value,10);if(isNaN(ignoreCount)||ignoreCount<0)
ignoreCount=0;}
return ignoreCount;}
_updateIgnoreCountText()
{if(this._parseIgnoreCountNumber()===1)
this._ignoreCountText.textContent=WI.UIString("time before stopping");else
this._ignoreCountText.textContent=WI.UIString("times before stopping");}
_createAddActionButton()
{this._contentElement.classList.remove("wide");this._actionsContainerElement.removeChildren();let addActionButton=this._actionsContainerElement.appendChild(document.createElement("button"));addActionButton.textContent=WI.UIString("Add Action");addActionButton.addEventListener("click",this._handleAddActionButtonClick.bind(this));}
_insertBreakpointActionView(breakpointActionView,index=this._actionViews.length)
{if(index>=this._actionViews.length){this._actionsContainerElement.appendChild(breakpointActionView.element);this._actionViews.push(breakpointActionView);}else{this._actionsContainerElement.insertBefore(breakpointActionView.element,this._actionViews[index].element);this._actionViews.splice(index,0,breakpointActionView)}}
_handleEnabledCheckboxChange(event)
{this._breakpoint.disabled=!event.target.checked;}
_handleConditionCodeMirrorBeforeChange(codeMirror,change)
{if(change.update){let newText=change.text.join("").replace(/\n/g,"");change.update(change.from,change.to,[newText]);}
return true;}
_handleConditionCodeMirrorChange(codeMirror,change)
{this._breakpoint.condition=this._conditionCodeMirror.getValue().trim();}
_handleIgnoreCountInputChange(event)
{let ignoreCount=this._parseIgnoreCountNumber();this._ignoreCountInputElement.value=ignoreCount;if(this._breakpoint)
this._breakpoint.ignoreCount=ignoreCount;this._updateIgnoreCountText();}
_handleAddActionButtonClick(event)
{this._contentElement.classList.add("wide");this._actionsContainerElement.removeChildren();let action=new WI.BreakpointAction(WI.BreakpointAction.Type.Evaluate);this._breakpoint?.addAction(action);let breakpointActionView=new WI.BreakpointActionView(action,this);this._insertBreakpointActionView(breakpointActionView);this._optionsRowElement.classList.remove("hidden");this.update();}
_handleAutoContinueCheckboxChange(event)
{if(this._breakpoint)
this._breakpoint.autoContinue=this._autoContinueCheckboxElement.checked;}};WI.BreakpointTreeElement=class BreakpointTreeElement extends WI.GeneralTreeElement
{constructor(breakpoint,{classNames,title,subtitle}={})
{if(!Array.isArray(classNames))
classNames=[];classNames.push("breakpoint");super(classNames,title,subtitle,breakpoint);this._breakpoint=breakpoint;this._probeSet=null;this.status=WI.ImageUtilities.useSVGSymbol("Images/Breakpoint.svg");this.status.className="status-image";this.status.addEventListener("mousedown",this._statusImageElementMouseDown.bind(this));this.status.addEventListener("click",this._statusImageElementClicked.bind(this));this.updateStatus();this._iconAnimationLayerElement=document.createElement("span");this.iconElement.appendChild(this._iconAnimationLayerElement);this.tooltipHandledSeparately=true;} 
get breakpoint()
{return this._breakpoint;}
ondelete()
{

this.__deletedViaDeleteKeyboardShortcut=true;if(this._breakpoint.removable){this._breakpoint.remove();return true;}
if(this._breakpoint.disabled)
InspectorFrontendHost.beep();else{this._breakpoint.disabled=true;this._breakpoint.reset();}
return false;}
onenter()
{this._breakpoint.cycleToNextMode();return true;}
onspace()
{this._breakpoint.cycleToNextMode();return true;}
onattach()
{super.onattach();this._breakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this.updateStatus,this);this._breakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this.updateStatus,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this.updateStatus,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);for(var probeSet of WI.debuggerManager.probeSets)
if(probeSet.breakpoint===this._breakpoint)
this._addProbeSet(probeSet);}
ondetach()
{super.ondetach();this._breakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this.updateStatus,this);this._breakpoint.removeEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this.updateStatus,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this.updateStatus,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);if(this._probeSet)
this._removeProbeSet(this._probeSet);}
populateContextMenu(contextMenu,event)
{WI.BreakpointPopover.appendContextMenuItems(contextMenu,this._breakpoint,this.status);super.populateContextMenu(contextMenu,event);} 
updateStatus()
{if(!this.status)
return;this.status.classList.toggle("resolved",this._breakpoint.resolved);this.status.classList.toggle("disabled",this._breakpoint.disabled);if(this._breakpoint.editable)
this.status.classList.toggle("auto-continue",this._breakpoint.autoContinue);} 
_addProbeSet(probeSet)
{this._probeSet=probeSet;probeSet.addEventListener(WI.ProbeSet.Event.SamplesCleared,this._samplesCleared,this);probeSet.dataTable.addEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);}
_removeProbeSet(probeSet)
{probeSet.removeEventListener(WI.ProbeSet.Event.SamplesCleared,this._samplesCleared,this);probeSet.dataTable.removeEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);this._probeSet=null;}
_probeSetAdded(event)
{var probeSet=event.data.probeSet;if(probeSet.breakpoint===this._breakpoint)
this._addProbeSet(probeSet);}
_probeSetRemoved(event)
{var probeSet=event.data.probeSet;if(probeSet.breakpoint===this._breakpoint)
this._removeProbeSet(probeSet);}
_samplesCleared(event)
{var oldTable=event.data.oldTable;oldTable.removeEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);this._probeSet.dataTable.addEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);}
_dataUpdated()
{if(this.element.classList.contains("data-updated")){clearTimeout(this._removeIconAnimationTimeoutIdentifier);this.element.classList.remove("data-updated");window.requestAnimationFrame(this._dataUpdated.bind(this));return;}
this.element.classList.add("data-updated");this._removeIconAnimationTimeoutIdentifier=setTimeout(()=>{this.element.classList.remove("data-updated");},WI.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration);}
_statusImageElementMouseDown(event)
{event.stopPropagation();}
_statusImageElementClicked(event)
{this._breakpoint.cycleToNextMode();}};WI.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration=400;WI.CPUTimelineOverviewGraph=class CPUTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("cpu");this._cpuTimeline=timeline;this._cpuTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);let size=new WI.Size(0,this.height);this._chart=new WI.StackedColumnChart(size);this._chart.initializeSections(["main-thread-usage","worker-thread-usage","total-usage"]);this.addSubview(this._chart);this.element.appendChild(this._chart.element);this._chart.element.addEventListener("click",this._handleChartClick.bind(this));this._legendElement=this.element.appendChild(document.createElement("div"));this._legendElement.classList.add("legend");this._lastSelectedRecordInLayout=null;this.reset();for(let record of this._cpuTimeline.records)
this._processRecord(record);} 
get height()
{return 60;}
reset()
{super.reset();this._maxUsage=0;this._cachedMaxUsage=undefined;this._lastSelectedRecordInLayout=null;this._updateLegend();this._chart.clear();this._chart.needsLayout();}
layout()
{super.layout();if(this.hidden)
return;this._updateLegend();this._chart.clear();let graphWidth=this.timelineOverview.scrollContainerWidth;if(isNaN(graphWidth))
return;this._lastSelectedRecordInLayout=this.selectedRecord;if(this._chart.size.width!==graphWidth||this._chart.size.height!==this.height)
this._chart.size=new WI.Size(graphWidth,this.height);let graphStartTime=this.startTime;let visibleEndTime=Math.min(this.endTime,this.currentTime);let secondsPerPixel=this.timelineOverview.secondsPerPixel;let maxCapacity=Math.max(20,this._maxUsage*1.05);function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
let height=this.height;function yScale(size){return(size/maxCapacity)*height;}
let visibleRecords=this._cpuTimeline.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:true,});if(!visibleRecords.length)
return;const minimumDisplayHeight=4;for(let record of visibleRecords){let additionalClass=record===this.selectedRecord?"selected":undefined;let w=(record.endTime-record.startTime)/secondsPerPixel;let x=xScale(record.startTime);let h1=Math.max(minimumDisplayHeight,yScale(record.mainThreadUsage));let h2=Math.max(minimumDisplayHeight,yScale(record.mainThreadUsage+record.workerThreadUsage));let h3=Math.max(minimumDisplayHeight,yScale(record.usage));this._chart.addColumnSet(x,height,w,[h1,h2,h3],additionalClass);}}
updateSelectedRecord()
{super.updateSelectedRecord();if(this._lastSelectedRecordInLayout!==this.selectedRecord){

this.needsLayout();}} 
_updateLegend()
{if(this._cachedMaxUsage===this._maxUsage)
return;this._cachedMaxUsage=this._maxUsage;if(!this._maxUsage){this._legendElement.hidden=true;this._legendElement.textContent="";}else{this._legendElement.hidden=false;this._legendElement.textContent=WI.UIString("Maximum CPU Usage: %s").format(Number.percentageString(this._maxUsage/100));}}
_graphPositionForMouseEvent(event)
{let elements=document.elementsFromPoint(event.pageX,event.pageY);let rectElement=elements.find((x)=>x.localName==="rect");if(!rectElement)
return NaN;let chartElement=rectElement.closest(".stacked-column-chart");if(!chartElement)
return NaN;let rect=chartElement.getBoundingClientRect();let position=event.pageX-rect.left;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
return rect.width-position;return position;}
_handleChartClick(event)
{let position=this._graphPositionForMouseEvent(event);if(isNaN(position))
return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let graphClickTime=position*secondsPerPixel;let graphStartTime=this.startTime;let clickTime=graphStartTime+graphClickTime;let record=this._cpuTimeline.closestRecordTo(clickTime);if(!record)
return;event.__timelineRecordClickEventHandled=true;this.selectedRecord=record;this.needsLayout();}
_cpuTimelineRecordAdded(event)
{let cpuTimelineRecord=event.data.record;this._processRecord(cpuTimelineRecord);this.needsLayout();}
_processRecord(cpuTimelineRecord)
{this._maxUsage=Math.max(this._maxUsage,cpuTimelineRecord.usage);}};WI.CPUTimelineView=class CPUTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);this._recording=extraArguments.recording;this.element.classList.add("cpu");this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._statisticsData=null;this._secondsPerPixelInLayout=undefined;this._visibleRecordsInLayout=[];this._discontinuitiesInLayout=[];this._stickingOverlay=false;this._overlayRecord=null;this._overlayTime=NaN;timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);} 
static displayNameForSampleType(type)
{switch(type){case CPUTimelineView.SampleType.JavaScript:return WI.UIString("JavaScript");case CPUTimelineView.SampleType.Layout:return WI.repeatedUIString.timelineRecordLayout();case CPUTimelineView.SampleType.Paint:return WI.repeatedUIString.timelineRecordPaint();case CPUTimelineView.SampleType.Style:return WI.UIString("Styles");}
console.error("Unknown sample type",type);}
static get cpuUsageViewHeight(){return 135;}
static get threadCPUUsageViewHeight(){return 65;}
static get indicatorViewHeight(){return 15;}
static get lowEnergyThreshold(){return 3;}
static get mediumEnergyThreshold(){return 30;}
static get highEnergyThreshold(){return 100;}
static get lowEnergyGraphBoundary(){return 10;}
static get mediumEnergyGraphBoundary(){return 70;}
static get highEnergyGraphBoundary(){return 100;}
static get defaultSectionLimit(){return 5;} 
attached()
{super.attached();this._timelineRuler?.needsLayout(WI.View.LayoutReason.Resize);}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);}
reset()
{super.reset();this._resetSourcesFilters();this.clear();}
clear()
{if(!this.didInitialLayout)
return;this._breakdownChart.clear();this._breakdownChart.needsLayout();this._clearBreakdownLegend();this._energyChart.clear();this._energyChart.needsLayout();this._clearEnergyImpactText();this._clearStatistics();this._clearSources();function clearUsageView(view){view.clear();let markersElement=view.chart.element.querySelector(".markers");if(markersElement)
markersElement.remove();}
clearUsageView(this._cpuUsageView);clearUsageView(this._mainThreadUsageView);clearUsageView(this._webkitThreadUsageView);clearUsageView(this._unknownThreadUsageView);this._removeWorkerThreadViews();this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._statisticsData=null;this._secondsPerPixelInLayout=undefined;this._visibleRecordsInLayout=[];this._discontinuitiesInLayout=[];this._stickingOverlay=false;this._hideGraphOverlay();} 
get showsFilterBar(){return false;}
get scrollableElements()
{return[this.element];}
initialLayout()
{this.element.style.setProperty("--cpu-usage-combined-view-height",CPUTimelineView.cpuUsageViewHeight+"px");this.element.style.setProperty("--cpu-usage-view-height",CPUTimelineView.threadCPUUsageViewHeight+"px");this.element.style.setProperty("--cpu-usage-indicator-view-height",CPUTimelineView.indicatorViewHeight+"px");let contentElement=this.element.appendChild(document.createElement("div"));contentElement.classList.add("content");let overviewElement=contentElement.appendChild(document.createElement("div"));overviewElement.classList.add("overview");function createChartContainer(parentElement,subtitle,tooltip){let chartElement=parentElement.appendChild(document.createElement("div"));chartElement.classList.add("chart");let chartSubtitleElement=chartElement.appendChild(document.createElement("div"));chartSubtitleElement.classList.add("subtitle");chartSubtitleElement.textContent=subtitle;if(tooltip)
chartSubtitleElement.title=tooltip;let chartFlexContainerElement=chartElement.appendChild(document.createElement("div"));chartFlexContainerElement.classList.add("container");return chartFlexContainerElement;}
function appendLegendRow(legendElement,sampleType){let rowElement=legendElement.appendChild(document.createElement("div"));rowElement.classList.add("row");let swatchElement=rowElement.appendChild(document.createElement("div"));swatchElement.classList.add("swatch",sampleType);let valueContainer=rowElement.appendChild(document.createElement("div"));let labelElement=valueContainer.appendChild(document.createElement("div"));labelElement.classList.add("label");labelElement.textContent=WI.CPUTimelineView.displayNameForSampleType(sampleType);let sizeElement=valueContainer.appendChild(document.createElement("div"));sizeElement.classList.add("size");return sizeElement;}
let breakdownChartContainerElement=createChartContainer(overviewElement,WI.UIString("Main Thread"),WI.UIString("Breakdown of time spent on the main thread"));this._breakdownChart=new WI.CircleChart({size:120,innerRadiusRatio:0.5});this._breakdownChart.segments=Object.values(WI.CPUTimelineView.SampleType);this.addSubview(this._breakdownChart);breakdownChartContainerElement.appendChild(this._breakdownChart.element);this._breakdownLegendElement=breakdownChartContainerElement.appendChild(document.createElement("div"));this._breakdownLegendElement.classList.add("legend");this._breakdownLegendScriptElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.JavaScript);this._breakdownLegendLayoutElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Layout);this._breakdownLegendPaintElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Paint);this._breakdownLegendStyleElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Style);let dividerElement=overviewElement.appendChild(document.createElement("div"));dividerElement.classList.add("divider");let energyContainerElement=createChartContainer(overviewElement,WI.UIString("Energy Impact"),WI.UIString("Estimated energy impact."));energyContainerElement.classList.add("energy");let energyChartElement=energyContainerElement.parentElement;let energySubtitleElement=energyChartElement.firstChild;let energyInfoElement=energySubtitleElement.appendChild(document.createElement("span"));energyInfoElement.classList.add("info",WI.Popover.IgnoreAutoDismissClassName);energyInfoElement.textContent="?";this._energyInfoPopover=null;this._energyInfoPopoverContentElement=null;energyInfoElement.addEventListener("click",(event)=>{if(!this._energyInfoPopover)
this._energyInfoPopover=new WI.Popover;if(!this._energyInfoPopoverContentElement){this._energyInfoPopoverContentElement=document.createElement("div");this._energyInfoPopoverContentElement.className="energy-info-popover-content";const precision=0;let lowPercent=Number.percentageString(CPUTimelineView.lowEnergyThreshold/100,precision);let p1=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p1.textContent=WI.UIString("Periods of high CPU utilization will rapidly drain battery. Strive to keep idle pages under %s average CPU utilization.").format(lowPercent);let p2=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p2.textContent=WI.UIString("There is an incurred energy penalty each time the page enters script. This commonly happens with timers, event handlers, and observers.");let p3=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p3.textContent=WI.UIString("To improve CPU utilization reduce or batch workloads when the page is not visible or during times when the page is not being interacted with.");}
let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let preferredEdges=isRTL?[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_X]:[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];let calculateTargetFrame=()=>WI.Rect.rectFromClientRect(energyInfoElement.getBoundingClientRect()).pad(3);this._energyInfoPopover.presentNewContentWithFrame(this._energyInfoPopoverContentElement,calculateTargetFrame(),preferredEdges);this._energyInfoPopover.windowResizeHandler=()=>{this._energyInfoPopover.present(calculateTargetFrame(),preferredEdges);};});this._energyChart=new WI.GaugeChart({height:110,strokeWidth:20,segments:[{className:"low",limit:CPUTimelineView.lowEnergyGraphBoundary},{className:"medium",limit:CPUTimelineView.mediumEnergyGraphBoundary},{className:"high",limit:CPUTimelineView.highEnergyGraphBoundary},]});this.addSubview(this._energyChart);energyContainerElement.appendChild(this._energyChart.element);let energyTextContainerElement=energyContainerElement.appendChild(document.createElement("div"));this._energyImpactLabelElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactLabelElement.className="energy-impact";this._energyImpactNumberElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactNumberElement.className="energy-impact-number";this._energyImpactDurationElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactDurationElement.className="energy-impact-number";let detailsContainerElement=contentElement.appendChild(document.createElement("div"));detailsContainerElement.classList.add("details");this._timelineRuler=new WI.TimelineRuler;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;this.addSubview(this._timelineRuler);detailsContainerElement.appendChild(this._timelineRuler.element);
this._timelineRuler.updateLayout(WI.View.LayoutReason.Resize);let detailsSubtitleElement=detailsContainerElement.appendChild(document.createElement("div"));detailsSubtitleElement.classList.add("subtitle");detailsSubtitleElement.textContent=WI.UIString("CPU Usage");this._cpuUsageView=new WI.CPUUsageCombinedView(WI.UIString("Total"));this.addSubview(this._cpuUsageView);detailsContainerElement.appendChild(this._cpuUsageView.element);this._cpuUsageView.rangeChart.element.addEventListener("click",this._handleIndicatorClick.bind(this));this._threadsDetailsElement=detailsContainerElement.appendChild(document.createElement("details"));this._threadsDetailsElement.open=WI.settings.cpuTimelineThreadDetailsExpanded.value;this._threadsDetailsElement.addEventListener("toggle",(event)=>{WI.settings.cpuTimelineThreadDetailsExpanded.value=this._threadsDetailsElement.open;if(this._threadsDetailsElement.open)
this.updateLayout(WI.CPUTimelineView.LayoutReason.Internal);});let threadsSubtitleElement=this._threadsDetailsElement.appendChild(document.createElement("summary"));threadsSubtitleElement.classList.add("subtitle","threads","expandable");threadsSubtitleElement.textContent=WI.UIString("Threads");this._mainThreadUsageView=new WI.CPUUsageView(WI.UIString("Main Thread"));this._mainThreadUsageView.element.classList.add("main-thread");this.addSubview(this._mainThreadUsageView);this._threadsDetailsElement.appendChild(this._mainThreadUsageView.element);this._webkitThreadUsageView=new WI.CPUUsageView(WI.UIString("WebKit Threads"));this.addSubview(this._webkitThreadUsageView);this._threadsDetailsElement.appendChild(this._webkitThreadUsageView.element);this._unknownThreadUsageView=new WI.CPUUsageView(WI.UIString("Other Threads"));this.addSubview(this._unknownThreadUsageView);this._threadsDetailsElement.appendChild(this._unknownThreadUsageView.element);this._workerViews=[];this._sourcesFilter={timer:new Set,event:new Set,observer:new Set,};let bottomOverviewElement=contentElement.appendChild(document.createElement("div"));bottomOverviewElement.classList.add("overview");let statisticsContainerElement=createChartContainer(bottomOverviewElement,WI.UIString("Statistics"));statisticsContainerElement.classList.add("stats");this._statisticsTable=statisticsContainerElement.appendChild(document.createElement("table"));this._statisticsRows=[];{let{headerCell,numberCell}=this._createTableRow(this._statisticsTable);headerCell.textContent=WI.UIString("Network Requests:");this._networkRequestsNumberElement=numberCell;}
{let{headerCell,numberCell}=this._createTableRow(this._statisticsTable);headerCell.textContent=WI.UIString("Script Entries:");this._scriptEntriesNumberElement=numberCell;}
this._clearStatistics();let bottomDividerElement=bottomOverviewElement.appendChild(document.createElement("div"));bottomDividerElement.classList.add("divider");let sourcesContainerElement=createChartContainer(bottomOverviewElement,WI.UIString("Sources"));sourcesContainerElement.classList.add("stats");this._sourcesTable=sourcesContainerElement.appendChild(document.createElement("table"));this._sourcesRows=[];{let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Filter:");this._sourcesFilterRow=row;this._sourcesFilterRow.hidden=true;this._sourcesFilterNumberElement=numberCell;this._sourcesFilterLabelElement=labelCell;let filterClearElement=numberCell.appendChild(document.createElement("span"));filterClearElement.className="filter-clear";filterClearElement.textContent=multiplicationSign;filterClearElement.addEventListener("click",(event)=>{this._resetSourcesFilters();this._layoutStatisticsAndSources();});}
{let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Timers:");this._timerInstallationsRow=row;this._timerInstallationsNumberElement=numberCell;this._timerInstallationsLabelElement=labelCell;}
{let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Event Handlers:");this._eventHandlersRow=row;this._eventHandlersNumberElement=numberCell;this._eventHandlersLabelElement=labelCell;}
{let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Observer Handlers:");this._observerHandlersRow=row;this._observerHandlersNumberElement=numberCell;this._observerHandlersLabelElement=labelCell;}
this._clearSources();this.element.addEventListener("click",this._handleGraphClick.bind(this));this.element.addEventListener("mousemove",this._handleGraphMouseMove.bind(this));this._overlayMarker=new WI.TimelineMarker(-1,WI.TimelineMarker.Type.TimeStamp);this._timelineRuler.addMarker(this._overlayMarker);}
layout()
{if(this.layoutReason===WI.View.LayoutReason.Resize)
return;if(this.layoutReason!==WI.CPUTimelineView.LayoutReason.Internal)
this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;let secondsPerPixel=this._timelineRuler.secondsPerPixel;if(!secondsPerPixel)
return;let graphStartTime=this.startTime;let graphEndTime=this.endTime;let visibleEndTime=Math.min(this.endTime,this.currentTime)||this.endTime;let visibleDuration=visibleEndTime-graphStartTime;let discontinuities=this._recording.discontinuitiesInTimeRange(graphStartTime,visibleEndTime);let originalDiscontinuities=discontinuities.slice();let visibleRecords=this.representedObject.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:!discontinuities.length||discontinuities[0].startTime>graphStartTime,includeRecordAfterEnd:true,});if(!visibleRecords.length||(visibleRecords.length===1&&visibleRecords[0].endTime<graphStartTime)){this.clear();return;}
this._secondsPerPixelInLayout=secondsPerPixel;this._visibleRecordsInLayout=visibleRecords;this._discontinuitiesInLayout=discontinuities.slice();this._statisticsData=this._computeStatisticsData(graphStartTime,visibleEndTime);this._layoutBreakdownChart();this._layoutStatisticsAndSources();let dataPoints=[];let workersDataMap=new Map;let workersSeenInCurrentRecord=new Set;let max=-Infinity;let mainThreadMax=-Infinity;let webkitThreadMax=-Infinity;let unknownThreadMax=-Infinity;let workerMax=-Infinity;let min=Infinity;let mainThreadMin=Infinity;let webkitThreadMin=Infinity;let unknownThreadMin=Infinity;let average=0;let mainThreadAverage=0;let webkitThreadAverage=0;let unknownThreadAverage=0;for(let record of visibleRecords){let time=record.timestamp;let{usage,mainThreadUsage,workerThreadUsage,webkitThreadUsage,unknownThreadUsage}=record;if(discontinuities.length&&discontinuities[0].endTime<=time){let startDiscontinuity=discontinuities.shift();let endDiscontinuity=startDiscontinuity;while(discontinuities.length&&discontinuities[0].endTime<=time)
endDiscontinuity=discontinuities.shift();if(dataPoints.length){let previousDataPoint=dataPoints.lastValue;dataPoints.push({time:startDiscontinuity.startTime,mainThreadUsage:previousDataPoint.mainThreadUsage,workerThreadUsage:previousDataPoint.workerThreadUsage,webkitThreadUsage:previousDataPoint.webkitThreadUsage,unknownThreadUsage:previousDataPoint.unknownThreadUsage,usage:previousDataPoint.usage,});}
dataPoints.push({time:startDiscontinuity.startTime,mainThreadUsage:0,workerThreadUsage:0,webkitThreadUsage:0,unknownThreadUsage:0,usage:0});dataPoints.push({time:endDiscontinuity.endTime,mainThreadUsage:0,workerThreadUsage:0,webkitThreadUsage:0,unknownThreadUsage:0,usage:0});dataPoints.push({time:endDiscontinuity.endTime,mainThreadUsage,workerThreadUsage,webkitThreadUsage,unknownThreadUsage,usage});}
dataPoints.push({time,mainThreadUsage,workerThreadUsage,webkitThreadUsage,unknownThreadUsage,usage});max=Math.max(max,usage);mainThreadMax=Math.max(mainThreadMax,mainThreadUsage);webkitThreadMax=Math.max(webkitThreadMax,webkitThreadUsage);unknownThreadMax=Math.max(unknownThreadMax,unknownThreadUsage);min=Math.min(min,usage);mainThreadMin=Math.min(mainThreadMin,mainThreadUsage);webkitThreadMin=Math.min(webkitThreadMin,webkitThreadUsage);unknownThreadMin=Math.min(unknownThreadMin,unknownThreadUsage);average+=usage;mainThreadAverage+=mainThreadUsage;webkitThreadAverage+=webkitThreadUsage;unknownThreadAverage+=unknownThreadUsage;let workersSeenInLastRecord=workersSeenInCurrentRecord;workersSeenInCurrentRecord=new Set;if(record.workersData&&record.workersData.length){for(let{targetId,usage}of record.workersData){workersSeenInCurrentRecord.add(targetId);let workerData=workersDataMap.get(targetId);if(!workerData){workerData={discontinuities:originalDiscontinuities.slice(),recordsCount:0,dataPoints:[],min:Infinity,max:-Infinity,average:0};while(workerData.discontinuities.length&&workerData.discontinuities[0].endTime<=graphStartTime)
workerData.discontinuities.shift();workerData.dataPoints.push({time:graphStartTime,usage:0});workerData.dataPoints.push({time,usage:0});workersDataMap.set(targetId,workerData);}
if(workerData.discontinuities.length&&workerData.discontinuities[0].endTime<time){let startDiscontinuity=workerData.discontinuities.shift();let endDiscontinuity=startDiscontinuity;while(workerData.discontinuities.length&&workerData.discontinuities[0].endTime<time)
endDiscontinuity=workerData.discontinuities.shift();if(workerData.dataPoints.length){let previousDataPoint=workerData.dataPoints.lastValue;workerData.dataPoints.push({time:startDiscontinuity.startTime,usage:previousDataPoint.usage});}
workerData.dataPoints.push({time:startDiscontinuity.startTime,usage:0});workerData.dataPoints.push({time:endDiscontinuity.endTime,usage:0});workerData.dataPoints.push({time:endDiscontinuity.endTime,usage});}
workerData.dataPoints.push({time,usage});workerData.recordsCount+=1;workerData.max=Math.max(workerData.max,usage);workerData.min=Math.min(workerData.min,usage);workerData.average+=usage;}}
if(workersSeenInLastRecord.size){let deadWorkers=workersSeenInLastRecord.difference(workersSeenInCurrentRecord);for(let workerId of deadWorkers){let workerData=workersDataMap.get(workerId);if(workerData.dataPoints.lastValue.usage!==0)
workerData.dataPoints.push({time,usage:0});}}}
average/=visibleRecords.length;mainThreadAverage/=visibleRecords.length;webkitThreadAverage/=visibleRecords.length;unknownThreadAverage/=visibleRecords.length;for(let[workerId,workerData]of workersDataMap){workerData.average=workerData.average/workerData.recordsCount;if(workerData.max>workerMax)
workerMax=workerData.max;}

if(discontinuities.length)
visibleEndTime=discontinuities[0].startTime;function bestThreadLayoutMax(value){if(value>100)
return Math.ceil(value);return(Math.floor(value/25)+1)*25;}
function removeGreaterThan(arr,max){return arr.filter((x)=>x<=max);}
function markerValuesForMaxValue(max){if(max<1)
return[0.5];if(max<7)
return removeGreaterThan([1,3,5],max);if(max<12.5)
return removeGreaterThan([5,10],max);if(max<20)
return removeGreaterThan([5,10,15],max);if(max<30)
return removeGreaterThan([10,20,30],max);if(max<50)
return removeGreaterThan([15,30,45],max);if(max<100)
return removeGreaterThan([25,50,75],max);if(max<200)
return removeGreaterThan([50,100,150],max);if(max>=200){let hundreds=Math.floor(max/100);let even=(hundreds%2)===0;if(even){let top=hundreds*100;let bottom=top/2;return[bottom,top];}
let top=hundreds*100;let bottom=100;let mid=(top+bottom)/2;return[bottom,mid,top];}}
function layoutView(view,property,graphHeight,layoutMax,{dataPoints,min,max,average}){if(min===Infinity)
min=0;if(max===-Infinity)
max=0;if(layoutMax===-Infinity)
layoutMax=0;let isAllThreadsGraph=property===null;let graphMax=layoutMax*1.05;function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
let size=new WI.Size(xScale(graphEndTime),graphHeight);function yScale(value){return size.height-((value/graphMax)*size.height);}
view.updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale,property);let markersElement=view.chart.element.querySelector(".markers");if(!markersElement){markersElement=view.chart.element.appendChild(document.createElement("div"));markersElement.className="markers";}
markersElement.removeChildren();let markerValues;if(isAllThreadsGraph)
markerValues=markerValuesForMaxValue(max);else{const minimumMarkerTextHeight=17;let percentPerPixel=1/(graphHeight/layoutMax);if(layoutMax<5){let minimumDisplayablePercentByTwo=Math.ceil((minimumMarkerTextHeight*percentPerPixel)/2)*2;markerValues=[Math.max(minimumDisplayablePercentByTwo,Math.floor(max))];}else{let minimumDisplayablePercentByFive=Math.ceil((minimumMarkerTextHeight*percentPerPixel)/5)*5;markerValues=[Math.max(minimumDisplayablePercentByFive,Math.floor(max))];}}
for(let value of markerValues){let marginTop=yScale(value);let markerElement=markersElement.appendChild(document.createElement("div"));markerElement.style.marginTop=marginTop.toFixed(2)+"px";let labelElement=markerElement.appendChild(document.createElement("span"));labelElement.classList.add("label");const precision=0;labelElement.innerText=Number.percentageString(value/100,precision);}}
this._layoutMax=max;this._threadLayoutMax=bestThreadLayoutMax(Math.max(mainThreadMax,webkitThreadMax,unknownThreadMax,workerMax));layoutView(this._cpuUsageView,null,CPUTimelineView.cpuUsageViewHeight,this._layoutMax,{dataPoints,min,max,average});if(this._threadsDetailsElement.open){layoutView(this._mainThreadUsageView,"mainThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:mainThreadMin,max:mainThreadMax,average:mainThreadAverage});layoutView(this._webkitThreadUsageView,"webkitThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:webkitThreadMin,max:webkitThreadMax,average:webkitThreadAverage});layoutView(this._unknownThreadUsageView,"unknownThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:unknownThreadMin,max:unknownThreadMax,average:unknownThreadAverage});this._removeWorkerThreadViews();for(let[workerId,workerData]of workersDataMap){let worker=WI.targetManager.targetForIdentifier(workerId);let displayName=worker?worker.displayName:WI.UIString("Worker Thread");let workerView=new WI.CPUUsageView(displayName);workerView.element.classList.add("worker-thread");workerView.__workerId=workerId;this.addSubview(workerView);this._threadsDetailsElement.insertBefore(workerView.element,this._webkitThreadUsageView.element);this._workerViews.push(workerView);layoutView(workerView,"usage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints:workerData.dataPoints,min:workerData.min,max:workerData.max,average:workerData.average});}}
function xScaleIndicatorRange(sampleIndex){return(sampleIndex/1000)/secondsPerPixel;}
let graphWidth=(graphEndTime-graphStartTime)/secondsPerPixel;let size=new WI.Size(graphWidth,CPUTimelineView.indicatorViewHeight);this._cpuUsageView.updateMainThreadIndicator(this._statisticsData.samples,size,visibleEndTime,xScaleIndicatorRange);this._layoutEnergyChart(average,visibleDuration);this._updateGraphOverlay();} 
_layoutBreakdownChart()
{let{samples,samplesScript,samplesLayout,samplesPaint,samplesStyle,samplesIdle}=this._statisticsData;let nonIdleSamplesCount=samples.length-samplesIdle;if(!nonIdleSamplesCount){this._breakdownChart.clear();this._breakdownChart.needsLayout();this._clearBreakdownLegend();return;}
let percentScript=samplesScript/nonIdleSamplesCount;let percentLayout=samplesLayout/nonIdleSamplesCount;let percentPaint=samplesPaint/nonIdleSamplesCount;let percentStyle=samplesStyle/nonIdleSamplesCount;this._breakdownLegendScriptElement.textContent=`${Number.percentageString(percentScript)} (${samplesScript})`;this._breakdownLegendLayoutElement.textContent=`${Number.percentageString(percentLayout)} (${samplesLayout})`;this._breakdownLegendPaintElement.textContent=`${Number.percentageString(percentPaint)} (${samplesPaint})`;this._breakdownLegendStyleElement.textContent=`${Number.percentageString(percentStyle)} (${samplesStyle})`;this._breakdownChart.values=[percentScript*100,percentLayout*100,percentPaint*100,percentStyle*100];this._breakdownChart.needsLayout();let centerElement=this._breakdownChart.centerElement;let samplesElement=centerElement.firstChild;if(!samplesElement){samplesElement=centerElement.appendChild(document.createElement("div"));samplesElement.classList.add("samples");samplesElement.title=WI.UIString("Time spent on the main thread");}
let millisecondsStringNoDecimal=WI.UIString("%.0fms").format(nonIdleSamplesCount);samplesElement.textContent=millisecondsStringNoDecimal;}
_layoutStatisticsAndSources()
{this._layoutStatisticsSection();this._layoutSourcesSection();}
_layoutStatisticsSection()
{let statistics=this._statisticsData;this._clearStatistics();this._networkRequestsNumberElement.textContent=statistics.networkRequests;this._scriptEntriesNumberElement.textContent=statistics.scriptEntries;let createFilterElement=(type,name)=>{let span=document.createElement("span");span.className="filter";span.textContent=name;span.addEventListener("mouseup",(event)=>{if(span.classList.contains("active"))
this._removeSourcesFilter(type,name);else
this._addSourcesFilter(type,name);this._layoutStatisticsAndSources();});span.classList.toggle("active",this._sourcesFilter[type].has(name));return span;};let expandAllSections=()=>{this._sectionLimit=Infinity;this._layoutStatisticsAndSources();};function createEllipsisElement(){let span=document.createElement("span");span.className="show-more";span.role="button";span.textContent=ellipsis;span.addEventListener("click",(event)=>{expandAllSections();});return span;}
function sortMapByEntryCount(map){let entries=Array.from(map);entries.sort((entryA,entryB)=>entryB[1]-entryA[1]);return new Map(entries);}
if(statistics.timerTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.timerTypes);for(let[timerType,count]of sorted){let headerValue=i===0?WI.UIString("Timers:"):"";let timerTypeElement=createFilterElement("timer",timerType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:timerTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}}
if(statistics.eventTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.eventTypes);for(let[eventType,count]of sorted){let headerValue=i===0?WI.UIString("Events:"):"";let eventTypeElement=createFilterElement("event",eventType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:eventTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}}
if(statistics.observerTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.observerTypes);for(let[observerType,count]of sorted){let headerValue=i===0?WI.UIString("Observers:"):"";let observerTypeElement=createFilterElement("observer",observerType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:observerTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}}}
_layoutSourcesSection()
{let statistics=this._statisticsData;this._clearSources();const unknownLocationKey="unknown";function keyForSourceCodeLocation(sourceCodeLocation){if(!sourceCodeLocation)
return unknownLocationKey;return sourceCodeLocation.sourceCode.url+":"+sourceCodeLocation.lineNumber+":"+sourceCodeLocation.columnNumber;}
function labelForLocation(key,sourceCodeLocation,functionName){if(key===unknownLocationKey){let span=document.createElement("span");span.className="unknown";span.textContent=WI.UIString("Unknown Location");return span;}
const options={nameStyle:WI.SourceCodeLocation.NameStyle.Short,columnStyle:WI.SourceCodeLocation.ColumnStyle.Shown,dontFloat:true,ignoreNetworkTab:true,ignoreSearchTab:true,};return WI.createSourceCodeLocationLink(sourceCodeLocation,options);}
let timerFilters=this._sourcesFilter.timer;let eventFilters=this._sourcesFilter.event;let observerFilters=this._sourcesFilter.observer;let hasFilters=(timerFilters.size||eventFilters.size||observerFilters.size);let sectionLimit=this._sectionLimit;if(isFinite(sectionLimit)&&hasFilters)
sectionLimit=CPUTimelineView.defaultSectionLimit*2;let expandAllSections=()=>{this._sectionLimit=Infinity;this._layoutStatisticsAndSources();};function createEllipsisElement(){let span=document.createElement("span");span.className="show-more";span.role="button";span.textContent=ellipsis;span.addEventListener("click",(event)=>{expandAllSections();});return span;}
let timerMap=new Map;let eventHandlerMap=new Map;let observerCallbackMap=new Map;let seenTimers=new Set;if(!hasFilters||timerFilters.size){for(let record of statistics.timerInstallationRecords){if(timerFilters.size){if(record.eventType===WI.ScriptTimelineRecord.EventType.AnimationFrameRequested&&!timerFilters.has("requestAnimationFrame"))
continue;if(record.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled&&!timerFilters.has("setTimeout"))
continue;}
let callFrame=record.initiatorCallFrame;let sourceCodeLocation=callFrame?callFrame.sourceCodeLocation:record.sourceCodeLocation;let functionName=callFrame?callFrame.functionName:"";let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=timerMap.getOrInitialize(key,{sourceCodeLocation,functionName,count:0,repeating:false});if(record.details){let timerIdentifier=record.details.timerId;let repeatingEntry=statistics.repeatingTimers.get(timerIdentifier);let count=repeatingEntry?repeatingEntry.count:1;entry.count+=count;if(record.details.repeating)
entry.repeating=true;seenTimers.add(timerIdentifier);}else
entry.count+=1;}
if(!hasFilters||timerFilters.has("setTimeout")){for(let[timerId,repeatingEntry]of statistics.repeatingTimers){if(seenTimers.has(timerId))
continue;

let sourceCodeLocation=repeatingEntry.record.sourceCodeLocation;let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=timerMap.getOrInitialize(key,{sourceCodeLocation,count:0,repeating:false});entry.count+=repeatingEntry.count;entry.repeating=true;}}}
if(!hasFilters||eventFilters.size){for(let record of statistics.eventHandlerRecords){if(eventFilters.size&&!eventFilters.has(record.details))
continue;let sourceCodeLocation=record.sourceCodeLocation;let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=eventHandlerMap.getOrInitialize(key,{sourceCodeLocation,count:0});entry.count+=1;}}
if(!hasFilters||observerFilters.size){for(let record of statistics.observerCallbackRecords){if(observerFilters.size&&!observerFilters.has(record.details))
continue;let sourceCodeLocation=record.sourceCodeLocation;let key=keyForSourceCodeLocation(record.sourceCodeLocation);let entry=observerCallbackMap.getOrInitialize(key,{sourceCodeLocation,count:0});entry.count+=1;}}
const headerValue="";function sortMapByEntryCountProperty(map){let entries=Array.from(map);entries.sort((entryA,entryB)=>entryB[1].count-entryA[1].count);return new Map(entries);}
if(timerMap.size){let i=0;let sorted=sortMapByEntryCountProperty(timerMap);for(let[key,entry]of sorted){let numberValue=entry.repeating?WI.UIString("~%s","Approximate Number","Approximate count of events").format(entry.count):entry.count;let sourceCodeLocation=entry.callFrame?entry.callFrame.sourceCodeLocation:entry.sourceCodeLocation;let labelValue=labelForLocation(key,sourceCodeLocation);let followingRow=this._eventHandlersRow;let row;if(i===0){row=this._timerInstallationsRow;this._timerInstallationsNumberElement.textContent=numberValue;this._timerInstallationsLabelElement.append(labelValue);}else
row=this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue,followingRow});if(entry.functionName)
row.querySelector(".label").append(` ${enDash} ${entry.functionName}`);if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement(),followingRow});break;}}}
if(eventHandlerMap.size){let i=0;let sorted=sortMapByEntryCountProperty(eventHandlerMap);for(let[key,entry]of sorted){let numberValue=entry.count;let labelValue=labelForLocation(key,entry.sourceCodeLocation);let followingRow=this._observerHandlersRow;if(i===0){this._eventHandlersNumberElement.textContent=numberValue;this._eventHandlersLabelElement.append(labelValue);}else
this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue,followingRow});if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement(),followingRow});break;}}}
if(observerCallbackMap.size){let i=0;let sorted=sortMapByEntryCountProperty(observerCallbackMap);for(let[key,entry]of sorted){let numberValue=entry.count;let labelValue=labelForLocation(key,entry.sourceCodeLocation);if(i===0){this._observerHandlersNumberElement.textContent=numberValue;this._observerHandlersLabelElement.append(labelValue);}else
this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue});if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement()});break;}}}}
_layoutEnergyChart(average,visibleDuration)
{function mapWithBias(value,rangeLow,rangeHigh,outputRangeLow,outputRangeHigh,bias){let percentInRange=(value-rangeLow)/(rangeHigh-rangeLow);let skewedPercent=Math.pow(percentInRange,bias);let valueInOutputRange=(skewedPercent*(outputRangeHigh-outputRangeLow))+outputRangeLow;return valueInOutputRange;}
this._clearEnergyImpactText();if(average<=CPUTimelineView.lowEnergyThreshold){this._energyImpactLabelElement.textContent=WI.UIString("Low","Low @ Timeline Energy Impact","Energy Impact: Low");this._energyImpactLabelElement.classList.add("low");this._energyChart.value=mapWithBias(average,0,CPUTimelineView.lowEnergyThreshold,0,CPUTimelineView.lowEnergyGraphBoundary,0.85);}else if(average<=CPUTimelineView.mediumEnergyThreshold){this._energyImpactLabelElement.textContent=WI.UIString("Medium","Medium @ Timeline Energy Impact","Energy Impact: Medium")
this._energyImpactLabelElement.classList.add("medium");this._energyChart.value=mapWithBias(average,CPUTimelineView.lowEnergyThreshold,CPUTimelineView.mediumEnergyThreshold,CPUTimelineView.lowEnergyGraphBoundary,CPUTimelineView.mediumEnergyGraphBoundary,0.6);}else if(average<CPUTimelineView.highEnergyThreshold){this._energyImpactLabelElement.textContent=WI.UIString("High","High @ Timeline Energy Impact","Energy Impact: High")
this._energyImpactLabelElement.classList.add("high");this._energyChart.value=mapWithBias(average,CPUTimelineView.mediumEnergyThreshold,CPUTimelineView.highEnergyThreshold,CPUTimelineView.mediumEnergyGraphBoundary,CPUTimelineView.highEnergyGraphBoundary,0.9);}else{this._energyImpactLabelElement.textContent=WI.UIString("Very High","Very High @ Timeline Energy Impact","Energy Impact: Very High")
this._energyImpactLabelElement.classList.add("high");this._energyChart.value=100;}
this._energyChart.needsLayout();this._energyImpactNumberElement.textContent=WI.UIString("Average CPU: %s").format(Number.percentageString(average/100));if(visibleDuration<5)
this._energyImpactDurationElement.textContent=WI.UIString("Duration: Short");else{let durationDisplayString=Math.floor(visibleDuration);this._energyImpactDurationElement.textContent=WI.UIString("Duration: %ss","The duration of the Timeline recording in seconds (s).").format(durationDisplayString);}}
_computeStatisticsData(startTime,endTime)
{







function incrementTypeCount(map,key){let entry=map.get(key);if(entry)
map.set(key,entry+1);else
map.set(key,1);}
let timerInstallationRecords=[];let eventHandlerRecords=[];let observerCallbackRecords=[];let scriptEntries=0;let timerTypes=new Map;let eventTypes=new Map;let observerTypes=new Map;let repeatingTimers=new Map;let possibleRepeatingTimers=new Set;let scriptTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Script);let scriptRecords=scriptTimeline?scriptTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];scriptRecords=scriptRecords.filter((record)=>{switch(record.eventType){case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.ObserverCallback:incrementTypeCount(observerTypes,record.details);observerCallbackRecords.push(record);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.EventDispatched:incrementTypeCount(eventTypes,record.details);eventHandlerRecords.push(record);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:
return true;case WI.ScriptTimelineRecord.EventType.TimerFired:incrementTypeCount(timerTypes,"setTimeout");if(possibleRepeatingTimers.has(record.details)){let entry=repeatingTimers.get(record.details);if(entry)
entry.count+=1;else
repeatingTimers.set(record.details,{record,count:1});}else
possibleRepeatingTimers.add(record.details);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:incrementTypeCount(timerTypes,"requestAnimationFrame");scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.TimerInstalled:timerInstallationRecords.push(record);return false;case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:case WI.ScriptTimelineRecord.EventType.TimerRemoved:case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:case WI.ScriptTimelineRecord.EventType.GarbageCollected:return false;default:console.error("Unhandled ScriptTimelineRecord.EventType",record.eventType);return false;}});let layoutTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Layout);let layoutRecords=layoutTimeline?layoutTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];layoutRecords=layoutRecords.filter((record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return true;case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.InvalidateLayout:return false;default:console.error("Unhandled LayoutTimelineRecord.EventType",record.eventType);return false;}});let networkTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Network);let networkRecords=networkTimeline?networkTimeline.recordsInTimeRange(startTime,endTime):[];let networkRequests=networkRecords.length;let millisecondStartTime=Math.round(startTime*1000);let millisecondEndTime=Math.round(endTime*1000);let millisecondDuration=millisecondEndTime-millisecondStartTime;let samples=new Array(millisecondDuration);function markRecordEntries(records,callback){for(let record of records){let recordStart=Math.round(record.startTime*1000);let recordEnd=Math.round(record.endTime*1000);if(recordStart>millisecondEndTime)
continue;if(recordEnd<millisecondStartTime)
continue;recordStart=Math.max(recordStart,millisecondStartTime);recordEnd=Math.min(recordEnd,millisecondEndTime);let value=callback(record);for(let t=recordStart;t<=recordEnd;++t)
samples[t-millisecondStartTime]=value;}}
markRecordEntries(scriptRecords,(record)=>{return CPUTimelineView.SampleType.JavaScript;});markRecordEntries(layoutRecords,(record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:return CPUTimelineView.SampleType.Style;case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:return CPUTimelineView.SampleType.Layout;case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return CPUTimelineView.SampleType.Paint;}});let samplesIdle=0;let samplesScript=0;let samplesLayout=0;let samplesPaint=0;let samplesStyle=0;for(let i=0;i<samples.length;++i){switch(samples[i]){case undefined:samplesIdle++;break;case CPUTimelineView.SampleType.JavaScript:samplesScript++;break;case CPUTimelineView.SampleType.Layout:samplesLayout++;break;case CPUTimelineView.SampleType.Paint:samplesPaint++;break;case CPUTimelineView.SampleType.Style:samplesStyle++;break;}}
return{samples,samplesIdle,samplesScript,samplesLayout,samplesPaint,samplesStyle,scriptEntries,networkRequests,timerTypes,eventTypes,observerTypes,timerInstallationRecords,eventHandlerRecords,observerCallbackRecords,repeatingTimers,};}
_removeWorkerThreadViews()
{if(!this._workerViews.length)
return;for(let view of this._workerViews)
this.removeSubview(view);this._workerViews=[];}
_resetSourcesFilters()
{if(!this._sourcesFilter)
return;this._sourcesFilterRow.hidden=true;this._sourcesFilterLabelElement.removeChildren();this._timerInstallationsRow.hidden=false;this._eventHandlersRow.hidden=false;this._observerHandlersRow.hidden=false;this._sourcesFilter.timer.clear();this._sourcesFilter.event.clear();this._sourcesFilter.observer.clear();}
_addSourcesFilter(type,name)
{this._sourcesFilter[type].add(name);this._updateSourcesFilters();}
_removeSourcesFilter(type,name)
{this._sourcesFilter[type].delete(name);this._updateSourcesFilters();}
_updateSourcesFilters()
{let timerFilters=this._sourcesFilter.timer;let eventFilters=this._sourcesFilter.event;let observerFilters=this._sourcesFilter.observer;if(!timerFilters.size&&!eventFilters.size&&!observerFilters.size){this._resetSourcesFilters();return;}
let createActiveFilterElement=(type,name)=>{let span=document.createElement("span");span.className="filter active";span.textContent=name;span.addEventListener("mouseup",(event)=>{this._removeSourcesFilter(type,name);this._layoutStatisticsAndSources();});return span;};this._sourcesFilterRow.hidden=false;this._sourcesFilterLabelElement.removeChildren();for(let name of timerFilters)
this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("timer",name));for(let name of eventFilters)
this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("event",name));for(let name of observerFilters)
this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("observer",name));this._timerInstallationsRow.hidden=!timerFilters.size;this._eventHandlersRow.hidden=!eventFilters.size;this._observerHandlersRow.hidden=!observerFilters.size;}
_createTableRow(table)
{let row=table.appendChild(document.createElement("tr"));let headerCell=row.appendChild(document.createElement("th"));let numberCell=row.appendChild(document.createElement("td"));numberCell.className="number";let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";return{row,headerCell,numberCell,labelCell};}
_insertTableRow(table,rowList,{headerValue,numberValue,labelValue,followingRow})
{let{row,headerCell,numberCell,labelCell}=this._createTableRow(table);rowList.push(row);if(followingRow)
table.insertBefore(row,followingRow);if(headerValue)
headerCell.textContent=headerValue;if(numberValue)
numberCell.textContent=numberValue;if(labelValue)
labelCell.append(labelValue);return row;}
_clearStatistics()
{this._networkRequestsNumberElement.textContent=emDash;this._scriptEntriesNumberElement.textContent=emDash;for(let row of this._statisticsRows)
row.remove();this._statisticsRows=[];}
_clearSources()
{this._timerInstallationsNumberElement.textContent=emDash;this._timerInstallationsLabelElement.textContent="";this._eventHandlersNumberElement.textContent=emDash;this._eventHandlersLabelElement.textContent="";this._observerHandlersNumberElement.textContent=emDash;this._observerHandlersLabelElement.textContent="";for(let row of this._sourcesRows)
row.remove();this._sourcesRows=[];}
_clearEnergyImpactText()
{this._energyImpactLabelElement.classList.remove("low","medium","high");this._energyImpactLabelElement.textContent=emDash;this._energyImpactNumberElement.textContent="";this._energyImpactDurationElement.textContent="";}
_clearBreakdownLegend()
{this._breakdownLegendScriptElement.textContent=emDash;this._breakdownLegendLayoutElement.textContent=emDash;this._breakdownLegendPaintElement.textContent=emDash;this._breakdownLegendStyleElement.textContent=emDash;this._breakdownChart.centerElement.removeChildren();}
_cpuTimelineRecordAdded(event)
{let cpuTimelineRecord=event.data.record;if(cpuTimelineRecord.startTime>=this.startTime&&cpuTimelineRecord.endTime<=this.endTime)
this.needsLayout();}
_graphPositionForMouseEvent(event)
{let chartElement=event.target.closest(".area-chart, .stacked-area-chart, .range-chart");if(!chartElement)
return NaN;let rect=chartElement.getBoundingClientRect();let position=event.pageX-rect.left;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
return rect.width-position;return position;}
_handleIndicatorClick(event)
{let clickPosition=this._graphPositionForMouseEvent(event);if(isNaN(clickPosition))
return;let secondsPerPixel=this._timelineRuler.secondsPerPixel;let graphClickTime=clickPosition*secondsPerPixel;let graphStartTime=this.startTime;let clickStartTime=graphStartTime+graphClickTime;let clickEndTime=clickStartTime+secondsPerPixel;if(event.target.localName==="rect"){if(this._attemptSelectIndicatatorTimelineRecord(clickStartTime,clickEndTime))
return;}
for(let i=1,delta=0;i<=4;++i){delta+=secondsPerPixel;if(this._attemptSelectIndicatatorTimelineRecord(clickStartTime-delta,clickStartTime))
return;if(this._attemptSelectIndicatatorTimelineRecord(clickEndTime,clickEndTime+delta))
return;}}
_attemptSelectIndicatatorTimelineRecord(startTime,endTime)
{let layoutTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Layout);let layoutRecords=layoutTimeline?layoutTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];layoutRecords=layoutRecords.filter((record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return true;case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.InvalidateLayout:return false;default:console.error("Unhandled LayoutTimelineRecord.EventType",record.eventType);return false;}});if(layoutRecords.length){this._selectTimelineRecord(layoutRecords[0]);return true;}
let scriptTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Script);let scriptRecords=scriptTimeline?scriptTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];scriptRecords=scriptRecords.filter((record)=>{switch(record.eventType){case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:case WI.ScriptTimelineRecord.EventType.ObserverCallback:case WI.ScriptTimelineRecord.EventType.EventDispatched:case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:case WI.ScriptTimelineRecord.EventType.TimerFired:case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:case WI.ScriptTimelineRecord.EventType.TimerInstalled:case WI.ScriptTimelineRecord.EventType.TimerRemoved:case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:case WI.ScriptTimelineRecord.EventType.GarbageCollected:return false;default:console.error("Unhandled ScriptTimelineRecord.EventType",record.eventType);return false;}});if(scriptRecords.length){this._selectTimelineRecord(scriptRecords[0]);return true;}
return false;}
_selectTimelineRecord(record)
{this.dispatchEventToListeners(WI.TimelineView.Event.RecordWasSelected,{record});}
_handleGraphClick(event)
{let mousePosition=this._graphPositionForMouseEvent(event);if(isNaN(mousePosition))
return;this._stickingOverlay=!this._stickingOverlay;if(!this._stickingOverlay)
this._handleGraphMouseMove(event);}
_handleGraphMouseMove(event)
{let mousePosition=this._graphPositionForMouseEvent(event);if(isNaN(mousePosition)){this._hideGraphOverlay();this.dispatchEventToListeners(WI.TimelineView.Event.ScannerHide);return;}
let secondsPerPixel=this._timelineRuler.secondsPerPixel;let time=this.startTime+(mousePosition*secondsPerPixel);if(!this._stickingOverlay)
this._showGraphOverlayNearTo(time);this.dispatchEventToListeners(WI.TimelineView.Event.ScannerShow,{time});}
_showGraphOverlayNearTo(time)
{let nearestRecord=null;let nearestDistance=Infinity;for(let record of this._visibleRecordsInLayout){let distance=Math.abs(time-record.timestamp);if(distance<nearestDistance){nearestRecord=record;nearestDistance=distance;}}
if(!nearestRecord){this._hideGraphOverlay();return;}
let bestTime=nearestRecord.timestamp;for(let{startTime,endTime}of this._discontinuitiesInLayout){let distance=Math.abs(time-startTime);if(distance<nearestDistance){nearestDistance=distance;bestTime=startTime;}
distance=Math.abs(time-endTime);if(distance<nearestDistance){nearestDistance=distance;bestTime=endTime;}}
let visibleEndTime=Math.min(this.endTime,this.currentTime);let distance=Math.abs(time-visibleEndTime);if(distance<nearestDistance){nearestDistance=distance;bestTime=visibleEndTime;}
let graphStartTime=this.startTime;let adjustedTime=Number.constrain(bestTime,graphStartTime,visibleEndTime);this._showGraphOverlay(nearestRecord,adjustedTime);}
_updateGraphOverlay()
{if(!this._overlayRecord)
return;this._showGraphOverlay(this._overlayRecord,this._overlayTime,true);}
_showGraphOverlay(record,time,force)
{if(!force&&record===this._overlayRecord&&time===this._overlayTime)
return;this._overlayRecord=record;this._overlayTime=time;let secondsPerPixel=this._secondsPerPixelInLayout;let graphStartTime=this.startTime;this._overlayMarker.time=time+(secondsPerPixel/2);function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
let x=xScale(time);let{mainThreadUsage,workerThreadUsage,webkitThreadUsage,unknownThreadUsage,workersData}=record;function addOverlayPoint(view,graphHeight,layoutMax,value){if(!value)
return;let graphMax=layoutMax*1.05;function yScale(value){return graphHeight-((value/graphMax)*graphHeight);}
view.chart.addPointMarker(x,yScale(value));view.chart.needsLayout();}
this._clearOverlayMarkers();this._cpuUsageView.updateLegend(record);addOverlayPoint(this._cpuUsageView,CPUTimelineView.cpuUsageViewHeight,this._layoutMax,mainThreadUsage);addOverlayPoint(this._cpuUsageView,CPUTimelineView.cpuUsageViewHeight,this._layoutMax,mainThreadUsage+workerThreadUsage);addOverlayPoint(this._cpuUsageView,CPUTimelineView.cpuUsageViewHeight,this._layoutMax,mainThreadUsage+workerThreadUsage+webkitThreadUsage+unknownThreadUsage);if(this._threadsDetailsElement.open){this._mainThreadUsageView.updateLegend(mainThreadUsage);addOverlayPoint(this._mainThreadUsageView,CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,mainThreadUsage);this._webkitThreadUsageView.updateLegend(webkitThreadUsage);addOverlayPoint(this._webkitThreadUsageView,CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,webkitThreadUsage);this._unknownThreadUsageView.updateLegend(unknownThreadUsage);addOverlayPoint(this._unknownThreadUsageView,CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,unknownThreadUsage);for(let workerView of this._workerViews)
workerView.updateLegend(NaN);if(workersData){for(let{targetId,usage}of workersData){let workerView=this._workerViews.find((x)=>x.__workerId===targetId);if(workerView){workerView.updateLegend(usage);addOverlayPoint(workerView,CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,usage);}}}}}
_clearOverlayMarkers()
{function clearGraphOverlayElement(view){view.clearLegend();view.chart.clearPointMarkers();view.chart.needsLayout();}
clearGraphOverlayElement(this._cpuUsageView);clearGraphOverlayElement(this._mainThreadUsageView);clearGraphOverlayElement(this._webkitThreadUsageView);clearGraphOverlayElement(this._unknownThreadUsageView);for(let workerView of this._workerViews)
clearGraphOverlayElement(workerView);}
_hideGraphOverlay()
{if(this._stickingOverlay)
return;this._overlayRecord=null;this._overlayTime=NaN;this._overlayMarker.time=-1;this._clearOverlayMarkers();}};WI.CPUTimelineView.LayoutReason={Internal:Symbol("cpu-timeline-view-internal-layout"),};WI.CPUTimelineView.SampleType={JavaScript:"sample-type-javascript",Layout:"sample-type-layout",Paint:"sample-type-paint",Style:"sample-type-style",};WI.CPUUsageCombinedView=class CPUUsageCombinedView extends WI.View
{constructor(displayName)
{super();this.element.classList.add("cpu-usage-combined-view");this._detailsElement=this.element.appendChild(document.createElement("div"));this._detailsElement.classList.add("details");let detailsNameElement=this._detailsElement.appendChild(document.createElement("span"));detailsNameElement.classList.add("name");detailsNameElement.textContent=displayName;this._detailsElement.appendChild(document.createElement("br"));this._detailsAverageElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsMaxElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsElement.appendChild(document.createElement("br"));this._updateDetails(NaN,NaN);this._graphElement=this.element.appendChild(document.createElement("div"));this._graphElement.classList.add("graph");this._chart=new WI.StackedAreaChart;this._chart.initializeSections(["main-thread-usage","worker-thread-usage","total-usage"]);this.addSubview(this._chart);this._graphElement.appendChild(this._chart.element);this._rangeChart=new WI.RangeChart;this.addSubview(this._rangeChart);this._graphElement.appendChild(this._rangeChart.element);function appendLegendRow(legendElement,className){let rowElement=legendElement.appendChild(document.createElement("div"));rowElement.classList.add("row");let swatchElement=rowElement.appendChild(document.createElement("div"));swatchElement.classList.add("swatch",className);let labelElement=rowElement.appendChild(document.createElement("div"));labelElement.classList.add("label");return labelElement;}
this._legendElement=this._detailsElement.appendChild(document.createElement("div"));this._legendElement.classList.add("legend-container");this._legendMainThreadElement=appendLegendRow(this._legendElement,"main-thread");this._legendWorkerThreadsElement=appendLegendRow(this._legendElement,"worker-threads");this._legendOtherThreadsElement=appendLegendRow(this._legendElement,"other-threads");this._legendTotalThreadsElement=appendLegendRow(this._legendElement,"total");this.clearLegend();} 
get graphElement(){return this._graphElement;}
get chart(){return this._chart;}
get rangeChart(){return this._rangeChart;}
clear()
{this._cachedAverageSize=undefined;this._cachedMaxSize=undefined;this._updateDetails(NaN,NaN);this.clearLegend();this._chart.clear();this._chart.needsLayout();this._rangeChart.clear();this._rangeChart.needsLayout();}
updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale)
{this._updateDetails(max,average);this._chart.clearPoints();this._chart.size=size;this._chart.needsLayout();if(!dataPoints.length)
return;if(!max)
return;let firstX=0;let firstY1=yScale(dataPoints[0].mainThreadUsage);let firstY2=yScale(dataPoints[0].mainThreadUsage+dataPoints[0].workerThreadUsage);let firstY3=yScale(dataPoints[0].usage);this._chart.addPointSet(firstX,[firstY1,firstY2,firstY3]);for(let dataPoint of dataPoints){let x=xScale(dataPoint.time);let y1=yScale(dataPoint.mainThreadUsage);let y2=yScale(dataPoint.mainThreadUsage+dataPoint.workerThreadUsage);let y3=yScale(dataPoint.usage);this._chart.addPointSet(x,[y1,y2,y3]);}
let lastDataPoint=dataPoints.lastValue;let lastX=Math.floor(xScale(visibleEndTime));let lastY1=yScale(lastDataPoint.mainThreadUsage);let lastY2=yScale(lastDataPoint.mainThreadUsage+lastDataPoint.workerThreadUsage);let lastY3=yScale(lastDataPoint.usage);this._chart.addPointSet(lastX,[lastY1,lastY2,lastY3]);}
updateMainThreadIndicator(samples,size,visibleEndTime,xScale)
{this._rangeChart.clear();this._rangeChart.size=size;this._rangeChart.needsLayout();if(!samples.length)
return;let ranges=[];let currentRange=null;let currentSampleType=undefined;for(let i=0;i<samples.length;++i){let type=samples[i];if(!type){if(currentRange){ranges.push(currentRange);currentRange=null;currentSampleType=undefined;}
continue;}
if(type===currentSampleType){currentRange.endIndex=i;continue;}
if(currentSampleType){ranges.push(currentRange);currentRange=null;currentSampleType=undefined;}
currentRange={type,startIndex:i,endIndex:i};currentSampleType=type;}
for(let{type,startIndex,endIndex}of ranges){let startX=xScale(startIndex);let endX=xScale(endIndex+1);let width=endX-startX;this._rangeChart.addRange(startX,width,type);}}
clearLegend()
{this._legendMainThreadElement.textContent=WI.UIString("Main Thread");this._legendWorkerThreadsElement.textContent=WI.UIString("Worker Threads");this._legendOtherThreadsElement.textContent=WI.UIString("Other Threads");this._legendTotalThreadsElement.textContent="";}
updateLegend(record)
{if(!record){this.clearLegend();return;}
let{usage,mainThreadUsage,workerThreadUsage,webkitThreadUsage,unknownThreadUsage}=record;this._legendMainThreadElement.textContent=WI.UIString("Main: %s").format(Number.percentageString(mainThreadUsage/100));this._legendWorkerThreadsElement.textContent=WI.UIString("Worker: %s").format(Number.percentageString(workerThreadUsage/100));this._legendOtherThreadsElement.textContent=WI.UIString("Other: %s").format(Number.percentageString((webkitThreadUsage+unknownThreadUsage)/100));this._legendTotalThreadsElement.textContent=WI.UIString("Total: %s").format(Number.percentageString(usage/100));} 
_updateDetails(maxSize,averageSize)
{if(this._cachedMaxSize===maxSize&&this._cachedAverageSize===averageSize)
return;this._cachedAverageSize=averageSize;this._cachedMaxSize=maxSize;this._detailsAverageElement.textContent=WI.UIString("Average: %s").format(Number.isFinite(maxSize)?Number.percentageString(averageSize/100):emDash);this._detailsMaxElement.textContent=WI.UIString("Highest: %s").format(Number.isFinite(maxSize)?Number.percentageString(maxSize/100):emDash);}};WI.CPUUsageView=class CPUUsageView extends WI.View
{constructor(displayName)
{super();this.element.classList.add("cpu-usage-view");this._detailsElement=this.element.appendChild(document.createElement("div"));this._detailsElement.classList.add("details");if(displayName){let detailsNameElement=this._detailsElement.appendChild(document.createElement("span"));detailsNameElement.classList.add("name");detailsNameElement.textContent=displayName;if(displayName.length>=20)
detailsNameElement.title=displayName;this._detailsElement.appendChild(document.createElement("br"));}
this._detailsAverageElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsUsageElement=this._detailsElement.appendChild(document.createElement("span"));this.clearLegend();this._updateDetails(NaN);this._graphElement=this.element.appendChild(document.createElement("div"));this._graphElement.classList.add("graph");this._chart=new WI.AreaChart;this.addSubview(this._chart);this._graphElement.appendChild(this._chart.element);} 
get graphElement(){return this._graphElement;}
get chart(){return this._chart;}
clear()
{this._cachedAverageSize=undefined;this._updateDetails(NaN);this.clearLegend();this._chart.clear();this._chart.needsLayout();}
updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale,property)
{this._updateDetails(average);this._chart.clearPoints();this._chart.size=size;this._chart.needsLayout();if(!dataPoints.length)
return;if(!max)
return;let firstX=0;let firstY=yScale(dataPoints[0][property]);this._chart.addPoint(firstX,firstY);for(let dataPoint of dataPoints){let x=xScale(dataPoint.time);let y=yScale(dataPoint[property]);this._chart.addPoint(x,y);}
let lastDataPoint=dataPoints.lastValue;let lastX=Math.floor(xScale(visibleEndTime));let lastY=yScale(lastDataPoint[property]);this._chart.addPoint(lastX,lastY);}
clearLegend()
{this._detailsUsageElement.hidden=true;this._detailsUsageElement.textContent=emDash;}
updateLegend(value)
{let usage=Number.isFinite(value)?Number.percentageString(value/100):emDash;this._detailsUsageElement.hidden=false;this._detailsUsageElement.textContent=WI.UIString("Usage: %s").format(usage);} 
_updateDetails(averageSize)
{if(this._cachedAverageSize===averageSize)
return;this._cachedAverageSize=averageSize;this._detailsAverageElement.hidden=!Number.isFinite(averageSize);this._detailsAverageElement.textContent=WI.UIString("Average: %s").format(Number.isFinite(averageSize)?Number.percentageString(averageSize/100):emDash);}};WI.CSSStyleSheetTreeElement=class CSSStyleSheetTreeElement extends WI.SourceCodeTreeElement
{constructor(styleSheet)
{const title=null;const subtitle=null;super(styleSheet,["style-sheet","style-sheet-icon"],title,subtitle);this.mainTitle=styleSheet.displayName;if(styleSheet.url){if(styleSheet.urlComponents.scheme==="web-inspector")
this.tooltip=this.mainTitle;else{let host=WI.displayNameForHost(styleSheet.urlComponents.host);this.subtitle=this.mainTitle!==host?host:null;this.tooltip=styleSheet.url;}}}};WI.CSSGridSection=class CSSGridSection extends WI.View
{constructor()
{super();this.element.classList.add("css-grid-section");this._gridNodeSet=new Set;this._checkboxElementByNodeMap=new WeakMap;this._toggleAllCheckboxElement=null;this._suppressUpdateToggleAllCheckbox=false;} 
set gridNodeSet(value)
{this._gridNodeSet=value;this.needsLayout();} 
attached()
{super.attached();WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayStateChanged,this);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._handleGridOverlayStateChanged,this);}
detached()
{WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayStateChanged,this);WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._handleGridOverlayStateChanged,this);super.detached();}
initialLayout()
{super.initialLayout();let settingsGroup=new WI.SettingsGroup(WI.UIString("Page Overlay Options","Page Overlay Options @ Layout Panel Section Header","Heading for list of grid overlay options"));this.element.append(settingsGroup.element);settingsGroup.addSetting(WI.settings.gridOverlayShowTrackSizes,WI.UIString("Track Sizes","Track sizes @ Layout Panel Overlay Options","Label for option to toggle the track sizes setting for CSS grid overlays"));settingsGroup.addSetting(WI.settings.gridOverlayShowLineNumbers,WI.UIString("Line Numbers","Line numbers @ Layout Panel Overlay Options","Label for option to toggle the line numbers setting for CSS grid overlays"));settingsGroup.addSetting(WI.settings.gridOverlayShowLineNames,WI.UIString("Line Names","Line names @ Layout Panel Overlay Options","Label for option to toggle the line names setting for CSS grid overlays"));settingsGroup.addSetting(WI.settings.gridOverlayShowAreaNames,WI.UIString("Area Names","Area names @ Layout Panel Overlay Options","Label for option to toggle the area names setting for CSS grid overlays"));settingsGroup.addSetting(WI.settings.gridOverlayShowExtendedGridLines,WI.UIString("Extended Grid Lines","Show extended lines @ Layout Panel Overlay Options","Label for option to toggle the extended lines setting for CSS grid overlays"));let listHeading=this.element.appendChild(document.createElement("h2"));listHeading.classList.add("heading");let label=listHeading.createChild("label");this._toggleAllCheckboxElement=label.createChild("input");this._toggleAllCheckboxElement.type="checkbox";this._toggleAllCheckboxElement.addEventListener("change",this._handleToggleAllCheckboxChanged.bind(this));let labelInner=label.createChild("span","toggle-all");labelInner.textContent=WI.UIString("Grid Overlays","Page Overlays @ Layout Sidebar Section Header","Heading for list of grid nodes");this._listElement=this.element.appendChild(document.createElement("ul"));this._listElement.classList.add("node-overlay-list");}
_handleToggleAllCheckboxChanged(event)
{let isChecked=event.target.checked;this._suppressUpdateToggleAllCheckbox=true;for(let domNode of this._gridNodeSet){if(isChecked)
WI.overlayManager.showGridOverlay(domNode,{initiator:WI.GridOverlayDiagnosticEventRecorder.Initiator.Panel});else
WI.overlayManager.hideGridOverlay(domNode);}
this._suppressUpdateToggleAllCheckbox=false;}
layout()
{super.layout();this._listElement.removeChildren();for(let domNode of this._gridNodeSet){let itemElement=this._listElement.appendChild(document.createElement("li"));let itemContainerElement=itemElement.appendChild(document.createElement("span"));itemContainerElement.classList.add("node-overlay-list-item-container");let labelElement=itemContainerElement.appendChild(document.createElement("label"));let checkboxElement=labelElement.appendChild(document.createElement("input"));checkboxElement.type="checkbox";checkboxElement.checked=WI.overlayManager.isGridOverlayVisible(domNode);const nodeDisplayName=labelElement.appendChild(document.createElement("span"));nodeDisplayName.classList.add("node-display-name");nodeDisplayName.textContent=domNode.displayName;this._checkboxElementByNodeMap.set(domNode,checkboxElement);checkboxElement.addEventListener("change",(event)=>{if(checkboxElement.checked)
WI.overlayManager.showGridOverlay(domNode,{color:swatch.value,initiator:WI.GridOverlayDiagnosticEventRecorder.Initiator.Panel});else
WI.overlayManager.hideGridOverlay(domNode);});let gridColor=WI.overlayManager.getGridColorForNode(domNode);let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Color,gridColor);swatch.shiftClickColorEnabled=false;itemContainerElement.append(swatch.element);swatch.addEventListener(WI.InlineSwatch.Event.ValueChanged,(event)=>{if(checkboxElement.checked)
WI.overlayManager.showGridOverlay(domNode,{color:event.data.value});},swatch);swatch.addEventListener(WI.InlineSwatch.Event.Deactivated,(event)=>{if(event.target.value===gridColor)
return;gridColor=event.target.value;WI.overlayManager.setGridColorForNode(domNode,gridColor);},swatch);let buttonElement=itemContainerElement.appendChild(WI.createGoToArrowButton());buttonElement.title=WI.repeatedUIString.revealInDOMTree();WI.bindInteractionsForNodeToElement(domNode,buttonElement);}
this._updateToggleAllCheckbox();} 
_handleGridOverlayStateChanged(event)
{let checkboxElement=this._checkboxElementByNodeMap.get(event.data.domNode);if(!checkboxElement)
return;checkboxElement.checked=event.type===WI.OverlayManager.Event.GridOverlayShown;this._updateToggleAllCheckbox();}
_updateToggleAllCheckbox()
{if(this._suppressUpdateToggleAllCheckbox)
return;let hasVisible=false;let hasHidden=false;for(let domNode of this._gridNodeSet){let isVisible=WI.overlayManager.isGridOverlayVisible(domNode);if(isVisible)
hasVisible=true;else
hasHidden=true;if(hasVisible&&hasHidden)
break;}
if(hasVisible&&hasHidden)
this._toggleAllCheckboxElement.indeterminate=true;else{this._toggleAllCheckboxElement.indeterminate=false;this._toggleAllCheckboxElement.checked=hasVisible;}}};WI.CallFrameTreeElement=class CallFrameTreeElement extends WI.GeneralTreeElement
{constructor(callFrame,isAsyncBoundaryCallFrame)
{let className=WI.CallFrameView.iconClassNameForCallFrame(callFrame);let title=callFrame.functionName||WI.UIString("(anonymous function)");const subtitle=null;super(["call-frame",className],title,subtitle,callFrame);this._callFrame=callFrame;this._isActiveCallFrame=false;this._isAsyncBoundaryCallFrame=isAsyncBoundaryCallFrame;if(this._isAsyncBoundaryCallFrame){this.addClassName("async-boundary");this.selectable=false;}
if(this._callFrame.nativeCode||!this._callFrame.sourceCodeLocation){this.subtitle="";this.selectable=false;return;}
let displayScriptURL=this._callFrame.sourceCodeLocation.displaySourceCode.url;if(displayScriptURL){this.subtitle=document.createElement("span");this._callFrame.sourceCodeLocation.populateLiveDisplayLocationString(this.subtitle,"textContent");this.tooltipHandledSeparately=true;}
this._isBlackboxed=WI.debuggerManager.blackboxDataForSourceCode(this._callFrame.sourceCodeLocation.sourceCode);if(this._isBlackboxed){this.addClassName("blackboxed");this.tooltipHandledSeparately=true;}} 
get callFrame(){return this._callFrame;}
get isAsyncBoundaryCallFrame(){return this._isAsyncBoundaryCallFrame;}
get isActiveCallFrame()
{return this._isActiveCallFrame;}
set isActiveCallFrame(x)
{if(this._isActiveCallFrame===x)
return;this._isActiveCallFrame=x;this._updateStatus();} 
onattach()
{super.onattach();if(this.tooltipHandledSeparately){let tailCallSuffix="";if(this._callFrame.isTailDeleted)
tailCallSuffix=" "+WI.UIString("(Tail Call)");let tooltipPrefix=this.mainTitle+tailCallSuffix+"\n";let tooltipSuffix="";if(this._isBlackboxed)
tooltipSuffix+="\n\n"+WI.UIString("Script ignored due to blackbox");this._callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element,tooltipPrefix,tooltipSuffix);}
this._updateStatus();}
populateContextMenu(contextMenu,event)
{if(this._callFrame.sourceCodeLocation)
WI.appendContextMenuItemsForSourceCode(contextMenu,this._callFrame.sourceCodeLocation);super.populateContextMenu(contextMenu,event);} 
_updateStatus()
{if(!this.element)
return;if(!this._isActiveCallFrame){this.status=null;return;}
if(!this._statusImageElement)
this._statusImageElement=WI.ImageUtilities.useSVGSymbol("Images/ActiveCallFrame.svg","status-image");this.status=this._statusImageElement;}};WI.CallFrameView=class CallFrameView extends WI.Object
{constructor(callFrame,{showFunctionName,indicateIfBlackboxed}={})
{var callFrameElement=document.createElement("div");callFrameElement.classList.add("call-frame",WI.CallFrameView.iconClassNameForCallFrame(callFrame));var subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");var sourceCodeLocation=callFrame.sourceCodeLocation;if(sourceCodeLocation){if(indicateIfBlackboxed)
callFrameElement.classList.toggle("blackboxed",WI.debuggerManager.blackboxDataForSourceCode(callFrame.sourceCodeLocation.sourceCode));WI.linkifyElement(callFrameElement,sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});var linkElement=document.createElement("a");linkElement.classList.add("source-link");linkElement.href=sourceCodeLocation.sourceCode.url;if(showFunctionName){var separatorElement=document.createElement("span");separatorElement.classList.add("separator");separatorElement.textContent=` ${emDash} `;subtitleElement.append(separatorElement);}
subtitleElement.append(linkElement);sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);sourceCodeLocation.populateLiveDisplayLocationString(linkElement,"textContent");}
var titleElement=document.createElement("span");titleElement.classList.add("title");if(showFunctionName){var imgElement=document.createElement("img");imgElement.classList.add("icon");titleElement.append(imgElement,callFrame.functionName||WI.UIString("(anonymous function)"));}
callFrameElement.append(titleElement,subtitleElement);return callFrameElement;}
static iconClassNameForCallFrame(callFrame)
{if(callFrame.isTailDeleted)
return WI.CallFrameView.TailDeletedIcon;if(callFrame.programCode)
return WI.CallFrameView.ProgramIconStyleClassName;
if(callFrame.functionName&&callFrame.functionName.startsWith("on")&&callFrame.functionName.length>=5)
return WI.CallFrameView.EventListenerIconStyleClassName;if(callFrame.nativeCode)
return WI.CallFrameView.NativeIconStyleClassName;return WI.CallFrameView.FunctionIconStyleClassName;}};WI.CallFrameView.ProgramIconStyleClassName="program-icon";WI.CallFrameView.FunctionIconStyleClassName="function-icon";WI.CallFrameView.EventListenerIconStyleClassName="event-listener-icon";WI.CallFrameView.NativeIconStyleClassName="native-icon";WI.CallFrameView.TailDeletedIcon="tail-deleted";WI.CanvasContentView=class CanvasContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("canvas");this._progressView=null;this._previewContainerElement=null;this._previewImageElement=null;this._errorElement=null;this._memoryCostElement=null;this._pendingContent=null;this._pixelSize=null;this._pixelSizeElement=null;this._canvasNode=null;this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this.handleRefreshButtonClicked,this);this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showGridButtonClicked,this);this._showGridButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;} 
get navigationItems()
{return[this._refreshButtonNavigationItem,this._showGridButtonNavigationItem];}
refreshPreview()
{this._pendingContent=null;this.representedObject.requestContent().then((content)=>{this._pendingContent=content;if(!this._pendingContent){this._showError();return;}
this.needsLayout();});}
handleRefreshButtonClicked()
{this.refreshPreview();} 
initialLayout()
{super.initialLayout();let isCard=!this._refreshButtonNavigationItem.parentNavigationBar;if(isCard){let header=this.element.appendChild(document.createElement("header"));header.addEventListener("click",(event)=>{event.stopPropagation();});let titles=header.appendChild(document.createElement("div"));titles.className="titles";let title=titles.appendChild(document.createElement("span"));title.className="title";title.textContent=this.representedObject.displayName;let subtitle=titles.appendChild(document.createElement("span"));subtitle.className="subtitle";subtitle.textContent=WI.Canvas.displayNameForContextType(this.representedObject.contextType);if(this.representedObject.contextAttributes.colorSpace){let subtitle=titles.appendChild(document.createElement("span"));subtitle.className="color-space";subtitle.textContent="("+WI.Canvas.displayNameForColorSpace(this.representedObject.contextAttributes.colorSpace)+")";}
let navigationBar=new WI.NavigationBar;if(this.representedObject.contextType===WI.Canvas.ContextType.Canvas2D||this.representedObject.contextType===WI.Canvas.ContextType.BitmapRenderer||this.representedObject.contextType===WI.Canvas.ContextType.WebGL||this.representedObject.contextType===WI.Canvas.ContextType.WebGL2){const toolTip=WI.UIString("Start recording canvas actions.\nShift-click to record a single frame.");const altToolTip=WI.UIString("Stop recording canvas actions");this._recordButtonNavigationItem=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleRecording,this);navigationBar.addNavigationItem(this._recordButtonNavigationItem);}
let canvasElementButtonNavigationItem=new WI.ButtonNavigationItem("canvas-element",WI.UIString("Canvas Element"),"Images/Markup.svg",16,16);canvasElementButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.addMouseDownContextMenuHandlers(canvasElementButtonNavigationItem.element,this._populateCanvasElementButtonContextMenu.bind(this));navigationBar.addNavigationItem(canvasElementButtonNavigationItem);navigationBar.addNavigationItem(this._refreshButtonNavigationItem);header.append(navigationBar.element);}
this._previewContainerElement=this.element.appendChild(document.createElement("div"));this._previewContainerElement.className="preview";if(isCard){let footer=this.element.appendChild(document.createElement("footer"));footer.addEventListener("click",(event)=>{event.stopPropagation();});this._viewRelatedItemsContainer=footer.appendChild(document.createElement("div"));this._viewRelatedItemsContainer.classList.add("view-related-items");this._viewShaderButton=document.createElement("img");this._viewShaderButton.classList.add("view-shader");this._viewShaderButton.title=WI.UIString("View Shader");WI.addMouseDownContextMenuHandlers(this._viewShaderButton,this._populateViewShaderButtonContextMenu.bind(this));this._viewRecordingButton=document.createElement("img");this._viewRecordingButton.classList.add("view-recording");this._viewRecordingButton.title=WI.UIString("View Recording");WI.addMouseDownContextMenuHandlers(this._viewRecordingButton,this._populateViewRecordingButtonContextMenu.bind(this));this._updateViewRelatedItems();let flexibleSpaceElement=footer.appendChild(document.createElement("div"));flexibleSpaceElement.className="flexible-space";let metrics=footer.appendChild(document.createElement("div"));this._pixelSizeElement=metrics.appendChild(document.createElement("span"));this._pixelSizeElement.className="pixel-size";this._memoryCostElement=metrics.appendChild(document.createElement("span"));this._memoryCostElement.className="memory-cost";}
if(this._errorElement)
this._showError();if(isCard)
this._refreshPixelSize();}
layout()
{super.layout();if(this._pendingContent){if(this._errorElement){this._errorElement.remove();this._errorElement=null;}
if(!this._previewImageElement){this._previewImageElement=document.createElement("img");this._previewImageElement.addEventListener("error",this._showError.bind(this));}
this._previewImageElement.src=this._pendingContent;this._pendingContent=null;if(!this._previewImageElement.parentNode)
this._previewContainerElement.appendChild(this._previewImageElement);}
this._updateRecordNavigationItem();this._updateProgressView();this._updateViewRelatedItems();this._updateMemoryCost();this._updateImageGrid();}
attached()
{super.attached();this.representedObject.addEventListener(WI.Canvas.Event.MemoryChanged,this._updateMemoryCost,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStarted,this.needsLayout,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingProgress,this.needsLayout,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStopped,this.needsLayout,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemAdded,this.needsLayout,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemRemoved,this.needsLayout,this);this.representedObject.requestNode().then((node)=>{if(!node)
return;if(this._canvasNode===node)
return;this._canvasNode=node;this._canvasNode.addEventListener(WI.DOMNode.Event.AttributeModified,this._refreshPixelSize,this);this._canvasNode.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshPixelSize,this);});WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);this.refreshPreview();}
detached()
{this.representedObject.removeEventListener(WI.Canvas.Event.MemoryChanged,this._updateMemoryCost,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingStarted,this.needsLayout,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingProgress,this.needsLayout,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingStopped,this.needsLayout,this);this.representedObject.shaderProgramCollection.removeEventListener(WI.Collection.Event.ItemAdded,this.needsLayout,this);this.representedObject.shaderProgramCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this.needsLayout,this);if(this._canvasNode){this._canvasNode.removeEventListener(WI.DOMNode.Event.AttributeModified,this._refreshPixelSize,this);this._canvasNode.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshPixelSize,this);this._canvasNode=null;}
WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);super.detached();} 
_showError()
{if(this._previewImageElement)
this._previewImageElement.remove();if(!this._errorElement){let isError=WI.Canvas.supportsRequestContentForContextType(this.representedObject.contextType);this._errorElement=WI.createMessageTextView(WI.UIString("No Preview Available"),isError);}
if(this._previewContainerElement)
this._previewContainerElement.appendChild(this._errorElement);}
_toggleRecording(event)
{if(this.representedObject.recordingActive)
this.representedObject.stopRecording();else{let singleFrame=event.data.nativeEvent.shiftKey;this.representedObject.startRecording(singleFrame);}}
_refreshPixelSize()
{let updatePixelSize=(size)=>{if(Object.shallowEqual(this._pixelSize,size))
return;this._pixelSize=size;if(this._pixelSizeElement){if(this._pixelSize)
this._pixelSizeElement.textContent=`${this._pixelSize.width} ${multiplicationSign} ${this._pixelSize.height}`;else
this._pixelSizeElement.textContent=emDash;}
this.refreshPreview();};this.representedObject.requestSize().then((size)=>{updatePixelSize(size);});}
_populateCanvasElementButtonContextMenu(contextMenu)
{contextMenu.appendItem(WI.UIString("Log Canvas Context"),()=>{WI.RemoteObject.resolveCanvasContext(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject)
return;const text=WI.UIString("Selected Canvas Context");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);});});contextMenu.appendSeparator();if(this._canvasNode)
WI.appendContextMenuItemsForDOMNode(contextMenu,this._canvasNode);}
_showGridButtonClicked()
{WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;}
_updateImageGrid()
{let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;if(this._previewImageElement)
this._previewImageElement.classList.toggle("show-grid",activated);}
_updateMemoryCost()
{if(!this._memoryCostElement)
return;let memoryCost=this.representedObject.memoryCost;if(isNaN(memoryCost))
this._memoryCostElement.textContent=emDash;else{const higherResolution=false;let bytesString=Number.bytesToString(memoryCost,higherResolution);this._memoryCostElement.textContent=`(${bytesString})`;}}
_updateRecordNavigationItem()
{if(!this._recordButtonNavigationItem)
return;let recordingActive=this.representedObject.recordingActive;this._recordButtonNavigationItem.toggled=recordingActive;this._refreshButtonNavigationItem.enabled=!recordingActive;this.element.classList.toggle("recording-active",recordingActive);}
_updateProgressView()
{if(!this._previewContainerElement)
return;if(!this.representedObject.recordingActive){if(this._progressView&&this._progressView.parentView){this.removeSubview(this._progressView);this._progressView=null;}
return;}
if(!this._progressView){this._progressView=new WI.ProgressView;this.element.insertBefore(this._progressView.element,this._previewContainerElement);this.addSubview(this._progressView);}
let title=null;if(this.representedObject.recordingFrameCount){let formatString=this.representedObject.recordingFrameCount===1?WI.UIString("%d Frame"):WI.UIString("%d Frames");title=formatString.format(this.representedObject.recordingFrameCount);}else
title=WI.UIString("Waiting for frames\u2026");this._progressView.title=title;this._progressView.subtitle=this.representedObject.recordingBufferUsed?Number.bytesToString(this.representedObject.recordingBufferUsed):"";}
_updateViewRelatedItems()
{if(!this._viewRelatedItemsContainer)
return;this._viewRelatedItemsContainer.removeChildren();if(this.representedObject.shaderProgramCollection.size)
this._viewRelatedItemsContainer.appendChild(this._viewShaderButton);if(this.representedObject.recordingCollection.size)
this._viewRelatedItemsContainer.appendChild(this._viewRecordingButton);}
_populateViewShaderButtonContextMenu(contextMenu,event)
{let shaderPrograms=this.representedObject.shaderProgramCollection;if(!shaderPrograms.size)
return;if(event.button===0&&shaderPrograms.size===1){WI.showRepresentedObject(Array.from(shaderPrograms)[0]);return;}
for(let shaderProgram of shaderPrograms){contextMenu.appendItem(shaderProgram.displayName,()=>{WI.showRepresentedObject(shaderProgram);});}}
_populateViewRecordingButtonContextMenu(contextMenu,event)
{let recordings=this.representedObject.recordingCollection;if(!recordings.size)
return;if(event.button===0&&recordings.size===1){WI.showRepresentedObject(Array.from(recordings)[0]);return;}
for(let recording of recordings){contextMenu.appendItem(recording.displayName,()=>{WI.showRepresentedObject(recording);});}}};WI.CanvasDetailsSidebarPanel=class CanvasDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("canvas",WI.UIString("Canvas"));this.element.classList.add("canvas");this._canvas=null;this._node=null;this._sections=[];this._emptyContentPlaceholder=null;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];objects=objects.map((object)=>{if(object instanceof WI.Recording)
return object.source;if(object instanceof WI.ShaderProgram)
return object.canvas;return object;});this.canvas=objects.find((object)=>object instanceof WI.Canvas);return!!this.canvas;}
get canvas()
{return this._canvas;}
set canvas(canvas)
{if(canvas===this._canvas)
return;if(this._node){this._node.removeEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);this._node=null;}
if(this._canvas){this._canvas.removeEventListener(WI.Canvas.Event.MemoryChanged,this._canvasMemoryChanged,this);this._canvas.removeEventListener(WI.Canvas.Event.ExtensionEnabled,this._refreshExtensionsSection,this);this._canvas.removeEventListener(WI.Canvas.Event.ClientNodesChanged,this._refreshClientsSection,this);}
this._canvas=canvas||null;if(this._canvas){this._canvas.addEventListener(WI.Canvas.Event.MemoryChanged,this._canvasMemoryChanged,this);this._canvas.addEventListener(WI.Canvas.Event.ExtensionEnabled,this._refreshExtensionsSection,this);this._canvas.addEventListener(WI.Canvas.Event.ClientNodesChanged,this._refreshClientsSection,this);}
this.needsLayout();} 
initialLayout()
{super.initialLayout();this._nameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._typeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._memoryRow=new WI.DetailsSectionSimpleRow(WI.UIString("Memory"));this._memoryRow.tooltip=WI.UIString("Memory usage of this canvas");let identitySection=new WI.DetailsSection("canvas-details",WI.UIString("Identity"));identitySection.groups=[new WI.DetailsSectionGroup([this._nameRow,this._typeRow,this._memoryRow])];this._sections.push(identitySection);this._nodeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Node"));this._cssCanvasRow=new WI.DetailsSectionSimpleRow(WI.UIString("CSS Canvas"));this._widthRow=new WI.DetailsSectionSimpleRow(WI.UIString("Width"));this._heightRow=new WI.DetailsSectionSimpleRow(WI.UIString("Height"));this._detachedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Detached"));let sourceSection=new WI.DetailsSection("canvas-source",WI.UIString("Source"));sourceSection.groups=[new WI.DetailsSectionGroup([this._nodeRow,this._cssCanvasRow,this._widthRow,this._heightRow,this._detachedRow])];this._sections.push(sourceSection);this._attributesDataGridRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Attributes"));this._attributesSection=new WI.DetailsSection("canvas-attributes",WI.UIString("Attributes"));this._attributesSection.groups=[new WI.DetailsSectionGroup([this._attributesDataGridRow])];this._attributesSection.element.hidden=true;this._sections.push(this._attributesSection);this._extensionsSection=new WI.DetailsSection("canvas-extensions",WI.UIString("Extensions"));this._extensionsSection.element.hidden=true;this._sections.push(this._extensionsSection);this._clientNodesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Nodes"));this._clientsSection=new WI.DetailsSection("canvas-clients",WI.UIString("Clients"));this._clientsSection.groups=[new WI.DetailsSectionGroup([this._clientNodesRow])];this._clientsSection.element.hidden=true;this._sections.push(this._clientsSection);const selectable=false;let backtraceTreeOutline=new WI.TreeOutline(selectable);backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.CallFrameTreeController(backtraceTreeOutline);let backtraceRow=new WI.DetailsSectionRow;backtraceRow.element.appendChild(backtraceTreeOutline.element);this._backtraceSection=new WI.DetailsSection("canvas-backtrace",WI.UIString("Backtrace"));this._backtraceSection.groups=[new WI.DetailsSectionGroup([backtraceRow])];this._backtraceSection.element.hidden=true;this._sections.push(this._backtraceSection);this._emptyContentPlaceholder=WI.createMessageTextView(WI.UIString("No Canvas Selected"));}
layout()
{super.layout();this.contentView.element.removeChildren();if(!this._canvas){this.contentView.element.appendChild(this._emptyContentPlaceholder);return;}
this.contentView.element.append(...this._sections.map(section=>section.element));this._refreshIdentitySection();this._refreshSourceSection();this._refreshAttributesSection();this._refreshExtensionsSection();this._refreshClientsSection();this._refreshBacktraceSection();}
sizeDidChange()
{super.sizeDidChange(); this._attributesDataGridRow.sizeDidChange();} 
_refreshIdentitySection()
{this._nameRow.value=this._canvas.displayName;this._typeRow.value=WI.Canvas.displayNameForContextType(this._canvas.contextType);this._formatMemoryRow();}
_refreshSourceSection()
{if(!this.didInitialLayout)
return;let hideNode=this._canvas.cssCanvasName||this._canvas.contextType===WI.Canvas.ContextType.WebGPU;this._nodeRow.value=hideNode?null:emDash;this._cssCanvasRow.value=this._canvas.cssCanvasName||null;this._widthRow.value=emDash;this._heightRow.value=emDash;this._detachedRow.value=null;this._canvas.requestNode().then((node)=>{if(!node){this._nodeRow.value=null;return;}
if(node!==this._node){if(this._node){this._node.removeEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);this._node=null;}
this._node=node;this._node.addEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);}
if(!hideNode){this._nodeRow.value=WI.linkifyNodeReference(this._node);if(!this._node.parentNode)
this._detachedRow.value=WI.UIString("Yes");}
let setRowValueIfValidAttributeValue=(row,attribute)=>{let value=Number(this._node.getAttribute(attribute));if(!Number.isInteger(value)||value<0)
return false;row.value=value;return true;};let validWidth=setRowValueIfValidAttributeValue(this._widthRow,"width");let validHeight=setRowValueIfValidAttributeValue(this._heightRow,"height");if(!validWidth||!validHeight){

 WI.RemoteObject.resolveNode(node).then((remoteObject)=>{function setRowValueToPropertyValue(row,property){remoteObject.getProperty(property,(error,result,wasThrown)=>{if(!error&&result.type==="number")
row.value=`${result.value}px`;});}
setRowValueToPropertyValue(this._widthRow,"width");setRowValueToPropertyValue(this._heightRow,"height");remoteObject.release();});}});}
_refreshAttributesSection()
{let hasAttributes=!isEmptyObject(this._canvas.contextAttributes);this._attributesSection.element.hidden=!hasAttributes;if(!hasAttributes)
return;let dataGrid=this._attributesDataGridRow.dataGrid;if(!dataGrid){dataGrid=this._attributesDataGridRow.dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name")},value:{title:WI.UIString("Value"),width:"30%"},});}
dataGrid.removeChildren();for(let attribute in this._canvas.contextAttributes){let data={name:attribute,value:this._canvas.contextAttributes[attribute]};let dataGridNode=new WI.DataGridNode(data);dataGrid.appendChild(dataGridNode);}
dataGrid.updateLayoutIfNeeded();}
_refreshExtensionsSection()
{let hasEnabledExtensions=this._canvas.extensions.size>0;this._extensionsSection.element.hidden=!hasEnabledExtensions;if(!hasEnabledExtensions)
return;let element=document.createElement("ul");for(let extension of this._canvas.extensions){let listElement=element.appendChild(document.createElement("li"));listElement.textContent=extension;}
this._extensionsSection.groups=[{element}];}
_refreshClientsSection()
{if(!this.didInitialLayout)
return;if(!this._canvas.cssCanvasName&&this._canvas.contextType!==WI.Canvas.ContextType.WebGPU){this._clientsSection.element.hidden=true;return;}
this._clientNodesRow.value=emDash;this._clientsSection.element.hidden=false;this._canvas.requestClientNodes((clientNodes)=>{if(!clientNodes.length)
return;let fragment=document.createDocumentFragment();for(let clientNode of clientNodes)
fragment.appendChild(WI.linkifyNodeReference(clientNode));this._clientNodesRow.value=fragment;});}
_refreshBacktraceSection()
{let callFrames=this._canvas.backtrace;this._backtraceTreeController.callFrames=callFrames;this._backtraceSection.element.hidden=!callFrames.length;}
_formatMemoryRow()
{if(!this.didInitialLayout)
return;if(!this._canvas.memoryCost||isNaN(this._canvas.memoryCost)){this._memoryRow.value=emDash;return;}
this._memoryRow.value=Number.bytesToString(this._canvas.memoryCost);}
_canvasMemoryChanged(event)
{this._formatMemoryRow();}};WI.CanvasOverviewContentView=class CanvasOverviewContentView extends WI.CollectionContentView
{constructor(representedObject)
{let contentPlaceholder=WI.animationManager.supported?document.createElement("div"):WI.createMessageTextView(WI.UIString("No Canvas Contexts"));let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";descriptionElement.textContent=WI.UIString("Waiting for canvas contexts created by script or CSS.");let importNavigationItem=new WI.ButtonNavigationItem("import-recording",WI.UIString("Import"),"Images/Import.svg",15,15);importNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to load a recording from file."),importNavigationItem);contentPlaceholder.appendChild(importHelpElement);super(representedObject,WI.CanvasContentView,contentPlaceholder);this.element.classList.add("canvas-overview");if(WI.CanvasManager.supportsRecordingAutoCapture()){this._recordingAutoCaptureFrameCountInputElement=document.createElement("input");this._recordingAutoCaptureFrameCountInputElement.type="number";this._recordingAutoCaptureFrameCountInputElement.min=0;this._recordingAutoCaptureFrameCountInputElement.addEventListener("input",this._handleRecordingAutoCaptureInput.bind(this));this._recordingAutoCaptureFrameCountInputElementValue=WI.settings.canvasRecordingAutoCaptureFrameCount.value;const label=null;this._recordingAutoCaptureNavigationItem=new WI.CheckboxNavigationItem("canvas-recording-auto-capture",label,!!WI.settings.canvasRecordingAutoCaptureEnabled.value);this._recordingAutoCaptureNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._recordingAutoCaptureNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,this._handleRecordingAutoCaptureCheckedDidChange,this);let frameCount=this._updateRecordingAutoCaptureInputElementSize();this._setRecordingAutoCaptureFrameCount(frameCount);this._updateRecordingAutoCaptureCheckboxLabel(frameCount);}
importNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);this._savedRecordingsContentView=null;this._savedRecordingsTreeOutline=null;} 
get navigationItems()
{let navigationItems=[];if(this._recordingAutoCaptureNavigationItem)
navigationItems.push(this._recordingAutoCaptureNavigationItem);return navigationItems;}
handleRefreshButtonClicked()
{for(let subview of this.subviews){if(subview instanceof WI.CanvasContentView)
subview.handleRefreshButtonClicked();}} 
contentViewAdded(contentView)
{contentView.element.addEventListener("mouseenter",this._contentViewMouseEnter);contentView.element.addEventListener("mouseleave",this._contentViewMouseLeave);if(this._savedRecordingsContentView){this.removeSubview(this._savedRecordingsContentView);this.addSubview(this._savedRecordingsContentView);}}
contentViewRemoved(contentView)
{contentView.element.removeEventListener("mouseenter",this._contentViewMouseEnter);contentView.element.removeEventListener("mouseleave",this._contentViewMouseLeave);}
attached()
{super.attached();WI.settings.canvasRecordingAutoCaptureEnabled.addEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureEnabledChanged,this);WI.settings.canvasRecordingAutoCaptureFrameCount.addEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureFrameCountChanged,this);WI.canvasManager.addEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSaved,this);if(this._savedRecordingsTreeOutline)
this._savedRecordingsTreeOutline.removeChildren();for(let recording of WI.canvasManager.savedRecordings)
this._addSavedRecording(recording);for(let subview of this.subviews){if(subview instanceof WI.CanvasContentView)
subview.refreshPreview();}}
detached()
{WI.domManager.hideDOMNodeHighlight();WI.canvasManager.removeEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSaved,this);WI.settings.canvasRecordingAutoCaptureFrameCount.removeEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureFrameCountChanged,this);WI.settings.canvasRecordingAutoCaptureEnabled.removeEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureEnabledChanged,this);super.detached();} 
_contentViewMouseEnter(event)
{let contentView=WI.View.fromElement(event.target);if(!(contentView instanceof WI.CanvasContentView))
return;let canvas=contentView.representedObject;if(canvas.cssCanvasName||canvas.contextType===WI.Canvas.ContextType.WebGPU){canvas.requestClientNodes((clientNodes)=>{WI.domManager.highlightDOMNodeList(clientNodes);});return;}
canvas.requestNode().then((node)=>{if(!node||!node.ownerDocument)
return;node.highlight();});}
_contentViewMouseLeave(event)
{WI.domManager.hideDOMNodeHighlight();}
_setRecordingAutoCaptureFrameCount(frameCount)
{if(this._recordingAutoCaptureNavigationItem.checked)
frameCount=Math.max(1,frameCount);let enabled=frameCount>0&&!!this._recordingAutoCaptureNavigationItem.checked;WI.canvasManager.setRecordingAutoCaptureFrameCount(enabled,frameCount);}
_updateRecordingAutoCaptureCheckboxLabel(frameCount)
{let active=document.activeElement===this._recordingAutoCaptureFrameCountInputElement;let selectionStart=this._recordingAutoCaptureFrameCountInputElement.selectionStart;let selectionEnd=this._recordingAutoCaptureFrameCountInputElement.selectionEnd;let direction=this._recordingAutoCaptureFrameCountInputElement.direction;let label=frameCount===1?WI.UIString("Record first %s frame"):WI.UIString("Record first %s frames");let fragment=document.createDocumentFragment();String.format(label,[this._recordingAutoCaptureFrameCountInputElement],String.standardFormatters,fragment,(a,b)=>{a.append(b);return a;});this._recordingAutoCaptureNavigationItem.label=fragment;if(active){this._recordingAutoCaptureFrameCountInputElement.selectionStart=selectionStart;this._recordingAutoCaptureFrameCountInputElement.selectionEnd=selectionEnd;this._recordingAutoCaptureFrameCountInputElement.direction=direction;}}
get _recordingAutoCaptureFrameCountInputElementValue()
{return parseInt(this._recordingAutoCaptureFrameCountInputElement.value);}
set _recordingAutoCaptureFrameCountInputElementValue(frameCount)
{if(this._recordingAutoCaptureFrameCountInputElement.value||frameCount)
this._recordingAutoCaptureFrameCountInputElement.value=frameCount;this._recordingAutoCaptureFrameCountInputElement.placeholder=frameCount;}
_updateRecordingAutoCaptureInputElementSize()
{let frameCount=this._recordingAutoCaptureFrameCountInputElementValue;if(isNaN(frameCount)||frameCount<0){frameCount=0;this._recordingAutoCaptureFrameCountInputElementValue=frameCount;}
this._recordingAutoCaptureFrameCountInputElement.autosize();return frameCount;}
_addSavedRecording(recording)
{if(!this._savedRecordingsContentView){this._savedRecordingsContentView=new WI.ContentView;this._savedRecordingsContentView.element.classList.add("canvas","saved-recordings");this.addSubview(this._savedRecordingsContentView);let header=this._savedRecordingsContentView.element.appendChild(document.createElement("header"));header.textContent=WI.UIString("Saved Recordings");this.hideContentPlaceholder();}
if(!this._savedRecordingsTreeOutline){const selectable=false;this._savedRecordingsTreeOutline=new WI.TreeOutline(selectable);this._savedRecordingsTreeOutline.addEventListener(WI.TreeOutline.Event.ElementClicked,this._handleSavedRecordingClicked,this);this._savedRecordingsContentView.element.appendChild(this._savedRecordingsTreeOutline.element);}
let recordingTreeElement=new WI.GeneralTreeElement(["recording"],recording.displayName,WI.Recording.displayNameForRecordingType(recording.type),recording);recordingTreeElement.selectable=false;this._savedRecordingsTreeOutline.appendChild(recordingTreeElement);}
_handleRecordingAutoCaptureInput(event)
{let frameCount=this._updateRecordingAutoCaptureInputElementSize();this._recordingAutoCaptureNavigationItem.checked=!!frameCount;this._setRecordingAutoCaptureFrameCount(frameCount);}
_handleRecordingAutoCaptureCheckedDidChange(event)
{this._setRecordingAutoCaptureFrameCount(this._recordingAutoCaptureFrameCountInputElementValue||0);}
_handleCanvasRecordingAutoCaptureEnabledChanged(event)
{this._recordingAutoCaptureNavigationItem.checked=WI.settings.canvasRecordingAutoCaptureEnabled.value;}
_handleCanvasRecordingAutoCaptureFrameCountChanged(event)
{if(this._recordingAutoCaptureFrameCountInputElementValue!==WI.settings.canvasRecordingAutoCaptureFrameCount.value)
this._recordingAutoCaptureFrameCountInputElementValue=WI.settings.canvasRecordingAutoCaptureFrameCount.value;this._updateRecordingAutoCaptureCheckboxLabel(WI.settings.canvasRecordingAutoCaptureFrameCount.value);}
_handleImportButtonNavigationItemClicked(event)
{WI.FileUtilities.importJSON((result)=>WI.canvasManager.processJSON(result),{multiple:true});}
_handleRecordingSaved(event)
{this._addSavedRecording(event.data.recording);}
_handleSavedRecordingClicked(event)
{WI.showRepresentedObject(event.data.treeElement.representedObject);}};WI.CanvasSidebarPanel=class CanvasSidebarPanel extends WI.NavigationSidebarPanel
{constructor()
{super("canvas",WI.UIString("Canvas"));this._canvas=null;this._recording=null;this._navigationBar=new WI.NavigationBar;this._scopeBar=null;this._placeholderScopeBarItem=null;const toolTip=WI.UIString("Start recording canvas actions.\nShift-click to record a single frame.");const altToolTip=WI.UIString("Stop recording canvas actions");this._recordButtonNavigationItem=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButtonNavigationItem.enabled=false;this._recordButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._recordButtonNavigationItem.label=WI.UIString("Start");this._recordButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleRecording,this);this._navigationBar.addNavigationItem(this._recordButtonNavigationItem);this._navigationBar.addNavigationItem(new WI.DividerNavigationItem);let importButtonNavigationItem=new WI.ButtonNavigationItem("import-recording",WI.UIString("Import"),"Images/Import.svg",15,15);importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);this._navigationBar.addNavigationItem(importButtonNavigationItem);this.addSubview(this._navigationBar);this._canvasTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._canvasTreeOutline.element.classList.add("canvas");this._recordingNavigationBar=new WI.NavigationBar;this._recordingNavigationBar.element.classList.add("hidden");this.contentView.addSubview(this._recordingNavigationBar);this._recordingContentContainer=this.contentView.element.appendChild(document.createElement("div"));this._recordingContentContainer.className="recording-content";this._recordingTreeOutline=this.contentTreeOutline;this._recordingContentContainer.appendChild(this._recordingTreeOutline.element);this._recordingTreeOutline.customIndent=true;this._recordingTreeOutline.registerScrollVirtualizer(this._recordingContentContainer,20);this._canvasTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);this._recordingTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);this._recordingProcessingOptionsContainer=null;this._selectedRecordingActionIndex=NaN;} 
get canvas()
{return this._canvas;}
set canvas(canvas)
{if(this._canvas===canvas)
return;if(this._canvas){this._canvas.removeEventListener(WI.Canvas.Event.RecordingStarted,this._updateRecordNavigationItem,this);this._canvas.removeEventListener(WI.Canvas.Event.RecordingStopped,this._updateRecordNavigationItem,this);this._canvas.recordingCollection.removeEventListener(WI.Collection.Event.ItemAdded,this._recordingAdded,this);this._canvas.recordingCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this._recordingRemoved,this);}
this._canvas=canvas;if(this._canvas){this._canvas.addEventListener(WI.Canvas.Event.RecordingStarted,this._updateRecordNavigationItem,this);this._canvas.addEventListener(WI.Canvas.Event.RecordingStopped,this._updateRecordNavigationItem,this);this._canvas.recordingCollection.addEventListener(WI.Collection.Event.ItemAdded,this._recordingAdded,this);this._canvas.recordingCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._recordingRemoved,this);}
this._canvasChanged();this._updateRecordNavigationItem();this._updateRecordingScopeBar();}
set recording(recording)
{if(recording===this._recording)
return;if(this._recording&&!this._recording.ready){this._recording.removeEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.removeEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);}
if(recording)
this.canvas=recording.source;this._recording=recording;if(this._recording&&!this._recording.ready){this._recording.addEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.addEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);}
this._updateRecordNavigationItem();this._updateRecordingScopeBar();this._recordingChanged();}
set action(action)
{if(!this._recording)
return;if(action===this._recording.actions[this._selectedRecordingActionIndex])
return;let selectedTreeElement=this._recordingTreeOutline.selectedTreeElement;if(!action){if(selectedTreeElement)
selectedTreeElement.deselect();return;}
if(selectedTreeElement&&selectedTreeElement instanceof WI.FolderTreeElement){let lastActionTreeElement=selectedTreeElement.children.lastValue;if(action===lastActionTreeElement.representedObject)
return;}
let treeElement=this._recordingTreeOutline.findTreeElement(action);if(!treeElement)
return;this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]=action;const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);this._selectedRecordingActionIndex=this._recording.actions.indexOf(action);}
updateRepresentedObjects()
{let objects=this.contentBrowser.currentRepresentedObjects;let canvas=objects.find((object)=>object instanceof WI.Canvas);if(canvas){this.canvas=canvas;let treeElement=this._canvasTreeOutline.findTreeElement(canvas);const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);return;}
let shaderProgram=objects.find((object)=>object instanceof WI.ShaderProgram);if(shaderProgram){this.canvas=shaderProgram.canvas;let treeElement=this._canvasTreeOutline.findTreeElement(shaderProgram);const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);return;}
let recording=objects.find((object)=>object instanceof WI.Recording);if(recording){this.canvas=recording.source;this.recording=recording;let recordingAction=objects.find((object)=>object instanceof WI.RecordingAction);if(recordingAction!==recording[WI.CanvasSidebarPanel.SelectedActionSymbol])
this.action=recordingAction;return;}
this.canvas=null;this.recording=null;}
attached()
{super.attached();this.contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this.updateRepresentedObjects,this);this.updateRepresentedObjects();if(this._recording){this._recordingTreeOutline.updateVirtualizedElementsDebouncer.force();let action=this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol];let treeElement=this._recordingTreeOutline.findTreeElement(action);if(treeElement){const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);}}}
detached()
{this.contentBrowser.removeEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this.updateRepresentedObjects,this);super.detached();}
canShowRepresentedObject(representedObject)
{return representedObject instanceof WI.Canvas||representedObject instanceof WI.ShaderProgram||representedObject instanceof WI.Recording;} 
get scrollElement()
{return this._recordingContentContainer;}
hasCustomFilters()
{return true;}
matchTreeElementAgainstCustomFilters(treeElement)
{if(treeElement instanceof WI.FolderTreeElement)
return true;if(treeElement instanceof WI.RecordingActionTreeElement&&treeElement.representedObject instanceof WI.RecordingInitialStateAction)
return true;return super.matchTreeElementAgainstCustomFilters(treeElement);}
initialLayout()
{super.initialLayout();let filterFunction=(treeElement)=>{if(!(treeElement.representedObject instanceof WI.RecordingAction))
return false;return treeElement.representedObject.isVisual||treeElement.representedObject instanceof WI.RecordingInitialStateAction;};const activatedByDefault=false;const defaultToolTip=WI.UIString("Only show visual actions");const activatedToolTip=WI.UIString("Show all actions");this.filterBar.addFilterBarButton("recording-show-visual-only",filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,"Images/Paint.svg",15,15);} 
_recordingAdded(event)
{this.recording=event.data.item;}
_recordingRemoved(event)
{this._updateRecordingScopeBar();let recording=event.data.item;if(recording===this.recording)
this.recording=this._canvas?Array.from(this._canvas.recordingCollection).lastValue:null;}
_scopeBarSelectionChanged()
{let selectedScopeBarItem=this._scopeBar.selectedItems[0];this.recording=selectedScopeBarItem.__recording||null;}
_toggleRecording(event)
{if(!this._canvas)
return;if(this._canvas.recordingActive)
this._canvas.stopRecording();else{let singleFrame=event.data.nativeEvent.shiftKey;this._canvas.startRecording(singleFrame);}}
_handleImportButtonNavigationItemClicked(event)
{WI.FileUtilities.importJSON((result)=>WI.canvasManager.processJSON(result),{multiple:true});}
_treeSelectionDidChange(event)
{let treeElement=event.target.selectedTreeElement;if(!treeElement)
return;if((treeElement instanceof WI.CanvasTreeElement)||(treeElement instanceof WI.ShaderProgramTreeElement)){if(this._placeholderScopeBarItem)
this._placeholderScopeBarItem.selected=true;this.showDefaultContentViewForTreeElement(treeElement);return;}
if(treeElement instanceof WI.FolderTreeElement)
treeElement=treeElement.children.lastValue;if(!(treeElement instanceof WI.RecordingActionTreeElement))
return;this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]=treeElement.representedObject;const onlyExisting=true;let recordingContentView=this.contentBrowser.contentViewForRepresentedObject(this._recording,onlyExisting);if(!recordingContentView)
return;this.contentBrowser.showContentView(recordingContentView);this._selectedRecordingActionIndex=treeElement.index;recordingContentView.updateActionIndex(this._selectedRecordingActionIndex);}
_canvasChanged()
{this._canvasTreeOutline.removeChildren();if(!this._canvas){this._recordingNavigationBar.element.classList.add("hidden");return;}
const showRecordings=false;let canvasTreeElement=new WI.CanvasTreeElement(this._canvas,showRecordings);canvasTreeElement.expanded=true;this._canvasTreeOutline.appendChild(canvasTreeElement);const omitFocus=false;const selectedByUser=false;canvasTreeElement.revealAndSelect(omitFocus,selectedByUser);if(WI.Canvas.ContextType.Canvas2D||this._canvas.contextType===WI.Canvas.ContextType.WebGL||this._canvas.contextType===WI.Canvas.ContextType.WebGL2)
this._recordButtonNavigationItem.enabled=true;this.recording=null;}
_recordingChanged()
{this._recordingTreeOutline.removeChildren();this._selectedRecordingActionIndex=NaN;if(this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer.remove();this._recordingProcessingOptionsContainer=null;}
if(!this._recording)
return;if(!this._recording.ready){if(!this._recording.processing)
this._recording.startProcessing();if(!this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer=this._recordingContentContainer.appendChild(document.createElement("div"));this._recordingProcessingOptionsContainer.classList.add("recording-processing-options");let createPauseButton=()=>{let spinner=new WI.IndeterminateProgressSpinner;this._recordingProcessingOptionsContainer.appendChild(spinner.element);let pauseButton=this._recordingProcessingOptionsContainer.appendChild(document.createElement("button"));pauseButton.textContent=WI.UIString("Pause Processing");pauseButton.addEventListener("click",(event)=>{this._recording.stopProcessing();spinner.element.remove();pauseButton.remove();createResumeButton();});};let createResumeButton=()=>{let resumeButton=this._recordingProcessingOptionsContainer.appendChild(document.createElement("button"));resumeButton.textContent=WI.UIString("Resume Processing");resumeButton.addEventListener("click",(event)=>{this._recording.startProcessing();resumeButton.remove();createPauseButton();});};if(this._recording.processing)
createPauseButton();else
createResumeButton();}}
this.contentBrowser.showContentViewForRepresentedObject(this._recording);if(this._scopeBar){let scopeBarItem=this._scopeBar.item(this._recording.displayName);scopeBarItem.selected=true;}
let initialStateAction=this._recording.actions[0];if(initialStateAction.ready&&!this._recordingTreeOutline.getCachedTreeElement(initialStateAction)){this._recordingTreeOutline.appendChild(new WI.RecordingActionTreeElement(initialStateAction,0,this._recording.type));if(!this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol])
this.action=initialStateAction;}
let cumulativeActionIndex=0;this._recording.frames.forEach((frame,frameIndex)=>{if(!frame.actions[0].ready)
return;let folder=this._recordingTreeOutline.getCachedTreeElement(frame);if(!folder)
folder=this._createRecordingFrameTreeElement(frame,frameIndex,this._recordingTreeOutline);for(let action of frame.actions){++cumulativeActionIndex;if(!action.ready||this._recordingTreeOutline.getCachedTreeElement(action))
break;this._createRecordingActionTreeElement(action,cumulativeActionIndex,folder);}});}
_updateRecordNavigationItem()
{if(!this._canvas||!(this._canvas.contextType===WI.Canvas.ContextType.Canvas2D||this._canvas.contextType===WI.Canvas.ContextType.WebGL||this._canvas.contextType===WI.Canvas.ContextType.WebGL2)){this._recordButtonNavigationItem.enabled=false;return;}
this._recordButtonNavigationItem.toggled=this._canvas.recordingActive;this._recordButtonNavigationItem.label=this._recordButtonNavigationItem.toggled?WI.UIString("Stop"):WI.UIString("Start");}
_updateRecordingScopeBar()
{if(this._scopeBar){this._placeholderScopeBarItem=null;this._recordingNavigationBar.removeNavigationItem(this._scopeBar);this._scopeBar=null;}
this._recordingNavigationBar.element.classList.toggle("hidden",!this._canvas);let hasRecordings=this._recording||(this._canvas&&this._canvas.recordingCollection.size);this.element.classList.toggle("has-recordings",hasRecordings);this.element.classList.toggle("showing-recording",!!this._recording);if(!hasRecordings)
return;let scopeBarItems=[];let selectedScopeBarItem=null;let createScopeBarItem=(recording)=>{let scopeBarItem=new WI.ScopeBarItem(recording.displayName,recording.displayName);if(recording===this._recording)
selectedScopeBarItem=scopeBarItem;else
scopeBarItem.selected=false;scopeBarItem.__recording=recording;scopeBarItems.push(scopeBarItem);};if(this._canvas&&this._canvas.recordingCollection){for(let recording of this._canvas.recordingCollection)
createScopeBarItem(recording);}
if(this._recording&&(!this._canvas||!this._canvas.recordingCollection.has(this._recording)))
createScopeBarItem(this._recording);if(!selectedScopeBarItem){selectedScopeBarItem=scopeBarItems[0];this._placeholderScopeBarItem=new WI.ScopeBarItem("canvas-recording-scope-bar-item-placeholder",WI.UIString("Recordings"),{exclusive:true,hidden:true});this._placeholderScopeBarItem.selected=true;scopeBarItems.unshift(this._placeholderScopeBarItem);}
this._scopeBar=new WI.ScopeBar("canvas-recording-scope-bar",scopeBarItems,selectedScopeBarItem,true);this._scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectionChanged,this);this._recordingNavigationBar.insertNavigationItem(this._scopeBar,0);}
_createRecordingFrameTreeElement(frame,index,parent)
{let folder=new WI.FolderTreeElement(WI.UIString("Frame %d").format((index+1).toLocaleString()),frame);if(!isNaN(frame.duration)){const higherResolution=true;folder.status=Number.secondsToString(frame.duration/1000,higherResolution);}
parent.appendChild(folder);return folder;}
_createRecordingActionTreeElement(action,index,parent)
{let treeElement=new WI.RecordingActionTreeElement(action,index,this._recording.type);parent.appendChild(treeElement);if(parent instanceof WI.FolderTreeElement&&parent.representedObject instanceof WI.RecordingFrame){if(action!==parent.representedObject.actions.lastValue){parent.addClassName("processing");if(!(parent.subtitle instanceof HTMLProgressElement))
parent.subtitle=document.createElement("progress");if(parent.statusElement)
parent.subtitle.style.setProperty("width",`calc(100% - ${parent.statusElement.offsetWidth + 4}px`);parent.subtitle.value=parent.representedObject.actions.indexOf(action)/parent.representedObject.actions.length;}else{parent.removeClassName("processing");if(parent.representedObject.incomplete)
parent.subtitle=WI.UIString("Incomplete");else
parent.subtitle="";}}
if(action===this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol])
this.action=action;return treeElement;}
_handleRecordingProcessedAction(event)
{let{action,index}=event.data;this._recordingTreeOutline.element.dataset.indent=Number.countDigits(index);let isInitialStateAction=!index;this._createRecordingActionTreeElement(action,index,isInitialStateAction?this._recordingTreeOutline:this._recordingTreeOutline.children.lastValue);if(!this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]){this.action=this._recording.actions[0];}
if(this._recording.ready){this._recording.removeEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.removeEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);if(this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer.remove();this._recordingProcessingOptionsContainer=null;}}}
_handleRecordingStartProcessingFrame(event)
{let{frame,index}=event.data;this._createRecordingFrameTreeElement(frame,index,this._recordingTreeOutline);}};WI.CanvasSidebarPanel.SelectedActionSymbol=Symbol("selected-action");WI.CanvasTreeElement=class CanvasTreeElement extends WI.FolderizedTreeElement
{constructor(representedObject,showRecordings=true)
{let subtitle=WI.Canvas.displayNameForContextType(representedObject.contextType);super(["canvas",representedObject.contextType],representedObject.displayName,subtitle,representedObject);this.registerFolderizeSettings("shader-programs",WI.UIString("Shader Programs"),this.representedObject.shaderProgramCollection,WI.ShaderProgramTreeElement);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStarted,this._updateStatus,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStopped,this._updateStatus,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);this._showRecordings=showRecordings;if(this._showRecordings){function createRecordingTreeElement(recording){return new WI.GeneralTreeElement(["recording"],recording.displayName,null,recording);}
this.registerFolderizeSettings("recordings",WI.UIString("Recordings"),this.representedObject.recordingCollection,createRecordingTreeElement);this.representedObject.recordingCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.recordingCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);}} 
onattach()
{super.onattach();this.element.addEventListener("mouseover",this._handleMouseOver.bind(this));this.element.addEventListener("mouseout",this._handleMouseOut.bind(this));this.onpopulate();}
onpopulate()
{super.onpopulate();if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();for(let program of this.representedObject.shaderProgramCollection)
this.addChildForRepresentedObject(program);if(this._showRecordings){for(let recording of this.representedObject.recordingCollection)
this.addChildForRepresentedObject(recording);}}
populateContextMenu(contextMenu,event)
{super.populateContextMenu(contextMenu,event);contextMenu.appendItem(WI.UIString("Log Canvas Context"),()=>{WI.RemoteObject.resolveCanvasContext(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject)
return;const text=WI.UIString("Selected Canvas Context");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);});});contextMenu.appendSeparator();} 
_handleItemAdded(event)
{this.addChildForRepresentedObject(event.data.item);}
_handleItemRemoved(event)
{this.removeChildForRepresentedObject(event.data.item);}
_handleMouseOver(event)
{if(this.representedObject.cssCanvasName||this.representedObject.contextType===WI.Canvas.ContextType.WebGPU){this.representedObject.requestClientNodes((clientNodes)=>{WI.domManager.highlightDOMNodeList(clientNodes);});}else{this.representedObject.requestNode((node)=>{if(!node||!node.ownerDocument)
return;node.highlight();});}}
_handleMouseOut(event)
{WI.domManager.hideDOMNodeHighlight();}
_updateStatus()
{if(this.representedObject.recordingActive){if(!this.status||!this.status.__showingSpinner){let spinner=new WI.IndeterminateProgressSpinner;this.status=spinner.element;this.status.__showingSpinner=true;}}else{if(this.status&&this.status.__showingSpinner)
this.status="";}}};WI.ChangesDetailsSidebarPanel=class ChangesDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel
{constructor()
{super("changes-details",WI.UIString("Changes"));this.element.classList.add("changes-panel");this.element.dir="ltr";} 
supportsDOMNode(nodeToInspect)
{return nodeToInspect.nodeType()===Node.ELEMENT_NODE;}
attached()
{super.attached();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.CSSManager.addEventListener(WI.CSSManager.Event.ModifiedStylesChanged,this.needsLayout,this);}
detached()
{WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.CSSManager.removeEventListener(WI.CSSManager.Event.ModifiedStylesChanged,this.needsLayout,this);super.detached();} 
layout()
{super.layout();this.element.removeChildren();let modifiedStyles=WI.cssManager.modifiedStyles;if(WI.settings.cssChangesPerNode.value){if(this.domNode){let stylesForNode=WI.cssManager.stylesForNode(this.domNode);modifiedStyles=modifiedStyles.filter((style)=>{if(style.node===this.domNode)
return true;if(style.ownerRule)
return stylesForNode.matchedRules.some((matchedRule)=>style.ownerRule.isEqualTo(matchedRule));return false;});}else
modifiedStyles=[];}
this.element.classList.toggle("empty",!modifiedStyles.length);if(!modifiedStyles.length){this.element.textContent=WI.UIString("No CSS Changes");return;}
let declarationsForStyleSheet=new Map();for(let style of modifiedStyles){let styleDeclarations=declarationsForStyleSheet.get(style.ownerStyleSheet);if(!styleDeclarations){styleDeclarations=[];declarationsForStyleSheet.set(style.ownerStyleSheet,styleDeclarations);}
styleDeclarations.push(style);}
for(let[styleSheet,styles]of declarationsForStyleSheet){let resourceSection=this.element.appendChild(document.createElement("section"));resourceSection.classList.add("resource-section");let resourceHeader=resourceSection.appendChild(document.createElement("div"));resourceHeader.classList.add("header");resourceHeader.append(styleSheet.isInlineStyleAttributeStyleSheet()?styles[0].selectorText:this._createLocationLink(styleSheet));for(let style of styles)
resourceSection.append(this._createRuleElement(style));}} 
_createRuleElement(style)
{let ruleElement=document.createElement("div");ruleElement.classList.add("css-rule");let selectorLineElement=ruleElement.appendChild(document.createElement("div"));selectorLineElement.className="selector-line";let selectorElement=selectorLineElement.appendChild(document.createElement("span"));selectorElement.className="selector";if(style.type===WI.CSSStyleDeclaration.Type.Inline){selectorElement.textContent=WI.UIString("Style Attribute");selectorElement.classList.add("style-attribute");}else
selectorElement.textContent=style.ownerRule.selectorText;selectorLineElement.append(" {\n");function onEach(cssProperty,action){let className="";if(action===1)
className="added";else if(action===-1)
className="removed";else
className="unchanged";let propertyLineElement=ruleElement.appendChild(document.createElement("div"));propertyLineElement.classList.add("css-property-line",className);const delegate=null;let stylePropertyView=new WI.SpreadsheetStyleProperty(delegate,cssProperty,{readOnly:true,hideDocumentation:true});propertyLineElement.append(WI.indentString(),stylePropertyView.element,"\n");}
function comparator(a,b){return a.equals(b);}
Array.diffArrays(style.initialState.visibleProperties,style.visibleProperties,onEach,comparator);let closeBraceElement=document.createElement("span");closeBraceElement.className="close-brace";closeBraceElement.textContent="}";ruleElement.append(closeBraceElement,"\n");return ruleElement;}
_createLocationLink(styleSheet)
{const options={nameStyle:WI.SourceCodeLocation.NameStyle.Short,columnStyle:WI.SourceCodeLocation.ColumnStyle.Hidden,dontFloat:true,ignoreNetworkTab:true,ignoreSearchTab:true,};const lineNumber=0;const columnNumber=0;let sourceCodeLocation=styleSheet.createSourceCodeLocation(lineNumber,columnNumber);return WI.createSourceCodeLocationLink(sourceCodeLocation,options);}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this.needsLayout();}};WI.ChartDetailsSectionRow=class ChartDetailsSectionRow extends WI.DetailsSectionRow
{constructor(delegate,chartSize,innerRadiusRatio)
{super(WI.UIString("No Chart Available"));innerRadiusRatio=innerRadiusRatio||0;this.element.classList.add("chart");this._titleElement=document.createElement("div");this._titleElement.className="title";this.element.appendChild(this._titleElement);let chartContentElement=document.createElement("div");chartContentElement.className="chart-content";this.element.appendChild(chartContentElement);this._chartElement=createSVGElement("svg");chartContentElement.appendChild(this._chartElement);this._legendElement=document.createElement("div");this._legendElement.className="legend";chartContentElement.appendChild(this._legendElement);this._delegate=delegate;this._items=new Map;this._title="";this._chartSize=chartSize;this._radius=(this._chartSize/2)-1;this._innerRadius=innerRadiusRatio?Math.floor(this._radius*innerRadiusRatio):0;this._total=0;this._svgFiltersElement=document.createElement("svg");this._svgFiltersElement.classList.add("defs-only");this.element.append(this._svgFiltersElement);this._checkboxStyleElement=document.createElement("style");this._checkboxStyleElement.id="checkbox-styles";document.getElementsByTagName("head")[0].append(this._checkboxStyleElement);function createEmptyChartPathData(c,r1,r2)
{const a1=0;const a2=Math.PI*1.9999;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,1,1,x2,y2,"Z","M",x3,y3,"A",r2,r2,0,1,0,x4,y4,"Z"].join(" ");}
this._emptyChartPath=createSVGElement("path");this._emptyChartPath.setAttribute("d",createEmptyChartPathData(this._chartSize/2,this._radius,this._innerRadius));this._emptyChartPath.classList.add("empty-chart");this._chartElement.appendChild(this._emptyChartPath);} 
get chartSize()
{return this._chartSize;}
set title(title)
{if(this._title===title)
return;this._title=title;this._titleElement.textContent=title;}
get total()
{return this._total;}
addItem(id,label,value,color,checkbox,checked)
{if(this._items.has(id))
return;if(value<0)
return;this._items.set(id,{label,value,color,checkbox,checked});this._total+=value;this._needsLayout();}
setItemValue(id,value)
{let item=this._items.get(id);if(!item)
return;if(value<0)
return;if(item.value===value)
return;this._total+=value-item.value;item.value=value;this._needsLayout();}
clearItems()
{for(let item of this._items.values()){let path=item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol];if(path)
path.remove();}
this._total=0;this._items.clear();this._needsLayout();} 
_addCheckboxColorFilter(id,r,g,b)
{for(let i=0;i<this._svgFiltersElement.childNodes.length;++i){if(this._svgFiltersElement.childNodes[i].id===id)
return;}
r/=255;b/=255;g/=255;let filterElement=createSVGElement("filter");filterElement.id=id;filterElement.setAttribute("color-interpolation-filters","sRGB");let values=[1-r,0,0,0,r,1-g,0,0,0,g,1-b,0,0,0,b,0,0,0,1,0];let colorMatrixPrimitive=createSVGElement("feColorMatrix");colorMatrixPrimitive.setAttribute("type","matrix");colorMatrixPrimitive.setAttribute("values",values.join(" "));function createGammaPrimitive(tagName,value)
{let gammaPrimitive=createSVGElement(tagName);gammaPrimitive.setAttribute("type","gamma");gammaPrimitive.setAttribute("exponent",value);return gammaPrimitive;}
let componentTransferPrimitive=createSVGElement("feComponentTransfer");componentTransferPrimitive.append(createGammaPrimitive("feFuncR",1.4),createGammaPrimitive("feFuncG",1.4),createGammaPrimitive("feFuncB",1.4));filterElement.append(colorMatrixPrimitive,componentTransferPrimitive);this._svgFiltersElement.append(filterElement);let styleSheet=this._checkboxStyleElement.sheet;styleSheet.insertRule(".details-section > .content > .group > .row.chart > .chart-content > .legend > .legend-item > label > input[type=checkbox]."+id+" { filter: grayscale(1) url(#"+id+") }",0);}
_updateLegend()
{if(!this._items.size){this._legendElement.removeChildren();return;}
function formatItemValue(item)
{if(this._delegate&&typeof this._delegate.formatChartValue==="function")
return this._delegate.formatChartValue(item.value);return item.value;}
for(let[id,item]of this._items){if(item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol]){let valueElement=item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol];valueElement.textContent=formatItemValue.call(this,item);continue;}
let labelElement=document.createElement("label");let keyElement;if(item.checkbox){let className=id.toLowerCase();let rgb=item.color.substring(4,item.color.length-1).replace(/ /g,"").split(",");if(rgb[0]===rgb[1]&&rgb[1]===rgb[2])
rgb[0]=rgb[1]=rgb[2]=Math.min(160,rgb[0]);keyElement=document.createElement("input");keyElement.type="checkbox";keyElement.classList.add(className);keyElement.checked=item.checked;keyElement[WI.ChartDetailsSectionRow.DataItemIdSymbol]=id;keyElement.addEventListener("change",this._legendItemCheckboxValueChanged.bind(this));this._addCheckboxColorFilter(className,rgb[0],rgb[1],rgb[2]);}else{keyElement=document.createElement("div");keyElement.classList.add("color-key");keyElement.style.backgroundColor=item.color;}
labelElement.append(keyElement,item.label);let valueElement=document.createElement("div");valueElement.classList.add("value");valueElement.textContent=formatItemValue.call(this,item);item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol]=valueElement;let legendItemElement=document.createElement("div");legendItemElement.classList.add("legend-item");legendItemElement.append(labelElement,valueElement);this._legendElement.append(legendItemElement);}}
_legendItemCheckboxValueChanged(event)
{let checkbox=event.target;let id=checkbox[WI.ChartDetailsSectionRow.DataItemIdSymbol];this.dispatchEventToListeners(WI.ChartDetailsSectionRow.Event.LegendItemChecked,{id,checked:checkbox.checked});}
_needsLayout()
{if(this._scheduledLayoutUpdateIdentifier)
return;this._scheduledLayoutUpdateIdentifier=requestAnimationFrame(this._updateLayout.bind(this));}
_updateLayout()
{if(this._scheduledLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier);this._scheduledLayoutUpdateIdentifier=undefined;}
this._updateLegend();this._chartElement.setAttribute("width",this._chartSize);this._chartElement.setAttribute("height",this._chartSize);this._chartElement.setAttribute("viewbox","0 0 "+this._chartSize+" "+this._chartSize);function createSegmentPathData(c,a1,a2,r1,r2)
{const largeArcFlag=((a2-a1)%(Math.PI*2))>Math.PI?1:0;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,largeArcFlag,1,x2,y2,"L",x3,y3,"A",r2,r2,0,largeArcFlag,0,x4,y4,"Z"].join(" ");}
const minimumDisplayValue=this._total*0.015;let items=[];for(let item of this._items.values()){item.displayValue=item.value?Math.max(minimumDisplayValue,item.value):0;if(item.displayValue)
items.push(item);}
if(items.length>1){items.sort(function(a,b){return a.value-b.value;});let largeItemCount=items.length;let totalAdjustedValue=0;for(let item of items){if(item.value<minimumDisplayValue){totalAdjustedValue+=minimumDisplayValue-item.value;largeItemCount--;continue;}
if(!totalAdjustedValue||!largeItemCount)
break;const donatedValue=totalAdjustedValue/largeItemCount;if(item.displayValue-donatedValue>=minimumDisplayValue){item.displayValue-=donatedValue;totalAdjustedValue-=donatedValue;}
largeItemCount--;}}
const center=this._chartSize/2;let startAngle=-Math.PI/2;let endAngle=0;for(let[id,item]of this._items){let path=item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol];if(!path){path=createSVGElement("path");path.classList.add("chart-segment");path.setAttribute("fill",item.color);this._chartElement.appendChild(path);item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol]=path;}
if(!item.value){path.classList.add("hidden");continue;}
const angle=(item.displayValue/this._total)*Math.PI*2;endAngle=startAngle+angle;path.setAttribute("d",createSegmentPathData(center,startAngle,endAngle,this._radius,this._innerRadius));path.classList.remove("hidden");startAngle=endAngle;}}};WI.ChartDetailsSectionRow.DataItemIdSymbol=Symbol("chart-details-section-row-data-item-id");WI.ChartDetailsSectionRow.ChartSegmentPathSymbol=Symbol("chart-details-section-row-chart-segment-path");WI.ChartDetailsSectionRow.LegendItemValueElementSymbol=Symbol("chart-details-section-row-legend-item-value-element");WI.ChartDetailsSectionRow.Event={LegendItemChecked:"chart-details-section-row-legend-item-checked"};WI.CheckboxNavigationItem=class CheckboxNavigationItem extends WI.NavigationItem
{constructor(identifier,label,checked)
{super(identifier,"checkbox");this._checkboxElement=this.element.appendChild(document.createElement("input"));this._checkboxElement.checked=checked;this._checkboxElement.id="checkbox-navigation-item-"+identifier;this._checkboxElement.type="checkbox";this._checkboxElement.addEventListener("change",this._checkboxChanged.bind(this));this._checkboxLabel=this.element.appendChild(document.createElement("label"));this._checkboxLabel.className="toggle";this._checkboxLabel.setAttribute("for",this._checkboxElement.id);this._checkboxLabel.addEventListener("click",this._handleLabelClick.bind(this));this.label=label;} 
get checked()
{return this._checkboxElement.checked;}
set checked(flag)
{this._checkboxElement.checked=flag;}
set label(label)
{this._checkboxLabel.removeChildren();if(label)
this._checkboxLabel.append(label);} 
get additionalClassNames()
{return["checkbox","button"];} 
_checkboxChanged(event)
{this.dispatchEventToListeners(WI.CheckboxNavigationItem.Event.CheckedDidChange);}
_handleLabelClick(event)
{if(WI.isEventTargetAnEditableField(event))
event.stop();}};WI.CheckboxNavigationItem.Event={CheckedDidChange:"checkbox-navigation-item-checked-did-change",};

WI.CircleChart=class CircleChart extends WI.View
{constructor({size,innerRadiusRatio})
{super();this._data=[];this._size=size;this._radius=(size/2)-1;this._innerRadius=innerRadiusRatio?Math.floor(this._radius*innerRadiusRatio):0;this.element.classList.add("circle-chart");this._chartElement=this.element.appendChild(createSVGElement("svg"));this._chartElement.setAttribute("width",size);this._chartElement.setAttribute("height",size);this._chartElement.setAttribute("viewBox",`0 0 ${size} ${size}`);this._pathElements=[];this._values=[];this._total=0;let backgroundPath=this._chartElement.appendChild(createSVGElement("path"));backgroundPath.setAttribute("d",this._createCompleteCirclePathData(this._size/2,this._radius,this._innerRadius));backgroundPath.classList.add("background");} 
get size(){return this._size;}
get centerElement()
{if(!this._centerElement){this._centerElement=this.element.appendChild(document.createElement("div"));this._centerElement.classList.add("center");this._centerElement.style.width=this._centerElement.style.height=this._radius+"px";this._centerElement.style.top=this._centerElement.style.left=(this._radius-this._innerRadius)+"px";}
return this._centerElement;}
get segments()
{return this._segments;}
set segments(segmentClassNames)
{for(let pathElement of this._pathElements)
pathElement.remove();this._pathElements=[];for(let className of segmentClassNames){let pathElement=this._chartElement.appendChild(createSVGElement("path"));pathElement.classList.add("segment",className);this._pathElements.push(pathElement);}}
get values()
{return this._values;}
set values(values)
{this._values=values;this._total=0;for(let value of values)
this._total+=value;}
clear()
{this.values=new Array(this._values.length).fill(0);} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;if(!this._values.length)
return;const center=this._size/2;let startAngle=-Math.PI/2;let endAngle=0;for(let i=0;i<this._values.length;++i){let value=this._values[i];let pathElement=this._pathElements[i];if(value===0)
pathElement.removeAttribute("d");else if(value===this._total)
pathElement.setAttribute("d",this._createCompleteCirclePathData(center,this._radius,this._innerRadius));else{let angle=(value/this._total)*Math.PI*2;endAngle=startAngle+angle;pathElement.setAttribute("d",this._createSegmentPathData(center,startAngle,endAngle,this._radius,this._innerRadius));startAngle=endAngle;}}} 
_createCompleteCirclePathData(c,r1,r2)
{const a1=0;const a2=Math.PI*1.9999;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,1,1,x2,y2,"Z","M",x3,y3,"A",r2,r2,0,1,0,x4,y4,"Z"].join(" ");}
_createSegmentPathData(c,a1,a2,r1,r2)
{const largeArcFlag=((a2-a1)%(Math.PI*2))>Math.PI?1:0;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,largeArcFlag,1,x2,y2,"L",x3,y3,"A",r2,r2,0,largeArcFlag,0,x4,y4,"Z"].join(" ");}};WI.ClusterContentView=class ClusterContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("cluster");this._contentViewContainer=new WI.ContentViewContainer;this._contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);this.addSubview(this._contentViewContainer);WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);} 
get navigationItems()
{var currentContentView=this._contentViewContainer.currentContentView;return currentContentView?currentContentView.navigationItems:[];}
get contentViewContainer()
{return this._contentViewContainer;}
get supportsSplitContentBrowser()
{if(this._contentViewContainer.currentContentView)
return this._contentViewContainer.currentContentView.supportsSplitContentBrowser;return super.supportsSplitContentBrowser;}
get shouldSaveStateWhenHidden()
{return true;}
closed()
{super.closed();this._contentViewContainer.closeAllContentViews();WI.ContentView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.removeEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.removeEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);}
canGoBack()
{return this._contentViewContainer.canGoBack();}
canGoForward()
{return this._contentViewContainer.canGoForward();}
goBack()
{this._contentViewContainer.goBack();}
goForward()
{this._contentViewContainer.goForward();}
get scrollableElements()
{if(!this._contentViewContainer.currentContentView)
return[];return this._contentViewContainer.currentContentView.scrollableElements;}
get selectionPathComponents()
{if(!this._contentViewContainer.currentContentView)
return[];return this._contentViewContainer.currentContentView.selectionPathComponents;}
get supplementalRepresentedObjects()
{if(!this._contentViewContainer.currentContentView)
return[];return this._contentViewContainer.currentContentView.supplementalRepresentedObjects;}
get handleCopyEvent()
{var currentContentView=this._contentViewContainer.currentContentView;return currentContentView&&typeof currentContentView.handleCopyEvent==="function"?currentContentView.handleCopyEvent.bind(currentContentView):null;}
get supportsSave()
{var currentContentView=this._contentViewContainer.currentContentView;return currentContentView&&currentContentView.supportsSave;}
get saveData()
{var currentContentView=this._contentViewContainer.currentContentView;return currentContentView&&currentContentView.saveData||null;}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return null;return currentContentView.numberOfSearchResults;}
get hasPerformedSearch()
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return false;return currentContentView.hasPerformedSearch;}
set automaticallyRevealFirstSearchResult(reveal)
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.automaticallyRevealFirstSearchResult=reveal;}
performSearch(query)
{this._searchQuery=query;var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.performSearch(query);}
searchCleared()
{this._searchQuery=null;var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.searchCleared();}
searchQueryWithSelection()
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return null;return currentContentView.searchQueryWithSelection();}
revealPreviousSearchResult(changeFocus)
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.revealPreviousSearchResult(changeFocus);}
revealNextSearchResult(changeFocus)
{var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch)
return;currentContentView.revealNextSearchResult(changeFocus);} 
_currentContentViewDidChange(event)
{var currentContentView=this._contentViewContainer.currentContentView;if(currentContentView&&currentContentView.supportsSearch){if(this._searchQuery)
currentContentView.performSearch(this._searchQuery);else
currentContentView.searchCleared();}
this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_contentViewSelectionPathComponentDidChange(event)
{if(event.target!==this._contentViewContainer.currentContentView)
return;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_contentViewSupplementalRepresentedObjectsDidChange(event)
{if(event.target!==this._contentViewContainer.currentContentView)
return;this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_contentViewNumberOfSearchResultsDidChange(event)
{if(event.target!==this._contentViewContainer.currentContentView)
return;this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};(function(){



function tokenizeLinkString(stream,state)
{if(state._linkQuoteCharacter)
stream.eatWhile(new RegExp("[^"+state._linkQuoteCharacter+"]"));else
stream.eatWhile(/[^\s\u00a0=<>\"\']/);if(!stream.eol())
state._linkTokenize=tokenizeEndOfLinkString;return"link";}
function tokenizeEndOfLinkString(stream,state)
{if(state._linkQuoteCharacter)
stream.eat(state._linkQuoteCharacter);var style=state._linkBaseStyle;delete state._linkTokenize;delete state._linkQuoteCharacter;delete state._linkBaseStyle;delete state._srcSetTokenizeState;return style;}
function tokenizeSrcSetString(stream,state)
{if(state._srcSetTokenizeState==="link"){if(state._linkQuoteCharacter)
stream.eatWhile(new RegExp("[^\\s,"+state._linkQuoteCharacter+"]"));else
stream.eatWhile(/[^\s,\u00a0=<>\"\']/);}else{stream.eatSpace();if(state._linkQuoteCharacter)
stream.eatWhile(new RegExp("[^,"+state._linkQuoteCharacter+"]"));else
stream.eatWhile(/[^\s\u00a0=<>\"\']/);stream.eatWhile(/[\s,]/);}


if(stream.eol()||(!state._linkQuoteCharacter||stream.peek()===state._linkQuoteCharacter))
state._linkTokenize=tokenizeEndOfLinkString;if(state._srcSetTokenizeState==="link"){state._srcSetTokenizeState="descriptor";return"link";}
state._srcSetTokenizeState="link";return state._linkBaseStyle;}
function extendedXMLToken(stream,state)
{if(state._linkTokenize){var style=state._linkTokenize(stream,state);return style&&(style+" m-"+this.name);}
var startPosition=stream.pos;var style=this._token(stream,state);if(style==="attribute"){
var text=stream.current().toLowerCase();if(text==="src"||/\bhref\b/.test(text))
state._expectLink=true;else if(text==="srcset")
state._expectSrcSet=true;else{delete state._expectLink;delete state._expectSrcSet;}}else if(state._expectLink&&style==="string"){var current=stream.current();
if(current!=="\"\""&&current!=="''"){delete state._expectLink;state._linkTokenize=tokenizeLinkString;state._linkBaseStyle=style;var quote=current[0];state._linkQuoteCharacter=quote==="'"||quote==="\""?quote:null;stream.pos=startPosition;
if(state._linkQuoteCharacter)
stream.eat(state._linkQuoteCharacter);}}else if(state._expectSrcSet&&style==="string"){var current=stream.current();
if(current!=="\"\""&&current!=="''"){delete state._expectSrcSet;state._srcSetTokenizeState="link";state._linkTokenize=tokenizeSrcSetString;state._linkBaseStyle=style;var quote=current[0];state._linkQuoteCharacter=quote==="'"||quote==="\""?quote:null;stream.pos=startPosition;
if(state._linkQuoteCharacter)
stream.eat(state._linkQuoteCharacter);}}else if(style){

delete state._expectLink;delete state._expectSrcSet;}
return style&&(style+" m-"+this.name);}
function tokenizeCSSURLString(stream,state)
{if(state._unquotedURLString&&stream.eatSpace())
return null;var ch=null;var escaped=false;var reachedEndOfURL=false;var lastNonWhitespace=stream.pos;var quote=state._urlQuoteCharacter;while((ch=stream.next())!=null){if(ch===quote&&!escaped){reachedEndOfURL=true;break;}
escaped=!escaped&&ch==="\\";if(!/[\s\u00a0]/.test(ch))
lastNonWhitespace=stream.pos;}
if(state._unquotedURLString)
stream.pos=lastNonWhitespace;if(reachedEndOfURL){if(!state._unquotedURLString)
stream.backUp(1);this._urlTokenize=tokenizeEndOfCSSURLString;}
return"link";}
function tokenizeEndOfCSSURLString(stream,state)
{if(!state._unquotedURLString)
stream.eat(state._urlQuoteCharacter);var style=state._urlBaseStyle;delete state._urlTokenize;delete state._urlQuoteCharacter;delete state._urlBaseStyle;return style;}
function extendedCSSToken(stream,state)
{var hexColorRegex=/#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b/g;if(state._urlTokenize){var style=state._urlTokenize(stream,state);return style&&(style+" m-"+(this.alternateName||this.name));}
var startPosition=stream.pos;var style=this._token(stream,state);if(style){if(style==="atom"){if(stream.current()==="url"){state._expectLink=true;}else if(hexColorRegex.test(stream.current()))
style=style+" hex-color";}else if(style==="error"){if(state.state==="atBlock"||state.state==="atBlock_parens"){switch(stream.current()){case"prefers-color-scheme":case"light":case"dark":case"prefers-reduced-motion":case"reduce":case"no-preference":case"inverted-colors":case"inverted":case"color-gamut":case"p3":case"rec2020":case"display-mode":case"fullscreen":case"standalone":case"minimal-ui":case"browser":case"video-playable-inline":case"transform-2d":case"transform-3d":style="property";break;}}}else if(state._expectLink){delete state._expectLink;if(style==="string"){state._urlTokenize=tokenizeCSSURLString;state._urlBaseStyle=style;var quote=stream.current()[0];state._urlQuoteCharacter=quote==="'"||quote==="\""?quote:")";state._unquotedURLString=state._urlQuoteCharacter===")";stream.pos=startPosition;
if(!state._unquotedURLString)
stream.eat(state._urlQuoteCharacter);}}}
return style&&(style+" m-"+(this.alternateName||this.name));}
function extendedJavaScriptToken(stream,state)
{var style=this._token(stream,state);if(style==="number"&&stream.current().endsWith("n"))
style+=" bigint";return style&&(style+" m-"+(this.alternateName||this.name));}
function scrollCursorIntoView(codeMirror,event)
{
event.preventDefault();function delayedWork()
{if(!codeMirror.getWrapperElement().classList.contains("CodeMirror-focused"))
return;var cursorElement=codeMirror.getScrollerElement().getElementsByClassName("CodeMirror-cursor")[0];if(cursorElement)
cursorElement.scrollIntoViewIfNeeded(false);}

setTimeout(delayedWork,0);}
CodeMirror.extendMode("css",{token:extendedCSSToken});CodeMirror.extendMode("xml",{token:extendedXMLToken});CodeMirror.extendMode("javascript",{token:extendedJavaScriptToken});CodeMirror.defineInitHook(function(codeMirror){codeMirror.on("scrollCursorIntoView",scrollCursorIntoView);});let whitespaceStyleElement=null;let whitespaceCountsWithStyling=new Set;CodeMirror.defineOption("showWhitespaceCharacters",false,function(cm,value,old){if(!value||(old&&old!==CodeMirror.Init)){cm.removeOverlay("whitespace");return;}
cm.addOverlay({name:"whitespace",token(stream){if(stream.peek()===" "){let count=0;while(stream.peek()===" "){++count;stream.next();}
if(!whitespaceCountsWithStyling.has(count)){whitespaceCountsWithStyling.add(count);if(!whitespaceStyleElement)
whitespaceStyleElement=document.head.appendChild(document.createElement("style"));const middleDot="\\00B7";let styleText=whitespaceStyleElement.textContent;styleText+=`.show-whitespace-characters .CodeMirror .cm-whitespace-${count}::before {`;styleText+=`content: "${middleDot.repeat(count)}";`;styleText+=`}`;whitespaceStyleElement.textContent=styleText;}
return`whitespace whitespace-${count}`;}
while(!stream.eol()&&stream.peek()!==" ")
stream.next();return null;}});});CodeMirror.defineExtension("hasLineClass",function(line,where,className){var classProperty=where==="text"?"textClass":(where==="background"?"bgClass":"wrapClass");var lineInfo=this.lineInfo(line);if(!lineInfo)
return false;if(!lineInfo[classProperty])
return false;if(lineInfo[classProperty]===className)
return true;var index=lineInfo[classProperty].indexOf(className);if(index===-1)
return false;var paddedClass=" "+lineInfo[classProperty]+" ";return paddedClass.indexOf(" "+className+" ",index)!==-1;});CodeMirror.defineExtension("setUniqueBookmark",function(position,options){var marks=this.findMarksAt(position);for(var i=0;i<marks.length;++i){if(marks[i].__uniqueBookmark){marks[i].clear();break;}}
var uniqueBookmark=this.setBookmark(position,options);uniqueBookmark.__uniqueBookmark=true;return uniqueBookmark;});CodeMirror.defineExtension("toggleLineClass",function(line,where,className){if(this.hasLineClass(line,where,className)){this.removeLineClass(line,where,className);return false;}
this.addLineClass(line,where,className);return true;});CodeMirror.defineExtension("alterNumberInRange",function(amount,startPosition,endPosition,updateSelection){if(startPosition.line!==endPosition.line)
return false;if(updateSelection){var selectionStart=this.getCursor("start");var selectionEnd=this.getCursor("end");}
var line=this.getLine(startPosition.line);var foundPeriod=false;var start=NaN;var end=NaN;for(var i=startPosition.ch;i>=0;--i){var character=line.charAt(i);if(character==="."){if(foundPeriod)
break;foundPeriod=true;}else if(character!=="-"&&character!=="+"&&isNaN(parseInt(character))){if(i===startPosition.ch){end=i;continue;}
break;}
start=i;}
if(isNaN(end)){for(var i=startPosition.ch+1;i<line.length;++i){var character=line.charAt(i);if(character==="."){if(foundPeriod){end=i;break;}
foundPeriod=true;}else if(isNaN(parseInt(character))){end=i;break;}
end=i+1;}}
if(isNaN(start)||isNaN(end))
return false;var number=parseFloat(line.substring(start,end));var alteredNumber=Number((number+amount).toFixed(6));var alteredNumberString=alteredNumber.toString();var from={line:startPosition.line,ch:start};var to={line:startPosition.line,ch:end};this.replaceRange(alteredNumberString,from,to);if(updateSelection){var previousLength=to.ch-from.ch;var newLength=alteredNumberString.length;

let diff=newLength-previousLength;if(selectionStart===selectionEnd)
selectionStart.ch+=diff;else{if(selectionStart.ch>from.ch)
selectionStart.ch+=diff;if(selectionEnd.ch>from.ch)
selectionEnd.ch+=diff;}
this.setSelection(selectionStart,selectionEnd);}
return true;});function alterNumber(amount,codeMirror)
{function findNumberToken(position)
{
var token=codeMirror.getTokenAt(position);if(token&&token.type&&/\bnumber\b/.test(token.type))
return token;return null;}
var position=codeMirror.getCursor("head");var token=findNumberToken(position);if(!token){
position.ch+=1;token=findNumberToken(position);}
if(!token)
return CodeMirror.Pass;var foundNumber=codeMirror.alterNumberInRange(amount,{ch:token.start,line:position.line},{ch:token.end,line:position.line},true);if(!foundNumber)
return CodeMirror.Pass;}
CodeMirror.defineExtension("rectsForRange",function(range){var lineRects=[];for(var line=range.start.line;line<=range.end.line;++line){var lineContent=this.getLine(line);var startChar=line===range.start.line?range.start.ch:(lineContent.length-lineContent.trimLeft().length);var endChar=line===range.end.line?range.end.ch:lineContent.length;var firstCharCoords=this.cursorCoords({ch:startChar,line});var endCharCoords=this.cursorCoords({ch:endChar,line});if(firstCharCoords.bottom!==endCharCoords.bottom){var maxY=-Number.MAX_VALUE;for(var ch=startChar;ch<=endChar;++ch){var coords=this.cursorCoords({ch,line});if(coords.bottom>maxY){if(ch>startChar){var maxX=Math.ceil(this.cursorCoords({ch:ch-1,line}).right);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));}
var minX=Math.floor(coords.left);var minY=Math.floor(coords.top);maxY=Math.ceil(coords.bottom);}}
maxX=Math.ceil(coords.right);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));}else{var minX=Math.floor(firstCharCoords.left);var minY=Math.floor(firstCharCoords.top);var maxX=Math.ceil(endCharCoords.right);var maxY=Math.ceil(endCharCoords.bottom);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));}}
return lineRects;});let mac=WI.Platform.name==="mac";CodeMirror.keyMap["default"]={"Alt-Up":alterNumber.bind(null,1),"Ctrl-Alt-Up":alterNumber.bind(null,0.1),"Shift-Alt-Up":alterNumber.bind(null,10),"Alt-PageUp":alterNumber.bind(null,10),"Shift-Alt-PageUp":alterNumber.bind(null,100),"Alt-Down":alterNumber.bind(null,-1),"Ctrl-Alt-Down":alterNumber.bind(null,-0.1),"Shift-Alt-Down":alterNumber.bind(null,-10),"Alt-PageDown":alterNumber.bind(null,-10),"Shift-Alt-PageDown":alterNumber.bind(null,-100),"Cmd-/":"toggleComment","Cmd-D":"selectNextOccurrence","Shift-Tab":"indentLess",fallthrough:mac?"macDefault":"pcDefault"};{let original=CodeMirror.commands.insertTab;CodeMirror.commands.insertTab=function(cm){if(cm.options.indentWithTabs)
original(cm);else
CodeMirror.commands.insertSoftTab(cm);};}

var extraXMLTypes=["text/xml","text/xsl"];extraXMLTypes.forEach(function(type){CodeMirror.defineMIME(type,"xml");});var extraHTMLTypes=["application/xhtml+xml","image/svg+xml"];extraHTMLTypes.forEach(function(type){CodeMirror.defineMIME(type,"htmlmixed");});var extraJavaScriptTypes=["text/ecmascript","application/javascript","application/ecmascript","application/x-javascript","text/x-javascript","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/jscript","text/livescript"];extraJavaScriptTypes.forEach(function(type){CodeMirror.defineMIME(type,"javascript");});var extraJSONTypes=["application/x-json","text/x-json","application/vnd.api+json"];extraJSONTypes.forEach(function(type){CodeMirror.defineMIME(type,{name:"javascript",json:true});});CodeMirror.defineMIME("x-pipeline/x-compute",CodeMirror.resolveMode("x-shader/x-vertex"));CodeMirror.defineMIME("x-pipeline/x-render",CodeMirror.resolveMode("x-shader/x-vertex"));})();WI.compareCodeMirrorPositions=function(a,b)
{var lineCompare=a.line-b.line;if(lineCompare!==0)
return lineCompare;var aColumn="ch"in a?a.ch:Number.MAX_VALUE;var bColumn="ch"in b?b.ch:Number.MAX_VALUE;return aColumn-bColumn;};WI.walkTokens=function(cm,mode,initialPosition,callback)
{let state=CodeMirror.copyState(mode,cm.getTokenAt(initialPosition).state);if(state.localState)
state=state.localState;let lineCount=cm.lineCount();let abort=false;for(let lineNumber=initialPosition.line;!abort&&lineNumber<lineCount;++lineNumber){let line=cm.getLine(lineNumber);let stream=new CodeMirror.StringStream(line);if(lineNumber===initialPosition.line)
stream.start=stream.pos=initialPosition.ch;while(!stream.eol()){let tokenType=mode.token(stream,state);if(!callback(tokenType,stream.current())){abort=true;break;}
stream.start=stream.pos;}}
if(!abort)
callback(null);};WI.tokenizeCSSValue=function(cssValue)
{const rulePrefix="*{X:";let cssRule=rulePrefix+cssValue+"}";let tokens=[];let mode=CodeMirror.getMode({indentUnit:0},"text/css");let state=CodeMirror.startState(mode);let stream=new CodeMirror.StringStream(cssRule);function processToken(token,tokenType,column){if(column<rulePrefix.length)
return;if(token==="}"&&!tokenType)
return;tokens.push({value:token,type:tokenType});}
while(!stream.eol()){let style=mode.token(stream,state);let value=stream.current();processToken(value,style,stream.start);stream.start=stream.pos;}
return tokens;};WI.CodeMirrorEditor=class CodeMirrorEditor
{static create(element,options)
{element.setAttribute("dir","ltr");element.classList.toggle("read-only",options.readOnly);let codeMirror=new CodeMirror(element,{indentWithTabs:WI.settings.indentWithTabs.value,indentUnit:WI.settings.indentUnit.value,tabSize:WI.settings.tabSize.value,lineWrapping:WI.settings.enableLineWrapping.value,showWhitespaceCharacters:WI.settings.showWhitespaceCharacters.value,...options,});function listenForChange(setting,codeMirrorOption){if(options[codeMirrorOption]!==undefined)
return;setting.addEventListener(WI.Setting.Event.Changed,function(event){this.setOption(codeMirrorOption,setting.value);},codeMirror);}
listenForChange(WI.settings.indentWithTabs,"indentWithTabs");listenForChange(WI.settings.indentUnit,"indentUnit");listenForChange(WI.settings.tabSize,"tabSize");listenForChange(WI.settings.enableLineWrapping,"lineWrapping");listenForChange(WI.settings.showWhitespaceCharacters,"showWhitespaceCharacters");if(WI.Platform.name==="mac"){codeMirror.addKeyMap({"Home":()=>{codeMirror.scrollIntoView({line:0,ch:0});},"End":()=>{codeMirror.scrollIntoView({line:codeMirror.lineCount()-1,ch:null});},});}

new WI.CodeMirrorTextKillController(codeMirror);return codeMirror;}};CodeMirror.defineMode("local-override-url",function(){function tokenBase(stream,state){if(state.parsedURL&&stream.sol()){stream.skipToEnd();return null;}
let url=stream.string;if(!state.parsedURL){try{state.parsedURL=new URL(url);let indexOfFragment=-1;if(state.parsedURL.hash)
indexOfFragment=url.lastIndexOf(state.parsedURL.hash);else if(url.endsWith("#"))
indexOfFragment=url.length-1;state.indexOfFragment=indexOfFragment;}catch{stream.skipToEnd();return null;}} 
if(stream.pos<state.parsedURL.protocol.length){if(state.parsedURL.protocol!=="http:"&&state.parsedURL.protocol!=="https:"){while(stream.pos<state.parsedURL.protocol.length&&!stream.eol())
stream.next();return"local-override-url-bad-scheme";}}
let indexOfFragment=state.indexOfFragment;if(indexOfFragment===-1){stream.skipToEnd();return null;}
if(stream.pos<indexOfFragment){while(stream.pos<indexOfFragment&&!stream.eol())
stream.next();return null;}
stream.skipToEnd();return"local-override-url-fragment";}
return{startState:function(){return{parsedURL:null,tokenize:tokenBase,};},token:function(stream,state){return state.tokenize(stream,state);}};});CodeMirror.defineMIME("text/x-local-override-url","local-override-url");CodeMirror.defineMode("regex",function(){function characterSetTokenizer(stream,state){let context=state.currentContext();if(context.negatedCharacterSet===undefined){context.negatedCharacterSet=stream.eat("^");if(context.negatedCharacterSet)
return"regex-character-set-negate";}
while(stream.peek()){if(stream.eat("\\"))
return consumeEscapeSequence(stream);if(stream.eat("]")){state.tokenize=tokenBase;return state.popContext();}
stream.next();}
return"error";}
function consumeEscapeSequence(stream){if(stream.match(/[bBdDwWsStrnvf0]/))
return"regex-special";if(stream.eat("x")){if(stream.match(/[0-9a-fA-F]{2}/))
return"regex-escape";return"error";}
if(stream.eat("u")){if(stream.match(/[0-9a-fA-F]{4}/))
return"regex-escape-2";return"error";}
if(stream.eat("c")){if(stream.match(/[A-Z]/))
return"regex-escape-3";return"error";}
if(stream.match(/[1-9]/))
return"regex-backreference";if(stream.next())
return"regex-literal";return"error";}
function tokenBase(stream,state){let ch=stream.next();if(ch==="\\")
return consumeEscapeSequence(stream);if(ch==="("){let style;if(stream.match(/\?[=!]/))
style="regex-lookahead";else{stream.match(/\?:/);style="regex-group";}
return state.pushContext(stream,style,")");}
let context=state.currentContext();if(context&&context.type===ch)
return state.popContext();if(/[*+?]/.test(ch))
return"regex-quantifier";if(ch==="{"){if(stream.match(/\d+}/))
return"regex-quantifier";let matches=stream.match(/(\d+),(\d+)?}/);if(!matches)
return"error";let minimum=parseInt(matches[1]);let maximum=parseInt(matches[2]);if(minimum>maximum)
return"error";return"regex-quantifier";}
if(ch==="["){state.tokenize=characterSetTokenizer;return state.pushContext(stream,"regex-character-set");}
if(/[.^$|]/.test(ch))
return"regex-special";return null;}
return{startState:function(){let contextStack=[];return{currentContext:function(){return contextStack.length?contextStack[contextStack.length-1]:null;},pushContext:function(stream,data,type){let context={data,type};contextStack.push(context);return data;},popContext:function(){return contextStack.pop().data;},tokenize:tokenBase,};},token:function(stream,state){return state.tokenize(stream,state);}};});CodeMirror.defineMIME("text/x-regex","regex");function createCodeMirrorTextMarkers({codeMirror,range,type,pattern,matchFunction,allowedTokens,callback})
{var createdMarkers=[];var start=range instanceof WI.TextRange?range.startLine:0;var end=range instanceof WI.TextRange?range.endLine+1:codeMirror.lineCount();for(var lineNumber=start;lineNumber<end;++lineNumber){var lineContent=codeMirror.getLine(lineNumber);var match=pattern.exec(lineContent);while(match){if(typeof matchFunction==="function"&&!matchFunction(lineContent,match)){match=pattern.exec(lineContent);continue;}
var from={line:lineNumber,ch:match.index};var to={line:lineNumber,ch:match.index+match[0].length};var foundMarker=false;var markers=codeMirror.findMarksAt(to);for(var j=0;j<markers.length;++j){if(WI.TextMarker.textMarkerForCodeMirrorTextMarker(markers[j]).type===WI.TextMarker.Type[type]){foundMarker=true;break;}}
if(foundMarker){match=pattern.exec(lineContent);continue;}
var tokenType=codeMirror.getTokenTypeAt(from);if(tokenType&&!tokenType.includes("keyword")&&(!allowedTokens||!allowedTokens.test(tokenType))){match=pattern.exec(lineContent);continue;}
let valueString=match[1];let value=WI[type]?WI[type].fromString(valueString):null;if(WI[type]&&!value){match=pattern.exec(lineContent);continue;}
var marker=codeMirror.markText(from,to);marker=new WI.TextMarker(marker,WI.TextMarker.Type[type]);createdMarkers.push(marker);if(typeof callback==="function")
callback(marker,value,valueString);match=pattern.exec(lineContent);}}
return createdMarkers;}
function createCodeMirrorColorTextMarkers(codeMirror,range,options={})
{ const pattern=/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b\w+\b(?![-.]))/g;function matchFunction(lineContent,match){if(!lineContent||!lineContent.length)
return false;

let openParenthesis=0;let index=match.index;let c=null;while(c=lineContent[index]){if(c==="(")
++openParenthesis;if(c===")")
--openParenthesis;if(openParenthesis>0)
break;--index;if(index<0)
break;}
if(/(repeating-)?(linear|radial)-gradient$/.test(lineContent.substring(0,index)))
return false;return!(match.index>0&&/[-.\"\']/.test(lineContent[match.index-1]));}
return createCodeMirrorTextMarkers({codeMirror,range,type:"Color",pattern,matchFunction,...options});}
function createCodeMirrorGradientTextMarkers(codeMirror,range,options={})
{var createdMarkers=[];var start=range instanceof WI.TextRange?range.startLine:0;var end=range instanceof WI.TextRange?range.endLine+1:codeMirror.lineCount();var gradientRegex=/(repeating-)?(linear|radial)-gradient\s*\(\s*/g;for(var lineNumber=start;lineNumber<end;++lineNumber){var lineContent=codeMirror.getLine(lineNumber);var match=gradientRegex.exec(lineContent);while(match){var startLine=lineNumber;var startChar=match.index;var endChar=match.index+match[0].length;var openParentheses=0;var c=null;while(c=lineContent[endChar]){if(c==="(")
openParentheses++;if(c===")")
openParentheses--;if(openParentheses===-1){endChar++;break;}
endChar++;if(endChar>=lineContent.length){lineNumber++;endChar=0;lineContent=codeMirror.getLine(lineNumber);if(!lineContent)
break;}}
if(openParentheses!==-1){match=gradientRegex.exec(lineContent);continue;}
var from={line:startLine,ch:startChar};var to={line:lineNumber,ch:endChar};var gradientString=codeMirror.getRange(from,to);var gradient=WI.Gradient.fromString(gradientString);if(!gradient){match=gradientRegex.exec(lineContent);continue;}
var marker=new WI.TextMarker(codeMirror.markText(from,to),WI.TextMarker.Type.Gradient);createdMarkers.push(marker);if(typeof callback==="function")
options.callback(marker,gradient,gradientString);match=gradientRegex.exec(lineContent);}}
return createdMarkers;}
function createCodeMirrorCubicBezierTextMarkers(codeMirror,range,options={})
{const pattern=/(cubic-bezier\([^)]+\)|\b\w+\b(?:-\b\w+\b){0,2})/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"CubicBezier",pattern,...options});}
function createCodeMirrorSpringTextMarkers(codeMirror,range,options={})
{const pattern=/(spring\([^)]+\))/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"Spring",pattern,...options});}
WI.ColorPicker=class ColorPicker extends WI.Object
{constructor()
{super();this._colorSquare=new WI.ColorSquare(this,200);this._hueSlider=new WI.Slider;this._hueSlider.delegate=this;this._hueSlider.element.classList.add("hue");this._opacitySlider=new WI.Slider;this._opacitySlider.delegate=this;this._opacitySlider.element.classList.add("opacity");this._colorInputs=[];this._colorInputsFormat=null;this._colorInputsHasAlpha=null;this._colorInputsContainerElement=document.createElement("div");this._colorInputsContainerElement.classList.add("color-inputs");this._colorInputsContainerElement.addEventListener("input",this._handleColorInputsContainerInput.bind(this));this._element=document.createElement("div");this._element.classList.add("color-picker");let wrapper=this._element.appendChild(document.createElement("div"));wrapper.className="wrapper";wrapper.appendChild(this._colorSquare.element);wrapper.appendChild(this._hueSlider.element);wrapper.appendChild(this._opacitySlider.element);this._element.appendChild(this._colorInputsContainerElement);this._opacity=0;this._opacityPattern="url(Images/Checkers.svg)";this._color=WI.Color.fromString("white");this._dontUpdateColor=false;this._enableColorComponentInputs=true;} 
get element(){return this._element;}
get colorSquare(){return this._colorSquare;}
set opacity(opacity)
{if(opacity===this._opacity)
return;this._opacity=opacity;this._updateColor();}
get color()
{return this._color;}
set color(color)
{this._dontUpdateColor=true;this._color=color;this._colorSquare.tintedColor=this._color;this._hueSlider.value=this._color.hsl[0]/360;this._opacitySlider.value=this._color.alpha;this._updateOpacitySlider();this._showColorComponentInputs();this._updateColorGamut();this._dontUpdateColor=false;}
set enableColorComponentInputs(value)
{this._enableColorComponentInputs=value;this._element.classList.toggle("hide-inputs",!this._enableColorComponentInputs);}
focus()
{this._colorSquare.element.focus();}
colorSquareColorDidChange(colorSquare)
{this._updateColor();this._updateOpacitySlider();}
sliderValueDidChange(slider,value)
{if(slider===this._opacitySlider)
this.opacity=value;else if(slider===this._hueSlider){this._colorSquare.hue=value*360;this._updateColor();this._updateOpacitySlider();}} 
_updateColor()
{if(this._dontUpdateColor)
return;let opacity=Math.round(this._opacity*100)/100;let format=this._color.format;let gamut=this._color.gamut;let components=null;if(format===WI.Color.Format.HSL||format===WI.Color.Format.HSLA){components=this._colorSquare.tintedColor.hsl.concat(opacity);if(opacity!==1)
format=WI.Color.Format.HSLA;}else if(format===WI.Color.Format.ColorFunction)
components=this._colorSquare.tintedColor.normalizedRGB.concat(opacity);else{components=this._colorSquare.tintedColor.rgb.concat(opacity);if(opacity!==1&&format===WI.Color.Format.RGB)
format=WI.Color.Format.RGBA;}
this._color=new WI.Color(format,components,gamut);this._showColorComponentInputs();this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color});this._updateColorGamut();}
_updateOpacitySlider()
{let color=this._colorSquare.tintedColor;let rgb=color.format===WI.Color.Format.ColorFunction?color.normalizedRGB:color.rgb;let gamut=color.gamut;let format=gamut===WI.Color.Gamut.DisplayP3?WI.Color.Format.ColorFunction:WI.Color.Format.RGBA;let opaque=new WI.Color(format,rgb.concat(1),gamut).toString();let transparent=new WI.Color(format,rgb.concat(0),gamut).toString();this._opacitySlider.element.style.setProperty("background-image","linear-gradient(0deg, "+transparent+", "+opaque+"), "+this._opacityPattern);}
_updateColorGamut()
{this._element.classList.toggle("gamut-p3",this._color.gamut===WI.Color.Gamut.DisplayP3);}
_createColorInputsIfNeeded()
{let hasAlpha=this._color.alpha!==1;if((this._color.format===this._colorInputsFormat)&&(hasAlpha===this._colorInputsHasAlpha))
return;this._colorInputsFormat=this._color.format;this._colorInputsHasAlpha=hasAlpha;this._colorInputs=[];this._colorInputsContainerElement.removeChildren();let createColorInput=(label,{max,step,units}={})=>{let containerElement=this._colorInputsContainerElement.createChild("div");containerElement.append(label);let numberInputElement=containerElement.createChild("input");numberInputElement.type="number";numberInputElement.min=0;numberInputElement.max=max;numberInputElement.step=step||1;this._colorInputs.push(numberInputElement);if(units&&units.length)
containerElement.append(units);};switch(this._color.format){case WI.Color.Format.RGB:case WI.Color.Format.RGBA:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:createColorInput("R",{max:255});createColorInput("G",{max:255});createColorInput("B",{max:255});break;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:createColorInput("H",{max:360});createColorInput("S",{max:100,units:"%"});createColorInput("L",{max:100,units:"%"});break;case WI.Color.Format.ColorFunction:createColorInput("R",{max:1,step:0.01});createColorInput("G",{max:1,step:0.01});createColorInput("B",{max:1,step:0.01});break;default:console.error(`Unknown color format: ${this._color.format}`);return;}
if(this._color.alpha!==1||this._color.format===WI.Color.Format.RGBA||this._color.format===WI.Color.Format.HSLA||this._color.format===WI.Color.Format.HEXAlpha||this._color.format===WI.Color.Format.ShortHEXAlpha){createColorInput("A",{max:1,step:0.01});}}
_showColorComponentInputs()
{if(!this._enableColorComponentInputs)
return;this._createColorInputsIfNeeded();let components=[];switch(this._color.format){case WI.Color.Format.RGB:case WI.Color.Format.RGBA:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:components=this._color.rgb.map((value)=>Math.round(value));break;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:components=this._color.hsl.map((value)=>value.maxDecimals(2));break;case WI.Color.Format.ColorFunction:components=this._color.normalizedRGB.map((value)=>value.maxDecimals(4));break;default:console.error(`Unknown color format: ${this._color.format}`);}
if(this._color.alpha!==1)
components.push(this._color.alpha);for(let i=0;i<components.length;++i)
this._colorInputs[i].value=components[i];}
_handleColorInputsContainerInput(event)
{let components=this._colorInputs.map((input)=>{return isNaN(input.valueAsNumber)?0:input.valueAsNumber;});this.color=new WI.Color(this._color.format,components,this._color.gamut);this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color});}};WI.ColorPicker.Event={ColorChanged:"css-color-picker-color-changed",};WI.ColorSquare=class ColorSquare
{constructor(delegate,dimension)
{this._delegate=delegate;this._hue=0;this._x=0;this._y=0;this._gamut=null;this._crosshairPosition=null;this._element=document.createElement("div");this._element.className="color-square";this._element.tabIndex=0;let saturationGradientElement=this._element.appendChild(document.createElement("div"));saturationGradientElement.className="saturation-gradient fill";let lightnessGradientElement=this._element.appendChild(document.createElement("div"));lightnessGradientElement.className="lightness-gradient fill";this._srgbLabelElement=null;this._svgElement=null;this._polylineElement=null;this._element.addEventListener("mousedown",this);this._element.addEventListener("keydown",this._handleKeyDown.bind(this));this._crosshairElement=this._element.appendChild(document.createElement("div"));this._crosshairElement.className="crosshair";this.dimension=dimension;} 
get element(){return this._element;}
set dimension(dimension)
{if(dimension===this._dimension)
return;this._dimension=dimension;this._element.style.width=this.element.style.height=`${this._dimension}px`;this._updateBaseColor();}
get hue()
{return this._hue;}
set hue(hue)
{this._hue=hue;this._updateBaseColor();}
get tintedColor()
{if(this._crosshairPosition){if(this._gamut===WI.Color.Gamut.DisplayP3){let rgb=WI.Color.hsv2rgb(this._hue,this._saturation,this._brightness);rgb=rgb.map(((x)=>Math.roundTo(x,0.001)));return new WI.Color(WI.Color.Format.ColorFunction,rgb,this._gamut);}
let hsl=WI.Color.hsv2hsl(this._hue,this._saturation,this._brightness);return new WI.Color(WI.Color.Format.HSL,hsl);}
return new WI.Color(WI.Color.Format.HSLA,[0,0,0,0]);}
set tintedColor(tintedColor)
{this._gamut=tintedColor.gamut;let[hue,saturation,value]=WI.Color.rgb2hsv(...tintedColor.normalizedRGB);let x=saturation/100*this._dimension;let y=(1-(value/100))*this._dimension;if(this._gamut===WI.Color.Gamut.DisplayP3)
this._drawSRGBOutline();this._setCrosshairPosition(new WI.Point(x,y));this._updateBaseColor();} 
handleEvent(event)
{switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}} 
get _saturation()
{let saturation=this._x/this._dimension;return Number.constrain(saturation,0,1)*100;}
get _brightness()
{let brightness=1-(this._y/this._dimension);return Number.constrain(brightness,0,1)*100;}
_handleMousedown(event)
{if(event.button!==0||event.ctrlKey)
return;window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._updateColorForMouseEvent(event);event.stop();this._element.focus();}
_handleMousemove(event)
{this._updateColorForMouseEvent(event);}
_handleMouseup(event)
{window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);}
_handleKeyDown(event)
{let dx=0;let dy=0;let step=event.shiftKey?10:1;switch(event.keyIdentifier){case"Right":dx+=step;break;case"Left":dx-=step;break;case"Down":dy+=step;break;case"Up":dy-=step;break;}
if(dx||dy){event.preventDefault();this._setCrosshairPosition(new WI.Point(this._x+dx,this._y+dy));if(this._delegate&&this._delegate.colorSquareColorDidChange)
this._delegate.colorSquareColorDidChange(this);}}
_updateColorForMouseEvent(event)
{let rect=this._element.getBoundingClientRect();this._setCrosshairPosition({x:event.pageX-rect.x,y:event.pageY-rect.y,});if(this._delegate&&this._delegate.colorSquareColorDidChange)
this._delegate.colorSquareColorDidChange(this);}
_setCrosshairPosition(point)
{this._crosshairPosition=point;this._x=Number.constrain(Math.round(point.x),0,this._dimension);this._y=Number.constrain(Math.round(point.y),0,this._dimension);this._crosshairElement.style.setProperty("transform",`translate(${this._x}px, ${this._y}px)`);this._updateCrosshairBackground();}
_updateBaseColor()
{if(this._gamut===WI.Color.Gamut.DisplayP3){let[r,g,b]=WI.Color.hsl2rgb(this._hue,100,50);this._element.style.backgroundColor=`color(display-p3 ${r / 255} ${g / 255} ${b / 255})`;}else
this._element.style.backgroundColor=`hsl(${this._hue}, 100%, 50%)`;this._updateCrosshairBackground();if(this._gamut===WI.Color.Gamut.DisplayP3)
this._drawSRGBOutline();}
_updateCrosshairBackground()
{this._crosshairElement.style.backgroundColor=this.tintedColor.toString();}
_drawSRGBOutline()
{if(!this._svgElement){this._srgbLabelElement=this._element.appendChild(document.createElement("span"));this._srgbLabelElement.className="srgb-label";this._srgbLabelElement.textContent=WI.unlocalizedString("sRGB");this._srgbLabelElement.title=WI.UIString("Edge of sRGB color space","Label for a guide within the color picker");const svgNamespace="http://www.w3.org/2000/svg";this._svgElement=this._element.appendChild(document.createElementNS(svgNamespace,"svg"));this._svgElement.classList.add("svg-root");this._polylineElement=this._svgElement.appendChild(document.createElementNS(svgNamespace,"polyline"));this._polylineElement.classList.add("srgb-edge");}
let points=[];let step=1/window.devicePixelRatio;let x=0;for(let y=0;y<this._dimension;y+=step){let value=100-((y/this._dimension)*100);
for(;x<this._dimension;x+=step){let saturation=x/this._dimension*100;let rgb=WI.Color.hsv2rgb(this._hue,saturation,value);let srgb=WI.Color.displayP3toSRGB(rgb[0],rgb[1],rgb[2]);if(srgb.some((value)=>value<0||value>1)){points.push({x,y});break;}}}
if(points.lastValue.y<this._dimension*0.95){points.push({x:this._dimension,y:points.lastValue.y});this._srgbLabelElement.style.removeProperty("bottom");this._srgbLabelElement.style.top=`${points.lastValue.y}px`;}else{this._srgbLabelElement.style.removeProperty("top");this._srgbLabelElement.style.bottom="0px";}
this._srgbLabelElement.style.right=`${this._dimension - points.lastValue.x}px`;this._polylineElement.points.clear();for(let{x,y}of points){let svgPoint=this._svgElement.createSVGPoint();svgPoint.x=x;svgPoint.y=y;this._polylineElement.points.appendItem(svgPoint);}}};
WI.ColumnChart=class ColumnChart extends WI.View
{constructor(size)
{super();this.element.classList.add("column-chart");this._svgElement=this.element.appendChild(createSVGElement("svg"));this._svgElement.setAttribute("preserveAspectRatio","none");this._columns=[];this.size=size;} 
get size()
{return this._size;}
set size(size)
{this._size=size;this._svgElement.setAttribute("viewBox",`0 0 ${size.width} ${size.height}`);}
addColumn(x,y,width,height)
{this._columns.push({x,y,width,height});}
clear()
{this._columns=[];} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;this._svgElement.removeChildren();for(let{x,y,width,height}of this._columns){let rect=this._svgElement.appendChild(createSVGElement("rect"));rect.setAttribute("width",width);rect.setAttribute("height",height);rect.setAttribute("x",x);rect.setAttribute("y",y);}}};WI.CompletionSuggestionsView=class CompletionSuggestionsView extends WI.Object
{constructor(delegate,{preventBlur}={})
{super();this._delegate=delegate||null;this._preventBlur=preventBlur||false;this._selectedIndex=NaN;this._moveIntervalIdentifier=null;this._element=document.createElement("div");this._element.setAttribute("dir","ltr");this._element.classList.add("completion-suggestions",WI.Popover.IgnoreAutoDismissClassName);this._containerElement=document.createElement("div");this._containerElement.classList.add("completion-suggestions-container");this._containerElement.addEventListener("mousedown",this._mouseDown.bind(this));this._containerElement.addEventListener("mouseup",this._mouseUp.bind(this));this._containerElement.addEventListener("click",this._itemClicked.bind(this));this._element.appendChild(this._containerElement);} 
get delegate()
{return this._delegate;}
get visible()
{return!!this._element.parentNode;}
get selectedIndex()
{return this._selectedIndex;}
set selectedIndex(index)
{var selectedItemElement=this._selectedItemElement;if(selectedItemElement)
selectedItemElement.classList.remove("selected");this._selectedIndex=index;selectedItemElement=this._selectedItemElement;if(!selectedItemElement)
return;selectedItemElement.classList.add("selected");selectedItemElement.scrollIntoViewIfNeeded(false);}
selectNext()
{var count=this._containerElement.children.length;if(isNaN(this._selectedIndex)||this._selectedIndex===count-1)
this.selectedIndex=0;else
++this.selectedIndex;var selectedItemElement=this._selectedItemElement;if(selectedItemElement&&this._delegate&&typeof this._delegate.completionSuggestionsSelectedCompletion==="function")
this._delegate.completionSuggestionsSelectedCompletion(this,selectedItemElement.textContent);}
selectPrevious()
{if(isNaN(this._selectedIndex)||this._selectedIndex===0)
this.selectedIndex=this._containerElement.children.length-1;else
--this.selectedIndex;var selectedItemElement=this._selectedItemElement;if(selectedItemElement&&this._delegate&&typeof this._delegate.completionSuggestionsSelectedCompletion==="function")
this._delegate.completionSuggestionsSelectedCompletion(this,selectedItemElement.textContent);}
isHandlingClickEvent()
{return this._mouseIsDown;}
show(anchorBounds)
{let intrinsicSize=WI.measureElement(this._containerElement);let containerWidth=Math.ceil(intrinsicSize.width);let containerHeight=Math.ceil(intrinsicSize.height);let margin=10;let absoluteMaximumHeight=160;let x=anchorBounds.origin.x;let y=anchorBounds.origin.y+anchorBounds.size.height;let maximumWidth=window.innerWidth-anchorBounds.origin.x-margin;let width=Math.min(containerWidth,maximumWidth);if(width<containerWidth){maximumWidth=window.innerWidth-margin;width=Math.min(containerWidth,maximumWidth);x=document.body.offsetWidth-width;}
let aboveHeight=anchorBounds.origin.y;let underHeight=window.innerHeight-anchorBounds.origin.y-anchorBounds.size.height;let maximumHeight=Math.min(absoluteMaximumHeight,Math.max(underHeight,aboveHeight)-margin);let height=Math.min(containerHeight,maximumHeight);if(underHeight-height<0)
y=aboveHeight-height;this._element.style.left=x+"px";this._element.style.top=y+"px";this._element.style.width=width+"px";this._element.style.height=height+"px";if(!this._element.parentNode)
document.body.appendChild(this._element);}
hide()
{this._element.remove();this._stopMoveTimer();}
hideWhenElementMoves(element)
{this._stopMoveTimer();let initialClientRect=element.getBoundingClientRect();this._moveIntervalIdentifier=setInterval(()=>{let clientRect=element.getBoundingClientRect();if(clientRect.x!==initialClientRect.x||clientRect.y!==initialClientRect.y)
this.hide();},200);}
update(completions,selectedIndex)
{this._containerElement.removeChildren();if(typeof selectedIndex==="number")
this._selectedIndex=selectedIndex;for(var i=0;i<completions.length;++i){var itemElement=document.createElement("div");itemElement.classList.add("item");itemElement.classList.toggle("selected",i===this._selectedIndex);itemElement.textContent=completions[i];this._containerElement.appendChild(itemElement);if(this._delegate&&typeof this._delegate.completionSuggestionsViewCustomizeCompletionElement==="function")
this._delegate.completionSuggestionsViewCustomizeCompletionElement(this,itemElement,completions[i]);}} 
get _selectedItemElement()
{if(isNaN(this._selectedIndex))
return null;var element=this._containerElement.children[this._selectedIndex]||null;return element;}
_mouseDown(event)
{if(event.button!==0)
return;if(this._preventBlur)
event.preventDefault();this._mouseIsDown=true;}
_mouseUp(event)
{if(event.button!==0)
return;this._mouseIsDown=false;}
_itemClicked(event)
{if(event.button!==0)
return;let itemElement=event.target.closest(".item");if(!itemElement)
return;if(this._delegate&&typeof this._delegate.completionSuggestionsClickedCompletion==="function")
this._delegate.completionSuggestionsClickedCompletion(this,itemElement.textContent);}
_stopMoveTimer()
{if(!this._moveIntervalIdentifier)
return;clearInterval(this._moveIntervalIdentifier);this._moveIntervalIdentifier=null;}};WI.ComputedStyleDetailsPanel=class ComputedStyleDetailsPanel extends WI.StyleDetailsPanel
{constructor(delegate)
{super(delegate,WI.ComputedStyleDetailsPanel.StyleClassName,"computed",WI.UIString("Styles \u2014 Computed"));this._computedStyleShowAllSetting=new WI.Setting("computed-style-show-all",false);this._computedStylePreferShorthandsSetting=new WI.Setting("computed-style-use-shorthands",false);this._filterText=null;} 
get minimumWidth()
{return this._boxModelDiagramRow?.minimumWidth??0;}
refresh(significantChange)
{
if(!significantChange){super.refresh();return;}
this._computedStyleSection.styleTraces=this._computePropertyTraces(this.nodeStyles.uniqueOrderedStyles);this._computedStyleSection.style=this.nodeStyles.computedStyle;this._propertiesSection.element.classList.toggle("hidden",!this._computedStyleSection.propertiesToRender.length);this._variablesTextEditor.style=this.nodeStyles.computedStyle;this._variablesSection.element.classList.toggle("hidden",!this._variablesTextEditor.propertiesToRender.length);this._boxModelDiagramRow.nodeStyles=this.nodeStyles;if(this._filterText)
this.applyFilter(this._filterText);super.refresh();}
applyFilter(filterText)
{this._filterText=filterText;if(!this.didInitialLayout)
return;this._computedStyleSection.applyFilter(filterText);this._variablesTextEditor.applyFilter(filterText);} 
spreadsheetCSSStyleDeclarationEditorShowProperty(editor,property)
{if(this._delegate.computedStyleDetailsPanelShowProperty)
this._delegate.computedStyleDetailsPanelShowProperty(property);} 
initialLayout()
{this._boxModelDiagramRow=new WI.BoxModelDetailsSectionRow;let boxModelGroup=new WI.DetailsSectionGroup([this._boxModelDiagramRow]);let boxModelSection=new WI.DetailsSection("computed-style-box-model",WI.UIString("Box Model"),[boxModelGroup]);this.element.appendChild(boxModelSection.element);let propertyFiltersElement=WI.ImageUtilities.useSVGSymbol("Images/FilterFieldGlyph.svg","filter");WI.addMouseDownContextMenuHandlers(propertyFiltersElement,(contextMenu)=>{contextMenu.appendCheckboxItem(WI.UIString("Show All"),()=>{this._computedStyleShowAllSetting.value=!this._computedStyleShowAllSetting.value;},this._computedStyleShowAllSetting.value);contextMenu.appendCheckboxItem(WI.UIString("Prefer Shorthands"),()=>{this._computedStylePreferShorthandsSetting.value=!this._computedStylePreferShorthandsSetting.value;},this._computedStylePreferShorthandsSetting.value);});this._computedStyleSection=new WI.ComputedStyleSection(this);this._computedStyleSection.addEventListener(WI.ComputedStyleSection.Event.FilterApplied,this._handleEditorFilterApplied,this);this._computedStyleSection.showsImplicitProperties=this._computedStyleShowAllSetting.value;this._computedStyleSection.propertyVisibilityMode=WI.ComputedStyleSection.PropertyVisibilityMode.HideVariables;this._computedStyleSection.showsShorthandsInsteadOfLonghands=this._computedStylePreferShorthandsSetting.value;this._computedStyleSection.alwaysShowPropertyNames=["display","width","height"];this._computedStyleSection.hideFilterNonMatchingProperties=true;let propertiesRow=new WI.DetailsSectionRow;let propertiesGroup=new WI.DetailsSectionGroup([propertiesRow]);this._propertiesSection=new WI.DetailsSection("computed-style-properties",WI.UIString("Properties"),[propertiesGroup],propertyFiltersElement);this._propertiesSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handlePropertiesSectionCollapsedStateChanged,this);this.addSubview(this._computedStyleSection);propertiesRow.element.appendChild(this._computedStyleSection.element);this._variablesTextEditor=new WI.SpreadsheetCSSStyleDeclarationEditor(this);this._variablesTextEditor.propertyVisibilityMode=WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideNonVariables;this._variablesTextEditor.hideFilterNonMatchingProperties=true;this._variablesTextEditor.sortPropertiesByName=true;this._variablesTextEditor.addEventListener(WI.SpreadsheetCSSStyleDeclarationEditor.Event.FilterApplied,this._handleEditorFilterApplied,this);this._variablesTextEditor.element.dir="ltr";let variablesRow=new WI.DetailsSectionRow;let variablesGroup=new WI.DetailsSectionGroup([variablesRow]);this._variablesSection=new WI.DetailsSection("computed-style-variables",WI.UIString("Variables"),[variablesGroup]);this._variablesSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleVariablesSectionCollapsedStateChanged,this);this.addSubview(this._variablesTextEditor);variablesRow.element.appendChild(this._variablesTextEditor.element);this.element.appendChild(this._propertiesSection.element);this.element.appendChild(this._variablesSection.element);this._computedStyleShowAllSetting.addEventListener(WI.Setting.Event.Changed,this._handleShowAllSettingChanged,this);this._computedStylePreferShorthandsSetting.addEventListener(WI.Setting.Event.Changed,this._handleUseShorthandsSettingChanged,this);}
filterDidChange(filterBar)
{this.applyFilter(filterBar.filters.text);} 
_computePropertyTraces(orderedDeclarations)
{let result=new Map();for(let rule of orderedDeclarations){for(let property of rule.properties){let properties=result.get(property.name);if(!properties){properties=[];result.set(property.name,properties);}
properties.push(property);}}
return result;}
_handlePropertiesSectionCollapsedStateChanged(event)
{if(event&&event.data&&!event.data.collapsed)
this._computedStyleSection.needsLayout();}
_handleVariablesSectionCollapsedStateChanged(event)
{if(event&&event.data&&!event.data.collapsed)
this._variablesTextEditor.needsLayout();}
_handleEditorFilterApplied(event)
{let section=null;if(event.target===this._computedStyleSection)
section=this._propertiesSection;else if(event.target===this._variablesTextEditor)
section=this._variablesSection;if(section)
section.element.classList.toggle("hidden",!event.data.matches);}
_handleShowAllSettingChanged(event)
{this._computedStyleSection.showsImplicitProperties=this._computedStyleShowAllSetting.value;}
_handleUseShorthandsSettingChanged(event)
{this._computedStyleSection.showsShorthandsInsteadOfLonghands=this._computedStylePreferShorthandsSetting.value;}};WI.ComputedStyleDetailsPanel.StyleClassName="computed";WI.ComputedStyleSection=class ComputedStyleSection extends WI.View
{constructor(delegate)
{super();this.element.classList.add(WI.ComputedStyleSection.StyleClassName);this.element.dir="ltr";this._delegate=delegate;this._style=null;this._styleTraces=[];this._propertyViews=[];this._showsImplicitProperties=false;this._showsShorthandsInsteadOfLonghands=false;this._alwaysShowPropertyNames=new Set;this._propertyVisibilityMode=WI.ComputedStyleSection.PropertyVisibilityMode.ShowAll;this._hideFilterNonMatchingProperties=false;this._filterText=null;} 
get style()
{return this._style;}
set style(style)
{if(this._style===style)
return;if(this._style)
this._style.removeEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._handlePropertiesChanged,this);this._style=style||null;if(this._style)
this._style.addEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._handlePropertiesChanged,this);this.needsLayout();}
get styleTraces()
{return this._styleTraces;}
set styleTraces(styleTraces)
{if(Array.shallowEqual(this._styleTraces,styleTraces))
return;this._styleTraces=styleTraces||null;this.needsLayout();}
set showsImplicitProperties(value)
{if(value===this._showsImplicitProperties)
return;this._showsImplicitProperties=value;this.needsLayout();}
set showsShorthandsInsteadOfLonghands(value)
{if(value===this._showsShorthandsInsteadOfLonghands)
return;this._showsShorthandsInsteadOfLonghands=value;this.needsLayout();}
set alwaysShowPropertyNames(propertyNames)
{this._alwaysShowPropertyNames=new Set(propertyNames);this.needsLayout();}
set propertyVisibilityMode(propertyVisibilityMode)
{if(this._propertyVisibilityMode===propertyVisibilityMode)
return;this._propertyVisibilityMode=propertyVisibilityMode;this.needsLayout();}
set hideFilterNonMatchingProperties(value)
{if(value===this._hideFilterNonMatchingProperties)
return;this._hideFilterNonMatchingProperties=value;this.needsLayout();}
get propertiesToRender()
{let properties=[];if(!this._style)
return properties;if(this._style._styleSheetTextRange)
properties=this._style.visibleProperties;else
properties=this._style.properties;let propertyNameMap=new Map(properties.map((property)=>[property.canonicalName,property]));function hasNonImplicitLonghand(property){if(property.canonicalName==="all")
return false;let longhandPropertyNames=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(property.canonicalName);if(!longhandPropertyNames)
return false;for(let longhandPropertyName of longhandPropertyNames){let property=propertyNameMap.get(longhandPropertyName);if(property&&!property.implicit)
return true;}
return false;}
let hideVariables=this._propertyVisibilityMode===ComputedStyleSection.PropertyVisibilityMode.HideVariables;let hideNonVariables=this._propertyVisibilityMode===ComputedStyleSection.PropertyVisibilityMode.HideNonVariables;properties=properties.filter((property)=>{if(this._alwaysShowPropertyNames.has(property.canonicalName))
return true;if(property.implicit&&!this._showsImplicitProperties){if(!(this._showsShorthandsInsteadOfLonghands&&property.isShorthand&&hasNonImplicitLonghand(property)))
return false;}
if(this._showsShorthandsInsteadOfLonghands){if(property.shorthandPropertyNames.length)
return false;}else if(property.isShorthand)
return false;if(property.isVariable&&hideVariables)
return false;if(!property.isVariable&&hideNonVariables)
return false;return true;});properties.sort((a,b)=>a.name.extendedLocaleCompare(b.name));return properties;}
layout()
{super.layout();this.element.removeChildren();this._propertyViews=[];let properties=this.propertiesToRender;for(let i=0;i<properties.length;i++){let property=properties[i];let propertyView=new WI.SpreadsheetStyleProperty(this,property);if(this._filterText){let matchesFilter=propertyView.applyFilter(this._filterText);if(!matchesFilter)
continue;}
propertyView.index=i;this._propertyViews.push(propertyView);let propertyTrace=this._styleTraces?this._styleTraces.get(property.name):null;let traceElement=null;if(propertyTrace&&propertyTrace.length>0)
traceElement=this._createTrace(propertyTrace);let expandableView=new WI.ExpandableView(property.name,propertyView.element,traceElement);expandableView.element.classList.add("computed-property-item");this.element.append(expandableView.element);}}
detached()
{super.detached();for(let propertyView of this._propertyViews)
propertyView.detached();}
applyFilter(filterText)
{this._filterText=filterText;if(!this.didInitialLayout)
return;this.needsLayout();} 
spreadsheetStylePropertyShowProperty(propertyView,property)
{if(this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty)
this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty(this,property);} 
_createTrace(propertyTrace)
{let traceElement=document.createElement("ul");traceElement.className="property-traces";for(let property of propertyTrace){let traceItemElement=document.createElement("li");traceItemElement.className="property-trace-item";let leftElement=document.createElement("div");leftElement.className="property-trace-item-left";let rightElement=document.createElement("div");rightElement.className="property-trace-item-right";traceItemElement.append(leftElement,rightElement);let propertyView=new WI.SpreadsheetStyleProperty(this,property,{readOnly:true});let selectorText="";let ownerStyle=property.ownerStyle;if(ownerStyle){let ownerRule=ownerStyle.ownerRule;if(ownerRule)
selectorText=ownerRule.selectorText;}
let selectorElement=document.createElement("span");selectorElement.textContent=selectorText.truncateMiddle(24);selectorElement.className="selector";leftElement.append(propertyView.element,selectorElement);if(property.ownerStyle){let styleOriginView=new WI.StyleOriginView();styleOriginView.update(property.ownerStyle);rightElement.append(styleOriginView.element);}
traceElement.append(traceItemElement);}
return traceElement;}
_handlePropertiesChanged(event)
{this.needsLayout();}};WI.ComputedStyleSection.Event={FilterApplied:"computed-style-section-filter-applied",};WI.ComputedStyleSection.StyleClassName="computed-style-section";WI.ComputedStyleSection.PropertyVisibilityMode={ShowAll:Symbol("variable-visibility-show-all"),HideVariables:Symbol("variable-visibility-hide-variables"),HideNonVariables:Symbol("variable-visibility-hide-non-variables"),};WI.ConsoleDrawer=class ConsoleDrawer extends WI.ContentBrowser
{constructor(element)
{const delegate=null;const disableBackForward=true;const disableFindBanner=false;super(element,delegate,disableBackForward,disableFindBanner);this.element.classList.add("console-drawer");this._drawerHeightSetting=new WI.Setting("console-drawer-height",150);this.navigationBar.element.addEventListener("mousedown",this._consoleResizerMouseDown.bind(this));this._toggleDrawerButton=new WI.ToggleButtonNavigationItem("toggle-drawer",WI.UIString("Hide Console"),WI.UIString("Show Console"),"Images/HideConsoleDrawer.svg","Images/ShowConsoleDrawer.svg");this._toggleDrawerButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._toggleDrawerButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.toggleSplitConsole();},this._toggleDrawerButton);this.navigationBar.insertNavigationItem(this._toggleDrawerButton,0);this.collapsed=true;WI.TabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._selectedTabContentViewDidChange,this);} 
toggleButtonShortcutTooltip(keyboardShortcut)
{this._toggleDrawerButton.defaultToolTip=WI.UIString("Hide Console (%s)").format(keyboardShortcut.displayName);}
get collapsed()
{return this._collapsed;}
set collapsed(flag)
{if(flag===this._collapsed)
return;this._collapsed=flag||false;this._toggleDrawerButton.toggled=this._collapsed;this.element.classList.toggle("hidden",this._collapsed);

this._didMoveToParent(this._collapsed?null:WI.View.rootView());this.dispatchEventToListeners(WI.ConsoleDrawer.Event.CollapsedStateChanged);}
get height()
{return this.element.offsetHeight;} 
attached()
{super.attached();this._restoreDrawerHeight();}
sizeDidChange()
{super.sizeDidChange();if(this._collapsed)
return;let height=this.height;this._restoreDrawerHeight();if(height!==this.height)
this.dispatchEventToListeners(WI.ConsoleDrawer.Event.Resized);} 
_consoleResizerMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;if(event.target!==this.navigationBar.element&&!event.target.classList.contains("flexible-space"))
return;let resizerElement=event.target;let quickConsoleHeight=window.innerHeight-(this.element.totalOffsetTop+this.height);let mouseOffset=quickConsoleHeight-(event.pageY-resizerElement.totalOffsetTop);function dockedResizerDrag(event)
{let height=window.innerHeight-event.pageY-mouseOffset;this._drawerHeightSetting.value=height;this._updateDrawerHeight(height);this.collapsed=false;}
function dockedResizerDragEnd(event)
{if(event.button!==0)
return;WI.elementDragEnd(event);}
WI.elementDragStart(resizerElement,dockedResizerDrag.bind(this),dockedResizerDragEnd.bind(this),event,"row-resize");}
_restoreDrawerHeight()
{this._updateDrawerHeight(this._drawerHeightSetting.value);}
_updateDrawerHeight(height)
{const minimumHeight=64;const maximumHeight=this.element.parentNode.offsetHeight-100;let heightCSSValue=Number.constrain(height,minimumHeight,maximumHeight)+"px";if(this.element.style.height===heightCSSValue)
return;this.element.style.height=heightCSSValue;this.dispatchEventToListeners(WI.ConsoleDrawer.Event.Resized);}
_selectedTabContentViewDidChange()
{if(WI.doesCurrentTabSupportSplitContentBrowser())
return;this.element.classList.add("hidden");}};WI.ConsoleDrawer.Event={CollapsedStateChanged:"console-drawer-collapsed-state-changed",Resized:"console-drawer-resized",};WI.ConsoleGroup=class ConsoleGroup extends WI.Object
{constructor(parentGroup)
{super();this._parentGroup=parentGroup;} 
get parentGroup()
{return this._parentGroup;}
render(messageView)
{var groupElement=document.createElement("div");groupElement.className="console-group";groupElement.group=this;this.element=groupElement;var titleElement=messageView.element;titleElement.classList.add(WI.LogContentView.ItemWrapperStyleClassName);titleElement.addEventListener("click",this._titleClicked.bind(this));titleElement.addEventListener("mousedown",this._titleMouseDown.bind(this));if(groupElement&&messageView.message.type===WI.ConsoleMessage.MessageType.StartGroupCollapsed)
groupElement.classList.add("collapsed");groupElement.appendChild(titleElement);var messagesElement=document.createElement("div");this._messagesElement=messagesElement;messagesElement.className="console-group-messages";groupElement.appendChild(messagesElement);return groupElement;}
addMessageView(messageView)
{var element=messageView.element;element.classList.add(WI.LogContentView.ItemWrapperStyleClassName);this.append(element);}
append(messageOrGroupElement)
{this._messagesElement.appendChild(messageOrGroupElement);} 
_titleMouseDown(event)
{event.preventDefault();}
_titleClicked(event)
{var groupTitleElement=event.target.closest(".console-group-title");if(groupTitleElement){var groupElement=groupTitleElement.closest(".console-group");if(groupElement)
if(groupElement.classList.contains("collapsed"))
groupElement.classList.remove("collapsed");else
groupElement.classList.add("collapsed");groupTitleElement.scrollIntoViewIfNeeded(true);}}};WI.ConsolePrompt=class ConsolePrompt extends WI.View
{constructor(delegate,mimeType)
{super();mimeType=parseMIMEType(mimeType).type;this.element.classList.add("console-prompt",WI.SyntaxHighlightedStyleClassName);this.element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/UserInputPrompt.svg","glyph"));this._delegate=delegate||null;this._codeMirror=WI.CodeMirrorEditor.create(this.element,{lineWrapping:true,mode:{name:mimeType,globalVars:true},matchBrackets:true});var keyMap={"Up":this._handlePreviousKey.bind(this),"Down":this._handleNextKey.bind(this),"Ctrl-P":this._handlePreviousKey.bind(this),"Ctrl-N":this._handleNextKey.bind(this),"Enter":this._handleEnterKey.bind(this),"Cmd-Enter":this._handleCommandEnterKey.bind(this),"Tab":this._handleTabKey.bind(this),"Esc":this._handleEscapeKey.bind(this)};this._codeMirror.addKeyMap(keyMap);this._completionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.PausedConsoleCommandLineAPI,this._codeMirror,this);this._completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let textarea=this._codeMirror.getInputField();if(textarea)
textarea.ariaLabel=WI.UIString("Console prompt");this._history=[{}];this._historyIndex=0;} 
get delegate()
{return this._delegate;}
set delegate(delegate)
{this._delegate=delegate||null;}
set escapeKeyHandlerWhenEmpty(handler)
{this._escapeKeyHandlerWhenEmpty=handler;}
get text()
{return this._codeMirror.getValue();}
set text(text)
{this._codeMirror.setValue(text||"");this._codeMirror.clearHistory();this._codeMirror.markClean();}
get history()
{this._history[this._historyIndex]=this._historyEntryForCurrentText();return this._history;}
set history(history)
{this._history=history instanceof Array?history.slice(0,WI.ConsolePrompt.MaximumHistorySize):[{}];this._historyIndex=0;this._restoreHistoryEntry(0);}
get focused()
{return this._codeMirror.getWrapperElement().classList.contains("CodeMirror-focused");}
focus()
{this._codeMirror.focus();}
updateCompletions(completions,implicitSuffix)
{this._completionController.updateCompletions(completions,implicitSuffix);}
pushHistoryItem(text)
{this._commitHistoryEntry({text});} 
completionControllerCompletionsNeeded(completionController,prefix,defaultCompletions,base,suffix,forced)
{if(this.delegate&&typeof this.delegate.consolePromptCompletionsNeeded==="function")
this.delegate.consolePromptCompletionsNeeded(this,defaultCompletions,base,prefix,suffix,forced);else
this._completionController.updateCompletions(defaultCompletions);}
completionControllerShouldAllowEscapeCompletion(completionController)
{
return!!this.text;}
sizeDidChange()
{super.sizeDidChange();if(this.text)
this._codeMirror.refresh();} 
_handleTabKey(codeMirror)
{var cursor=codeMirror.getCursor();var line=codeMirror.getLine(cursor.line);if(!line.trim().length)
return CodeMirror.Pass;var firstNonSpace=line.search(/[^\s]/);if(cursor.ch<=firstNonSpace)
return CodeMirror.Pass;this._completionController.completeAtCurrentPositionIfNeeded().then(function(result){if(result===WI.CodeMirrorCompletionController.UpdatePromise.NoCompletionsFound)
InspectorFrontendHost.beep();});}
_handleEscapeKey(codeMirror)
{if(this.text)
return CodeMirror.Pass;if(!this._escapeKeyHandlerWhenEmpty)
return CodeMirror.Pass;this._escapeKeyHandlerWhenEmpty();}
_handlePreviousKey(codeMirror)
{if(this._codeMirror.somethingSelected())
return CodeMirror.Pass;if(this._codeMirror.getCursor().line)
return CodeMirror.Pass;var historyEntry=this._history[this._historyIndex+1];if(!historyEntry)
return CodeMirror.Pass;this._rememberCurrentTextInHistory();++this._historyIndex;this._restoreHistoryEntry(this._historyIndex);}
_handleNextKey(codeMirror)
{if(this._codeMirror.somethingSelected())
return CodeMirror.Pass;if(this._codeMirror.getCursor().line!==this._codeMirror.lastLine())
return CodeMirror.Pass;var historyEntry=this._history[this._historyIndex-1];if(!historyEntry)
return CodeMirror.Pass;this._rememberCurrentTextInHistory();--this._historyIndex;this._restoreHistoryEntry(this._historyIndex);}
_handleEnterKey(codeMirror,forceCommit,keepCurrentText)
{var currentText=this.text;if(!currentText.trim())
return;var cursor=this._codeMirror.getCursor();var lastLine=this._codeMirror.lastLine();var lastLineLength=this._codeMirror.getLine(lastLine).length;var cursorIsAtLastPosition=positionsEqual(cursor,{line:lastLine,ch:lastLineLength});function positionsEqual(a,b)
{return a.line===b.line&&a.ch===b.ch;}
function commitTextOrInsertNewLine(commit)
{if(!commit){if(positionsEqual(cursor,this._codeMirror.getCursor()))
CodeMirror.commands.newlineAndIndent(this._codeMirror);return;}
this._commitHistoryEntry(this._historyEntryForCurrentText());if(!keepCurrentText){this._codeMirror.setValue("");this._codeMirror.clearHistory();}
if(this.delegate&&typeof this.delegate.consolePromptHistoryDidChange==="function")
this.delegate.consolePromptHistoryDidChange(this);if(this.delegate&&typeof this.delegate.consolePromptTextCommitted==="function")
this.delegate.consolePromptTextCommitted(this,currentText);}
if(!forceCommit&&this.delegate&&typeof this.delegate.consolePromptShouldCommitText==="function"){this.delegate.consolePromptShouldCommitText(this,currentText,cursorIsAtLastPosition,commitTextOrInsertNewLine.bind(this));return;}
commitTextOrInsertNewLine.call(this,true);}
_commitHistoryEntry(historyEntry)
{if(this._history[1]&&(!this._history[1].text||this._history[1].text===historyEntry.text)){this._history[1]=historyEntry;this._history[0]={};}else{this._history[0]=historyEntry;this._history.unshift({});if(this._history.length>WI.ConsolePrompt.MaximumHistorySize)
this._history=this._history.slice(0,WI.ConsolePrompt.MaximumHistorySize);}
this._historyIndex=0;}
_handleCommandEnterKey(codeMirror)
{this._handleEnterKey(codeMirror,true,true);}
_restoreHistoryEntry(index)
{var historyEntry=this._history[index];this._codeMirror.setValue(historyEntry.text||"");if(historyEntry.undoHistory)
this._codeMirror.setHistory(historyEntry.undoHistory);else
this._codeMirror.clearHistory();this._codeMirror.setCursor(historyEntry.cursor||{line:0});}
_historyEntryForCurrentText()
{return{text:this.text,undoHistory:this._codeMirror.getHistory(),cursor:this._codeMirror.getCursor()};}
_rememberCurrentTextInHistory()
{this._history[this._historyIndex]=this._historyEntryForCurrentText();if(this.delegate&&typeof this.delegate.consolePromptHistoryDidChange==="function")
this.delegate.consolePromptHistoryDidChange(this);}};WI.ConsolePrompt.MaximumHistorySize=30;WI.ConsoleSession=class ConsoleSession extends WI.Object
{constructor(data)
{super();this._hasMessages=false;let element=document.createElement("div");element.className="console-session";let header=document.createElement("div");header.classList.add("console-session-header");let headerText="";switch(data.newSessionReason){case WI.ConsoleSession.NewSessionReason.PageReloaded:headerText=WI.UIString("Page reloaded at %s");break;case WI.ConsoleSession.NewSessionReason.PageNavigated:headerText=WI.UIString("Page navigated at %s");break;case WI.ConsoleSession.NewSessionReason.ConsoleCleared:headerText=WI.UIString("Console cleared at %s");break;default:headerText=WI.UIString("Console opened at %s");break;}
let timestamp=data.timestamp||Date.now();header.textContent=headerText.format(new Date(timestamp).toLocaleTimeString());element.append(header);this.element=element;this._messagesElement=element;} 
addMessageView(messageView)
{var messageElement=messageView.element;messageElement.classList.add(WI.LogContentView.ItemWrapperStyleClassName);this.append(messageElement);}
append(messageOrGroupElement)
{this._hasMessages=true;this._messagesElement.append(messageOrGroupElement);}
hasMessages()
{return this._hasMessages;}};WI.ConsoleSession.NewSessionReason={PageReloaded:Symbol("Page reloaded"),PageNavigated:Symbol("Page navigated"),ConsoleCleared:Symbol("Console cleared"),};WI.ContentViewContainer=class ContentViewContainer extends WI.View
{constructor({disableBackForwardNavigation}={})
{super();this._disableBackForwardNavigation=!!disableBackForwardNavigation;this.element.classList.add("content-view-container");this._backForwardList=[];this._currentIndex=-1;} 
get currentIndex()
{return this._currentIndex;}
get backForwardList()
{return this._backForwardList;}
get currentContentView()
{if(this._currentIndex<0||this._currentIndex>this._backForwardList.length-1)
return null;return this._backForwardList[this._currentIndex].contentView;}
get currentBackForwardEntry()
{if(this._currentIndex<0||this._currentIndex>this._backForwardList.length-1)
return null;return this._backForwardList[this._currentIndex];}
contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments)
{return WI.ContentView.contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments);}
showContentViewForRepresentedObject(representedObject,extraArguments)
{var contentView=this.contentViewForRepresentedObject(representedObject,false,extraArguments);if(!contentView)
return null;this.showContentView(contentView);return contentView;}
showContentView(contentView,cookie)
{if(this._disableBackForwardNavigation&&this.currentContentView){this.replaceContentView(this.currentContentView,contentView,cookie);return;}
if(!(contentView instanceof WI.ContentView))
return null;if(contentView===this.currentContentView&&!cookie)
return contentView;
if(contentView.parentContainer!==this)
this._takeOwnershipOfContentView(contentView);let currentEntry=this.currentBackForwardEntry;


let provisionalEntry=null;for(let i=this._backForwardList.length-1;i>=0;--i){if(this._backForwardList[i].contentView===contentView){provisionalEntry=this._backForwardList[i].makeCopy(cookie);break;}}
if(!provisionalEntry)
provisionalEntry=new WI.BackForwardEntry(contentView,cookie);if(provisionalEntry.isEqual(currentEntry)){currentEntry.prepareToShow();return currentEntry.contentView;}

let newIndex=this._currentIndex+1;let removedEntries=this._backForwardList.splice(newIndex,this._backForwardList.length-newIndex,provisionalEntry);for(let i=0;i<removedEntries.length;++i){let shouldDissociateContentView=!this._backForwardList.some((existingEntry)=>existingEntry.contentView===removedEntries[i].contentView);if(shouldDissociateContentView)
this._disassociateFromContentView(removedEntries[i].contentView,removedEntries[i].tombstone);}
contentView._parentContainer=this;this.showBackForwardEntryForIndex(newIndex);return contentView;}
showBackForwardEntryForIndex(index)
{if(index<0||index>this._backForwardList.length-1)
return;if(this._currentIndex===index)
return;var previousEntry=this.currentBackForwardEntry;this._currentIndex=index;var currentEntry=this.currentBackForwardEntry;if(previousEntry&&(!currentEntry.contentView.isAttached||previousEntry.contentView!==currentEntry.contentView))
this._hideEntry(previousEntry);this._showEntry(currentEntry);this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);}
replaceContentView(oldContentView,newContentView,newCookie)
{if(!(oldContentView instanceof WI.ContentView))
return;if(!(newContentView instanceof WI.ContentView))
return;if(oldContentView.parentContainer!==this)
return;if(newContentView.parentContainer&&newContentView.parentContainer!==this)
return;var currentlyShowing=this.currentContentView===oldContentView;if(currentlyShowing)
this._hideEntry(this.currentBackForwardEntry);this._disassociateFromContentView(oldContentView,false);newContentView._parentContainer=this;for(var i=0;i<this._backForwardList.length;++i){if(this._backForwardList[i].contentView===oldContentView){let currentCookie=newCookie??this._backForwardList[i].cookie;this._backForwardList[i]=new WI.BackForwardEntry(newContentView,currentCookie);}}
this._removeIdenticalAdjacentBackForwardEntries();if(currentlyShowing){this._showEntry(this.currentBackForwardEntry);this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);}}
closeContentView(contentViewToClose)
{if(!this._backForwardList.length){return;}
var allSameContentView=true;for(var i=this._backForwardList.length-1;i>=0;--i){if(this._backForwardList[i].contentView!==contentViewToClose){allSameContentView=false;break;}}
if(allSameContentView){this.closeAllContentViews();return;}
var visibleContentView=this.currentContentView;var backForwardListDidChange=false;for(var i=this._backForwardList.length-1;i>=0;--i){var entry=this._backForwardList[i];if(entry.contentView!==contentViewToClose)
continue;if(entry.contentView===visibleContentView)
this._hideEntry(entry);if(this._currentIndex>=i){
--this._currentIndex;}
this._disassociateFromContentView(entry.contentView,entry.tombstone);this._backForwardList.splice(i,1);backForwardListDidChange=true;}
if(backForwardListDidChange)
this._removeIdenticalAdjacentBackForwardEntries();var currentEntry=this.currentBackForwardEntry;if(currentEntry&&currentEntry.contentView!==visibleContentView||backForwardListDidChange){this._showEntry(currentEntry);this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);}}
closeAllContentViews(filter)
{if(!this._backForwardList.length){return;}
var visibleContentView=this.currentContentView;for(let i=0;i<this._backForwardList.length;++i){let entry=this._backForwardList[i];if(filter&&!filter(entry.contentView))
continue;if(entry.contentView===visibleContentView)
this._hideEntry(entry);this._disassociateFromContentView(entry.contentView,entry.tombstone);}
this._backForwardList=[];this._currentIndex=-1;this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);}
canGoBack()
{return this._currentIndex>0;}
canGoForward()
{return this._currentIndex<this._backForwardList.length-1;}
goBack()
{if(!this.canGoBack())
return;this.showBackForwardEntryForIndex(this._currentIndex-1);}
goForward()
{if(!this.canGoForward())
return;this.showBackForwardEntryForIndex(this._currentIndex+1);}
attached()
{super.attached();var currentEntry=this.currentBackForwardEntry;if(currentEntry)
this._showEntry(currentEntry);}
detached()
{var currentEntry=this.currentBackForwardEntry;if(currentEntry)
this._hideEntry(currentEntry);super.detached();} 
_takeOwnershipOfContentView(contentView)
{if(contentView.parentContainer===this)
return;if(contentView.parentContainer)
contentView.parentContainer._placeTombstonesForContentView(contentView);contentView._parentContainer=this;this._clearTombstonesForContentView(contentView);contentView.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_placeTombstonesForContentView(contentView)
{let tombstoneContentViewContainers=this._tombstoneContentViewContainersForContentView(contentView);let visibleContentView=this.currentContentView;for(let entry of this._backForwardList){if(entry.contentView!==contentView)
continue;if(entry.contentView===visibleContentView){this._hideEntry(entry);visibleContentView=null;}
entry.tombstone=true;tombstoneContentViewContainers.push(this);}}
_clearTombstonesForContentView(contentView)
{let tombstoneContentViewContainers=this._tombstoneContentViewContainersForContentView(contentView);tombstoneContentViewContainers.removeAll(this);for(let entry of this._backForwardList){if(entry.contentView!==contentView)
continue;entry.tombstone=false;}}
_disassociateFromContentView(contentView,isTombstone)
{if(isTombstone){let tombstoneContentViewContainers=this._tombstoneContentViewContainersForContentView(contentView);tombstoneContentViewContainers.remove(this);return;}
if(contentView.constructor.shouldNotRemoveFromDOMWhenHidden()&&!contentView.visible)
return;this.removeSubview(contentView);if(!contentView._parentContainer)
return;contentView._parentContainer=null;
let tombstoneContentViewContainers=this._tombstoneContentViewContainersForContentView(contentView);if(tombstoneContentViewContainers&&tombstoneContentViewContainers.length){tombstoneContentViewContainers[0]._takeOwnershipOfContentView(contentView);return;}
contentView.closed();if(contentView.representedObject)
WI.ContentView.closedContentViewForRepresentedObject(contentView.representedObject);}
_showEntry(entry)
{
if(entry.tombstone){this._takeOwnershipOfContentView(entry.contentView);}
if(!this.subviews.includes(entry.contentView))
this.addSubview(entry.contentView);else if(entry.contentView.constructor.shouldNotRemoveFromDOMWhenHidden()){entry.contentView.visible=true;entry.contentView._didMoveToParent(this);}
entry.prepareToShow();}
_hideEntry(entry)
{
if(entry.tombstone)
return;entry.prepareToHide();if(this.subviews.includes(entry.contentView)){if(entry.contentView.constructor.shouldNotRemoveFromDOMWhenHidden()){entry.contentView.visible=false;entry.contentView._didMoveToParent(null);}else
this.removeSubview(entry.contentView);}}
_tombstoneContentViewContainersForContentView(contentView)
{let tombstoneContentViewContainers=contentView[WI.ContentViewContainer.TombstoneContentViewContainersSymbol];if(!tombstoneContentViewContainers)
tombstoneContentViewContainers=contentView[WI.ContentViewContainer.TombstoneContentViewContainersSymbol]=[];return tombstoneContentViewContainers;}
_removeIdenticalAdjacentBackForwardEntries()
{if(this._backForwardList.length<2)
return;let previousEntry;for(let i=this._backForwardList.length-1;i>=0;--i){let entry=this._backForwardList[i];if(!entry.isEqual(previousEntry)){previousEntry=entry;continue;}
if(this._currentIndex>=i){
--this._currentIndex;}
this._backForwardList.splice(i,1);}}};WI.ContentViewContainer.Event={CurrentContentViewDidChange:"content-view-container-current-content-view-did-change"};WI.ContentViewContainer.TombstoneContentViewContainersSymbol=Symbol("content-view-container-tombstone-content-view-containers");WI.ContextMenuItem=class ContextMenuItem extends WI.Object
{constructor(topLevelMenu,type,label,disabled,checked)
{super();this._type=type;this._label=label;this._disabled=disabled;this._checked=checked;this._contextMenu=topLevelMenu||this;if(type==="item"||type==="checkbox")
this._id=topLevelMenu.nextId();} 
id()
{return this._id;}
type()
{return this._type;}
isEnabled()
{return!this._disabled;}
setEnabled(enabled)
{this._disabled=!enabled;} 
_buildDescriptor()
{switch(this._type){case"item":return{type:"item",id:this._id,label:this._label,enabled:!this._disabled};case"separator":return{type:"separator"};case"checkbox":return{type:"checkbox",id:this._id,label:this._label,checked:!!this._checked,enabled:!this._disabled};}}};WI.ContextSubMenuItem=class ContextSubMenuItem extends WI.ContextMenuItem
{constructor(topLevelMenu,label,disabled)
{super(topLevelMenu,"subMenu",label,disabled);this._items=[];} 
appendItem(label,handler,disabled)
{let item=new WI.ContextMenuItem(this._contextMenu,"item",label,disabled);this.pushItem(item);this._contextMenu._setHandler(item.id(),handler);return item;}
appendSubMenuItem(label,disabled)
{let item=new WI.ContextSubMenuItem(this._contextMenu,label,disabled);this.pushItem(item);return item;}
appendCheckboxItem(label,handler,checked,disabled)
{let item=new WI.ContextMenuItem(this._contextMenu,"checkbox",label,disabled,checked);this.pushItem(item);this._contextMenu._setHandler(item.id(),handler);return item;}
appendHeader(label)
{return this.appendItem(label,()=>{},true);}
appendSeparator()
{if(this._items.length)
this._pendingSeparator=true;}
pushItem(item)
{if(this._pendingSeparator){this._items.push(new WI.ContextMenuItem(this._contextMenu,"separator"));this._pendingSeparator=null;}
this._items.push(item);}
isEmpty()
{return!this._items.length;} 
_buildDescriptor()
{if(this.isEmpty())
return null;let subItems=this._items.map((item)=>item._buildDescriptor()).filter((item)=>!!item);return{type:"subMenu",label:this._label,enabled:!this._disabled,subItems};}};WI.ContextMenu=class ContextMenu extends WI.ContextSubMenuItem
{constructor(event)
{super(null,"");this._event=event;this._handlers={};this._id=0;this._beforeShowCallbacks=[];} 
static createFromEvent(event,onlyExisting=false)
{if(!event[WI.ContextMenu.ProposedMenuSymbol]&&!onlyExisting)
event[WI.ContextMenu.ProposedMenuSymbol]=new WI.ContextMenu(event);return event[WI.ContextMenu.ProposedMenuSymbol]||null;}
static contextMenuItemSelected(id)
{if(WI.ContextMenu._lastContextMenu)
WI.ContextMenu._lastContextMenu._itemSelected(id);}
static contextMenuCleared()
{
} 
nextId()
{return this._id++;}
show()
{let menuObject=this._buildDescriptor();if(menuObject.length){WI.ContextMenu._lastContextMenu=this;if(this._event.type!=="contextmenu"&&typeof InspectorFrontendHost.dispatchEventAsContextMenuEvent==="function"){this._menuObject=menuObject;this._event.target.addEventListener("contextmenu",this,true);InspectorFrontendHost.dispatchEventAsContextMenuEvent(this._event);}else
InspectorFrontendHost.showContextMenu(this._event,menuObject);}
if(this._event)
this._event.stopImmediatePropagation();}
addBeforeShowCallback(callback)
{this._beforeShowCallbacks.push(callback);} 
handleEvent(event)
{for(let callback of this._beforeShowCallbacks)
callback(this);this._event.target.removeEventListener("contextmenu",this,true);InspectorFrontendHost.showContextMenu(event,this._menuObject);this._menuObject=null;event.stopImmediatePropagation();} 
_setHandler(id,handler)
{if(handler)
this._handlers[id]=handler;}
_buildDescriptor()
{return this._items.map((item)=>item._buildDescriptor()).filter((item)=>!!item);}
_itemSelected(id)
{try{if(this._handlers[id])
this._handlers[id].call(this);}catch(e){WI.reportInternalError(e);}}};WI.ContextMenu.ProposedMenuSymbol=Symbol("context-menu-proposed-menu");WI.addMouseDownContextMenuHandlers=function(element,populateContextMenuCallback)
{let ignoreMouseDown=false;element.addEventListener("mousedown",(event)=>{if(event.button!==0)
return;event.stop();if(ignoreMouseDown)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.addBeforeShowCallback(()=>{ignoreMouseDown=false;});populateContextMenuCallback(contextMenu,event);ignoreMouseDown=!contextMenu.isEmpty();contextMenu.show();});element.addEventListener("contextmenu",(event)=>{let contextMenu=WI.ContextMenu.createFromEvent(event);populateContextMenuCallback(contextMenu,event);});};WI.appendContextMenuItemsForSourceCode=function(contextMenu,sourceCodeOrLocation)
{if(!(contextMenu instanceof WI.ContextMenu))
return;let sourceCode=sourceCodeOrLocation;let location=null;if(sourceCodeOrLocation instanceof WI.SourceCodeLocation){sourceCode=sourceCodeOrLocation.sourceCode;location=sourceCodeOrLocation;}
if(!(sourceCode instanceof WI.SourceCode))
return;if(contextMenu.__domBreakpointItemsAdded)
return;if(!contextMenu.__localOverrideItemsAdded&&WI.NetworkManager.supportsOverridingResponses()){contextMenu.__localOverrideItemsAdded=true;if(WI.networkManager.canBeOverridden(sourceCode)){contextMenu.appendSeparator();if(WI.NetworkManager.supportsOverridingRequests()){contextMenu.appendItem(WI.UIString("Create Request Local Override"),async()=>{let localResourceOverride=await sourceCode.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Request);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}
contextMenu.appendItem(WI.UIString("Create Response Local Override"),async()=>{let localResourceOverride=await sourceCode.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}else{let localResourceOverride=WI.networkManager.localResourceOverridesForURL(sourceCode.url)[0];if(localResourceOverride){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal Local Override"),()=>{WI.showLocalResourceOverride(localResourceOverride,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});contextMenu.appendItem(localResourceOverride.disabled?WI.UIString("Enable Local Override"):WI.UIString("Disable Local Override"),()=>{localResourceOverride.disabled=!localResourceOverride.disabled;});contextMenu.appendItem(WI.UIString("Delete Local Override"),()=>{WI.networkManager.removeLocalResourceOverride(localResourceOverride);});}}}
contextMenu.appendSeparator();if(location&&(sourceCode instanceof WI.Script||(sourceCode instanceof WI.Resource&&sourceCode.type===WI.Resource.Type.Script&&!sourceCode.localResourceOverride))){let existingBreakpoint=WI.debuggerManager.breakpointForSourceCodeLocation(location);if(existingBreakpoint){contextMenu.appendItem(WI.UIString("Delete Breakpoint"),()=>{WI.debuggerManager.removeBreakpoint(existingBreakpoint);});}else{contextMenu.appendItem(WI.UIString("Add Breakpoint"),()=>{WI.debuggerManager.addBreakpoint(new WI.JavaScriptBreakpoint(location));});}}
if(sourceCode.supportsScriptBlackboxing){let blackboxData=WI.debuggerManager.blackboxDataForSourceCode(sourceCode);if(blackboxData&&blackboxData.type===WI.DebuggerManager.BlackboxType.Pattern){contextMenu.appendItem(WI.UIString("Reveal Blackbox Pattern"),()=>{WI.showSettingsTab({blackboxPatternToSelect:blackboxData.regex,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}else{contextMenu.appendItem(blackboxData?WI.UIString("Unblackbox Script"):WI.UIString("Blackbox Script"),()=>{WI.debuggerManager.setShouldBlackboxScript(sourceCode,!blackboxData);});}}
contextMenu.appendSeparator();WI.appendContextMenuItemsForURL(contextMenu,sourceCode.url,{sourceCode,location});if(sourceCode instanceof WI.Resource&&!sourceCode.localResourceOverride){if(sourceCode.urlComponents.scheme!=="data"){contextMenu.appendItem(WI.UIString("Copy as cURL"),()=>{InspectorFrontendHost.copyText(sourceCode.generateCURLCommand());});contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Copy HTTP Request"),()=>{InspectorFrontendHost.copyText(sourceCode.stringifyHTTPRequest());});if(sourceCode.hasResponse()){contextMenu.appendItem(WI.UIString("Copy HTTP Response"),()=>{InspectorFrontendHost.copyText(sourceCode.stringifyHTTPResponse());});}}}
contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Save File"),()=>{sourceCode.requestContent().then(()=>{let saveData={url:sourceCode.url,content:sourceCode.content,base64Encoded:sourceCode.base64Encoded,};if(sourceCode.urlComponents.path==="/"){let extension=WI.fileExtensionForMIMEType(sourceCode.mimeType);if(extension)
saveData.suggestedName=`index.${extension}`;}
const forceSaveAs=true;WI.FileUtilities.save(saveData,forceSaveAs);});});contextMenu.appendSeparator();};WI.appendContextMenuItemsForURL=function(contextMenu,url,options={})
{if(!url)
return;function showResourceWithOptions(options){options.initiatorHint=WI.TabBrowser.TabNavigationInitiator.ContextMenu;if(options.location)
WI.showSourceCodeLocation(options.location,options);else if(options.sourceCode)
WI.showSourceCode(options.sourceCode,options);else
WI.openURL(url,options.frame,options);}
if(!url.startsWith("javascript:")&&!url.startsWith("data:")){contextMenu.appendItem(WI.UIString("Open in New Window","Open in New Window @ Context Menu Item","Context menu item for opening the target item in a new window."),()=>{const frame=null;WI.openURL(url,frame,{alwaysOpenExternally:true});});}
if(WI.networkManager.resourcesForURL(url).size){if(!WI.isShowingSourcesTab()){contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{showResourceWithOptions({preferredTabType:WI.SourcesTabContentView.Type});});}
if(!WI.isShowingNetworkTab()){contextMenu.appendItem(WI.UIString("Reveal in Network Tab"),()=>{showResourceWithOptions({preferredTabType:WI.NetworkTabContentView.Type});});}}
contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Copy Link"),()=>{InspectorFrontendHost.copyText(url);});};WI.appendContextMenuItemsForDOMNode=function(contextMenu,domNode,options={})
{if(!(contextMenu instanceof WI.ContextMenu))
return;if(!(domNode instanceof WI.DOMNode))
return;let copySubMenu=options.copySubMenu||contextMenu.appendSubMenuItem(WI.UIString("Copy"));let isElement=domNode.nodeType()===Node.ELEMENT_NODE;let attached=domNode.attached;if(isElement&&attached){copySubMenu.appendItem(WI.UIString("Selector Path"),()=>{let cssPath=WI.cssPath(domNode);InspectorFrontendHost.copyText(cssPath);});}
if(!domNode.isPseudoElement()&&attached){copySubMenu.appendItem(WI.UIString("XPath"),()=>{let xpath=WI.xpath(domNode);InspectorFrontendHost.copyText(xpath);});}
contextMenu.appendSeparator();if(!options.usingLocalDOMNode){if(domNode.isCustomElement()){contextMenu.appendItem(WI.UIString("Jump to Definition"),()=>{function didGetFunctionDetails(error,response){if(error)
return;let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,WI.mainTarget);if(!sourceCode)
return;let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);WI.showSourceCodeLocation(sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});}
WI.RemoteObject.resolveNode(domNode).then((remoteObject)=>{remoteObject.getProperty("constructor",(error,result,wasThrown)=>{if(error)
return;if(result.type==="function")
remoteObject.target.DebuggerAgent.getFunctionDetails(result.objectId,didGetFunctionDetails);result.release();});remoteObject.release();});});contextMenu.appendSeparator();}
if(!options.disallowEditing&&WI.cssManager.canForcePseudoClasses()&&domNode.attached){contextMenu.appendSeparator();let pseudoSubMenu=contextMenu.appendSubMenuItem(WI.UIString("Forced Pseudo-Classes","A context menu item to force (override) a DOM node's pseudo-classes"));let enabledPseudoClasses=domNode.enabledPseudoClasses;WI.CSSManager.ForceablePseudoClasses.forEach((pseudoClass)=>{let enabled=enabledPseudoClasses.includes(pseudoClass);pseudoSubMenu.appendCheckboxItem(pseudoClass.capitalize(),()=>{domNode.setPseudoClassEnabled(pseudoClass,!enabled);},enabled);});}
if(WI.domDebuggerManager.supported&&isElement&&!domNode.isPseudoElement()&&attached){contextMenu.appendSeparator();WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,domNode,options);}
contextMenu.appendSeparator();let canLogShadowTree=!domNode.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees({frontendOnly:true});if(!options.excludeLogElement&&canLogShadowTree&&!domNode.destroyed&&!domNode.isPseudoElement()){let label=isElement?WI.UIString("Log Element","Log (print) DOM element to Console"):WI.UIString("Log Node","Log (print) DOM node to Console");contextMenu.appendItem(label,()=>{WI.RemoteObject.resolveNode(domNode,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{let text=isElement?WI.UIString("Selected Element","Selected DOM element"):WI.UIString("Selected Node","Selected DOM node");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);});});}
if(!options.excludeRevealElement&&InspectorBackend.hasDomain("DOM")&&attached){contextMenu.appendItem(WI.repeatedUIString.revealInDOMTree(),()=>{WI.domManager.inspectElement(domNode.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}
if(InspectorBackend.hasDomain("LayerTree")&&attached){contextMenu.appendItem(WI.UIString("Reveal in Layers Tab","Open Layers tab and select the layer corresponding to this node"),()=>{WI.showLayersTab({nodeToSelect:domNode,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}
if(InspectorBackend.hasCommand("Page.snapshotNode")&&attached){contextMenu.appendItem(WI.UIString("Capture Screenshot","Capture screenshot of the selected DOM node"),()=>{let target=WI.assumingMainTarget();target.PageAgent.snapshotNode(domNode.id,(error,dataURL)=>{if(error){const target=WI.mainTarget;const source=WI.ConsoleMessage.MessageSource.Other;const level=WI.ConsoleMessage.MessageLevel.Error;let consoleMessage=new WI.ConsoleMessage(target,source,level,error);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);return;}
WI.FileUtilities.save({content:parseDataURL(dataURL).data,base64Encoded:true,suggestedName:WI.FileUtilities.screenshotString()+".png",});});});}
if(isElement&&attached){contextMenu.appendItem(WI.UIString("Scroll into View","Scroll selected DOM node into view on the inspected web page"),()=>{domNode.scrollIntoView();});}
contextMenu.appendSeparator();}};WI.appendContextMenuItemsForDOMNodeBreakpoints=function(contextMenu,domNode,options={})
{if(contextMenu.__domBreakpointItemsAdded)
return;contextMenu.__domBreakpointItemsAdded=true;let breakpoints=WI.domDebuggerManager.domBreakpointsForNode(domNode);contextMenu.appendSeparator();let subMenu=contextMenu.appendSubMenuItem(WI.UIString("Break on"));for(let type of Object.values(WI.DOMBreakpoint.Type)){let label=WI.DOMBreakpoint.displayNameForType(type);let breakpoint=breakpoints.find((breakpoint)=>breakpoint.type===type);subMenu.appendCheckboxItem(label,function(){if(breakpoint)
WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);else
WI.domDebuggerManager.addDOMBreakpoint(new WI.DOMBreakpoint(domNode,type));},!!breakpoint);}
if(breakpoints.length&&!WI.isShowingSourcesTab()){contextMenu.appendItem(breakpoints.length===1?WI.UIString("Reveal Breakpoint in Sources Tab"):WI.UIString("Reveal Breakpoints in Sources Tab"),()=>{WI.showSourcesTab({representedObjectToSelect:breakpoints.length===1?breakpoints[0]:domNode,});});}
contextMenu.appendSeparator();if(breakpoints.length===1)
WI.BreakpointPopover.appendContextMenuItems(contextMenu,breakpoints[0],options.popoverTargetElement);else if(breakpoints.length){let shouldEnable=breakpoints.some((breakpoint)=>breakpoint.disabled);contextMenu.appendItem(shouldEnable?WI.UIString("Enable Breakpoints"):WI.UIString("Disable Breakpoints"),()=>{for(let breakpoint of breakpoints)
breakpoint.disabled=!shouldEnable;});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{for(let breakpoint of breakpoints)
WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);});contextMenu.appendSeparator();}
let subtreeBreakpoints=WI.domDebuggerManager.domBreakpointsInSubtree(domNode);if(subtreeBreakpoints.length){if(options.revealDescendantBreakpointsMenuItemHandler)
contextMenu.appendItem(WI.UIString("Reveal Descendant Breakpoints"),options.revealDescendantBreakpointsMenuItemHandler);let subtreeShouldEnable=subtreeBreakpoints.some((breakpoint)=>breakpoint.disabled);contextMenu.appendItem(subtreeShouldEnable?WI.UIString("Enable Descendant Breakpoints"):WI.UIString("Disable Descendant Breakpoints"),()=>{for(let subtreeBreakpoint of subtreeBreakpoints)
subtreeBreakpoint.disabled=!subtreeShouldEnable;});contextMenu.appendItem(WI.UIString("Delete Descendant Breakpoints"),()=>{for(let subtreeBreakpoint of subtreeBreakpoints)
WI.domDebuggerManager.removeDOMBreakpoint(subtreeBreakpoint);});contextMenu.appendSeparator();}};WI.CSSDocumentationPopover=class CSSDocumentationPopover extends WI.Popover
{constructor(cssProperty,delegate)
{super(delegate);this._cssProperty=cssProperty;this._targetElement=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} 
show(targetElement)
{this._targetElement=targetElement;let documentationDetails=this._getDocumentationDetails(this._cssProperty);let documentationElement=this._createDocumentationElement(documentationDetails);this.content=documentationElement;this._presentOverTargetElement();} 
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),[WI.RectEdge.MIN_X,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_Y]);}
_getDocumentationDetails(property)
{let propertyName="";if(property.canonicalName in CSSDocumentation)
propertyName=property.canonicalName;else if(property.name in CSSDocumentation)
propertyName=property.name;let propertyDocumentation=CSSDocumentation[propertyName];return{name:propertyName,description:propertyDocumentation.description,syntax:propertyDocumentation.syntax,url:propertyDocumentation.url,};}
_createDocumentationElement(details)
{let documentationElement=document.createElement("div");documentationElement.className="documentation-popover-content";let nameElement=documentationElement.appendChild(document.createElement("p"));nameElement.className="name-header";nameElement.textContent=details.name;let descriptionElement=documentationElement.appendChild(document.createElement("p"));descriptionElement.textContent=details.description;if(details.syntax&&WI.settings.showCSSPropertySyntaxInDocumentationPopover.value){let syntaxElement=documentationElement.appendChild(document.createElement("p"));syntaxElement.className="syntax";let syntaxTitleElement=syntaxElement.appendChild(document.createElement("span"));syntaxTitleElement.className="syntax-title";syntaxTitleElement.textContent=details.name;let syntaxBodyElement=syntaxElement.appendChild(document.createElement("span"));syntaxBodyElement.textContent=`: ${details.syntax}`;}
if(details.url){let referenceLinkElement=documentationElement.appendChild(document.createElement("a"));referenceLinkElement.className="reference-link";referenceLinkElement.textContent=WI.unlocalizedString("MDN Reference");referenceLinkElement.href=details.url;}
return documentationElement;}};WI.CookiePopover=class CookiePopover extends WI.Popover
{constructor(delegate)
{super(delegate);this._nameInputElement=null;this._valueInputElement=null;this._domainInputElement=null;this._pathInputElement=null;this._sessionCheckboxElement=null;this._expiresInputElement=null;this._httpOnlyCheckboxElement=null;this._secureCheckboxElement=null;this._sameSiteSelectElement=null;this._serializedDataWhenShown=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} 
get serializedData()
{if(!this._targetElement)
return null;let name=this._nameInputElement.value;if(!name)
return null;let domain=this._domainInputElement.value||this._domainInputElement.placeholder;if(!domain)
return null;let path=this._pathInputElement.value||this._pathInputElement.placeholder;if(!path)
return null;let session=this._sessionCheckboxElement.checked;let expires=this._parseExpires();if(!session&&isNaN(expires))
return null;try{let url=new URL(domain);domain=url.hostname;}catch{}
if(!path.startsWith("/"))
path="/"+path;let data={name,value:this._valueInputElement.value,domain,path,httpOnly:this._httpOnlyCheckboxElement.checked,secure:this._secureCheckboxElement.checked,sameSite:this._sameSiteSelectElement.value,};if(session)
data.session=true;else
data.expires=expires;if(JSON.stringify(data)===JSON.stringify(this._serializedDataWhenShown))
return null;return data;}
show(cookie,targetElement,preferredEdges,options={})
{this._targetElement=targetElement;this._preferredEdges=preferredEdges;function formatDate(date){function pad(number){return String(number).padStart(2,"0");}
return[date.getFullYear(),"-",pad(date.getMonth()+1),"-",pad(date.getDate()),"T",pad(date.getHours()),":",pad(date.getMinutes()),":",pad(date.getSeconds()),].join("");}
let data={};if(cookie){data.name=cookie.name;data.value=cookie.value;data.domain=cookie.domain;data.path=cookie.path;data.expires=formatDate(cookie.expires||this._defaultExpires());data.session=cookie.session;data.httpOnly=cookie.httpOnly;data.secure=cookie.secure;data.sameSite=cookie.sameSite;}else{let urlComponents=WI.networkManager.mainFrame.mainResource.urlComponents;data.name="";data.value="";data.domain=urlComponents.host;data.path=urlComponents.path;data.expires=formatDate(this._defaultExpires());data.session=true;data.httpOnly=false;data.secure=false;data.sameSite=WI.Cookie.SameSiteType.None;}
let popoverContentElement=document.createElement("div");popoverContentElement.className="cookie-popover-content";let tableElement=popoverContentElement.appendChild(document.createElement("table"));function createRow(id,label,editorElement){let domId=`cookie-popover-${id}-editor`;let rowElement=tableElement.appendChild(document.createElement("tr"));let headerElement=rowElement.appendChild(document.createElement("th"));let labelElement=headerElement.appendChild(document.createElement("label"));labelElement.setAttribute("for",domId);labelElement.textContent=label;let dataElement=rowElement.appendChild(document.createElement("td"));editorElement.id=domId;dataElement.appendChild(editorElement);if(id===options.focusField){setTimeout(()=>{editorElement.focus();editorElement.select?.();});}
return{rowElement};}
let boundHandleInputKeyDown=this._handleInputKeyDown.bind(this);function createInputRow(id,label,type,value){let inputElement=document.createElement("input");inputElement.type=type;if(type==="checkbox")
inputElement.checked=value;else{if(cookie)
inputElement.value=value;inputElement.placeholder=value;inputElement.spellcheck=false;inputElement.addEventListener("keydown",boundHandleInputKeyDown);}
let rowElement=createRow(id,label,inputElement).rowElement;return{inputElement,rowElement};}
this._nameInputElement=createInputRow("name",WI.UIString("Name"),"text",data.name).inputElement;this._nameInputElement.required=true;this._valueInputElement=createInputRow("value",WI.UIString("Value"),"text",data.value).inputElement;this._domainInputElement=createInputRow("domain",WI.unlocalizedString("Domain"),"text",data.domain).inputElement;this._pathInputElement=createInputRow("path",WI.unlocalizedString("Path"),"text",data.path).inputElement;this._sessionCheckboxElement=createInputRow("session",WI.unlocalizedString("Session"),"checkbox",data.session).inputElement;let expiresInputRow=createInputRow("expires",WI.unlocalizedString("Expires"),"datetime-local",data.expires);this._expiresInputElement=expiresInputRow.inputElement;this._expiresInputElement.step=1;this._expiresInputElement.addEventListener("input",(event)=>{this._expiresInputElement.classList.toggle("invalid",isNaN(this._parseExpires()));});this._httpOnlyCheckboxElement=createInputRow("http-only",WI.unlocalizedString("HttpOnly"),"checkbox",data.httpOnly).inputElement;this._secureCheckboxElement=createInputRow("secure",WI.unlocalizedString("Secure"),"checkbox",data.secure).inputElement;this._sameSiteSelectElement=document.createElement("select");for(let sameSiteType of Object.values(WI.Cookie.SameSiteType)){let optionElement=this._sameSiteSelectElement.appendChild(document.createElement("option"));optionElement.value=sameSiteType;optionElement.textContent=WI.Cookie.displayNameForSameSiteType(sameSiteType);}
this._sameSiteSelectElement.value=data.sameSite;createRow("same-site",WI.unlocalizedString("SameSite"),this._sameSiteSelectElement);let toggleExpiresRow=()=>{expiresInputRow.rowElement.hidden=this._sessionCheckboxElement.checked;this.update();};this._sessionCheckboxElement.addEventListener("change",(event)=>{toggleExpiresRow();});toggleExpiresRow();this._serializedDataWhenShown=this.serializedData;this.content=popoverContentElement;this._presentOverTargetElement();} 
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),this._preferredEdges);}
_defaultExpires()
{return new Date(Date.now()+(1000*60*60*24));}
_parseExpires()
{let timestamp=Date.parse(this._expiresInputElement.value||this._expiresInputElement.placeholder);if(timestamp<Date.now())
return NaN;return timestamp;}
_handleInputKeyDown(event)
{if(event.key==="Enter"||event.key==="Esc")
this.dismiss();}};WI.CookieStorageContentView=class CookieStorageContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("cookie-storage");this._cookies=[];this._filteredCookies=[];this._sortComparator=null;this._table=null;this._knownCells=new WeakSet;this._emptyFilterResultsMessageElement=null;this._filterBarNavigationItem=new WI.FilterBarNavigationItem;this._filterBarNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._handleFilterBarFilterDidChange,this);if(InspectorBackend.hasCommand("Page.setCookie")){this._setCookieButtonNavigationItem=new WI.ButtonNavigationItem("cookie-storage-set-cookie",WI.UIString("Add Cookie"),"Images/Plus15.svg",15,15);this._setCookieButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleSetCookieButtonClick,this);}
if(InspectorBackend.hasCommand("Page.getCookies")){this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("cookie-storage-refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshButtonClicked,this);}
if(InspectorBackend.hasCommand("Page.deleteCookie")){this._clearButtonNavigationItem=new WI.ButtonNavigationItem("cookie-storage-clear",WI.UIString("Clear Cookies"),"Images/NavigationItemTrash.svg",15,15);this._clearButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._clearButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleClearNavigationItemClicked,this);}} 
get navigationItems()
{let navigationItems=[];navigationItems.push(this._filterBarNavigationItem);navigationItems.push(new WI.DividerNavigationItem);if(this._setCookieButtonNavigationItem)
navigationItems.push(this._setCookieButtonNavigationItem);if(this._refreshButtonNavigationItem)
navigationItems.push(this._refreshButtonNavigationItem);if(this._clearButtonNavigationItem)
navigationItems.push(this._clearButtonNavigationItem);return navigationItems;}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.CookieStorage;cookie.host=this.representedObject.host;}
get scrollableElements()
{if(!this._table)
return[];return[this._table.scrollContainer];}
get canFocusFilterBar()
{return true;}
focusFilterBar()
{this._filterBarNavigationItem.filterBar.focus();}
handleCopyEvent(event)
{if(!this._table||!this._table.selectedRows.length)
return;let cookies=this._cookiesAtIndexes(this._table.selectedRows);if(!cookies.length)
return;event.clipboardData.setData("text/plain",this._formatCookiesAsText(cookies));event.stopPropagation();event.preventDefault();} 
tableIndexForRepresentedObject(table,object)
{let index=this._filteredCookies.indexOf(object);return index;}
tableRepresentedObjectForIndex(table,index)
{return this._filteredCookies[index];}
tableNumberOfRows(table)
{return this._filteredCookies.length;}
tableSortChanged(table)
{this._generateSortComparator();if(!this._sortComparator)
return;this._updateSort();this._updateFilteredCookies();this._updateEmptyFilterResultsMessage();this._table.reloadData();} 
tableCellContextMenuClicked(table,cell,column,rowIndex,event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.appendSeparator();if(InspectorBackend.hasCommand("Page.setCookie")&&column.identifier!=="size"){contextMenu.appendItem(WI.UIString("Edit %s").format(column.name),()=>{this._showCookiePopover(cell,this._filteredCookies[rowIndex],column.identifier);});}
contextMenu.appendItem(WI.UIString("Copy"),()=>{let rowIndexes;if(table.isRowSelected(rowIndex))
rowIndexes=table.selectedRows;else
rowIndexes=[rowIndex];let cookies=this._cookiesAtIndexes(rowIndexes);InspectorFrontendHost.copyText(this._formatCookiesAsText(cookies));});if(InspectorBackend.hasCommand("Page.deleteCookie")){contextMenu.appendItem(WI.UIString("Delete"),()=>{if(table.isRowSelected(rowIndex))
table.removeSelectedRows();else
table.removeRow(rowIndex);});}
contextMenu.appendSeparator();}
tableDidRemoveRows(table,rowIndexes)
{if(!rowIndexes.length)
return;for(let i=rowIndexes.length-1;i>=0;--i){let rowIndex=rowIndexes[i];let cookie=this._filteredCookies[rowIndex];if(!cookie)
continue;this._filteredCookies.splice(rowIndex,1);this._cookies.remove(cookie);let target=WI.assumingMainTarget();target.PageAgent.deleteCookie(cookie.name,cookie.url);}}
tablePopulateCell(table,cell,column,rowIndex)
{let cookie=this._filteredCookies[rowIndex];cell.textContent=this._formatCookiePropertyForColumn(cookie,column);if(!this._knownCells.has(cell)){this._knownCells.add(cell);cell.addEventListener("dblclick",(event)=>{if(column.identifier==="size"){InspectorFrontendHost.beep();return;}
this._showCookiePopover(cell,cookie,column.identifier);});}
return cell;} 
willDismissPopover(popover)
{if(popover instanceof WI.CookiePopover){this._willDismissCookiePopover(popover);return;}} 
initialLayout()
{super.initialLayout();this._table=new WI.Table("cookies-table",this,this,20);this._table.allowsMultipleSelection=true;this._nameColumn=new WI.TableColumn("name",WI.UIString("Name"),{minWidth:70,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked,});this._valueColumn=new WI.TableColumn("value",WI.UIString("Value"),{minWidth:100,maxWidth:600,initialWidth:200,hideable:false,});this._domainColumn=new WI.TableColumn("domain",WI.unlocalizedString("Domain"),{minWidth:100,maxWidth:200,initialWidth:120,});this._pathColumn=new WI.TableColumn("path",WI.unlocalizedString("Path"),{minWidth:50,maxWidth:300,initialWidth:100,});this._expiresColumn=new WI.TableColumn("expires",WI.unlocalizedString("Expires"),{minWidth:100,maxWidth:200,initialWidth:150,});this._sizeColumn=new WI.TableColumn("size",WI.UIString("Size"),{minWidth:50,maxWidth:80,initialWidth:65,align:"right",});this._secureColumn=new WI.TableColumn("secure",WI.unlocalizedString("Secure"),{minWidth:70,maxWidth:70,align:"center",});this._httpOnlyColumn=new WI.TableColumn("httpOnly",WI.unlocalizedString("HttpOnly"),{minWidth:80,maxWidth:80,align:"center",});this._sameSiteColumn=new WI.TableColumn("sameSite",WI.unlocalizedString("SameSite"),{minWidth:40,maxWidth:80,initialWidth:70,align:"center",});this._table.addColumn(this._nameColumn);this._table.addColumn(this._valueColumn);this._table.addColumn(this._domainColumn);this._table.addColumn(this._pathColumn);this._table.addColumn(this._expiresColumn);this._table.addColumn(this._sizeColumn);this._table.addColumn(this._secureColumn);this._table.addColumn(this._httpOnlyColumn);this._table.addColumn(this._sameSiteColumn);if(!this._table.sortColumnIdentifier){this._table.sortOrder=WI.Table.SortOrder.Ascending;this._table.sortColumnIdentifier="name";}
this.addSubview(this._table);this._table.element.addEventListener("keydown",this._handleTableKeyDown.bind(this));this._reloadCookies();} 
_getCookiesForHost(cookies,host)
{let resourceMatchesStorageDomain=(resource)=>{let urlComponents=resource.urlComponents;return urlComponents&&urlComponents.host&&urlComponents.host===host;};let allResources=[];for(let frame of WI.networkManager.frames){allResources.push(frame.mainResource,...frame.resourceCollection);}
let resourcesForDomain=allResources.filter(resourceMatchesStorageDomain);let cookiesForDomain=cookies.filter((cookie)=>{return resourcesForDomain.some((resource)=>{return WI.CookieStorageObject.cookieMatchesResourceURL(cookie,resource.url);});});return cookiesForDomain;}
_generateSortComparator()
{let sortColumnIdentifier=this._table.sortColumnIdentifier;if(!sortColumnIdentifier){this._sortComparator=null;return;}
let comparator=null;switch(sortColumnIdentifier){case"name":case"value":case"domain":case"path":case"sameSite":comparator=(a,b)=>(a[sortColumnIdentifier]||"").extendedLocaleCompare(b[sortColumnIdentifier]||"");break;case"size":case"httpOnly":case"secure":comparator=(a,b)=>a[sortColumnIdentifier]-b[sortColumnIdentifier];break;case"expires":comparator=(a,b)=>{if(!a.expires)
return 1;if(!b.expires)
return-1;return a.expires-b.expires;};break;default:return;}
let reverseFactor=this._table.sortOrder===WI.Table.SortOrder.Ascending?1:-1;this._sortComparator=(a,b)=>reverseFactor*comparator(a,b);}
_showCookiePopover(targetElement,cookie,columnIdentifier){this._editingCookie=cookie;let options={};if(columnIdentifier){switch(columnIdentifier){case"name":case"value":case"domain":case"path":case"secure":options.focusField=columnIdentifier;break;case"expires":options.focusField=this._editingCookie.session?"session":"expires";break;case"httpOnly":options.focusField="http-only";break;case"sameSite":options.focusField="same-site";break;default:break;}}
let popover=new WI.CookiePopover(this);popover.show(this._editingCookie,targetElement,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X,WI.RectEdge.MAX_X],options);}
async _willDismissCookiePopover(popover)
{let editingCookie=this._editingCookie;this._editingCookie=null;let serializedData=popover.serializedData;if(!serializedData){InspectorFrontendHost.beep();return;}
let cookieToSet=WI.Cookie.fromPayload(serializedData);let cookieProtocolPayload=cookieToSet.toProtocol();if(!cookieProtocolPayload){InspectorFrontendHost.beep();return;}
let target=WI.assumingMainTarget();let promises=[];if(editingCookie)
promises.push(target.PageAgent.deleteCookie(editingCookie.name,editingCookie.url));promises.push(target.PageAgent.setCookie(cookieProtocolPayload));promises.push(this._reloadCookies());await Promise.all(promises);let index=this._filteredCookies.findIndex((existingCookie)=>cookieToSet.equals(existingCookie));if(index>=0)
this._table.selectRow(index);}
_handleFilterBarFilterDidChange(event)
{this._updateFilteredCookies();this._updateEmptyFilterResultsMessage();this._table.reloadData();}
_handleSetCookieButtonClick(event)
{this._showCookiePopover(this._setCookieButtonNavigationItem.element,null,"name");}
_refreshButtonClicked(event)
{this._reloadCookies();}
_handleClearNavigationItemClicked(event)
{let target=WI.assumingMainTarget();for(let cookie of this._cookies)
target.PageAgent.deleteCookie(cookie.name,cookie.url);this._reloadCookies();}
_reloadCookies()
{let target=WI.assumingMainTarget();if(!target.hasCommand("Page.getCookies"))
return;target.PageAgent.getCookies().then((payload)=>{this._cookies=this._getCookiesForHost(payload.cookies.map(WI.Cookie.fromPayload),this.representedObject.host);this._updateSort();this._updateFilteredCookies();this._updateEmptyFilterResultsMessage();this._table.reloadData();}).catch((error)=>{console.error("Could not fetch cookies: ",error);});}
_updateSort()
{if(!this._sortComparator)
return;this._cookies.sort(this._sortComparator);}
_updateFilteredCookies()
{this._filteredCookies=this._cookies;let filterBar=this._filterBarNavigationItem.filterBar;filterBar.invalid=false;let filterText=filterBar.filters.text;if(!filterText)
return;let regex=WI.SearchUtilities.filterRegExpForString(filterText,WI.SearchUtilities.defaultSettings);if(!regex){filterBar.invalid=true;return;}
this._filteredCookies=this._filteredCookies.filter((cookie)=>{for(let column of this._table.columns){let text=this._formatCookiePropertyForColumn(cookie,column);if(text&&regex.test(text))
return true;}
return false;});}
_updateEmptyFilterResultsMessage()
{if(this._filteredCookies.length||!this._filterBarNavigationItem.filterBar.filters.text){if(this._emptyFilterResultsMessageElement)
this._emptyFilterResultsMessageElement.remove();this._emptyFilterResultsMessageElement=null;}else{if(!this._emptyFilterResultsMessageElement){let buttonElement=document.createElement("button");buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",(event)=>{this._filterBarNavigationItem.filterBar.clear();});this._emptyFilterResultsMessageElement=WI.createMessageTextView(WI.UIString("No Filter Results"));this._emptyFilterResultsMessageElement.appendChild(buttonElement);}
this.element.appendChild(this._emptyFilterResultsMessageElement);}}
_handleTableKeyDown(event)
{if(event.keyCode===WI.KeyboardShortcut.Key.Backspace.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Delete.keyCode){if(InspectorBackend.hasCommand("Page.deleteCookie"))
this._table.removeSelectedRows();else
InspectorFrontendHost.beep();}}
_cookiesAtIndexes(indexes)
{if(!this._filteredCookies.length)
return[];return indexes.map((index)=>this._filteredCookies[index]);}
_formatCookiesAsText(cookies)
{let visibleColumns=this._table.columns.filter((column)=>!column.hidden);if(!visibleColumns.length)
return"";let lines=cookies.map((cookie)=>{const usePunctuation=false;let values=visibleColumns.map((column)=>this._formatCookiePropertyForColumn(cookie,column,usePunctuation));return values.join("\t");});return lines.join("\n");}
_formatCookiePropertyForColumn(cookie,column,usePunctuation=true)
{const checkmark="\u2713";const missingValue=usePunctuation?emDash:"";const missingCheckmark=usePunctuation?zeroWidthSpace:"";switch(column.identifier){case"name":return cookie.name;case"value":return cookie.value;case"domain":return cookie.domain||missingValue;case"path":return cookie.path||missingValue;case"expires":return(!cookie.session&&cookie.expires)?cookie.expires.toLocaleString():WI.UIString("Session");case"size":return Number.bytesToString(cookie.size);case"secure":return cookie.secure?checkmark:missingCheckmark;case"httpOnly":return cookie.httpOnly?checkmark:missingCheckmark;case"sameSite":return cookie.sameSite===WI.Cookie.SameSiteType.None?missingValue:WI.Cookie.displayNameForSameSiteType(cookie.sameSite);}
return"";}};WI.CookieType={Request:0,Response:1};WI.CookieStorageTreeElement=class CookieStorageTreeElement extends WI.StorageTreeElement
{constructor(representedObject)
{super("cookie-icon",WI.displayNameForHost(representedObject.host),representedObject);} 
get name()
{return this.representedObject.host;}
get categoryName()
{return WI.UIString("Cookies");}};WI.CreateAuditPopover=class CreateAuditPopover extends WI.Popover
{constructor(delegate)
{super(delegate);this._audit=null;this._targetElement=null;this._preferredEdges=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} 
get audit(){return this._audit;}
show(targetElement,preferredEdges)
{this._targetElement=targetElement;this._preferredEdges=preferredEdges;let contentElement=document.createElement("div");contentElement.classList.add("create-audit-content");let label=contentElement.appendChild(document.createElement("div"));label.classList.add("label");label.textContent=WI.UIString("Create audit:");let editorWrapper=contentElement.appendChild(document.createElement("div"));editorWrapper.classList.add("editor-wrapper");this._typeSelectElement=editorWrapper.appendChild(document.createElement("select"));let createOption=(text,value)=>{let optionElement=this._typeSelectElement.appendChild(document.createElement("option"));optionElement.textContent=text;optionElement.value=value;return optionElement;};createOption(WI.UIString("Test Case","Test Case @ Audit Tab Navigation Sidebar","Dropdown option inside the popover used to creating an audit test case."),"test-case");createOption(WI.UIString("Group","Group @ Audit Tab Navigation Sidebar","Dropdown option inside the popover used to creating an audit group."),"group");this._nameInputElement=editorWrapper.appendChild(document.createElement("input"));this._nameInputElement.placeholder=WI.UIString("Name");this._nameInputElement.addEventListener("keydown",(event)=>{if(event.keyCode===WI.KeyboardShortcut.Key.Enter.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode){event.stop();this.dismiss();}});editorWrapper.appendChild(WI.createReferencePageLink("audit-tab","creating-audits"));this.content=contentElement;this._presentOverTargetElement();}
dismiss()
{const placeholderTestFunctionString=WI.DefaultAudits.newAuditPlaceholder.toString();let type=this._typeSelectElement.value;let name=this._nameInputElement.value;if(type&&name){switch(type){case"test-case":this._audit=new WI.AuditTestCase(name,placeholderTestFunctionString);break;case"group":this._audit=new WI.AuditTestGroup(name,[new WI.AuditTestCase(WI.unlocalizedString("test-case"),placeholderTestFunctionString)]);break;}}
super.dismiss();} 
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),this._preferredEdges);}};WI.DOMBreakpointTreeElement=class DOMBreakpointTreeElement extends WI.BreakpointTreeElement
{constructor(breakpoint,{classNames,title}={})
{if(!Array.isArray(classNames))
classNames=[];classNames.push("dom",breakpoint.type);if(!title)
title=breakpoint.displayName;super(breakpoint,{classNames,title});}};WI.DOMEventsBreakdownView=class DOMEventsBreakdownView extends WI.View
{constructor(domNodeOrEvents,{includeGraph}={})
{super();if(domNodeOrEvents instanceof WI.DOMNode){this._domNode=domNodeOrEvents;this._domNode.addEventListener(WI.DOMNode.Event.DidFireEvent,this._handleDOMNodeDidFireEvent,this);if(this._domNode.canEnterPowerEfficientPlaybackState())
this._domNode.addEventListener(WI.DOMNode.Event.PowerEfficientPlaybackStateChanged,this._handleDOMNodePowerEfficientPlaybackStateChanged,this);this._domEvents=null;}else{this._domNode=null;this._domEvents=domNodeOrEvents;}
this._includeGraph=includeGraph||false;this._tableBodyElement=null;this.element.classList.add("dom-events-breakdown");} 
initialLayout()
{super.initialLayout();let tableElement=this.element.appendChild(document.createElement("table"));let headElement=tableElement.appendChild(document.createElement("thead"));let headRowElement=headElement.appendChild(document.createElement("tr"));let eventHeadCell=headRowElement.appendChild(document.createElement("th"));eventHeadCell.textContent=WI.UIString("Event");if(this._includeGraph)
headRowElement.appendChild(document.createElement("th"));let timeHeadCell=headRowElement.appendChild(document.createElement("th"));timeHeadCell.classList.add("time");timeHeadCell.textContent=WI.UIString("Time");let originatorHeadCell=headRowElement.appendChild(document.createElement("th"));originatorHeadCell.classList.add("originator");originatorHeadCell.textContent=WI.UIString("Originator");this._tableBodyElement=tableElement.appendChild(document.createElement("tbody"));}
layout()
{if(this.layoutReason!==WI.View.LayoutReason.Dirty)
return;this._tableBodyElement.removeChildren();let domEvents=this._domEvents||this._domNode.domEvents;let startTimestamp=domEvents[0].timestamp;let endTimestamp=domEvents.lastValue.timestamp;let totalTime=endTimestamp-startTimestamp;let styleAttribute=WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR?"left":"right";function percentOfTotalTime(time){return time/totalTime*100;}
let fullscreenRanges=[];let fullscreenDOMEvents=WI.DOMNode.getFullscreenDOMEvents(domEvents);for(let fullscreenDOMEvent of fullscreenDOMEvents){let{enabled}=fullscreenDOMEvent.data;if(enabled||!fullscreenRanges.length){fullscreenRanges.push({startTimestamp:enabled?fullscreenDOMEvent.timestamp:startTimestamp,});}
fullscreenRanges.lastValue.endTimestamp=(enabled&&fullscreenDOMEvent===fullscreenDOMEvents.lastValue)?endTimestamp:fullscreenDOMEvent.timestamp;if(fullscreenDOMEvent.originator)
fullscreenRanges.lastValue.originator=fullscreenDOMEvent.originator;}
let powerEfficientPlaybackRanges=this._domNode?this._domNode.powerEfficientPlaybackRanges:[];for(let domEvent of domEvents){let rowElement=this._tableBodyElement.appendChild(document.createElement("tr"));let nameCell=rowElement.appendChild(document.createElement("td"));nameCell.classList.add("name");nameCell.textContent=domEvent.eventName;if(this._includeGraph){let graphCell=rowElement.appendChild(document.createElement("td"));graphCell.classList.add("graph");let fullscreenRange=fullscreenRanges.find((range)=>domEvent.timestamp>=range.startTimestamp&&domEvent.timestamp<=range.endTimestamp);if(fullscreenRange){let fullscreenArea=graphCell.appendChild(document.createElement("div"));fullscreenArea.classList.add("area","fullscreen");fullscreenArea.style.setProperty(styleAttribute,percentOfTotalTime(fullscreenRange.startTimestamp-startTimestamp)+"%");fullscreenArea.style.setProperty("width",percentOfTotalTime(fullscreenRange.endTimestamp-fullscreenRange.startTimestamp)+"%");if(fullscreenRange.originator)
fullscreenArea.title=WI.UIString("Full-Screen from \u201C%s\u201D").format(fullscreenRange.originator.displayName);else
fullscreenArea.title=WI.UIString("Full-Screen");}
let powerEfficientPlaybackRange=powerEfficientPlaybackRanges.find((range)=>domEvent.timestamp>=range.startTimestamp&&domEvent.timestamp<=range.endTimestamp);if(powerEfficientPlaybackRange){let powerEfficientPlaybackArea=graphCell.appendChild(document.createElement("div"));powerEfficientPlaybackArea.classList.add("area","power-efficient-playback");powerEfficientPlaybackArea.title=WI.UIString("Power Efficient Playback");powerEfficientPlaybackArea.style.setProperty(styleAttribute,percentOfTotalTime(powerEfficientPlaybackRange.startTimestamp-startTimestamp)+"%");powerEfficientPlaybackArea.style.setProperty("width",percentOfTotalTime(powerEfficientPlaybackRange.endTimestamp-powerEfficientPlaybackRange.startTimestamp)+"%");}
let graphImage=graphCell.appendChild(document.createElement("img"));graphImage.style.setProperty(styleAttribute,`calc(${percentOfTotalTime(domEvent.timestamp - startTimestamp)}% - (var(--img-size) / 2))`);if(WI.DOMNode.isPlayEvent(domEvent.eventName))
graphImage.src="Images/EventPlay.svg";else if(WI.DOMNode.isPauseEvent(domEvent.eventName))
graphImage.src="Images/EventPause.svg";else if(WI.DOMNode.isStopEvent(domEvent.eventName))
graphImage.src="Images/EventStop.svg";else
graphImage.src="Images/EventProcessing.svg";}
let timeCell=rowElement.appendChild(document.createElement("td"));timeCell.classList.add("time");const higherResolution=true;timeCell.textContent=Number.secondsToString(domEvent.timestamp,higherResolution);let originatorCell=rowElement.appendChild(document.createElement("td"));originatorCell.classList.add("originator");if(domEvent.originator){originatorCell.appendChild(WI.linkifyNodeReference(domEvent.originator));rowElement.classList.add("inherited");this.element.classList.add("has-inherited");}}} 
_handleDOMNodeDidFireEvent(event)
{this.needsLayout();}
_handleDOMNodePowerEfficientPlaybackStateChanged(event)
{this.needsLayout();}};WI.DOMNodeDetailsSidebarPanel=class DOMNodeDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel
{constructor()
{super("dom-node-details",WI.UIString("Node"));this._eventListenerGroupingMethodSetting=new WI.Setting("dom-node-event-listener-grouping-method",WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Event);this.element.classList.add("dom-node");this._nodeRemoteObject=null;} 
closed()
{if(this.didInitialLayout){WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeModified,this._attributesChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CustomElementStateChanged,this._customElementStateChanged,this);}
super.closed();} 
initialLayout()
{super.initialLayout();WI.domManager.addEventListener(WI.DOMManager.Event.AttributeModified,this._attributesChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.addEventListener(WI.DOMManager.Event.CustomElementStateChanged,this._customElementStateChanged,this);this._identityNodeTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._identityNodeNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._identityNodeValueRow=new WI.DetailsSectionSimpleRow(WI.UIString("Value"));this._identityNodeContentSecurityPolicyHashRow=new WI.DetailsSectionSimpleRow(WI.UIString("CSP Hash"));var identityGroup=new WI.DetailsSectionGroup([this._identityNodeTypeRow,this._identityNodeNameRow,this._identityNodeValueRow,this._identityNodeContentSecurityPolicyHashRow]);var identitySection=new WI.DetailsSection("dom-node-identity",WI.UIString("Identity"),[identityGroup]);this.contentView.element.appendChild(identitySection.element);this._attributesDataGridRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Attributes"));var attributesGroup=new WI.DetailsSectionGroup([this._attributesDataGridRow]);var attributesSection=new WI.DetailsSection("dom-node-attributes",WI.UIString("Attributes"),[attributesGroup]);this.contentView.element.appendChild(attributesSection.element);if(InspectorBackend.hasCommand("DOM.resolveNode")){this._propertiesRow=new WI.DetailsSectionRow;let propertiesGroup=new WI.DetailsSectionGroup([this._propertiesRow]);let propertiesSection=new WI.DetailsSection("dom-node-properties",WI.UIString("Properties"),[propertiesGroup]);this.contentView.element.appendChild(propertiesSection.element);}
let eventListenersFilterElement=WI.ImageUtilities.useSVGSymbol("Images/FilterFieldGlyph.svg","filter",WI.UIString("Grouping Method"));WI.addMouseDownContextMenuHandlers(eventListenersFilterElement,this._populateEventListenersFilterContextMenu.bind(this));this._eventListenersSectionGroup=new WI.DetailsSectionGroup;let eventListenersSection=new WI.DetailsSection("dom-node-event-listeners",WI.UIString("Event Listeners"),[this._eventListenersSectionGroup],eventListenersFilterElement);this.contentView.element.appendChild(eventListenersSection.element);if(InspectorBackend.hasCommand("DOM.getDataBindingsForNode")){this._dataBindingsSection=new WI.DetailsSection("dom-node-data-bindings",WI.UIString("Data Bindings"),[]);this.contentView.element.appendChild(this._dataBindingsSection.element);}
if(InspectorBackend.hasCommand("DOM.getAssociatedDataForNode")){this._associatedDataGrid=new WI.DetailsSectionRow(WI.UIString("No Associated Data"));let associatedDataGroup=new WI.DetailsSectionGroup([this._associatedDataGrid]);let associatedSection=new WI.DetailsSection("dom-node-associated-data",WI.UIString("Associated Data"),[associatedDataGroup]);this.contentView.element.appendChild(associatedSection.element);}
if(this._accessibilitySupported()){this._accessibilityEmptyRow=new WI.DetailsSectionRow(WI.UIString("No Accessibility Information"));this._accessibilityNodeActiveDescendantRow=new WI.DetailsSectionSimpleRow(WI.UIString("Shared Focus"));this._accessibilityNodeBusyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Busy"));this._accessibilityNodeCheckedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Checked"));this._accessibilityNodeChildrenRow=new WI.DetailsSectionSimpleRow(WI.UIString("Children"));this._accessibilityNodeControlsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Controls"));this._accessibilityNodeCurrentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Current"));this._accessibilityNodeDisabledRow=new WI.DetailsSectionSimpleRow(WI.UIString("Disabled"));this._accessibilityNodeExpandedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Expanded"));this._accessibilityNodeFlowsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Flows"));this._accessibilityNodeFocusedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Focused"));this._accessibilityNodeHeadingLevelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Heading Level"));this._accessibilityNodehierarchyLevelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Hierarchy Level"));this._accessibilityNodeIgnoredRow=new WI.DetailsSectionSimpleRow(WI.UIString("Ignored"));this._accessibilityNodeInvalidRow=new WI.DetailsSectionSimpleRow(WI.UIString("Invalid"));this._accessibilityNodeLiveRegionStatusRow=new WI.DetailsSectionSimpleRow(WI.UIString("Live"));this._accessibilityNodeMouseEventRow=new WI.DetailsSectionSimpleRow("");this._accessibilityNodeLabelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Label"));this._accessibilityNodeOwnsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Owns"));this._accessibilityNodeParentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Parent"));this._accessibilityNodePressedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Pressed"));this._accessibilityNodeReadonlyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Readonly"));this._accessibilityNodeRequiredRow=new WI.DetailsSectionSimpleRow(WI.UIString("Required"));this._accessibilityNodeRoleRow=new WI.DetailsSectionSimpleRow(WI.UIString("Role"));this._accessibilityNodeSelectedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Selected"));this._accessibilityNodeSelectedChildrenRow=new WI.DetailsSectionSimpleRow(WI.UIString("Selected Items"));this._accessibilityGroup=new WI.DetailsSectionGroup([this._accessibilityEmptyRow]);var accessibilitySection=new WI.DetailsSection("dom-node-accessibility",WI.UIString("Accessibility"),[this._accessibilityGroup]);this.contentView.element.appendChild(accessibilitySection.element);}}
layout()
{super.layout();if(!this.domNode||this.domNode.destroyed)
return;this._refreshIdentity();this._refreshAttributes();this._refreshProperties();this._refreshEventListeners();this._refreshDataBindings();this._refreshAssociatedData();this._refreshAccessibility();}
sizeDidChange()
{super.sizeDidChange(); this._attributesDataGridRow.sizeDidChange();}
attached()
{super.attached();WI.DOMNode.addEventListener(WI.DOMNode.Event.EventListenersChanged,this._eventListenersChanged,this);}
detached()
{WI.DOMNode.removeEventListener(WI.DOMNode.Event.EventListenersChanged,this._eventListenersChanged,this);super.detached();} 
_accessibilitySupported()
{return InspectorBackend.hasCommand("DOM.getAccessibilityPropertiesForNode");}
_refreshIdentity()
{const domNode=this.domNode;this._identityNodeTypeRow.value=this._nodeTypeDisplayName();this._identityNodeNameRow.value=domNode.nodeNameInCorrectCase();this._identityNodeValueRow.value=domNode.nodeValue();this._identityNodeContentSecurityPolicyHashRow.value=domNode.contentSecurityPolicyHash();}
_refreshAttributes()
{let domNode=this.domNode;if(!domNode||!domNode.hasAttributes()){this._attributesDataGridRow.dataGrid=null;return;}
let dataGrid=this._attributesDataGridRow.dataGrid;if(!dataGrid){const columns={name:{title:WI.UIString("Name"),width:"30%"},value:{title:WI.UIString("Value")},};dataGrid=this._attributesDataGridRow.dataGrid=new WI.DataGrid(columns);}
dataGrid.removeChildren();let attributes=domNode.attributes();attributes.sort((a,b)=>a.name.extendedLocaleCompare(b.name));for(let attribute of attributes){let dataGridNode=new WI.EditableDataGridNode(attribute);dataGridNode.addEventListener(WI.EditableDataGridNode.Event.ValueChanged,this._attributeNodeValueChanged,this);dataGrid.appendChild(dataGridNode);}
dataGrid.updateLayoutIfNeeded();}
_refreshProperties()
{if(!this._propertiesRow)
return;if(this._nodeRemoteObject){this._nodeRemoteObject.release();this._nodeRemoteObject=null;}
let target=WI.assumingMainTarget();const objectGroup="dom-node-details-sidebar-properties-object-group";target.RuntimeAgent.releaseObjectGroup(objectGroup);let domNode=this.domNode;WI.RemoteObject.resolveNode(domNode,objectGroup).then((object)=>{if(this.domNode!==domNode)
return;this._nodeRemoteObject=object;function inspectedPage_node_collectPrototypes()
{

var prototype=this;var result=[];var counter=1;while(prototype){result[counter++]=prototype;prototype=prototype.__proto__;}
return result;}
const args=undefined;const generatePreview=false;object.callFunction(inspectedPage_node_collectPrototypes,args,generatePreview,nodePrototypesReady.bind(this));}).catch((error)=>{if(this.domNode!==domNode)
return;});function nodePrototypesReady(error,object,wasThrown)
{if(error||wasThrown||!object)
return;if(this.domNode!==domNode)
return;object.getPropertyDescriptors(fillSection.bind(this),{ownProperties:true});}
function fillSection(prototypes)
{if(!prototypes)
return;if(this.domNode!==domNode)
return;let element=this._propertiesRow.element;element.removeChildren();let propertyPath=new WI.PropertyPath(this._nodeRemoteObject,"node");let initialSection=true;for(let i=0;i<prototypes.length;++i){if(!parseInt(prototypes[i].name,10))
continue;let prototype=prototypes[i].value;let prototypeName=prototype.description;let title=prototypeName;if(/Prototype$/.test(title)){prototypeName=prototypeName.replace(/Prototype$/,"");title=prototypeName+WI.UIString(" (Prototype)");}else if(title==="Object")
title=title+WI.UIString(" (Prototype)");let mode=initialSection?WI.ObjectTreeView.Mode.Properties:WI.ObjectTreeView.Mode.PureAPI;let objectTree=new WI.ObjectTreeView(prototype,mode,propertyPath);objectTree.showOnlyProperties();objectTree.setPrototypeNameOverride(prototypeName);let detailsSection=new WI.DetailsSection(prototype.description.hash+"-prototype-properties",title,null,null,true);detailsSection.groups[0].rows=[new WI.ObjectPropertiesDetailSectionRow(objectTree,detailsSection)];element.appendChild(detailsSection.element);initialSection=false;}}}
_refreshEventListeners()
{var domNode=this.domNode;if(!domNode)
return;const windowTargetIdentifier=Symbol("window");function createEventListenerSection(title,eventListeners,options={}){let groups=eventListeners.map((eventListener)=>new WI.EventListenerSectionGroup(eventListener,options));let optionsElement=null;if((WI.DOMManager.supportsDisablingEventListeners()||WI.DOMManager.supportsEventListenerBreakpoints())&&groups.some((group)=>group.supportsStateModification)){optionsElement=WI.ImageUtilities.useSVGSymbol("Images/Gear.svg","event-listener-options",WI.UIString("Options"));WI.addMouseDownContextMenuHandlers(optionsElement,(contextMenu)=>{if(WI.DOMManager.supportsDisablingEventListeners()){let shouldDisable=groups.some((eventListener)=>!eventListener.isEventListenerDisabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Event Listeners"):WI.UIString("Enable Event Listeners"),()=>{for(let group of groups)
group.isEventListenerDisabled=shouldDisable;});}
if(WI.DOMManager.supportsEventListenerBreakpoints()){let shouldBreakpoint=groups.some((eventListener)=>!eventListener.hasEventListenerBreakpoint);contextMenu.appendItem(shouldBreakpoint?WI.UIString("Add Breakpoints"):WI.UIString("Delete Breakpoints"),()=>{for(let group of groups)
group.hasEventListenerBreakpoint=shouldBreakpoint;});}});}
const defaultCollapsedSettingValue=true;let identifier=`${options.identifier ?? title}-event-listener-section`;let section=new WI.DetailsSection(identifier,title,groups,optionsElement,defaultCollapsedSettingValue);section.element.classList.add("event-listener-section");return section;}
function generateGroupsByEvent(eventListeners){let eventListenerTypes=new Map;for(let eventListener of eventListeners){if(eventListener.nodeId)
eventListener.node=WI.domManager.nodeForId(eventListener.nodeId);let eventListenersForType=eventListenerTypes.get(eventListener.type);if(!eventListenersForType)
eventListenerTypes.set(eventListener.type,eventListenersForType=[]);eventListenersForType.push(eventListener);}
let rows=[];let types=Array.from(eventListenerTypes.keys());types.sort();for(let type of types)
rows.push(createEventListenerSection(type,eventListenerTypes.get(type),{hideType:true}));return rows;}
function generateGroupsByTarget(eventListeners){let eventListenerTargets=new Map;for(let eventListener of eventListeners){if(eventListener.nodeId)
eventListener.node=WI.domManager.nodeForId(eventListener.nodeId);let target=eventListener.onWindow?windowTargetIdentifier:eventListener.node;let eventListenersForTarget=eventListenerTargets.get(target);if(!eventListenersForTarget)
eventListenerTargets.set(target,eventListenersForTarget=[]);eventListenersForTarget.push(eventListener);}
let rows=[];function generateSectionForTarget(target){let eventListenersForTarget=eventListenerTargets.get(target);if(!eventListenersForTarget)
return;eventListenersForTarget.sort((a,b)=>a.type.toLowerCase().extendedLocaleCompare(b.type.toLowerCase()));let title=target===windowTargetIdentifier?WI.unlocalizedString("window"):target.displayName;let identifier=target===windowTargetIdentifier?WI.unlocalizedString("window"):target.unescapedSelector;let section=createEventListenerSection(title,eventListenersForTarget,{hideTarget:true,identifier});if(target instanceof WI.DOMNode)
WI.bindInteractionsForNodeToElement(target,section.titleElement,{ignoreClick:true});rows.push(section);}
let currentNode=domNode;do{generateSectionForTarget(currentNode);}while(currentNode=currentNode.parentNode);generateSectionForTarget(windowTargetIdentifier);return rows;}
function eventListenersCallback(error,eventListeners)
{if(error)
return;if(this.domNode!==domNode)
return;if(!eventListeners.length){var emptyRow=new WI.DetailsSectionRow(WI.UIString("No Event Listeners"));emptyRow.showEmptyMessage();this._eventListenersSectionGroup.rows=[emptyRow];return;}
switch(this._eventListenerGroupingMethodSetting.value){case WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Event:this._eventListenersSectionGroup.rows=generateGroupsByEvent.call(this,eventListeners);break;case WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Target:this._eventListenersSectionGroup.rows=generateGroupsByTarget.call(this,eventListeners);break;}}
domNode.getEventListeners(eventListenersCallback.bind(this));}
_refreshDataBindings()
{if(!this._dataBindingsSection)
return;let domNode=this.domNode;if(!domNode)
return;let target=WI.assumingMainTarget();target.DOMAgent.getDataBindingsForNode(this.domNode.id).then(({dataBindings})=>{if(this.domNode!==domNode)
return;if(!dataBindings.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Data Bindings"));emptyRow.showEmptyMessage();this._dataBindingsSection.groups=[new WI.DetailsSectionGroup([emptyRow])];return;}
let groups=[];for(let{binding,type,value}of dataBindings){groups.push(new WI.DetailsSectionGroup([new WI.DetailsSectionSimpleRow(WI.UIString("Binding"),binding),new WI.DetailsSectionSimpleRow(WI.UIString("Type"),type),new WI.DetailsSectionSimpleRow(WI.UIString("Value"),value),]));}
this._dataBindingsSection.groups=groups;});}
_refreshAssociatedData()
{if(!this._associatedDataGrid)
return;let target=WI.assumingMainTarget();const objectGroup="dom-node-details-sidebar-associated-data-object-group";target.RuntimeAgent.releaseObjectGroup(objectGroup);let domNode=this.domNode;if(!domNode)
return;target.DOMAgent.getAssociatedDataForNode(domNode.id).then(({associatedData})=>{if(this.domNode!==domNode)
return;if(!associatedData){this._associatedDataGrid.showEmptyMessage();return;}
let expression=associatedData;const options={objectGroup,doNotPauseOnExceptionsAndMuteConsole:true,};WI.runtimeManager.evaluateInInspectedWindow(expression,options,(result,wasThrown)=>{if(!result){this._associatedDataGrid.showEmptyMessage();return;}
this._associatedDataGrid.hideEmptyMessage();const propertyPath=null;const forceExpanding=true;let element=WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(result,propertyPath,forceExpanding);let objectTree=element.__objectTree;if(objectTree){objectTree.showOnlyJSON();objectTree.expand();}
this._associatedDataGrid.element.appendChild(element);});});}
_refreshAccessibility()
{if(!this._accessibilitySupported())
return;var domNode=this.domNode;if(!domNode)
return;var properties={};function booleanValueToLocalizedStringIfTrue(property){if(properties[property])
return WI.UIString("Yes");return"";}
function booleanValueToLocalizedStringIfPropertyDefined(property){if(properties[property]!==undefined){if(properties[property])
return WI.UIString("Yes");else
return WI.UIString("No");}
return"";}
function linkForNodeId(nodeId){var link=null;if(nodeId!==undefined&&typeof nodeId==="number"){var node=WI.domManager.nodeForId(nodeId);if(node)
link=WI.linkifyAccessibilityNodeReference(node);}
return link;}
function linkListForNodeIds(nodeIds){if(!nodeIds)
return null;const itemsToShow=5;let hasLinks=false;let listItemCount=0;let container=document.createElement("div");container.classList.add("list-container");let linkList=container.createChild("ul","node-link-list");let initiallyHiddenItems=[];for(let nodeId of nodeIds){let node=WI.domManager.nodeForId(nodeId);if(!node)
continue;let link=WI.linkifyAccessibilityNodeReference(node);hasLinks=true;let li=linkList.createChild("li");li.appendChild(link);if(listItemCount>=itemsToShow){li.hidden=true;initiallyHiddenItems.push(li);}
listItemCount++;}
container.appendChild(linkList);if(listItemCount>itemsToShow){let moreNodesButton=container.createChild("button","expand-list-button");moreNodesButton.textContent=WI.UIString("%d More\u2026").format(listItemCount-itemsToShow);moreNodesButton.addEventListener("click",()=>{initiallyHiddenItems.forEach((element)=>{element.hidden=false;});moreNodesButton.remove();});}
if(hasLinks)
return container;return null;}
function accessibilityPropertiesCallback(accessibilityProperties){if(this.domNode!==domNode)
return;properties=accessibilityProperties;if(accessibilityProperties&&accessibilityProperties.exists){var activeDescendantLink=linkForNodeId(accessibilityProperties.activeDescendantNodeId);var busy=booleanValueToLocalizedStringIfPropertyDefined("busy");var checked="";if(accessibilityProperties.checked!==undefined){if(accessibilityProperties.checked===InspectorBackend.Enum.DOM.AccessibilityPropertiesChecked.True)
checked=WI.UIString("Yes");else if(accessibilityProperties.checked===InspectorBackend.Enum.DOM.AccessibilityPropertiesChecked.Mixed)
checked=WI.UIString("Mixed");else
 checked=WI.UIString("No");}
var childNodeLinkList=linkListForNodeIds(accessibilityProperties.childNodeIds);var controlledNodeLinkList=linkListForNodeIds(accessibilityProperties.controlledNodeIds);var current="";switch(accessibilityProperties.current){case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.True:current=WI.UIString("True");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Page:current=WI.UIString("Page");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Location:current=WI.UIString("Location");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Step:current=WI.UIString("Step");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Date:current=WI.UIString("Date");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Time:current=WI.UIString("Time");break;default:current="";}
var disabled=booleanValueToLocalizedStringIfTrue("disabled");var expanded=booleanValueToLocalizedStringIfPropertyDefined("expanded");var flowedNodeLinkList=linkListForNodeIds(accessibilityProperties.flowedNodeIds);var focused=booleanValueToLocalizedStringIfPropertyDefined("focused");var ignored="";if(accessibilityProperties.ignored){ignored=WI.UIString("Yes");if(accessibilityProperties.hidden)
ignored=WI.UIString("%s (hidden)").format(ignored);else if(accessibilityProperties.ignoredByDefault)
ignored=WI.UIString("%s (default)").format(ignored);}
var invalid="";if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.True)
invalid=WI.UIString("Yes");else if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.Grammar)
invalid=WI.UIString("Grammar");else if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.Spelling)
invalid=WI.UIString("Spelling");var label=accessibilityProperties.label;var liveRegionStatus="";var liveRegionStatusNode=null;var liveRegionStatusToken=accessibilityProperties.liveRegionStatus;switch(liveRegionStatusToken){case InspectorBackend.Enum.DOM.AccessibilityPropertiesLiveRegionStatus.Assertive:liveRegionStatus=WI.UIString("Assertive");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesLiveRegionStatus.Polite:liveRegionStatus=WI.UIString("Polite");break;default:liveRegionStatus="";}
if(liveRegionStatus){var liveRegionRelevant=accessibilityProperties.liveRegionRelevant;if(liveRegionRelevant&&liveRegionRelevant.length){if(liveRegionRelevant.length===3&&liveRegionRelevant[0]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Additions&&liveRegionRelevant[1]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Removals&&liveRegionRelevant[2]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Text)
liveRegionRelevant=[WI.UIString("All Changes")];else{liveRegionRelevant=liveRegionRelevant.map(function(value){switch(value){case InspectorBackend.Enum.DOM.LiveRegionRelevant.Additions:return WI.UIString("Additions");case InspectorBackend.Enum.DOM.LiveRegionRelevant.Removals:return WI.UIString("Removals");case InspectorBackend.Enum.DOM.LiveRegionRelevant.Text:return WI.UIString("Text");default:return"\""+value+"\"";}});}
liveRegionStatus+=" ("+liveRegionRelevant.join(", ")+")";}
if(accessibilityProperties.liveRegionAtomic){liveRegionStatusNode=document.createElement("div");liveRegionStatusNode.className="value-with-clarification";liveRegionStatusNode.setAttribute("role","text");liveRegionStatusNode.append(liveRegionStatus);var clarificationNode=document.createElement("div");clarificationNode.className="clarification";clarificationNode.append(WI.UIString("Region announced in its entirety."));liveRegionStatusNode.appendChild(clarificationNode);}}
var mouseEventNodeId=accessibilityProperties.mouseEventNodeId;var mouseEventTextValue="";var mouseEventNodeLink=null;if(mouseEventNodeId){if(mouseEventNodeId===accessibilityProperties.nodeId)
mouseEventTextValue=WI.UIString("Yes");else
mouseEventNodeLink=linkForNodeId(mouseEventNodeId);}
var ownedNodeLinkList=linkListForNodeIds(accessibilityProperties.ownedNodeIds);var parentNodeLink=linkForNodeId(accessibilityProperties.parentNodeId);var pressed=booleanValueToLocalizedStringIfPropertyDefined("pressed");var readonly=booleanValueToLocalizedStringIfTrue("readonly");var required=booleanValueToLocalizedStringIfPropertyDefined("required");var role=accessibilityProperties.role;let hasPopup=accessibilityProperties.isPopupButton;let roleType=null;let buttonType=null;let buttonTypePopupString=WI.UIString("popup");let buttonTypeToggleString=WI.UIString("toggle");let buttonTypePopupToggleString=WI.UIString("popup, toggle");if(role===""||role==="unknown")
role=WI.UIString("No matching ARIA role");else if(role){if(role==="button"){if(pressed)
buttonType=buttonTypeToggleString;

if(hasPopup)
buttonType=buttonType?buttonTypePopupToggleString:buttonTypePopupString;}
if(!domNode.getAttribute("role"))
roleType=WI.UIString("default");else if(buttonType||domNode.getAttribute("role")!==role)
roleType=WI.UIString("computed");if(buttonType&&roleType)
role=WI.UIString("%s (%s, %s)").format(role,buttonType,roleType);else if(roleType||buttonType){let extraInfo=roleType||buttonType;role=WI.UIString("%s (%s)").format(role,extraInfo);}}
var selected=booleanValueToLocalizedStringIfTrue("selected");var selectedChildNodeLinkList=linkListForNodeIds(accessibilityProperties.selectedChildNodeIds);var headingLevel=accessibilityProperties.headingLevel;var hierarchyLevel=accessibilityProperties.hierarchyLevel;this._accessibilityNodeActiveDescendantRow.value=activeDescendantLink||"";this._accessibilityNodeBusyRow.value=busy;this._accessibilityNodeCheckedRow.value=checked;this._accessibilityNodeChildrenRow.value=childNodeLinkList||"";this._accessibilityNodeControlsRow.value=controlledNodeLinkList||"";this._accessibilityNodeCurrentRow.value=current;this._accessibilityNodeDisabledRow.value=disabled;this._accessibilityNodeExpandedRow.value=expanded;this._accessibilityNodeFlowsRow.value=flowedNodeLinkList||"";this._accessibilityNodeFocusedRow.value=focused;this._accessibilityNodeHeadingLevelRow.value=headingLevel||"";this._accessibilityNodehierarchyLevelRow.value=hierarchyLevel||"";this._accessibilityNodeIgnoredRow.value=ignored;this._accessibilityNodeInvalidRow.value=invalid;this._accessibilityNodeLabelRow.value=label;this._accessibilityNodeLiveRegionStatusRow.value=liveRegionStatusNode||liveRegionStatus;this._accessibilityNodeMouseEventRow.label=mouseEventNodeLink?WI.UIString("Click Listener"):WI.UIString("Clickable");this._accessibilityNodeMouseEventRow.value=mouseEventNodeLink||mouseEventTextValue;this._accessibilityNodeOwnsRow.value=ownedNodeLinkList||"";this._accessibilityNodeParentRow.value=parentNodeLink||"";this._accessibilityNodePressedRow.value=pressed;this._accessibilityNodeReadonlyRow.value=readonly;this._accessibilityNodeRequiredRow.value=required;this._accessibilityNodeRoleRow.value=role;this._accessibilityNodeSelectedRow.value=selected;this._accessibilityNodeSelectedChildrenRow.label=WI.UIString("Selected Items");this._accessibilityNodeSelectedChildrenRow.value=selectedChildNodeLinkList||"";if(selectedChildNodeLinkList&&accessibilityProperties.selectedChildNodeIds.length===1)
this._accessibilityNodeSelectedChildrenRow.label=WI.UIString("Selected Item");this._accessibilityGroup.rows=[this._accessibilityNodeIgnoredRow,this._accessibilityNodeRoleRow,this._accessibilityNodeLabelRow,this._accessibilityNodeParentRow,this._accessibilityNodeActiveDescendantRow,this._accessibilityNodeSelectedChildrenRow,this._accessibilityNodeChildrenRow,this._accessibilityNodeOwnsRow,this._accessibilityNodeControlsRow,this._accessibilityNodeFlowsRow,this._accessibilityNodeMouseEventRow,this._accessibilityNodeFocusedRow,this._accessibilityNodeHeadingLevelRow,this._accessibilityNodehierarchyLevelRow,this._accessibilityNodeBusyRow,this._accessibilityNodeLiveRegionStatusRow,this._accessibilityNodeCurrentRow,this._accessibilityNodeDisabledRow,this._accessibilityNodeInvalidRow,this._accessibilityNodeRequiredRow,this._accessibilityNodeCheckedRow,this._accessibilityNodeExpandedRow,this._accessibilityNodePressedRow,this._accessibilityNodeReadonlyRow,this._accessibilityNodeSelectedRow];this._accessibilityEmptyRow.hideEmptyMessage();}else{this._accessibilityGroup.rows=[this._accessibilityEmptyRow];this._accessibilityEmptyRow.showEmptyMessage();}}
domNode.accessibilityProperties(accessibilityPropertiesCallback.bind(this));}
_populateEventListenersFilterContextMenu(contextMenu)
{let addGroupingMethodCheckboxItem=(label,groupingMethod)=>{contextMenu.appendCheckboxItem(label,()=>{this._eventListenerGroupingMethodSetting.value=groupingMethod;this._refreshEventListeners();},this._eventListenerGroupingMethodSetting.value===groupingMethod);};addGroupingMethodCheckboxItem(WI.UIString("Group by Event","Group by Event @ Node Event Listeners","Group DOM event listeners by DOM event"),WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Event);addGroupingMethodCheckboxItem(WI.UIString("Group by Target","Group by Target @ Node Event Listeners","Group DOM event listeners by DOM node"),WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Target);}
_eventListenersChanged(event)
{if(event.target===this.domNode||event.target.isAncestor(this.domNode))
this._refreshEventListeners();}
_attributesChanged(event)
{if(event.data.node!==this.domNode)
return;this._refreshAttributes();this._refreshAccessibility();this._refreshDataBindings();}
_attributeNodeValueChanged(event)
{let change=event.data;let data=event.target.data;if(change.columnIdentifier==="name"){this.domNode.removeAttribute(data[change.columnIdentifier],(error)=>{this.domNode.setAttribute(change.value,`${change.value}="${data.value}"`);});}else if(change.columnIdentifier==="value")
this.domNode.setAttributeValue(data.name,change.value);}
_characterDataModified(event)
{if(event.data.node!==this.domNode)
return;this._identityNodeValueRow.value=this.domNode.nodeValue();}
_customElementStateChanged(event)
{if(event.data.node!==this.domNode)
return;this._refreshIdentity();}
_nodeTypeDisplayName()
{switch(this.domNode.nodeType()){case Node.ELEMENT_NODE:{const nodeName=WI.UIString("Element");const state=this._customElementState();return state===null?nodeName:`${nodeName} (${state})`;}
case Node.TEXT_NODE:return WI.UIString("Text Node");case Node.COMMENT_NODE:return WI.UIString("Comment");case Node.DOCUMENT_NODE:return WI.UIString("Document");case Node.DOCUMENT_TYPE_NODE:return WI.UIString("Document Type");case Node.DOCUMENT_FRAGMENT_NODE:return WI.UIString("Document Fragment");case Node.CDATA_SECTION_NODE:return WI.UIString("Character Data");case Node.PROCESSING_INSTRUCTION_NODE:return WI.UIString("Processing Instruction");default:console.error("Unknown DOM node type: ",this.domNode.nodeType());return this.domNode.nodeType();}}
_customElementState()
{const state=this.domNode.customElementState();switch(state){case WI.DOMNode.CustomElementState.Builtin:return null;case WI.DOMNode.CustomElementState.Custom:return WI.UIString("Custom");case WI.DOMNode.CustomElementState.Waiting:return WI.UIString("Undefined custom element");case WI.DOMNode.CustomElementState.Failed:return WI.UIString("Failed to upgrade");}
console.error("Unknown DOM custom element state: ",state);return null;}};WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod={Event:"event",Target:"target",};WI.DOMNodeEventsContentView=class DOMNodeEventsContentView extends WI.ContentView
{constructor(domNode)
{const representedObject=null;super(representedObject);this._domNode=domNode;this.element.classList.add("dom-node-details","dom-events");this._breakdownView=null;} 
initialLayout()
{super.initialLayout();this._breakdownView=new WI.DOMEventsBreakdownView(this._domNode,{includeGraph:true,});this.addSubview(this._breakdownView);}};WI.DOMNodeTreeElement=class DOMNodeTreeElement extends WI.GeneralTreeElement
{constructor(domNode)
{const subtitle=null;super("dom-node",domNode.displayName,subtitle,domNode,{hasChildren:true});this.status=WI.linkifyNodeReferenceElement(domNode,WI.createGoToArrowButton());this.tooltipHandledSeparately=true;} 
ondelete()
{

this.__deletedViaDeleteKeyboardShortcut=true;WI.domDebuggerManager.removeDOMBreakpointsForNode(this.representedObject);WI.domManager.removeEventListenerBreakpointsForNode(this.representedObject);return true;}
populateContextMenu(contextMenu,event)
{contextMenu.appendSeparator();WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,this.representedObject);contextMenu.appendSeparator();contextMenu.appendItem(WI.repeatedUIString.revealInDOMTree(),()=>{WI.domManager.inspectElement(this.representedObject.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}};WI.DOMStorageContentView=class DOMStorageContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("dom-storage");representedObject.addEventListener(WI.DOMStorageObject.Event.ItemsCleared,this.itemsCleared,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemAdded,this.itemAdded,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemRemoved,this.itemRemoved,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemUpdated,this.itemUpdated,this);let columns={};columns.key={title:WI.UIString("Key"),sortable:true};columns.value={title:WI.UIString("Value"),sortable:true};this._dataGrid=new WI.DataGrid(columns,{editCallback:this._editingCallback.bind(this),copyCallback:this._dataGridCopy.bind(this),deleteCallback:this._deleteCallback.bind(this),});this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.sortColumnIdentifier="key";this._dataGrid.allowsMultipleSelection=true;this._dataGrid.createSettings("dom-storage-content-view");this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);this.addSubview(this._dataGrid);this._filterBarNavigationItem=new WI.FilterBarNavigationItem;this._filterBarNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._handleFilterBarFilterDidChange,this);let clearButtonLabel=representedObject.isLocalStorage()?WI.UIString("Clear Local Storage"):WI.UIString("Clear Session Storage");this._clearButtonNavigationItem=new WI.ButtonNavigationItem("dom-storage-clear",clearButtonLabel,"Images/NavigationItemTrash.svg",15,15);this._clearButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._clearButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleClearNavigationItemClicked,this);this._populate();} 
get navigationItems()
{return[this._filterBarNavigationItem,new WI.DividerNavigationItem,this._clearButtonNavigationItem,];}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.DOMStorage;cookie.isLocalStorage=this.representedObject.isLocalStorage();cookie.host=this.representedObject.host;}
get scrollableElements()
{return[this._dataGrid.scrollContainer];}
get canFocusFilterBar()
{return true;}
focusFilterBar()
{this._filterBarNavigationItem.filterBar.focus();}
itemsCleared(event)
{this._dataGrid.removeChildren();this._dataGrid.addPlaceholderNode();}
itemRemoved(event)
{for(let node of this._dataGrid.children){if(node.data.key===event.data.key)
return this._dataGrid.removeChild(node);}
return null;}
itemAdded(event)
{let{key,value}=event.data;let originalValue=value;value=this._truncateValue(value);for(let node of this._dataGrid.children){if(node.data.key===key)
return;}
this._dataGrid.appendChild(new WI.DataGridNode({key,value,originalValue}));this._sortDataGrid();}
itemUpdated(event)
{let{key,newValue:value}=event.data;let originalValue=value;value=this._truncateValue(value);let keyFound=false;for(let childNode of this._dataGrid.children){if(childNode.data.key===key){if(keyFound){this._dataGrid.removeChild(childNode);continue;}
keyFound=true;childNode.data.value=value;childNode.data.originalValue=originalValue;childNode.refresh();}}
this._sortDataGrid();} 
_truncateValue(value)
{return value.truncate(200);}
_populate()
{this.representedObject.getEntries(function(error,entries){if(error)
return;for(let[key,value]of entries){if(!key||!value)
continue;let originalValue=value;value=this._truncateValue(value);let node=new WI.DataGridNode({key,value,originalValue});this._dataGrid.appendChild(node);}
this._sortDataGrid();this._dataGrid.addPlaceholderNode();this._dataGrid.updateLayout();}.bind(this));}
_sortDataGrid()
{let sortColumnIdentifier=this._dataGrid.sortColumnIdentifier||"key";function comparator(a,b)
{return a.data[sortColumnIdentifier].extendedLocaleCompare(b.data[sortColumnIdentifier]);}
this._dataGrid.sortNodesImmediately(comparator);}
_deleteCallback()
{for(let dataGridNode of this._dataGrid.selectedDataGridNodes){if(dataGridNode.isPlaceholderNode)
continue;this._dataGrid.removeChild(dataGridNode);this.representedObject.removeItem(dataGridNode.data["key"]);}}
_editingCallback(editingNode,columnIdentifier,oldText,newText,moveDirection)
{var key=editingNode.data["key"].trim().removeWordBreakCharacters();var value=editingNode.data["value"].trim().removeWordBreakCharacters();var previousValue=oldText.trim().removeWordBreakCharacters();var enteredValue=newText.trim().removeWordBreakCharacters();var hasUncommittedEdits=editingNode.__hasUncommittedEdits;var hasChange=previousValue!==enteredValue;var isEditingKey=columnIdentifier==="key";var isEditingValue=!isEditingKey;var domStorage=this.representedObject;if(!hasChange&&!hasUncommittedEdits)
return;if(hasChange&&!editingNode.__hasUncommittedEdits){editingNode.__hasUncommittedEdits=true;editingNode.__originalKey=isEditingKey?previousValue:key;editingNode.__originalValue=isEditingValue?previousValue:value;}
function cleanup()
{editingNode.element.classList.remove(WI.DOMStorageContentView.MissingKeyStyleClassName);editingNode.element.classList.remove(WI.DOMStorageContentView.MissingValueStyleClassName);editingNode.element.classList.remove(WI.DOMStorageContentView.DuplicateKeyStyleClassName);editingNode.__hasUncommittedEdits=undefined;editingNode.__originalKey=undefined;editingNode.__originalValue=undefined;}
if(isEditingKey){if(key.length)
editingNode.element.classList.remove(WI.DOMStorageContentView.MissingKeyStyleClassName);else
editingNode.element.classList.add(WI.DOMStorageContentView.MissingKeyStyleClassName);}else if(isEditingValue){if(value.length)
editingNode.element.classList.remove(WI.DOMStorageContentView.MissingValueStyleClassName);else
editingNode.element.classList.add(WI.DOMStorageContentView.MissingValueStyleClassName);}
var keyChanged=key!==editingNode.__originalKey;if(keyChanged){if(domStorage.entries.has(key))
editingNode.element.classList.add(WI.DOMStorageContentView.DuplicateKeyStyleClassName);else
editingNode.element.classList.remove(WI.DOMStorageContentView.DuplicateKeyStyleClassName);}
var columnIndex=this._dataGrid.orderedColumns.indexOf(columnIdentifier);var mayMoveToNextRow=moveDirection==="forward"&&columnIndex===this._dataGrid.orderedColumns.length-1;var mayMoveToPreviousRow=moveDirection==="backward"&&columnIndex===0;var doneEditing=mayMoveToNextRow||mayMoveToPreviousRow||!moveDirection;if(!doneEditing)
return;if(!key.length&&!value.length&&!editingNode.isPlaceholderNode){this._dataGrid.removeChild(editingNode);domStorage.removeItem(editingNode.__originalKey);return;}
var isDuplicate=editingNode.element.classList.contains(WI.DOMStorageContentView.DuplicateKeyStyleClassName);if(!key.length||!value.length||isDuplicate)
return;if(keyChanged&&!editingNode.isPlaceholderNode)
domStorage.removeItem(editingNode.__originalKey);if(editingNode.isPlaceholderNode)
this._dataGrid.addPlaceholderNode();cleanup();domStorage.setItem(key,value);}
_dataGridCopy(node,columnIdentifier,text)
{if(columnIdentifier==="value"&&node.data.originalValue)
return node.data.originalValue;return text;}
_handleFilterBarFilterDidChange(event)
{this._dataGrid.filterText=this._filterBarNavigationItem.filterBar.filters.text||"";}
_handleClearNavigationItemClicked(event)
{this.representedObject.clear();}};WI.DOMStorageContentView.DuplicateKeyStyleClassName="duplicate-key";WI.DOMStorageContentView.MissingKeyStyleClassName="missing-key";WI.DOMStorageContentView.MissingValueStyleClassName="missing-value";WI.DOMStorageTreeElement=class DOMStorageTreeElement extends WI.StorageTreeElement
{constructor(representedObject)
{if(representedObject.isLocalStorage())
var className=WI.DOMStorageTreeElement.LocalStorageIconStyleClassName;else
var className=WI.DOMStorageTreeElement.SessionStorageIconStyleClassName;super(className,WI.displayNameForHost(representedObject.host),representedObject);} 
get name()
{return WI.displayNameForHost(this.representedObject.host);}
get categoryName()
{if(this.representedObject.isLocalStorage())
return WI.UIString("Local Storage");return WI.UIString("Session Storage");}};WI.DOMStorageTreeElement.LocalStorageIconStyleClassName="local-storage-icon";WI.DOMStorageTreeElement.SessionStorageIconStyleClassName="session-storage-icon";WI.DOMTreeElement=class DOMTreeElement extends WI.TreeElement
{constructor(node,elementCloseTag)
{super("",node);this._elementCloseTag=elementCloseTag;this.hasChildren=!elementCloseTag&&this._hasVisibleChildren();if(this.representedObject.nodeType()===Node.ELEMENT_NODE&&!elementCloseTag)
this._canAddAttributes=true;this._searchQuery=null;this._expandedChildrenLimit=WI.DOMTreeElement.InitialChildrenLimit;this._breakpointStatus=WI.DOMTreeElement.BreakpointStatus.None;this._animatingHighlight=false;this._shouldHighlightAfterReveal=false;this._boundHighlightAnimationEnd=this._highlightAnimationEnd.bind(this);this._subtreeBreakpointTreeElements=null;this._showGoToArrow=false;this._highlightedAttributes=new Set;this._recentlyModifiedAttributes=new Map;this._closeTagTreeElement=null;this._gridBadgeElement=null;node.addEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassIndicator,this);this._ignoreSingleTextChild=false;this._forceUpdateTitle=false;} 
static shadowRootTypeDisplayName(type)
{switch(type){case WI.DOMNode.ShadowRootType.UserAgent:return WI.UIString("User Agent");case WI.DOMNode.ShadowRootType.Open:return WI.UIString("Open");case WI.DOMNode.ShadowRootType.Closed:return WI.UIString("Closed");}} 
get statusImageElement(){return this._statusImageElement;}
get hasBreakpoint()
{return this._breakpointStatus!==WI.DOMTreeElement.BreakpointStatus.None||(this._subtreeBreakpointTreeElements&&this._subtreeBreakpointTreeElements.size);}
get breakpointStatus()
{return this._breakpointStatus;}
set breakpointStatus(status)
{if(this._breakpointStatus===status)
return;let increment;if(this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.None)
increment=1;else if(status===WI.DOMTreeElement.BreakpointStatus.None)
increment=-1;this._breakpointStatus=status;this._updateBreakpointStatus();if(!increment)
return;let parentElement=this.parent;while(parentElement&&!parentElement.root){parentElement._subtreeBreakpointChanged(this);parentElement=parentElement.parent;}}
bindRevealDescendantBreakpointsMenuItemHandler()
{if(!this._subtreeBreakpointTreeElements||!this._subtreeBreakpointTreeElements.size)
return null;let subtreeBreakpointTreeElements=Array.from(this._subtreeBreakpointTreeElements);return()=>{for(let subtreeBreakpointTreeElement of subtreeBreakpointTreeElements)
subtreeBreakpointTreeElement.reveal();};}
get closeTagTreeElement(){return this._closeTagTreeElement;}
revealAndHighlight()
{if(this._animatingHighlight)
return;this._shouldHighlightAfterReveal=true;this.reveal();}
isCloseTag()
{return this._elementCloseTag;}
highlightSearchResults(searchQuery)
{if(this._searchQuery!==searchQuery){this._updateSearchHighlight(false);this._highlightResult=undefined;}
this._searchQuery=searchQuery;this._searchHighlightsVisible=true;this.updateTitle(true);}
hideSearchHighlights()
{this._searchHighlightsVisible=false;this._updateSearchHighlight(false);}
emphasizeSearchHighlight()
{var highlightElement=this.title.querySelector("."+WI.DOMTreeElement.SearchHighlightStyleClassName);if(!highlightElement)
return;if(this._bouncyHighlightElement)
this._bouncyHighlightElement.remove();this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className=WI.DOMTreeElement.BouncyHighlightStyleClassName;this._bouncyHighlightElement.textContent=highlightElement.textContent;var highlightElementRect=highlightElement.getBoundingClientRect();var treeOutlineRect=this.treeOutline.element.getBoundingClientRect();this._bouncyHighlightElement.style.top=(highlightElementRect.top-treeOutlineRect.top)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-treeOutlineRect.left)+"px";this.title.appendChild(this._bouncyHighlightElement);function animationEnded()
{if(!this._bouncyHighlightElement)
return;this._bouncyHighlightElement.remove();this._bouncyHighlightElement=null;}
this._bouncyHighlightElement.addEventListener("animationend",animationEnded.bind(this));}
_updateSearchHighlight(show)
{if(!this._highlightResult)
return;function updateEntryShow(entry)
{switch(entry.type){case"added":entry.parent.insertBefore(entry.node,entry.nextSibling);break;case"changed":entry.node.textContent=entry.newText;break;}}
function updateEntryHide(entry)
{switch(entry.type){case"added":entry.node.remove();break;case"changed":entry.node.textContent=entry.oldText;break;}}
var updater=show?updateEntryShow:updateEntryHide;for(var i=0,size=this._highlightResult.length;i<size;++i)
updater(this._highlightResult[i]);}
get hovered()
{return this._hovered;}
set hovered(value)
{if(this._hovered===value)
return;this._hovered=value;if(this.listItemElement){this.listItemElement.classList.toggle("hovered",this._hovered);this.updateSelectionArea();}}
get editable()
{let node=this.representedObject;if(node.destroyed)
return false;if(node.isShadowRoot())
return false;if(node.isInUserAgentShadowTree()&&!WI.DOMManager.supportsEditingUserAgentShadowTrees())
return false;if(node.isPseudoElement())
return false;return this.treeOutline.editable;}
get expandedChildrenLimit()
{return this._expandedChildrenLimit;}
set expandedChildrenLimit(x)
{if(this._expandedChildrenLimit===x)
return;this._expandedChildrenLimit=x;if(this.treeOutline&&!this._updateChildrenInProgress)
this._updateChildren(true);}
get expandedChildCount()
{var count=this.children.length;if(count&&this.children[count-1]._elementCloseTag)
count--;if(count&&this.children[count-1].expandAllButton)
count--;return count;}
set showGoToArrow(x)
{if(this._showGoToArrow===x)
return;this._showGoToArrow=x;this.updateTitle();}
attributeDidChange(name)
{if(this._recentlyModifiedAttributes.has(name))
return;this._recentlyModifiedAttributes.set(name,{value:null,timestamp:NaN,element:null,listener:null,});}
highlightAttribute(name)
{this._highlightedAttributes.add(name);}
showChildNode(node)
{if(this._elementCloseTag)
return null;var index=this._visibleChildren().indexOf(node);if(index===-1)
return null;if(index>=this.expandedChildrenLimit){this._expandedChildrenLimit=index+1;this._updateChildren(true);}
return this.children[index];}
toggleElementVisibility(forceHidden)
{let effectiveNode=this.representedObject;if(effectiveNode.isPseudoElement()){effectiveNode=effectiveNode.parentNode;if(!effectiveNode)
return;}
if(effectiveNode.nodeType()!==Node.ELEMENT_NODE)
return;function inspectedPage_node_injectStyleAndToggleClass(hiddenClassName,force){let root=this.getRootNode()||document;let styleElement=root.getElementById(hiddenClassName);if(!styleElement){styleElement=document.createElement("style");styleElement.id=hiddenClassName;styleElement.textContent=`.${hiddenClassName} { visibility: hidden !important; }`;if(root instanceof HTMLDocument)
root.head.appendChild(styleElement);else
root.insertBefore(styleElement,root.firstChild);}
this.classList.toggle(hiddenClassName,force);}
WI.RemoteObject.resolveNode(effectiveNode).then((object)=>{object.callFunction(inspectedPage_node_injectStyleAndToggleClass,[WI.DOMTreeElement.HideElementStyleSheetIdOrClassName,forceHidden],false);object.release();});}
_createTooltipForNode()
{var node=this.representedObject;if(!node.nodeName()||node.nodeName().toLowerCase()!=="img")
return;function setTooltip(error,result,wasThrown)
{if(error||wasThrown||!result||result.type!=="string")
return;try{var properties=JSON.parse(result.description);var offsetWidth=properties[0];var offsetHeight=properties[1];var naturalWidth=properties[2];var naturalHeight=properties[3];if(offsetHeight===naturalHeight&&offsetWidth===naturalWidth)
this.tooltip=WI.UIString("%d \xd7 %d pixels").format(offsetWidth,offsetHeight);else
this.tooltip=WI.UIString("%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)").format(offsetWidth,offsetHeight,naturalWidth,naturalHeight);}catch(e){console.error(e);}}
WI.RemoteObject.resolveNode(node).then((object)=>{function inspectedPage_node_dimensions(){return"["+this.offsetWidth+","+this.offsetHeight+","+this.naturalWidth+","+this.naturalHeight+"]";}
object.callFunction(inspectedPage_node_dimensions,undefined,false,setTooltip.bind(this));object.release();});}
updateSelectionArea()
{let listItemElement=this.listItemElement;if(!listItemElement)
return;let indicatesTreeOutlineState=this.treeOutline&&(this.treeOutline.dragOverTreeElement===this||this.selected||this._animatingHighlight);if(!this.hovered&&!indicatesTreeOutlineState){if(this._selectionElement){this._selectionElement.remove();this._selectionElement=null;}
return;}
if(!this._selectionElement){this._selectionElement=document.createElement("div");this._selectionElement.className="selection-area";listItemElement.insertBefore(this._selectionElement,listItemElement.firstChild);}
this._selectionElement.style.height=listItemElement.offsetHeight+"px";}
onattach()
{if(this.hovered)
this.listItemElement.classList.add("hovered");this.updateTitle();if(this.editable){this.listItemElement.draggable=true;this.listItemElement.addEventListener("dragstart",this);}
if(this.representedObject.layoutContextType===WI.DOMNode.LayoutContextType.Grid){WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._updateGridBadgeStatus,this);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._updateGridBadgeStatus,this);}
this.representedObject.addEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);this._updateGridBadge();}
ondetach()
{if(this.representedObject.layoutContextType===WI.DOMNode.LayoutContextType.Grid){WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayShown,this._updateGridBadgeStatus,this);WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._updateGridBadgeStatus,this);}
this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);}
onpopulate()
{if(this.children.length||!this._hasVisibleChildren()||this._elementCloseTag)
return;this.updateChildren();}
expandRecursively()
{this.representedObject.getSubtree(-1,super.expandRecursively.bind(this,Number.MAX_VALUE));}
updateChildren(fullRefresh)
{if(this._elementCloseTag)
return;this.representedObject.getChildNodes(this._updateChildren.bind(this,fullRefresh));}
insertChildElement(child,index,closingTag)
{var newElement=new WI.DOMTreeElement(child,closingTag);newElement.selectable=this.treeOutline.selectable;this.insertChild(newElement,index);return newElement;}
moveChild(child,targetIndex)
{if(this.children[targetIndex]===child)
return;var originalSelectedChild=this.treeOutline.selectedTreeElement;this.removeChild(child);this.insertChild(child,targetIndex);if(originalSelectedChild!==this.treeOutline.selectedTreeElement)
originalSelectedChild.select();}
_updateChildren(fullRefresh)
{if(this._updateChildrenInProgress||!this.treeOutline._visible)
return;this._closeTagTreeElement=null;this._updateChildrenInProgress=true;var node=this.representedObject;var selectedNode=this.treeOutline.selectedDOMNode();var originalScrollTop=0;var hasVisibleChildren=this._hasVisibleChildren();if(fullRefresh||!hasVisibleChildren){var treeOutlineContainerElement=this.treeOutline.element.parentNode;originalScrollTop=treeOutlineContainerElement.scrollTop;var selectedTreeElement=this.treeOutline.selectedTreeElement;if(selectedTreeElement&&selectedTreeElement.hasAncestor(this))
this.select();this.removeChildren();if(!hasVisibleChildren){this.hasChildren=false;this.updateTitle();this._updateChildrenInProgress=false;return;}}
if(!this.hasChildren){this.hasChildren=true;this.updateTitle();}
var existingChildTreeElements=new Map;for(var i=this.children.length-1;i>=0;--i){var currentChildTreeElement=this.children[i];var currentNode=currentChildTreeElement.representedObject;var currentParentNode=currentNode.parentNode;if(currentParentNode===node){existingChildTreeElements.set(currentNode,currentChildTreeElement);continue;}
this.removeChildAtIndex(i);}
var elementToSelect=null;var visibleChildren=this._visibleChildren();for(var i=0;i<visibleChildren.length&&i<this.expandedChildrenLimit;++i){var childNode=visibleChildren[i];var existingChildTreeElement=existingChildTreeElements.get(childNode);if(existingChildTreeElement){this.moveChild(existingChildTreeElement,i);continue;}
var newChildTreeElement=this.insertChildElement(childNode,i);if(childNode===selectedNode)
elementToSelect=newChildTreeElement;if(this.expandedChildCount>this.expandedChildrenLimit)
this.expandedChildrenLimit++;}
this.adjustCollapsedRange();var lastChild=this.children.lastValue;if(node.nodeType()===Node.ELEMENT_NODE&&(!lastChild||!lastChild._elementCloseTag))
this._closeTagTreeElement=this.insertChildElement(this.representedObject,this.children.length,true);if(fullRefresh&&elementToSelect){elementToSelect.select();if(treeOutlineContainerElement&&originalScrollTop<=treeOutlineContainerElement.scrollHeight)
treeOutlineContainerElement.scrollTop=originalScrollTop;}
this._updateChildrenInProgress=false;}
adjustCollapsedRange()
{
if(this.expandAllButtonElement&&this.expandAllButtonElement.__treeElement.parent)
this.removeChild(this.expandAllButtonElement.__treeElement);if(!this._hasVisibleChildren())
return;var visibleChildren=this._visibleChildren();var totalChildrenCount=visibleChildren.length;for(var i=this.expandedChildCount,limit=Math.min(this.expandedChildrenLimit,totalChildrenCount);i<limit;++i)
this.insertChildElement(visibleChildren[i],i);var expandedChildCount=this.expandedChildCount;if(totalChildrenCount>this.expandedChildCount){var targetButtonIndex=expandedChildCount;if(!this.expandAllButtonElement){var button=document.createElement("button");button.className="show-all-nodes";button.value="";var item=new WI.TreeElement(button,null,false);item.selectable=false;item.expandAllButton=true;this.insertChild(item,targetButtonIndex);this.expandAllButtonElement=button;this.expandAllButtonElement.__treeElement=item;this.expandAllButtonElement.addEventListener("click",this.handleLoadAllChildren.bind(this),false);}else if(!this.expandAllButtonElement.__treeElement.parent)
this.insertChild(this.expandAllButtonElement.__treeElement,targetButtonIndex);this.expandAllButtonElement.textContent=WI.UIString("Show All Nodes (%d More)").format(totalChildrenCount-expandedChildCount);}else if(this.expandAllButtonElement)
this.expandAllButtonElement=null;}
handleLoadAllChildren()
{var visibleChildren=this._visibleChildren();this.expandedChildrenLimit=Math.max(visibleChildren.length,this.expandedChildrenLimit+WI.DOMTreeElement.InitialChildrenLimit);}
onexpand()
{if(this._elementCloseTag)
return;if(!this.listItemElement)
return;this.updateTitle();for(let treeElement of this.children)
treeElement.updateSelectionArea();}
oncollapse()
{if(this._elementCloseTag)
return;this.updateTitle();}
onreveal()
{let listItemElement=this.listItemElement;if(!listItemElement)
return;let tagSpans=listItemElement.getElementsByClassName("html-tag-name");if(tagSpans.length)
tagSpans[0].scrollIntoViewIfNeeded(false);else
listItemElement.scrollIntoViewIfNeeded(false);if(!this._shouldHighlightAfterReveal)
return;this._shouldHighlightAfterReveal=false;this._animatingHighlight=true;this.updateSelectionArea();listItemElement.addEventListener("animationend",this._boundHighlightAnimationEnd);listItemElement.classList.add(WI.DOMTreeElement.HighlightStyleClassName);}
onenter()
{if(!this.editable)
return false;
if(this.treeOutline.editing)
return false;this._startEditing(); return true;}
canSelectOnMouseDown(event)
{if(this._editing)
return false;if(event.detail>=2){event.preventDefault();return false;}
return true;}
ondblclick(event)
{if(!this.editable)
return false;if(this._editing||this._elementCloseTag)
return;if(this._startEditingTarget(event.target))
return;if(this.hasChildren&&!this.expanded)
this.expand();}
_insertInLastAttributePosition(tag,node)
{if(tag.getElementsByClassName("html-attribute").length>0)
tag.insertBefore(node,tag.lastChild);else{let tagNameElement=tag.querySelector(".html-tag-name");tagNameElement.parentNode.insertBefore(node,tagNameElement.nextSibling);}
this.updateSelectionArea();}
_startEditingTarget(eventTarget)
{if(this.treeOutline.selectedDOMNode()!==this.representedObject)
return false;if(this.representedObject.isShadowRoot())
return false;if(this.representedObject.isInUserAgentShadowTree()&&!WI.DOMManager.supportsEditingUserAgentShadowTrees())
return false;if(this.representedObject.isPseudoElement())
return false;if(this.representedObject.nodeType()!==Node.ELEMENT_NODE&&this.representedObject.nodeType()!==Node.TEXT_NODE)
return false;var textNode=eventTarget.closest(".html-text-node");if(textNode)
return this._startEditingTextNode(textNode);var attribute=eventTarget.closest(".html-attribute");if(attribute)
return this._startEditingAttribute(attribute,eventTarget);var tagName=eventTarget.closest(".html-tag-name");if(tagName)
return this._startEditingTagName(tagName);return false;}
populateDOMNodeContextMenu(contextMenu,subMenus,event)
{let attributeNode=event.target.closest(".html-attribute");let textNode=event.target.closest(".html-text-node");let attributeName=null;if(attributeNode){let attributeNameElement=attributeNode.getElementsByClassName("html-attribute-name")[0];if(attributeNameElement)
attributeName=attributeNameElement.textContent.trim();}
if(event.target&&event.target.tagName==="A")
WI.appendContextMenuItemsForURL(contextMenu,event.target.href,{frame:this.representedObject.frame});contextMenu.appendSeparator();let isEditableNode=this.representedObject.nodeType()===Node.ELEMENT_NODE&&this.editable;let isNonShadowEditable=isEditableNode&&(!this.representedObject.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees());let alreadyEditingHTML=this._htmlEditElement&&WI.isBeingEdited(this._htmlEditElement);if(isEditableNode){if(!DOMTreeElement.ForbiddenClosingTagElements.has(this.representedObject.nodeNameInCorrectCase())){subMenus.add.appendItem(WI.UIString("Child","A submenu item of 'Add' to append DOM nodes to the selected DOM node"),()=>{this._addHTML();},alreadyEditingHTML);}
subMenus.add.appendItem(WI.UIString("Previous Sibling","A submenu item of 'Add' to add DOM nodes before the selected DOM node"),()=>{this._addPreviousSibling();},alreadyEditingHTML);subMenus.add.appendItem(WI.UIString("Next Sibling","A submenu item of 'Add' to add DOM nodes after the selected DOM node"),()=>{this._addNextSibling();},alreadyEditingHTML);}
if(isNonShadowEditable){subMenus.add.appendItem(WI.UIString("Attribute"),()=>{this._addNewAttribute();});}
if(this.editable){subMenus.edit.appendItem(WI.UIString("HTML"),()=>{this._editAsHTML();},alreadyEditingHTML);}
if(isNonShadowEditable){if(attributeName){subMenus.edit.appendItem(WI.UIString("Attribute"),()=>{this._startEditingAttribute(attributeNode,event.target);},WI.isBeingEdited(attributeNode));}
if(InspectorBackend.hasCommand("DOM.setNodeName")&&!DOMTreeElement.UneditableTagNames.has(this.representedObject.nodeNameInCorrectCase())){let tagNameNode=event.target.closest(".html-tag-name");subMenus.edit.appendItem(WI.UIString("Tag","A submenu item of 'Edit' to change DOM element's tag name"),()=>{this._startEditingTagName(tagNameNode);},WI.isBeingEdited(tagNameNode));}}
if(textNode&&this.editable){subMenus.edit.appendItem(WI.UIString("Text"),()=>{this._startEditingTextNode(textNode);},WI.isBeingEdited(textNode));}
if(!this.representedObject.destroyed&&!this.representedObject.isPseudoElement()){subMenus.copy.appendItem(WI.UIString("HTML"),()=>{this.representedObject.getOuterHTML().then((outerHTML)=>{InspectorFrontendHost.copyText(outerHTML);});});}
if(attributeName){subMenus.copy.appendItem(WI.UIString("Attribute"),()=>{let text=attributeName;let attributeValue=this.representedObject.getAttribute(attributeName);if(attributeValue)
text+="=\""+attributeValue.replace(/"/g,"\\\"")+"\"";InspectorFrontendHost.copyText(text);});}
if(textNode&&textNode.textContent.length){subMenus.copy.appendItem(WI.UIString("Text"),()=>{InspectorFrontendHost.copyText(textNode.textContent);});}
if(this.editable&&(!this.selected||this.treeOutline.selectedTreeElements.length===1)){subMenus.delete.appendItem(WI.UIString("Node"),()=>{this.remove();});}
if(attributeName&&isNonShadowEditable){subMenus.delete.appendItem(WI.UIString("Attribute"),()=>{this.representedObject.removeAttribute(attributeName);});}
for(let subMenu of Object.values(subMenus))
contextMenu.pushItem(subMenu);if(this.treeOutline.editable){if(this.selected&&this.treeOutline&&this.treeOutline.selectedTreeElements.length>1){let forceHidden=!this.treeOutline.selectedTreeElements.every((treeElement)=>treeElement.isNodeHidden);let label=forceHidden?WI.UIString("Hide Elements"):WI.UIString("Show Elements");contextMenu.appendItem(label,()=>{this.treeOutline.toggleSelectedElementsVisibility(forceHidden);});}else if(isEditableNode){contextMenu.appendItem(WI.UIString("Toggle Visibility"),()=>{this.toggleElementVisibility();});}}}
_startEditing()
{if(this.treeOutline.selectedDOMNode()!==this.representedObject)
return false;if(!this.editable)
return false;var listItem=this.listItemElement;if(this._canAddAttributes){var attribute=listItem.getElementsByClassName("html-attribute")[0];if(attribute)
return this._startEditingAttribute(attribute,attribute.getElementsByClassName("html-attribute-value")[0]);return this._addNewAttribute();}
if(this.representedObject.nodeType()===Node.TEXT_NODE){var textNode=listItem.getElementsByClassName("html-text-node")[0];if(textNode)
return this._startEditingTextNode(textNode);return false;}}
_addNewAttribute()
{
var container=document.createElement("span");this._buildAttributeDOM(container," ","");var attr=container.firstChild;attr.style.marginLeft="2px"; attr.style.marginRight="2px"; var tag=this.listItemElement.getElementsByClassName("html-tag")[0];this._insertInLastAttributePosition(tag,attr);return this._startEditingAttribute(attr,attr);}
_triggerEditAttribute(attributeName)
{var attributeElements=this.listItemElement.getElementsByClassName("html-attribute-name");for(var i=0,len=attributeElements.length;i<len;++i){if(attributeElements[i].textContent===attributeName){for(var elem=attributeElements[i].nextSibling;elem;elem=elem.nextSibling){if(elem.nodeType!==Node.ELEMENT_NODE)
continue;if(elem.classList.contains("html-attribute-value"))
return this._startEditingAttribute(elem.parentNode,elem);}}}}
_startEditingAttribute(attribute,elementForSelection)
{if(WI.isBeingEdited(attribute))
return true;var attributeNameElement=attribute.getElementsByClassName("html-attribute-name")[0];if(!attributeNameElement)
return false;var attributeName=attributeNameElement.textContent;function removeZeroWidthSpaceRecursive(node)
{if(node.nodeType===Node.TEXT_NODE){node.nodeValue=node.nodeValue.replace(/\u200B/g,"");return;}
if(node.nodeType!==Node.ELEMENT_NODE)
return;for(var child=node.firstChild;child;child=child.nextSibling)
removeZeroWidthSpaceRecursive(child);}
removeZeroWidthSpaceRecursive(attribute);var config=new WI.EditingConfig(this._attributeEditingCommitted.bind(this),this._editingCancelled.bind(this),attributeName);config.setNumberCommitHandler(this._attributeNumberEditingCommitted.bind(this));this._editing=WI.startEditing(attribute,config);window.getSelection().setBaseAndExtent(elementForSelection,0,elementForSelection,1);return true;}
_startEditingTextNode(textNode)
{if(WI.isBeingEdited(textNode))
return true;var config=new WI.EditingConfig(this._textNodeEditingCommitted.bind(this),this._editingCancelled.bind(this));config.spellcheck=true;this._editing=WI.startEditing(textNode,config);window.getSelection().setBaseAndExtent(textNode,0,textNode,1);return true;}
_startEditingTagName(tagNameElement)
{if(!InspectorBackend.hasCommand("DOM.setNodeName"))
return false;if(!tagNameElement){tagNameElement=this.listItemElement.getElementsByClassName("html-tag-name")[0];if(!tagNameElement)
return false;}
var tagName=tagNameElement.textContent;if(WI.DOMTreeElement.UneditableTagNames.has(tagName.toLowerCase()))
return false;if(WI.isBeingEdited(tagNameElement))
return true;let closingTagElement=this._distinctClosingTagElement();let originalClosingTagTextContent=closingTagElement?closingTagElement.textContent:"";function keyupListener(event)
{if(closingTagElement)
closingTagElement.textContent="</"+tagNameElement.textContent+">";}
function editingComitted(element,newTagName)
{tagNameElement.removeEventListener("keyup",keyupListener,false);this._tagNameEditingCommitted.apply(this,arguments);}
function editingCancelled()
{if(closingTagElement)
closingTagElement.textContent=originalClosingTagTextContent;tagNameElement.removeEventListener("keyup",keyupListener,false);this._editingCancelled.apply(this,arguments);}
tagNameElement.addEventListener("keyup",keyupListener,false);var config=new WI.EditingConfig(editingComitted.bind(this),editingCancelled.bind(this),tagName);this._editing=WI.startEditing(tagNameElement,config);window.getSelection().setBaseAndExtent(tagNameElement,0,tagNameElement,1);return true;}
_startEditingAsHTML(commitCallback,options={})
{if(this._htmlEditElement&&WI.isBeingEdited(this._htmlEditElement))
return;if(options.hideExistingElements){let child=this.listItemElement.firstChild;while(child){child.style.display="none";child=child.nextSibling;}
if(this._childrenListNode)
this._childrenListNode.style.display="none";}
let positionInside=options.position==="afterbegin"||options.position==="beforeend";if(positionInside&&this._childrenListNode){this._htmlEditElement=document.createElement("li");let referenceNode=options.position==="afterbegin"?this._childrenListNode.firstElementChild:this._childrenListNode.lastElementChild;this._childrenListNode.insertBefore(this._htmlEditElement,referenceNode);}else if(options.position&&!positionInside){this._htmlEditElement=document.createElement("li");let targetNode=(options.position==="afterend"&&this._childrenListNode)?this._childrenListNode:this.listItemElement;targetNode.insertAdjacentElement(options.position,this._htmlEditElement);}else{this._htmlEditElement=document.createElement("div");this.listItemElement.appendChild(this._htmlEditElement);}
if(options.initialValue)
this._htmlEditElement.textContent=options.initialValue;this.updateSelectionArea();function commit()
{commitCallback(this._htmlEditElement.textContent);dispose.call(this);}
function dispose()
{this._editing=false;this._htmlEditElement.remove();this._htmlEditElement=null;if(options.hideExistingElements){if(this._childrenListNode)
this._childrenListNode.style.removeProperty("display");let child=this.listItemElement.firstChild;while(child){child.style.removeProperty("display");child=child.nextSibling;}}
this.updateSelectionArea();}
var config=new WI.EditingConfig(commit.bind(this),dispose.bind(this));config.setMultiline(true);this._editing=WI.startEditing(this._htmlEditElement,config);if(options.initialValue&&!isNaN(options.startPosition)){let range=document.createRange();range.setStart(this._htmlEditElement.firstChild,options.startPosition);range.collapse(true);let selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);}}
_attributeEditingCommitted(element,newText,oldText,attributeName,moveDirection)
{this._editing=false;if(!newText.trim())
element.remove();if(!moveDirection&&newText===oldText)
return;const nbspRegex=/\xA0/g;newText=newText.replace(nbspRegex," ");var treeOutline=this.treeOutline;function moveToNextAttributeIfNeeded(error)
{if(error)
this._editingCancelled(element,attributeName);if(!moveDirection)
return;treeOutline._updateModifiedNodes();var attributes=this.representedObject.attributes();for(var i=0;i<attributes.length;++i){if(attributes[i].name!==attributeName)
continue;if(moveDirection==="backward"){if(i===0)
this._startEditingTagName();else
this._triggerEditAttribute(attributes[i-1].name);}else{if(i===attributes.length-1)
this._addNewAttribute();else
this._triggerEditAttribute(attributes[i+1].name);}
return;}
if(moveDirection==="backward"){if(newText===" "){ if(attributes.length)
this._triggerEditAttribute(attributes.lastValue.name);}else{ if(attributes.length>1)
this._triggerEditAttribute(attributes[attributes.length-2].name);}}else if(moveDirection==="forward"){if(!/^\s*$/.test(newText))
this._addNewAttribute();else
this._startEditingTagName();}}
this.representedObject.setAttribute(attributeName,newText,moveToNextAttributeIfNeeded.bind(this));}
_attributeNumberEditingCommitted(element,newText,oldText,attributeName,moveDirection)
{if(newText===oldText)
return;this.representedObject.setAttribute(attributeName,newText);}
_tagNameEditingCommitted(element,newText,oldText,tagName,moveDirection)
{this._editing=false;var self=this;function cancel()
{var closingTagElement=self._distinctClosingTagElement();if(closingTagElement)
closingTagElement.textContent="</"+tagName+">";self._editingCancelled(element,tagName);moveToNextAttributeIfNeeded.call(self);}
function moveToNextAttributeIfNeeded()
{if(moveDirection!=="forward"){this._addNewAttribute();return;}
var attributes=this.representedObject.attributes();if(attributes.length>0)
this._triggerEditAttribute(attributes[0].name);else
this._addNewAttribute();}
newText=newText.trim();if(newText===oldText){cancel();return;}
var treeOutline=this.treeOutline;var wasExpanded=this.expanded;function changeTagNameCallback(error,nodeId)
{if(error||!nodeId){cancel();return;}
var node=WI.domManager.nodeForId(nodeId);treeOutline._updateModifiedNodes();treeOutline.selectDOMNode(node,true);var newTreeItem=treeOutline.findTreeElement(node);if(wasExpanded)
newTreeItem.expand();moveToNextAttributeIfNeeded.call(newTreeItem);}
this.representedObject.setNodeName(newText,changeTagNameCallback);}
_textNodeEditingCommitted(element,newText)
{this._editing=false;var textNode;if(this.representedObject.nodeType()===Node.ELEMENT_NODE){
textNode=this.representedObject.firstChild;}else if(this.representedObject.nodeType()===Node.TEXT_NODE)
textNode=this.representedObject;textNode.setNodeValue(newText,this.updateTitle.bind(this));}
_editingCancelled(element,context)
{this._editing=false;this.updateTitle();}
_distinctClosingTagElement()
{
if(this.expanded){var closers=this._childrenListNode.querySelectorAll(".close");return closers[closers.length-1];}


var tags=this.listItemElement.getElementsByClassName("html-tag");return tags.length===1?null:tags[tags.length-1];}
updateTitle(onlySearchQueryChanged)
{if(this._editing&&!this._forceUpdateTitle)
return;if(onlySearchQueryChanged){if(this._highlightResult)
this._updateSearchHighlight(false);}else{this.title=document.createElement("span");this.title.appendChild(this._nodeTitleInfo().titleDOM);this._highlightResult=undefined;}
this._updateGridBadge();
this._selectionElement=null;this.updateSelectionArea();this._highlightSearchResults();this._updatePseudoClassIndicator();this._updateBreakpointStatus();}
_buildAttributeDOM(parentElement,name,value,node)
{let hasText=value.length>0;let attrSpanElement=parentElement.createChild("span","html-attribute");let attrNameElement=attrSpanElement.createChild("span","html-attribute-name");attrNameElement.textContent=name;let attrValueElement=null;if(hasText)
attrSpanElement.append("=\u200B\"");if(name==="src"||/\bhref\b/.test(name)){let baseURL=node.frame?node.frame.url:null;let rewrittenURL=absoluteURL(value,baseURL);value=value.insertWordBreakCharacters();if(!rewrittenURL){attrValueElement=attrSpanElement.createChild("span","html-attribute-value");attrValueElement.textContent=value;}else{if(value.startsWith("data:"))
value=value.truncateMiddle(60);attrValueElement=document.createElement("a");attrValueElement.href=rewrittenURL;attrValueElement.textContent=value;attrSpanElement.appendChild(attrValueElement);}}else if(name==="srcset"){let baseURL=node.frame?node.frame.url:null;attrValueElement=attrSpanElement.createChild("span","html-attribute-value");let groups=value.split(/\s*,\s*/);for(let i=0;i<groups.length;++i){let string=groups[i].trim();let spaceIndex=string.search(/\s/);if(spaceIndex===-1){let linkText=string;let rewrittenURL=absoluteURL(string,baseURL);let linkElement=attrValueElement.appendChild(document.createElement("a"));linkElement.href=rewrittenURL;linkElement.textContent=linkText.insertWordBreakCharacters();}else{let linkText=string.substring(0,spaceIndex);let descriptorText=string.substring(spaceIndex).insertWordBreakCharacters();let rewrittenURL=absoluteURL(linkText,baseURL);let linkElement=attrValueElement.appendChild(document.createElement("a"));linkElement.href=rewrittenURL;linkElement.textContent=linkText.insertWordBreakCharacters();let descriptorElement=attrValueElement.appendChild(document.createElement("span"));descriptorElement.textContent=descriptorText;}
if(i<groups.length-1){let commaElement=attrValueElement.appendChild(document.createElement("span"));commaElement.textContent=", ";}}}else{value=value.insertWordBreakCharacters();attrValueElement=attrSpanElement.createChild("span","html-attribute-value");attrValueElement.textContent=value;}
if(hasText)
attrSpanElement.append("\"");this._createModifiedAnimation(name,value,hasText?attrValueElement:attrNameElement);if(this._highlightedAttributes.has(name))
attrSpanElement.classList.add("highlight");}
_buildTagDOM({parentElement,tagName,isClosingTag,isDistinctTreeElement,willRenderCloseTagInline})
{var node=this.representedObject;var classes=["html-tag"];if(isClosingTag&&isDistinctTreeElement)
classes.push("close");var tagElement=parentElement.createChild("span",classes.join(" "));tagElement.append("<");var tagNameElement=tagElement.createChild("span",isClosingTag?"":"html-tag-name");tagNameElement.textContent=(isClosingTag?"/":"")+tagName;if(!isClosingTag&&node.hasAttributes()){var attributes=node.attributes();for(var i=0;i<attributes.length;++i){var attr=attributes[i];tagElement.append(" ");this._buildAttributeDOM(tagElement,attr.name,attr.value,node);}}
tagElement.append(">");parentElement.append("\u200B");if(this._showGoToArrow&&node.nodeType()===Node.ELEMENT_NODE&&willRenderCloseTagInline===isClosingTag){let goToArrowElement=parentElement.appendChild(WI.createGoToArrowButton());goToArrowElement.title=WI.UIString("Reveal in Elements Tab");goToArrowElement.addEventListener("click",(event)=>{WI.domManager.inspectElement(this.representedObject.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});}}
_nodeTitleInfo()
{var node=this.representedObject;var info={titleDOM:document.createDocumentFragment(),hasChildren:this.hasChildren};function trimedNodeValue()
{
return node.nodeValue().replace(/^[\n\r]*/,"").replace(/\s*$/,"");}
switch(node.nodeType()){case Node.DOCUMENT_FRAGMENT_NODE:var fragmentElement=info.titleDOM.createChild("span","html-fragment");if(node.shadowRootType()){fragmentElement.textContent=WI.UIString("Shadow Content (%s)").format(WI.DOMTreeElement.shadowRootTypeDisplayName(node.shadowRootType()));this.listItemElement.classList.add("shadow");}else if(node.parentNode&&node.parentNode.templateContent()===node){fragmentElement.textContent=WI.UIString("Template Content");this.listItemElement.classList.add("template");}else{fragmentElement.textContent=WI.UIString("Document Fragment");this.listItemElement.classList.add("fragment");}
break;case Node.ATTRIBUTE_NODE:var value=node.value||"\u200B";this._buildAttributeDOM(info.titleDOM,node.name,value);break;case Node.ELEMENT_NODE:if(node.isPseudoElement()){var pseudoElement=info.titleDOM.createChild("span","html-pseudo-element");pseudoElement.textContent="::"+node.pseudoType();info.titleDOM.appendChild(document.createTextNode("\u200B"));info.hasChildren=false;break;}
var tagName=node.nodeNameInCorrectCase();if(this._elementCloseTag){this._buildTagDOM({parentElement:info.titleDOM,tagName,isClosingTag:true,isDistinctTreeElement:true,willRenderCloseTagInline:false,});info.hasChildren=false;break;}
var textChild=this._singleTextChild(node);var showInlineText=textChild&&textChild.nodeValue().length<WI.DOMTreeElement.MaximumInlineTextChildLength;var showInlineEllipsis=!this.expanded&&!showInlineText&&(this.treeOutline.isXMLMimeType||!WI.DOMTreeElement.ForbiddenClosingTagElements.has(tagName));this._buildTagDOM({parentElement:info.titleDOM,tagName,isClosingTag:false,isDistinctTreeElement:false,willRenderCloseTagInline:showInlineText||showInlineEllipsis,});if(showInlineEllipsis){if(this.hasChildren){var textNodeElement=info.titleDOM.createChild("span","html-text-node");textNodeElement.textContent=ellipsis;info.titleDOM.append("\u200B");}
this._buildTagDOM({parentElement:info.titleDOM,tagName,isClosingTag:true,isDistinctTreeElement:false,willRenderCloseTagInline:true,});}
 
if(showInlineText){var textNodeElement=info.titleDOM.createChild("span","html-text-node");var nodeNameLowerCase=node.nodeName().toLowerCase();if(nodeNameLowerCase==="script")
textNodeElement.appendChild(WI.syntaxHighlightStringAsDocumentFragment(textChild.nodeValue().trim(),"text/javascript"));else if(nodeNameLowerCase==="style")
textNodeElement.appendChild(WI.syntaxHighlightStringAsDocumentFragment(textChild.nodeValue().trim(),"text/css"));else
textNodeElement.textContent=textChild.nodeValue();info.titleDOM.append("\u200B");this._buildTagDOM({parentElement:info.titleDOM,tagName,isClosingTag:true,isDistinctTreeElement:false,willRenderCloseTagInline:true,});info.hasChildren=false;}
break;case Node.TEXT_NODE:if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==="script"){var newNode=info.titleDOM.createChild("span","html-text-node large");newNode.appendChild(WI.syntaxHighlightStringAsDocumentFragment(trimedNodeValue(),"text/javascript"));}else if(node.parentNode&&node.parentNode.nodeName().toLowerCase()==="style"){var newNode=info.titleDOM.createChild("span","html-text-node large");newNode.appendChild(WI.syntaxHighlightStringAsDocumentFragment(trimedNodeValue(),"text/css"));}else{info.titleDOM.append("\"");var textNodeElement=info.titleDOM.createChild("span","html-text-node");textNodeElement.textContent=node.nodeValue();info.titleDOM.append("\"");}
break;case Node.COMMENT_NODE:var commentElement=info.titleDOM.createChild("span","html-comment");commentElement.append("<!--"+node.nodeValue()+"-->");break;case Node.DOCUMENT_TYPE_NODE:var docTypeElement=info.titleDOM.createChild("span","html-doctype");docTypeElement.append("<!DOCTYPE "+node.nodeName());if(node.publicId){docTypeElement.append(" PUBLIC \""+node.publicId+"\"");if(node.systemId)
docTypeElement.append(" \""+node.systemId+"\"");}else if(node.systemId)
docTypeElement.append(" SYSTEM \""+node.systemId+"\"");docTypeElement.append(">");break;case Node.CDATA_SECTION_NODE:var cdataElement=info.titleDOM.createChild("span","html-text-node");cdataElement.append("<![CDATA["+node.nodeValue()+"]]>");break;case Node.PROCESSING_INSTRUCTION_NODE:var processingInstructionElement=info.titleDOM.createChild("span","html-processing-instruction");var data=node.nodeValue();var dataString=data.length?" "+data:"";var title="<?"+node.nodeNameInCorrectCase()+dataString+"?>";processingInstructionElement.append(title);break;default:info.titleDOM.append(node.nodeNameInCorrectCase().collapseWhitespace());}
return info;}
_singleTextChild(node)
{if(!node||this._ignoreSingleTextChild)
return null;var firstChild=node.firstChild;if(!firstChild||firstChild.nodeType()!==Node.TEXT_NODE)
return null;if(node.hasShadowRoots())
return null;if(node.templateContent())
return null;if(node.hasPseudoElements())
return null;var sibling=firstChild.nextSibling;return sibling?null:firstChild;}
_showInlineText(node)
{if(node.nodeType()===Node.ELEMENT_NODE){var textChild=this._singleTextChild(node);if(textChild&&textChild.nodeValue().length<WI.DOMTreeElement.MaximumInlineTextChildLength)
return true;}
return false;}
_hasVisibleChildren()
{var node=this.representedObject;if(this._showInlineText(node))
return false;if(node.hasChildNodes())
return true;if(node.templateContent())
return true;if(node.hasPseudoElements())
return true;return false;}
_visibleChildren()
{var node=this.representedObject;var visibleChildren=[];var templateContent=node.templateContent();if(templateContent)
visibleChildren.push(templateContent);var beforePseudoElement=node.beforePseudoElement();if(beforePseudoElement)
visibleChildren.push(beforePseudoElement);if(node.childNodeCount&&node.children)
visibleChildren.pushAll(node.children);var afterPseudoElement=node.afterPseudoElement();if(afterPseudoElement)
visibleChildren.push(afterPseudoElement);return visibleChildren;}
remove()
{var parentElement=this.parent;if(!parentElement)
return;var self=this;function removeNodeCallback(error,removedNodeId)
{if(error)
return;if(!self.parent)
return;parentElement.removeChild(self);parentElement.adjustCollapsedRange();}
this.representedObject.removeNode(removeNodeCallback);}
_insertAdjacentHTML(position,options={})
{let hasChildren=this.hasChildren;let commitCallback=(value)=>{this._ignoreSingleTextChild=false;if(!value.length){if(!hasChildren){this._forceUpdateTitle=true;this.hasChildren=false;this._forceUpdateTitle=false;}
return;}
this.representedObject.insertAdjacentHTML(position,value);};if(position==="afterbegin"||position==="beforeend"){this._ignoreSingleTextChild=true;this.hasChildren=true;this.expand();}
this._startEditingAsHTML(commitCallback,{...options,position});}
_addHTML(event)
{let options={};switch(this.representedObject.nodeNameInCorrectCase()){case"ul":case"ol":options.initialValue="<li></li>";options.startPosition=4;break;case"table":case"thead":case"tbody":case"tfoot":options.initialValue="<tr></tr>";options.startPosition=4;break;case"tr":options.initializing="<td></td>";options.startPosition=4;break;}
this._insertAdjacentHTML("beforeend",options);}
_addPreviousSibling(event)
{let options={};let nodeName=this.representedObject.nodeNameInCorrectCase();if(nodeName==="li"||nodeName==="tr"||nodeName==="th"||nodeName==="td"){options.initialValue=`<${nodeName}></${nodeName}>`;options.startPosition=nodeName.length+2;}
this._insertAdjacentHTML("beforebegin",options);}
_addNextSibling(event)
{let options={};let nodeName=this.representedObject.nodeNameInCorrectCase();if(nodeName==="li"||nodeName==="tr"||nodeName==="th"||nodeName==="td"){options.initialValue=`<${nodeName}></${nodeName}>`;options.startPosition=nodeName.length+2;}
this._insertAdjacentHTML("afterend",options);}
_editAsHTML()
{var treeOutline=this.treeOutline;var node=this.representedObject;var parentNode=node.parentNode;var index=node.index;var wasExpanded=this.expanded;function selectNode(error,nodeId)
{if(error)
return;treeOutline._updateModifiedNodes();var newNode=parentNode?parentNode.children[index]||parentNode:null;if(!newNode)
return;treeOutline.selectDOMNode(newNode,true);if(wasExpanded){var newTreeItem=treeOutline.findTreeElement(newNode);if(newTreeItem)
newTreeItem.expand();}}
function commitChange(value)
{node.setOuterHTML(value,selectNode);}
node.getOuterHTML((error,initialValue)=>{if(error)
return;this._startEditingAsHTML(commitChange,{initialValue,hideExistingElements:true,});});}
_highlightSearchResults()
{if(!this.title||!this._searchQuery||!this._searchHighlightsVisible)
return;if(this._highlightResult){this._updateSearchHighlight(true);return;}
let searchRegex=WI.SearchUtilities.searchRegExpForString(this._searchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this.hideSearchHighlights();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;}
var text=this.title.textContent;var match=searchRegex.exec(text);var matchRanges=[];while(match){matchRanges.push({offset:match.index,length:match[0].length});match=searchRegex.exec(text);}
if(!matchRanges.length)
matchRanges.push({offset:0,length:text.length});this._highlightResult=[];WI.highlightRangesWithStyleClass(this.title,matchRanges,WI.DOMTreeElement.SearchHighlightStyleClassName,this._highlightResult);}
_createModifiedAnimation(key,value,element)
{let existing=this._recentlyModifiedAttributes.get(key);if(!existing)
return;if(existing.element){if(existing.listener)
existing.element.removeEventListener("animationend",existing.listener);existing.element.classList.remove("node-state-changed");existing.element.style.removeProperty("animation-delay");}
existing.listener=(event)=>{element.classList.remove("node-state-changed");element.style.removeProperty("animation-delay");this._recentlyModifiedAttributes.delete(key);};element.classList.remove("node-state-changed");element.style.removeProperty("animation-delay");if(existing.value===value)
element.style.setProperty("animation-delay","-"+(performance.now()-existing.timestamp)+"ms");else
existing.timestamp=performance.now();existing.value=value;existing.element=element;element.addEventListener("animationend",existing.listener,{once:true});element.classList.add("node-state-changed");}
get isNodeHidden()
{let classes=this.representedObject.getAttribute("class");return classes&&classes.includes(WI.DOMTreeElement.HideElementStyleSheetIdOrClassName);}
_updatePseudoClassIndicator()
{if(!this.listItemElement||this._elementCloseTag)
return;if(this.representedObject.enabledPseudoClasses.length){if(!this._pseudoClassIndicatorElement){this._pseudoClassIndicatorElement=document.createElement("div");this._pseudoClassIndicatorElement.classList.add("pseudo-class-indicator");}
this.listItemElement.insertBefore(this._pseudoClassIndicatorElement,this.listItemElement.firstChild);}else{if(this._pseudoClassIndicatorElement){this._pseudoClassIndicatorElement.remove();this._pseudoClassIndicatorElement=null;}}}
handleEvent(event)
{if(event.type==="dragstart"&&this._editing)
event.preventDefault();}
_subtreeBreakpointChanged(treeElement)
{if(treeElement.hasBreakpoint){if(!this._subtreeBreakpointTreeElements)
this._subtreeBreakpointTreeElements=new Set;this._subtreeBreakpointTreeElements.add(treeElement);}else{this._subtreeBreakpointTreeElements.delete(treeElement);if(!this._subtreeBreakpointTreeElements.size)
this._subtreeBreakpointTreeElements=null;}
this._updateBreakpointStatus();}
_updateBreakpointStatus()
{let listItemElement=this.listItemElement;if(!listItemElement)
return;let hasBreakpoint=this._breakpointStatus!==WI.DOMTreeElement.BreakpointStatus.None;let hasSubtreeBreakpoints=this._subtreeBreakpointTreeElements&&this._subtreeBreakpointTreeElements.size;if(!hasBreakpoint&&!hasSubtreeBreakpoints){if(this._statusImageElement)
this._statusImageElement.remove();return;}
if(!this._statusImageElement){this._statusImageElement=WI.ImageUtilities.useSVGSymbol("Images/DOMBreakpoint.svg","status-image");this._statusImageElement.classList.add("breakpoint");this._statusImageElement.addEventListener("click",this._statusImageClicked.bind(this));this._statusImageElement.addEventListener("contextmenu",this._statusImageContextmenu.bind(this));this._statusImageElement.addEventListener("mousedown",(event)=>{event.stopPropagation();});}
this._statusImageElement.classList.toggle("subtree",!hasBreakpoint&&hasSubtreeBreakpoints);this.listItemElement.insertBefore(this._statusImageElement,this.listItemElement.firstChild);let disabled=this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.DisabledBreakpoint;this._statusImageElement.classList.toggle("disabled",disabled);}
_statusImageClicked(event)
{if(this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.None)
return;if(event.button!==0||event.ctrlKey)
return;let breakpoints=WI.domDebuggerManager.domBreakpointsForNode(this.representedObject);if(!breakpoints||!breakpoints.length)
return;let shouldEnable=breakpoints.some((breakpoint)=>breakpoint.disabled);breakpoints.forEach((breakpoint)=>{breakpoint.disabled=!shouldEnable});}
_statusImageContextmenu(event)
{if(!this.hasBreakpoint)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,this.representedObject,{popoverTargetElement:event.target,revealDescendantBreakpointsMenuItemHandler:this.bindRevealDescendantBreakpointsMenuItemHandler(),});}
_highlightAnimationEnd()
{let listItemElement=this.listItemElement;if(!listItemElement)
return;listItemElement.removeEventListener("animationend",this._boundHighlightAnimationEnd);listItemElement.classList.remove(WI.DOMTreeElement.HighlightStyleClassName);this._animatingHighlight=false;}
_updateGridBadge()
{if(!this.listItemElement||this._elementCloseTag)
return;if(this._gridBadgeElement){this._gridBadgeElement.remove();this._gridBadgeElement=null;}
if(this.representedObject.layoutContextType!==WI.DOMNode.LayoutContextType.Grid)
return;this._gridBadgeElement=document.createElement("span");this._gridBadgeElement.className="badge-css-grid";this._gridBadgeElement.textContent=WI.unlocalizedString("grid");this._updateGridBadgeStatus();this.title.append(this._gridBadgeElement);this._gridBadgeElement.addEventListener("click",this._gridBadgeClicked.bind(this),true);this._gridBadgeElement.addEventListener("dblclick",this._gridBadgeDoubleClicked,true);}
_gridBadgeClicked(event)
{if(event.button!==0||event.ctrlKey)
return;event.stop();WI.overlayManager.toggleGridOverlay(this.representedObject,{initiator:WI.GridOverlayDiagnosticEventRecorder.Initiator.Badge});}
_gridBadgeDoubleClicked(event)
{event.stop();}
_updateGridBadgeStatus()
{if(!this._gridBadgeElement)
return;let isGridVisible=WI.overlayManager.isGridOverlayVisible(this.representedObject);this._gridBadgeElement.classList.toggle("activated",isGridVisible);if(isGridVisible){let color=WI.overlayManager.getGridColorForNode(this.representedObject);let hue=color.hsl[0];this._gridBadgeElement.style.borderColor=color.toString();this._gridBadgeElement.style.backgroundColor=`hsl(${hue}, 90%, 95%)`;this._gridBadgeElement.style.setProperty("color",`hsl(${hue}, 55%, 40%)`);}else
this._gridBadgeElement.removeAttribute("style");}
_handleLayoutContextTypeChanged(event)
{let domNode=event.target;if(domNode.layoutContextType===WI.DOMNode.LayoutContextType.Grid){WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._updateGridBadgeStatus,this);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._updateGridBadgeStatus,this);}else{WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayShown,this._updateGridBadgeStatus,this);WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._updateGridBadgeStatus,this);}
this._updateGridBadge();}};WI.DOMTreeElement.InitialChildrenLimit=500;WI.DOMTreeElement.MaximumInlineTextChildLength=80;
WI.DOMTreeElement.ForbiddenClosingTagElements=new Set(["area","base","basefont","br","canvas","col","command","embed","frame","hr","img","input","keygen","link","meta","param","source","wbr","track","menuitem"]);WI.DOMTreeElement.UneditableTagNames=new Set(["html","head","body"]);WI.DOMTreeElement.BreakpointStatus={None:Symbol("none"),Breakpoint:Symbol("breakpoint"),DisabledBreakpoint:Symbol("disabled-breakpoint"),};WI.DOMTreeElement.HighlightStyleClassName="highlight";WI.DOMTreeElement.SearchHighlightStyleClassName="search-highlight";WI.DOMTreeElement.BouncyHighlightStyleClassName="bouncy-highlight";WI.DOMTreeElement.HideElementStyleSheetIdOrClassName="__WebInspectorHideElement__";WI.DOMTreeElementPathComponent=class DOMTreeElementPathComponent extends WI.HierarchicalPathComponent
{constructor(domTreeElement,representedObject)
{var node=domTreeElement.representedObject;var title=null;switch(node.nodeType()){case Node.ELEMENT_NODE:if(node.isPseudoElement()){title="::"+node.pseudoType();}else{title=node.displayName;}
break;case Node.TEXT_NODE:title="\""+node.nodeValue().truncateEnd(32)+"\"";break;case Node.COMMENT_NODE:title="<!--"+node.nodeValue().truncateEnd(32)+"-->";break;case Node.DOCUMENT_TYPE_NODE:title="<!DOCTYPE>";break;case Node.DOCUMENT_NODE:title=node.nodeNameInCorrectCase();break;case Node.CDATA_SECTION_NODE:title="<![CDATA["+node.truncateEnd(32)+"]]>";break;case Node.DOCUMENT_FRAGMENT_NODE: if(node.shadowRootType())
title=WI.UIString("Shadow Content");else
title=node.displayName;break;case Node.PROCESSING_INSTRUCTION_NODE:title=node.nodeNameInCorrectCase();break;default:console.error("Unknown DOM node type: ",node.nodeType());title=node.nodeNameInCorrectCase();}
super(title,DOMTreeElementPathComponent.iconClassNameForNode(node),representedObject||domTreeElement.representedObject);this._domTreeElement=domTreeElement;}
static iconClassNameForNode(domNode)
{switch(domNode.nodeType()){case Node.ELEMENT_NODE:if(domNode.isPseudoElement())
return WI.DOMTreeElementPathComponent.DOMPseudoElementIconStyleClassName;return WI.DOMTreeElementPathComponent.DOMElementIconStyleClassName;case Node.TEXT_NODE:return WI.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName;case Node.COMMENT_NODE:return WI.DOMTreeElementPathComponent.DOMCommentIconStyleClassName;case Node.DOCUMENT_TYPE_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;case Node.DOCUMENT_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName;case Node.CDATA_SECTION_NODE:return WI.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName;case Node.DOCUMENT_FRAGMENT_NODE: return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;case Node.PROCESSING_INSTRUCTION_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;}
console.error("Unknown DOM node type: ",domNode.nodeType());return WI.DOMTreeElementPathComponent.DOMNodeIconStyleClassName;} 
get domTreeElement()
{return this._domTreeElement;}
get previousSibling()
{if(!this._domTreeElement.previousSibling)
return null;return new WI.DOMTreeElementPathComponent(this._domTreeElement.previousSibling);}
get nextSibling()
{if(!this._domTreeElement.nextSibling)
return null;if(this._domTreeElement.nextSibling.isCloseTag())
return null;return new WI.DOMTreeElementPathComponent(this._domTreeElement.nextSibling);} 
mouseOver()
{let node=this._domTreeElement.representedObject;node.highlight();}
mouseOut()
{WI.domManager.hideDOMNodeHighlight();}};WI.DOMTreeElementPathComponent.DOMElementIconStyleClassName="dom-element-icon";WI.DOMTreeElementPathComponent.DOMPseudoElementIconStyleClassName="dom-pseudo-element-icon";WI.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName="dom-text-node-icon";WI.DOMTreeElementPathComponent.DOMCommentIconStyleClassName="dom-comment-icon";WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName="dom-document-type-icon";WI.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName="dom-document-icon";WI.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName="dom-character-data-icon";WI.DOMTreeElementPathComponent.DOMNodeIconStyleClassName="dom-node-icon";WI.DOMTreeOutline=class DOMTreeOutline extends WI.TreeOutline
{constructor({selectable,omitRootDOMNode,excludeRevealElementContextMenu,showInspectedNode}={})
{super(selectable);this.element.addEventListener("mousedown",this._onmousedown.bind(this),false);this.element.addEventListener("mousemove",this._onmousemove.bind(this),false);this.element.addEventListener("mouseout",this._onmouseout.bind(this),false);this.element.addEventListener("dragstart",this._ondragstart.bind(this),false);this.element.addEventListener("dragover",this._ondragover.bind(this),false);this.element.addEventListener("dragleave",this._ondragleave.bind(this),false);this.element.addEventListener("drop",this._ondrop.bind(this),false);this.element.addEventListener("dragend",this._ondragend.bind(this),false);this.element.classList.add("dom",WI.SyntaxHighlightedStyleClassName);this.element.dir="ltr";this.element.role="tree";this._includeRootDOMNode=!omitRootDOMNode;this._excludeRevealElementContextMenu=excludeRevealElementContextMenu;this._rootDOMNode=null;this._selectedDOMNode=null;this._treeElementsToRemove=null;this._editable=false;this._editing=false;this._visible=false;this._usingLocalDOMNode=false;this._hideElementsKeyboardShortcut=new WI.KeyboardShortcut(null,"H",this._hideElements.bind(this),this.element);this._hideElementsKeyboardShortcut.implicitlyPreventsDefault=false;if(showInspectedNode)
WI.domManager.addEventListener(WI.DOMManager.Event.InspectedNodeChanged,this._handleInspectedNodeChanged,this);} 
wireToDomAgent()
{this._elementsTreeUpdater=new WI.DOMTreeUpdater(this);}
close()
{if(this._elementsTreeUpdater){this._elementsTreeUpdater.close();this._elementsTreeUpdater=null;}}
setVisible(visible,omitFocus)
{this._visible=visible;if(!this._visible)
return;this._updateModifiedNodes();if(this._selectedDOMNode)
this._revealAndSelectNode(this._selectedDOMNode,omitFocus);this.update();}
get rootDOMNode()
{return this._rootDOMNode;}
set rootDOMNode(x)
{if(this._rootDOMNode===x)
return;this._rootDOMNode=x;this._isXMLMimeType=x&&x.isXMLNode();this.update();}
get isXMLMimeType()
{return this._isXMLMimeType;}
markAsUsingLocalDOMNode()
{this._editable=false;this._usingLocalDOMNode=true;}
selectedDOMNode()
{return this._selectedDOMNode;}
selectDOMNode(node,focus)
{if(this._selectedDOMNode===node){this._revealAndSelectNode(node,!focus);return;}
this._selectedDOMNode=node;this._revealAndSelectNode(node,!focus);

if(!node||this._selectedDOMNode===node)
this._selectedNodeChanged();}
get editable()
{return this._editable&&this.rootDOMNode&&!this.rootDOMNode.destroyed;}
set editable(x)
{this._editable=x;}
get editing()
{return this._editing;}
update()
{if(!this.rootDOMNode)
return;let selectedTreeElements=this.selectedTreeElements;this.removeChildren();var treeElement;if(this._includeRootDOMNode){treeElement=new WI.DOMTreeElement(this.rootDOMNode);treeElement.selectable=this.selectable;this.appendChild(treeElement);}else{ var node=this.rootDOMNode.firstChild;while(node){treeElement=new WI.DOMTreeElement(node);treeElement.selectable=this.selectable;this.appendChild(treeElement);node=node.nextSibling;if(treeElement.hasChildren&&!treeElement.expanded)
treeElement.expand();}}
if(!selectedTreeElements.length)
return;
selectedTreeElements=selectedTreeElements.map((oldTreeElement)=>{let treeElement=this.findTreeElement(oldTreeElement.representedObject);if(treeElement&&oldTreeElement.isCloseTag()){if(treeElement.closeTagTreeElement)
treeElement=treeElement.closeTagTreeElement;}
return treeElement;});selectedTreeElements=selectedTreeElements.filter((x)=>!!x);if(!selectedTreeElements.length)
return;this.selectTreeElements(selectedTreeElements);if(this.selectedTreeElement)
this.selectedTreeElement.reveal();}
updateSelectionArea()
{

let selectedTreeElements=this.selectedTreeElements;for(let treeElement of selectedTreeElements)
treeElement.updateSelectionArea();}
toggleSelectedElementsVisibility(forceHidden)
{for(let treeElement of this.selectedTreeElements)
treeElement.toggleElementVisibility(forceHidden);}
_selectedNodeChanged()
{this.dispatchEventToListeners(WI.DOMTreeOutline.Event.SelectedNodeChanged);}
findTreeElement(node)
{let isAncestorNode=(ancestor,node)=>ancestor.isAncestor(node);let parentNode=(node)=>node.parentNode;let treeElement=super.findTreeElement(node,isAncestorNode,parentNode);if(!treeElement&&node.nodeType()===Node.TEXT_NODE){treeElement=super.findTreeElement(node.parentNode,isAncestorNode,parentNode);}
return treeElement;}
createTreeElementFor(node)
{var treeElement=this.findTreeElement(node);if(treeElement)
return treeElement;if(!node.parentNode)
return null;treeElement=this.createTreeElementFor(node.parentNode);if(!treeElement)
return null;return treeElement.showChildNode(node);}
set suppressRevealAndSelect(x)
{if(this._suppressRevealAndSelect===x)
return;this._suppressRevealAndSelect=x;}
populateContextMenu(contextMenu,event,treeElement)
{let subMenus={add:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Add")),edit:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Edit")),copy:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Copy")),delete:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Delete")),};if(this.editable&&treeElement.selected&&this.selectedTreeElements.length>1){subMenus.delete.appendItem(WI.UIString("Nodes"),()=>{this.ondelete();});}
if(treeElement.populateDOMNodeContextMenu)
treeElement.populateDOMNodeContextMenu(contextMenu,subMenus,event,subMenus);let options={disallowEditing:!this.editable,usingLocalDOMNode:this._usingLocalDOMNode,excludeRevealElement:this._excludeRevealElementContextMenu,copySubMenu:subMenus.copy,popoverTargetElement:treeElement.statusImageElement,};if(treeElement.bindRevealDescendantBreakpointsMenuItemHandler)
options.revealDescendantBreakpointsMenuItemHandler=treeElement.bindRevealDescendantBreakpointsMenuItemHandler();WI.appendContextMenuItemsForDOMNode(contextMenu,treeElement.representedObject,options);super.populateContextMenu(contextMenu,event,treeElement);}
adjustCollapsedRange()
{}
ondelete()
{if(!this.editable)
return false;this._treeElementsToRemove=this.selectedTreeElements;
for(let treeElement of this._treeElementsToRemove)
treeElement.reveal();this._selectionController.removeSelectedItems();let levelMap=new Map;function getLevel(treeElement){let level=levelMap.get(treeElement);if(isNaN(level)){level=0;let current=treeElement;while(current=current.parent)
level++;levelMap.set(treeElement,level);}
return level;}

this._treeElementsToRemove.sort((a,b)=>getLevel(b)-getLevel(a));
let removedDOMNodes=new Set;for(let treeElement of this._treeElementsToRemove){if(removedDOMNodes.has(treeElement.representedObject))
continue;removedDOMNodes.add(treeElement.representedObject);treeElement.remove();}
this._treeElementsToRemove=null;if(this.selectedTreeElement&&!this.selectedTreeElement.isCloseTag()){this.selectedTreeElement.reveal();}
return true;} 
selectionControllerPreviousSelectableItem(controller,item)
{let treeElement=this.getCachedTreeElement(item);if(!treeElement)
return null;if(this._treeElementsToRemove){
if(!treeElement.previousSelectableSibling&&treeElement.nextSelectableSibling)
return null;}
return super.selectionControllerPreviousSelectableItem(controller,item);} 
canSelectTreeElement(treeElement)
{if(!super.canSelectTreeElement(treeElement))
return false;let willRemoveAncestorOrSelf=false;if(this._treeElementsToRemove){while(treeElement&&!willRemoveAncestorOrSelf){willRemoveAncestorOrSelf=this._treeElementsToRemove.includes(treeElement);treeElement=treeElement.parent;}}
return!willRemoveAncestorOrSelf;}
objectForSelection(treeElement)
{if(treeElement instanceof WI.DOMTreeElement&&treeElement.isCloseTag()){

if(!treeElement.__closeTagProxyObject)
treeElement.__closeTagProxyObject={__proxyObjectTreeElement:treeElement};return treeElement.__closeTagProxyObject;}
return super.objectForSelection(treeElement);} 
_revealAndSelectNode(node,omitFocus)
{if(!node||this._suppressRevealAndSelect)
return;var treeElement=this.createTreeElementFor(node);if(!treeElement)
return;treeElement.revealAndSelect(omitFocus);}
_onmousedown(event)
{let element=this.treeElementFromEvent(event);if(!element||element.isEventWithinDisclosureTriangle(event)){event.preventDefault();return;}}
_onmousemove(event)
{if(this._usingLocalDOMNode)
return;let element=this.treeElementFromEvent(event);if(element&&this._previousHoveredElement===element)
return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;this._previousHoveredElement=null;}
if(element){element.hovered=true;this._previousHoveredElement=element;if(element.representedObject){if(!element.tooltip&&element._createTooltipForNode)
element._createTooltipForNode();element.representedObject.highlight();}else
WI.domManager.hideDOMNodeHighlight();}else
WI.domManager.hideDOMNodeHighlight();}
_onmouseout(event)
{if(this._usingLocalDOMNode)
return;var nodeUnderMouse=document.elementFromPoint(event.pageX,event.pageY);if(nodeUnderMouse&&this.element.contains(nodeUnderMouse))
return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;this._previousHoveredElement=null;}
WI.domManager.hideDOMNodeHighlight();}
_ondragstart(event)
{if(!this.editable)
return false;let treeElement=this.treeElementFromEvent(event);if(!treeElement)
return false;event.dataTransfer.effectAllowed="copyMove";event.dataTransfer.setData(DOMTreeOutline.DOMNodeIdDragType,treeElement.representedObject.id);if(!this._isValidDragSourceOrTarget(treeElement))
return false;if(treeElement.representedObject.nodeName()==="BODY"||treeElement.representedObject.nodeName()==="HEAD")
return false;event.dataTransfer.setData("text/plain",treeElement.listItemElement.textContent);this._nodeBeingDragged=treeElement.representedObject;WI.domManager.hideDOMNodeHighlight();return true;}
_ondragover(event)
{if(!this.editable)
return false;if(event.dataTransfer.types.includes(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType)){event.preventDefault();event.dataTransfer.dropEffect="copy";return false;}
if(!this._nodeBeingDragged)
return false;let treeElement=this.treeElementFromEvent(event);if(!this._isValidDragSourceOrTarget(treeElement))
return false;let node=treeElement.representedObject;while(node){if(node===this._nodeBeingDragged)
return false;node=node.parentNode;}
this.dragOverTreeElement=treeElement;treeElement.listItemElement.classList.add("elements-drag-over");treeElement.updateSelectionArea();event.preventDefault();event.dataTransfer.dropEffect="move";return false;}
_ondragleave(event)
{if(!this.editable)
return false;this._clearDragOverTreeElementMarker();event.preventDefault();return false;}
_isValidDragSourceOrTarget(treeElement)
{if(!treeElement)
return false;var node=treeElement.representedObject;if(!(node instanceof WI.DOMNode))
return false;if(!node.parentNode||node.parentNode.nodeType()!==Node.ELEMENT_NODE)
return false;return true;}
_ondrop(event)
{if(!this.editable)
return;event.preventDefault();function callback(error,newNodeId)
{if(error)
return;this._updateModifiedNodes();var newNode=WI.domManager.nodeForId(newNodeId);if(newNode)
this.selectDOMNode(newNode,true);}
let treeElement=this.treeElementFromEvent(event);if(this._nodeBeingDragged&&treeElement){let parentNode=null;let anchorNode=null;if(treeElement._elementCloseTag){parentNode=treeElement.representedObject;}else{let dragTargetNode=treeElement.representedObject;parentNode=dragTargetNode.parentNode;anchorNode=dragTargetNode;}
this._nodeBeingDragged.moveTo(parentNode,anchorNode,callback.bind(this));}else{let className=event.dataTransfer.getData(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType);if(className&&treeElement)
treeElement.representedObject.toggleClass(className,true);}
delete this._nodeBeingDragged;}
_ondragend(event)
{if(!this.editable)
return;event.preventDefault();this._clearDragOverTreeElementMarker();delete this._nodeBeingDragged;}
_clearDragOverTreeElementMarker()
{if(this.dragOverTreeElement){let element=this.dragOverTreeElement;this.dragOverTreeElement=null;element.listItemElement.classList.remove("elements-drag-over");element.updateSelectionArea();}}
_updateModifiedNodes()
{if(this._elementsTreeUpdater)
this._elementsTreeUpdater._updateModifiedNodes();}
_handleInspectedNodeChanged(event)
{let{lastInspectedNode}=event.data;if(lastInspectedNode){let lastInspectedNodeTreeElement=this.findTreeElement(lastInspectedNode);if(lastInspectedNodeTreeElement)
lastInspectedNodeTreeElement.listItemElement.classList.remove("inspected-node");}
let inspectedNodeTreeElement=this.findTreeElement(WI.domManager.inspectedNode);if(inspectedNodeTreeElement)
inspectedNodeTreeElement.listItemElement.classList.add("inspected-node");}
_hideElements(event,keyboardShortcut)
{if(!this.editable)
return;if(!this.selectedTreeElement||WI.isEditingAnyField())
return;event.preventDefault();let forceHidden=!this.selectedTreeElements.every((treeElement)=>treeElement.isNodeHidden);this.toggleSelectedElementsVisibility(forceHidden);}};WI.DOMTreeOutline.Event={SelectedNodeChanged:"dom-tree-outline-selected-node-changed"};WI.DOMTreeOutline.DOMNodeIdDragType="web-inspector/dom-node-id";WI.DOMTreeUpdater=function(treeOutline)
{WI.domManager.addEventListener(WI.DOMManager.Event.NodeInserted,this._nodeInserted,this);WI.domManager.addEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeModified,this._attributesUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.addEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.ChildNodeCountUpdated,this._childNodeCountUpdated,this);this._treeOutline=treeOutline;this._recentlyInsertedNodes=new Map;this._recentlyDeletedNodes=new Map;this._recentlyModifiedNodes=new Set;this._recentlyModifiedAttributes=new Map;this._textContentAttributeSymbol=Symbol("text-content-attribute");this._updateModifiedNodesDebouncer=new Debouncer(()=>{this._updateModifiedNodes();});};WI.DOMTreeUpdater.prototype={close:function()
{WI.domManager.removeEventListener(WI.DOMManager.Event.NodeInserted,this._nodeInserted,this);WI.domManager.removeEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeModified,this._attributesUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.removeEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.ChildNodeCountUpdated,this._childNodeCountUpdated,this);},_documentUpdated:function(event)
{this._reset();},_attributesUpdated:function(event)
{let{node,name}=event.data;this._nodeAttributeModified(node,name);},_characterDataModified:function(event)
{let{node}=event.data;this._nodeAttributeModified(node,this._textContentAttributeSymbol);},_nodeAttributeModified:function(node,attribute)
{if(!this._recentlyModifiedAttributes.has(attribute))
this._recentlyModifiedAttributes.set(attribute,new Set);this._recentlyModifiedAttributes.get(attribute).add(node);this._recentlyModifiedNodes.add(node);if(this._treeOutline._visible)
this._updateModifiedNodesDebouncer.delayForFrame();},_nodeInserted:function(event)
{this._recentlyInsertedNodes.set(event.data.node,{parent:event.data.parent});if(this._treeOutline._visible)
this._updateModifiedNodesDebouncer.delayForFrame();},_nodeRemoved:function(event)
{let parent=event.data.parent;if(!parent)
return;this._recentlyDeletedNodes.set(event.data.node,{parent});if(this._treeOutline._visible)
this._updateModifiedNodesDebouncer.delayForFrame();},_childNodeCountUpdated:function(event)
{var treeElement=this._treeOutline.findTreeElement(event.data);if(treeElement)
treeElement.hasChildren=event.data.hasChildNodes();},_updateModifiedNodes:function()
{
let parentElementsToUpdate=new Set;let markNodeParentForUpdate=(value,key,map)=>{let parentNode=value.parent;let parentTreeElement=this._treeOutline.findTreeElement(parentNode);if(parentTreeElement)
parentElementsToUpdate.add(parentTreeElement);};this._recentlyInsertedNodes.forEach(markNodeParentForUpdate);this._recentlyDeletedNodes.forEach(markNodeParentForUpdate);for(let parentTreeElement of parentElementsToUpdate){if(parentTreeElement.treeOutline&&parentTreeElement.listItemElement){parentTreeElement.updateTitle();parentTreeElement.updateChildren();}}
for(let node of this._recentlyModifiedNodes.values()){let nodeTreeElement=this._treeOutline.findTreeElement(node);if(!nodeTreeElement)
continue;for(let[attribute,nodes]of this._recentlyModifiedAttributes.entries()){if(attribute===this._textContentAttributeSymbol)
continue;if(nodes.has(node))
nodeTreeElement.attributeDidChange(attribute);}
nodeTreeElement.updateTitle();}
this._recentlyInsertedNodes.clear();this._recentlyDeletedNodes.clear();this._recentlyModifiedNodes.clear();this._recentlyModifiedAttributes.clear();},_reset:function()
{WI.domManager.hideDOMNodeHighlight();this._recentlyInsertedNodes.clear();this._recentlyDeletedNodes.clear();this._recentlyModifiedNodes.clear();this._recentlyModifiedAttributes.clear();}};WI.DatabaseContentView=class DatabaseContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.database=representedObject;this.element.classList.add("storage-view","query","monospace");this._prompt=new WI.ConsolePrompt(this,"text/x-sql");this.addSubview(this._prompt);this.element.addEventListener("click",this._messagesClicked.bind(this),true);} 
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.Database;cookie.host=this.representedObject.host;cookie.name=this.representedObject.name;}
consolePromptCompletionsNeeded(prompt,defaultCompletions,base,prefix,suffix)
{let results=[];prefix=prefix.toLowerCase();function accumulateMatches(textArray)
{for(let text of textArray){if(text.toLowerCase().startsWith(prefix))
results.push(text);}}
function tableNamesCallback(tableNames)
{accumulateMatches(tableNames);accumulateMatches(["SELECT","FROM","WHERE","LIMIT","DELETE FROM","CREATE","DROP","TABLE","INDEX","UPDATE","INSERT INTO","VALUES"]);this._prompt.updateCompletions(results," ");}
this.database.getTableNames(tableNamesCallback.bind(this));}
consolePromptTextCommitted(prompt,query)
{this.database.executeSQL(query,this._queryFinished.bind(this,query),this._queryError.bind(this,query));} 
_messagesClicked()
{this._prompt.focus();}
_queryFinished(query,columnNames,values)
{let trimmedQuery=query.trim();let queryView=new WI.DatabaseUserQuerySuccessView(trimmedQuery,columnNames,values);this.insertSubviewBefore(queryView,this._prompt);if(queryView.dataGrid)
queryView.dataGrid.autoSizeColumns(5);this._prompt.element.scrollIntoView(false);if(trimmedQuery.match(/^create /i)||trimmedQuery.match(/^drop table /i))
this.dispatchEventToListeners(WI.DatabaseContentView.Event.SchemaUpdated,this.database);}
_queryError(query,error)
{let message;if(error.message)
message=error.message;else if(error.code===2)
message=WI.UIString("Database no longer has expected version.");else
message=WI.UIString("An unexpected error %s occurred.").format(error.code);let queryView=new WI.DatabaseUserQueryErrorView(query,message);this.insertSubviewBefore(queryView,this._prompt);this._prompt.element.scrollIntoView(false);}};WI.DatabaseContentView.Event={SchemaUpdated:"SchemaUpdated"};WI.DatabaseHostTreeElement=class DatabaseHostTreeElement extends WI.StorageTreeElement
{constructor(host)
{super(WI.FolderTreeElement.FolderIconStyleClassName,WI.displayNameForHost(host),null);this._host=host;this.hasChildren=true;this.expanded=true;} 
get name()
{return WI.displayNameForHost(this._host);}
get categoryName()
{return WI.UIString("Databases");}};WI.DatabaseTableContentView=class DatabaseTableContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this.element.classList.add("database-table");this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("database-table-refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshButtonClicked,this);this._messageTextViewElement=null;this.update();} 
get navigationItems()
{return[this._refreshButtonNavigationItem];}
update()
{this.representedObject.database.executeSQL("SELECT * FROM \""+this._escapeTableName(this.representedObject.name)+"\"",this._queryFinished.bind(this),this._queryError.bind(this));}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.DatabaseTable;cookie.host=this.representedObject.host;cookie.name=this.representedObject.name;cookie.database=this.representedObject.database.name;}
get scrollableElements()
{if(!this._dataGrid)
return[];return[this._dataGrid.scrollContainer];} 
_escapeTableName(name)
{return name.replace(/"/g,"\"\"");}
_queryFinished(columnNames,values)
{

if(this._dataGrid){this.removeSubview(this._dataGrid);this._dataGrid=null;}
if(this._messageTextViewElement)
this._messageTextViewElement.remove();if(columnNames.length){this._dataGrid=WI.DataGrid.createSortableDataGrid(columnNames,values);this.addSubview(this._dataGrid);this._dataGrid.updateLayout();return;}

this._messageTextViewElement=WI.createMessageTextView(WI.UIString("The \u201C%s\u201D\ntable is empty.").format(this.representedObject.name),false);this.element.appendChild(this._messageTextViewElement);}
_queryError(error)
{if(this._dataGrid){this.removeSubview(this._dataGrid);this._dataGrid=null;}
if(this._messageTextViewElement)
this._messageTextViewElement.remove();this._messageTextViewElement=WI.createMessageTextView(WI.UIString("An error occurred trying to read the \u201C%s\u201D table.").format(this.representedObject.name),true);this.element.appendChild(this._messageTextViewElement);}
_refreshButtonClicked()
{this.update();}};WI.DatabaseTableTreeElement=class DatabaseTableTreeElement extends WI.GeneralTreeElement
{constructor(representedObject)
{const subtitle=null;super("database-table-icon",representedObject.name,subtitle,representedObject);}};WI.DatabaseTreeElement=class DatabaseTreeElement extends WI.GeneralTreeElement
{constructor(representedObject)
{const subtitle=null;super("database-icon",representedObject.name,subtitle,representedObject,{hasChildren:true});this.hasChildren=false;
this.onpopulate();}
oncollapse()
{this.shouldRefreshChildren=true;}
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();function tableNamesCallback(tableNames)
{for(var i=0;i<tableNames.length;++i){var databaseTable=new WI.DatabaseTableObject(tableNames[i],this.representedObject);this.appendChild(new WI.DatabaseTableTreeElement(databaseTable));}
this.hasChildren=tableNames.length;}
this.representedObject.getTableNames(tableNamesCallback.bind(this));}};WI.DividerNavigationItem=class DividerNavigationItem extends WI.NavigationItem
{ get additionalClassNames()
{return["divider"];}};

WI.DropZoneView=class DropZoneView extends WI.View
{constructor(delegate)
{super();this._delegate=delegate;this._targetElement=null;this._activelyHandlingDrag=false;this.element.classList.add("drop-zone");} 
get delegate(){return this._delegate;}
get targetElement()
{return this._targetElement;}
set targetElement(element)
{if(this._targetElement===element)
return;if(!this._boundHandleDragEnter)
this._boundHandleDragEnter=this._handleDragEnter.bind(this);if(this._targetElement)
this._targetElement.removeEventListener("dragenter",this._boundHandleDragEnter);this._targetElement=element;if(this._targetElement)
this._targetElement.addEventListener("dragenter",this._boundHandleDragEnter);}
set text(text)
{this.element.textContent=text;} 
initialLayout()
{super.initialLayout();this.element.addEventListener("dragover",this._handleDragOver.bind(this));this.element.addEventListener("dragleave",this._handleDragLeave.bind(this));this.element.addEventListener("drop",this._handleDrop.bind(this));} 
_startActiveDrag()
{this._activelyHandlingDrag=true;this.element.classList.add("visible");}
_stopActiveDrag()
{this._activelyHandlingDrag=false;this.element.classList.remove("visible");}
_handleDragEnter(event)
{if(this._activelyHandlingDrag)
return;if(!this._delegate.dropZoneShouldAppearForDragEvent(this,event))
return;this._startActiveDrag();if(this._delegate.dropZoneHandleDragEnter)
this._delegate.dropZoneHandleDragEnter(this,event);}
_handleDragLeave(event)
{if(!this._activelyHandlingDrag)
return;this._stopActiveDrag();if(this._delegate.dropZoneHandleDragLeave)
this._delegate.dropZoneHandleDragLeave(this,event);}
_handleDragOver(event)
{if(!this._activelyHandlingDrag)
return;event.preventDefault();event.dataTransfer.dropEffect="copy";}
_handleDrop(event)
{if(!this._activelyHandlingDrag)
return;event.preventDefault();this._stopActiveDrag();if(this._delegate.dropZoneHandleDrop)
this._delegate.dropZoneHandleDrop(this,event);}};WI.EditableDataGridNode=class EditableDataGridNode extends WI.DataGridNode
{ get element()
{let element=super.element;if(element)
element.classList.add("editable");return element;} 
createCellContent(columnIdentifier,cell)
{let content=super.createCellContent(columnIdentifier,cell);if(typeof content!=="string")
return content;let inputElement=document.createElement("input");inputElement.spellcheck=false;inputElement.value=content;inputElement.addEventListener("keypress",this._handleKeyPress.bind(this,columnIdentifier));inputElement.addEventListener("blur",this._handleBlur.bind(this,columnIdentifier));return inputElement;} 
_handleKeyPress(columnIdentifier,event)
{if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode)
this.dataGrid.element.focus();if(event.keyCode===WI.KeyboardShortcut.Key.Enter.keyCode)
this._notifyInputElementValueChanged(columnIdentifier,event.target.value);}
_handleBlur(columnIdentifier,event)
{this._notifyInputElementValueChanged(columnIdentifier,event.target.value);}
_notifyInputElementValueChanged(columnIdentifier,value)
{if(value!==this.data[columnIdentifier])
this.dispatchEventToListeners(WI.EditableDataGridNode.Event.ValueChanged,{value,columnIdentifier});}};WI.EditableDataGridNode.Event={ValueChanged:"editable-data-grid-node-value-changed",};WI.enclosingCodeMirror=function(element)
{while(element){if(element.CodeMirror)
return element.CodeMirror;element=element.parentNode;}
return null;};WI.isBeingEdited=function(element)
{while(element){if(element.__editing)
return true;element=element.parentNode;}
return false;};WI.markBeingEdited=function(element,value)
{if(value){if(element.__editing)
return false;element.__editing=true;WI.__editingCount=(WI.__editingCount||0)+1;}else{if(!element.__editing)
return false;delete element.__editing;--WI.__editingCount;}
return true;};WI.isEditingAnyField=function()
{return!!WI.__editingCount;};WI.isEventTargetAnEditableField=function(event)
{if(event.target instanceof HTMLInputElement||event.target instanceof HTMLTextAreaElement)
return true;if(event.target.isContentEditable)
return true;if(WI.isBeingEdited(event.target))
return true;let codeMirror=WI.enclosingCodeMirror(event.target);if(codeMirror)
return!codeMirror.getOption("readOnly");return false;};WI.EditingConfig=class EditingConfig
{constructor(commitHandler,cancelHandler,context)
{this.commitHandler=commitHandler;this.cancelHandler=cancelHandler;this.context=context;this.spellcheck=false;}
setPasteHandler(pasteHandler)
{this.pasteHandler=pasteHandler;}
setMultiline(multiline)
{this.multiline=multiline;}
setCustomFinishHandler(customFinishHandler)
{this.customFinishHandler=customFinishHandler;}
setNumberCommitHandler(numberCommitHandler)
{this.numberCommitHandler=numberCommitHandler;}};WI.startEditing=function(element,config)
{if(!WI.markBeingEdited(element,true))
return null;config=config||new WI.EditingConfig(function(){},function(){});var committedCallback=config.commitHandler;var cancelledCallback=config.cancelHandler;var pasteCallback=config.pasteHandler;var context=config.context;var oldText=getContent(element);var moveDirection="";element.classList.add("editing");element.contentEditable="plaintext-only";var oldSpellCheck=element.hasAttribute("spellcheck")?element.spellcheck:undefined;element.spellcheck=config.spellcheck;if(config.multiline)
element.classList.add("multiline");var oldTabIndex=element.tabIndex;if(element.tabIndex<0)
element.tabIndex=0;function blurEventListener(){editingCommitted.call(element);}
function getContent(element){if(element.tagName==="INPUT"&&element.type==="text")
return element.value;else
return element.textContent;}
function cleanUpAfterEditing()
{WI.markBeingEdited(element,false);this.classList.remove("editing");this.contentEditable=false;this.scrollTop=0;this.scrollLeft=0;if(oldSpellCheck===undefined)
element.removeAttribute("spellcheck");else
element.spellcheck=oldSpellCheck;if(oldTabIndex===-1)
this.removeAttribute("tabindex");else
this.tabIndex=oldTabIndex;element.removeEventListener("blur",blurEventListener,false);element.removeEventListener("keydown",keyDownEventListener,true);if(pasteCallback)
element.removeEventListener("paste",pasteEventListener,true);WI.restoreFocusFromElement(element);}
function editingCancelled()
{if(this.tagName==="INPUT"&&this.type==="text")
this.value=oldText;else
this.textContent=oldText;cleanUpAfterEditing.call(this);cancelledCallback(this,context);}
function editingCommitted()
{cleanUpAfterEditing.call(this);committedCallback(this,getContent(this),oldText,context,moveDirection);}
function defaultFinishHandler(event)
{var hasOnlyMetaModifierKey=event.metaKey&&!event.shiftKey&&!event.ctrlKey&&!event.altKey;if(isEnterKey(event)&&(!config.multiline||hasOnlyMetaModifierKey))
return"commit";else if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode||event.keyIdentifier==="U+001B")
return"cancel";else if(event.keyIdentifier==="U+0009") 
return"move-"+(event.shiftKey?"backward":"forward");else if(event.altKey){if(event.keyIdentifier==="Up"||event.keyIdentifier==="Down")
return"modify-"+(event.keyIdentifier==="Up"?"up":"down");if(event.keyIdentifier==="PageUp"||event.keyIdentifier==="PageDown")
return"modify-"+(event.keyIdentifier==="PageUp"?"up-big":"down-big");}}
function handleEditingResult(result,event)
{if(result==="commit"){editingCommitted.call(element);event.preventDefault();event.stopPropagation();}else if(result==="cancel"){editingCancelled.call(element);event.preventDefault();event.stopPropagation();}else if(result&&result.startsWith("move-")){moveDirection=result.substring(5);if(event.keyIdentifier!=="U+0009")
blurEventListener();}else if(result&&result.startsWith("modify-")){let direction=result.substring(7);let delta=direction.startsWith("up")?1:-1;if(direction.endsWith("big"))
delta*=10;if(event.shiftKey)
delta*=10;else if(event.ctrlKey)
delta/=10;let modified=WI.incrementElementValue(element,delta);if(!modified)
return;if(typeof config.numberCommitHandler==="function")
config.numberCommitHandler(element,getContent(element),oldText,context,moveDirection);event.preventDefault();}}
function pasteEventListener(event)
{var result=pasteCallback(event);handleEditingResult(result,event);}
function keyDownEventListener(event)
{var handler=config.customFinishHandler||defaultFinishHandler;var result=handler(event);handleEditingResult(result,event);}
element.addEventListener("blur",blurEventListener,false);element.addEventListener("keydown",keyDownEventListener,true);if(pasteCallback)
element.addEventListener("paste",pasteEventListener,true);element.focus();return{cancel:editingCancelled.bind(element),commit:editingCommitted.bind(element)};};WI.incrementElementValue=function(element,delta)
{let selection=element.ownerDocument.defaultView.getSelection();if(!selection.rangeCount)
return false;let range=selection.getRangeAt(0);if(!element.contains(range.commonAncestorContainer))
return false;let wordRange=range.startContainer.rangeOfWord(range.startOffset,WI.EditingSupport.StyleValueDelimiters,element);let word=wordRange.toString();let wordPrefix="";let wordSuffix="";let nonNumberInWord=/[^\d-\.]+/.exec(word);if(nonNumberInWord){let nonNumberEndOffset=nonNumberInWord.index+nonNumberInWord[0].length;if(range.startOffset>wordRange.startOffset+nonNumberInWord.index&&nonNumberEndOffset<word.length&&range.startOffset!==wordRange.startOffset){wordPrefix=word.substring(0,nonNumberEndOffset);word=word.substring(nonNumberEndOffset);}else{wordSuffix=word.substring(nonNumberInWord.index);word=word.substring(0,nonNumberInWord.index);}}
let matches=WI.EditingSupport.CSSNumberRegex.exec(word);if(!matches||matches.length!==4)
return false;let replacement=matches[1]+(Math.round((parseFloat(matches[2])+delta)*100)/100)+matches[3];selection.removeAllRanges();selection.addRange(wordRange);document.execCommand("insertText",false,wordPrefix+replacement+wordSuffix);let container=range.commonAncestorContainer;let startOffset=range.startOffset;




if(container.parentNode.classList.contains("editing")&&container.nextSibling){container=container.nextSibling.firstChild;startOffset=0;}
startOffset+=wordPrefix.length;if(!container)
return false;let replacementSelectionRange=document.createRange();replacementSelectionRange.setStart(container,startOffset);replacementSelectionRange.setEnd(container,startOffset+replacement.length);selection.removeAllRanges();selection.addRange(replacementSelectionRange);return true;};WI.EditingSupport={StyleValueDelimiters:" \xA0\t\n\"':;,/()",CSSNumberRegex:/(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/,NumberRegex:/^(-?(?:\d+(?:\.\d+)?|\.\d+))$/};WI.ErrorObjectView=class ErrorObjectView extends WI.Object
{constructor(object)
{super();this._object=object;this._expanded=false;this._hasStackTrace=false;this._element=document.createElement("div");this._element.classList.add("error-object");var previewElement=WI.FormattedValue.createElementForError(this._object);this._element.append(previewElement);previewElement.addEventListener("click",this._handlePreviewOrTitleElementClick.bind(this));this._outlineElement=this._element.appendChild(document.createElement("div"));this._outlineElement.className="content";} 
static makeSourceLinkWithPrefix(sourceURL,lineNumber,columnNumber)
{if(!sourceURL)
return null;var span=document.createElement("span");span.classList.add("error-object-link-container");span.textContent=` ${emDash} `;const options={ignoreNetworkTab:true,ignoreSearchTab:true,};let a=WI.linkifyLocation(sourceURL,new WI.SourceCodePosition(parseInt(lineNumber)-1,parseInt(columnNumber)),options);a.classList.add("error-object-link");span.appendChild(a);return span;} 
get object()
{return this._object;}
get element()
{return this._element;}
get expanded()
{return this._expanded;}
update()
{if(this._hasStackTrace)
return;const options={ownProperties:true,generatePreview:true,};this._object.getPropertyDescriptors((properties)=>{if(!properties||this._hasStackTrace)
return;let stackProperty=properties.find((property)=>property.name==="stack");if(!stackProperty)
return;this._buildStackTrace(stackProperty.value.value);this._hasStackTrace=true;},options);}
expand()
{if(this._expanded)
return;this._expanded=true;this._element.classList.add("expanded");this.update();}
collapse()
{if(!this._expanded)
return;this._expanded=false;this._element.classList.remove("expanded");}
appendTitleSuffix(suffixElement)
{this._element.insertBefore(suffixElement,this._outlineElement);} 
_handlePreviewOrTitleElementClick(event)
{if(!this._expanded)
this.expand();else
this.collapse();event.stopPropagation();}
_buildStackTrace(stackString)
{let stackTrace=WI.StackTrace.fromString(this._object.target,stackString);let stackTraceElement=new WI.StackTraceView(stackTrace).element;this._outlineElement.appendChild(stackTraceElement);}};WI.EventBreakpointPopover=class EventBreakpointPopover extends WI.BreakpointPopover
{constructor(delegate,breakpoint)
{super(delegate,breakpoint);this._currentEventNameCompletions=[];this._eventNameSuggestionsView=new WI.CompletionSuggestionsView(this,{preventBlur:true});} 
static get supportsEditing()
{return WI.EventBreakpoint.supportsEditing;} 
dismiss()
{this._eventNameSuggestionsView.hide();super.dismiss();} 
completionSuggestionsClickedCompletion(suggestionsView,selectedText)
{this._domEventNameInputElement.value=selectedText;this.dismiss();} 
get codeMirrorCompletionControllerMode()
{return WI.CodeMirrorCompletionController.Mode.EventBreakpoint;}
populateContent()
{let eventLabelElement=document.createElement("label");eventLabelElement.textContent=WI.UIString("Event");this._domEventNameInputElement=document.createElement("input");this._domEventNameInputElement.id="edit-breakpoint-popover-content-event-name";this._domEventNameInputElement.setAttribute("dir","ltr");this._domEventNameInputElement.spellcheck=false;this._domEventNameInputElement.addEventListener("keydown",this._handleEventInputKeydown.bind(this));this._domEventNameInputElement.addEventListener("input",this._handleEventInputInput.bind(this));this._domEventNameInputElement.addEventListener("blur",this._handleEventInputBlur.bind(this));eventLabelElement.setAttribute("for",this._domEventNameInputElement.id);this.addRow("event",eventLabelElement,this._domEventNameInputElement);setTimeout(()=>{this._domEventNameInputElement.focus();});}
createBreakpoint(options={})
{options.eventName=this._domEventNameInputElement.value;if(!options.eventName)
return null;return new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener,options);} 
_showSuggestionsView()
{let computedStyle=window.getComputedStyle(this._domEventNameInputElement);let padding=parseInt(computedStyle.borderLeftWidth)+parseInt(computedStyle.paddingLeft);let rect=WI.Rect.rectFromClientRect(this._domEventNameInputElement.getBoundingClientRect());rect.origin.x+=padding;rect.size.width-=padding+parseInt(computedStyle.borderRightWidth)+parseInt(computedStyle.paddingRight);this._eventNameSuggestionsView.show(rect.pad(2));}
_handleEventInputKeydown(event)
{let shouldDismiss=isEnterKey(event);if(shouldDismiss||(event.key==="Tab"&&this._eventNameSuggestionsView.visible)){if(this._eventNameSuggestionsView.visible&&this._eventNameSuggestionsView.selectedIndex<this._currentEventNameCompletions.length)
this._domEventNameInputElement.value=this._currentEventNameCompletions[this._eventNameSuggestionsView.selectedIndex];}else if((event.key==="ArrowUp"||event.key==="ArrowDown")&&this._eventNameSuggestionsView.visible){event.stop();if(event.key==="ArrowDown")
this._eventNameSuggestionsView.selectNext();else
this._eventNameSuggestionsView.selectPrevious();}
if(shouldDismiss)
this.dismiss();}
_handleEventInputInput(event)
{let eventName=this._domEventNameInputElement.value.toLowerCase();WI.domManager.getSupportedEventNames().then((supportedEventNames)=>{this._currentEventNameCompletions=[];for(let supportedEventName of supportedEventNames){if(supportedEventName.toLowerCase().startsWith(eventName))
this._currentEventNameCompletions.push(supportedEventName);}
if(!this._currentEventNameCompletions.length||(this._currentEventNameCompletions.length===1&&this._currentEventNameCompletions[0].toLowerCase()===eventName)){this._eventNameSuggestionsView.hide();return;}
this._eventNameSuggestionsView.update(this._currentEventNameCompletions);this._showSuggestionsView();});}
_handleEventInputBlur(event)
{this._eventNameSuggestionsView.hide();}};WI.EventBreakpointPopover.ReferencePage=WI.ReferencePage.EventBreakpoints;WI.EventBreakpointTreeElement=class EventBreakpointTreeElement extends WI.BreakpointTreeElement
{constructor(breakpoint,{classNames,title}={})
{if(!Array.isArray(classNames))
classNames=[];classNames.push("event",breakpoint.type);if(!title)
title=breakpoint.displayName;super(breakpoint,{classNames,title});}};WI.EventListenerSectionGroup=class EventListenerSectionGroup extends WI.DetailsSectionGroup
{constructor(eventListener,options={})
{super();this._eventListener=eventListener;var rows=[];if(!options.hideType)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Event"),this._eventListener.type));if(!options.hideTarget)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Target"),this._targetTextOrLink()));rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Function"),this._functionTextOrLink()));if(this._eventListener.useCapture)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Capturing"),WI.UIString("Yes")));else
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Bubbling"),WI.UIString("Yes")));if(this._eventListener.isAttribute)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Attribute"),WI.UIString("Yes")));if(this._eventListener.passive)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Passive"),WI.UIString("Yes")));if(this._eventListener.once)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Once"),WI.UIString("Yes")));if(this.supportsStateModification){if(WI.DOMManager.supportsDisablingEventListeners()){this._eventListenerEnabledToggleElement=document.createElement("input");this._eventListenerEnabledToggleElement.type="checkbox";this._updateDisabledToggle();this._eventListenerEnabledToggleElement.addEventListener("change",(event)=>{this.isEventListenerDisabled=!this._eventListenerEnabledToggleElement.checked;this.hasEventListenerBreakpoint=false;});let toggleLabel=document.createElement("span");toggleLabel.textContent=WI.UIString("Enabled");toggleLabel.addEventListener("click",(event)=>{this._eventListenerEnabledToggleElement.click();});rows.push(new WI.DetailsSectionSimpleRow(toggleLabel,this._eventListenerEnabledToggleElement));}
if(WI.DOMManager.supportsEventListenerBreakpoints()){let toggleContainer=document.createElement("span");this._eventListenerBreakpointToggleElement=toggleContainer.appendChild(document.createElement("input"));this._eventListenerBreakpointToggleElement.type="checkbox";this._updateBreakpointToggle();this._eventListenerBreakpointToggleElement.addEventListener("change",(event)=>{this.isEventListenerDisabled=false;this.hasEventListenerBreakpoint=!!this._eventListenerBreakpointToggleElement.checked;});if(WI.DOMManager.supportsEventListenerBreakpointConfiguration()){let revealBreakpointGoToArrow=toggleContainer.appendChild(WI.createGoToArrowButton());revealBreakpointGoToArrow.title=WI.UIString("Reveal in Sources Tab");revealBreakpointGoToArrow.addEventListener("click",(event)=>{WI.showSourcesTab({representedObjectToSelect:WI.domManager.breakpointForEventListenerId(this._eventListener.eventListenerId),});});}
let toggleLabel=document.createElement("span");toggleLabel.textContent=WI.UIString("Breakpoint");toggleLabel.addEventListener("click",(event)=>{this._eventListenerBreakpointToggleElement.click();});rows.push(new WI.DetailsSectionSimpleRow(toggleLabel,toggleContainer));}}
this.rows=rows;} 
get supportsStateModification()
{return!!this._eventListener.eventListenerId;}
get isEventListenerDisabled()
{if(!this.supportsStateModification)
return false;return this._eventListener.disabled;}
set isEventListenerDisabled(disabled)
{if(!this.supportsStateModification)
return;if(this._eventListener.disabled===disabled)
return;this._eventListener.disabled=disabled;this._updateDisabledToggle();WI.domManager.setEventListenerDisabled(this._eventListener,this._eventListener.disabled);}
get hasEventListenerBreakpoint()
{if(!this.supportsStateModification)
return false;return this._eventListener.hasBreakpoint;}
set hasEventListenerBreakpoint(hasBreakpoint)
{if(!this.supportsStateModification)
return;if(this._eventListener.hasBreakpoint===hasBreakpoint)
return;this._eventListener.hasBreakpoint=hasBreakpoint;this._updateBreakpointToggle();if(this._eventListener.hasBreakpoint)
WI.domManager.setBreakpointForEventListener(this._eventListener);else
WI.domManager.removeBreakpointForEventListener(this._eventListener);} 
_targetTextOrLink()
{if(this._eventListener.onWindow)
return WI.unlocalizedString("window");let node=this._eventListener.node;if(node)
return WI.linkifyNodeReference(node);return"";}
_functionTextOrLink()
{let anonymous=false;let functionName=this._eventListener.handlerName;if(!functionName&&this._eventListener.handlerBody){let match=this._eventListener.handlerBody.match(/function ([^\(]+?)\(/);if(match)
functionName=match[1];}
if(!functionName){anonymous=true;functionName=WI.UIString("(anonymous function)");}
if(!this._eventListener.location)
return functionName;var sourceCode=WI.debuggerManager.scriptForIdentifier(this._eventListener.location.scriptId,WI.mainTarget);if(!sourceCode)
return functionName;var sourceCodeLocation=sourceCode.createSourceCodeLocation(this._eventListener.location.lineNumber,this._eventListener.location.columnNumber||0);const options={dontFloat:anonymous,ignoreNetworkTab:true,ignoreSearchTab:true,};let linkElement=WI.createSourceCodeLocationLink(sourceCodeLocation,options);if(anonymous)
return linkElement;var fragment=document.createDocumentFragment();fragment.append(linkElement,functionName);return fragment;}
_updateDisabledToggle()
{this._eventListenerEnabledToggleElement.checked=!this._eventListener.disabled;this._eventListenerEnabledToggleElement.title=this._eventListener.disabled?WI.UIString("Enable Event Listener"):WI.UIString("Disable Event Listener");}
_updateBreakpointToggle()
{this._eventListenerBreakpointToggleElement.checked=this._eventListener.hasBreakpoint;this._eventListenerBreakpointToggleElement.title=this._eventListener.hasBreakpoint?WI.UIString("Delete Breakpoint"):WI.UIString("Add Breakpoint");}};WI.ExpandableView=class ExpandableView
{constructor(key,titleElement,childElement)
{this._element=document.createElement("div");if(childElement){this._disclosureButton=this._element.createChild("button","disclosure-button");this._disclosureButton.addEventListener("click",this._onDisclosureButtonClick.bind(this));this._disclosureButton.addEventListener("keydown",this._handleDisclosureButtonKeyDown.bind(this));}
this._element.append(titleElement);this._expandedSetting=new WI.Setting("expanded-"+key,false);if(childElement)
this._element.append(childElement);this._update();} 
get element()
{return this._element;} 
_onDisclosureButtonClick(event)
{this._expandedSetting.value=!this._expandedSetting.value;this._update();}
_handleDisclosureButtonKeyDown(event)
{if(event.code!=="ArrowRight"&&event.code!=="ArrowLeft")
return;event.preventDefault();let collapsed=event.code==="ArrowLeft";if(WI.resolveLayoutDirectionForElement(this._disclosureButton)===WI.LayoutDirection.RTL)
collapsed=!collapsed;this._expandedSetting.value=!collapsed;this._update();}
_update()
{let isExpanded=this._expandedSetting.value;this._element.classList.toggle("expanded",isExpanded);this._disclosureButton?.setAttribute("aria-expanded",isExpanded);}};WI.FilterBar=class FilterBar extends WI.Object
{constructor(element)
{super();this._element=element||document.createElement("div");this._element.classList.add("filter-bar");this._filterFunctionsMap=new Map;this._inputField=document.createElement("input");this._inputField.type="search";this._inputField.placeholder=WI.UIString("Filter");this._inputField.spellcheck=false;this._inputField.incremental=true;this._inputField.addEventListener("search",this._handleFilterChanged.bind(this));this._inputField.addEventListener("input",this._handleFilterInputEvent.bind(this));this._element.appendChild(this._inputField);this._filtersNavigationBar=new WI.NavigationBar;this._element.appendChild(this._filtersNavigationBar.element);this._lastFilterValue=this.filters;this._invalid=false;} 
get element()
{return this._element;}
get inputField()
{return this._inputField;}
get placeholder()
{return this._inputField.placeholder;}
set placeholder(text)
{this._inputField.placeholder=text;}
get incremental()
{return this._inputField.incremental;}
set incremental(incremental)
{this._inputField.incremental=incremental;}
get invalid()
{return this._invalid;}
set invalid(invalid)
{this._invalid=!!invalid;this._element.classList.toggle("invalid",this._invalid);}
get filters()
{return{text:this._inputField.value,functions:[...this._filterFunctionsMap.values()]};}
set filters(filters)
{filters=filters||{};var oldTextValue=this._inputField.value;this._inputField.value=filters.text||"";if(oldTextValue!==this._inputField.value)
this._handleFilterChanged();}
focus()
{if(!this._inputField.value.length)
this._inputField.focus();else
this._inputField.select();}
clear()
{this._filterFunctionsMap.clear();this.filters=null;
for(let navigationItem of this._filtersNavigationBar.navigationItems){if(navigationItem instanceof WI.FilterBarButton)
navigationItem.toggle(false);}
this._inputField.value=null;this.invalid=false;}
addFilterNavigationItem(navigationItem)
{this._filtersNavigationBar.addNavigationItem(navigationItem);}
addFilterBarButton(identifier,filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight)
{var filterBarButton=new WI.FilterBarButton(identifier,filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight);filterBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleFilterBarButtonClicked,this);filterBarButton.addEventListener(WI.FilterBarButton.Event.ActivatedStateToggled,this._handleFilterButtonToggled,this);this.addFilterNavigationItem(filterBarButton);if(filterBarButton.activated){this._filterFunctionsMap.set(filterBarButton.identifier,filterBarButton.filterFunction);this._handleFilterChanged();}}
hasActiveFilters()
{return!!this._inputField.value||!!this._filterFunctionsMap.size;}
hasFilterChanged()
{var currentFunctions=this.filters.functions;if(this._lastFilterValue.text!==this._inputField.value||this._lastFilterValue.functions.length!==currentFunctions.length)
return true;for(var i=0;i<currentFunctions.length;++i){if(this._lastFilterValue.functions[i]!==currentFunctions[i])
return true;}
return false;} 
_handleFilterBarButtonClicked(event)
{var filterBarButton=event.target;filterBarButton.toggle();}
_handleFilterButtonToggled(event)
{var filterBarButton=event.target;if(filterBarButton.activated)
this._filterFunctionsMap.set(filterBarButton.identifier,filterBarButton.filterFunction);else
this._filterFunctionsMap.delete(filterBarButton.identifier);this._handleFilterChanged();}
_handleFilterChanged()
{if(this.hasFilterChanged()){this._lastFilterValue=this.filters;this.dispatchEventToListeners(WI.FilterBar.Event.FilterDidChange);}else if(!this._inputField.value)
this._inputField.blur();}
_handleFilterInputEvent(event)
{if(this.incremental)
return;if(!this._inputField.value)
this._handleFilterChanged();}};WI.FilterBar.Event={FilterDidChange:"filter-bar-text-filter-did-change"};WI.FilterBarButton=class FilterBarButton extends WI.ActivateButtonNavigationItem
{constructor(identifier,filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight,role)
{super(identifier,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight,role);this._filterFunction=filterFunction;this._activatedSetting=new WI.Setting(identifier,activatedByDefault);this.activated=!!this._activatedSetting.value;} 
get filterFunction()
{return this._filterFunction;}
toggle(value)
{this.activated=value===undefined?!this.activated:value;this._activatedSetting.value=this.activated;this.dispatchEventToListeners(WI.FilterBarButton.Event.ActivatedStateToggled);}};WI.FilterBarButton.Event={ActivatedStateToggled:"filter-bar-activated-state-toggled"};WI.FilterBarNavigationItem=class FilterBarNavigationItem extends WI.NavigationItem
{constructor()
{super();this._filterBar=new WI.FilterBar(this.element);} 
get filterBar()
{return this._filterBar;}};WI.FindBanner=class FindBanner extends WI.NavigationItem
{constructor(delegate,className,alwaysShowing=false)
{super();this._delegate=delegate||null;this._alwaysShowing=alwaysShowing;this.element.classList.add("find-banner");if(className)
this.element.classList.add(className);this._resultCountLabel=document.createElement("label");this.element.appendChild(this._resultCountLabel);this._inputField=document.createElement("input");this._inputField.type="search";this._inputField.placeholder=" ";this._inputField.spellcheck=false;this._inputField.incremental=true;this._inputField.setAttribute("results",5);this._inputField.setAttribute("autosave","inspector-search");this._inputField.addEventListener("keydown",this._inputFieldKeyDown.bind(this),false);this._inputField.addEventListener("keyup",this._inputFieldKeyUp.bind(this),false);this._inputField.addEventListener("search",this._inputFieldSearch.bind(this),false);this.element.appendChild(this._inputField);this._previousResultButton=document.createElement("button");this._previousResultButton.classList.add("segmented","previous-result");this._previousResultButton.disabled=true;this._previousResultButton.title=WI.UIString("Find Previous (%s)").format(WI.findPreviousKeyboardShortcut.displayName);this._previousResultButton.addEventListener("click",this._previousResultButtonClicked.bind(this));this.element.appendChild(this._previousResultButton);let previousResultButtonGlyphElement=document.createElement("div");previousResultButtonGlyphElement.classList.add(WI.FindBanner.SegmentGlyphStyleClassName);this._previousResultButton.appendChild(previousResultButtonGlyphElement);this._nextResultButton=document.createElement("button");this._nextResultButton.classList.add("segmented","next-result");this._nextResultButton.disabled=true;this._nextResultButton.title=WI.UIString("Find Next (%s)").format(WI.findNextKeyboardShortcut.displayName);this._nextResultButton.addEventListener("click",this._nextResultButtonClicked.bind(this));this.element.appendChild(this._nextResultButton);let nextResultButtonGlyphElement=document.createElement("div");nextResultButtonGlyphElement.classList.add(WI.FindBanner.SegmentGlyphStyleClassName);this._nextResultButton.appendChild(nextResultButtonGlyphElement);if(this._alwaysShowing){this.element.classList.add(WI.FindBanner.ShowingStyleClassName);this._clearAndBlurKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape,this.clearAndBlur.bind(this),this.element);}else{let doneButtonElement=document.createElement("button");doneButtonElement.textContent=WI.UIString("Done");doneButtonElement.addEventListener("click",this._doneButtonClicked.bind(this));this.element.appendChild(doneButtonElement);this._hideKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape,this.hide.bind(this),this.element);}
this._numberOfResults=null;this._searchBackwards=false;this._searchKeyPressed=false;this._previousSearchValue="";} 
get delegate(){return this._delegate;}
set delegate(newDelegate){this._delegate=newDelegate||null;}
get inputField(){return this._inputField;}
get searchQuery(){return this._inputField.value||"";}
set searchQuery(query){this._inputField.value=query||"";}
get numberOfResults(){return this._numberOfResults;}
set numberOfResults(numberOfResults)
{if(numberOfResults===undefined||isNaN(numberOfResults))
numberOfResults=null;this._numberOfResults=numberOfResults;this._previousResultButton.disabled=this._nextResultButton.disabled=numberOfResults<=0;if(numberOfResults===null)
this._resultCountLabel.textContent="";else if(numberOfResults<=0)
this._resultCountLabel.textContent=WI.UIString("Not found");else if(numberOfResults===1)
this._resultCountLabel.textContent=WI.UIString("1 match");else if(numberOfResults>1)
this._resultCountLabel.textContent=WI.UIString("%d matches").format(numberOfResults);}
get targetElement()
{return this._targetElement;}
set targetElement(element)
{function delayedWork()
{oldTargetElement.classList.remove(WI.FindBanner.NoTransitionStyleClassName);this.element.classList.remove(WI.FindBanner.NoTransitionStyleClassName);}
if(this._targetElement){var oldTargetElement=this._targetElement;this._targetElement.classList.add(WI.FindBanner.NoTransitionStyleClassName);this._targetElement.classList.remove(WI.FindBanner.SupportsFindBannerStyleClassName);this._targetElement.classList.remove(WI.FindBanner.ShowingFindBannerStyleClassName);this.element.classList.add(WI.FindBanner.NoTransitionStyleClassName);if(!this._alwaysShowing)
this.element.classList.remove(WI.FindBanner.ShowingStyleClassName);setTimeout(delayedWork.bind(this),0);}
this._targetElement=element||null;if(this._targetElement)
this._targetElement.classList.add(WI.FindBanner.SupportsFindBannerStyleClassName);}
get showing()
{return this.element.classList.contains(WI.FindBanner.ShowingStyleClassName);}
focus()
{if(!this._inputField.value.length)
this._inputField.focus();else
this._inputField.select();}
clearAndBlur()
{this.numberOfResults=null;this._inputField.value="";this._previousSearchValue="";if(this._delegate.findBannerSearchCleared)
this._delegate.findBannerSearchCleared();if(this._delegate.findBannerWantsToClearAndBlur)
this._delegate.findBannerWantsToClearAndBlur();}
show()
{if(!this._targetElement)
return;if(!this._targetElement.parentNode)
return;if(this.element.parentNode!==this._targetElement.parentNode)
this._targetElement.parentNode.insertBefore(this.element,this._targetElement);function delayedWork()
{this._targetElement.classList.add(WI.FindBanner.ShowingFindBannerStyleClassName);this.element.classList.add(WI.FindBanner.ShowingStyleClassName);this._inputField.select();}

setTimeout(delayedWork.bind(this),0);this.dispatchEventToListeners(WI.FindBanner.Event.DidShow);}
hide()
{if(!this._targetElement)
return;this._inputField.blur();this._targetElement.classList.remove(WI.FindBanner.ShowingFindBannerStyleClassName);if(!this._alwaysShowing)
this.element.classList.remove(WI.FindBanner.ShowingStyleClassName);this.dispatchEventToListeners(WI.FindBanner.Event.DidHide);} 
_inputFieldKeyDown(event)
{if(event.keyIdentifier==="Shift")
this._searchBackwards=true;else if(event.keyIdentifier==="Enter")
this._searchKeyPressed=true;}
_inputFieldKeyUp(event)
{if(event.keyIdentifier==="Shift")
this._searchBackwards=false;else if(event.keyIdentifier==="Enter")
this._searchKeyPressed=false;}
_inputFieldSearch(event)
{if(this._inputField.value){if(this._previousSearchValue!==this.searchQuery){if(this._delegate&&typeof this._delegate.findBannerPerformSearch==="function")
this._delegate.findBannerPerformSearch(this,this.searchQuery);}else if(this._searchKeyPressed&&this._numberOfResults>0){if(this._searchBackwards){if(this._delegate&&typeof this._delegate.findBannerRevealPreviousResult==="function")
this._delegate.findBannerRevealPreviousResult(this);}else{if(this._delegate&&typeof this._delegate.findBannerRevealNextResult==="function")
this._delegate.findBannerRevealNextResult(this);}}}else{this.numberOfResults=null;if(this._delegate&&typeof this._delegate.findBannerSearchCleared==="function")
this._delegate.findBannerSearchCleared(this);}
this._previousSearchValue=this.searchQuery;}
_previousResultButtonClicked(event)
{if(this._delegate&&typeof this._delegate.findBannerRevealPreviousResult==="function")
this._delegate.findBannerRevealPreviousResult(this);}
_nextResultButtonClicked(event)
{if(this._delegate&&typeof this._delegate.findBannerRevealNextResult==="function")
this._delegate.findBannerRevealNextResult(this);}
_doneButtonClicked(event)
{this.hide();}};WI.FindBanner.SupportsFindBannerStyleClassName="supports-find-banner";WI.FindBanner.ShowingFindBannerStyleClassName="showing-find-banner";WI.FindBanner.NoTransitionStyleClassName="no-find-banner-transition";WI.FindBanner.ShowingStyleClassName="showing";WI.FindBanner.SegmentGlyphStyleClassName="glyph";WI.FindBanner.Event={DidShow:"find-banner-did-show",DidHide:"find-banner-did-hide"};WI.FlexibleSpaceNavigationItem=class FlexibleSpaceNavigationItem extends WI.NavigationItem
{constructor(navigationItem,alignItem)
{super();this._navigationItem=navigationItem||null;if(this._navigationItem){this._navigationItem=navigationItem;this.element.classList.add(alignItem||WI.FlexibleSpaceNavigationItem.Align.Start);}} 
get additionalClassNames()
{return["flexible-space"];}
update(options={})
{super.update(options);if(!this._navigationItem)
return;if(!options.expandOnly)
return;let flexibleWidth=this.width;if(!flexibleWidth)
return;this.element.appendChild(this._navigationItem.element);this._navigationItem.update(options);let itemWidth=this._navigationItem.width;let remainingWidth=flexibleWidth-itemWidth;if(remainingWidth<=0)
this.element.removeChild(this._navigationItem.element);}};WI.FlexibleSpaceNavigationItem.Align={Start:"align-start",End:"align-end",};WI.FontDetailsPanel=class FontDetailsPanel extends WI.StyleDetailsPanel
{constructor(delegate)
{const className="font";const identifier="font";const label=WI.UIString("Font","Font @ Font Details Sidebar Title","Title for the Font details sidebar.");super(delegate,className,identifier,label);this._fontPropertiesMap=new Map;this._fontVariationsMap=new Map;this._fontFeaturesMap=new Map;} 
get supportsToggleCSSClass()
{return false;}
refresh(significantChange)
{super.refresh(significantChange);let fontMap=this.nodeStyles.computedPrimaryFont?.calculateFontProperties(this.nodeStyles)??{};this._fontPropertiesMap=fontMap.propertiesMap??new Map;this._fontVariationsMap=fontMap.variationsMap??new Map;this._fontFeaturesMap=fontMap.featuresMap??new Map;this._fontNameRow.value=this.nodeStyles.computedPrimaryFont.name;this._fontSizeRow.value=this._formatSizeValue(this._fontPropertiesMap.get("font-size"));this._fontStyleRow.value=this._formatStyleValue(this._fontPropertiesMap.get("font-style"));this._fontWeightRow.value=this._formatSimpleSingleValue(this._fontPropertiesMap.get("font-weight"),"wght","%s");this._fontStretchRow.value=this._formatSimpleSingleValue(this._fontPropertiesMap.get("font-stretch"),"wdth",WI.UIString("%s%%","%s%% @ Font Details Sidebar","A single value expressed as a percentage where the value has already been converted from a number to a string."));this._fontVariantLigaturesRow.value=this._formatLigatureValue(this._fontPropertiesMap.get("font-variant-ligatures"));this._fontVariantPositionRow.value=this._formatPositionValue(this._fontPropertiesMap.get("font-variant-position"));this._fontVariantCapsRow.value=this._formatCapitalsValue(this._fontPropertiesMap.get("font-variant-caps"));this._fontVariantNumericRow.value=this._formatNumericValue(this._fontPropertiesMap.get("font-variant-numeric"));this._fontVariantAlternatesRow.value=this._formatAlternatesValue(this._fontPropertiesMap.get("font-variant-alternates"));this._fontVariantEastAsianRow.value=this._formatEastAsianValue(this._fontPropertiesMap.get("font-variant-east-asian"));let featureRows=[];for(let[key,value]of this._fontFeaturesMap)
featureRows.push(new WI.DetailsSectionSimpleRow(key,value));this._fontAdditionalFeaturesGroup.rows=featureRows;this._fontAdditionalFeaturesGroup.hidden=!featureRows.length;let variationRows=[];for(let[key,value]of this._fontVariationsMap){let name=value.name?WI.UIString("%s (%s)").format(value.name,key):key;variationRows.push(new WI.DetailsSectionSimpleRow(name,this._formatVariationValue(value)));}
if(!variationRows.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No additional variation axes.","No additional variation axes. @ Font Details Sidebar","Message shown when there are no additional variation axes to show."));emptyRow.showEmptyMessage();variationRows.push(emptyRow);}
this._fontVariationsGroup.rows=variationRows;} 
initialLayout()
{super.initialLayout(); this._fontNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name","Name @ Font Details Sidebar Property","Property title for the family name of the font."));let previewGroup=new WI.DetailsSectionGroup([this._fontNameRow]);let fontNameSection=new WI.DetailsSection("font-identity",WI.UIString("Identity","Identity @ Font Details Sidebar Section","Section title for font identity information."),[previewGroup]);this.element.appendChild(fontNameSection.element); this._fontSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Size","Size @ Font Details Sidebar Property","Property title for `font-size`."));this._fontStyleRow=new WI.DetailsSectionSimpleRow(WI.UIString("Style","Style @ Font Details Sidebar Property","Property title for `font-style`."));this._fontWeightRow=new WI.DetailsSectionSimpleRow(WI.UIString("Weight","Weight @ Font Details Sidebar Property","Property title for `font-weight`."));this._fontStretchRow=new WI.DetailsSectionSimpleRow(WI.UIString("Stretch","Stretch @ Font Details Sidebar Property","Property title for `font-stretch`."));let basicPropertiesGroup=new WI.DetailsSectionGroup([this._fontSizeRow,this._fontStyleRow,this._fontWeightRow,this._fontStretchRow]);let fontBasicPropertiesSection=new WI.DetailsSection("font-basic-properties",WI.UIString("Basic Properties","Basic Properties @ Font Details Sidebar Section","Section title for basic font properties."),[basicPropertiesGroup]);this.element.appendChild(fontBasicPropertiesSection.element); this._fontVariantLigaturesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Ligatures","Ligatures @ Font Details Sidebar Property","Property title for `font-variant-ligatures`."));this._fontVariantPositionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Position","Position @ Font Details Sidebar Property","Property title for `font-variant-position`."));this._fontVariantCapsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Capitals","Capitals @ Font Details Sidebar Property","Property title for `font-variant-caps`."));this._fontVariantNumericRow=new WI.DetailsSectionSimpleRow(WI.UIString("Numeric","Numeric @ Font Details Sidebar Property","Property title for `font-variant-numeric`."));this._fontVariantAlternatesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Alternate Glyphs","Alternate Glyphs @ Font Details Sidebar Property","Property title for `font-variant-alternates`."));this._fontVariantEastAsianRow=new WI.DetailsSectionSimpleRow(WI.UIString("East Asian","East Asian @ Font Details Sidebar Property","Property title for `font-variant-east-asian`."));let featurePropertiesGroup=new WI.DetailsSectionGroup([this._fontVariantLigaturesRow,this._fontVariantPositionRow,this._fontVariantCapsRow,this._fontVariantNumericRow,this._fontVariantAlternatesRow,this._fontVariantEastAsianRow]);this._fontAdditionalFeaturesGroup=new WI.DetailsSectionGroup;let fontFeaturePropertiesSection=new WI.DetailsSection("font-feature-properties",WI.UIString("Feature Properties","Feature Properties @ Font Details Sidebar Section","Section title for font feature properties."),[featurePropertiesGroup,this._fontAdditionalFeaturesGroup]);this.element.appendChild(fontFeaturePropertiesSection.element); this._fontVariationsGroup=new WI.DetailsSectionGroup;let fontVariationPropertiesSection=new WI.DetailsSection("font-variation-properties",WI.UIString("Variation Properties","Variation Properties @ Font Details Sidebar Section","Section title for font variation properties."),[this._fontVariationsGroup]);this.element.appendChild(fontVariationPropertiesSection.element);}
_formatSizeValue(property)
{return property.value;}
_formatStyleValue(property)
{if(this._hasVariationValue(property,"slnt"))
return WI.UIString("Oblique %ddeg","Oblique %ddeg @ Font Details Sidebar Property Value","Property value for oblique text.").format(-1*parseFloat(property.variations.get("slnt").value));if(this._hasVariationValue(property,"ital"))
return WI.UIString("Italic","Italic @ Font Details Sidebar Property Value","Property value for oblique text.");if(property.value==="normal")
return WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value.");return property.value;}
_formatSimpleSingleValue(property,variationTag,variationFormat)
{let result;if(this._hasVariationValue(property,variationTag))
result=variationFormat.format(this._formatAxisValueAsString(property.variations.get(variationTag).value));else
result=this._formatAxisValueAsString(property.value);if(this._hasVariationValue(property,variationTag,{optional:true})){let axis=property.variations.get(variationTag);return this._createVariationValueElement(result,axis.minimumValue,axis.maximumValue,axis.defaultValue);}
return result;}
_formatVariationValue(variation)
{let value=variation.value||variation.value===0?variation.value:variation.defaultValue;return this._createVariationValueElement(this._formatAxisValueAsString(value),variation.minimumValue,variation.maximumValue,variation.defaultValue);}
_createVariationValueElement(value,minimumValue,maximumValue,defaultValue)
{let valueElement=document.createElement("div");valueElement.textContent=value;let secondaryElement=valueElement.appendChild(document.createElement("span"));secondaryElement.className="secondary";secondaryElement.textContent=WI.UIString(" (Range: %s-%s, Default: %s)"," (Range: %s-%s, Default: %s) @ Font Details Sidebar","A range and default value for a single variation axis of a font.").format(this._formatAxisValueAsString(minimumValue),this._formatAxisValueAsString(maximumValue),this._formatAxisValueAsString(defaultValue));return valueElement;}
_formatAxisValueAsString(value)
{const options={minimumFractionDigits:0,maximumFractionDigits:2,useGrouping:false,}
return value.toLocaleString(undefined,options);}
_formatSimpleFeatureValues(property,features,noMatchesResult)
{let valueParts=property.value.match(WI.Font.SettingPattern);let results=[];let resultGroups=new Set;for(let feature of features){if((!feature.group||!resultGroups.has(feature.group))&&this._featureIsEnabled(property,feature.tag,valueParts.includes(feature.name))){results.push(feature.result);resultGroups.add(feature.group);}}
if(results.length)
return results.join(WI.UIString(", "));return noMatchesResult;}
_formatLigatureValue(property)
{let valueParts=property.value.match(WI.Font.SettingPattern);let results=[];if(!this._featureIsEnabled(property,WI.unlocalizedString("clig"),!valueParts.includes(WI.unlocalizedString("no-common-ligatures"))))
results.push(WI.UIString("Disabled Common","Disabled Common @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: no-common-ligatures`."));else
results.push(WI.UIString("Common","Common @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: common-ligatures`."));let otherResults=this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("dlig"),name:WI.unlocalizedString("discretionary-ligatures"),result:WI.UIString("Discretionary","Discretionary @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: discretionary-ligatures`."),},{tag:WI.unlocalizedString("hlig"),name:WI.unlocalizedString("historical-ligatures"),result:WI.UIString("Historical","Historical @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: historical-ligatures`."),},{tag:WI.unlocalizedString("calt"),name:WI.unlocalizedString("contextual"),result:WI.UIString("Contextual Alternates","Contextual Alternates @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: contextual`."),},]);if(otherResults)
results.push(otherResults);return results.join(WI.UIString(", "));}
_formatPositionValue(property)
{return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("subs"),name:WI.unlocalizedString("sub"),result:WI.UIString("Subscript","Subscript @ Font Details Sidebar Property Value","Property value for `font-variant-position: sub`."),group:"position",},{tag:WI.unlocalizedString("sups"),name:WI.unlocalizedString("super"),result:WI.UIString("Superscript","Superscript @ Font Details Sidebar Property Value","Property value for `font-variant-position: super`."),group:"position",},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));}
_formatCapitalsValue(property)
{return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("c2sc"),name:WI.unlocalizedString("all-small-caps"),result:WI.UIString("All Small Capitals","All Small Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: all-small-caps`."),group:"capitals",},{tag:WI.unlocalizedString("smcp"),name:WI.unlocalizedString("small-caps"),result:WI.UIString("Small Capitals","Small Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: small-caps`."),group:"capitals",},{tag:WI.unlocalizedString("c2pc"),name:WI.unlocalizedString("all-petite-caps"),result:WI.UIString("All Petite Capitals","All Petite Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: all-petite-caps`."),group:"capitals",},{tag:WI.unlocalizedString("pcap"),name:WI.unlocalizedString("petite-caps"),result:WI.UIString("Petite Capitals","Petite Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: petite-caps`."),group:"capitals",},{tag:WI.unlocalizedString("unic"),name:WI.unlocalizedString("unicase"),result:WI.UIString("Unicase","Unicase @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: unicase`."),group:"capitals",},{tag:WI.unlocalizedString("titl"),name:WI.unlocalizedString("titling-caps"),result:WI.UIString("Titling Capitals","Titling Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: titling-caps`."),group:"capitals",},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));}
_formatNumericValue(property)
{return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("lnum"),name:WI.unlocalizedString("lining-nums"),result:WI.UIString("Lining Numerals","Lining Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: lining-nums`."),group:"figures",},{tag:WI.unlocalizedString("onum"),name:WI.unlocalizedString("oldstyle-nums"),result:WI.UIString("Old-Style Numerals","Old-Style Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: oldstyle-nums`."),group:"figures",},{tag:WI.unlocalizedString("pnum"),name:WI.unlocalizedString("proportional-nums"),result:WI.UIString("Proportional Numerals","Proportional Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: proportional-nums`."),group:"spacing",},{tag:WI.unlocalizedString("tnum"),name:WI.unlocalizedString("tabular-nums"),result:WI.UIString("Tabular Numerals","Tabular Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: tabular-nums`."),group:"spacing",},{tag:WI.unlocalizedString("frac"),name:WI.unlocalizedString("diagonal-fractions"),result:WI.UIString("Diagonal Fractions","Diagonal Fractions @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: diagonal-fractions`."),group:"fractions",},{tag:WI.unlocalizedString("afrc"),name:WI.unlocalizedString("stacked-fractions"),result:WI.UIString("Stacked Fractions","Stacked Fractions @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: stacked-fractions`."),group:"fractions",},{tag:WI.unlocalizedString("ordn"),name:WI.unlocalizedString("ordinal"),result:WI.UIString("Ordinal Letter Forms","Ordinal Letter Forms @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: ordinal`."),},{tag:WI.unlocalizedString("zero"),name:WI.unlocalizedString("slashed-zero"),result:WI.UIString("Slashed Zeros","Slashed Zeros @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: slashed-zero`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));}
_formatAlternatesValue(property)
{return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("hist"),name:WI.unlocalizedString("historical-forms"),result:WI.UIString("Historical Forms","Historical Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: historical-forms`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));}
_formatEastAsianValue(property)
{return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("jp78"),name:WI.unlocalizedString("jis78"),result:WI.UIString("JIS78 Forms","JIS78 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis78`."),group:"forms",},{tag:WI.unlocalizedString("jp83"),name:WI.unlocalizedString("jis83"),result:WI.UIString("JIS83 Forms","JIS83 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis83`."),group:"forms",},{tag:WI.unlocalizedString("jp90"),name:WI.unlocalizedString("jis90"),result:WI.UIString("JIS90 Forms","JIS90 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis90`."),group:"forms",},{tag:WI.unlocalizedString("jp04"),name:WI.unlocalizedString("jis04"),result:WI.UIString("JIS2004 Forms","JIS2004 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis04`."),group:"forms",},{tag:WI.unlocalizedString("smpl"),name:WI.unlocalizedString("simplified"),result:WI.UIString("Simplified Forms","Simplified Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: simplified`."),group:"forms",},{tag:WI.unlocalizedString("trad"),name:WI.unlocalizedString("traditional"),result:WI.UIString("Traditional Forms","Traditional Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: traditional`."),group:"forms",},{tag:WI.unlocalizedString("fwid"),name:WI.unlocalizedString("full-width"),result:WI.UIString("Full-Width Variants","Full-Width Variants @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: full-width`."),group:"width",},{tag:WI.unlocalizedString("pwid"),name:WI.unlocalizedString("proportional-width"),result:WI.UIString("Proportional-Width Variants","Proportional-Width Variants @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: proportional-width`."),group:"width",},{tag:WI.unlocalizedString("ruby"),name:WI.unlocalizedString("ruby"),result:WI.UIString("Ruby Glyphs","Ruby Glyphs @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: ruby`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));}
_featureIsEnabled(property,featureTag,tagNotPresentCondition)
{let featureValue=property.features?.get(featureTag);if(featureValue||featureValue===0)
return!!featureValue;return tagNotPresentCondition;}
_hasVariationValue(property,variationTag,{optional}={})
{if(property.variations?.has(variationTag))
return property.variations.get(variationTag).value||optional;return false;}};WI.FontDetailsSidebarPanel=class FontDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel
{constructor()
{super("style-font",WI.UIString("Font"),WI.FontDetailsPanel);}};WI.FontResourceContentView=class FontResourceContentView extends WI.ResourceContentView
{constructor(resource)
{super(resource,"font");this._styleElement=null;this._previewElement=null;this._previewContainer=null;} 
sizeToFit()
{if(!this._previewElement)
return;for(var fontSize=WI.FontResourceContentView.MaximumFontSize;fontSize>=WI.FontResourceContentView.MinimumFontSize;fontSize-=5){this._previewElement.style.fontSize=fontSize+"px";if(this._previewElement.offsetWidth<=this.element.offsetWidth)
break;}}
contentAvailable(content,base64Encoded)
{this._fontObjectURL=this.resource.createObjectURL();if(!this._fontObjectURL){this.showGenericErrorMessage();return;}
this.removeLoadingIndicator();this._previewContainer=this.element.appendChild(document.createElement("div"));this._previewContainer.className="preview-container";this._updatePreviewElement();if(WI.NetworkManager.supportsOverridingResponses()){let dropZoneView=new WI.DropZoneView(this);dropZoneView.targetElement=this._previewContainer;this.addSubview(dropZoneView);if(this.resource.localResourceOverride)
this.resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._handleLocalResourceContentDidChange,this);}}
attached()
{super.attached();if(this._styleElement)
document.head.appendChild(this._styleElement);}
detached()
{if(this._styleElement)
this._styleElement.remove();super.detached();}
closed()
{


if(this._fontObjectURL)
URL.revokeObjectURL(this._fontObjectURL);super.closed();} 
layout()
{this.sizeToFit();} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{let existingOverrides=WI.networkManager.localResourceOverridesForURL(this.resource.url);if(existingOverrides.length>1)
return false;let localResourceOverride=this.resource.localResourceOverride||existingOverrides[0];if(localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.Request)
return false;return event.dataTransfer.types.includes("Files");}
dropZoneHandleDragEnter(dropZone,event)
{if(this.resource.localResourceOverride)
dropZone.text=WI.UIString("Update Font");else if(WI.networkManager.localResourceOverridesForURL(this.resource.url).length)
dropZone.text=WI.UIString("Update Local Override");else
dropZone.text=WI.UIString("Create Local Override");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readData(files,async({dataURL,mimeType,base64Encoded,content})=>{let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this.resource.url)[0];if(!localResourceOverride){localResourceOverride=await this.resource.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response);WI.networkManager.addLocalResourceOverride(localResourceOverride);}
let revision=localResourceOverride.localResource.editableRevision;revision.updateRevisionContent(content,{base64Encoded,mimeType});if(!this.resource.localResourceOverride)
WI.showLocalResourceOverride(localResourceOverride);});} 
_updatePreviewElement()
{if(this._styleElement)
this._styleElement.remove();if(this._previewElement)
this._previewElement.remove();const uniqueFontName="WebInspectorFontPreview"+(++WI.FontResourceContentView._uniqueFontIdentifier);let format="";if(this.resource.mimeTypeComponents.type==="image/svg+xml")
format=" format(\"svg\")";this._styleElement=document.createElement("style");this._styleElement.textContent=`@font-face { font-family: "${uniqueFontName}"; src: url(${this._fontObjectURL}) ${format}; }`;if(this.isAttached)
document.head.appendChild(this._styleElement);this._previewElement=document.createElement("div");this._previewElement.className="preview";this._previewElement.style.fontFamily=uniqueFontName;function createMetricElement(className){let metricElement=document.createElement("div");metricElement.className="metric "+className;return metricElement;}
for(let line of WI.FontResourceContentView.PreviewLines){let lineElement=document.createElement("div");lineElement.className="line";lineElement.appendChild(createMetricElement("top"));lineElement.appendChild(createMetricElement("xheight"));lineElement.appendChild(createMetricElement("middle"));lineElement.appendChild(createMetricElement("baseline"));lineElement.appendChild(createMetricElement("bottom"));let contentElement=document.createElement("div");contentElement.className="content";contentElement.textContent=line;lineElement.appendChild(contentElement);this._previewElement.appendChild(lineElement);}
this._previewContainer.appendChild(this._previewElement);this.sizeToFit();}
_handleLocalResourceContentDidChange(event)
{this._fontObjectURL=this.resource.createObjectURL();this._updatePreviewElement();}};WI.FontResourceContentView._uniqueFontIdentifier=0;WI.FontResourceContentView.PreviewLines=["ABCDEFGHIJKLM","NOPQRSTUVWXYZ","abcdefghijklm","nopqrstuvwxyz","1234567890"];WI.FontResourceContentView.MaximumFontSize=72;WI.FontResourceContentView.MinimumFontSize=12;WI.FormattedValue={};WI.FormattedValue.MaxPreviewStringLength=140;WI.FormattedValue.isSimpleString=function(string)
{return string.length<=WI.FormattedValue.MaxPreviewStringLength&&!string.slice(0,WI.FormattedValue.MaxPreviewStringLength).includes("\n");};WI.FormattedValue.hasSimpleDisplay=function(object)
{switch(object.type){case"boolean":case"number":case"symbol":case"bigint":case"undefined":return true;case"string":return WI.FormattedValue.isSimpleString(object.description);case"function":return false;case"object":var subtype=object.subtype;return subtype==="null"||subtype==="regexp"||subtype==="date";}
return false;};WI.FormattedValue.classNameForTypes=function(type,subtype)
{return"formatted-"+(subtype?subtype:type);};WI.FormattedValue.classNameForObject=function(object)
{return WI.FormattedValue.classNameForTypes(object.type,object.subtype);};WI.FormattedValue.createLinkifiedElementString=function(string)
{var span=document.createElement("span");span.className="formatted-string";span.append("\"",WI.linkifyStringAsFragment(string.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")),"\"");return span;};WI.FormattedValue.createElementForNode=function(object)
{var span=document.createElement("span");span.className="formatted-node";object.pushNodeToFrontend(function(nodeId){if(!nodeId){span.textContent=object.description;return;}
var treeOutline=new WI.DOMTreeOutline;treeOutline.setVisible(true);treeOutline.rootDOMNode=WI.domManager.nodeForId(nodeId);if(!treeOutline.children[0].hasChildren)
treeOutline.element.classList.add("single-node");span.appendChild(treeOutline.element);});return span;};WI.FormattedValue.createElementForError=function(object)
{var span=document.createElement("span");span.classList.add("formatted-error");span.textContent=object.description;if(!object.preview)
return span;function previewToObject(preview)
{var result={};for(var property of preview.propertyPreviews)
result[property.name]=property.value;return result;}
var preview=previewToObject(object.preview);if(!preview.sourceURL)
return span;var sourceLinkWithPrefix=WI.ErrorObjectView.makeSourceLinkWithPrefix(preview.sourceURL,preview.line,preview.column);span.append(sourceLinkWithPrefix);return span;};WI.FormattedValue.createElementForNodePreview=function(preview,{remoteObjectAccessor}={})
{var value=preview.value||preview.description;var span=document.createElement("span");span.className="formatted-node-preview syntax-highlighted";if(remoteObjectAccessor){let domNode=null;span.addEventListener("mouseenter",(event)=>{if(domNode){domNode.highlight();return;}
remoteObjectAccessor((remoteObject)=>{remoteObject.pushNodeToFrontend((nodeId)=>{domNode=WI.domManager.nodeForId(nodeId);if(domNode)
domNode.highlight();});});});span.addEventListener("mouseleave",(event)=>{WI.domManager.hideDOMNodeHighlight();});span.addEventListener("contextmenu",(event)=>{if(!domNode)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNode(contextMenu,domNode);});}
if(value.startsWith("<!--")){var comment=span.appendChild(document.createElement("span"));comment.className="html-comment";comment.textContent=value;return span;}
if(value.startsWith("<!DOCTYPE")){var doctype=span.appendChild(document.createElement("span"));doctype.className="html-doctype";doctype.textContent=value;return span;}
var matches=value.match(/^<(\S+?)(?: (\S+?)="(.*?)")?>$/);if(!matches){span.textContent=value;return span;}
var tag=document.createElement("span");tag.className="html-tag";tag.append("<");var tagName=tag.appendChild(document.createElement("span"));tagName.className="html-tag-name";tagName.textContent=matches[1];if(matches[2]){tag.append(" ");var attribute=tag.appendChild(document.createElement("span"));attribute.className="html-attribute";var attributeName=attribute.appendChild(document.createElement("span"));attributeName.className="html-attribute-name";attributeName.textContent=matches[2];attribute.append("=\"");var attributeValue=attribute.appendChild(document.createElement("span"));attributeValue.className="html-attribute-value";attributeValue.textContent=matches[3];attribute.append("\"");}
tag.append(">");span.appendChild(tag);return span;};WI.FormattedValue.createElementForFunctionWithName=function(description)
{var span=document.createElement("span");span.classList.add("formatted-function");span.textContent=description.substring(0,description.indexOf("("));return span;};WI.FormattedValue.createElementForTypesAndValue=function(type,subtype,displayString,size,isPreview,hadException)
{var span=document.createElement("span");span.classList.add(WI.FormattedValue.classNameForTypes(type,subtype));if(hadException){span.textContent="[Exception: "+displayString+"]";return span;}
if(type==="string"){displayString=displayString.truncate(WI.FormattedValue.MaxPreviewStringLength);span.textContent=doubleQuotedString(displayString.replace(/\n/g,"\u21B5"));return span;}
if(type==="function"){if(subtype==="class")
span.textContent=displayString;else
span.textContent=isPreview?"function":displayString;return span;}
span.textContent=displayString;if(size!==undefined&&(subtype==="array"||subtype==="set"||subtype==="map"||subtype==="weakmap"||subtype==="weakset")){var sizeElement=span.appendChild(document.createElement("span"));sizeElement.className="size";sizeElement.textContent=" ("+size+")";}
return span;};WI.FormattedValue.createElementForRemoteObject=function(object,hadException)
{return WI.FormattedValue.createElementForTypesAndValue(object.type,object.subtype,object.description,object.size,false,hadException);};WI.FormattedValue.createElementForObjectPreview=function(objectPreview)
{return WI.FormattedValue.createElementForTypesAndValue(objectPreview.type,objectPreview.subtype,objectPreview.description,objectPreview.size,true,false);};WI.FormattedValue.createElementForPropertyPreview=function(propertyPreview)
{return WI.FormattedValue.createElementForTypesAndValue(propertyPreview.type,propertyPreview.subtype,propertyPreview.value,undefined,true,false);};WI.FormattedValue.createObjectPreviewOrFormattedValueForObjectPreview=function(objectPreview,previewViewMode)
{if(objectPreview.subtype==="node")
return WI.FormattedValue.createElementForNodePreview(objectPreview);if(objectPreview.type==="function")
return WI.FormattedValue.createElementForFunctionWithName(objectPreview.description);const object=null;return new WI.ObjectPreviewView(object,objectPreview,previewViewMode).element;};WI.FormattedValue.createObjectPreviewOrFormattedValueForRemoteObject=function(object,previewViewMode)
{if(object.subtype==="node")
return WI.FormattedValue.createElementForNode(object);if(object.subtype==="error")
return WI.FormattedValue.createElementForError(object);if(object.preview)
return new WI.ObjectPreviewView(object,object.preview,previewViewMode);return WI.FormattedValue.createElementForRemoteObject(object);};WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject=function(object,propertyPath,forceExpanding)
{if(object.subtype==="node")
return WI.FormattedValue.createElementForNode(object);if(object.subtype==="null")
return WI.FormattedValue.createElementForRemoteObject(object);if(object.type==="object"||object.subtype==="class"){var objectTree=new WI.ObjectTreeView(object,null,propertyPath,forceExpanding);return objectTree.element;}
return WI.FormattedValue.createElementForRemoteObject(object);};WI.FrameDOMTreeContentView=class FrameDOMTreeContentView extends WI.DOMTreeContentView
{constructor(domTree)
{super(domTree);this._domTree=domTree;this._domTree.addEventListener(WI.DOMTree.Event.RootDOMNodeInvalidated,this._rootDOMNodeInvalidated,this);this._requestRootDOMNode();} 
get domTree()
{return this._domTree;}
closed()
{this._domTree.removeEventListener(WI.DOMTree.Event.RootDOMNodeInvalidated,this._rootDOMNodeInvalidated,this);super.closed();}
getSearchContextNodes(callback)
{this._domTree.requestRootDOMNode(function(rootDOMNode){callback([rootDOMNode.id]);});} 
_rootDOMNodeAvailable(rootDOMNode)
{if(this.isClosed)
return;this.domTreeOutline.rootDOMNode=rootDOMNode;if(!rootDOMNode){this.domTreeOutline.selectDOMNode(null,false);return;}
this._restoreBreakpointsAfterUpdate();this._restoreSelectedNodeAfterUpdate(this._domTree.frame.url,rootDOMNode.body||rootDOMNode.documentElement||rootDOMNode.firstChild);}
_rootDOMNodeInvalidated(event)
{this._requestRootDOMNode();}
_requestRootDOMNode()
{this._domTree.requestRootDOMNode(this._rootDOMNodeAvailable.bind(this));}};WI.FrameTreeElement=class FrameTreeElement extends WI.ResourceTreeElement
{constructor(frame)
{super(frame.mainResource,frame);this._frame=frame;this._updateExpandedSetting();frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceWasAdded,this);frame.addEventListener(WI.Frame.Event.ResourceWasRemoved,this._resourceWasRemoved,this);frame.addEventListener(WI.Frame.Event.ExtraScriptAdded,this._extraScriptAdded,this);frame.addEventListener(WI.Frame.Event.ChildFrameWasAdded,this._childFrameWasAdded,this);frame.addEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._childFrameWasRemoved,this);this.shouldRefreshChildren=true;this.folderSettingsKey=this._frame.url.hash;this.registerFolderizeSettings("frames",WI.UIString("Frames"),this._frame.childFrameCollection,WI.FrameTreeElement);this.registerFolderizeSettings("extra-scripts",WI.UIString("Extra Scripts"),this._frame.extraScriptCollection,WI.ScriptTreeElement);function forwardingConstructor(representedObject,...extraArguments){if(representedObject instanceof WI.CSSStyleSheet)
return new WI.CSSStyleSheetTreeElement(representedObject,...extraArguments);return new WI.ResourceTreeElement(representedObject,...extraArguments);}
for(let[key,value]of Object.entries(WI.Resource.Type)){let folderName=WI.Resource.displayNameForType(value,true);let treeElementConstructor=forwardingConstructor;if(value===WI.Resource.Type.WebSocket)
treeElementConstructor=WI.WebSocketResourceTreeElement;this.registerFolderizeSettings(key,folderName,this._frame.resourceCollectionForType(value),treeElementConstructor);}
this.updateParentStatus();} 
get frame()
{return this._frame;}
descendantResourceTreeElementTypeDidChange(resourceTreeElement,oldType)
{
this._addTreeElement(resourceTreeElement);}
descendantResourceTreeElementMainTitleDidChange(resourceTreeElement,oldMainTitle)
{
this._addTreeElement(resourceTreeElement);}
updateSourceMapResources()
{if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren)
return;if(!this._frame)
return;this.updateParentStatus();if(this.resource&&this.resource.sourceMaps.length)
this.shouldRefreshChildren=true;}
onattach()
{WI.GeneralTreeElement.prototype.onattach.call(this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._styleSheetAdded,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._styleSheetRemoved,this);}
ondetach()
{WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetAdded,this._styleSheetAdded,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._styleSheetRemoved,this);super.ondetach();}
compareChildTreeElements(a,b)
{if(a===b)
return 0;var aIsResource=a instanceof WI.ResourceTreeElement;var bIsResource=b instanceof WI.ResourceTreeElement;if(aIsResource&&bIsResource)
return WI.ResourceTreeElement.compareResourceTreeElements(a,b);if(!aIsResource&&!bIsResource){return super.compareChildTreeElements(a,b);}
return aIsResource?1:-1;}
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();this.updateParentStatus();this.prepareToPopulate();for(let frame of this._frame.childFrameCollection)
this.addChildForRepresentedObject(frame);for(let resource of this._frame.resourceCollection)
this.addChildForRepresentedObject(resource);var sourceMaps=this.resource&&this.resource.sourceMaps;for(var i=0;i<sourceMaps.length;++i){var sourceMap=sourceMaps[i];for(var j=0;j<sourceMap.resources.length;++j)
this.addChildForRepresentedObject(sourceMap.resources[j]);}
for(let extraScript of this._frame.extraScriptCollection){if(extraScript.sourceURL||extraScript.sourceMappingURL)
this.addChildForRepresentedObject(extraScript);}
for(let styleSheet of WI.cssManager.inspectorStyleSheetsForFrame(this._frame))
this.addChildForRepresentedObject(styleSheet);}
onexpand()
{this._expandedSetting.value=true;}
oncollapse()
{if(this.hasChildren)
this._expandedSetting.value=false;} 
get mainTitleText()
{if(this.resource.parentFrame.name)
return WI.UIString("%s (%s)").format(this.resource.parentFrame.name,super.mainTitleText);return super.mainTitleText;} 
_updateExpandedSetting()
{this._expandedSetting=new WI.Setting("frame-expanded-"+this._frame.url.hash,this._frame.isMainFrame()?true:false);if(this._expandedSetting.value)
this.expand();else
this.collapse();}
_mainResourceDidChange(event)
{this._updateResource(this._frame.mainResource);this.updateParentStatus();this.removeChildren();
this._updateExpandedSetting();this.shouldRefreshChildren=true;}
_resourceWasAdded(event)
{this.addRepresentedObjectToNewChildQueue(event.data.resource);}
_resourceWasRemoved(event)
{this.removeChildForRepresentedObject(event.data.resource);}
_extraScriptAdded(event)
{let extraScript=event.data.script;if(extraScript.sourceURL||extraScript.sourceMappingURL)
this.addRepresentedObjectToNewChildQueue(extraScript);}
_childFrameWasAdded(event)
{this.addRepresentedObjectToNewChildQueue(event.data.childFrame);}
_childFrameWasRemoved(event)
{this.removeChildForRepresentedObject(event.data.childFrame);}
_styleSheetAdded(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author||styleSheet.injected||styleSheet.anonymous)
return;this.addRepresentedObjectToNewChildQueue(styleSheet);}
_styleSheetRemoved(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author||styleSheet.injected||styleSheet.anonymous)
return;this.removeChildForRepresentedObject(styleSheet);}};


WI.GaugeChart=class GaugeChart extends WI.View
{constructor({height,strokeWidth,segments})
{super();strokeWidth=strokeWidth||10;this._needleValue=null;const needleOverhangSpace=10;const needleUnderhangSpace=8;this._center=height-needleUnderhangSpace;this._radius=height-needleUnderhangSpace-needleOverhangSpace-1;this._innerRadius=Math.floor(this._radius-strokeWidth);let width=(this._radius+needleOverhangSpace+1)*2;this._size=new WI.Size(width,height);this._segments=segments;this.element.classList.add("gauge-chart");this._chartElement=this.element.appendChild(createSVGElement("svg"));this._chartElement.setAttribute("width",width);this._chartElement.setAttribute("height",height);this._chartElement.setAttribute("viewBox",`0 0 ${width} ${height}`);this._needleElement=null;} 
get size(){return this._size;}
get segments(){return this._segments;}
get value()
{return this._needleValue;}
set value(value)
{this._needleValue=value;}
clear()
{this._needleValue=null;} 
initialLayout()
{super.initialLayout();let startAngle=Math.PI;const onePercentAngle=Math.PI/100;for(let{className,limit}of this._segments){let offset=limit===100?0:1;let endAngle=Math.PI+(((limit-offset)/100)*Math.PI);let pathElement=this._chartElement.appendChild(createSVGElement("path"));pathElement.classList.add("segment",className);pathElement.setAttribute("d",this._createSegmentPathData(this._center,startAngle,endAngle,this._radius,this._innerRadius));startAngle=endAngle+onePercentAngle;}
const needlePointExtraDraw=0.5;const needleBaseExtraDraw=4.5;const needleUnderhangDraw=6;let midX=this.size.width/2;let midY=this._center;this._needleElement=this._chartElement.appendChild(createSVGElement("polygon"));this._needleElement.classList.add("needle");this._needleElement.setAttribute("points",`0,${midY + needlePointExtraDraw}, 0,${midY - needlePointExtraDraw} ${midX + needleUnderhangDraw},${midY - needleBaseExtraDraw} ${midX + needleUnderhangDraw},${midY + needleBaseExtraDraw}`);this._needleElement.style.transformOrigin=`${midX}px ${midY}px`;}
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;let empty=this._needleValue===null;this.element.classList.toggle("empty",empty);let value=empty?0:this._needleValue;let degrees=180*(value/100);this._needleElement.style.transform=`rotate(${degrees}deg)`;} 
_validateSegments(segments)
{let lastLimit=-1;for(let{className,limit}of segments){lastLimit=limit;}
return true;}
_createSegmentPathData(c,a1,a2,r1,r2)
{const startIndicatorUnderhang=7;let r3=(r2-startIndicatorUnderhang);let onePercentArc=Math.PI/100;let largeArcFlag=((a2-a1)%(Math.PI*2))>Math.PI?1:0;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1+onePercentArc)*r2,y4=c+Math.sin(a1+onePercentArc)*r2,x5=c+Math.cos(a1+onePercentArc)*r3,y5=c+Math.sin(a1+onePercentArc)*r3,x6=c+Math.cos(a1)*r3,y6=c+Math.sin(a1)*r3;return["M",x1,y1,"A",r1,r1,0,largeArcFlag,1,x2,y2,"L",x3,y3,"A",r2,r2,0,largeArcFlag,0,x4,y4,"L",x5,y5,"A",r3,r3,0,largeArcFlag,0,x6,y6,"Z"].join(" ");}};WI.GeneralTreeElementPathComponent=class GeneralTreeElementPathComponent extends WI.HierarchicalPathComponent
{constructor(generalTreeElement)
{super(generalTreeElement.mainTitle,generalTreeElement.classNames,generalTreeElement.representedObject);this._generalTreeElement=generalTreeElement;this._generalTreeElement.addEventListener(WI.GeneralTreeElement.Event.MainTitleDidChange,this._mainTitleDidChange,this);} 
get generalTreeElement(){return this._generalTreeElement;}
get previousSibling()
{let previousSibling=this._generalTreeElement.previousSibling;while(previousSibling&&previousSibling.hidden)
previousSibling=previousSibling.previousSibling;if(!previousSibling)
return null;return new WI.GeneralTreeElementPathComponent(previousSibling);}
get nextSibling()
{let nextSibling=this._generalTreeElement.nextSibling;while(nextSibling&&nextSibling.hidden)
nextSibling=nextSibling.nextSibling;if(!nextSibling)
return null;return new WI.GeneralTreeElementPathComponent(nextSibling);} 
_mainTitleDidChange(event)
{this.displayName=this._generalTreeElement.mainTitle;}};WI.GenericResourceContentView=class GenericResourceContentView extends WI.ResourceContentView
{constructor(resource)
{super(resource,"generic");}};WI.GoToLineDialog=class GoToLineDialog extends WI.Dialog
{constructor(delegate)
{super(delegate);this.element.classList.add("go-to-line-dialog");let field=this.element.appendChild(document.createElement("div"));this._input=field.appendChild(document.createElement("input"));this._input.type="text";this._input.placeholder=WI.UIString("Line Number");this._input.spellcheck=false;this._clearIcon=field.appendChild(document.createElement("img"));this._input.addEventListener("input",this);this._input.addEventListener("keydown",this);this._input.addEventListener("blur",this);this._clearIcon.addEventListener("mousedown",this);this._clearIcon.addEventListener("click",this);this._dismissing=false;} 
handleEvent(event)
{switch(event.type){case"input":this._handleInputEvent(event);break;case"keydown":this._handleKeydownEvent(event);break;case"blur":this._handleBlurEvent(event);break;case"mousedown":this._handleMousedownEvent(event);break;case"click":this._handleClickEvent(event);break;}}
didPresentDialog()
{this._input.focus();this._clear();} 
_handleInputEvent(event)
{let force=this._input.value!=="";this.element.classList.toggle(WI.GoToLineDialog.NonEmptyClassName,force);}
_handleKeydownEvent(event)
{if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode){if(this._input.value===""){this.dismiss();event.preventDefault();}else
this._clear();event.preventDefault();}else if(event.keyCode===WI.KeyboardShortcut.Key.Enter.keyCode){let value=parseInt(this._input.value,10);if(this.representedObjectIsValid(value)){this.dismiss(value);event.preventDefault();return;}
this._input.select();InspectorFrontendHost.beep();}}
_handleBlurEvent(event)
{this.dismiss();}
_handleMousedownEvent(event)
{this._input.select();
event.preventDefault();}
_handleClickEvent(event)
{this._clear();}
_clear()
{this._input.value="";this.element.classList.remove(WI.GoToLineDialog.NonEmptyClassName);}};WI.GoToLineDialog.NonEmptyClassName="non-empty";WI.GradientEditor=class GradientEditor extends WI.Object
{constructor()
{super();this._element=document.createElement("div");this._element.classList.add("gradient-editor");this._gradient=null;this._gradientTypes={"linear-gradient":{type:WI.LinearGradient,label:WI.UIString("Linear Gradient"),repeats:false},"radial-gradient":{type:WI.RadialGradient,label:WI.UIString("Radial Gradient"),repeats:false},"repeating-linear-gradient":{type:WI.LinearGradient,label:WI.UIString("Repeating Linear Gradient"),repeats:true},"repeating-radial-gradient":{type:WI.RadialGradient,label:WI.UIString("Repeating Radial Gradient"),repeats:true}};this._editingColor=false;this._gradientTypePicker=this._element.appendChild(document.createElement("select"));this._gradientTypePicker.classList.add("gradient-type-select");for(let type in this._gradientTypes){let option=this._gradientTypePicker.appendChild(document.createElement("option"));option.value=type;option.text=this._gradientTypes[type].label;}
this._gradientTypePicker.addEventListener("change",this._gradientTypeChanged.bind(this));this._gradientSlider=new WI.GradientSlider(this);this._element.appendChild(this._gradientSlider.element);this._colorPicker=new WI.ColorPicker;this._colorPicker.colorSquare.dimension=195;this._colorPicker.enableColorComponentInputs=false;this._colorPicker.addEventListener(WI.ColorPicker.Event.ColorChanged,this._colorPickerColorChanged,this);let angleContainerElement=this._element.appendChild(document.createElement("div"));angleContainerElement.classList.add("gradient-angle");angleContainerElement.append(WI.UIString("Angle"));let boundAngleValueChanged=this._angleValueChanged.bind(this);this._angleSliderElement=angleContainerElement.appendChild(document.createElement("input"));this._angleSliderElement.type="range";this._angleSliderElement.addEventListener("input",boundAngleValueChanged);this._angleInputElement=angleContainerElement.appendChild(document.createElement("input"));this._angleInputElement.type="number";this._angleInputElement.addEventListener("input",boundAngleValueChanged);this._angleUnitsSelectElement=angleContainerElement.appendChild(document.createElement("select"));this._angleUnitsSelectElement.addEventListener("change",this._angleUnitsChanged.bind(this));const angleUnitsData=[{name:WI.LinearGradient.AngleUnits.DEG,min:0,max:360,step:1},{name:WI.LinearGradient.AngleUnits.RAD,min:0,max:2*Math.PI,step:0.01},{name:WI.LinearGradient.AngleUnits.GRAD,min:0,max:400,step:1},{name:WI.LinearGradient.AngleUnits.TURN,min:0,max:1,step:0.01}];this._angleUnitsConfiguration=new Map(angleUnitsData.map(({name,min,max,step})=>{let optionElement=this._angleUnitsSelectElement.appendChild(document.createElement("option"));optionElement.value=optionElement.textContent=name;return[name,{element:optionElement,min,max,step}];}));}
get element()
{return this._element;}
set gradient(gradient)
{if(!gradient)
return;const isLinear=gradient instanceof WI.LinearGradient;const isRadial=gradient instanceof WI.RadialGradient;if(!isLinear&&!isRadial)
return;this._gradient=gradient;this._gradientSlider.stops=this._gradient.stops;if(isLinear){this._gradientTypePicker.value=this._gradient.repeats?"repeating-linear-gradient":"linear-gradient";this._angleUnitsChanged();}else
this._gradientTypePicker.value=this._gradient.repeats?"repeating-radial-gradient":"radial-gradient";this._updateCSSClassForGradientType();}
get gradient()
{return this._gradient;} 
gradientSliderStopsDidChange(gradientSlider)
{this._gradient.stops=gradientSlider.stops;this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});}
gradientSliderStopWasSelected(gradientSlider,stop)
{const selectedStop=gradientSlider.selectedStop;if(selectedStop&&!this._editingColor){this._element.appendChild(this._colorPicker.element);this._element.classList.add("editing-color");this._colorPicker.color=selectedStop.color;this._editingColor=true;}else if(!selectedStop){this._colorPicker.element.remove();this._element.classList.remove("editing-color");this._editingColor=false;}

this._angleInputElement.blur();this.dispatchEventToListeners(WI.GradientEditor.Event.ColorPickerToggled);this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});} 
_updateCSSClassForGradientType()
{const isRadial=this._gradient instanceof WI.RadialGradient;this._element.classList.toggle("radial-gradient",isRadial);this.dispatchEventToListeners(WI.GradientEditor.Event.ColorPickerToggled);}
_gradientTypeChanged(event)
{const descriptor=this._gradientTypes[this._gradientTypePicker.value];if(!(this._gradient instanceof descriptor.type)){if(descriptor.type===WI.LinearGradient){this._gradient=new WI.LinearGradient({value:180,units:WI.LinearGradient.AngleUnits.DEG},this._gradient.stops);this._angleUnitsChanged();}else
this._gradient=new WI.RadialGradient("",this._gradient.stops);this._updateCSSClassForGradientType();}
this._gradient.repeats=descriptor.repeats;this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});}
_colorPickerColorChanged(event)
{this._gradientSlider.selectedStop.color=event.target.color;this._gradientSlider.stops=this._gradient.stops;this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});}
_angleValueChanged(event)
{switch(event.target){case this._angleInputElement:this._gradient.angleValue=this._angleSliderElement.value=parseFloat(this._angleInputElement.value)||0;break;case this._angleSliderElement:this._gradient.angleValue=this._angleInputElement.value=parseFloat(this._angleSliderElement.value)||0;break;default:WI.reportInternalError("Input event fired for disabled color component input");return;}
this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});}
_angleUnitsChanged(event)
{let units=this._angleUnitsSelectElement.value;let configuration=this._angleUnitsConfiguration.get(units);if(!configuration){WI.reportInternalError(`Missing configuration data for selected angle units "${units}"`);return;}
this._gradient.angleUnits=units;this._angleInputElement.min=this._angleSliderElement.min=configuration.min;this._angleInputElement.max=this._angleSliderElement.max=configuration.max;this._angleInputElement.step=this._angleSliderElement.step=configuration.step;this._angleInputElement.value=this._angleSliderElement.value=this._gradient.angleValue;this.dispatchEventToListeners(WI.GradientEditor.Event.GradientChanged,{gradient:this._gradient});}};WI.GradientEditor.Event={GradientChanged:"gradient-editor-gradient-changed",ColorPickerToggled:"gradient-editor-color-picker-toggled"};WI.GradientSlider=class GradientSlider extends WI.Object
{constructor(delegate)
{super();this.delegate=delegate;this._element=null;this._stops=[];this._knobs=[];this._selectedKnob=null;this._canvas=document.createElement("canvas");this._keyboardShortcutEsc=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape);} 
get element()
{if(!this._element){this._element=document.createElement("div");this._element.className="gradient-slider";this._element.appendChild(this._canvas);this._addArea=this._element.appendChild(document.createElement("div"));this._addArea.addEventListener("mouseover",this);this._addArea.addEventListener("mousemove",this);this._addArea.addEventListener("mouseout",this);this._addArea.addEventListener("click",this);this._addArea.className=WI.GradientSlider.AddAreaClassName;}
return this._element;}
get stops()
{return this._stops;}
set stops(stops)
{this._stops=stops;this._updateStops();}
get selectedStop()
{return this._selectedKnob?this._selectedKnob.stop:null;} 
handleEvent(event)
{switch(event.type){case"mouseover":this._handleMouseover(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseout":this._handleMouseout(event);break;case"click":this._handleClick(event);break;}}
handleKeydownEvent(event)
{if(!this._keyboardShortcutEsc.matchesEvent(event)||!this._selectedKnob||!this._selectedKnob.selected)
return false;this._selectedKnob.selected=false;return true;}
knobXDidChange(knob)
{knob.stop.offset=knob.x/WI.GradientSlider.Width;this._sortStops();this._updateCanvas();}
knobCanDetach(knob)
{return this._knobs.length>2;}
knobWillDetach(knob)
{knob.element.classList.add(WI.GradientSlider.DetachingClassName);this._stops.remove(knob.stop);this._knobs.remove(knob);this._sortStops();this._updateCanvas();}
knobSelectionChanged(knob)
{if(this._selectedKnob&&this._selectedKnob!==knob&&knob.selected)
this._selectedKnob.selected=false;this._selectedKnob=knob.selected?knob:null;if(this.delegate&&typeof this.delegate.gradientSliderStopWasSelected==="function")
this.delegate.gradientSliderStopWasSelected(this,knob.stop);if(this._selectedKnob)
WI.addWindowKeydownListener(this);else
WI.removeWindowKeydownListener(this);} 
_handleMouseover(event)
{this._updateShadowKnob(event);}
_handleMousemove(event)
{this._updateShadowKnob(event);}
_handleMouseout(event)
{if(!this._shadowKnob)
return;this._shadowKnob.element.remove();delete this._shadowKnob;}
_handleClick(event)
{this._updateShadowKnob(event);this._knobs.push(this._shadowKnob);this._shadowKnob.element.classList.remove(WI.GradientSlider.ShadowClassName);var stop={offset:this._shadowKnob.x/WI.GradientSlider.Width,color:this._shadowKnob.wellColor};this._stops.push(stop);this._sortStops();this._updateStops();this._knobs[this._stops.indexOf(stop)].selected=true;delete this._shadowKnob;}
_updateShadowKnob(event)
{if(!this._shadowKnob){this._shadowKnob=new WI.GradientSliderKnob(this);this._shadowKnob.element.classList.add(WI.GradientSlider.ShadowClassName);this.element.appendChild(this._shadowKnob.element);}
this._shadowKnob.x=event.pageX-this.element.getBoundingClientRect().x;var colorData=this._canvas.getContext("2d").getImageData(this._shadowKnob.x-1,0,1,1).data;this._shadowKnob.wellColor=new WI.Color(WI.Color.Format.RGB,[colorData[0],colorData[1],colorData[2],colorData[3]/255]);}
_sortStops()
{this._stops.sort(function(a,b){return a.offset-b.offset;});}
_updateStops()
{this._updateCanvas();this._updateKnobs();}
_updateCanvas()
{var w=WI.GradientSlider.Width;var h=WI.GradientSlider.Height;this._canvas.width=w;this._canvas.height=h;var ctx=this._canvas.getContext("2d");var gradient=ctx.createLinearGradient(0,0,w,0);for(var stop of this._stops)
gradient.addColorStop(stop.offset,stop.color);ctx.clearRect(0,0,w,h);ctx.fillStyle=gradient;ctx.fillRect(0,0,w,h);if(this.delegate&&typeof this.delegate.gradientSliderStopsDidChange==="function")
this.delegate.gradientSliderStopsDidChange(this);}
_updateKnobs()
{var selectedStop=this._selectedKnob?this._selectedKnob.stop:null;while(this._knobs.length>this._stops.length)
this._knobs.pop().element.remove();while(this._knobs.length<this._stops.length){var knob=new WI.GradientSliderKnob(this);this.element.appendChild(knob.element);this._knobs.push(knob);}
for(var i=0;i<this._stops.length;++i){var stop=this._stops[i];var knob=this._knobs[i];knob.stop=stop;knob.x=Math.round(stop.offset*WI.GradientSlider.Width);knob.selected=stop===selectedStop;}}};WI.GradientSlider.Width=238;WI.GradientSlider.Height=19;WI.GradientSlider.AddAreaClassName="add-area";WI.GradientSlider.DetachingClassName="detaching";WI.GradientSlider.ShadowClassName="shadow";WI.GradientSliderKnob=class GradientSliderKnob extends WI.Object
{constructor(delegate)
{super();this._x=0;this._y=0;this._stop=null;this.delegate=delegate;this._element=document.createElement("div");this._element.className="gradient-slider-knob";this._element.appendChild(document.createElement("img"));this._well=this._element.appendChild(document.createElement("div"));this._element.addEventListener("mousedown",this);} 
get element()
{return this._element;}
get stop()
{return this._stop;}
set stop(stop)
{this.wellColor=stop.color;this._stop=stop;}
get x()
{return this._x;}
set x(x){this._x=x;this._updateTransform();}
get y()
{return this._x;}
set y(y){this._y=y;this._updateTransform();}
get wellColor()
{return this._wellColor;}
set wellColor(color)
{this._wellColor=color;this._well.style.backgroundColor=color;}
get selected()
{return this._element.classList.contains(WI.GradientSliderKnob.SelectedClassName);}
set selected(selected)
{if(this.selected===selected)
return;this._element.classList.toggle(WI.GradientSliderKnob.SelectedClassName,selected);if(this.delegate&&typeof this.delegate.knobSelectionChanged==="function")
this.delegate.knobSelectionChanged(this);} 
handleEvent(event)
{event.preventDefault();event.stopPropagation();switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;case"transitionend":this._handleTransitionEnd(event);break;}} 
_handleMousedown(event)
{this._moved=false;this._detaching=false;window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._startX=this.x;this._startMouseX=event.pageX;this._startMouseY=event.pageY;}
_handleMousemove(event)
{var w=WI.GradientSlider.Width;this._moved=true;if(!this._detaching&&Math.abs(event.pageY-this._startMouseY)>50){this._detaching=this.delegate&&typeof this.delegate.knobCanDetach==="function"&&this.delegate.knobCanDetach(this);if(this._detaching&&this.delegate&&typeof this.delegate.knobWillDetach==="function"){var translationFromParentToBody=window.webkitConvertPointFromNodeToPage(this.element.parentNode,new WebKitPoint(0,0));this._startMouseX-=translationFromParentToBody.x;this._startMouseY-=translationFromParentToBody.y;document.body.appendChild(this.element);this.delegate.knobWillDetach(this);}}
var x=this._startX+event.pageX-this._startMouseX;if(!this._detaching)
x=Math.min(Math.max(0,x),w);this.x=x;if(this._detaching)
this.y=event.pageY-this._startMouseY;else if(this.delegate&&typeof this.delegate.knobXDidChange==="function")
this.delegate.knobXDidChange(this);}
_handleMouseup(event)
{window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);if(this._detaching){this.element.addEventListener("transitionend",this);this.element.classList.add(WI.GradientSliderKnob.FadeOutClassName);this.selected=false;}else if(!this._moved)
this.selected=!this.selected;}
_handleTransitionEnd(event)
{this.element.removeEventListener("transitionend",this);this.element.classList.remove(WI.GradientSliderKnob.FadeOutClassName);this.element.remove();}
_updateTransform()
{this.element.style.webkitTransform="translate3d("+this._x+"px, "+this._y+"px, 0)";}};WI.GradientSliderKnob.SelectedClassName="selected";WI.GradientSliderKnob.FadeOutClassName="fade-out";WI.GraphicsOverviewContentView=class GraphicsOverviewContentView extends WI.ContentView
{constructor()
{super();this.element.classList.add("graphics-overview");this._importButtonNavigationItem=new WI.ButtonNavigationItem("import-recording",WI.UIString("Import"),"Images/Import.svg",15,15);this._importButtonNavigationItem.tooltip=WI.UIString("Import");this._importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleRefreshButtonClicked,this);this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleShowGridButtonClicked,this);this._canvasOverviewContentView=new WI.CanvasOverviewContentView(WI.canvasManager.canvasCollection);this._overviewViews=[];} 
get supplementalRepresentedObjects()
{return this._overviewViews.flatMap((subview)=>subview.supplementalRepresentedObjects);}
get navigationItems()
{let navigationItems=[];if(!WI.animationManager.supported){navigationItems.pushAll(this._canvasOverviewContentView.navigationItems);navigationItems.push(new WI.DividerNavigationItem);}
navigationItems.push(this._importButtonNavigationItem,new WI.DividerNavigationItem,this._refreshButtonNavigationItem,this._showGridButtonNavigationItem);return navigationItems;} 
attached()
{super.attached();WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);this._handleShowImageGridSettingChanged();}
detached()
{WI.domManager.hideDOMNodeHighlight();WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);super.detached();}
initialLayout()
{super.initialLayout();if(WI.animationManager.supported){let createSection=(identifier,title,overviewView)=>{let sectionElement=this.element.appendChild(document.createElement("section"));sectionElement.className=identifier;let headerElement=sectionElement.appendChild(document.createElement("div"));headerElement.className="header";let titleElement=headerElement.appendChild(document.createElement("h1"));titleElement.textContent=title;let navigationItems=overviewView.navigationItems;if(navigationItems.length){let navigationBar=new WI.NavigationBar(document.createElement("nav"),{navigationItems});headerElement.appendChild(navigationBar.element);this.addSubview(navigationBar);}
let contentElement=sectionElement.appendChild(document.createElement("div"));contentElement.className="content";contentElement.appendChild(overviewView.element);this.addSubview(overviewView);overviewView.addEventListener(WI.CollectionContentView.Event.SelectedItemChanged,this._handleOverviewViewSelectedItemChanged,this);overviewView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._handleOverviewViewSupplementalRepresentedObjectsDidChange,this);this._overviewViews.push(overviewView);};createSection("canvas",WI.UIString("Canvases"),this._canvasOverviewContentView);let animationCollection=WI.animationManager.animationCollection;createSection("web-animation",WI.UIString("Web Animations"),new WI.AnimationCollectionContentView(animationCollection.animationCollectionForType(WI.Animation.Type.WebAnimation)));createSection("css-animation",WI.UIString("CSS Animations"),new WI.AnimationCollectionContentView(animationCollection.animationCollectionForType(WI.Animation.Type.CSSAnimation)));createSection("css-transition",WI.UIString("CSS Transitions"),new WI.AnimationCollectionContentView(animationCollection.animationCollectionForType(WI.Animation.Type.CSSTransition)));this.element.addEventListener("click",this._handleClick.bind(this));}else
this.addSubview(this._canvasOverviewContentView);} 
_handleRefreshButtonClicked()
{for(let overviewView of this._overviewViews)
overviewView.handleRefreshButtonClicked();}
_handleShowGridButtonClicked(event)
{WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;}
_handleShowImageGridSettingChanged()
{this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;}
_handleImportButtonNavigationItemClicked(event)
{WI.FileUtilities.importJSON((result)=>WI.canvasManager.processJSON(result),{multiple:true});}
_handleOverviewViewSelectedItemChanged(event)
{if(!event.target.selectedItem)
return;for(let overviewView of this._overviewViews){if(overviewView!==event.target&&overviewView.selectionEnabled)
overviewView.selectedItem=null;}}
_handleOverviewViewSupplementalRepresentedObjectsDidChange(evnet)
{this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_handleClick(event)
{if(event.target!==this.element)
return;for(let overviewView of this._overviewViews){if(overviewView.selectionEnabled)
overviewView.selectedItem=null;}}};WI.HeapAllocationsTimelineDataGridNode=class HeapAllocationsTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);this._heapAllocationsView=options.heapAllocationsView;this.heapSnapshot.addEventListener(WI.HeapSnapshotProxy.Event.CollectedNodes,this._handleHeapSnapshotCollectedNodes,this);this.heapSnapshot.addEventListener(WI.HeapSnapshotProxy.Event.Invalidated,this._handleHeapSnapshotInvalidated,this);} 
get heapSnapshot()
{return this.record.heapSnapshot;}
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.name=this.displayName();this._cachedData.timestamp=this.record.timestamp-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.size=this.heapSnapshot.totalSize;this._cachedData.liveSize=this.heapSnapshot.liveSize;return this._cachedData;}
createCellContent(columnIdentifier,cell)
{const higherResolution=true;let value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());var fragment=document.createDocumentFragment();var titleElement=fragment.appendChild(document.createElement("span"));titleElement.textContent=value;if(this._heapAllocationsView&&!this.heapSnapshot.invalid){var goToButton=fragment.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",(event)=>{this._heapAllocationsView.showHeapSnapshotTimelineRecord(this.record);});}
return fragment;case"timestamp":{return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);}
case"size":case"liveSize":return Number.bytesToString(value,higherResolution);}
return super.createCellContent(columnIdentifier,cell);}
markAsBaseline()
{this.element.classList.add("baseline");}
clearBaseline()
{this.element.classList.remove("baseline");} 
createCells()
{super.createCells();if(this.heapSnapshot.invalid)
this.element.classList.add("invalid");} 
_handleHeapSnapshotCollectedNodes()
{this.needsRefresh();}
_handleHeapSnapshotInvalidated()
{this.needsRefresh();}};WI.HeapAllocationsTimelineDataGridNodePathComponent=class HeapAllocationsTimelineDataGridNodePathComponent extends WI.TimelineDataGridNodePathComponent
{ get previousSibling()
{let previousSibling=this.timelineDataGridNode.previousSibling;while(previousSibling&&(previousSibling.hidden||previousSibling.record.heapSnapshot.invalid))
previousSibling=previousSibling.previousSibling;if(!previousSibling)
return null;return new WI.HeapAllocationsTimelineDataGridNodePathComponent(previousSibling);}
get nextSibling()
{let nextSibling=this.timelineDataGridNode.nextSibling;while(nextSibling&&(nextSibling.hidden||nextSibling.record.heapSnapshot.invalid))
nextSibling=nextSibling.nextSibling;if(!nextSibling)
return null;return new WI.HeapAllocationsTimelineDataGridNodePathComponent(nextSibling);}};WI.HeapAllocationsTimelineOverviewGraph=class HeapAllocationsTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("heap-allocations");this._heapAllocationsTimeline=timeline;this._heapAllocationsTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._heapAllocationTimelineRecordAdded,this);this._selectedImageElement=null;this.reset();} 
reset()
{super.reset();this.element.removeChildren();}
layout()
{super.layout();if(this.hidden)
return;this.element.removeChildren();if(this._selectedImageElement){this._selectedImageElement.classList.remove("selected");this._selectedImageElement=null;}
let visibleRecords=this._heapAllocationsTimeline.recordsInTimeRange(this.startTime,this.endTime);if(!visibleRecords.length)
return;let graphStartTime=this.startTime;let secondsPerPixel=this.timelineOverview.secondsPerPixel;function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
for(let record of visibleRecords){if(isNaN(record.timestamp))
continue;const halfImageWidth=8;let x=xScale(record.timestamp)-halfImageWidth;if(x<=1)
x=1;let imageElement=record[WI.HeapAllocationsTimelineOverviewGraph.RecordElementAssociationSymbol];if(!imageElement){imageElement=record[WI.HeapAllocationsTimelineOverviewGraph.RecordElementAssociationSymbol]=document.createElement("img");imageElement.classList.add("snapshot");imageElement.addEventListener("click",(event)=>{if(record.heapSnapshot.invalid)
return;event.__timelineRecordClickEventHandled=true;this.selectedRecord=record;});}
imageElement.style.setProperty(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left",`${x}px`);if(record.heapSnapshot.invalid)
imageElement.classList.add("invalid");this.element.appendChild(imageElement);}
this._updateSnapshotMarkers();}
updateSelectedRecord()
{this._updateSnapshotMarkers();} 
_updateSnapshotMarkers()
{if(this._selectedImageElement)
this._selectedImageElement.classList.remove("selected");if(!this.selectedRecord){this._selectedImageElement=null;return;}
let imageElement=this.selectedRecord[WI.HeapAllocationsTimelineOverviewGraph.RecordElementAssociationSymbol];if(!imageElement)
return;imageElement.classList.add("selected");this._selectedImageElement=imageElement;}
_heapAllocationTimelineRecordAdded(event)
{this.needsLayout();}};WI.HeapAllocationsTimelineOverviewGraph.RecordElementAssociationSymbol=Symbol("record-element-association");WI.HeapAllocationsTimelineView=class HeapAllocationsTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);this.element.classList.add("heap-allocations");let columns={name:{title:WI.UIString("Name"),width:"150px",icon:true,},timestamp:{title:WI.UIString("Time"),width:"80px",sortable:true,aligned:"right",},size:{title:WI.UIString("Size"),width:"80px",sortable:true,aligned:"right",},liveSize:{title:WI.UIString("Live Size"),width:"80px",sortable:true,aligned:"right",},};this._importButtonNavigationItem=new WI.ButtonNavigationItem("import",WI.UIString("Import"),"Images/Import.svg",15,15);this._importButtonNavigationItem.tooltip=WI.UIString("Import");this._importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._importButtonNavigationItemClicked,this);let snapshotTooltip=WI.UIString("Take snapshot");this._takeHeapSnapshotButtonItem=new WI.ButtonNavigationItem("take-snapshot",snapshotTooltip,"Images/Camera.svg",16,16);this._takeHeapSnapshotButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._takeHeapSnapshotClicked,this);let defaultToolTip=WI.UIString("Compare snapshots");let activatedToolTip=WI.UIString("Cancel comparison");this._compareHeapSnapshotsButtonItem=new WI.ActivateButtonNavigationItem("compare-heap-snapshots",defaultToolTip,activatedToolTip,"Images/Compare.svg",16,16);this._compareHeapSnapshotsButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._compareHeapSnapshotsClicked,this);this._compareHeapSnapshotsButtonItem.enabled=false;this._compareHeapSnapshotsButtonItem.activated=false;this._compareHeapSnapshotHelpTextItem=new WI.TextNavigationItem("compare-heap-snapshot-help-text","");this._selectingComparisonHeapSnapshots=false;this._baselineDataGridNode=null;this._baselineHeapSnapshotTimelineRecord=null;this._heapSnapshotDiff=null;this._snapshotListScrollTop=0;this._showingSnapshotList=true;this._snapshotListPathComponent=new WI.HierarchicalPathComponent(WI.UIString("Snapshot List"),"snapshot-list-icon","snapshot-list",false,false);this._snapshotListPathComponent.addEventListener(WI.HierarchicalPathComponent.Event.Clicked,this._snapshotListPathComponentClicked,this);this._unseenRecords=[];this._unseenRecordsBannerView=new WI.BannerView(WI.UIString("There are new snapshots that have been filtered","There are new snapshots that have been filtered @ Heap Allocations Timeline View","Message displayed in a banner when one or more snapshots that the user has not yet seen are being filtered."),{actionButtonMessage:WI.UIString("Clear Filters","Clear Filters @ Heap Allocations Timeline View","Text for button that will clear both text filters and time range filters."),showDismissButton:true,});this._unseenRecordsBannerView.addEventListener(WI.BannerView.Event.ActionButtonClicked,this._handleUnseenRecordsBannerClearFiltersClicked,this);this._unseenRecordsBannerView.addEventListener(WI.BannerView.Event.DismissButtonClicked,this._handleUnseenRecordsBannerDismissClicked,this);this._dataGrid=new WI.TimelineDataGrid(columns);this._dataGrid.sortColumnIdentifier="timestamp";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("heap-allocations-timeline-view");this._dataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridNodeSelected,this);this.setupDataGrid(this._dataGrid);this.addSubview(this._dataGrid);this._contentViewContainer=new WI.ContentViewContainer;this._contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);this._pendingRecords=Array.from(timeline.records);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._heapAllocationsTimelineRecordAdded,this);WI.HeapSnapshotProxy.addEventListener(WI.HeapSnapshotProxy.Event.Invalidated,this._heapSnapshotInvalidated,this);WI.HeapSnapshotWorkerProxy.singleton().addEventListener(WI.HeapSnapshotWorkerProxy.Event.Collection,this._heapSnapshotCollectionEvent,this);} 
get scrollableElements()
{if(this._showingSnapshotList)
return[this._dataGrid.scrollContainer];if(this._contentViewContainer.currentContentView)
return this._contentViewContainer.currentContentView.scrollableElements;return[];}
showHeapSnapshotList()
{if(this._showingSnapshotList)
return;this._showingSnapshotList=true;this._heapSnapshotDiff=null;this._cancelSelectComparisonHeapSnapshots();this.removeSubview(this._contentViewContainer);this.addSubview(this._dataGrid);this._dataGrid.scrollContainer.scrollTop=this._snapshotListScrollTop;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
showHeapSnapshotTimelineRecord(heapSnapshotTimelineRecord)
{if(this._showingSnapshotList){this._snapshotListScrollTop=this._dataGrid.scrollContainer.scrollTop;this.removeSubview(this._dataGrid);this.addSubview(this._contentViewContainer);}
this._showingSnapshotList=false;this._heapSnapshotDiff=null;this._cancelSelectComparisonHeapSnapshots();for(let dataGridNode of this._dataGrid.children){if(dataGridNode.record===heapSnapshotTimelineRecord){dataGridNode.hidden=false;dataGridNode.select();break;}}
let shouldTriggerContentViewUpdate=this._contentViewContainer.currentContentView&&this._contentViewContainer.currentContentView.representedObject===heapSnapshotTimelineRecord.heapSnapshot;this._contentViewContainer.showContentViewForRepresentedObject(heapSnapshotTimelineRecord.heapSnapshot);if(shouldTriggerContentViewUpdate)
this._currentContentViewDidChange();}
showHeapSnapshotDiff(heapSnapshotDiff)
{if(this._showingSnapshotList){this.removeSubview(this._dataGrid);this.addSubview(this._contentViewContainer);}
this._showingSnapshotList=false;this._heapSnapshotDiff=heapSnapshotDiff;this._contentViewContainer.showContentViewForRepresentedObject(heapSnapshotDiff);} 
get navigationItems()
{if(this._showingSnapshotList){let items=[this._importButtonNavigationItem,this._takeHeapSnapshotButtonItem,this._compareHeapSnapshotsButtonItem];if(this._selectingComparisonHeapSnapshots)
items.push(this._compareHeapSnapshotHelpTextItem);return items;}
if(this._contentViewContainer.currentContentView)
return this._contentViewContainer.currentContentView.navigationItems;return[];}
get selectionPathComponents()
{let components=[this._snapshotListPathComponent];if(this._showingSnapshotList)
return components;if(this._heapSnapshotDiff){let firstSnapshotIdentifier=this._heapSnapshotDiff.snapshot1.identifier;let secondSnapshotIdentifier=this._heapSnapshotDiff.snapshot2.identifier;let diffComponent=new WI.HierarchicalPathComponent(WI.UIString("Snapshot Comparison (%d and %d)").format(firstSnapshotIdentifier,secondSnapshotIdentifier),"snapshot-diff-icon","snapshot-diff");components.push(diffComponent);}else if(this._dataGrid.selectedNode){let heapSnapshotPathComponent=new WI.HeapAllocationsTimelineDataGridNodePathComponent(this._dataGrid.selectedNode);heapSnapshotPathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._snapshotPathComponentSelected,this);components.push(heapSnapshotPathComponent);}
if(this._contentViewContainer.currentContentView)
components.pushAll(this._contentViewContainer.currentContentView.selectionPathComponents);return components;}
selectRecord(record)
{if(record)
this.showHeapSnapshotTimelineRecord(record);else
this.showHeapSnapshotList();}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._heapAllocationsTimelineRecordAdded,this);this._dataGrid.closed();this._contentViewContainer.closeAllContentViews();WI.ContentView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.HeapSnapshotProxy.removeEventListener(WI.HeapSnapshotProxy.Event.Invalidated,this._heapSnapshotInvalidated,this);WI.HeapSnapshotWorkerProxy.singleton().removeEventListener(WI.HeapSnapshotWorkerProxy.Event.Collection,this._heapSnapshotCollectionEvent,this);}
layout()
{super.layout();if(!this._pendingRecords.length)
return;for(let heapAllocationsTimelineRecord of this._pendingRecords){let dataGridNode=new WI.HeapAllocationsTimelineDataGridNode(heapAllocationsTimelineRecord,{graphDataSource:this,heapAllocationsView:this,});this._dataGrid.addRowInSortOrder(dataGridNode);if(dataGridNode.hidden)
this._unseenRecords.push(dataGridNode);}
this._pendingRecords=[];this._updateUnseenRecordsBannerView();this._updateCompareHeapSnapshotButton();}
reset()
{super.reset();this._dataGrid.reset();this.showHeapSnapshotList();this._pendingRecords=[];this._unseenRecords=[];this._updateUnseenRecordsBannerView();this._updateCompareHeapSnapshotButton();}
updateFilter(filters)
{if(this._showingSnapshotList){this._dataGrid.filterText=filters?filters.text:"";return;}
this._contentViewContainer.currentContentView.updateFilter(filters);}
filterDidChange()
{super.filterDidChange();this._updateUnseenRecordsBannerView();} 
_heapAllocationsTimelineRecordAdded(event)
{this._pendingRecords.push(event.data.record);this.needsLayout();}
_heapSnapshotCollectionEvent(event)
{function updateHeapSnapshotForEvent(heapSnapshot){if(heapSnapshot.invalid)
return;heapSnapshot.updateForCollectionEvent(event);}
for(let node of this._dataGrid.children)
updateHeapSnapshotForEvent(node.record.heapSnapshot);for(let record of this._pendingRecords)
updateHeapSnapshotForEvent(record.heapSnapshot);if(this._heapSnapshotDiff)
updateHeapSnapshotForEvent(this._heapSnapshotDiff);}
_snapshotListPathComponentClicked(event)
{this.showHeapSnapshotList();}
_snapshotPathComponentSelected(event)
{this.showHeapSnapshotTimelineRecord(event.data.pathComponent.representedObject);}
_currentContentViewDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_contentViewSelectionPathComponentDidChange(event)
{if(event.target!==this._contentViewContainer.currentContentView)
return;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_heapSnapshotInvalidated(event)
{let heapSnapshot=event.target;if(this._baselineHeapSnapshotTimelineRecord){if(heapSnapshot===this._baselineHeapSnapshotTimelineRecord.heapSnapshot)
this._cancelSelectComparisonHeapSnapshots();}
if(this._heapSnapshotDiff){if(heapSnapshot===this._heapSnapshotDiff.snapshot1||heapSnapshot===this._heapSnapshotDiff.snapshot2)
this.showHeapSnapshotList();}else if(this._dataGrid.selectedNode){if(heapSnapshot===this._dataGrid.selectedNode.record.heapSnapshot)
this.showHeapSnapshotList();}
this._updateCompareHeapSnapshotButton();}
_updateCompareHeapSnapshotButton()
{let hasAtLeastTwoValidSnapshots=false;let count=0;for(let node of this._dataGrid.children){if(node.revealed&&!node.hidden&&!node.record.heapSnapshot.invalid){count++;if(count===2){hasAtLeastTwoValidSnapshots=true;break;}}}
this._compareHeapSnapshotsButtonItem.enabled=hasAtLeastTwoValidSnapshots;}
_updateUnseenRecordsBannerView()
{this._unseenRecords=this._unseenRecords.filter((record)=>record.hidden);if(this._unseenRecords.length){if(this._unseenRecordsBannerView.parentView!==this)
this.insertSubviewBefore(this._unseenRecordsBannerView,this._dataGrid);}else{if(this._unseenRecordsBannerView.parentView===this)
this.removeSubview(this._unseenRecordsBannerView);}}
_importButtonNavigationItemClicked()
{WI.FileUtilities.importText((result)=>{let snapshotStringData=result.text;let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createImportedSnapshot(snapshotStringData,result.filename,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;const timestamp=NaN;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);this.dispatchEventToListeners(WI.TimelineView.Event.NeedsEntireSelectedRange);});},{multiple:true});}
_takeHeapSnapshotClicked()
{WI.heapManager.snapshot((error,timestamp,snapshotStringData)=>{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);this.dispatchEventToListeners(WI.TimelineView.Event.NeedsEntireSelectedRange);});});}
_cancelSelectComparisonHeapSnapshots()
{if(!this._selectingComparisonHeapSnapshots)
return;if(this._baselineDataGridNode)
this._baselineDataGridNode.clearBaseline();this._selectingComparisonHeapSnapshots=false;this._baselineDataGridNode=null;this._baselineHeapSnapshotTimelineRecord=null;this._compareHeapSnapshotsButtonItem.activated=false;this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_compareHeapSnapshotsClicked(event)
{let newActivated=!this._compareHeapSnapshotsButtonItem.activated;this._compareHeapSnapshotsButtonItem.activated=newActivated;if(!newActivated){this._cancelSelectComparisonHeapSnapshots();return;}
if(this._dataGrid.selectedNode)
this._dataGrid.selectedNode.deselect();this._selectingComparisonHeapSnapshots=true;this._baselineHeapSnapshotTimelineRecord=null;this._compareHeapSnapshotHelpTextItem.text=WI.UIString("Select baseline snapshot");this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_dataGridNodeSelected(event)
{if(!this._selectingComparisonHeapSnapshots)
return;let dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode)
return;let heapAllocationsTimelineRecord=dataGridNode.record;if(heapAllocationsTimelineRecord.heapSnapshot.invalid||this._baselineHeapSnapshotTimelineRecord===heapAllocationsTimelineRecord){this._dataGrid.selectedNode.deselect();return;}
if(!this._baselineHeapSnapshotTimelineRecord){this._baselineDataGridNode=dataGridNode;this._baselineDataGridNode.markAsBaseline();this._baselineHeapSnapshotTimelineRecord=heapAllocationsTimelineRecord;this._dataGrid.selectedNode.deselect();this._compareHeapSnapshotHelpTextItem.text=WI.UIString("Select comparison snapshot");this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);return;}
let snapshot1=this._baselineHeapSnapshotTimelineRecord.heapSnapshot;let snapshot2=heapAllocationsTimelineRecord.heapSnapshot;if(snapshot1.identifier>snapshot2.identifier)
[snapshot1,snapshot2]=[snapshot2,snapshot1];let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshotDiff(snapshot1.proxyObjectId,snapshot2.proxyObjectId,({objectId,snapshotDiff:serializedSnapshotDiff})=>{let diff=WI.HeapSnapshotDiffProxy.deserialize(objectId,serializedSnapshotDiff);this.showHeapSnapshotDiff(diff);});this._baselineDataGridNode.clearBaseline();this._baselineDataGridNode=null;this._selectingComparisonHeapSnapshots=false;this._compareHeapSnapshotsButtonItem.activated=false;}
_handleUnseenRecordsBannerClearFiltersClicked(event)
{this.dispatchEventToListeners(WI.TimelineView.Event.NeedsFiltersCleared);this.dispatchEventToListeners(WI.TimelineView.Event.NeedsEntireSelectedRange);}
_handleUnseenRecordsBannerDismissClicked(event)
{this._unseenRecords=[];this._updateUnseenRecordsBannerView();}};WI.HeapSnapshotClassDataGridNode=class HeapSnapshotClassDataGridNode extends WI.DataGridNode
{constructor(data,tree)
{super(data,{hasChildren:true});this._data=data;this._tree=tree;this._batched=false;this._instances=null;this.addEventListener(WI.DataGridNode.Event.Populate,this._populate,this);} 
get data(){return this._data;}
createCellContent(columnIdentifier)
{if(columnIdentifier==="retainedSize"){let size=this._data.retainedSize;let fragment=document.createDocumentFragment();let sizeElement=fragment.appendChild(document.createElement("span"));sizeElement.classList.add("size");sizeElement.textContent=Number.bytesToString(size);let percentElement=fragment.appendChild(document.createElement("span"));percentElement.classList.add("percentage");percentElement.textContent=emDash;return fragment;}
if(columnIdentifier==="size")
return Number.bytesToString(this._data.size);if(columnIdentifier==="className"){const internal=false;let{className,isObjectSubcategory}=this._data;let fragment=document.createDocumentFragment();let iconElement=fragment.appendChild(document.createElement("img"));iconElement.classList.add("icon",WI.HeapSnapshotClusterContentView.iconStyleClassNameForClassName(className,internal,isObjectSubcategory));let nameElement=fragment.appendChild(document.createElement("span"));nameElement.classList.add("class-name");nameElement.textContent=className;return fragment;}
return super.createCellContent(columnIdentifier);}
sort()
{if(this._batched){this._removeFetchMoreDataGridNode();this._sortInstances();this._updateBatchedChildren();this._appendFetchMoreDataGridNode();return;}
let children=this.children;children.sort(this._tree._sortComparator);for(let i=0;i<children.length;++i){children[i]._recalculateSiblings(i);children[i].sort();}}
removeCollectedNodes(collectedNodes)
{let nodesToRemove=[];this.forEachImmediateChild((dataGridNode)=>{if(dataGridNode instanceof WI.HeapSnapshotInstanceDataGridNode){let heapSnapshotNode=dataGridNode.node;if(heapSnapshotNode.id in collectedNodes)
nodesToRemove.push(dataGridNode);}});if(nodesToRemove.length){for(let dataGridNode of nodesToRemove)
this.removeChild(dataGridNode);}
if(this._instances){this._instances=this._instances.filter((instance)=>!(instance.id in collectedNodes));this._fetchBatch(nodesToRemove.length);}}
updateCount(count)
{if(count===this._data.count)
return;if(!count){this._tree.removeChild(this);return;}
this._data.count=count;this.needsRefresh();} 
_populate()
{this.removeEventListener(WI.DataGridNode.Event.Populate,this._populate,this);this._tree.heapSnapshot.instancesWithClassName(this._data.className,(instances)=>{ this._instances=instances.filter((instance)=>!instance.dead);this._sortInstances();if(instances.length>WI.HeapSnapshotClassDataGridNode.ChildrenBatchLimit){this._batched=true;this._fetchBatch(WI.HeapSnapshotClassDataGridNode.ChildrenBatchLimit);return;}
for(let instance of this._instances)
this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this._tree));});}
_fetchBatch(batchSize)
{if(this._batched&&this.children.length)
this._removeFetchMoreDataGridNode();let oldCount=this.children.length;let newCount=oldCount+batchSize;if(newCount>=this._instances.length){newCount=this._instances.length-1;this._batched=false;}
let count=newCount-oldCount;if(count){for(let i=0;i<=count;++i){let instance=this._instances[oldCount+i];this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this._tree));}}
if(this._batched)
this._appendFetchMoreDataGridNode();}
_sortInstances()
{this._instances.sort((a,b)=>{let fakeDataGridNodeA={data:a};let fakeDataGridNodeB={data:b};return this._tree._sortComparator(fakeDataGridNodeA,fakeDataGridNodeB);});}
_updateBatchedChildren()
{let count=this.children.length;this.removeChildren();for(let i=0;i<count;++i)
this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(this._instances[i],this._tree));}
_removeFetchMoreDataGridNode()
{this.removeChild(this.children[this.children.length-1]);}
_appendFetchMoreDataGridNode()
{let count=this.children.length;let totalCount=this._instances.length;let remainingCount=totalCount-count;let batchSize=remainingCount>=WI.HeapSnapshotClassDataGridNode.ChildrenBatchLimit?WI.HeapSnapshotClassDataGridNode.ChildrenBatchLimit:0;this.appendChild(new WI.HeapSnapshotInstanceFetchMoreDataGridNode(this._tree,batchSize,remainingCount,this._fetchBatch.bind(this)));}};WI.HeapSnapshotClassDataGridNode.ChildrenBatchLimit=100;WI.HeapSnapshotClusterContentView=class HeapSnapshotClusterContentView extends WI.ClusterContentView
{constructor(heapSnapshot)
{super(heapSnapshot);this._heapSnapshot=heapSnapshot;function createPathComponent(displayName,className,identifier)
{let pathComponent=new WI.HierarchicalPathComponent(displayName,className,identifier,false,true);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._pathComponentSelected,this);pathComponent.comparisonData=heapSnapshot;return pathComponent;}
this._shownInitialContent=false;this._instancesContentView=null;this._objectGraphContentView=null;this._instancesPathComponent=createPathComponent.call(this,WI.UIString("Instances"),"heap-snapshot-instances-icon",WI.HeapSnapshotClusterContentView.InstancesIdentifier);this._objectGraphPathComponent=createPathComponent.call(this,WI.UIString("Object Graph"),"heap-snapshot-object-graph-icon",WI.HeapSnapshotClusterContentView.ObjectGraphIdentifier);if(this._supportsObjectGraph()){this._instancesPathComponent.nextSibling=this._objectGraphPathComponent;this._objectGraphPathComponent.previousSibling=this._instancesPathComponent;}
this._currentContentViewSetting=new WI.Setting("heap-snapshot-cluster-current-view",WI.HeapSnapshotClusterContentView.InstancesIdentifier);} 
static iconStyleClassNameForClassName(className,internal,isObjectType)
{if(internal)
return"native";if(isObjectType)
return"object";switch(className){case"Object":case"Array":case"Map":case"Set":case"WeakMap":case"WeakSet":case"Promise":case"Error":case"Window":case"Map Iterator":case"Set Iterator":case"Math":case"JSON":case"GlobalObject":return"object";case"Function":return"function";case"RegExp":return"regex";case"Number":return"number";case"Boolean":return"boolean";case"String":case"string":return"string";case"Symbol":case"symbol":return"symbol";case"BigInt":case"bigint":return"bigint";}
if(className.endsWith("Prototype"))
return"object";if(className.endsWith("Element")||className==="Node"||className==="Text")
return"node";return"native";} 
get heapSnapshot(){return this._heapSnapshot;}
get instancesContentView()
{if(!this._instancesContentView)
this._instancesContentView=new WI.HeapSnapshotInstancesContentView(this._heapSnapshot);return this._instancesContentView;}
get objectGraphContentView()
{if(!this._supportsObjectGraph())
return null;if(!this._objectGraphContentView)
this._objectGraphContentView=new WI.HeapSnapshotObjectGraphContentView(this._heapSnapshot);return this._objectGraphContentView;}
get selectionPathComponents()
{let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView)
return[];let components=[this._pathComponentForContentView(currentContentView)];return components.concat(currentContentView.selectionPathComponents);}
attached()
{super.attached();if(this._shownInitialContent)
return;this._showContentViewForIdentifier(this._currentContentViewSetting.value);}
closed()
{super.closed();this._shownInitialContent=false;}
saveToCookie(cookie)
{cookie[WI.HeapSnapshotClusterContentView.ContentViewIdentifierCookieKey]=this._currentContentViewSetting.value;}
restoreFromCookie(cookie)
{this._showContentViewForIdentifier(cookie[WI.HeapSnapshotClusterContentView.ContentViewIdentifierCookieKey]);}
showInstances()
{this._shownInitialContent=true;return this._showContentViewForIdentifier(WI.HeapSnapshotClusterContentView.InstancesIdentifier);}
showObjectGraph()
{this._shownInitialContent=true;return this._showContentViewForIdentifier(WI.HeapSnapshotClusterContentView.ObjectGraphIdentifier);}
updateFilter(filters)
{this._contentViewContainer.currentContentView.updateFilter(filters);} 
_supportsObjectGraph()
{return this._heapSnapshot instanceof WI.HeapSnapshotProxy;}
_pathComponentForContentView(contentView)
{if(!contentView)
return null;if(contentView===this._instancesContentView)
return this._instancesPathComponent;if(contentView===this._objectGraphContentView)
return this._objectGraphPathComponent;console.error("Unknown contentView.");return null;}
_identifierForContentView(contentView)
{if(!contentView)
return null;if(contentView===this._instancesContentView)
return WI.HeapSnapshotClusterContentView.InstancesIdentifier;if(contentView===this._objectGraphContentView)
return WI.HeapSnapshotClusterContentView.ObjectGraphIdentifier;console.error("Unknown contentView.");return null;}
_showContentViewForIdentifier(identifier)
{let contentViewToShow=null;switch(identifier){case WI.HeapSnapshotClusterContentView.InstancesIdentifier:contentViewToShow=this.instancesContentView;break;case WI.HeapSnapshotClusterContentView.ObjectGraphIdentifier:contentViewToShow=this.objectGraphContentView;break;}
if(!contentViewToShow)
contentViewToShow=this.instancesContentView;this._shownInitialContent=true;this._currentContentViewSetting.value=this._identifierForContentView(contentViewToShow);return this.contentViewContainer.showContentView(contentViewToShow);}
_pathComponentSelected(event)
{this._showContentViewForIdentifier(event.data.pathComponent.representedObject);}};WI.HeapSnapshotClusterContentView.ContentViewIdentifierCookieKey="heap-snapshot-cluster-content-view-identifier";WI.HeapSnapshotClusterContentView.InstancesIdentifier="instances";WI.HeapSnapshotClusterContentView.ObjectGraphIdentifier="object-graph";WI.HeapSnapshotContentView=class HeapSnapshotContentView extends WI.ContentView
{constructor(representedObject,identifier,columns,heapSnapshotDataGridTreeConstructor)
{super(representedObject);this.element.classList.add("heap-snapshot");this._exportButtonNavigationItem=new WI.ButtonNavigationItem("export",WI.UIString("Export"),"Images/Export.svg",15,15);this._exportButtonNavigationItem.tooltip=WI.UIString("Export (%s)").format(WI.saveKeyboardShortcut.displayName);this._exportButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._exportButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){this._exportSnapshot();},this);this._dataGrid=new WI.DataGrid(columns);this._dataGrid.sortColumnIdentifier="retainedSize";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Descending;this._dataGrid.filterDelegate=this;this._dataGrid.createSettings(identifier);this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);let sortComparator=WI.HeapSnapshotDataGridTree.buildSortComparator(this._dataGrid.sortColumnIdentifier,this._dataGrid.sortOrder);this._heapSnapshotDataGridTree=new heapSnapshotDataGridTreeConstructor(this.representedObject,sortComparator);this._heapSnapshotDataGridTree.addEventListener(WI.HeapSnapshotDataGridTree.Event.DidPopulate,this._heapSnapshotDataGridTreeDidPopulate,this);for(let child of this._heapSnapshotDataGridTree.children)
this._dataGrid.appendChild(child);this.addSubview(this._dataGrid);this._dataGrid.updateLayout();} 
updateFilter(filters)
{this._dataGrid.filterText=filters?filters.text:"";} 
dataGridMatchNodeAgainstCustomFilters(node)
{if(node instanceof WI.HeapSnapshotInstanceFetchMoreDataGridNode)
return false;return true;}
dataGridMatchShouldPopulateWhenFilteringNode(node)
{return true;} 
get navigationItems()
{if(this.representedObject instanceof WI.HeapSnapshotProxy)
return[this._exportButtonNavigationItem];return[];}
attached()
{super.attached();this._heapSnapshotDataGridTree.shown();}
detached()
{this._heapSnapshotDataGridTree.hidden();super.detached();}
get scrollableElements()
{return[this._dataGrid.scrollContainer];} 
_exportSnapshot()
{if(!this.representedObject.snapshotStringData){InspectorFrontendHost.beep();return;}
let date=new Date;let values=[date.getFullYear(),Number.zeroPad(date.getMonth()+1,2),Number.zeroPad(date.getDate(),2),Number.zeroPad(date.getHours(),2),Number.zeroPad(date.getMinutes(),2),Number.zeroPad(date.getSeconds(),2),];WI.FileUtilities.save({content:this.representedObject.snapshotStringData,suggestedName:WI.UIString("Heap Snapshot %s-%s-%s at %s.%s.%s").format(...values)+".json",forceSaveAs:true,});}
_sortDataGrid()
{if(!this._heapSnapshotDataGridTree)
return;this._heapSnapshotDataGridTree.sortComparator=WI.HeapSnapshotDataGridTree.buildSortComparator(this._dataGrid.sortColumnIdentifier,this._dataGrid.sortOrder);this._dataGrid.removeChildren();for(let child of this._heapSnapshotDataGridTree.children)
this._dataGrid.appendChild(child);}
_heapSnapshotDataGridTreeDidPopulate()
{this._dataGrid.removeChildren();for(let child of this._heapSnapshotDataGridTree.children)
this._dataGrid.appendChild(child);}};WI.HeapSnapshotInstancesContentView=class HeapSnapshotInstancesContentView extends WI.HeapSnapshotContentView
{constructor(representedObject)
{let columns={retainedSize:{title:WI.UIString("Retained Size"),tooltip:WI.UIString("Size of current object plus all objects it keeps alive"),width:"140px",aligned:"right",sortable:true,},size:{title:WI.UIString("Self Size"),width:"90px",aligned:"right",sortable:true,},count:{title:WI.UIString("Count"),width:"75px",aligned:"right",sortable:true,},className:{title:WI.UIString("Name"),sortable:true,disclosure:true,}};super(representedObject,"heap-snapshot-instances-content-view",columns,WI.HeapSnapshotInstancesDataGridTree);}};WI.HeapSnapshotObjectGraphContentView=class HeapSnapshotObjectGraphContentView extends WI.HeapSnapshotContentView
{constructor(representedObject)
{let columns={retainedSize:{title:WI.UIString("Retained Size"),tooltip:WI.UIString("Size of current object plus all objects it keeps alive"),width:"140px",aligned:"right",sortable:true,},size:{title:WI.UIString("Self Size"),width:"90px",aligned:"right",sortable:true,},className:{title:WI.UIString("Name"),sortable:true,disclosure:true,}};super(representedObject,"heap-snapshot-object-graph-content-view",columns,WI.HeapSnapshotObjectGraphDataGridTree);}};WI.HeapSnapshotDataGridTree=class HeapSnapshotDataGridTree extends WI.Object
{constructor(heapSnapshot,sortComparator)
{super();this._heapSnapshot=heapSnapshot;this._heapSnapshot.addEventListener(WI.HeapSnapshotProxy.Event.CollectedNodes,this._heapSnapshotCollectedNodes,this);this._children=[];this._sortComparator=sortComparator;this._visible=false;this._popover=null;this._popoverGridNode=null;this._popoverTargetElement=null;this.populateTopLevel();} 
static buildSortComparator(columnIdentifier,sortOrder)
{let multiplier=sortOrder===WI.DataGrid.SortOrder.Ascending?1:-1;let numberCompare=(columnIdentifier,a,b)=>multiplier*(a.data[columnIdentifier]-b.data[columnIdentifier]);let nameCompare=(a,b)=>{if(a.propertyName||b.propertyName){if(a.propertyName&&!b.propertyName)
return multiplier*-1;if(!a.propertyName&&b.propertyName)
return multiplier*1;let propertyNameCompare=a.propertyName.extendedLocaleCompare(b.propertyName);return multiplier*propertyNameCompare;}
let classNameCompare=a.data.className.extendedLocaleCompare(b.data.className);if(classNameCompare)
return multiplier*classNameCompare;if(a.data.id||b.data.id)
return multiplier*(a.data.id-b.data.id);return 0;};switch(columnIdentifier){case"retainedSize":return numberCompare.bind(this,"retainedSize");case"size":return numberCompare.bind(this,"size");case"count":return numberCompare.bind(this,"count");case"className":return nameCompare;}} 
get heapSnapshot(){return this._heapSnapshot;}
get visible(){return this._visible;}
get popoverGridNode(){return this._popoverGridNode;}
set popoverGridNode(x){this._popoverGridNode=x;}
get popoverTargetElement(){return this._popoverTargetElement;}
set popoverTargetElement(x){this._popoverTargetElement=x;}
get popover()
{if(!this._popover){this._popover=new WI.Popover(this);this._popover.windowResizeHandler=()=>{let bounds=WI.Rect.rectFromClientRect(this._popoverTargetElement.getBoundingClientRect());this._popover.present(bounds.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);};}
return this._popover;}
get children()
{return this._children;}
appendChild(node)
{this._children.push(node);}
insertChild(node,index)
{this._children.splice(index,0,node);}
removeChild(node)
{this._children.remove(node,true);}
removeChildren()
{this._children=[];}
set sortComparator(comparator)
{this._sortComparator=comparator;this.sort();}
sort()
{let children=this._children;children.sort(this._sortComparator);for(let i=0;i<children.length;++i){children[i]._recalculateSiblings(i);children[i].sort();}}
shown()
{this._visible=true;}
hidden()
{this._visible=false;if(this._popover&&this._popover.visible)
this._popover.dismiss();} 
willDismissPopover(popover)
{this._popoverGridNode=null;this._popoverTargetElement=null;} 
get alwaysShowRetainedSize()
{return false;}
populateTopLevel()
{}
removeCollectedNodes(collectedNodes)
{}
didPopulate()
{this.sort();this.dispatchEventToListeners(WI.HeapSnapshotDataGridTree.Event.DidPopulate);} 
_heapSnapshotCollectedNodes(event)
{this.removeCollectedNodes(event.data.collectedNodes);}};WI.HeapSnapshotDataGridTree.Event={DidPopulate:"heap-snapshot-data-grid-tree-did-populate",};WI.HeapSnapshotInstancesDataGridTree=class HeapSnapshotInstancesDataGridTree extends WI.HeapSnapshotDataGridTree
{get alwaysShowRetainedSize()
{return false;}
populateTopLevel()
{let skipInternalOnlyObjects=!WI.settings.engineeringShowInternalObjectsInHeapSnapshot.value;for(let[className,{size,retainedSize,count,internalCount,deadCount,objectCount}]of this.heapSnapshot.categories){if(skipInternalOnlyObjects&&count===internalCount)
continue; let liveCount=count-deadCount;if(!liveCount)
continue;let isObjectSubcategory=(objectCount/count)>0.5;this.appendChild(new WI.HeapSnapshotClassDataGridNode({className,size,retainedSize,isObjectSubcategory,count:liveCount},this));}
this.didPopulate();}
removeCollectedNodes(collectedNodes)
{for(let classDataGridNode of this.children){let{count,deadCount}=this.heapSnapshot.categories.get(classDataGridNode.data.className);let liveCount=count-deadCount;classDataGridNode.updateCount(liveCount);if(liveCount)
classDataGridNode.removeCollectedNodes(collectedNodes);}
this.didPopulate();}};WI.HeapSnapshotObjectGraphDataGridTree=class HeapSnapshotInstancesDataGridTree extends WI.HeapSnapshotDataGridTree
{get alwaysShowRetainedSize()
{return true;}
populateTopLevel()
{ this.heapSnapshot.instancesWithClassName("GlobalObject",(instances)=>{for(let instance of instances)
this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this));});this.heapSnapshot.instancesWithClassName("CallbackGlobalObject",(instances)=>{for(let instance of instances)
this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this));});this.heapSnapshot.instancesWithClassName("Window",(instances)=>{for(let instance of instances){
if(instance.dominatorNodeIdentifier===0)
this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this));}
this.didPopulate();});}};WI.HeapSnapshotInstanceDataGridNode=class HeapSnapshotInstanceDataGridNode extends WI.DataGridNode
{constructor(node,tree,edge,base)
{let hasChildren=node.hasChildren&&node.className!=="string";super(node,{hasChildren,copyable:false});this._node=node;this._tree=tree;this._edge=edge||null;this._base=base||null;if(hasChildren)
this.addEventListener(WI.DataGridNode.Event.Populate,this._populate,this);} 
static logHeapSnapshotNode(node)
{node.shortestGCRootPath((gcRootPath)=>{let text=WI.UIString("Heap Snapshot Object (%s)").format("@"+node.id);let addSpecialUserLogClass=!gcRootPath.length;if(gcRootPath.length){gcRootPath=gcRootPath.slice().reverse();let windowIndex=gcRootPath.findIndex((x)=>{return x instanceof WI.HeapSnapshotNodeProxy&&x.className==="Window";});let heapSnapshotRootPath=WI.HeapSnapshotRootPath.emptyPath();for(let i=windowIndex===-1?0:windowIndex;i<gcRootPath.length;++i){let component=gcRootPath[i];if(component instanceof WI.HeapSnapshotNodeProxy){if(component.className==="Window")
heapSnapshotRootPath=heapSnapshotRootPath.appendGlobalScopeName(component,"window");}else if(component instanceof WI.HeapSnapshotEdgeProxy)
heapSnapshotRootPath=heapSnapshotRootPath.appendEdge(component);}
if(heapSnapshotRootPath.isFullPathImpossible())
addSpecialUserLogClass=true;else
text=heapSnapshotRootPath.fullPath;}
const shouldRevealConsole=true;if(node.className==="string"){WI.heapManager.getPreview(node,function(error,string,functionDetails,objectPreviewPayload){let remoteObject=error?WI.RemoteObject.fromPrimitiveValue(undefined):WI.RemoteObject.fromPrimitiveValue(string);WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass,shouldRevealConsole);});}else{WI.heapManager.getRemoteObject(node,WI.RuntimeManager.ConsoleObjectGroup,function(error,remoteObjectPayload){let remoteObject=error?WI.RemoteObject.fromPrimitiveValue(undefined):WI.RemoteObject.fromPayload(remoteObjectPayload,WI.assumingMainTarget());WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass,shouldRevealConsole);});}});} 
get data(){return this._node;}
get node(){return this._node;}
get propertyName()
{if(!this._edge)
return"";if(!this._propertyName)
this._propertyName=WI.HeapSnapshotRootPath.pathComponentForIndividualEdge(this._edge);return this._propertyName;}
createCells()
{super.createCells();this.element.classList.add("instance");}
createCellContent(columnIdentifier)
{if(columnIdentifier==="retainedSize"){let subRetainedSize=false;if(this._base&&!this._tree.alwaysShowRetainedSize){if(this._isDominatedByNonBaseParent())
subRetainedSize=true;else if(!this._isDominatedByBase())
return emDash;}
let size=this._node.retainedSize;let fragment=document.createDocumentFragment();let sizeElement=fragment.appendChild(document.createElement("span"));sizeElement.classList.add("size");sizeElement.textContent=Number.bytesToString(size);let fraction=size/this._tree._heapSnapshot.totalSize;let percentElement=fragment.appendChild(document.createElement("span"));percentElement.classList.add("percentage");percentElement.textContent=Number.percentageString(fraction);if(subRetainedSize){sizeElement.classList.add("sub-retained");percentElement.classList.add("sub-retained");}
return fragment;}
if(columnIdentifier==="size")
return Number.bytesToString(this._node.size);if(columnIdentifier==="className"){let{className,id,internal,isObjectType}=this._node;let containerElement=document.createElement("span");containerElement.addEventListener("contextmenu",this._contextMenuHandler.bind(this));let iconElement=containerElement.appendChild(document.createElement("img"));iconElement.classList.add("icon",WI.HeapSnapshotClusterContentView.iconStyleClassNameForClassName(className,internal,isObjectType));if(this._edge){let nameElement=containerElement.appendChild(document.createElement("span"));let propertyName=this.propertyName;if(propertyName)
nameElement.textContent=propertyName+": "+this._node.className+" ";else
nameElement.textContent=this._node.className+" ";}
let idElement=containerElement.appendChild(document.createElement("span"));idElement.classList.add("object-id");idElement.textContent="@"+id;idElement.addEventListener("click",WI.HeapSnapshotInstanceDataGridNode.logHeapSnapshotNode.bind(null,this._node));idElement.addEventListener("mouseover",this._mouseoverHandler.bind(this));let spacerElement=containerElement.appendChild(document.createElement("span"));spacerElement.textContent=" ";if(className==="Window"&&this._node.dominatorNodeIdentifier===0){containerElement.append("Window ");this._populateWindowPreview(containerElement);}else
this._populatePreview(containerElement);return containerElement;}
return super.createCellContent(columnIdentifier);}
sort()
{let children=this.children;children.sort(this._tree._sortComparator);for(let i=0;i<children.length;++i){children[i]._recalculateSiblings(i);children[i].sort();}} 
_isDominatedByBase()
{return this._node.dominatorNodeIdentifier===this._base.node.id;}
_isDominatedByNonBaseParent()
{for(let p=this.parent;p;p=p.parent){if(p===this._base)
return false;if(this._node.dominatorNodeIdentifier===p.node.id)
return true;}
return false;}
_populate()
{this.removeEventListener(WI.DataGridNode.Event.Populate,this._populate,this);function propertyName(edge){return edge?WI.HeapSnapshotRootPath.pathComponentForIndividualEdge(edge):"";}
this._node.retainedNodes((instances,edges)=>{for(let i=0;i<instances.length;++i)
instances[i].__edge=edges[i];instances.sort((a,b)=>{let fakeDataGridNodeA={data:a,propertyName:propertyName(a.__edge)};let fakeDataGridNodeB={data:b,propertyName:propertyName(b.__edge)};return this._tree._sortComparator(fakeDataGridNodeA,fakeDataGridNodeB);});for(let instance of instances){if(instance.__edge&&instance.__edge.isPrivateSymbol())
continue;this.appendChild(new WI.HeapSnapshotInstanceDataGridNode(instance,this._tree,instance.__edge,this._base||this));}});}
_contextMenuHandler(event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Log Value"),WI.HeapSnapshotInstanceDataGridNode.logHeapSnapshotNode.bind(null,this._node));}
_populateError(containerElement)
{if(this._node.internal)
return;let previewErrorElement=containerElement.appendChild(document.createElement("span"));previewErrorElement.classList.add("preview-error");previewErrorElement.textContent=WI.UIString("No preview available");}
_populateWindowPreview(containerElement)
{const objectGroup=undefined;WI.heapManager.getRemoteObject(this._node,objectGroup,(error,remoteObjectPayload)=>{if(error){this._populateError(containerElement);return;}
function inspectedPage_window_getLocationHref(){return this.location.href;}
let remoteObject=WI.RemoteObject.fromPayload(remoteObjectPayload,WI.assumingMainTarget());remoteObject.callFunctionJSON(inspectedPage_window_getLocationHref,undefined,(href)=>{remoteObject.release();if(!href)
this._populateError(containerElement);else{let primitiveRemoteObject=WI.RemoteObject.fromPrimitiveValue(href);containerElement.appendChild(WI.FormattedValue.createElementForRemoteObject(primitiveRemoteObject));}});});}
_populatePreview(containerElement)
{WI.heapManager.getPreview(this._node,(error,string,functionDetails,objectPreviewPayload)=>{if(error){this._populateError(containerElement);return;}
if(string){if(this._node.className==="BigInt"){let bigIntRemoteObject=WI.RemoteObject.createBigIntFromDescriptionString(string+"n");containerElement.appendChild(WI.FormattedValue.createElementForRemoteObject(bigIntRemoteObject));}else{let primitiveRemoteObject=WI.RemoteObject.fromPrimitiveValue(string);containerElement.appendChild(WI.FormattedValue.createElementForRemoteObject(primitiveRemoteObject));}
return;}
if(functionDetails){let{location,name,displayName}=functionDetails;let functionNameElement=containerElement.appendChild(document.createElement("span"));functionNameElement.classList.add("function-name");functionNameElement.textContent=name||displayName||WI.UIString("(anonymous function)");let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,WI.assumingMainTarget());if(sourceCode){let locationElement=containerElement.appendChild(document.createElement("span"));locationElement.classList.add("location");let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber);sourceCodeLocation.populateLiveDisplayLocationString(locationElement,"textContent",WI.SourceCodeLocation.ColumnStyle.Hidden,WI.SourceCodeLocation.NameStyle.Short);const options={dontFloat:true,useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};let goToArrowButtonLink=WI.createSourceCodeLocationLink(sourceCodeLocation,options);containerElement.appendChild(goToArrowButtonLink);}
return;}
if(objectPreviewPayload){let objectPreview=WI.ObjectPreview.fromPayload(objectPreviewPayload);let previewElement=WI.FormattedValue.createObjectPreviewOrFormattedValueForObjectPreview(objectPreview);containerElement.appendChild(previewElement);return;}});}
_mouseoverHandler(event)
{let targetFrame=WI.Rect.rectFromClientRect(event.target.getBoundingClientRect());if(!targetFrame.size.width&&!targetFrame.size.height)
return;if(this._tree.popoverGridNode===this._node)
return;this._tree.popoverGridNode=this._node;this._tree.popoverTargetElement=event.target;let popoverContentElement=document.createElement("div");popoverContentElement.classList.add("heap-snapshot","heap-snapshot-instance-popover-content");function appendTitle(node){let idElement=document.createElement("span");idElement.classList.add("object-id");idElement.textContent="@"+node.id;idElement.addEventListener("click",WI.HeapSnapshotInstanceDataGridNode.logHeapSnapshotNode.bind(null,node));let title=popoverContentElement.appendChild(document.createElement("div"));title.classList.add("title");let localizedString=WI.UIString("Shortest property path to %s").format("@@@");let[before,after]=localizedString.split(/\s*@@@\s*/);title.append(before+" ",idElement," "+after);}
function appendPath(path){let tableContainer=popoverContentElement.appendChild(document.createElement("div"));tableContainer.classList.add("table-container");let tableElement=tableContainer.appendChild(document.createElement("table"));path=path.slice().reverse();let windowIndex=path.findIndex((x)=>{return x instanceof WI.HeapSnapshotNodeProxy&&x.className==="Window";});let edge=null;for(let i=windowIndex===-1?0:windowIndex;i<path.length;++i){let component=path[i];if(component instanceof WI.HeapSnapshotEdgeProxy){edge=component;continue;}
appendPathRow(tableElement,edge,component);edge=null;}}
function appendPathRow(tableElement,edge,node){let tableRow=tableElement.appendChild(document.createElement("tr"));let pathDataElement=tableRow.appendChild(document.createElement("td"));pathDataElement.classList.add("edge-name");if(node.className==="Window")
pathDataElement.textContent="window";else if(edge){let edgeString=stringifyEdge(edge);pathDataElement.textContent=typeof edgeString==="string"?edgeString:emDash;}else
pathDataElement.textContent=emDash;if(pathDataElement.textContent.length>10)
pathDataElement.title=pathDataElement.textContent;let objectDataElement=tableRow.appendChild(document.createElement("td"));objectDataElement.classList.add("object-data");let containerElement=objectDataElement.appendChild(document.createElement("div"));containerElement.classList.add("node");let iconElement=containerElement.appendChild(document.createElement("img"));iconElement.classList.add("icon",WI.HeapSnapshotClusterContentView.iconStyleClassNameForClassName(node.className,node.internal,node.isObjectType));let classNameElement=containerElement.appendChild(document.createElement("span"));classNameElement.textContent=sanitizeClassName(node.className)+" ";let idElement=containerElement.appendChild(document.createElement("span"));idElement.classList.add("object-id");idElement.textContent="@"+node.id;idElement.addEventListener("click",WI.HeapSnapshotInstanceDataGridNode.logHeapSnapshotNode.bind(null,node));if(node.className==="Function"){let goToArrowPlaceHolderElement=containerElement.appendChild(document.createElement("span"));goToArrowPlaceHolderElement.style.display="inline-block";goToArrowPlaceHolderElement.style.width="10px";WI.heapManager.getPreview(node,function(error,string,functionDetails,objectPreviewPayload){if(functionDetails){let location=functionDetails.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,WI.assumingMainTarget());if(sourceCode){let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber);const options={dontFloat:true,useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};let goToArrowButtonLink=WI.createSourceCodeLocationLink(sourceCodeLocation,options);containerElement.replaceChild(goToArrowButtonLink,goToArrowPlaceHolderElement);}}});}}
function sanitizeClassName(className){if(className.endsWith("LexicalEnvironment"))
return WI.UIString("Scope");return className;}
function stringifyEdge(edge){switch(edge.type){case WI.HeapSnapshotEdgeProxy.EdgeType.Property:case WI.HeapSnapshotEdgeProxy.EdgeType.Variable:if(/^(?![0-9])\w+$/.test(edge.data))
return edge.data;return"["+doubleQuotedString(edge.data)+"]";case WI.HeapSnapshotEdgeProxy.EdgeType.Index:return"["+edge.data+"]";case WI.HeapSnapshotEdgeProxy.EdgeType.Internal:default:return null;}}
this._node.shortestGCRootPath((path)=>{if(!this._tree.visible)
return;if(path.length){appendTitle(this._node);appendPath(path);}else if(this._node.gcRoot){let textElement=popoverContentElement.appendChild(document.createElement("div"));textElement.textContent=WI.UIString("This object is a root");}else{let emptyElement=popoverContentElement.appendChild(document.createElement("div"));emptyElement.textContent=WI.UIString("This object is referenced by internal objects");}
this._tree.popover.presentNewContentWithFrame(popoverContentElement,targetFrame.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});}};WI.HeapSnapshotInstanceFetchMoreDataGridNode=class HeapSnapshotInstanceFetchMoreDataGridNode extends WI.DataGridNode
{constructor(tree,batchCount,remainingCount,fetchCallback)
{super();this._tree=tree;this._batchCount=batchCount;this._remainingCount=remainingCount;this._fetchCallback=fetchCallback;} 
createCellContent(columnIdentifier)
{if(columnIdentifier!=="className")
return"";let fragment=document.createDocumentFragment();if(this._batchCount){let buttonElement=fragment.appendChild(document.createElement("span"));buttonElement.classList.add("more");buttonElement.textContent=WI.UIString("Show %d More").format(this._batchCount);buttonElement.addEventListener("click",(event)=>{this._fetchCallback(this._batchCount);});}
let buttonElement=fragment.appendChild(document.createElement("span"));buttonElement.classList.add("more");buttonElement.textContent=WI.UIString("Show Remaining (%d)").format(this._remainingCount);buttonElement.addEventListener("click",(event)=>{this._fetchCallback(this._remainingCount);});return fragment;}
sort()
{}};WI.HierarchicalPathNavigationItem=class HierarchicalPathNavigationItem extends WI.NavigationItem
{constructor(identifier,components)
{super(identifier);this._collapsedComponent=null;this._needsUpdate=false;this.components=components;} 
get components()
{return this._components;}
set components(newComponents)
{if(!newComponents)
newComponents=[];let componentsEqual=function(a,b){let getRepresentedObjects=(component)=>component.representedObject;let representedObjectsA=a.map(getRepresentedObjects);let representedObjectsB=b.map(getRepresentedObjects);if(!Array.shallowEqual(representedObjectsA,representedObjectsB))
return false;let getExtraComparisonData=(component)=>component.comparisonData;let extraComparisonDataA=a.map(getExtraComparisonData);let extraComparisonDataB=b.map(getExtraComparisonData);return Array.shallowEqual(extraComparisonDataA,extraComparisonDataB);};if(this._components&&componentsEqual(this._components,newComponents))
return;if(this._components){for(let component of this._components)
component.removeEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._siblingPathComponentWasSelected,this);}
this._components=newComponents.slice(0);for(let component of this._components)
component.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._siblingPathComponentWasSelected,this);this._needsUpdate=true;if(this.parentNavigationBar)
this.parentNavigationBar.needsLayout();}
get lastComponent()
{return this._components.lastValue||null;}
get alwaysShowLastPathComponentSeparator()
{return this.element.classList.contains(WI.HierarchicalPathNavigationItem.AlwaysShowLastPathComponentSeparatorStyleClassName);}
set alwaysShowLastPathComponentSeparator(flag)
{if(flag)
this.element.classList.add(WI.HierarchicalPathNavigationItem.AlwaysShowLastPathComponentSeparatorStyleClassName);else
this.element.classList.remove(WI.HierarchicalPathNavigationItem.AlwaysShowLastPathComponentSeparatorStyleClassName);}
update(options={})
{this._updateComponentsIfNeeded();super.update(options);var navigationBar=this.parentNavigationBar;if(!navigationBar)
return;if(this._collapsedComponent){this.element.removeChild(this._collapsedComponent.element);this._collapsedComponent=null;}
let sizesToFit=navigationBar.sizesToFit;for(var i=0;i<this._components.length;++i){this._components[i].hidden=false;this._components[i].forcedWidth=null;this._components[i].hideTooltip=!sizesToFit;}
if(options.expandOnly)
return;if(sizesToFit)
return;var totalOtherItemsWidth=0;for(var i=0;i<navigationBar.navigationItems.length;++i){if(navigationBar.navigationItems[i]===this)
continue;if(navigationBar.navigationItems[i]instanceof WI.FlexibleSpaceNavigationItem)
continue;totalOtherItemsWidth+=navigationBar.navigationItems[i].element.realOffsetWidth;}
var thisItemWidth=0;var componentWidths=[];for(var i=0;i<this._components.length;++i){var componentWidth=this._components[i].element.realOffsetWidth;componentWidths.push(componentWidth);thisItemWidth+=componentWidth;}
var barWidth=navigationBar.element.realOffsetWidth;if(totalOtherItemsWidth+thisItemWidth<=barWidth)
return;
var widthToRemove=totalOtherItemsWidth+thisItemWidth-barWidth;for(var i=0;i<this._components.length;++i){var componentWidth=componentWidths[i];this._components[i].hideTooltip=false;var forcedWidth=componentWidth-widthToRemove;this._components[i].forcedWidth=forcedWidth;
componentWidths[i]=Math.max(this._components[i].minimumWidth,forcedWidth);widthToRemove-=componentWidth-componentWidths[i];if(widthToRemove<=0)
break;}
if(widthToRemove<=0)
return;

if(this._components.length<=3)
return;var middle=this._components.length>>1;var distance=-1;var i=middle;this._collapsedComponent=new WI.HierarchicalPathComponent(ellipsis,[]);this._collapsedComponent.collapsed=true;this.element.insertBefore(this._collapsedComponent.element,this._components[middle].element);widthToRemove+=this._collapsedComponent.minimumWidth;var hiddenDisplayNames=[];while(i>=0&&i<=this._components.length-1){if(i>0&&i<this._components.length-1){var component=this._components[i];component.hidden=true;if(distance>0)
hiddenDisplayNames.unshift(component.displayName);else
hiddenDisplayNames.push(component.displayName);widthToRemove-=componentWidths[i];if(widthToRemove<=0)
break;}
i=middle+distance;if(distance>0)
++distance;distance*=-1;}
this._collapsedComponent.element.title=hiddenDisplayNames.join("\n");} 
get additionalClassNames()
{return["hierarchical-path"];} 
_updateComponentsIfNeeded()
{if(!this._needsUpdate)
return;this._needsUpdate=false;this.element.removeChildren();this._collapsedComponent=null;for(let component of this._components)
this.element.appendChild(component.element);}
_siblingPathComponentWasSelected(event)
{this.dispatchEventToListeners(WI.HierarchicalPathNavigationItem.Event.PathComponentWasSelected,event.data);}};WI.HierarchicalPathNavigationItem.AlwaysShowLastPathComponentSeparatorStyleClassName="always-show-last-path-component-separator";WI.HierarchicalPathNavigationItem.Event={PathComponentWasSelected:"hierarchical-path-navigation-item-path-component-was-selected"};WI.HoverMenu=class HoverMenu extends WI.Object
{constructor(delegate)
{super();this.delegate=delegate;this._element=document.createElement("div");this._element.className="hover-menu";this._element.addEventListener("transitionend",this,true);this._outlineElement=this._element.appendChild(document.createElementNS("http://www.w3.org/2000/svg","svg"));this._button=this._element.appendChild(document.createElement("img"));this._button.addEventListener("click",this);} 
get element()
{return this._element;}
present(rects)
{this._outlineElement.textContent="";document.body.appendChild(this._element);this._drawOutline(rects);this._element.classList.add(WI.HoverMenu.VisibleClassName);window.addEventListener("scroll",this,true);}
dismiss(discrete)
{if(this._element.parentNode!==document.body)
return;if(discrete)
this._element.remove();this._element.classList.remove(WI.HoverMenu.VisibleClassName);window.removeEventListener("scroll",this,true);} 
handleEvent(event)
{switch(event.type){case"scroll":if(!this._element.contains(event.target))
this.dismiss(true);break;case"click":this._handleClickEvent(event);break;case"transitionend":if(!this._element.classList.contains(WI.HoverMenu.VisibleClassName))
this._element.remove();break;}} 
_handleClickEvent(event)
{if(this.delegate&&typeof this.delegate.hoverMenuButtonWasPressed==="function")
this.delegate.hoverMenuButtonWasPressed(this);}
_drawOutline(rects)
{var buttonWidth=this._button.width;var buttonHeight=this._button.height;var lastRect=rects.pop();lastRect.size.width+=buttonWidth;rects.push(lastRect);if(rects.length===1)
this._drawSingleLine(rects[0]);else if(rects.length===2&&rects[0].minX()>=rects[1].maxX())
this._drawTwoNonOverlappingLines(rects);else
this._drawOverlappingLines(rects);var bounds=WI.Rect.unionOfRects(rects).pad(3); var style=this._element.style;style.left=bounds.minX()+"px";style.top=bounds.minY()+"px";style.width=bounds.size.width+"px";style.height=bounds.size.height+"px";this._outlineElement.style.width=bounds.size.width+"px";this._outlineElement.style.height=bounds.size.height+"px";this._button.style.left=(lastRect.maxX()-bounds.minX()-buttonWidth)+"px";this._button.style.top=(lastRect.maxY()-bounds.minY()-buttonHeight)+"px";}
_addRect(rect)
{var r=4;var svgRect=document.createElementNS("http://www.w3.org/2000/svg","rect");svgRect.setAttribute("x",1);svgRect.setAttribute("y",1);svgRect.setAttribute("width",rect.size.width);svgRect.setAttribute("height",rect.size.height);svgRect.setAttribute("rx",r);svgRect.setAttribute("ry",r);return this._outlineElement.appendChild(svgRect);}
_addPath(commands,tx,ty)
{var path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d",commands.join(" "));path.setAttribute("transform","translate("+(tx+1)+","+(ty+1)+")");return this._outlineElement.appendChild(path);}
_drawSingleLine(rect)
{this._addRect(rect.pad(2));}
_drawTwoNonOverlappingLines(rects)
{var r=4;var firstRect=rects[0].pad(2);var secondRect=rects[1].pad(2);var tx=-secondRect.minX();var ty=-firstRect.minY();var rect=firstRect;this._addPath(["M",rect.maxX(),rect.minY(),"H",rect.minX()+r,"q",-r,0,-r,r,"V",rect.maxY()-r,"q",0,r,r,r,"H",rect.maxX()],tx,ty);rect=secondRect;this._addPath(["M",rect.minX(),rect.minY(),"H",rect.maxX()-r,"q",r,0,r,r,"V",rect.maxY()-r,"q",0,r,-r,r,"H",rect.minX()],tx,ty);}
_drawOverlappingLines(rects)
{var PADDING=2;var r=4;var minX=Number.MAX_VALUE;var maxX=-Number.MAX_VALUE;for(var rect of rects){var minX=Math.min(rect.minX(),minX);var maxX=Math.max(rect.maxX(),maxX);}
minX-=PADDING;maxX+=PADDING;var minY=rects[0].minY()-PADDING;var maxY=rects.lastValue.maxY()+PADDING;var firstLineMinX=rects[0].minX()-PADDING;var lastLineMaxX=rects.lastValue.maxX()+PADDING;if(firstLineMinX===minX&&lastLineMaxX===maxX)
return this._addRect(new WI.Rect(minX,minY,maxX-minX,maxY-minY));var lastLineMinY=rects.lastValue.minY()+PADDING;if(rects[0].minX()===minX+PADDING){return this._addPath(["M",minX+r,minY,"H",maxX-r,"q",r,0,r,r,"V",lastLineMinY-r,"q",0,r,-r,r,"H",lastLineMaxX+r,"q",-r,0,-r,r,"V",maxY-r,"q",0,r,-r,r,"H",minX+r,"q",-r,0,-r,-r,"V",minY+r,"q",0,-r,r,-r],-minX,-minY);}
var firstLineMaxY=rects[0].maxY()-PADDING;if(rects.lastValue.maxX()===maxX-PADDING){return this._addPath(["M",firstLineMinX+r,minY,"H",maxX-r,"q",r,0,r,r,"V",maxY-r,"q",0,r,-r,r,"H",minX+r,"q",-r,0,-r,-r,"V",firstLineMaxY+r,"q",0,-r,r,-r,"H",firstLineMinX-r,"q",r,0,r,-r,"V",minY+r,"q",0,-r,r,-r],-minX,-minY);}
return this._addPath(["M",firstLineMinX+r,minY,"H",maxX-r,"q",r,0,r,r,"V",lastLineMinY-r,"q",0,r,-r,r,"H",lastLineMaxX+r,"q",-r,0,-r,r,"V",maxY-r,"q",0,r,-r,r,"H",minX+r,"q",-r,0,-r,-r,"V",firstLineMaxY+r,"q",0,-r,r,-r,"H",firstLineMinX-r,"q",r,0,r,-r,"V",minY+r,"q",0,-r,r,-r],-minX,-minY);}};WI.HoverMenu.VisibleClassName="visible";WI.IdleTreeElement=class IdleTreeElement extends WI.GeneralTreeElement
{constructor()
{super("idle",WI.UIString("Idle"));}};WI.ImageResourceContentView=class ImageResourceContentView extends WI.ResourceContentView
{constructor(resource,{disableInteractions}={})
{super(resource,"image");this._imageElement=null;this._draggingInternalImageElement=false;this._disableInteractions=disableInteractions||false;const toolTip=WI.repeatedUIString.showTransparencyGridTooltip();const activatedToolTip=WI.UIString("Hide transparency grid");this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",toolTip,activatedToolTip,"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showGridButtonClicked,this);this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;if(!this._disableInteractions){this._resetGestureButtonNavitationItem=new WI.ButtonNavigationItem("image-gesture-reset","");this._resetGestureButtonNavitationItem.tooltip=WI.UIString("Click to reset","Click to reset @ Image Resource Content View Gesture Controls","Title of text button that resets the gesture controls in the image resource content view.");this._resetGestureButtonNavitationItem.hidden=true;this._resetGestureButtonNavitationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleResetGestureButtonNavitationItemClicked,this);this._zoomOutGestureButtonNavitationItem=new WI.ButtonNavigationItem("image-gesture-zoom-out",WI.UIString("Zoom Out","Zoom Out @ Image Resource Content View Gesture Controls","Title of image button that decreases the zoom of the image resource content view."),"Images/ZoomOut.svg",16,16);this._zoomOutGestureButtonNavitationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._zoomOutGestureButtonNavitationItem.hidden=true;this._zoomOutGestureButtonNavitationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleZoomOutGestureButtonNavitationItemClicked,this);this._zoomInGestureButtonNavitationItem=new WI.ButtonNavigationItem("image-gesture-zoom-in",WI.UIString("Zoom In","Zoom In @ Image Resource Content View Gesture Controls","Title of image button that increases the zoom of the image resource content view."),"Images/ZoomIn.svg",16,16);this._zoomInGestureButtonNavitationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._zoomInGestureButtonNavitationItem.hidden=true;this._zoomInGestureButtonNavitationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleZoomInGestureButtonNavitationItemClicked,this);this._gestureNavigationItemsDivider=new WI.DividerNavigationItem;this._gestureNavigationItemsDivider.hidden=true;}} 
get navigationItems()
{let items=[];if(!this._disableInteractions){items.push(this._resetGestureButtonNavitationItem);items.push(this._zoomOutGestureButtonNavitationItem);items.push(this._zoomInGestureButtonNavitationItem);items.push(new WI.DividerNavigationItem);}
items.pushAll(super.navigationItems);items.push(this._showGridButtonNavigationItem);return items;}
contentAvailable(content,base64Encoded)
{this.removeLoadingIndicator();if(!content){this.showGenericNoContentMessage();return;}
let objectURL=this.resource.createObjectURL();if(!objectURL){this.showGenericErrorMessage();return;}
this._imageContainer=this.element.appendChild(document.createElement("div"));this._imageContainer.className="img-container";this._imageElement=this._imageContainer.appendChild(document.createElement("img"));this._imageElement.addEventListener("load",function(){URL.revokeObjectURL(objectURL);});this._imageElement.src=objectURL;this._imageElement.setAttribute("filename",this.resource.urlComponents.lastPathComponent||"");this._imageElement.draggable=true;this._updateImageGrid();this._imageElement.addEventListener("dragstart",(event)=>{this._draggingInternalImageElement=true;});this._imageElement.addEventListener("dragend",(event)=>{this._draggingInternalImageElement=false;});if(!this._disableInteractions){this._gestureController=new WI.GestureController(this._imageElement,this,{container:this._imageContainer,supportsScale:true,supportsTranslate:true});this._resetGestureButtonNavitationItem.hidden=false;this._zoomOutGestureButtonNavitationItem.hidden=false;this._zoomInGestureButtonNavitationItem.hidden=false;this._gestureNavigationItemsDivider.hidden=false;this._updateResetGestureButtonNavigationItemLabel();if(WI.NetworkManager.supportsOverridingResponses()){let dropZoneView=new WI.DropZoneView(this);dropZoneView.targetElement=this._imageContainer;this.addSubview(dropZoneView);if(this.resource.localResourceOverride)
this.resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._handleLocalResourceContentDidChange,this);}}} 
attached()
{super.attached();this._updateImageGrid();WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);}
detached()
{WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);super.detached();} 
gestureControllerDidScale(gestureController)
{this._imageElement.style.setProperty("scale",this._gestureController.scale);this._updateResetGestureButtonNavigationItemLabel();}
gestureControllerDidTranslate(gestureController,x,y)
{this._imageElement.style.setProperty("translate",`${this._gestureController.translate.x}px ${this._gestureController.translate.y}px`);} 
dropZoneShouldAppearForDragEvent(dropZone,event)
{if(this._draggingInternalImageElement)
return false;let existingOverrides=WI.networkManager.localResourceOverridesForURL(this.resource.url);if(existingOverrides.length>1)
return false;let localResourceOverride=this.resource.localResourceOverride||existingOverrides[0];if(localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.Request)
return false;return event.dataTransfer.types.includes("Files");}
dropZoneHandleDragEnter(dropZone,event)
{if(this.resource.localResourceOverride)
dropZone.text=WI.UIString("Update Image");else if(WI.networkManager.localResourceOverridesForURL(this.resource.url).length)
dropZone.text=WI.UIString("Update Local Override");else
dropZone.text=WI.UIString("Create Local Override");}
dropZoneHandleDrop(dropZone,event)
{let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;}
WI.FileUtilities.readData(files,async({dataURL,mimeType,base64Encoded,content})=>{let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this.resource.url)[0];if(!localResourceOverride){localResourceOverride=await this.resource.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response);WI.networkManager.addLocalResourceOverride(localResourceOverride);}
let revision=localResourceOverride.localResource.editableRevision;revision.updateRevisionContent(content,{base64Encoded,mimeType});if(!this.resource.localResourceOverride)
WI.showLocalResourceOverride(localResourceOverride);});} 
_updateImageGrid()
{if(!this._imageElement)
return;let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;this._imageElement.classList.toggle("show-grid",activated);}
_updateResetGestureButtonNavigationItemLabel()
{const precision=0;this._resetGestureButtonNavitationItem.label=Number.percentageString(this._gestureController.scale,precision);}
_showGridButtonClicked(event)
{WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;this._updateImageGrid();}
_handleResetGestureButtonNavitationItemClicked(event)
{this._gestureController.reset();}
_handleZoomOutGestureButtonNavitationItemClicked(event)
{this._gestureController.scale/=2;}
_handleZoomInGestureButtonNavitationItemClicked(event)
{this._gestureController.scale*=2;}
_handleLocalResourceContentDidChange(event)
{this._imageElement.src=this.resource.createObjectURL();}};WI.IndeterminateProgressSpinner=class IndeterminateProgressSpinner extends WI.Object
{constructor()
{super();this._element=document.createElement("div");this._element.classList.add("indeterminate-progress-spinner");} 
get element()
{return this._element;}};WI.IndeterminateProgressSpinnerNavigationItem=class IndeterminateProgressSpinnerNavigationItem extends WI.NavigationItem
{constructor(identifier,tooltip)
{super(identifier);this.element.classList.add("indeterminate-progress-spinner-item");this._spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(this._spinner.element);this.tooltip=tooltip??"";}};WI.IndexedDatabaseContentView=class IndexedDatabaseContentView extends WI.ContentView
{constructor(database)
{super(database);this._element.classList.add("indexed-database");this._databaseHostRow=new WI.DetailsSectionSimpleRow(WI.UIString("Host"));this._databaseSecurityOriginRow=new WI.DetailsSectionSimpleRow(WI.UIString("Security Origin"));this._databaseVersionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Version"));this._databaseGroup=new WI.DetailsSectionGroup([this._databaseHostRow,this._databaseSecurityOriginRow,this._databaseVersionRow]);this._databaseSection=new WI.DetailsSection("indexed-database-details",WI.UIString("Database"),[this._databaseGroup]);this.element.append(this._databaseSection.element);this._databaseHostRow.value=database.host;this._databaseSecurityOriginRow.value=database.securityOrigin;this._databaseVersionRow.value=database.version.toLocaleString();}};WI.IndexedDatabaseDetailsSidebarPanel=class IndexedDatabaseDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("indexed-database-details",WI.UIString("Storage"));this.element.classList.add("indexed-database");this._database=null;this._objectStore=null;this._index=null;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];this._database=null;this._objectStore=null;this._index=null;for(let object of objects){if(object instanceof WI.IndexedDatabaseObjectStore){this._objectStore=object;this._database=this._objectStore.parentDatabase;}else if(object instanceof WI.IndexedDatabaseObjectStoreIndex){this._index=object;this._objectStore=this._index.parentObjectStore;this._database=this._objectStore.parentDatabase;}}
let hasObject=this._database||this._objectStore||this._index;if(hasObject)
this.needsLayout();return hasObject;} 
initialLayout()
{super.initialLayout();this._databaseNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._databaseVersionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Version"));this._databaseSecurityOriginRow=new WI.DetailsSectionSimpleRow(WI.UIString("Security Origin"));let databaseGroup=new WI.DetailsSectionGroup([this._databaseNameRow,this._databaseVersionRow,this._databaseSecurityOriginRow]);this._databaseSection=new WI.DetailsSection("indexed-database-database",WI.UIString("Database"),[databaseGroup]);this._objectStoreNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._objectStoreKeyPathRow=new WI.DetailsSectionSimpleRow(WI.UIString("Key Path"));this._objectStoreAutoIncrementRow=new WI.DetailsSectionSimpleRow(WI.UIString("Auto Increment"));let objectStoreGroup=new WI.DetailsSectionGroup([this._objectStoreNameRow,this._objectStoreKeyPathRow,this._objectStoreAutoIncrementRow]);this._objectStoreSection=new WI.DetailsSection("indexed-database-object-store",WI.UIString("Object Store"),[objectStoreGroup]);this._indexNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._indexKeyPathRow=new WI.DetailsSectionSimpleRow(WI.UIString("Key Path"));this._indexUniqueRow=new WI.DetailsSectionSimpleRow(WI.UIString("Unique"));this._indexMultiEntryRow=new WI.DetailsSectionSimpleRow(WI.UIString("Multi-Entry"));let indexGroup=new WI.DetailsSectionGroup([this._indexNameRow,this._indexKeyPathRow,this._indexUniqueRow,this._indexMultiEntryRow]);this._indexSection=new WI.DetailsSection("indexed-database-index",WI.UIString("Index"),[indexGroup]);this.contentView.element.appendChild(this._databaseSection.element);this.contentView.element.appendChild(this._objectStoreSection.element);this.contentView.element.appendChild(this._indexSection.element);}
layout()
{super.layout();if(!this._database)
this._databaseSection.element.hidden=true;else{this._databaseSection.element.hidden=false;this._databaseSecurityOriginRow.value=this._database.securityOrigin;this._databaseNameRow.value=this._database.name;this._databaseVersionRow.value=this._database.version.toLocaleString();}
if(!this._objectStore)
this._objectStoreSection.element.hidden=true;else{this._objectStoreSection.element.hidden=false;this._objectStoreNameRow.value=this._objectStore.name;this._objectStoreKeyPathRow.value=this._keyPathString(this._objectStore.keyPath);this._objectStoreAutoIncrementRow.value=this._objectStore.autoIncrement?WI.UIString("Yes"):WI.UIString("No");}
if(!this._index)
this._indexSection.element.hidden=true;else{this._indexSection.element.hidden=false;this._indexNameRow.value=this._index.name;this._indexKeyPathRow.value=this._keyPathString(this._index.keyPath);this._indexUniqueRow.value=this._index.unique?WI.UIString("Yes"):WI.UIString("No");if(this._index.keyPath.type!==InspectorBackend.Enum.IndexedDB.KeyPathType.Array)
this._indexMultiEntryRow.value=null;else
this._indexMultiEntryRow.value=this._index.multiEntry?WI.UIString("Yes"):WI.UIString("No");}} 
_keyPathString(keyPath)
{return keyPath?JSON.stringify(keyPath):emDash;}};WI.IndexedDatabaseEntryDataGridNode=class IndexedDatabaseEntryDataGridNode extends WI.DataGridNode
{constructor(entry)
{super(entry);this._entry=entry;} 
get entry()
{return this._entry;}
createCellContent(columnIdentifier,cell)
{var value=this._entry[columnIdentifier];if(value instanceof WI.RemoteObject)
return WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(value,null,true);return super.createCellContent(columnIdentifier,cell);}};WI.IndexedDatabaseHostTreeElement=class IndexedDatabaseHostTreeElement extends WI.StorageTreeElement
{constructor(host)
{super(WI.FolderTreeElement.FolderIconStyleClassName,WI.displayNameForHost(host),null);this._host=host;this.hasChildren=true;this.expanded=true;} 
get name()
{return WI.displayNameForHost(this._host);}
get categoryName()
{return WI.UIString("Indexed Databases");}};WI.IndexedDatabaseObjectStoreContentView=class IndexedDatabaseObjectStoreContentView extends WI.ContentView
{constructor(objectStoreOrIndex)
{super(objectStoreOrIndex);this.element.classList.add("indexed-database-object-store");if(objectStoreOrIndex instanceof WI.IndexedDatabaseObjectStore){this._objectStore=objectStoreOrIndex;this._objectStoreIndex=null;}else if(objectStoreOrIndex instanceof WI.IndexedDatabaseObjectStoreIndex){this._objectStore=objectStoreOrIndex.parentObjectStore;this._objectStoreIndex=objectStoreOrIndex;}
function displayKeyPath(keyPath)
{if(!keyPath)
return"";if(keyPath instanceof Array)
return keyPath.join(WI.UIString(", "));return keyPath;}
var displayPrimaryKeyPath=displayKeyPath(this._objectStore.keyPath);var columnInfo={primaryKey:{title:displayPrimaryKeyPath?WI.UIString("Primary Key \u2014 %s").format(displayPrimaryKeyPath):WI.UIString("Primary Key")},key:{},value:{title:WI.UIString("Value")}};if(this._objectStoreIndex){var displayIndexKeyPath=displayKeyPath(this._objectStoreIndex.keyPath);columnInfo.key.title=WI.UIString("Index Key \u2014 %s").format(displayIndexKeyPath);}else{
delete columnInfo.key;}
this._dataGrid=new WI.DataGrid(columnInfo);this._dataGrid.variableHeightRows=true;this._dataGrid.filterDelegate=this;this._dataGrid.scrollContainer.addEventListener("scroll",this._dataGridScrolled.bind(this));this.addSubview(this._dataGrid);this._entries=[];this._fetchingMoreData=false;this._fetchMoreData();this._filterBarNavigationItem=new WI.FilterBarNavigationItem;this._filterBarNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._handleFilterBarFilterDidChange,this);this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("indexed-database-object-store-refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshButtonClicked,this);this._clearButtonNavigationItem=new WI.ButtonNavigationItem("indexed-database-object-store-clear",WI.UIString("Clear object store"),"Images/NavigationItemTrash.svg",15,15);this._clearButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._clearButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearButtonClicked,this);} 
get navigationItems()
{return[this._filterBarNavigationItem,new WI.DividerNavigationItem,this._refreshButtonNavigationItem,this._clearButtonNavigationItem,];}
closed()
{super.closed();this._reset();}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.IndexedDatabaseObjectStore;cookie.securityOrigin=this._objectStore.parentDatabase.securityOrigin;cookie.databaseName=this._objectStore.parentDatabase.name;cookie.objectStoreName=this._objectStore.name;cookie.objectStoreIndexName=this._objectStoreIndex&&this._objectStoreIndex.name;}
get scrollableElements()
{return[this._dataGrid.scrollContainer];}
get canFocusFilterBar()
{return true;}
focusFilterBar()
{this._filterBarNavigationItem.filterBar.focus();} 
dataGridMatchNodeAgainstCustomFilters(node)
{let filterBar=this._filterBarNavigationItem.filterBar;filterBar.invalid=false;let filterText=filterBar.filters.text;if(!filterText)
return true;let regex=WI.SearchUtilities.filterRegExpForString(filterText,WI.SearchUtilities.defaultSettings);if(!regex){filterBar.invalid=true;return true;}
for(let child of node.element.children){if(regex.test(child.textContent))
return true;}
return false;} 
_reset()
{for(var entry of this._entries){entry.primaryKey.release();entry.key.release();entry.value.release();}
this._entries=[];this._dataGrid.removeChildren();}
_dataGridScrolled()
{if(!this._moreEntriesAvailable||!this._dataGrid.isScrolledToLastRow())
return;this._fetchMoreData();}
_fetchMoreData()
{if(this._fetchingMoreData)
return;function processEntries(entries,moreAvailable)
{this._entries.pushAll(entries);this._moreEntriesAvailable=moreAvailable;for(var entry of entries){var dataGridNode=new WI.IndexedDatabaseEntryDataGridNode(entry);this._dataGrid.appendChild(dataGridNode);}
this._fetchingMoreData=false;if(moreAvailable&&this._dataGrid.isScrolledToLastRow())
this._fetchMoreData();}
this._fetchingMoreData=true;WI.indexedDBManager.requestIndexedDatabaseData(this._objectStore,this._objectStoreIndex,this._entries.length,25,processEntries.bind(this));}
_handleFilterBarFilterDidChange(event)
{this._dataGrid.filterDidChange();}
_refreshButtonClicked()
{this._reset();this._fetchMoreData();}
_clearButtonClicked()
{WI.indexedDBManager.clearObjectStore(this._objectStore);this._reset();}};WI.IndexedDatabaseObjectStoreIndexTreeElement=class IndexedDatabaseObjectStoreIndexTreeElement extends WI.GeneralTreeElement
{constructor(objectStoreIndex)
{const subtitle=null;super("database-table-icon",objectStoreIndex.name,subtitle,objectStoreIndex);this._objectStoreIndex=objectStoreIndex;} 
get objectStoreIndex()
{return this._objectStoreIndex;}};WI.IndexedDatabaseObjectStoreTreeElement=class IndexedDatabaseObjectStoreTreeElement extends WI.GeneralTreeElement
{constructor(objectStore)
{const subtitle=null;super("database-table-icon",objectStore.name,subtitle,objectStore,{hasChildren:!!objectStore.indexes.length});this._objectStore=objectStore;} 
get objectStore()
{return this._objectStore;}
oncollapse()
{this.shouldRefreshChildren=true;}
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();for(var objectStoreIndex of this._objectStore.indexes)
this.appendChild(new WI.IndexedDatabaseObjectStoreIndexTreeElement(objectStoreIndex));}};WI.IndexedDatabaseTreeElement=class IndexedDatabaseTreeElement extends WI.GeneralTreeElement
{constructor(indexedDatabase)
{const subtitle=null;super("database-icon",indexedDatabase.name,subtitle,indexedDatabase,{hasChildren:!!indexedDatabase.objectStores.length});this._indexedDatabase=indexedDatabase;} 
get indexedDatabase()
{return this._indexedDatabase;}
oncollapse()
{this.shouldRefreshChildren=true;}
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();for(var objectStore of this._indexedDatabase.objectStores)
this.appendChild(new WI.IndexedDatabaseObjectStoreTreeElement(objectStore));}};WI.InlineSwatch=class InlineSwatch extends WI.Object
{constructor(type,value,readOnly)
{super();this._type=type;switch(this._type){case WI.InlineSwatch.Type.Bezier:case WI.InlineSwatch.Type.Spring:this._swatchElement=WI.ImageUtilities.useSVGSymbol("Images/CubicBezier.svg");break;case WI.InlineSwatch.Type.BoxShadow:this._swatchElement=WI.ImageUtilities.useSVGSymbol("Images/BoxShadow.svg");break;case WI.InlineSwatch.Type.Variable:this._swatchElement=WI.ImageUtilities.useSVGSymbol("Images/CSSVariable.svg");break;default:this._swatchElement=document.createElement("span");break;}
this._swatchElement.classList.add("inline-swatch",this._type.replace("inline-swatch-type-",""));if(readOnly)
this._swatchElement.classList.add("read-only");else{switch(this._type){case WI.InlineSwatch.Type.Bezier:this._swatchElement.title=WI.UIString("Edit \u201Ccubic-bezier\u201D function");break;case WI.InlineSwatch.Type.BoxShadow:this._swatchElement.title=WI.UIString("Edit \u201Cbox-shadow\u201D");break;case WI.InlineSwatch.Type.Color:this._shiftClickColorEnabled=true;break;case WI.InlineSwatch.Type.Gradient:this._swatchElement.title=WI.UIString("Edit custom gradient");break;case WI.InlineSwatch.Type.Image:this._swatchElement.title=WI.UIString("View Image");break;case WI.InlineSwatch.Type.Spring:this._swatchElement.title=WI.UIString("Edit \u201Cspring\u201D function");break;case WI.InlineSwatch.Type.Variable:this._swatchElement.title=WI.UIString("Click to view variable value\nShift-click to replace variable with value");break;default:WI.reportInternalError(`Unknown InlineSwatch type "${type}"`);break;}
this._swatchElement.addEventListener("click",this._swatchElementClicked.bind(this));if(this._type===WI.InlineSwatch.Type.Color)
this._swatchElement.addEventListener("contextmenu",this._handleContextMenuEvent.bind(this));}
this._swatchInnerElement=this._swatchElement.createChild("span");this._value=value||this._fallbackValue();this._valueEditor=null;this._readOnly=readOnly;this._updateSwatch();} 
get element()
{return this._swatchElement;}
get value()
{if(typeof this._value==="function")
return this._value();return this._value;}
set value(value)
{this._value=value;this._updateSwatch(true);}
set shiftClickColorEnabled(value)
{this._shiftClickColorEnabled=!!value;this._updateSwatch(true);} 
didDismissPopover(popover)
{if(!this._valueEditor)
return;if(this._valueEditor.removeListeners)
this._valueEditor.removeListeners();if(this._valueEditor instanceof WI.BezierEditor)
this._valueEditor.removeEventListener(WI.BezierEditor.Event.BezierChanged,this._valueEditorValueDidChange,this);else if(this._valueEditor instanceof WI.BoxShadowEditor)
this._valueEditor.removeEventListener(WI.BoxShadowEditor.Event.BoxShadowChanged,this._valueEditorValueDidChange,this);else if(this._valueEditor instanceof WI.ColorPicker)
this._valueEditor.removeEventListener(WI.ColorPicker.Event.ColorChanged,this._valueEditorValueDidChange,this);else if(this._valueEditor instanceof WI.GradientEditor)
this._valueEditor.removeEventListener(WI.GradientEditor.Event.GradientChanged,this._valueEditorValueDidChange,this);else if(this._valueEditor instanceof WI.SpringEditor)
this._valueEditor.removeEventListener(WI.SpringEditor.Event.SpringChanged,this._valueEditorValueDidChange,this);this._valueEditor=null;this.dispatchEventToListeners(WI.InlineSwatch.Event.Deactivated);} 
_fallbackValue()
{switch(this._type){case WI.InlineSwatch.Type.Bezier:return WI.CubicBezier.fromString("linear");case WI.InlineSwatch.Type.BoxShadow:return WI.BoxShadow.fromString("none");case WI.InlineSwatch.Type.Color:return WI.Color.fromString("white");case WI.InlineSwatch.Type.Gradient:return WI.Gradient.fromString("linear-gradient(transparent, transparent)");case WI.InlineSwatch.Type.Spring:return WI.Spring.fromString("1 100 10 0");default:return null;}}
_updateSwatch(dontFireEvents)
{let value=this.value;if(this._type===WI.InlineSwatch.Type.Color||this._type===WI.InlineSwatch.Type.Gradient)
this._swatchInnerElement.style.background=value?value.toString():null;else if(this._type===WI.InlineSwatch.Type.Image)
this._swatchInnerElement.style.setProperty("background-image",`url(${value.src})`);if(this._type===WI.InlineSwatch.Type.Color){if(this._allowChangingColorFormats())
this._swatchElement.title=WI.UIString("Click to select a color\nShift-click to switch color formats");else
this._swatchElement.title=WI.UIString("Click to select a color");}
if(!dontFireEvents)
this.dispatchEventToListeners(WI.InlineSwatch.Event.ValueChanged,{value});}
_allowChangingColorFormats()
{return this._shiftClickColorEnabled&&!this._readOnly&&!this.value.isOutsideSRGB();}
_swatchElementClicked(event)
{event.stop();let value=this.value;if(event.shiftKey&&value){if(this._type===WI.InlineSwatch.Type.Color){if(!this._allowChangingColorFormats()){InspectorFrontendHost.beep();return;}
let nextFormat=value.nextFormat();if(nextFormat){value.format=nextFormat;this._updateSwatch();}
return;}
if(this._type===WI.InlineSwatch.Type.Variable){this._swatchElement.remove();this._updateSwatch();return;}}
if(this._valueEditor)
return;if(!value)
value=this._fallbackValue();let popover=new WI.Popover(this);popover.windowResizeHandler=()=>{this._presentPopover(popover);};this._valueEditor=null;switch(this._type){case WI.InlineSwatch.Type.Bezier:this._valueEditor=new WI.BezierEditor;this._valueEditor.addEventListener(WI.BezierEditor.Event.BezierChanged,this._valueEditorValueDidChange,this);break;case WI.InlineSwatch.Type.BoxShadow:this._valueEditor=new WI.BoxShadowEditor;this._valueEditor.addEventListener(WI.BoxShadowEditor.Event.BoxShadowChanged,this._valueEditorValueDidChange,this);break;case WI.InlineSwatch.Type.Color:this._valueEditor=new WI.ColorPicker;this._valueEditor.addEventListener(WI.ColorPicker.Event.ColorChanged,this._valueEditorValueDidChange,this);break;case WI.InlineSwatch.Type.Gradient:this._valueEditor=new WI.GradientEditor;this._valueEditor.addEventListener(WI.GradientEditor.Event.GradientChanged,this._valueEditorValueDidChange,this);this._valueEditor.addEventListener(WI.GradientEditor.Event.ColorPickerToggled,function(event){this.update();},popover);break;case WI.InlineSwatch.Type.Image:if(value.src){this._valueEditor={};this._valueEditor.element=document.createElement("img");this._valueEditor.element.src=value.src;this._valueEditor.element.classList.add("show-grid");this._valueEditor.element.style.setProperty("max-width","50vw");this._valueEditor.element.style.setProperty("max-height","50vh");}
break;case WI.InlineSwatch.Type.Spring:this._valueEditor=new WI.SpringEditor;this._valueEditor.addEventListener(WI.SpringEditor.Event.SpringChanged,this._valueEditorValueDidChange,this);break;case WI.InlineSwatch.Type.Variable:this._valueEditor={};this._valueEditor.element=document.createElement("div");this._valueEditor.element.classList.add("inline-swatch-variable-popover");this._valueEditor.codeMirror=WI.CodeMirrorEditor.create(this._valueEditor.element,{mode:"css",readOnly:true,});this._valueEditor.codeMirror.on("update",()=>{popover.update();});break;}
if(!this._valueEditor)
return;popover.content=this._valueEditor.element;this._presentPopover(popover);this.dispatchEventToListeners(WI.InlineSwatch.Event.Activated);switch(this._type){case WI.InlineSwatch.Type.Bezier:this._valueEditor.bezier=value;break;case WI.InlineSwatch.Type.BoxShadow:this._valueEditor.boxShadow=value;break;case WI.InlineSwatch.Type.Color:this._valueEditor.color=value;this._valueEditor.focus();break;case WI.InlineSwatch.Type.Gradient:this._valueEditor.gradient=value;break;case WI.InlineSwatch.Type.Spring:this._valueEditor.spring=value;break;case WI.InlineSwatch.Type.Variable:{let codeMirror=this._valueEditor.codeMirror;codeMirror.setValue(value);const range=null;function optionsForType(type){return{allowedTokens:/\btag\b/,callback(marker,valueObject,valueString){let swatch=new WI.InlineSwatch(type,valueObject,true);codeMirror.setUniqueBookmark({line:0,ch:0},swatch.element);}};}
createCodeMirrorColorTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Color));createCodeMirrorGradientTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Gradient));createCodeMirrorCubicBezierTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Bezier));createCodeMirrorSpringTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Spring));break;}}}
_valueEditorValueDidChange(event)
{switch(this._type){case WI.InlineSwatch.Type.BoxShadow:this._value=event.data.boxShadow;break;case WI.InlineSwatch.Type.Bezier:this._value=event.data.bezier;break;case WI.InlineSwatch.Type.Color:this._value=event.data.color;break;case WI.InlineSwatch.Type.Gradient:this._value=event.data.gradient;break;case WI.InlineSwatch.Type.Spring:this._value=event.data.spring;break;}
this._updateSwatch();}
_presentPopover(popover)
{let bounds=WI.Rect.rectFromClientRect(this._swatchElement.getBoundingClientRect());popover.present(bounds.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X]);}
_handleContextMenuEvent(event)
{let value=this.value;if(!value)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);let isColorOutsideSRGB=value.isOutsideSRGB();if(!isColorOutsideSRGB){if(value.isKeyword()&&value.format!==WI.Color.Format.Keyword){contextMenu.appendItem(WI.UIString("Format: Keyword"),()=>{value.format=WI.Color.Format.Keyword;this._updateSwatch();});}
let hexInfo=this._getNextValidHEXFormat();if(hexInfo){contextMenu.appendItem(hexInfo.title,()=>{value.format=hexInfo.format;this._updateSwatch();});}
if(value.simple&&value.format!==WI.Color.Format.HSL){contextMenu.appendItem(WI.UIString("Format: HSL"),()=>{value.format=WI.Color.Format.HSL;this._updateSwatch();});}else if(value.format!==WI.Color.Format.HSLA){contextMenu.appendItem(WI.UIString("Format: HSLA"),()=>{value.format=WI.Color.Format.HSLA;this._updateSwatch();});}
if(value.simple&&value.format!==WI.Color.Format.RGB){contextMenu.appendItem(WI.UIString("Format: RGB"),()=>{value.format=WI.Color.Format.RGB;this._updateSwatch();});}else if(value.format!==WI.Color.Format.RGBA){contextMenu.appendItem(WI.UIString("Format: RGBA"),()=>{value.format=WI.Color.Format.RGBA;this._updateSwatch();});}
if(value.format!==WI.Color.Format.ColorFunction){contextMenu.appendItem(WI.UIString("Format: Color Function"),()=>{value.format=WI.Color.Format.ColorFunction;this._updateSwatch();});}
contextMenu.appendSeparator();}
if(value.gamut!==WI.Color.Gamut.DisplayP3){contextMenu.appendItem(WI.UIString("Convert to Display-P3"),()=>{value.gamut=WI.Color.Gamut.DisplayP3;this._updateSwatch();});}
if(value.gamut!==WI.Color.Gamut.SRGB){let label=isColorOutsideSRGB?WI.UIString("Clamp to sRGB"):WI.UIString("Convert to sRGB");contextMenu.appendItem(label,()=>{value.gamut=WI.Color.Gamut.SRGB;this._updateSwatch();});}}
_getNextValidHEXFormat()
{if(this._type!==WI.InlineSwatch.Type.Color)
return false;let value=this.value;function hexMatchesCurrentColor(hexInfo){let nextIsSimple=hexInfo.format===WI.Color.Format.ShortHEX||hexInfo.format===WI.Color.Format.HEX;if(nextIsSimple&&!value.simple)
return false;let nextIsShort=hexInfo.format===WI.Color.Format.ShortHEX||hexInfo.format===WI.Color.Format.ShortHEXAlpha;if(nextIsShort&&!value.canBeSerializedAsShortHEX())
return false;return true;}
const hexFormats=[{format:WI.Color.Format.ShortHEX,title:WI.UIString("Format: Short Hex")},{format:WI.Color.Format.ShortHEXAlpha,title:WI.UIString("Format: Short Hex with Alpha")},{format:WI.Color.Format.HEX,title:WI.UIString("Format: Hex")},{format:WI.Color.Format.HEXAlpha,title:WI.UIString("Format: Hex with Alpha")}];let currentColorIsHEX=hexFormats.some((info)=>info.format===value.format);for(let i=0;i<hexFormats.length;++i){if(currentColorIsHEX&&value.format!==hexFormats[i].format)
continue;for(let j=~~currentColorIsHEX;j<hexFormats.length;++j){let nextIndex=(i+j)%hexFormats.length;if(hexMatchesCurrentColor(hexFormats[nextIndex]))
return hexFormats[nextIndex];}
return null;}
return hexFormats[0];}};WI.InlineSwatch.Type={Color:"inline-swatch-type-color",Gradient:"inline-swatch-type-gradient",Bezier:"inline-swatch-type-bezier",BoxShadow:"inline-swatch-type-box-shadow",Spring:"inline-swatch-type-spring",Variable:"inline-swatch-type-variable",Image:"inline-swatch-type-image",};WI.InlineSwatch.Event={ValueChanged:"inline-swatch-value-changed",Activated:"inline-swatch-activated",Deactivated:"inline-swatch-deactivated",};WI.InputPopover=class InputPopover extends WI.Popover
{constructor(message,delegate)
{super(delegate);this._message=message;this._value=null;this._result=WI.InputPopover.Result.None;this._targetElement=null;this._preferredEdges=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);}
get value(){return this._value;}
get result(){return this._result;}
show(targetElement,preferredEdges)
{this._targetElement=targetElement;this._preferredEdges=preferredEdges;let contentElement=document.createElement("div");contentElement.classList.add("input-popover-content");if(this._message){let label=document.createElement("div");label.classList.add("label");label.textContent=this._message;contentElement.appendChild(label);}
this._inputElement=document.createElement("input");this._inputElement.spellcheck=false;this._inputElement.addEventListener("keydown",(event)=>{if(!isEnterKey(event))
return;this._result=WI.InputPopover.Result.Committed;this._value=event.target.value;this.dismiss();});contentElement.appendChild(this._inputElement);this.content=contentElement;this._presentOverTargetElement();} 
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame,this._preferredEdges);this._inputElement.select();}};WI.InputPopover.Result={None:Symbol("result-none"),Cancelled:Symbol("result-cancelled"),Committed:Symbol("result-committed"),};WI.IssueTreeElement=class IssueTreeElement extends WI.GeneralTreeElement
{constructor(issueMessage)
{var levelStyleClassName;switch(issueMessage.level){case"error":levelStyleClassName=WI.IssueTreeElement.ErrorStyleClassName;break;case"warning":levelStyleClassName=WI.IssueTreeElement.WarningStyleClassName;break;}
const title=null;const subtitle=null;super([WI.IssueTreeElement.StyleClassName,levelStyleClassName],title,subtitle,issueMessage);this._issueMessage=issueMessage;this._updateTitles();this._issueMessage.addEventListener(WI.IssueMessage.Event.DisplayLocationDidChange,this._updateTitles,this);} 
get issueMessage()
{return this._issueMessage;} 
_updateTitles()
{if(this._issueMessage.sourceCodeLocation){let displayLineNumber=this._issueMessage.sourceCodeLocation.displayLineNumber;let displayColumnNumber=this._issueMessage.sourceCodeLocation.displayColumnNumber;var lineNumberLabel;if(displayColumnNumber>0)
lineNumberLabel=WI.UIString("Line %d:%d").format(displayLineNumber+1,displayColumnNumber+1);else
lineNumberLabel=WI.UIString("Line %d").format(displayLineNumber+1);this.mainTitle=`${lineNumberLabel} ${this._issueMessage.text}`;}else
this.mainTitle=this._issueMessage.text;}};WI.IssueTreeElement.StyleClassName="issue";WI.IssueTreeElement.ErrorStyleClassName="error";WI.IssueTreeElement.WarningStyleClassName="warning";WI.JavaScriptBreakpointTreeElement=class JavaScriptBreakpointTreeElement extends WI.BreakpointTreeElement
{constructor(breakpoint,{classNames,title}={})
{if(!Array.isArray(classNames))
classNames=["line"];classNames.push("javascript");if(!title&&breakpoint.special)
title=breakpoint.displayName;super(breakpoint,{classNames,title});} 
get filterableData()
{return{text:[this.breakpoint.contentIdentifier]};}
onattach()
{super.onattach();if(!this.breakpoint.special){this.breakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._breakpointLocationDidChange,this);this._updateTitles();}
this.breakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this.updateStatus,this);}
ondetach()
{if(!this.breakpoint.special)
this.breakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._breakpointLocationDidChange,this);this.breakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this.updateStatus,this);super.ondetach();} 
_updateTitles()
{let sourceCodeLocation=this.breakpoint.sourceCodeLocation;let displayLineNumber=sourceCodeLocation.displayLineNumber;let displayColumnNumber=sourceCodeLocation.displayColumnNumber;if(displayColumnNumber>0)
this.mainTitle=WI.UIString("Line %d:%d").format(displayLineNumber+1,displayColumnNumber+1);else
this.mainTitle=WI.UIString("Line %d").format(displayLineNumber+1);if(sourceCodeLocation.hasMappedLocation()){this.subtitle=sourceCodeLocation.formattedLocationString();if(sourceCodeLocation.hasFormattedLocation())
this.subtitleElement.classList.add("formatted-location");else
this.subtitleElement.classList.remove("formatted-location");this.tooltip=this.mainTitle+" \u2014 "+WI.UIString("originally %s").format(sourceCodeLocation.originalLocationString());}}
_breakpointLocationDidChange(event)
{if(event.data.oldDisplaySourceCode===this.breakpoint.displaySourceCode)
return;this._updateTitles();}};WI.LayerDetailsSidebarPanel=class LayerDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("layer",WI.UIString("All Layers"));this.element.classList.add("layer");this._layers=[];this._layerIdToSelect=null;this._dataGrid=null;this._hoveredDataGridNode=null;this._dataGridNodesByLayerId=new Map;this._bottomBar=null;this._bottomBarWidth=NaN;this._layersCountLabel=null;this._layersMemoryLabel=null;} 
get minimumWidth()
{let minimumWidth=super.minimumWidth;if(isNaN(this._bottomBarWidth)&&this._layersCountLabel&&this._layersMemoryLabel)
this._bottomBarWidth=this._layersCountLabel.realOffsetWidth+this._layersMemoryLabel.realOffsetWidth;if(!isNaN(this._bottomBarWidth))
minimumWidth=Math.max(minimumWidth,this._bottomBarWidth);return minimumWidth;}
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];let layers=objects.filter((object)=>object instanceof WI.Layer);this._updateLayers(layers);return!!layers.length;}
selectNodeByLayerId(layerId)
{this._layerIdToSelect=null;let node=this._dataGridNodesByLayerId.get(layerId);if(node===this._dataGrid.selectedNode)
return;const suppressEvent=true;if(node)
node.revealAndSelect(suppressEvent);else if(this._dataGrid.selectedNode)
this._dataGrid.selectedNode.deselect(suppressEvent);else
this._layerIdToSelect=layerId;} 
_buildDataGrid()
{const columns={name:{title:WI.UIString("Node"),sortable:false,},paintCount:{title:WI.UIString("Paints"),sortable:true,aligned:"right",width:"70px",},memory:{title:WI.UIString("Memory"),sortable:true,aligned:"right",width:"70px",}};this._dataGrid=new WI.DataGrid(columns);this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);this._dataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridSelectedNodeChanged,this);this._dataGrid.sortColumnIdentifier="memory";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Descending;this._dataGrid.createSettings("layer-details-sidebar-panel");this._dataGrid.element.addEventListener("mousemove",this._dataGridMouseMove.bind(this));this._dataGrid.element.addEventListener("mouseleave",this._dataGridMouseLeave.bind(this));this._dataGrid.inline=true;this._dataGrid.element.classList.remove("inline");this.contentView.addSubview(this._dataGrid);}
_buildBottomBar()
{this._bottomBar=this.element.appendChild(document.createElement("div"));this._bottomBar.className="bottom-bar";this._layersCountLabel=this._bottomBar.appendChild(document.createElement("div"));this._layersCountLabel.className="layers-count-label";this._layersMemoryLabel=this._bottomBar.appendChild(document.createElement("div"));this._layersMemoryLabel.className="layers-memory-label";this._bottomBarWidth=NaN;}
_sortDataGrid()
{let sortColumnIdentifier=this._dataGrid.sortColumnIdentifier;function comparator(a,b){let itemA=a.layer[sortColumnIdentifier]||0;let itemB=b.layer[sortColumnIdentifier]||0;return itemA-itemB;}
this._dataGrid.sortNodes(comparator);}
_dataGridSelectedNodeChanged()
{let layerId=this._dataGrid.selectedNode?this._dataGrid.selectedNode.layer.layerId:null;this.dispatchEventToListeners(WI.LayerDetailsSidebarPanel.Event.SelectedLayerChanged,{layerId});}
_dataGridMouseMove(event)
{let dataGridNode=this._dataGrid.dataGridNodeFromNode(event.target);if(dataGridNode===this._hoveredDataGridNode)
return;if(!dataGridNode){this._hideDOMNodeHighlight();return;}
this._hoveredDataGridNode=dataGridNode;let layer=dataGridNode.layer;if(layer.isGeneratedContent||layer.isReflection||layer.isAnonymous){const usePageCoordinates=true;WI.domManager.highlightRect(layer.bounds,usePageCoordinates);}else{let domNode=WI.domManager.nodeForId(layer.nodeId);if(domNode)
domNode.highlight();else
WI.domManager.hideDOMNodeHighlight();}}
_dataGridMouseLeave(event)
{this._hideDOMNodeHighlight();}
_hideDOMNodeHighlight()
{WI.domManager.hideDOMNodeHighlight();this._hoveredDataGridNode=null;}
_updateLayers(newLayers)
{this._updateDataGrid(newLayers);this._updateBottomBar(newLayers);this._layers=newLayers;}
_updateDataGrid(newLayers)
{if(!this._dataGrid)
this._buildDataGrid();let{removals,additions,preserved}=WI.layerTreeManager.layerTreeMutations(this._layers,newLayers);removals.forEach((layer)=>{let node=this._dataGridNodesByLayerId.get(layer.layerId);this._dataGrid.removeChild(node);this._dataGridNodesByLayerId.delete(layer.layerId);});additions.forEach((layer)=>{let node=new WI.LayerTreeDataGridNode(layer);this._dataGridNodesByLayerId.set(layer.layerId,node);this._dataGrid.appendChild(node);});preserved.forEach((layer)=>{let node=this._dataGridNodesByLayerId.get(layer.layerId);node.layer=layer;});this._sortDataGrid();if(this._layerIdToSelect)
this.selectNodeByLayerId(this._layerIdToSelect);}
_updateBottomBar(newLayers)
{if(!this._bottomBar)
this._buildBottomBar();this._layersCountLabel.textContent=WI.UIString("Layer Count: %d").format(newLayers.length);let totalMemory=newLayers.reduce((total,layer)=>total+(layer.memory||0),0);this._layersMemoryLabel.textContent=WI.UIString("Memory: %s").format(Number.bytesToString(totalMemory));this._bottomBarWidth=NaN;}};WI.LayerDetailsSidebarPanel.Event={SelectedLayerChanged:"selected-layer-changed"};WI.LayerTreeDataGridNode=class LayerTreeDataGridNode extends WI.DataGridNode
{constructor(layer)
{super();this._outlets={};this.layer=layer;}
createCells()
{super.createCells();this._cellsWereCreated=true;}
createCellContent(columnIdentifier,cell)
{cell=columnIdentifier==="name"?this._makeNameCell():this._makeOutlet(columnIdentifier,document.createTextNode(enDash));this._updateCell(columnIdentifier);return cell;} 
get layer()
{return this._layer;}
set layer(layer)
{this._layer=layer;var domNode=WI.domManager.nodeForId(layer.nodeId);this.data={name:domNode?domNode.displayName:WI.UIString("Unknown node"),paintCount:layer.paintCount||emDash,memory:Number.bytesToString(layer.memory||0)};}
get data()
{return this._data;}
set data(data)
{Object.keys(data).forEach(function(columnIdentifier){if(this._data[columnIdentifier]===data[columnIdentifier])
return;this._data[columnIdentifier]=data[columnIdentifier];if(this._cellsWereCreated)
this._updateCell(columnIdentifier);},this);} 
_makeOutlet(name,element)
{this._outlets[name]=element;return element;}
_makeNameCell()
{var fragment=document.createDocumentFragment();fragment.appendChild(document.createElement("img")).className="icon";var goToButton=this._makeOutlet("goToButton",fragment.appendChild(WI.createGoToArrowButton()));goToButton.addEventListener("click",this._goToArrowWasClicked.bind(this),false);var label=this._makeOutlet("label",fragment.appendChild(document.createElement("span")));label.className="label";var nameLabel=this._makeOutlet("nameLabel",label.appendChild(document.createElement("span")));nameLabel.className="name";var pseudoLabel=this._makeOutlet("pseudoLabel",document.createElement("span"));pseudoLabel.className="pseudo-element";var reflectionLabel=this._makeOutlet("reflectionLabel",document.createElement("span"));reflectionLabel.className="reflection";reflectionLabel.textContent=" \u2014 "+WI.UIString("Reflection");return fragment;}
_updateCell(columnIdentifier)
{var data=this._data[columnIdentifier];if(columnIdentifier==="name")
this._updateNameCellData(data);else
this._outlets[columnIdentifier].textContent=data;}
_updateNameCellData(data)
{var layer=this._layer;var label=this._outlets.label;this._outlets.nameLabel.textContent=data;if(WI.domManager.nodeForId(layer.nodeId))
label.parentNode.insertBefore(this._outlets.goToButton,label.parentNode.firstChild);else if(this._outlets.goToButton.parentNode)
label.parentNode.removeChild(this._outlets.goToButton);if(layer.pseudoElement)
label.appendChild(this._outlets.pseudoLabel).textContent="::"+layer.pseudoElement;else if(this._outlets.pseudoLabel.parentNode)
label.removeChild(this._outlets.pseudoLabel);if(layer.isReflection)
label.appendChild(this._outlets.reflectionLabel);else if(this._outlets.reflectionLabel.parentNode)
label.removeChild(this._outlets.reflectionLabel);var element=this.element;if(layer.isReflection)
element.classList.add("reflection");else if(layer.pseudoElement)
element.classList.add("pseudo-element");}
_goToArrowWasClicked()
{var domNode=WI.domManager.nodeForId(this._layer.nodeId);WI.showMainFrameDOMTree(domNode,{ignoreSearchTab:true});}};WI.LayerTreeDetailsSidebarPanel=class LayerTreeDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel
{constructor()
{super("layer-tree",WI.UIString("Layers"));this._dataGridNodesByLayerId=new Map;this.element.classList.add("layer-tree");}
attached()
{super.attached();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.LayerTreeDidChange,this._layerTreeDidChange,this);}
detached()
{WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.LayerTreeDidChange,this._layerTreeDidChange,this);super.detached();} 
supportsDOMNode(nodeToInspect)
{return WI.layerTreeManager.supported&&nodeToInspect.nodeType()===Node.ELEMENT_NODE;} 
initialLayout()
{super.initialLayout();this._buildLayerInfoSection();this._buildDataGridSection();this._buildBottomBar();}
layout()
{super.layout();if(!this.domNode||this.domNode.destroyed)
return;WI.layerTreeManager.layersForNode(this.domNode,(layers)=>{let layerForNode=layers[0]&&layers[0].nodeId===this.domNode.id&&!layers[0].isGeneratedContent?layers[0]:null;let childLayers=layers.slice(layerForNode?1:0);this._unfilteredChildLayers=childLayers;this._updateDisplayWithLayers(layerForNode,childLayers);});}
sizeDidChange()
{super.sizeDidChange(); this._childLayersRow.sizeDidChange();} 
_layerTreeDidChange(event)
{this.needsLayout();}
_buildLayerInfoSection()
{var rows=this._layerInfoRows={};var rowsArray=[];rowsArray.push(rows["Width"]=new WI.DetailsSectionSimpleRow(WI.UIString("Width")));rowsArray.push(rows["Height"]=new WI.DetailsSectionSimpleRow(WI.UIString("Height")));rowsArray.push(rows["Paints"]=new WI.DetailsSectionSimpleRow(WI.UIString("Paints")));rowsArray.push(rows["Memory"]=new WI.DetailsSectionSimpleRow(WI.UIString("Memory")));this._layerInfoGroup=new WI.DetailsSectionGroup(rowsArray);var emptyRow=new WI.DetailsSectionRow(WI.UIString("No Layer Available"));emptyRow.showEmptyMessage();this._noLayerInformationGroup=new WI.DetailsSectionGroup([emptyRow]);this._layerInfoSection=new WI.DetailsSection("layer-info",WI.UIString("Layer Info"),[this._noLayerInformationGroup]);this.contentView.element.appendChild(this._layerInfoSection.element);}
_buildDataGridSection()
{var columns={name:{},paintCount:{},memory:{}};columns.name.title=WI.UIString("Node");columns.name.sortable=false;columns.paintCount.title=WI.UIString("Paints","Paints @ Column title","A count of how many times an element was painted (rendered)");columns.paintCount.sortable=true;columns.paintCount.aligned="right";columns.paintCount.width="70px";columns.memory.title=WI.UIString("Memory");columns.memory.sortable=true;columns.memory.aligned="right";columns.memory.width="70px";this._dataGrid=new WI.DataGrid(columns);this._dataGrid.inline=true;this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);this._dataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._selectedDataGridNodeChanged,this);this._dataGrid.sortColumnIdentifier="memory";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Descending;this._dataGrid.createSettings("layer-tree-details-sidebar-panel");var element=this._dataGrid.element;element.addEventListener("focus",this._dataGridGainedFocus.bind(this),false);element.addEventListener("blur",this._dataGridLostFocus.bind(this),false);element.addEventListener("click",this._dataGridWasClicked.bind(this),false);this._childLayersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Child Layers"));var group=new WI.DetailsSectionGroup([this._childLayersRow]);var section=new WI.DetailsSection("layer-children",WI.UIString("Child Layers"),[group],null,true);this.contentView.element.appendChild(section.element);}
_buildBottomBar()
{var bottomBar=this.element.appendChild(document.createElement("div"));bottomBar.className="bottom-bar";this._layersCountLabel=bottomBar.appendChild(document.createElement("div"));this._layersCountLabel.className="layers-count-label";this._layersMemoryLabel=bottomBar.appendChild(document.createElement("div"));this._layersMemoryLabel.className="layers-memory-label";}
_sortDataGrid()
{var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier;function comparator(a,b)
{var item1=a.layer[sortColumnIdentifier]||0;var item2=b.layer[sortColumnIdentifier]||0;return item1-item2;}
this._dataGrid.sortNodes(comparator);this._updatePopoverForSelectedNode();}
_selectedDataGridNodeChanged()
{if(this._dataGrid.selectedNode){this._highlightSelectedNode();this._showPopoverForSelectedNode();}else{WI.domManager.hideDOMNodeHighlight();this._hidePopover();}}
_dataGridGainedFocus(event)
{this._highlightSelectedNode();this._showPopoverForSelectedNode();}
_dataGridLostFocus(event)
{WI.domManager.hideDOMNodeHighlight();this._hidePopover();}
_dataGridWasClicked(event)
{if(this._dataGrid.selectedNode&&event.target.parentNode.classList.contains("filler"))
this._dataGrid.selectedNode.deselect();}
_highlightSelectedNode()
{var dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode)
return;var layer=dataGridNode.layer;if(layer.isGeneratedContent||layer.isReflection||layer.isAnonymous)
WI.domManager.highlightRect(layer.bounds,true);else{let domNode=WI.domManager.nodeForId(layer.nodeId);if(domNode)
domNode.highlight();else
WI.domManager.hideDOMNodeHighlight();}}
_updateDisplayWithLayers(layerForNode,childLayers)
{this._updateLayerInfoSection(layerForNode);this._updateDataGrid(layerForNode,childLayers);this._updateMetrics(layerForNode,childLayers);this._layerForNode=layerForNode;this._childLayers=childLayers;}
_updateLayerInfoSection(layer)
{this._layerInfoSection.groups=layer?[this._layerInfoGroup]:[this._noLayerInformationGroup];if(!layer)
return;this._layerInfoRows["Memory"].value=Number.bytesToString(layer.memory);this._layerInfoRows["Width"].value=layer.compositedBounds.width+"px";this._layerInfoRows["Height"].value=layer.compositedBounds.height+"px";this._layerInfoRows["Paints"].value=layer.paintCount+"";}
_updateDataGrid(layerForNode,childLayers)
{let dataGrid=this._dataGrid;let mutations=WI.layerTreeManager.layerTreeMutations(this._childLayers,childLayers);mutations.removals.forEach(function(layer){let node=this._dataGridNodesByLayerId.get(layer.layerId);if(node){dataGrid.removeChild(node);this._dataGridNodesByLayerId.delete(layer.layerId);}},this);mutations.additions.forEach(function(layer){let node=this._dataGridNodeForLayer(layer);if(node)
dataGrid.appendChild(node);},this);mutations.preserved.forEach(function(layer){let node=this._dataGridNodesByLayerId.get(layer.layerId);if(node)
node.layer=layer;},this);this._sortDataGrid();this._childLayersRow.dataGrid=!isEmptyObject(childLayers)?this._dataGrid:null;}
_dataGridNodeForLayer(layer)
{let node=new WI.LayerTreeDataGridNode(layer);this._dataGridNodesByLayerId.set(layer.layerId,node);return node;}
_updateMetrics(layerForNode,childLayers)
{var layerCount=0;var totalMemory=0;if(layerForNode){layerCount++;totalMemory+=layerForNode.memory||0;}
childLayers.forEach(function(layer){layerCount++;totalMemory+=layer.memory||0;});this._layersCountLabel.textContent=WI.UIString("Layer Count: %d").format(layerCount);this._layersMemoryLabel.textContent=WI.UIString("Memory: %s").format(Number.bytesToString(totalMemory));}
_showPopoverForSelectedNode()
{var dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode)
return;this._contentForPopover(dataGridNode.layer,(content)=>{if(dataGridNode===this._dataGrid.selectedNode)
this._updatePopoverForSelectedNode(content);});}
_updatePopoverForSelectedNode(content)
{var dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode)
return;var popover=this._popover;if(!popover){popover=this._popover=new WI.Popover;popover.windowResizeHandler=()=>{this._updatePopoverForSelectedNode();};}
var targetFrame=WI.Rect.rectFromClientRect(dataGridNode.element.getBoundingClientRect());if(content)
this._popover.presentNewContentWithFrame(content,targetFrame.pad(2),[WI.RectEdge.MIN_X]);else
popover.present(targetFrame.pad(2),[WI.RectEdge.MIN_X]);}
_hidePopover()
{if(this._popover)
this._popover.dismiss();}
_contentForPopover(layer,callback)
{var content=document.createElement("div");content.className="layer-tree-popover";content.appendChild(document.createElement("p")).textContent=WI.UIString("Reasons for compositing:");var list=content.appendChild(document.createElement("ul"));WI.layerTreeManager.reasonsForCompositingLayer(layer,(compositingReasons)=>{if(isEmptyObject(compositingReasons)){callback(content);return;}
this._populateListOfCompositingReasons(list,compositingReasons);callback(content);});return content;}
_populateListOfCompositingReasons(list,compositingReasons)
{function addReason(reason)
{list.appendChild(document.createElement("li")).textContent=reason;}
if(compositingReasons.transform3D)
addReason(WI.UIString("Element has a 3D transform"));if(compositingReasons.video)
addReason(WI.UIString("Element is <video>"));if(compositingReasons.canvas)
addReason(WI.UIString("Element is <canvas>"));if(compositingReasons.plugin)
addReason(WI.UIString("Element is a plug-in"));if(compositingReasons.iFrame)
addReason(WI.UIString("Element is <iframe>"));if(compositingReasons.model)
addReason(WI.UIString("Element is <model>"));if(compositingReasons.backfaceVisibilityHidden)
addReason(WI.UIString("Element has \u201Cbackface-visibility: hidden\u201D style"));if(compositingReasons.clipsCompositingDescendants)
addReason(WI.UIString("Element clips compositing descendants"));if(compositingReasons.animation)
addReason(WI.UIString("Element is animated"));if(compositingReasons.filters)
addReason(WI.UIString("Element has CSS filters applied"));if(compositingReasons.positionFixed)
addReason(WI.UIString("Element has \u201Cposition: fixed\u201D style"));if(compositingReasons.positionSticky)
addReason(WI.UIString("Element has \u201Cposition: sticky\u201D style"));if(compositingReasons.overflowScrollingTouch)
addReason(WI.UIString("Element has \u201C-webkit-overflow-scrolling: touch\u201D style"));if(compositingReasons.stacking)
addReason(WI.UIString("Element may overlap another compositing element"));if(compositingReasons.overlap)
addReason(WI.UIString("Element overlaps other compositing element"));if(compositingReasons.negativeZIndexChildren)
addReason(WI.UIString("Element has children with a negative z-index"));if(compositingReasons.transformWithCompositedDescendants)
addReason(WI.UIString("Element has a 2D transform and composited descendants"));if(compositingReasons.opacityWithCompositedDescendants)
addReason(WI.UIString("Element has opacity applied and composited descendants"));if(compositingReasons.maskWithCompositedDescendants)
addReason(WI.UIString("Element is masked and has composited descendants"));if(compositingReasons.reflectionWithCompositedDescendants)
addReason(WI.UIString("Element has a reflection and composited descendants"));if(compositingReasons.filterWithCompositedDescendants)
addReason(WI.UIString("Element has CSS filters applied and composited descendants"));if(compositingReasons.blendingWithCompositedDescendants)
addReason(WI.UIString("Element has CSS blending applied and composited descendants"));if(compositingReasons.isolatesCompositedBlendingDescendants)
addReason(WI.UIString("Element is a stacking context and has composited descendants with CSS blending applied"));if(compositingReasons.perspective)
addReason(WI.UIString("Element has perspective applied"));if(compositingReasons.preserve3D)
addReason(WI.UIString("Element has \u201Ctransform-style: preserve-3d\u201D style"));if(compositingReasons.willChange)
addReason(WI.UIString("Element has \u201Cwill-change\u201D style which includes opacity, transform, transform-style, perspective, filter or backdrop-filter"));if(compositingReasons.root)
addReason(WI.UIString("Element is the root element"));if(compositingReasons.blending)
addReason(WI.UIString("Element has \u201Cblend-mode\u201D style"));}};WI.Layers3DContentView=class Layers3DContentView extends WI.ContentView
{constructor()
{super();this.element.classList.add("layers-3d");this._compositingBordersButtonNavigationItem=new WI.ActivateButtonNavigationItem("layer-borders",WI.UIString("Show compositing borders"),WI.UIString("Hide compositing borders"),"Images/LayerBorders.svg",13,13);this._compositingBordersButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCompositingBordersButtonClicked,this);this._compositingBordersButtonNavigationItem.enabled=WI.LayerTreeManager.supportsVisibleCompositingBorders();this._compositingBordersButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._paintFlashingButtonNavigationItem=new WI.ActivateButtonNavigationItem("paint-flashing",WI.UIString("Enable paint flashing"),WI.UIString("Disable paint flashing"),"Images/Paint.svg",16,16);this._paintFlashingButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handlePaingFlashingButtonClicked,this);this._paintFlashingButtonNavigationItem.enabled=WI.LayerTreeManager.supportsShowingPaintRects();this._paintFlashingButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._layers=[];this._layerGroupsById=new Map;this._selectedLayerGroup=null;this._candidateSelection=null;this._nodeToSelect=null;this._renderer=null;this._camera=null;this._controls=null;this._scene=null;this._boundingBox=null;this._raycaster=null;this._animationFrameRequestId=null;this._documentNode=null;this._layerInfoElement=null;this._compositedDimensionsElement=null;this._visibleDimensionsElement=null;this._reasonsListElement=null;} 
get navigationItems()
{return[this._compositingBordersButtonNavigationItem,this._paintFlashingButtonNavigationItem];}
get supplementalRepresentedObjects()
{return this._layers;}
selectLayerById(layerId)
{let layerGroup=this._layerGroupsById.get(layerId);this._updateLayerGroupSelection(layerGroup);this._updateLayerInfoElement();this._centerOnSelection();}
selectLayerForNode(node)
{if(!this._layers.length){this._nodeToSelect=node;return;}
this._nodeToSelect=null;let layer=null;while(node&&!layer){layer=this._layers.find((layer)=>layer.nodeId===node.id);if(!layer)
node=node.parentNode;}
if(!layer)
return;this.selectLayerById(layer.layerId);this.dispatchEventToListeners(WI.Layers3DContentView.Event.SelectedLayerChanged,{layerId:layer.layerId});} 
attached()
{super.attached();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.LayerTreeDidChange,this._layerTreeDidChange,this);if(this.didInitialLayout)
this._animate();WI.layerTreeManager.updateCompositingBordersVisibleFromPageIfNeeded();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.CompositingBordersVisibleChanged,this._handleCompositingBordersVisibleChanged,this);this._handleCompositingBordersVisibleChanged();WI.layerTreeManager.addEventListener(WI.LayerTreeManager.Event.ShowPaintRectsChanged,this._handleShowPaintRectsChanged,this);this._handleShowPaintRectsChanged();}
detached()
{WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.LayerTreeDidChange,this._layerTreeDidChange,this);this._stopAnimation();WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.ShowPaintRectsChanged,this._handleShowPaintRectsChanged,this);WI.layerTreeManager.removeEventListener(WI.LayerTreeManager.Event.CompositingBordersVisibleChanged,this._handleCompositingBordersVisibleChanged,this);super.detached();}
initialLayout()
{super.initialLayout();this._renderer=new THREE.WebGLRenderer({antialias:true});this._renderer.setSize(this.element.offsetWidth,this.element.offsetHeight);let updateBackground=()=>{this._renderer.setClearColor(window.getComputedStyle(this.element).getPropertyValue("--background-color-content").trim());};window.matchMedia("(prefers-color-scheme: dark)").addListener(updateBackground);updateBackground();this._camera=new THREE.PerspectiveCamera(45,this.element.offsetWidth/this.element.offsetHeight,1,100_000);this._controls=new THREE.OrbitControls(this._camera,this._renderer.domElement);this._controls.enableDamping=true;this._controls.panSpeed=0.5;this._controls.enableKeys=false;this._controls.zoomSpeed=0.5;this._controls.minDistance=1000;this._controls.rotateSpeed=0.5;this._controls.minAzimuthAngle=-Math.PI/2;this._controls.maxAzimuthAngle=Math.PI/2;this._controls.screenSpacePanning=true;this._renderer.domElement.addEventListener("contextmenu",(event)=>{event.stopPropagation();});this._scene=new THREE.Scene;this._boundingBox=new THREE.Box3;this._raycaster=new THREE.Raycaster;this._renderer.domElement.addEventListener("mousedown",this._canvasMouseDown.bind(this));this._renderer.domElement.addEventListener("mouseup",this._canvasMouseUp.bind(this));this.element.appendChild(this._renderer.domElement);this._animate();}
layout()
{if(this.layoutReason===WI.View.LayoutReason.Resize)
return;WI.domManager.requestDocument((node)=>{let documentWasUpdated=this._updateDocument(node);WI.layerTreeManager.layersForNode(node,(layers)=>{this._updateLayers(layers);if(documentWasUpdated)
this._resetCamera();if(this._nodeToSelect)
this.selectLayerForNode(this._nodeToSelect);});});}
sizeDidChange()
{super.sizeDidChange();this._stopAnimation();this._camera.aspect=this.element.offsetWidth/this.element.offsetHeight;this._camera.updateProjectionMatrix();this._renderer.setSize(this.element.offsetWidth,this.element.offsetHeight);this._animate();} 
_layerTreeDidChange(event)
{this.needsLayout();}
_animate()
{this._controls.update();this._restrictPan();this._renderer.render(this._scene,this._camera);this._animationFrameRequestId=requestAnimationFrame(()=>{this._animate();});}
_stopAnimation()
{cancelAnimationFrame(this._animationFrameRequestId);this._animationFrameRequestId=null;}
_updateDocument(documentNode)
{if(documentNode===this._documentNode)
return false;this._scene.children.length=0;this._layerGroupsById.clear();this._layers.length=0;this._documentNode=documentNode;return true;}
_updateLayers(newLayers)
{let{removals,additions}=WI.layerTreeManager.layerTreeMutations(this._layers,newLayers);for(let layer of removals){let layerGroup=this._layerGroupsById.get(layer.layerId);this._scene.remove(layerGroup);this._layerGroupsById.delete(layer.layerId);}
if(this._selectedLayerGroup&&!this._layerGroupsById.get(this._selectedLayerGroup.userData.layer.layerId))
this.selectedLayerGroup=null;for(let layer of additions){let layerGroup=this._createLayerGroup(layer);this._layerGroupsById.set(layer.layerId,layerGroup);this._scene.add(layerGroup);}
const zInterval=25;newLayers.forEach((layer,index)=>{let layerGroup=this._layerGroupsById.get(layer.layerId);layerGroup.position.set(layer.bounds.x,-layer.bounds.y,index*zInterval);});this._boundingBox.setFromObject(this._scene);this._controls.maxDistance=this._boundingBox.max.z+WI.Layers3DContentView._zPadding;this._layers=newLayers;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_createLayerGroup(layer){let layerGroup=new THREE.Group;layerGroup.userData.layer=layer;layerGroup.add(this._createLayerMesh(layer.bounds),this._createLayerMesh(layer.compositedBounds,true));return layerGroup;}
_createLayerMesh({width,height},isOutline=false)
{let geometry=new THREE.Geometry;geometry.vertices.push(new THREE.Vector3(0,0,0),new THREE.Vector3(0,-height,0),new THREE.Vector3(width,-height,0),new THREE.Vector3(width,0,0),);if(isOutline){let material=new THREE.LineBasicMaterial({color:WI.Layers3DContentView._layerColor.stroke});return new THREE.LineLoop(geometry,material);}
geometry.faces.push(new THREE.Face3(0,1,3),new THREE.Face3(1,2,3));let material=new THREE.MeshBasicMaterial({color:WI.Layers3DContentView._layerColor.fill,transparent:true,opacity:0.4,side:THREE.DoubleSide,depthWrite:false,});return new THREE.Mesh(geometry,material);}
_canvasMouseDown(event)
{let x=(event.offsetX/event.target.offsetWidth)*2-1;let y=-(event.offsetY/event.target.offsetHeight)*2+1;this._raycaster.setFromCamera(new THREE.Vector2(x,y),this._camera);const recursive=true;let intersects=this._raycaster.intersectObjects(this._scene.children,recursive);let layerGroup=intersects.length?intersects[0].object.parent:null;this._candidateSelection={layerGroup};let canvasMouseMove=(event)=>{this._candidateSelection=null;this._renderer.domElement.removeEventListener("mousemove",canvasMouseMove);};this._renderer.domElement.addEventListener("mousemove",canvasMouseMove);}
_canvasMouseUp(event)
{if(!this._candidateSelection)
return;let selection=this._candidateSelection.layerGroup;if(selection&&selection===this._selectedLayerGroup){if(!event.metaKey)
return;selection=null;}
this._updateLayerGroupSelection(selection);this._updateLayerInfoElement();let layerId=selection?selection.userData.layer.layerId:null;this.dispatchEventToListeners(WI.Layers3DContentView.Event.SelectedLayerChanged,{layerId});}
_updateLayerGroupSelection(layerGroup)
{let setColor=({fill,stroke})=>{let[plane,outline]=this._selectedLayerGroup.children;plane.material.color.set(fill);outline.material.color.set(stroke);};if(this._selectedLayerGroup)
setColor(WI.Layers3DContentView._layerColor);this._selectedLayerGroup=layerGroup;if(this._selectedLayerGroup)
setColor(WI.Layers3DContentView._selectedLayerColor);}
_centerOnSelection()
{if(!this._selectedLayerGroup)
return;let{x,y,width,height}=this._selectedLayerGroup.userData.layer.bounds;this._controls.target.set(x+(width/2),-y-(height/2),0);this._camera.position.set(x+(width/2),-y-(height/2),this._selectedLayerGroup.position.z+WI.Layers3DContentView._zPadding/2);}
_resetCamera()
{let{x,y,width,height}=this._layers[0].bounds;this._controls.target.set(x+(width/2),-y-(height/2),0);this._camera.position.set(x+(width/2),-y-(height/2),this._controls.maxDistance-WI.Layers3DContentView._zPadding/2);}
_restrictPan()
{let delta=new THREE.Vector3;this._boundingBox.clampPoint(this._controls.target,delta).setZ(0).sub(this._controls.target);this._controls.target.add(delta);this._camera.position.add(delta);}
_handleCompositingBordersVisibleChanged(event)
{this._compositingBordersButtonNavigationItem.activated=WI.layerTreeManager.compositingBordersVisible;}
_handleCompositingBordersButtonClicked(event)
{WI.layerTreeManager.compositingBordersVisible=!WI.layerTreeManager.compositingBordersVisible;}
_handleShowPaintRectsChanged(event)
{this._paintFlashingButtonNavigationItem.activated=WI.layerTreeManager.showPaintRects;}
_handlePaingFlashingButtonClicked(event)
{WI.layerTreeManager.showPaintRects=!WI.layerTreeManager.showPaintRects;}
_buildLayerInfoElement()
{this._layerInfoElement=this._element.appendChild(document.createElement("div"));this._layerInfoElement.classList.add("layer-info","hidden");let content=this._layerInfoElement.appendChild(document.createElement("div"));content.className="content";let dimensionsTitle=content.appendChild(document.createElement("div"));dimensionsTitle.textContent=WI.UIString("Dimensions");let dimensionsTable=content.appendChild(document.createElement("table"));let compositedRow=dimensionsTable.appendChild(document.createElement("tr"));let compositedLabel=compositedRow.appendChild(document.createElement("td"));compositedLabel.textContent=WI.UIString("Composited");this._compositedDimensionsElement=compositedRow.appendChild(document.createElement("td"));let visibleRow=dimensionsTable.appendChild(document.createElement("tr"));let visibleLabel=visibleRow.appendChild(document.createElement("td"));visibleLabel.textContent=WI.UIString("Visible");this._visibleDimensionsElement=visibleRow.appendChild(document.createElement("td"));let reasonsTitle=content.appendChild(document.createElement("div"));reasonsTitle.textContent=WI.UIString("Reasons for compositing");this._reasonsListElement=content.appendChild(document.createElement("ul"));}
_updateLayerInfoElement()
{if(!this._layerInfoElement)
this._buildLayerInfoElement();if(!this._selectedLayerGroup){this._layerInfoElement.classList.add("hidden");return;}
let layer=this._selectedLayerGroup.userData.layer;this._compositedDimensionsElement.textContent=`${layer.compositedBounds.width}px ${multiplicationSign} ${layer.compositedBounds.height}px`;this._visibleDimensionsElement.textContent=`${layer.bounds.width}px ${multiplicationSign} ${layer.bounds.height}px`;WI.layerTreeManager.reasonsForCompositingLayer(layer,(compositingReasons)=>{this._updateReasonsList(compositingReasons);this._layerInfoElement.classList.remove("hidden");});}
_updateReasonsList(compositingReasons)
{this._reasonsListElement.removeChildren();let addReason=(reason)=>{let item=this._reasonsListElement.appendChild(document.createElement("li"));item.textContent=reason;};if(compositingReasons.transform3D)
addReason(WI.UIString("Element has a 3D transform"));if(compositingReasons.video)
addReason(WI.UIString("Element is <video>"));if(compositingReasons.canvas)
addReason(WI.UIString("Element is <canvas>"));if(compositingReasons.plugin)
addReason(WI.UIString("Element is a plug-in"));if(compositingReasons.iFrame)
addReason(WI.UIString("Element is <iframe>"));if(compositingReasons.model)
addReason(WI.UIString("Element is <model>"));if(compositingReasons.backfaceVisibilityHidden)
addReason(WI.UIString("Element has \u201Cbackface-visibility: hidden\u201D style"));if(compositingReasons.clipsCompositingDescendants)
addReason(WI.UIString("Element clips compositing descendants"));if(compositingReasons.animation)
addReason(WI.UIString("Element is animated"));if(compositingReasons.filters)
addReason(WI.UIString("Element has CSS filters applied"));if(compositingReasons.positionFixed)
addReason(WI.UIString("Element has \u201Cposition: fixed\u201D style"));if(compositingReasons.positionSticky)
addReason(WI.UIString("Element has \u201Cposition: sticky\u201D style"));if(compositingReasons.overflowScrollingTouch)
addReason(WI.UIString("Element has \u201C-webkit-overflow-scrolling: touch\u201D style"));if(compositingReasons.stacking)
addReason(WI.UIString("Element may overlap another compositing element"));if(compositingReasons.overlap)
addReason(WI.UIString("Element overlaps other compositing element"));if(compositingReasons.negativeZIndexChildren)
addReason(WI.UIString("Element has children with a negative z-index"));if(compositingReasons.transformWithCompositedDescendants)
addReason(WI.UIString("Element has a 2D transform and composited descendants"));if(compositingReasons.opacityWithCompositedDescendants)
addReason(WI.UIString("Element has opacity applied and composited descendants"));if(compositingReasons.maskWithCompositedDescendants)
addReason(WI.UIString("Element is masked and has composited descendants"));if(compositingReasons.reflectionWithCompositedDescendants)
addReason(WI.UIString("Element has a reflection and composited descendants"));if(compositingReasons.filterWithCompositedDescendants)
addReason(WI.UIString("Element has CSS filters applied and composited descendants"));if(compositingReasons.blendingWithCompositedDescendants)
addReason(WI.UIString("Element has CSS blending applied and composited descendants"));if(compositingReasons.isolatesCompositedBlendingDescendants)
addReason(WI.UIString("Element is a stacking context and has composited descendants with CSS blending applied"));if(compositingReasons.perspective)
addReason(WI.UIString("Element has perspective applied"));if(compositingReasons.preserve3D)
addReason(WI.UIString("Element has \u201Ctransform-style: preserve-3d\u201D style"));if(compositingReasons.willChange)
addReason(WI.UIString("Element has \u201Cwill-change\u201D style which includes opacity, transform, transform-style, perspective, filter or backdrop-filter"));if(compositingReasons.root)
addReason(WI.UIString("Element is the root element"));if(compositingReasons.blending)
addReason(WI.UIString("Element has \u201Cblend-mode\u201D style"));}};WI.Layers3DContentView._zPadding=3000;WI.Layers3DContentView._layerColor={fill:"hsl(76, 49%, 75%)",stroke:"hsl(79, 45%, 50%)"};WI.Layers3DContentView._selectedLayerColor={fill:"hsl(208, 66%, 79%)",stroke:"hsl(202, 57%, 68%)"};WI.Layers3DContentView.Event={SelectedLayerChanged:"selected-layer-changed"};WI.LayoutDetailsSidebarPanel=class LayoutDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel
{constructor()
{super("layout-details",WI.UIString("Layout","Layout @ Styles Sidebar","Title of the CSS style panel."));this._gridNodeSet=new Set;this._nodeStyles=null;this.element.classList.add("layout-panel");} 
inspect(objects)
{let hasDOMNode=super.inspect(objects);if(!hasDOMNode)
return false;let stylesForNode=WI.cssManager.stylesForNode(this.domNode);stylesForNode.refreshIfNeeded().then((nodeStyles)=>{if(nodeStyles===this._nodeStyles)
return;if(this._nodeStyles){this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.Refreshed,this._nodeStylesRefreshed,this);this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);}
this._nodeStyles=nodeStyles;if(this._nodeStyles){this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.Refreshed,this._nodeStylesRefreshed,this);this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);}
this.needsLayout();});return hasDOMNode;}
supportsDOMNode(nodeToInspect)
{return nodeToInspect.nodeType()===Node.ELEMENT_NODE;} 
attached()
{super.attached();WI.DOMNode.addEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.cssManager.layoutContextTypeChangedMode=WI.CSSManager.LayoutContextTypeChangedMode.All;this._refreshGridNodeSet();}
detached()
{WI.cssManager.layoutContextTypeChangedMode=WI.CSSManager.LayoutContextTypeChangedMode.Observed;WI.DOMNode.removeEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);super.detached();}
initialLayout()
{this._gridDetailsSectionRow=new WI.DetailsSectionRow(WI.UIString("No CSS Grid Contexts","No CSS Grid Contexts @ Layout Details Sidebar Panel","Message shown when there are no CSS Grid contexts on the inspected page."));let gridGroup=new WI.DetailsSectionGroup([this._gridDetailsSectionRow]);let gridDetailsSection=new WI.DetailsSection("layout-css-grid",WI.UIString("Grid","Grid @ Elements details sidebar","CSS Grid layout section name"),[gridGroup]);this.contentView.element.appendChild(gridDetailsSection.element);this._gridSection=new WI.CSSGridSection;}
layout()
{super.layout();if(!this._gridNodeSet.size){this._gridDetailsSectionRow.showEmptyMessage();if(this._gridSection.isAttached)
this.removeSubview(this._gridSection);}else{this._gridDetailsSectionRow.hideEmptyMessage();this._gridDetailsSectionRow.element.appendChild(this._gridSection.element);if(!this._gridSection.isAttached)
this.addSubview(this._gridSection);this._gridSection.gridNodeSet=this._gridNodeSet;}} 
_handleLayoutContextTypeChanged(event)
{let domNode=event.target;if(domNode.layoutContextType===WI.DOMNode.LayoutContextType.Grid)
this._gridNodeSet.add(domNode);else
this._gridNodeSet.delete(domNode);this.needsLayout();}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this.needsLayout();}
_nodeStylesRefreshed()
{if(this.isAttached)
this.needsLayout();}
_nodeStylesNeedsRefreshed()
{if(this.isAttached)
this._nodeStyles?.refresh();}
_refreshGridNodeSet()
{this._gridNodeSet=new Set(WI.domManager.nodesWithLayoutContextType(WI.DOMNode.LayoutContextType.Grid));}};WI.LayoutTimelineDataGrid=class LayoutTimelineDataGrid extends WI.TimelineDataGrid
{ callFramePopoverAnchorElement()
{return this.selectedNode.elementWithColumnIdentifier("initiator");}
shouldShowCallFramePopover()
{return this.isColumnVisible("initiator");}};WI.LayoutTimelineDataGridNode=class LayoutTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);} 
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.type=this.record.eventType;this._cachedData.name=this.displayName();this._cachedData.width=this.record.width;this._cachedData.height=this.record.height;this._cachedData.area=this.record.width*this.record.height;this._cachedData.startTime=this.record.startTime-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.totalTime=this.record.duration;this._cachedData.initiator=this.record.initiatorCallFrame;this._cachedData.source=this.record.initiatorCallFrame; return this._cachedData;}
createCellContent(columnIdentifier,cell)
{var value=this.data[columnIdentifier];const higherResolution=true;switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return value;case"width":case"height":return isNaN(value)?emDash:WI.UIString("%dpx").format(value);case"area":return isNaN(value)?emDash:WI.UIString("%dpx\u00B2").format(value);case"startTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"totalTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"source": return super.createCellContent("initiator",cell);}
return super.createCellContent(columnIdentifier,cell);}};WI.LayoutTimelineOverviewGraph=class LayoutTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("layout-overview");this._layoutTimeline=timeline;this._layoutTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._layoutTimelineRecordAdded,this);this.reset();for(let record of this._layoutTimeline.records)
this._processRecord(record);} 
reset()
{super.reset();function createRecordRow()
{var element=document.createElement("div");element.className="graph-row";this.element.appendChild(element);return{element,recordBars:[],records:[]};}
this.element.removeChildren();this._timelineLayoutRecordRow=createRecordRow.call(this);this._timelinePaintRecordRow=createRecordRow.call(this);} 
layout()
{super.layout();if(this.hidden)
return;this._updateRowLayout(this._timelinePaintRecordRow);this._updateRowLayout(this._timelineLayoutRecordRow);}
updateSelectedRecord()
{super.updateSelectedRecord();for(let recordRow of[this._timelineLayoutRecordRow,this._timelinePaintRecordRow]){for(let recordBar of recordRow.recordBars){if(recordBar.records.includes(this.selectedRecord)){this.selectedRecordBar=recordBar;return;}}}
this.selectedRecordBar=null;} 
_updateRowLayout(row)
{var secondsPerPixel=this.timelineOverview.secondsPerPixel;var recordBarIndex=0;function createBar(records,renderMode)
{var timelineRecordBar=row.recordBars[recordBarIndex];if(!timelineRecordBar)
timelineRecordBar=row.recordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;}
timelineRecordBar.refresh(this);if(!timelineRecordBar.element.parentNode)
row.element.appendChild(timelineRecordBar.element);++recordBarIndex;}
WI.TimelineRecordBar.createCombinedBars(row.records,secondsPerPixel,this,createBar.bind(this));for(;recordBarIndex<row.recordBars.length;++recordBarIndex){row.recordBars[recordBarIndex].records=null;row.recordBars[recordBarIndex].element.remove();}}
_layoutTimelineRecordAdded(event)
{let layoutTimelineRecord=event.data.record;this._processRecord(layoutTimelineRecord);this.needsLayout();}
_processRecord(layoutTimelineRecord)
{if(layoutTimelineRecord.eventType===WI.LayoutTimelineRecord.EventType.Paint||layoutTimelineRecord.eventType===WI.LayoutTimelineRecord.EventType.Composite)
this._timelinePaintRecordRow.records.push(layoutTimelineRecord);else
this._timelineLayoutRecordRow.records.push(layoutTimelineRecord);}};WI.LayoutTimelineView=class LayoutTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);let columns={type:{},name:{},initiator:{},area:{},width:{},height:{},startTime:{},totalTime:{}};columns.name.title=WI.UIString("Type");columns.name.width="15%";var typeToLabelMap=new Map;for(var key in WI.LayoutTimelineRecord.EventType){var value=WI.LayoutTimelineRecord.EventType[key];typeToLabelMap.set(value,WI.LayoutTimelineRecord.displayNameForEventType(value));}
columns.type.scopeBar=WI.TimelineDataGrid.createColumnScopeBar("layout",typeToLabelMap);columns.type.hidden=true;columns.type.locked=true;columns.name.disclosure=true;columns.name.icon=true;columns.name.locked=true;this._scopeBar=columns.type.scopeBar;columns.initiator.title=WI.UIString("Initiator");columns.initiator.width="25%";columns.area.title=WI.UIString("Area");columns.area.width="8%";columns.width.title=WI.UIString("Width");columns.width.width="8%";columns.height.title=WI.UIString("Height");columns.height.width="8%";columns.startTime.title=WI.UIString("Start Time");columns.startTime.width="8%";columns.startTime.aligned="right";columns.totalTime.title=WI.UIString("Duration");columns.totalTime.width="8%";columns.totalTime.aligned="right";for(var column in columns)
columns[column].sortable=true;this._dataGrid=new WI.LayoutTimelineDataGrid(columns);this._dataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridSelectedNodeChanged,this);this.setupDataGrid(this._dataGrid);this._dataGrid.sortColumnIdentifier="startTime";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("layout-timeline-view");this._hoveredTreeElement=null;this._hoveredDataGridNode=null;this._showingHighlight=false;this._showingHighlightForRecord=null;this._dataGrid.element.addEventListener("mouseover",this._mouseOverDataGrid.bind(this));this._dataGrid.element.addEventListener("mouseleave",this._mouseLeaveDataGrid.bind(this));this.element.classList.add("layout");this.addSubview(this._dataGrid);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._layoutTimelineRecordAdded,this);this._pendingRecords=[];for(let record of timeline.records)
this._processRecord(record);} 
get selectionPathComponents()
{let dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode||dataGridNode.hidden)
return null;let pathComponents=[];while(dataGridNode&&!dataGridNode.root){if(dataGridNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(dataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);pathComponents.unshift(pathComponent);dataGridNode=dataGridNode.parent;}
return pathComponents;}
attached()
{super.attached();this._updateHighlight();}
detached()
{this._hideHighlightIfNeeded();super.detached();}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._layoutTimelineRecordAdded,this);this._dataGrid.closed();}
reset()
{super.reset();this._hideHighlightIfNeeded();this._dataGrid.reset();this._pendingRecords=[];} 
dataGridNodePathComponentSelected(event)
{let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}
filterDidChange()
{super.filterDidChange();this._updateHighlight();}
treeElementSelected(treeElement,selectedByUser)
{if(this._dataGrid.shouldIgnoreSelectionEvent())
return;super.treeElementSelected(treeElement,selectedByUser);this._updateHighlight();}
layout()
{this._processPendingRecords();} 
_processPendingRecords()
{if(!this._pendingRecords.length)
return;for(var layoutTimelineRecord of this._pendingRecords){let dataGridNode=new WI.LayoutTimelineDataGridNode(layoutTimelineRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(dataGridNode);let stack=[{children:layoutTimelineRecord.children,parentDataGridNode:dataGridNode,index:0}];while(stack.length){let entry=stack.lastValue;if(entry.index>=entry.children.length){stack.pop();continue;}
let childRecord=entry.children[entry.index];const options={graphDataSource:this,};let childDataGridNode=null;if(childRecord.type===WI.TimelineRecord.Type.Script)
childDataGridNode=new WI.ScriptTimelineDataGridNode(childRecord,options);else{childDataGridNode=new WI.LayoutTimelineDataGridNode(childRecord,options);}
this._dataGrid.addRowInSortOrder(childDataGridNode,entry.parentDataGridNode);if(childDataGridNode&&childRecord.children.length)
stack.push({children:childRecord.children,parentDataGridNode:childDataGridNode,index:0});++entry.index;}}
this._pendingRecords=[];}
_layoutTimelineRecordAdded(event)
{let layoutTimelineRecord=event.data.record;this._processRecord(layoutTimelineRecord);this.needsLayout();}
_processRecord(layoutTimelineRecord)
{if(layoutTimelineRecord.parent instanceof WI.LayoutTimelineRecord)
return;this._pendingRecords.push(layoutTimelineRecord);}
_updateHighlight()
{var record=this._hoveredOrSelectedRecord();if(!record){this._hideHighlightIfNeeded();return;}
this._showHighlightForRecord(record);}
_showHighlightForRecord(record)
{if(this._showingHighlightForRecord===record)
return;this._showingHighlightForRecord=record;let target=WI.assumingMainTarget();const contentColor={r:111,g:168,b:220,a:0.66};const outlineColor={r:255,g:229,b:153,a:0.66};var quad=record.quad;if(quad){target.DOMAgent.highlightQuad(quad.toProtocol(),contentColor,outlineColor);this._showingHighlight=true;return;}
if(this._showingHighlight){this._showingHighlight=false;target.DOMAgent.hideHighlight();}}
_hideHighlightIfNeeded()
{this._showingHighlightForRecord=null;if(this._showingHighlight){this._showingHighlight=false;let target=WI.assumingMainTarget();target.DOMAgent.hideHighlight();}}
_hoveredOrSelectedRecord()
{if(this._hoveredDataGridNode)
return this._hoveredDataGridNode.record;if(this._dataGrid.selectedNode&&this._dataGrid.selectedNode.revealed)
return this._dataGrid.selectedNode.record;return null;}
_mouseOverDataGrid(event)
{var hoveredDataGridNode=this._dataGrid.dataGridNodeFromNode(event.target);if(!hoveredDataGridNode)
return;this._hoveredDataGridNode=hoveredDataGridNode;this._updateHighlight();}
_mouseLeaveDataGrid(event)
{this._hoveredDataGridNode=null;this._updateHighlight();}
_dataGridSelectedNodeChanged(event)
{this._updateHighlight();}};WI.LocalDOMContentView=class LocalDOMContentView extends WI.LocalRemoteObjectContentView
{constructor(content,mimeType,representedObject)
{super(representedObject);this._content=content;this._mimeType=mimeType;} 
get expression()
{return`(new DOMParser).parseFromString(${JSON.stringify(this._content)}, ${JSON.stringify(this._mimeType)})`;}
renderRemoteObject(remoteObject)
{remoteObject.pushNodeToFrontend((nodeId)=>{let domNode=WI.domManager.nodeForId(nodeId);domNode.getSubtree(3,()=>{let treeOutline=new WI.DOMTreeOutline({omitRootDOMNode:true,selectable:false});treeOutline.markAsUsingLocalDOMNode();treeOutline.setVisible(true);treeOutline.rootDOMNode=domNode;this.element.appendChild(treeOutline.element);});});}};WI.LocalJSONContentView=class LocalJSONContentView extends WI.LocalRemoteObjectContentView
{constructor(json,representedObject)
{super(representedObject);this._json=json;} 
get expression()
{return this._json;}
renderRemoteObject(remoteObject)
{const propertyPath=null;const forceExpanding=true;let objectTree=new WI.ObjectTreeView(remoteObject,WI.ObjectTreeView.Mode.Properties,propertyPath,forceExpanding);objectTree.showOnlyJSON();objectTree.expand();this.element.appendChild(objectTree.element);}};WI.LocalResourceOverrideLabelView=class LocalResourceOverrideLabelView extends WI.View
{constructor(localResourceOverride)
{super();this._localResourceOverride=localResourceOverride;this.element.classList.add("local-resource-override-label-view");} 
initialLayout()
{let labelElement=document.createElement("span");labelElement.className="label";if(this._localResourceOverride.type===WI.LocalResourceOverride.InterceptType.Request)
labelElement.textContent=WI.UIString("Request Override","Request Override @ Local Override Content View","Label indicating that the shown content is from a request local override.");else
labelElement.textContent=WI.UIString("Response Override","Response Override @ Local Override Content View","Label indicating that the shown content is from a response local override.");let urlElement=document.createElement("span");urlElement.textContent=this._localResourceOverride.displayURL({full:true});urlElement.className="url";let container=this.element.appendChild(document.createElement("div"));container.append(labelElement," ",urlElement);}};WI.LocalResourceOverridePopover=class LocalResourceOverridePopover extends WI.Popover
{constructor(delegate)
{super(delegate);this._typeSelectElement=null;this._urlCodeMirror=null;this._isCaseSensitiveCheckbox=null;this._isRegexCheckbox=null;this._requestURLCodeMirror=null;this._methodSelectElement=null;this._mimeTypeCodeMirror=null;this._statusCodeCodeMirror=null;this._statusTextCodeMirror=null;this._headersDataGrid=null;this._skipNetworkCheckbox=null;this._originalRequestURL=null;this._serializedDataWhenShown=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} 
get serializedData()
{if(!this._targetElement)
return null;let data={type:this._skipNetworkCheckbox?.checked?WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:this._typeSelectElement.value,url:WI.urlWithoutFragment(this._urlCodeMirror.getValue()),isCaseSensitive:!this._isCaseSensitiveCheckbox||this._isCaseSensitiveCheckbox.checked,isRegex:!!this._isRegexCheckbox?.checked,};if(!data.url)
return null;if(!data.isRegex){const schemes=["http:","https:","file:"];if(!schemes.some((scheme)=>data.url.toLowerCase().startsWith(scheme)))
return null;}
let headers={};for(let node of this._headersDataGrid.children){let{name,value}=node.data;if(!name||!value)
continue;if(data.type!==WI.LocalResourceOverride.InterceptType.Request){if(name.toLowerCase()==="content-type")
continue;if(name.toLowerCase()==="set-cookie")
continue;}
headers[name]=value;}
switch(data.type){case WI.LocalResourceOverride.InterceptType.Request:data.requestURL=this._requestURLCodeMirror.getValue();data.requestMethod=this._methodSelectElement.value;data.requestHeaders=headers;break;case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:

data.responseMIMEType=this._mimeTypeCodeMirror.getValue()||this._mimeTypeCodeMirror.getOption("placeholder");if(!data.responseMIMEType)
return null;data.responseStatusCode=parseInt(this._statusCodeCodeMirror.getValue());if(isNaN(data.responseStatusCode))
data.responseStatusCode=parseInt(this._statusCodeCodeMirror.getOption("placeholder"));if(isNaN(data.responseStatusCode)||data.responseStatusCode<0)
return null;data.responseStatusText=this._statusTextCodeMirror.getValue()||this._statusTextCodeMirror.getOption("placeholder");if(!data.responseStatusText)
return null;data.responseHeaders=headers;break;}
if(!data.requestURL){if(data.isCaseSensitive&&!data.isRegex)
data.requestURL=data.url;else if(this._originalRequestURL)
data.requestURL=this._originalRequestURL;}
if(!data.responseMIMEType&&data.requestURL){data.responseMIMEType=WI.mimeTypeForFileExtension(WI.fileExtensionForURL(data.requestURL));if(data.type!==WI.LocalResourceOverride.InterceptType.Request)
headers["Content-Type"]=data.responseMIMEType;}
let oldSerialized=JSON.stringify(this._serializedDataWhenShown);let newSerialized=JSON.stringify(data);if(oldSerialized===newSerialized)
return null;return data;}
show(localResourceOverride,targetElement,preferredEdges)
{this._targetElement=targetElement;this._preferredEdges=preferredEdges;let localResource=localResourceOverride?localResourceOverride.localResource:null;let placeholderData={};let valueData={};if(localResource){placeholderData.url=valueData.url=localResourceOverride.url;placeholderData.requestURL=valueData.requestURL=localResource.url;placeholderData.method=valueData.method=localResource.requestMethod;placeholderData.mimeType=valueData.mimeType=localResource.mimeType;placeholderData.statusCode=valueData.statusCode=String(localResource.statusCode);placeholderData.statusText=valueData.statusText=localResource.statusText;}
placeholderData.url||=this._defaultURL();placeholderData.requestURL||=placeholderData.url;placeholderData.method||="GET";placeholderData.mimeType||="text/javascript";if(!placeholderData.statusCode||placeholderData.statusCode==="NaN"){placeholderData.statusCode="200";placeholderData.statusText=undefined;valueData.statusCode=undefined;valueData.statusText=undefined;}
if(!placeholderData.statusText){placeholderData.statusText=WI.HTTPUtilities.statusTextForStatusCode(parseInt(placeholderData.statusCode));valueData.statusText=undefined;}
let requestHeaders=localResource?.requestHeaders??{};let responseHeaders=localResource?.responseHeaders??{};let popoverContentElement=document.createElement("div");popoverContentElement.className="local-resource-override-popover-content";let table=popoverContentElement.appendChild(document.createElement("table"));let createRow=(label,id,value,placeholder)=>{let row=table.appendChild(document.createElement("tr"));let headerElement=row.appendChild(document.createElement("th"));let dataElement=row.appendChild(document.createElement("td"));let labelElement=headerElement.appendChild(document.createElement("label"));labelElement.textContent=label;let editorElement=dataElement.appendChild(document.createElement("div"));editorElement.classList.add("editor",id);let codeMirror=this._createEditor(editorElement,{value,placeholder});let inputField=codeMirror.getInputField();inputField.id=`local-resource-override-popover-${id}-input-field`;labelElement.setAttribute("for",inputField.id);return{element:row,dataElement,codeMirror};};this._typeSelectElement=document.createElement("select");for(let type of[WI.LocalResourceOverride.InterceptType.Request,WI.LocalResourceOverride.InterceptType.Response]){let optionElement=this._typeSelectElement.appendChild(document.createElement("option"));optionElement.textContent=WI.LocalResourceOverride.displayNameForType(type);optionElement.value=type;}
this._typeSelectElement.value=localResourceOverride?.type??WI.LocalResourceOverride.InterceptType.Request;if(!localResourceOverride&&WI.NetworkManager.supportsOverridingRequests()){let typeRowElement=table.appendChild(document.createElement("tr"));let typeHeaderElement=typeRowElement.appendChild(document.createElement("th"));let typeLabelElement=typeHeaderElement.appendChild(document.createElement("label"));typeLabelElement.textContent=WI.UIString("Type");let typeDataElement=typeRowElement.appendChild(document.createElement("td"));typeDataElement.appendChild(this._typeSelectElement);this._typeSelectElement.addEventListener("change",(event)=>{toggleInputsForType();this.update();});this._typeSelectElement.id="local-resource-override-popover-type-input-field";typeLabelElement.setAttribute("for",this._typeSelectElement.id);}
let urlRow=createRow(WI.UIString("URL"),"url",valueData.url||"",placeholderData.url);this._urlCodeMirror=urlRow.codeMirror;let updateURLCodeMirrorMode=()=>{let isRegex=this._isRegexCheckbox&&this._isRegexCheckbox.checked;this._urlCodeMirror.setOption("mode",isRegex?"text/x-regex":"text/x-local-override-url");if(!isRegex){let url=this._urlCodeMirror.getValue();if(url){const schemes=["http:","https:","file:"];if(!schemes.some((scheme)=>url.toLowerCase().startsWith(scheme)))
this._urlCodeMirror.setValue("http://"+url);}}};if(InspectorBackend.hasCommand("Network.addInterception","caseSensitive")){let isCaseSensitiveLabel=urlRow.dataElement.appendChild(document.createElement("label"));isCaseSensitiveLabel.className="is-case-sensitive";this._isCaseSensitiveCheckbox=isCaseSensitiveLabel.appendChild(document.createElement("input"));this._isCaseSensitiveCheckbox.type="checkbox";this._isCaseSensitiveCheckbox.checked=localResourceOverride?localResourceOverride.isCaseSensitive:true;isCaseSensitiveLabel.append(WI.UIString("Case Sensitive"));}
if(InspectorBackend.hasCommand("Network.addInterception","isRegex")){let isRegexLabel=urlRow.dataElement.appendChild(document.createElement("label"));isRegexLabel.className="is-regex";this._isRegexCheckbox=isRegexLabel.appendChild(document.createElement("input"));this._isRegexCheckbox.type="checkbox";this._isRegexCheckbox.checked=localResourceOverride?localResourceOverride.isRegex:false;this._isRegexCheckbox.addEventListener("change",(event)=>{updateURLCodeMirrorMode();});isRegexLabel.append(WI.UIString("Regular Expression"));}
let requestURLRow=null;let methodRowElement=null;if(WI.NetworkManager.supportsOverridingRequests()){requestURLRow=createRow(WI.UIString("Redirect"),"redirect",valueData.requestURL||"",placeholderData.requestURL);this._requestURLCodeMirror=requestURLRow.codeMirror;methodRowElement=table.appendChild(document.createElement("tr"));let methodHeaderElement=methodRowElement.appendChild(document.createElement("th"));let methodLabelElement=methodHeaderElement.appendChild(document.createElement("label"));methodLabelElement.textContent=WI.UIString("Method");let methodDataElement=methodRowElement.appendChild(document.createElement("td"));this._methodSelectElement=methodDataElement.appendChild(document.createElement("select"));[WI.HTTPUtilities.RequestMethod.GET,WI.HTTPUtilities.RequestMethod.POST,null, WI.HTTPUtilities.RequestMethod.HEAD,WI.HTTPUtilities.RequestMethod.PATCH,WI.HTTPUtilities.RequestMethod.PUT,WI.HTTPUtilities.RequestMethod.DELETE,null, WI.HTTPUtilities.RequestMethod.OPTIONS,WI.HTTPUtilities.RequestMethod.CONNECT,WI.HTTPUtilities.RequestMethod.TRACE,].forEach((method)=>{if(!method){this._methodSelectElement.appendChild(document.createElement("hr"));return;}
let optionElement=this._methodSelectElement.appendChild(document.createElement("option"));optionElement.textContent=method;});this._methodSelectElement.value=valueData.method||placeholderData.method;this._methodSelectElement.id="local-resource-override-popover-method-input-field";methodLabelElement.setAttribute("for",this._methodSelectElement.id);}
let mimeTypeRow=createRow(WI.UIString("MIME Type","MIME Type @ Local Override Popover","Label for MIME type input for the local override currently being edited."),"mime",valueData.mimeType||"",placeholderData.mimeType);this._mimeTypeCodeMirror=mimeTypeRow.codeMirror;let statusCodeRow=createRow(WI.UIString("Status","Status @ Local Override Popover","Label for the HTTP status code input for the local override currently being edited."),"status",valueData.statusCode||"",placeholderData.statusCode);this._statusCodeCodeMirror=statusCodeRow.codeMirror;let statusTextEditorElement=statusCodeRow.dataElement.appendChild(document.createElement("div"));statusTextEditorElement.className="editor status-text";this._statusTextCodeMirror=this._createEditor(statusTextEditorElement,{value:valueData.statusText||"",placeholder:placeholderData.statusText});let editCallback=()=>{};let deleteCallback=(node)=>{if(node===contentTypeDataGridNode)
return;let siblingToSelect=node.nextSibling||node.previousSibling;this._headersDataGrid.removeChild(node);if(siblingToSelect)
siblingToSelect.select();toggleHeadersDataGridVisibility();this.update();};let columns={name:{title:WI.UIString("Name"),width:"30%",},value:{title:WI.UIString("Value"),},};this._headersDataGrid=new WI.DataGrid(columns,{editCallback,deleteCallback});this._headersDataGrid.inline=true;this._headersDataGrid.variableHeightRows=true;this._headersDataGrid.copyTextDelimiter=": ";let addDataGridNodeForHeader=(name,value,options={})=>{let node=new WI.DataGridNode({name,value},options);this._headersDataGrid.appendChild(node);return node;};let toggleHeadersDataGridVisibility=(force)=>{this._headersDataGrid.element.hidden=force!==undefined?force:!this._headersDataGrid.hasChildren;this._headersDataGrid.updateLayoutIfNeeded();};let contentTypeDataGridNode=addDataGridNodeForHeader(WI.unlocalizedString("Content-Type"),valueData.mimeType||placeholderData.mimeType,{selectable:false,editable:false,classNames:["header-content-type"]});let headersRow=table.appendChild(document.createElement("tr"));let headersHeader=headersRow.appendChild(document.createElement("th"));let headersData=headersRow.appendChild(document.createElement("td"));let headersLabel=headersHeader.appendChild(document.createElement("label"));headersLabel.textContent=WI.UIString("Headers");headersData.appendChild(this._headersDataGrid.element);let addHeaderButton=headersData.appendChild(document.createElement("button"));addHeaderButton.className="add-header";addHeaderButton.textContent=WI.UIString("Add Header");addHeaderButton.addEventListener("click",(event)=>{let newNode=new WI.DataGridNode({name:WI.UIString("Header","Header @ Local Override Popover New Headers Data Grid Item","Placeholder text in an editable field for the name of a HTTP header"),value:WI.UIString("value","value @ Local Override Popover New Headers Data Grid Item","Placeholder text in an editable field for the value of a HTTP header"),});this._headersDataGrid.appendChild(newNode);toggleHeadersDataGridVisibility(false);this.update();this._headersDataGrid.startEditingNode(newNode);});let optionsRowElement=null;if(WI.NetworkManager.supportsOverridingRequestsWithResponses()){optionsRowElement=table.appendChild(document.createElement("tr"));optionsRowElement.className="options";let optionsHeader=optionsRowElement.appendChild(document.createElement("th"));let optionsLabel=optionsHeader.appendChild(document.createElement("label"));optionsLabel.textContent=WI.UIString("Options");let optionsData=optionsRowElement.appendChild(document.createElement("td"));let skipNetworkLabel=optionsData.appendChild(document.createElement("label"));skipNetworkLabel.className="skip-network";this._skipNetworkCheckbox=skipNetworkLabel.appendChild(document.createElement("input"));this._skipNetworkCheckbox.type="checkbox";this._skipNetworkCheckbox.checked=localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork;skipNetworkLabel.appendChild(document.createTextNode(WI.UIString("Skip Network","Skip Network @ Local Override Popover Options","Label for checkbox that controls whether the local override will actually perform a network request or skip it to immediately serve the response.")));}
popoverContentElement.appendChild(WI.createReferencePageLink(WI.ReferencePage.LocalOverrides,"configuring-local-overrides"));let incrementStatusCode=()=>{let x=parseInt(this._statusCodeCodeMirror.getValue());if(isNaN(x))
x=parseInt(this._statusCodeCodeMirror.getOption("placeholder"));if(isNaN(x)||x>=999)
return;if(WI.modifierKeys.shiftKey){ x=(x-(x%100))+100;}else
x+=1;if(x>999)
x=999;this._statusCodeCodeMirror.setValue(`${x}`);this._statusCodeCodeMirror.setCursor(this._statusCodeCodeMirror.lineCount(),0);};let decrementStatusCode=()=>{let x=parseInt(this._statusCodeCodeMirror.getValue());if(isNaN(x))
x=parseInt(this._statusCodeCodeMirror.getOption("placeholder"));if(isNaN(x)||x<=0)
return;if(WI.modifierKeys.shiftKey){ let original=x;x=(x-(x%100));if(original===x)
x-=100;}else
x-=1;if(x<0)
x=0;this._statusCodeCodeMirror.setValue(`${x}`);this._statusCodeCodeMirror.setCursor(this._statusCodeCodeMirror.lineCount(),0);};this._statusCodeCodeMirror.addKeyMap({"Up":incrementStatusCode,"Shift-Up":incrementStatusCode,"Down":decrementStatusCode,"Shift-Down":decrementStatusCode,});this._statusCodeCodeMirror.on("change",(cm)=>{let statusCode=parseInt(cm.getValue());if(isNaN(statusCode)){this._statusTextCodeMirror.setValue("");return;}
let statusText=WI.HTTPUtilities.statusTextForStatusCode(statusCode);this._statusTextCodeMirror.setValue(statusText);});this._urlCodeMirror.on("change",(cm)=>{if(this._isRegexCheckbox&&this._isRegexCheckbox.checked)
return;let extension=WI.fileExtensionForURL(cm.getValue());if(!extension)
return;let mimeType=WI.mimeTypeForFileExtension(extension);if(!mimeType)
return;this._mimeTypeCodeMirror.setValue(mimeType);contentTypeDataGridNode.data={name:"Content-Type",value:mimeType};});this._mimeTypeCodeMirror.on("change",(cm)=>{let mimeType=cm.getValue()||cm.getOption("placeholder");contentTypeDataGridNode.data={name:"Content-Type",value:mimeType};});updateURLCodeMirrorMode();let toggleInputsForType=(initializeHeaders)=>{let isRequest=this._typeSelectElement.value===WI.LocalResourceOverride.InterceptType.Request;popoverContentElement.classList.toggle("request",isRequest);popoverContentElement.classList.toggle("response",!isRequest);if(initializeHeaders){let headers=isRequest?requestHeaders:responseHeaders;for(let name in headers){if(!isRequest){if(name.toLowerCase()==="content-type")
continue;if(name.toLowerCase()==="set-cookie")
continue;}
addDataGridNodeForHeader(name,headers[name]);}}
if(requestURLRow)
requestURLRow.element.hidden=!isRequest;if(methodRowElement)
methodRowElement.hidden=!isRequest;mimeTypeRow.element.hidden=isRequest;statusCodeRow.element.hidden=isRequest;if(optionsRowElement)
optionsRowElement.hidden=isRequest;if(isRequest){this._requestURLCodeMirror.refresh();if(contentTypeDataGridNode.parent)
this._headersDataGrid.removeChild(contentTypeDataGridNode);}else{this._mimeTypeCodeMirror.refresh();this._statusCodeCodeMirror.refresh();this._statusTextCodeMirror.refresh();if(!contentTypeDataGridNode.parent)
this._headersDataGrid.insertChild(contentTypeDataGridNode,0);}
toggleHeadersDataGridVisibility();};toggleInputsForType(true);this._originalRequestURL=localResource?.url??null;this._serializedDataWhenShown=this.serializedData;this.content=popoverContentElement;this._presentOverTargetElement();setTimeout(()=>{this._urlCodeMirror.refresh();this._requestURLCodeMirror?.refresh();this._mimeTypeCodeMirror.refresh();this._statusCodeCodeMirror.refresh();this._statusTextCodeMirror.refresh();this._urlCodeMirror.focus();this._urlCodeMirror.setCursor(this._urlCodeMirror.lineCount(),0);this.update();});} 
_createEditor(element,options={})
{let codeMirror=WI.CodeMirrorEditor.create(element,{extraKeys:{"Tab":false,"Shift-Tab":false},lineWrapping:false,mode:"text/plain",matchBrackets:true,scrollbarStyle:null,...options,});codeMirror.addKeyMap({"Enter":()=>{this.dismiss();},"Shift-Enter":()=>{this.dismiss();},"Esc":()=>{this.dismiss();},});return codeMirror;}
_defaultURL()
{

let mainFrame=WI.networkManager.mainFrame;if(mainFrame&&mainFrame.securityOrigin.startsWith("http"))
return mainFrame.securityOrigin+"/path";return"https://";}
_presentOverTargetElement()
{if(!this._targetElement)
return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),this._preferredEdges);}};WI.LocalResourceOverrideRequestContentView=class LocalResourceOverrideRequestContentView extends WI.TextContentView
{constructor(localResourceOverride)
{let localResource=localResourceOverride.localResource;let string=localResource.requestData||"";let mimeType=localResource.requestDataContentType;super(string,mimeType,localResourceOverride);this.element.classList.add("local-resource-override-request");this._removeLocalResourceOverrideButtonNavigationItem=new WI.ButtonNavigationItem("remove-local-resource-override",WI.UIString("Delete Local Override"),"Images/NavigationItemTrash.svg",15,15);this._removeLocalResourceOverrideButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleRemoveLocalResourceOverride,this);this._removeLocalResourceOverrideButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;} 
get navigationItems()
{return[this._removeLocalResourceOverrideButtonNavigationItem];}
get saveData()
{let saveData=super.saveData;saveData.suggestedName=WI.UIString("%s Request Data","%s Request Data @ Local Override Request Content View","Format string for the suggested filename when saving the content for a request local override.").format(this.representedObject.url)+".txt";return saveData;} 
initialLayout()
{super.initialLayout();this.insertSubviewBefore(new WI.LocalResourceOverrideLabelView(this.representedObject),this.textEditor);this.textEditor.readOnly=false;this.textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,this._handleTextEditorContentDidChange,this);let requestMethod=this.representedObject.localResource.requestMethod;if(!WI.HTTPUtilities.RequestMethodsWithBody.has(requestMethod)){let message=WI.createMessageTextView(WI.UIString("%s requests do not have a body").format(requestMethod));this.element.appendChild(message);}} 
_handleRemoveLocalResourceOverride(event)
{WI.networkManager.removeLocalResourceOverride(this.representedObject);}
_handleTextEditorContentDidChange(event)
{this.representedObject.localResource.updateLocalResourceOverrideRequestData(this.textEditor.string);}};WI.LocalResourceOverrideTreeElement=class LocalResourceOverrideTreeElement extends WI.ResourceTreeElement
{constructor(localResourceOverride,options)
{super(localResourceOverride.localResource,localResourceOverride,options);this._localResourceOverride=localResourceOverride;this._popover=null;} 
get mainTitleText()
{return this.representedObject.displayName;}
onattach()
{super.onattach();this._localResourceOverride.addEventListener(WI.LocalResourceOverride.Event.DisabledChanged,this._handleLocalResourceOverrideDisabledChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);this._updateStatusCheckbox();}
ondetach()
{this._localResourceOverride.removeEventListener(WI.LocalResourceOverride.Event.DisabledChanged,this._handleLocalResourceOverrideDisabledChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);super.ondetach();}
ondelete()
{WI.networkManager.removeLocalResourceOverride(this._localResourceOverride);return true;}
onspace()
{this._localResourceOverride.disabled=!this._localResourceOverride.disabled;return true;}
canSelectOnMouseDown(event)
{if(this.status.contains(event.target))
return false;return super.canSelectOnMouseDown(event);}
populateContextMenu(contextMenu,event)
{contextMenu.__localOverrideItemsAdded=true;contextMenu.appendItem(WI.UIString("Edit Local Override\u2026"),(event)=>{let popover=new WI.LocalResourceOverridePopover(this);popover.show(this._localResourceOverride,this.status,[WI.RectEdge.MAX_X,WI.RectEdge.MIN_X]);});let toggleEnabledString=this._localResourceOverride.disabled?WI.UIString("Enable Local Override"):WI.UIString("Disable Local Override");contextMenu.appendItem(toggleEnabledString,()=>{this._localResourceOverride.disabled=!this._localResourceOverride.disabled;});contextMenu.appendItem(WI.UIString("Delete Local Override"),()=>{WI.networkManager.removeLocalResourceOverride(this._localResourceOverride);});super.populateContextMenu(contextMenu,event);}
updateStatus()
{} 
willDismissPopover(popover)
{let serializedData=popover.serializedData;if(!serializedData)
return;if(WI.networkManager.localResourceOverrides.some((existingOverride)=>existingOverride!==this._localResourceOverride&&existingOverride.equals(this._localResourceOverride))){InspectorFrontendHost.beep();return;}
let wasSelected=this.selected;if(serializedData.type!==WI.LocalResourceOverride.InterceptType.Request){let revision=this._localResourceOverride.localResource.currentRevision;serializedData.responseContent=revision.content;serializedData.responseBase64Encoded=revision.base64Encoded;}
let newLocalResourceOverride=WI.LocalResourceOverride.create(serializedData.url,serializedData.type,serializedData);WI.networkManager.removeLocalResourceOverride(this._localResourceOverride);WI.networkManager.addLocalResourceOverride(newLocalResourceOverride);if(wasSelected){const cookie=null;const options={ignoreNetworkTab:true,ignoreSearchTab:true};WI.showRepresentedObject(newLocalResourceOverride,cookie,options);}} 
_updateStatusCheckbox()
{this.status=document.createElement("input");this.status.type="checkbox";this.status.checked=!this._localResourceOverride.disabled;this.status.addEventListener("change",(event)=>{this._localResourceOverride.disabled=!event.target.checked;});}
_handleLocalResourceOverrideDisabledChanged(event)
{this.status.checked=!this._localResourceOverride.disabled;}
_handleFrameMainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._updateTitles();}};WI.LocalResourceOverrideWarningView=class LocalResourceOverrideWarningView extends WI.View
{constructor(resource)
{super();this._resource=resource;this.element.classList.add("local-resource-override-warning-view");} 
attached()
{super.attached();WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAddedOrRemoved,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideAddedOrRemoved,this);this._updateContent();}
detached()
{WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAddedOrRemoved,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideAddedOrRemoved,this);super.detached();}
initialLayout()
{this._revealButton=document.createElement("button");this._revealButton.textContent=WI.UIString("Reveal");this._revealButton.addEventListener("click",(event)=>{const cookie=null;const options={ignoreNetworkTab:true,ignoreSearchTab:true};let localResourceOverride=WI.networkManager.localResourceOverridesForURL(this._resource.url)[0];WI.showRepresentedObject(localResourceOverride,cookie,options);});let container=this.element.appendChild(document.createElement("div"));container.append(this._revealButton,WI.UIString("This resource came from a local override"));this._updateContent();} 
_updateContent()
{if(!this._revealButton)
return;this._revealButton.hidden=!WI.networkManager.localResourceOverridesForURL(this._resource.url).length;let resourceShowingOverrideContent=this._resource.responseSource===WI.Resource.ResponseSource.InspectorOverride;this.element.hidden=!resourceShowingOverrideContent;}
_handleLocalResourceOverrideAddedOrRemoved(event)
{let{localResourceOverride}=event.data;if(!localResourceOverride.matches(this._resource.url))
return;this._updateContent();}};WI.LogContentView=class LogContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);this._nestingLevel=0;this._selectedMessages=[];this._immediatelyHiddenMessages=new Set;this._provisionalMessages=[];this.element.classList.add("log");this.messagesElement=document.createElement("div");this.messagesElement.classList.add("console-messages");this.messagesElement.tabIndex=0;this.messagesElement.setAttribute("role","log");this.messagesElement.addEventListener("mousedown",this._mousedown.bind(this));this.messagesElement.addEventListener("keydown",this._keyDown.bind(this));this.messagesElement.addEventListener("keypress",this._keyPress.bind(this));this.messagesElement.addEventListener("dragstart",this._ondragstart.bind(this),true);this.messagesElement.addEventListener("dragover",this._handleDragOver.bind(this));this.messagesElement.addEventListener("drop",this._handleDrop.bind(this));this.element.appendChild(this.messagesElement);this.prompt=WI.quickConsole.prompt;this._keyboardShortcutCommandA=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"A");this._keyboardShortcutEsc=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape);this._logViewController=new WI.JavaScriptLogViewController(this.messagesElement,this.messagesElement,this.prompt,this,"console-prompt-history");this._lastMessageView=null;const fixed=true;this._findBanner=new WI.FindBanner(this,"console-find-banner",fixed);this._findBanner.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._findBanner.targetElement=this.element;this._currentSearchQuery="";this._searchMatches=[];this._selectedSearchMatch=null;this._selectedSearchMatchIsValid=false;this._preserveLogNavigationItem=new WI.CheckboxNavigationItem("preserve-log",WI.UIString("Preserve Log"),!WI.settings.clearLogOnNavigate.value);this._preserveLogNavigationItem.tooltip=WI.UIString("Do not clear the console on new page loads");this._preserveLogNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,function(event){WI.settings.clearLogOnNavigate.value=!WI.settings.clearLogOnNavigate.value;},this);WI.settings.clearLogOnNavigate.addEventListener(WI.Setting.Event.Changed,this._handleClearLogOnNavigateSettingChanged,this);let checkboxesNavigationItems=[this._preserveLogNavigationItem];if(WI.sharedApp.isWebDebuggable()&&InspectorBackend.hasCommand("Runtime.evaluate","emulateUserGesture")){this._emulateUserGestureNavigationItem=new WI.CheckboxNavigationItem("emulate-in-user-gesture",WI.UIString("Emulate User Gesture","Emulate User Gesture @ Console","Checkbox shown in the Console to cause future evaluations as though they are in response to user interaction."),WI.settings.emulateInUserGesture.value);this._emulateUserGestureNavigationItem.tooltip=WI.UIString("Run console commands as if inside a user gesture");this._emulateUserGestureNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,function(event){WI.settings.emulateInUserGesture.value=!WI.settings.emulateInUserGesture.value;},this);WI.settings.emulateInUserGesture.addEventListener(WI.Setting.Event.Changed,this._handleEmulateInUserGestureSettingChanged,this);checkboxesNavigationItems.push(this._emulateUserGestureNavigationItem);}
checkboxesNavigationItems.push(new WI.DividerNavigationItem);this._checkboxesNavigationItemGroup=new WI.GroupNavigationItem(checkboxesNavigationItems);let scopeBarItems=[new WI.ScopeBarItem(WI.LogContentView.Scopes.All,WI.UIString("All"),{exclusive:true}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Evaluations,WI.UIString("Evaluations"),{className:"evaluations"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Errors,WI.UIString("Errors"),{className:"errors"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Warnings,WI.UIString("Warnings"),{className:"warnings"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Logs,WI.UIString("Logs"),{className:"logs"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Infos,WI.UIString("Infos"),{className:"infos",hidden:true}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Debugs,WI.UIString("Debugs"),{className:"debugs",hidden:true}),];this._scopeBar=new WI.ScopeBar("log-scope-bar",scopeBarItems,scopeBarItems[0]);this._scopeBar.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectionDidChange,this);this._hasNonDefaultLogChannelMessage=false;if(WI.ConsoleManager.supportsLogChannels()){let messageChannelBarItems=[new WI.ScopeBarItem(WI.LogContentView.Scopes.AllChannels,WI.UIString("All"),{exclusive:true}),new WI.ScopeBarItem(WI.LogContentView.Scopes.Media,WI.UIString("Media"),{className:"media"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.MediaSource,WI.UIString("MediaSource"),{className:"mediasource"}),new WI.ScopeBarItem(WI.LogContentView.Scopes.WebRTC,WI.UIString("WebRTC"),{className:"webrtc"}),];this._messageSourceBar=new WI.ScopeBar("message-channel-scope-bar",messageChannelBarItems,messageChannelBarItems[0]);this._messageSourceBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._messageSourceBarSelectionDidChange,this);}
this._garbageCollectNavigationItem=new WI.ButtonNavigationItem("garbage-collect",WI.UIString("Collect garbage"),"Images/NavigationItemGarbageCollect.svg",16,16);this._garbageCollectNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._garbageCollect,this);this._clearLogNavigationItem=new WI.ButtonNavigationItem("clear-log",WI.UIString("Clear log (%s or %s)").format(WI.clearKeyboardShortcut.displayName,this._logViewController.messagesAlternateClearKeyboardShortcut.displayName),"Images/NavigationItemTrash.svg",15,15);this._clearLogNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._clearLogNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearLog,this);this._showConsoleTabNavigationItem=new WI.ButtonNavigationItem("show-tab",WI.UIString("Show Console tab"),"Images/SplitToggleUp.svg",16,16);this._showConsoleTabNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._showConsoleTabNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showConsoleTab,this);this.messagesElement.addEventListener("contextmenu",this._handleContextMenuEvent.bind(this),false);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.SessionStarted,this._sessionStarted,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.MessageAdded,this._messageAdded,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.PreviousMessageRepeatCountUpdated,this._previousMessageRepeatCountUpdated,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._logCleared,this);WI.Frame.addEventListener(WI.Frame.Event.ProvisionalLoadStarted,this._provisionalLoadStarted,this);} 
get navigationItems()
{let navigationItems=[this._findBanner,this._checkboxesNavigationItemGroup,new WI.DividerNavigationItem,this._scopeBar,new WI.DividerNavigationItem];if(this._hasNonDefaultLogChannelMessage&&this._messageSourceBar)
navigationItems.push(this._messageSourceBar,new WI.DividerNavigationItem);if(InspectorBackend.hasCommand("Heap.gc"))
navigationItems.push(this._garbageCollectNavigationItem);navigationItems.push(this._clearLogNavigationItem);if(WI.isShowingSplitConsole())
navigationItems.push(new WI.DividerNavigationItem,this._showConsoleTabNavigationItem);return navigationItems;}
get scopeBar()
{return this._scopeBar;}
get logViewController()
{return this._logViewController;}
get scrollableElements()
{return[this.messagesElement];}
get shouldKeepElementsScrolledToBottom()
{return true;}
attached()
{super.attached();this._logViewController.renderPendingMessages();}
closed()
{

super.closed();}
didAppendConsoleMessageView(messageView)
{var type=messageView instanceof WI.ConsoleCommandView?null:messageView.message.type;if(this._nestingLevel&&type!==WI.ConsoleMessage.MessageType.EndGroup){var x=16*this._nestingLevel;var messageElement=messageView.element;messageElement.style.left=x+"px";messageElement.style.width="calc(100% - "+x+"px)";}
switch(type){case WI.ConsoleMessage.MessageType.StartGroup:case WI.ConsoleMessage.MessageType.StartGroupCollapsed:++this._nestingLevel;break;case WI.ConsoleMessage.MessageType.EndGroup:if(this._nestingLevel>0)
--this._nestingLevel;break;}
this._clearFocusableChildren();let target=messageView.message?messageView.message.target:WI.runtimeManager.activeExecutionContext.target;target.connection.runAfterPendingDispatches(this._clearFocusableChildren.bind(this));if(!this._scopeBar.item(WI.LogContentView.Scopes.All).selected){if(messageView instanceof WI.ConsoleCommandView||messageView.message instanceof WI.ConsoleCommandResultMessage)
this._scopeBar.item(WI.LogContentView.Scopes.Evaluations).toggle(true,{extendSelection:true});}
this._filterMessageElements([messageView.element]);if(!this._isMessageVisible(messageView.element)){this._immediatelyHiddenMessages.add(messageView);this._showHiddenMessagesBannerIfNeeded();}
this._lastMessageView=messageView;}
get supportsSearch(){return true;}
get numberOfSearchResults(){return this.hasPerformedSearch?this._searchMatches.length:null;}
get hasPerformedSearch(){return this._currentSearchQuery!=="";}
get supportsCustomFindBanner()
{return true;}
showCustomFindBanner()
{if(!this.isAttached)
return;this._findBanner.focus();}
get supportsSave()
{if(!this.isAttached)
return false;if(WI.isShowingSplitConsole())
return false;return true;}
get saveData()
{return{content:this._formatMessagesAsData(false),suggestedName:WI.UIString("Console")+".txt",forceSaveAs:true,};}
handleCopyEvent(event)
{if(!this._selectedMessages.length)
return;event.clipboardData.setData("text/plain",this._formatMessagesAsData(true));event.stopPropagation();event.preventDefault();}
handleClearShortcut(event)
{this._logViewController.requestClearMessages();}
handlePopulateFindShortcut()
{if(!WI.updateFindString(this.searchQueryWithSelection()))
return;this._findBanner.searchQuery=WI.findString;this.performSearch(this._findBanner.searchQuery);}
handleFindNextShortcut()
{this.highlightNextSearchMatch();}
handleFindPreviousShortcut()
{this.highlightPreviousSearchMatch();}
findBannerRevealPreviousResult()
{this.highlightPreviousSearchMatch();}
highlightPreviousSearchMatch()
{if(!this.hasPerformedSearch||(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString)){this._findBanner.searchQuery=WI.findString;this.performSearch(this._findBanner.searchQuery);}
if(isEmptyObject(this._searchMatches))
return;var index=this._selectedSearchMatch?this._searchMatches.indexOf(this._selectedSearchMatch):this._searchMatches.length;this._highlightSearchMatchAtIndex(index-1);}
findBannerRevealNextResult()
{this.highlightNextSearchMatch();}
highlightNextSearchMatch()
{if(!this.hasPerformedSearch||(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString)){this._findBanner.searchQuery=WI.findString;this.performSearch(this._findBanner.searchQuery);}
if(isEmptyObject(this._searchMatches))
return;var index=this._selectedSearchMatch?this._searchMatches.indexOf(this._selectedSearchMatch)+1:0;this._highlightSearchMatchAtIndex(index);}
findBannerWantsToClearAndBlur(findBanner)
{if(this._selectedMessages.length)
this.messagesElement.focus();else
this.prompt.focus();} 
_formatMessagesAsData(onlySelected)
{var messages=this._allMessageElements();if(onlySelected){messages=messages.filter(function(message){return message.classList.contains(WI.LogContentView.SelectedStyleClassName);});}
var data="";var isPrefixOptional=messages.length<=1&&onlySelected;messages.forEach(function(messageElement,index){var messageView=messageElement.__messageView||messageElement.__commandView;if(!messageView)
return;if(index>0)
data+="\n";data+=messageView.toClipboardString(isPrefixOptional);});return data;}
_sessionStarted(event)
{if(WI.settings.clearLogOnNavigate.value){this._reappendProvisionalMessages();return;}
for(let messageElement of this._allMessageElements()){if(messageElement.__messageView)
messageElement.__messageView.clearSessionState();}
const isFirstSession=false;const newSessionReason=event.data.wasReloaded?WI.ConsoleSession.NewSessionReason.PageReloaded:WI.ConsoleSession.NewSessionReason.PageNavigated;this._logViewController.startNewSession(isFirstSession,{newSessionReason,timestamp:event.data.timestamp});this._clearProvisionalState();}
_scopeFromMessageSource(source)
{switch(source){case WI.ConsoleMessage.MessageSource.Media:return WI.LogContentView.Scopes.Media;case WI.ConsoleMessage.MessageSource.WebRTC:return WI.LogContentView.Scopes.WebRTC;case WI.ConsoleMessage.MessageSource.MediaSource:return WI.LogContentView.Scopes.MediaSource;}
return undefined;}
_scopeFromMessageLevel(level)
{switch(level){case WI.ConsoleMessage.MessageLevel.Warning:return WI.LogContentView.Scopes.Warnings;case WI.ConsoleMessage.MessageLevel.Error:return WI.LogContentView.Scopes.Errors;case WI.ConsoleMessage.MessageLevel.Log:return WI.LogContentView.Scopes.Logs;case WI.ConsoleMessage.MessageLevel.Info:return this._hasNonDefaultLogChannelMessage?WI.LogContentView.Scopes.Infos:WI.LogContentView.Scopes.Logs;case WI.ConsoleMessage.MessageLevel.Debug:return this._hasNonDefaultLogChannelMessage?WI.LogContentView.Scopes.Debugs:WI.LogContentView.Scopes.Logs;}
return undefined;}
_messageAdded(event)
{let message=event.data.message;if(this._startedProvisionalLoad)
this._provisionalMessages.push(message);if(!this._hasNonDefaultLogChannelMessage&&WI.consoleManager.customLoggingChannels.some((channel)=>channel.source===message.source)){this._hasNonDefaultLogChannelMessage=true;this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);this._scopeBar.item(WI.LogContentView.Scopes.Infos).hidden=false;this._scopeBar.item(WI.LogContentView.Scopes.Debugs).hidden=false;}
this._logViewController.appendConsoleMessage(message);}
_previousMessageRepeatCountUpdated(event)
{if(!this._logViewController.updatePreviousMessageRepeatCount(event.data.count))
return;if(this._lastMessageView){if(this._isMessageVisible(this._lastMessageView.element))
return;this._immediatelyHiddenMessages.add(this._lastMessageView);}
this._showHiddenMessagesBannerIfNeeded();}
_handleContextMenuEvent(event)
{if(!window.getSelection().isCollapsed){
return;}

if(this._selectedMessages.length&&!this._selectedMessages.some(element=>element.contains(event.target))){this._clearMessagesSelection();this._mousedown(event);}


if(!this._selectedMessages.length)
this._mouseup(event);if(event.target.closest("a"))
return;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.appendSeparator();if(this._selectedMessages.length){contextMenu.appendItem(WI.UIString("Copy Selected"),()=>{InspectorFrontendHost.copyText(this._formatMessagesAsData(true));});contextMenu.appendItem(WI.UIString("Save Selected"),()=>{const forceSaveAs=true;WI.FileUtilities.save({content:this._formatMessagesAsData(true),suggestedName:WI.UIString("Console")+".txt",},forceSaveAs);});contextMenu.appendSeparator();}
contextMenu.appendItem(WI.UIString("Clear Log"),this._clearLog.bind(this));contextMenu.appendSeparator();}
_mousedown(event)
{if(this._selectedMessages.length&&(event.button!==0||event.ctrlKey))
return;if(event.defaultPrevented){
this._clearMessagesSelection();return;}
this._mouseDownWrapper=event.target.closest("."+WI.LogContentView.ItemWrapperStyleClassName);this._mouseDownShiftKey=event.shiftKey;this._mouseDownCommandKey=event.metaKey;this._mouseMoveIsRowSelection=false;window.addEventListener("mousemove",this);window.addEventListener("mouseup",this);}
_targetInMessageCanBeSelected(target,message)
{if(target.closest("a"))
return false;return true;}
_mousemove(event)
{var selection=window.getSelection();var wrapper=event.target.closest("."+WI.LogContentView.ItemWrapperStyleClassName);if(!wrapper){if(!selection.isCollapsed){let focusElement=selection.focusNode;if(!(focusElement instanceof Element))
focusElement=focusElement.parentElement;wrapper=focusElement.closest("."+WI.LogContentView.ItemWrapperStyleClassName);}
if(!wrapper){selection.removeAllRanges();return;}}
if(!selection.isCollapsed)
this._clearMessagesSelection();if(wrapper===this._mouseDownWrapper&&!this._mouseMoveIsRowSelection)
return;if(!this.element.contains(event.target))
return;selection.removeAllRanges();if(!this._mouseMoveIsRowSelection)
this._updateMessagesSelection(this._mouseDownWrapper,this._mouseDownCommandKey,this._mouseDownShiftKey,false);this._updateMessagesSelection(wrapper,false,true,false);this._mouseMoveIsRowSelection=true;event.preventDefault();event.stopPropagation();}
_mouseup(event)
{window.removeEventListener("mousemove",this);window.removeEventListener("mouseup",this);var selection=window.getSelection();var wrapper=event.target.closest("."+WI.LogContentView.ItemWrapperStyleClassName);if(wrapper&&(selection.isCollapsed||event.shiftKey)){selection.removeAllRanges();if(this._targetInMessageCanBeSelected(event.target,wrapper)){var sameWrapper=wrapper===this._mouseDownWrapper;this._updateMessagesSelection(wrapper,sameWrapper?this._mouseDownCommandKey:false,sameWrapper?this._mouseDownShiftKey:true,false);}}else if(!selection.isCollapsed){this._clearMessagesSelection();}else if(!this._mouseDownWrapper){this._clearMessagesSelection();setTimeout(()=>{this.prompt.focus();},0);}
delete this._mouseMoveIsRowSelection;delete this._mouseDownWrapper;delete this._mouseDownShiftKey;delete this._mouseDownCommandKey;}
_ondragstart(event)
{if(event.target.closest("."+WI.DOMTreeOutline.StyleClassName)){event.stopPropagation();event.preventDefault();}}
_handleDragOver(event)
{if(event.dataTransfer.types.includes(WI.DOMTreeOutline.DOMNodeIdDragType)){event.preventDefault();event.dataTransfer.dropEffect="copy";}}
_handleDrop(event)
{let domNodeId=event.dataTransfer.getData(WI.DOMTreeOutline.DOMNodeIdDragType);if(domNodeId){event.preventDefault();let domNode=WI.domManager.nodeForId(domNodeId);WI.RemoteObject.resolveNode(domNode,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{let text=domNode.nodeType()===Node.ELEMENT_NODE?WI.UIString("Dropped Element"):WI.UIString("Dropped Node");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);this.prompt.focus();});}}
handleEvent(event)
{switch(event.type){case"mousemove":this._mousemove(event);break;case"mouseup":this._mouseup(event);break;}}
_updateMessagesSelection(message,multipleSelection,rangeSelection,shouldScrollIntoView)
{if(!message)
return;var alreadySelectedMessage=this._selectedMessages.includes(message);if(alreadySelectedMessage&&this._selectedMessages.length&&multipleSelection){message.classList.remove(WI.LogContentView.SelectedStyleClassName);this._selectedMessages.remove(message);return;}
if(!multipleSelection&&!rangeSelection)
this._clearMessagesSelection();if(rangeSelection){var messages=this._visibleMessageElements();var refIndex=this._referenceMessageForRangeSelection?messages.indexOf(this._referenceMessageForRangeSelection):0;var targetIndex=messages.indexOf(message);var newRange=[Math.min(refIndex,targetIndex),Math.max(refIndex,targetIndex)];if(this._selectionRange&&this._selectionRange[0]===newRange[0]&&this._selectionRange[1]===newRange[1])
return;var startIndex=this._selectionRange?Math.min(this._selectionRange[0],newRange[0]):newRange[0];var endIndex=this._selectionRange?Math.max(this._selectionRange[1],newRange[1]):newRange[1];for(var i=startIndex;i<=endIndex;++i){var messageInRange=messages[i];if(i>=newRange[0]&&i<=newRange[1]&&!messageInRange.classList.contains(WI.LogContentView.SelectedStyleClassName)){messageInRange.classList.add(WI.LogContentView.SelectedStyleClassName);this._selectedMessages.push(messageInRange);}else if(i<newRange[0]||i>newRange[1]&&messageInRange.classList.contains(WI.LogContentView.SelectedStyleClassName)){messageInRange.classList.remove(WI.LogContentView.SelectedStyleClassName);this._selectedMessages.remove(messageInRange);}}
this._selectionRange=newRange;}else{message.classList.add(WI.LogContentView.SelectedStyleClassName);this._selectedMessages.push(message);this._selectionRange=null;}
if(!rangeSelection)
this._referenceMessageForRangeSelection=message;if(shouldScrollIntoView&&!alreadySelectedMessage){let lastMessage=this._selectedMessages.lastValue;if(lastMessage)
lastMessage.scrollIntoViewIfNeeded();}}
_isMessageVisible(message)
{var node=message;if(node.classList.contains(WI.LogContentView.FilteredOutStyleClassName))
return false;if(this.hasPerformedSearch&&node.classList.contains(WI.LogContentView.FilteredOutBySearchStyleClassName))
return false;if(message.classList.contains("console-group-title"))
node=node.parentNode.parentNode;while(node&&node!==this.messagesElement){if(node.classList.contains("collapsed"))
return false;node=node.parentNode;}
return true;}
_isMessageSelected(message)
{return message.classList.contains(WI.LogContentView.SelectedStyleClassName);}
_clearMessagesSelection()
{this._selectedMessages.forEach(function(message){message.classList.remove(WI.LogContentView.SelectedStyleClassName);});this._selectedMessages=[];delete this._referenceMessageForRangeSelection;}
_selectAllMessages()
{this._clearMessagesSelection();var messages=this._visibleMessageElements();for(var i=0;i<messages.length;++i){var message=messages[i];message.classList.add(WI.LogContentView.SelectedStyleClassName);this._selectedMessages.push(message);}}
_allMessageElements()
{return Array.from(this.messagesElement.querySelectorAll(".console-message, .console-user-command"));}
_unfilteredMessageElements()
{return this._allMessageElements().filter(function(message){return!message.classList.contains(WI.LogContentView.FilteredOutStyleClassName);});}
_visibleMessageElements()
{var unfilteredMessages=this._unfilteredMessageElements();if(!this.hasPerformedSearch)
return unfilteredMessages;return unfilteredMessages.filter(function(message){return!message.classList.contains(WI.LogContentView.FilteredOutBySearchStyleClassName);});}
_logCleared(event)
{for(let messageElement of this._allMessageElements()){if(messageElement.__messageView)
messageElement.__messageView.clearSessionState();}
this._logViewController.clear();this._nestingLevel=0;this._selectedMessages=[];this._immediatelyHiddenMessages.clear();if(this._currentSearchQuery)
this.performSearch(this._currentSearchQuery);this._showHiddenMessagesBannerIfNeeded();}
_showConsoleTab()
{const requestedScope=null;WI.showConsoleTab(requestedScope,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ButtonClick,});}
_clearLog()
{WI.consoleManager.requestClearMessages();}
_garbageCollect()
{for(let target of WI.targets)
target.HeapAgent.gc();}
_messageShouldBeVisible(message)
{let messageSource=this._messageSourceBar&&this._scopeFromMessageSource(message.source);if(messageSource&&!this._messageSourceBar.item(messageSource).selected&&!this._messageSourceBar.item(WI.LogContentView.Scopes.AllChannels).selected)
return false;let messageLevel=this._scopeFromMessageLevel(message.level);if(messageLevel)
return this._scopeBar.item(messageLevel).selected||this._scopeBar.item(WI.LogContentView.Scopes.All).selected;return true;}
_messageSourceBarSelectionDidChange(event)
{let items=this._messageSourceBar.selectedItems;if(items.some((item)=>item.id===WI.LogContentView.Scopes.AllChannels))
items=this._messageSourceBar.items;this._filterMessageElements(this._allMessageElements());this._showHiddenMessagesBannerIfNeeded();}
_scopeBarSelectionDidChange(event)
{let items=this._scopeBar.selectedItems;if(items.some((item)=>item.id===WI.LogContentView.Scopes.All))
items=this._scopeBar.items;this._filterMessageElements(this._allMessageElements());this._showHiddenMessagesBannerIfNeeded();}
_filterMessageElements(messageElements)
{messageElements.forEach(function(messageElement){let visible=false;if(messageElement.__commandView instanceof WI.ConsoleCommandView||messageElement.__message instanceof WI.ConsoleCommandResultMessage)
visible=this._scopeBar.selectedItems.some((item)=>item.id===WI.LogContentView.Scopes.Evaluations||item.id===WI.LogContentView.Scopes.All);else
visible=this._messageShouldBeVisible(messageElement.__message);let classList=messageElement.classList;if(visible){classList.remove(WI.LogContentView.FilteredOutStyleClassName);this._immediatelyHiddenMessages.delete(messageElement.__messageView);}else{this._selectedMessages.remove(messageElement);classList.remove(WI.LogContentView.SelectedStyleClassName);classList.add(WI.LogContentView.FilteredOutStyleClassName);}},this);this.performSearch(this._currentSearchQuery);}
_handleClearLogOnNavigateSettingChanged()
{this._preserveLogNavigationItem.checked=!WI.settings.clearLogOnNavigate.value;}
_handleEmulateInUserGestureSettingChanged()
{this._emulateUserGestureNavigationItem.checked=WI.settings.emulateInUserGesture.value;}
_keyDown(event)
{if(this._keyboardShortcutCommandA.matchesEvent(event))
this._commandAWasPressed(event);else if(this._keyboardShortcutEsc.matchesEvent(event))
this._escapeWasPressed(event);else if(event.keyIdentifier==="Up")
this._upArrowWasPressed(event);else if(event.keyIdentifier==="Down")
this._downArrowWasPressed(event);else if(event.keyIdentifier==="Left")
this._leftArrowWasPressed(event);else if(event.keyIdentifier==="Right")
this._rightArrowWasPressed(event);else if(event.keyIdentifier==="Enter"&&event.metaKey)
this._commandEnterWasPressed(event);}
_keyPress(event)
{const isCommandC=event.metaKey&&event.keyCode===99;if(!isCommandC)
this.prompt.focus();}
_commandAWasPressed(event)
{this._selectAllMessages();event.preventDefault();}
_escapeWasPressed(event)
{if(this._selectedMessages.length)
this._clearMessagesSelection();else
this.prompt.focus();event.preventDefault();}
_upArrowWasPressed(event)
{var messages=this._visibleMessageElements();if(!this._selectedMessages.length){if(messages.length)
this._updateMessagesSelection(messages.lastValue,false,false,true);return;}
var lastMessage=this._selectedMessages.lastValue;var previousMessage=this._previousMessage(lastMessage);if(previousMessage){this._updateMessagesSelection(previousMessage,false,event.shiftKey,true);event.preventDefault();}else if(!event.shiftKey){this._clearMessagesSelection();if(messages.length){this._updateMessagesSelection(messages[0],false,false,true);event.preventDefault();}}}
_downArrowWasPressed(event)
{var messages=this._visibleMessageElements();if(!this._selectedMessages.length){if(messages.length)
this._updateMessagesSelection(messages[0],false,false,true);return;}
var lastMessage=this._selectedMessages.lastValue;var nextMessage=this._nextMessage(lastMessage);if(nextMessage){this._updateMessagesSelection(nextMessage,false,event.shiftKey,true);event.preventDefault();}else if(!event.shiftKey){this._clearMessagesSelection();if(messages.length){this._updateMessagesSelection(messages.lastValue,false,false,true);event.preventDefault();}}}
_leftArrowWasPressed(event)
{if(this._selectedMessages.length!==1)
return;var currentMessage=this._selectedMessages[0];if(currentMessage.classList.contains("console-group-title")){currentMessage.parentNode.classList.add("collapsed");event.preventDefault();}else if(currentMessage.__messageView&&currentMessage.__messageView.expandable){currentMessage.__messageView.collapse();event.preventDefault();}}
_rightArrowWasPressed(event)
{if(this._selectedMessages.length!==1)
return;var currentMessage=this._selectedMessages[0];if(currentMessage.classList.contains("console-group-title")){currentMessage.parentNode.classList.remove("collapsed");event.preventDefault();}else if(currentMessage.__messageView&&currentMessage.__messageView.expandable){currentMessage.__messageView.expand();event.preventDefault();}}
_commandEnterWasPressed(event)
{if(this._selectedMessages.length!==1)
return;let message=this._selectedMessages[0];if(message.__commandView&&message.__commandView.commandText){this._logViewController.consolePromptTextCommitted(null,message.__commandView.commandText);event.preventDefault();}}
_previousMessage(message)
{var messages=this._visibleMessageElements();for(var i=messages.indexOf(message)-1;i>=0;--i){if(this._isMessageVisible(messages[i]))
return messages[i];}
return null;}
_nextMessage(message)
{var messages=this._visibleMessageElements();for(var i=messages.indexOf(message)+1;i<messages.length;++i){if(this._isMessageVisible(messages[i]))
return messages[i];}
return null;}
_clearFocusableChildren()
{var focusableElements=this.messagesElement.querySelectorAll("[tabindex]");for(var i=0,count=focusableElements.length;i<count;++i)
focusableElements[i].removeAttribute("tabindex");}
findBannerPerformSearch(findBanner,searchQuery)
{this.performSearch(searchQuery);}
findBannerSearchCleared()
{this.searchCleared();}
revealNextSearchResult()
{this.findBannerRevealNextResult();}
revealPreviousSearchResult()
{this.findBannerRevealPreviousResult();}
performSearch(searchQuery)
{if(!isEmptyObject(this._searchHighlightDOMChanges))
WI.revertDOMChanges(this._searchHighlightDOMChanges);this._currentSearchQuery=searchQuery;this._searchHighlightDOMChanges=[];this._searchMatches=[];this._selectedSearchMatchIsValid=false;this._selectedSearchMatch=null;let numberOfResults=0;if(this._currentSearchQuery===""){this.element.classList.remove(WI.LogContentView.SearchInProgressStyleClassName);this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);return;}
let searchRegex=WI.SearchUtilities.searchRegExpForString(this._currentSearchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this._findBanner.numberOfResults=0;this.element.classList.remove(WI.LogContentView.SearchInProgressStyleClassName);this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);return;}
this.element.classList.add(WI.LogContentView.SearchInProgressStyleClassName);this._unfilteredMessageElements().forEach(function(message){let matchRanges=[];let text=message.textContent;let match=searchRegex.exec(text);while(match){numberOfResults++;matchRanges.push({offset:match.index,length:match[0].length});match=searchRegex.exec(text);}
if(!isEmptyObject(matchRanges))
this._highlightRanges(message,matchRanges);let classList=message.classList;if(!isEmptyObject(matchRanges))
classList.remove(WI.LogContentView.FilteredOutBySearchStyleClassName);else
classList.add(WI.LogContentView.FilteredOutBySearchStyleClassName);},this);this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);this._findBanner.numberOfResults=numberOfResults;if(!this._selectedSearchMatchIsValid&&this._selectedSearchMatch){this._selectedSearchMatch.highlight.classList.remove(WI.LogContentView.SelectedStyleClassName);this._selectedSearchMatch=null;}}
searchHidden()
{this.searchCleared();}
searchCleared()
{this.performSearch("");}
_highlightRanges(message,matchRanges)
{var highlightedElements=WI.highlightRangesWithStyleClass(message,matchRanges,WI.LogContentView.HighlightedStyleClassName,this._searchHighlightDOMChanges);matchRanges.forEach(function(range,index){this._searchMatches.push({message,range,highlight:highlightedElements[index]});if(this._selectedSearchMatch&&!this._selectedSearchMatchIsValid&&this._selectedSearchMatch.message===message){this._selectedSearchMatchIsValid=this._rangesOverlap(this._selectedSearchMatch.range,range);if(this._selectedSearchMatchIsValid){delete this._selectedSearchMatch;this._highlightSearchMatchAtIndex(this._searchMatches.length-1);}}},this);}
_rangesOverlap(range1,range2)
{return range1.offset<=range2.offset+range2.length&&range2.offset<=range1.offset+range1.length;}
_highlightSearchMatchAtIndex(index)
{if(index>=this._searchMatches.length)
index=0;else if(index<0)
index=this._searchMatches.length-1;if(this._selectedSearchMatch)
this._selectedSearchMatch.highlight.classList.remove(WI.LogContentView.SelectedStyleClassName);this._selectedSearchMatch=this._searchMatches[index];this._selectedSearchMatch.highlight.classList.add(WI.LogContentView.SelectedStyleClassName);this._selectedSearchMatch.message.scrollIntoViewIfNeeded(false);}
_provisionalLoadStarted()
{this._startedProvisionalLoad=true;}
_reappendProvisionalMessages()
{if(!this._startedProvisionalLoad)
return;this._startedProvisionalLoad=false;for(let provisionalMessage of this._provisionalMessages)
this._logViewController.appendConsoleMessage(provisionalMessage);this._provisionalMessages=[];}
_clearProvisionalState()
{this._startedProvisionalLoad=false;this._provisionalMessages=[];}
_showHiddenMessagesBannerIfNeeded()
{if(!this._immediatelyHiddenMessages.size){if(this._hiddenMessagesBannerElement)
this._hiddenMessagesBannerElement.remove();return;}
if(!this._hiddenMessagesBannerElement){this._hiddenMessagesBannerElement=document.createElement("div");this._hiddenMessagesBannerElement.className="hidden-messages-banner";this._hiddenMessagesBannerElement.appendChild(document.createTextNode(WI.UIString("There are unread messages that have been filtered")));let clearFiltersButtonElement=this._hiddenMessagesBannerElement.appendChild(document.createElement("button"));clearFiltersButtonElement.textContent=WI.UIString("Clear Filters");clearFiltersButtonElement.addEventListener("click",(event)=>{this._findBanner.clearAndBlur();this._scopeBar.resetToDefault();this._hiddenMessagesBannerElement.remove();});let dismissBannerIconElement=this._hiddenMessagesBannerElement.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Close.svg","dismiss",WI.UIString("Dismiss")));dismissBannerIconElement.addEventListener("click",(event)=>{this._immediatelyHiddenMessages.clear();this._hiddenMessagesBannerElement.remove();});}
if(this.element.firstChild!==this._hiddenMessagesBannerElement)
this.element.insertAdjacentElement("afterbegin",this._hiddenMessagesBannerElement);}};WI.LogContentView.Scopes={All:"log-all",Debugs:"log-debugs",Errors:"log-errors",Evaluations:"log-evaluations",Infos:"log-infos",Logs:"log-logs",Warnings:"log-warnings",AllChannels:"log-all-channels",Media:"log-media",MediaSource:"log-mediasource",WebRTC:"log-webrtc",};WI.LogContentView.ItemWrapperStyleClassName="console-item";WI.LogContentView.FilteredOutStyleClassName="filtered-out";WI.LogContentView.SelectedStyleClassName="selected";WI.LogContentView.SearchInProgressStyleClassName="search-in-progress";WI.LogContentView.FilteredOutBySearchStyleClassName="filtered-out-by-search";WI.LogContentView.HighlightedStyleClassName="highlighted";WI.MediaTimelineDataGridNode=class MediaTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);} 
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.name=this.record.displayName;this._cachedData.element=this.record.domNode;this._cachedData.source=this.record.domNode; return this._cachedData;}
createCellContent(columnIdentifier,cell)
{let value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return this._createNameCellDocumentFragment();case"element":case"source": if(!value)
return emDash;if(!(value instanceof WI.DOMNode)){cell.classList.add(WI.DOMTreeElementPathComponent.DOMNodeIconStyleClassName);return value.displayName;}
break;}
return super.createCellContent(columnIdentifier,cell);} 
timelineRecordBarCustomChildren(timelineRecordBar)
{let children=[];let record=this.record;let timestamps=record.timestamps;switch(record.eventType){case WI.MediaTimelineRecord.EventType.CSSAnimation:case WI.MediaTimelineRecord.EventType.CSSTransition:{let readyStartTime=NaN;function addReadySegment(startTime,endTime){children.push({startTime,endTime,classNames:["segment","css-animation-ready"],title:WI.UIString("Ready","Tooltip for a time range bar that represents when a CSS animation/transition exists but has not started processing"),});readyStartTime=NaN;}
let delayStartTime=NaN;function addDelaySegment(startTime,endTime){children.push({startTime,endTime,classNames:["segment","css-animation-delay"],title:WI.UIString("Delay","Tooltip for a time range bar that represents when a CSS animation/transition is delayed"),});delayStartTime=NaN;}
let activeStartTime=NaN;function addActiveSegment(startTime,endTime){children.push({startTime,endTime,classNames:["segment","css-animation-active"],title:WI.UIString("Active","Tooltip for a time range bar that represents when a CSS animation/transition is running"),});activeStartTime=NaN;}
for(let item of timestamps){switch(item.type){case WI.MediaTimelineRecord.TimestampType.CSSAnimationReady:if(isNaN(readyStartTime))
readyStartTime=item.timestamp;break;case WI.MediaTimelineRecord.TimestampType.CSSAnimationDelay:if(isNaN(delayStartTime))
delayStartTime=item.timestamp;if(!isNaN(readyStartTime))
addReadySegment(readyStartTime,item.timestamp);break;case WI.MediaTimelineRecord.TimestampType.CSSAnimationActive:if(isNaN(activeStartTime))
activeStartTime=item.timestamp;if(!isNaN(readyStartTime))
addReadySegment(readyStartTime,item.timestamp);if(!isNaN(delayStartTime))
addDelaySegment(delayStartTime,item.timestamp);break;case WI.MediaTimelineRecord.TimestampType.CSSAnimationCancel:case WI.MediaTimelineRecord.TimestampType.CSSAnimationDone:if(!isNaN(readyStartTime))
addReadySegment(readyStartTime,item.timestamp);if(!isNaN(delayStartTime))
addDelaySegment(delayStartTime,item.timestamp);if(!isNaN(activeStartTime))
addActiveSegment(activeStartTime,item.timestamp);break;}}
if(!isNaN(readyStartTime))
addReadySegment(readyStartTime,NaN);if(!isNaN(delayStartTime))
addDelaySegment(delayStartTime,NaN);if(!isNaN(activeStartTime))
addActiveSegment(activeStartTime,NaN);break;}
case WI.MediaTimelineRecord.EventType.MediaElement:{let fullScreenSegments=[];let powerEfficientPlaybackSegments=[];let activeSegments=[];let fullScreenStartTime=NaN;let fullScreenOriginator=null;function addFullScreenSegment(startTime,endTime){fullScreenSegments.push({startTime,endTime,classNames:["segment","media-element-full-screen"],title:fullScreenOriginator?WI.UIString("Full-Screen from \u201C%s\u201D").format(fullScreenOriginator.displayName):WI.UIString("Full-Screen"),});fullScreenStartTime=NaN;fullScreenOriginator=null;}
let powerEfficientPlaybackStartTime=NaN;function addPowerEfficientPlaybackSegment(startTime,endTime){powerEfficientPlaybackSegments.push({startTime,endTime,classNames:["segment","media-element-power-efficient-playback"],title:WI.UIString("Power Efficient Playback"),});powerEfficientPlaybackStartTime=NaN;}
let pausedStartTime=NaN;function addPausedSegment(startTime,endTime){activeSegments.push({startTime,endTime,classNames:["segment","media-element-paused"],title:WI.UIString("Paused","Tooltip for a time range bar that represents when the playback of a audio/video element is paused"),});pausedStartTime=NaN;}
let playingStartTime=NaN;function addPlayingSegment(startTime,endTime){activeSegments.push({startTime,endTime,classNames:["segment","media-element-playing"],title:WI.UIString("Playing","Tooltip for a time range bar that represents when the playback of a audio/video element is running"),});playingStartTime=NaN;}
for(let item of timestamps){if(item.type===WI.MediaTimelineRecord.TimestampType.MediaElementDOMEvent){if(WI.DOMNode.isPlayEvent(item.eventName)){if(isNaN(playingStartTime))
playingStartTime=item.timestamp;if(!isNaN(pausedStartTime))
addPausedSegment(pausedStartTime,item.timestamp);}else if(WI.DOMNode.isPauseEvent(item.eventName)){if(isNaN(pausedStartTime))
pausedStartTime=item.timestamp;if(!isNaN(playingStartTime))
addPlayingSegment(playingStartTime,item.timestamp);}else if(WI.DOMNode.isStopEvent(item.eventName)){if(!isNaN(pausedStartTime))
addPausedSegment(pausedStartTime,item.timestamp);if(!isNaN(playingStartTime))
addPlayingSegment(playingStartTime,item.timestamp);}else if(item.eventName==="webkitfullscreenchange"){if(!fullScreenOriginator&&item.originator)
fullScreenOriginator=item.originator;if(isNaN(fullScreenStartTime)){if(item.data&&item.data.enabled)
fullScreenStartTime=item.timestamp;else
addFullScreenSegment(this.graphDataSource?this.graphDataSource.startTime:record.startTime,item.timestamp);}else if(!item.data||!item.data.enabled)
addFullScreenSegment(fullScreenStartTime,item.timestamp);}}else if(item.type===WI.MediaTimelineRecord.TimestampType.MediaElementPowerEfficientPlaybackStateChange){if(isNaN(powerEfficientPlaybackStartTime)){if(item.isPowerEfficient)
powerEfficientPlaybackStartTime=item.timestamp;else
addPowerEfficientPlaybackSegment(this.graphDataSource?this.graphDataSource.startTime:record.startTime,item.timestamp);}else if(!item.isPowerEfficient)
addPowerEfficientPlaybackSegment(powerEfficientPlaybackStartTime,item.timestamp);}}
if(!isNaN(fullScreenStartTime))
addFullScreenSegment(fullScreenStartTime,NaN);if(!isNaN(powerEfficientPlaybackStartTime))
addPowerEfficientPlaybackSegment(powerEfficientPlaybackStartTime,NaN);if(!isNaN(pausedStartTime))
addPausedSegment(pausedStartTime,NaN);if(!isNaN(playingStartTime))
addPlayingSegment(playingStartTime,NaN);children.pushAll(fullScreenSegments);children.pushAll(powerEfficientPlaybackSegments);children.pushAll(activeSegments);break;}}
timestamps.forEach((item,i)=>{let image={startTime:item.timestamp,classNames:[],};switch(item.type){case WI.MediaTimelineRecord.TimestampType.CSSAnimationReady:case WI.MediaTimelineRecord.TimestampType.CSSAnimationDelay:case WI.MediaTimelineRecord.TimestampType.CSSAnimationDone:case WI.MediaTimelineRecord.TimestampType.MediaElementPowerEfficientPlaybackStateChange:return;case WI.MediaTimelineRecord.TimestampType.CSSAnimationActive:
if(!i||timestamps[i-1].type!==WI.MediaTimelineRecord.TimestampType.CSSAnimationActive)
return;image.image="Images/EventIteration.svg";image.title=WI.UIString("Iteration","Tooltip for a timestamp marker that represents when a CSS animation/transition iterates");break;case WI.MediaTimelineRecord.TimestampType.CSSAnimationCancel:image.image="Images/EventCancel.svg";image.title=WI.UIString("Canceled","Tooltip for a timestamp marker that represents when a CSS animation/transition is canceled");break;case WI.MediaTimelineRecord.TimestampType.MediaElementDOMEvent:
if(item.eventName==="webkitfullscreenchange")
return;image.title=WI.UIString("DOM Event \u201C%s\u201D").format(item.eventName);if(WI.DOMNode.isPlayEvent(item.eventName))
image.image="Images/EventPlay.svg";else if(WI.DOMNode.isPauseEvent(item.eventName))
image.image="Images/EventPause.svg";else if(WI.DOMNode.isStopEvent(item.eventName))
image.image="Images/EventStop.svg";else
image.image="Images/EventProcessing.svg";break;}
children.push(image);});return children;} 
filterableDataForColumn(columnIdentifier)
{switch(columnIdentifier){case"name":return[this.record.displayName,this.record.subtitle];case"element":case"source": if(this.record.domNode)
return this.record.domNode.displayName;break;}
return super.filterableDataForColumn(columnIdentifier);} 
_createNameCellDocumentFragment()
{let fragment=document.createDocumentFragment();fragment.append(this.record.displayName);if(this.record.subtitle){let subtitleElement=fragment.appendChild(document.createElement("span"));subtitleElement.className="subtitle";subtitleElement.textContent=this.record.subtitle;}
return fragment;}};WI.MediaTimelineOverviewGraph=class MediaTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("media");this.reset();for(let record of timeline.records)
this._processRecord(record);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._handleRecordAdded,this);timeline.addEventListener(WI.Timeline.Event.TimesUpdated,this._handleTimesUpdated,this);} 
static get maximumRowCount(){return 6;} 
reset()
{super.reset();this._recordsWithoutStartTime=new Set;this.element.removeChildren();this._nextDumpRow=0;this._timelineRecordGridRows=[];for(let i=0;i<MediaTimelineOverviewGraph.maximumRowCount;++i){let rowElement=this.element.appendChild(document.createElement("div"));rowElement.className="graph-row";this._timelineRecordGridRows.push({records:[],recordBars:[],element:rowElement,});}} 
layout()
{super.layout();if(this.hidden)
return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let recordBarIndex=0;let createBar=(element,recordBars,records,renderMode)=>{let timelineRecordBar=recordBars[recordBarIndex];if(!timelineRecordBar)
timelineRecordBar=recordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;}
timelineRecordBar.refresh(this);if(!timelineRecordBar.element.parentNode)
element.appendChild(timelineRecordBar.element);++recordBarIndex;};for(let{records,recordBars,element}of this._timelineRecordGridRows){recordBarIndex=0;WI.TimelineRecordBar.createCombinedBars(records,secondsPerPixel,this,createBar.bind(this,element,recordBars));for(;recordBarIndex<recordBars.length;++recordBarIndex){recordBars[recordBarIndex].records=null;recordBars[recordBarIndex].element.remove();}}}
updateSelectedRecord()
{super.updateSelectedRecord();for(let{recordBars}of this._timelineRecordGridRows){for(let recordBar of recordBars){if(recordBar.records.includes(this.selectedRecord)){this.selectedRecordBar=recordBar;return;}}}
this.selectedRecordBar=null;} 
_processRecord(record)
{if(isNaN(record.startTime)){this._recordsWithoutStartTime.add(record);record.singleFireEventListener(WI.TimelineRecord.Event.Updated,function(event){this._processRecord(record);this.needsLayout();},this);return;}
this._recordsWithoutStartTime.delete(record);function compareByStartTime(a,b){return a.startTime-b.startTime;}
let minimumBarPaddingTime=WI.TimelineOverview.MinimumDurationPerPixel*(WI.TimelineRecordBar.MinimumWidthPixels+WI.TimelineRecordBar.MinimumMarginPixels);for(let i=0;i<this._timelineRecordGridRows.length;++i){let records=this._timelineRecordGridRows[i].records;let lastRecord=records.lastValue;if(!lastRecord||lastRecord.endTime+minimumBarPaddingTime<=record.startTime){insertObjectIntoSortedArray(record,records,compareByStartTime);this._nextDumpRow=i+1;return;}}
for(let i=0;i<this._timelineRecordGridRows.length;++i){let records=this._timelineRecordGridRows[i].records;let lastRecord=records.lastValue;if(lastRecord.usesActiveStartTime&&lastRecord.activeStartTime+minimumBarPaddingTime<=record.startTime){insertObjectIntoSortedArray(record,records,compareByStartTime);this._nextDumpRow=i+1;break;}}
if(this._nextDumpRow>=MediaTimelineOverviewGraph.maximumRowCount)
this._nextDumpRow=0;insertObjectIntoSortedArray(record,this._timelineRecordGridRows[this._nextDumpRow++].records,compareByStartTime);}
_handleRecordAdded(event)
{this._processRecord(event.data.record);this.needsLayout();}
_handleTimesUpdated(event)
{this.needsLayout();}};WI.MediaTimelineView=class MediaTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);this._timelineRuler=new WI.TimelineRuler;const columns={name:{title:WI.UIString("Name"),width:"200px",icon:true,sortable:true,locked:true,},element:{title:WI.UIString("Element"),width:"150px",sortable:true,locked:true,},graph:{headerView:this._timelineRuler,sortable:true,locked:true,},};this._dataGrid=new WI.TimelineDataGrid(columns);this._dataGrid.sortDelegate=this;this._dataGrid.sortColumnIdentifier="graph";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("media-timeline-view");this.setupDataGrid(this._dataGrid);this.addSubview(this._dataGrid);this.element.classList.add("media");timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._handleRecordAdded,this);this._pendingRecords=[];for(let record of timeline.records)
this._processRecord(record);} 
get secondsPerPixel(){return this._timelineRuler.secondsPerPixel;}
get selectionPathComponents()
{if(!this._dataGrid.selectedNode||this._dataGrid.selectedNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(this._dataGrid.selectedNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._handleSelectionPathComponentSiblingSelected,this);return[pathComponent];}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._handleRecordAdded,this);this._dataGrid.closed();super.closed();}
reset()
{this._dataGrid.reset();this._pendingRecords=[];super.reset();} 
dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2)
{function compareDOMNodes(a,b){if(a&&!b)
return-1;if(b&&!a)
return 1;if(!a&&!b)
return 0;return a.displayName.extendedLocaleCompare(b.displayName);}
if(sortColumnIdentifier==="name"){let displayName1=node1.displayName();let displayName2=node2.displayName();return displayName1.extendedLocaleCompare(displayName2)*sortDirection;}
if(sortColumnIdentifier==="element")
return compareDOMNodes(node1.record.domNode,node2.record.domNode)*sortDirection;if(sortColumnIdentifier==="graph")
return(node1.record.startTime-node2.record.startTime)*sortDirection;return null;} 
layout()
{super.layout();this.endTime=Math.min(this.endTime,this.currentTime);let oldZeroTime=this._timelineRuler.zeroTime;let oldStartTime=this._timelineRuler.startTime;let oldEndTime=this._timelineRuler.endTime;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;if(this.zeroTime!==oldZeroTime||this.startTime!==oldStartTime||this.endTime!==oldEndTime){for(let dataGridNode of this._dataGrid.children)
dataGridNode.refreshGraph();}
this._processPendingRecords();} 
_processPendingRecords()
{if(!this._pendingRecords.length)
return;for(let timelineRecord of this._pendingRecords){this._dataGrid.addRowInSortOrder(new WI.MediaTimelineDataGridNode(timelineRecord,{graphDataSource:this,}));}
this._pendingRecords=[];}
_handleRecordAdded(event)
{let mediaTimelineRecord=event.data.record;this._processRecord(mediaTimelineRecord);this.needsLayout();}
_processRecord(mediaTimelineRecord)
{this._pendingRecords.push(mediaTimelineRecord);}
_handleSelectionPathComponentSiblingSelected(event)
{let pathComponent=event.data.pathComponent;let dataGridNode=pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}};WI.MemoryCategoryView=class MemoryCategoryView extends WI.View
{constructor(category,displayName)
{super();this._category=category;this.element.classList.add("memory-category-view",category);this._detailsElement=this.element.appendChild(document.createElement("div"));this._detailsElement.classList.add("details");let detailsNameElement=this._detailsElement.appendChild(document.createElement("span"));detailsNameElement.classList.add("name");detailsNameElement.textContent=displayName;this._detailsElement.appendChild(document.createElement("br"));this._detailsMaxElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsMinElement=this._detailsElement.appendChild(document.createElement("span"));this._updateDetails(NaN,NaN);this._graphElement=this.element.appendChild(document.createElement("div"));this._graphElement.classList.add("graph");this._chart=new WI.AreaChart;this.addSubview(this._chart);this._graphElement.appendChild(this._chart.element);} 
get category(){return this._category;}
clear()
{this._cachedMinSize=undefined;this._cachedMaxSize=undefined;this._updateDetails(NaN,NaN);this._chart.clear();}
updateChart(dataPoints,size,visibleEndTime,min,max,xScale,yScale)
{this._updateDetails(min,max);this._chart.clear();this._chart.size=size;this._chart.needsLayout();if(!dataPoints.length)
return;if(!max)
return;let firstX=0;let firstY=yScale(dataPoints[0].size);this._chart.addPoint(firstX,firstY);for(let dataPoint of dataPoints){let x=xScale(dataPoint.time);let y=yScale(dataPoint.size);this._chart.addPoint(x,y);}
let lastDataPoint=dataPoints.lastValue;let lastX=Math.floor(xScale(visibleEndTime));let lastY=yScale(lastDataPoint.size);this._chart.addPoint(lastX,lastY);} 
_updateDetails(minSize,maxSize)
{if(this._cachedMinSize===minSize&&this._cachedMaxSize===maxSize)
return;this._cachedMinSize=minSize;this._cachedMaxSize=maxSize;this._detailsMaxElement.textContent=WI.UIString("Highest: %s").format(Number.isFinite(maxSize)?Number.bytesToString(maxSize):emDash);this._detailsMinElement.textContent=WI.UIString("Lowest: %s").format(Number.isFinite(minSize)?Number.bytesToString(minSize):emDash);}};WI.MemoryTimelineOverviewGraph=class MemoryTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("memory");this._memoryTimeline=timeline;this._memoryTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._memoryTimelineRecordAdded,this);this._memoryTimeline.addEventListener(WI.MemoryTimeline.Event.MemoryPressureEventAdded,this._memoryTimelineMemoryPressureEventAdded,this);this._didInitializeCategories=false;this._chart=new WI.StackedAreaChart;this._chart.size=new WI.Size(0,this.height);this.addSubview(this._chart);this.element.appendChild(this._chart.element);this._legendElement=this.element.appendChild(document.createElement("div"));this._legendElement.classList.add("legend");this._memoryPressureMarkersContainerElement=this.element.appendChild(document.createElement("div"));this._memoryPressureMarkersContainerElement.classList.add("memory-pressure-markers-container");this._memoryPressureMarkerElements=[];this.reset();for(let record of this._memoryTimeline.records)
this._processRecord(record);} 
get height()
{return 108;}
reset()
{super.reset();this._maxSize=0;this._cachedMaxSize=undefined;this._updateLegend();this._chart.clear();this._chart.needsLayout();this._memoryPressureMarkersContainerElement.removeChildren();this._memoryPressureMarkerElements=[];}
layout()
{super.layout();if(this.hidden)
return;this._updateLegend();this._chart.clear();if(!this._didInitializeCategories)
return;let graphWidth=this.timelineOverview.scrollContainerWidth;if(isNaN(graphWidth))
return;if(this._chart.size.width!==graphWidth||this._chart.size.height!==this.height)
this._chart.size=new WI.Size(graphWidth,this.height);let graphStartTime=this.startTime;let visibleEndTime=Math.min(this.endTime,this.currentTime);let secondsPerPixel=this.timelineOverview.secondsPerPixel;let maxCapacity=this._maxSize*1.05;function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
let height=this.height;function yScale(size){return height-((size/maxCapacity)*height);}
let visibleMemoryPressureEventMarkers=this._visibleMemoryPressureEvents(graphStartTime,visibleEndTime);for(let i=0;i<visibleMemoryPressureEventMarkers.length;++i){let markerElement=this._memoryPressureMarkerElements[i];if(!markerElement){markerElement=this._memoryPressureMarkersContainerElement.appendChild(document.createElement("div"));markerElement.classList.add("memory-pressure-event");this._memoryPressureMarkerElements[i]=markerElement;}
let memoryPressureEvent=visibleMemoryPressureEventMarkers[i];let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";markerElement.style.setProperty(property,`${xScale(memoryPressureEvent.timestamp)}px`);}
let excess=this._memoryPressureMarkerElements.length-visibleMemoryPressureEventMarkers.length;if(excess){let elementsToRemove=this._memoryPressureMarkerElements.splice(visibleMemoryPressureEventMarkers.length);for(let element of elementsToRemove)
element.remove();}
let discontinuities=this.timelineOverview.discontinuitiesInTimeRange(graphStartTime,visibleEndTime);let visibleRecords=this._memoryTimeline.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:!discontinuities.length||discontinuities[0].startTime>graphStartTime,includeRecordAfterEnd:true,});if(!visibleRecords.length)
return;function pointSetForRecord(record){let size=0;let ys=[];for(let i=0;i<record.categories.length;++i){size+=record.categories[i].size;ys[i]=yScale(size);}
return ys;}
if(visibleRecords[0]===this._memoryTimeline.records[0]&&(!discontinuities.length||discontinuities[0].startTime>visibleRecords[0].startTime))
this._chart.addPointSet(0,pointSetForRecord(visibleRecords[0]));function insertDiscontinuity(previousRecord,startDiscontinuity,endDiscontinuity,nextRecord)
{if(!(previousRecord||nextRecord))
return;let xStart=xScale(previousRecord?previousRecord.endTime:startDiscontinuity.startTime);let xEnd=xScale(endDiscontinuity.endTime);if(previousRecord)
this._chart.addPointSet(xStart,pointSetForRecord(previousRecord));let zeroValues=Array((previousRecord||nextRecord).categories.length).fill(yScale(0));this._chart.addPointSet(xStart,zeroValues);if(nextRecord){this._chart.addPointSet(xEnd,zeroValues);this._chart.addPointSet(xEnd,pointSetForRecord(nextRecord));}else{
this._chart.addPointSet(xScale(visibleEndTime),zeroValues);}}
let previousRecord=null;for(let record of visibleRecords){if(discontinuities.length&&discontinuities[0].endTime<=record.startTime){let startDiscontinuity=discontinuities.shift();let endDiscontinuity=startDiscontinuity;while(discontinuities.length&&discontinuities[0].endTime<=record.startTime)
endDiscontinuity=discontinuities.shift();insertDiscontinuity.call(this,previousRecord,startDiscontinuity,endDiscontinuity,record);}
let x=xScale(record.startTime);this._chart.addPointSet(x,pointSetForRecord(record));previousRecord=record;}
if(discontinuities.length)
insertDiscontinuity.call(this,previousRecord,discontinuities[0],discontinuities[0],null);else{let lastRecord=visibleRecords.lastValue;if(lastRecord.startTime<=visibleEndTime){let x=Math.floor(xScale(lastRecord.endTime));this._chart.addPointSet(x,pointSetForRecord(lastRecord));}}} 
_updateLegend()
{if(this._cachedMaxSize===this._maxSize)
return;this._cachedMaxSize=this._maxSize;if(!this._maxSize){this._legendElement.hidden=true;this._legendElement.textContent="";}else{this._legendElement.hidden=false;this._legendElement.textContent=WI.UIString("Maximum Size: %s").format(Number.bytesToString(this._maxSize));}}
_visibleMemoryPressureEvents(startTime,endTime)
{let events=this._memoryTimeline.memoryPressureEvents;if(!events.length)
return[];let lowerIndex=events.lowerBound(startTime,(time,event)=>time-event.timestamp);let upperIndex=events.upperBound(endTime,(time,event)=>time-event.timestamp);return events.slice(lowerIndex,upperIndex);}
_memoryTimelineRecordAdded(event)
{let memoryTimelineRecord=event.data.record;this._processRecord(memoryTimelineRecord);this.needsLayout();}
_processRecord(memoryTimelineRecord)
{this._maxSize=Math.max(this._maxSize,memoryTimelineRecord.totalSize);if(!this._didInitializeCategories){this._didInitializeCategories=true;let types=[];for(let category of memoryTimelineRecord.categories)
types.push(category.type);this._chart.initializeSections(types);}}
_memoryTimelineMemoryPressureEventAdded(event)
{this.needsLayout();}};WI.MemoryTimelineView=class MemoryTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);this._recording=extraArguments.recording;this.element.classList.add("memory");let contentElement=this.element.appendChild(document.createElement("div"));contentElement.classList.add("content");let overviewElement=contentElement.appendChild(document.createElement("div"));overviewElement.classList.add("overview");function createChartContainer(parentElement,subtitle,tooltip){let chartElement=parentElement.appendChild(document.createElement("div"));chartElement.classList.add("chart");let chartSubtitleElement=chartElement.appendChild(document.createElement("div"));chartSubtitleElement.classList.add("subtitle");chartSubtitleElement.textContent=subtitle;chartSubtitleElement.title=tooltip;let chartFlexContainerElement=chartElement.appendChild(document.createElement("div"));chartFlexContainerElement.classList.add("container");return chartFlexContainerElement;}
let usageTooltip=WI.UIString("Breakdown of each memory category at the end of the selected time range");let usageChartContainerElement=createChartContainer(overviewElement,WI.UIString("Breakdown"),usageTooltip);this._usageCircleChart=new WI.CircleChart({size:120,innerRadiusRatio:0.5});this.addSubview(this._usageCircleChart);usageChartContainerElement.appendChild(this._usageCircleChart.element);this._usageLegendElement=usageChartContainerElement.appendChild(document.createElement("div"));this._usageLegendElement.classList.add("legend","usage");let dividerElement=overviewElement.appendChild(document.createElement("div"));dividerElement.classList.add("divider");let maxComparisonTooltip=WI.UIString("Comparison of total memory size at the end of the selected time range to the maximum memory size in this recording");let maxComparisonChartContainerElement=createChartContainer(overviewElement,WI.UIString("Max Comparison"),maxComparisonTooltip);this._maxComparisonCircleChart=new WI.CircleChart({size:120,innerRadiusRatio:0.5});this.addSubview(this._maxComparisonCircleChart);maxComparisonChartContainerElement.appendChild(this._maxComparisonCircleChart.element);this._maxComparisonLegendElement=maxComparisonChartContainerElement.appendChild(document.createElement("div"));this._maxComparisonLegendElement.classList.add("legend","maximum");let detailsContainerElement=this._detailsContainerElement=contentElement.appendChild(document.createElement("div"));detailsContainerElement.classList.add("details");this._timelineRuler=new WI.TimelineRuler;this.addSubview(this._timelineRuler);detailsContainerElement.appendChild(this._timelineRuler.element);let detailsSubtitleElement=detailsContainerElement.appendChild(document.createElement("div"));detailsSubtitleElement.classList.add("subtitle");detailsSubtitleElement.textContent=WI.UIString("Categories");this._didInitializeCategories=false;this._categoryViews=[];this._usageLegendSizeElementMap=new Map;this._maxSize=0;this._maxComparisonMaximumSizeElement=null;this._maxComparisonCurrentSizeElement=null;timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._memoryTimelineRecordAdded,this);this.element.addEventListener("mousemove",this._handleGraphMouseMove.bind(this));for(let record of timeline.records)
this._processRecord(record);} 
static displayNameForCategory(category)
{switch(category){case WI.MemoryCategory.Type.JavaScript:return WI.UIString("JavaScript");case WI.MemoryCategory.Type.Images:return WI.UIString("Images");case WI.MemoryCategory.Type.Layers:return WI.UIString("Layers");case WI.MemoryCategory.Type.Page:return WI.UIString("Page");}}
static get memoryCategoryViewHeight(){return 75;} 
attached()
{super.attached();this._timelineRuler.needsLayout(WI.View.LayoutReason.Resize);}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._memoryTimelineRecordAdded,this);}
reset()
{super.reset();this._maxSize=0;this.clear();}
clear()
{this._cachedLegendRecord=null;this._cachedLegendMaxSize=undefined;this._cachedLegendCurrentSize=undefined;this._usageCircleChart.clear();this._usageCircleChart.needsLayout();this._clearUsageLegend();this._maxComparisonCircleChart.clear();this._maxComparisonCircleChart.needsLayout();this._clearMaxComparisonLegend();for(let categoryView of this._categoryViews)
categoryView.clear();}
get scrollableElements()
{return[this.element];} 
get showsFilterBar(){return false;}
initialLayout()
{super.initialLayout();this.element.style.setProperty("--memory-category-view-height",MemoryTimelineView.memoryCategoryViewHeight+"px");}
layout()
{if(this.layoutReason===WI.View.LayoutReason.Resize)
return;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;if(!this._didInitializeCategories)
return;let graphStartTime=this.startTime;let graphEndTime=this.endTime;let secondsPerPixel=this._timelineRuler.secondsPerPixel;let visibleEndTime=Math.min(this.endTime,this.currentTime);let discontinuities=this._recording.discontinuitiesInTimeRange(graphStartTime,visibleEndTime);let visibleRecords=this.representedObject.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:!discontinuities.length||discontinuities[0].startTime>graphStartTime,includeRecordAfterEnd:true,});if(!visibleRecords.length||(visibleRecords.length===1&&visibleRecords[0].endTime<graphStartTime)){this.clear();return;}
let lastRecord=visibleRecords.lastValue;let values=[];for(let{size}of lastRecord.categories)
values.push(size);this._usageCircleChart.values=values;this._usageCircleChart.updateLayout();this._updateUsageLegend(lastRecord);this._maxComparisonCircleChart.values=[lastRecord.totalSize,this._maxSize-lastRecord.totalSize];this._maxComparisonCircleChart.updateLayout();this._updateMaxComparisonLegend(lastRecord.totalSize);let categoryDataMap={};for(let categoryView of this._categoryViews)
categoryDataMap[categoryView.category]={dataPoints:[],max:-Infinity,min:Infinity};for(let record of visibleRecords){let time=record.startTime;let startDiscontinuity=null;let endDiscontinuity=null;if(discontinuities.length&&discontinuities[0].endTime<=time){startDiscontinuity=discontinuities.shift();endDiscontinuity=startDiscontinuity;while(discontinuities.length&&discontinuities[0].endTime<=time)
endDiscontinuity=discontinuities.shift();}
for(let category of record.categories){let categoryData=categoryDataMap[category.type];if(startDiscontinuity){if(categoryData.dataPoints.length){let previousDataPoint=categoryData.dataPoints.lastValue;categoryData.dataPoints.push({time:startDiscontinuity.startTime,size:previousDataPoint.size});}
categoryData.dataPoints.push({time:startDiscontinuity.startTime,size:0});categoryData.dataPoints.push({time:endDiscontinuity.endTime,size:0});categoryData.dataPoints.push({time:endDiscontinuity.endTime,size:category.size});}
categoryData.dataPoints.push({time,size:category.size});categoryData.max=Math.max(categoryData.max,category.size);categoryData.min=Math.min(categoryData.min,category.size);}}

if(discontinuities.length)
visibleEndTime=discontinuities[0].startTime;function layoutCategoryView(categoryView,{dataPoints,min,max}){if(min===Infinity)
min=0;if(max===-Infinity)
max=0;let graphMin=min*0.95;let graphMax=(max*1.05)-graphMin;function xScale(time){return(time-graphStartTime)/secondsPerPixel;}
let size=new WI.Size(xScale(graphEndTime),MemoryTimelineView.memoryCategoryViewHeight);function yScale(value){return size.height-(((value-graphMin)/graphMax)*size.height);}
categoryView.updateChart(dataPoints,size,visibleEndTime,min,max,xScale,yScale);}
for(let categoryView of this._categoryViews)
layoutCategoryView(categoryView,categoryDataMap[categoryView.category]);} 
_graphPositionForMouseEvent(event)
{let chartElement=event.target.closest(".area-chart, .stacked-area-chart, .range-chart");if(!chartElement)
return NaN;let chartRect=chartElement.getBoundingClientRect();let position=event.pageX-chartRect.left;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
return chartRect.width-position;return position;}
_handleGraphMouseMove(event)
{let mousePosition=this._graphPositionForMouseEvent(event);if(isNaN(mousePosition)){this.dispatchEventToListeners(WI.TimelineView.Event.ScannerHide);return;}
let secondsPerPixel=this._timelineRuler.secondsPerPixel;let time=this.startTime+(mousePosition*secondsPerPixel);this.dispatchEventToListeners(WI.TimelineView.Event.ScannerShow,{time});}
_clearUsageLegend()
{for(let sizeElement of this._usageLegendSizeElementMap.values())
sizeElement.textContent=emDash;let totalElement=this._usageCircleChart.centerElement.firstChild;if(totalElement){totalElement.firstChild.textContent="";totalElement.lastChild.textContent="";}}
_updateUsageLegend(record)
{if(this._cachedLegendRecord===record)
return;this._cachedLegendRecord=record;for(let{type,size}of record.categories){let sizeElement=this._usageLegendSizeElementMap.get(type);sizeElement.textContent=Number.isFinite(size)?Number.bytesToString(size):emDash;}
let centerElement=this._usageCircleChart.centerElement;let totalElement=centerElement.firstChild;if(!totalElement){totalElement=centerElement.appendChild(document.createElement("div"));totalElement.classList.add("total-usage");totalElement.appendChild(document.createElement("span")); totalElement.appendChild(document.createElement("br"));totalElement.appendChild(document.createElement("span"));}
let totalSize=Number.bytesToString(record.totalSize).split(/\s+/);totalElement.firstChild.textContent=totalSize[0];totalElement.lastChild.textContent=totalSize[1];}
_clearMaxComparisonLegend()
{if(this._maxComparisonMaximumSizeElement)
this._maxComparisonMaximumSizeElement.textContent=emDash;if(this._maxComparisonCurrentSizeElement)
this._maxComparisonCurrentSizeElement.textContent=emDash;let totalElement=this._maxComparisonCircleChart.centerElement.firstChild;if(totalElement)
totalElement.textContent="";}
_updateMaxComparisonLegend(currentSize)
{if(this._cachedLegendMaxSize===this._maxSize&&this._cachedLegendCurrentSize===currentSize)
return;this._cachedLegendMaxSize=this._maxSize;this._cachedLegendCurrentSize=currentSize;this._maxComparisonMaximumSizeElement.textContent=Number.isFinite(this._maxSize)?Number.bytesToString(this._maxSize):emDash;this._maxComparisonCurrentSizeElement.textContent=Number.isFinite(currentSize)?Number.bytesToString(currentSize):emDash;let centerElement=this._maxComparisonCircleChart.centerElement;let totalElement=centerElement.firstChild;if(!totalElement){totalElement=centerElement.appendChild(document.createElement("div"));totalElement.classList.add("max-percentage");}
let percent=currentSize/this._maxSize;totalElement.textContent=Number.percentageString(percent===1?percent:(percent-0.0005));}
_initializeCategoryViews(record)
{this._didInitializeCategories=true;let segments=[];let lastCategoryViewElement=null;function appendLegendRow(legendElement,swatchClass,label,tooltip){let rowElement=legendElement.appendChild(document.createElement("div"));rowElement.classList.add("row");let swatchElement=rowElement.appendChild(document.createElement("div"));swatchElement.classList.add("swatch",swatchClass);let valueContainer=rowElement.appendChild(document.createElement("div"));valueContainer.classList.add("value");let labelElement=valueContainer.appendChild(document.createElement("div"));labelElement.classList.add("label");labelElement.textContent=label;let sizeElement=valueContainer.appendChild(document.createElement("div"));sizeElement.classList.add("size");if(tooltip)
rowElement.title=tooltip;return sizeElement;}
for(let{type}of record.categories){segments.push(type);let categoryView=new WI.MemoryCategoryView(type,WI.MemoryTimelineView.displayNameForCategory(type));this._categoryViews.push(categoryView);this.addSubview(categoryView);if(!lastCategoryViewElement)
this._detailsContainerElement.appendChild(categoryView.element);else
this._detailsContainerElement.insertBefore(categoryView.element,lastCategoryViewElement);lastCategoryViewElement=categoryView.element;let sizeElement=appendLegendRow.call(this,this._usageLegendElement,type,WI.MemoryTimelineView.displayNameForCategory(type));this._usageLegendSizeElementMap.set(type,sizeElement);}
this._usageCircleChart.segments=segments;this._maxComparisonCircleChart.segments=["current","remainder"];this._maxComparisonMaximumSizeElement=appendLegendRow.call(this,this._maxComparisonLegendElement,"remainder",WI.UIString("Maximum"),WI.UIString("Maximum maximum memory size in this recording"));this._maxComparisonCurrentSizeElement=appendLegendRow.call(this,this._maxComparisonLegendElement,"current",WI.UIString("Current"),WI.UIString("Total memory size at the end of the selected time range"));}
_memoryTimelineRecordAdded(event)
{let memoryTimelineRecord=event.data.record;this._processRecord(memoryTimelineRecord);if(memoryTimelineRecord.startTime>=this.startTime&&memoryTimelineRecord.endTime<=this.endTime)
this.needsLayout();}
_processRecord(memoryTimelineRecord)
{if(!this._didInitializeCategories)
this._initializeCategoryViews(memoryTimelineRecord);this._maxSize=Math.max(this._maxSize,memoryTimelineRecord.totalSize);}};WI.MultipleScopeBarItem=class MultipleScopeBarItem extends WI.Object
{constructor(scopeBarItems)
{super();this._element=document.createElement("li");this._element.classList.add("multiple");this._titleElement=document.createElement("span");this._element.appendChild(this._titleElement);this._element.addEventListener("mousedown",this._handleMouseDown.bind(this));this._selectElement=document.createElement("select");this._selectElement.addEventListener("change",this._selectElementSelectionChanged.bind(this));this._element.appendChild(this._selectElement);this._element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/UpDownArrows.svg","arrows"));this.scopeBarItems=scopeBarItems;} 
get element()
{return this._element;}
get exclusive()
{return false;}
get scopeBarItems()
{return this._scopeBarItems;}
set scopeBarItems(scopeBarItems)
{if(this._scopeBarItems){for(var scopeBarItem of this._scopeBarItems){scopeBarItem.removeEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);scopeBarItem.removeEventListener(WI.ScopeBarItem.Event.HiddenChanged,this._handleItemHiddenChanged,this);}}
this._scopeBarItems=scopeBarItems||[];this._visibleScopeBarItems=[];this._selectedScopeBarItem=null;this._selectElement.removeChildren();function createOption(scopeBarItem)
{var optionElement=document.createElement("option");var maxPopupMenuLength=130; optionElement.textContent=scopeBarItem.label.length<=maxPopupMenuLength?scopeBarItem.label:scopeBarItem.label.substring(0,maxPopupMenuLength)+ellipsis;return optionElement;}
for(let scopeBarItem of this._scopeBarItems){scopeBarItem.addEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);scopeBarItem.addEventListener(WI.ScopeBarItem.Event.HiddenChanged,this._handleItemHiddenChanged,this);if(scopeBarItem.hidden)
continue;if(scopeBarItem.selected&&!this._selectedScopeBarItem)
this._selectedScopeBarItem=scopeBarItem;else if(scopeBarItem.selected){scopeBarItem.selected=false;}
this._visibleScopeBarItems.push(scopeBarItem);this._selectElement.appendChild(createOption(scopeBarItem));}
this._lastSelectedScopeBarItem=this._selectedScopeBarItem||this._scopeBarItems[0]||null;this._titleElement.textContent=this._lastSelectedScopeBarItem?this._lastSelectedScopeBarItem.label:"";this._element.classList.toggle("selected",!!this._selectedScopeBarItem);this._selectElement.selectedIndex=this._scopeBarItems.indexOf(this._selectedScopeBarItem);}
get selected()
{return!!this._selectedScopeBarItem;}
set selected(selected)
{this.selectedScopeBarItem=selected?this._lastSelectedScopeBarItem:null;}
get selectedScopeBarItem()
{return this._selectedScopeBarItem;}
set selectedScopeBarItem(selectedScopeBarItem)
{this._ignoreItemSelectedEvent=true;if(this._selectedScopeBarItem){this._selectedScopeBarItem.selected=false;this._lastSelectedScopeBarItem=this._selectedScopeBarItem;}else if(!this._lastSelectedScopeBarItem)
this._lastSelectedScopeBarItem=selectedScopeBarItem;this._element.classList.toggle("selected",!!selectedScopeBarItem);this._selectedScopeBarItem=selectedScopeBarItem||null;let selectedIndex=this._visibleScopeBarItems.indexOf(this._selectedScopeBarItem);if(selectedIndex<0)
selectedIndex=0;this._selectElement.selectedIndex=selectedIndex;if(this._selectedScopeBarItem){this.displaySelectedItem();this._selectedScopeBarItem.selected=true;}
this.dispatchEventToListeners(WI.ScopeBarItem.Event.SelectionChanged,{extendSelection:WI.modifierKeys.metaKey&&!WI.modifierKeys.ctrlKey&&!WI.modifierKeys.altKey&&!WI.modifierKeys.shiftKey,});this._ignoreItemSelectedEvent=false;}
displaySelectedItem()
{this._titleElement.textContent=(this._selectedScopeBarItem||this._scopeBarItems[0]).label;}
displayWidestItem()
{let widestLabel=null;let widestSize=0;for(let option of Array.from(this._selectElement.options)){this._titleElement.textContent=option.label;if(this._titleElement.realOffsetWidth>widestSize){widestSize=this._titleElement.realOffsetWidth;widestLabel=option.label;}}
this._titleElement.textContent=widestLabel;} 
_handleMouseDown(event)
{if(event.button!==0)
return;if(event.__original)
return;if(this._element.classList.contains("selected")){let newEvent=new event.constructor(event.type,event);newEvent.__original=event;event.stop();this._selectElement.dispatchEvent(newEvent);return;}
this.selected=true;}
_selectElementSelectionChanged(event)
{this.selectedScopeBarItem=this._visibleScopeBarItems[this._selectElement.selectedIndex];}
_itemSelectionDidChange(event)
{if(this._ignoreItemSelectedEvent)
return;let scopeBarItem=event.target;if(scopeBarItem.hidden)
return;this.selectedScopeBarItem=scopeBarItem.selected?scopeBarItem:null;}
_handleItemHiddenChanged(event)
{this.scopeBarItems=this._scopeBarItems;}};WI.MultiSidebar=class MultiSidebar extends WI.Sidebar
{constructor(element,side,label)
{super(element,side,label);this.element.classList.add("multi-sidebar");this._sidebars=[];this._allowMultipleSidebars=false;this._multipleSidebarsVisible=false;this._ignoringSidebarCollapsedStateDidChangeEvents=false;this.addSidebar(new WI.SingleSidebar(null,this.side,label,true));this.primarySidebar.collapsed=false;this._requiredMinimumWidthForMultipleSidebars=0;window.addEventListener("resize",this._handleWindowResize.bind(this));} 
get sidebars(){return this._sidebars;}
get primarySidebar()
{return this._sidebars[0];}
get allowMultipleSidebars()
{return this._allowMultipleSidebars;}
set allowMultipleSidebars(allow)
{if(allow===this._allowMultipleSidebars)
return;this._allowMultipleSidebars=!!allow;this._updateMultipleSidebarLayout();}
get multipleSidebarsVisible()
{return this._multipleSidebarsVisible;}
set multipleSidebarsVisible(visible)
{if(visible===this._multipleSidebarsVisible)
return;this._multipleSidebarsVisible=!!visible;this.element.classList.toggle("showing-multiple",this._multipleSidebarsVisible);this._updateMultipleSidebarLayout();this.dispatchEventToListeners(WI.MultiSidebar.Event.MultipleSidebarsVisibleChanged);}
addSidebar(sidebar)
{if(!(sidebar instanceof WI.Sidebar))
return;this._addSidebarEventListeners(sidebar);this._sidebars.push(sidebar);this.addSubview(sidebar);this.dispatchEventToListeners(WI.MultiSidebar.Event.SidebarAdded,{sidebar});}
removeSidebar(sidebar)
{if(!(sidebar instanceof WI.Sidebar))
return;if(sidebar===this.primarySidebar)
return;this._removeSidebarEventListeners(sidebar);this._sidebars.remove(sidebar);this.removeSubview(sidebar);}
get selectedSidebarPanel()
{return this.primarySidebar.selectedSidebarPanel;}
set selectedSidebarPanel(sidebarPanelOrIdentifierOrIndex)
{this.primarySidebar.selectedSidebarPanel=sidebarPanelOrIdentifierOrIndex;}
get collapsable()
{return super.collapsable;}
set collapsable(allow)
{super.collapsable=allow;this.primarySidebar.collapsable=this.collapsable;}
get minimumWidth()
{let minimumWidth=0;for(let sidebar of this.sidebars)
minimumWidth+=sidebar.minimumWidth;return minimumWidth;}
get width()
{return this.element.offsetWidth;} 
didInsertSidebarPanel(sidebarPanel,index)
{this._updateMinimumWidthForMultipleSidebars({ignoreExistingComputedValue:true});this._updateMultipleSidebarLayout();}
didRemoveSidebarPanel(sidebarPanel)
{let sidebar=this._findSidebarForSidebarPanel(sidebarPanel);if(sidebar){sidebar.removeSidebarPanel(sidebarPanel);if(sidebar!==this.primarySidebar)
this.removeSidebar(sidebar);}
this._updateMinimumWidthForMultipleSidebars({ignoreExistingComputedValue:true});this._updateMultipleSidebarLayout();}
didSetCollapsed()
{this.primarySidebar.collapsed=this.collapsed;this._updateMinimumWidthForMultipleSidebars({ignoreExistingComputedValue:true});this._updateMultipleSidebarLayout();} 
get _canShowMultipleSidebars()
{return this._allowMultipleSidebars&&this._multipleSidebarsVisible&&this._hasSidebarPanelSupportingExclusive&&this.sidebarPanels.length>=2;}
_updateMinimumWidthForMultipleSidebars({ignoreExistingComputedValue}={})
{if(!ignoreExistingComputedValue&&this._requiredMinimumWidthForMultipleSidebars)
return;if(this.collapsed||!this.isAttached)
return;

const minimumWidthEasement=50;let requiredMinimumWidth=this.primarySidebar.minimumWidth+minimumWidthEasement;for(let sidebarPanel of this.sidebarPanels){if(sidebarPanel.allowExclusivePresentation)
requiredMinimumWidth+=Math.max(WI.Sidebar.AbsoluteMinimumWidth,sidebarPanel.minimumWidth);}
this._requiredMinimumWidthForMultipleSidebars=requiredMinimumWidth;this.multipleSidebarsVisible=this._hasWidthForMultipleSidebars;}
get _hasWidthForMultipleSidebars()
{this._updateMinimumWidthForMultipleSidebars();return this._requiredMinimumWidthForMultipleSidebars<this.maximumWidth;}
get _hasSidebarPanelSupportingExclusive()
{return this.sidebarPanels.some((sidebarPanel)=>sidebarPanel.allowExclusivePresentation);}
_updateMultipleSidebarLayout()
{for(let sidebarPanel of this.sidebarPanels){let sidebar=this._findSidebarForSidebarPanel(sidebarPanel);if(this._canSidebarPanelBeExclusive(sidebarPanel)&&(sidebar===this.primarySidebar||!sidebar))
this._makeSidebarPanelExclusive(sidebarPanel);else if(!this._canSidebarPanelBeExclusive(sidebarPanel)&&sidebar!==this.primarySidebar)
this._makeSidebarPanelNotExclusive(sidebarPanel);}
this.primarySidebar.allowResizingToCollapse=this.sidebars.length<=1;}
_canSidebarPanelBeExclusive(sidebarPanel)
{return sidebarPanel.allowExclusivePresentation&&this._canShowMultipleSidebars;}
_makeSidebarPanelExclusive(sidebarPanel)
{let existingSidebar=this._findSidebarForSidebarPanel(sidebarPanel);if(existingSidebar===this.primarySidebar)
existingSidebar.removeSidebarPanel(sidebarPanel);sidebarPanel.exclusive=true;let sidebar=new WI.SingleSidebar(null,this.side,sidebarPanel.navigationItem.label);sidebar.collapsable=false;sidebar.addSidebarPanel(sidebarPanel);sidebar.selectedSidebarPanel=sidebarPanel;this.addSidebar(sidebar);}
_makeSidebarPanelNotExclusive(sidebarPanel)
{let existingSidebar=this._findSidebarForSidebarPanel(sidebarPanel);if(existingSidebar&&existingSidebar!==this.primarySidebar){existingSidebar.removeSidebarPanel(sidebarPanel);sidebarPanel.exclusive=false;this.removeSidebar(existingSidebar);}
this.primarySidebar.insertSidebarPanel(sidebarPanel,this._nonExclusiveIndexOfSidebarPanel(sidebarPanel));}
_nonExclusiveIndexOfSidebarPanel(sidebarPanel)
{let index=this._sidebarPanels.indexOf(sidebarPanel);if(this.multipleSidebarsVisible){for(let i=index-1;i>=0;i--){if(this._canSidebarPanelBeExclusive(this._sidebarPanels[i]))
index--;}}
return index;}
_findSidebarForSidebarPanel(sidebarPanel)
{if(sidebarPanel.parentSidebar)
return sidebarPanel.parentSidebar;return this._sidebars.find((sidebar)=>sidebar.sidebarPanels.includes(sidebarPanel))||null;}
_addSidebarEventListeners(sidebar)
{sidebar.addEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._handleSidebarPanelSelected,this);sidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);sidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarWidthDidChange,this);}
_removeSidebarEventListeners(sidebar)
{sidebar.removeEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._handleSidebarPanelSelected,this);sidebar.removeEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);sidebar.removeEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarWidthDidChange,this);}
_handleSidebarPanelSelected(event)
{if(event.target===this.primarySidebar)
this.dispatchEventToListeners(WI.Sidebar.Event.SidebarPanelSelected);}
_handleSidebarCollapsedStateDidChange(event)
{if(event.target===this.primarySidebar)
this.collapsed=event.target.collapsed;}
_handleSidebarWidthDidChange(event)
{this.dispatchEventToListeners(WI.Sidebar.Event.WidthDidChange,{sidebar:event.target,newWidth:event.data.newWidth});}
_handleWindowResize(event)
{if(!this.collapsed&&this.allowMultipleSidebars)
this.multipleSidebarsVisible=this._hasWidthForMultipleSidebars;}};WI.MultiSidebar.Event={MultipleSidebarsVisibleChanged:"multi-sidebar-multiple-sidebars-visible-changed",SidebarAdded:"multi-sidebar-sidebar-added",};WI.NavigationBar=class NavigationBar extends WI.View
{constructor(element,{role,sizesToFit,navigationItems}={})
{super(element);this.element.classList.add(this.constructor.StyleClassName||"navigation-bar");if(role)
this.element.setAttribute("role",role);this.element.addEventListener("keydown",this._keyDown.bind(this),false);this.element.addEventListener("mousedown",this._mouseDown.bind(this),true);this._role=role;this._sizesToFit=sizesToFit||false;this._minimumWidth=NaN;this._navigationItems=[];this._selectedNavigationItem=null;this._mouseMovedEventListener=this._mouseMoved.bind(this);this._mouseUpEventListener=this._mouseUp.bind(this);if(navigationItems){for(var i=0;i<navigationItems.length;++i)
this.addNavigationItem(navigationItems[i]);}} 
get sizesToFit(){return this._sizesToFit;}
addNavigationItem(navigationItem,parentElement)
{return this.insertNavigationItem(navigationItem,Infinity,parentElement);}
insertNavigationItem(navigationItem,index,parentElement)
{if(!(navigationItem instanceof WI.NavigationItem))
return null;if(navigationItem.parentNavigationBar)
navigationItem.parentNavigationBar.removeNavigationItem(navigationItem);navigationItem.didAttach(this);index=Math.max(0,Math.min(index,this._navigationItems.length));this._navigationItems.splice(index,0,navigationItem);if(!parentElement)
parentElement=this.element;var nextSibling=this._navigationItems[index+1];var nextSiblingElement=nextSibling?nextSibling.element:null;if(nextSiblingElement&&nextSiblingElement.parentNode!==parentElement)
nextSiblingElement=null;parentElement.insertBefore(navigationItem.element,nextSiblingElement);this._minimumWidth=NaN;this.needsLayout();return navigationItem;}
removeNavigationItem(navigationItem)
{if(!(navigationItem instanceof WI.NavigationItem))
return null;if(!navigationItem._parentNavigationBar)
return null;if(navigationItem._parentNavigationBar!==this)
return null;navigationItem.didDetach();if(this._selectedNavigationItem===navigationItem)
this.selectedNavigationItem=null;this._navigationItems.remove(navigationItem);navigationItem.element.remove();this._minimumWidth=NaN;this.needsLayout();return navigationItem;}
get selectedNavigationItem()
{return this._selectedNavigationItem;}
set selectedNavigationItem(navigationItem)
{let navigationItemHasOtherParent=navigationItem&&navigationItem.parentNavigationBar!==this;if(navigationItemHasOtherParent)
return;if(!(navigationItem instanceof WI.RadioButtonNavigationItem))
navigationItem=null;if(this._selectedNavigationItem===navigationItem)
return;if(this._selectedNavigationItem)
this._selectedNavigationItem.selected=false;this._selectedNavigationItem=navigationItem||null;if(this._selectedNavigationItem)
this._selectedNavigationItem.selected=true;if(!this._mouseIsDown)
this.dispatchEventToListeners(WI.NavigationBar.Event.NavigationItemSelected);}
get navigationItems()
{return this._navigationItems;}
get minimumWidth()
{if(isNaN(this._minimumWidth))
this._minimumWidth=this._calculateMinimumWidth();return this._minimumWidth;}
findNavigationItem(identifier)
{function matchingSelfOrChild(item){if(item.identifier===identifier)
return item;if(item instanceof WI.GroupNavigationItem){for(let childItem of item.navigationItems){let result=matchingSelfOrChild(childItem);if(result)
return result;}}
return null;}
for(let item of this._navigationItems){let result=matchingSelfOrChild(item);if(result)
return result;}
return null;}
layout()
{super.layout();this._minimumWidth=NaN;this.element.classList.remove(WI.NavigationBar.CollapsedStyleClassName);function forceItemHidden(item,hidden){item[WI.NavigationBar.ForceHiddenSymbol]=hidden;item.element.classList.toggle("force-hidden",hidden);}
function isDivider(item){return item instanceof WI.DividerNavigationItem;}
for(let item of this._navigationItems){forceItemHidden(item,false);item.update({expandOnly:true});}
if(this.sizesToFit)
return;let visibleNavigationItems=this._visibleNavigationItems;function calculateVisibleItemWidth(){return visibleNavigationItems.reduce((total,item)=>total+item.width,0);}
let totalItemWidth=calculateVisibleItemWidth();const barWidth=this.element.realOffsetWidth;if(totalItemWidth>barWidth)
this.element.classList.add(WI.NavigationBar.CollapsedStyleClassName);for(let item of visibleNavigationItems)
item.update();totalItemWidth=calculateVisibleItemWidth();if(totalItemWidth>barWidth){if(this.parentView instanceof WI.Sidebar){this.parentView.width=this.minimumWidth;return;}

visibleNavigationItems.sort((a,b)=>a.visibilityPriority-b.visibilityPriority);while(totalItemWidth>barWidth&&visibleNavigationItems.length){let navigationItem=visibleNavigationItems.shift();totalItemWidth-=navigationItem.width;forceItemHidden(navigationItem,true);}
visibleNavigationItems=this._visibleNavigationItems;}
let previousItem=null;for(let item of visibleNavigationItems){if(isDivider(item)&&(!previousItem||isDivider(previousItem))){forceItemHidden(item);continue;}
previousItem=item;}
if(isDivider(previousItem))
forceItemHidden(previousItem);} 
_mouseDown(event)
{if(event.button!==0)
return;var itemElement=event.target.closest("."+WI.RadioButtonNavigationItem.StyleClassName);if(!itemElement||!itemElement.navigationItem)
return;if(this._role==="tablist"){if(this.element.contains(document.activeElement)){event.stopPropagation();}}
this._previousSelectedNavigationItem=this.selectedNavigationItem;this.selectedNavigationItem=itemElement.navigationItem;this._mouseIsDown=true;if(typeof this.selectedNavigationItem.dontPreventDefaultOnNavigationBarMouseDown==="function"&&this.selectedNavigationItem.dontPreventDefaultOnNavigationBarMouseDown()&&this._previousSelectedNavigationItem===this.selectedNavigationItem)
return;document.addEventListener("mousemove",this._mouseMovedEventListener,false);document.addEventListener("mouseup",this._mouseUpEventListener,false);}
_mouseMoved(event)
{if(!this._mouseIsDown)
return;event.preventDefault();event.stopPropagation();var itemElement=event.target.closest("."+WI.RadioButtonNavigationItem.StyleClassName);if(!itemElement||!itemElement.navigationItem||!this.element.contains(itemElement)){
var element=document.elementFromPoint(event.pageX,this.element.totalOffsetTop+(this.element.offsetHeight/2));if(!element)
return;itemElement=element.closest("."+WI.RadioButtonNavigationItem.StyleClassName);if(!itemElement||!itemElement.navigationItem||!this.element.contains(itemElement))
return;}
if(this.selectedNavigationItem)
this.selectedNavigationItem.active=false;this.selectedNavigationItem=itemElement.navigationItem;this.selectedNavigationItem.active=true;}
_mouseUp(event)
{if(!this._mouseIsDown)
return;if(this.selectedNavigationItem)
this.selectedNavigationItem.active=false;this._mouseIsDown=false;document.removeEventListener("mousemove",this._mouseMovedEventListener,false);document.removeEventListener("mouseup",this._mouseUpEventListener,false);
if(this._previousSelectedNavigationItem!==this.selectedNavigationItem)
this.dispatchEventToListeners(WI.NavigationBar.Event.NavigationItemSelected);delete this._previousSelectedNavigationItem;event.preventDefault();event.stopPropagation();}
_keyDown(event)
{let isLeftArrow=event.code==="ArrowLeft";if(!isLeftArrow&&event.code!=="ArrowRight")
return;if(this._selectedNavigationItem?.element!==document.activeElement)
return;event.preventDefault();event.stopPropagation();let delta=isLeftArrow?-1:1;if(WI.resolveLayoutDirectionForElement(this._element)===WI.LayoutDirection.RTL)
delta*=-1;let selectedIndex=this._navigationItems.indexOf(this._selectedNavigationItem);if(selectedIndex===-1)
selectedIndex=(this._navigationItems.length+delta)%this._navigationItems.length;while(true){selectedIndex+=delta;if(selectedIndex<0||selectedIndex>=this._navigationItems.length)
break;let selectedItemCandidate=this._navigationItems[selectedIndex];if(selectedItemCandidate instanceof WI.RadioButtonNavigationItem){this.selectedNavigationItem=selectedItemCandidate;this.selectedNavigationItem.element.focus();break;}}}
_calculateMinimumWidth()
{let visibleNavigationItems=this._visibleNavigationItems;if(!visibleNavigationItems.length)
return 0;const wasCollapsed=this.element.classList.contains(WI.NavigationBar.CollapsedStyleClassName);if(!wasCollapsed)
this.element.classList.add(WI.NavigationBar.CollapsedStyleClassName);let totalItemWidth=visibleNavigationItems.reduce((total,item)=>total+Math.ceil(item.minimumWidth),0);if(!wasCollapsed)
this.element.classList.remove(WI.NavigationBar.CollapsedStyleClassName);return totalItemWidth;}
get _visibleNavigationItems()
{return this._navigationItems.filter((item)=>{if(item instanceof WI.FlexibleSpaceNavigationItem)
return false;if(item.hidden||item[WI.NavigationBar.ForceHiddenSymbol])
return false;return true;});}};WI.NavigationBar.ForceHiddenSymbol=Symbol("force-hidden");WI.NavigationBar.CollapsedStyleClassName="collapsed";WI.NavigationBar.Event={NavigationItemSelected:"navigation-bar-navigation-item-selected"};WI.NetworkDOMNodeDetailView=class NetworkDOMNodeDetailView extends WI.NetworkDetailView
{constructor(domNode,delegate)
{super(domNode,delegate);this.element.classList.add("dom-node");this._domEventsContentView=null;} 
initialLayout()
{this.createDetailNavigationItem("dom-events",WI.UIString("DOM Events"));super.initialLayout();} 
showContentViewForIdentifier(identifier)
{super.showContentViewForIdentifier(identifier);switch(identifier){case"dom-events":if(!this._domEventsContentView){this._domEventsContentView=new WI.DOMNodeEventsContentView(this.representedObject);}
this._contentBrowser.showContentView(this._domEventsContentView,this._contentViewCookie);break;}}};WI.NetworkResourceDetailView=class NetworkResourceDetailView extends WI.NetworkDetailView
{constructor(resource,delegate)
{super(resource,delegate);this.element.classList.add("resource");this._resourceContentView=null;this._headersContentView=null;this._cookiesContentView=null;this._sizesContentView=null;this._timingContentView=null;this._securityContentView=null;} 
attached()
{super.attached();if(this._contentBrowser&&this._contentViewCookie&&"lineNumber"in this._contentViewCookie&&"columnNumber"in this._contentViewCookie)
this._contentBrowser.navigationBar.selectedNavigationItem=this.detailNavigationItemForIdentifier("preview");} 
headersContentViewGoToRequestData(headersContentView)
{this._contentBrowser.navigationBar.selectedNavigationItem=this.detailNavigationItemForIdentifier("preview");this._resourceContentView.showRequest();} 
sizesContentViewGoToHeaders(metricsContentView)
{this._contentBrowser.navigationBar.selectedNavigationItem=this.detailNavigationItemForIdentifier("headers");}
sizesContentViewGoToRequestBody(metricsContentView)
{this._contentBrowser.navigationBar.selectedNavigationItem=this.detailNavigationItemForIdentifier("preview");this._resourceContentView.showRequest();}
sizesContentViewGoToResponseBody(metricsContentView)
{this._contentBrowser.navigationBar.selectedNavigationItem=this.detailNavigationItemForIdentifier("preview");this._resourceContentView.showResponse();} 
initialLayout()
{this.createDetailNavigationItem("preview",WI.UIString("Preview"));this.createDetailNavigationItem("headers",WI.UIString("Headers"));this.createDetailNavigationItem("cookies",WI.UIString("Cookies"));this.createDetailNavigationItem("sizes",WI.UIString("Sizes"));this.createDetailNavigationItem("timing",WI.UIString("Timing"));this.createDetailNavigationItem("security",WI.UIString("Security"));super.initialLayout();} 
showContentViewForIdentifier(identifier)
{super.showContentViewForIdentifier(identifier);if(this._contentViewCookie&&"lineNumber"in this._contentViewCookie&&"columnNumber"in this._contentViewCookie)
identifier="preview";switch(identifier){case"preview":if(!this._resourceContentView)
this._resourceContentView=this._contentBrowser.showContentViewForRepresentedObject(this.representedObject);this._contentBrowser.showContentView(this._resourceContentView,this._contentViewCookie);break;case"headers":if(!this._headersContentView)
this._headersContentView=new WI.ResourceHeadersContentView(this.representedObject,this);this._contentBrowser.showContentView(this._headersContentView,this._contentViewCookie);break;case"cookies":if(!this._cookiesContentView)
this._cookiesContentView=new WI.ResourceCookiesContentView(this.representedObject);this._contentBrowser.showContentView(this._cookiesContentView,this._contentViewCookie);break;case"sizes":if(!this._sizesContentView)
this._sizesContentView=new WI.ResourceSizesContentView(this.representedObject,this);this._contentBrowser.showContentView(this._sizesContentView,this._contentViewCookie);break;case"timing":if(!this._timingContentView)
this._timingContentView=new WI.ResourceTimingContentView(this.representedObject);this._contentBrowser.showContentView(this._timingContentView,this._contentViewCookie);break;case"security":if(!this._securityContentView)
this._securityContentView=new WI.ResourceSecurityContentView(this.representedObject);this._contentBrowser.showContentView(this._securityContentView,this._contentViewCookie);break;}
this._contentViewCookie=null;}};WI.NetworkTableContentView=class NetworkTableContentView extends WI.ContentView
{constructor(representedObject,extraArguments)
{super(representedObject);this._collections=[];this._activeCollection=null;this._mainCollection=this._addCollection();this._setActiveCollection(this._mainCollection);this._entriesSortComparator=null;this._showingRepresentedObjectCookie=null;this._table=null;this._nameColumnWidthSetting=new WI.Setting("network-table-content-view-name-column-width",250);this._selectedObject=null;this._detailView=null;this._detailViewMap=new Map;this._domNodeEntries=new Map;this._waterfallTimelineRuler=null;this._waterfallPopover=null;this._statistics={};this.element.classList.add("network-table");this._typeFilterScopeBarItemAll=new WI.ScopeBarItem("network-type-filter-all",WI.UIString("All"),{exclusive:true});let typeFilterScopeBarItems=[this._typeFilterScopeBarItemAll];function addScopeBarItem(id,label,checker){let scopeBarItem=new WI.ScopeBarItem("network-type-filter-"+id,label);scopeBarItem.__checker=checker;typeFilterScopeBarItems.push(scopeBarItem);}
addScopeBarItem("document",WI.UIString("Document"),(type)=>type===WI.Resource.Type.Document);addScopeBarItem("styleSheet",WI.unlocalizedString("CSS"),(type)=>type===WI.Resource.Type.StyleSheet);addScopeBarItem("image",WI.UIString("Image"),(type)=>type===WI.Resource.Type.Image);addScopeBarItem("font",WI.UIString("Font"),(type)=>type===WI.Resource.Type.Font);addScopeBarItem("script",WI.unlocalizedString("JS"),(type)=>type===WI.Resource.Type.Script);addScopeBarItem("xhr-fetch",WI.UIString("%s/Fetch","%s/Fetch @ Network Tab Table Filter","Scope bar button that filter for dynamic resource loads, like from the 'fetch' method.").format(WI.unlocalizedString("XHR")),(type)=>type===WI.Resource.Type.XHR||type===WI.Resource.Type.Fetch);addScopeBarItem("other",WI.UIString("Other"),(type)=>{return type!==WI.Resource.Type.Document&&type!==WI.Resource.Type.StyleSheet&&type!==WI.Resource.Type.Image&&type!==WI.Resource.Type.Font&&type!==WI.Resource.Type.Script&&type!==WI.Resource.Type.XHR&&type!==WI.Resource.Type.Fetch;});this._typeFilterScopeBar=new WI.ScopeBar("network-type-filter-scope-bar",typeFilterScopeBarItems,typeFilterScopeBarItems[0]);this._typeFilterScopeBar.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._typeFilterScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._typeFilterScopeBarSelectionChanged,this);if(WI.MediaInstrument.supported()){this._groupMediaRequestsByDOMNodeNavigationItem=new WI.CheckboxNavigationItem("group-media-requests",WI.UIString("Group Media Requests"),WI.settings.groupMediaRequestsByDOMNode.value);this._groupMediaRequestsByDOMNodeNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._groupMediaRequestsByDOMNodeNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,this._handleGroupMediaRequestsByDOMNodeCheckedDidChange,this);}else
WI.settings.groupMediaRequestsByDOMNode.value=false;this._urlFilterSearchText=null;this._urlFilterSearchRegex=null;this._urlFilterIsActive=false;this._urlFilterNavigationItem=new WI.FilterBarNavigationItem;this._urlFilterNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._urlFilterNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._urlFilterDidChange,this);this._urlFilterNavigationItem.filterBar.placeholder=WI.UIString("Filter Full URL");this._activeTypeFilters=this._generateTypeFilter();this._activeURLFilterResources=new Set;this._emptyFilterResultsMessageElement=null;this._clearOnLoadNavigationItem=new WI.CheckboxNavigationItem("preserve-log",WI.UIString("Preserve Log"),!WI.settings.clearNetworkOnNavigate.value);this._clearOnLoadNavigationItem.tooltip=WI.UIString("Do not clear network items on new page loads");this._clearOnLoadNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,function(event){WI.settings.clearNetworkOnNavigate.value=!WI.settings.clearNetworkOnNavigate.value;},this);WI.settings.clearNetworkOnNavigate.addEventListener(WI.Setting.Event.Changed,this._clearNetworkOnNavigateSettingChanged,this);this._harImportNavigationItem=new WI.ButtonNavigationItem("har-import",WI.UIString("Import"),"Images/Import.svg",15,15);this._harImportNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._harImportNavigationItem.tooltip=WI.UIString("HAR Import");this._harImportNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){this._importHAR();},this);this._harExportNavigationItem=new WI.ButtonNavigationItem("har-export",WI.UIString("Export"),"Images/Export.svg",15,15);this._harExportNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._harExportNavigationItem.tooltip=WI.UIString("HAR Export (%s)").format(WI.saveKeyboardShortcut.displayName);this._harExportNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){this._exportHAR();},this);this._collectionsPathNavigationItem=new WI.HierarchicalPathNavigationItem;this._collectionsPathNavigationItem.addEventListener(WI.HierarchicalPathNavigationItem.Event.PathComponentWasSelected,this._collectionsHierarchicalPathComponentWasSelected,this);this._pathComponentsMap=new Map;this._lastPathComponent=null;let pathComponent=this._addCollectionPathComponent(this._mainCollection,WI.UIString("Live Activity"),"network-overview-icon");this._collectionsPathNavigationItem.components=[pathComponent];this._checkboxesNavigationItemGroup=new WI.GroupNavigationItem([this._clearOnLoadNavigationItem,new WI.DividerNavigationItem]);this._pathComponentsNavigationItemGroup=new WI.GroupNavigationItem([this._collectionsPathNavigationItem,new WI.DividerNavigationItem]);this._pathComponentsNavigationItemGroup.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._pathComponentsNavigationItemGroup.hidden=true;this._buttonsNavigationItemGroup=new WI.GroupNavigationItem([this._harImportNavigationItem,this._harExportNavigationItem,new WI.DividerNavigationItem]);this._buttonsNavigationItemGroup.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;if(InspectorBackend.hasCommand("Network.setResourceCachingDisabled")){let toolTipForDisableResourceCache=WI.UIString("Ignore the resource cache when loading resources");let activatedToolTipForDisableResourceCache=WI.UIString("Use the resource cache when loading resources");this._disableResourceCacheNavigationItem=new WI.ActivateButtonNavigationItem("disable-resource-cache",toolTipForDisableResourceCache,activatedToolTipForDisableResourceCache,"Images/IgnoreCaches.svg",16,16);this._disableResourceCacheNavigationItem.activated=WI.settings.resourceCachingDisabled.value;this._disableResourceCacheNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._disableResourceCacheNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleDisableResourceCache,this);WI.settings.resourceCachingDisabled.addEventListener(WI.Setting.Event.Changed,this._resourceCachingDisabledSettingChanged,this);}
this._clearNetworkItemsNavigationItem=new WI.ButtonNavigationItem("clear-network-items",WI.UIString("Clear Network Items (%s)").format(WI.clearKeyboardShortcut.displayName),"Images/NavigationItemTrash.svg",15,15);this._clearNetworkItemsNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){this.reset();},this);WI.Target.addEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Frame.addEventListener(WI.Frame.Event.ChildFrameWasAdded,this._handleFrameWasAdded,this);WI.Resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this._resourceLoadingDidFinish,this);WI.Resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._resourceLoadingDidFail,this);WI.Resource.addEventListener(WI.Resource.Event.SizeDidChange,this._handleResourceSizeDidChange,this);WI.Resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);this._needsInitialPopulate=true;

this._transitioningPageTarget=false;WI.notifications.addEventListener(WI.Notification.TransitionPageTarget,this._transitionPageTarget,this);} 
static displayNameForResource(resource)
{if(resource.type===WI.Resource.Type.Image||resource.type===WI.Resource.Type.Font||resource.type===WI.Resource.Type.Other){let fileExtension;if(resource.mimeType)
fileExtension=WI.fileExtensionForMIMEType(resource.mimeType);if(!fileExtension)
fileExtension=WI.fileExtensionForURL(resource.url);if(fileExtension)
return fileExtension;}
switch(resource.type){case WI.Resource.Type.Document:return WI.UIString("document","document @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for document resources.");case WI.Resource.Type.StyleSheet:return WI.unlocalizedString("css");case WI.Resource.Type.Image:return WI.UIString("image","image @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for image resources.");case WI.Resource.Type.Font:return WI.UIString("font","font @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for font resources.");case WI.Resource.Type.Script:return WI.unlocalizedString("js");case WI.Resource.Type.XHR:return WI.unlocalizedString("xhr");case WI.Resource.Type.Fetch:return WI.UIString("fetch","fetch @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for resources loaded via the 'fetch' method.");case WI.Resource.Type.Ping:return WI.UIString("ping","ping @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for resources loaded via '<a ping>' elements.");case WI.Resource.Type.Beacon:return WI.UIString("beacon","beacon @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for resources loaded via the Beacon API.");case WI.Resource.Type.WebSocket:return WI.UIString("socket","socket @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for WebSocket resources.");case WI.Resource.Type.Other:return WI.UIString("other","other @ Network Tab Resource Type Column Value","Shown in the 'Type' column of the Network Table for resources that don't fall into any of the other known types/categories.");}
return"";}
static get nodeWaterfallDOMEventSize(){return 8;} 
get selectionPathComponents()
{return null;}
get navigationItems()
{let items=[this._checkboxesNavigationItemGroup,this._pathComponentsNavigationItemGroup,this._buttonsNavigationItemGroup];if(this._disableResourceCacheNavigationItem)
items.push(this._disableResourceCacheNavigationItem);items.push(this._clearNetworkItemsNavigationItem);return items;}
get filterNavigationItems()
{let navigationItems=[this._urlFilterNavigationItem,this._typeFilterScopeBar];if(WI.MediaInstrument.supported())
navigationItems.push(this._groupMediaRequestsByDOMNodeNavigationItem);return navigationItems;}
get supportsSave()
{return this._canExportHAR();}
get saveData()
{return{customSaveHandler:()=>{this._exportHAR();}};}
detached()
{this._hidePopover();super.detached();}
closed()
{for(let detailView of this._detailViewMap.values())
detailView.dispose();this._detailViewMap.clear();this._domNodeEntries.clear();this._hidePopover();this._hideDetailView();WI.settings.clearNetworkOnNavigate.removeEventListener(WI.Setting.Event.Changed,this._clearNetworkOnNavigateSettingChanged,this);if(InspectorBackend.hasCommand("Network.setResourceCachingDisabled"))
WI.settings.resourceCachingDisabled.removeEventListener(WI.Setting.Event.Changed,this._resourceCachingDisabledSettingChanged,this);WI.Target.removeEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Frame.removeEventListener(WI.Frame.Event.ChildFrameWasAdded,this._handleFrameWasAdded,this);WI.Resource.removeEventListener(WI.Resource.Event.LoadingDidFinish,this._resourceLoadingDidFinish,this);WI.Resource.removeEventListener(WI.Resource.Event.LoadingDidFail,this._resourceLoadingDidFail,this);WI.Resource.removeEventListener(WI.Resource.Event.SizeDidChange,this._handleResourceSizeDidChange,this);WI.Resource.removeEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);super.closed();}
reset()
{this._runForMainCollection((collection,wasMain)=>{this._resetCollection(collection);if(wasMain)
this._updateStatistics();});for(let detailView of this._detailViewMap.values())
detailView.dispose();this._detailViewMap.clear();this._domNodeEntries.clear();this._updateWaterfallTimelineRuler();this._updateExportButton();if(this._table){this._selectedObject=null;this._table.reloadData();this._hidePopover();this._hideDetailView();}}
showRepresentedObject(representedObject,cookie)
{let rowIndex=this._rowIndexForRepresentedObject(representedObject);if(rowIndex===-1){this._selectedObject=null;this._table.deselectAll();this._hideDetailView();return;}
this._showingRepresentedObjectCookie=cookie;this._table.selectRow(rowIndex);this._showingRepresentedObjectCookie=null;}
get canFocusFilterBar()
{return!this._detailView;}
focusFilterBar()
{this._urlFilterNavigationItem.filterBar.focus();} 
networkDetailViewClose(networkDetailView)
{this._selectedObject=null;this._table.deselectAll();this._hideDetailView();} 
tableIndexForRepresentedObject(table,object)
{return this._activeCollection.filteredEntries.indexOf(object);}
tableRepresentedObjectForIndex(table,index)
{return this._activeCollection.filteredEntries[index];}
tableNumberOfRows(table)
{return this._activeCollection.filteredEntries.length;}
tableSortChanged(table)
{this._generateSortComparator();if(!this._entriesSortComparator)
return;this._hideDetailView();for(let nodeEntry of this._domNodeEntries.values())
nodeEntry.initiatedResourceEntries.sort(this._entriesSortComparator);this._updateSort();this._updateFilteredEntries();this._reloadTable();} 
tableCellContextMenuClicked(table,cell,column,rowIndex,event)
{if(column!==this._nameColumn)
return;this._table.selectRow(rowIndex);let entry=this._activeCollection.filteredEntries[rowIndex];let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForSourceCode(contextMenu,entry.resource);contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Export HAR"),()=>{this._exportHAR();},!this._canExportHAR());}
tableShouldSelectRow(table,cell,column,rowIndex)
{return column===this._nameColumn;}
tableSelectionDidChange(table)
{let rowIndex=table.selectedRow;if(isNaN(rowIndex)){this._selectedObject=null;this._hideDetailView();return;}
let entry=this._activeCollection.filteredEntries[rowIndex];if(entry.resource===this._selectedObject||entry.domNode===this._selectedObject)
return;this._selectedObject=entry.resource||entry.domNode;if(this._selectedObject)
this._showDetailView(this._selectedObject);else
this._hideDetailView();}
tablePopulateCell(table,cell,column,rowIndex)
{let entry=this._activeCollection.filteredEntries[rowIndex];cell.classList.toggle("current-session",entry.currentSession);if(entry.resource)
cell.classList.toggle("error",entry.resource.hadLoadingError());let setTextContent=(accessor)=>{let uniqueValues=this._uniqueValuesForDOMNodeEntry(entry,accessor);if(uniqueValues){if(uniqueValues.size>1){cell.classList.add("multiple");cell.textContent=WI.UIString("(multiple)");return;}
cell.textContent=uniqueValues.values().next().value||emDash;return;}
cell.textContent=accessor(entry)||emDash;};switch(column.identifier){case"name":this._populateNameCell(cell,entry);break;case"domain":this._populateDomainCell(cell,entry);break;case"type":setTextContent((resourceEntry)=>resourceEntry.displayType);break;case"mimeType":setTextContent((resourceEntry)=>resourceEntry.mimeType);break;case"method":setTextContent((resourceEntry)=>resourceEntry.method);break;case"scheme":setTextContent((resourceEntry)=>resourceEntry.scheme);break;case"status":setTextContent((resourceEntry)=>resourceEntry.status);break;case"protocol":setTextContent((resourceEntry)=>resourceEntry.protocol);break;case"initiator":this._populateInitiatorCell(cell,entry);break;case"priority":setTextContent((resourceEntry)=>WI.Resource.displayNameForPriority(resourceEntry.priority));break;case"remoteAddress":setTextContent((resourceEntry)=>resourceEntry.remoteAddress);break;case"connectionIdentifier":setTextContent((resourceEntry)=>resourceEntry.connectionIdentifier);break;case"resourceSize":{let resourceSize=entry.resourceSize;let resourceEntries=entry.initiatedResourceEntries;if(resourceEntries)
resourceSize=resourceEntries.reduce((accumulator,current)=>accumulator+(current.resourceSize||0),0);cell.textContent=isNaN(resourceSize)?emDash:Number.bytesToString(resourceSize);break;}
case"transferSize":this._populateTransferSizeCell(cell,entry);break;case"time":{let time=entry.time;let resourceEntries=entry.initiatedResourceEntries;if(resourceEntries)
time=resourceEntries.reduce((accumulator,current)=>accumulator+(current.time||0),0);cell.textContent=isNaN(time)?emDash:Number.secondsToString(Math.max(time,0));break;}
case"waterfall":this._populateWaterfallGraph(cell,entry);break;}
return cell;} 
_addCollection()
{let collection={};this._resetCollection(collection);this._collections.push(collection);return collection;}
_resetCollection(collection)
{collection.entries=[];collection.filteredEntries=[];collection.pendingInsertions=[];collection.pendingUpdates=[];collection.waterfallStartTime=NaN;collection.waterfallEndTime=NaN;}
_setActiveCollection(collection)
{if(this._activeCollection===collection)
return;this._activeCollection=collection;}
_addCollectionPathComponent(collection,displayName,iconClassName)
{let pathComponent=new WI.HierarchicalPathComponent(displayName,iconClassName,collection);this._pathComponentsMap.set(collection,pathComponent);if(this._lastPathComponent){this._lastPathComponent.nextSibling=pathComponent;pathComponent.previousSibling=this._lastPathComponent;}
this._lastPathComponent=pathComponent;if(this._pathComponentsNavigationItemGroup&&this._pathComponentsMap.size>1)
this._pathComponentsNavigationItemGroup.hidden=false;return pathComponent;}
_collectionsHierarchicalPathComponentWasSelected(event)
{let collection=event.data.pathComponent.representedObject;this._changeCollection(collection);}
_changeCollection(collection)
{if(collection===this._activeCollection)
return;this._setActiveCollection(collection);let isMain=collection===this._mainCollection;this._checkboxesNavigationItemGroup.hidden=!isMain;this._groupMediaRequestsByDOMNodeNavigationItem.hidden=!isMain;this._clearNetworkItemsNavigationItem.enabled=isMain;this._collectionsPathNavigationItem.components=[this._pathComponentsMap.get(collection)];this._updateSort();this._updateActiveFilterResources();this._updateFilteredEntries();this._updateWaterfallTimelineRuler();this._reloadTable();this._updateStatistics();this._hideDetailView();this.needsLayout();}
_populateNameCell(cell,entry)
{function createIconElement(){let iconElement=cell.appendChild(document.createElement("img"));iconElement.className="icon";return iconElement;}
let domNode=entry.domNode;if(domNode){this._table.element.classList.add("grouped");cell.classList.add("parent");let disclosureElement=cell.appendChild(document.createElement("img"));disclosureElement.classList.add("disclosure");disclosureElement.classList.toggle("expanded",!!entry.expanded);disclosureElement.addEventListener("click",(event)=>{entry.expanded=!entry.expanded;this._updateFilteredEntries();this._reloadTable();});createIconElement();cell.classList.add("dom-node");cell.appendChild(WI.linkifyNodeReference(domNode));return;}
let resource=entry.resource;if(resource.isLoading()){let statusElement=cell.appendChild(document.createElement("div"));statusElement.className="status";let spinner=new WI.IndeterminateProgressSpinner;statusElement.appendChild(spinner.element);}
let resourceIconElement=createIconElement();cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(resource));if(WI.settings.groupMediaRequestsByDOMNode.value&&resource.initiatorNode){let nodeEntry=this._domNodeEntries.get(resource.initiatorNode);if(nodeEntry.initiatedResourceEntries.length>1||nodeEntry.domNode.domEvents.length)
cell.classList.add("child");}
let nameElement=cell.appendChild(document.createElement("span"));nameElement.textContent=entry.name;let range=resource.requestedByteRange;if(range){let rangeElement=nameElement.appendChild(document.createElement("span"));rangeElement.classList.add("range");rangeElement.textContent=WI.UIString("Byte Range %s\u2013%s").format(range.start,range.end);}
cell.title=resource.url;if(resource.responseSource===WI.Resource.ResponseSource.InspectorOverride)
resourceIconElement.title=WI.UIString("This resource was loaded from a local override");}
_populateDomainCell(cell,entry)
{function createIconAndText(scheme,domain){let secure=scheme==="https"||scheme==="wss";if(secure){let lockIconElement=cell.appendChild(document.createElement("img"));lockIconElement.className="lock";}
cell.append(domain||emDash);}
let uniqueSchemeValues=this._uniqueValuesForDOMNodeEntry(entry,(resourceEntry)=>resourceEntry.scheme);let uniqueDomainValues=this._uniqueValuesForDOMNodeEntry(entry,(resourceEntry)=>resourceEntry.domain);if(uniqueSchemeValues&&uniqueDomainValues){if(uniqueSchemeValues.size>1||uniqueDomainValues.size>1){cell.classList.add("multiple");cell.textContent=WI.UIString("(multiple)");return;}
createIconAndText(uniqueSchemeValues.values().next().value,uniqueDomainValues.values().next().value);return;}
createIconAndText(entry.scheme,entry.domain);}
_populateInitiatorCell(cell,entry)
{let domNode=entry.domNode;if(domNode){cell.textContent=emDash;return;}
let initiatorLocation=entry.resource.initiatorSourceCodeLocation;if(!initiatorLocation){cell.textContent=emDash;return;}
const options={dontFloat:true,ignoreSearchTab:true,};cell.appendChild(WI.createSourceCodeLocationLink(initiatorLocation,options));}
_populateTransferSizeCell(cell,entry)
{let resourceEntries=entry.initiatedResourceEntries;if(resourceEntries){if(resourceEntries.every((resourceEntry)=>resourceEntry.resource.responseSource===WI.Resource.ResponseSource.MemoryCache)){cell.classList.add("cache-type");cell.textContent=WI.UIString("(memory)");cell.title=WI.UIString("This resource was loaded from the memory cache");return;}
if(resourceEntries.every((resourceEntry)=>resourceEntry.resource.responseSource===WI.Resource.ResponseSource.DiskCache)){cell.classList.add("cache-type");cell.textContent=WI.UIString("(disk)");cell.title=WI.UIString("This resource was loaded from the disk cache");return;}
if(resourceEntries.every((resourceEntry)=>resourceEntry.resource.responseSource===WI.Resource.ResponseSource.ServiceWorker)){cell.classList.add("cache-type");cell.textContent=WI.UIString("(service worker)");cell.title=WI.UIString("This resource was loaded from a service worker");return;}
let transferSize=resourceEntries.reduce((accumulator,current)=>accumulator+(current.transferSize||0),0);cell.textContent=isNaN(transferSize)?emDash:Number.bytesToString(transferSize);cell.title="";return;}
let responseSource=entry.resource.responseSource;if(responseSource===WI.Resource.ResponseSource.MemoryCache){cell.classList.add("cache-type");cell.textContent=WI.UIString("(memory)");cell.title=WI.UIString("This resource was loaded from the memory cache");return;}
if(responseSource===WI.Resource.ResponseSource.DiskCache){cell.classList.add("cache-type");cell.textContent=WI.UIString("(disk)");cell.title=WI.UIString("This resource was loaded from the disk cache");return;}
if(responseSource===WI.Resource.ResponseSource.ServiceWorker){cell.classList.add("cache-type");cell.textContent=WI.UIString("(service worker)");cell.title=WI.UIString("This resource was loaded from a service worker");return;}
if(responseSource===WI.Resource.ResponseSource.InspectorOverride){cell.classList.add("cache-type");cell.textContent=WI.UIString("(local override)");cell.title=WI.UIString("This resource was loaded from a local override");return;}
let transferSize=entry.transferSize;cell.textContent=isNaN(transferSize)?emDash:Number.bytesToString(transferSize);cell.title="";}
_populateWaterfallGraph(cell,entry)
{cell.classList.add("network");cell.removeChildren();let container=cell.appendChild(document.createElement("div"));container.className="waterfall-container";let collection=this._activeCollection;let graphStartTime=this._waterfallTimelineRuler.startTime;let secondsPerPixel=this._waterfallTimelineRuler.secondsPerPixel;function positionByStartOffset(element,timestamp){let styleAttribute=WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR?"left":"right";element.style.setProperty(styleAttribute,((timestamp-graphStartTime)/secondsPerPixel)+"px");}
function setWidthForDuration(element,startTimestamp,endTimestamp){element.style.setProperty("width",((endTimestamp-startTimestamp)/secondsPerPixel)+"px");}
let domNode=entry.domNode;if(domNode){let groupedDOMEvents=[];for(let domEvent of domNode.domEvents){if(domEvent.originator)
continue;if(!groupedDOMEvents.length||(domEvent.timestamp-groupedDOMEvents.lastValue.endTimestamp)>=(NetworkTableContentView.nodeWaterfallDOMEventSize*secondsPerPixel)){groupedDOMEvents.push({startTimestamp:domEvent.timestamp,domEvents:[],});}
groupedDOMEvents.lastValue.endTimestamp=domEvent.timestamp;groupedDOMEvents.lastValue.domEvents.push(domEvent);}
let fullscreenDOMEvents=WI.DOMNode.getFullscreenDOMEvents(domNode.domEvents);if(fullscreenDOMEvents.length){if(!fullscreenDOMEvents[0].data.enabled)
fullscreenDOMEvents.unshift({timestamp:graphStartTime});if(fullscreenDOMEvents.lastValue.data.enabled)
fullscreenDOMEvents.push({timestamp:collection.waterfallEndTime});for(let i=0;i<fullscreenDOMEvents.length;i+=2){let fullscreenElement=container.appendChild(document.createElement("div"));fullscreenElement.classList.add("area","dom-fullscreen");positionByStartOffset(fullscreenElement,fullscreenDOMEvents[i].timestamp);setWidthForDuration(fullscreenElement,fullscreenDOMEvents[i].timestamp,fullscreenDOMEvents[i+1].timestamp);let originator=fullscreenDOMEvents[i].originator||fullscreenDOMEvents[i+1].originator;if(originator)
fullscreenElement.title=WI.UIString("Full-Screen from \u201C%s\u201D").format(originator.displayName);else
fullscreenElement.title=WI.UIString("Full-Screen");}}
for(let powerEfficientPlaybackRange of domNode.powerEfficientPlaybackRanges){let startTimestamp=powerEfficientPlaybackRange.startTimestamp||graphStartTime;let endTimestamp=powerEfficientPlaybackRange.endTimestamp||collection.waterfallEndTime;let powerEfficientPlaybackRangeElement=container.appendChild(document.createElement("div"));powerEfficientPlaybackRangeElement.classList.add("area","power-efficient-playback");powerEfficientPlaybackRangeElement.title=WI.UIString("Power Efficient Playback");positionByStartOffset(powerEfficientPlaybackRangeElement,startTimestamp);setWidthForDuration(powerEfficientPlaybackRangeElement,startTimestamp,endTimestamp);}
let playing=false;function createDOMEventLine(domEvents,startTimestamp,endTimestamp){if(WI.DOMNode.isStopEvent(domEvents.lastValue.eventName))
return;for(let i=domEvents.length-1;i>=0;--i){let domEvent=domEvents[i];if(WI.DOMNode.isPlayEvent(domEvent.eventName)){playing=true;break;}
if(WI.DOMNode.isPauseEvent(domEvent.eventName)){playing=false;break;}}
let lineElement=container.appendChild(document.createElement("div"));lineElement.classList.add("dom-activity");lineElement.classList.toggle("playing",playing);positionByStartOffset(lineElement,startTimestamp);setWidthForDuration(lineElement,startTimestamp,endTimestamp);}
for(let[a,b]of groupedDOMEvents.adjacencies())
createDOMEventLine(a.domEvents,a.endTimestamp,b.startTimestamp);if(groupedDOMEvents.length)
createDOMEventLine(groupedDOMEvents.lastValue.domEvents,groupedDOMEvents.lastValue.endTimestamp,collection.waterfallEndTime);for(let{startTimestamp,endTimestamp,domEvents}of groupedDOMEvents){let paddingForCentering=NetworkTableContentView.nodeWaterfallDOMEventSize*secondsPerPixel/2;let eventElement=container.appendChild(document.createElement("div"));eventElement.classList.add("dom-event");positionByStartOffset(eventElement,startTimestamp-paddingForCentering);setWidthForDuration(eventElement,startTimestamp,endTimestamp+paddingForCentering);eventElement.addEventListener("mousedown",(event)=>{if(event.button!==0||event.ctrlKey)
return;this._handleNodeEntryMousedownWaterfall(entry,domEvents);});for(let domEvent of domEvents)
entry.domEventElements.set(domEvent,eventElement);}
return;}
let resource=entry.resource;if(!resource.hasResponse()){cell.textContent=zeroWidthSpace;return;}
let{startTime,redirectStart,redirectEnd,fetchStart,domainLookupStart,domainLookupEnd,connectStart,connectEnd,secureConnectionStart,requestStart,responseStart,responseEnd}=resource.timingData;if(isNaN(startTime)||isNaN(responseEnd)||startTime>responseEnd){cell.textContent=zeroWidthSpace;return;}
if(responseEnd<graphStartTime){cell.textContent=zeroWidthSpace;return;}
let graphEndTime=this._waterfallTimelineRuler.endTime;if(startTime>graphEndTime){cell.textContent=zeroWidthSpace;return;}
let lastEndTimestamp=NaN;function appendBlock(startTimestamp,endTimestamp,className){if(isNaN(startTimestamp)||isNaN(endTimestamp))
return null;if(Math.abs(startTimestamp-lastEndTimestamp)<secondsPerPixel*2)
startTimestamp=lastEndTimestamp;lastEndTimestamp=endTimestamp;let block=container.appendChild(document.createElement("div"));block.classList.add("block",className);positionByStartOffset(block,startTimestamp);setWidthForDuration(block,startTimestamp,endTimestamp);return block;}
let padSeconds=10*secondsPerPixel;let mouseBlock=appendBlock(startTime-padSeconds,responseEnd+padSeconds,"mouse-tracking");mouseBlock.addEventListener("mousedown",(event)=>{if(event.button!==0||event.ctrlKey)
return;this._handleResourceEntryMousedownWaterfall(entry);});let totalWidth=(responseEnd-startTime)/secondsPerPixel;if(totalWidth<=3){let twoPixels=secondsPerPixel*2;appendBlock(startTime,startTime+twoPixels,"queue");appendBlock(startTime+twoPixels,startTime+(2*twoPixels),"response");return;}
appendBlock(startTime,responseEnd,"filler"); appendBlock(redirectStart,redirectEnd,"redirect");if(domainLookupStart){appendBlock(fetchStart,domainLookupStart,"queue");appendBlock(domainLookupStart,domainLookupEnd||connectStart||requestStart,"dns");}else if(connectStart)
appendBlock(fetchStart,connectStart,"queue");else if(requestStart)
appendBlock(fetchStart,requestStart,"queue");if(connectStart)
appendBlock(connectStart,secureConnectionStart||connectEnd,"connect");if(secureConnectionStart)
appendBlock(secureConnectionStart,connectEnd,"secure");appendBlock(requestStart,responseStart,"request");appendBlock(responseStart,responseEnd,"response");}
_generateSortComparator()
{let sortColumnIdentifier=this._table.sortColumnIdentifier;if(!sortColumnIdentifier){this._entriesSortComparator=null;return;}
let comparator;switch(sortColumnIdentifier){case"name":case"domain":case"mimeType":case"method":case"scheme":case"protocol":case"initiator":case"remoteAddress":comparator=(a,b)=>(a[sortColumnIdentifier]||"").extendedLocaleCompare(b[sortColumnIdentifier]||"");break;case"status":case"connectionIdentifier":case"resourceSize":case"time":comparator=(a,b)=>{let aValue=a[sortColumnIdentifier];let bValue=b[sortColumnIdentifier];if(isNaN(aValue)&&isNaN(bValue))
return 0;if(isNaN(aValue))
return 1;if(isNaN(bValue))
return-1;return aValue-bValue;};break;case"priority":comparator=(a,b)=>WI.Resource.comparePriority(a.priority,b.priority);break;case"type":comparator=(a,b)=>(a.displayType||"").extendedLocaleCompare(b.displayType||"");break;case"transferSize":comparator=(a,b)=>{let transferSizeA=a.transferSize;let transferSizeB=b.transferSize;if(isNaN(transferSizeA)&&isNaN(transferSizeB))
return 0;if(isNaN(transferSizeA))
return 1;if(isNaN(transferSizeB))
return-1;let sourceA=a.resource.responseSource;if(sourceA===WI.Resource.ResponseSource.MemoryCache)
transferSizeA=-20;else if(sourceA===WI.Resource.ResponseSource.DiskCache)
transferSizeA=-10;else if(sourceA===WI.Resource.ResponseSource.ServiceWorker)
transferSizeA=-5;else if(sourceA===WI.Resource.ResponseSource.InspectorOverride)
transferSizeA=-3;let sourceB=b.resource.responseSource;if(sourceB===WI.Resource.ResponseSource.MemoryCache)
transferSizeB=-20;else if(sourceB===WI.Resource.ResponseSource.DiskCache)
transferSizeB=-10;else if(sourceB===WI.Resource.ResponseSource.ServiceWorker)
transferSizeB=-5;else if(sourceB===WI.Resource.ResponseSource.InspectorOverride)
transferSizeB=-3;return transferSizeA-transferSizeB;};break;case"waterfall":comparator=(a,b)=>a.startTime-b.startTime;break;default:return;}
let reverseFactor=this._table.sortOrder===WI.Table.SortOrder.Ascending?1:-1;

let substitute=(entry,other)=>{if(WI.settings.groupMediaRequestsByDOMNode.value&&entry.resource.initiatorNode){let nodeEntry=this._domNodeEntries.get(entry.resource.initiatorNode);if(!nodeEntry.initiatedResourceEntries.includes(other))
return nodeEntry.initiatedResourceEntries[0];}
return entry;};this._entriesSortComparator=(a,b)=>reverseFactor*comparator(substitute(a,b),substitute(b,a));} 
initialLayout()
{super.initialLayout();this.element.style.setProperty("--node-waterfall-dom-event-size",NetworkTableContentView.nodeWaterfallDOMEventSize+"px");this._waterfallTimelineRuler=new WI.TimelineRuler;this._waterfallTimelineRuler.allowsClippedLabels=true;this._nameColumn=new WI.TableColumn("name",WI.UIString("Name"),{minWidth:WI.Sidebar.AbsoluteMinimumWidth,maxWidth:500,initialWidth:this._nameColumnWidthSetting.value,resizeType:WI.TableColumn.ResizeType.Locked,});this._domainColumn=new WI.TableColumn("domain",WI.UIString("Domain"),{minWidth:120,maxWidth:200,initialWidth:150,});this._typeColumn=new WI.TableColumn("type",WI.UIString("Type"),{minWidth:70,maxWidth:120,initialWidth:90,});this._mimeTypeColumn=new WI.TableColumn("mimeType",WI.UIString("MIME Type"),{hidden:true,minWidth:100,maxWidth:150,initialWidth:120,});this._methodColumn=new WI.TableColumn("method",WI.UIString("Method"),{hidden:true,minWidth:55,maxWidth:80,initialWidth:65,});this._schemeColumn=new WI.TableColumn("scheme",WI.UIString("Scheme"),{hidden:true,minWidth:55,maxWidth:80,initialWidth:65,});this._statusColumn=new WI.TableColumn("status",WI.UIString("Status"),{hidden:true,minWidth:50,maxWidth:50,align:"left",});this._protocolColumn=new WI.TableColumn("protocol",WI.UIString("Protocol"),{hidden:true,minWidth:65,maxWidth:80,initialWidth:75,});this._initiatorColumn=new WI.TableColumn("initiator",WI.UIString("Initiator"),{hidden:true,minWidth:75,maxWidth:175,initialWidth:125,});this._priorityColumn=new WI.TableColumn("priority",WI.UIString("Priority"),{hidden:true,minWidth:65,maxWidth:80,initialWidth:70,});this._remoteAddressColumn=new WI.TableColumn("remoteAddress",WI.UIString("IP Address"),{hidden:true,minWidth:150,});this._connectionIdentifierColumn=new WI.TableColumn("connectionIdentifier",WI.UIString("Connection ID"),{hidden:true,minWidth:50,maxWidth:120,initialWidth:80,align:"right",});this._resourceSizeColumn=new WI.TableColumn("resourceSize",WI.UIString("Resource Size"),{hidden:true,minWidth:80,maxWidth:100,initialWidth:80,align:"right",});this._transferSizeColumn=new WI.TableColumn("transferSize",WI.UIString("Transfer Size","Amount of data sent over the network for a single resource"),{minWidth:100,maxWidth:150,initialWidth:100,align:"right",});this._timeColumn=new WI.TableColumn("time",WI.UIString("Time"),{minWidth:65,maxWidth:90,initialWidth:65,align:"right",});this._waterfallColumn=new WI.TableColumn("waterfall",WI.UIString("Waterfall"),{minWidth:230,headerView:this._waterfallTimelineRuler,needsReloadOnResize:true,});this._nameColumn.addEventListener(WI.TableColumn.Event.WidthDidChange,this._tableNameColumnDidChangeWidth,this);this._waterfallColumn.addEventListener(WI.TableColumn.Event.WidthDidChange,this._tableWaterfallColumnDidChangeWidth,this);this._table=new WI.Table("network-table",this,this,20);this._table.addColumn(this._nameColumn);this._table.addColumn(this._domainColumn);this._table.addColumn(this._typeColumn);this._table.addColumn(this._mimeTypeColumn);this._table.addColumn(this._methodColumn);this._table.addColumn(this._schemeColumn);this._table.addColumn(this._statusColumn);this._table.addColumn(this._protocolColumn);this._table.addColumn(this._initiatorColumn);this._table.addColumn(this._priorityColumn);this._table.addColumn(this._remoteAddressColumn);this._table.addColumn(this._connectionIdentifierColumn);this._table.addColumn(this._resourceSizeColumn);this._table.addColumn(this._transferSizeColumn);this._table.addColumn(this._timeColumn);this._table.addColumn(this._waterfallColumn);if(!this._table.sortColumnIdentifier){this._table.sortOrder=WI.Table.SortOrder.Ascending;this._table.sortColumnIdentifier="waterfall";}
this.addSubview(this._table);let statisticsContainer=this.element.appendChild(document.createElement("div"));statisticsContainer.className="statistics";let createStatisticElement=(name,image)=>{let statistic=this._statistics[name];if(!statistic)
statistic=this._statistics[name]={};statistic.container=statisticsContainer.appendChild(document.createElement("div"));statistic.container.classList.add("statistic",name);statistic.container.appendChild(WI.ImageUtilities.useSVGSymbol(image,"icon"));statistic.element=statistic.container.appendChild(document.createElement("div"));statistic.element.className="text";};createStatisticElement("domain-count","Images/Origin.svg");createStatisticElement("resource-count","Images/Resources.svg");createStatisticElement("resource-size","Images/Weight.svg");createStatisticElement("transfer-size","Images/Network.svg");createStatisticElement("redirect-count","Images/StepOver.svg");createStatisticElement("load-time","Images/Time.svg");this._updateStatistics();}
layout()
{this._updateWaterfallTimelineRuler();this._processPendingEntries();this._positionDetailView();this._updateExportButton();}
didLayoutSubtree()
{super.didLayoutSubtree();if(this._waterfallPopover)
this._waterfallPopover.resize();}
processHAR(result)
{let resources=WI.networkManager.processHAR(result);if(!resources)
return;let importedCollection=this._addCollection();let displayName=WI.UIString("Imported - %s").format(result.filename);this._addCollectionPathComponent(importedCollection,displayName,"network-har-icon");this._changeCollection(importedCollection);for(let resource of resources)
this._insertResourceAndReloadTable(resource);this._updateStatistics();}
handleClearShortcut(event)
{if(!this._isShowingMainCollection())
return;this.reset();} 
_updateWaterfallTimeRange(startTimestamp,endTimestamp)
{let collection=this._activeCollection;if(isNaN(collection.waterfallStartTime)||startTimestamp<collection.waterfallStartTime)
collection.waterfallStartTime=startTimestamp;if(isNaN(collection.waterfallEndTime)||endTimestamp>collection.waterfallEndTime)
collection.waterfallEndTime=endTimestamp;}
_updateWaterfallTimelineRuler()
{if(!this._waterfallTimelineRuler)
return;let collection=this._activeCollection;if(isNaN(collection.waterfallStartTime)){this._waterfallTimelineRuler.zeroTime=0;this._waterfallTimelineRuler.startTime=0;this._waterfallTimelineRuler.endTime=0.250;}else{this._waterfallTimelineRuler.zeroTime=collection.waterfallStartTime;this._waterfallTimelineRuler.startTime=collection.waterfallStartTime;this._waterfallTimelineRuler.endTime=collection.waterfallEndTime;const paddingPixels=5;let padSeconds=paddingPixels*this._waterfallTimelineRuler.secondsPerPixel;this._waterfallTimelineRuler.zeroTime=collection.waterfallStartTime-padSeconds;this._waterfallTimelineRuler.startTime=collection.waterfallStartTime-padSeconds;this._waterfallTimelineRuler.endTime=collection.waterfallEndTime+padSeconds;}}
_canExportHAR()
{if(!this._isShowingMainCollection())
return false;let mainFrame=WI.networkManager.mainFrame;if(!mainFrame)
return false;let mainResource=mainFrame.mainResource;if(!mainResource)
return false;if(!mainResource.requestSentDate)
return false;if(!this._HARResources().length)
return false;return true;}
_updateExportButton()
{this._harExportNavigationItem.enabled=this._canExportHAR();}
_processPendingEntries()
{let collection=this._activeCollection;let needsSort=collection.pendingUpdates.length>0;if(!needsSort){let originalLength=collection.pendingInsertions.length;for(let resource of collection.pendingInsertions)
this._insertResourceAndReloadTable(resource);collection.pendingInsertions=[];this._updateStatistics();return;}
for(let resource of collection.pendingInsertions){let resourceEntry=this._entryForResource(resource);this._tryLinkResourceToDOMNode(resourceEntry);collection.entries.push(resourceEntry);}
collection.pendingInsertions=[];for(let updateObject of collection.pendingUpdates){if(updateObject instanceof WI.Resource)
this._updateEntryForResource(updateObject);}
collection.pendingUpdates=[];this._updateSort();this._updateFilteredEntries();this._reloadTable();this._updateStatistics();}
_populateWithInitialResourcesIfNeeded(collection)
{if(!this._needsInitialPopulate)
return;this._needsInitialPopulate=false;let populateResourcesForFrame=(frame)=>{if(frame.provisionalMainResource)
collection.pendingInsertions.push(frame.provisionalMainResource);else if(frame.mainResource)
collection.pendingInsertions.push(frame.mainResource);for(let resource of frame.resourceCollection)
collection.pendingInsertions.push(resource);for(let childFrame of frame.childFrameCollection)
populateResourcesForFrame(childFrame);};let populateResourcesForTarget=(target)=>{if(target.mainResource instanceof WI.Resource)
collection.pendingInsertions.push(target.mainResource);for(let resource of target.resourceCollection)
collection.pendingInsertions.push(resource);};for(let target of WI.targets){if(target===WI.pageTarget)
populateResourcesForFrame(WI.networkManager.mainFrame);else
populateResourcesForTarget(target);}
this.needsLayout();}
_checkURLFilterAgainstResource(resource)
{if(this._urlFilterSearchRegex.test(resource.url)){this._activeURLFilterResources.add(resource);return;}
for(let redirect of resource.redirects){if(this._urlFilterSearchRegex.test(redirect.url)){this._activeURLFilterResources.add(resource);return;}}}
_rowIndexForRepresentedObject(object)
{return this._activeCollection.filteredEntries.findIndex((x)=>{if(x.resource===object)
return true;if(x.domNode===object)
return true;return false;});}
_updateEntryForResource(resource)
{let collection=this._activeCollection;let index=collection.entries.findIndex((x)=>x.resource===resource);if(index===-1)
return;function updateExistingEntry(existingEntry,newEntry){for(let key in newEntry)
existingEntry[key]=newEntry[key];}
let entry=this._entryForResource(resource);updateExistingEntry(collection.entries[index],entry);let rowIndex=this._rowIndexForRepresentedObject(resource);if(rowIndex===-1)
return;updateExistingEntry(collection.filteredEntries[rowIndex],entry);this._updateStatistics();}
_hidePopover()
{if(this._waterfallPopover)
this._waterfallPopover.dismiss();}
_hideDetailView()
{if(!this._detailView)
return;this.element.classList.remove("showing-detail");this._table.scrollContainer.style.removeProperty("width");this.removeSubview(this._detailView);this._detailView=null;this._table.updateLayout(WI.View.LayoutReason.Resize);this._table.reloadVisibleColumnCells(this._waterfallColumn);}
_showDetailView(object)
{let oldDetailView=this._detailView;this._detailView=this._detailViewMap.get(object);if(this._detailView===oldDetailView)
return;if(!this._detailView){if(object instanceof WI.Resource)
this._detailView=new WI.NetworkResourceDetailView(object,this);else if(object instanceof WI.DOMNode){this._detailView=new WI.NetworkDOMNodeDetailView(object,this);}
this._detailViewMap.set(object,this._detailView);}
if(oldDetailView)
this.replaceSubview(oldDetailView,this._detailView);else
this.addSubview(this._detailView);if(this._showingRepresentedObjectCookie)
this._detailView.willShowWithCookie(this._showingRepresentedObjectCookie);this.element.classList.add("showing-detail");this._table.scrollContainer.style.width=this._nameColumn.width+"px";
this.updateLayout();}
_positionDetailView()
{if(!this._detailView)
return;let side=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._detailView.element.style[side]=this._nameColumn.width+"px";this._table.scrollContainer.style.width=this._nameColumn.width+"px";}
_updateEmptyFilterResultsMessage()
{if(this._hasActiveFilter()&&!this._activeCollection.filteredEntries.length)
this._showEmptyFilterResultsMessage();else
this._hideEmptyFilterResultsMessage();}
_showEmptyFilterResultsMessage()
{if(!this._emptyFilterResultsMessageElement){let buttonElement=document.createElement("button");buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",()=>{this._resetFilters();});this._emptyFilterResultsMessageElement=WI.createMessageTextView(WI.UIString("No Filter Results"));this._emptyFilterResultsMessageElement.appendChild(buttonElement);}
this.element.appendChild(this._emptyFilterResultsMessageElement);}
_hideEmptyFilterResultsMessage()
{if(!this._emptyFilterResultsMessageElement)
return;this._emptyFilterResultsMessageElement.remove();}
_clearNetworkOnNavigateSettingChanged()
{this._clearOnLoadNavigationItem.checked=!WI.settings.clearNetworkOnNavigate.value;}
_resourceCachingDisabledSettingChanged()
{this._disableResourceCacheNavigationItem.activated=WI.settings.resourceCachingDisabled.value;}
_toggleDisableResourceCache()
{WI.settings.resourceCachingDisabled.value=!WI.settings.resourceCachingDisabled.value;}
_mainResourceDidChange(event)
{let frame=event.target;if(frame.isMainFrame()&&!this._transitioningPageTarget)
this._startUpdatingLoadTimeStatistic();this._runForMainCollection((collection,wasMain)=>{if(frame.isMainFrame()){if(WI.settings.clearNetworkOnNavigate.value){this._resetCollection(collection);if(wasMain&&!this._needsInitialPopulate)
this._hideDetailView();}else{for(let entry of collection.entries)
entry.currentSession=false;}}
if(this._transitioningPageTarget){this._transitioningPageTarget=false;this._needsInitialPopulate=true;this._populateWithInitialResourcesIfNeeded(collection);}else
this._insertResourceAndReloadTable(frame.mainResource);if(wasMain)
this._updateStatistics();});}
_mainFrameDidChange()
{this._runForMainCollection((collection)=>{this._populateWithInitialResourcesIfNeeded(collection);});}
_resourceLoadingDidFinish(event)
{this._runForMainCollection((collection,wasMain)=>{let resource=event.target;collection.pendingUpdates.push(resource);this._updateWaterfallTimeRange(resource.firstTimestamp,resource.timingData.responseEnd);if(this._hasURLFilter())
this._checkURLFilterAgainstResource(resource);if(wasMain)
this.needsLayout();});}
_resourceLoadingDidFail(event)
{this._runForMainCollection((collection,wasMain)=>{let resource=event.target;collection.pendingUpdates.push(resource);this._updateWaterfallTimeRange(resource.firstTimestamp,resource.timingData.responseEnd);if(this._hasURLFilter())
this._checkURLFilterAgainstResource(resource);if(wasMain)
this.needsLayout();});}
_handleResourceSizeDidChange(event)
{if(!this._table)
return;this._runForMainCollection((collection,wasMain)=>{let resource=event.target;if(this._table.sortColumnIdentifier==="resourceSize"){collection.pendingUpdates.push(resource);this.needsLayout();return;}
let index=collection.entries.findIndex((x)=>x.resource===resource);if(index===-1)
return;let entry=collection.entries[index];entry.resourceSize=resource.size;if(!wasMain)
return;let rowIndex=this._rowIndexForRepresentedObject(resource);if(rowIndex===-1)
return;this._table.reloadCell(rowIndex,"resourceSize");this._updateStatistics();});}
_resourceTransferSizeDidChange(event)
{if(!this._table)
return;this._runForMainCollection((collection,wasMain)=>{let resource=event.target;if(this._table.sortColumnIdentifier==="transferSize"){collection.pendingUpdates.push(resource);this.needsLayout();return;}
let index=collection.entries.findIndex((x)=>x.resource===resource);if(index===-1)
return;let entry=collection.entries[index];entry.transferSize=!isNaN(resource.networkTotalTransferSize)?resource.networkTotalTransferSize:resource.estimatedTotalTransferSize;if(!wasMain)
return;let rowIndex=this._rowIndexForRepresentedObject(resource);if(rowIndex===-1)
return;this._table.reloadCell(rowIndex,"transferSize");this._updateStatistics();});}
_handleResourceAdded(event)
{this._runForMainCollection((collection,wasMain)=>{this._insertResourceAndReloadTable(event.data.resource);if(wasMain)
this._updateStatistics();});}
_handleFrameWasAdded(event)
{if(this._needsInitialPopulate)
return;this._runForMainCollection((collection,wasMain)=>{let frame=event.data.childFrame;let mainResource=frame.provisionalMainResource||frame.mainResource;this._insertResourceAndReloadTable(mainResource);if(wasMain)
this._updateStatistics();});}
_runForMainCollection(callback)
{let currentCollection=this._activeCollection;let wasMain=currentCollection===this._mainCollection;if(!wasMain)
this._setActiveCollection(this._mainCollection);callback(this._activeCollection,wasMain);if(!wasMain)
this._setActiveCollection(currentCollection);}
_isShowingMainCollection()
{return this._activeCollection===this._mainCollection;}
_isDefaultSort()
{return this._table.sortColumnIdentifier==="waterfall"&&this._table.sortOrder===WI.Table.SortOrder.Ascending;}
_insertResourceAndReloadTable(resource)
{if(this._needsInitialPopulate)
return;let collection=this._activeCollection;this._updateWaterfallTimeRange(resource.firstTimestamp,resource.timingData.responseEnd);if(!this._table||!(WI.tabBrowser.selectedTabContentView instanceof WI.NetworkTabContentView)){collection.pendingInsertions.push(resource);this.needsLayout();return;}
let resourceEntry=this._entryForResource(resource);this._tryLinkResourceToDOMNode(resourceEntry);if(WI.settings.groupMediaRequestsByDOMNode.value&&resource.initiatorNode){if(!this._entriesSortComparator)
this._generateSortComparator();}else if(this._isDefaultSort()||!this._entriesSortComparator){collection.entries.push(resourceEntry);if(this._passFilter(resourceEntry)){collection.filteredEntries.push(resourceEntry);this._table.reloadDataAddedToEndOnly();}
return;}
insertObjectIntoSortedArray(resourceEntry,collection.entries,this._entriesSortComparator);if(this._passFilter(resourceEntry)){if(WI.settings.groupMediaRequestsByDOMNode.value)
this._updateFilteredEntries();else
insertObjectIntoSortedArray(resourceEntry,collection.filteredEntries,this._entriesSortComparator);
if(collection.filteredEntries.lastValue===resourceEntry)
this._table.reloadDataAddedToEndOnly();else
this._reloadTable();}}
_entryForResource(resource)
{
 return{resource,name:WI.displayNameForURL(resource.url,resource.urlComponents),domain:WI.displayNameForHost(resource.urlComponents.host),scheme:resource.urlComponents.scheme?resource.urlComponents.scheme.toLowerCase():"",method:resource.requestMethod,type:resource.type,displayType:WI.NetworkTableContentView.displayNameForResource(resource),mimeType:resource.mimeType,status:resource.statusCode,cached:resource.cached,resourceSize:resource.size,transferSize:!isNaN(resource.networkTotalTransferSize)?resource.networkTotalTransferSize:resource.estimatedTotalTransferSize,time:resource.totalDuration,protocol:resource.protocol,initiator:resource.initiatorSourceCodeLocation?resource.initiatorSourceCodeLocation.displayLocationString():"",priority:resource.priority,remoteAddress:resource.remoteAddress,connectionIdentifier:resource.connectionIdentifier,startTime:resource.firstTimestamp,currentSession:true,};}
_entryForDOMNode(domNode)
{return{domNode,initiatedResourceEntries:[],domEventElements:new Map,expanded:true,};}
_tryLinkResourceToDOMNode(resourceEntry)
{let resource=resourceEntry.resource;if(!resource||!resource.initiatorNode)
return;let nodeEntry=this._domNodeEntries.get(resource.initiatorNode);if(!nodeEntry){nodeEntry=this._entryForDOMNode(resource.initiatorNode,Object.keys(resourceEntry));this._domNodeEntries.set(resource.initiatorNode,nodeEntry);resource.initiatorNode.addEventListener(WI.DOMNode.Event.DidFireEvent,this._handleNodeDidFireEvent,this);if(resource.initiatorNode.canEnterPowerEfficientPlaybackState())
resource.initiatorNode.addEventListener(WI.DOMNode.Event.PowerEfficientPlaybackStateChanged,this._handleDOMNodePowerEfficientPlaybackStateChanged,this);}
if(!this._entriesSortComparator)
this._generateSortComparator();insertObjectIntoSortedArray(resourceEntry,nodeEntry.initiatedResourceEntries,this._entriesSortComparator);}
_uniqueValuesForDOMNodeEntry(nodeEntry,accessor)
{let resourceEntries=nodeEntry.initiatedResourceEntries;if(!resourceEntries)
return null;return resourceEntries.reduce((accumulator,current)=>{let value=accessor(current);if(value||typeof value==="number")
accumulator.add(value);return accumulator;},new Set);}
_handleNodeDidFireEvent(event)
{this._runForMainCollection((collection,wasMain)=>{let domNode=event.target;let{domEvent}=event.data;collection.pendingUpdates.push(domNode);this._updateWaterfallTimeRange(NaN,domEvent.timestamp+(this._waterfallTimelineRuler.secondsPerPixel*10));if(wasMain)
this.needsLayout();});}
_handleDOMNodePowerEfficientPlaybackStateChanged(event)
{this._runForMainCollection((collection,wasMain)=>{let domNode=event.target;let{timestamp}=event.data;collection.pendingUpdates.push(domNode);this._updateWaterfallTimeRange(NaN,timestamp+(this._waterfallTimelineRuler.secondsPerPixel*10));if(wasMain)
this.needsLayout();});}
_hasTypeFilter()
{return!!this._activeTypeFilters;}
_hasURLFilter()
{return this._urlFilterIsActive;}
_hasActiveFilter()
{return this._hasTypeFilter()||this._hasURLFilter();}
_passTypeFilter(entry)
{if(!this._hasTypeFilter())
return true;return this._activeTypeFilters.some((checker)=>checker(entry.resource.type));}
_passURLFilter(entry)
{if(!this._hasURLFilter())
return true;return this._activeURLFilterResources.has(entry.resource);}
_passFilter(entry)
{return this._passTypeFilter(entry)&&this._passURLFilter(entry);}
_updateSort()
{if(this._entriesSortComparator){let collection=this._activeCollection;collection.entries=collection.entries.sort(this._entriesSortComparator);}}
_updateFilteredEntries()
{let collection=this._activeCollection;if(this._hasActiveFilter())
collection.filteredEntries=collection.entries.filter(this._passFilter,this);else
collection.filteredEntries=collection.entries.slice();if(WI.settings.groupMediaRequestsByDOMNode.value){for(let nodeEntry of this._domNodeEntries.values()){if(nodeEntry.initiatedResourceEntries.length<2&&!nodeEntry.domNode.domEvents.length)
continue;let firstIndex=Infinity;for(let resourceEntry of nodeEntry.initiatedResourceEntries){if(this._hasActiveFilter()&&!this._passFilter(resourceEntry))
continue;let index=collection.filteredEntries.indexOf(resourceEntry);if(index>=0&&index<firstIndex)
firstIndex=index;}
if(!isFinite(firstIndex))
continue;collection.filteredEntries.insertAtIndex(nodeEntry,firstIndex);}
collection.filteredEntries=collection.filteredEntries.filter((entry)=>{if(entry.resource&&entry.resource.initiatorNode){let nodeEntry=this._domNodeEntries.get(entry.resource.initiatorNode);if(!nodeEntry.expanded)
return false;}
return true;});}
this._updateStatistics();this._updateEmptyFilterResultsMessage();}
_updateStatistics()
{if(!this.didInitialLayout)
return;let entries=this._activeCollection.filteredEntries.filter((entry)=>entry.currentSession);let domains=new Set;let resourceSize=0;let transferSize=0;let redirectCount=0;for(let entry of entries){domains.add(entry.domain);if(!isNaN(entry.resourceSize))
resourceSize+=entry.resourceSize;if(!isNaN(entry.transferSize))
transferSize+=entry.transferSize;if(entry.resource)
redirectCount+=entry.resource.redirects.length;}
this._updateStatistic("domain-count",domains.size===1?WI.UIString("%d domain"):WI.UIString("%d domains"),domains.size);let resourceCount=entries.length;this._updateStatistic("resource-count",resourceCount===1?WI.UIString("%d resource"):WI.UIString("%d resources"),resourceCount);const higherResolution=false;this._updateStatistic("resource-size",WI.UIString("%s total"),Number.bytesToString(resourceSize,higherResolution));this._updateStatistic("transfer-size",WI.UIString("%s transferred"),Number.bytesToString(transferSize,higherResolution));this._updateStatistic("redirect-count",redirectCount===1?WI.UIString("%d redirect"):WI.UIString("%d redirects"),redirectCount);let loadTimeStatistic=this._statistics["load-time"];if(loadTimeStatistic.format&&this._isShowingMainCollection()&&!this._hasActiveFilter()){this._updateStatistic("load-time");loadTimeStatistic.container.hidden=false;}else
loadTimeStatistic.container.hidden=true;}
_updateStatistic(name,format,value)
{let statistic=this._statistics[name];if(format)
statistic.format=format;else
format=statistic.format;if(value||value===0)
statistic.value=value;else
value=statistic.value;if(statistic.container)
statistic.container.title=format.format(value);if(statistic.element)
statistic.element.textContent=value;}
_startUpdatingLoadTimeStatistic()
{this._stopUpdatingLoadTimeStatistic();let loadTimeStatistic=this._statistics["load-time"];if(!loadTimeStatistic)
loadTimeStatistic=this._statistics["load-time"]={};loadTimeStatistic.start=Date.now();loadTimeStatistic.delay=50;loadTimeStatistic.timer=setInterval(this._updateLoadTimeStatistic.bind(this),loadTimeStatistic.delay);}
_stopUpdatingLoadTimeStatistic()
{let loadTimeStatistic=this._statistics["load-time"];if(!loadTimeStatistic)
return;if(loadTimeStatistic.timer){clearInterval(loadTimeStatistic.timer);loadTimeStatistic.timer=undefined;}}
_updateLoadTimeStatistic()
{let loadTimeStatistic=this._statistics["load-time"];let duration=Date.now()-loadTimeStatistic.start;let delay=loadTimeStatistic.delay;if(duration>=1_000) 
delay=100;else if(duration>=60_000) 
delay=1_000;else if(duration>=3_600_000) 
delay=10_000;if(delay!==loadTimeStatistic.delay){loadTimeStatistic.delay=delay;clearInterval(loadTimeStatistic.timer);loadTimeStatistic.timer=setInterval(this._updateLoadTimeStatistic.bind(this),loadTimeStatistic.delay);}
let mainFrame=WI.networkManager.mainFrame;let mainFrameStartTime=mainFrame.mainResource.firstTimestamp;let mainFrameLoadEventTime=mainFrame.loadEventTimestamp;if(loadTimeStatistic.container)
loadTimeStatistic.container.hidden=!this._isShowingMainCollection()||this._hasActiveFilter();if(isNaN(mainFrameStartTime)||isNaN(mainFrameLoadEventTime)){this._updateStatistic("load-time",WI.UIString("Loading for %s"),Number.secondsToString(duration/1_000));return;}
this._updateStatistic("load-time",WI.UIString("Loaded in %s"),Number.secondsToString(mainFrameLoadEventTime-mainFrameStartTime));this._stopUpdatingLoadTimeStatistic();}
_reloadTable()
{this._table.reloadData();this._restoreSelectedRow();}
_generateTypeFilter()
{let selectedItems=this._typeFilterScopeBar.selectedItems;if(!selectedItems.length||selectedItems.includes(this._typeFilterScopeBarItemAll))
return null;return selectedItems.map((item)=>item.__checker);}
_resetFilters()
{this._urlFilterSearchText=null;this._urlFilterSearchRegex=null;this._urlFilterIsActive=false;this._activeURLFilterResources.clear();this._urlFilterNavigationItem.filterBar.clear();this._typeFilterScopeBar.resetToDefault();this._updateFilteredEntries();this._reloadTable();}
_areFilterListsIdentical(listA,listB)
{if(listA&&listB){if(listA.length!==listB.length)
return false;for(let i=0;i<listA.length;++i){if(listA[i]!==listB[i])
return false;}
return true;}
return false;}
_typeFilterScopeBarSelectionChanged(event)
{
let oldFilter=this._activeTypeFilters;let newFilter=this._generateTypeFilter();if(this._areFilterListsIdentical(oldFilter,newFilter))
return;this._hideDetailView();this._activeTypeFilters=newFilter;this._updateFilteredEntries();this._reloadTable();}
_handleGroupMediaRequestsByDOMNodeCheckedDidChange(event)
{WI.settings.groupMediaRequestsByDOMNode.value=this._groupMediaRequestsByDOMNodeNavigationItem.checked;if(!WI.settings.groupMediaRequestsByDOMNode.value){this._table.element.classList.remove("grouped");if(this._selectedObject&&this._selectedObject instanceof WI.DOMNode){this._selectedObject=null;this._hideDetailView();}}
this._updateSort();this._updateFilteredEntries();this._reloadTable();}
_urlFilterDidChange(event)
{let filterBar=this._urlFilterNavigationItem.filterBar;let searchQuery=filterBar.filters.text;if(searchQuery===this._urlFilterSearchText)
return;this._hideDetailView();this._urlFilterSearchRegex=searchQuery?WI.SearchUtilities.filterRegExpForString(searchQuery,WI.SearchUtilities.defaultSettings):null;filterBar.invalid=searchQuery&&!this._urlFilterSearchRegex

if(!this._urlFilterSearchRegex){this._urlFilterSearchText=null;this._urlFilterSearchRegex=null;this._urlFilterIsActive=false;this._activeURLFilterResources.clear();this._updateFilteredEntries();this._reloadTable();return;}
this._urlFilterIsActive=true;this._urlFilterSearchText=searchQuery;this._updateActiveFilterResources();this._updateFilteredEntries();this._reloadTable();}
_updateActiveFilterResources()
{this._activeURLFilterResources.clear();if(this._hasURLFilter()){for(let entry of this._activeCollection.entries)
this._checkURLFilterAgainstResource(entry.resource);}}
_restoreSelectedRow()
{if(!this._selectedObject)
return;let rowIndex=this._rowIndexForRepresentedObject(this._selectedObject);if(rowIndex===-1){this._selectedObject=null;this._table.deselectAll();return;}
this._table.selectRow(rowIndex);this._showDetailView(this._selectedObject);}
_HARResources()
{let resources=this._activeCollection.filteredEntries.map((x)=>x.resource);const supportedHARSchemes=new Set(["http","https","ws","wss"]);return resources.filter((resource)=>{if(!resource){return false;}
if(!resource.finished)
return false;if(!resource.requestSentDate)
return false;if(!supportedHARSchemes.has(resource.urlComponents.scheme))
return false;return true;});}
_exportHAR()
{let resources=this._HARResources();if(!resources.length){InspectorFrontendHost.beep();return;}
WI.HARBuilder.buildArchive(resources).then((har)=>{let mainFrame=WI.networkManager.mainFrame;let archiveName=mainFrame.mainResource.urlComponents.host||mainFrame.mainResource.displayName||"Archive";WI.FileUtilities.save({content:JSON.stringify(har,null,2),suggestedName:archiveName+".har",forceSaveAs:true,});});}
_importHAR()
{WI.FileUtilities.importJSON((result)=>this.processHAR(result),{multiple:true});}
_waterfallPopoverContent()
{let contentElement=document.createElement("div");contentElement.classList.add("waterfall-popover-content");return contentElement;}
_waterfallPopoverContentForResourceEntry(resourceEntry)
{let contentElement=this._waterfallPopoverContent();let resource=resourceEntry.resource;if(!resource.hasResponse()||!resource.firstTimestamp||!resource.lastTimestamp){contentElement.textContent=WI.UIString("Resource has no timing data");return contentElement;}
let breakdownView=new WI.ResourceTimingBreakdownView(resource,300);contentElement.appendChild(breakdownView.element);breakdownView.updateLayout();return contentElement;}
_waterfallPopoverContentForNodeEntry(nodeEntry,domEvents)
{let contentElement=this._waterfallPopoverContent();let breakdownView=new WI.DOMEventsBreakdownView(domEvents);contentElement.appendChild(breakdownView.element);breakdownView.updateLayout();return contentElement;}
_handleResourceEntryMousedownWaterfall(resourceEntry)
{let popoverContentElement=this._waterfallPopoverContentForResourceEntry(resourceEntry);this._handleMousedownWaterfall(resourceEntry,popoverContentElement,(cell)=>{return cell.querySelector(".block.mouse-tracking");});}
_handleNodeEntryMousedownWaterfall(nodeEntry,domEvents)
{let popoverContentElement=this._waterfallPopoverContentForNodeEntry(nodeEntry,domEvents);this._handleMousedownWaterfall(nodeEntry,popoverContentElement,(cell)=>{let domEventElement=nodeEntry.domEventElements.get(domEvents[0]);if(domEventElement&&this._waterfallPopover.visible){let newDOMEvents=Array.from(nodeEntry.domEventElements).filter(([domEvent,element])=>element===domEventElement).map(([domEvent,element])=>domEvent);this._waterfallPopover.content=this._waterfallPopoverContentForNodeEntry(nodeEntry,newDOMEvents);}
return domEventElement;});}
_handleMousedownWaterfall(entry,popoverContentElement,updateTargetAndContentFunction)
{if(!this._waterfallPopover){this._waterfallPopover=new WI.Popover;this._waterfallPopover.element.classList.add("waterfall-popover");}
if(this._waterfallPopover.visible)
return;let calculateTargetFrame=()=>{let rowIndex=this._rowIndexForRepresentedObject(entry.resource||entry.domNode);let cell=this._table.cellForRowAndColumn(rowIndex,this._waterfallColumn);if(cell){let targetElement=updateTargetAndContentFunction(cell);if(targetElement)
return WI.Rect.rectFromClientRect(targetElement.getBoundingClientRect());}
this._waterfallPopover.dismiss();return null;};let targetFrame=calculateTargetFrame();if(!targetFrame)
return;if(!targetFrame.size.width&&!targetFrame.size.height)
return;let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let preferredEdges=isRTL?[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]:[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X];this._waterfallPopover.windowResizeHandler=()=>{let bounds=calculateTargetFrame();if(bounds)
this._waterfallPopover.present(bounds,preferredEdges);};this._waterfallPopover.presentNewContentWithFrame(popoverContentElement,targetFrame,preferredEdges);}
_tableNameColumnDidChangeWidth(event)
{this._nameColumnWidthSetting.value=event.target.width;this._positionDetailView();}
_tableWaterfallColumnDidChangeWidth(event)
{this._table.reloadVisibleColumnCells(this._waterfallColumn);}
_transitionPageTarget(event)
{this._transitioningPageTarget=true;}};WI.NetworkTimelineOverviewGraph=class NetworkTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("network");timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._networkTimelineRecordAdded,this);timeline.addEventListener(WI.Timeline.Event.TimesUpdated,this.needsLayout,this);this.reset();for(let record of timeline.records)
this._processRecord(record);} 
reset()
{super.reset();this._nextDumpRow=0;this._timelineRecordGridRows=[];for(let i=0;i<WI.NetworkTimelineOverviewGraph.MaximumRowCount;++i)
this._timelineRecordGridRows.push([]);this.element.removeChildren();for(let rowRecords of this._timelineRecordGridRows){rowRecords.__element=document.createElement("div");rowRecords.__element.classList.add("graph-row");this.element.appendChild(rowRecords.__element);rowRecords.__recordBars=[];}} 
layout()
{super.layout();if(this.hidden)
return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let recordBarIndex=0;function createBar(rowElement,rowRecordBars,records,renderMode)
{let timelineRecordBar=rowRecordBars[recordBarIndex];if(!timelineRecordBar)
timelineRecordBar=rowRecordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;}
timelineRecordBar.refresh(this);if(!timelineRecordBar.element.parentNode)
rowElement.appendChild(timelineRecordBar.element);++recordBarIndex;}
for(let rowRecords of this._timelineRecordGridRows){let rowElement=rowRecords.__element;let rowRecordBars=rowRecords.__recordBars;recordBarIndex=0;WI.TimelineRecordBar.createCombinedBars(rowRecords,secondsPerPixel,this,createBar.bind(this,rowElement,rowRecordBars));for(;recordBarIndex<rowRecordBars.length;++recordBarIndex){rowRecordBars[recordBarIndex].records=null;rowRecordBars[recordBarIndex].element.remove();}}} 
_networkTimelineRecordAdded(event)
{let resourceTimelineRecord=event.data.record;this._processRecord(resourceTimelineRecord);this.needsLayout();}
_processRecord(resourceTimelineRecord)
{let compareByStartTime=(a,b)=>a.startTime-b.startTime;let minimumBarPaddingTime=WI.TimelineOverview.MinimumDurationPerPixel*(WI.TimelineRecordBar.MinimumWidthPixels+WI.TimelineRecordBar.MinimumMarginPixels);let foundRowForRecord=false;for(let i=0;i<this._timelineRecordGridRows.length;++i){let rowRecords=this._timelineRecordGridRows[i];let lastRecord=rowRecords.lastValue;if(!lastRecord||lastRecord.endTime+minimumBarPaddingTime<=resourceTimelineRecord.startTime){insertObjectIntoSortedArray(resourceTimelineRecord,rowRecords,compareByStartTime);this._nextDumpRow=i+1;foundRowForRecord=true;break;}}
if(!foundRowForRecord){for(let i=0;i<this._timelineRecordGridRows.length;++i){let rowRecords=this._timelineRecordGridRows[i];let lastRecord=rowRecords.lastValue;if(lastRecord.activeStartTime+minimumBarPaddingTime<=resourceTimelineRecord.startTime){insertObjectIntoSortedArray(resourceTimelineRecord,rowRecords,compareByStartTime);this._nextDumpRow=i+1;foundRowForRecord=true;break;}}}
if(!foundRowForRecord){if(this._nextDumpRow>=WI.NetworkTimelineOverviewGraph.MaximumRowCount)
this._nextDumpRow=0;insertObjectIntoSortedArray(resourceTimelineRecord,this._timelineRecordGridRows[this._nextDumpRow++],compareByStartTime);}}};WI.NetworkTimelineOverviewGraph.MaximumRowCount=6;WI.NetworkTimelineView=class NetworkTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);let columns={name:{},domain:{},type:{},method:{},scheme:{},statusCode:{},cached:{},protocol:{},priority:{},remoteAddress:{},connectionIdentifier:{},size:{},transferSize:{},requestSent:{},latency:{},duration:{},initiator:{},graph:{}};columns.name.title=WI.UIString("Name");columns.name.icon=true;columns.name.width="10%";columns.name.locked=true;columns.domain.title=WI.UIString("Domain");columns.domain.width="8%";columns.type.title=WI.UIString("Type");columns.type.width="7%";let typeToLabelMap=new Map;for(let key in WI.Resource.Type){let value=WI.Resource.Type[key];typeToLabelMap.set(value,WI.Resource.displayNameForType(value,true));}
columns.type.scopeBar=WI.TimelineDataGrid.createColumnScopeBar("network",typeToLabelMap);this._scopeBar=columns.type.scopeBar;columns.method.title=WI.UIString("Method");columns.method.width="4%";columns.scheme.title=WI.UIString("Scheme");columns.scheme.width="4%";columns.statusCode.title=WI.UIString("Status");columns.statusCode.width="4%";columns.cached.title=WI.UIString("Cached");columns.cached.width="6%";columns.protocol.title=WI.UIString("Protocol");columns.protocol.width="5%";columns.protocol.hidden=true;columns.priority.title=WI.UIString("Priority");columns.priority.width="5%";columns.priority.hidden=true;columns.remoteAddress.title=WI.UIString("IP Address");columns.remoteAddress.width="8%";columns.remoteAddress.hidden=true;columns.connectionIdentifier.title=WI.UIString("Connection ID");columns.connectionIdentifier.width="5%";columns.connectionIdentifier.hidden=true;columns.connectionIdentifier.aligned="right";columns.size.title=WI.UIString("Size");columns.size.width="6%";columns.size.aligned="right";columns.transferSize.title=WI.UIString("Transferred");columns.transferSize.width="8%";columns.transferSize.aligned="right";columns.requestSent.title=WI.UIString("Start Time");columns.requestSent.width="9%";columns.requestSent.aligned="right";columns.latency.title=WI.UIString("Latency");columns.latency.width="9%";columns.latency.aligned="right";columns.duration.title=WI.UIString("Duration");columns.duration.width="9%";columns.duration.aligned="right";columns.initiator.title=WI.UIString("Initiator");columns.initiator.width="9%";columns.initiator.hidden=true;for(let column in columns)
columns[column].sortable=true;this._timelineRuler=new WI.TimelineRuler;this._timelineRuler.allowsClippedLabels=true;columns.graph.title=WI.UIString("Timeline");columns.graph.width="15%";columns.graph.headerView=this._timelineRuler;columns.graph.sortable=false;if(!InspectorBackend.hasEvent("Network.loadingFinished","metrics")){delete columns.protocol;delete columns.priority;delete columns.remoteAddress;delete columns.connectionIdentifier;}
this._dataGrid=new WI.TimelineDataGrid(columns);this._dataGrid.sortDelegate=this;this._dataGrid.sortColumnIdentifier="requestSent";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("network-timeline-view");this.setupDataGrid(this._dataGrid);this.element.classList.add("network");this.addSubview(this._dataGrid);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._networkTimelineRecordAdded,this);this._pendingRecords=[];this._resourceDataGridNodeMap=new Map;for(let record of timeline.records)
this._processRecord(record);} 
get secondsPerPixel(){return this._timelineRuler.secondsPerPixel;}
get selectionPathComponents()
{if(!this._dataGrid.selectedNode||this._dataGrid.selectedNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(this._dataGrid.selectedNode,this._dataGrid.selectedNode.resource);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);return[pathComponent];}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._networkTimelineRecordAdded,this);this._dataGrid.closed();}
reset()
{super.reset();this._dataGrid.reset();this._pendingRecords=[];this._resourceDataGridNodeMap.clear();} 
dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2)
{if(sortColumnIdentifier==="priority")
return WI.Resource.comparePriority(node1.data.priority,node2.data.priority)*sortDirection;if(sortColumnIdentifier==="name"){let displayName1=node1.displayName();let displayName2=node2.displayName();if(displayName1!==displayName2)
return displayName1.extendedLocaleCompare(displayName2)*sortDirection;return node1.resource.url.extendedLocaleCompare(node2.resource.url)*sortDirection;}
return null;} 
dataGridNodePathComponentSelected(event)
{let pathComponent=event.data.pathComponent;let dataGridNode=pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}
layout()
{this.endTime=Math.min(this.endTime,this.currentTime);let oldZeroTime=this._timelineRuler.zeroTime;let oldStartTime=this._timelineRuler.startTime;let oldEndTime=this._timelineRuler.endTime;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;if(this.zeroTime!==oldZeroTime||this.startTime!==oldStartTime||this.endTime!==oldEndTime){for(let dataGridNode of this._resourceDataGridNodeMap.values())
dataGridNode.refreshGraph();}
this._processPendingRecords();} 
_processPendingRecords()
{if(!this._pendingRecords.length)
return;for(let resourceTimelineRecord of this._pendingRecords){let dataGridNode=this._resourceDataGridNodeMap.get(resourceTimelineRecord.resource);if(dataGridNode)
continue;dataGridNode=new WI.ResourceTimelineDataGridNode(resourceTimelineRecord,{graphDataSource:this,shouldShowPopover:true,});this._resourceDataGridNodeMap.set(resourceTimelineRecord.resource,dataGridNode);this._dataGrid.addRowInSortOrder(dataGridNode);}
this._pendingRecords=[];}
_networkTimelineRecordAdded(event)
{let resourceTimelineRecord=event.data.record;this._processRecord(resourceTimelineRecord);this.needsLayout();}
_processRecord(resourceTimelineRecord)
{this._pendingRecords.push(resourceTimelineRecord);}};WI.ObjectPreviewView=class ObjectPreviewView extends WI.Object
{constructor(object,preview,mode)
{super();this._object=object||null;this._preview=preview;this._mode=mode||WI.ObjectPreviewView.Mode.Full;this._element=document.createElement("span");this._element.className="object-preview";this._previewElement=this._element.appendChild(document.createElement("span"));this._previewElement.className="preview";this._lossless=this._appendPreview(this._previewElement,this._preview);this._titleElement=this._element.appendChild(document.createElement("span"));this._titleElement.className="title";this._titleElement.hidden=true;this._initTitleElement();if(this._preview.hasSize()){var sizeElement=this._element.appendChild(document.createElement("span"));sizeElement.className="size";sizeElement.textContent=" ("+this._preview.size+")";}
if(this._lossless)
this._element.classList.add("lossless");} 
get preview()
{return this._preview;}
get element()
{return this._element;}
get mode()
{return this._mode;}
get lossless()
{return this._lossless;}
showTitle()
{this._titleElement.hidden=false;this._previewElement.hidden=true;}
showPreview()
{this._titleElement.hidden=true;this._previewElement.hidden=false;}
setOriginatingObjectInfo(remoteObject,propertyPath)
{this._remoteObject=remoteObject;this._propertyPath=propertyPath||null;this.element.addEventListener("contextmenu",this._contextMenuHandler.bind(this));} 
_initTitleElement()
{if(this._preview.subtype==="regexp"||this._preview.subtype==="null")
this._titleElement.appendChild(WI.FormattedValue.createElementForObjectPreview(this._preview));else if(this._preview.subtype==="node")
this._titleElement.appendChild(WI.FormattedValue.createElementForNodePreview(this._preview,{remoteObjectAccessor:(callback)=>callback(this._object)}));else
this._titleElement.textContent=this._preview.description||"";}
_numberOfPropertiesToShowInMode()
{return this._mode===WI.ObjectPreviewView.Mode.Brief?3:Infinity;}
_appendPreview(element,preview)
{var displayObjectAsValue=false;if(preview.type==="object"){if(preview.subtype==="regexp"||preview.subtype==="null"||preview.subtype==="node"){displayObjectAsValue=true;}else if((preview.subtype==="array"&&preview.description!=="Array")||(preview.subtype!=="array"&&preview.description!=="Object")){var nameElement=element.appendChild(document.createElement("span"));nameElement.className="object-preview-name";nameElement.textContent=preview.description+" ";}}
var bodyElement=element.appendChild(document.createElement("span"));bodyElement.className="object-preview-body";if(!displayObjectAsValue){if(preview.collectionEntryPreviews)
return this._appendEntryPreviews(bodyElement,preview);if(preview.propertyPreviews)
return this._appendPropertyPreviews(bodyElement,preview);}
return this._appendValuePreview(bodyElement,preview);}
_appendEntryPreviews(element,preview)
{var lossless=preview.lossless&&!preview.propertyPreviews.length;var overflow=preview.overflow;var isIterator=preview.subtype==="iterator";element.append(isIterator?"[":"{");var limit=Math.min(preview.collectionEntryPreviews.length,this._numberOfPropertiesToShowInMode());for(var i=0;i<limit;++i){if(i>0)
element.append(", ");var keyPreviewLossless=true;var entry=preview.collectionEntryPreviews[i];if(entry.keyPreview){keyPreviewLossless=this._appendPreview(element,entry.keyPreview);element.append(" => ");}
var valuePreviewLossless=this._appendPreview(element,entry.valuePreview);if(!keyPreviewLossless||!valuePreviewLossless)
lossless=false;}
if(preview.collectionEntryPreviews.length>limit){lossless=false;overflow=true;}
if(overflow){if(limit>0)
element.append(", ");element.append(ellipsis);}
element.append(isIterator?"]":"}");return lossless;}
_appendPropertyPreviews(element,preview)
{if(preview.subtype==="error")
return false;if(preview.subtype==="date")
return!preview.propertyPreviews.length;var lossless=preview.lossless;var overflow=preview.overflow;var isArray=preview.subtype==="array";element.append(isArray?"[":"{");var numberAdded=0;var limit=this._numberOfPropertiesToShowInMode();for(let i=0;i<preview.propertyPreviews.length&&numberAdded<limit;++i){let property=preview.propertyPreviews[i];if(property.type==="accessor")
continue;if(property.name==="constructor")
continue;if(numberAdded++>0)
element.append(", ");if(!isArray||property.name!=i){let nameElement=element.appendChild(document.createElement("span"));nameElement.className="name";nameElement.textContent=property.name;element.append(": ");}
if(property.valuePreview)
this._appendPreview(element,property.valuePreview);else if(property.subtype==="node"){let options={};if(preview===this._preview&&this._object){options.remoteObjectAccessor=(callback)=>{this._object.getProperty(property.name,(error,remoteObject,wasThrown)=>{if(!error&&remoteObject&&!wasThrown){WI.consoleManager.releaseRemoteObjectWithConsoleClear(remoteObject);callback(remoteObject);}});};}
element.appendChild(WI.FormattedValue.createElementForNodePreview(property,options));}else
element.appendChild(WI.FormattedValue.createElementForPropertyPreview(property));}
if(numberAdded===limit&&preview.propertyPreviews.length>limit){lossless=false;overflow=true;}
if(overflow){if(limit>0)
element.append(", ");element.append(ellipsis);}
element.append(isArray?"]":"}");return lossless;}
_appendValuePreview(element,preview)
{if(preview.subtype==="node"){let options={};if(preview===this._preview&&this._object)
options.remoteObjectAccessor=(callback)=>callback(this._object);element.appendChild(WI.FormattedValue.createElementForNodePreview(preview,options));return false;}
element.appendChild(WI.FormattedValue.createElementForObjectPreview(preview));return true;}
_contextMenuHandler(event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);event.__addedObjectPreviewContextMenuItems=true;contextMenu.appendItem(WI.UIString("Log Value"),()=>{let isImpossible=!this._propertyPath||this._propertyPath.isFullPathImpossible();let text=isImpossible?WI.UIString("Selected Value"):this._propertyPath.displayPath(WI.PropertyPath.Type.Value);if(!isImpossible)
WI.quickConsole.prompt.pushHistoryItem(text);WI.consoleLogViewController.appendImmediateExecutionWithResult(text,this._remoteObject,isImpossible);});}};WI.ObjectPreviewView.Mode={Brief:Symbol("object-preview-brief"),Full:Symbol("object-preview-full"),};WI.ObjectPropertiesDetailSectionRow=class ObjectPropertiesDetailSectionRow extends WI.DetailsSectionRow
{constructor(objectTree,sectionForDeferredExpand)
{super();this._objectTree=objectTree;this.hideEmptyMessage();this.element.classList.add("properties",WI.SyntaxHighlightedStyleClassName);this.element.appendChild(objectTree.element);if(sectionForDeferredExpand&&sectionForDeferredExpand.collapsed)
sectionForDeferredExpand.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._detailsSectionCollapsedStateChanged,this);else
this._objectTree.expand();} 
get objectTree(){return this._objectTree;} 
_detailsSectionCollapsedStateChanged(event)
{this._objectTree.expand();event.target.removeEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._detailsSectionCollapsedStateChanged,this);}};WI.ObjectTreeArrayIndexTreeElement=class ObjectTreeArrayIndexTreeElement extends WI.ObjectTreeBaseTreeElement
{constructor(property,propertyPath)
{super(property,propertyPath,property);this.mainTitle=this._titleFragment();this.addClassName("object-tree-property");this.addClassName("object-tree-array-index");if(!this.property.hasValue())
this.addClassName("accessor");} 
invokedGetter()
{this.mainTitle=this._titleFragment();this.removeClassName("accessor");} 
_titleFragment()
{var container=document.createDocumentFragment();var nameElement=container.appendChild(document.createElement("span"));nameElement.className="index-name";nameElement.textContent=this.property.name;nameElement.title=this.propertyPathString(this.thisPropertyPath());container.append(" ");var valueElement=container.appendChild(document.createElement("span"));valueElement.className="index-value";var resolvedValue=this.resolvedValue();if(resolvedValue)
valueElement.appendChild(WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(resolvedValue,this.resolvedValuePropertyPath()));else{if(this.property.hasGetter())
container.appendChild(this.createGetterElement(true));if(this.property.hasSetter())
container.appendChild(this.createSetterElement());}
valueElement.classList.add("value");if(this.hadError())
valueElement.classList.add("error");return container;}};WI.ObjectTreeMapEntryTreeElement=class ObjectTreeMapEntryTreeElement extends WI.ObjectTreeBaseTreeElement
{constructor(object,propertyPath)
{super(object,propertyPath);this._object=object;this.addClassName("object-tree-array-index");this.addClassName("object-tree-map-entry");} 
get object()
{return this._object;} 
resolvedValue()
{return this._object;}
propertyPathType()
{return WI.PropertyPath.Type.Value;}
titleFragment()
{var container=document.createDocumentFragment();var propertyPath=this.resolvedValuePropertyPath();var nameElement=container.appendChild(document.createElement("span"));nameElement.className="index-name";nameElement.textContent=this.displayPropertyName();nameElement.title=this.propertyPathString(propertyPath);container.append(" ");var valueElement=container.appendChild(document.createElement("span"));valueElement.className="index-value";valueElement.appendChild(WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(this._object,propertyPath));return container;}};WI.ObjectTreeMapKeyTreeElement=class ObjectTreeMapKeyTreeElement extends WI.ObjectTreeMapEntryTreeElement
{constructor(object,propertyPath)
{super(object,propertyPath);this.mainTitle=this.titleFragment();this.addClassName("key");} 
displayPropertyName()
{return WI.UIString("key");}
resolvedValuePropertyPath()
{return this._propertyPath.appendMapKey(this._object);}};WI.ObjectTreeMapValueTreeElement=class ObjectTreeMapValueTreeElement extends WI.ObjectTreeMapEntryTreeElement
{constructor(object,propertyPath,key)
{super(object,propertyPath);this._key=key;this.mainTitle=this.titleFragment();this.addClassName("value");} 
displayPropertyName()
{return WI.UIString("value");}
resolvedValuePropertyPath()
{return this._propertyPath.appendMapValue(this._object,this._key);}};WI.ObjectTreePropertyTreeElement=class ObjectTreePropertyTreeElement extends WI.ObjectTreeBaseTreeElement
{constructor(property,propertyPath,mode,prototypeName)
{super(property,propertyPath,property);this._mode=mode||WI.ObjectTreeView.Mode.Properties;this._prototypeName=prototypeName;this._fetchStart=0;this._fetchEnd=WI.ObjectTreeView.showMoreFetchCount;this._fetchEndIndex=0;this.mainTitle=this._titleFragment();this.addClassName("object-tree-property");if(this.property.hasValue()){this.addClassName(this.property.value.type);if(this.property.value.subtype)
this.addClassName(this.property.value.subtype);}else
this.addClassName("accessor");if(this.property.wasThrown)
this.addClassName("had-error");if(this.property.name==="__proto__")
this.addClassName("prototype-property");this._updateTooltips();this._updateHasChildren();} 
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this._fetchStart=0;this._fetchEndIndex=0;this._updateChildren();}
onexpand()
{if(this._previewView)
this._previewView.showTitle();}
oncollapse()
{if(this._previewView)
this._previewView.showPreview();}
invokedGetter()
{this.mainTitle=this._titleFragment();var resolvedValue=this.resolvedValue();this.addClassName(resolvedValue.type);if(resolvedValue.subtype)
this.addClassName(resolvedValue.subtype);if(this.hadError())
this.addClassName("had-error");this.removeClassName("accessor");this._updateHasChildren();} 
_updateHasChildren()
{var resolvedValue=this.resolvedValue();var valueHasChildren=resolvedValue&&resolvedValue.hasChildren;var wasThrown=this.hadError();if(this._mode===WI.ObjectTreeView.Mode.Properties)
this.hasChildren=!wasThrown&&valueHasChildren;else
this.hasChildren=!wasThrown&&valueHasChildren&&(this.property.name==="__proto__"||this._alwaysDisplayAsProperty());}
_updateTooltips()
{var attributes=[];if(this.property.configurable)
attributes.push("configurable");if(this.property.enumerable)
attributes.push("enumerable");if(this.property.writable)
attributes.push("writable");this.iconElement.title=attributes.join(" ");}
_titleFragment()
{if(this.property.name==="__proto__")
return this._createTitlePrototype();if(this._mode===WI.ObjectTreeView.Mode.Properties)
return this._createTitlePropertyStyle();else
return this._createTitleAPIStyle();}
_createTitlePrototype()
{var nameElement=document.createElement("span");nameElement.className="prototype-name";nameElement.textContent=WI.UIString("%s Prototype").format(this._sanitizedPrototypeString(this.property.value));nameElement.title=this.propertyPathString(this.thisPropertyPath());return nameElement;}
_createTitlePropertyStyle()
{var container=document.createDocumentFragment();var nameElement=document.createElement("span");nameElement.className="property-name";nameElement.textContent=this.property.name+": ";nameElement.title=this.propertyPathString(this.thisPropertyPath());if(this._mode===WI.ObjectTreeView.Mode.Properties){if(!this.property.enumerable)
nameElement.classList.add("not-enumerable");}
var valueOrGetterElement;var resolvedValue=this.resolvedValue();if(resolvedValue){if(resolvedValue.preview){this._previewView=new WI.ObjectPreviewView(resolvedValue,resolvedValue.preview);valueOrGetterElement=this._previewView.element;}else{this._loadPreviewLazilyIfNeeded();valueOrGetterElement=WI.FormattedValue.createElementForRemoteObject(resolvedValue,this.hadError());if(resolvedValue.type==="function")
valueOrGetterElement.textContent=this._functionPropertyString();}}else{valueOrGetterElement=document.createElement("span");if(this.property.hasGetter())
valueOrGetterElement.appendChild(this.createGetterElement(this._mode!==WI.ObjectTreeView.Mode.ClassAPI));if(this.property.hasSetter())
valueOrGetterElement.appendChild(this.createSetterElement());}
valueOrGetterElement.classList.add("value");if(this.hadError())
valueOrGetterElement.classList.add("error");container.appendChild(nameElement);container.appendChild(valueOrGetterElement);return container;}
_createTitleAPIStyle()
{if(this._alwaysDisplayAsProperty())
return this._createTitlePropertyStyle();var isFunction=this.property.hasValue()&&this.property.value.type==="function";if(!isFunction&&!this.property.hasGetter()&&!this.property.hasSetter())
return null;var container=document.createDocumentFragment();var nameElement=document.createElement("span");nameElement.className="property-name";nameElement.textContent=this.property.name;nameElement.title=this.propertyPathString(this.thisPropertyPath());container.appendChild(nameElement);if(isFunction){var paramElement=document.createElement("span");paramElement.className="function-parameters";paramElement.textContent=this._functionParameterString();container.appendChild(paramElement);}else{var spacer=container.appendChild(document.createElement("span"));spacer.className="spacer";if(this.property.hasGetter())
container.appendChild(this.createGetterElement(this._mode!==WI.ObjectTreeView.Mode.ClassAPI));if(this.property.hasSetter())
container.appendChild(this.createSetterElement());}
return container;}
_loadPreviewLazilyIfNeeded()
{let resolvedValue=this.resolvedValue();if(!resolvedValue.canLoadPreview())
return;resolvedValue.updatePreview((preview)=>{if(preview){this.mainTitle=this._titleFragment();if(this.expanded)
this._previewView.showTitle();}});}
_alwaysDisplayAsProperty()
{if(this.property.name==="constructor")
return true;if(this.property.hasValue()&&this.property.value.type!=="function")
return true;if(this._getterValue)
return true;return false;}
_functionPropertyString()
{return"function"+this._functionParameterString();}
_functionParameterString()
{var resolvedValue=this.resolvedValue();if(isFunctionStringNativeCode(resolvedValue.description)){if(this._prototypeName){if(WI.NativePrototypeFunctionParameters[this._prototypeName]){var params=WI.NativePrototypeFunctionParameters[this._prototypeName][this._property.name];return params?"("+params+")":"()";}}
var parentDescription=this._propertyPath.object.description;if(isFunctionStringNativeCode(parentDescription)){var match=parentDescription.match(/^function\s+([^)]+?)\(/);if(match){var name=match[1];if(WI.NativeConstructorFunctionParameters[name]){var params=WI.NativeConstructorFunctionParameters[name][this._property.name];return params?"("+params+")":"()";}}}
if(parentDescription.endsWith("Constructor")||["Math","JSON","Reflect","Console"].includes(parentDescription)){var name=parentDescription;if(WI.NativeConstructorFunctionParameters[name]){var params=WI.NativeConstructorFunctionParameters[name][this._property.name];return params?"("+params+")":"()";}}}
var match=resolvedValue.functionDescription.match(/^function.*?(\([^)]*?\))/);return match?match[1]:"()";}
_sanitizedPrototypeString(value)
{ if(value.type==="function")
return"Function";if(value.subtype==="date")
return"Date";if(value.subtype==="regexp")
return"RegExp";return value.description.replace(/Prototype$/,"");}
_updateChildren()
{let resolvedValue=this.resolvedValue();let wrap=(handler,mode)=>(list)=>{if(this._fetchEndIndex===0)
this.removeChildren();if(!list){let errorMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("Could not fetch properties. Object may no longer exist."));this.appendChild(new WI.TreeElement(errorMessageElement));return;}
handler.call(this,list,this.resolvedValuePropertyPath(),mode);this.dispatchEventToListeners(WI.ObjectTreeView.Event.Updated);};let options={ownProperties:true,generatePreview:true,};if(isFinite(this._fetchEnd)&&this._fetchEnd<resolvedValue.size){options.fetchStart=this._fetchStart;options.fetchCount=this._fetchEnd-this._fetchStart;}
if(resolvedValue.isCollectionType()&&this._mode===WI.ObjectTreeView.Mode.Properties)
resolvedValue.getCollectionEntries(wrap(this._updateEntries,this._mode),options);else if(this._mode===WI.ObjectTreeView.Mode.ClassAPI||this._mode===WI.ObjectTreeView.Mode.PureAPI)
resolvedValue.getPropertyDescriptors(wrap(this._updateProperties,WI.ObjectTreeView.Mode.ClassAPI),options);else if(this.property.name==="__proto__")
resolvedValue.getPropertyDescriptors(wrap(this._updateProperties,WI.ObjectTreeView.Mode.PrototypeAPI),options);else
resolvedValue.getDisplayablePropertyDescriptors(wrap(this._updateProperties,this._mode),options);}
_updateEntries(entries,propertyPath,mode)
{let resolvedValue=this.resolvedValue();entries.forEach((entry,i)=>{if(entry.key){this.insertChild(new WI.ObjectTreeMapKeyTreeElement(entry.key,propertyPath),this._fetchEndIndex++);this.insertChild(new WI.ObjectTreeMapValueTreeElement(entry.value,propertyPath,entry.key),this._fetchEndIndex++);}else
this.insertChild(new WI.ObjectTreeSetIndexTreeElement(entry.value,propertyPath),this._fetchEndIndex++);});if(!this.children.length){let emptyMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("No Entries"));this.appendChild(new WI.TreeElement(emptyMessageElement));}else{WI.ObjectTreeView.addShowMoreIfNeeded({resolvedValue,representation:this,parentTreeElement:this,handleShowMoreClicked:()=>{this._updateChildren();},handleShowAllClicked:()=>{this.shouldRefreshChildren=true;},});}
if(this._fetchStart===0){resolvedValue.getOwnPropertyDescriptor("__proto__",(propertyDescriptor)=>{if(propertyDescriptor)
this.appendChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,mode));});}}
_updateProperties(properties,propertyPath,mode)
{properties.sort(WI.ObjectTreeView.comparePropertyDescriptors);var resolvedValue=this.resolvedValue();var isArray=resolvedValue.isArray();var isPropertyMode=mode===WI.ObjectTreeView.Mode.Properties||this._getterValue;var isAPI=mode!==WI.ObjectTreeView.Mode.Properties;var prototypeName;if(this.property.name==="__proto__"){if(resolvedValue.description)
prototypeName=this._sanitizedPrototypeString(resolvedValue);}
var hadProto=false;for(var propertyDescriptor of properties){
if(isAPI&&propertyDescriptor.nativeGetter)
continue;if(propertyDescriptor.name==="__proto__"){hadProto=true;this.appendChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,mode,prototypeName));continue;}
if(isArray&&isPropertyMode){if(propertyDescriptor.isIndexProperty())
this.insertChild(new WI.ObjectTreeArrayIndexTreeElement(propertyDescriptor,propertyPath),this._fetchEndIndex++);}else
this.insertChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,mode,prototypeName),this._fetchEndIndex++);}
if(!this.children.length||(hadProto&&this.children.length===1)){let emptyMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("No Properties"));this.insertChild(new WI.TreeElement(emptyMessageElement),0);}else if(isArray&&isPropertyMode){WI.ObjectTreeView.addShowMoreIfNeeded({resolvedValue,representation:this,parentTreeElement:this,handleShowMoreClicked:()=>{this._updateChildren();},handleShowAllClicked:()=>{this.shouldRefreshChildren=true;},});}}};WI.ObjectTreeSetIndexTreeElement=class ObjectTreeSetIndexTreeElement extends WI.ObjectTreeBaseTreeElement
{constructor(object,propertyPath)
{super(object,propertyPath);this._object=object;this.mainTitle=this._titleFragment();this.addClassName("object-tree-array-index");} 
get object()
{return this._object;} 
resolvedValue()
{return this._object;}
resolvedValuePropertyPath()
{return this.propertyPath.appendSetIndex(this._object);} 
_titleFragment()
{var container=document.createDocumentFragment();var propertyPath=this.resolvedValuePropertyPath();var nameElement=container.appendChild(document.createElement("span"));nameElement.className="index-name";nameElement.textContent="\u2022";nameElement.title=WI.UIString("Unable to determine path to property from root");container.append(" ");var valueElement=container.appendChild(document.createElement("span"));valueElement.className="index-value";valueElement.appendChild(WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(this._object,propertyPath));return container;}};WI.ObjectTreeView=class ObjectTreeView extends WI.Object
{constructor(object,mode,propertyPath,forceExpanding)
{super();var providedPropertyPath=propertyPath instanceof WI.PropertyPath;this._object=object;this._mode=mode||WI.ObjectTreeView.defaultModeForObject(object);this._propertyPath=propertyPath||new WI.PropertyPath(this._object,"this");this._expanded=false;this._hasLosslessPreview=false;this._includeProtoProperty=true;

this._inConsole=true;this._fetchStart=0;this._fetchEnd=ObjectTreeView.showMoreFetchCount;this._fetchEndIndex=0;if(this._object.isClass())
forceExpanding=true;this._element=document.createElement("div");this._element.__objectTree=this;this._element.className="object-tree";if(this._object.preview){this._previewView=new WI.ObjectPreviewView(this._object,this._object.preview);this._previewView.setOriginatingObjectInfo(this._object,providedPropertyPath?propertyPath:null);this._previewView.element.addEventListener("click",this._handlePreviewOrTitleElementClick.bind(this));this._element.appendChild(this._previewView.element);if(this._previewView.lossless&&!this._propertyPath.parent&&!forceExpanding){this._hasLosslessPreview=true;this.element.classList.add("lossless-preview");}}else{this._titleElement=document.createElement("span");this._titleElement.className="title";this._titleElement.appendChild(WI.FormattedValue.createElementForRemoteObject(this._object));this._titleElement.addEventListener("click",this._handlePreviewOrTitleElementClick.bind(this));this._element.appendChild(this._titleElement);}
this._outline=new WI.TreeOutline;this._outline.compact=true;this._outline.customIndent=true;this._outline.element.classList.add("object");this._element.appendChild(this._outline.element);} 
static defaultModeForObject(object)
{if(object.subtype==="class")
return WI.ObjectTreeView.Mode.ClassAPI;return WI.ObjectTreeView.Mode.Properties;}
static createEmptyMessageElement(message)
{var emptyMessageElement=document.createElement("div");emptyMessageElement.className="empty-message";emptyMessageElement.textContent=message;return emptyMessageElement;}
static get showMoreFetchCount(){return 100;}
static addShowMoreIfNeeded({resolvedValue,representation,parentTreeElement,handleShowMoreClicked,handleShowAllClicked})
{if(!InspectorBackend.hasCommand("Runtime.getProperties","fetchStart"))
return;let remaining=resolvedValue.size-representation._fetchEnd;if(remaining<=0)
return;let treeElement=new WI.TreeElement(document.createElement("span"));treeElement.selectable=false;parentTreeElement.insertChild(treeElement,representation._fetchEndIndex); let buttons=[];let createButton=(textContent,handleClick)=>{let button=treeElement.title.appendChild(document.createElement("button"));button.textContent=textContent;button.addEventListener("click",(event)=>{event.stop();representation.singleFireEventListener(ObjectTreeView.Event.Updated,function(event){if(treeElement.parent===parentTreeElement)
parentTreeElement.removeChild(treeElement);},button);for(let other of buttons)
other.disabled=true;let spinner=new WI.IndeterminateProgressSpinner;buttons.lastValue.insertAdjacentElement("afterend",spinner.element);handleClick();});buttons.push(button);};if(!resolvedValue.isWeakCollection()&&remaining>ObjectTreeView.showMoreFetchCount){createButton(WI.UIString("Show %d More").format(ObjectTreeView.showMoreFetchCount),()=>{representation._fetchStart=representation._fetchEnd;representation._fetchEnd=representation._fetchStart+ObjectTreeView.showMoreFetchCount;handleShowMoreClicked();});}
createButton(WI.UIString("Show All (%d More)").format(remaining),()=>{representation._fetchStart=0;representation._fetchEnd=Infinity;representation._fetchEndIndex=0;handleShowAllClicked();});}
static comparePropertyDescriptors(propertyA,propertyB)
{var a=propertyA.name;var b=propertyB.name;if(a==="__proto__")
return 1;if(b==="__proto__")
return-1;if(propertyA.isInternalProperty&&!propertyB.isInternalProperty)
return-1;if(propertyB.isInternalProperty&&!propertyA.isInternalProperty)
return 1;if(propertyA.symbol&&!propertyB.symbol)
return 1;if(propertyB.symbol&&!propertyA.symbol)
return-1;if(a===b)
return 0;var diff=0;var chunk=/^\d+|^\D+/;var chunka,chunkb,anum,bnum;while(diff===0){if(!a&&b)
return-1;if(!b&&a)
return 1;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){diff=chunka-chunkb;if(diff===0&&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);}
return diff;} 
get object()
{return this._object;}
get element()
{return this._element;}
get treeOutline()
{return this._outline;}
get expanded()
{return this._expanded;}
expand()
{if(this._expanded)
return;if(this._hasLosslessPreview)
return;this._expanded=true;this._element.classList.add("expanded");if(this._previewView)
this._previewView.showTitle();this._trackWeakEntries();this.update();}
collapse()
{if(!this._expanded)
return;this._expanded=false;this._element.classList.remove("expanded");if(this._previewView)
this._previewView.showPreview();this._untrackWeakEntries();}
showOnlyProperties()
{this._inConsole=false;this._element.classList.add("properties-only");this._includeProtoProperty=false;}
showOnlyJSON()
{this.showOnlyProperties();this._element.classList.add("json-only");}
appendTitleSuffix(suffixElement)
{if(this._previewView)
this._previewView.element.appendChild(suffixElement);else
this._titleElement.appendChild(suffixElement);}
appendExtraPropertyDescriptor(propertyDescriptor)
{if(!this._extraProperties)
this._extraProperties=[];this._extraProperties.push(propertyDescriptor);}
setPrototypeNameOverride(override)
{this._prototypeNameOverride=override;}
resetPropertyPath()
{this._propertyPath.pathComponent="this";} 
update()
{this._fetchStart=0;this._fetchEndIndex=0;this._updateChildren();} 
_updateChildren()
{let options={ownProperties:true,generatePreview:true,};if(isFinite(this._fetchEnd)&&this._fetchEnd<this._object.size){options.fetchStart=this._fetchStart;options.fetchCount=this._fetchEnd-this._fetchStart;}
let wrap=(handler)=>(list)=>{if(this._fetchEndIndex===0)
this._outline.removeChildren();if(!list){let errorMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("Could not fetch properties. Object may no longer exist."));this._outline.appendChild(new WI.TreeElement(errorMessageElement));return;}
handler.call(this,list,this._propertyPath);this.dispatchEventToListeners(ObjectTreeView.Event.Updated);};if(this._object.isCollectionType()&&this._mode===ObjectTreeView.Mode.Properties)
this._object.getCollectionEntries(wrap(this._updateEntries),options);else if(this._object.isClass())
this._object.classPrototype.getDisplayablePropertyDescriptors(wrap(this._updateProperties),options);else if(this._mode===ObjectTreeView.Mode.PureAPI)
this._object.getPropertyDescriptors(wrap(this._updateProperties),options);else
this._object.getDisplayablePropertyDescriptors(wrap(this._updateProperties),options);}
_updateEntries(entries,propertyPath)
{entries.forEach((entry,i)=>{if(entry.key){this._outline.insertChild(new WI.ObjectTreeMapKeyTreeElement(entry.key,propertyPath),this._fetchEndIndex++);this._outline.insertChild(new WI.ObjectTreeMapValueTreeElement(entry.value,propertyPath,entry.key),this._fetchEndIndex++);}else
this._outline.insertChild(new WI.ObjectTreeSetIndexTreeElement(entry.value,propertyPath),this._fetchEndIndex++);});if(!this._outline.children.length){let emptyMessageElement=ObjectTreeView.createEmptyMessageElement(WI.UIString("No Entries"));this._outline.appendChild(new WI.TreeElement(emptyMessageElement));}else{ObjectTreeView.addShowMoreIfNeeded({resolvedValue:this._object,representation:this,parentTreeElement:this._outline,handleShowMoreClicked:()=>{this._updateChildren();},handleShowAllClicked:()=>{this.update();},});}
if(this._fetchStart===0){this._object.getOwnPropertyDescriptor("__proto__",(propertyDescriptor)=>{if(propertyDescriptor)
this._outline.appendChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,this._mode));});}}
_updateProperties(properties,propertyPath)
{if(this._extraProperties)
properties.pushAll(this._extraProperties);properties.sort(WI.ObjectTreeView.comparePropertyDescriptors);var isArray=this._object.isArray();var isPropertyMode=this._mode===WI.ObjectTreeView.Mode.Properties;var hadProto=false;for(var propertyDescriptor of properties){if(propertyDescriptor.name==="__proto__"){if(!this._includeProtoProperty)
continue;hadProto=true;this._outline.appendChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,this._mode,this._prototypeNameOverride));continue;}
if(isArray&&isPropertyMode){if(propertyDescriptor.isIndexProperty())
this._outline.insertChild(new WI.ObjectTreeArrayIndexTreeElement(propertyDescriptor,propertyPath),this._fetchEndIndex++);}else
this._outline.insertChild(new WI.ObjectTreePropertyTreeElement(propertyDescriptor,propertyPath,this._mode,this._prototypeNameOverride),this._fetchEndIndex++);}
if(!this._outline.children.length||(hadProto&&this._outline.children.length===1)){let emptyMessageElement=ObjectTreeView.createEmptyMessageElement(WI.UIString("No Properties"));this._outline.insertChild(new WI.TreeElement(emptyMessageElement),0);}else if(isArray&&isPropertyMode){ObjectTreeView.addShowMoreIfNeeded({resolvedValue:this._object,representation:this,parentTreeElement:this._outline,handleShowMoreClicked:()=>{this._updateChildren();},handleShowAllClicked:()=>{this.update();},});}}
_handlePreviewOrTitleElementClick(event)
{if(this._hasLosslessPreview)
return;if(!this._expanded)
this.expand();else
this.collapse();event.stopPropagation();}
_trackWeakEntries()
{if(this._trackingEntries)
return;if(!this._object.isWeakCollection())
return;this._trackingEntries=true;if(this._inConsole){WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._untrackWeakEntries,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.SessionStarted,this._untrackWeakEntries,this);}}
_untrackWeakEntries()
{if(!this._trackingEntries)
return;if(!this._object.isWeakCollection())
return;this._trackingEntries=false;this._object.releaseWeakCollectionEntries();if(this._inConsole){WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.Cleared,this._untrackWeakEntries,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.SessionStarted,this._untrackWeakEntries,this);}
}};WI.ObjectTreeView.Mode={Properties:Symbol("object-tree-properties"), PrototypeAPI:Symbol("object-tree-prototype-api"),ClassAPI:Symbol("object-tree-class-api"),PureAPI:Symbol("object-tree-pure-api"),};WI.ObjectTreeView.Event={Updated:"object-tree-updated",};WI.OpenResourceDialog=class OpenResourceDialog extends WI.Dialog
{constructor(delegate)
{super(delegate);this.element.classList.add("open-resource-dialog");let fieldElement=this.element.appendChild(document.createElement("div"));fieldElement.classList.add("field");this._inputElement=fieldElement.appendChild(document.createElement("input"));this._inputElement.type="text";this._inputElement.placeholder=WI.UIString("File or Resource");this._inputElement.spellcheck=false;this._clearIconElement=fieldElement.appendChild(document.createElement("img"));this._inputElement.addEventListener("keydown",this._handleKeydownEvent.bind(this));this._inputElement.addEventListener("keyup",this._handleKeyupEvent.bind(this));this._inputElement.addEventListener("blur",this._handleBlurEvent.bind(this));this._clearIconElement.addEventListener("mousedown",this._handleMousedownEvent.bind(this));this._clearIconElement.addEventListener("click",this._handleClickEvent.bind(this));this._treeOutline=new WI.TreeOutline;this._treeOutline.allowsRepeatSelection=true;this._treeOutline.disclosureButtons=false;this._treeOutline.large=true;this._treeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);this._treeOutline.element.addEventListener("focus",()=>{this._inputElement.focus();});this.element.appendChild(this._treeOutline.element);this._queryController=new WI.ResourceQueryController;this._filteredResults=[];} 
representedObjectIsValid(value)
{if(value instanceof WI.Script&&value.anonymous)
return false;if(value instanceof WI.CSSStyleSheet&&value.anonymous)
return false;return super.representedObjectIsValid(value);}
_populateResourceTreeOutline()
{function createHighlightedTitleFragment(title,highlightTextRanges)
{let titleFragment=document.createDocumentFragment();let lastIndex=0;for(let textRange of highlightTextRanges){if(textRange.startColumn>lastIndex)
titleFragment.append(title.substring(lastIndex,textRange.startColumn));let highlightSpan=document.createElement("span");highlightSpan.classList.add("highlighted");highlightSpan.append(title.substring(textRange.startColumn,textRange.endColumn));titleFragment.append(highlightSpan);lastIndex=textRange.endColumn;}
if(lastIndex<title.length)
titleFragment.append(title.substring(lastIndex,title.length));return titleFragment;}
function createTreeElement(representedObject)
{let treeElement=null;if(representedObject instanceof WI.SourceMapResource)
treeElement=new WI.SourceMapResourceTreeElement(representedObject);else if(representedObject instanceof WI.Resource)
treeElement=new WI.ResourceTreeElement(representedObject);else if(representedObject instanceof WI.Script)
treeElement=new WI.ScriptTreeElement(representedObject);else if(representedObject instanceof WI.CSSStyleSheet)
treeElement=new WI.CSSStyleSheetTreeElement(representedObject);return treeElement;}
for(let result of this._filteredResults){let resource=result.resource;if(this._treeOutline.findTreeElement(resource))
continue;let treeElement=createTreeElement(resource);if(!treeElement)
continue;treeElement.mainTitle=createHighlightedTitleFragment(resource.displayName,result.matchingTextRanges);if(resource instanceof WI.LocalResource&&resource.localResourceOverride)
treeElement.subtitle=WI.UIString("Local Override");let path=resource.urlComponents.path;let lastPathComponent=resource.urlComponents.lastPathComponent;if(path&&lastPathComponent){let parentPath=path.substring(0,path.length-lastPathComponent.length);if(parentPath.length&&parentPath!=="/")
treeElement.titlesElement.dataset.path=parentPath;}
treeElement[WI.OpenResourceDialog.ResourceMatchCookieDataSymbol]=result.cookie;this._treeOutline.appendChild(treeElement);}
if(this._treeOutline.children.length)
this._treeOutline.children[0].select(true,false,true);}
didDismissDialog()
{WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceWasAdded,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasRemoved,this._resourceWasRemoved,this);WI.Target.removeEventListener(WI.Target.Event.ResourceAdded,this._resourceWasAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptAdded,this._scriptAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._scriptRemoved,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleStyleSheetAdded,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleStyleSheetRemoved,this);this._queryController.reset();}
didPresentDialog()
{WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceWasAdded,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasRemoved,this._resourceWasRemoved,this);WI.Target.addEventListener(WI.Target.Event.ResourceAdded,this._resourceWasAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptAdded,this._scriptAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._scriptRemoved,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleStyleSheetAdded,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleStyleSheetRemoved,this);if(WI.networkManager.mainFrame)
this._addResourcesForFrame(WI.networkManager.mainFrame);this._addScriptsForTarget(WI.mainTarget);for(let target of WI.targets){if(target!==WI.mainTarget)
this._addResourcesForTarget(target);}
this._addLocalResourceOverrides();if(WI.NetworkManager.supportsBootstrapScript()){let bootstrapScript=WI.networkManager.bootstrapScript;if(bootstrapScript){const suppressFilterUpdate=true;this._addResource(bootstrapScript,suppressFilterUpdate);}}
for(let styleSheet of WI.cssManager.styleSheets){if(styleSheet.origin!==WI.CSSStyleSheet.Type.Author&&!styleSheet.anonymous)
this._addResource(styleSheet);}
this._updateFilter();this._inputElement.focus();this._clear();} 
_handleKeydownEvent(event)
{if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode){if(this._inputElement.value===""){this.dismiss();event.preventDefault();}else
this._clear();event.preventDefault();}else if(event.keyCode===WI.KeyboardShortcut.Key.Enter.keyCode){if(this._treeOutline.selectedTreeElement){this.dismiss(this._treeOutline.selectedTreeElement.representedObject,this._treeOutline.selectedTreeElement[WI.OpenResourceDialog.ResourceMatchCookieDataSymbol]);event.preventDefault();return;}
if(/^:\d/.test(this._inputElement.value)){let visibleContentView=WI.focusedOrVisibleContentView();let representedObject=visibleContentView?visibleContentView.representedObject:null;if(representedObject&&representedObject instanceof WI.SourceCode){let[,lineNumber,columnNumber]=this._inputElement.value.split(":");lineNumber=lineNumber?parseInt(lineNumber,10)-1:0;columnNumber=columnNumber?parseInt(columnNumber,10)-1:0;this.dismiss(representedObject,{lineNumber,columnNumber});event.preventDefault();return;}}
this._inputElement.select();}else if(event.keyCode===WI.KeyboardShortcut.Key.Up.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Down.keyCode){let treeElement=this._treeOutline.selectedTreeElement;if(!treeElement)
return;let adjacentSiblingProperty=event.keyCode===WI.KeyboardShortcut.Key.Up.keyCode?"previousSibling":"nextSibling";treeElement=treeElement[adjacentSiblingProperty];if(treeElement)
treeElement.revealAndSelect(true,false,true);event.preventDefault();}}
_handleKeyupEvent(event)
{if(event.keyCode===WI.KeyboardShortcut.Key.Up.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Down.keyCode)
return;this._updateFilter();}
_handleBlurEvent(event)
{if(event.relatedTarget===this._treeOutline.element)
return;this.dismiss();}
_handleMousedownEvent(event)
{this._inputElement.select();
event.preventDefault();}
_handleClickEvent(event)
{this._clear();}
_clear()
{this._inputElement.value="";this._updateFilter();}
_updateFilter()
{this._filteredResults=[];this._treeOutline.removeChildren();let filterText=this._inputElement.value.trim();if(filterText){this._filteredResults=this._queryController.executeQuery(filterText);this._populateResourceTreeOutline();}
this.element.classList.toggle("non-empty",this._inputElement.value!=="");this.element.classList.toggle("has-results",this._treeOutline.children.length);}
_treeSelectionDidChange(event)
{let treeElement=this._treeOutline.selectedTreeElement;if(!treeElement)
return;if(!event.data.selectedByUser)
return;this.dismiss(treeElement.representedObject,treeElement[WI.OpenResourceDialog.ResourceMatchCookieDataSymbol]);}
_addResource(resource,suppressFilterUpdate)
{if(!this.representedObjectIsValid(resource))
return;for(let sourceMap of resource.sourceMaps){for(let sourceMapResource of sourceMap.resources)
this._addResource(sourceMapResource,suppressFilterUpdate);}
this._queryController.addResource(resource);if(suppressFilterUpdate)
return;this._updateFilter();}
_removeResource(resource)
{if(!this.representedObjectIsValid(resource))
return;this._queryController.removeResource(resource);this._updateFilter();}
_addResourcesForFrame(frame)
{const suppressFilterUpdate=true;let frames=[frame];while(frames.length){let currentFrame=frames.shift();this._addResource(currentFrame.mainResource,suppressFilterUpdate);for(let resource of currentFrame.resourceCollection)
this._addResource(resource,suppressFilterUpdate);frames.pushAll(currentFrame.childFrameCollection);}}
_addResourcesForTarget(target)
{const suppressFilterUpdate=true;this._addResource(target.mainResource);for(let resource of target.resourceCollection)
this._addResource(resource,suppressFilterUpdate);this._addScriptsForTarget(target);}
_addScriptsForTarget(target)
{const suppressFilterUpdate=true;let targetData=WI.debuggerManager.dataForTarget(target);for(let script of targetData.scripts){if(script.anonymous||script.resource||script.dynamicallyAddedScriptElement)
continue;if(!WI.settings.debugShowConsoleEvaluations.value&&isWebInspectorConsoleEvaluationScript(script.sourceURL))
continue;if(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(script.sourceURL))
continue;this._addResource(script,suppressFilterUpdate);}
for(let script of target.extraScriptCollection){if(script.resource)
continue;this._addResource(script,suppressFilterUpdate);}}
_addLocalResourceOverrides()
{if(!WI.NetworkManager.supportsOverridingResponses())
return;const suppressFilterUpdate=true;for(let localResourceOverride of WI.networkManager.localResourceOverrides)
this._addResource(localResourceOverride.localResource,suppressFilterUpdate);}
_mainResourceDidChange(event)
{if(event.target.isMainFrame())
this._queryController.reset();this._addResource(event.target.mainResource);}
_resourceWasAdded(event)
{this._addResource(event.data.resource);}
_resourceWasRemoved(event)
{this._removeResource(event.data.resource);}
_scriptAdded(event)
{let{script}=event.data;if(script.resource||script.target===WI.mainTarget)
return;this._addResource(script);}
_scriptRemoved(event)
{let{script}=event.data;if(script.resource||script.target===WI.mainTarget)
return;this._removeResource(script);}
_handleStyleSheetAdded(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author||styleSheet.anonymous)
return;this._addResource(styleSheet);}
_handleStyleSheetRemoved(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author||styleSheet.anonymous)
return;this._removeResource(styleSheet);}};WI.OpenResourceDialog.ResourceMatchCookieDataSymbol=Symbol("open-resource-dialog-resource-match-cookie-data");WI.OriginTreeElement=class OriginTreeElement extends WI.GeneralTreeElement
{constructor(title,representedObject,options)
{const classNames=["origin-icon"];const subtitle=null;super(classNames,title,subtitle,representedObject,options);}};WI.OverviewTimelineView=class OverviewTimelineView extends WI.TimelineView
{constructor(recording,extraArguments)
{super(recording,extraArguments);this._recording=recording;this._pendingRepresentedObjects=[];this._resourceDataGridNodeMap=new Map;if(WI.TimelineRecording.sourceCodeTimelinesSupported()&&!this._recording.imported){WI.settings.timelineOverviewGroupBySourceCode.addEventListener(WI.Setting.Event.Changed,this._handleGroupBySourceCodeSettingChanged,this);this._groupBySourceCodeNavigationItem=new WI.CheckboxNavigationItem("overview-timeline-group-by-resource",WI.UIString("Group By Resource"),WI.settings.timelineOverviewGroupBySourceCode.value);this._groupBySourceCodeNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,this._handleGroupBySourceCodeNavigationItemCheckedDidChange,this);}
let columns={name:{},source:{},graph:{}};columns.name.title=WI.UIString("Name");columns.name.width="20%";columns.name.icon=true;columns.name.locked=true;if(this._shouldGroupBySourceCode)
columns.name.disclosure=true;columns.source.title=WI.UIString("Source");columns.source.width="10%";columns.source.icon=true;columns.source.locked=true;if(this._shouldGroupBySourceCode)
columns.source.hidden=true;this._timelineRuler=new WI.TimelineRuler;this._timelineRuler.allowsClippedLabels=true;columns.graph.width="70%";columns.graph.headerView=this._timelineRuler;columns.graph.locked=true;this._dataGrid=new WI.TimelineDataGrid(columns);this.setupDataGrid(this._dataGrid);this._currentTimeMarker=new WI.TimelineMarker(0,WI.TimelineMarker.Type.CurrentTime);this._timelineRuler.addMarker(this._currentTimeMarker);this.element.classList.add("overview");this.addSubview(this._dataGrid);for(let timeline of this._relevantTimelines)
timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._handleTimelineRecordAdded,this);recording.addEventListener(WI.TimelineRecording.Event.SourceCodeTimelineAdded,this._sourceCodeTimelineAdded,this);recording.addEventListener(WI.TimelineRecording.Event.MarkerAdded,this._markerAdded,this);recording.addEventListener(WI.TimelineRecording.Event.Reset,this._recordingReset,this);this._loadExistingRecords();} 
get secondsPerPixel()
{return this._timelineRuler.secondsPerPixel;}
set secondsPerPixel(x)
{this._timelineRuler.secondsPerPixel=x;}
attached()
{super.attached();this._timelineRuler.needsLayout(WI.View.LayoutReason.Resize);}
closed()
{for(let timeline of this._recording.timelines.values())
timeline.removeEventListener(WI.Timeline.Event.RecordAdded,this._handleTimelineRecordAdded,this);this._recording.removeEventListener(WI.TimelineRecording.Event.SourceCodeTimelineAdded,this._sourceCodeTimelineAdded,this);this._recording.removeEventListener(WI.TimelineRecording.Event.MarkerAdded,this._markerAdded,this);this._recording.removeEventListener(WI.TimelineRecording.Event.Reset,this._recordingReset,this);}
get navigationItems()
{let navigationItems=[];if(this._groupBySourceCodeNavigationItem)
navigationItems.push(this._groupBySourceCodeNavigationItem);return navigationItems;}
get selectionPathComponents()
{let dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode||dataGridNode.hidden)
return null;let pathComponents=[];while(dataGridNode&&!dataGridNode.root){if(dataGridNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(dataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);pathComponents.unshift(pathComponent);dataGridNode=dataGridNode.parent;}
return pathComponents;}
reset()
{super.reset();this._dataGrid.reset();this._pendingRepresentedObjects=[];this._resourceDataGridNodeMap.clear();} 
get showsImportedRecordingMessage()
{return true;}
dataGridNodePathComponentSelected(event)
{let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}
layout()
{let oldZeroTime=this._timelineRuler.zeroTime;let oldStartTime=this._timelineRuler.startTime;let oldEndTime=this._timelineRuler.endTime;let oldCurrentTime=this._currentTimeMarker.time;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;this._currentTimeMarker.time=this.currentTime;if(this.zeroTime!==oldZeroTime||this.startTime!==oldStartTime||this.endTime!==oldEndTime||this.currentTime!==oldCurrentTime){let dataGridNode=this._dataGrid.children[0];while(dataGridNode){dataGridNode.refreshGraph();dataGridNode=dataGridNode.traverseNextNode(true,null,true);}}
this._processPendingRepresentedObjects();} 
get _relevantTimelines()
{let timelines=[];for(let[type,timeline]of this._recording.timelines){if(type===WI.TimelineRecord.Type.RenderingFrame||type===WI.TimelineRecord.Type.CPU||type===WI.TimelineRecord.Type.Memory)
continue;timelines.push(timeline);}
return timelines;}
get _shouldGroupBySourceCode()
{if(this._recording.imported)
return false;return WI.TimelineRecording.sourceCodeTimelinesSupported()&&WI.settings.timelineOverviewGroupBySourceCode.value;}
_loadExistingRecords()
{this._pendingRepresentedObjects=[];this._resourceDataGridNodeMap.clear();this._dataGrid.removeChildren();if(this._shouldGroupBySourceCode){let networkTimeline=this._recording.timelines.get(WI.TimelineRecord.Type.Network);if(networkTimeline)
this._pendingRepresentedObjects.pushAll(networkTimeline.records.map((record)=>record.resource));this._pendingRepresentedObjects.pushAll(this._recording.sourceCodeTimelines);}else{for(let timeline of this._relevantTimelines)
this._pendingRepresentedObjects.pushAll(timeline.records);}
this.needsLayout();}
_compareDataGridNodesByStartTime(a,b)
{function getStartTime(dataGridNode)
{if(dataGridNode instanceof WI.ResourceTimelineDataGridNode)
return dataGridNode.resource.firstTimestamp;if(dataGridNode instanceof WI.SourceCodeTimelineTimelineDataGridNode)
return dataGridNode.sourceCodeTimeline.startTime;console.error("Unknown data grid node.",dataGridNode);return 0;}
let result=getStartTime(a)-getStartTime(b);if(result)
return result;return a.displayName().extendedLocaleCompare(b.displayName());}
_insertDataGridNode(dataGridNode,parentDataGridNode)
{if(!parentDataGridNode)
parentDataGridNode=this._dataGrid;parentDataGridNode.insertChild(dataGridNode,insertionIndexForObjectInListSortedByFunction(dataGridNode,parentDataGridNode.children,this._compareDataGridNodesByStartTime));}
_addResourceToDataGridIfNeeded(resource)
{if(!resource)
return null;let dataGridNode=this._resourceDataGridNodeMap.get(resource);if(!dataGridNode){let resourceTimelineRecord=this._networkTimeline?this._networkTimeline.recordForResource(resource):null;if(!resourceTimelineRecord)
resourceTimelineRecord=new WI.ResourceTimelineRecord(resource);dataGridNode=new WI.ResourceTimelineDataGridNode(resourceTimelineRecord,{graphDataSource:this,includesGraph:true,});this._resourceDataGridNodeMap.set(resource,dataGridNode);}
if(!dataGridNode.parent){let parentFrame=resource.parentFrame;if(!parentFrame)
return null;let expandedByDefault=false;if(parentFrame.mainResource===resource||parentFrame.provisionalMainResource===resource){parentFrame=parentFrame.parentFrame;expandedByDefault=!parentFrame;}
if(expandedByDefault)
dataGridNode.expand();let parentDataGridNode=null;if(parentFrame){let parentResource=parentFrame.provisionalMainResource||parentFrame.mainResource;parentDataGridNode=this._addResourceToDataGridIfNeeded(parentResource);if(!parentDataGridNode)
return null;}
this._insertDataGridNode(dataGridNode,parentDataGridNode);}
dataGridNode.refresh();return dataGridNode;}
_addSourceCodeTimeline(sourceCodeTimeline)
{let dataGridNode=this._resourceDataGridNodeMap.get(sourceCodeTimeline);if(!dataGridNode){dataGridNode=new WI.SourceCodeTimelineTimelineDataGridNode(sourceCodeTimeline,{graphDataSource:this,});this._resourceDataGridNodeMap.set(sourceCodeTimeline,dataGridNode);}
if(!dataGridNode.parent){let parentDataGridNode=sourceCodeTimeline.sourceCodeLocation?this._addResourceToDataGridIfNeeded(sourceCodeTimeline.sourceCode):null;this._insertDataGridNode(dataGridNode,parentDataGridNode);}}
_processPendingRepresentedObjects()
{if(!this._pendingRepresentedObjects.length)
return;for(var representedObject of this._pendingRepresentedObjects){if(this._shouldGroupBySourceCode){if(representedObject instanceof WI.Resource)
this._addResourceToDataGridIfNeeded(representedObject);else if(representedObject instanceof WI.SourceCodeTimeline)
this._addSourceCodeTimeline(representedObject);else
console.error("Unknown represented object",representedObject);}else{const options={graphDataSource:this,shouldShowPopover:true,};let dataGridNode=null;if(representedObject instanceof WI.ResourceTimelineRecord)
dataGridNode=new WI.ResourceTimelineDataGridNode(representedObject,options);else if(representedObject instanceof WI.LayoutTimelineRecord)
dataGridNode=new WI.LayoutTimelineDataGridNode(representedObject,options);else if(representedObject instanceof WI.MediaTimelineRecord)
dataGridNode=new WI.MediaTimelineDataGridNode(representedObject,options);else if(representedObject instanceof WI.ScriptTimelineRecord)
dataGridNode=new WI.ScriptTimelineDataGridNode(representedObject,options);else if(representedObject instanceof WI.HeapAllocationsTimelineRecord)
dataGridNode=new WI.HeapAllocationsTimelineDataGridNode(representedObject,options);if(!dataGridNode)
continue;let comparator=(a,b)=>{return a.record.startTime-b.record.startTime;};this._dataGrid.insertChild(dataGridNode,insertionIndexForObjectInListSortedByFunction(dataGridNode,this._dataGrid.children,comparator));}}
this._pendingRepresentedObjects=[];}
_handleGroupBySourceCodeSettingChanged(event)
{let groupBySourceCode=this._shouldGroupBySourceCode;this._dataGrid.disclosureColumnIdentifier=groupBySourceCode?"name":undefined;this._dataGrid.setColumnVisible("source",!groupBySourceCode);if(this._groupBySourceCodeNavigationItem)
this._groupBySourceCodeNavigationItem.checked=groupBySourceCode;this._loadExistingRecords();}
_handleGroupBySourceCodeNavigationItemCheckedDidChange(event)
{WI.settings.timelineOverviewGroupBySourceCode.value=!WI.settings.timelineOverviewGroupBySourceCode.value;}
_handleTimelineRecordAdded(event)
{let{record}=event.data;if(this._shouldGroupBySourceCode){if(event.target.type!==WI.TimelineRecord.Type.Network)
return;this._pendingRepresentedObjects.push(record.resource);}else
this._pendingRepresentedObjects.push(record);this.needsLayout();}
_sourceCodeTimelineAdded(event)
{if(!this._shouldGroupBySourceCode)
return;var sourceCodeTimeline=event.data.sourceCodeTimeline;if(!sourceCodeTimeline)
return;this._pendingRepresentedObjects.push(sourceCodeTimeline);this.needsLayout();}
_markerAdded(event)
{this._timelineRuler.addMarker(event.data.marker);}
_recordingReset(event)
{this._timelineRuler.clearMarkers();this._timelineRuler.addMarker(this._currentTimeMarker);}};WI.ProbeDetailsSidebarPanel=class ProbeDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("probe",WI.UIString("Probes"));this._probeSetSections=new Map;this._inspectedProbeSets=[];} 
get inspectedProbeSets()
{return this._inspectedProbeSets.slice();}
set inspectedProbeSets(newProbeSets)
{for(let probeSet of this._inspectedProbeSets){let removedSection=this._probeSetSections.get(probeSet);if(removedSection)
removedSection.element.remove();}
this._inspectedProbeSets=newProbeSets;for(let probeSet of newProbeSets){let shownSection=this._probeSetSections.get(probeSet);if(shownSection)
this.contentView.element.appendChild(shownSection.element);}}
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];var inspectedProbeSets=objects.filter(function(object){return object instanceof WI.ProbeSet;});inspectedProbeSets.sort(function sortBySourceLocation(aProbeSet,bProbeSet){if(!(aProbeSet instanceof WI.JavaScriptBreakpoint))
return 1;if(!(bProbeSet instanceof WI.JavaScriptBreakpoint))
return-1;var aLocation=aProbeSet.breakpoint.sourceCodeLocation;var bLocation=bProbeSet.breakpoint.sourceCodeLocation;var comparisonResult=aLocation.sourceCode.displayName.extendedLocaleCompare(bLocation.sourceCode.displayName);if(comparisonResult!==0)
return comparisonResult;comparisonResult=aLocation.displayLineNumber-bLocation.displayLineNumber;if(comparisonResult!==0)
return comparisonResult;return aLocation.displayColumnNumber-bLocation.displayColumnNumber;});this.inspectedProbeSets=inspectedProbeSets;return!!this._inspectedProbeSets.length;}
closed()
{if(this.didInitialLayout){WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);}
super.closed();} 
initialLayout()
{super.initialLayout();WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);for(let probeSet of new Set([...this._inspectedProbeSets,...WI.debuggerManager.probeSets]))
this._probeSetAdded(probeSet);this.inspectedProbeSets=this._inspectedProbeSets;}
sizeDidChange()
{super.sizeDidChange(); for(let detailsSection of this._probeSetSections.values())
detailsSection.sizeDidChange();} 
_probeSetAdded(probeSetOrEvent)
{var probeSet;if(probeSetOrEvent instanceof WI.ProbeSet)
probeSet=probeSetOrEvent;else
probeSet=probeSetOrEvent.data.probeSet;var newSection=new WI.ProbeSetDetailsSection(probeSet);this._probeSetSections.set(probeSet,newSection);}
_probeSetRemoved(event)
{var probeSet=event.data.probeSet;var inspectedProbeSets=this.inspectedProbeSets;var index=inspectedProbeSets.indexOf(probeSet);if(index!==-1){inspectedProbeSets.splice(index,1);this.inspectedProbeSets=inspectedProbeSets;}
var removedSection=this._probeSetSections.get(probeSet);this._probeSetSections.delete(probeSet);removedSection.closed();}};WI.ProbeSetDataGrid=class ProbeSetDataGrid extends WI.DataGrid
{constructor(probeSet)
{var columns={};for(var probe of probeSet.probes){var title=probe.expression||WI.UIString("(uninitialized)");columns[WI.ProbeSetDataGrid.columnIdentifierForProbe(probe)]={title};}
super(columns);this.probeSet=probeSet;this.inline=true;this._frameNodes=new Map;this._lastUpdatedFrame=null;this._nodesSinceLastNavigation=[];probeSet.addEventListener(WI.ProbeSet.Event.ProbeAdded,this._setupProbe,this);probeSet.addEventListener(WI.ProbeSet.Event.ProbeRemoved,this._teardownProbe,this);probeSet.addEventListener(WI.ProbeSet.Event.SamplesCleared,this._setupData,this);WI.Probe.addEventListener(WI.Probe.Event.ExpressionChanged,this._probeExpressionChanged,this);this._setupData();} 
static columnIdentifierForProbe(probe)
{return"probe"+probe.id;} 
closed()
{for(var probe of this.probeSet)
this._teardownProbe(probe);this.probeSet.removeEventListener(WI.ProbeSet.Event.ProbeAdded,this._setupProbe,this);this.probeSet.removeEventListener(WI.ProbeSet.Event.ProbeRemoved,this._teardownProbe,this);this.probeSet.removeEventListener(WI.ProbeSet.Event.SamplesCleared,this._setupData,this);WI.Probe.removeEventListener(WI.Probe.Event.ExpressionChanged,this._probeExpressionChanged,this);} 
_setupProbe(event)
{var probe=event.data;this.insertColumn(WI.ProbeSetDataGrid.columnIdentifierForProbe(probe),{title:probe.expression});for(var frame of this._data.frames)
this._updateNodeForFrame(frame);}
_teardownProbe(event)
{var probe=event.data;this.removeColumn(WI.ProbeSetDataGrid.columnIdentifierForProbe(probe));for(var frame of this._data.frames)
this._updateNodeForFrame(frame);}
_setupData()
{this._data=this.probeSet.dataTable;for(var frame of this._data.frames)
this._updateNodeForFrame(frame);this._data.addEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataFrameInserted,this);this._data.addEventListener(WI.ProbeSetDataTable.Event.SeparatorInserted,this._dataSeparatorInserted,this);this._data.addEventListener(WI.ProbeSetDataTable.Event.WillRemove,this._teardownData,this);}
_teardownData()
{this._data.removeEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataFrameInserted,this);this._data.removeEventListener(WI.ProbeSetDataTable.Event.SeparatorInserted,this._dataSeparatorInserted,this);this._data.removeEventListener(WI.ProbeSetDataTable.Event.WillRemove,this._teardownData,this);this.removeChildren();this._frameNodes=new Map;this._lastUpdatedFrame=null;}
_updateNodeForFrame(frame)
{var node=null;if(this._frameNodes.has(frame)){node=this._frameNodes.get(frame);node.frame=frame;node.refresh();}else{node=new WI.ProbeSetDataGridNode(this);node.frame=frame;this._frameNodes.set(frame,node);node.createCells();var sortFunction=function(a,b){return WI.ProbeSetDataFrame.compare(a.frame,b.frame);};var insertionIndex=insertionIndexForObjectInListSortedByFunction(node,this.children,sortFunction);if(insertionIndex===this.children.length)
this.appendChild(node);else if(this.children[insertionIndex].frame.key===frame.key){this.removeChild(this.children[insertionIndex]);this.insertChild(node,insertionIndex);}else
this.insertChild(node,insertionIndex);} 
this.updateLayoutIfNeeded();node.element.classList.add("data-updated");window.setTimeout(function(){node.element.classList.remove("data-updated");},WI.ProbeSetDataGrid.DataUpdatedAnimationDuration);this._nodesSinceLastNavigation.push(node);}
_updateNodeForSeparator(frame)
{this._frameNodes.get(frame).updateCellsForSeparator(frame,this.probeSet);for(var node of this._nodesSinceLastNavigation)
node.element.classList.add("past-value");this._nodesSinceLastNavigation=[];}
_dataFrameInserted(event)
{var frame=event.data;this._lastUpdatedFrame=frame;this._updateNodeForFrame(frame);}
_dataSeparatorInserted(event)
{var frame=event.data;this._updateNodeForSeparator(frame);}
_probeExpressionChanged(event)
{var probe=event.target;if(probe.breakpoint!==this.probeSet.breakpoint)
return;let columnIdentifier=WI.ProbeSetDataGrid.columnIdentifierForProbe(probe);if(!this.columns.has(columnIdentifier))
return;var oldColumn=this.columns.get(columnIdentifier);this.removeColumn(columnIdentifier);var ordinal=oldColumn["ordinal"];var newColumn={title:event.data.newValue};this.insertColumn(columnIdentifier,newColumn,ordinal);for(var frame of this._data.frames)
this._updateNodeForFrame(frame);}};WI.ProbeSetDataGrid.DataUpdatedAnimationDuration=300;WI.ProbeSetDataGridNode=class ProbeSetDataGridNode extends WI.DataGridNode
{constructor(dataGrid)
{super();this.dataGrid=dataGrid;this._data={};this._element=document.createElement("tr");this._element.dataGridNode=this;this._element.classList.add("revealed");} 
get element()
{return this._element;}
get data()
{return this._data;}
set frame(value)
{this._frame=value;var data={};for(var probe of this.dataGrid.probeSet.probes){let columnIdentifier=WI.ProbeSetDataGrid.columnIdentifierForProbe(probe);var sample=this.frame[probe.id];if(!sample||!sample.object)
data[columnIdentifier]=WI.ProbeSetDataFrame.MissingValue;else
data[columnIdentifier]=sample.object;}
this._data=data;}
get frame()
{return this._frame;}
createCellContent(columnIdentifier,cell)
{var sample=this.data[columnIdentifier];if(sample===WI.ProbeSetDataFrame.MissingValue){cell.classList.add("unknown-value");return sample;}
if(sample instanceof WI.RemoteObject)
return WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(sample,null);return sample;}
updateCellsFromFrame(frame,probeSet)
{}
updateCellsForSeparator(frame,probeSet)
{this._element.classList.add("separator");}};WI.ProbeSetDetailsSection=class ProbeSetDetailsSection extends WI.DetailsSection
{constructor(probeSet)
{let title=probeSet.breakpoint.displayName;var optionsElement=document.createElement("div");var dataGrid=new WI.ProbeSetDataGrid(probeSet);var singletonRow=new WI.DetailsSectionRow;singletonRow.element.appendChild(dataGrid.element);var probeSectionGroup=new WI.DetailsSectionGroup([singletonRow]);super("probe",title,[probeSectionGroup],optionsElement);this.element.classList.add("probe-set");this._probeSet=probeSet;this._dataGrid=dataGrid;this._navigationBar=new WI.NavigationBar;this._optionsElement.appendChild(this._navigationBar.element);this._addProbeButtonItem=new WI.ButtonNavigationItem("add-probe",WI.UIString("Add probe expression"),"Images/Plus13.svg",13,13);this._addProbeButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._addProbeButtonClicked,this);this._navigationBar.addNavigationItem(this._addProbeButtonItem);this._clearSamplesButtonItem=new WI.ButtonNavigationItem("clear-samples",WI.UIString("Clear samples"),"Images/NavigationItemTrash.svg",15,15);this._clearSamplesButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearSamplesButtonClicked,this);this._clearSamplesButtonItem.enabled=this._probeSetHasSamples();this._navigationBar.addNavigationItem(this._clearSamplesButtonItem);this._removeProbeButtonItem=new WI.ButtonNavigationItem("remove-probe",WI.UIString("Delete probe"),"Images/CloseLarge.svg",12,12);this._removeProbeButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._removeProbeButtonClicked,this);this._navigationBar.addNavigationItem(this._removeProbeButtonItem);this._probeSet.addEventListener(WI.ProbeSet.Event.SampleAdded,this._probeSetSamplesChanged,this);this._probeSet.addEventListener(WI.ProbeSet.Event.SamplesCleared,this._probeSetSamplesChanged,this);if(this._probeSet.breakpoint instanceof WI.JavaScriptBreakpoint){this._updateLinkElement();this._probeSet.breakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._updateLinkElement,this);}} 
closed()
{this._probeSet.removeEventListener(WI.ProbeSet.Event.SampleAdded,this._probeSetSamplesChanged,this);this._probeSet.removeEventListener(WI.ProbeSet.Event.SamplesCleared,this._probeSetSamplesChanged,this);if(this._probeSet.breakpoint instanceof WI.JavaScriptBreakpoint)
this._probeSet.breakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._updateLinkElement,this);this.element.remove();} 
sizeDidChange()
{ this._dataGrid.sizeDidChange();} 
_updateLinkElement()
{const options={ignoreNetworkTab:true,ignoreSearchTab:true,};var breakpoint=this._probeSet.breakpoint;if(breakpoint.sourceCodeLocation.sourceCode)
this.titleElement=WI.createSourceCodeLocationLink(breakpoint.sourceCodeLocation,options);else{this.titleElement=WI.linkifyLocation(breakpoint.contentIdentifier,breakpoint.sourceCodeLocation.position,options);}
this.titleElement.classList.add(WI.ProbeSetDetailsSection.DontFloatLinkStyleClassName);}
_addProbeButtonClicked(event)
{function createProbeFromEnteredExpression(visiblePopover,event)
{if(event.keyCode!==13)
return;let expression=event.target.value;this._probeSet.createProbe(expression);visiblePopover.dismiss();}
let popover=new WI.Popover;let content=document.createElement("div");content.classList.add(WI.ProbeSetDetailsSection.ProbePopoverElementStyleClassName);content.createChild("div").textContent=WI.UIString("Add New Probe Expression");let textBox=content.createChild("input");textBox.addEventListener("keypress",createProbeFromEnteredExpression.bind(this,popover));textBox.addEventListener("click",function(event){event.target.select();});textBox.spellcheck=false;textBox.placeholder=WI.UIString("Expression");popover.content=content;let target=WI.Rect.rectFromClientRect(event.target.element.getBoundingClientRect());popover.present(target,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);popover.windowResizeHandler=()=>{let target=WI.Rect.rectFromClientRect(event.target.element.getBoundingClientRect());popover.present(target,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);};textBox.select();}
_clearSamplesButtonClicked(event)
{this._probeSet.clearSamples();}
_removeProbeButtonClicked(event)
{this._probeSet.clear();}
_probeSetSamplesChanged(event)
{this._clearSamplesButtonItem.enabled=this._probeSetHasSamples();}
_probeSetHasSamples()
{return this._probeSet.probes.some((probe)=>probe.samples.length);}};WI.ProbeSetDetailsSection.DontFloatLinkStyleClassName="dont-float";WI.ProbeSetDetailsSection.ProbePopoverElementStyleClassName="probe-popover";WI.ProfileDataGridNode=class ProfileDataGridNode extends WI.DataGridNode
{constructor(callingContextTreeNode,tree)
{super(callingContextTreeNode,{copyable:false});this._node=callingContextTreeNode;this._tree=tree;this._childrenToChargeToSelf=new Set;this._extraSelfTimeFromChargedChildren=0;this.addEventListener(WI.DataGridNode.Event.Populate,this._populate,this);this._updateChildrenForModifiers();this._recalculateData();} 
get callingContextTreeNode(){return this._node;}
displayName()
{let title=this._node.name;if(!title)
return WI.UIString("(anonymous function)");if(title==="(program)")
return WI.UIString("(program)");return title;}
iconClassName()
{let script=WI.debuggerManager.scriptForIdentifier(this._node.sourceID,WI.assumingMainTarget());if(!script||!script.url)
return"native-icon";if(this._node.name==="(program)")
return"program-icon";return"function-icon";} 
get data()
{return this._data;}
createCellContent(columnIdentifier,cell)
{switch(columnIdentifier){case"totalTime":return this._totalTimeContent();case"selfTime":return Number.secondsToMillisecondsString(this._data.selfTime);case"function":return this._displayContent();}
return super.createCellContent(columnIdentifier,cell);}
sort()
{let children=this.children;children.sort(this._tree._sortComparator);for(let i=0;i<children.length;++i){children[i]._recalculateSiblings(i);children[i].sort();}}
refresh()
{this._updateChildrenForModifiers();this._recalculateData();super.refresh();}
appendContextMenuItems(contextMenu)
{let disableFocus=this===this._tree.currentFocusNode;contextMenu.appendItem(WI.UIString("Focus on Subtree"),()=>{this._tree.addFocusNode(this);},disableFocus); let disableChargeToCaller=this._tree.callingContextTree.type===WI.CallingContextTree.Type.BottomUp;contextMenu.appendItem(WI.UIString("Charge \u201C%s\u201D to Callers").format(this.displayName()),()=>{this._tree.addModifier({type:WI.ProfileDataGridTree.ModifierType.ChargeToCaller,source:this._node});},disableChargeToCaller);contextMenu.appendSeparator();} 
filterableDataForColumn(columnIdentifier)
{if(columnIdentifier==="function"){let filterableData=[this.displayName()];let script=WI.debuggerManager.scriptForIdentifier(this._node.sourceID,WI.assumingMainTarget());if(script&&script.url&&this._node.line>=0&&this._node.column>=0)
filterableData.push(script.url);return filterableData;}
return super.filterableDataForColumn(columnIdentifier);} 
_updateChildrenForModifiers()
{ let isBottomUp=this._tree.callingContextTree.type===WI.CallingContextTree.Type.BottomUp;if(!this._tree.hasModifiers()||isBottomUp){if(!this.shouldRefreshChildren&&this._childrenToChargeToSelf.size){for(let child of this._childrenToChargeToSelf){this.appendChild(new WI.ProfileDataGridNode(child,this._tree));}
this.sort();}
this._extraSelfTimeFromChargedChildren=0;this._childrenToChargeToSelf.clear();this.hasChildren=this._node.hasChildrenInTimeRange(this._tree.startTime,this._tree.endTime);return;}
this._extraSelfTimeFromChargedChildren=0;this._childrenToChargeToSelf.clear();let hasNonChargedChild=false;this._node.forEachChild((child)=>{if(child.hasStackTraceInTimeRange(this._tree.startTime,this._tree.endTime)){for(let{type,source}of this._tree.modifiers){if(type===WI.ProfileDataGridTree.ModifierType.ChargeToCaller){if(child.equals(source)){this._childrenToChargeToSelf.add(child);this._extraSelfTimeFromChargedChildren+=child.filteredTimestampsAndDuration(this._tree.startTime,this._tree.endTime).duration;continue;}}
hasNonChargedChild=true;}}});this.hasChildren=hasNonChargedChild;if(!this.shouldRefreshChildren&&this._childrenToChargeToSelf.size){for(let childDataGridNode of this.children){if(this._childrenToChargeToSelf.has(childDataGridNode.callingContextTreeNode))
this.removeChild(childDataGridNode);}}}
_recalculateData()
{let{timestamps,duration}=this._node.filteredTimestampsAndDuration(this._tree.startTime,this._tree.endTime);let{leafTimestamps,leafDuration}=this._node.filteredLeafTimestampsAndDuration(this._tree.startTime,this._tree.endTime);let totalTime=duration;let selfTime=leafDuration+this._extraSelfTimeFromChargedChildren;let fraction=totalTime/this._tree.totalSampleTime;this._data={totalTime,selfTime,fraction};}
_totalTimeContent()
{let{totalTime,fraction}=this._data;let fragment=document.createDocumentFragment();let timeElement=fragment.appendChild(document.createElement("span"));timeElement.classList.add("time");timeElement.textContent=Number.secondsToMillisecondsString(totalTime);let percentElement=fragment.appendChild(document.createElement("span"));percentElement.classList.add("percentage");percentElement.textContent=Number.percentageString(fraction);return fragment;}
_displayContent()
{let title=this.displayName();let iconClassName=this.iconClassName();let fragment=document.createDocumentFragment();let iconElement=fragment.appendChild(document.createElement("img"));iconElement.classList.add("icon",iconClassName);let titleElement=fragment.appendChild(document.createElement("span"));titleElement.textContent=title;let script=WI.debuggerManager.scriptForIdentifier(this._node.sourceID,WI.assumingMainTarget());if(script&&script.url&&this._node.line>=0&&this._node.column>=0){let sourceCodeLocation=script.createSourceCodeLocation(this._node.line-1,this._node.column-1);let locationElement=fragment.appendChild(document.createElement("span"));locationElement.classList.add("location");sourceCodeLocation.populateLiveDisplayLocationString(locationElement,"textContent",WI.SourceCodeLocation.ColumnStyle.Hidden,WI.SourceCodeLocation.NameStyle.Short);const options={dontFloat:true,useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};fragment.appendChild(WI.createSourceCodeLocationLink(sourceCodeLocation,options));}
return fragment;}
_populate()
{if(!this.shouldRefreshChildren)
return;this.removeEventListener(WI.DataGridNode.Event.Populate,this._populate,this);this._node.forEachChild((child)=>{if(!this._childrenToChargeToSelf.has(child)){if(child.hasStackTraceInTimeRange(this._tree.startTime,this._tree.endTime))
this.appendChild(new WI.ProfileDataGridNode(child,this._tree));}});this.sort();}};WI.ProfileDataGridTree=class ProfileDataGridTree extends WI.Object
{constructor(callingContextTree,startTime,endTime,sortComparator)
{super();this._children=[];this._sortComparator=sortComparator;this._callingContextTree=callingContextTree;this._startTime=startTime;this._endTime=endTime;this._totalSampleTime=this._callingContextTree.totalDurationInTimeRange(startTime,endTime);this._focusNodes=[];this._modifiers=[];this._repopulate();} 
static buildSortComparator(columnIdentifier,sortOrder)
{let ascending=sortOrder===WI.DataGrid.SortOrder.Ascending;return function(a,b){let result=a.data[columnIdentifier]-b.data[columnIdentifier];return ascending?result:-result;};} 
get callingContextTree(){return this._callingContextTree;}
get focusNodes()
{return this._focusNodes;}
get currentFocusNode()
{return this._focusNodes.lastValue;}
get modifiers()
{return this._modifiers;}
get startTime()
{if(this._focusNodes.length)
return this._currentFocusStartTime;return this._startTime;}
get endTime()
{if(this._focusNodes.length)
return this._currentFocusEndTime;return this._endTime;}
get totalSampleTime()
{if(this._focusNodes.length)
return this._currentFocusTotalSampleTime;return this._totalSampleTime;}
get children()
{return this._children;}
appendChild(node)
{this._children.push(node);}
insertChild(node,index)
{this._children.splice(index,0,node);}
removeChildren()
{this._children=[];}
set sortComparator(comparator)
{this._sortComparator=comparator;this.sort();}
sort()
{let children=this._children;children.sort(this._sortComparator);for(let i=0;i<children.length;++i){children[i]._recalculateSiblings(i);children[i].sort();}}
refresh()
{for(let child of this._children)
child.refreshRecursively();}
addFocusNode(profileDataGridNode)
{this._saveFocusedNodeOriginalParent(profileDataGridNode);this._focusNodes.push(profileDataGridNode);this._focusChanged();}
rollbackFocusNode(profileDataGridNode)
{let index=this._focusNodes.indexOf(profileDataGridNode);if(index===-1)
return;this._focusParentsToExpand=[];for(let i=index+1;i<this._focusNodes.length;++i)
this._restoreFocusedNodeToOriginalParent(this._focusNodes[i]);this._focusNodes.splice(index+1);this._focusChanged();}
clearFocusNodes()
{this._focusParentsToExpand=[];for(let profileDataGridNode of this._focusNodes)
this._restoreFocusedNodeToOriginalParent(profileDataGridNode);this._focusNodes=[];this._focusChanged();}
hasModifiers()
{return this._modifiers.length>0;}
addModifier(modifier)
{this._modifiers.push(modifier);this._modifiersChanged();}
clearModifiers()
{this._modifiers=[];this._modifiersChanged();} 
_repopulate()
{this.removeChildren();if(this._focusNodes.length){this.appendChild(this.currentFocusNode);}else{this._callingContextTree.forEachChild((child)=>{if(child.hasStackTraceInTimeRange(this._startTime,this._endTime))
this.appendChild(new WI.ProfileDataGridNode(child,this));});}
this.sort();}
_focusChanged()
{let profileDataGridNode=this.currentFocusNode;if(profileDataGridNode)
this._updateCurrentFocusDetails(profileDataGridNode);this._repopulate();this.dispatchEventToListeners(WI.ProfileDataGridTree.Event.FocusChanged);if(this._focusParentsToExpand){for(let profileDataGridNode of this._focusParentsToExpand)
profileDataGridNode.expand();this._focusParentsToExpand=null;}}
_updateCurrentFocusDetails(focusDataGridNode)
{let{timestamps,duration}=focusDataGridNode.callingContextTreeNode.filteredTimestampsAndDuration(this._startTime,this._endTime);this._currentFocusStartTime=timestamps[0];this._currentFocusEndTime=timestamps.lastValue;this._currentFocusTotalSampleTime=duration;}
_saveFocusedNodeOriginalParent(focusDataGridNode)
{focusDataGridNode.__previousParent=focusDataGridNode.parent;focusDataGridNode.__previousParent.removeChild(focusDataGridNode);}
_restoreFocusedNodeToOriginalParent(focusDataGridNode)
{







focusDataGridNode.__previousParent.collapse();this._focusParentsToExpand.push(focusDataGridNode.__previousParent);focusDataGridNode.__previousParent.appendChild(focusDataGridNode);focusDataGridNode.__previousParent=undefined;}
_modifiersChanged()
{this.dispatchEventToListeners(WI.ProfileDataGridTree.Event.ModifiersChanged);}};WI.ProfileDataGridTree.Event={FocusChanged:"profile-data-grid-tree-focus-changed",ModifiersChanged:"profile-data-grid-tree-modifiers-changed",};WI.ProfileDataGridTree.ModifierType={ChargeToCaller:"charge",};WI.ProfileNodeDataGridNode=class ProfileNodeDataGridNode extends WI.TimelineDataGridNode
{constructor(profileNode,options={})
{options.hasChildren=!!profileNode.childNodes.length;super(null,options);this._profileNode=profileNode;this.addEventListener(WI.DataGridNode.Event.Populate,this._populate,this);} 
get profileNode(){return this._profileNode;}
get data()
{if(this._cachedData)
return this._cachedData;let baseStartTime=0;let rangeStartTime=0;let rangeEndTime=Infinity;if(this.graphDataSource){baseStartTime=this.graphDataSource.zeroTime;rangeStartTime=this.graphDataSource.startTime;rangeEndTime=this.graphDataSource.endTime;}
let callInfo=this._profileNode.computeCallInfoForTimeRange(rangeStartTime,rangeEndTime);this._cachedData=super.data;for(let key in callInfo)
this._cachedData[key]=callInfo[key];this._cachedData.startTime-=baseStartTime;this._cachedData.name=this.displayName();this._cachedData.location=this._profileNode.sourceCodeLocation;return this._cachedData;}
createCellContent(columnIdentifier,cell)
{const higherResolution=true;var value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return value;case"startTime":case"selfTime":case"totalTime":case"averageTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);}
return super.createCellContent(columnIdentifier,cell);}
displayName()
{let title=this._profileNode.functionName;if(!title){switch(this._profileNode.type){case WI.ProfileNode.Type.Function:title=WI.UIString("(anonymous function)");break;case WI.ProfileNode.Type.Program:title=WI.UIString("(program)");break;default:title=WI.UIString("(anonymous function)");console.error("Unknown ProfileNode type: "+this._profileNode.type);}}
return title;}
iconClassNames()
{let className;switch(this._profileNode.type){case WI.ProfileNode.Type.Function:className=WI.CallFrameView.FunctionIconStyleClassName;if(!this._profileNode.sourceCodeLocation)
className=WI.CallFrameView.NativeIconStyleClassName;break;case WI.ProfileNode.Type.Program:className=WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass;break;}

if(this._profileNode.functionName&&this._profileNode.functionName.startsWith("on")&&this._profileNode.functionName.length>=5)
className=WI.CallFrameView.EventListenerIconStyleClassName;return[className];} 
_populate()
{if(!this.shouldRefreshChildren)
return;this.removeEventListener(WI.DataGridNode.Event.Populate,this._populate,this);this.removeChildren();for(let node of this._profileNode.childNodes)
this.appendChild(new WI.ProfileNodeDataGridNode(node,{graphDataSource:this.graphDataSource,}));}};WI.ProfileNodeTreeElement=class ProfileNodeTreeElement extends WI.GeneralTreeElement
{constructor(profileNode,delegate)
{var title=profileNode.functionName;var subtitle="";if(!title){switch(profileNode.type){case WI.ProfileNode.Type.Function:title=WI.UIString("(anonymous function)");break;case WI.ProfileNode.Type.Program:title=WI.UIString("(program)");break;default:title=WI.UIString("(anonymous function)");console.error("Unknown ProfileNode type: "+profileNode.type);}}
var sourceCodeLocation=profileNode.sourceCodeLocation;if(sourceCodeLocation){subtitle=document.createElement("span");sourceCodeLocation.populateLiveDisplayLocationString(subtitle,"textContent");}
var className;switch(profileNode.type){case WI.ProfileNode.Type.Function:className=WI.CallFrameView.FunctionIconStyleClassName;if(!sourceCodeLocation)
className=WI.CallFrameView.NativeIconStyleClassName;break;case WI.ProfileNode.Type.Program:className=WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass;break;}

if(profileNode.functionName&&profileNode.functionName.startsWith("on")&&profileNode.functionName.length>=5)
className=WI.CallFrameView.EventListenerIconStyleClassName;super([className],title,subtitle,profileNode,{hasChildren:!!profileNode.childNodes.length});this._profileNode=profileNode;this._delegate=delegate||null;this.shouldRefreshChildren=true;if(sourceCodeLocation)
this.tooltipHandledSeparately=true;} 
get profileNode()
{return this._profileNode;}
get filterableData()
{var url=this._profileNode.sourceCodeLocation?this._profileNode.sourceCodeLocation.sourceCode.url:"";return{text:[this.mainTitle,url||""]};} 
onattach()
{super.onattach();if(!this.tooltipHandledSeparately)
return;var tooltipPrefix=this.mainTitle+"\n";this._profileNode.sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element,tooltipPrefix);}
onpopulate()
{if(!this.hasChildren||!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();if(this._delegate&&typeof this._delegate.populateProfileNodeTreeElement==="function"){this._delegate.populateProfileNodeTreeElement(this);return;}
for(var childProfileNode of this._profileNode.childNodes){var childTreeElement=new WI.ProfileNodeTreeElement(childProfileNode);this.appendChild(childTreeElement);}}};WI.ProfileView=class ProfileView extends WI.ContentView
{constructor(callingContextTree,extraArguments)
{super(callingContextTree);this._startTime=0;this._endTime=Infinity;this._callingContextTree=callingContextTree;this._hoveredDataGridNode=null;this.element.classList.add("profile");let columns={totalTime:{title:WI.UIString("Total Time"),width:"120px",sortable:true,aligned:"right",},selfTime:{title:WI.UIString("Self Time"),width:"75px",sortable:true,aligned:"right",},function:{title:WI.UIString("Function"),disclosure:true,},};this._dataGrid=new WI.DataGrid(columns);this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._dataGridSortChanged,this);this._dataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridNodeSelected,this);this._dataGrid.addEventListener(WI.DataGrid.Event.ExpandedNode,this._dataGridNodeExpanded,this);this._dataGrid.element.addEventListener("mouseover",this._mouseOverDataGrid.bind(this));this._dataGrid.element.addEventListener("mouseleave",this._mouseLeaveDataGrid.bind(this));this._dataGrid.indentWidth=20;this._dataGrid.sortColumnIdentifier="totalTime";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Descending;this._dataGrid.createSettings("profile-view");this._selectedDataGridNode=null;
this._sharedData=extraArguments;this.addSubview(this._dataGrid);} 
get callingContextTree(){return this._callingContextTree;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get dataGrid(){return this._dataGrid;}
setStartAndEndTime(startTime,endTime)
{this._startTime=startTime;this._endTime=endTime;this._recreate();}
hasFocusNodes()
{if(!this._profileDataGridTree)
return false;return this._profileDataGridTree.focusNodes.length>0;}
clearFocusNodes()
{if(!this._profileDataGridTree)
return;this._profileDataGridTree.clearFocusNodes();}
get scrollableElements()
{return[this._dataGrid.scrollContainer];} 
get selectionPathComponents()
{let pathComponents=[];if(this._profileDataGridTree){for(let profileDataGridNode of this._profileDataGridTree.focusNodes){let displayName=profileDataGridNode.displayName();let className=profileDataGridNode.iconClassName();let pathComponent=new WI.HierarchicalPathComponent(displayName,className,profileDataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.Clicked,this._pathComponentClicked,this);pathComponents.push(pathComponent);}}
return pathComponents;} 
_recreate()
{let hadFocusNodes=this.hasFocusNodes();let sortComparator=WI.ProfileDataGridTree.buildSortComparator(this._dataGrid.sortColumnIdentifier,this._dataGrid.sortOrder);this._profileDataGridTree=new WI.ProfileDataGridTree(this._callingContextTree,this._startTime,this._endTime,sortComparator);this._profileDataGridTree.addEventListener(WI.ProfileDataGridTree.Event.FocusChanged,this._dataGridTreeFocusChanged,this);this._profileDataGridTree.addEventListener(WI.ProfileDataGridTree.Event.ModifiersChanged,this._dataGridTreeModifiersChanged,this);this._repopulateDataGridFromTree();if(hadFocusNodes)
this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_repopulateDataGridFromTree()
{this._dataGrid.removeChildren();for(let child of this._profileDataGridTree.children)
this._dataGrid.appendChild(child);this._restoreSharedState();}
_restoreSharedState()
{const skipHidden=false;const stayWithin=this._dataGrid;const dontPopulate=true;if(this._sharedData.selectedNodeHash){let nodeToSelect=this._dataGrid.findNode((node)=>node.callingContextTreeNode.hash===this._sharedData.selectedNodeHash,skipHidden,stayWithin,dontPopulate);if(nodeToSelect)
nodeToSelect.revealAndSelect();}}
_pathComponentClicked(event)
{if(!event.data.pathComponent)
return;let profileDataGridNode=event.data.pathComponent.representedObject;if(profileDataGridNode===this._profileDataGridTree.currentFocusNode)
return;this._profileDataGridTree.rollbackFocusNode(event.data.pathComponent.representedObject);}
_dataGridTreeFocusChanged(event)
{this._repopulateDataGridFromTree();this._profileDataGridTree.refresh();this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_dataGridTreeModifiersChanged(event)
{this._profileDataGridTree.refresh();}
_dataGridSortChanged()
{if(!this._profileDataGridTree)
return;this._profileDataGridTree.sortComparator=WI.ProfileDataGridTree.buildSortComparator(this._dataGrid.sortColumnIdentifier,this._dataGrid.sortOrder);this._repopulateDataGridFromTree();}
_dataGridNodeSelected(event)
{if(this._selectedDataGridNode){this._removeGuidanceElement(WI.ProfileView.GuidanceType.Selected,this._selectedDataGridNode);this._selectedDataGridNode.forEachChildInSubtree((node)=>this._removeGuidanceElement(WI.ProfileView.GuidanceType.Selected,node));}
this._selectedDataGridNode=this._dataGrid.selectedNode;if(this._selectedDataGridNode){this._removeGuidanceElement(WI.ProfileView.GuidanceType.Selected,this._selectedDataGridNode);this._selectedDataGridNode.forEachChildInSubtree((node)=>this._appendGuidanceElement(WI.ProfileView.GuidanceType.Selected,node,this._selectedDataGridNode));this._sharedData.selectedNodeHash=this._selectedDataGridNode.callingContextTreeNode.hash;}}
_dataGridNodeExpanded(event)
{let expandedNode=event.data.dataGridNode;if(this._dataGrid.selectedNode){if(expandedNode.isInSubtreeOfNode(this._dataGrid.selectedNode))
expandedNode.forEachImmediateChild((node)=>this._appendGuidanceElement(WI.ProfileView.GuidanceType.Selected,node,this._dataGrid.selectedNode));}
if(this._hoveredDataGridNode){if(expandedNode.isInSubtreeOfNode(this._hoveredDataGridNode))
expandedNode.forEachImmediateChild((node)=>this._appendGuidanceElement(WI.ProfileView.GuidanceType.Hover,node,this._hoveredDataGridNode));}}
_mouseOverDataGrid(event)
{let hoveredDataGridNode=this._dataGrid.dataGridNodeFromNode(event.target);if(hoveredDataGridNode===this._hoveredDataGridNode)
return;if(this._hoveredDataGridNode){this._removeGuidanceElement(WI.ProfileView.GuidanceType.Hover,this._hoveredDataGridNode);this._hoveredDataGridNode.forEachChildInSubtree((node)=>this._removeGuidanceElement(WI.ProfileView.GuidanceType.Hover,node));}
this._hoveredDataGridNode=hoveredDataGridNode;if(this._hoveredDataGridNode){this._appendGuidanceElement(WI.ProfileView.GuidanceType.Hover,this._hoveredDataGridNode,this._hoveredDataGridNode);this._hoveredDataGridNode.forEachChildInSubtree((node)=>this._appendGuidanceElement(WI.ProfileView.GuidanceType.Hover,node,this._hoveredDataGridNode));}}
_mouseLeaveDataGrid(event)
{if(!this._hoveredDataGridNode)
return;this._removeGuidanceElement(WI.ProfileView.GuidanceType.Hover,this._hoveredDataGridNode);this._hoveredDataGridNode.forEachChildInSubtree((node)=>this._removeGuidanceElement(WI.ProfileView.GuidanceType.Hover,node));this._hoveredDataGridNode=null;}
_guidanceElementKey(type)
{return"guidance-element-"+type;}
_removeGuidanceElement(type,node)
{let key=this._guidanceElementKey(type);let element=node.elementWithColumnIdentifier("function");if(!element||!element[key])
return;element[key].remove();element[key]=null;}
_appendGuidanceElement(type,node,baseElement)
{let depth=baseElement.depth;let guidanceMarkerLeft=depth?(depth*this._dataGrid.indentWidth)+1.5:7.5;let key=this._guidanceElementKey(type);let element=node.elementWithColumnIdentifier("function");let guidanceElement=element[key]||element.appendChild(document.createElement("div"));element[key]=guidanceElement;guidanceElement.classList.add("guidance",type);guidanceElement.classList.toggle("base",node===baseElement);guidanceElement.style.left=guidanceMarkerLeft+"px";}};WI.ProfileView.GuidanceType={Selected:"selected",Hover:"hover",};WI.ProgressView=class ProgressView extends WI.View
{constructor(title,subtitle)
{super();this.element.classList.add("progress-view");this._title=title||"";this._subtitle=subtitle||"";this._titlesElement=null;this._titleElement=null;this._subtitleElement=null;} 
get title()
{return this._title;}
set title(title)
{title=title||"";if(this._title===title)
return;this._title=title;this._updateTitles();}
get subtitle()
{return this._subtitle;}
set subtitle(subtitle)
{subtitle=subtitle||"";if(this._subtitle===subtitle)
return;this._subtitle=subtitle;this._updateTitles();}
get visible(){return this._visible;}
set visible(x)
{if(this._visible===x)
return;this._visible=x;this.element.classList.toggle("hidden",!this._visible);} 
initialLayout()
{super.initialLayout();this._titlesElement=this.element.appendChild(document.createElement("div"));this._titlesElement.className="titles";this._titleElement=this._titlesElement.appendChild(document.createElement("span"));this._titleElement.className="title";this._subtitleElement=this._titlesElement.appendChild(document.createElement("span"));this._subtitleElement.className="subtitle";let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._updateTitles();}
_updateTitles()
{if(!this._titlesElement)
return;this._titleElement.textContent=this._title;this._titleElement.classList.toggle("hidden",!this._title);this._subtitleElement.textContent=this._subtitle;this._subtitleElement.classList.toggle("hidden",!this._subtitle);}};WI.QuickConsole=class QuickConsole extends WI.View
{constructor(element)
{super(element);this._toggleOrFocusKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape,this._toggleOrFocus.bind(this));this._toggleOrFocusKeyboardShortcut.implicitlyPreventsDefault=false;this._keyboardShortcutDisabled=false;this._useExecutionContextOfInspectedNode=InspectorBackend.hasDomain("DOM");this._restoreSelectedExecutionContextForFrame=null;this.element.classList.add("quick-console");this.element.addEventListener("mousedown",this._handleMouseDown.bind(this));this.element.addEventListener("dragover",this._handleDragOver.bind(this));this.element.addEventListener("drop",this._handleDrop.bind(this),true);this.prompt=new WI.ConsolePrompt(null,"text/javascript");this.addSubview(this.prompt);


this.prompt.escapeKeyHandlerWhenEmpty=function(){WI.toggleSplitConsole();};const navigationbarElement=null;this._navigationBar=new WI.NavigationBar(navigationbarElement,{sizesToFit:true});this.addSubview(this._navigationBar);this._activeExecutionContextNavigationItemDivider=new WI.DividerNavigationItem;this._navigationBar.addNavigationItem(this._activeExecutionContextNavigationItemDivider);this._activeExecutionContextNavigationItem=new WI.NavigationItem("active-execution-context");WI.addMouseDownContextMenuHandlers(this._activeExecutionContextNavigationItem.element,this._populateActiveExecutionContextNavigationItemContextMenu.bind(this));this._navigationBar.addNavigationItem(this._activeExecutionContextNavigationItem);this._updateActiveExecutionContextDisplay();WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,this._handleConsoleSavedResultAliasSettingChanged,this);WI.settings.engineeringShowInternalExecutionContexts.addEventListener(WI.Setting.Event.Changed,this._handleEngineeringShowInternalExecutionContextsSettingChanged,this);WI.Frame.addEventListener(WI.Frame.Event.PageExecutionContextChanged,this._handleFramePageExecutionContextChanged,this);WI.Frame.addEventListener(WI.Frame.Event.ExecutionContextsCleared,this._handleFrameExecutionContextsCleared,this);WI.Frame.addEventListener(WI.Frame.Event.ExecutionContextAdded,this._handleFrameExecutionContextAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.runtimeManager.addEventListener(WI.RuntimeManager.Event.ActiveExecutionContextChanged,this._handleActiveExecutionContextChanged,this);WI.notifications.addEventListener(WI.Notification.TransitionPageTarget,this._handleTransitionPageTarget,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this);WI.domManager.addEventListener(WI.DOMManager.Event.InspectedNodeChanged,this._handleInspectedNodeChanged,this);WI.consoleDrawer.toggleButtonShortcutTooltip(this._toggleOrFocusKeyboardShortcut);WI.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged,this._updateStyles,this);WI.TabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._updateStyles,this);WI.whenTargetsAvailable().then(()=>{this._updateActiveExecutionContextDisplay();});} 
set keyboardShortcutDisabled(disabled)
{this._keyboardShortcutDisabled=disabled;}
closed()
{WI.settings.consoleSavedResultAlias.removeEventListener(WI.Setting.Event.Changed,this._handleConsoleSavedResultAliasSettingChanged,this);WI.settings.engineeringShowInternalExecutionContexts.removeEventListener(WI.Setting.Event.Changed,this._handleEngineeringShowInternalExecutionContextsSettingChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.PageExecutionContextChanged,this._handleFramePageExecutionContextChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.ExecutionContextsCleared,this._handleFrameExecutionContextsCleared,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.runtimeManager.removeEventListener(WI.RuntimeManager.Event.ActiveExecutionContextChanged,this._handleActiveExecutionContextChanged,this);WI.notifications.removeEventListener(WI.Notification.TransitionPageTarget,this._handleTransitionPageTarget,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this);WI.domManager.removeEventListener(WI.DOMManager.Event.InspectedNodeChanged,this._handleInspectedNodeChanged,this);WI.consoleDrawer.removeEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged,this._updateStyles,this);WI.TabBrowser.removeEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._updateStyles,this);super.closed();} 
_displayNameForExecutionContext(context,maxLength=Infinity)
{function truncate(string,length){if(!Number.isFinite(maxLength))
return string;return string.trim().truncateMiddle(length);}
if(context.type===WI.ExecutionContext.Type.Internal)
return WI.unlocalizedString("[Internal] ")+context.name;if(context.type===WI.ExecutionContext.Type.User){let extensionName=WI.browserManager.extensionNameForExecutionContext(context);if(extensionName)
return truncate(extensionName,maxLength);}
let target=context.target;if(target.type===WI.TargetType.Worker)
return truncate(target.displayName,maxLength);let frame=context.frame;if(frame){if(context===frame.executionContextList.pageExecutionContext){let resourceName=frame.mainResource.displayName;let frameName=frame.name;if(frameName){
let frameNameMaxLength=Math.max(maxLength-resourceName.length,20);return WI.UIString("%s (%s)").format(truncate(frameName,frameNameMaxLength),truncate(resourceName,maxLength-frameNameMaxLength));}
return truncate(resourceName,maxLength);}}
return truncate(context.name,maxLength);}
_resolveDesiredActiveExecutionContext(forceInspectedNode)
{let executionContext=null;if(this._useExecutionContextOfInspectedNode||forceInspectedNode){let inspectedNode=WI.domManager.inspectedNode;if(inspectedNode){let frame=inspectedNode.frame;if(frame){let pageExecutionContext=frame.pageExecutionContext;if(pageExecutionContext)
executionContext=pageExecutionContext;}}}
if(!executionContext&&WI.networkManager.mainFrame)
executionContext=WI.networkManager.mainFrame.pageExecutionContext;return executionContext||WI.mainTarget.executionContext;}
_setActiveExecutionContext(context)
{let wasActive=WI.runtimeManager.activeExecutionContext===context;WI.runtimeManager.activeExecutionContext=context;if(wasActive)
this._updateActiveExecutionContextDisplay();}
_updateActiveExecutionContextDisplay()
{let toggleHidden=(hidden)=>{this._activeExecutionContextNavigationItemDivider.hidden=hidden;this._activeExecutionContextNavigationItem.hidden=hidden;};if(WI.debuggerManager.activeCallFrame){toggleHidden(true);return;}
if(!WI.runtimeManager.activeExecutionContext||!WI.networkManager.mainFrame){toggleHidden(true);return;}
if(WI.networkManager.frames.length===1&&!WI.targetManager.workerTargets.length){let mainFrameContexts=WI.networkManager.mainFrame.executionContextList.contexts;let contextsToShow=mainFrameContexts.filter((context)=>context.type!==WI.ExecutionContext.Type.Internal||WI.settings.engineeringShowInternalExecutionContexts.value);if(contextsToShow.length<=1){toggleHidden(true);return;}}
const maxLength=40;if(this._useExecutionContextOfInspectedNode){this._activeExecutionContextNavigationItem.element.classList.add("automatic");this._activeExecutionContextNavigationItem.element.textContent=WI.UIString("Auto \u2014 %s").format(this._displayNameForExecutionContext(WI.runtimeManager.activeExecutionContext,maxLength));this._activeExecutionContextNavigationItem.tooltip=WI.UIString("Execution context for %s").format(WI.RuntimeManager.preferredSavedResultPrefix()+"0");}else{this._activeExecutionContextNavigationItem.element.classList.remove("automatic");this._activeExecutionContextNavigationItem.element.textContent=this._displayNameForExecutionContext(WI.runtimeManager.activeExecutionContext,maxLength);this._activeExecutionContextNavigationItem.tooltip=this._displayNameForExecutionContext(WI.runtimeManager.activeExecutionContext);}
this._activeExecutionContextNavigationItem.element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/UpDownArrows.svg","selector-arrows"));toggleHidden(false);}
_populateActiveExecutionContextNavigationItemContextMenu(contextMenu)
{const maxLength=120;let activeExecutionContext=WI.runtimeManager.activeExecutionContext;if(InspectorBackend.hasDomain("DOM")){let executionContextForInspectedNode=this._resolveDesiredActiveExecutionContext(true);contextMenu.appendCheckboxItem(WI.UIString("Auto \u2014 %s").format(this._displayNameForExecutionContext(executionContextForInspectedNode,maxLength)),()=>{this._useExecutionContextOfInspectedNode=true;this._setActiveExecutionContext(executionContextForInspectedNode);},this._useExecutionContextOfInspectedNode);contextMenu.appendSeparator();}
let indent=0;let addExecutionContext=(context)=>{if(context.type===WI.ExecutionContext.Type.Internal&&!WI.settings.engineeringShowInternalExecutionContexts.value)
return;let additionalIndent=(context.frame&&context!==context.frame.executionContextList.pageExecutionContext)||context.type!==WI.ExecutionContext.Type.Normal;contextMenu.appendCheckboxItem("   ".repeat(indent+additionalIndent)+this._displayNameForExecutionContext(context,maxLength),()=>{this._useExecutionContextOfInspectedNode=false;this._setActiveExecutionContext(context);},activeExecutionContext===context);};let addExecutionContextsForFrame=(frame)=>{let pageExecutionContext=frame.executionContextList.pageExecutionContext;let contexts=frame.executionContextList.contexts.sort((a,b)=>{if(a===pageExecutionContext)
return-1;if(b===pageExecutionContext)
return 1;const executionContextTypeRanking=[WI.ExecutionContext.Type.Normal,WI.ExecutionContext.Type.User,WI.ExecutionContext.Type.Internal,];return executionContextTypeRanking.indexOf(a.type)-executionContextTypeRanking.indexOf(b.type);});for(let context of contexts)
addExecutionContext(context);};let mainFrame=WI.networkManager.mainFrame;addExecutionContextsForFrame(mainFrame);indent=1;let otherFrames=WI.networkManager.frames.filter((frame)=>frame!==mainFrame&&frame.executionContextList.pageExecutionContext);if(otherFrames.length){contextMenu.appendHeader(WI.UIString("Frames","Frames @ Execution Context Picker","Title for list of HTML subframe JavaScript execution contexts"));for(let frame of otherFrames)
addExecutionContextsForFrame(frame);}
let workerTargets=WI.targetManager.workerTargets;if(workerTargets.length){contextMenu.appendHeader(WI.UIString("Workers","Workers @ Execution Context Picker","Title for list of JavaScript web worker execution contexts"));for(let target of workerTargets)
addExecutionContext(target.executionContext);}}
_handleMouseDown(event)
{if(event.target!==this.element)
return;event.preventDefault();this.prompt.focus();}
_handleDragOver(event)
{if(event.dataTransfer.types.includes(WI.DOMTreeOutline.DOMNodeIdDragType)){event.preventDefault();event.dataTransfer.dropEffect="copy";}}
_handleDrop(event)
{let domNodeId=event.dataTransfer.getData(WI.DOMTreeOutline.DOMNodeIdDragType);if(domNodeId){event.preventDefault();let domNode=WI.domManager.nodeForId(domNodeId);WI.RemoteObject.resolveNode(domNode,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{let text=domNode.nodeType()===Node.ELEMENT_NODE?WI.UIString("Dropped Element"):WI.UIString("Dropped Node");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);this.prompt.focus();});}}
_handleConsoleSavedResultAliasSettingChanged()
{this._updateActiveExecutionContextDisplay();}
_handleEngineeringShowInternalExecutionContextsSettingChanged(event)
{this._updateActiveExecutionContextDisplay();if(WI.runtimeManager.activeExecutionContext.type!==WI.ExecutionContext.Type.Internal)
return;this._useExecutionContextOfInspectedNode=InspectorBackend.hasDomain("DOM");this._setActiveExecutionContext(this._resolveDesiredActiveExecutionContext());}
_handleFramePageExecutionContextChanged(event)
{let frame=event.target;if(this._restoreSelectedExecutionContextForFrame!==frame)
return;this._restoreSelectedExecutionContextForFrame=null;this._useExecutionContextOfInspectedNode=false;this._setActiveExecutionContext(frame.pageExecutionContext);}
_handleFrameExecutionContextAdded(event)
{this._updateActiveExecutionContextDisplay();}
_handleFrameExecutionContextsCleared(event)
{let{committingProvisionalLoad,contexts}=event.data;let hasActiveExecutionContext=contexts.some((context)=>context===WI.runtimeManager.activeExecutionContext);if(!hasActiveExecutionContext){this._updateActiveExecutionContextDisplay();return;}
if(committingProvisionalLoad&&!this._restoreSelectedExecutionContextForFrame){this._restoreSelectedExecutionContextForFrame=event.target;setTimeout(()=>{if(this._restoreSelectedExecutionContextForFrame)
this._updateActiveExecutionContextDisplay();this._restoreSelectedExecutionContextForFrame=null;},10);return;}
this._useExecutionContextOfInspectedNode=InspectorBackend.hasDomain("DOM");this._setActiveExecutionContext(this._resolveDesiredActiveExecutionContext());}
_handleDebuggerActiveCallFrameDidChange(event)
{this._updateActiveExecutionContextDisplay();}
_handleActiveExecutionContextChanged(event)
{this._updateActiveExecutionContextDisplay();}
_handleTransitionPageTarget()
{this._updateActiveExecutionContextDisplay();}
_handleTargetRemoved(event)
{let{target}=event.data;if(target!==WI.runtimeManager.activeExecutionContext){this._updateActiveExecutionContextDisplay();return;}
this._useExecutionContextOfInspectedNode=InspectorBackend.hasDomain("DOM");this._setActiveExecutionContext(this._resolveDesiredActiveExecutionContext());}
_handleInspectedNodeChanged(event)
{if(!this._useExecutionContextOfInspectedNode)
return;this._setActiveExecutionContext(this._resolveDesiredActiveExecutionContext());}
_toggleOrFocus(event)
{if(this._keyboardShortcutDisabled)
return;if(this.prompt.focused){WI.toggleSplitConsole();event.preventDefault();}else if(!WI.isEditingAnyField()&&!WI.isEventTargetAnEditableField(event)){this.prompt.focus();event.preventDefault();}}
_updateStyles()
{this.element.classList.toggle("showing-log",WI.isShowingConsoleTab()||WI.isShowingSplitConsole());}};WI.RadioButtonNavigationItem=class RadioButtonNavigationItem extends WI.ButtonNavigationItem
{constructor(identifier,toolTip,image,imageWidth,imageHeight)
{super(identifier,toolTip,image,imageWidth,imageHeight,"tab");} 
get selected()
{return this.element.classList.contains(WI.RadioButtonNavigationItem.SelectedStyleClassName);}
set selected(flag)
{if(flag){this.element.classList.add(WI.RadioButtonNavigationItem.SelectedStyleClassName);this.element.setAttribute("aria-selected","true");this.element.tabIndex=0;}else{this.element.classList.remove(WI.RadioButtonNavigationItem.SelectedStyleClassName);this.element.setAttribute("aria-selected","false");this.element.tabIndex=-1;}}
get active()
{return this.element.classList.contains(WI.RadioButtonNavigationItem.ActiveStyleClassName);}
set active(flag)
{this.element.classList.toggle(WI.RadioButtonNavigationItem.ActiveStyleClassName,flag);}
get buttonStyle()
{return super.buttonStyle;}
set buttonStyle(newButtonStyle)
{if(newButtonStyle!==WI.ButtonNavigationItem.Style.Text)
return;super.buttonStyle=newButtonStyle;} 
get additionalClassNames()
{return["radio","button"];}
get tabbable()
{return this.selected;}};WI.RadioButtonNavigationItem.StyleClassName="radio";WI.RadioButtonNavigationItem.ActiveStyleClassName="active";WI.RadioButtonNavigationItem.SelectedStyleClassName="selected";

WI.RangeChart=class RangeChart extends WI.View
{constructor()
{super();this.element.classList.add("range-chart");this._svgElement=this.element.appendChild(createSVGElement("svg"));this._svgElement.setAttribute("preserveAspectRatio","none");this._ranges=[];this._size=null;} 
get size()
{return this._size;}
set size(size)
{if(this._size&&this._size.equals(size))
return;this._size=size;this._svgElement.setAttribute("viewBox",`0 0 ${size.width} ${size.height}`);}
addRange(x,width,className)
{this._ranges.push({x,width,className});}
clear()
{this._ranges=[];} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;if(!this._size)
return;this._svgElement.removeChildren();let height=this.size.height;for(let{x,width,className}of this._ranges){let rect=this._svgElement.appendChild(createSVGElement("rect"));rect.setAttribute("width",width);rect.setAttribute("height",height);rect.setAttribute("x",x);rect.classList.add(className);}}};WI.RecordingActionTreeElement=class RecordingActionTreeElement extends WI.GeneralTreeElement
{constructor(representedObject,index,recordingType)
{let{titleFragment,copyText}=WI.RecordingActionTreeElement._generateDOM(representedObject,recordingType);let classNames=WI.RecordingActionTreeElement._getClassNames(representedObject);const subtitle=null;super(classNames,titleFragment,subtitle,representedObject);this._index=index;this._copyText=copyText;if(this.representedObject.valid)
this.representedObject.singleFireEventListener(WI.RecordingAction.Event.ValidityChanged,this._handleValidityChanged,this);} 
static _generateDOM(recordingAction,recordingType)
{let parameterCount=recordingAction.parameters.length;function createParameterElement(parameter,swizzleType,index){let parameterElement=document.createElement("span");parameterElement.classList.add("parameter");switch(swizzleType){case WI.Recording.Swizzle.Number:var constantNameForParameter=WI.RecordingAction.constantNameForParameter(recordingType,recordingAction.name,parameter,index,parameterCount);if(constantNameForParameter){parameterElement.classList.add("constant");parameterElement.textContent="context."+constantNameForParameter;}else
parameterElement.textContent=parameter.maxDecimals(2);break;case WI.Recording.Swizzle.Boolean:parameterElement.textContent=parameter;break;case WI.Recording.Swizzle.String:parameterElement.textContent=JSON.stringify(parameter);break;case WI.Recording.Swizzle.Array:parameterElement.classList.add("swizzled");parameterElement.textContent=JSON.stringify(parameter);break;case WI.Recording.Swizzle.TypedArray:case WI.Recording.Swizzle.Image:case WI.Recording.Swizzle.ImageBitmap:case WI.Recording.Swizzle.ImageData:case WI.Recording.Swizzle.DOMMatrix:case WI.Recording.Swizzle.Path2D:case WI.Recording.Swizzle.CanvasGradient:case WI.Recording.Swizzle.CanvasPattern:case WI.Recording.Swizzle.WebGLBuffer:case WI.Recording.Swizzle.WebGLFramebuffer:case WI.Recording.Swizzle.WebGLRenderbuffer:case WI.Recording.Swizzle.WebGLTexture:case WI.Recording.Swizzle.WebGLShader:case WI.Recording.Swizzle.WebGLProgram:case WI.Recording.Swizzle.WebGLUniformLocation:case WI.Recording.Swizzle.WebGLQuery:case WI.Recording.Swizzle.WebGLSampler:case WI.Recording.Swizzle.WebGLSync:case WI.Recording.Swizzle.WebGLTransformFeedback:case WI.Recording.Swizzle.WebGLVertexArrayObject:parameterElement.classList.add("swizzled");parameterElement.textContent=WI.Recording.displayNameForSwizzleType(swizzleType);break;}
if(!parameterElement.textContent){parameterElement.classList.add("invalid");parameterElement.textContent=swizzleType===WI.Recording.Swizzle.None?parameter:WI.Recording.displayNameForSwizzleType(swizzleType);}
return parameterElement;}
let titleFragment=document.createDocumentFragment();let copyText=recordingAction.name;let contextReplacer=recordingAction.contextReplacer;if(contextReplacer){copyText=contextReplacer+"."+copyText;let contextReplacerContainer=titleFragment.appendChild(document.createElement("span"));contextReplacerContainer.classList.add("context-replacer");contextReplacerContainer.textContent=contextReplacer;}
let nameContainer=titleFragment.appendChild(document.createElement("span"));nameContainer.classList.add("name");nameContainer.textContent=recordingAction.name;if(!parameterCount)
return{titleFragment,copyText};let parametersContainer=titleFragment.appendChild(document.createElement("span"));parametersContainer.classList.add("parameters");if(recordingAction.isFunction)
copyText+="(";else
copyText+=" = ";for(let i=0;i<parameterCount;++i){let parameter=recordingAction.parameters[i];let swizzleType=recordingAction.swizzleTypes[i];let parameterElement=createParameterElement(parameter,swizzleType,i);parametersContainer.appendChild(parameterElement);if(i)
copyText+=", ";copyText+=parameterElement.textContent;}
if(recordingAction.isFunction)
copyText+=")";let colorParameters=recordingAction.getColorParameters();if(colorParameters.length){let swatch=WI.RecordingActionTreeElement._createSwatchForColorParameters(colorParameters);if(swatch){let insertionIndex=recordingAction.parameters.indexOf(colorParameters[0]);parametersContainer.insertBefore(swatch.element,parametersContainer.children[insertionIndex]);}}
let imageParameters=recordingAction.getImageParameters();let isImage=imageParameters[0]instanceof HTMLImageElement;let isImageBitmap=imageParameters[0]instanceof ImageBitmap;let isImageData=imageParameters[0]instanceof ImageData;let isCanvasGradient=imageParameters[0]instanceof CanvasGradient;let isCanvasPattern=imageParameters[0]instanceof CanvasPattern;if(imageParameters.length&&(isImage||isImageBitmap||isImageData||isCanvasGradient||isCanvasPattern)){let image=imageParameters[0];if(isImageBitmap)
image=WI.ImageUtilities.imageFromImageBitmap(image);else if(isImageData)
image=WI.ImageUtilities.imageFromImageData(image);else if(isCanvasGradient)
image=WI.ImageUtilities.imageFromCanvasGradient(image,100,100);else if(isCanvasPattern)
image=image.__image;if(image){let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Image,image);let insertionIndex=recordingAction.parameters.indexOf(imageParameters[0]);let parameterElement=parametersContainer.children[insertionIndex];parametersContainer.insertBefore(swatch.element,parameterElement);}}
return{titleFragment,copyText};}
static _createSwatchForColorParameters(parameters)
{let rgb=[];let color=null;switch(parameters.length){case 1:case 2:if(typeof parameters[0]==="string")
color=WI.Color.fromString(parameters[0].trim());else if(!isNaN(parameters[0]))
rgb=WI.Color.normalized2rgb(parameters[0],parameters[0],parameters[0]);break;case 4:rgb=WI.Color.normalized2rgb(parameters[0],parameters[1],parameters[2]);break;case 5:rgb=WI.Color.cmyk2rgb(...parameters);break;default:console.error("Unexpected number of color parameters.");return null;}
if(!color){if(rgb.length!==3)
return null;let alpha=parameters.length===1?1:parameters.lastValue;color=new WI.Color(WI.Color.Format.RGBA,[...rgb,alpha]);if(!color)
return null;}
const readOnly=true;return new WI.InlineSwatch(WI.InlineSwatch.Type.Color,color,readOnly);}
static _getClassNames(recordingAction)
{let classNames=["recording-action"];if(recordingAction instanceof WI.RecordingInitialStateAction){classNames.push("initial-state");return classNames;}
if(!recordingAction.isFunction)
classNames.push("attribute");let actionClassName=WI.RecordingActionTreeElement._classNameForAction(recordingAction);if(actionClassName.length)
classNames.push(actionClassName);if(recordingAction.isVisual)
classNames.push("visual");if(!recordingAction.valid)
classNames.push("invalid");return classNames;}
static _classNameForAction(recordingAction)
{if(recordingAction.contextReplacer)
return"has-context-replacer";switch(recordingAction.name){case"arc":case"arcTo":return"arc";case"globalAlpha":case"globalCompositeOperation":case"setAlpha":case"setGlobalAlpha":case"setCompositeOperation":case"setGlobalCompositeOperation":return"composite";case"bezierCurveTo":case"quadraticCurveTo":return"curve";case"clearRect":case"fill":case"fillRect":case"fillText":return"fill";case"createImageData":case"drawFocusIfNeeded":case"drawImage":case"drawImageFromRect":case"filter":case"getImageData":case"imageSmoothingEnabled":case"imageSmoothingQuality":case"putImageData":case"transferFromImageBitmap":case"webkitImageSmoothingEnabled":return"image";case"getLineDash":case"lineCap":case"lineDashOffset":case"lineJoin":case"lineWidth":case"miterLimit":case"setLineCap":case"setLineDash":case"setLineJoin":case"setLineWidth":case"setMiterLimit":case"webkitLineDash":case"webkitLineDashOffset":return"line-style";case"closePath":case"lineTo":return"line-to";case"beginPath":case"moveTo":return"move-to";case"isPointInPath":return"point-in-path";case"isPointInStroke":return"point-in-stroke";case"clearShadow":case"setShadow":case"shadowBlur":case"shadowColor":case"shadowOffsetX":case"shadowOffsetY":return"shadow";case"createConicGradient":case"createLinearGradient":case"createPattern":case"createRadialGradient":case"fillStyle":case"setFillColor":case"setStrokeColor":case"strokeStyle":return"style";case"stroke":case"strokeRect":case"strokeText":return"stroke";case"direction":case"font":case"measureText":case"textAlign":case"textBaseline":return"text";case"getTransform":case"resetTransform":case"rotate":case"scale":case"setTransform":case"transform":case"translate":return"transform";case"clip":case"ellipse":case"rect":case"restore":case"save":return recordingAction.name;}
return"name-unknown";} 
get index(){return this._index;}
get filterableData()
{let text=[];function getText(stringOrElement){if(typeof stringOrElement==="string")
text.push(stringOrElement);else if(stringOrElement instanceof Node)
text.push(stringOrElement.textContent);}
getText(this._mainTitleElement||this._mainTitle);getText(this._subtitleElement||this._subtitle);return{text};} 
customTitleTooltip()
{return this._copyText;}
onattach()
{super.onattach();this.element.dataset.index=this._index.toLocaleString();if(this.representedObject.valid&&this.representedObject.warning){this.addClassName("warning");this.status=WI.ImageUtilities.useSVGSymbol("Images/Warning.svg","warning",this.representedObject.warning);}}
populateContextMenu(contextMenu,event)
{contextMenu.appendItem(WI.UIString("Copy Action"),()=>{InspectorFrontendHost.copyText("context."+this._copyText+";");});contextMenu.appendSeparator();let sourceCodeLocation=null;for(let callFrame of this.representedObject.trace){if(callFrame.sourceCodeLocation){sourceCodeLocation=callFrame.sourceCodeLocation;break;}}
if(sourceCodeLocation){contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showSourceCodeLocation(sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});contextMenu.appendSeparator();}
super.populateContextMenu(contextMenu,event);} 
_handleValidityChanged(event)
{this.addClassName("invalid");}};WI.RecordingContentView=class RecordingContentView extends WI.ContentView
{constructor(representedObject)
{super(representedObject);let isCanvas2D=this.representedObject.type===WI.Recording.Type.Canvas2D;let isCanvasBitmapRenderer=this.representedObject.type===WI.Recording.Type.CanvasBitmapRenderer;let isCanvasWebGL=this.representedObject.type===WI.Recording.Type.CanvasWebGL;let isCanvasWebGL2=this.representedObject.type===WI.Recording.Type.CanvasWebGL2;this._index=NaN;this._action=null;this._snapshots=[];this._initialContent=null;this._generateContentThrottler=new Throttler(()=>{if(isCanvas2D)
this._generateContentCanvas2D(this._index);else if(isCanvasBitmapRenderer||isCanvasWebGL||isCanvasWebGL2)
this._generateContentFromSnapshot(this._index);},200);this.element.classList.add("recording",this.representedObject.type);if(isCanvas2D||isCanvasBitmapRenderer||isCanvasWebGL||isCanvasWebGL2){if(isCanvas2D&&WI.ImageUtilities.supportsCanvasPathDebugging()){this._pathContext=null;this._showPathButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-path",WI.UIString("Show Path"),WI.UIString("Hide Path"),"Images/Path.svg",16,16);this._showPathButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showPathButtonClicked,this);this._showPathButtonNavigationItem.activated=!!WI.settings.showCanvasPath.value;}
this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showGridButtonClicked,this);this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;this._exportButtonNavigationItem=new WI.ButtonNavigationItem("export-recording",WI.UIString("Export"),"Images/Export.svg",15,15);this._exportButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._exportButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportNavigationItemClicked,this);this._updateExportButton();}} 
get navigationItems()
{let isCanvas2D=this.representedObject.type===WI.Recording.Type.Canvas2D;let isCanvasBitmapRenderer=this.representedObject.type===WI.Recording.Type.CanvasBitmapRenderer;let isCanvasWebGL=this.representedObject.type===WI.Recording.Type.CanvasWebGL;let isCanvasWebGL2=this.representedObject.type===WI.Recording.Type.CanvasWebGL2;if(!isCanvas2D&&!isCanvasBitmapRenderer&&!isCanvasWebGL&&!isCanvasWebGL2)
return[];let navigationItems=[this._exportButtonNavigationItem,new WI.DividerNavigationItem];if(isCanvas2D&&WI.ImageUtilities.supportsCanvasPathDebugging())
navigationItems.push(this._showPathButtonNavigationItem);navigationItems.push(this._showGridButtonNavigationItem);return navigationItems;}
get supplementalRepresentedObjects()
{return this._action?[this._action]:[];}
updateActionIndex(index)
{if(!this.representedObject)
return;if(this._index===index)
return;if(index<0||index>=this.representedObject.actions.length)
return;this._index=index;this._updateSliderValue();if(this.didInitialLayout)
this._generateContentThrottler.fire();this._action=this.representedObject.actions[this._index];this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
attached()
{super.attached();let isCanvas2D=this.representedObject.type===WI.Recording.Type.Canvas2D;let isCanvasBitmapRenderer=this.representedObject.type===WI.Recording.Type.CanvasBitmapRenderer;let isCanvasWebGL=this.representedObject.type===WI.Recording.Type.CanvasWebGL;let isCanvasWebGL2=this.representedObject.type===WI.Recording.Type.CanvasWebGL2;if(isCanvas2D||isCanvasBitmapRenderer||isCanvasWebGL||isCanvasWebGL2){if(isCanvas2D&&WI.ImageUtilities.supportsCanvasPathDebugging())
this._updateCanvasPath();this._updateImageGrid();}}
detached()
{this._generateContentThrottler.cancel();super.detached();} 
get supportsSave()
{return true;}
get saveData()
{return{customSaveHandler:()=>{this._exportRecording();}};}
initialLayout()
{let previewHeader=this.element.appendChild(document.createElement("header"));let sliderContainer=previewHeader.appendChild(document.createElement("div"));sliderContainer.className="slider-container";this._previewContainer=this.element.appendChild(document.createElement("div"));this._previewContainer.className="preview-container";this._sliderValueElement=sliderContainer.appendChild(document.createElement("div"));this._sliderValueElement.className="slider-value";this._sliderElement=sliderContainer.appendChild(document.createElement("input"));this._sliderElement.addEventListener("input",this._sliderChanged.bind(this));this._sliderElement.type="range";this._sliderElement.min=0;this._sliderElement.max=0;if(!this.representedObject.ready){this.representedObject.addEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);if(!this.representedObject.processing)
this.representedObject.startProcessing();}
this._updateSliderValue();if(!isNaN(this._index))
this._generateContentThrottler.fire();} 
_exportRecording()
{let filename=this.representedObject.displayName;WI.FileUtilities.save({content:JSON.stringify(this.representedObject.toJSON()),suggestedName:filename+".json",forceSaveAs:true,});}
_exportReduction()
{if(!this.representedObject.ready){InspectorFrontendHost.beep();return;}
let filename=this.representedObject.displayName;WI.FileUtilities.save({content:this.representedObject.toHTML(),suggestedName:filename+".html",forceSaveAs:true,});}
_generateContentCanvas2D(index)
{let imageLoad=(event)=>{if(index!==this._index)
return;this._generateContentCanvas2D(index);};let initialState=this.representedObject.initialState;if(initialState.content&&!this._initialContent){this._initialContent=new Image;this._initialContent.src=initialState.content;this._initialContent.addEventListener("load",imageLoad);return;}
let snapshotIndex=Math.floor(index/WI.RecordingContentView.SnapshotInterval);let snapshot=this._snapshots[snapshotIndex];let showCanvasPath=WI.ImageUtilities.supportsCanvasPathDebugging()&&WI.settings.showCanvasPath.value;let indexOfLastBeginPathAction=Infinity;let actions=this.representedObject.actions;let applyActions=(from,to,callback)=>{let saveCount=0;snapshot.context.save();for(let attribute in snapshot.attributes)
snapshot.element[attribute]=snapshot.attributes[attribute];if(snapshot.content){snapshot.context.clearRect(0,0,snapshot.element.width,snapshot.element.height);snapshot.context.drawImage(snapshot.content,0,0);}
for(let state of snapshot.states){state.apply(this.representedObject.type,snapshot.context);++saveCount;snapshot.context.save();}
let lastPathPoint={};let subPathStartPoint={};for(let i=from;i<=to;++i){if(actions[i].name==="save")
++saveCount;else if(actions[i].name==="restore"){if(!saveCount)
continue;}
actions[i].apply(snapshot.context);}
if(showCanvasPath&&indexOfLastBeginPathAction<=to){if(!this._pathContext){let pathCanvas=document.createElement("canvas");pathCanvas.classList.add("path");this._pathContext=pathCanvas.getContext("2d");}
this._pathContext.canvas.width=snapshot.element.width;this._pathContext.canvas.height=snapshot.element.height;this._pathContext.clearRect(0,0,snapshot.element.width,snapshot.element.height);this._pathContext.save();this._pathContext.fillStyle="hsla(0, 0%, 100%, 0.75)";this._pathContext.fillRect(0,0,snapshot.element.width,snapshot.element.height);function actionModifiesPath(action){switch(action.name){case"arc":case"arcTo":case"beginPath":case"bezierCurveTo":case"closePath":case"ellipse":case"lineTo":case"moveTo":case"quadraticCurveTo":case"rect":return true;}
return false;}
for(let i=indexOfLastBeginPathAction;i<=to;++i){if(!actionModifiesPath(actions[i]))
continue;lastPathPoint={x:this._pathContext.currentX,y:this._pathContext.currentY};if(i===indexOfLastBeginPathAction)
this._pathContext.setTransform(snapshot.context.getTransform());let isMoveTo=actions[i].name==="moveTo";this._pathContext.lineWidth=isMoveTo?0.5:1;this._pathContext.setLineDash(isMoveTo?[5,5]:[]);this._pathContext.strokeStyle=i===to?"red":"black";this._pathContext.beginPath();if(!isEmptyObject(lastPathPoint))
this._pathContext.moveTo(lastPathPoint.x,lastPathPoint.y);if(actions[i].name==="closePath"&&!isEmptyObject(subPathStartPoint)){this._pathContext.lineTo(subPathStartPoint.x,subPathStartPoint.y);subPathStartPoint={};}else{actions[i].apply(this._pathContext,{nameOverride:isMoveTo?"lineTo":null});if(isMoveTo)
subPathStartPoint={x:this._pathContext.currentX,y:this._pathContext.currentY};}
this._pathContext.stroke();}
this._pathContext.restore();this._previewContainer.appendChild(this._pathContext.canvas);}else if(this._pathContext)
this._pathContext.canvas.remove();snapshot.context.restore();while(saveCount-->0)
snapshot.context.restore();};if(!snapshot){snapshot=this._snapshots[snapshotIndex]={};snapshot.index=snapshotIndex*WI.RecordingContentView.SnapshotInterval;while(snapshot.index&&actions[snapshot.index].name!=="beginPath")
--snapshot.index;snapshot.context=this.representedObject.createContext();snapshot.element=snapshot.context.canvas;let lastSnapshotIndex=snapshotIndex;while(--lastSnapshotIndex>=0){if(this._snapshots[lastSnapshotIndex])
break;}
let startIndex=0;if(lastSnapshotIndex<0){snapshot.content=this._initialContent;snapshot.states=actions[0].states;snapshot.attributes=Object.shallowCopy(initialState.attributes);}else{let lastSnapshot=this._snapshots[lastSnapshotIndex];snapshot.content=lastSnapshot.content;snapshot.states=lastSnapshot.states;snapshot.attributes={};for(let attribute in initialState.attributes)
snapshot.attributes[attribute]=lastSnapshot.element[attribute];startIndex=lastSnapshot.index;}
applyActions(startIndex,snapshot.index-1);if(snapshot.index>0)
snapshot.states=actions[snapshot.index-1].states;snapshot.content=new Image;snapshot.content.src=snapshot.element.toDataURL();snapshot.content.addEventListener("load",imageLoad);return;}
this._previewContainer.removeChildren();if(showCanvasPath){indexOfLastBeginPathAction=this._index;while(indexOfLastBeginPathAction>snapshot.index&&actions[indexOfLastBeginPathAction].name!=="beginPath")
--indexOfLastBeginPathAction;}
applyActions(snapshot.index,this._index);this._previewContainer.insertAdjacentElement("afterbegin",snapshot.element);this._updateImageGrid();}
_generateContentFromSnapshot(index)
{let imageLoad=(event)=>{if(index!==this._index)
return;this._generateContentFromSnapshot(index);};let initialState=this.representedObject.initialState;if(initialState.content&&!this._initialContent){this._initialContent=new Image;this._initialContent.src=initialState.content;this._initialContent.addEventListener("load",imageLoad);return;}
let actions=this.representedObject.actions;let visualIndex=index;while(!actions[visualIndex].isVisual&&!(actions[visualIndex]instanceof WI.RecordingInitialStateAction))
visualIndex--;let snapshot=this._snapshots[visualIndex];if(!snapshot){if(actions[visualIndex].snapshot){snapshot=this._snapshots[visualIndex]={element:new Image};snapshot.element.src=actions[visualIndex].snapshot;snapshot.element.addEventListener("load",imageLoad);return;}
if(actions[visualIndex]instanceof WI.RecordingInitialStateAction)
snapshot=this._snapshots[visualIndex]={element:this._initialContent};}
if(snapshot){this._previewContainer.removeChildren();this._previewContainer.appendChild(snapshot.element);this._updateImageGrid();}}
_updateExportButton()
{if(this.representedObject.type===WI.Recording.Type.Canvas2D&&this.representedObject.ready)
this._exportButtonNavigationItem.tooltip=WI.UIString("Export recording (%s)\nShift-click to export a HTML reduction").format(WI.saveKeyboardShortcut.displayName);else
this._exportButtonNavigationItem.tooltip=WI.UIString("Export recording (%s)").format(WI.saveKeyboardShortcut.displayName);}
_updateCanvasPath()
{let activated=WI.settings.showCanvasPath.value;if(this._showPathButtonNavigationItem.activated!==activated)
this._generateContentCanvas2D(this._index);this._showPathButtonNavigationItem.activated=activated;}
_updateImageGrid()
{let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;if(this.didInitialLayout&&!isNaN(this._index))
this._previewContainer.firstElementChild.classList.toggle("show-grid",activated);}
_updateSliderValue()
{if(!this._sliderElement)
return;let visualActionIndexes=this.representedObject.visualActionIndexes;let visualActionIndex=0;if(this._index>0){while(visualActionIndex<visualActionIndexes.length&&visualActionIndexes[visualActionIndex]<=this._index)
visualActionIndex++;}
this._sliderElement.value=visualActionIndex;this._sliderElement.max=visualActionIndexes.length;this._sliderValueElement.textContent=WI.UIString("%d of %d").format(visualActionIndex,visualActionIndexes.length);}
_showPathButtonClicked(event)
{WI.settings.showCanvasPath.value=!this._showPathButtonNavigationItem.activated;this._updateCanvasPath();}
_showGridButtonClicked(event)
{WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;this._updateImageGrid();}
_handleExportNavigationItemClicked(event)
{if(event.data.nativeEvent.shiftKey&&this.representedObject.type===WI.Recording.Type.Canvas2D&&this.representedObject.ready)
this._exportReduction();else
this._exportRecording();}
_sliderChanged()
{let index=0;let visualActionIndex=parseInt(this._sliderElement.value)-1;if(visualActionIndex!==-1)
index=this.representedObject.visualActionIndexes[visualActionIndex];this.updateActionIndex(index);}
_handleRecordingProcessedAction(event)
{this._updateExportButton();this._updateSliderValue();if(this.representedObject.ready)
this.representedObject.removeEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);}};WI.RecordingContentView.SnapshotInterval=5000;WI.RecordingStateDetailsSidebarPanel=class RecordingStateDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("recording-state",WI.UIString("State"));this._recording=null;this._action=null;this._dataGrids=[];} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];this.recording=objects.find((object)=>object instanceof WI.Recording&&object.type===WI.Recording.Type.Canvas2D);this.action=objects.find((object)=>object instanceof WI.RecordingAction);return this._recording&&this._action;}
set recording(recording)
{if(recording===this._recording)
return;this._recording=recording;this._action=null;for(let subview of this.contentView.subviews)
this.contentView.removeSubview(subview);this._dataGrids=[];}
set action(action)
{if(!this._recording||action===this._action)
return;this._action=action;if(this._action&&this._recording.type===WI.Recording.Type.Canvas2D)
this._generateDetailsCanvas2D(this._action);this.updateLayoutIfNeeded();} 
get scrollElement()
{if(this._dataGrids.length===1)
return this._dataGrids[0].scrollContainer;return super.scrollElement;}
sizeDidChange()
{super.sizeDidChange();if(this._dataGrids.length===1)
return; for(let dataGrid of this._dataGrids)
dataGrid.sizeDidChange();} 
_generateDetailsCanvas2D(action)
{if(this._dataGrids.length===1)
this.contentView.removeSubview(this._dataGrids[0]);this.contentView.element.removeChildren();this._dataGrids=[];let currentState=action.states.lastValue;if(!currentState)
return;let createStateDataGrid=(state)=>{let dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name")},value:{title:WI.UIString("Value")},});this._dataGrids.push(dataGrid);for(let[name,value]of state){if(name==="setPath")
continue;if(typeof value==="object"){let isGradient=value instanceof CanvasGradient;let isPattern=value instanceof CanvasPattern;if(isGradient||isPattern){let textElement=document.createElement("span");textElement.classList.add("unavailable");let image=null;if(isGradient){textElement.textContent=WI.unlocalizedString("CanvasGradient");image=WI.ImageUtilities.imageFromCanvasGradient(value,100,100);}else if(isPattern){textElement.textContent=WI.unlocalizedString("CanvasPattern");image=value.__image;}
let fragment=document.createDocumentFragment();if(image){let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Image,image);fragment.appendChild(swatch.element);}
fragment.appendChild(textElement);value=fragment;}else{if(value instanceof DOMMatrix)
value=[value.a,value.b,value.c,value.d,value.e,value.f];value=JSON.stringify(value);}}else if(name==="fillStyle"||name==="strokeStyle"||name==="shadowColor"){let color=WI.Color.fromString(value);const readOnly=true;let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Color,color,readOnly);value=document.createElement("span");value.append(swatch.element,color.toString());}
let classNames=[];if(state===currentState&&!action.isGetter&&action.stateModifiers.has(name))
classNames.push("modified");if(name.startsWith("webkit"))
classNames.push("non-standard");dataGrid.appendChild(new WI.DataGridNode({name,value},{classNames}));}
dataGrid.updateLayoutIfNeeded();return dataGrid;};let createStateSection=(state,index=NaN)=>{let isCurrentState=isNaN(index);let dataGrid=createStateDataGrid(state);let row=new WI.DetailsSectionDataGridRow(dataGrid);let group=new WI.DetailsSectionGroup([row]);let identifier=isCurrentState?"recording-current-state":`recording-saved-state-${index + 1}`;const title=null;const optionsElement=null;let defaultCollapsedSettingValue=!isCurrentState;let section=new WI.DetailsSection(identifier,title,[group],optionsElement,defaultCollapsedSettingValue);if(isCurrentState)
section.title=WI.UIString("Current State");else{section.title=WI.UIString("Save %d").format(index+1);if(state.source){let sourceIndex=this._recording.actions.indexOf(state.source);if(sourceIndex>=0){let sourceElement=section.titleElement.appendChild(document.createElement("span"));sourceElement.classList.add("source");sourceElement.textContent=WI.UIString("(Action %s)").format(sourceIndex);}}}
return section;};if(action.states.length===1){this.contentView.addSubview(createStateDataGrid(currentState));return;}
let currentStateSection=createStateSection(currentState);this.contentView.element.appendChild(currentStateSection.element);let savedStateSections=[];for(let i=action.states.length-2;i>=0;--i){let savedStateSection=createStateSection(action.states[i],i);savedStateSections.push(savedStateSection);}
let savedStatesGroup=new WI.DetailsSectionGroup(savedStateSections);let savedStatesSection=new WI.DetailsSection("recording-saved-states",WI.UIString("Saved States"),[savedStatesGroup]);this.contentView.element.appendChild(savedStatesSection.element);}};WI.RecordingTraceDetailsSidebarPanel=class RecordingTraceDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("recording-trace",WI.UIString("Trace"));const selectable=false;this._backtraceTreeOutline=new WI.TreeOutline(selectable);this._backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.CallFrameTreeController(this._backtraceTreeOutline);this._recording=null;this._action=null;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];this.recording=objects.find((object)=>object instanceof WI.Recording);this.action=objects.find((object)=>object instanceof WI.RecordingAction);return this._recording&&this._action;}
set recording(recording)
{if(recording===this._recording)
return;this._recording=recording;this._action=null;this.contentView.element.removeChildren();}
set action(action)
{if(!this._recording||action===this._action)
return;this._action=action;this.contentView.element.removeChildren();if(!this._action)
return;let trace=this._action.trace;this._backtraceTreeController.callFrames=trace;if(!trace.length){let noTraceDataElement=this.contentView.element.appendChild(document.createElement("div"));noTraceDataElement.classList.add("no-trace-data");let noTraceDataMessageElement=noTraceDataElement.appendChild(document.createElement("div"));noTraceDataMessageElement.classList.add("message");noTraceDataMessageElement.textContent=WI.UIString("Call Stack Unavailable");return;}
this.contentView.element.appendChild(this._backtraceTreeOutline.element);}};WI.RenderingFrameTimelineDataGridNode=class RenderingFrameTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);} 
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.name=WI.TimelineTabContentView.displayNameForRecord(this.record);this._cachedData.startTime=this.record.startTime-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.totalTime=this.record.duration;this._cachedData.scriptTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Script);this._cachedData.layoutTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Layout);this._cachedData.paintTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Paint);this._cachedData.otherTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Other);return this._cachedData;}
createCellContent(columnIdentifier,cell)
{const higherResolution=true;var value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return value;case"startTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"scriptTime":case"layoutTime":case"paintTime":case"otherTime":case"totalTime":return(isNaN(value)||value===0)?emDash:Number.secondsToString(value,higherResolution);}
return super.createCellContent(columnIdentifier,cell);}};WI.RenderingFrameTimelineOverviewGraph=class RenderingFrameTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("rendering-frame");this.element.addEventListener("click",this._mouseClicked.bind(this));this._renderingFrameTimeline=timeline;this._renderingFrameTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._timelineRecordAdded,this);this._selectedFrameMarker=document.createElement("div");this._selectedFrameMarker.classList.add("frame-marker");this._timelineRecordFrames=[];this._selectedTimelineRecordFrame=null;this._graphHeightSeconds=NaN;this._framesPerSecondDividerMap=new Map;this.reset();} 
get graphHeightSeconds()
{if(!isNaN(this._graphHeightSeconds))
return this._graphHeightSeconds;var maximumFrameDuration=this._renderingFrameTimeline.records.reduce(function(previousValue,currentValue){return Math.max(previousValue,currentValue.duration);},0);this._graphHeightSeconds=maximumFrameDuration*1.1;this._graphHeightSeconds=Math.min(this._graphHeightSeconds,WI.RenderingFrameTimelineOverviewGraph.MaximumGraphHeightSeconds);this._graphHeightSeconds=Math.max(this._graphHeightSeconds,WI.RenderingFrameTimelineOverviewGraph.MinimumGraphHeightSeconds);return this._graphHeightSeconds;}
reset()
{super.reset();this.element.removeChildren();this.selectedRecord=null;this._framesPerSecondDividerMap.clear();}
recordWasFiltered(record,filtered)
{super.recordWasFiltered(record,filtered);if(!(record instanceof WI.RenderingFrameTimelineRecord))
return;record[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol]=filtered;const startIndex=Math.floor(this.startTime);const endIndex=Math.min(Math.floor(this.endTime),this._renderingFrameTimeline.records.length-1);if(record.frameIndex<startIndex||record.frameIndex>endIndex)
return;const frameIndex=record.frameIndex-startIndex;this._timelineRecordFrames[frameIndex].filtered=filtered;} 
get height()
{return 108;}
layout()
{super.layout();if(this.hidden)
return;if(!this._renderingFrameTimeline.records.length)
return;let records=this._renderingFrameTimeline.records;let startIndex=Math.floor(this.startTime);let endIndex=Math.min(Math.floor(this.endTime),records.length-1);let recordFrameIndex=0;for(let i=startIndex;i<=endIndex;++i){let record=records[i];let timelineRecordFrame=this._timelineRecordFrames[recordFrameIndex];if(!timelineRecordFrame)
timelineRecordFrame=this._timelineRecordFrames[recordFrameIndex]=new WI.TimelineRecordFrame(this,record);else
timelineRecordFrame.record=record;timelineRecordFrame.refresh(this);if(!timelineRecordFrame.element.parentNode)
this.element.appendChild(timelineRecordFrame.element);timelineRecordFrame.filtered=record[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol]||false;++recordFrameIndex;}
for(;recordFrameIndex<this._timelineRecordFrames.length;++recordFrameIndex){this._timelineRecordFrames[recordFrameIndex].record=null;this._timelineRecordFrames[recordFrameIndex].element.remove();}
this._updateDividers();this._updateFrameMarker();}
updateSelectedRecord()
{if(!this.selectedRecord){this._updateFrameMarker();return;}
const visibleDuration=this.timelineOverview.visibleDuration;const frameIndex=this.selectedRecord.frameIndex;if(frameIndex<Math.ceil(this.timelineOverview.scrollStartTime)||frameIndex>=this.timelineOverview.scrollStartTime+visibleDuration){var scrollStartTime=frameIndex;if(!this._selectedTimelineRecordFrame||Math.abs(this._selectedTimelineRecordFrame.record.frameIndex-this.selectedRecord.frameIndex)>1){scrollStartTime-=Math.floor(visibleDuration/2);scrollStartTime=Math.max(Math.min(scrollStartTime,this.timelineOverview.endTime),this.timelineOverview.startTime);}
this.timelineOverview.scrollStartTime=scrollStartTime;return;}
this._updateFrameMarker();} 
_timelineRecordAdded(event)
{this._graphHeightSeconds=NaN;this.needsLayout();}
_updateDividers()
{if(this.graphHeightSeconds===0)
return;let overviewGraphHeight=this.height;function createDividerAtPosition(framesPerSecond)
{var secondsPerFrame=1/framesPerSecond;var dividerTop=1-secondsPerFrame/this.graphHeightSeconds;if(dividerTop<0.01||dividerTop>=1)
return;var divider=this._framesPerSecondDividerMap.get(framesPerSecond);if(!divider){divider=document.createElement("div");divider.classList.add("divider");var label=document.createElement("div");label.classList.add("label");label.innerText=WI.UIString("%d FPS").format(framesPerSecond);divider.appendChild(label);this.element.appendChild(divider);this._framesPerSecondDividerMap.set(framesPerSecond,divider);}
divider.style.marginTop=(dividerTop*overviewGraphHeight).toFixed(2)+"px";}
createDividerAtPosition.call(this,60);createDividerAtPosition.call(this,30);}
_updateFrameMarker()
{if(this._selectedTimelineRecordFrame){this._selectedTimelineRecordFrame.selected=false;this._selectedTimelineRecordFrame=null;}
if(!this.selectedRecord){if(this._selectedFrameMarker.parentElement)
this.element.removeChild(this._selectedFrameMarker);return;}
var frameWidth=1/this.timelineOverview.secondsPerPixel;this._selectedFrameMarker.style.width=frameWidth+"px";var markerLeftPosition=this.selectedRecord.frameIndex-this.startTime;let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._selectedFrameMarker.style.setProperty(property,((markerLeftPosition/this.timelineOverview.visibleDuration)*100).toFixed(2)+"%");if(!this._selectedFrameMarker.parentElement)
this.element.appendChild(this._selectedFrameMarker);var index=this._timelineRecordFrames.binaryIndexOf(this.selectedRecord,function(record,frame){return frame.record?record.frameIndex-frame.record.frameIndex:-1;});if(index<0||index>=this._timelineRecordFrames.length)
return;this._selectedTimelineRecordFrame=this._timelineRecordFrames[index];this._selectedTimelineRecordFrame.selected=true;}
_mouseClicked(event)
{let position=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
position=this.element.totalOffsetRight-event.pageX;else
position=event.pageX-this.element.totalOffsetLeft;var frameIndex=Math.floor(position*this.timelineOverview.secondsPerPixel+this.startTime);if(frameIndex<0||frameIndex>=this._renderingFrameTimeline.records.length)
return;var newSelectedRecord=this._renderingFrameTimeline.records[frameIndex];if(newSelectedRecord[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol])
return;event.__timelineRecordClickEventHandled=true;if(this.selectedRecord===newSelectedRecord)
return;if(frameIndex>=this.timelineOverview.selectionStartTime&&frameIndex<this.timelineOverview.selectionStartTime+this.timelineOverview.selectionDuration){this.selectedRecord=newSelectedRecord;return;}
this.selectedRecord=newSelectedRecord;this.timelineOverview.selectionStartTime=frameIndex;this.timelineOverview.selectionDuration=1;}};WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol=Symbol("rendering-frame-overview-graph-record-was-filtered");WI.RenderingFrameTimelineOverviewGraph.MaximumGraphHeightSeconds=0.037;WI.RenderingFrameTimelineOverviewGraph.MinimumGraphHeightSeconds=0.0185;WI.RenderingFrameTimelineView=class RenderingFrameTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);var scopeBarItems=[];for(var key in WI.RenderingFrameTimelineView.DurationFilter){var value=WI.RenderingFrameTimelineView.DurationFilter[key];scopeBarItems.push(new WI.ScopeBarItem(value,WI.RenderingFrameTimelineView.displayNameForDurationFilter(value)));}
this._scopeBar=new WI.ScopeBar("rendering-frame-scope-bar",scopeBarItems,scopeBarItems[0],true);this._scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectionDidChange,this);let columns={name:{},totalTime:{},scriptTime:{},layoutTime:{},paintTime:{},otherTime:{},startTime:{},location:{}};columns.name.title=WI.UIString("Name");columns.name.width="20%";columns.name.icon=true;columns.name.disclosure=true;columns.name.locked=true;columns.totalTime.title=WI.UIString("Total Time");columns.totalTime.width="15%";columns.totalTime.aligned="right";columns.scriptTime.title=WI.RenderingFrameTimelineRecord.displayNameForTaskType(WI.RenderingFrameTimelineRecord.TaskType.Script);columns.scriptTime.width="10%";columns.scriptTime.aligned="right";columns.layoutTime.title=WI.RenderingFrameTimelineRecord.displayNameForTaskType(WI.RenderingFrameTimelineRecord.TaskType.Layout);columns.layoutTime.width="10%";columns.layoutTime.aligned="right";columns.paintTime.title=WI.RenderingFrameTimelineRecord.displayNameForTaskType(WI.RenderingFrameTimelineRecord.TaskType.Paint);columns.paintTime.width="10%";columns.paintTime.aligned="right";columns.otherTime.title=WI.RenderingFrameTimelineRecord.displayNameForTaskType(WI.RenderingFrameTimelineRecord.TaskType.Other);columns.otherTime.width="10%";columns.otherTime.aligned="right";columns.startTime.title=WI.UIString("Start Time");columns.startTime.width="15%";columns.startTime.aligned="right";columns.location.title=WI.UIString("Location");for(var column in columns)
columns[column].sortable=true;this._dataGrid=new WI.TimelineDataGrid(columns);this._dataGrid.sortColumnIdentifier="startTime";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("rendering-frame-timeline-view");this.setupDataGrid(this._dataGrid);this.element.classList.add("rendering-frame");this.addSubview(this._dataGrid);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._renderingFrameTimelineRecordAdded,this);this._pendingRecords=[];for(let record of timeline.records)
this._processRecord(record);}
static displayNameForDurationFilter(filter)
{switch(filter){case WI.RenderingFrameTimelineView.DurationFilter.All:return WI.UIString("All");case WI.RenderingFrameTimelineView.DurationFilter.OverOneMillisecond:return WI.UIString("Over 1 ms");case WI.RenderingFrameTimelineView.DurationFilter.OverFifteenMilliseconds:return WI.UIString("Over 15 ms");default:console.error("Unknown filter type",filter);}
return null;} 
get showsLiveRecordingData(){return false;}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._renderingFrameTimelineRecordAdded,this);this._dataGrid.closed();}
get selectionPathComponents()
{let dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode||dataGridNode.hidden)
return null;let pathComponents=[];while(dataGridNode&&!dataGridNode.root){if(dataGridNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(dataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);pathComponents.unshift(pathComponent);dataGridNode=dataGridNode.parent;}
return pathComponents;}
get filterStartTime()
{let records=this.representedObject.records;let startIndex=this.startTime;if(startIndex>=records.length)
return Infinity;return records[startIndex].startTime;}
get filterEndTime()
{let records=this.representedObject.records;let endIndex=this.endTime-1;if(endIndex>=records.length)
return Infinity;return records[endIndex].endTime;}
reset()
{super.reset();this._dataGrid.reset();this._pendingRecords=[];} 
dataGridNodePathComponentSelected(event)
{let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}
matchDataGridNodeAgainstCustomFilters(node)
{if(!super.matchDataGridNodeAgainstCustomFilters(node))
return false;let selectedScopeBarItem=this._scopeBar.selectedItems[0];if(!selectedScopeBarItem||selectedScopeBarItem.id===WI.RenderingFrameTimelineView.DurationFilter.All)
return true;while(node&&!(node.record instanceof WI.RenderingFrameTimelineRecord))
node=node.parent;if(!node)
return false;let minimumDuration=selectedScopeBarItem.id===WI.RenderingFrameTimelineView.DurationFilter.OverOneMillisecond?0.001:0.015;return node.record.duration>minimumDuration;}
layout()
{this._processPendingRecords();} 
_processPendingRecords()
{if(!this._pendingRecords.length)
return;for(let renderingFrameTimelineRecord of this._pendingRecords){let dataGridNode=new WI.RenderingFrameTimelineDataGridNode(renderingFrameTimelineRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(dataGridNode);let stack=[{children:renderingFrameTimelineRecord.children,parentDataGridNode:dataGridNode,index:0}];while(stack.length){let entry=stack.lastValue;if(entry.index>=entry.children.length){stack.pop();continue;}
let childRecord=entry.children[entry.index];let childDataGridNode=null;if(childRecord.type===WI.TimelineRecord.Type.Layout){childDataGridNode=new WI.LayoutTimelineDataGridNode(childRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(childDataGridNode,entry.parentDataGridNode);}else if(childRecord.type===WI.TimelineRecord.Type.Script){let rootNodes=[];if(childRecord.profile){rootNodes=childRecord.profile.topDownRootNodes;}
childDataGridNode=new WI.ScriptTimelineDataGridNode(childRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(childDataGridNode,entry.parentDataGridNode);for(let profileNode of rootNodes){let profileNodeDataGridNode=new WI.ProfileNodeDataGridNode(profileNode,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(profileNodeDataGridNode,childDataGridNode);}}
if(childDataGridNode&&childRecord.children.length)
stack.push({children:childRecord.children,parentDataGridNode:childDataGridNode,index:0});++entry.index;}}
this._pendingRecords=[];}
_renderingFrameTimelineRecordAdded(event)
{let renderingFrameTimelineRecord=event.data.record;this._processRecord(renderingFrameTimelineRecord);this.needsLayout();}
_processRecord(renderingFrameTimelineRecord)
{this._pendingRecords.push(renderingFrameTimelineRecord);}
_scopeBarSelectionDidChange()
{this._dataGrid.filterDidChange();}};WI.RenderingFrameTimelineView.DurationFilter={All:"rendering-frame-timeline-view-duration-filter-all",OverOneMillisecond:"rendering-frame-timeline-view-duration-filter-over-1-ms",OverFifteenMilliseconds:"rendering-frame-timeline-view-duration-filter-over-15-ms"};WI.Resizer=class Resizer extends WI.Object
{constructor(ruleOrientation,delegate)
{super();this._delegate=delegate;this._orientation=ruleOrientation;this._element=document.createElement("div");this._element.classList.add("resizer");if(this._orientation===WI.Resizer.RuleOrientation.Horizontal)
this._element.classList.add("horizontal-rule");else if(this._orientation===WI.Resizer.RuleOrientation.Vertical)
this._element.classList.add("vertical-rule");this._element.addEventListener("mousedown",this._resizerMouseDown.bind(this),false);this._resizerMouseMovedEventListener=this._resizerMouseMoved.bind(this);this._resizerMouseUpEventListener=this._resizerMouseUp.bind(this);} 
get element()
{return this._element;}
get orientation()
{return this._orientation;}
get initialPosition()
{return this._resizerMouseDownPosition||NaN;} 
_currentPosition()
{if(this._orientation===WI.Resizer.RuleOrientation.Vertical)
return event.pageX;if(this._orientation===WI.Resizer.RuleOrientation.Horizontal)
return event.pageY;}
_resizerMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;this._resizerMouseDownPosition=this._currentPosition();var delegateRequestedAbort=false;if(typeof this._delegate.resizerDragStarted==="function")
delegateRequestedAbort=this._delegate.resizerDragStarted(this,event.target);if(delegateRequestedAbort){delete this._resizerMouseDownPosition;return;}
if(this._orientation===WI.Resizer.RuleOrientation.Vertical)
document.body.style.cursor="col-resize";else{document.body.style.cursor="row-resize";}
document.addEventListener("mousemove",this._resizerMouseMovedEventListener,false);document.addEventListener("mouseup",this._resizerMouseUpEventListener,false);event.preventDefault();event.stopPropagation();if(WI._elementDraggingGlassPane)
WI._elementDraggingGlassPane.remove();var glassPaneElement=document.createElement("div");glassPaneElement.className="glass-pane-for-drag";document.body.appendChild(glassPaneElement);WI._elementDraggingGlassPane=glassPaneElement;}
_resizerMouseMoved(event)
{event.preventDefault();event.stopPropagation();if(typeof this._delegate.resizerDragging==="function")
this._delegate.resizerDragging(this,this._resizerMouseDownPosition-this._currentPosition());}
_resizerMouseUp(event)
{if(event.button!==0||event.ctrlKey)
return;document.body.style.removeProperty("cursor");if(WI._elementDraggingGlassPane){WI._elementDraggingGlassPane.remove();delete WI._elementDraggingGlassPane;}
document.removeEventListener("mousemove",this._resizerMouseMovedEventListener,false);document.removeEventListener("mouseup",this._resizerMouseUpEventListener,false);event.preventDefault();event.stopPropagation();if(typeof this._delegate.resizerDragEnded==="function")
this._delegate.resizerDragEnded(this);delete this._resizerMouseDownPosition;}};WI.Resizer.RuleOrientation={Horizontal:Symbol("resizer-rule-orientation-horizontal"),Vertical:Symbol("resizer-rule-orientation-vertical"),};WI.ResourceClusterContentView=class ResourceClusterContentView extends WI.ClusterContentView
{constructor(resource)
{super(resource);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);this._resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this._resourceLoadingDidFinish,this);this._responsePathComponent=this._createPathComponent({displayName:WI.UIString("Response"),identifier:ResourceClusterContentView.Identifier.Response,styleClassNames:["response-icon"],});if(this._canShowRequestContentView()){this._requestPathComponent=this._createPathComponent({displayName:WI.UIString("Request"),identifier:ResourceClusterContentView.Identifier.Request,styleClassNames:["request-icon"],nextSibling:this._responsePathComponent,});this._tryEnableCustomRequestContentViews();}


this._currentContentViewSetting=new WI.Setting("resource-current-view-"+this._resource.url.hash,ResourceClusterContentView.Identifier.Response);this._tryEnableCustomResponseContentViews();} 
get resource(){return this._resource;}
get selectionPathComponents()
{let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView)
return[];if(!this._canShowRequestContentView()&&!this._canShowCustomRequestContentView()&&!this._canShowCustomResponseContentView())
return currentContentView.selectionPathComponents;let components=[this._pathComponentForContentView(currentContentView)];return components.concat(currentContentView.selectionPathComponents);}
attached()
{super.attached();if(this._shownInitialContent)
return;this._showContentViewForIdentifier(this._currentContentViewSetting.value);}
closed()
{super.closed();this._shownInitialContent=false;}
restoreFromCookie(cookie)
{let contentView=this._showContentViewForIdentifier(cookie[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]);if(typeof contentView.revealPosition==="function"&&"lineNumber"in cookie&&"columnNumber"in cookie)
contentView.revealPosition(new WI.SourceCodePosition(cookie.lineNumber,cookie.columnNumber));}
showRequest()
{this._shownInitialContent=true;return this._showContentViewForIdentifier(ResourceClusterContentView.Identifier.Request);}
showResponse(positionToReveal,textRangeToSelect,forceUnformatted)
{this._shownInitialContent=true;if(!this._resource.finished){this._positionToReveal=positionToReveal;this._textRangeToSelect=textRangeToSelect;this._forceUnformatted=forceUnformatted;}
let responseContentView=this._showContentViewForIdentifier(ResourceClusterContentView.Identifier.Response);if(typeof responseContentView.revealPosition==="function")
responseContentView.revealPosition(positionToReveal,textRangeToSelect,forceUnformatted);return responseContentView;} 
get requestContentView()
{if(!this._canShowRequestContentView())
return null;if(this._requestContentView)
return this._requestContentView;this._requestContentView=new WI.TextContentView(this._resource.requestData||"",this._resource.requestDataContentType);return this._requestContentView;}
get responseContentView()
{if(this._responseContentView)
return this._responseContentView;this._responseContentView=this._contentViewForResourceType(this._resource.type);if(this._responseContentView)
return this._responseContentView;let typeFromMIMEType=WI.Resource.typeFromMIMEType(this._resource.mimeType);this._responseContentView=this._contentViewForResourceType(typeFromMIMEType);if(this._responseContentView)
return this._responseContentView;if(WI.shouldTreatMIMETypeAsText(this._resource.mimeType)){this._responseContentView=new WI.TextResourceContentView(this._resource);return this._responseContentView;}
this._responseContentView=new WI.GenericResourceContentView(this._resource);return this._responseContentView;}
get customRequestDOMContentView()
{if(!this._customRequestDOMContentView&&this._customRequestDOMContentViewInitializer)
this._customRequestDOMContentView=this._customRequestDOMContentViewInitializer();return this._customRequestDOMContentView;}
get customRequestJSONContentView()
{if(!this._customRequestJSONContentView&&this._customRequestJSONContentViewInitializer)
this._customRequestJSONContentView=this._customRequestJSONContentViewInitializer();return this._customRequestJSONContentView;}
get customResponseDOMContentView()
{if(!this._customResponseDOMContentView&&this._customResponseDOMContentViewInitializer)
this._customResponseDOMContentView=this._customResponseDOMContentViewInitializer();return this._customResponseDOMContentView;}
get customResponseJSONContentView()
{if(!this._customResponseJSONContentView&&this._customResponseJSONContentViewInitializer)
this._customResponseJSONContentView=this._customResponseJSONContentViewInitializer();return this._customResponseJSONContentView;}
get customResponseTextContentView()
{if(!this._customResponseTextContentView&&this._customResponseTextContentViewInitializer)
this._customResponseTextContentView=this._customResponseTextContentViewInitializer();return this._customResponseTextContentView;}
_createPathComponent({displayName,styleClassNames,identifier,previousSibling,nextSibling})
{const textOnly=false;const showSelectorArrows=true;let pathComponent=new WI.HierarchicalPathComponent(displayName,styleClassNames,identifier,textOnly,showSelectorArrows);pathComponent.comparisonData=this._resource;if(previousSibling){previousSibling.nextSibling=pathComponent;pathComponent.previousSibling=previousSibling;}
if(nextSibling){nextSibling.previousSibling=pathComponent;pathComponent.nextSibling=nextSibling;}
pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._pathComponentSelected,this);return pathComponent;}
_canShowRequestContentView()
{let requestData=this._resource.requestData;if(!requestData)
return false;if(this._resource.hasRequestFormParameters())
return false;return true;}
_canShowCustomRequestContentView()
{return!!(this._customRequestDOMContentViewInitializer||this._customRequestJSONContentViewInitializer);}
_canShowCustomResponseContentView()
{return!!(this._customResponseDOMContentViewInitializer||this._customResponseJSONContentViewInitializer||this._customResponseTextContentViewInitializer);}
_contentViewForResourceType(type)
{switch(type){case WI.Resource.Type.Document:case WI.Resource.Type.Script:case WI.Resource.Type.StyleSheet:return new WI.TextResourceContentView(this._resource);case WI.Resource.Type.Image:return new WI.ImageResourceContentView(this._resource);case WI.Resource.Type.Font:return new WI.FontResourceContentView(this._resource);case WI.Resource.Type.WebSocket:return new WI.WebSocketContentView(this._resource);default:return null;}}
_pathComponentForContentView(contentView)
{switch(contentView){case this._requestContentView:return this._requestPathComponent;case this._customRequestDOMContentView:return this._customRequestDOMPathComponent;case this._customRequestJSONContentView:return this._customRequestJSONPathComponent;case this._responseContentView:return this._responsePathComponent;case this._customResponseDOMContentView:return this._customResponseDOMPathComponent;case this._customResponseJSONContentView:return this._customResponseJSONPathComponent;case this._customResponseTextContentView:return this._customResponseTextPathComponent;}
console.error("Unknown contentView",contentView);return null;}
_identifierForContentView(contentView)
{switch(contentView){case this._requestContentView:return ResourceClusterContentView.Identifier.Request;case this._customRequestDOMContentView:return ResourceClusterContentView.Identifier.RequestDOM;case this._customRequestJSONContentView:return ResourceClusterContentView.Identifier.RequestJSON;case this._responseContentView:return ResourceClusterContentView.Identifier.Response;case this._customResponseDOMContentView:return ResourceClusterContentView.Identifier.ResponseDOM;case this._customResponseJSONContentView:return ResourceClusterContentView.Identifier.ResponseJSON;case this._customResponseTextContentView:return ResourceClusterContentView.Identifier.ResponseText;}
console.error("Unknown contentView",contentView);return null;}
_showContentViewForIdentifier(identifier)
{let contentViewToShow=null;switch(identifier){case ResourceClusterContentView.Identifier.RequestDOM:contentViewToShow=this.customRequestDOMContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.RequestJSON:contentViewToShow=this.customRequestJSONContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.Request:contentViewToShow=this.requestContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.ResponseDOM:contentViewToShow=this.customResponseDOMContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.ResponseJSON:contentViewToShow=this.customResponseJSONContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.ResponseText:contentViewToShow=this.customResponseTextContentView;if(contentViewToShow)
break; case ResourceClusterContentView.Identifier.Response:default:contentViewToShow=this.responseContentView;break;}
this._currentContentViewSetting.value=this._identifierForContentView(contentViewToShow);return this.contentViewContainer.showContentView(contentViewToShow);}
_pathComponentSelected(event)
{this._showContentViewForIdentifier(event.data.pathComponent.representedObject);}
_resourceTypeDidChange(event)
{

let currentResponseContentView=this._responseContentView;if(!currentResponseContentView)
return;this._responseContentView=null;this.contentViewContainer.replaceContentView(currentResponseContentView,this.responseContentView);}
_resourceLoadingDidFinish(event)
{this._tryEnableCustomResponseContentViews();if("_positionToReveal"in this){if(this._contentViewContainer.currentContentView===this._responseContentView)
this._responseContentView.revealPosition(this._positionToReveal,this._textRangeToSelect,this._forceUnformatted);delete this._positionToReveal;delete this._textRangeToSelect;delete this._forceUnformatted;}}
_canUseJSONContentViewForContent(content)
{return typeof content==="string"&&content.isJSON((json)=>json&&(typeof json==="object"||Array.isArray(json)));}
_canUseDOMContentViewForContent(content,mimeType)
{if(typeof content!=="string")
return false;switch(mimeType){case"text/html":return true;case"text/xml":case"application/xml":case"application/xhtml+xml":case"image/svg+xml":try{let dom=(new DOMParser).parseFromString(content,mimeType);return!dom.querySelector("parsererror");}catch{}
return false;}
return false;}
_normalizeMIMETypeForDOM(mimeType)
{mimeType=parseMIMEType(mimeType).type;if(!mimeType)
return mimeType;if(mimeType.endsWith("/html")||mimeType.endsWith("+html"))
return"text/html";if(mimeType.endsWith("/xml")||mimeType.endsWith("+xml")){if(mimeType!=="application/xhtml+xml"&&mimeType!=="image/svg+xml")
return"application/xml";}
if(mimeType.endsWith("/xhtml")||mimeType.endsWith("+xhtml"))
return"application/xhtml+xml";if(mimeType.endsWith("/svg")||mimeType.endsWith("+svg"))
return"image/svg+xml";return mimeType;}
_tryEnableCustomRequestContentViews()
{let content=this._resource.requestData;if(this._canUseJSONContentViewForContent(content)){this._customRequestJSONContentViewInitializer=()=>new WI.LocalJSONContentView(content,this._resource);this._customRequestJSONPathComponent=this._createPathComponent({displayName:WI.UIString("Request (Object Tree)"),styleClassNames:["object-icon"],identifier:ResourceClusterContentView.Identifier.RequestJSON,previousSibling:this._requestPathComponent,nextSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}
let mimeType=this._normalizeMIMETypeForDOM(this._resource.requestDataContentType);if(this._canUseDOMContentViewForContent(content,mimeType)){this._customRequestDOMContentViewInitializer=()=>new WI.LocalDOMContentView(content,mimeType,this._resource);this._customRequestDOMPathComponent=this._createPathComponent({displayName:WI.UIString("Request (DOM Tree)"),styleClassNames:["dom-document-icon"],identifier:ResourceClusterContentView.Identifier.RequestDOM,previousSibling:this._requestPathComponent,nextSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}}
_tryEnableCustomResponseContentViews()
{if(!this._resource.hasResponse())
return;if(this._resource instanceof WI.WebSocketResource)
return;this._resource.requestContent().then(({error,content})=>{if(error||typeof content!=="string")
return;if(this._canUseJSONContentViewForContent(content)){this._customResponseJSONContentViewInitializer=()=>new WI.LocalJSONContentView(content,this._resource);this._customResponseJSONPathComponent=this._createPathComponent({displayName:WI.UIString("Response (Object Tree)"),styleClassNames:["object-icon"],identifier:ResourceClusterContentView.Identifier.ResponseJSON,previousSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}
let mimeType=this._normalizeMIMETypeForDOM(this._resource.mimeType);if(this._canUseDOMContentViewForContent(content,mimeType)){if(mimeType==="image/svg+xml"){this._customResponseTextContentViewInitializer=()=>new WI.TextContentView(content,mimeType,this._resource);this._customResponseTextPathComponent=this._createPathComponent({displayName:WI.UIString("Response (Text)"),styleClassNames:["source-icon"],identifier:ResourceClusterContentView.Identifier.ResponseText,previousSibling:this._responsePathComponent,});}
this._customResponseDOMContentViewInitializer=()=>new WI.LocalDOMContentView(content,mimeType,this._resource);this._customResponseDOMPathComponent=this._createPathComponent({displayName:WI.UIString("Response (DOM Tree)"),styleClassNames:["dom-document-icon"],identifier:ResourceClusterContentView.Identifier.ResponseDOM,previousSibling:this._customResponseTextPathComponent||this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}});}};WI.ResourceClusterContentView.ContentViewIdentifierCookieKey="resource-cluster-content-view-identifier";WI.ResourceClusterContentView.Identifier={Request:"request",RequestDOM:"request-dom",RequestJSON:"request-json",Response:"response",ResponseDOM:"response-dom",ResponseJSON:"response-json",ResponseText:"response-text",};WI.ResourceCollectionContentView=class ResourceCollectionContentView extends WI.CollectionContentView
{constructor(collection)
{let contentViewConstructor=null;if(collection.resourceType===WI.Resource.Type.Image)
contentViewConstructor=WI.ImageResourceContentView;super(collection,contentViewConstructor);this.element.classList.add("resource-collection");if(collection.resourceType===WI.Resource.Type.Image){this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleShowGridButtonClicked,this);this._showGridButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;let allItem=new WI.ScopeBarItem("all",WI.UIString("All"));let items=[allItem];this._scopeBarItemTypeMap={};let addItem=(key,label)=>{let item=new WI.ScopeBarItem(key,label);items.push(item);this._scopeBarItemTypeMap[key]=item;};addItem("bmp",WI.UIString("BMP"));addItem("gif",WI.UIString("GIF"));addItem("ico",WI.UIString("ICO"));addItem("jp2",WI.UIString("JP2"));addItem("jpg",WI.UIString("JPEG"));addItem("pdf",WI.UIString("PDF"));addItem("png",WI.UIString("PNG"));addItem("svg",WI.UIString("SVG"));addItem("tiff",WI.UIString("TIFF"));addItem("webp",WI.UIString("WebP"));addItem("xbm",WI.UIString("XBM"));const shouldGroupNonExclusiveItems=true;this._imageTypeScopeBar=new WI.ScopeBar("resource-collection-image-type-scope-bar",items,allItem,shouldGroupNonExclusiveItems);this._imageTypeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleImageTypeSelectionChanged,this);}} 
get navigationItems()
{let navigationItems=[];if(this._imageTypeScopeBar)
navigationItems.push(this._imageTypeScopeBar);if(this._showGridButtonNavigationItem)
navigationItems.push(this._showGridButtonNavigationItem);navigationItems.pushAll(super.navigationItems);return navigationItems;} 
attached()
{super.attached();WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);}
detached()
{WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);super.detached();}
get contentViewConstructorOptions()
{let contentViewConstructorOptions=super.contentViewConstructorOptions;if(this.representedObject.resourceType===WI.Resource.Type.Image)
contentViewConstructorOptions.disableInteractions=true;return contentViewConstructorOptions;}
contentViewAdded(contentView)
{let resource=contentView.representedObject;this._updateImageTypeScopeBar();contentView.addEventListener(WI.ResourceContentView.Event.ContentError,this._handleContentError,this);contentView.element.title=WI.displayNameForURL(resource.url,resource.urlComponents);}
contentViewRemoved(contentView)
{this._updateImageTypeScopeBar();contentView.removeEventListener(WI.ResourceContentView.Event.ContentError,this._handleContentError,this);} 
_updateImageTypeScopeBar()
{let extensions=new Set;let visibleExtensions=0;for(let resource of this.representedObject)
extensions.add(WI.fileExtensionForMIMEType(resource.mimeType));for(let[key,item]of Object.entries(this._scopeBarItemTypeMap)){let hidden=!extensions.has(key);item.hidden=hidden;if(hidden&&item.selected)
item.selected=false;if(!item.hidden)
++visibleExtensions;}
this._imageTypeScopeBar.hidden=visibleExtensions<=1;this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_handleShowGridButtonClicked(event)
{WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;}
_handleImageTypeSelectionChanged()
{let selectedTypes=this._imageTypeScopeBar.selectedItems.map((item)=>item.id);let allTypesAllowed=selectedTypes.length===1&&selectedTypes[0]==="all";for(let view of this.subviews){let hidden=!allTypesAllowed;if(hidden&&view instanceof WI.ResourceContentView)
hidden=!selectedTypes.includes(WI.fileExtensionForMIMEType(view.representedObject.mimeType));view.element.hidden=hidden;}}
_handleShowImageGridSettingChanged(event)
{let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;}
_handleContentError(event)
{if(event&&event.target)
this.removeContentViewForItem(event.target.representedObject);}};WI.ResourceCookiesContentView=class ResourceCookiesContentView extends WI.ContentView
{constructor(resource)
{super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);this.element.classList.add("resource-details","resource-cookies");} 
tableNumberOfRows(table)
{return this._dataSourceForTable(table).length;}
tableSortChanged(table)
{let sortComparator=this._generateSortComparator(table);if(!sortComparator)
return;let dataSource=this._dataSourceForTable(table);dataSource.sort(sortComparator);table.reloadData();}
tableIndexForRepresentedObject(table,object)
{let cookies=this._dataSourceForTable(table);let index=cookies.indexOf(object);return index;}
tableRepresentedObjectForIndex(table,index)
{let cookies=this._dataSourceForTable(table);return cookies[index];} 
tableShouldSelectRow(table,cell,column,rowIndex)
{return false;}
tablePopulateCell(table,cell,column,rowIndex)
{let cookie=this._dataSourceForTable(table)[rowIndex];const checkmark="\u2713";switch(column.identifier){case"name":cell.textContent=cookie.name;break;case"value":cell.textContent=cookie.value;break;case"domain":cell.textContent=cookie.domain||emDash;break;case"path":cell.textContent=cookie.path||emDash;break;case"expires":cell.textContent=(!cookie.session&&cookie.expires)?cookie.expires.toLocaleString():WI.UIString("Session");break;case"maxAge":cell.textContent=cookie.maxAge||emDash;break;case"secure":cell.textContent=cookie.secure?checkmark:zeroWidthSpace;break;case"httpOnly":cell.textContent=cookie.httpOnly?checkmark:zeroWidthSpace;break;case"sameSite":cell.textContent=cookie.sameSite===WI.Cookie.SameSiteType.None?emDash:WI.Cookie.displayNameForSameSiteType(cookie.sameSite);break;}
return cell;} 
initialLayout()
{super.initialLayout();this._requestCookiesSection=new WI.ResourceDetailsSection(WI.UIString("Request Cookies"));this.element.appendChild(this._requestCookiesSection.element);this._refreshRequestCookiesSection();this._responseCookiesSection=new WI.ResourceDetailsSection(WI.UIString("Response Cookies"));this.element.appendChild(this._responseCookiesSection.element);this._refreshResponseCookiesSection();} 
_dataSourceForTable(table)
{return table===this._requestCookiesTable?this._requestCookiesDataSource:this._responseCookiesDataSource;}
_generateSortComparator(table)
{let sortColumnIdentifier=table.sortColumnIdentifier;if(!sortColumnIdentifier)
return null;let comparator;switch(sortColumnIdentifier){case"name":case"value":case"domain":case"path":case"sameSite":comparator=(a,b)=>(a[sortColumnIdentifier]||"").extendedLocaleCompare(b[sortColumnIdentifier]||"");break;case"maxAge":comparator=(a,b)=>{let aValue=a[sortColumnIdentifier];if(isNaN(aValue))
return 1;let bValue=b[sortColumnIdentifier];if(isNaN(bValue))
return-1;return aValue-bValue;};break;case"httpOnly":case"secure":comparator=(a,b)=>a[sortColumnIdentifier]-b[sortColumnIdentifier];break;case"expires":comparator=(a,b)=>{let aExpires=a.expires;if(!aExpires)
return 1;let bExpires=b.expires;if(!bExpires)
return-1;return aExpires.getTime()-bExpires.getTime();};break;default:return null;}
let reverseFactor=table.sortOrder===WI.Table.SortOrder.Ascending?1:-1;return(a,b)=>reverseFactor*comparator(a,b);}
_refreshRequestCookiesSection()
{let detailsElement=this._requestCookiesSection.detailsElement;detailsElement.removeChildren();if(this._resource.responseSource===WI.Resource.ResponseSource.MemoryCache){this._requestCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No request, served from the memory cache."));return;}
this._requestCookiesDataSource=this._resource.requestCookies;if(!this._requestCookiesTable){this._requestCookiesTable=new WI.Table("request-cookies",this,this,20);this._requestCookiesTable.addColumn(new WI.TableColumn("name",WI.UIString("Name"),{minWidth:150,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked}));this._requestCookiesTable.addColumn(new WI.TableColumn("value",WI.UIString("Value"),{minWidth:150,hideable:false}));if(!this._requestCookiesTable.sortColumnIdentifier){this._requestCookiesTable.sortOrder=WI.Table.SortOrder.Ascending;this._requestCookiesTable.sortColumnIdentifier="name";}}
if(!this._requestCookiesDataSource.length){if(this._requestCookiesTable.isAttached)
this.removeSubview(this._requestCookiesTable);this._requestCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No request cookies."));}else{this._requestCookiesSection.toggleIncomplete(false);this._requestCookiesTable.element.style.height=this._sizeForTable(this._requestCookiesTable)+"px";this.addSubview(this._requestCookiesTable);detailsElement.classList.add("has-table");detailsElement.appendChild(this._requestCookiesTable.element);}}
_refreshResponseCookiesSection()
{let detailsElement=this._responseCookiesSection.detailsElement;detailsElement.removeChildren();if(!this._resource.hasResponse()){this._responseCookiesSection.markIncompleteSectionWithLoadingIndicator();return;}
this._responseCookiesDataSource=this._resource.responseCookies;if(!this._responseCookiesTable){this._responseCookiesTable=new WI.Table("request-cookies",this,this,20);this._responseCookiesTable.addColumn(new WI.TableColumn("name",WI.UIString("Name"),{minWidth:150,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked}));this._responseCookiesTable.addColumn(new WI.TableColumn("value",WI.UIString("Value"),{minWidth:150,hideable:false}));this._responseCookiesTable.addColumn(new WI.TableColumn("domain",WI.unlocalizedString("Domain"),{}));this._responseCookiesTable.addColumn(new WI.TableColumn("path",WI.unlocalizedString("Path"),{}));this._responseCookiesTable.addColumn(new WI.TableColumn("expires",WI.unlocalizedString("Expires"),{maxWidth:150}));this._responseCookiesTable.addColumn(new WI.TableColumn("maxAge",WI.unlocalizedString("Max-Age"),{maxWidth:90,align:"right"}));this._responseCookiesTable.addColumn(new WI.TableColumn("secure",WI.unlocalizedString("Secure"),{minWidth:55,maxWidth:65,align:"center"}));this._responseCookiesTable.addColumn(new WI.TableColumn("httpOnly",WI.unlocalizedString("HttpOnly"),{minWidth:55,maxWidth:65,align:"center"}));this._responseCookiesTable.addColumn(new WI.TableColumn("sameSite",WI.unlocalizedString("SameSite"),{minWidth:55,maxWidth:65}));if(!this._responseCookiesTable.sortColumnIdentifier){this._responseCookiesTable.sortOrder=WI.Table.SortOrder.Ascending;this._responseCookiesTable.sortColumnIdentifier="name";}}
if(!this._responseCookiesDataSource.length){if(this._responseCookiesTable.isAttached)
this.removeSubview(this._responseCookiesTable);this._responseCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No response cookies."));}else{this._responseCookiesSection.toggleIncomplete(false);this._responseCookiesTable.element.style.height=this._sizeForTable(this._responseCookiesTable)+"px";this.addSubview(this._responseCookiesTable);detailsElement.classList.add("has-table");detailsElement.appendChild(this._responseCookiesTable.element);}}
_sizeForTable(table)
{const headerHeight=28;const borderHeight=3;let rowsHeight=this._dataSourceForTable(table).length*table.rowHeight;return rowsHeight+headerHeight+borderHeight;}
_resourceRequestHeadersDidChange(event)
{this._refreshRequestCookiesSection();}
_resourceResponseReceived(event)
{this._refreshResponseCookiesSection();}};WI.ResourceDetailsSection=class ResourceDetailsSection
{constructor(title,className)
{this._element=document.createElement("section");if(className)
this._element.className=className;this._titleElement=this._element.appendChild(document.createElement("div"));this._titleElement.className="title";this._titleElement.textContent=title;this._detailsElement=this._element.appendChild(document.createElement("div"));this._detailsElement.className="details";this._element.appendChild(document.createElement("br"));} 
get element(){return this._element;}
get titleElement(){return this._titleElement;}
get detailsElement(){return this._detailsElement;}
toggleIncomplete(isIncomplete)
{this.element.classList.toggle("incomplete",isIncomplete);}
toggleError(isError)
{this.element.classList.toggle("error",isError);}
markIncompleteSectionWithMessage(message)
{this.toggleIncomplete(true);let p=this._detailsElement.appendChild(document.createElement("p"));p.textContent=message;}
markIncompleteSectionWithLoadingIndicator()
{this.toggleIncomplete(true);let p=this._detailsElement.appendChild(document.createElement("p"));let spinner=new WI.IndeterminateProgressSpinner;p.appendChild(spinner.element);}
appendKeyValuePair(key,value,className)
{let p=this._detailsElement.appendChild(document.createElement("p"));p.className="pair";if(className)
p.classList.add(className);let keyElement=p.appendChild(document.createElement("span"));keyElement.className="key";if(key instanceof Node)
keyElement.appendChild(key);else{keyElement.textContent=key+(value?": ":"");let valueElement=p.appendChild(document.createElement("bdi"));valueElement.className="value";valueElement.append(value||"");}
return p;}};WI.ResourceDetailsSidebarPanel=class ResourceDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("resource-details",WI.UIString("Resource"));this.element.classList.add("resource");this._resource=null;this._needsToApplyResourceEventListeners=false;this._needsToRemoveResourceEventListeners=false;} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];var resourceToInspect=null;for(let object of objects){if(object instanceof WI.Resource){resourceToInspect=object;break;}
if(object instanceof WI.Frame){resourceToInspect=object.mainResource;break;}

if(object instanceof WI.Script&&object.isMainResource()&&object.resource){resourceToInspect=object.resource;break;}}
this.resource=resourceToInspect;return!!this._resource;}
get resource()
{return this._resource;}
set resource(resource)
{if(resource===this._resource)
return;if(this._resource&&this._needsToRemoveResourceEventListeners){this._resource.removeEventListener(WI.Resource.Event.URLDidChange,this._refreshURL,this);this._resource.removeEventListener(WI.Resource.Event.MIMETypeDidChange,this._refreshMIMEType,this);this._resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._refreshResourceType,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFail,this._refreshErrorReason,this);this._resource.removeEventListener(WI.Resource.Event.RequestHeadersDidChange,this._refreshRequestHeaders,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.CacheStatusDidChange,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.SizeDidChange,this._refreshDecodedSize,this);this._resource.removeEventListener(WI.Resource.Event.TransferSizeDidChange,this._refreshTransferSize,this);this._resource.removeEventListener(WI.Resource.Event.InitiatedResourcesDidChange,this._handleResourceInitiatedResourcesDidChange,this);this._refreshRelatedResourcesSectionThrottler.cancel();this._needsToRemoveResourceEventListeners=false;}
this._resource=resource;if(this._resource){if(this.didInitialLayout)
this._applyResourceEventListeners();else
this._needsToApplyResourceEventListeners=true;}
this.needsLayout();} 
initialLayout()
{super.initialLayout();this._typeMIMETypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("MIME Type"));this._typeResourceTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Resource Type"));this._typeSection=new WI.DetailsSection("resource-type",WI.UIString("Type"));this._typeSection.groups=[new WI.DetailsSectionGroup([this._typeMIMETypeRow,this._typeResourceTypeRow])];this._locationFullURLRow=new WI.DetailsSectionSimpleRow(WI.UIString("Full URL"));this._locationSchemeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Scheme"));this._locationHostRow=new WI.DetailsSectionSimpleRow(WI.UIString("Host"));this._locationPortRow=new WI.DetailsSectionSimpleRow(WI.UIString("Port"));this._locationPathRow=new WI.DetailsSectionSimpleRow(WI.UIString("Path"));this._locationQueryStringRow=new WI.DetailsSectionSimpleRow(WI.UIString("Query String"));this._locationFragmentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Fragment"));this._locationFilenameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Filename"));this._initiatorRow=new WI.DetailsSectionSimpleRow(WI.UIString("Initiator"));this._initiatedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Initiated"));var firstGroup=[this._locationFullURLRow];var secondGroup=[this._locationSchemeRow,this._locationHostRow,this._locationPortRow,this._locationPathRow,this._locationQueryStringRow,this._locationFragmentRow,this._locationFilenameRow];var thirdGroup=[this._initiatorRow,this._initiatedRow];this._fullURLGroup=new WI.DetailsSectionGroup(firstGroup);this._locationURLComponentsGroup=new WI.DetailsSectionGroup(secondGroup);this._relatedResourcesGroup=new WI.DetailsSectionGroup(thirdGroup);this._locationSection=new WI.DetailsSection("resource-location",WI.UIString("Location"),[this._fullURLGroup,this._locationURLComponentsGroup,this._relatedResourcesGroup]);this._queryParametersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Query Parameters"));this._queryParametersSection=new WI.DetailsSection("resource-query-parameters",WI.UIString("Query Parameters"));this._queryParametersSection.groups=[new WI.DetailsSectionGroup([this._queryParametersRow])];this._requestDataSection=new WI.DetailsSection("resource-request-data",WI.UIString("Request Data"));this._requestMethodRow=new WI.DetailsSectionSimpleRow(WI.UIString("Method"));this._protocolRow=new WI.DetailsSectionSimpleRow(WI.UIString("Protocol"));this._priorityRow=new WI.DetailsSectionSimpleRow(WI.UIString("Priority"));this._cachedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Cached"));this._statusTextRow=new WI.DetailsSectionSimpleRow(WI.UIString("Status"));this._statusCodeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Code"));this._errorReasonRow=new WI.DetailsSectionSimpleRow(WI.UIString("Error"));this._remoteAddressRow=new WI.DetailsSectionSimpleRow(WI.UIString("IP Address"));this._connectionIdentifierRow=new WI.DetailsSectionSimpleRow(WI.UIString("Connection ID"));this._encodedSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Encoded"));this._decodedSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Decoded"));this._transferSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Transferred"));this._compressedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Compressed"));this._compressionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Compression"));let requestGroup=new WI.DetailsSectionGroup([this._requestMethodRow,this._protocolRow,this._priorityRow,this._cachedRow]);let statusGroup=new WI.DetailsSectionGroup([this._statusTextRow,this._statusCodeRow,this._errorReasonRow]);let connectionGroup=new WI.DetailsSectionGroup([this._remoteAddressRow,this._connectionIdentifierRow]);let sizeGroup=new WI.DetailsSectionGroup([this._encodedSizeRow,this._decodedSizeRow,this._transferSizeRow]);let compressionGroup=new WI.DetailsSectionGroup([this._compressedRow,this._compressionRow]);this._requestAndResponseSection=new WI.DetailsSection("resource-request-response",WI.UIString("Request & Response"));this._requestAndResponseSection.groups=[requestGroup,statusGroup,connectionGroup,sizeGroup,compressionGroup];this._requestHeadersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Request Headers"));this._requestHeadersSection=new WI.DetailsSection("resource-request-headers",WI.UIString("Request Headers"));this._requestHeadersSection.groups=[new WI.DetailsSectionGroup([this._requestHeadersRow])];this._responseHeadersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Response Headers"));this._responseHeadersSection=new WI.DetailsSection("resource-response-headers",WI.UIString("Response Headers"));this._responseHeadersSection.groups=[new WI.DetailsSectionGroup([this._responseHeadersRow])];this._imageWidthRow=new WI.DetailsSectionSimpleRow(WI.UIString("Width"));this._imageHeightRow=new WI.DetailsSectionSimpleRow(WI.UIString("Height"));this._imageSizeSection=new WI.DetailsSection("resource-type",WI.UIString("Image Size"));this._imageSizeSection.groups=[new WI.DetailsSectionGroup([this._imageWidthRow,this._imageHeightRow])];this.contentView.element.appendChild(this._typeSection.element);this.contentView.element.appendChild(this._locationSection.element);this.contentView.element.appendChild(this._requestAndResponseSection.element);this.contentView.element.appendChild(this._requestHeadersSection.element);this.contentView.element.appendChild(this._responseHeadersSection.element);if(this._needsToApplyResourceEventListeners){this._applyResourceEventListeners();this._needsToApplyResourceEventListeners=false;}}
layout()
{super.layout();if(!this._resource)
return;this._refreshURL();this._refreshMIMEType();this._refreshResourceType();this._refreshRequestAndResponse();this._refreshDecodedSize();this._refreshTransferSize();this._refreshRequestHeaders();this._refreshImageSizeSection();this._refreshRequestDataSection();this._refreshRelatedResourcesSectionThrottler.force();}
sizeDidChange()
{super.sizeDidChange(); this._queryParametersRow.sizeDidChange();this._requestHeadersRow.sizeDidChange();this._responseHeadersRow.sizeDidChange();} 
_refreshURL()
{if(!this._resource)
return;this._locationFullURLRow.value=this._resource.displayURL.insertWordBreakCharacters();var urlComponents=this._resource.urlComponents;if(urlComponents.scheme){this._locationSection.groups=[this._fullURLGroup,this._locationURLComponentsGroup,this._relatedResourcesGroup];this._locationSchemeRow.value=urlComponents.scheme?urlComponents.scheme:null;this._locationHostRow.value=urlComponents.host?urlComponents.host:null;this._locationPortRow.value=urlComponents.port?urlComponents.port:null;this._locationPathRow.value=urlComponents.path?urlComponents.path.insertWordBreakCharacters():null;this._locationQueryStringRow.value=urlComponents.queryString?urlComponents.queryString.insertWordBreakCharacters():null;this._locationFragmentRow.value=urlComponents.fragment?urlComponents.fragment.insertWordBreakCharacters():null;this._locationFilenameRow.value=urlComponents.lastPathComponent?urlComponents.lastPathComponent.insertWordBreakCharacters():null;}else{this._locationSection.groups=[this._fullURLGroup,this._relatedResourcesGroup];}
if(urlComponents.queryString){this.contentView.element.insertBefore(this._queryParametersSection.element,this._requestAndResponseSection.element.nextSibling);this._queryParametersRow.dataGrid=this._createNameValueDataGrid(parseQueryString(urlComponents.queryString,true));}else{var queryParametersSectionElement=this._queryParametersSection.element;if(queryParametersSectionElement.parentNode)
queryParametersSectionElement.parentNode.removeChild(queryParametersSectionElement);}}
_refreshRelatedResourcesSection()
{let groups=this._locationSection.groups;let isSectionVisible=groups.includes(this._relatedResourcesGroup);if(!this._resource.initiatorSourceCodeLocation&&!this._resource.initiatedResources.length){if(isSectionVisible){groups.remove(this._relatedResourcesGroup);this._locationSection.groups=groups;}
return;}
if(!isSectionVisible){groups.push(this._relatedResourcesGroup);this._locationSection.groups=groups;}
let initiatorLocation=this._resource.initiatorSourceCodeLocation;if(initiatorLocation){const options={dontFloat:true,ignoreSearchTab:true,};this._initiatorRow.value=WI.createSourceCodeLocationLink(initiatorLocation,options);}else
this._initiatorRow.value=null;let initiatedResources=this._resource.initiatedResources;if(initiatedResources.length){let resourceLinkContainer=document.createElement("div");for(let resource of initiatedResources)
resourceLinkContainer.appendChild(WI.createResourceLink(resource));this._initiatedRow.value=resourceLinkContainer;}else
this._initiatedRow.value=null;}
_refreshResourceType()
{if(!this._resource)
return;this._typeResourceTypeRow.value=WI.Resource.displayNameForType(this._resource.type);}
_refreshMIMEType()
{if(!this._resource)
return;this._typeMIMETypeRow.value=this._resource.mimeType;}
_refreshErrorReason()
{if(!this._resource)
return;if(!this._resource.hadLoadingError()){this._errorReasonRow.value=null;return;}
if(this._resource.failureReasonText)
this._errorReasonRow.value=this._resource.failureReasonText;else if(this._resource.statusCode>=400)
this._errorReasonRow.value=WI.UIString("Failure status code");else if(this._resource.canceled)
this._errorReasonRow.value=WI.UIString("Load cancelled");else
this._errorReasonRow.value=WI.UIString("Unknown error");}
_refreshRequestAndResponse()
{if(!this._resource)
return;this._requestMethodRow.value=this._resource.requestMethod||emDash;if(InspectorBackend.hasEvent("Network.loadingFinished","metrics")){let protocolDisplayName=WI.Resource.displayNameForProtocol(this._resource.protocol);this._protocolRow.value=protocolDisplayName||emDash;this._protocolRow.tooltip=protocolDisplayName?this._resource.protocol:"";this._priorityRow.value=WI.Resource.displayNameForPriority(this._resource.priority)||emDash;this._remoteAddressRow.value=this._resource.remoteAddress||emDash;this._connectionIdentifierRow.value=this._resource.connectionIdentifier||emDash;}
this._cachedRow.value=this._cachedRowValue();this._statusCodeRow.value=this._resource.statusCode||emDash;this._statusTextRow.value=this._resource.statusText||emDash;this._refreshErrorReason();this._refreshResponseHeaders();this._refreshCompressed();}
_valueForSize(size)
{return size>0?Number.bytesToString(size):emDash;}
_refreshCompressed()
{if(this._resource.compressed){this._compressedRow.value=WI.UIString("Yes");if(!this._resource.size)
this._compressionRow.value=emDash;else if(!isNaN(this._resource.networkEncodedSize))
this._compressionRow.value=this._resource.networkEncodedSize?WI.UIString("%.2f\u00d7").format(this._resource.size/this._resource.networkEncodedSize):emDash;else
this._compressionRow.value=this._resource.estimatedNetworkEncodedSize?WI.UIString("%.2f\u00d7").format(this._resource.size/this._resource.estimatedNetworkEncodedSize):emDash;}else{this._compressedRow.value=WI.UIString("No");this._compressionRow.value=null;}}
_refreshDecodedSize()
{if(!this._resource)
return;let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let decodedSize=!isNaN(this._resource.networkDecodedSize)?this._resource.networkDecodedSize:this._resource.size;this._encodedSizeRow.value=this._valueForSize(encodedSize);this._decodedSizeRow.value=this._valueForSize(decodedSize);this._refreshCompressed();}
_refreshTransferSize()
{if(!this._resource)
return;let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let transferSize=!isNaN(this._resource.networkTotalTransferSize)?this._resource.networkTotalTransferSize:this._resource.estimatedTotalTransferSize;this._encodedSizeRow.value=this._valueForSize(encodedSize);this._transferSizeRow.value=this._valueForSize(transferSize);this._refreshCompressed();}
_refreshRequestHeaders()
{if(!this._resource)
return;this._requestHeadersRow.dataGrid=this._createNameValueDataGrid(this._resource.requestHeaders);}
_refreshResponseHeaders()
{if(!this._resource)
return;this._responseHeadersRow.dataGrid=this._createNameValueDataGrid(this._resource.responseHeaders);}
_createNameValueDataGrid(data)
{if(!data||data instanceof Array?!data.length:isEmptyObject(data))
return null;var dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name"),width:"30%",sortable:true},value:{title:WI.UIString("Value"),sortable:true}});dataGrid.copyTextDelimiter=": ";function addDataGridNode(nodeValue)
{var node=new WI.DataGridNode({name:nodeValue.name,value:nodeValue.value||""});dataGrid.appendChild(node);}
if(data instanceof Array){for(var i=0;i<data.length;++i)
addDataGridNode(data[i]);}else{for(var name in data)
addDataGridNode({name,value:data[name]||""});}
dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,sortDataGrid,this);function sortDataGrid()
{var sortColumnIdentifier=dataGrid.sortColumnIdentifier;function comparator(a,b)
{var item1=a.data[sortColumnIdentifier];var item2=b.data[sortColumnIdentifier];return item1.extendedLocaleCompare(item2);}
dataGrid.sortNodes(comparator);}
return dataGrid;}
_refreshImageSizeSection()
{var resource=this._resource;if(!resource)
return;function hideImageSection(){this._imageSizeSection.element.remove();}
if(resource.type!==WI.Resource.Type.Image||resource.failed){hideImageSection.call(this);return;}
this.contentView.element.insertBefore(this._imageSizeSection.element,this._locationSection.element);resource.getImageSize((size)=>{if(size){this._imageWidthRow.value=WI.UIString("%dpx").format(size.width);this._imageHeightRow.value=WI.UIString("%dpx").format(size.height);}else
hideImageSection.call(this);});}
_cachedRowValue()
{let responseSource=this._resource.responseSource;if(responseSource===WI.Resource.ResponseSource.MemoryCache||responseSource===WI.Resource.ResponseSource.DiskCache){let span=document.createElement("span");let cacheType=document.createElement("span");cacheType.classList="cache-type";cacheType.textContent=responseSource===WI.Resource.ResponseSource.MemoryCache?WI.UIString("(Memory)"):WI.UIString("(Disk)");span.append(WI.UIString("Yes")," ",cacheType);return span;}
return this._resource.cached?WI.UIString("Yes"):WI.UIString("No");}
_goToRequestDataClicked()
{const options={ignoreSearchTab:true,};WI.showResourceRequest(this._resource,options);}
_refreshRequestDataSection()
{var resource=this._resource;if(!resource)
return;var requestData=resource.requestData;if(!requestData){this._requestDataSection.element.remove();return;}
this.contentView.element.insertBefore(this._requestDataSection.element,this._requestHeadersSection.element);var requestDataContentType=resource.requestDataContentType||"";if(requestDataContentType&&requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){var parametersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Parameters"));parametersRow.dataGrid=this._createNameValueDataGrid(parseQueryString(requestData,true));this._requestDataSection.groups=[new WI.DetailsSectionGroup([parametersRow])];return;}
var mimeTypeComponents=parseMIMEType(requestDataContentType);var mimeType=mimeTypeComponents.type;var boundary=mimeTypeComponents.boundary;var encoding=mimeTypeComponents.encoding;var rows=[];var mimeTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("MIME Type"));mimeTypeRow.value=mimeType;rows.push(mimeTypeRow);if(boundary){var boundryRow=new WI.DetailsSectionSimpleRow(WI.UIString("Boundary"));boundryRow.value=boundary;rows.push(boundryRow);}
if(encoding){var encodingRow=new WI.DetailsSectionSimpleRow(WI.UIString("Encoding"));encodingRow.value=encoding;rows.push(encodingRow);}
var sizeValue=Number.bytesToString(requestData.length);var dataValue=document.createDocumentFragment();dataValue.append(sizeValue);var goToButton=dataValue.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",this._goToRequestDataClicked.bind(this));var dataRow=new WI.DetailsSectionSimpleRow(WI.UIString("Data"));dataRow.value=dataValue;rows.push(dataRow);this._requestDataSection.groups=[new WI.DetailsSectionGroup(rows)];}
_applyResourceEventListeners()
{if(!this._refreshRelatedResourcesSectionThrottler){this._refreshRelatedResourcesSectionThrottler=new Throttler(()=>{this._refreshRelatedResourcesSection();},250);}
this._resource.addEventListener(WI.Resource.Event.URLDidChange,this._refreshURL,this);this._resource.addEventListener(WI.Resource.Event.MIMETypeDidChange,this._refreshMIMEType,this);this._resource.addEventListener(WI.Resource.Event.TypeDidChange,this._refreshResourceType,this);this._resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._refreshErrorReason,this);this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._refreshRequestHeaders,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.CacheStatusDidChange,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.SizeDidChange,this._refreshDecodedSize,this);this._resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._refreshTransferSize,this);this._resource.addEventListener(WI.Resource.Event.InitiatedResourcesDidChange,this._handleResourceInitiatedResourcesDidChange,this);this._needsToRemoveResourceEventListeners=true;}
_handleResourceInitiatedResourcesDidChange(event)
{this._refreshRelatedResourcesSectionThrottler.fire();}};WI.ResourceHeadersContentView=class ResourceHeadersContentView extends WI.ContentView
{constructor(resource,delegate)
{super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);this._delegate=delegate;this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;this._automaticallyRevealFirstSearchResult=false;this._bouncyHighlightElement=null;this._popover=null;this._popoverCallStackIconElement=null;this._redirectDetailsSections=[];this.element.classList.add("resource-details","resource-headers");this.element.tabIndex=0;this._needsSummaryRefresh=false;this._needsRedirectHeadersRefresh=false;this._needsRequestHeadersRefresh=false;this._needsResponseHeadersRefresh=false;} 
initialLayout()
{super.initialLayout();this._summarySection=new WI.ResourceDetailsSection(WI.UIString("Summary"),"summary");this.element.appendChild(this._summarySection.element);this._refreshSummarySection();this._refreshRedirectHeadersSections();this._requestHeadersSection=new WI.ResourceDetailsSection(WI.UIString("Request"),"headers");this.element.appendChild(this._requestHeadersSection.element);this._refreshRequestHeadersSection();this._responseHeadersSection=new WI.ResourceDetailsSection(WI.UIString("Response"),"headers");this.element.appendChild(this._responseHeadersSection.element);this._refreshResponseHeadersSection();if(this._resource.urlComponents.queryString){this._queryStringSection=new WI.ResourceDetailsSection(WI.UIString("Query String Parameters"));this.element.appendChild(this._queryStringSection.element);this._refreshQueryStringSection();}
if(this._resource.requestData){this._requestDataSection=new WI.ResourceDetailsSection(WI.UIString("Request Data"));this.element.appendChild(this._requestDataSection.element);this._refreshRequestDataSection();}
this._needsSummaryRefresh=false;this._needsRedirectHeadersRefresh=false;this._needsRequestHeadersRefresh=false;this._needsResponseHeadersRefresh=false;}
layout()
{super.layout();if(this._needsSummaryRefresh){this._refreshSummarySection();this._needsSummaryRefresh=false;}
if(this._needsRedirectHeadersRefresh){this._refreshRedirectHeadersSections();this._needsRedirectHeadersRefresh=false;}
if(this._needsRequestHeadersRefresh){this._refreshRequestHeadersSection();this._needsRequestHeadersRefresh=false;}
if(this._needsResponseHeadersRefresh){this._refreshResponseHeadersSection();this._needsResponseHeadersRefresh=false;}}
detached()
{if(this._popover)
this._popover.dismiss();super.detached();}
closed()
{this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.removeEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);super.closed();}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._searchResults?this._searchResults.length:null;}
get hasPerformedSearch()
{return this._searchResults!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this.numberOfSearchResults>0){if(this._searchIndex===-1)
this.revealNextSearchResult();}}
performSearch(query)
{if(query===this._searchQuery)
return;WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=query;this._searchResults=[];this._searchDOMChanges=[];this._searchIndex=-1;this._perfomSearchOnKeyValuePairs();this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0)
this.revealNextSearchResult();}
searchCleared()
{WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;}
revealPreviousSearchResult(changeFocus)
{if(!this.numberOfSearchResults)
return;if(this._searchIndex>0)
--this._searchIndex;else
this._searchIndex=this._searchResults.length-1;this._revealSearchResult(this._searchIndex,changeFocus);}
revealNextSearchResult(changeFocus)
{if(!this.numberOfSearchResults)
return;if(this._searchIndex+1<this._searchResults.length)
++this._searchIndex;else
this._searchIndex=0;this._revealSearchResult(this._searchIndex,changeFocus);} 
_responseSourceDisplayString(responseSource)
{switch(responseSource){case WI.Resource.ResponseSource.Network:return WI.UIString("Network");case WI.Resource.ResponseSource.MemoryCache:return WI.UIString("Memory Cache");case WI.Resource.ResponseSource.DiskCache:return WI.UIString("Disk Cache");case WI.Resource.ResponseSource.ServiceWorker:return WI.UIString("Service Worker");case WI.Resource.ResponseSource.InspectorOverride:return WI.UIString("Local Override");case WI.Resource.ResponseSource.Unknown:default:return null;}}
_refreshSummarySection()
{let detailsElement=this._summarySection.detailsElement;detailsElement.removeChildren();this._summarySection.toggleError(this._resource.hadLoadingError());for(let redirect of this._resource.redirects)
this._summarySection.appendKeyValuePair(WI.UIString("URL"),redirect.url.insertWordBreakCharacters(),"url");this._summarySection.appendKeyValuePair(WI.UIString("URL"),this._resource.displayURL.insertWordBreakCharacters(),"url");let status=emDash;if(!isNaN(this._resource.statusCode))
status=this._resource.statusCode+(this._resource.statusText?" "+this._resource.statusText:"");this._summarySection.appendKeyValuePair(WI.UIString("Status"),status); let source=this._responseSourceDisplayString(this._resource.responseSource)||emDash;this._summarySection.appendKeyValuePair(WI.UIString("Source"),source);if(this._resource.remoteAddress)
this._summarySection.appendKeyValuePair(WI.UIString("Address"),this._resource.remoteAddress);let initiatorLocation=this._resource.initiatorSourceCodeLocation;if(initiatorLocation){let fragment=document.createDocumentFragment();const options={dontFloat:true,ignoreSearchTab:true,ignoreNetworkTab:true,};let link=WI.createSourceCodeLocationLink(initiatorLocation,options);fragment.appendChild(link);let callFrames=this._resource.initiatorCallFrames;if(callFrames){this._popoverCallStackIconElement=document.createElement("img");this._popoverCallStackIconElement.className="call-stack";fragment.appendChild(this._popoverCallStackIconElement);this._popoverCallStackIconElement.addEventListener("click",(event)=>{if(!this._popover){this._popover=new WI.Popover(this);this._popover.windowResizeHandler=()=>{this._presentPopoverBelowCallStackElement();};}
const selectable=false;let callFramesTreeOutline=new WI.TreeOutline(selectable);callFramesTreeOutline.disclosureButtons=false;let callFrameTreeController=new WI.CallFrameTreeController(callFramesTreeOutline);callFrameTreeController.callFrames=callFrames;let popoverContent=document.createElement("div");popoverContent.appendChild(callFrameTreeController.treeOutline.element);this._popover.content=popoverContent;this._presentPopoverBelowCallStackElement();});}
let pair=this._summarySection.appendKeyValuePair(WI.UIString("Initiator"),fragment);pair.classList.add("initiator");if(this._popover&&this._popover.visible)
this._presentPopoverBelowCallStackElement();}}
_refreshRedirectHeadersSections()
{let referenceElement=this._redirectDetailsSections.length?this._redirectDetailsSections.lastValue.element:this._summarySection.element;for(let i=this._redirectDetailsSections.length;i<this._resource.redirects.length;++i){let redirect=this._resource.redirects[i];let redirectRequestSection=new WI.ResourceDetailsSection(WI.UIString("Request"),"redirect"); redirectRequestSection.appendKeyValuePair(`${redirect.requestMethod} ${redirect.urlComponents.path}`,null,"h1-status");for(let key in redirect.requestHeaders)
redirectRequestSection.appendKeyValuePair(key,redirect.requestHeaders[key],"header");referenceElement=this.element.insertBefore(redirectRequestSection.element,referenceElement.nextElementSibling);this._redirectDetailsSections.push(redirectRequestSection);let redirectResponseSection=new WI.ResourceDetailsSection(WI.UIString("Redirect Response"),"redirect"); redirectResponseSection.appendKeyValuePair(`${redirect.responseStatusCode} ${redirect.responseStatusText}`,null,"h1-status");for(let key in redirect.responseHeaders)
redirectResponseSection.appendKeyValuePair(key,redirect.responseHeaders[key],"header");referenceElement=this.element.insertBefore(redirectResponseSection.element,referenceElement.nextElementSibling);this._redirectDetailsSections.push(redirectResponseSection);}}
_refreshRequestHeadersSection()
{let detailsElement=this._requestHeadersSection.detailsElement;detailsElement.removeChildren();if(this._resource.statusCode!==304){if(this._resource.responseSource===WI.Resource.ResponseSource.MemoryCache){this._requestHeadersSection.markIncompleteSectionWithMessage(WI.UIString("No request, served from the memory cache."));return;}
if(this._resource.responseSource===WI.Resource.ResponseSource.DiskCache){this._requestHeadersSection.markIncompleteSectionWithMessage(WI.UIString("No request, served from the disk cache."));return;}}
let protocol=this._resource.protocol||"";let urlComponents=this._resource.urlComponents;if(protocol.startsWith("http/1")){ let requestLine=`${this._resource.requestMethod} ${urlComponents.path} ${protocol.toUpperCase()}`;this._requestHeadersSection.appendKeyValuePair(requestLine,null,"h1-status");}else if(protocol==="h2"){ this._requestHeadersSection.appendKeyValuePair(":method",this._resource.requestMethod,"h2-pseudo-header");this._requestHeadersSection.appendKeyValuePair(":scheme",urlComponents.scheme,"h2-pseudo-header");this._requestHeadersSection.appendKeyValuePair(":authority",WI.h2Authority(urlComponents),"h2-pseudo-header");this._requestHeadersSection.appendKeyValuePair(":path",WI.h2Path(urlComponents),"h2-pseudo-header");}
let requestHeaders=this._resource.requestHeaders;for(let key in requestHeaders)
this._requestHeadersSection.appendKeyValuePair(key,requestHeaders[key],"header");if(!detailsElement.firstChild)
this._requestHeadersSection.markIncompleteSectionWithMessage(WI.UIString("No request headers"));}
_refreshResponseHeadersSection()
{let detailsElement=this._responseHeadersSection.detailsElement;detailsElement.removeChildren();if(!this._resource.hasResponse()){this._responseHeadersSection.markIncompleteSectionWithLoadingIndicator();return;}
this._responseHeadersSection.toggleIncomplete(false);let protocol=this._resource.protocol||"";if(protocol.startsWith("http/1")){ let responseLine=`${protocol.toUpperCase()} ${this._resource.statusCode} ${this._resource.statusText}`;this._responseHeadersSection.appendKeyValuePair(responseLine,null,"h1-status");}else if(protocol==="h2"){ this._responseHeadersSection.appendKeyValuePair(":status",this._resource.statusCode,"h2-pseudo-header");}
let responseHeaders=this._resource.responseHeaders;for(let key in responseHeaders){if(key.toLowerCase()==="set-cookie"){let responseCookies=this._resource.responseCookies;for(let cookie of responseCookies)
this._responseHeadersSection.appendKeyValuePair(key,cookie.header,"header");continue;}
this._responseHeadersSection.appendKeyValuePair(key,responseHeaders[key],"header");}
if(!detailsElement.firstChild)
this._responseHeadersSection.markIncompleteSectionWithMessage(WI.UIString("No response headers"));}
_refreshQueryStringSection()
{if(!this._queryStringSection)
return;let detailsElement=this._queryStringSection.detailsElement;detailsElement.removeChildren();let queryString=this._resource.urlComponents.queryString;let queryStringPairs=parseQueryString(queryString,true);for(let{name,value}of queryStringPairs)
this._queryStringSection.appendKeyValuePair(name,value);}
_refreshRequestDataSection()
{if(!this._requestDataSection)
return;let detailsElement=this._requestDataSection.detailsElement;detailsElement.removeChildren();let requestData=this._resource.requestData;let requestDataContentType=this._resource.requestDataContentType||"";if(requestDataContentType&&requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){this._requestDataSection.appendKeyValuePair(WI.UIString("MIME Type"),requestDataContentType);let queryStringPairs=parseQueryString(requestData,true);for(let{name,value}of queryStringPairs)
this._requestDataSection.appendKeyValuePair(name,value);return;}
let mimeTypeComponents=parseMIMEType(requestDataContentType);let mimeType=mimeTypeComponents.type;let boundary=mimeTypeComponents.boundary;let encoding=mimeTypeComponents.encoding;this._requestDataSection.appendKeyValuePair(WI.UIString("MIME Type"),mimeType);if(boundary)
this._requestDataSection.appendKeyValuePair(WI.UIString("Boundary"),boundary);if(encoding)
this._requestDataSection.appendKeyValuePair(WI.UIString("Encoding"),encoding);let goToButton=detailsElement.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",()=>{this._delegate.headersContentViewGoToRequestData(this);});this._requestDataSection.appendKeyValuePair(WI.UIString("Request Data"),goToButton);}
_perfomSearchOnKeyValuePairs()
{let searchRegex=WI.SearchUtilities.searchRegExpForString(this._searchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;}
let elements=this.element.querySelectorAll(".key, .value");for(let element of elements){let matchRanges=[];let text=element.textContent;let match;while(match=searchRegex.exec(text))
matchRanges.push({offset:match.index,length:match[0].length});if(matchRanges.length){let highlightedNodes=WI.highlightRangesWithStyleClass(element,matchRanges,"search-highlight",this._searchDOMChanges);this._searchResults.pushAll(highlightedNodes);}}}
_revealSearchResult(index,changeFocus)
{let highlightElement=this._searchResults[index];if(!highlightElement)
return;highlightElement.scrollIntoViewIfNeeded();if(!this._bouncyHighlightElement){this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className="bouncy-highlight";this._bouncyHighlightElement.addEventListener("animationend",(event)=>{this._bouncyHighlightElement.remove();});}
this._bouncyHighlightElement.remove();let computedStyles=window.getComputedStyle(highlightElement);let highlightElementRect=highlightElement.getBoundingClientRect();let contentViewRect=this.element.getBoundingClientRect();let contentViewScrollTop=this.element.scrollTop;let contentViewScrollLeft=this.element.scrollLeft;this._bouncyHighlightElement.textContent=highlightElement.textContent;this._bouncyHighlightElement.style.top=(highlightElementRect.top-contentViewRect.top+contentViewScrollTop)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-contentViewRect.left+contentViewScrollLeft)+"px";this._bouncyHighlightElement.style.fontWeight=computedStyles.fontWeight;this.element.appendChild(this._bouncyHighlightElement);}
_presentPopoverBelowCallStackElement()
{let bounds=WI.Rect.rectFromClientRect(this._popoverCallStackIconElement.getBoundingClientRect());this._popover.present(bounds.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);}
_resourceMetricsDidChange(event)
{this._needsSummaryRefresh=true;this._needsRequestHeadersRefresh=true;this._needsResponseHeadersRefresh=true;this.needsLayout();}
_resourceRequestHeadersDidChange(event)
{this._needsSummaryRefresh=true;this._needsRedirectHeadersRefresh=true;this._needsRequestHeadersRefresh=true;this.needsLayout();}
_resourceResponseReceived(event)
{this._needsSummaryRefresh=true;this._needsResponseHeadersRefresh=true;this.needsLayout();}};WI.ResourceSecurityContentView=class ResourceSecurityContentView extends WI.ContentView
{constructor(resource)
{super();this._resource=resource;this._insecureMessageElement=null;this._needsConnectionRefresh=true;this._needsCertificateRefresh=true;this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;this._automaticallyRevealFirstSearchResult=false;this._bouncyHighlightElement=null;this.element.classList.add("resource-details","resource-security");} 
initialLayout()
{super.initialLayout();this._connectionSection=new WI.ResourceDetailsSection(WI.UIString("Connection"),"connection");this.element.appendChild(this._connectionSection.element);this._certificateSection=new WI.ResourceDetailsSection(WI.UIString("Certificate"),"certificate");this.element.appendChild(this._certificateSection.element);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._handleResourceResponseReceived,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._handleResourceMetricsDidChange,this);}
layout()
{super.layout();if(!this._resource.loadedSecurely){if(!this._insecureMessageElement)
this._insecureMessageElement=WI.createMessageTextView(WI.UIString("The resource was requested insecurely."),true);this.element.appendChild(this._insecureMessageElement);return;}
if(this._needsConnectionRefresh){this._needsConnectionRefresh=false;this._refreshConnectionSection();}
if(this._needsCertificateRefresh){this._needsCertificateRefresh=false;this._refreshCetificateSection();}}
closed()
{if(this.didInitialLayout){this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._handleResourceResponseReceived,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._handleResourceMetricsDidChange,this);}
super.closed();}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._searchResults?this._searchResults.length:null;}
get hasPerformedSearch()
{return this._searchResults!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this.numberOfSearchResults>0){if(this._searchIndex===-1)
this.revealNextSearchResult();}}
performSearch(query)
{if(query===this._searchQuery)
return;WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=query;this._searchResults=[];this._searchDOMChanges=[];this._searchIndex=-1;this._perfomSearchOnKeyValuePairs();this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0)
this.revealNextSearchResult();}
searchCleared()
{WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;}
revealPreviousSearchResult(changeFocus)
{if(!this.numberOfSearchResults)
return;if(this._searchIndex>0)
--this._searchIndex;else
this._searchIndex=this._searchResults.length-1;this._revealSearchResult(this._searchIndex,changeFocus);}
revealNextSearchResult(changeFocus)
{if(!this.numberOfSearchResults)
return;if(this._searchIndex<this._searchResults.length-1)
++this._searchIndex;else
this._searchIndex=0;this._revealSearchResult(this._searchIndex,changeFocus);} 
_refreshConnectionSection()
{let detailsElement=this._connectionSection.detailsElement;detailsElement.removeChildren();let security=this._resource.security;if(isEmptyObject(security)){this._connectionSection.markIncompleteSectionWithMessage(WI.UIString("No connection security information."));return;}
let connection=security.connection;if(isEmptyObject(connection)||Object.values(connection).every((value)=>!value)){this._connectionSection.markIncompleteSectionWithMessage(WI.UIString("No connection security information."));return;}
this._connectionSection.appendKeyValuePair(WI.UIString("Protocol"),connection.protocol||emDash);this._connectionSection.appendKeyValuePair(WI.UIString("Cipher"),connection.cipher||emDash);}
_refreshCetificateSection()
{let detailsElement=this._certificateSection.detailsElement;detailsElement.removeChildren();let security=this._resource.security;if(isEmptyObject(security)){this._certificateSection.markIncompleteSectionWithMessage(WI.UIString("No certificate security information."));return;}
let certificate=security.certificate;if(isEmptyObject(certificate)||Object.values(certificate).every((value)=>!value)){this._certificateSection.markIncompleteSectionWithMessage(WI.UIString("No certificate security information."));return;}
if(WI.NetworkManager.supportsShowCertificate()){let button=document.createElement("button");button.textContent=WI.UIString("Show full certificate");let errorElement=null;button.addEventListener("click",(event)=>{this._resource.showCertificate().then(()=>{if(errorElement){errorElement.remove();errorElement=null;}}).catch((error)=>{if(!errorElement)
errorElement=WI.ImageUtilities.useSVGSymbol("Images/Error.svg","error",error);button.insertAdjacentElement("afterend",errorElement);});});let pairElement=this._certificateSection.appendKeyValuePair(button);pairElement.classList.add("show-certificate");}
this._certificateSection.appendKeyValuePair(WI.UIString("Subject"),certificate.subject||emDash);let appendFormattedDate=(key,timestamp)=>{if(isNaN(timestamp))
return;let date=new Date(timestamp*1000);let timeElement=document.createElement("time");timeElement.datetime=date.toISOString();timeElement.textContent=date.toLocaleString();this._certificateSection.appendKeyValuePair(key,timeElement);};appendFormattedDate(WI.UIString("Valid From"),certificate.validFrom);appendFormattedDate(WI.UIString("Valid Until"),certificate.validUntil);let appendList=(key,values,className)=>{if(!Array.isArray(values))
return;const initialCount=5;for(let i=0;i<Math.min(values.length,initialCount);++i)
this._certificateSection.appendKeyValuePair(key,values[i],className);let remaining=values.length-initialCount;if(remaining<=0)
return;let showMoreElement=document.createElement("a");showMoreElement.classList.add("show-more");showMoreElement.textContent=WI.UIString("Show %d More").format(remaining);let showMorePair=this._certificateSection.appendKeyValuePair(key,showMoreElement,className);showMoreElement.addEventListener("click",(event)=>{showMorePair.remove();for(let i=initialCount;i<values.length;++i)
this._certificateSection.appendKeyValuePair(key,values[i],className);},{once:true});};appendList(WI.UIString("DNS"),certificate.dnsNames,"dns-name");appendList(WI.UIString("IP"),certificate.ipAddresses,"ip-address");}
_perfomSearchOnKeyValuePairs()
{let searchRegex=WI.SearchUtilities.searchRegExpForString(this._searchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;}
let elements=this.element.querySelectorAll(".key, .value");for(let element of elements){let matchRanges=[];let text=element.textContent;let match;while(match=searchRegex.exec(text))
matchRanges.push({offset:match.index,length:match[0].length});if(matchRanges.length){let highlightedNodes=WI.highlightRangesWithStyleClass(element,matchRanges,"search-highlight",this._searchDOMChanges);this._searchResults.pushAll(highlightedNodes);}}}
_revealSearchResult(index,changeFocus)
{let highlightElement=this._searchResults[index];if(!highlightElement)
return;highlightElement.scrollIntoViewIfNeeded();if(!this._bouncyHighlightElement){this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className="bouncy-highlight";this._bouncyHighlightElement.addEventListener("animationend",(event)=>{this._bouncyHighlightElement.remove();});}
this._bouncyHighlightElement.remove();let computedStyles=window.getComputedStyle(highlightElement);let highlightElementRect=highlightElement.getBoundingClientRect();let contentViewRect=this.element.getBoundingClientRect();let contentViewScrollTop=this.element.scrollTop;let contentViewScrollLeft=this.element.scrollLeft;this._bouncyHighlightElement.textContent=highlightElement.textContent;this._bouncyHighlightElement.style.top=(highlightElementRect.top-contentViewRect.top+contentViewScrollTop)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-contentViewRect.left+contentViewScrollLeft)+"px";this._bouncyHighlightElement.style.fontWeight=computedStyles.fontWeight;this.element.appendChild(this._bouncyHighlightElement);}
_handleResourceResponseReceived(event)
{this._needsCertificateRefresh=true;this.needsLayout();}
_handleResourceMetricsDidChange(event)
{this._needsConnectionRefresh=true;this.needsLayout();}};WI.ResourceSizesContentView=class ResourceSizesContentView extends WI.ContentView
{constructor(resource,delegate)
{super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.SizeDidChange,this._resourceSizeDidChange,this);this._resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._delegate=delegate;this.element.classList.add("resource-details","resource-sizes");this._needsTransferSizesRefresh=false;this._needsResourceSizeRefresh=false;} 
initialLayout()
{super.initialLayout();let contentElement=this.element.appendChild(document.createElement("div"));contentElement.className="content";let networkSection=contentElement.appendChild(document.createElement("section"));networkSection.className="network split";function createSizeComponents(parentElement,subtitle,imageSource,label1,label2){let subtitleElement=parentElement.appendChild(document.createElement("div"));subtitleElement.className="subtitle";subtitleElement.textContent=subtitle;let container=parentElement.appendChild(document.createElement("div"));container.className="container";let imageElement=container.appendChild(document.createElement("img"));if(imageSource)
imageElement.src=imageSource;let bytesElement=container.appendChild(document.createElement("div"));bytesElement.className="bytes";let table=parentElement.appendChild(document.createElement("table"));let headerRow=table.appendChild(document.createElement("tr"));let label1Element=headerRow.appendChild(document.createElement("td"));let value1Element=headerRow.appendChild(document.createElement("td"));let bodyRow=table.appendChild(document.createElement("tr"));let label2Element=bodyRow.appendChild(document.createElement("td"));let value2Element=bodyRow.appendChild(document.createElement("td"));label1Element.textContent=label1;label1Element.className="label";label2Element.textContent=label2;label2Element.className="label";return{container,bytesElement,imageElement,value1Element,value2Element,};}
let sendingSection=networkSection.appendChild(document.createElement("div"));sendingSection.className="subsection";let sendingComponents=createSizeComponents(sendingSection,WI.UIString("Bytes Sent"),"Images/Sending.svg",WI.UIString("Headers:"),WI.UIString("Body:"));this._sendingBytesElement=sendingComponents.bytesElement;this._sendingHeaderBytesElement=sendingComponents.value1Element;this._sendingBodyBytesElement=sendingComponents.value2Element;let bytesDivider=networkSection.appendChild(document.createElement("div"));bytesDivider.className="divider";let receivingSection=networkSection.appendChild(document.createElement("div"));receivingSection.className="subsection";let receivingComponents=createSizeComponents(receivingSection,WI.UIString("Bytes Received"),"Images/Receiving.svg",WI.UIString("Headers:"),WI.UIString("Body:"));this._receivingBytesElement=receivingComponents.bytesElement;this._receivingHeaderBytesElement=receivingComponents.value1Element;this._receivingBodyBytesElement=receivingComponents.value2Element;let resourceDivider=networkSection.appendChild(document.createElement("div"));resourceDivider.className="divider";let resourceSection=networkSection.appendChild(document.createElement("div"));resourceSection.className="subsection large";let resourceComponents=createSizeComponents(resourceSection,WI.UIString("Resource Size"),null,WI.UIString("Compression:"),WI.UIString("MIME Type:"));resourceComponents.container.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(this._resource));resourceComponents.imageElement.classList.add("icon");if(this._resource.responseSource===WI.Resource.ResponseSource.InspectorOverride)
resourceComponents.imageElement.title=WI.UIString("This resource was loaded from a local override");this._resourceBytesElement=resourceComponents.bytesElement;this._compressionElement=resourceComponents.value1Element;this._contentTypeElement=resourceComponents.value2Element;this._refreshTransferSizeSections();this._refreshResourceSizeSection();this._needsTransferSizesRefresh=false;this._needsResourceSizeRefresh=false;}
layout()
{super.layout();if(this._needsTransferSizesRefresh){this._refreshTransferSizeSections();this._needsTransferSizesRefresh=false;}
if(this._needsResourceSizeRefresh){this._refreshResourceSizeSection();this._needsResourceSizeRefresh=false;}}
closed()
{this._resource.removeEventListener(WI.Resource.Event.SizeDidChange,this._resourceSizeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);super.closed();} 
_formattedSizeComponent(bytes)
{
const higherResolution=false;const bytesThreshold=100;return Number.bytesToString(bytes,higherResolution,bytesThreshold);}
_refreshTransferSizeSections()
{let bytesSentHeader=this._resource.requestHeadersTransferSize;let bytesSentBody=this._resource.requestBodyTransferSize;let bytesSent=bytesSentHeader+bytesSentBody;let bytesReceivedHeader=this._resource.responseHeadersTransferSize;let bytesReceivedBody=this._resource.responseBodyTransferSize;let bytesReceived=bytesReceivedHeader+bytesReceivedBody;this._sendingBytesElement.textContent=this._formattedSizeComponent(bytesSent||0);this._sendingHeaderBytesElement.textContent=bytesSentHeader?Number.bytesToString(bytesSentHeader):emDash;this._sendingBodyBytesElement.textContent=bytesSentBody?Number.bytesToString(bytesSentBody):emDash;this._receivingBytesElement.textContent=this._formattedSizeComponent(bytesReceived||0);this._receivingHeaderBytesElement.textContent=bytesReceivedHeader?Number.bytesToString(bytesReceivedHeader):emDash;this._receivingBodyBytesElement.textContent=bytesReceivedBody?Number.bytesToString(bytesReceivedBody):emDash;function appendGoToArrow(parentElement,handler){let goToButton=parentElement.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",handler);}
if(bytesSentHeader)
appendGoToArrow(this._sendingHeaderBytesElement,()=>{this._delegate.sizesContentViewGoToHeaders(this);});if(bytesSentBody)
appendGoToArrow(this._sendingBodyBytesElement,()=>{this._delegate.sizesContentViewGoToRequestBody(this);});if(bytesReceivedHeader)
appendGoToArrow(this._receivingHeaderBytesElement,()=>{this._delegate.sizesContentViewGoToHeaders(this);});if(bytesReceivedBody)
appendGoToArrow(this._receivingBodyBytesElement,()=>{this._delegate.sizesContentViewGoToResponseBody(this);});}
_refreshResourceSizeSection()
{let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let decodedSize=!isNaN(this._resource.networkDecodedSize)?this._resource.networkDecodedSize:this._resource.size;let compressionRate=decodedSize/encodedSize;let compressionString=compressionRate>0&&isFinite(compressionRate)?WI.UIString("%.2f\u00d7").format(compressionRate):WI.UIString("None");this._resourceBytesElement.textContent=this._formattedSizeComponent(decodedSize||0);let contentEncoding=this._resource.responseHeaders.valueForCaseInsensitiveKey("Content-Encoding");if(contentEncoding)
compressionString+=` (${contentEncoding.toLowerCase()})`;this._compressionElement.textContent=compressionString;this._contentTypeElement.textContent=this._resource.mimeType||emDash;const minimumSizeBeforeWarning=1024;if(compressionRate<=1&&encodedSize>=minimumSizeBeforeWarning&&WI.shouldTreatMIMETypeAsText(this._resource.mimeType))
this._compressionElement.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Warning.svg","warning",WI.UIString("This text resource could benefit from compression")));}
_resourceSizeDidChange(event)
{this._needsTransferSizesRefresh=true;this.needsLayout();}
_resourceTransferSizeDidChange(event)
{this._needsTransferSizesRefresh=true;this.needsLayout();}
_resourceMetricsDidChange(event)
{this._needsTransferSizesRefresh=true;this._needsResourceSizeRefresh=true;this.needsLayout();}};WI.ResourceTimelineDataGridNode=class ResourceTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);this._shouldShowPopover=options.shouldShowPopover;this.resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.URLDidChange,this._needsRefresh,this);if(options.includesGraph)
this.record.addEventListener(WI.TimelineRecord.Event.Updated,this._timelineRecordUpdated,this);else{this.resource.addEventListener(WI.Resource.Event.TypeDidChange,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.SizeDidChange,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._needsRefresh,this);}} 
get resource()
{return this.record.resource;}
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.domain=WI.displayNameForHost(this.resource.urlComponents.host);this._cachedData.scheme=this.resource.urlComponents.scheme?this.resource.urlComponents.scheme.toUpperCase():"";this._cachedData.method=this.resource.requestMethod;this._cachedData.type=this.resource.type;this._cachedData.statusCode=this.resource.statusCode;this._cachedData.cached=this.resource.cached;this._cachedData.size=this.resource.size;this._cachedData.transferSize=!isNaN(this.resource.networkTotalTransferSize)?this.resource.networkTotalTransferSize:this.resource.estimatedTotalTransferSize;this._cachedData.requestSent=this.resource.requestSentTimestamp-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.duration=this.resource.receiveDuration;this._cachedData.latency=this.resource.latency;this._cachedData.protocol=this.resource.protocol;this._cachedData.priority=this.resource.priority;this._cachedData.remoteAddress=this.resource.remoteAddress;this._cachedData.connectionIdentifier=this.resource.connectionIdentifier;this._cachedData.initiator=this.resource.initiatorSourceCodeLocation;this._cachedData.source=this.resource.initiatorSourceCodeLocation; return this._cachedData;}
createCellContent(columnIdentifier,cell)
{if(this.resource.hadLoadingError())
cell.classList.add("error");let value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());cell.title=this.resource.displayURL;this._updateStatus(cell);return this._createNameCellDocumentFragment();case"type":var text=WI.Resource.displayNameForType(value);cell.title=text;return text;case"statusCode":cell.title=this.resource.statusText||"";return value||emDash;case"cached":var fragment=this._cachedCellContent();cell.title=fragment.textContent;return fragment;case"size":case"transferSize":var text=emDash;if(!isNaN(value)){text=Number.bytesToString(value,true);cell.title=text;}
return text;case"requestSent":case"latency":case"duration":var text=emDash;if(!isNaN(value)){text=Number.secondsToString(value,true);cell.title=text;}
return text;case"domain":case"method":case"scheme":case"protocol":case"remoteAddress":case"connectionIdentifier":if(value)
cell.title=value;return value||emDash;case"priority":var title=WI.Resource.displayNameForPriority(value);if(title)
cell.title=title;return title||emDash;case"source": return super.createCellContent("initiator",cell);}
return super.createCellContent(columnIdentifier,cell);}
generateIconTitle(columnIdentifier)
{if(columnIdentifier==="name"){if(this.resource.responseSource===WI.Resource.ResponseSource.InspectorOverride)
return WI.UIString("This resource was loaded from a local override");}
return super.generateIconTitle(columnIdentifier);}
refresh()
{if(this._scheduledRefreshIdentifier){cancelAnimationFrame(this._scheduledRefreshIdentifier);this._scheduledRefreshIdentifier=undefined;}
this._cachedData=null;super.refresh();}
iconClassNames()
{return[WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(this.resource)];}
appendContextMenuItems(contextMenu)
{WI.appendContextMenuItemsForSourceCode(contextMenu,this.resource);} 
didAddRecordBar(recordBar)
{if(!this._shouldShowPopover)
return;if(!recordBar.records.length||recordBar.records[0].type!==WI.TimelineRecord.Type.Network)
return;this._mouseEnterRecordBarListener=this._mouseoverRecordBar.bind(this);recordBar.element.addEventListener("mouseenter",this._mouseEnterRecordBarListener);}
didRemoveRecordBar(recordBar)
{if(!this._shouldShowPopover)
return;if(!recordBar.records.length||recordBar.records[0].type!==WI.TimelineRecord.Type.Network)
return;recordBar.element.removeEventListener("mouseenter",this._mouseEnterRecordBarListener);this._mouseEnterRecordBarListener=null;}
filterableDataForColumn(columnIdentifier)
{if(columnIdentifier==="name")
return this.resource.url;return super.filterableDataForColumn(columnIdentifier);} 
_createNameCellDocumentFragment()
{let fragment=document.createDocumentFragment();let mainTitle=this.displayName();fragment.append(mainTitle);let frame=this.resource.parentFrame;let isMainResource=this.resource.isMainResource();let parentResourceHost;if(frame&&isMainResource){parentResourceHost=frame.parentFrame?frame.parentFrame.mainResource.urlComponents.host:null;}else if(frame){parentResourceHost=frame.mainResource.urlComponents.host;}
if(parentResourceHost!==this.resource.urlComponents.host||frame.isMainFrame()&&isMainResource){let subtitle=WI.displayNameForHost(this.resource.urlComponents.host);if(mainTitle!==subtitle){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");subtitleElement.textContent=subtitle;fragment.append(subtitleElement);}}
return fragment;}
_cachedCellContent()
{if(!this.resource.hasResponse())
return emDash;let responseSource=this.resource.responseSource;if(responseSource===WI.Resource.ResponseSource.MemoryCache||responseSource===WI.Resource.ResponseSource.DiskCache){let span=document.createElement("span");let cacheType=document.createElement("span");cacheType.classList="cache-type";cacheType.textContent=responseSource===WI.Resource.ResponseSource.MemoryCache?WI.UIString("(Memory)"):WI.UIString("(Disk)");span.append(WI.UIString("Yes")," ",cacheType);return span;}
let fragment=document.createDocumentFragment();fragment.append(this.resource.cached?WI.UIString("Yes"):WI.UIString("No"));return fragment;}
_needsRefresh()
{if(this.dataGrid instanceof WI.TimelineDataGrid){this.dataGrid.dataGridNodeNeedsRefresh(this);return;}
if(this._scheduledRefreshIdentifier)
return;this._scheduledRefreshIdentifier=requestAnimationFrame(this.refresh.bind(this));}
_timelineRecordUpdated(event)
{if(this.isRecordVisible(this.record))
this.needsGraphRefresh();}
_dataGridNodeGoToArrowClicked()
{const options={ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,};WI.showSourceCode(this.resource,options);}
_updateStatus(cell)
{if(this.resource.failed)
cell.classList.add("error");else{cell.classList.remove("error");if(this.resource.finished)
this.createGoToArrowButton(cell,this._dataGridNodeGoToArrowClicked.bind(this));}
if(this.resource.isLoading()){if(!this._spinner)
this._spinner=new WI.IndeterminateProgressSpinner;let contentElement=cell.firstChild;contentElement.appendChild(this._spinner.element);}else{if(this._spinner)
this._spinner.element.remove();}}
_mouseoverRecordBar(event)
{let recordBar=WI.TimelineRecordBar.fromElement(event.target);if(!recordBar)
return;let calculateTargetFrame=()=>{let columnRect=WI.Rect.rectFromClientRect(this.elementWithColumnIdentifier("graph").getBoundingClientRect());let barRect=WI.Rect.rectFromClientRect(event.target.getBoundingClientRect());return columnRect.intersectionWithRect(barRect);};let targetFrame=calculateTargetFrame();if(!targetFrame.size.width&&!targetFrame.size.height)
return;let resource=recordBar.records[0].resource;if(!resource.timingData)
return;if(!resource.timingData.responseEnd)
return;if(this.dataGrid._dismissPopoverTimeout){clearTimeout(this.dataGrid._dismissPopoverTimeout);this.dataGrid._dismissPopoverTimeout=undefined;}
let popoverContentElement=document.createElement("div");popoverContentElement.classList.add("resource-timing-popover-content");if(resource.failed||resource.urlComponents.scheme==="data"||(resource.cached&&resource.statusCode!==304)){let descriptionElement=document.createElement("span");descriptionElement.classList.add("description");if(resource.failed)
descriptionElement.textContent=WI.UIString("Resource failed to load.");else if(resource.urlComponents.scheme==="data")
descriptionElement.textContent=WI.UIString("Resource was loaded with the \u201Cdata\u201D scheme.");else
descriptionElement.textContent=WI.UIString("Resource was served from the cache.");popoverContentElement.appendChild(descriptionElement);}else{let columns={description:{width:"80px"},graph:{width:`${WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels}px`},duration:{width:"70px",aligned:"right"}};let popoverDataGrid=new WI.DataGrid(columns);popoverDataGrid.inline=true;popoverDataGrid.headerVisible=false;popoverContentElement.appendChild(popoverDataGrid.element);let graphDataSource={get secondsPerPixel(){return resource.totalDuration/WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels;},get zeroTime(){return resource.firstTimestamp;},get startTime(){return this.zeroTime;},get currentTime(){return resource.lastTimestamp+this._extraTimePadding;},get endTime(){return this.currentTime;},get _extraTimePadding(){return this.secondsPerPixel*WI.TimelineRecordBar.MinimumWidthPixels;},};if(resource.timingData.redirectEnd-resource.timingData.redirectStart){ popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Redirects"),resource.timingData.redirectStart,resource.timingData.redirectEnd,graphDataSource));}
let secondTimestamp=resource.timingData.domainLookupStart||resource.timingData.connectStart||resource.timingData.requestStart;if(secondTimestamp-resource.timingData.fetchStart)
popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Stalled"),resource.timingData.fetchStart,secondTimestamp,graphDataSource));if(resource.timingData.domainLookupStart)
popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("DNS"),resource.timingData.domainLookupStart,resource.timingData.domainLookupEnd,graphDataSource));if(resource.timingData.connectStart)
popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Connection"),resource.timingData.connectStart,resource.timingData.connectEnd,graphDataSource));if(resource.timingData.secureConnectionStart)
popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Secure"),resource.timingData.secureConnectionStart,resource.timingData.connectEnd,graphDataSource));popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Request"),resource.timingData.requestStart,resource.timingData.responseStart,graphDataSource));popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Response"),resource.timingData.responseStart,resource.timingData.responseEnd,graphDataSource));const higherResolution=true;let totalData={description:WI.UIString("Total time"),duration:Number.secondsToMillisecondsString(resource.timingData.responseEnd-resource.timingData.startTime,higherResolution)};popoverDataGrid.appendChild(new WI.DataGridNode(totalData));popoverDataGrid.updateLayout();}
if(!this.dataGrid._popover)
this.dataGrid._popover=new WI.Popover;let preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X];this.dataGrid._popover.windowResizeHandler=()=>{let bounds=calculateTargetFrame();this.dataGrid._popover.present(bounds.pad(2),preferredEdges);};recordBar.element.addEventListener("mouseleave",()=>{if(!this.dataGrid)
return;this.dataGrid._dismissPopoverTimeout=setTimeout(()=>{if(this.dataGrid)
this.dataGrid._popover.dismiss();},WI.ResourceTimelineDataGridNode.DelayedPopoverDismissalTimeout);},{once:true});this.dataGrid._popover.presentNewContentWithFrame(popoverContentElement,targetFrame.pad(2),preferredEdges);}};WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels=110;WI.ResourceTimelineDataGridNode.DelayedPopoverDismissalTimeout=500;WI.ResourceTimingBreakdownView=class ResourceTimingBreakdownView extends WI.View
{constructor(resource,fixedWidth)
{super(null);this._resource=resource;this.element.classList.add("resource-timing-breakdown");if(fixedWidth)
this.element.style.width=fixedWidth+"px";} 
_appendEmptyRow()
{let row=this._tableElement.appendChild(document.createElement("tr"));row.className="empty";return row;}
_appendHeaderRow(label,time,additionalClassName)
{let row=this._tableElement.appendChild(document.createElement("tr"));row.className="header";if(additionalClassName)
row.classList.add(additionalClassName);let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;labelCell.colSpan=2;let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";if(time)
timeCell.textContent=time;else if(time===undefined)
timeCell.appendChild(document.createElement("hr"));return row;}
_appendRow(label,type,startTime,endTime)
{let row=this._tableElement.appendChild(document.createElement("tr"));let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;let duration=endTime-startTime;let graphWidth=(duration/this._graphDuration)*100;let graphOffset=((startTime-this._graphStartTime)/this._graphDuration)*100;let positionProperty=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";let graphCell=row.appendChild(document.createElement("td"));graphCell.className="graph";let block=graphCell.appendChild(document.createElement("div"));block.classList.add("block",type);block.style.width=graphWidth+"%";block.style[positionProperty]=graphOffset+"%";let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";timeCell.textContent=Number.secondsToMillisecondsString(duration);return row;}
_appendServerTimingRow(label,duration,maxDuration)
{let row=this._tableElement.appendChild(document.createElement("tr"));let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;if(duration!==undefined){let graphWidth=(duration/maxDuration)*100;let graphCell=row.appendChild(document.createElement("td"));graphCell.className="graph";let block=graphCell.appendChild(document.createElement("div"));block.classList.add("block","response");block.style.width=graphWidth+"%";block.style.right=0;let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";timeCell.textContent=Number.secondsToMillisecondsString(duration/1000);}
return row;}
_appendDividerRow()
{let emptyCell=this._appendEmptyRow().appendChild(document.createElement("td"));emptyCell.colSpan=3;emptyCell.appendChild(document.createElement("hr"));}
initialLayout()
{super.initialLayout();let{startTime,redirectStart,redirectEnd,fetchStart,domainLookupStart,domainLookupEnd,connectStart,connectEnd,secureConnectionStart,requestStart,responseStart,responseEnd}=this._resource.timingData;let serverTiming=this._resource.serverTiming;this._tableElement=this.element.appendChild(document.createElement("table"));this._tableElement.className="waterfall network";this._graphStartTime=startTime;this._graphEndTime=responseEnd;this._graphDuration=this._graphEndTime-this._graphStartTime;this._appendHeaderRow(WI.UIString("Scheduling:"));if(redirectEnd-redirectStart){ this._appendRow(WI.UIString("Redirects"),"redirect",redirectStart,redirectEnd);}
this._appendRow(WI.UIString("Queued"),"queue",fetchStart,domainLookupStart||connectStart||requestStart);if(domainLookupStart||connectStart){this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Connection:"));if(domainLookupStart)
this._appendRow(WI.UIString("DNS"),"dns",domainLookupStart,domainLookupEnd||connectStart||requestStart);if(connectStart)
this._appendRow(WI.UIString("TCP"),"connect",connectStart,connectEnd||requestStart);if(secureConnectionStart)
this._appendRow(WI.UIString("Secure"),"secure",secureConnectionStart,connectEnd||requestStart);}
this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Response:"));this._appendRow(WI.UIString("Waiting"),"request",requestStart,responseStart);this._appendRow(WI.UIString("Download"),"response",responseStart,responseEnd);this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Totals:"));this._appendHeaderRow(WI.UIString("Time to First Byte"),Number.secondsToMillisecondsString(responseStart-startTime),"total-row");this._appendHeaderRow(WI.UIString("Start to Finish"),Number.secondsToMillisecondsString(responseEnd-startTime),"total-row");if(serverTiming.length>0){this._appendDividerRow();this._appendHeaderRow(WI.UIString("Server Timing:"));let maxDuration=serverTiming.reduce((max,{duration=0})=>Math.max(max,duration),0);for(let entry of serverTiming){let{name,duration,description}=entry;this._appendServerTimingRow(description||name,duration,maxDuration);}}}};WI.ResourceTimingContentView=class ResourceTimingContentView extends WI.ContentView
{constructor(resource)
{super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.addEventListener(WI.Resource.Event.TimestampsDidChange,this._resourceTimestampsDidChange,this);this.element.classList.add("resource-details","resource-timing");this._needsTimingRefresh=false;} 
initialLayout()
{super.initialLayout();this._refreshTimingSection();this._needsTimingRefresh=false;}
layout()
{super.layout();if(this._needsTimingRefresh){this._refreshTimingSection();this._needsTimingRefresh=false;}}
closed()
{this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TimestampsDidChange,this._resourceTimestampsDidChange,this);super.closed();} 
_refreshTimingSection()
{this.element.removeChildren();if(!this._resource.hasResponse()){let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);return;}
if(!this._resource.timingData.startTime||!this._resource.timingData.responseEnd){const isError=false;this.element.appendChild(WI.createMessageTextView(WI.UIString("Resource does not have timing data"),isError));return;}
let contentElement=this.element.appendChild(document.createElement("div"));contentElement.className="content";let timingSection=contentElement.appendChild(document.createElement("section"));timingSection.className="timing";let breakdownView=new WI.ResourceTimingBreakdownView(this._resource);timingSection.appendChild(breakdownView.element);breakdownView.updateLayout();}
_resourceMetricsDidChange(event)
{this._needsTimingRefresh=true;this.needsLayout();}
_resourceTimestampsDidChange(event)
{this._needsTimingRefresh=true;this.needsLayout();}};WI.ResourceTimingPopoverDataGridNode=class ResourceTimingPopoverDataGridNode extends WI.TimelineDataGridNode
{constructor(description,startTime,endTime,graphDataSource)
{let record=new WI.TimelineRecord(WI.TimelineRecord.Type.Network,startTime,endTime);super([record],{includesGraph:true,graphDataSource,});const higherResolution=true;let duration=Number.secondsToMillisecondsString(endTime-startTime,higherResolution);this._data={description,duration};} 
get data(){return this._data;}
get selectable()
{return false;} 
createCellContent(columnIdentifier,cell)
{let value=this.data[columnIdentifier];switch(columnIdentifier){case"description":case"duration":return value||emDash;}
return super.createCellContent(columnIdentifier,cell);}};WI.ScopeBar=class ScopeBar extends WI.NavigationItem
{constructor(identifier,items,defaultItem,shouldGroupNonExclusiveItems)
{super(identifier);this._element.classList.add("scope-bar");this._items=items;this._defaultItem=defaultItem;this._shouldGroupNonExclusiveItems=shouldGroupNonExclusiveItems||false;for(let item of this._items)
item.scopeBar=this;this._minimumWidth=0;this._populate();this._element.addEventListener("keydown",this._handleKeyDown.bind(this));} 
get minimumWidth()
{if(!this._minimumWidth){


this.element.style.flexWrap="initial !important";if(this._multipleItem)
this._multipleItem.displayWidestItem();this._minimumWidth=this.element.realOffsetWidth;this.element.style.flexWrap=null;if(this._multipleItem)
this._multipleItem.displaySelectedItem();}
return this._minimumWidth;}
get defaultItem()
{return this._defaultItem;}
get items()
{return this._items;}
item(id)
{return this._itemsById.get(id);}
get selectedItems()
{return this._items.filter((item)=>item.selected);}
hasNonDefaultItemSelected()
{return this._items.some((item)=>item.selected&&item!==this._defaultItem);}
resetToDefault()
{let selectedItems=this.selectedItems;if(selectedItems.length===1&&selectedItems[0]===this._defaultItem)
return;for(let item of this._items)
item.selected=false;this._defaultItem.selected=true;this.dispatchEventToListeners(WI.ScopeBar.Event.SelectionChanged);} 
_populate()
{this._itemsById=new Map;if(this._shouldGroupNonExclusiveItems){var nonExclusiveItems=[];for(var item of this._items){this._itemsById.set(item.id,item);if(item.exclusive)
this._element.appendChild(item.element);else
nonExclusiveItems.push(item);item.addEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);}
this._multipleItem=new WI.MultipleScopeBarItem(nonExclusiveItems);this._element.appendChild(this._multipleItem.element);}else{for(var item of this._items){this._itemsById.set(item.id,item);this._element.appendChild(item.element);item.addEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);}}
if(this._defaultItem){if(!this.selectedItems.length)
this._defaultItem.selected=true;this._element.classList.toggle("default-item-selected",this._defaultItem.selected);}}
_itemSelectionDidChange(event)
{var sender=event.target;var item;if(sender.exclusive&&sender.selected){for(var i=0;i<this._items.length;++i){item=this._items[i];if(item!==sender)
item.selected=false;}}else{let replacesCurrentSelection=this._shouldGroupNonExclusiveItems||!event.data.extendSelection;for(var i=0;i<this._items.length;++i){item=this._items[i];if(item.exclusive&&item!==sender&&sender.selected)
item.selected=false;else if(sender.selected&&replacesCurrentSelection&&sender!==item)
item.selected=false;}}
if(this._defaultItem){if(!this.selectedItems.length)
this._defaultItem.selected=true;this._element.classList.toggle("default-item-selected",this._defaultItem.selected);}
this.dispatchEventToListeners(WI.ScopeBar.Event.SelectionChanged);}
_handleKeyDown(event)
{if(event.code==="ArrowLeft"||event.code==="ArrowRight"){event.stop();let focusedIndex=-1;for(let i=0;i<this._items.length;++i){let element=this._items[i].element;if(element===document.activeElement){focusedIndex=i;break;}}
if(focusedIndex===-1)
return;let delta=(event.code==="ArrowLeft")?-1:1;if(WI.resolveLayoutDirectionForElement(this._element)===WI.LayoutDirection.RTL)
delta*=-1;focusedIndex+=delta;focusedIndex=(focusedIndex+this._items.length)%this._items.length;this._items[focusedIndex].element.focus();}}};WI.ScopeBar.Event={SelectionChanged:"scopebar-selection-did-change"};WI.ScopeBarItem=class ScopeBarItem extends WI.Object
{constructor(id,label,{className,exclusive,independent,hidden}={})
{super();this._element=document.createElement("li");this._element.classList.toggle("exclusive",!!exclusive);if(className)
this._element.classList.add(className);this._element.textContent=label;this._element.addEventListener("mousedown",this._handleMouseDown.bind(this));this._element.addEventListener("keydown",this._handleKeyDown.bind(this));this._id=id;this._label=label;this._exclusive=!!exclusive;this._independent=!!independent;this._hidden=!!hidden;this._scopeBar=null;this._selectedSetting=new WI.Setting("scopebaritem-"+id,false);this._updateSelected(this._selectedSetting.value);this._element.classList.toggle("hidden",this._hidden);} 
get scopeBar(){return this._scopeBar;}
set scopeBar(scopeBar){this._scopeBar=scopeBar;}
get element()
{return this._element;}
get id()
{return this._id;}
get label()
{return this._label;}
get exclusive()
{return this._exclusive;}
get selected()
{return this._selectedSetting.value;}
set selected(selected)
{this.toggle(selected,{extendSelection:this._independent||(WI.modifierKeys.metaKey&&!WI.modifierKeys.ctrlKey&&!WI.modifierKeys.altKey&&!WI.modifierKeys.shiftKey),});}
get hidden()
{return this._hidden;}
set hidden(flag)
{if(this._hidden===flag)
return;this._hidden=flag;this._element.classList.toggle("hidden",flag);this.dispatchEventToListeners(WI.ScopeBarItem.Event.HiddenChanged);}
toggle(selected,{extendSelection}={})
{if(this._selectedSetting.value===selected)
return;this._updateSelected(selected);this._selectedSetting.value=selected;this.dispatchEventToListeners(WI.ScopeBarItem.Event.SelectionChanged,{extendSelection});} 
_updateSelected(selected)
{selected=!!selected;this._element.classList.toggle("selected",selected);this._element.ariaPressed=selected;this._element.tabIndex=selected?0:-1;}
_handleMouseDown(event)
{if(event.button!==0)
return;this.selected=!this.selected;if(!this._scopeBar?.element.contains(document.activeElement))
event.preventDefault();}
_handleKeyDown(event)
{if(event.code==="Space"||event.code==="Enter"){event.stop();this.selected=!this.selected;}}};WI.ScopeBarItem.Event={SelectionChanged:"scope-bar-item-selection-changed",HiddenChanged:"scope-bar-item-hidden-changed",};WI.ScopeChainDetailsSidebarPanel=class ScopeChainDetailsSidebarPanel extends WI.DetailsSidebarPanel
{constructor()
{super("scope-chain",WI.UIString("Scope Chain"));this._callFrame=null;this._watchExpressionsSetting=new WI.Setting("watch-expressions",[]);this._watchExpressionsSetting.addEventListener(WI.Setting.Event.Changed,this._updateWatchExpressionsNavigationBar,this);this._watchExpressionOptionsElement=document.createElement("div");this._watchExpressionOptionsElement.classList.add("options");this._navigationBar=new WI.NavigationBar;this._watchExpressionOptionsElement.appendChild(this._navigationBar.element);let addWatchExpressionButton=new WI.ButtonNavigationItem("add-watch-expression",WI.UIString("Add watch expression"),"Images/Plus13.svg",13,13);addWatchExpressionButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._addWatchExpressionButtonClicked,this);this._navigationBar.addNavigationItem(addWatchExpressionButton);this._clearAllWatchExpressionButton=new WI.ButtonNavigationItem("clear-watch-expressions",WI.UIString("Clear watch expressions"),"Images/NavigationItemTrash.svg",15,15);this._clearAllWatchExpressionButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearAllWatchExpressionsButtonClicked,this);this._navigationBar.addNavigationItem(this._clearAllWatchExpressionButton);this._refreshAllWatchExpressionButton=new WI.ButtonNavigationItem("refresh-watch-expressions",WI.UIString("Refresh watch expressions"),"Images/ReloadFull.svg",13,13);this._refreshAllWatchExpressionButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshAllWatchExpressionsButtonClicked,this);this._navigationBar.addNavigationItem(this._refreshAllWatchExpressionButton);this._watchExpressionsSectionGroup=new WI.DetailsSectionGroup;this._watchExpressionsSection=new WI.DetailsSection("watch-expressions",WI.UIString("Watch Expressions"),[this._watchExpressionsSectionGroup],this._watchExpressionOptionsElement);this.contentView.element.appendChild(this._watchExpressionsSection.element);this._updateWatchExpressionsNavigationBar();this.needsLayout();WI.runtimeManager.addEventListener(WI.RuntimeManager.Event.DidEvaluate,this._didEvaluateExpression,this);WI.runtimeManager.addEventListener(WI.RuntimeManager.Event.ActiveExecutionContextChanged,this._activeExecutionContextChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);} 
inspect(objects)
{if(!(objects instanceof Array))
objects=[objects];var callFrameToInspect=null;for(var i=0;i<objects.length;++i){if(!(objects[i]instanceof WI.CallFrame))
continue;callFrameToInspect=objects[i];break;}
this.callFrame=callFrameToInspect;return true;}
get callFrame()
{return this._callFrame;}
set callFrame(callFrame)
{if(callFrame===this._callFrame)
return;this._callFrame=callFrame;this.needsLayout();}
closed()
{WI.runtimeManager.removeEventListener(WI.RuntimeManager.Event.DidEvaluate,this._didEvaluateExpression,this);WI.runtimeManager.removeEventListener(WI.RuntimeManager.Event.ActiveExecutionContextChanged,this._activeExecutionContextChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);super.closed();} 
layout()
{super.layout();if(this.layoutReason!==WI.View.LayoutReason.Dirty)
return;let callFrame=this._callFrame;Promise.all([this._generateWatchExpressionsSection(),this._generateCallFramesSection()]).then(function(sections){let[watchExpressionsSection,callFrameSections]=sections;function delayedWork()
{clearTimeout(timeout);if(watchExpressionsSection)
this._watchExpressionsSectionGroup.rows=[watchExpressionsSection];else{let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Watch Expressions"));this._watchExpressionsSectionGroup.rows=[emptyRow];emptyRow.showEmptyMessage();}
this.contentView.element.removeChildren();this.contentView.element.appendChild(this._watchExpressionsSection.element);if(this._callFrame!==callFrame)
return;if(!callFrameSections)
return;for(let callFrameSection of callFrameSections)
this.contentView.element.appendChild(callFrameSection.element);}


let delay=WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.size===0?50:250;let timeout=setTimeout(delayedWork.bind(this),delay);
InspectorBackend.runAfterPendingDispatches(delayedWork.bind(this));}.bind(this)).catch(function(e){console.error(e);});}
_generateCallFramesSection()
{let callFrame=this._callFrame;if(!callFrame)
return Promise.resolve(null);let detailsSections=[];let foundLocalScope=false;let sectionCountByType=new Map;for(let type in WI.ScopeChainNode.Type)
sectionCountByType.set(WI.ScopeChainNode.Type[type],0);let scopeChain=callFrame.mergedScopeChain();for(let scope of scopeChain){if(scope.empty&&scope.type!==WI.ScopeChainNode.Type.Local)
continue;let title=null;let extraPropertyDescriptor=null;let collapsedByDefault=false;let count=sectionCountByType.get(scope.type);sectionCountByType.set(scope.type,++count);switch(scope.type){case WI.ScopeChainNode.Type.Local:foundLocalScope=true;collapsedByDefault=false;title=WI.UIString("Local Variables");if(callFrame.thisObject)
extraPropertyDescriptor=new WI.PropertyDescriptor({name:"this",value:callFrame.thisObject});break;case WI.ScopeChainNode.Type.Closure:if(scope.__baseClosureScope&&scope.name)
title=WI.UIString("Closure Variables (%s)").format(scope.name);else
title=WI.UIString("Closure Variables");collapsedByDefault=false;break;case WI.ScopeChainNode.Type.Block:title=WI.UIString("Block Variables");collapsedByDefault=false;break;case WI.ScopeChainNode.Type.Catch:title=WI.UIString("Catch Variables");collapsedByDefault=false;break;case WI.ScopeChainNode.Type.FunctionName:title=WI.UIString("Function Name Variable");collapsedByDefault=true;break;case WI.ScopeChainNode.Type.With:title=WI.UIString("With Object Properties");collapsedByDefault=foundLocalScope;break;case WI.ScopeChainNode.Type.Global:title=WI.UIString("Global Variables");collapsedByDefault=true;break;case WI.ScopeChainNode.Type.GlobalLexicalEnvironment:title=WI.UIString("Global Lexical Environment");collapsedByDefault=true;break;}
let detailsSectionIdentifier=scope.type+"-"+sectionCountByType.get(scope.type);let detailsSection=new WI.DetailsSection(detailsSectionIdentifier,title,null,null,collapsedByDefault);
let rows=[];for(let object of scope.objects){let scopePropertyPath=WI.PropertyPath.emptyPropertyPathForScope(object);let objectTree=new WI.ObjectTreeView(object,WI.ObjectTreeView.Mode.Properties,scopePropertyPath);objectTree.showOnlyProperties();if(extraPropertyDescriptor){objectTree.appendExtraPropertyDescriptor(extraPropertyDescriptor);extraPropertyDescriptor=null;}
let treeOutline=objectTree.treeOutline;treeOutline.registerScrollVirtualizer(this.contentView.element,16);treeOutline.addEventListener(WI.TreeOutline.Event.ElementAdded,function(event){this._treeElementAdded(detailsSectionIdentifier,event);},this);treeOutline.addEventListener(WI.TreeOutline.Event.ElementDisclosureDidChanged,function(event){this._treeElementDisclosureDidChange(detailsSectionIdentifier,event);},this);rows.push(new WI.ObjectPropertiesDetailSectionRow(objectTree,detailsSection));}
detailsSection.groups[0].rows=rows;detailsSections.push(detailsSection);}
return Promise.resolve(detailsSections);}
_generateWatchExpressionsSection()
{let watchExpressions=this._watchExpressionsSetting.value;if(!watchExpressions.length){if(this._usedWatchExpressionsObjectGroup){this._usedWatchExpressionsObjectGroup=false;for(let target of WI.targets)
target.RuntimeAgent.releaseObjectGroup(WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName);}
return Promise.resolve(null);}
for(let target of WI.targets)
target.RuntimeAgent.releaseObjectGroup(WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName);this._usedWatchExpressionsObjectGroup=true;let watchExpressionsRemoteObject=WI.RemoteObject.createFakeRemoteObject();let fakePropertyPath=WI.PropertyPath.emptyPropertyPathForScope(watchExpressionsRemoteObject);let objectTree=new WI.ObjectTreeView(watchExpressionsRemoteObject,WI.ObjectTreeView.Mode.Properties,fakePropertyPath);objectTree.showOnlyProperties();let treeOutline=objectTree.treeOutline;const watchExpressionSectionIdentifier="watch-expressions";treeOutline.addEventListener(WI.TreeOutline.Event.ElementAdded,function(event){this._treeElementAdded(watchExpressionSectionIdentifier,event);},this);treeOutline.addEventListener(WI.TreeOutline.Event.ElementDisclosureDidChanged,function(event){this._treeElementDisclosureDidChange(watchExpressionSectionIdentifier,event);},this);treeOutline.objectTreeElementAddContextMenuItems=this._objectTreeElementAddContextMenuItems.bind(this);let promises=[];for(let expression of watchExpressions){promises.push(new Promise(function(resolve,reject){let options={objectGroup:WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName,includeCommandLineAPI:false,doNotPauseOnExceptionsAndMuteConsole:true,returnByValue:false,generatePreview:true,saveResult:false};WI.runtimeManager.evaluateInInspectedWindow(expression,options,function(object,wasThrown){object=object||WI.RemoteObject.fromPrimitiveValue(undefined);let propertyDescriptor=new WI.PropertyDescriptor({name:expression,value:object},undefined,undefined,wasThrown);objectTree.appendExtraPropertyDescriptor(propertyDescriptor);resolve();});}));}
return Promise.all(promises).then(function(){return Promise.resolve(new WI.ObjectPropertiesDetailSectionRow(objectTree));});}
_addWatchExpression(expression)
{let watchExpressions=this._watchExpressionsSetting.value.slice(0);watchExpressions.push(expression);this._watchExpressionsSetting.value=watchExpressions;this.needsLayout();}
_removeWatchExpression(expression)
{let watchExpressions=this._watchExpressionsSetting.value.slice(0);watchExpressions.remove(expression,true);this._watchExpressionsSetting.value=watchExpressions;this.needsLayout();}
_clearAllWatchExpressions()
{this._watchExpressionsSetting.value=[];this.needsLayout();}
_addWatchExpressionButtonClicked(event)
{function presentPopoverOverTargetElement()
{let target=WI.Rect.rectFromClientRect(event.target.element.getBoundingClientRect());popover.present(target,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);}
let popover=new WI.Popover(this);let content=document.createElement("div");content.classList.add("watch-expression");content.appendChild(document.createElement("div")).textContent=WI.UIString("Add New Watch Expression");let editorElement=content.appendChild(document.createElement("div"));editorElement.classList.add("watch-expression-editor",WI.SyntaxHighlightedStyleClassName);this._codeMirror=WI.CodeMirrorEditor.create(editorElement,{lineWrapping:true,mode:"text/javascript",matchBrackets:true,value:"",});this._popoverCommitted=false;this._codeMirror.addKeyMap({"Enter":()=>{this._popoverCommitted=true;popover.dismiss();},});let completionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.FullConsoleCommandLineAPI,this._codeMirror);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let previousHeight=0;this._codeMirror.on("changes",function(cm,event){let height=cm.getScrollInfo().height;if(previousHeight!==height){previousHeight=height;popover.update(false);}});popover.content=content;popover.windowResizeHandler=presentPopoverOverTargetElement;presentPopoverOverTargetElement();setTimeout(()=>{this._codeMirror.refresh();this._codeMirror.focus();popover.update();},0);}
willDismissPopover(popover)
{if(this._popoverCommitted){let expression=this._codeMirror.getValue().trim();if(expression)
this._addWatchExpression(expression);}
this._codeMirror=null;}
_refreshAllWatchExpressionsButtonClicked(event)
{this.needsLayout();}
_clearAllWatchExpressionsButtonClicked(event)
{this._clearAllWatchExpressions();}
_didEvaluateExpression(event)
{if(event.data.objectGroup===WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName)
return;this.needsLayout();}
_activeExecutionContextChanged()
{this.needsLayout();}
_activeCallFrameDidChange()
{this.needsLayout();}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this.needsLayout();}
_objectTreeElementAddContextMenuItems(objectTreeElement,contextMenu)
{if(objectTreeElement.parent!==objectTreeElement.treeOutline)
return;contextMenu.appendItem(WI.UIString("Delete Watch Expression"),()=>{let expression=objectTreeElement.property.name;this._removeWatchExpression(expression);});}
_propertyPathIdentifierForTreeElement(identifier,objectPropertyTreeElement)
{if(!objectPropertyTreeElement.property)
return null;let propertyPath=objectPropertyTreeElement.thisPropertyPath();if(propertyPath.isFullPathImpossible())
return null;return identifier+"-"+propertyPath.fullPath;}
_treeElementAdded(identifier,event)
{let treeElement=event.data.element;let propertyPathIdentifier=this._propertyPathIdentifierForTreeElement(identifier,treeElement);if(!propertyPathIdentifier)
return;if(WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.has(propertyPathIdentifier))
treeElement.expand();}
_treeElementDisclosureDidChange(identifier,event)
{let treeElement=event.data.element;let propertyPathIdentifier=this._propertyPathIdentifierForTreeElement(identifier,treeElement);if(!propertyPathIdentifier)
return;if(treeElement.expanded)
WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.add(propertyPathIdentifier);else
WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.delete(propertyPathIdentifier);}
_updateWatchExpressionsNavigationBar()
{let enabled=this._watchExpressionsSetting.value.length;this._refreshAllWatchExpressionButton.enabled=enabled;this._clearAllWatchExpressionButton.enabled=enabled;}};WI.ScopeChainDetailsSidebarPanel._autoExpandProperties=new Set;WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName="watch-expressions";WI.ScriptClusterTimelineView=class ScriptClusterTimelineView extends WI.ClusterContentView
{constructor(timeline,extraArguments)
{super(timeline);this._currentContentViewSetting=new WI.Setting("script-cluster-timeline-view-current-view",WI.ScriptClusterTimelineView.EventsIdentifier);function createPathComponent(displayName,className,identifier)
{const showSelectorArrows=true;let pathComponent=new WI.HierarchicalPathComponent(displayName,className,identifier,false,showSelectorArrows);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._pathComponentSelected,this);pathComponent.comparisonData=timeline;return pathComponent;}
this._eventsPathComponent=createPathComponent.call(this,WI.UIString("Events"),"events-icon",WI.ScriptClusterTimelineView.EventsIdentifier);this._profilePathComponent=createPathComponent.call(this,WI.UIString("Call Trees"),"call-trees-icon",WI.ScriptClusterTimelineView.ProfileIdentifier);this._eventsPathComponent.nextSibling=this._profilePathComponent;this._profilePathComponent.previousSibling=this._eventsPathComponent;this._eventsContentView=new WI.ScriptDetailsTimelineView(this.representedObject,extraArguments);this._profileContentView=new WI.ScriptProfileTimelineView(this.representedObject,extraArguments);this._showContentViewForIdentifier(this._currentContentViewSetting.value);this.contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._scriptClusterViewCurrentContentViewDidChange,this);}

get showsLiveRecordingData(){return this._contentViewContainer.currentContentView.showsLiveRecordingData;}
get showsFilterBar(){return this._contentViewContainer.currentContentView.showsFilterBar;}
get zeroTime(){return this._contentViewContainer.currentContentView.zeroTime;}
set zeroTime(x){this._contentViewContainer.currentContentView.zeroTime=x;}
get startTime(){return this._contentViewContainer.currentContentView.startTime;}
set startTime(x){this._contentViewContainer.currentContentView.startTime=x;}
get endTime(){return this._contentViewContainer.currentContentView.endTime;}
set endTime(x){this._contentViewContainer.currentContentView.endTime=x;}
get currentTime(){return this._contentViewContainer.currentContentView.currentTime;}
set currentTime(x){this._contentViewContainer.currentContentView.currentTime=x;}
selectRecord(record){this._contentViewContainer.currentContentView.selectRecord(record);}
updateFilter(filters){return this._contentViewContainer.currentContentView.updateFilter(filters);}
filterDidChange(){return this._contentViewContainer.currentContentView.filterDidChange();}
matchDataGridNodeAgainstCustomFilters(node){return this._contentViewContainer.currentContentView.matchDataGridNodeAgainstCustomFilters(node);}
reset()
{this._eventsContentView.reset();this._profileContentView.reset();} 
get eventsContentView()
{return this._eventsContentView;}
get profileContentView()
{return this._profileContentView;}
get selectionPathComponents()
{let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView)
return[];let components=[this._pathComponentForContentView(currentContentView)];let subComponents=currentContentView.selectionPathComponents;if(subComponents)
components.pushAll(subComponents);return components;}
saveToCookie(cookie)
{cookie[WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey]=this._currentContentViewSetting.value;}
restoreFromCookie(cookie)
{this._showContentViewForIdentifier(cookie[WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey]);}
showEvents()
{return this._showContentViewForIdentifier(WI.ScriptClusterTimelineView.EventsIdentifier);}
showProfile()
{return this._showContentViewForIdentifier(WI.ScriptClusterTimelineView.ProfileIdentifier);} 
_pathComponentForContentView(contentView)
{if(!contentView)
return null;if(contentView===this._eventsContentView)
return this._eventsPathComponent;if(contentView===this._profileContentView)
return this._profilePathComponent;console.error("Unknown contentView.");return null;}
_identifierForContentView(contentView)
{if(!contentView)
return null;if(contentView===this._eventsContentView)
return WI.ScriptClusterTimelineView.EventsIdentifier;if(contentView===this._profileContentView)
return WI.ScriptClusterTimelineView.ProfileIdentifier;console.error("Unknown contentView.");return null;}
_showContentViewForIdentifier(identifier)
{let contentViewToShow=null;switch(identifier){case WI.ScriptClusterTimelineView.EventsIdentifier:contentViewToShow=this.eventsContentView;break;case WI.ScriptClusterTimelineView.ProfileIdentifier:contentViewToShow=this.profileContentView;break;}
if(!contentViewToShow)
contentViewToShow=this.eventsContentView;this._currentContentViewSetting.value=this._identifierForContentView(contentViewToShow);return this.contentViewContainer.showContentView(contentViewToShow);}
_pathComponentSelected(event)
{this._showContentViewForIdentifier(event.data.pathComponent.representedObject);}
_scriptClusterViewCurrentContentViewDidChange(event)
{let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView)
return;let previousContentView=currentContentView===this._eventsContentView?this._profileContentView:this._eventsContentView;currentContentView.zeroTime=previousContentView.zeroTime;currentContentView.startTime=previousContentView.startTime;currentContentView.endTime=previousContentView.endTime;currentContentView.currentTime=previousContentView.currentTime;}};WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey="script-cluster-timeline-view-identifier";WI.ScriptClusterTimelineView.EventsIdentifier="events";WI.ScriptClusterTimelineView.ProfileIdentifier="profile";WI.ScriptContentView=class ScriptContentView extends WI.ContentView
{constructor(script)
{super(script);this.element.classList.add("script");var spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._script=script;
var toolTip=WI.UIString("Pretty print");var activatedToolTip=WI.UIString("Original formatting");this._prettyPrintButtonNavigationItem=new WI.ActivateButtonNavigationItem("pretty-print",toolTip,activatedToolTip,"Images/NavigationItemCurleyBraces.svg",13,13);this._prettyPrintButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrettyPrint,this);this._prettyPrintButtonNavigationItem.enabled=false;this._prettyPrintButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;var toolTipTypes=WI.UIString("Show type information");var activatedToolTipTypes=WI.UIString("Hide type information");this._showTypesButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-types",toolTipTypes,activatedToolTipTypes,"Images/NavigationItemTypes.svg",13,14);this._showTypesButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleTypeAnnotations,this);this._showTypesButtonNavigationItem.enabled=false;this._showTypesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);let toolTipCodeCoverage=WI.UIString("Fade unexecuted code");let activatedToolTipCodeCoverage=WI.UIString("Do not fade unexecuted code");this._codeCoverageButtonNavigationItem=new WI.ActivateButtonNavigationItem("code-coverage",toolTipCodeCoverage,activatedToolTipCodeCoverage,"Images/NavigationItemCodeCoverage.svg",13,14);this._codeCoverageButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleUnexecutedCodeHighlights,this);this._codeCoverageButtonNavigationItem.enabled=false;this._codeCoverageButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);this._textEditor=new WI.SourceCodeTextEditor(script);this._textEditor.addEventListener(WI.TextEditor.Event.ExecutionLineNumberDidChange,this._executionLineNumberDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.FormattingDidChange,this._textEditorFormattingDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.MIMETypeChanged,this._handleTextEditorMIMETypeChanged,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentWillPopulate,this._contentWillPopulate,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentDidPopulate,this._contentDidPopulate,this);if(this._script instanceof WI.LocalScript&&this._script.editable)
this._textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,this._handleTextEditorContentDidChange,this);} 
get navigationItems()
{return[this._prettyPrintButtonNavigationItem,this._showTypesButtonNavigationItem,this._codeCoverageButtonNavigationItem];}
get script()
{return this._script;}
get textEditor()
{return this._textEditor;}
get supplementalRepresentedObjects()
{if(isNaN(this._textEditor.executionLineNumber))
return[];
return[WI.debuggerManager.activeCallFrame];}
revealPosition(position,textRangeToSelect,forceUnformatted)
{this._textEditor.revealPosition(position,textRangeToSelect,forceUnformatted);}
closed()
{super.closed();WI.settings.showJavaScriptTypeInformation.removeEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);WI.settings.enableControlFlowProfiler.removeEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);this._textEditor.close();}
saveToCookie(cookie)
{cookie.type=WI.ContentViewCookieType.Resource;cookie.url=this.representedObject.url;}
restoreFromCookie(cookie)
{if("lineNumber"in cookie&&"columnNumber"in cookie)
this.revealPosition(new WI.SourceCodePosition(cookie.lineNumber,cookie.columnNumber));}
get supportsSave()
{return true;}
get saveData()
{let saveData={url:this._script.url,content:this._textEditor.string,};if(!this._script.url)
saveData.suggestedName=this._script.displayName+".js";return saveData;}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._textEditor.numberOfSearchResults;}
get hasPerformedSearch()
{return this._textEditor.currentSearchQuery!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._textEditor.automaticallyRevealFirstSearchResult=reveal;}
performSearch(query)
{this._textEditor.performSearch(query);}
searchCleared()
{this._textEditor.searchCleared();}
searchQueryWithSelection()
{return this._textEditor.searchQueryWithSelection();}
revealPreviousSearchResult(changeFocus)
{this._textEditor.revealPreviousSearchResult(changeFocus);}
revealNextSearchResult(changeFocus)
{this._textEditor.revealNextSearchResult(changeFocus);} 
_contentWillPopulate(event)
{if(this._textEditor.element.parentNode===this.element)
return;if(this._script.urlComponents.scheme==="file"||(this._script instanceof WI.LocalScript&&this._script.editable))
this._textEditor.readOnly=false;this.element.removeChildren();this.addSubview(this._textEditor);}
_contentDidPopulate(event)
{let isLocalScript=this._script instanceof WI.LocalScript;this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();this._showTypesButtonNavigationItem.enabled=!isLocalScript&&this._textEditor.canShowTypeAnnotations();this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;this._codeCoverageButtonNavigationItem.enabled=!isLocalScript&&this._textEditor.canShowCoverageHints();this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;}
_handleTextEditorContentDidChange(event)
{this._script.editableRevision.updateRevisionContent(this._textEditor.string);}
_togglePrettyPrint(event)
{var activated=!this._prettyPrintButtonNavigationItem.activated;this._textEditor.updateFormattedState(activated);}
_toggleTypeAnnotations(event)
{this._showTypesButtonNavigationItem.enabled=false;this._textEditor.toggleTypeAnnotations().then(()=>{this._showTypesButtonNavigationItem.enabled=true;});}
_toggleUnexecutedCodeHighlights(event)
{this._codeCoverageButtonNavigationItem.enabled=false;this._textEditor.toggleUnexecutedCodeHighlights().then(()=>{this._codeCoverageButtonNavigationItem.enabled=true;});}
_showJavaScriptTypeInformationSettingChanged(event)
{this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;}
_enableControlFlowProfilerSettingChanged(event)
{this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;}
_textEditorFormattingDidChange(event)
{this._prettyPrintButtonNavigationItem.activated=this._textEditor.formatted;}
_handleTextEditorMIMETypeChanged(event)
{this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();}
_executionLineNumberDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_numberOfSearchResultsDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};WI.ScriptDetailsTimelineView=class ScriptDetailsTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);let columns={name:{},location:{},callCount:{},startTime:{},totalTime:{},selfTime:{},averageTime:{}};columns.name.title=WI.UIString("Name");columns.name.width="30%";columns.name.icon=true;columns.name.disclosure=true;columns.name.locked=true;columns.location.title=WI.UIString("Location");columns.location.icon=true;columns.location.width="15%";columns.callCount.title=WI.UIString("Samples");columns.callCount.width="5%";columns.callCount.aligned="right";columns.startTime.title=WI.UIString("Start Time");columns.startTime.width="10%";columns.startTime.aligned="right";columns.totalTime.title=WI.UIString("Total Time");columns.totalTime.width="10%";columns.totalTime.aligned="right";columns.selfTime.title=WI.UIString("Self Time");columns.selfTime.width="10%";columns.selfTime.aligned="right";columns.averageTime.title=WI.UIString("Average Time");columns.averageTime.width="10%";columns.averageTime.aligned="right";for(var column in columns)
columns[column].sortable=true;this._dataGrid=new WI.ScriptTimelineDataGrid(columns);this._dataGrid.sortDelegate=this;this._dataGrid.sortColumnIdentifier="startTime";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("script-timeline-view");this.setupDataGrid(this._dataGrid);this.element.classList.add("script");this.addSubview(this._dataGrid);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);timeline.addEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);this._pendingRecords=[];for(let record of timeline.records)
this._processRecord(record);} 
get showsLiveRecordingData(){return false;}
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);this.representedObject.removeEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);this._dataGrid.closed();}
get selectionPathComponents()
{var dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode)
return null;var pathComponents=[];while(dataGridNode&&!dataGridNode.root){if(dataGridNode.hidden)
return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(dataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);pathComponents.unshift(pathComponent);dataGridNode=dataGridNode.parent;}
return pathComponents;}
reset()
{super.reset();this._dataGrid.reset();this._pendingRecords=[];} 
dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2)
{if(sortColumnIdentifier!=="name")
return null;let displayName1=node1.displayName();let displayName2=node2.displayName();if(displayName1!==displayName2)
return displayName1.extendedLocaleCompare(displayName2)*sortDirection;return node1.subtitle.extendedLocaleCompare(node2.subtitle)*sortDirection;} 
dataGridNodePathComponentSelected(event)
{let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();}
layout()
{if(this.startTime!==this._oldStartTime||this.endTime!==this._oldEndTime){let dataGridNode=this._dataGrid.children[0];while(dataGridNode){if(dataGridNode.revealed)
dataGridNode.refresh();else
dataGridNode.needsRefresh();dataGridNode=dataGridNode.traverseNextNode(false,null,true);}
this._oldStartTime=this.startTime;this._oldEndTime=this.endTime;}
this._processPendingRecords();} 
_processPendingRecords()
{if(WI.timelineManager.scriptProfilerIsTracking())
return;if(!this._pendingRecords.length)
return;for(let scriptTimelineRecord of this._pendingRecords){let rootNodes=[];if(scriptTimelineRecord.profile){rootNodes=scriptTimelineRecord.profile.topDownRootNodes;}
let dataGridNode=new WI.ScriptTimelineDataGridNode(scriptTimelineRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(dataGridNode);for(let profileNode of rootNodes){let profileNodeDataGridNode=new WI.ProfileNodeDataGridNode(profileNode,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(profileNodeDataGridNode,dataGridNode);}}
this._pendingRecords=[];}
_scriptTimelineRecordAdded(event)
{let scriptTimelineRecord=event.data.record;this._processRecord(scriptTimelineRecord);this.needsLayout();}
_processRecord(scriptTimelineRecord)
{this._pendingRecords.push(scriptTimelineRecord);}
_scriptTimelineRecordRefreshed(event)
{this.needsLayout();}};WI.ScriptProfileTimelineView=class ScriptProfileTimelineView extends WI.TimelineView
{constructor(timeline,extraArguments)
{super(timeline,extraArguments);this.element.classList.add("script");this._recording=extraArguments.recording;this._forceNextLayout=false;this._lastLayoutStartTime=undefined;this._lastLayoutEndTime=undefined;this._sharedProfileViewData={selectedNodeHash:null,};if(!WI.ScriptProfileTimelineView.profileOrientationSetting)
WI.ScriptProfileTimelineView.profileOrientationSetting=new WI.Setting("script-profile-timeline-view-profile-orientation-setting",WI.ScriptProfileTimelineView.ProfileOrientation.TopDown);if(!WI.ScriptProfileTimelineView.profileTypeSetting)
WI.ScriptProfileTimelineView.profileTypeSetting=new WI.Setting("script-profile-timeline-view-profile-type-setting",WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy);this._showProfileViewForOrientation(WI.ScriptProfileTimelineView.profileOrientationSetting.value,WI.ScriptProfileTimelineView.profileTypeSetting.value);let clearTooltip=WI.UIString("Clear focus");this._clearFocusNodesButtonItem=new WI.ButtonNavigationItem("clear-profile-focus",clearTooltip,"Images/Close.svg",16,16);this._clearFocusNodesButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearFocusNodes,this);this._updateClearFocusNodesButtonItem();this._profileOrientationButton=new WI.TextToggleButtonNavigationItem("profile-orientation",WI.UIString("Inverted"));this._profileOrientationButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._profileOrientationButtonClicked,this);if(WI.ScriptProfileTimelineView.profileOrientationSetting.value===WI.ScriptProfileTimelineView.ProfileOrientation.TopDown)
this._profileOrientationButton.activated=false;else
this._profileOrientationButton.activated=true;this._topFunctionsButton=new WI.TextToggleButtonNavigationItem("top-functions",WI.UIString("Top Functions"));this._topFunctionsButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._topFunctionsButtonClicked,this);if(WI.ScriptProfileTimelineView.profileTypeSetting.value===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy)
this._topFunctionsButton.activated=false;else
this._topFunctionsButton.activated=true;timeline.addEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);} 
get scrollableElements(){return this._profileView.scrollableElements;}
get showsLiveRecordingData(){return false;} 
closed()
{this.representedObject.removeEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);}
get navigationItems()
{return[this._clearFocusNodesButtonItem,this._profileOrientationButton,this._topFunctionsButton];}
get selectionPathComponents()
{return this._profileView.selectionPathComponents;}
layout()
{if(!this._forceNextLayout&&(this._lastLayoutStartTime===this.startTime&&this._lastLayoutEndTime===this.endTime))
return;this._forceNextLayout=false;this._lastLayoutStartTime=this.startTime;this._lastLayoutEndTime=this.endTime;this._profileView.setStartAndEndTime(this.startTime,this.endTime);} 
_callingContextTreeForOrientation(profileOrientation,profileViewType)
{switch(profileOrientation){case WI.ScriptProfileTimelineView.ProfileOrientation.TopDown:return profileViewType===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy?this._recording.topDownCallingContextTree:this._recording.topFunctionsTopDownCallingContextTree;case WI.ScriptProfileTimelineView.ProfileOrientation.BottomUp:return profileViewType===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy?this._recording.bottomUpCallingContextTree:this._recording.topFunctionsBottomUpCallingContextTree;}
return this._recording.topDownCallingContextTree;}
_profileViewSelectionPathComponentsDidChange(event)
{this._updateClearFocusNodesButtonItem();this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}
_scriptTimelineRecordRefreshed(event)
{this._forceNextLayout=true;this.needsLayout();}
_profileOrientationButtonClicked()
{this._profileOrientationButton.activated=!this._profileOrientationButton.activated;let isInverted=this._profileOrientationButton.activated;let newOrientation;if(isInverted)
newOrientation=WI.ScriptProfileTimelineView.ProfileOrientation.BottomUp;else
newOrientation=WI.ScriptProfileTimelineView.ProfileOrientation.TopDown;WI.ScriptProfileTimelineView.profileOrientationSetting.value=newOrientation;this._showProfileViewForOrientation(newOrientation,WI.ScriptProfileTimelineView.profileTypeSetting.value);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this._forceNextLayout=true;this.needsLayout();}
_topFunctionsButtonClicked()
{this._topFunctionsButton.activated=!this._topFunctionsButton.activated;let isTopFunctionsEnabled=this._topFunctionsButton.activated;let newOrientation;if(isTopFunctionsEnabled)
newOrientation=WI.ScriptProfileTimelineView.ProfileViewType.TopFunctions;else
newOrientation=WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy;WI.ScriptProfileTimelineView.profileTypeSetting.value=newOrientation;this._showProfileViewForOrientation(WI.ScriptProfileTimelineView.profileOrientationSetting.value,newOrientation);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this._forceNextLayout=true;this.needsLayout();}
_showProfileViewForOrientation(profileOrientation,profileViewType)
{let filterText;if(this._profileView){this._profileView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._profileViewSelectionPathComponentsDidChange,this);this.removeSubview(this._profileView);filterText=this._profileView.dataGrid.filterText;}
let callingContextTree=this._callingContextTreeForOrientation(profileOrientation,profileViewType);this._profileView=new WI.ProfileView(callingContextTree,this._sharedProfileViewData);this._profileView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._profileViewSelectionPathComponentsDidChange,this);this.addSubview(this._profileView);this.setupDataGrid(this._profileView.dataGrid);if(filterText)
this._profileView.dataGrid.filterText=filterText;}
_updateClearFocusNodesButtonItem()
{this._clearFocusNodesButtonItem.enabled=this._profileView.hasFocusNodes();}
_clearFocusNodes()
{this._profileView.clearFocusNodes();}};WI.ScriptProfileTimelineView.ProfileOrientation={BottomUp:"bottom-up",TopDown:"top-down",};WI.ScriptProfileTimelineView.ProfileViewType={Hierarchy:"hierarchy",TopFunctions:"top-functions",};WI.ScriptTimelineDataGrid=class ScriptTimelineDataGrid extends WI.TimelineDataGrid
{ callFramePopoverAnchorElement()
{return this.selectedNode.elementWithColumnIdentifier("location");}
shouldShowCallFramePopover()
{return this.isColumnVisible("location");}};WI.ScriptTimelineDataGridNode=class ScriptTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(record,options={})
{super([record],options);} 
get data()
{if(this._cachedData)
return this._cachedData;let baseStartTime=0;let rangeStartTime=0;let rangeEndTime=Infinity;if(this.graphDataSource){baseStartTime=this.graphDataSource.zeroTime;rangeStartTime=this.graphDataSource.startTime;rangeEndTime=this.graphDataSource.endTime;}
let startTime=this.record.startTime;let duration=this.record.startTime+this.record.duration-startTime;this._cachedData=super.data;this._cachedData.type=this.record.eventType;this._cachedData.name=this.displayName();this._cachedData.startTime=startTime-baseStartTime;this._cachedData.selfTime=duration;this._cachedData.totalTime=duration;this._cachedData.averageTime=duration;this._cachedData.callCount=this.record.callCountOrSamples;this._cachedData.location=this.record.initiatorCallFrame||this.record.sourceCodeLocation;return this._cachedData;}
get subtitle()
{if(this._subtitle!==undefined)
return this._subtitle;this._subtitle="";if(this.record.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled){let timeoutString=Number.secondsToString(this.record.details.timeout/1000);if(this.record.details.repeating)
this._subtitle=WI.UIString("%s interval").format(timeoutString);else
this._subtitle=WI.UIString("%s delay").format(timeoutString);}else if(this.record.eventType===WI.ScriptTimelineRecord.EventType.EventDispatched){if(this.record.extraDetails&&this.record.extraDetails.defaultPrevented)
this._subtitle=WI.UIString("default prevented");}
return this._subtitle;}
createCellContent(columnIdentifier,cell)
{const higherResolution=true;var value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return this._createNameCellDocumentFragment();case"startTime":case"selfTime":case"totalTime":case"averageTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"callCount":return isNaN(value)?emDash:value.toLocaleString();case"width":case"height":case"area":return zeroWidthSpace;case"source": return super.createCellContent("location",cell);}
return super.createCellContent(columnIdentifier,cell);} 
filterableDataForColumn(columnIdentifier)
{if(columnIdentifier==="name")
return[this.displayName(),this.subtitle];return super.filterableDataForColumn(columnIdentifier);} 
_createNameCellDocumentFragment(cellElement)
{let fragment=document.createDocumentFragment();fragment.append(this.displayName());if(this.subtitle){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");subtitleElement.textContent=this.subtitle;fragment.append(subtitleElement);}
return fragment;}};WI.ScriptTimelineOverviewGraph=class ScriptTimelineOverviewGraph extends WI.TimelineOverviewGraph
{constructor(timeline,timelineOverview)
{super(timelineOverview);this.element.classList.add("script");this._scriptTimeline=timeline;this._scriptTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);this._timelineRecordBars=[];this.reset();} 
reset()
{super.reset();this.element.removeChildren();} 
layout()
{super.layout();if(this.hidden)
return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let recordBarIndex=0;function createBar(records,renderMode)
{let timelineRecordBar=this._timelineRecordBars[recordBarIndex];if(!timelineRecordBar)
timelineRecordBar=this._timelineRecordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;}
timelineRecordBar.refresh(this);if(!timelineRecordBar.element.parentNode)
this.element.appendChild(timelineRecordBar.element);++recordBarIndex;}
let[gcRecords,nonGCRecords]=this._scriptTimeline.records.partition((x)=>x.isGarbageCollection());let boundCreateBar=createBar.bind(this);WI.TimelineRecordBar.createCombinedBars(nonGCRecords,secondsPerPixel,this,boundCreateBar);WI.TimelineRecordBar.createCombinedBars(gcRecords,secondsPerPixel,this,boundCreateBar);for(;recordBarIndex<this._timelineRecordBars.length;++recordBarIndex){this._timelineRecordBars[recordBarIndex].records=null;this._timelineRecordBars[recordBarIndex].element.remove();}}
updateSelectedRecord()
{super.updateSelectedRecord();for(let recordBar of this._timelineRecordBars){if(recordBar.records.includes(this.selectedRecord)){this.selectedRecordBar=recordBar;return;}}
this.selectedRecordBar=null;} 
_scriptTimelineRecordAdded(event)
{this.needsLayout();}};WI.ScrubberNavigationItem=class ScrubberNavigationItem extends WI.FlexibleSpaceNavigationItem
{constructor(identifier)
{super(identifier);this._sliderElement=this._element.appendChild(document.createElement("input"));this._sliderElement.type="range";this._sliderElement.addEventListener("input",this._sliderChanged.bind(this));} 
get value(){return parseInt(this._sliderElement.value);}
set value(value){this._sliderElement.value=value;}
get min(){return parseInt(this._sliderElement.min);}
set min(min){this._sliderElement.min=min;}
get max(){return parseInt(this._sliderElement.max);}
set max(max){this._sliderElement.max=max;}
get disabled()
{return this._sliderElement.disabled;}
set disabled(flag)
{this._sliderElement.disabled=!!flag;} 
get additionalClassNames()
{let additionalClassNames=super.additionalClassNames;additionalClassNames.push("scrubber");return additionalClassNames;} 
_sliderChanged(event)
{this.dispatchEventToListeners(WI.ScrubberNavigationItem.Event.ValueChanged);}};WI.ScrubberNavigationItem.Event={ValueChanged:"slider-navigation-item-value-changed",};WI.SearchResultTreeElement=class SearchResultTreeElement extends WI.GeneralTreeElement
{constructor(representedObject)
{var title=WI.SearchResultTreeElement.truncateAndHighlightTitle(representedObject.title,representedObject.searchTerm,representedObject.sourceCodeTextRange);const subtitle=null;super(representedObject.className,title,subtitle,representedObject);} 
static truncateAndHighlightTitle(title,searchTerm,sourceCodeTextRange)
{let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;const charactersToShowBeforeSearchMatch=isRTL?20:15;const charactersToShowAfterSearchMatch=isRTL?15:50;var textRange=sourceCodeTextRange.textRange;let searchTermIndex=textRange.startColumn;let searchTermLength=textRange.endColumn-textRange.startColumn;
var modifiedTitle=null;if(searchTermIndex>charactersToShowBeforeSearchMatch){modifiedTitle=ellipsis+title.substring(searchTermIndex-charactersToShowBeforeSearchMatch);searchTermIndex=charactersToShowBeforeSearchMatch+1;}else
modifiedTitle=title;modifiedTitle=modifiedTitle.truncateEnd(searchTermIndex+searchTermLength+charactersToShowAfterSearchMatch);var highlightedTitle=document.createDocumentFragment();highlightedTitle.append(modifiedTitle.substring(0,searchTermIndex));var highlightSpan=document.createElement("span");highlightSpan.className="highlighted";highlightSpan.append(modifiedTitle.substring(searchTermIndex,searchTermIndex+searchTermLength));highlightedTitle.appendChild(highlightSpan);highlightedTitle.append(modifiedTitle.substring(searchTermIndex+searchTermLength));return highlightedTitle;} 
get filterableData()
{return{text:[this.representedObject.title]};}
get synthesizedTextValue()
{return this.representedObject.sourceCodeTextRange.synthesizedTextValue+":"+this.representedObject.title;} 
populateContextMenu(contextMenu,event)
{if(this.representedObject instanceof WI.DOMSearchMatchObject){contextMenu.appendItem(WI.UIString("Reveal in Elements Tab"),()=>{WI.showMainFrameDOMTree(this.representedObject.domNode,{ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}else if(this.representedObject instanceof WI.SourceCodeSearchMatchObject){contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showOriginalOrFormattedSourceCodeTextRange(this.representedObject.sourceCodeTextRange,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}
super.populateContextMenu(contextMenu,event);}};WI.SearchSidebarPanel=class SearchSidebarPanel extends WI.NavigationSidebarPanel
{constructor()
{super("search",WI.UIString("Search"),true,true);this._searchInputSettings=WI.SearchUtilities.createSettings("search-sidebar");for(let setting of Object.values(this._searchInputSettings)){setting.addEventListener(WI.Setting.Event.Changed,function(event){this.focusSearchField(true);},this);}
this._inputContainer=this.element.appendChild(document.createElement("div"));this._inputContainer.classList.add("search-bar");this._inputElement=this._inputContainer.appendChild(document.createElement("input"));this._inputElement.type="search";this._inputElement.spellcheck=false;this._inputElement.addEventListener("search",this._searchFieldChanged.bind(this));this._inputElement.addEventListener("input",this._searchFieldInput.bind(this));this._inputElement.setAttribute("results",5);this._inputElement.setAttribute("autosave","inspector-search-autosave");this._inputElement.setAttribute("placeholder",WI.UIString("Search Resource Content"));this._inputContainer.appendChild(WI.SearchUtilities.createSettingsButton(this._searchInputSettings));this._searchQuerySetting=new WI.Setting("search-sidebar-query","");this._inputElement.value=this._searchQuerySetting.value;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this.contentTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);} 
showDefaultContentView()
{let contentView=new WI.ContentView;let contentPlaceholder=WI.createMessageTextView(this._searchQuerySetting.value?WI.UIString("No search results"):WI.UIString("No search string"));contentView.element.appendChild(contentPlaceholder);let searchNavigationItem=new WI.ButtonNavigationItem("search",WI.UIString("Search Resource Content"),"Images/Search.svg",15,15);searchNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleDefaultContentViewSearchNavigationItemClicked,this);let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to see recent searches."),searchNavigationItem);contentPlaceholder.appendChild(importHelpElement);this.contentBrowser.showContentView(contentView);}
closed()
{super.closed();WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);}
focusSearchField(performSearch)
{if(!this.parentSidebar)
return;this.parentSidebar.selectedSidebarPanel=this;this.parentSidebar.collapsed=false;this._inputElement.select();if(performSearch)
this.performSearch(this._inputElement.value,{omitFocus:true});}
performSearch(searchQuery,{omitFocus}={})
{this._inputElement.value=searchQuery;this._searchQuerySetting.value=searchQuery;this.element.classList.remove("changed");if(this._changedBanner)
this._changedBanner.remove();if(!searchQuery.length){this._inputContainer.classList.remove("invalid");this.hideEmptyContentPlaceholder();this.showDefaultContentView();return;}
let isCaseSensitive=!!this._searchInputSettings.caseSensitive.value;let isRegex=!!this._searchInputSettings.regularExpression.value;let searchRegex=WI.SearchUtilities.searchRegExpForString(searchQuery,{caseSensitive:isCaseSensitive,regularExpression:isRegex,});this._inputContainer.classList.toggle("invalid",!searchRegex);if(!searchRegex)
return;this.hideEmptyContentPlaceholder();this.contentTreeOutline.removeChildren();this.contentBrowser.contentViewContainer.closeAllContentViews();let createSearchingPlaceholder=()=>{let searchingPlaceholder=WI.createMessageTextView("");String.format(WI.UIString("Searching %s"),[(new WI.IndeterminateProgressSpinner).element],String.standardFormatters,searchingPlaceholder,(a,b)=>{a.append(b);return a;});this.updateEmptyContentPlaceholder(searchingPlaceholder);};if(!WI.targetsAvailable()&&WI.sharedApp.isWebDebuggable()){createSearchingPlaceholder();WI.whenTargetsAvailable().then(()=>{if(this._searchQuerySetting.value===searchQuery)
this.performSearch(searchQuery,{omitFocus});});return;}
let target=WI.assumingMainTarget();let promiseCount=0;let countPromise=async(promise,callback)=>{++promiseCount;if(promiseCount===1)
createSearchingPlaceholder();let value=await promise;if(callback)
callback(value);--promiseCount;if(promiseCount===0){this.updateEmptyContentPlaceholder(WI.UIString("No Search Results"));if(!this.contentTreeOutline.children.length)
this.showDefaultContentView();}};function createTreeElementForMatchObject(matchObject,parentTreeElement)
{let matchTreeElement=new WI.SearchResultTreeElement(matchObject);matchTreeElement.addEventListener(WI.TreeElement.Event.DoubleClick,this._treeElementDoubleClick,this);parentTreeElement.appendChild(matchTreeElement);if(!this.contentTreeOutline.selectedTreeElement){const selectedByUser=true;matchTreeElement.revealAndSelect(omitFocus??false,selectedByUser);}}
function forEachMatch(lineContent,callback)
{var lineMatch;while((searchRegex.lastIndex<lineContent.length)&&(lineMatch=searchRegex.exec(lineContent)))
callback(lineMatch,searchRegex.lastIndex);}
let resourceCallback=(frameId,url,{result})=>{if(!result||!result.length)
return;var frame=WI.networkManager.frameForIdentifier(frameId);if(!frame)
return;let resource=frame.url===url?frame.mainResource:frame.resourcesForURL(url).firstValue;if(!resource)
return;var resourceTreeElement=this._searchTreeElementForResource(resource);for(var i=0;i<result.length;++i){var match=result[i];forEachMatch(match.lineContent,(lineMatch,lastIndex)=>{var matchObject=new WI.SourceCodeSearchMatchObject(resource,match.lineContent,searchQuery,new WI.TextRange(match.lineNumber,lineMatch.index,match.lineNumber,lastIndex));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);});}
if(!resourceTreeElement.children.length)
this.contentTreeOutline.removeChild(resourceTreeElement);};let resourcesCallback=({result})=>{let preventDuplicates=new Set;for(let searchResult of result){if(!searchResult.url||!searchResult.frameId)
continue;
let key=searchResult.frameId+":"+searchResult.url;if(preventDuplicates.has(key))
continue;preventDuplicates.add(key);countPromise(target.PageAgent.searchInResource(searchResult.frameId,searchResult.url,searchQuery,isCaseSensitive,isRegex,searchResult.requestId),resourceCallback.bind(this,searchResult.frameId,searchResult.url));}
let promises=[WI.Frame.awaitEvent(WI.Frame.Event.ResourceWasAdded,this),WI.Target.awaitEvent(WI.Target.Event.ResourceAdded,this),];Promise.race(promises).then(this._contentChanged.bind(this));};let scriptCallback=(script,{result})=>{if(!result||!result.length)
return;var scriptTreeElement=this._searchTreeElementForScript(script);for(let match of result){forEachMatch(match.lineContent,(lineMatch,lastIndex)=>{var matchObject=new WI.SourceCodeSearchMatchObject(script,match.lineContent,searchQuery,new WI.TextRange(match.lineNumber,lineMatch.index,match.lineNumber,lastIndex));createTreeElementForMatchObject.call(this,matchObject,scriptTreeElement);});}
if(!scriptTreeElement.children.length)
this.contentTreeOutline.removeChild(scriptTreeElement);};let searchScripts=(scriptsToSearch)=>{if(!scriptsToSearch.length)
return;for(let script of scriptsToSearch)
countPromise(script.target.DebuggerAgent.searchInContent(script.id,searchQuery,isCaseSensitive,isRegex),scriptCallback.bind(this,script));};let domCallback=({searchId,resultCount})=>{if(!resultCount)
return;this._domSearchIdentifier=searchId;let domSearchResults=({nodeIds})=>{if(this._domSearchIdentifier!==searchId)
return;for(let nodeId of nodeIds){let domNode=WI.domManager.nodeForId(nodeId);if(!domNode||!domNode.ownerDocument)
continue;if(domNode.nodeType()===Node.DOCUMENT_NODE)
continue;let resource=WI.networkManager.resourcesForURL(domNode.ownerDocument.documentURL).firstValue;if(!resource)
continue;var resourceTreeElement=this._searchTreeElementForResource(resource);var domNodeTitle=WI.DOMSearchMatchObject.titleForDOMNode(domNode);var didFindTextualMatch=false;forEachMatch(domNodeTitle,(lineMatch,lastIndex)=>{var matchObject=new WI.DOMSearchMatchObject(resource,domNode,domNodeTitle,searchQuery,new WI.TextRange(0,lineMatch.index,0,lastIndex));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);didFindTextualMatch=true;});if(!didFindTextualMatch){var matchObject=new WI.DOMSearchMatchObject(resource,domNode,domNodeTitle,domNodeTitle,new WI.TextRange(0,0,0,domNodeTitle.length));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);}
if(!resourceTreeElement.children.length)
this.contentTreeOutline.removeChild(resourceTreeElement);}};countPromise(target.DOMAgent.getSearchResults(searchId,0,resultCount),domSearchResults);};WI.domManager.ensureDocument();if(target.hasCommand("Page.searchInResources"))
countPromise(target.PageAgent.searchInResources(searchQuery,isCaseSensitive,isRegex),resourcesCallback);setTimeout(searchScripts.bind(this,WI.debuggerManager.searchableScripts),0);if(target.hasDomain("DOM")){if(this._domSearchIdentifier){target.DOMAgent.discardSearchResults(this._domSearchIdentifier);this._domSearchIdentifier=undefined;}
let commandArguments={query:searchQuery,caseSensitive:isCaseSensitive,};countPromise(target.DOMAgent.performSearch.invoke(commandArguments),domCallback);}
} 
_searchFieldChanged(event)
{this.performSearch(event.target.value);}
_searchFieldInput(event)
{if(!event.target.value.length)
this.performSearch("");}
_searchTreeElementForResource(resource)
{var resourceTreeElement=this.contentTreeOutline.getCachedTreeElement(resource);if(!resourceTreeElement){resourceTreeElement=new WI.ResourceTreeElement(resource);resourceTreeElement.hasChildren=true;resourceTreeElement.expand();this.contentTreeOutline.appendChild(resourceTreeElement);}
return resourceTreeElement;}
_searchTreeElementForScript(script)
{var scriptTreeElement=this.contentTreeOutline.getCachedTreeElement(script);if(!scriptTreeElement){scriptTreeElement=new WI.ScriptTreeElement(script);scriptTreeElement.hasChildren=true;scriptTreeElement.expand();this.contentTreeOutline.appendChild(scriptTreeElement);}
return scriptTreeElement;}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;if(this._delayedSearchTimeout){clearTimeout(this._delayedSearchTimeout);this._delayedSearchTimeout=undefined;}
this.contentTreeOutline.removeChildren();this.contentBrowser.contentViewContainer.closeAllContentViews();if(this.visible){const performSearch=true;this.focusSearchField(performSearch);}}
_treeSelectionDidChange(event)
{if(!this.selected)
return;let treeElement=this.contentTreeOutline.selectedTreeElement;if(!treeElement||treeElement instanceof WI.FolderTreeElement)
return;const options={ignoreNetworkTab:true,};if(treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement){const cookie=null;WI.showRepresentedObject(treeElement.representedObject,cookie,options);return;}
if(!(treeElement instanceof WI.SearchResultTreeElement))
return;if(treeElement.representedObject instanceof WI.DOMSearchMatchObject)
WI.showMainFrameDOMTree(treeElement.representedObject.domNode);else if(treeElement.representedObject instanceof WI.SourceCodeSearchMatchObject)
WI.showOriginalOrFormattedSourceCodeTextRange(treeElement.representedObject.sourceCodeTextRange,options);}
_treeElementDoubleClick(event)
{let treeElement=event.target;if(!treeElement)
return;if(treeElement.representedObject instanceof WI.DOMSearchMatchObject){WI.showMainFrameDOMTree(treeElement.representedObject.domNode,{ignoreSearchTab:true,});}else if(treeElement.representedObject instanceof WI.SourceCodeSearchMatchObject){WI.showOriginalOrFormattedSourceCodeTextRange(treeElement.representedObject.sourceCodeTextRange,{ignoreNetworkTab:true,ignoreSearchTab:true,});}}
_contentChanged(event)
{this.element.classList.add("changed");if(!this._changedBanner){this._changedBanner=document.createElement("div");this._changedBanner.classList.add("banner");this._changedBanner.append(WI.UIString("The page's content has changed"),document.createElement("br"));let performSearchLink=this._changedBanner.appendChild(document.createElement("a"));performSearchLink.textContent=WI.UIString("Search Again");performSearchLink.addEventListener("click",()=>{const performSearch=true;this.focusSearchField(performSearch);});}
this.element.appendChild(this._changedBanner);}
_handleDefaultContentViewSearchNavigationItemClicked(event)
{this.focusSearchField();}};WI.ShaderProgramContentView=class ShaderProgramContentView extends WI.ContentView
{constructor(shaderProgram)
{super(shaderProgram);let isWebGPU=this.representedObject.canvas.contextType===WI.Canvas.ContextType.WebGPU;let sharesVertexFragmentShader=isWebGPU&&this.representedObject.sharesVertexFragmentShader;this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshContent,this);let contentDidChangeDebouncer=new Debouncer((event)=>{this._contentDidChange(event);});this.element.classList.add("shader-program",this.representedObject.programType);let createEditor=(shaderType)=>{let container=this.element.appendChild(document.createElement("div"));let header=container.appendChild(document.createElement("header"));let shaderTypeContainer=header.appendChild(document.createElement("div"));shaderTypeContainer.classList.add("shader-type");let textEditor=new WI.TextEditor;textEditor.readOnly=false;textEditor.addEventListener(WI.TextEditor.Event.Focused,this._editorFocused,this);textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,function(event){contentDidChangeDebouncer.delayForTime(250,event);},textEditor);switch(shaderType){case WI.ShaderProgram.ShaderType.Compute:shaderTypeContainer.textContent=WI.UIString("Compute Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-compute":"x-shader/x-compute";break;case WI.ShaderProgram.ShaderType.Fragment:shaderTypeContainer.textContent=WI.UIString("Fragment Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-render":"x-shader/x-fragment";break;case WI.ShaderProgram.ShaderType.Vertex:if(sharesVertexFragmentShader)
shaderTypeContainer.textContent=WI.UIString("Vertex/Fragment Shader");else
shaderTypeContainer.textContent=WI.UIString("Vertex Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-render":"x-shader/x-vertex";break;}
this.addSubview(textEditor);container.appendChild(textEditor.element);container.classList.add("shader",shaderType);container.classList.toggle("shares-vertex-fragment-shader",sharesVertexFragmentShader);return textEditor;};switch(this.representedObject.programType){case WI.ShaderProgram.ProgramType.Compute:{this._computeEditor=createEditor(WI.ShaderProgram.ShaderType.Compute);this._lastActiveEditor=this._computeEditor;break;}
case WI.ShaderProgram.ProgramType.Render:{this._vertexEditor=createEditor(WI.ShaderProgram.ShaderType.Vertex);if(!sharesVertexFragmentShader){this._fragmentEditor=createEditor(WI.ShaderProgram.ShaderType.Fragment);}
this._lastActiveEditor=this._vertexEditor;break;}}} 
get navigationItems()
{return[this._refreshButtonNavigationItem];} 
attached()
{super.attached();this._refreshContent();}
get supportsSave()
{return true;}
get saveData()
{let filename="";switch(this._lastActiveEditor){case this._computeEditor:filename=WI.UIString("Compute");break;case this._fragmentEditor:filename=WI.UIString("Fragment");break;case this._vertexEditor:filename=WI.UIString("Vertex");break;}
let extension="";switch(this.representedObject.canvas.contextType){case WI.Canvas.ContextType.WebGL:case WI.Canvas.ContextType.WebGL2:extension=WI.unlocalizedString(".glsl");break;case WI.Canvas.ContextType.WebGPU:extension=WI.unlocalizedString(".wsl");break;}
return{content:this._lastActiveEditor.string,suggestedName:filename+extension,forceSaveAs:true,};}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._lastActiveEditor.numberOfSearchResults;}
get hasPerformedSearch()
{return this._lastActiveEditor.currentSearchQuery!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._lastActiveEditor.automaticallyRevealFirstSearchResult=reveal;}
performSearch(query)
{this._lastActiveEditor.performSearch(query);}
searchCleared()
{this._lastActiveEditor.searchCleared();}
searchQueryWithSelection()
{return this._lastActiveEditor.searchQueryWithSelection();}
revealPreviousSearchResult(changeFocus)
{this._lastActiveEditor.revealPreviousSearchResult(changeFocus);}
revealNextSearchResult(changeFocus)
{this._lastActiveEditor.revealNextSearchResult(changeFocus);}
revealPosition(position,textRangeToSelect,forceUnformatted)
{this._lastActiveEditor.revealPosition(position,textRangeToSelect,forceUnformatted);} 
_refreshContent()
{let spinnerContainer=null;if(!this.didInitialLayout){spinnerContainer=this.element.appendChild(document.createElement("div"));spinnerContainer.className="spinner-container";spinnerContainer.appendChild((new WI.IndeterminateProgressSpinner).element);this._contentErrorMessageElement?.remove();}
let createCallback=(textEditor)=>{return(source)=>{spinnerContainer?.remove();if(source===null){if(!this._contentErrorMessageElement){const isError=true;this._contentErrorMessageElement=WI.createMessageTextView(WI.UIString("An error occurred trying to load the resource."),isError);}
if(!this._contentErrorMessageElement.parentNode)
this.element.appendChild(this._contentErrorMessageElement);return;}
textEditor.string=source||"";};};switch(this.representedObject.programType){case WI.ShaderProgram.ProgramType.Compute:this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Compute,createCallback(this._computeEditor));return;case WI.ShaderProgram.ProgramType.Render:this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Vertex,createCallback(this._vertexEditor));if(!this.representedObject.sharesVertexFragmentShader)
this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Fragment,createCallback(this._fragmentEditor));return;}}
_updateShader(shaderType)
{switch(shaderType){case WI.ShaderProgram.ShaderType.Compute:this.representedObject.updateShader(shaderType,this._computeEditor.string);return;case WI.ShaderProgram.ShaderType.Fragment:this.representedObject.updateShader(shaderType,this._fragmentEditor.string);return;case WI.ShaderProgram.ShaderType.Vertex:this.representedObject.updateShader(shaderType,this._vertexEditor.string);return;}}
_editorFocused(event)
{if(this._lastActiveEditor===event.target)
return;let currentSearchQuery=null;if(this._lastActiveEditor){currentSearchQuery=this._lastActiveEditor.currentSearchQuery;this._lastActiveEditor.searchCleared();}
this._lastActiveEditor=event.target;if(currentSearchQuery)
this._lastActiveEditor.performSearch(currentSearchQuery);}
_numberOfSearchResultsDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}
_contentDidChange(event)
{switch(event.target){case this._computeEditor:this._updateShader(WI.ShaderProgram.ShaderType.Compute);return;case this._fragmentEditor:this._updateShader(WI.ShaderProgram.ShaderType.Fragment);return;case this._vertexEditor:this._updateShader(WI.ShaderProgram.ShaderType.Vertex);return;}}};WI.ShaderProgramTreeElement=class ShaderProgramTreeElement extends WI.GeneralTreeElement
{constructor(shaderProgram)
{const subtitle=null;super("shader-program",shaderProgram.displayName,subtitle,shaderProgram);let contextType=this.representedObject.canvas.contextType;if(contextType===WI.Canvas.ContextType.WebGL||contextType===WI.Canvas.ContextType.WebGL2){this._disabledImageElement=document.createElement("img");this._disabledImageElement.title=WI.UIString("Disable Program");this._disabledImageElement.addEventListener("click",this._disabledImageElementClicked.bind(this));this.status=this._disabledImageElement;}} 
onattach()
{super.onattach();let contextType=this.representedObject.canvas.contextType;if(contextType===WI.Canvas.ContextType.WebGL||contextType===WI.Canvas.ContextType.WebGL2){this.representedObject.addEventListener(WI.ShaderProgram.Event.DisabledChanged,this._handleShaderProgramDisabledChanged,this);this.element.addEventListener("mouseover",this._handleMouseOver.bind(this));this.element.addEventListener("mouseout",this._handleMouseOut.bind(this));}}
ondetach()
{let contextType=this.representedObject.canvas.contextType;if(contextType===WI.Canvas.ContextType.WebGL||contextType===WI.Canvas.ContextType.WebGL2)
this.representedObject.removeEventListener(WI.ShaderProgram.Event.DisabledChanged,this._handleShaderProgramDisabledChanged,this);super.ondetach();}
canSelectOnMouseDown(event)
{if(this._disabledImageElement&&this._disabledImageElement.contains(event.target))
return false;return super.canSelectOnMouseDown(event);}
populateContextMenu(contextMenu,event)
{let contextType=this.representedObject.canvas.contextType;if(contextType===WI.Canvas.ContextType.WebGL||contextType===WI.Canvas.ContextType.WebGL2){let disabled=this.representedObject.disabled;contextMenu.appendItem(disabled?WI.UIString("Enable Program"):WI.UIString("Disable Program"),()=>{this.representedObject.disabled=!disabled;});contextMenu.appendSeparator();}
super.populateContextMenu(contextMenu,event);} 
_disabledImageElementClicked(event)
{this.representedObject.disabled=!this.representedObject.disabled;}
_handleShaderProgramDisabledChanged(event)
{this._listItemNode.classList.toggle("disabled",!!this.representedObject.disabled);this._disabledImageElement.title=this.representedObject.disabled?WI.UIString("Enable Program"):WI.UIString("Disable Program");}
_handleMouseOver(event)
{this.representedObject.showHighlight();}
_handleMouseOut(event)
{this.representedObject.hideHighlight();}};WI.SingleSidebar=class SingleSidebar extends WI.Sidebar
{constructor(element,side,label,supportsMultiplePanels)
{super(element,side,label);this.element.classList.add("single-sidebar");this._allowResizingToCollapse=true;if(supportsMultiplePanels){this.element.classList.add("has-navigation-bar");const navigationBarElement=null;this._navigationBar=new WI.NavigationBar(navigationBarElement,{role:"tablist"});this._navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._handleNavigationItemSelected,this);this.addSubview(this._navigationBar);}
this._resizer=new WI.Resizer(WI.Resizer.RuleOrientation.Vertical,this);this.element.insertBefore(this._resizer.element,this.element.firstChild);} 
get allowResizingToCollapse(){return this._allowResizingToCollapse;}
set allowResizingToCollapse(allow){this._allowResizingToCollapse=!!allow;}
get minimumWidth()
{let minimumWidth=super.minimumWidth;if(this._navigationBar)
minimumWidth=Math.max(minimumWidth,this._navigationBar.minimumWidth);return minimumWidth;}
get width()
{return this.element.offsetWidth;}
set width(newWidth)
{if(newWidth===this.width)
return;this._recalculateWidth(newWidth);} 
shouldInsertSidebarPanel(sidebarPanel,index)
{return!sidebarPanel.parentSidebar||sidebarPanel.parentSidebar===this;}
didInsertSidebarPanel(sidebarPanel,index)
{if(!this._navigationBar)
return;this._navigationBar.insertNavigationItem(sidebarPanel.navigationItem,index);this._recalculateWidth();}
didRemoveSidebarPanel(sidebarPanel)
{if(!this._navigationBar)
return;this._navigationBar.removeNavigationItem(sidebarPanel.navigationItem);this._recalculateWidth();}
willSetSelectedSidebarPanel(sidebarPanel)
{if(this.selectedSidebarPanel){this.removeSubview(this.selectedSidebarPanel);this.selectedSidebarPanel.selected=false;}}
didSetSelectedSidebarPanel(sidebarPanel)
{if(this.selectedSidebarPanel){this.selectedSidebarPanel.selected=true;this.addSubview(this.selectedSidebarPanel);}
if(this._navigationBar)
this._navigationBar.selectedNavigationItem=this.selectedSidebarPanel?.navigationItem??null;}
didSetCollapsed()
{if(this.selectedSidebarPanel){if(this.collapsed){if(this.selectedSidebarPanel.isAttached)
this.removeSubview(this.selectedSidebarPanel);}else{if(!this.selectedSidebarPanel.isAttached)
this.addSubview(this.selectedSidebarPanel);}}
if(!this.collapsed&&this._navigationBar)
this._navigationBar.needsLayout();}
resizerDragStarted(resizer)
{this._widthBeforeResize=this.width;}
resizerDragging(resizer,positionDelta)
{if(this._side===WI.Sidebar.Sides.Leading)
positionDelta*=-1;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
positionDelta*=-1;let newWidth=positionDelta+this._widthBeforeResize;this.width=newWidth;if(this.collapsable&&this._allowResizingToCollapse)
this.collapsed=newWidth<(this.minimumWidth/2);}
resizerDragEnded(resizer)
{if(this._widthBeforeResize===this.width)
return;if(!this.collapsed&&this._navigationBar)
this._navigationBar.sizeDidChange();if(!this.collapsed&&this._selectedSidebarPanel)
this._selectedSidebarPanel.sizeDidChange();} 
_recalculateWidth(newWidth=this.width)
{newWidth=Math.ceil(Number.constrain(newWidth,this.minimumWidth+1,this.maximumWidth));this.element.style.width=`${newWidth}px`;this.element.style.minWidth=`${this.minimumWidth}px`;if(this.collapsed)
return;if(this._navigationBar)
this._navigationBar.needsLayout(WI.View.LayoutReason.Resize);if(this.selectedSidebarPanel)
this.selectedSidebarPanel.needsLayout(WI.View.LayoutReason.Resize);this.dispatchEventToListeners(WI.Sidebar.Event.WidthDidChange,{newWidth});}
_handleNavigationItemSelected(event)
{this.selectedSidebarPanel=event.target.selectedNavigationItem?.identifier??null;}};WI.Slider=class Slider extends WI.Object
{constructor()
{super();this._element=document.createElement("div");this._element.className="slider";this._element.tabIndex=0;this._knob=this._element.appendChild(document.createElement("img"));this._value=0;this._knobY=0;this._maxY=0;this._element.addEventListener("mousedown",this);this._element.addEventListener("keydown",this._handleKeyDown.bind(this));} 
get element()
{return this._element;}
get value()
{return this._value;}
set value(value)
{value=Math.max(Math.min(value,1),0);if(value===this._value){this.recalculateKnobY();return;}
this.knobY=value;if(this.delegate&&typeof this.delegate.sliderValueDidChange==="function")
this.delegate.sliderValueDidChange(this,value);}
set knobY(value)
{this._value=value;this._knobY=Math.round((1-value)*this.maxY);this._knob.style.setProperty("--translate-y",`${this._knobY}px`);}
get maxY()
{if(this._maxY<=0&&document.body.contains(this._element))
this._maxY=Math.max(this._element.offsetHeight-Math.ceil(WI.Slider.KnobWidth/2),0);return this._maxY;}
recalculateKnobY()
{this._maxY=0;this.knobY=this._value;} 
handleEvent(event)
{switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}} 
_handleMousedown(event)
{if(event.button!==0||event.ctrlKey)
return;if(event.target!==this._knob)
this.value=1-((this._localPointForEvent(event).y-3)/this.maxY);this._startKnobY=this._knobY;this._startMouseY=this._localPointForEvent(event).y;this._element.classList.add("dragging");window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._element.focus();}
_handleMousemove(event)
{let dy=this._localPointForEvent(event).y-this._startMouseY;let y=Math.max(Math.min(this._startKnobY+dy,this.maxY),0);this.value=1-(y/this.maxY);}
_handleMouseup(event)
{this._element.classList.remove("dragging");window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);}
_handleKeyDown(event)
{let y=0;let step=event.shiftKey?0.1:0.01;switch(event.keyIdentifier){case"Down":y-=step;break;case"Up":y+=step;break;}
if(y){event.preventDefault();this.value+=y;}}
_localPointForEvent(event)
{
let rect=this._element.getBoundingClientRect();return{x:event.pageX-rect.x,y:event.pageY-rect.y,};}};WI.Slider.KnobWidth=13;WI.SoftContextMenu=class SoftContextMenu
{constructor(items,parentMenu)
{this._items=items;this._parentMenu=parentMenu;} 
show(event)
{const isSubMenu=!!this._parentMenu;this._contextMenuElement=document.createElement("div");this._contextMenuElement.className="soft-context-menu";this._contextMenuElement.style.left=event.pageX+"px";this._contextMenuElement.style.top=event.pageY+"px";this._contextMenuElement.tabIndex=0;this._contextMenuElement.addEventListener("keydown",this._menuKeyDown.bind(this),false);for(let item of this._items)
this._contextMenuElement.appendChild(this._createMenuItem(item));if(!isSubMenu){this._glassPaneElement=document.createElement("div");this._glassPaneElement.className="soft-context-menu-glass-pane";this._glassPaneElement.addEventListener("mousedown",this._glassPaneMouseDown.bind(this),false);this._glassPaneElement.appendChild(this._contextMenuElement);document.body.appendChild(this._glassPaneElement);this._focus();this._consumeEvent(event,true);}else
this._parentGlassPaneElement().appendChild(this._contextMenuElement);this._repositionMenuOnScreen(isSubMenu);} 
_consumeEvent(event,preventDefault)
{event.stopImmediatePropagation();if(preventDefault)
event.preventDefault();event.handled=true;}
_parentGlassPaneElement()
{if(!this._parentMenu)
return null;if(this._parentMenu._glassPaneElement)
return this._parentMenu._glassPaneElement;return this._parentMenu._parentGlassPaneElement();}
_createMenuItem(item)
{if(item.type==="separator")
return this._createSeparator();const checkmark="\u2713";const blackRightPointingTriangle="\u25b6";const menuItemElement=document.createElement("div");menuItemElement.className="item";if(!item.enabled)
menuItemElement.classList.add("disabled");const checkMarkElement=document.createElement("span");checkMarkElement.textContent=item.checked?checkmark:"";checkMarkElement.className="checkmark";menuItemElement.appendChild(checkMarkElement);const labelElement=document.createElement("span");labelElement.textContent=item.label;labelElement.className="label";menuItemElement.appendChild(labelElement);if(item.type==="subMenu"){const subMenuArrowElement=document.createElement("span");subMenuArrowElement.textContent=blackRightPointingTriangle;subMenuArrowElement.className="submenu-arrow";menuItemElement.appendChild(subMenuArrowElement);menuItemElement._subItems=item.subItems;}else
menuItemElement._actionId=item.id;menuItemElement.addEventListener("contextmenu",this._menuItemContextMenu.bind(this),false);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("mouseout",this._menuItemMouseOut.bind(this),false);return menuItemElement;}
_createSeparator()
{const separatorElement=document.createElement("div");separatorElement.className="separator";separatorElement._isSeparator=true;separatorElement.createChild("div","line");separatorElement.addEventListener("contextmenu",this._menuItemContextMenu.bind(this),false);separatorElement.addEventListener("mousedown",this._menuItemMouseDown.bind(this),false);separatorElement.addEventListener("mouseup",this._menuItemMouseUp.bind(this),false);separatorElement.addEventListener("mouseover",this._menuItemMouseOver.bind(this),false);return separatorElement;}
_repositionMenuOnScreen(isSubMenu)
{if(this._contextMenuElement.offsetLeft+this._contextMenuElement.offsetWidth>document.body.offsetWidth){if(isSubMenu){const parentContextMenuElement=this._parentMenu._contextMenuElement;const leftOfParent=parentContextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth+2;const fromParentRight=this._contextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth+2;this._contextMenuElement.style.left=(leftOfParent>=0?leftOfParent:fromParentRight)+"px";}else{const leftOfCursor=this._contextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth;const fromRightEdge=document.body.offsetWidth-this._contextMenuElement.offsetWidth;this._contextMenuElement.style.left=(leftOfCursor>=0?leftOfCursor:fromRightEdge)+"px";}}
if(this._contextMenuElement.offsetTop+this._contextMenuElement.offsetHeight>document.body.offsetHeight){const aboveCursor=this._contextMenuElement.offsetTop-this._contextMenuElement.offsetHeight;const fromBottomEdge=document.body.offsetHeight-this._contextMenuElement.offsetHeight;this._contextMenuElement.style.top=(!isSubMenu&&aboveCursor>=0?aboveCursor:fromBottomEdge)+"px";}}
_showSubMenu(menuItemElement)
{if(menuItemElement._subMenuTimer){clearTimeout(menuItemElement._subMenuTimer);menuItemElement._subMenuTimer=0;}
if(this._subMenu)
return;this._subMenu=new WI.SoftContextMenu(menuItemElement._subItems,this);this._subMenu.show({pageX:this._contextMenuElement.offsetLeft+menuItemElement.offsetWidth,pageY:this._contextMenuElement.offsetTop+menuItemElement.offsetTop-4});}
_hideSubMenu()
{if(!this._subMenu)
return;this._subMenu._discardSubMenus();this._focus();}
_menuItemContextMenu(event)
{this._consumeEvent(event,true);}
_menuItemMouseDown(event)
{this._consumeEvent(event,true);}
_menuItemMouseUp(event)
{this._triggerAction(event.target,event);this._consumeEvent(event);}
_menuItemMouseOver(event)
{this._highlightMenuItem(event.target._isSeparator?null:event.target);}
_menuItemMouseOut(event)
{const shouldUnhighlight=!this._subMenu||!event.relatedTarget||this._contextMenuElement.contains(event.relatedTarget)||event.relatedTarget.classList.contains("soft-context-menu-glass-pane");if(shouldUnhighlight)
this._highlightMenuItem(null);}
_menuKeyDown(event)
{switch(event.keyIdentifier){case"Up":this._highlightPrevious();break;case"Down":this._highlightNext();break;case"Left":if(this._parentMenu){this._highlightMenuItem(null);this._parentMenu._hideSubMenu();}
break;case"Enter":if(!isEnterKey(event))
break; case"U+0020": if(this._highlightedMenuItemElement&&!this._highlightedMenuItemElement._subItems)
this._triggerAction(this._highlightedMenuItemElement,event); case"Right":if(this._highlightedMenuItemElement&&this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._focus();this._subMenu._highlightNext();}
break;case"U+001B": this._discardMenu(true,event);break;}
this._consumeEvent(event,true);}
_glassPaneMouseDown(event)
{this._discardMenu(true,event);this._consumeEvent(event);}
_focus()
{this._contextMenuElement.focus();}
_triggerAction(menuItemElement,event)
{if(!menuItemElement._subItems){this._discardMenu(true,event);if(typeof menuItemElement._actionId==="number"){WI.ContextMenu.contextMenuItemSelected(menuItemElement._actionId);menuItemElement._actionId=null;}
return;}
this._showSubMenu(menuItemElement);this._consumeEvent(event);}
_highlightMenuItem(menuItemElement,skipSubMenuExpansion)
{if(this._highlightedMenuItemElement===menuItemElement)
return;this._hideSubMenu();if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.remove("highlighted");if(this._highlightedMenuItemElement._subItems&&this._highlightedMenuItemElement._subMenuTimer){clearTimeout(this._highlightedMenuItemElement._subMenuTimer);this._highlightedMenuItemElement._subMenuTimer=0;}}
this._highlightedMenuItemElement=menuItemElement;if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.add("highlighted");this._contextMenuElement.focus();if(!skipSubMenuExpansion&&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=menuItemElement.previousSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,true);}
_highlightNext()
{let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&menuItemElement._isSeparator)
menuItemElement=menuItemElement.nextSibling;if(menuItemElement)
this._highlightMenuItem(menuItemElement,true);}
_discardMenu(closeParentMenus,event)
{if(this._subMenu&&!closeParentMenus)
return;if(this._glassPaneElement){const glassPane=this._glassPaneElement;this._glassPaneElement=null;document.body.removeChild(glassPane);if(this._parentMenu){this._parentMenu._subMenu=null;if(closeParentMenus)
this._parentMenu._discardMenu(closeParentMenus,event);}
if(event)
this._consumeEvent(event,true);}else if(this._parentMenu&&this._contextMenuElement.parentElement){this._discardSubMenus();if(closeParentMenus)
this._parentMenu._discardMenu(closeParentMenus,event);if(event)
this._consumeEvent(event,true);}}
_discardSubMenus()
{if(this._subMenu)
this._subMenu._discardSubMenus();if(this._contextMenuElement.parentElement)
this._contextMenuElement.parentElement.removeChild(this._contextMenuElement);if(this._parentMenu)
this._parentMenu._subMenu=null;}};WI.SourceCodeTextEditor=class SourceCodeTextEditor extends WI.TextEditor
{constructor(sourceCode)
{super();this.delegate=this;this._sourceCode=sourceCode;this._breakpointMap={};this._issuesLineNumberMap=new Map;this._widgetMap=new Map;this._contentPopulated=false;this._invalidLineNumbers={0:true};this._requestingScriptContent=false;this._activeCallFrameSourceCodeLocation=null;this._threadLineNumberMap=new Map;this._threadWidgetMap=new Map; this._threadTargetMap=new Map; this._typeTokenScrollHandler=null;this._typeTokenAnnotator=null;this._basicBlockAnnotator=null;this._editingController=null;this._autoFormat=false;this._isProbablyMinified=false;this._ignoreContentDidChange=0;this._ignoreLocationUpdateBreakpoint=null;this._ignoreBreakpointAddedBreakpoint=null;this._ignoreBreakpointRemovedBreakpoint=null;this._ignoreAllBreakpointLocationUpdates=false;this._updateTokenTrackingControllerState();this.element.classList.add("source-code");if(this._supportsDebugging){WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._updateBreakpointLocation,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetAdded,this._targetAdded,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._targetRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._breakpointAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._breakpointRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._callFramesDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._debuggerDidPause,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerDidResume,this);if(WI.debuggerManager.activeCallFrame)
this._debuggerDidPause();this._activeCallFrameDidChange();}
WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._handleFormatterDidChange,this);if(this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length>0)
WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);else
this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);sourceCode.requestContent().then(this._contentAvailable.bind(this));new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,"G",this.showGoToLineDialog.bind(this),this.element);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._logCleared,this);} 
get sourceCode()
{return this._sourceCode;}
get target()
{if(this._sourceCode instanceof WI.SourceMapResource){if(this._sourceCode.sourceMap.originalSourceCode instanceof WI.Script)
return this._sourceCode.sourceMap.originalSourceCode.target;}
if(this._sourceCode instanceof WI.Script)
return this._sourceCode.target;return WI.mainTarget;}
attached()
{super.attached();if(WI.settings.showJavaScriptTypeInformation.value){if(this._typeTokenAnnotator)
this._typeTokenAnnotator.resume();if(!this._typeTokenScrollHandler&&this._typeTokenAnnotator)
this._enableScrollEventsForTypeTokenAnnotator();}else{if(this._typeTokenAnnotator)
this._setTypeTokenAnnotatorEnabledState(false);}
if(WI.settings.enableControlFlowProfiler.value){if(this._basicBlockAnnotator)
this._basicBlockAnnotator.resume();if(!this._controlFlowScrollHandler&&this._basicBlockAnnotator)
this._enableScrollEventsForControlFlowAnnotator();}else{this._basicBlockAnnotatorEnabled=false;}}
detached()
{this.tokenTrackingController.removeHighlightedRange();this._dismissPopover();this._dismissEditingController(true);if(this._typeTokenAnnotator)
this._typeTokenAnnotator.pause();if(this._basicBlockAnnotator)
this._basicBlockAnnotator.pause();super.detached();}
close()
{if(this._supportsDebugging){WI.JavaScriptBreakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._updateBreakpointLocation,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetAdded,this._targetAdded,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetRemoved,this._targetRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._breakpointAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._breakpointRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._callFramesDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Paused,this._debuggerDidPause,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerDidResume,this);if(this._activeCallFrameSourceCodeLocation){this._activeCallFrameSourceCodeLocation.removeEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this);this._activeCallFrameSourceCodeLocation=null;}}
WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.FormatterDidChange,this._handleFormatterDidChange,this);if(this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length>0)
WI.notifications.removeEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);else
this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.Cleared,this._logCleared,this);}
canBeFormatted()
{

if(this._sourceCode instanceof WI.SourceMapResource)
return false;return super.canBeFormatted();}
canShowTypeAnnotations()
{return!!this._getAssociatedScript()&&!this.hasModified;}
canShowCoverageHints()
{return!!this._getAssociatedScript()&&!this.hasModified;}
customPerformSearch(query)
{let queryRegex=WI.SearchUtilities.searchRegExpForString(query,WI.SearchUtilities.defaultSettings);if(!queryRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return true;}
function searchResultCallback(error,matches)
{if(this.currentSearchQuery!==query)
return;if(error||!matches||!matches.length){this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;}
var searchResults=[];for(var i=0;i<matches.length;++i){var matchLineNumber=matches[i].lineNumber;var line=this.line(matchLineNumber);if(!line)
return;queryRegex.lastIndex=0;var lineMatch=null;while(queryRegex.lastIndex+query.length<=line.length&&(lineMatch=queryRegex.exec(line))){var resultTextRange=new WI.TextRange(matchLineNumber,lineMatch.index,matchLineNumber,queryRegex.lastIndex);searchResults.push(resultTextRange);}}
this.addSearchResults(searchResults);this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);}
if(this.hasEdits())
return false;if(this._sourceCode instanceof WI.SourceMapResource)
return false;if(this._sourceCode instanceof WI.LocalResource)
return false;if(this._sourceCode instanceof WI.LocalScript)
return false;let target=this._sourceCode.target;let caseSensitive=WI.SearchUtilities.defaultSettings.caseSensitive.value;let isRegex=WI.SearchUtilities.defaultSettings.regularExpression.value;if(this._sourceCode instanceof WI.Resource&&target.hasCommand("Page.searchInResource")){target.PageAgent.searchInResource(this._sourceCode.parentFrame.id,this._sourceCode.url,query,caseSensitive,isRegex,searchResultCallback.bind(this));return true;}
if(this._sourceCode instanceof WI.Script){target.DebuggerAgent.searchInContent(this._sourceCode.id,query,caseSensitive,isRegex,searchResultCallback.bind(this));return true;}
return false;}
showGoToLineDialog()
{if(!this._goToLineDialog)
this._goToLineDialog=new WI.GoToLineDialog(this);this._goToLineDialog.present(this.element);}
isDialogRepresentedObjectValid(goToLineDialog,lineNumber)
{return!isNaN(lineNumber)&&lineNumber>0&&lineNumber<=this.lineCount;}
dialogWasDismissedWithRepresentedObject(goToLineDialog,lineNumber)
{let position=new WI.SourceCodePosition(lineNumber-1,0);let range=new WI.TextRange(lineNumber-1,0,lineNumber,0);this.revealPosition(position,range,false,true);}
contentDidChange(replacedRanges,newRanges)
{super.contentDidChange(replacedRanges,newRanges);if(this._ignoreContentDidChange>0)
return;for(var range of newRanges)
this._updateEditableMarkers(range);if(this._basicBlockAnnotator){this._basicBlockAnnotatorEnabled=false;this._basicBlockAnnotator=null;}
if(this._typeTokenAnnotator){this._setTypeTokenAnnotatorEnabledState(false);this._typeTokenAnnotator=null;}}
toggleTypeAnnotations()
{if(!this._typeTokenAnnotator)
return Promise.reject(new Error("TypeTokenAnnotator is not initialized."));var newActivatedState=!this._typeTokenAnnotator.isActive();if(newActivatedState&&this._isProbablyMinified&&!this.formatted){return this.updateFormattedState(true).then(()=>{this._setTypeTokenAnnotatorEnabledState(newActivatedState);});}
this._setTypeTokenAnnotatorEnabledState(newActivatedState);return Promise.resolve();}
toggleUnexecutedCodeHighlights()
{if(!this._basicBlockAnnotator)
return Promise.reject(new Error("BasicBlockAnnotator is not initialized."));let newActivatedState=!this._basicBlockAnnotator.isActive();if(newActivatedState&&this._isProbablyMinified&&!this.formatted){return this.updateFormattedState(true).then(()=>{this._basicBlockAnnotatorEnabled=newActivatedState;});}
this._basicBlockAnnotatorEnabled=newActivatedState;return Promise.resolve();}
showPopoverForTypes(typeDescription,bounds,title)
{var content=document.createElement("div");content.className="object expandable";var titleElement=document.createElement("div");titleElement.className="title";titleElement.textContent=title;content.appendChild(titleElement);var bodyElement=content.appendChild(document.createElement("div"));bodyElement.className="body";var typeTreeView=new WI.TypeTreeView(typeDescription);bodyElement.appendChild(typeTreeView.element);this._showPopover(content,bounds);} 
prettyPrint(pretty)
{

var shouldResumeBasicBlockAnnotator=this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive();if(shouldResumeBasicBlockAnnotator)
this._basicBlockAnnotatorEnabled=false;let shouldResumeTypeTokenAnnotator=this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive();if(shouldResumeTypeTokenAnnotator)
this._setTypeTokenAnnotatorEnabledState(false);return super.prettyPrint(pretty).then(()=>{if(pretty||!this._isProbablyMinified){if(shouldResumeBasicBlockAnnotator)
this._basicBlockAnnotatorEnabled=true;if(shouldResumeTypeTokenAnnotator)
this._setTypeTokenAnnotatorEnabledState(true);}else{if(this._basicBlockAnnotator)
this._basicBlockAnnotatorEnabled=false;this._setTypeTokenAnnotatorEnabledState(false);}});} 
_unformattedLineInfoForEditorLineInfo(lineInfo)
{if(this.formatterSourceMap)
return this.formatterSourceMap.formattedToOriginal(lineInfo.lineNumber,lineInfo.columnNumber);return lineInfo;}
_sourceCodeLocationForEditorPosition(position)
{var lineInfo={lineNumber:position.line,columnNumber:position.ch};var unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(lineInfo);return this.sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);}
_editorLineInfoForSourceCodeLocation(sourceCodeLocation)
{if(this._sourceCode instanceof WI.SourceMapResource)
return{lineNumber:sourceCodeLocation.displayLineNumber,columnNumber:sourceCodeLocation.displayColumnNumber};return{lineNumber:sourceCodeLocation.formattedLineNumber,columnNumber:sourceCodeLocation.formattedColumnNumber};}
_breakpointForEditorLineInfo(lineInfo)
{if(!this._breakpointMap[lineInfo.lineNumber])
return null;return this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber];}
_addBreakpointWithEditorLineInfo(breakpoint,lineInfo)
{if(!this._breakpointMap[lineInfo.lineNumber])
this._breakpointMap[lineInfo.lineNumber]={};this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber]=breakpoint;}
_removeBreakpointWithEditorLineInfo(breakpoint,lineInfo)
{delete this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber];if(isEmptyObject(this._breakpointMap[lineInfo.lineNumber]))
delete this._breakpointMap[lineInfo.lineNumber];}
_populateWithContent(content)
{content=content||"";this._prepareEditorForInitialContent(content);if(this._autoFormat){this._autoFormat=false;this.deferReveal=true;this.string=content;this.deferReveal=false;this.updateFormattedState(true).then(()=>{this._proceedPopulateWithContent(this.string);});return;}
this._proceedPopulateWithContent(content);}
_proceedPopulateWithContent(content)
{this.dispatchEventToListeners(WI.SourceCodeTextEditor.Event.ContentWillPopulate);this.string=content;this._createBasicBlockAnnotator();if(WI.settings.enableControlFlowProfiler.value&&this._basicBlockAnnotator)
this._basicBlockAnnotatorEnabled=true;this._createTypeTokenAnnotator();if(WI.settings.showJavaScriptTypeInformation.value)
this._setTypeTokenAnnotatorEnabledState(true);this._contentDidPopulate();}
_contentDidPopulate()
{this._contentPopulated=true;this.dispatchEventToListeners(WI.SourceCodeTextEditor.Event.ContentDidPopulate);

this._reinsertAllIssues();this._reinsertAllThreadIndicators();this._updateEditableMarkers();}
_prepareEditorForInitialContent(content)
{if(this._contentPopulated)
return;if(this._supportsDebugging){this._breakpointMap={};for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(this._sourceCode)){var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}}
if(this._sourceCode instanceof WI.Resource)
this.mimeType=this._sourceCode.syntheticMIMEType;else if(this._sourceCode instanceof WI.Script)
this.mimeType="text/javascript";else if(this._sourceCode instanceof WI.CSSStyleSheet)
this.mimeType="text/css";if(this.canBeFormatted()&&isTextLikelyMinified(content)){this._autoFormat=true;this._isProbablyMinified=true;}}
_contentAvailable(parameters)
{if(parameters.error)
return;if(parameters.message){this._showMessage(parameters.message);return;}
var sourceCode=parameters.sourceCode;var content=sourceCode.content;var base64Encoded=parameters.base64Encoded;if(this._fullContentPopulated)
return;this._fullContentPopulated=true;this._invalidLineNumbers={};
this.repeatReveal=!!this.string;this._populateWithContent(content);this.repeatReveal=false;}
_showMessage(message)
{this.element.removeChildren();this.element.appendChild(WI.createMessageTextView(message));}
_breakpointStatusDidChange(event)
{this._updateBreakpointStatus(event.target);}
_breakpointsEnabledDidChange()
{for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(this._sourceCode))
this._updateBreakpointStatus(breakpoint);}
_updateBreakpointStatus(breakpoint)
{if(!this._contentPopulated)
return;if(!this._matchesBreakpoint(breakpoint))
return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}
_updateBreakpointLocation(event)
{if(!this._contentPopulated)
return;var breakpoint=event.target;if(!this._matchesBreakpoint(breakpoint))
return;if(this._ignoreAllBreakpointLocationUpdates)
return;if(breakpoint===this._ignoreLocationUpdateBreakpoint)
return;var sourceCodeLocation=breakpoint.sourceCodeLocation;if(this._sourceCode instanceof WI.SourceMapResource){if(sourceCodeLocation.displaySourceCode!==this._sourceCode)
return;var oldLineInfo={lineNumber:event.data.oldDisplayLineNumber,columnNumber:event.data.oldDisplayColumnNumber};var newLineInfo={lineNumber:sourceCodeLocation.displayLineNumber,columnNumber:sourceCodeLocation.displayColumnNumber};}else{if(sourceCodeLocation.sourceCode!==this._sourceCode)
return;var oldLineInfo={lineNumber:event.data.oldFormattedLineNumber,columnNumber:event.data.oldFormattedColumnNumber};var newLineInfo={lineNumber:sourceCodeLocation.formattedLineNumber,columnNumber:sourceCodeLocation.formattedColumnNumber};}
var existingBreakpoint=this._breakpointForEditorLineInfo(oldLineInfo);if(!existingBreakpoint)
return;this.setBreakpointInfoForLineAndColumn(oldLineInfo.lineNumber,oldLineInfo.columnNumber,null);this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));this._removeBreakpointWithEditorLineInfo(breakpoint,oldLineInfo);this._addBreakpointWithEditorLineInfo(breakpoint,newLineInfo);}
_breakpointAdded(event)
{if(!this._contentPopulated)
return;var breakpoint=event.data.breakpoint;if(!this._matchesBreakpoint(breakpoint))
return;if(breakpoint===this._ignoreBreakpointAddedBreakpoint)
return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}
_breakpointRemoved(event)
{if(!this._contentPopulated)
return;var breakpoint=event.data.breakpoint;if(!this._matchesBreakpoint(breakpoint))
return;if(breakpoint===this._ignoreBreakpointRemovedBreakpoint)
return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._removeBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,null);}
_targetAdded(event)
{if(WI.targets.length===2)
this._reinsertAllThreadIndicators();}
_targetRemoved(event)
{if(WI.targets.length===1){this._reinsertAllThreadIndicators();return;}
let target=event.data.target;this._removeThreadIndicatorForTarget(target);}
_callFramesDidChange(event)
{if(WI.targets.length===1)
return;let target=event.data.target;this._removeThreadIndicatorForTarget(target);this._addThreadIndicatorForTarget(target);}
_addThreadIndicatorForTarget(target)
{let targetData=WI.debuggerManager.dataForTarget(target);let topCallFrame=targetData.callFrames[0];if(!topCallFrame)
return;let sourceCodeLocation=topCallFrame.sourceCodeLocation;if(!sourceCodeLocation)
return;if(!this._looselyMatchesSourceCodeLocation(sourceCodeLocation))
return;let lineNumberWithIndicator=sourceCodeLocation.formattedLineNumber;this._threadTargetMap.set(target,lineNumberWithIndicator);let threads=this._threadLineNumberMap.get(lineNumberWithIndicator);if(!threads){threads=[];this._threadLineNumberMap.set(lineNumberWithIndicator,threads);}
threads.push(target);let widget=this._threadIndicatorWidgetForLine(target,lineNumberWithIndicator);this._updateThreadIndicatorWidget(widget,threads);this.addStyleClassToLine(lineNumberWithIndicator,"thread-indicator");}
_removeThreadIndicatorForTarget(target)
{let lineNumberWithIndicator=this._threadTargetMap.take(target);if(lineNumberWithIndicator===undefined)
return;let threads=this._threadLineNumberMap.get(lineNumberWithIndicator);threads.remove(target);if(threads.length){let widget=this._threadWidgetMap.get(lineNumberWithIndicator);this._updateThreadIndicatorWidget(widget,threads);return;}
this._threadLineNumberMap.delete(lineNumberWithIndicator);let widget=this._threadWidgetMap.take(lineNumberWithIndicator);if(widget)
widget.clear();this.removeStyleClassFromLine(lineNumberWithIndicator,"thread-indicator");}
_threadIndicatorWidgetForLine(target,lineNumber)
{let widget=this._threadWidgetMap.get(lineNumber);if(widget)
return widget;widget=this.createWidgetForLine(lineNumber);if(!widget)
return null;let widgetElement=widget.widgetElement;widgetElement.classList.add("line-indicator-widget","thread-widget","inline");widgetElement.addEventListener("click",this._handleThreadIndicatorWidgetClick.bind(this,widget,lineNumber));this._threadWidgetMap.set(lineNumber,widget);return widget;}
_updateThreadIndicatorWidget(widget,threads)
{if(!widget)
return;let widgetElement=widget.widgetElement;widgetElement.removeChildren();widget[WI.SourceCodeTextEditor.WidgetContainsMultipleThreadsSymbol]=threads.length>1;if(widgetElement.classList.contains("inline")||threads.length===1){let textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";textElement.textContent=threads.length===1?threads[0].displayName:WI.UIString("%d Threads").format(threads.length);}else{for(let target of threads){let textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";textElement.textContent=target.displayName;widgetElement.appendChild(document.createElement("br"));}}
widget.update();}
_handleThreadIndicatorWidgetClick(widget,lineNumber,event)
{if(!this._isWidgetToggleable(widget))
return;widget.widgetElement.classList.toggle("inline");let threads=this._threadLineNumberMap.get(lineNumber);this._updateThreadIndicatorWidget(widget,threads);}
_activeCallFrameDidChange()
{if(this._activeCallFrameSourceCodeLocation){this._activeCallFrameSourceCodeLocation.removeEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this);this._activeCallFrameSourceCodeLocation=null;}
let activeCallFrame=WI.debuggerManager.activeCallFrame;if(!activeCallFrame||!this._matchesSourceCodeLocation(activeCallFrame.sourceCodeLocation)){this.setExecutionLineAndColumn(NaN,NaN);return;}
this._dismissPopover();this._activeCallFrameSourceCodeLocation=activeCallFrame.sourceCodeLocation;this._activeCallFrameSourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this);
let lineInfo=this._editorLineInfoForSourceCodeLocation(activeCallFrame.sourceCodeLocation);this.setExecutionLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber);if(this._fullContentPopulated||!(this._sourceCode instanceof WI.Resource)||this._requestingScriptContent)
return;

if(this._sourceCode.type===WI.Resource.Type.Document)
this._populateWithInlineScriptContent();else
this._populateWithScriptContent();}
_activeCallFrameSourceCodeLocationChanged(event)
{if(isNaN(this.executionLineNumber))
return;var lineInfo=this._editorLineInfoForSourceCodeLocation(this._activeCallFrameSourceCodeLocation);this.setExecutionLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber);}
_populateWithInlineScriptContent()
{var scripts=this._sourceCode.scripts;if(!scripts.length)
return;var pendingRequestCount=scripts.length;if(this._inlineScriptContentPopulated===pendingRequestCount)
return;this._inlineScriptContentPopulated=pendingRequestCount;function scriptContentAvailable(parameters)
{if(--pendingRequestCount)
return;this._requestingScriptContent=false;if(this._fullContentPopulated)
return;var scriptOpenTag="<script>";var scriptCloseTag="</script>";var content="";var lineNumber=0;var columnNumber=0;this._invalidLineNumbers={};for(var i=0;i<scripts.length;++i){for(var newLinesCount=scripts[i].range.startLine-lineNumber;newLinesCount>0;--newLinesCount){if(!columnNumber)
this._invalidLineNumbers[scripts[i].range.startLine-newLinesCount]=true;columnNumber=0;content+="\n";}
for(var spacesCount=scripts[i].range.startColumn-columnNumber-scriptOpenTag.length;spacesCount>0;--spacesCount)
content+=" ";content+=scriptOpenTag;content+=scripts[i].content;content+=scriptCloseTag;lineNumber=scripts[i].range.endLine;columnNumber=scripts[i].range.endColumn+scriptCloseTag.length;}
this._populateWithContent(content);}
this._requestingScriptContent=true;var boundScriptContentAvailable=scriptContentAvailable.bind(this);for(var i=0;i<scripts.length;++i)
scripts[i].requestContent().then(boundScriptContentAvailable);}
_populateWithScriptContent()
{var scripts=this._sourceCode.scripts;if(!scripts.length)
return;function scriptContentAvailable(parameters)
{var content=parameters.content;this._requestingScriptContent=false;if(this._fullContentPopulated)
return;this._fullContentPopulated=true;this._populateWithContent(content);}
this._requestingScriptContent=true;scripts[0].requestContent().then(scriptContentAvailable.bind(this));}
_looselyMatchesSourceCodeLocation(sourceCodeLocation)
{if(this._sourceCode instanceof WI.SourceMapResource)
return sourceCodeLocation.displaySourceCode===this._sourceCode;if(this._sourceCode instanceof WI.Resource||this._sourceCode instanceof WI.Script||this._sourceCode instanceof WI.CSSStyleSheet)
return sourceCodeLocation.sourceCode.url===this._sourceCode.url;return false;}
_matchesSourceCodeLocation(sourceCodeLocation)
{if(this._sourceCode instanceof WI.SourceMapResource)
return sourceCodeLocation.displaySourceCode===this._sourceCode;if(this._sourceCode instanceof WI.Resource||this._sourceCode instanceof WI.CSSStyleSheet)
return sourceCodeLocation.sourceCode.url===this._sourceCode.url;if(this._sourceCode instanceof WI.Script)
return sourceCodeLocation.sourceCode===this._sourceCode;return false;}
_matchesBreakpoint(breakpoint)
{if(this._sourceCode instanceof WI.SourceMapResource)
return breakpoint.sourceCodeLocation.displaySourceCode===this._sourceCode;if(this._sourceCode instanceof WI.Resource)
return breakpoint.contentIdentifier===this._sourceCode.contentIdentifier;if(this._sourceCode instanceof WI.Script)
return breakpoint.contentIdentifier===this._sourceCode.contentIdentifier||breakpoint.scriptIdentifier===this._sourceCode.id;return false;}
_issueWasAdded(event)
{var issue=event.data.issue;if(!WI.ConsoleManager.issueMatchSourceCode(issue,this._sourceCode))
return;this._addIssue(issue);}
_addIssue(issue)
{var sourceCodeLocation=issue.sourceCodeLocation;if(!sourceCodeLocation)
return;var lineNumber=sourceCodeLocation.formattedLineNumber;var lineNumberIssues=this._issuesLineNumberMap.get(lineNumber);if(!lineNumberIssues){lineNumberIssues=[];this._issuesLineNumberMap.set(lineNumber,lineNumberIssues);}
for(var existingIssue of lineNumberIssues){if(existingIssue.sourceCodeLocation.columnNumber===sourceCodeLocation.columnNumber&&existingIssue.text===issue.text)
return;}
lineNumberIssues.push(issue);if(issue.level===WI.IssueMessage.Level.Error)
this.addStyleClassToLine(lineNumber,WI.SourceCodeTextEditor.LineErrorStyleClassName);else if(issue.level===WI.IssueMessage.Level.Warning)
this.addStyleClassToLine(lineNumber,WI.SourceCodeTextEditor.LineWarningStyleClassName);else
console.error("Unknown issue level");var widget=this._issueWidgetForLine(lineNumber);if(widget){if(issue.level===WI.IssueMessage.Level.Error)
widget.widgetElement.classList.add(WI.SourceCodeTextEditor.LineErrorStyleClassName);else if(issue.level===WI.IssueMessage.Level.Warning)
widget.widgetElement.classList.add(WI.SourceCodeTextEditor.LineWarningStyleClassName);this._updateIssueWidgetForIssues(widget,lineNumberIssues);}}
_issueWidgetForLine(lineNumber)
{var widget=this._widgetMap.get(lineNumber);if(widget)
return widget;widget=this.createWidgetForLine(lineNumber);if(!widget)
return null;var widgetElement=widget.widgetElement;widgetElement.classList.add("line-indicator-widget","issue-widget","inline");widgetElement.addEventListener("click",this._handleWidgetClick.bind(this,widget,lineNumber));this._widgetMap.set(lineNumber,widget);return widget;}
_iconClassNameForIssueLevel(level)
{if(level===WI.IssueMessage.Level.Warning)
return"icon-warning";return"icon-error";}
_updateIssueWidgetForIssues(widget,issues)
{var widgetElement=widget.widgetElement;widgetElement.removeChildren();if(widgetElement.classList.contains("inline")||issues.length===1){var iconElement=widgetElement.appendChild(document.createElement("span"));iconElement.className="icon";var textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";if(issues.length===1){iconElement.classList.add(this._iconClassNameForIssueLevel(issues[0].level));textElement.textContent=issues[0].text;}else{var errorsCount=0;var warningsCount=0;for(var issue of issues){if(issue.level===WI.IssueMessage.Level.Error)
++errorsCount;else if(issue.level===WI.IssueMessage.Level.Warning)
++warningsCount;}
if(warningsCount&&errorsCount){iconElement.classList.add(this._iconClassNameForIssueLevel(issue.level));textElement.textContent=WI.UIString("%d Errors, %d Warnings").format(errorsCount,warningsCount);}else if(errorsCount){iconElement.classList.add(this._iconClassNameForIssueLevel(issue.level));textElement.textContent=WI.UIString("%d Errors").format(errorsCount);}else if(warningsCount){iconElement.classList.add(this._iconClassNameForIssueLevel(issue.level));textElement.textContent=WI.UIString("%d Warnings").format(warningsCount);}
widget[WI.SourceCodeTextEditor.WidgetContainsMultipleIssuesSymbol]=true;}}else{for(var issue of issues){var iconElement=widgetElement.appendChild(document.createElement("span"));iconElement.className="icon";iconElement.classList.add(this._iconClassNameForIssueLevel(issue.level));var textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";textElement.textContent=issue.text;widgetElement.appendChild(document.createElement("br"));}}
widget.update();}
_isWidgetToggleable(widget)
{if(widget[WI.SourceCodeTextEditor.WidgetContainsMultipleIssuesSymbol])
return true;if(widget[WI.SourceCodeTextEditor.WidgetContainsMultipleThreadsSymbol])
return true;if(!widget.widgetElement.classList.contains("inline"))
return true;var textElement=widget.widgetElement.lastChild;if(textElement.offsetWidth!==textElement.scrollWidth)
return true;return false;}
_handleWidgetClick(widget,lineNumber,event)
{if(!this._isWidgetToggleable(widget))
return;widget.widgetElement.classList.toggle("inline");var lineNumberIssues=this._issuesLineNumberMap.get(lineNumber);this._updateIssueWidgetForIssues(widget,lineNumberIssues);}
_breakpointInfoForBreakpoint(breakpoint)
{return{resolved:breakpoint.resolved,disabled:breakpoint.disabled,autoContinue:breakpoint.autoContinue};}
get _supportsDebugging()
{if(this._sourceCode instanceof WI.Resource){if(this._sourceCode.localResourceOverride)
return false;return this._sourceCode.type===WI.Resource.Type.Document||this._sourceCode.type===WI.Resource.Type.Script;}
if(this._sourceCode instanceof WI.Script)
return!(this._sourceCode instanceof WI.LocalScript);return false;} 
textEditorBaseURL(textEditor)
{return this._sourceCode.url;}
textEditorScriptSourceType(textEditor)
{let script=this._getAssociatedScript();return script?script.sourceType:WI.Script.SourceType.Program;}
textEditorShouldHideLineNumber(textEditor,lineNumber)
{return lineNumber in this._invalidLineNumbers;}
textEditorGutterContextMenu(textEditor,lineNumber,columnNumber,editorBreakpoints,event)
{if(!this._supportsDebugging)
return;event.preventDefault();let addBreakpoint=()=>{let data=this.textEditorBreakpointAdded(this,lineNumber,columnNumber);this.setBreakpointInfoForLineAndColumn(data.lineNumber,data.columnNumber,data.breakpointInfo);};let contextMenu=WI.ContextMenu.createFromEvent(event);if(WI.debuggerManager.paused){let editorLineInfo={lineNumber,columnNumber};let unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(editorLineInfo);let sourceCodeLocation=this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);let script;if(sourceCodeLocation.sourceCode instanceof WI.Script)
script=sourceCodeLocation.sourceCode;else if(sourceCodeLocation.sourceCode instanceof WI.Resource)
script=sourceCodeLocation.sourceCode.scriptForLocation(sourceCodeLocation);if(script){contextMenu.appendItem(WI.UIString("Continue to Here"),()=>{WI.debuggerManager.continueToLocation(script,sourceCodeLocation.lineNumber,sourceCodeLocation.columnNumber);});contextMenu.appendSeparator();}}
let breakpoints=[];for(let lineInfo of editorBreakpoints){let breakpoint=this._breakpointForEditorLineInfo(lineInfo);if(breakpoint)
breakpoints.push(breakpoint);}
if(!breakpoints.length){contextMenu.appendItem(WI.UIString("Add Breakpoint"),addBreakpoint.bind(this));return;}
if(breakpoints.length===1){WI.BreakpointPopover.appendContextMenuItems(contextMenu,breakpoints[0],event.target);if(!WI.isShowingSourcesTab()){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showSourcesTab({representedObjectToSelect:breakpoints[0],initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}
return;}
let shouldDisable=breakpoints.some((breakpoint)=>!breakpoint.disabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Breakpoints"):WI.UIString("Enable Breakpoints"),()=>{for(let breakpoint of breakpoints)
breakpoint.disabled=shouldDisable;});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{for(let breakpoint of breakpoints)
WI.debuggerManager.removeBreakpoint(breakpoint);});}
textEditorBreakpointAdded(textEditor,lineNumber,columnNumber)
{if(!this._supportsDebugging)
return null;var editorLineInfo={lineNumber,columnNumber};var unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(editorLineInfo);var sourceCodeLocation=this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);var breakpoint=new WI.JavaScriptBreakpoint(sourceCodeLocation);var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this._ignoreBreakpointAddedBreakpoint=breakpoint;WI.debuggerManager.addBreakpoint(breakpoint);this._ignoreBreakpointAddedBreakpoint=null;return{breakpointInfo:this._breakpointInfoForBreakpoint(breakpoint),lineNumber:lineInfo.lineNumber,columnNumber:lineInfo.columnNumber};}
textEditorBreakpointRemoved(textEditor,lineNumber,columnNumber)
{if(!this._supportsDebugging)
return;var lineInfo={lineNumber,columnNumber};var breakpoint=this._breakpointForEditorLineInfo(lineInfo);if(!breakpoint)
return;this._removeBreakpointWithEditorLineInfo(breakpoint,lineInfo);this._ignoreBreakpointRemovedBreakpoint=breakpoint;WI.debuggerManager.removeBreakpoint(breakpoint);this._ignoreBreakpointRemovedBreakpoint=null;}
textEditorBreakpointMoved(textEditor,oldLineNumber,oldColumnNumber,newLineNumber,newColumnNumber)
{if(!this._supportsDebugging)
return;var oldLineInfo={lineNumber:oldLineNumber,columnNumber:oldColumnNumber};var breakpoint=this._breakpointForEditorLineInfo(oldLineInfo);if(!breakpoint)
return;this._removeBreakpointWithEditorLineInfo(breakpoint,oldLineInfo);var newLineInfo={lineNumber:newLineNumber,columnNumber:newColumnNumber};var unformattedNewLineInfo=this._unformattedLineInfoForEditorLineInfo(newLineInfo);this._ignoreLocationUpdateBreakpoint=breakpoint;breakpoint.sourceCodeLocation.update(this._sourceCode,unformattedNewLineInfo.lineNumber,unformattedNewLineInfo.columnNumber);this._ignoreLocationUpdateBreakpoint=null;var accurateNewLineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,accurateNewLineInfo);if(accurateNewLineInfo.lineNumber!==newLineInfo.lineNumber||accurateNewLineInfo.columnNumber!==newLineInfo.columnNumber)
this.updateBreakpointLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,accurateNewLineInfo.lineNumber,accurateNewLineInfo.columnNumber);}
textEditorBreakpointClicked(textEditor,lineNumber,columnNumber)
{if(!this._supportsDebugging)
return;var breakpoint=this._breakpointForEditorLineInfo({lineNumber,columnNumber});if(!breakpoint)
return;breakpoint.cycleToNextMode();}
textEditorUpdatedFormatting(textEditor)
{this._ignoreAllBreakpointLocationUpdates=true;this._sourceCode.formatterSourceMap=this.formatterSourceMap;this._ignoreAllBreakpointLocationUpdates=false;
if(this._sourceCode instanceof WI.Resource&&!(this._sourceCode instanceof WI.SourceMapResource)){var scripts=this._sourceCode.scripts;for(var i=0;i<scripts.length;++i)
scripts[i].formatterSourceMap=this.formatterSourceMap;}else if(this._sourceCode instanceof WI.Script){if(this._sourceCode.resource)
this._sourceCode.resource.formatterSourceMap=this.formatterSourceMap;}
this._handleFormatterDidChange();}
textEditorExecutionHighlightRange(currentPosition,callback)
{let position=this.currentPositionToOriginalPosition(currentPosition);let script=this._getAssociatedScript(position);if(!script){callback(null);return;}
let{startLine,startColumn}=script.range;function toInlineScriptPosition(position){let columnNumber=position.lineNumber===startLine?position.columnNumber-startColumn:position.columnNumber;return new WI.SourceCodePosition(position.lineNumber-startLine,columnNumber);}
function fromInlineScriptPosition(position){let columnNumber=position.lineNumber?position.columnNumber:position.columnNumber+startColumn;return new WI.SourceCodePosition(position.lineNumber+startLine,columnNumber);}
let highlightSourceCodeRange=(startPosition,endPosition)=>{startPosition=this.originalPositionToCurrentPosition(fromInlineScriptPosition(startPosition));endPosition=this.originalPositionToCurrentPosition(fromInlineScriptPosition(endPosition));callback({startPosition,endPosition});};script.requestScriptSyntaxTree((syntaxTree)=>{if(!syntaxTree){callback(null);return;}
position=toInlineScriptPosition(position);let nodes=syntaxTree.containersOfPosition(position);if(!nodes.length){callback(null);return;}
for(let node of nodes){if(node.startPosition.equals(position)&&node.type!==WI.ScriptSyntaxTree.NodeType.Program){highlightSourceCodeRange(node.startPosition,node.endPosition);return;}
if(node.type===WI.ScriptSyntaxTree.NodeType.ForInStatement||node.type===WI.ScriptSyntaxTree.NodeType.ForOfStatement){if(node.left.startPosition.equals(position)){highlightSourceCodeRange(node.left.startPosition,node.right.endPosition);return;}}
if(node.startPosition.isAfter(position))
break;}
for(let node of nodes){if(node.endPosition.equals(position)){if(node.type===WI.ScriptSyntaxTree.NodeType.BlockStatement){highlightSourceCodeRange(position.offsetColumn(-1),position);return;}}
if(node.startPosition.isAfter(position))
break;}
nodes.sort((a,b)=>{let aLength=a.range[1]-a.range[0];let bLength=b.range[1]-b.range[0];return aLength-bLength;});let characterAtPosition=this.getTextInRange(currentPosition,currentPosition.offsetColumn(1));let characterAtPositionIsDotOrBracket=characterAtPosition==="."||characterAtPosition==="[";for(let i=0;i<nodes.length;++i){let node=nodes[i];if(node.type===WI.ScriptSyntaxTree.NodeType.CallExpression||node.type===WI.ScriptSyntaxTree.NodeType.NewExpression||node.type===WI.ScriptSyntaxTree.NodeType.ThrowStatement){highlightSourceCodeRange(node.startPosition,node.endPosition);return;}






if(node.type===WI.ScriptSyntaxTree.NodeType.ThisExpression||(characterAtPositionIsDotOrBracket&&(node.type===WI.ScriptSyntaxTree.NodeType.Identifier||node.type===WI.ScriptSyntaxTree.NodeType.MemberExpression))){let memberExpressionNode=null;for(let j=i+1;j<nodes.length;++j){let nextNode=nodes[j];if(nextNode.type===WI.ScriptSyntaxTree.NodeType.MemberExpression){memberExpressionNode=nextNode;if(position.equals(memberExpressionNode.endPosition))
continue;}
break;}
if(memberExpressionNode){highlightSourceCodeRange(memberExpressionNode.startPosition,memberExpressionNode.endPosition);return;}
highlightSourceCodeRange(node.startPosition,node.endPosition);return;}}
callback(null);});}
_clearIssueWidgets()
{for(var widget of this._widgetMap.values())
widget.clear();this._widgetMap.clear();}
_reinsertAllIssues()
{this._issuesLineNumberMap.clear();this._clearIssueWidgets();let issues=WI.consoleManager.issuesForSourceCode(this._sourceCode);for(let issue of issues)
this._addIssue(issue);}
_reinsertAllThreadIndicators()
{for(let lineNumber of this._threadLineNumberMap.keys())
this.removeStyleClassFromLine(lineNumber,"thread-indicator");this._threadLineNumberMap.clear();for(let widget of this._threadWidgetMap.values())
widget.clear();this._threadWidgetMap.clear();this._threadTargetMap.clear();let debuggableTargets=WI.targets;if(debuggableTargets.length>1){for(let target of debuggableTargets)
this._addThreadIndicatorForTarget(target);}}
_debuggerDidPause(event)
{this._updateTokenTrackingControllerState();if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive())
this._typeTokenAnnotator.refresh();if(this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive())
this._basicBlockAnnotator.refresh();}
_debuggerDidResume(event)
{this._updateTokenTrackingControllerState();this._dismissPopover();if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive())
this._typeTokenAnnotator.refresh();if(this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive())
this._basicBlockAnnotator.refresh();}
_handleFormatterDidChange(event)
{if(this._ignoreAllBreakpointLocationUpdates)
return;
var oldBreakpointMap=this._breakpointMap;this._breakpointMap={};for(var lineNumber in oldBreakpointMap){for(var columnNumber in oldBreakpointMap[lineNumber]){var breakpoint=oldBreakpointMap[lineNumber][columnNumber];var newLineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,newLineInfo);this.setBreakpointInfoForLineAndColumn(lineNumber,columnNumber,null);this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}}
this._reinsertAllIssues();this._reinsertAllThreadIndicators();}
_sourceCodeSourceMapAdded(event)
{WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._updateTokenTrackingControllerState();}
_updateTokenTrackingControllerState()
{var mode=WI.CodeMirrorTokenTrackingController.Mode.None;if(WI.debuggerManager.paused)
mode=WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression;else if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive())
mode=WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation;else if(this._hasColorMarkers())
mode=WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens;else if((this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length!==0)&&WI.modifierKeys.metaKey&&!WI.modifierKeys.altKey&&!WI.modifierKeys.shiftKey)
mode=WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens;this.tokenTrackingController.enabled=mode!==WI.CodeMirrorTokenTrackingController.Mode.None;if(mode===this.tokenTrackingController.mode)
return;switch(mode){case WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens:this.tokenTrackingController.mouseOverDelayDuration=0;this.tokenTrackingController.mouseOutReleaseDelayDuration=0;break;case WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens:this.tokenTrackingController.mouseOverDelayDuration=0;this.tokenTrackingController.mouseOutReleaseDelayDuration=0;this.tokenTrackingController.classNameForHighlightedRange=WI.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName;this._dismissPopover();break;case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression:case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation:this.tokenTrackingController.mouseOverDelayDuration=WI.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken;this.tokenTrackingController.mouseOutReleaseDelayDuration=WI.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease;this.tokenTrackingController.classNameForHighlightedRange=WI.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName;break;}
this.tokenTrackingController.mode=mode;}
_hasColorMarkers()
{for(var marker of this.markers){if(marker.type===WI.TextMarker.Type.Color)
return true;}
return false;} 
tokenTrackingControllerCanReleaseHighlightedRange(tokenTrackingController,element)
{if(!this._popover)
return true;if(!window.getSelection().isCollapsed&&this._popover.element.contains(window.getSelection().anchorNode))
return false;return true;}
tokenTrackingControllerHighlightedRangeReleased(tokenTrackingController,forceHide=false)
{if(forceHide||!this._mouseIsOverPopover)
this._dismissPopover();}
tokenTrackingControllerHighlightedRangeWasClicked(tokenTrackingController)
{if(this.tokenTrackingController.mode!==WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens)
return;if(/\blink\b/.test(this.tokenTrackingController.candidate.hoveredToken.type))
return;const options={ignoreNetworkTab:true,ignoreSearchTab:true,};var sourceCodeLocation=this._sourceCodeLocationForEditorPosition(this.tokenTrackingController.candidate.hoveredTokenRange.start);if(this.sourceCode instanceof WI.SourceMapResource)
WI.showOriginalOrFormattedSourceCodeLocation(sourceCodeLocation,options);else
WI.showSourceCodeLocation(sourceCodeLocation,options);}
tokenTrackingControllerNewHighlightCandidate(tokenTrackingController,candidate)
{if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens){this.tokenTrackingController.highlightRange(candidate.hoveredTokenRange);return;}
if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression){this._tokenTrackingControllerHighlightedJavaScriptExpression(candidate);return;}
if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation){this._tokenTrackingControllerHighlightedJavaScriptTypeInformation(candidate);return;}
if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens){var markers=this.markersAtPosition(candidate.hoveredTokenRange.start);if(markers.length>0)
this._tokenTrackingControllerHighlightedMarkedExpression(candidate,markers);else
this._dismissEditingController();}}
tokenTrackingControllerMouseOutOfHoveredMarker(tokenTrackingController,hoveredMarker)
{this._dismissEditingController();}
_tokenTrackingControllerHighlightedJavaScriptExpression(candidate)
{let target=WI.debuggerManager.activeCallFrame?WI.debuggerManager.activeCallFrame.target:this.target;let expression=appendWebInspectorSourceURL(candidate.expression);function populate(error,result,wasThrown)
{if(error||wasThrown)
return;if(candidate!==this.tokenTrackingController.candidate)
return;let data=WI.RemoteObject.fromPayload(result,target);switch(data.type){case"function":this._showPopoverForFunction(data);break;case"object":if(data.subtype==="null"||data.subtype==="regexp")
this._showPopoverWithFormattedValue(data);else
this._showPopoverForObject(data);break;case"string":case"number":case"boolean":case"symbol":case"bigint":case"undefined":this._showPopoverWithFormattedValue(data);break;}}
if(WI.debuggerManager.activeCallFrame){target.DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId:WI.debuggerManager.activeCallFrame.id,expression,objectGroup:"popover",doNotPauseOnExceptionsAndMuteConsole:true},populate.bind(this));return;}
target.RuntimeAgent.evaluate.invoke({expression,objectGroup:"popover",doNotPauseOnExceptionsAndMuteConsole:true},populate.bind(this));}
_tokenTrackingControllerHighlightedJavaScriptTypeInformation(candidate)
{var sourceCode=this._sourceCode;var sourceID=sourceCode instanceof WI.Script?sourceCode.id:sourceCode.scripts[0].id;var range=candidate.hoveredTokenRange;var offset=this.currentPositionToOriginalOffset(range.start);var allRequests=[{typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:offset}];function handler(error,allTypes){if(error)
return;if(candidate!==this.tokenTrackingController.candidate)
return;if(!allTypes.length)
return;var typeDescription=WI.TypeDescription.fromPayload(allTypes[0]);if(typeDescription.valid){var popoverTitle=WI.TypeTokenView.titleForPopover(WI.TypeTokenView.TitleType.Variable,candidate.expression);this.showPopoverForTypes(typeDescription,null,popoverTitle);}}
this.target.RuntimeAgent.getRuntimeTypesForVariablesAtOffsets(allRequests,handler.bind(this));}
_showPopover(content,bounds)
{var shouldHighlightRange=false;var candidate=this.tokenTrackingController.candidate;if(!bounds){if(!candidate)
return;var rects=this.rectsForRange(candidate.hoveredTokenRange);bounds=WI.Rect.unionOfRects(rects);if(this._popover&&this._popover.visible){let intersection=bounds.intersectionWithRect(this._popover.frame);if(intersection.size.width&&intersection.size.height)
return;}
shouldHighlightRange=true;}
content.classList.add(WI.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName);if(!this._popover){this._popover=new WI.Popover(this);this._popover.element.addEventListener("mouseover",this._popoverMouseover.bind(this));this._popover.element.addEventListener("mouseout",this._popoverMouseout.bind(this));}
this._popover.presentNewContentWithFrame(content,bounds.pad(5),[WI.RectEdge.MIN_Y,WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X]);if(shouldHighlightRange)
this.tokenTrackingController.highlightRange(candidate.expressionRange);}
_showPopoverForFunction(data)
{let candidate=this.tokenTrackingController.candidate;function didGetDetails(error,response)
{if(error){console.error(error);this._dismissPopover();return;}

if(candidate!==this.tokenTrackingController.candidate)
return;let content=document.createElement("div");content.classList.add("function");let title=document.createElement("div");title.classList.add("title");title.textContent=response.name||response.displayName||WI.UIString("(anonymous function)");content.appendChild(title);let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,this.target);let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber);let functionSourceCodeLink=WI.createSourceCodeLocationLink(sourceCodeLocation);title.appendChild(functionSourceCodeLink);let wrapper=document.createElement("div");wrapper.classList.add("body");content.appendChild(wrapper);let codeMirror=WI.CodeMirrorEditor.create(wrapper,{mode:"text/javascript",readOnly:"nocursor",});const isModule=false;const indentString=WI.indentString();const includeSourceMapData=false;let workerProxy=WI.FormatterWorkerProxy.singleton();workerProxy.formatJavaScript(data.description,isModule,indentString,includeSourceMapData,({formattedText})=>{if(candidate!==this.tokenTrackingController.candidate)
return;this._showPopover(content);codeMirror.setValue(formattedText||data.description);this._popover.update();setTimeout(()=>{codeMirror.refresh();});});}
data.target.DebuggerAgent.getFunctionDetails(data.objectId,didGetDetails.bind(this));}
_showPopoverForObject(data)
{var content=document.createElement("div");content.className="object expandable";var titleElement=document.createElement("div");titleElement.className="title";titleElement.textContent=data.description;content.appendChild(titleElement);if(data.subtype==="node"){data.pushNodeToFrontend(function(nodeId){if(!nodeId)
return;var domNode=WI.domManager.nodeForId(nodeId);if(!domNode.ownerDocument)
return;WI.bindInteractionsForNodeToElement(domNode,titleElement,{ignoreClick:true,});var goToButton=titleElement.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",function(){WI.domManager.inspectElement(nodeId,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});});}
var objectTree=new WI.ObjectTreeView(data);objectTree.showOnlyProperties();objectTree.expand();var bodyElement=content.appendChild(document.createElement("div"));bodyElement.className="body";bodyElement.appendChild(objectTree.element);var candidate=this.tokenTrackingController.candidate;objectTree.singleFireEventListener(WI.ObjectTreeView.Event.Updated,function(event){if(candidate===this.tokenTrackingController.candidate)
this._showPopover(content);},this);}
_showPopoverWithFormattedValue(remoteObject)
{let wrapper=document.createElement("div");wrapper.className="formatted";wrapper.appendChild(WI.FormattedValue.createElementForRemoteObject(remoteObject));this._showPopover(wrapper);}
willDismissPopover(popover)
{this.tokenTrackingController.removeHighlightedRange();this.target.RuntimeAgent.releaseObjectGroup("popover");}
_dismissPopover()
{if(!this._popover)
return;this._popover.dismiss();}
_popoverMouseover(event)
{this._mouseIsOverPopover=true;}
_popoverMouseout(event)
{this._mouseIsOverPopover=this._popover.element.contains(event.relatedTarget);}
_hasStyleSheetContents()
{let mimeType=this.mimeType;return mimeType==="text/css"||mimeType==="text/x-less"||mimeType==="text/x-sass"||mimeType==="text/x-scss";}
_updateEditableMarkers(range)
{if(this._hasStyleSheetContents()){this.createColorMarkers(range);this.createGradientMarkers(range);this.createCubicBezierMarkers(range);this.createSpringMarkers(range);}
this._updateTokenTrackingControllerState();}
_tokenTrackingControllerHighlightedMarkedExpression(candidate,markers)
{var editableMarker;for(var marker of markers){if(!marker.range||!Object.values(WI.TextMarker.Type).includes(marker.type))
continue;if(!editableMarker||(marker.range.startLine<editableMarker.range.startLine||(marker.range.startLine===editableMarker.range.startLine&&marker.range.startColumn<editableMarker.range.startColumn)))
editableMarker=marker;}
if(!editableMarker){this.tokenTrackingController.hoveredMarker=null;return;}
if(this.tokenTrackingController.hoveredMarker===editableMarker)
return;this._dismissEditingController();this.tokenTrackingController.hoveredMarker=editableMarker;this._editingController=this.editingControllerForMarker(editableMarker);if(marker.type===WI.TextMarker.Type.Color){var color=this._editingController.value;if(!color||!color.valid){editableMarker.clear();this._editingController=null;return;}}
this._editingController.delegate=this;this._editingController.presentHoverMenu();}
_dismissEditingController(discrete)
{if(this._editingController)
this._editingController.dismissHoverMenu(discrete);this.tokenTrackingController.hoveredMarker=null;this._editingController=null;} 
editingControllerDidStartEditing(editingController)
{

this.tokenTrackingController.enabled=false;editingController.marker.clear();this._ignoreContentDidChange++;}
editingControllerDidFinishEditing(editingController)
{this._updateEditableMarkers(editingController.range);this._ignoreContentDidChange--;this._editingController=null;}
_setTypeTokenAnnotatorEnabledState(shouldActivate)
{if(!this._typeTokenAnnotator)
return;if(shouldActivate){this._typeTokenAnnotator.reset();if(!this._typeTokenScrollHandler)
this._enableScrollEventsForTypeTokenAnnotator();}else{this._typeTokenAnnotator.clear();if(this._typeTokenScrollHandler)
this._disableScrollEventsForTypeTokenAnnotator();}
WI.settings.showJavaScriptTypeInformation.value=shouldActivate;this._updateTokenTrackingControllerState();}
set _basicBlockAnnotatorEnabled(shouldActivate)
{if(!this._basicBlockAnnotator)
return;if(shouldActivate){this._basicBlockAnnotator.reset();if(!this._controlFlowScrollHandler)
this._enableScrollEventsForControlFlowAnnotator();}else{this._basicBlockAnnotator.clear();if(this._controlFlowScrollHandler)
this._disableScrollEventsForControlFlowAnnotator();}
WI.settings.enableControlFlowProfiler.value=shouldActivate;}
_getAssociatedScript(position)
{let script=null;if(this._sourceCode instanceof WI.Script)
script=this._sourceCode;else if(this._sourceCode instanceof WI.Resource&&this._sourceCode.scripts.length){if(this._sourceCode.type===WI.Resource.Type.Script)
script=this._sourceCode.scripts[0];else if(this._sourceCode.type===WI.Resource.Type.Document&&position){for(let inlineScript of this._sourceCode.scripts){if(inlineScript.range.contains(position.lineNumber,position.columnNumber)){if(isNaN(inlineScript.range.startOffset))
inlineScript.range.resolveOffsets(this._sourceCode.content);script=inlineScript;break;}}}}
return script;}
_createTypeTokenAnnotator()
{var script=this._getAssociatedScript();if(!script)
return;this._typeTokenAnnotator=new WI.TypeTokenAnnotator(this,script);}
_createBasicBlockAnnotator()
{var script=this._getAssociatedScript();if(!script)
return;this._basicBlockAnnotator=new WI.BasicBlockAnnotator(this,script);}
_enableScrollEventsForTypeTokenAnnotator()
{this._typeTokenScrollHandler=this._createTypeTokenScrollEventHandler();this.addScrollHandler(this._typeTokenScrollHandler);}
_enableScrollEventsForControlFlowAnnotator()
{this._controlFlowScrollHandler=this._createControlFlowScrollEventHandler();this.addScrollHandler(this._controlFlowScrollHandler);}
_disableScrollEventsForTypeTokenAnnotator()
{this.removeScrollHandler(this._typeTokenScrollHandler);this._typeTokenScrollHandler=null;}
_disableScrollEventsForControlFlowAnnotator()
{this.removeScrollHandler(this._controlFlowScrollHandler);this._controlFlowScrollHandler=null;}
_createTypeTokenScrollEventHandler()
{let timeoutIdentifier=null;let scrollHandler=()=>{if(timeoutIdentifier)
clearTimeout(timeoutIdentifier);else{if(this._typeTokenAnnotator)
this._typeTokenAnnotator.pause();}
timeoutIdentifier=setTimeout(()=>{timeoutIdentifier=null;if(this._typeTokenAnnotator)
this._typeTokenAnnotator.resume();},WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling);};return scrollHandler;}
_createControlFlowScrollEventHandler()
{let timeoutIdentifier=null;let scrollHandler=()=>{if(timeoutIdentifier)
clearTimeout(timeoutIdentifier);else if(this._basicBlockAnnotator)
this._basicBlockAnnotator.pause();timeoutIdentifier=setTimeout(()=>{timeoutIdentifier=null;if(this._basicBlockAnnotator)
this._basicBlockAnnotator.resume();},WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling);};return scrollHandler;}
_logCleared(event)
{for(let lineNumber of this._issuesLineNumberMap.keys()){this.removeStyleClassFromLine(lineNumber,WI.SourceCodeTextEditor.LineErrorStyleClassName);this.removeStyleClassFromLine(lineNumber,WI.SourceCodeTextEditor.LineWarningStyleClassName);}
this._issuesLineNumberMap.clear();this._clearIssueWidgets();}};WI.SourceCodeTextEditor.LineErrorStyleClassName="error";WI.SourceCodeTextEditor.LineWarningStyleClassName="warning";WI.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName="debugger-popover-content";WI.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName="hovered-expression-highlight";WI.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken=500;WI.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease=1000;WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling=100;WI.SourceCodeTextEditor.WidgetContainsMultipleIssuesSymbol=Symbol("source-code-widget-contains-multiple-issues");WI.SourceCodeTextEditor.WidgetContainsMultipleThreadsSymbol=Symbol("source-code-widget-contains-multiple-threads");WI.SourceCodeTextEditor.Event={ContentWillPopulate:"source-code-text-editor-content-will-populate",ContentDidPopulate:"source-code-text-editor-content-did-populate"};WI.SourceCodeTimelineTimelineDataGridNode=class SourceCodeTimelineTimelineDataGridNode extends WI.TimelineDataGridNode
{constructor(sourceCodeTimeline,options={})
{const records=[];super(records,{includesGraph:true,...options});this._sourceCodeTimeline=sourceCodeTimeline;this._sourceCodeTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._timelineRecordAdded,this);} 
get records()
{return this._sourceCodeTimeline.records;}
get sourceCodeTimeline()
{return this._sourceCodeTimeline;}
get data()
{if(this._cachedData)
return this._cachedData;this._cachedData=super.data;this._cachedData.graph=this._sourceCodeTimeline.startTime;return this._cachedData;}
createCellContent(columnIdentifier,cell)
{if(columnIdentifier==="name"&&this.records.length){cell.classList.add(...this.iconClassNames());return this._createNameCellContent(cell);}
return super.createCellContent(columnIdentifier,cell);} 
filterableDataForColumn(columnIdentifier)
{if(columnIdentifier==="name")
return this.displayName();return super.filterableDataForColumn(columnIdentifier);} 
_createNameCellContent(cellElement)
{if(!this.records.length)
return null;let fragment=document.createDocumentFragment();let mainTitle=this.displayName();fragment.append(mainTitle);let sourceCodeLocation=this._sourceCodeTimeline.sourceCodeLocation;if(sourceCodeLocation){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");sourceCodeLocation.populateLiveDisplayLocationString(subtitleElement,"textContent",null,WI.SourceCodeLocation.NameStyle.None,WI.UIString("line "));const options={useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};let goToArrowButtonLink=WI.createSourceCodeLocationLink(sourceCodeLocation,options);fragment.append(goToArrowButtonLink,subtitleElement);sourceCodeLocation.populateLiveDisplayLocationTooltip(cellElement,mainTitle+"\n");}else
cellElement.title=mainTitle;return fragment;}
_timelineRecordAdded(event)
{if(this.isRecordVisible(event.data.record))
this.needsGraphRefresh();}};WI.SourcesNavigationSidebarPanel=class SourcesNavigationSidebarPanel extends WI.NavigationSidebarPanel
{constructor()
{const shouldAutoPruneStaleTopLevelResourceTreeElements=true;super("sources",WI.UIString("Sources"),shouldAutoPruneStaleTopLevelResourceTreeElements);this._workerTargetTreeElementMap=new Map;this._mainFrameTreeElement=null;this._extensionScriptsFolderTreeElement=null;this._extensionStyleSheetsFolderTreeElement=null;this._extraScriptsFolderTreeElement=null;this._extraStyleSheetsFolderTreeElement=null;this._anonymousScriptsFolderTreeElement=null;this._anonymousStyleSheetsFolderTreeElement=null;this._originTreeElementMap=new Map;this._boundCompareTreeElements=this._compareTreeElements.bind(this);this._debuggerNavigationBar=new WI.NavigationBar;this.addSubview(this._debuggerNavigationBar);let createActivateNavigationItem=({identifier,defaultToolTip,activatedToolTip,image})=>{let navigationItem=new WI.ActivateButtonNavigationItem(identifier,defaultToolTip,activatedToolTip,image,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};let createToggleNavigationItem=({identifier,defaultToolTip,alternateToolTip,defaultImage,alternateImage})=>{let navigationItem=new WI.ToggleButtonNavigationItem(identifier,defaultToolTip,alternateToolTip,defaultImage,alternateImage,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};let createButtonNavigationitem=({identifier,toolTipOrLabel,image})=>{let navigationItem=new WI.ButtonNavigationItem(identifier,toolTipOrLabel,image,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};this._debuggerBreakpointsButtonItem=createActivateNavigationItem({identifier:"debugger-breakpoints",defaultToolTip:WI.UIString("Enable all breakpoints (%s)").format(WI.toggleBreakpointsKeyboardShortcut.displayName),activatedToolTip:WI.UIString("Disable all breakpoints (%s)").format(WI.toggleBreakpointsKeyboardShortcut.displayName),image:"Images/Breakpoints.svg",});this._debuggerBreakpointsButtonItem.activated=WI.debuggerManager.breakpointsEnabled;this._debuggerBreakpointsButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerToggleBreakpoints,this);this._debuggerPauseResumeButtonItem=createToggleNavigationItem({identifier:"debugger-pause-resume",defaultToolTip:WI.UIString("Pause script execution (%s or %s)").format(WI.pauseOrResumeKeyboardShortcut.displayName,WI.pauseOrResumeAlternateKeyboardShortcut.displayName),alternateToolTip:WI.UIString("Continue script execution (%s or %s)").format(WI.pauseOrResumeKeyboardShortcut.displayName,WI.pauseOrResumeAlternateKeyboardShortcut.displayName),defaultImage:"Images/Pause.svg",alternateImage:"Images/Resume.svg",});this._debuggerPauseResumeButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerPauseResumeToggle,this);this._debuggerStepOverButtonItem=createButtonNavigationitem({identifier:"debugger-step-over",toolTipOrLabel:WI.UIString("Step over (%s or %s)").format(WI.stepOverKeyboardShortcut.displayName,WI.stepOverAlternateKeyboardShortcut.displayName),image:"Images/StepOver.svg",});this._debuggerStepOverButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepOver,this);this._debuggerStepOverButtonItem.enabled=false;this._debuggerStepIntoButtonItem=createButtonNavigationitem({identifier:"debugger-step-into",toolTipOrLabel:WI.UIString("Step into (%s or %s)").format(WI.stepIntoKeyboardShortcut.displayName,WI.stepIntoAlternateKeyboardShortcut.displayName),image:"Images/StepInto.svg",});this._debuggerStepIntoButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepInto,this);this._debuggerStepIntoButtonItem.enabled=false;this._debuggerStepOutButtonItem=createButtonNavigationitem({identifier:"debugger-step-out",toolTipOrLabel:WI.UIString("Step out (%s or %s)").format(WI.stepOutKeyboardShortcut.displayName,WI.stepOutAlternateKeyboardShortcut.displayName),image:"Images/StepOut.svg",});this._debuggerStepOutButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepOut,this);this._debuggerStepOutButtonItem.enabled=false;if(InspectorBackend.hasCommand("Debugger.stepNext")){this._debuggerStepNextButtonItem=createButtonNavigationitem({identifier:"debugger-step-next",toolTipOrLabel:WI.UIString("Step (%s or %s)").format(WI.stepNextKeyboardShortcut.displayName,WI.stepNextAlternateKeyboardShortcut.displayName),image:"Images/StepNext.svg",});this._debuggerStepNextButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepNext,this);this._debuggerStepNextButtonItem.enabled=false;}
this._timelineRecordingWarningElement=null;this._auditTestWarningElement=null;this._breakpointsDisabledWarningElement=null;this._pauseReasonTreeOutline=null;this._pauseReasonLinkContainerElement=document.createElement("span");this._pauseReasonTextRow=new WI.DetailsSectionTextRow;this._pauseReasonGroup=new WI.DetailsSectionGroup([this._pauseReasonTextRow]);this._pauseReasonSection=new WI.DetailsSection("paused-reason",WI.UIString("Pause Reason"),[this._pauseReasonGroup],this._pauseReasonLinkContainerElement);this._pauseReasonContainer=this.contentView.element.appendChild(document.createElement("div"));this._pauseReasonContainer.classList.add("pause-reason-container");this._pauseReasonContainer.hidden=true;this._pauseReasonContainer.appendChild(this._pauseReasonSection.element);this._callStackTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._callStackTreeOutline.allowsMultipleSelection=true;this._callStackTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._callStackTreeOutline.populateContextMenu=(contextMenu,event,treeElement)=>{if(this._callStackTreeOutline.selectedTreeElements.length){contextMenu.appendItem(WI.UIString("Copy"),()=>{this.handleCopyEvent(event);});contextMenu.appendSeparator();}
WI.TreeOutline.prototype.populateContextMenu(contextMenu,event,treeElement);};let callStackRow=new WI.DetailsSectionRow;callStackRow.element.appendChild(this._callStackTreeOutline.element);let callStackGroup=new WI.DetailsSectionGroup([callStackRow]);this._callStackSection=new WI.DetailsSection("call-stack",WI.UIString("Call Stack"),[callStackGroup]);this._callStackContainer=this.contentView.element.appendChild(document.createElement("div"));this._callStackContainer.classList.add("call-stack-container");this._callStackContainer.hidden=true;this._callStackContainer.appendChild(this._callStackSection.element);this._mainTargetTreeElement=null;this._activeCallFrameTreeElement=null;this._breakpointsTreeOutline=this.createContentTreeOutline({ignoreCookieRestoration:true});this._breakpointsTreeOutline.addEventListener(WI.TreeOutline.Event.ElementRemoved,this._handleBreakpointTreeOutlineElementRemoved,this);this._breakpointsTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._breakpointsTreeOutline.ondelete=(selectedTreeElement)=>{if(selectedTreeElement.representedObject instanceof WI.Breakpoint&&!selectedTreeElement.representedObject.removable){let treeElementToSelect=selectedTreeElement.nextSelectableSibling;if(treeElementToSelect){const omitFocus=true;const selectedByUser=true;treeElementToSelect.select(omitFocus,selectedByUser);}}else if(selectedTreeElement instanceof WI.ResourceTreeElement||selectedTreeElement instanceof WI.ScriptTreeElement){let breakpoints=this._breakpointsBeneathTreeElement(selectedTreeElement);this._removeAllBreakpoints(breakpoints);}else if(selectedTreeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject){let eventBreakpointsOnWindow=WI.domManager.eventListenerBreakpoints.filter((eventBreakpoint)=>eventBreakpoint.eventListener.onWindow);for(let eventBreakpoint of eventBreakpointsOnWindow)
WI.domManager.removeBreakpointForEventListener(eventBreakpoint.eventListener);}
return true;};this._breakpointsTreeOutline.populateContextMenu=(contextMenu,event,treeElement)=>{
if(treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement){let breakpoints=this._breakpointsBeneathTreeElement(treeElement);let shouldDisable=breakpoints.some((breakpoint)=>!breakpoint.disabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Breakpoints"):WI.UIString("Enable Breakpoints"),()=>{this._toggleAllBreakpoints(breakpoints,shouldDisable);});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{this._removeAllBreakpoints(breakpoints);});}
WI.TreeOutline.prototype.populateContextMenu(contextMenu,event,treeElement);};let breakpointsRow=new WI.DetailsSectionRow;breakpointsRow.element.appendChild(this._breakpointsTreeOutline.element);let breakpointNavigationBarWrapper=document.createElement("div");let breakpointNavigationBar=new WI.NavigationBar;breakpointNavigationBarWrapper.appendChild(breakpointNavigationBar.element);this._createBreakpointButton=new WI.ButtonNavigationItem("create-breakpoint",WI.UIString("Create Breakpoint"),"Images/Plus13.svg",13,13);WI.addMouseDownContextMenuHandlers(this._createBreakpointButton.element,this._populateCreateBreakpointContextMenu.bind(this));breakpointNavigationBar.addNavigationItem(this._createBreakpointButton);let breakpointsGroup=new WI.DetailsSectionGroup([breakpointsRow]);this._breakpointsSection=new WI.DetailsSection("breakpoints",WI.UIString("Breakpoints"),[breakpointsGroup],breakpointNavigationBarWrapper);let breakpointsContainer=this.contentView.element.appendChild(document.createElement("div"));breakpointsContainer.classList.add("breakpoints-container");breakpointsContainer.appendChild(this._breakpointsSection.element);this._localOverridesTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._localOverridesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._localOverridesRow=new WI.DetailsSectionRow(WI.UIString("No Overrides"));let localOverrideNavigationBarWrapper=document.createElement("div");let localOverrideNavigationBar=new WI.NavigationBar;localOverrideNavigationBarWrapper.appendChild(localOverrideNavigationBar.element);this._createLocalOverrideButton=new WI.ButtonNavigationItem("create-local-override",WI.UIString("Create Local Override"),"Images/Plus13.svg",13,13);WI.addMouseDownContextMenuHandlers(this._createLocalOverrideButton.element,this._populateCreateLocalOverrideContextMenu.bind(this));localOverrideNavigationBar.addNavigationItem(this._createLocalOverrideButton);let localOverridesGroup=new WI.DetailsSectionGroup([this._localOverridesRow]);this._localOverridesSection=new WI.DetailsSection("local-overrides",WI.UIString("Local Overrides"),[localOverridesGroup],localOverrideNavigationBarWrapper);this._localOverridesContainer=this.contentView.element.appendChild(document.createElement("div"));this._localOverridesContainer.classList.add("local-overrides-container");this._localOverridesContainer.hidden=true;this._localOverridesContainer.appendChild(this._localOverridesSection.element);this._resourcesNavigationBar=new WI.NavigationBar;this.contentView.addSubview(this._resourcesNavigationBar);this._resourceGroupingModeScopeBarItems={};let createResourceGroupingModeScopeBarItem=(mode,label)=>{this._resourceGroupingModeScopeBarItems[mode]=new WI.ScopeBarItem("sources-resource-grouping-mode-"+mode,label,{exclusive:true});this._resourceGroupingModeScopeBarItems[mode][SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol]=mode;};createResourceGroupingModeScopeBarItem(WI.Resource.GroupingMode.Type,WI.UIString("By Type"));createResourceGroupingModeScopeBarItem(WI.Resource.GroupingMode.Path,WI.UIString("By Path"));this._resourceGroupingModeScopeBar=new WI.ScopeBar("sources-resource-grouping-mode-scope-bar",Object.values(this._resourceGroupingModeScopeBarItems),this._resourceGroupingModeScopeBarItems[WI.settings.resourceGroupingMode.value]);this._resourceGroupingModeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleResourceGroupingModeScopeBarSelectionChanged,this);this._resourcesNavigationBar.addNavigationItem(this._resourceGroupingModeScopeBar);let resourcesContainer=this.contentView.element.appendChild(document.createElement("div"));resourcesContainer.classList.add("resources-container");this._resourcesTreeOutline=this.contentTreeOutline;this._resourcesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._resourcesTreeOutline.includeSourceMapResourceChildren=true;resourcesContainer.appendChild(this._resourcesTreeOutline.element);if(WI.NetworkManager.supportsOverridingResponses()||WI.NetworkManager.supportsBootstrapScript()||WI.CSSManager.supportsInspectorStyleSheet()){let createResourceNavigationBar=new WI.NavigationBar;let createResourceButtonNavigationItem=new WI.ButtonNavigationItem("create-resource",WI.UIString("Create Resource"),"Images/Plus15.svg",15,15);WI.addMouseDownContextMenuHandlers(createResourceButtonNavigationItem.element,this._populateCreateResourceContextMenu.bind(this));createResourceNavigationBar.addNavigationItem(createResourceButtonNavigationItem);this.filterBar.element.insertBefore(createResourceNavigationBar.element,this.filterBar.element.firstChild);}
const activatedByDefault=false;this.filterBar.addFilterBarButton("sources-only-show-resources-with-issues",this._filterByResourcesWithIssues.bind(this),activatedByDefault,WI.UIString("Only show resources with issues"),WI.UIString("Show all resources"),"Images/Errors.svg",15,15);const resourceTypeScopeItemPrefix="sources-resource-type-";let resourceTypeScopeBarItems=[];resourceTypeScopeBarItems.push(new WI.ScopeBarItem(resourceTypeScopeItemPrefix+"all",WI.UIString("All")));for(let value of Object.values(WI.Resource.Type)){let scopeBarItem=new WI.ScopeBarItem(resourceTypeScopeItemPrefix+value,WI.Resource.displayNameForType(value,true));scopeBarItem[SourcesNavigationSidebarPanel.ResourceTypeSymbol]=value;resourceTypeScopeBarItems.push(scopeBarItem);}
const shouldGroupNonExclusiveItems=true;this._resourceTypeScopeBar=new WI.ScopeBar("sources-resource-type-scope-bar",resourceTypeScopeBarItems,resourceTypeScopeBarItems[0],shouldGroupNonExclusiveItems);this._resourceTypeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleResourceTypeScopeBarSelectionChanged,this);this.filterBar.addFilterNavigationItem(this._resourceTypeScopeBar);WI.settings.resourceGroupingMode.addEventListener(WI.Setting.Event.Changed,this._handleResourceGroupingModeChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Target.addEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.FrameWasAdded,this._handleFrameWasAdded,this);if(WI.NetworkManager.supportsBootstrapScript()){WI.networkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptCreated,this._handleBootstrapScriptCreated,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptDestroyed,this._handleBootstrapScriptDestroyed,this);}
if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAdded,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideRemoved,this);}
WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.EventBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.URLBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.URLBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._handleDebuggerBreakpointsEnabledDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptAdded,this._handleDebuggerScriptAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._handleDebuggerScriptRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptsCleared,this._handleDebuggerScriptsCleared,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._handleDebuggerCallFramesDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.WaitingToPause,this._handleDebuggerWaitingToPause,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.IssueMessage.addEventListener(WI.IssueMessage.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._handleConsoleIssueAdded,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._handleConsoleCleared,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleCSSStyleSheetAdded,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleCSSStyleSheetRemoved,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetAdded,this._handleTargetAdded,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this); WI.notifications.addEventListener(WI.Notification.ExtraDomainsActivated,this._handleExtraDomainsActivated,this);if(WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()){this._resourcesTreeOutline.disclosureButtons=false;WI.SourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,function(event){this._resourcesTreeOutline.disclosureButtons=true;},this);}
if(WI.debuggerManager.debuggerStatementsBreakpoint)
this._addBreakpoint(WI.debuggerManager.debuggerStatementsBreakpoint);if(WI.debuggerManager.allExceptionsBreakpoint)
this._addBreakpoint(WI.debuggerManager.allExceptionsBreakpoint);if(WI.debuggerManager.uncaughtExceptionsBreakpoint)
this._addBreakpoint(WI.debuggerManager.uncaughtExceptionsBreakpoint);if(WI.debuggerManager.assertionFailuresBreakpoint)
this._addBreakpoint(WI.debuggerManager.assertionFailuresBreakpoint);if(WI.debuggerManager.allMicrotasksBreakpoint)
this._addBreakpoint(WI.debuggerManager.allMicrotasksBreakpoint);for(let target of WI.targets)
this._addTarget(target);this._updateCallStackTreeOutline();this._handleResourceGroupingModeChanged();if(WI.NetworkManager.supportsBootstrapScript()){let bootstrapScript=WI.networkManager.bootstrapScript;if(bootstrapScript)
this._addLocalOverride(bootstrapScript);}
if(WI.NetworkManager.supportsOverridingResponses()){for(let localResourceOverride of WI.networkManager.localResourceOverrides)
this._addLocalOverride(localResourceOverride);}
if(WI.domDebuggerManager.supported){if(WI.domDebuggerManager.allAnimationFramesBreakpoint)
this._addBreakpoint(WI.domDebuggerManager.allAnimationFramesBreakpoint);if(WI.domDebuggerManager.allTimeoutsBreakpoint)
this._addBreakpoint(WI.domDebuggerManager.allTimeoutsBreakpoint);if(WI.domDebuggerManager.allIntervalsBreakpoint)
this._addBreakpoint(WI.domDebuggerManager.allIntervalsBreakpoint);if(WI.domDebuggerManager.allListenersBreakpoint)
this._addBreakpoint(WI.domDebuggerManager.allListenersBreakpoint);for(let eventBreakpoint of WI.domDebuggerManager.listenerBreakpoints)
this._addBreakpoint(eventBreakpoint);for(let eventListenerBreakpoint of WI.domManager.eventListenerBreakpoints)
this._addBreakpoint(eventListenerBreakpoint);for(let domBreakpoint of WI.domDebuggerManager.domBreakpoints)
this._addBreakpoint(domBreakpoint);if(WI.domDebuggerManager.allRequestsBreakpoint)
this._addBreakpoint(WI.domDebuggerManager.allRequestsBreakpoint);for(let urlBreakpoints of WI.domDebuggerManager.urlBreakpoints)
this._addBreakpoint(urlBreakpoints);}
if(WI.debuggerManager.paused)
this._handleDebuggerPaused();if(WI.debuggerManager.breakpointsDisabledTemporarily){this._handleTimelineCapturingStateChanged();if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active||WI.auditManager.runningState===WI.AuditManager.RunningState.Stopping)
this._handleAuditManagerTestScheduled();}
this._updateBreakpointsDisabledBanner();} 
static shouldPlaceResourcesAtTopLevel()
{return WI.sharedApp.debuggableType===WI.DebuggableType.ITML||WI.sharedApp.debuggableType===WI.DebuggableType.JavaScript||WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker;} 
get minimumWidth()
{return Math.max(this._debuggerNavigationBar.minimumWidth,this._resourcesNavigationBar.minimumWidth);}
closed()
{WI.settings.resourceGroupingMode.removeEventListener(WI.Setting.Event.Changed,this._handleResourceGroupingModeChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Target.removeEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.FrameWasAdded,this._handleFrameWasAdded,this);if(WI.NetworkManager.supportsBootstrapScript()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptCreated,this._handleBootstrapScriptCreated,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptDestroyed,this._handleBootstrapScriptDestroyed,this);}
if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAdded,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideRemoved,this);}
WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.EventBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.URLBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.URLBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._handleDebuggerBreakpointsEnabledDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptAdded,this._handleDebuggerScriptAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._handleDebuggerScriptRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptsCleared,this._handleDebuggerScriptsCleared,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._handleDebuggerCallFramesDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.WaitingToPause,this._handleDebuggerWaitingToPause,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.IssueMessage.removeEventListener(WI.IssueMessage.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._handleConsoleIssueAdded,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.Cleared,this._handleConsoleCleared,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleCSSStyleSheetAdded,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleCSSStyleSheetRemoved,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetAdded,this._handleTargetAdded,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this); WI.notifications.removeEventListener(WI.Notification.ExtraDomainsActivated,this._handleExtraDomainsActivated,this);super.closed();}
showDefaultContentView()
{if(WI.networkManager.mainFrame){this.contentBrowser.showContentViewForRepresentedObject(WI.networkManager.mainFrame);return;}
let firstTreeElement=this._resourcesTreeOutline.children[0];if(firstTreeElement)
this.showDefaultContentViewForTreeElement(firstTreeElement);}
treeElementForRepresentedObject(representedObject)
{if(representedObject instanceof WI.LocalResourceOverride)
return this._localOverridesTreeOutline.findTreeElement(representedObject);if(representedObject instanceof WI.LocalResource){let localResourceOverride=representedObject.localResourceOverride||WI.networkManager.localResourceOverridesForURL(representedObject.url)[0];return this._localOverridesTreeOutline.findTreeElement(localResourceOverride);}
if(representedObject instanceof WI.Script&&representedObject===WI.networkManager.bootstrapScript)
return this._localOverridesTreeOutline.findTreeElement(representedObject);if(!this._mainFrameTreeElement&&(representedObject instanceof WI.Resource||representedObject instanceof WI.Frame||representedObject instanceof WI.Collection)){return null;}
switch(WI.settings.resourceGroupingMode.value){case WI.Resource.GroupingMode.Path:if(representedObject instanceof WI.Frame)
representedObject=representedObject.mainResource;break;default:WI.reportInternalError("Unknown resource grouping mode",{"Resource Grouping Mode":WI.settings.resourceGroupingMode.value});case WI.Resource.GroupingMode.Type:if(representedObject instanceof WI.Resource&&representedObject.parentFrame&&representedObject.parentFrame.mainResource===representedObject)
representedObject=representedObject.parentFrame;break;}
function isAncestor(ancestor,resourceOrFrame){if(resourceOrFrame instanceof WI.SourceMapResource){if(resourceOrFrame.sourceMap.originalSourceCode===ancestor)
return true;resourceOrFrame=resourceOrFrame.sourceMap.originalSourceCode;}
let currentFrame=resourceOrFrame.parentFrame;while(currentFrame){if(currentFrame===ancestor)
return true;currentFrame=currentFrame.parentFrame;}
return false;}
function getParent(resourceOrFrame){if(resourceOrFrame instanceof WI.SourceMapResource)
return resourceOrFrame.sourceMap.originalSourceCode;return resourceOrFrame.parentFrame;}
function searchTreeOutline(treeOutline,forceSearch){if(!treeOutline||(!treeOutline.selectedTreeElement&&!forceSearch))
return null;return treeOutline.findTreeElement(representedObject,isAncestor,getParent);}
let treeElement=searchTreeOutline(this._pauseReasonTreeOutline)||searchTreeOutline(this._callStackTreeOutline)||searchTreeOutline(this._breakpointsTreeOutline)||searchTreeOutline(this._resourcesTreeOutline,true);if(treeElement)
return treeElement;if(representedObject instanceof WI.Script){if(representedObject.url){return null;}


if(!this._anonymousScriptsFolderTreeElement)
this._anonymousScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Anonymous Scripts"),new WI.ScriptCollection);if(!this._anonymousScriptsFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(this._anonymousScriptsFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(this._anonymousScriptsFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;}
this._anonymousScriptsFolderTreeElement.representedObject.add(representedObject);let scriptTreeElement=new WI.ScriptTreeElement(representedObject);this._anonymousScriptsFolderTreeElement.appendChild(scriptTreeElement);return scriptTreeElement;}
if(representedObject instanceof WI.CSSStyleSheet){if(representedObject.url){return null;}
if(!this._anonymousStyleSheetsFolderTreeElement)
this._anonymousStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Anonymous Style Sheets"),new WI.CSSStyleSheetCollection);if(!this._anonymousStyleSheetsFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(this._anonymousStyleSheetsFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(this._anonymousStyleSheetsFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;}
let cssStyleSheetTreeElement=new WI.CSSStyleSheetTreeElement(representedObject);this._anonymousStyleSheetsFolderTreeElement.appendChild(cssStyleSheetTreeElement);return cssStyleSheetTreeElement;}
return null;}
handleCopyEvent(event)
{let selectedTreeElements=new Set(this._callStackTreeOutline.selectedTreeElements);if(!selectedTreeElements.size)
return;let treeElement=this._callStackTreeOutline.children[0];const ignoreHidden=true;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(!treeElement.revealed(ignoreHidden))
treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);let indentString=WI.indentString();let threads=[];let asyncBoundary=null;while(treeElement){if(treeElement instanceof WI.ThreadTreeElement){threads.push({name:treeElement.mainTitle,frames:[],});asyncBoundary=null;}else if(treeElement instanceof WI.CallFrameTreeElement){if(treeElement.isAsyncBoundaryCallFrame){asyncBoundary=treeElement.mainTitle;}else if(selectedTreeElements.has(treeElement)){if(asyncBoundary){threads.lastValue.frames.push("--- "+asyncBoundary+" ---");asyncBoundary=null;}
let line=treeElement.mainTitle;let sourceCodeLocation=treeElement.callFrame.sourceCodeLocation;if(sourceCodeLocation)
line+=" ("+sourceCodeLocation.displayLocationString()+")";threads.lastValue.frames.push(line);}}
treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);}
let multipleFramesSelected=threads.filter(({frames})=>frames.length).length>1;let lines=[];for(let{name,frames}of threads){if(multipleFramesSelected)
lines.push(name);for(let frame of frames){let prefix="";if(multipleFramesSelected)
prefix=indentString;lines.push(prefix+frame);}}
if(!lines.length)
return;setTimeout(()=>{InspectorFrontendHost.copyText(lines.join("\n"));});event.stop();} 
createContentTreeOutline(options={})
{let treeOutline=super.createContentTreeOutline(options);treeOutline.addEventListener(WI.TreeOutline.Event.ElementRevealed,function(event){let treeElement=event.data.element;let detailsSections=[this._pauseReasonSection,this._callStackSection,this._breakpointsSection,this._localOverridesSection];let detailsSection=detailsSections.find((detailsSection)=>detailsSection.element.contains(treeElement.listItemElement));if(!detailsSection)
return;

let offset=detailsSection.headerElement.totalOffsetBottom-treeElement.listItemElement.totalOffsetTop;if(offset>0)
this.scrollElement.scrollBy(0,-offset);},this);return treeOutline;}
resetFilter()
{this._resourceTypeScopeBar.resetToDefault();super.resetFilter();}
hasCustomFilters()
{let selectedScopeBarItem=this._resourceTypeScopeBar.selectedItems[0];return selectedScopeBarItem&&selectedScopeBarItem!==this._resourceTypeScopeBar.defaultItem;}
matchTreeElementAgainstCustomFilters(treeElement,flags)
{if(treeElement.treeOutline!==this._resourcesTreeOutline)
return true;let selectedScopeBarItem=this._resourceTypeScopeBar.selectedItems[0];if(!selectedScopeBarItem||selectedScopeBarItem===this._resourceTypeScopeBar.defaultItem)
return true;if(treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.OriginTreeElement)
return false;if(treeElement instanceof WI.IssueTreeElement)
treeElement=treeElement.parent;function match()
{if(treeElement instanceof WI.FrameTreeElement)
return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.Document;if(treeElement instanceof WI.ScriptTreeElement)
return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.Script;if(treeElement instanceof WI.CSSStyleSheetTreeElement)
return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.StyleSheet;if(!(treeElement instanceof WI.ResourceTreeElement))
return false;return treeElement.resource.type===selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol];}
let matched=match();if(matched)
flags.expandTreeElement=true;return matched;} 
willDismissPopover(popover)
{if(popover instanceof WI.LocalResourceOverridePopover){this._willDismissLocalOverridePopover(popover);return;}
if(popover instanceof WI.EventBreakpointPopover){this._willDismissEventBreakpointPopover(popover);return;}
if(popover instanceof WI.URLBreakpointPopover){this._willDismissURLBreakpointPopover(popover);return;}} 
_willDismissLocalOverridePopover(popover)
{let serializedData=popover.serializedData;if(!serializedData){if(!this._localOverridesTreeOutline.children.length)
this._localOverridesContainer.hidden=true;InspectorFrontendHost.beep();return;}
if(WI.networkManager.localResourceOverrides.some((existingOverride)=>existingOverride.equals(serializedData))){InspectorFrontendHost.beep();return;}
let localResourceOverride=WI.LocalResourceOverride.create(serializedData.url,serializedData.type,serializedData);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride);}
_willDismissEventBreakpointPopover(popover)
{let breakpoint=popover.breakpoint;if(!breakpoint){InspectorFrontendHost.beep();return;}
if(!WI.domDebuggerManager.addEventBreakpoint(breakpoint))
InspectorFrontendHost.beep();}
_willDismissURLBreakpointPopover(popover)
{let breakpoint=popover.breakpoint;if(!breakpoint){InspectorFrontendHost.beep();return;}
if(!WI.domDebuggerManager.addURLBreakpoint(breakpoint))
InspectorFrontendHost.beep();}
_filterByResourcesWithIssues(treeElement)
{if(treeElement.treeOutline!==this._resourcesTreeOutline)
return true;if(treeElement instanceof WI.IssueTreeElement)
return true;if(treeElement.hasChildren){for(let child of treeElement.children){if(child instanceof WI.IssueTreeElement)
return true;}}
return false;}
_compareTreeElements(a,b)
{const rankFunctions=[(treeElement)=>treeElement instanceof WI.ScriptTreeElement&&treeElement.representedObject===WI.networkManager.bootstrapScript,(treeElement)=>treeElement instanceof WI.LocalResourceOverrideTreeElement,(treeElement)=>treeElement instanceof WI.CSSStyleSheetTreeElement&&treeElement.representedObject.isInspectorStyleSheet(),(treeElement)=>treeElement===this._mainFrameTreeElement,(treeElement)=>treeElement instanceof WI.FrameTreeElement,(treeElement)=>treeElement instanceof WI.OriginTreeElement,(treeElement)=>{return treeElement!==this._extensionScriptsFolderTreeElement&&treeElement!==this._extensionStyleSheetsFolderTreeElement&&treeElement!==this._extraScriptsFolderTreeElement&&treeElement!==this._extraStyleSheetsFolderTreeElement&&treeElement!==this._anonymousScriptsFolderTreeElement&&treeElement!==this._anonymousStyleSheetsFolderTreeElement;},(treeElement)=>treeElement===this._extensionScriptsFolderTreeElement,(treeElement)=>treeElement===this._extensionStyleSheetsFolderTreeElement,(treeElement)=>treeElement===this._extraScriptsFolderTreeElement,(treeElement)=>treeElement===this._extraStyleSheetsFolderTreeElement,(treeElement)=>treeElement===this._anonymousScriptsFolderTreeElement,(treeElement)=>treeElement===this._anonymousStyleSheetsFolderTreeElement,];let aRank=rankFunctions.findIndex((rankFunction)=>rankFunction(a));let bRank=rankFunctions.findIndex((rankFunction)=>rankFunction(b));if((aRank>=0&&bRank<0)||aRank<bRank)
return-1;if((bRank>=0&&aRank<0)||bRank<aRank)
return 1;return a.mainTitle.extendedLocaleCompare(b.mainTitle)||a.subtitle.extendedLocaleCompare(b.subtitle);}
_closeContentViewsFilter(contentView)
{if(contentView.representedObject instanceof WI.LocalResource&&contentView.representedObject.localResourceOverride)
return false;return true;}
_updateMainFrameTreeElement(mainFrame)
{if(this.didInitialLayout)
this.contentBrowser.contentViewContainer.closeAllContentViews(this._closeContentViewsFilter);let oldMainFrameTreeElement=this._mainFrameTreeElement;if(this._mainFrameTreeElement){this._resourcesTreeOutline.removeChild(this._mainFrameTreeElement);this._mainFrameTreeElement=null;}
if(!mainFrame)
return;switch(WI.settings.resourceGroupingMode.value){case WI.Resource.GroupingMode.Path:{for(let treeElement of this._originTreeElementMap.values()){if(treeElement!==oldMainFrameTreeElement)
this._resourcesTreeOutline.removeChild(treeElement);}
this._originTreeElementMap.clear();let origin=mainFrame.urlComponents.origin;this._mainFrameTreeElement=new WI.OriginTreeElement(origin,mainFrame,{hasChildren:true});this._originTreeElementMap.set(origin,this._mainFrameTreeElement);break;}
default:WI.reportInternalError("Unknown resource grouping mode",{"Resource Grouping Mode":WI.settings.resourceGroupingMode.value});case WI.Resource.GroupingMode.Type:this._mainFrameTreeElement=new WI.FrameTreeElement(mainFrame);break;}
this._resourcesTreeOutline.insertChild(this._mainFrameTreeElement,0);setTimeout(()=>{if(this._resourcesTreeOutline.selectedTreeElement)
return;let currentContentView=this.contentBrowser.currentContentView;let treeElement=currentContentView?this.treeElementForRepresentedObject(currentContentView.representedObject):null;if(!treeElement)
treeElement=this.treeElementForRepresentedObject(WI.networkManager.mainFrame);this.showDefaultContentViewForTreeElement(treeElement);});}
_addTarget(target)
{let treeElement=new WI.ThreadTreeElement(target);this._callStackTreeOutline.appendChild(treeElement);if(target===WI.mainTarget)
this._mainTargetTreeElement=treeElement;this._updateCallStackTreeOutline();}
_findCallStackTargetTreeElement(target)
{for(let child of this._callStackTreeOutline.children){if(child.target===target)
return child;}
return null;}
_updateCallStackTreeOutline()
{let singleThreadShowing=WI.targets.length<=1;this._callStackTreeOutline.element.classList.toggle("single-thread",singleThreadShowing);if(this._mainTargetTreeElement)
this._mainTargetTreeElement.selectable=!singleThreadShowing;}
_addResource(resource)
{if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){if(!this._mainFrameTreeElement||this._resourcesTreeOutline.findTreeElement(resource))
return;let parentTreeElement=null;if(resource instanceof WI.CSSStyleSheet){parentTreeElement=this._resourcesTreeOutline.findTreeElement(resource.parentFrame.mainResource);}
if(!parentTreeElement){let origin=resource.urlComponents.origin;if(origin){let originTreeElement=this._originTreeElementMap.get(origin);if(!originTreeElement){let representedObject=resource.type===WI.Resource.Type.Document?resource.parentFrame:null;originTreeElement=new WI.OriginTreeElement(origin,representedObject,{hasChildren:true});this._originTreeElementMap.set(origin,originTreeElement);let index=insertionIndexForObjectInListSortedByFunction(originTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(originTreeElement,index);}
let subpath=resource.urlComponents.path;if(subpath&&subpath[0]==="/")
subpath=subpath.substring(1);parentTreeElement=originTreeElement.createFoldersAsNeededForSubpath(subpath,this._boundCompareTreeElements);}else
parentTreeElement=this._resourcesTreeOutline;}
let resourceTreeElement=null;if(resource instanceof WI.CSSStyleSheet)
resourceTreeElement=new WI.CSSStyleSheetTreeElement(resource);else{let constructor=resource.type===WI.Resource.Type.WebSocket?WI.WebSocketResourceTreeElement:WI.ResourceTreeElement;resourceTreeElement=new constructor(resource,resource,{allowDirectoryAsName:true,hideOrigin:true});}
let index=insertionIndexForObjectInListSortedByFunction(resourceTreeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(resourceTreeElement,index);}
if(resource.type===WI.Resource.Type.Document||resource.type===WI.Resource.Type.Script){this._addBreakpointsForSourceCode(resource);this._addIssuesForSourceCode(resource);}}
_addResourcesRecursivelyForFrame(frame)
{this._addResource(frame.mainResource);for(let resource of frame.resourceCollection)
this._addResource(resource);for(let childFrame of frame.childFrameCollection)
this._addResourcesRecursivelyForFrame(childFrame);if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){for(let styleSheet of WI.cssManager.inspectorStyleSheetsForFrame(frame))
this._addResource(styleSheet);}}
_addStyleSheet(styleSheet)
{

if(styleSheet.anonymous)
return;let parentTreeElement=null;if(WI.browserManager.isExtensionScheme(styleSheet.urlComponents.scheme)){if(!this._extensionStyleSheetsFolderTreeElement)
this._extensionStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extension Style Sheets"),new WI.CSSStyleSheetCollection);parentTreeElement=this._extensionStyleSheetsFolderTreeElement;}else{if(!this._extraStyleSheetsFolderTreeElement)
this._extraStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extra Style Sheets"),new WI.CSSStyleSheetCollection);parentTreeElement=this._extraStyleSheetsFolderTreeElement;}
if(!parentTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(parentTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(parentTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;}
let treeElement=new WI.CSSStyleSheetTreeElement(styleSheet);let index=insertionIndexForObjectInListSortedByFunction(treeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(treeElement,index);}
_addScript(script)
{
if(script.anonymous)
return;if(WI.sharedApp.debuggableType!==WI.DebuggableType.JavaScript&&WI.sharedApp.debuggableType!==WI.DebuggableType.ITML){if(script.target!==WI.pageTarget){if(script.isMainResource()){this._addWorkerTargetWithMainResource(script.target);this._addBreakpointsForSourceCode(script);this._addIssuesForSourceCode(script);}
this._resourcesTreeOutline.disclosureButtons=true;return;}}
if(script.resource||script.dynamicallyAddedScriptElement)
return;let scriptTreeElement=new WI.ScriptTreeElement(script);if(!script.injected&&WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()){let index=insertionIndexForObjectInListSortedByFunction(scriptTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(scriptTreeElement,index);}else{let parentFolderTreeElement=null;if(WI.browserManager.isExtensionScheme(script.urlComponents.scheme)){if(!this._extensionScriptsFolderTreeElement){let collection=new WI.ScriptCollection;this._extensionScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extension Scripts"),collection);}
parentFolderTreeElement=this._extensionScriptsFolderTreeElement;}else{if(!this._extraScriptsFolderTreeElement){let collection=new WI.ScriptCollection;this._extraScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extra Scripts"),collection);}
parentFolderTreeElement=this._extraScriptsFolderTreeElement;}
if(parentFolderTreeElement)
parentFolderTreeElement.representedObject.add(script);if(!parentFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(parentFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(parentFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;}
parentFolderTreeElement.appendChild(scriptTreeElement);}
this._addBreakpointsForSourceCode(script);this._addIssuesForSourceCode(script);}
_addWorkerTargetWithMainResource(target)
{let targetTreeElement=new WI.WorkerTreeElement(target);this._workerTargetTreeElementMap.set(target,targetTreeElement);let index=insertionIndexForObjectInListSortedByFunction(targetTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(targetTreeElement,index);}
_addDebuggerTreeElementForSourceCode(sourceCode)
{let treeElement=this._breakpointsTreeOutline.findTreeElement(sourceCode);if(!treeElement){if(sourceCode instanceof WI.SourceMapResource)
treeElement=new WI.SourceMapResourceTreeElement(sourceCode);else if(sourceCode instanceof WI.Resource)
treeElement=new WI.ResourceTreeElement(sourceCode);else if(sourceCode instanceof WI.Script)
treeElement=new WI.ScriptTreeElement(sourceCode);}
if(!treeElement){console.error("Unknown sourceCode instance",sourceCode);return null;}
if(!treeElement.parent){treeElement.hasChildren=false;treeElement.expand();this._insertDebuggerTreeElement(treeElement,this._breakpointsTreeOutline);}
return treeElement;}
_insertDebuggerTreeElement(treeElement,parentTreeElement)
{let comparator=(a,b)=>{const rankFunctions=[(treeElement)=>treeElement.representedObject===WI.debuggerManager.debuggerStatementsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.allExceptionsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.uncaughtExceptionsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.assertionFailuresBreakpoint,(treeElement)=>treeElement instanceof WI.JavaScriptBreakpointTreeElement||treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement,(treeElement)=>treeElement.representedObject===WI.debuggerManager.allMicrotasksBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allAnimationFramesBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allTimeoutsBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allIntervalsBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allListenersBreakpoint,(treeElement)=>treeElement instanceof WI.EventBreakpointTreeElement,(treeElement)=>treeElement instanceof WI.DOMNodeTreeElement,(treeElement)=>treeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject,(treeElement)=>treeElement instanceof WI.DOMBreakpointTreeElement,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allRequestsBreakpoint,(treeElement)=>treeElement instanceof WI.URLBreakpointTreeElement,];let aRank=rankFunctions.findIndex((rankFunction)=>rankFunction(a));let bRank=rankFunctions.findIndex((rankFunction)=>rankFunction(b));if(aRank>=0&&bRank>=0){if(aRank<bRank)
return-1;if(bRank<aRank)
return 1;}
if(a instanceof WI.JavaScriptBreakpointTreeElement&&b instanceof WI.JavaScriptBreakpointTreeElement)
return this._compareJavaScriptBreakpointTreeElements(a,b);return a.mainTitle.extendedLocaleCompare(b.mainTitle)||a.subtitle.extendedLocaleCompare(b.subtitle);};parentTreeElement.insertChild(treeElement,insertionIndexForObjectInListSortedByFunction(treeElement,parentTreeElement.children,comparator));}
_compareJavaScriptBreakpointTreeElements(a,b)
{if(!a.representedObject||!b.representedObject)
return 0;let aLocation=a.representedObject.sourceCodeLocation;let bLocation=b.representedObject.sourceCodeLocation;if(!aLocation||!bLocation)
return 0;return aLocation.displayLineNumber-bLocation.displayLineNumber||aLocation.displayColumnNumber-bLocation.displayColumnNumber;}
_addBreakpoint(breakpoint)
{if(this._breakpointsTreeOutline.findTreeElement(breakpoint))
return null;let constructor=WI.JavaScriptBreakpointTreeElement;let options={};let parentTreeElement=this._breakpointsTreeOutline;let getDOMNodeTreeElement=(domNode)=>{let domNodeTreeElement=this._breakpointsTreeOutline.findTreeElement(domNode);if(!domNodeTreeElement){domNodeTreeElement=new WI.DOMNodeTreeElement(domNode);this._insertDebuggerTreeElement(domNodeTreeElement,this._breakpointsTreeOutline);}
return domNodeTreeElement;};if(breakpoint===WI.debuggerManager.debuggerStatementsBreakpoint)
options.classNames=["debugger-statement"];else if(breakpoint===WI.debuggerManager.allExceptionsBreakpoint)
options.classNames=["exception"];else if(breakpoint===WI.debuggerManager.uncaughtExceptionsBreakpoint)
options.classNames=["exception"];else if(breakpoint===WI.debuggerManager.assertionFailuresBreakpoint)
options.classNames=["assertion"];else if(breakpoint===WI.debuggerManager.allMicrotasksBreakpoint)
options.classNames=["microtask"];else if(breakpoint instanceof WI.DOMBreakpoint){if(!breakpoint.domNode)
return null;constructor=WI.DOMBreakpointTreeElement;parentTreeElement=getDOMNodeTreeElement(breakpoint.domNode);}else if(breakpoint instanceof WI.EventBreakpoint){constructor=WI.EventBreakpointTreeElement;if(breakpoint.eventListener){let eventTargetTreeElement=null;if(breakpoint.eventListener.onWindow){if(!SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject)
SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject={__window:true};eventTargetTreeElement=this._breakpointsTreeOutline.findTreeElement(SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject);if(!eventTargetTreeElement){const subtitle=null;eventTargetTreeElement=new WI.GeneralTreeElement(["event-target-window"],WI.unlocalizedString("window"),subtitle,SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject);this._insertDebuggerTreeElement(eventTargetTreeElement,this._breakpointsTreeOutline);}}else if(breakpoint.eventListener.node)
eventTargetTreeElement=getDOMNodeTreeElement(breakpoint.eventListener.node);if(eventTargetTreeElement)
parentTreeElement=eventTargetTreeElement;}}else if(breakpoint instanceof WI.URLBreakpoint)
constructor=WI.URLBreakpointTreeElement;else{let sourceCode=breakpoint.sourceCodeLocation&&breakpoint.sourceCodeLocation.displaySourceCode;if(!sourceCode)
return null;parentTreeElement=this._addDebuggerTreeElementForSourceCode(sourceCode);

if(breakpoint.disabled)
breakpoint.resolved=true;}
let breakpointTreeElement=new constructor(breakpoint,options);this._insertDebuggerTreeElement(breakpointTreeElement,parentTreeElement);if(parentTreeElement.children.length===1)
parentTreeElement.expand();return breakpointTreeElement;}
_removeBreakpoint(breakpoint)
{if(this._pauseReasonTreeOutline){let pauseReasonBreakpointTreeElement=this._pauseReasonTreeOutline.findTreeElement(breakpoint);if(pauseReasonBreakpointTreeElement)
pauseReasonBreakpointTreeElement.status=null;}
let breakpointTreeElement=this._breakpointsTreeOutline.findTreeElement(breakpoint);if(!breakpointTreeElement)
return;this._removeDebuggerTreeElement(breakpointTreeElement);}
_removeAllBreakpoints(breakpoints)
{for(let breakpoint of breakpoints){if(breakpoint.removable)
WI.debuggerManager.removeBreakpoint(breakpoint);}}
_toggleAllBreakpoints(breakpoints,disabled)
{for(let breakpoint of breakpoints)
breakpoint.disabled=disabled;}
_breakpointsBeneathTreeElement(treeElement)
{if(!(treeElement instanceof WI.ResourceTreeElement)&&!(treeElement instanceof WI.ScriptTreeElement))
return[];let breakpoints=[];for(let child of treeElement.children){let breakpoint=child.breakpoint;if(breakpoint)
breakpoints.push(breakpoint);}
return breakpoints;}
_addIssue(issueMessage,sourceCode)
{let issueTreeElement=this._resourcesTreeOutline.findTreeElement(issueMessage);if(!issueTreeElement){let parentTreeElement=this._resourcesTreeOutline.findTreeElement(sourceCode||issueMessage.sourceCodeLocation.sourceCode);if(!parentTreeElement)
return null;issueTreeElement=new WI.IssueTreeElement(issueMessage);parentTreeElement.insertChild(issueTreeElement,insertionIndexForObjectInListSortedByFunction(issueTreeElement,parentTreeElement.children,this._compareJavaScriptBreakpointTreeElements));if(parentTreeElement.children.length===1)
parentTreeElement.expand();}
return issueTreeElement;}
_removeDebuggerTreeElement(debuggerTreeElement)
{

if(!debuggerTreeElement.__deletedViaDeleteKeyboardShortcut)
debuggerTreeElement.deselect();let parentTreeElement=debuggerTreeElement.parent;parentTreeElement.removeChild(debuggerTreeElement);if(parentTreeElement.children.length||parentTreeElement===this._breakpointsTreeOutline)
return;parentTreeElement.treeOutline.removeChild(parentTreeElement);}
_addBreakpointsForSourceCode(sourceCode)
{for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(sourceCode))
this._addBreakpoint(breakpoint);}
_addIssuesForSourceCode(sourceCode)
{for(let issue of WI.consoleManager.issuesForSourceCode(sourceCode))
this._addIssue(issue,sourceCode);}
_addLocalOverride(localOverride)
{if(this._localOverridesTreeOutline.findTreeElement(localOverride))
return;let parentTreeElement=this._localOverridesTreeOutline;let localOverrideTreeElement=null;if(localOverride===WI.networkManager.bootstrapScript)
localOverrideTreeElement=new WI.BootstrapScriptTreeElement(localOverride);else if(localOverride instanceof WI.LocalResourceOverride)
localOverrideTreeElement=new WI.LocalResourceOverrideTreeElement(localOverride);let index=insertionIndexForObjectInListSortedByFunction(localOverrideTreeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(localOverrideTreeElement,index);this._localOverridesRow.hideEmptyMessage();this._localOverridesRow.element.appendChild(this._localOverridesTreeOutline.element);this._localOverridesContainer.hidden=false;}
_removeResourceOverride(localOverride)
{let resourceTreeElement=this._localOverridesTreeOutline.findTreeElement(localOverride);if(!resourceTreeElement)
return;let wasSelected=resourceTreeElement.selected;let parentTreeElement=this._localOverridesTreeOutline;parentTreeElement.removeChild(resourceTreeElement);if(!parentTreeElement.children.length){this._localOverridesContainer.hidden=true;if(wasSelected&&WI.networkManager.mainFrame&&WI.networkManager.mainFrame.mainResource)
WI.showRepresentedObject(WI.networkManager.mainFrame.mainResource);}}
_updateTemporarilyDisabledBreakpointsButtons()
{let breakpointsDisabledTemporarily=WI.debuggerManager.breakpointsDisabledTemporarily;this._debuggerBreakpointsButtonItem.enabled=!breakpointsDisabledTemporarily;this._debuggerPauseResumeButtonItem.enabled=!breakpointsDisabledTemporarily;}
_updateBreakpointsDisabledBanner()
{if(!WI.debuggerManager.breakpointsEnabled&&!this._timelineRecordingWarningElement&&!this._auditTestWarningElement){if(!this._breakpointsDisabledWarningElement){let enableBreakpointsButton=document.createElement("button");enableBreakpointsButton.textContent=WI.UIString("Enable Breakpoints");enableBreakpointsButton.addEventListener("click",()=>{WI.debuggerToggleBreakpoints();});this._breakpointsDisabledWarningElement=document.createElement("div");this._breakpointsDisabledWarningElement.classList.add("warning-banner");this._breakpointsDisabledWarningElement.append(WI.UIString("Breakpoints disabled"),document.createElement("br"),enableBreakpointsButton);}
this.contentView.element.insertBefore(this._breakpointsDisabledWarningElement,this.contentView.element.firstChild);}else if(this._breakpointsDisabledWarningElement){this._breakpointsDisabledWarningElement.remove();this._breakpointsDisabledWarningElement=null;}}
_updatePauseReason()
{this._pauseReasonTreeOutline=null;this._updatePauseReasonGotoArrow();let target=WI.debuggerManager.activeCallFrame.target;let targetData=WI.debuggerManager.dataForTarget(target);return this._updatePauseReasonSection(target,targetData.pauseReason,targetData.pauseData);}
_updatePauseReasonGotoArrow()
{this._pauseReasonLinkContainerElement.removeChildren();let activeCallFrame=WI.debuggerManager.activeCallFrame;if(!activeCallFrame)
return;let sourceCodeLocation=activeCallFrame.sourceCodeLocation;if(!sourceCodeLocation)
return;const options={useGoToArrowButton:true,};let linkElement=WI.createSourceCodeLocationLink(sourceCodeLocation,options);this._pauseReasonLinkContainerElement.appendChild(linkElement);}
_updatePauseReasonSection(target,pauseReason,pauseData)
{switch(pauseReason){case WI.DebuggerManager.PauseReason.AnimationFrame:{this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let eventBreakpointTreeElement=new WI.EventBreakpointTreeElement(WI.domDebuggerManager.allAnimationFramesBreakpoint,{classNames:["paused"],title:WI.UIString("requestAnimationFrame Fired"),});this._pauseReasonTreeOutline.appendChild(eventBreakpointTreeElement);let eventBreakpointRow=new WI.DetailsSectionRow;eventBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[eventBreakpointRow];return true;}
case WI.DebuggerManager.PauseReason.Assertion:if(pauseData&&pauseData.message)
this._pauseReasonTextRow.text=WI.UIString("Assertion with message: %s").format(pauseData.message);else
this._pauseReasonTextRow.text=WI.UIString("Assertion Failed");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.BlackboxedScript:{if(pauseData)
this._updatePauseReasonSection(target,WI.DebuggerManager.pauseReasonFromPayload(pauseData.originalReason),pauseData.originalData);let blackboxReasonTextRow=new WI.DetailsSectionTextRow(WI.UIString("Deferred pause from blackboxed script"));blackboxReasonTextRow.__blackboxReason=true;let existingRows=this._pauseReasonGroup.rows.filter((row)=>!row.__blackboxReason);this._pauseReasonGroup.rows=[blackboxReasonTextRow,...existingRows];return true;}
case WI.DebuggerManager.PauseReason.Breakpoint:{if(!pauseData||!pauseData.breakpointId)
break;this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._pauseReasonTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);let breakpoint=WI.debuggerManager.breakpointForIdentifier(pauseData.breakpointId);let breakpointTreeElement=new WI.JavaScriptBreakpointTreeElement(breakpoint,{classNames:["paused"],title:WI.UIString("Triggered Breakpoint"),});let breakpointDetailsSection=new WI.DetailsSectionRow;this._pauseReasonTreeOutline.appendChild(breakpointTreeElement);breakpointDetailsSection.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[breakpointDetailsSection];return true;}
case WI.DebuggerManager.PauseReason.CSPViolation:if(!pauseData)
break;this._pauseReasonTextRow.text=WI.UIString("Content Security Policy violation of directive: %s").format(pauseData.directive);this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.DebuggerStatement:this._pauseReasonTextRow.text=WI.UIString("Debugger Statement");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.DOM:{if(!pauseData||!pauseData.nodeId)
break;let domNode=WI.domManager.nodeForId(pauseData.nodeId);let domBreakpoints=WI.domDebuggerManager.domBreakpointsForNode(domNode);let domBreakpoint;for(let breakpoint of domBreakpoints){if(breakpoint.type===pauseData.type){domBreakpoint=breakpoint;break;}}
if(!domBreakpoint)
break;this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let type=WI.DOMBreakpoint.displayNameForType(domBreakpoint.type);let domBreakpointTreeElement=new WI.DOMBreakpointTreeElement(domBreakpoint,{classNames:["paused"],title:type,});let domBreakpointRow=new WI.DetailsSectionRow;this._pauseReasonTreeOutline.appendChild(domBreakpointTreeElement);domBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);let ownerElementRow=new WI.DetailsSectionSimpleRow(WI.UIString("Element"),WI.linkifyNodeReference(domNode));this._pauseReasonGroup.rows=[domBreakpointRow,ownerElementRow];let updateTargetDescription=(nodeId)=>{if(!nodeId)
return;let node=WI.domManager.nodeForId(nodeId);if(!node)
return;let fragment=document.createDocumentFragment();let description=null;switch(domBreakpoint.type){case WI.DOMBreakpoint.Type.SubtreeModified:description=pauseData.insertion?WI.UIString("Child added to "):WI.UIString("Removed descendant ");break;case WI.DOMBreakpoint.Type.NodeRemoved:description=WI.UIString("Removed ancestor ");break;}
fragment.append(description,WI.linkifyNodeReference(node));let targetDescriptionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Details"),fragment);targetDescriptionRow.element.classList.add("target-description");this._pauseReasonGroup.rows=this._pauseReasonGroup.rows.concat(targetDescriptionRow);};if(pauseData.targetNodeId){updateTargetDescription(pauseData.targetNodeId);}else if(pauseData.targetNode){let remoteObject=WI.RemoteObject.fromPayload(pauseData.targetNode,target);remoteObject.pushNodeToFrontend(updateTargetDescription);}
return true;}
case WI.DebuggerManager.PauseReason.Listener:case WI.DebuggerManager.PauseReason.EventListener:{if(!pauseData)
break;let eventBreakpoint=null;if(pauseData.eventListenerId)
eventBreakpoint=WI.domManager.breakpointForEventListenerId(pauseData.eventListenerId);if(!eventBreakpoint)
eventBreakpoint=WI.domDebuggerManager.listenerBreakpointForEventName(pauseData.eventName);if(!eventBreakpoint)
break;this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let eventBreakpointTreeElement=new WI.EventBreakpointTreeElement(eventBreakpoint,{classNames:["paused"],title:WI.UIString("\u201C%s\u201D Event Fired").format(pauseData.eventName),});this._pauseReasonTreeOutline.appendChild(eventBreakpointTreeElement);let eventBreakpointRow=new WI.DetailsSectionRow;eventBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);let rows=[eventBreakpointRow];let eventListener=eventBreakpoint.eventListener;if(eventListener){let value=null;if(eventListener.onWindow)
value=WI.unlocalizedString("window");else if(eventListener.node)
value=WI.linkifyNodeReference(eventListener.node);if(value)
rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Target"),value));}
this._pauseReasonGroup.rows=rows;return true;}
case WI.DebuggerManager.PauseReason.Exception:{if(!pauseData)
break;let data=WI.RemoteObject.fromPayload(pauseData,target);this._pauseReasonTextRow.text=WI.UIString("Exception with thrown value: %s").format(data.description);this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;}
case WI.DebuggerManager.PauseReason.Interval:{this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let eventBreakpointTreeElement=new WI.EventBreakpointTreeElement(WI.domDebuggerManager.allIntervalsBreakpoint,{classNames:["paused"],title:WI.UIString("setInterval Fired"),});this._pauseReasonTreeOutline.appendChild(eventBreakpointTreeElement);let eventBreakpointRow=new WI.DetailsSectionRow;eventBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[eventBreakpointRow];return true;}
case WI.DebuggerManager.PauseReason.Microtask:this._pauseReasonTextRow.text=WI.UIString("Microtask Fired");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.PauseOnNextStatement:this._pauseReasonTextRow.text=WI.UIString("Immediate Pause Requested");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.Timer:{if(!pauseData)
break;let eventBreakpoint=null;switch(pauseData.eventName){case"setTimeout":eventBreakpoint=WI.domDebuggerManager.allTimeoutsBreakpoint;break;case"setInterval":eventBreakpoint=WI.domDebuggerManager.allIntervalsBreakpoint;break;}
if(!eventBreakpoint)
break;this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let eventBreakpointTreeElement=new WI.EventBreakpointTreeElement(eventBreakpoint,{classNames:["paused"],title:WI.UIString("%s Fired").format(pauseData.eventName),});this._pauseReasonTreeOutline.appendChild(eventBreakpointTreeElement);let eventBreakpointRow=new WI.DetailsSectionRow;eventBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[eventBreakpointRow];return true;}
case WI.DebuggerManager.PauseReason.Timeout:{this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let eventBreakpointTreeElement=new WI.EventBreakpointTreeElement(WI.domDebuggerManager.allTimeoutsBreakpoint,{classNames:["paused"],title:WI.UIString("setTimeout Fired"),});this._pauseReasonTreeOutline.appendChild(eventBreakpointTreeElement);let eventBreakpointRow=new WI.DetailsSectionRow;eventBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[eventBreakpointRow];return true;}
case WI.DebuggerManager.PauseReason.Fetch:case WI.DebuggerManager.PauseReason.XHR:{if(!pauseData)
break;if(pauseData.breakpointURL){let urlBreakpoint=WI.domDebuggerManager.urlBreakpointForURL(pauseData.breakpointURL);this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});let urlBreakpointTreeElement=new WI.URLBreakpointTreeElement(urlBreakpoint,{classNames:["paused"],title:WI.UIString("Triggered URL Breakpoint"),});let urlBreakpointRow=new WI.DetailsSectionRow;this._pauseReasonTreeOutline.appendChild(urlBreakpointTreeElement);urlBreakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonTextRow.text=pauseData.url;this._pauseReasonGroup.rows=[urlBreakpointRow,this._pauseReasonTextRow];}else{this._pauseReasonTextRow.text=WI.UIString("Requesting: %s").format(pauseData.url);this._pauseReasonGroup.rows=[this._pauseReasonTextRow];}
this._pauseReasonTextRow.element.title=pauseData.url;return true;}
case WI.DebuggerManager.PauseReason.Other:console.error("Paused for unknown reason. We should always have a reason.");break;}
return false;}
_handleResourceGroupingModeScopeBarSelectionChanged(event)
{let selectedScopeBarItem=this._resourceGroupingModeScopeBar.selectedItems[0];WI.settings.resourceGroupingMode.value=selectedScopeBarItem[SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol]||WI.Resource.GroupingMode.Type;}
_handleResourceTypeScopeBarSelectionChanged(event)
{this.updateFilter();}
_handleTreeSelectionDidChange(event)
{if(!this.selected)
return;let treeElement=event.target.selectedTreeElement;if(!treeElement)
return;if(treeElement instanceof WI.DOMNodeTreeElement||treeElement instanceof WI.DOMBreakpointTreeElement||treeElement instanceof WI.EventBreakpointTreeElement||treeElement instanceof WI.URLBreakpointTreeElement)
return;if(treeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject)
return;if(treeElement instanceof WI.LocalResourceOverrideTreeElement){WI.showRepresentedObject(treeElement.representedObject);return;}

let selectTreeElementInResourcesTreeOutline=(sourceCode)=>{let resourceTreeElement=this._resourcesTreeOutline.findTreeElement(sourceCode);if(!resourceTreeElement)
return;const omitFocus=true;const selectedByUser=false;const suppressNotification=true;resourceTreeElement.select(omitFocus,selectedByUser,suppressNotification);};if(treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.OriginTreeElement||treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement||treeElement instanceof WI.CSSStyleSheetTreeElement){let representedObject=treeElement.representedObject;if(representedObject instanceof WI.Script&&representedObject.resource)
representedObject=representedObject.resource;if(treeElement.treeOutline!==this._resourcesTreeOutline)
selectTreeElementInResourcesTreeOutline(representedObject);if(representedObject instanceof WI.Collection||representedObject instanceof WI.SourceCode||representedObject instanceof WI.Frame)
WI.showRepresentedObject(representedObject);return;}
if(treeElement instanceof WI.CallFrameTreeElement){let callFrame=treeElement.callFrame;if(callFrame.id)
WI.debuggerManager.activeCallFrame=callFrame;if(callFrame.sourceCodeLocation)
WI.showSourceCodeLocation(callFrame.sourceCodeLocation);return;}
if(treeElement instanceof WI.IssueTreeElement){WI.showSourceCodeLocation(treeElement.issueMessage.sourceCodeLocation);return;}
if(treeElement instanceof WI.JavaScriptBreakpointTreeElement){let breakpoint=treeElement.breakpoint;if(breakpoint.special)
return;let sourceCode=breakpoint.sourceCodeLocation.displaySourceCode;if(sourceCode instanceof WI.Script&&sourceCode.resource)
sourceCode=sourceCode.resource;selectTreeElementInResourcesTreeOutline(sourceCode);WI.showSourceCodeLocation(breakpoint.sourceCodeLocation);return;}
if(treeElement instanceof WI.BlackboxedGroupTreeElement)
return;console.error("Unknown tree element",treeElement);}
_handleBreakpointTreeOutlineElementRemoved(event)
{let selectedTreeElement=this._breakpointsTreeOutline.selectedTreeElement;if(!selectedTreeElement)
return;if(selectedTreeElement.representedObject instanceof WI.Breakpoint&&!selectedTreeElement.representedObject.removable){const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;let treeElementToSelect=selectedTreeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);if(treeElementToSelect){const omitFocus=true;const selectedByUser=true;treeElementToSelect.select(omitFocus,selectedByUser);}}}
_populateCreateBreakpointContextMenu(contextMenu)
{function addToggleForSpecialBreakpoint(label,breakpoint,callback){contextMenu.appendCheckboxItem(label,()=>{if(breakpoint)
breakpoint.remove();else
callback();},!!breakpoint);}
addToggleForSpecialBreakpoint(WI.repeatedUIString.assertionFailures(),WI.debuggerManager.assertionFailuresBreakpoint,()=>{WI.debuggerManager.createAssertionFailuresBreakpoint();});contextMenu.appendSeparator();if(WI.JavaScriptBreakpoint.supportsMicrotasks()){addToggleForSpecialBreakpoint(WI.repeatedUIString.allMicrotasks(),WI.debuggerManager.allMicrotasksBreakpoint,()=>{WI.debuggerManager.createAllMicrotasksBreakpoint();});}
if(WI.DOMDebuggerManager.supportsEventBreakpoints()||WI.DOMDebuggerManager.supportsEventListenerBreakpoints()){addToggleForSpecialBreakpoint(WI.repeatedUIString.allAnimationFrames(),WI.domDebuggerManager.allAnimationFramesBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.AnimationFrame));});addToggleForSpecialBreakpoint(WI.repeatedUIString.allTimeouts(),WI.domDebuggerManager.allTimeoutsBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Timeout));});addToggleForSpecialBreakpoint(WI.repeatedUIString.allIntervals(),WI.domDebuggerManager.allIntervalsBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Interval));});contextMenu.appendSeparator();if(WI.DOMDebuggerManager.supportsAllListenersBreakpoint())
addToggleForSpecialBreakpoint(WI.repeatedUIString.allEvents(),WI.domDebuggerManager.allListenersBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener));});contextMenu.appendItem(WI.UIString("Event Breakpoint\u2026"),()=>{let popover=new WI.EventBreakpointPopover(this);popover.show(this._createBreakpointButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});}
if(WI.DOMDebuggerManager.supportsURLBreakpoints()||WI.DOMDebuggerManager.supportsXHRBreakpoints()){contextMenu.appendSeparator();addToggleForSpecialBreakpoint(WI.repeatedUIString.allRequests(),WI.domDebuggerManager.allRequestsBreakpoint,()=>{const url="";WI.domDebuggerManager.addURLBreakpoint(new WI.URLBreakpoint(WI.URLBreakpoint.Type.Text,url));});contextMenu.appendItem(WI.DOMDebuggerManager.supportsURLBreakpoints()?WI.UIString("URL Breakpoint\u2026"):WI.UIString("XHR Breakpoint\u2026"),()=>{let popover=new WI.URLBreakpointPopover(this);popover.show(this._createBreakpointButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});}}
_populateCreateLocalOverrideContextMenu(contextMenu)
{if(WI.NetworkManager.supportsOverridingResponses()){contextMenu.appendItem(WI.UIString("Local Override\u2026"),()=>{let popover=new WI.LocalResourceOverridePopover(this);popover.show(null,this._createLocalOverrideButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});}
if(WI.NetworkManager.supportsBootstrapScript()){contextMenu.appendItem(WI.UIString("Inspector Bootstrap Script"),async()=>{await WI.networkManager.createBootstrapScript();WI.networkManager.bootstrapScriptEnabled=true;WI.showRepresentedObject(WI.networkManager.bootstrapScript);});}}
_populateCreateResourceContextMenu(contextMenu)
{if(WI.NetworkManager.supportsOverridingResponses()){contextMenu.appendItem(WI.UIString("Local Override\u2026"),()=>{if(!this._localOverridesTreeOutline.children.length)
this._localOverridesRow.showEmptyMessage();this._localOverridesContainer.hidden=false;this._createLocalOverrideButton.element.scrollIntoViewIfNeeded(false);requestAnimationFrame(()=>{let popover=new WI.LocalResourceOverridePopover(this);popover.show(null,this._createLocalOverrideButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});});}
if(WI.NetworkManager.supportsBootstrapScript()){contextMenu.appendItem(WI.UIString("Inspector Bootstrap Script"),async()=>{await WI.networkManager.createBootstrapScript();WI.networkManager.bootstrapScriptEnabled=true;WI.showRepresentedObject(WI.networkManager.bootstrapScript);});}
if(WI.CSSManager.supportsInspectorStyleSheet()){let addInspectorStyleSheetItem=(menu,frame)=>{menu.appendItem(WI.UIString("Inspector Style Sheet"),()=>{if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){let parentFrameTreeElement=this._resourcesTreeOutline.findTreeElement(frame.mainResource);parentFrameTreeElement.reveal();parentFrameTreeElement.expand();}
WI.cssManager.preferredInspectorStyleSheetForFrame(frame,(styleSheet)=>{WI.showRepresentedObject(styleSheet);});});};addInspectorStyleSheetItem(contextMenu,WI.networkManager.mainFrame);let frames=WI.networkManager.frames;if(frames.length>2){let framesSubMenu=contextMenu.appendSubMenuItem(WI.UIString("Frames"));for(let frame of frames){if(frame===WI.networkManager.mainFrame||frame.mainResource.type!==WI.Resource.Type.Document)
continue;let frameSubMenuItem=framesSubMenu.appendSubMenuItem(frame.name?WI.UIString("%s (%s)").format(frame.name,frame.mainResource.displayName):frame.mainResource.displayName);addInspectorStyleSheetItem(frameSubMenuItem,frame);}}}}
_handleResourceGroupingModeChanged(event)
{this._workerTargetTreeElementMap.clear();this._mainFrameTreeElement=null;this._extensionScriptsFolderTreeElement=null;this._extensionStyleSheetsFolderTreeElement=null;this._extraScriptsFolderTreeElement=null;this._extraStyleSheetsFolderTreeElement=null;this._anonymousScriptsFolderTreeElement=null;this._anonymousStyleSheetsFolderTreeElement=null;this._originTreeElementMap.clear();let resourceGroupingModeScopeBarItem=this._resourceGroupingModeScopeBarItems[WI.settings.resourceGroupingMode.value];if(resourceGroupingModeScopeBarItem)
resourceGroupingModeScopeBarItem.selected=true;this._resourcesTreeOutline.removeChildren();let mainFrame=WI.networkManager.mainFrame;if(mainFrame){this._updateMainFrameTreeElement(mainFrame);this._addResourcesRecursivelyForFrame(mainFrame);for(let frame of WI.networkManager.frames){if(frame!==mainFrame)
this._addResourcesRecursivelyForFrame(frame);}}
for(let script of WI.debuggerManager.knownNonResourceScripts){this._addScript(script);if(script.sourceMaps.length&&WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel())
this._resourcesTreeOutline.disclosureButtons=true;}
for(let styleSheet of WI.cssManager.styleSheets){if(styleSheet.origin!==WI.CSSStyleSheet.Type.Author&&!styleSheet.isInspectorStyleSheet())
this._addStyleSheet(styleSheet);}}
_handleFrameMainResourceDidChange(event)
{let frame=event.target;if(frame.isMainFrame()){this._updateMainFrameTreeElement(frame);this._addResourcesRecursivelyForFrame(frame);for(let domBreakpoint of WI.domDebuggerManager.domBreakpoints)
this._removeBreakpoint(domBreakpoint);}
if(!event.data.oldMainResource){let resource=event.target.mainResource;this._addBreakpointsForSourceCode(resource);this._addIssuesForSourceCode(resource);}}
_handleResourceAdded(event)
{this._addResource(event.data.resource);}
_handleFrameWasAdded(event)
{let{frame}=event.data;if(frame.isMainFrame())
this._updateMainFrameTreeElement(frame);this._addResourcesRecursivelyForFrame(frame);}
_handleBootstrapScriptCreated(event)
{this._addLocalOverride(event.data.bootstrapScript);}
_handleBootstrapScriptDestroyed(event)
{this._removeResourceOverride(event.data.bootstrapScript);}
_handleLocalResourceOverrideAdded(event)
{this._addLocalOverride(event.data.localResourceOverride);}
_handleLocalResourceOverrideRemoved(event)
{this._removeResourceOverride(event.data.localResourceOverride);}
_handleDebuggerBreakpointAdded(event)
{this._addBreakpoint(event.data.breakpoint);}
_handleDebuggerBreakpointRemoved(event)
{this._removeBreakpoint(event.data.breakpoint);}
_handleDebuggerBreakpointsEnabledDidChange(event)
{this._debuggerBreakpointsButtonItem.activated=WI.debuggerManager.breakpointsEnabled;this._updateBreakpointsDisabledBanner();}
_handleDebuggerScriptAdded(event)
{this._addScript(event.data.script);}
_handleDebuggerScriptRemoved(event)
{let script=event.data.script;let scriptTreeElement=this._resourcesTreeOutline.findTreeElement(script);if(!scriptTreeElement)
return;let parentTreeElement=scriptTreeElement.parent;parentTreeElement.removeChild(scriptTreeElement);if(parentTreeElement instanceof WI.FolderTreeElement||parentTreeElement instanceof WI.OriginTreeElement){parentTreeElement.representedObject.remove(script);if(!parentTreeElement.children.length)
parentTreeElement.parent.removeChild(parentTreeElement);}}
_handleDebuggerScriptsCleared(event)
{const suppressOnDeselect=true;const suppressSelectSibling=true;for(let i=this._breakpointsTreeOutline.children.length-1;i>=0;--i){let treeElement=this._breakpointsTreeOutline.children[i];if(!(treeElement instanceof WI.ScriptTreeElement))
continue;this._breakpointsTreeOutline.removeChild(treeElement,suppressOnDeselect,suppressSelectSibling);}
if(this._extensionScriptsFolderTreeElement){if(this._extensionScriptsFolderTreeElement.parent)
this._extensionScriptsFolderTreeElement.parent.removeChild(this._extensionScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._extensionScriptsFolderTreeElement.representedObject.clear();this._extensionScriptsFolderTreeElement=null;}
if(this._extraScriptsFolderTreeElement){if(this._extraScriptsFolderTreeElement.parent)
this._extraScriptsFolderTreeElement.parent.removeChild(this._extraScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._extraScriptsFolderTreeElement.representedObject.clear();this._extraScriptsFolderTreeElement=null;}
if(this._anonymousScriptsFolderTreeElement){if(this._anonymousScriptsFolderTreeElement.parent)
this._anonymousScriptsFolderTreeElement.parent.removeChild(this._anonymousScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._anonymousScriptsFolderTreeElement.representedObject.clear();this._anonymousScriptsFolderTreeElement=null;}
if(this._workerTargetTreeElementMap.size){for(let treeElement of this._workerTargetTreeElementMap.values())
treeElement.parent.removeChild(treeElement,suppressOnDeselect,suppressSelectSibling);this._workerTargetTreeElementMap.clear();}
this._addResourcesRecursivelyForFrame(WI.networkManager.mainFrame);}
_handleDebuggerPaused(event)
{this._callStackContainer.hidden=false;if(this._updatePauseReason())
this._pauseReasonContainer.hidden=false;this._debuggerPauseResumeButtonItem.enabled=true;this._debuggerPauseResumeButtonItem.toggled=true;this._debuggerStepOverButtonItem.enabled=true;this._debuggerStepIntoButtonItem.enabled=true;this._debuggerStepOutButtonItem.enabled=true;if(this._debuggerStepNextButtonItem)
this._debuggerStepNextButtonItem.enabled=true;this.element.classList.add("paused");}
_handleDebuggerResumed(event)
{this._callStackContainer.hidden=true;this._pauseReasonContainer.hidden=true;this._debuggerPauseResumeButtonItem.enabled=true;this._debuggerPauseResumeButtonItem.toggled=false;this._debuggerStepOverButtonItem.enabled=false;this._debuggerStepIntoButtonItem.enabled=false;this._debuggerStepOutButtonItem.enabled=false;if(this._debuggerStepNextButtonItem)
this._debuggerStepNextButtonItem.enabled=false;this.element.classList.remove("paused");}
_handleDebuggerCallFramesDidChange(event)
{let{target}=event.data;let treeElement=this._findCallStackTargetTreeElement(target);if(treeElement)
treeElement.refresh();let activeCallFrameTreeElement=this._callStackTreeOutline.findTreeElement(WI.debuggerManager.activeCallFrame);if(activeCallFrameTreeElement)
activeCallFrameTreeElement.reveal();}
_handleDebuggerActiveCallFrameDidChange(event)
{if(this._activeCallFrameTreeElement){this._activeCallFrameTreeElement.isActiveCallFrame=false;this._activeCallFrameTreeElement=null;}
if(!WI.debuggerManager.activeCallFrame)
return;this._activeCallFrameTreeElement=this._callStackTreeOutline.findTreeElement(WI.debuggerManager.activeCallFrame);if(this._activeCallFrameTreeElement)
this._activeCallFrameTreeElement.isActiveCallFrame=true;}
_handleDebuggerWaitingToPause(event)
{this._debuggerPauseResumeButtonItem.enabled=false;}
_handleDebuggerObjectDisplayLocationDidChange(event)
{let debuggerObject=event.target;if(event.data.oldDisplaySourceCode===debuggerObject.sourceCodeLocation.displaySourceCode)
return;
let wasSelected=false;let oldDebuggerTreeElement=null;let newDebuggerTreeElement=null;if(debuggerObject instanceof WI.JavaScriptBreakpoint){oldDebuggerTreeElement=this._breakpointsTreeOutline.findTreeElement(debuggerObject);if(oldDebuggerTreeElement)
wasSelected=oldDebuggerTreeElement.selected;newDebuggerTreeElement=this._addBreakpoint(debuggerObject);}else if(debuggerObject instanceof WI.IssueMessage){oldDebuggerTreeElement=this._resourcesTreeOutline.findTreeElement(debuggerObject);if(oldDebuggerTreeElement)
wasSelected=oldDebuggerTreeElement.selected;newDebuggerTreeElement=this._addIssue(debuggerObject);}
if(!newDebuggerTreeElement)
return;if(oldDebuggerTreeElement)
this._removeDebuggerTreeElement(oldDebuggerTreeElement);if(wasSelected)
newDebuggerTreeElement.revealAndSelect(true,false,true);}
_handleDOMBreakpointDOMNodeWillChange(event)
{let breakpoint=event.target;this._removeBreakpoint(breakpoint);}
_handleDOMBreakpointDOMNodeDidChange(event)
{let breakpoint=event.target;this._addBreakpoint(breakpoint);}
_handleConsoleIssueAdded(event)
{let{issue}=event.data;if(!issue.sourceCodeLocation||!issue.sourceCodeLocation.sourceCode||(issue.source!=="javascript"&&issue.source!=="console-api"))
return;this._addIssue(issue);}
_handleConsoleCleared(event)
{let issueTreeElements=[];let currentTreeElement=this._resourcesTreeOutline.children[0];while(currentTreeElement&&!currentTreeElement.root){if(currentTreeElement instanceof WI.IssueTreeElement)
issueTreeElements.push(currentTreeElement);const skipUnrevealed=false;const stayWithin=null;const dontPopulate=true;currentTreeElement=currentTreeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);}
issueTreeElements.forEach((treeElement)=>treeElement.parent.removeChild(treeElement));}
_handleTimelineCapturingStateChanged(event)
{this._updateTemporarilyDisabledBreakpointsButtons();switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Starting:if(!this._timelineRecordingWarningElement){let stopRecordingButton=document.createElement("button");stopRecordingButton.textContent=WI.UIString("Stop recording");stopRecordingButton.addEventListener("click",()=>{WI.timelineManager.stopCapturing();});this._timelineRecordingWarningElement=document.createElement("div");this._timelineRecordingWarningElement.classList.add("warning-banner");this._timelineRecordingWarningElement.append(WI.UIString("Debugger disabled during Timeline recording"),document.createElement("br"),stopRecordingButton);}
this.contentView.element.insertBefore(this._timelineRecordingWarningElement,this.contentView.element.firstChild);break;case WI.TimelineManager.CapturingState.Inactive:if(this._timelineRecordingWarningElement){this._timelineRecordingWarningElement.remove();this._timelineRecordingWarningElement=null;}
break;}
this._updateBreakpointsDisabledBanner();}
_handleAuditManagerTestScheduled(event)
{this._updateTemporarilyDisabledBreakpointsButtons();if(!this._auditTestWarningElement){let stopAuditButton=document.createElement("button");stopAuditButton.textContent=WI.UIString("Stop Audit");stopAuditButton.addEventListener("click",(event)=>{WI.auditManager.stop();});this._auditTestWarningElement=document.createElement("div");this._auditTestWarningElement.classList.add("warning-banner");this._auditTestWarningElement.append(WI.UIString("Debugger disabled during Audit"),document.createElement("br"),stopAuditButton);}
this.contentView.element.insertBefore(this._auditTestWarningElement,this.contentView.element.firstChild);this._updateBreakpointsDisabledBanner();}
_handleAuditManagerTestCompleted(event)
{this._updateTemporarilyDisabledBreakpointsButtons();if(this._auditTestWarningElement){this._auditTestWarningElement.remove();this._auditTestWarningElement=null;}
this._updateBreakpointsDisabledBanner();}
_handleCSSStyleSheetAdded(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author)
return;if(styleSheet.isInspectorStyleSheet()){if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Type){let frameTreeElement=this.treeElementForRepresentedObject(styleSheet.parentFrame);if(frameTreeElement){frameTreeElement.addRepresentedObjectToNewChildQueue(styleSheet);return;}}
this._addResource(styleSheet);}else
this._addStyleSheet(styleSheet);}
_handleCSSStyleSheetRemoved(event)
{let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author)
return;let treeElement=this._resourcesTreeOutline.findTreeElement(styleSheet);if(!treeElement)
return;let parent=treeElement.parent;treeElement.parent.removeChild(treeElement);if(!parent.children.length)
parent.parent.removeChild(parent);switch(parent){case this._extensionStyleSheetsFolderTreeElement:this._extensionStyleSheetsFolderTreeElement=null;break;case this._extraStyleSheetsFolderTreeElement:this._extraStyleSheetsFolderTreeElement=null;break;case this._anonymousStyleSheetsFolderTreeElement:this._anonymousStyleSheetsFolderTreeElement=null;break;}}
_handleTargetAdded(event)
{this._addTarget(event.data.target);}
_handleTargetRemoved(event)
{let{target}=event.data;let workerTreeElement=this._workerTargetTreeElementMap.take(target);if(workerTreeElement)
workerTreeElement.parent.removeChild(workerTreeElement);let callStackTreeElement=this._findCallStackTargetTreeElement(target);if(callStackTreeElement)
this._callStackTreeOutline.removeChild(callStackTreeElement);this._updateCallStackTreeOutline();}
_handleExtraDomainsActivated()
{ if(WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel())
this._resourcesTreeOutline.disclosureButtons=true;}};WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol=Symbol("resource-type");WI.SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol=Symbol("resource-grouping-mode");WI.SourceMapResourceTreeElement=class SourceMapResourceTreeElement extends WI.ResourceTreeElement
{constructor(sourceMapResource)
{super(sourceMapResource);this.addClassName("source-map-resource");} 
_updateTitles()
{var oldMainTitle=this.mainTitle;this.mainTitle=this.resource.displayName;var sourceMapHost=this.resource.urlComponents.host;var originalHost=this.resource.sourceMap.originalSourceCode.urlComponents.host;var subtitle=sourceMapHost!==originalHost?WI.displayNameForHost(sourceMapHost):null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;if(oldMainTitle!==this.mainTitle)
this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange",[this,oldMainTitle]);}};WI.SpanningDataGridNode=class SpanningDataGridNode extends WI.DataGridNode
{constructor(text)
{super({[WI.SpanningDataGridNode.ColumnIdentifier]:text});} 
createCells()
{let cellElement=this.createCell(WI.SpanningDataGridNode.ColumnIdentifier);cellElement.classList.add("spanning");cellElement.setAttribute("colspan",this.dataGrid.columns.size);this.element.appendChild(cellElement);}};WI.SpanningDataGridNode.ColumnIdentifier="spanning-text";WI.SpreadsheetCSSStyleDeclarationEditor=class SpreadsheetCSSStyleDeclarationEditor extends WI.View
{constructor(delegate,style)
{super();this.element.classList.add(WI.SpreadsheetCSSStyleDeclarationEditor.StyleClassName);this._delegate=delegate;this.style=style;this._propertyViews=[];this._focused=false;this._inlineSwatchActive=false;this._showsImplicitProperties=false;this._alwaysShowPropertyNames=new Set;this._propertyVisibilityMode=WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideUnusedInheritedVariables;this._hiddenUnusedVariables=new Set;this._hideFilterNonMatchingProperties=false;this._sortPropertiesByName=false;this._propertyPendingStartEditing=null;this._pendingAddBlankPropertyIndexOffset=NaN;this._filterText=null;this._anchorIndex=NaN;this._focusIndex=NaN;} 
initialLayout()
{if(!this._style)
return;this.element.addEventListener("focus",()=>{this.focused=true;},true);this.element.addEventListener("blur",(event)=>{let focusedElement=event.relatedTarget;if(focusedElement&&this.element.contains(focusedElement))
return;this.focused=false;},true);this.element.addEventListener("keydown",this._handleKeyDown.bind(this));this.element.addEventListener("cut",this._handleCut.bind(this));this.element.addEventListener("copy",this._handleCopy.bind(this));}
layout()
{
if(this.editing&&!this._propertyPendingStartEditing&&isNaN(this._pendingAddBlankPropertyIndexOffset))
return;super.layout();this.element.removeChildren();if(this._style)
this._style.updatePropertiesModifiedState();let properties=this.propertiesToRender;this._propertyViews=[];let propertyViewPendingStartEditing=null;for(let index=0;index<properties.length;index++){let property=properties[index];let propertyView=new WI.SpreadsheetStyleProperty(this,property,{selectable:true});propertyView.index=index;this.element.append(propertyView.element);this._propertyViews.push(propertyView);if(property===this._propertyPendingStartEditing)
propertyViewPendingStartEditing=propertyView;}
if(this._hiddenUnusedVariables.size){let showHiddenVariablesButtonElement=this.element.appendChild(document.createElement("button"));showHiddenVariablesButtonElement.classList.add("hidden-variables-button");showHiddenVariablesButtonElement.title=WI.UIString("Option-click to show unused CSS variables from all rules","Option-click to show unused CSS variables from all rules @ Styles Sidebar Panel Tooltip","Tooltip with instructions on how to show all hidden CSS variables");const labelSingular=WI.UIString("Show %d unused CSS variable","Show %d unused CSS variable (singular) @ Styles Sidebar Panel","Text label for button to reveal one unused CSS variable");const labelPlural=WI.UIString("Show %d unused CSS variables","Show %d unused CSS variables (plural) @ Styles Sidebar Panel","Text label for button to reveal multiple unused CSS variables");let label=this._hiddenUnusedVariables.size>1?labelPlural:labelSingular;showHiddenVariablesButtonElement.textContent=label.format(this._hiddenUnusedVariables.size);showHiddenVariablesButtonElement.addEventListener("click",(event)=>{if(event.altKey){this._setAllPropertyVisibilityMode(WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.ShowAll);return;}
this.propertyVisibilityMode=WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.ShowAll;});}
if(propertyViewPendingStartEditing){propertyViewPendingStartEditing.startEditingName();this._propertyPendingStartEditing=null;}
if(this._filterText)
this.applyFilter(this._filterText);if(!isNaN(this._pendingAddBlankPropertyIndexOffset))
this.addBlankProperty(this._propertyViews.length-1-this._pendingAddBlankPropertyIndexOffset);else if(this.hasSelectedProperties())
this.selectProperties(this._anchorIndex,this._focusIndex);if(this._pendingPropertyToHighlight){this.highlightProperty(this._pendingPropertyToHighlight);this._pendingPropertyToHighlight=null;}
this._updateDebugLockStatus();}
detached()
{this._inlineSwatchActive=false;this.focused=false;for(let propertyView of this._propertyViews)
propertyView.detached();super.detached();}
get style()
{return this._style;}
set style(style)
{if(this._style===style)
return;if(this._style)
this._style.removeEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._propertiesChanged,this);this._style=style||null;if(this._style)
this._style.addEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._propertiesChanged,this);this.needsLayout();}
get editing()
{return this._focused||this._inlineSwatchActive;}
set focused(value)
{this._focused=value;this._updateStyleLock();}
set inlineSwatchActive(value)
{this._inlineSwatchActive=value;this._updateStyleLock();}
set showsImplicitProperties(value)
{if(value===this._showsImplicitProperties)
return;this._showsImplicitProperties=value;this.needsLayout();}
set alwaysShowPropertyNames(propertyNames)
{this._alwaysShowPropertyNames=new Set(propertyNames);this.needsLayout();}
set propertyVisibilityMode(propertyVisibilityMode)
{if(this._propertyVisibilityMode===propertyVisibilityMode)
return;this._propertyVisibilityMode=propertyVisibilityMode;this.needsLayout();}
set hideFilterNonMatchingProperties(value)
{if(value===this._hideFilterNonMatchingProperties)
return;this._hideFilterNonMatchingProperties=value;this.needsLayout();}
set sortPropertiesByName(value)
{if(value===this._sortPropertiesByName)
return;this._sortPropertiesByName=value;this.needsLayout();}
get propertiesToRender()
{let properties=[];if(!this._style)
return properties;if(this._style._styleSheetTextRange)
properties=this._style.visibleProperties;else
properties=this._style.properties;if(this._style.inherited)
properties=properties.filter((property)=>property.inherited);if(this._sortPropertiesByName)
properties.sort((a,b)=>a.name.extendedLocaleCompare(b.name));let hideVariables=this._propertyVisibilityMode===SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideVariables;let hideNonVariables=this._propertyVisibilityMode===SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideNonVariables;let hideUnusedInheritedVariables=this._propertyVisibilityMode===SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideUnusedInheritedVariables;this._hiddenUnusedVariables=new Set;return properties.filter((property)=>{if(!property.isVariable&&hideNonVariables)
return false;if(property.isVariable&&hideVariables)
return false;if(property.isVariable&&hideUnusedInheritedVariables&&this._style.inherited&&!this._style.nodeStyles.usedCSSVariables.has(property.name)){this._hiddenUnusedVariables.add(property);return false;}
return!property.implicit||this._showsImplicitProperties||this._alwaysShowPropertyNames.has(property.canonicalName);});}
get selectionRange()
{let startIndex=Math.min(this._anchorIndex,this._focusIndex);let endIndex=Math.max(this._anchorIndex,this._focusIndex);return[startIndex,endIndex];}
startEditingFirstProperty()
{let firstEditableProperty=this._editablePropertyAfter(-1);if(firstEditableProperty)
firstEditableProperty.startEditingName();else{const appendAfterLast=-1;this.addBlankProperty(appendAfterLast);}}
startEditingLastProperty()
{let lastEditableProperty=this._editablePropertyBefore(this._propertyViews.length);if(lastEditableProperty)
lastEditableProperty.startEditingValue();else{const appendAfterLast=-1;this.addBlankProperty(appendAfterLast);}}
highlightProperty(property)
{if(!property.overridden&&this._hiddenUnusedVariables.find(propertiesMatch)){this._pendingPropertyToHighlight=property;this.propertyVisibilityMode=WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.ShowAll;return true;}
function propertiesMatch(cssProperty){if(cssProperty.attached&&!cssProperty.overridden){if(cssProperty.canonicalName===property.canonicalName||hasMatchingLonghandProperty(cssProperty))
return true;}
return false;}
function hasMatchingLonghandProperty(cssProperty){let cssProperties=cssProperty.relatedLonghandProperties;if(!cssProperties.length)
return false;for(let property of cssProperties){if(propertiesMatch(property))
return true;}
return false;}
for(let i=0;i<this._propertyViews.length;++i){if(propertiesMatch(this._propertyViews[i].property)){this.selectProperties(i,i);return true;}}
return false;}
addBlankProperty(index)
{this._pendingAddBlankPropertyIndexOffset=NaN;if(index===-1){index=this._propertyViews.length;}
this._propertyPendingStartEditing=this._style.newBlankProperty(index);this.needsLayout();}
hasSelectedProperties()
{return!isNaN(this._anchorIndex)&&!isNaN(this._focusIndex);}
selectProperties(anchorIndex,focusIndex)
{if(isNaN(anchorIndex)||isNaN(focusIndex)){console.error(`Nothing to select. anchorIndex (${anchorIndex}) and focusIndex (${focusIndex}) must be numbers.`);this.deselectProperties();return;}
this._anchorIndex=anchorIndex;this._focusIndex=focusIndex;let[startIndex,endIndex]=this.selectionRange;for(let i=0;i<this._propertyViews.length;++i){let propertyView=this._propertyViews[i];let isSelected=i>=startIndex&&i<=endIndex;propertyView.selected=isSelected;}
this._suppressBlur=true;let property=this._propertyViews[focusIndex];property.element.focus();this._suppressBlur=false;}
extendSelectedProperties(focusIndex)
{this.selectProperties(this._anchorIndex,focusIndex);}
deselectProperties()
{for(let propertyView of this._propertyViews)
propertyView.selected=false;this._focused=false;this._anchorIndex=NaN;this._focusIndex=NaN;}
placeTextCaretInFocusedProperty()
{if(isNaN(this._focusIndex))
return;let focusedProperty=this._propertyViews[this._focusIndex];let selection=window.getSelection();selection.removeAllRanges();selection.setBaseAndExtent(focusedProperty.element,0,focusedProperty.element,0);}
applyFilter(filterText)
{this._filterText=filterText;if(!this.didInitialLayout)
return;let matches=false;for(let propertyView of this._propertyViews){if(propertyView.applyFilter(this._filterText)){matches=true;if(this._hideFilterNonMatchingProperties)
this.element.append(propertyView.element);}else if(this._hideFilterNonMatchingProperties)
propertyView.element.remove();}
this.dispatchEventToListeners(WI.SpreadsheetCSSStyleDeclarationEditor.Event.FilterApplied,{matches});} 
spreadsheetStylePropertyBlur(event,property)
{if(this._suppressBlur)
return;if(this._delegate.spreadsheetCSSStyleDeclarationEditorPropertyBlur)
this._delegate.spreadsheetCSSStyleDeclarationEditorPropertyBlur(event,property);}
spreadsheetStylePropertyMouseEnter(event,property)
{if(this._delegate.spreadsheetCSSStyleDeclarationEditorPropertyMouseEnter)
this._delegate.spreadsheetCSSStyleDeclarationEditorPropertyMouseEnter(event,property);}
spreadsheetStylePropertyFocusMoved(propertyView,{direction,willRemoveProperty})
{this._updatePropertiesStatus();if(!direction)
return;let movedFromIndex=this._propertyViews.indexOf(propertyView);if(movedFromIndex===-1){if(this._style.selectorEditable)
this._delegate.spreadsheetCSSStyleDeclarationEditorStartEditingRuleSelector();return;}
if(direction==="forward"){let propertyView=this._editablePropertyAfter(movedFromIndex);if(propertyView)
propertyView.startEditingName();else{if(willRemoveProperty){const delta=1;this._delegate.spreadsheetCSSStyleDeclarationEditorStartEditingAdjacentRule(this,delta);}else{const appendAfterLast=-1;this.addBlankProperty(appendAfterLast);}}}else{let propertyView=this._editablePropertyBefore(movedFromIndex);if(propertyView){propertyView.startEditingValue();}else{if(this._style.selectorEditable)
this._delegate.spreadsheetCSSStyleDeclarationEditorStartEditingRuleSelector();else{const delta=-1;this._delegate.spreadsheetCSSStyleDeclarationEditorStartEditingAdjacentRule(this,delta);}}}}
spreadsheetStylePropertySelect(index)
{this.selectProperties(index,index);}
spreadsheetStylePropertySelectByProperty(property)
{if(this._delegate&&this._delegate.spreadsheetCSSStyleDeclarationEditorSelectProperty)
this._delegate.spreadsheetCSSStyleDeclarationEditorSelectProperty(property);}
spreadsheetStylePropertyAddBlankPropertySoon(propertyView,{index})
{if(isNaN(index))
index=this._propertyViews.length;this._pendingAddBlankPropertyIndexOffset=this._propertyViews.length-index;}
spreadsheetStylePropertyWillRemove(propertyView)
{this._propertyViews.remove(propertyView);for(let index=0;index<this._propertyViews.length;index++)
this._propertyViews[index].index=index;let wasFocused=document.activeElement&&propertyView.element.contains(document.activeElement);if(wasFocused)
this.focused=false;}
spreadsheetStylePropertyShowProperty(propertyView,property)
{if(this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty)
this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty(this,property);}
spreadsheetStylePropertyDidPressEsc(propertyView)
{let index=this._propertyViews.indexOf(propertyView);if(index!==-1)
this.selectProperties(index,index);}
stylePropertyInlineSwatchActivated()
{this.inlineSwatchActive=true;}
stylePropertyInlineSwatchDeactivated()
{this.inlineSwatchActive=false;} 
_handleKeyDown(event)
{if(!this.hasSelectedProperties()||!this._propertyViews.length)
return;if(event.key==="ArrowUp"||event.key==="ArrowDown"){let delta=event.key==="ArrowUp"?-1:1;let focusIndex=Number.constrain(this._focusIndex+delta,0,this._propertyViews.length-1);if(event.shiftKey)
this.extendSelectedProperties(focusIndex);else
this.selectProperties(focusIndex,focusIndex);event.stop();}else if(event.key==="Tab"||event.key==="Enter"){if(!this.style.editable)
return;let property=this._propertyViews[this._focusIndex];if(property&&property.enabled){event.stop();property.startEditingName();}}else if(event.key==="Backspace"||event.key==="Delete"){if(!this.style.editable){InspectorFrontendHost.beep();return;}
this._removeSelectedProperties();event.stop();}else if((event.code==="Space"&&!event.shiftKey&&!event.metaKey&&!event.ctrlKey)||(event.key==="/"&&event.commandOrControlKey&&!event.shiftKey)){if(!this.style.editable)
return;let[startIndex,endIndex]=this.selectionRange;let disabled=this._propertyViews[startIndex].property.enabled;for(let i=endIndex;i>=startIndex;--i){let propertyView=this._propertyViews[i];propertyView.property.commentOut(disabled);propertyView.update();}
event.stop();}else if(event.key==="a"&&event.commandOrControlKey){this.selectProperties(0,this._propertyViews.length-1);event.stop();}else if(event.key==="Esc")
this.deselectProperties();}
_handleCopy(event)
{if(!this.hasSelectedProperties())
return;this._copySelectedProperties(event);}
_handleCut(event)
{if(!this.style.editable){InspectorFrontendHost.beep();return;}
if(!this.hasSelectedProperties())
return;this._copySelectedProperties(event);this._removeSelectedProperties();}
_copySelectedProperties(event)
{let[startIndex,endIndex]=this.selectionRange;let formattedProperties=this._propertyViews.slice(startIndex,endIndex+1).map((propertyView)=>propertyView.property.formattedText);event.clipboardData.setData("text/plain",formattedProperties.join("\n"));event.stop();}
_removeSelectedProperties()
{let[startIndex,endIndex]=this.selectionRange;let propertyIndexToSelect=NaN;if(endIndex+1!==this._propertyViews.length)
propertyIndexToSelect=startIndex;else if(startIndex>0)
propertyIndexToSelect=startIndex-1;this.deselectProperties();for(let i=endIndex;i>=startIndex;i--)
this._propertyViews[i].remove();if(!isNaN(propertyIndexToSelect))
this.selectProperties(propertyIndexToSelect,propertyIndexToSelect);}
_editablePropertyAfter(propertyIndex)
{for(let index=propertyIndex+1;index<this._propertyViews.length;index++){let property=this._propertyViews[index];if(property.enabled)
return property;}
return null;}
_editablePropertyBefore(propertyIndex)
{for(let index=propertyIndex-1;index>=0;index--){let property=this._propertyViews[index];if(property.enabled)
return property;}
return null;}
_propertiesChanged(event)
{if(this.editing&&isNaN(this._pendingAddBlankPropertyIndexOffset))
this._updatePropertiesStatus();else
this.needsLayout();}
_updatePropertiesStatus()
{for(let propertyView of this._propertyViews)
propertyView.updateStatus();}
_updateStyleLock()
{if(!this._style)
return;this._style.locked=this._focused||this._inlineSwatchActive;this._updateDebugLockStatus();}
_updateDebugLockStatus()
{if(!this._style||!WI.settings.debugEnableStyleEditingDebugMode.value)
return;this.element.classList.toggle("debug-style-locked",this._style.locked);}
_setAllPropertyVisibilityMode(propertyVisibilityMode)
{this._delegate?.spreadsheetCSSStyleDeclarationEditorSetAllPropertyVisibilityMode?.(this,propertyVisibilityMode);}};WI.SpreadsheetCSSStyleDeclarationEditor.Event={FilterApplied:"spreadsheet-css-style-declaration-editor-filter-applied",};WI.SpreadsheetCSSStyleDeclarationEditor.StyleClassName="spreadsheet-style-declaration-editor";WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode={ShowAll:Symbol("variable-visibility-show-all"),HideVariables:Symbol("variable-visibility-hide-variables"),HideNonVariables:Symbol("variable-visibility-hide-non-variables"),HideUnusedInheritedVariables:Symbol("variable-visibility-hide-unused-inherited-variables"),};WI.SpreadsheetCSSStyleDeclarationSection=class SpreadsheetCSSStyleDeclarationSection extends WI.View
{constructor(delegate,style)
{let element=document.createElement("section");element.classList.add("spreadsheet-css-declaration");super(element);this._delegate=delegate||null;this._style=style;this._propertiesEditor=null;this._selectorElements=[];this._groupingElements=[];this._filterText=null;this._shouldFocusSelectorElement=false;this._wasEditing=false;this._isMousePressed=false;this._mouseDownIndex=NaN;this._mouseDownPoint=null;this._boundHandleWindowMouseMove=null;} 
get style(){return this._style;}
get editable()
{return this._style.editable;}
set propertyVisibilityMode(propertyVisibilityMode)
{this._propertiesEditor.propertyVisibilityMode=propertyVisibilityMode;}
initialLayout()
{super.initialLayout();let iconClassName=null;switch(this._style.type){case WI.CSSStyleDeclaration.Type.Rule:if(this._style.inherited){iconClassName="inherited-style-rule-icon";break;}
switch(this._style.ownerRule.type){case WI.CSSStyleSheet.Type.Author:iconClassName="author-style-rule-icon";break;case WI.CSSStyleSheet.Type.User:iconClassName="user-style-rule-icon";break;case WI.CSSStyleSheet.Type.UserAgent:iconClassName="user-agent-style-rule-icon";break;case WI.CSSStyleSheet.Type.Inspector:iconClassName="inspector-style-rule-icon";break;}
break;case WI.CSSStyleDeclaration.Type.Inline:case WI.CSSStyleDeclaration.Type.Attribute:if(this._style.inherited)
iconClassName="inherited-element-style-rule-icon";else
iconClassName=WI.DOMTreeElementPathComponent.DOMElementIconStyleClassName;break;}
this._element.classList.add("has-icon",iconClassName);let groupings=this._style.groupings.filter((grouping)=>grouping.text!=="all");if(groupings.length){let groupingsElement=this.element.appendChild(document.createElement("div"));groupingsElement.classList.add("header-groupings");let currentGroupingType=null;let groupingTypeElement=null;this._groupingElements=groupings.map((grouping)=>{if(grouping.type!==currentGroupingType){groupingTypeElement=groupingsElement.appendChild(document.createElement("div"));groupingTypeElement.classList.add("grouping");groupingTypeElement.textContent=grouping.prefix+" ";currentGroupingType=grouping.type;}else
groupingTypeElement.append(", ");let span=groupingTypeElement.appendChild(document.createElement("span"));span.textContent=grouping.text;return span;});}
this._headerElement=this._element.appendChild(document.createElement("div"));this._headerElement.classList.add("header");this._styleOriginView=new WI.StyleOriginView();this._headerElement.append(this._styleOriginView.element);this._selectorElement=document.createElement("span");this._selectorElement.classList.add("selector");this._selectorElement.addEventListener("mouseenter",this._highlightNodesWithSelector.bind(this));this._selectorElement.addEventListener("mouseleave",this._hideDOMNodeHighlight.bind(this));this._headerElement.append(this._selectorElement);this._openBrace=document.createElement("span");this._openBrace.classList.add("open-brace");this._openBrace.textContent=" {";this._headerElement.append(this._openBrace);if(this._style.selectorEditable){this._selectorTextField=new WI.SpreadsheetSelectorField(this,this._selectorElement);this._selectorTextField.addEventListener(WI.SpreadsheetSelectorField.Event.StartedEditing,function(event){this._headerElement.classList.add("editing-selector");},this);this._selectorTextField.addEventListener(WI.SpreadsheetSelectorField.Event.StoppedEditing,function(event){this._headerElement.classList.remove("editing-selector");},this);this._selectorElement.tabIndex=0;}
this._propertiesEditor=new WI.SpreadsheetCSSStyleDeclarationEditor(this,this._style);this._propertiesEditor.element.classList.add("properties");this._propertiesEditor.addEventListener(WI.SpreadsheetCSSStyleDeclarationEditor.Event.FilterApplied,this._handleEditorFilterApplied,this);this._closeBrace=document.createElement("span");this._closeBrace.classList.add("close-brace");this._closeBrace.textContent="}";this.addSubview(this._propertiesEditor);this._propertiesEditor.needsLayout();this._element.append(this._closeBrace);if(!this._style.editable)
this._element.classList.add("locked");else if(!this._style.ownerRule)
this._element.classList.add("selector-locked");this.element.addEventListener("mousedown",this._handleMouseDown.bind(this));if(this._style.editable){this.element.addEventListener("click",this._handleClick.bind(this));new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"S",this._save.bind(this),this._element);new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"S",this._save.bind(this),this._element);}}
layout()
{super.layout();this._styleOriginView.update(this._style);this._renderSelector();if(this._shouldFocusSelectorElement)
this.startEditingRuleSelector();}
startEditingRuleSelector()
{if(!this._selectorElement){this._shouldFocusSelectorElement=true;return;}
this._shouldFocusSelectorElement=false;if(this._style.selectorEditable)
this._selectorTextField.startEditing();else
this._propertiesEditor.startEditingFirstProperty();}
highlightProperty(property)
{
if(!this.didInitialLayout)
this.updateLayout();if(this._propertiesEditor.highlightProperty(property)){this._element.scrollIntoView();return true;}
return false;} 
spreadsheetSelectorFieldDidCommit(changed)
{let selectorText=this._selectorElement.textContent.trim();if(selectorText&&changed){this.dispatchEventToListeners(WI.SpreadsheetCSSStyleDeclarationSection.Event.SelectorWillChange);this._style.ownerRule.setSelectorText(selectorText).finally(this._renderSelector.bind(this));}else
this._discardSelectorChange();}
spreadsheetSelectorFieldWillNavigate(direction)
{if(direction==="forward")
this._propertiesEditor.startEditingFirstProperty();else if(direction==="backward"){if(this._delegate.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule){const delta=-1;this._delegate.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule(this,delta);}else
this._propertiesEditor.startEditingLastProperty();}}
spreadsheetSelectorFieldDidDiscard()
{this._discardSelectorChange();} 
spreadsheetCSSStyleDeclarationEditorStartEditingRuleSelector()
{this.startEditingRuleSelector();}
spreadsheetCSSStyleDeclarationEditorStartEditingAdjacentRule(propertiesEditor,delta)
{if(!this._delegate)
return;if(this._delegate.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule)
this._delegate.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule(this,delta);}
spreadsheetCSSStyleDeclarationEditorPropertyBlur(event,property)
{if(!this._isMousePressed)
this._propertiesEditor.deselectProperties();}
spreadsheetCSSStyleDeclarationEditorPropertyMouseEnter(event,property)
{if(this._isMousePressed){let index=parseInt(property.element.dataset.propertyIndex);this._propertiesEditor.selectProperties(this._mouseDownIndex,index);}}
spreadsheetCSSStyleDeclarationEditorSelectProperty(property)
{if(this._delegate&&this._delegate.spreadsheetCSSStyleDeclarationSectionSelectProperty)
this._delegate.spreadsheetCSSStyleDeclarationSectionSelectProperty(property);}
spreadsheetCSSStyleDeclarationEditorSetAllPropertyVisibilityMode(editor,propertyVisibilityMode)
{this._delegate?.spreadsheetCSSStyleDeclarationSectionSetAllPropertyVisibilityMode?.(this,propertyVisibilityMode);}
applyFilter(filterText)
{this._filterText=filterText;if(!this.didInitialLayout)
return;this._element.classList.remove(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName);this._propertiesEditor.applyFilter(this._filterText);} 
_discardSelectorChange()
{this._renderSelector();}
_renderSelector()
{this._selectorElement.removeChildren();this._selectorElements=[];let appendSelector=(selector,matched)=>{let selectorElement=this._selectorElement.appendChild(document.createElement("span"));selectorElement.textContent=selector.text;if(matched)
selectorElement.classList.add(WI.SpreadsheetCSSStyleDeclarationSection.MatchedSelectorElementStyleClassName);if(selector.specificity){let specificity=selector.specificity.map((number)=>number.toLocaleString());let tooltip=WI.UIString("Specificity: (%d, %d, %d)").format(...specificity);if(selector.dynamic){tooltip+="\n";if(this._style.inherited)
tooltip+=WI.UIString("Dynamically calculated for the parent element");else
tooltip+=WI.UIString("Dynamically calculated for the selected element");}
selectorElement.title=tooltip;}else if(selector.dynamic){let tooltip=WI.UIString("Specificity: No value for selected element");tooltip+="\n";tooltip+=WI.UIString("Dynamically calculated for the selected element and did not match");selectorElement.title=tooltip;}
this._selectorElements.push(selectorElement);};let appendSelectorTextKnownToMatch=(selectorText)=>{let selectorElement=this._selectorElement.appendChild(document.createElement("span"));selectorElement.textContent=selectorText;selectorElement.classList.add(WI.SpreadsheetCSSStyleDeclarationSection.MatchedSelectorElementStyleClassName);};if(!this._iconElement){this._iconElement=document.createElement("img");this._iconElement.classList.add("icon");WI.addMouseDownContextMenuHandlers(this._iconElement,this._populateIconElementContextMenu.bind(this));}
this._selectorElement.appendChild(this._iconElement);switch(this._style.type){case WI.CSSStyleDeclaration.Type.Rule:var hasMatchingPseudoSelector=false;var selectors=this._style.ownerRule.selectors;if(selectors.length){for(let i=0;i<selectors.length;++i){let matched=this._style.ownerRule.matchedSelectorIndices.includes(i);if(matched&&selectors[i].isPseudoSelector())
hasMatchingPseudoSelector=true;appendSelector(selectors[i],matched);if(i<selectors.length-1)
this._selectorElement.append(", ");}}else
appendSelectorTextKnownToMatch(this._style.ownerRule.selectorText);this._element.classList.toggle("pseudo-selector",hasMatchingPseudoSelector);break;case WI.CSSStyleDeclaration.Type.Inline:{this._selectorElement.classList.add("style-attribute");let wrapper=this._selectorElement.appendChild(document.createElement("span"));wrapper.textContent=WI.UIString("Style Attribute","CSS properties defined via HTML style attribute");break;}
case WI.CSSStyleDeclaration.Type.Attribute:appendSelectorTextKnownToMatch(this._style.node.displayName);break;}
if(this._filterText)
this.applyFilter(this._filterText);}
_save(event)
{event.stop();if(this._style.type!==WI.CSSStyleDeclaration.Type.Rule){InspectorFrontendHost.beep();return;}
let sourceCode=this._style.ownerRule.sourceCodeLocation.sourceCode;if(sourceCode.type!==WI.Resource.Type.StyleSheet){InspectorFrontendHost.beep();return;}
let url;if(sourceCode.urlComponents.scheme==="data"){let mainResource=WI.networkManager.mainFrame.mainResource;if(mainResource.urlComponents.lastPathComponent.endsWith(".html"))
url=mainResource.url.replace(/\.html$/,"-data.css");else{let pathDirectory=mainResource.url.slice(0,-mainResource.urlComponents.lastPathComponent.length);url=pathDirectory+"data.css";}}else
url=sourceCode.url;const saveAs=event.shiftKey;WI.FileUtilities.save({url:url,content:sourceCode.content},saveAs);}
_handleMouseDown(event)
{if(event.button!==0)
return;this._wasEditing=this._propertiesEditor.editing||document.activeElement===this._selectorElement;let propertyElement=event.target.closest(".property");if(!propertyElement)
return;this._isMousePressed=true;event.preventDefault();if(this._wasEditing&&document.activeElement)
document.activeElement.blur();window.addEventListener("click",this._handleWindowClick.bind(this),{capture:true,once:true});let propertyIndex=parseInt(propertyElement.dataset.propertyIndex);if(event.shiftKey&&this._propertiesEditor.hasSelectedProperties())
this._propertiesEditor.extendSelectedProperties(propertyIndex);else{this._propertiesEditor.deselectProperties();this._mouseDownPoint=WI.Point.fromEvent(event);if(!this._boundHandleWindowMouseMove)
this._boundHandleWindowMouseMove=this._handleWindowMouseMove.bind(this);window.addEventListener("mousemove",this._boundHandleWindowMouseMove);}
if(propertyElement.parentNode){this._mouseDownIndex=propertyIndex;this._element.classList.add("selecting");}else
this._stopSelection();}
_populateIconElementContextMenu(contextMenu)
{contextMenu.appendItem(WI.UIString("Copy Rule"),()=>{InspectorFrontendHost.copyText(this._style.generateFormattedText({includeGroupingsAndSelectors:true,multiline:true}));});if(this._style.editable&&this._style.properties.length){let shouldDisable=this._style.properties.some((property)=>property.enabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Rule"):WI.UIString("Enable Rule"),()=>{for(let property of this._style.properties)
property.commentOut(shouldDisable);});}
if(!this._style.inherited&&InspectorBackend.hasCommand("CSS.addRule")){let generateSelector=()=>{if(this._style.type===WI.CSSStyleDeclaration.Type.Attribute)
return this._style.node.displayName;return this._style.selectorText;};let createNewRule=(selector,text)=>{if(this._delegate&&this._delegate.spreadsheetCSSStyleDeclarationSectionAddNewRule)
this._delegate.spreadsheetCSSStyleDeclarationSectionAddNewRule(this,selector,text);else
this._style.nodeStyles.addRule(selector,text);};contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Duplicate Selector"),()=>{createNewRule(generateSelector());});if(!WI.CSSManager.PseudoElementNames.some((className)=>this._style.selectorText.includes(":"+className))){let addPseudoRule=(pseudoSelector,text)=>{let selector=null;if(this._style.ownerRule)
selector=this._style.ownerRule.selectors.map((selector)=>selector.text+pseudoSelector).join(", ");else
selector=generateSelector()+pseudoSelector;createNewRule(selector,text);};if(WI.CSSManager.ForceablePseudoClasses.every((className)=>!this._style.selectorText.includes(":"+className))){contextMenu.appendSeparator();for(let pseudoClass of WI.CSSManager.ForceablePseudoClasses){if(pseudoClass==="visited"&&this._style.node.nodeName()!=="A")
continue;let pseudoClassSelector=":"+pseudoClass;contextMenu.appendItem(WI.UIString("Add %s Rule").format(pseudoClassSelector),()=>{if(WI.cssManager.canForcePseudoClasses())
this._style.node.setPseudoClassEnabled(pseudoClass,true);addPseudoRule(pseudoClassSelector);});}}
if(this._style.type===WI.CSSStyleDeclaration.Type.Rule){contextMenu.appendSeparator();for(let pseudoElement of WI.CSSManager.PseudoElementNames){let pseudoElementSelector="::"+pseudoElement;contextMenu.appendItem(WI.UIString("Create %s Rule").format(pseudoElementSelector),()=>{addPseudoRule(pseudoElementSelector,"content: \"\";");});}}}}
if(this._style.ownerRule&&this._style.ownerRule.sourceCodeLocation){contextMenu.appendSeparator();let label=null;let sourceCode=this._style.ownerRule.sourceCodeLocation.displaySourceCode;if(sourceCode instanceof WI.CSSStyleSheet||(sourceCode instanceof WI.Resource&&sourceCode.type===WI.Resource.Type.StyleSheet))
label=WI.UIString("Reveal in Style Sheet");else
label=WI.UIString("Reveal in Sources Tab");contextMenu.appendItem(label,()=>{WI.showSourceCodeLocation(this._style.ownerRule.sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}}
_handleWindowClick(event)
{if(this._propertiesEditor.hasSelectedProperties()){event.stop();}
this._stopSelection();}
_handleWindowMouseMove(event)
{if(this._mouseDownPoint.distance(WI.Point.fromEvent(event))<8)
return;if(!this._propertiesEditor.hasSelectedProperties()){this._propertiesEditor.selectProperties(this._mouseDownIndex,this._mouseDownIndex);}
window.removeEventListener("mousemove",this._boundHandleWindowMouseMove);this._mouseDownPoint=null;}
_handleClick(event)
{this._stopSelection();if(this._wasEditing||this._propertiesEditor.hasSelectedProperties())
return;if(window.getSelection().type==="Range")
return;event.stop();if(event.target.classList.contains(WI.SpreadsheetStyleProperty.StyleClassName)){let propertyIndex=parseInt(event.target.dataset.propertyIndex);this._propertiesEditor.addBlankProperty(propertyIndex+1);return;}
if(event.target===this._headerElement||event.target===this._openBrace){this._propertiesEditor.addBlankProperty(0);return;}
if(event.target===this._element||event.target===this._closeBrace){const appendAfterLast=-1;this._propertiesEditor.addBlankProperty(appendAfterLast);}}
_stopSelection()
{this._isMousePressed=false;this._mouseDownIndex=NaN;this._element.classList.remove("selecting");this._propertiesEditor.placeTextCaretInFocusedProperty();window.removeEventListener("mousemove",this._boundHandleWindowMouseMove);this._mouseDownPoint=null;}
_highlightNodesWithSelector()
{let node=this._style.node;if(!this._style.ownerRule){node.highlight();return;}
let selectorText=this._selectorElement.textContent.trim();if(node.frame)
WI.domManager.highlightSelector(selectorText,node.frame.id);else
WI.domManager.highlightSelector(selectorText);}
_hideDOMNodeHighlight()
{WI.domManager.hideDOMNodeHighlight();}
_handleEditorFilterApplied(event)
{let matchesGrouping=false;for(let groupingElement of this._groupingElements){groupingElement.classList.remove(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName);if(groupingElement.textContent.includes(this._filterText)){groupingElement.classList.add(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName);matchesGrouping=true;}}
let matchesSelector=false;for(let selectorElement of this._selectorElements){selectorElement.classList.remove(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName);if(selectorElement.textContent.includes(this._filterText)){selectorElement.classList.add(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName);matchesSelector=true;}}
let matches=event.data.matches||matchesGrouping||matchesSelector;if(!matches)
this._element.classList.add(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName);this.dispatchEventToListeners(WI.SpreadsheetCSSStyleDeclarationSection.Event.FilterApplied,{matches});}};WI.SpreadsheetCSSStyleDeclarationSection.Event={FilterApplied:"spreadsheet-css-style-declaration-section-filter-applied",SelectorWillChange:"spreadsheet-css-style-declaration-section-selector-will-change",};WI.SpreadsheetCSSStyleDeclarationSection.MatchedSelectorElementStyleClassName="matched";WI.SpreadsheetRulesStyleDetailsPanel=class SpreadsheetRulesStyleDetailsPanel extends WI.StyleDetailsPanel
{constructor(delegate)
{const className="rules";const identifier="rules";const label=WI.UIString("Styles \u2014 Rules");super(delegate,className,identifier,label);this.element.dir="ltr";this._headerMap=new Map;this._sections=[];this._newRuleSelector=null;this._ruleMediaAndInherticanceList=[];this._propertyToSelectAndHighlight=null;this._filterText=null;this._shouldRefreshSubviews=false;this._suppressLayoutAfterSelectorChange=false;this._emptyFilterResultsElement=WI.createMessageTextView(WI.UIString("No Results Found"));} 
get supportsNewRule()
{return this.nodeStyles&&!this.nodeStyles.node.isInUserAgentShadowTree()&&InspectorBackend.hasCommand("CSS.addRule");}
refresh(significantChange)
{
if(significantChange){this._shouldRefreshSubviews=true;this.needsLayout();}
super.refresh(significantChange);}
scrollToSectionAndHighlightProperty(property)
{if(!this.isAttached||this.layoutPending){this._propertyToSelectAndHighlight=property;return;}
for(let section of this._sections){if(section.highlightProperty(property))
return;}}
nodeStylesRefreshed(event)
{super.nodeStylesRefreshed(event);if(this._propertyToSelectAndHighlight){this.scrollToSectionAndHighlightProperty(this._propertyToSelectAndHighlight);this._propertyToSelectAndHighlight=null;}}
newRuleButtonClicked()
{this._addNewRule();}
newRuleButtonContextMenu(event)
{let styleSheets=WI.cssManager.styleSheets.filter(styleSheet=>styleSheet.hasInfo()&&!styleSheet.isInlineStyleTag()&&!styleSheet.isInlineStyleAttributeStyleSheet());if(!styleSheets.length)
return;let contextMenu=WI.ContextMenu.createFromEvent(event);const handler=null;const disabled=true;contextMenu.appendItem(WI.UIString("Available Style Sheets"),handler,disabled);let[inspectorStyleSheets,regularStyleSheets]=styleSheets.partition(styleSheet=>styleSheet.isInspectorStyleSheet());contextMenu.appendItem(WI.UIString("Inspector Style Sheet"),()=>{this._addNewRule(inspectorStyleSheets.length?inspectorStyleSheets[0].id:null);});for(let styleSheet of regularStyleSheets){contextMenu.appendItem(styleSheet.displayName,()=>{this._addNewRule(styleSheet.id);});}}
applyFilter(filterText)
{this._filterText=filterText;if(!this.didInitialLayout)
return;if(this._filterText)
this.element.classList.add("filter-non-matching");for(let header of this._headerMap.values())
header.classList.add(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName);for(let section of this._sections)
section.applyFilter(this._filterText);}
focusFirstSection()
{this.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule(null,1);}
focusLastSection()
{this.spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule(null,-1);} 
spreadsheetCSSStyleDeclarationSectionSelectProperty(property)
{this.scrollToSectionAndHighlightProperty(property);}
spreadsheetCSSStyleDeclarationSectionStartEditingAdjacentRule(currentSection,delta)
{let index=this._sections.indexOf(currentSection);if(index<0){if(delta<0)
index=this._sections.length;else if(delta>0)
index=-1;}
index+=delta;while(this._sections[index]!==currentSection){if(index<0){if(this._delegate&&this._delegate.styleDetailsPanelFocusLastPseudoClassCheckbox){this._delegate.styleDetailsPanelFocusLastPseudoClassCheckbox(this);break;}
index=this._sections.length-1;}else if(index>=this._sections.length){if(this._delegate&&this._delegate.styleDetailsPanelFocusFilterBar){this._delegate.styleDetailsPanelFocusFilterBar(this);break;}
index=0;}
let section=this._sections[index];if(section.editable){if(delta<0)
section._propertiesEditor.startEditingLastProperty();else
section.startEditingRuleSelector();break;}
index+=delta;}}
spreadsheetCSSStyleDeclarationSectionAddNewRule(section,selector,text)
{this._newRuleSelector=selector;this.nodeStyles.addRule(this._newRuleSelector,text);}
spreadsheetCSSStyleDeclarationSectionSetAllPropertyVisibilityMode(section,propertyVisibilityMode)
{for(let section of this._sections)
section.propertyVisibilityMode=propertyVisibilityMode;} 
layout()
{if(!this._shouldRefreshSubviews)
return;this._shouldRefreshSubviews=false;if(this._suppressLayoutAfterSelectorChange){this._suppressLayoutAfterSelectorChange=false;return;}
this.removeAllSubviews();let previousStyle=null;let currentHeader=null;this._headerMap.clear();this._sections=[];let addHeader=(text,nodeOrPseudoId)=>{currentHeader=this.element.appendChild(document.createElement("h2"));currentHeader.classList.add("section-header");currentHeader.append(text);if(nodeOrPseudoId){if(nodeOrPseudoId instanceof WI.DOMNode){currentHeader.append(" ",WI.linkifyNodeReference(nodeOrPseudoId,{maxLength:100,excludeRevealElement:true,}));}else
currentHeader.append(" ",WI.CSSManager.displayNameForPseudoId(nodeOrPseudoId));}};let addSection=(section)=>{if(section.style.inherited&&(!previousStyle||previousStyle.node!==section.style.node))
addHeader(WI.UIString("Inherited From","A section of CSS rules matching an ancestor DOM node"),section.style.node);this.addSubview(section);this._sections.push(section);section.needsLayout();if(currentHeader)
this._headerMap.set(section.style,currentHeader);previousStyle=section.style;};let createSection=(style)=>{let section=style[SpreadsheetRulesStyleDetailsPanel.StyleSectionSymbol];if(!section){section=new WI.SpreadsheetCSSStyleDeclarationSection(this,style);section.addEventListener(WI.SpreadsheetCSSStyleDeclarationSection.Event.FilterApplied,this._handleSectionFilterApplied,this);section.addEventListener(WI.SpreadsheetCSSStyleDeclarationSection.Event.SelectorWillChange,this._handleSectionSelectorWillChange,this);style[SpreadsheetRulesStyleDetailsPanel.StyleSectionSymbol]=section;}
if(this._newRuleSelector===style.selectorText&&style.enabledProperties.length===0)
section.startEditingRuleSelector();addSection(section);};let addedPseudoStyles=false;let addPseudoStyles=()=>{if(addedPseudoStyles)
return;let beforePseudoId=null;let afterPseudoId=null;if(InspectorBackend.Enum.CSS.PseudoId){beforePseudoId=WI.CSSManager.PseudoSelectorNames.Before;afterPseudoId=WI.CSSManager.PseudoSelectorNames.After;}else{beforePseudoId=4;afterPseudoId=5;}
for(let[pseudoId,pseudoElementInfo]of this.nodeStyles.pseudoElements){let pseudoElement=null;if(pseudoId===beforePseudoId)
pseudoElement=this.nodeStyles.node.beforePseudoElement();else if(pseudoId===afterPseudoId)
pseudoElement=this.nodeStyles.node.afterPseudoElement();addHeader(WI.UIString("Pseudo-Element"),pseudoElement||pseudoId);for(let style of WI.DOMNodeStyles.uniqueOrderedStyles(pseudoElementInfo.orderedStyles))
createSection(style);}
addedPseudoStyles=true;};for(let style of this.nodeStyles.uniqueOrderedStyles){if(style.inherited)
addPseudoStyles();createSection(style);}
addPseudoStyles();this._newRuleSelector=null;this.element.append(this._emptyFilterResultsElement);if(this._filterText)
this.applyFilter(this._filterText);}
filterDidChange(filterBar)
{this.applyFilter(filterBar.filters.text);} 
_handleSectionFilterApplied(event)
{if(!event.data.matches)
return;this.element.classList.remove("filter-non-matching");let header=this._headerMap.get(event.target.style);if(header)
header.classList.remove(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName);}
_addNewRule(stylesheetId)
{const justSelector=true;this._newRuleSelector=this.nodeStyles.node.appropriateSelectorFor(justSelector);const text="";this.nodeStyles.addRule(this._newRuleSelector,text,stylesheetId);}
_handleSectionSelectorWillChange(event)
{this._suppressLayoutAfterSelectorChange=true;}};WI.SpreadsheetRulesStyleDetailsPanel.StyleSectionSymbol=Symbol("style-section");WI.SpreadsheetSelectorField=class SpreadsheetSelectorField extends WI.Object
{constructor(delegate,element)
{super();this._delegate=delegate;this._element=element;this._element.classList.add("spreadsheet-selector-field");this._element.addEventListener("mousedown",this._handleMouseDown.bind(this));this._element.addEventListener("mouseup",this._handleMouseUp.bind(this));this._element.addEventListener("blur",this._handleBlur.bind(this));this._element.addEventListener("keydown",this._handleKeyDown.bind(this));this._editing=false;this._valueBeforeEditing="";this._handledMouseDown=false;} 
get editing(){return this._editing;}
startEditing()
{if(this._editing)
return;this._editing=true;this._valueBeforeEditing=this._element.textContent;let element=this._element;element.classList.add("editing");element.contentEditable="plaintext-only";element.spellcheck=false;element.scrollIntoViewIfNeeded(false);element.textContent=element.textContent;this._selectText();this.dispatchEventToListeners(WI.SpreadsheetSelectorField.Event.StartedEditing);}
stopEditing()
{if(!this._editing)
return;this._editing=false;this._valueBeforeEditing="";this._element.classList.remove("editing");this._element.contentEditable=false;this.dispatchEventToListeners(WI.SpreadsheetSelectorField.Event.StoppedEditing);} 
_selectText()
{window.getSelection().selectAllChildren(this._element);}
_handleMouseDown(event)
{this._handledMouseDown=true;}
_handleMouseUp(event)
{if(!this._handledMouseDown)
return;this._handledMouseDown=false;this.startEditing();}
_handleBlur(event)
{if(document.activeElement===this._element)
return;if(this._delegate&&typeof this._delegate.spreadsheetSelectorFieldDidCommit==="function"){let changed=this._element.textContent!==this._valueBeforeEditing;this._delegate.spreadsheetSelectorFieldDidCommit(changed);}
this.stopEditing();}
_handleKeyDown(event)
{if(event.key==="Enter"&&!this._editing){event.stop();this.startEditing();return;}
if(!this._editing)
return;if(event.key==="Enter"||event.key==="Tab"){event.stop();if(this._delegate&&typeof this._delegate.spreadsheetSelectorFieldWillNavigate==="function"){let direction=(event.shiftKey&&event.key==="Tab")?"backward":"forward";this._delegate.spreadsheetSelectorFieldWillNavigate(direction);}
this.stopEditing();return;}
if(event.key==="Escape"){event.stop();this.stopEditing();if(this._delegate&&typeof this._delegate.spreadsheetSelectorFieldDidDiscard==="function")
this._delegate.spreadsheetSelectorFieldDidDiscard();}}};WI.SpreadsheetSelectorField.Event={StartedEditing:"spreadsheet-selector-field-started-editing",StoppedEditing:"spreadsheet-selector-field-stopped-editing",};WI.SpreadsheetStyleProperty=class SpreadsheetStyleProperty extends WI.Object
{constructor(delegate,property,options={})
{super();this._delegate=delegate||null;this._property=property;this._readOnly=options.readOnly||false;this._hideDocumentation=!!options.hideDocumentation;this._element=document.createElement("div");if(options.selectable)
this._element.tabIndex=-1;this._contentElement=null;this._nameElement=null;this._valueElement=null;this._cssDocumentationButton=null;this._jumpToEffectivePropertyButton=null;this._nameTextField=null;this._valueTextField=null;this._selected=false;this._hasInvalidVariableValue=false;this._cssDocumentationPopover=null;this.update();property.addEventListener(WI.CSSProperty.Event.OverriddenStatusChanged,this.updateStatus,this);property.addEventListener(WI.CSSProperty.Event.Changed,this.updateStatus,this);if(!this._readOnly){property.addEventListener(WI.CSSProperty.Event.ModifiedChanged,this.updateStatus,this);this._element.addEventListener("blur",(event)=>{if(document.activeElement===this._element)
return;if(this._delegate.spreadsheetStylePropertyBlur)
this._delegate.spreadsheetStylePropertyBlur(event,this);});this._element.addEventListener("mouseenter",(event)=>{if(this._delegate.spreadsheetStylePropertyMouseEnter)
this._delegate.spreadsheetStylePropertyMouseEnter(event,this);});new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Slash,()=>{this._toggle();this._select();},this._element);}} 
get element(){return this._element;}
get property(){return this._property;}
get enabled(){return this._property.enabled;}
set index(index)
{this._element.dataset.propertyIndex=index;}
get selected()
{return this._selected;}
set selected(value)
{if(value===this._selected)
return;this._selected=value;this.updateStatus();}
startEditingName()
{if(!this._nameTextField)
return;this._nameTextField.startEditing();}
startEditingValue()
{if(!this._valueTextField)
return;this._valueTextField.startEditing();}
detached()
{if(this._nameTextField?.editing)
this._nameTextField.element.blur();else if(this._valueTextField?.editing)
this._valueTextField.element.blur();if(this._nameTextField)
this._nameTextField.detached();if(this._valueTextField)
this._valueTextField.detached();}
remove(replacement=null)
{if(this._delegate&&typeof this._delegate.spreadsheetStylePropertyWillRemove==="function")
this._delegate.spreadsheetStylePropertyWillRemove(this);this.element.remove();if(replacement)
this._property.text=replacement;else
this._property.remove();this.detached();}
update()
{this.element.removeChildren();if(this._isEditable()){this._checkboxElement=this.element.appendChild(document.createElement("input"));this._checkboxElement.classList.add("property-toggle");this._checkboxElement.type="checkbox";this._checkboxElement.checked=this._property.enabled;this._checkboxElement.tabIndex=-1;this._checkboxElement.addEventListener("click",(event)=>{event.stopPropagation();this._toggle();});}
this._contentElement=this.element.appendChild(document.createElement("span"));this._contentElement.className="content";if(!this._property.enabled)
this._contentElement.append("/* ");this._nameElement=this._contentElement.appendChild(document.createElement("span"));this._nameElement.classList.add("name");this._nameElement.textContent=this._property.name;let colonElement=this._contentElement.appendChild(document.createElement("span"));colonElement.classList.add("colon");colonElement.textContent=": ";let valueContainer=this._contentElement.appendChild(document.createElement("span"));valueContainer.className="value-container";this._valueElement=valueContainer.appendChild(document.createElement("span"));this._valueElement.classList.add("value");this._renderValue(this._property.rawValue);if(this._isEditable()&&this._property.enabled){this._nameElement.tabIndex=0;this._nameElement.addEventListener("beforeinput",this._handleNameBeforeInput.bind(this));this._nameElement.addEventListener("paste",this._handleNamePaste.bind(this));this._nameTextField=new WI.SpreadsheetTextField(this,this._nameElement,this._nameCompletionDataProvider.bind(this));this._valueElement.tabIndex=0;this._valueElement.addEventListener("beforeinput",this._handleValueBeforeInput.bind(this));this._valueTextField=new WI.SpreadsheetTextField(this,this._valueElement,this._valueCompletionDataProvider.bind(this));}
if(this._isEditable()){this._setupJumpToSymbol(this._nameElement);this._setupJumpToSymbol(this._valueElement);}
let semicolonElement=valueContainer.appendChild(document.createElement("span"));semicolonElement.classList.add("semicolon");semicolonElement.textContent=";";if(this._property.enabled){this._warningElement=this.element.appendChild(document.createElement("span"));this._warningElement.className="warning";}else
this._contentElement.append(" */");this._addCSSDocumentationButton();if(!this._property.implicit&&this._property.ownerStyle.type===WI.CSSStyleDeclaration.Type.Computed&&!this._property.isShorthand){let effectiveProperty=this._property.ownerStyle.nodeStyles.effectivePropertyForName(this._property.name);if(effectiveProperty&&!effectiveProperty.styleSheetTextRange)
effectiveProperty=effectiveProperty.relatedShorthandProperty;let ownerRule=effectiveProperty?effectiveProperty.ownerStyle.ownerRule:null;let arrowElement=this._contentElement.appendChild(WI.createGoToArrowButton());arrowElement.addEventListener("click",(event)=>{if(!effectiveProperty||!ownerRule||!event.altKey){if(this._delegate.spreadsheetStylePropertyShowProperty)
this._delegate.spreadsheetStylePropertyShowProperty(this,this._property);return;}
let sourceCode=ownerRule.sourceCodeLocation.sourceCode;let{startLine,startColumn}=effectiveProperty.styleSheetTextRange;WI.showSourceCodeLocation(sourceCode.createSourceCodeLocation(startLine,startColumn),{ignoreNetworkTab:true,ignoreSearchTab:true,});});if(effectiveProperty&&ownerRule)
arrowElement.title=WI.UIString("Option-click to show source");}
this.updateStatus();}
updateStatus()
{let duplicatePropertyExistsBelow=(cssProperty)=>{let propertyFound=false;for(let property of this._property.ownerStyle.enabledProperties){if(property===cssProperty)
propertyFound=true;else if(property.name===cssProperty.name&&propertyFound)
return true;}
return false;};let classNames=[WI.SpreadsheetStyleProperty.StyleClassName];let elementTitle="";if(this._property.overridden){if(!this._jumpToEffectivePropertyButton&&this._delegate&&this._delegate.spreadsheetStylePropertySelectByProperty&&WI.settings.experimentalEnableStylesJumpToEffective.value){if(this._property.overridingProperty){this._jumpToEffectivePropertyButton=WI.createGoToArrowButton();this._jumpToEffectivePropertyButton.classList.add("select-effective-property");this._jumpToEffectivePropertyButton.dataset.value=this._property.overridingProperty.rawValue;this._element.append(this._jumpToEffectivePropertyButton);this._jumpToEffectivePropertyButton.addEventListener("click",(event)=>{event.stop();this._delegate.spreadsheetStylePropertySelectByProperty(this._property.overridingProperty);});}}
classNames.push("overridden");if(duplicatePropertyExistsBelow(this._property)){classNames.push("has-warning");elementTitle=WI.UIString("Duplicate property");}}
if(this._property.implicit)
classNames.push("implicit");if(this._property.ownerStyle.inherited&&!this._property.inherited)
classNames.push("not-inherited");if(!this._property.valid&&this._property.hasOtherVendorNameOrKeyword())
classNames.push("other-vendor");else if(this._hasInvalidVariableValue||(!this._property.valid&&this._property.value!=="")){let propertyNameIsValid=false;if(WI.CSSCompletions.cssNameCompletions)
propertyNameIsValid=WI.CSSCompletions.cssNameCompletions.isValidPropertyName(this._property.name);classNames.push("has-warning");if(!propertyNameIsValid){classNames.push("invalid-name");elementTitle=WI.UIString("Unsupported property name");}else{classNames.push("invalid-value");elementTitle=WI.UIString("Unsupported property value");}}
if(!this._property.enabled)
classNames.push("disabled");if(this._property.modified&&this._property.name&&this._property.rawValue)
classNames.push("modified");if(this._selected)
classNames.push("selected");if(this._valueTextField&&this._valueTextField.value.includes("\n"))
classNames.push("has-newline");this._element.className=classNames.join(" ");this._element.title=elementTitle;}
applyFilter(filterText)
{let matchesName=this._nameElement.textContent.includes(filterText);this._nameElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName,!!matchesName);let matchesValue=this._valueElement.textContent.includes(filterText);this._valueElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName,!!matchesValue);let matches=matchesName||matchesValue;this._contentElement.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInPropertyClassName,!matches);return matches;}
additionalFunctionValueCompletionsProvider(functionName)
{switch(functionName){case"var":return Array.from(this._property.ownerStyle.nodeStyles.allCSSVariables);case"attr":return this._property.ownerStyle.node.attributes().map((attribute)=>attribute.name);}
return[];} 
spreadsheetTextFieldWillStartEditing(textField)
{let isEditingName=textField===this._nameTextField;textField.value=isEditingName?this._property.name:this._property.rawValue;}
spreadsheetTextFieldAllowsNewlines(textField)
{return textField===this._valueTextField;}
spreadsheetTextFieldDidChange(textField)
{if(textField===this._valueTextField)
this._handleValueChange();else if(textField===this._nameTextField)
this._handleNameChange();}
spreadsheetTextFieldDidCommit(textField,{direction})
{let willRemoveProperty=false;let isEditingName=textField===this._nameTextField;if(!this._property.name||(!this._property.rawValue&&!isEditingName&&direction==="forward"))
willRemoveProperty=true;if(!isEditingName&&!willRemoveProperty)
this._renderValue(this._property.rawValue);this._cssDocumentationPopover?.dismiss();if(direction==="forward"){if(isEditingName&&!willRemoveProperty){this._valueTextField.startEditing();return;}}else{if(!isEditingName){this._nameTextField.startEditing();return;}}
if(typeof this._delegate.spreadsheetStylePropertyFocusMoved==="function"){this._delegate.spreadsheetStylePropertyFocusMoved(this,{direction,willRemoveProperty});}
if(willRemoveProperty)
this.remove();}
spreadsheetTextFieldDidBlur(textField,event,changed)
{this._addCSSDocumentationButton();let focusedOutsideThisProperty=event.relatedTarget!==this._nameElement&&event.relatedTarget!==this._valueElement;if(focusedOutsideThisProperty&&(!this._nameTextField.value.trim()||!this._valueTextField.value.trim())){this.remove();return;}
if(textField===this._valueTextField)
this._renderValue(this._property.rawValue);if(typeof this._delegate.spreadsheetStylePropertyFocusMoved==="function")
this._delegate.spreadsheetStylePropertyFocusMoved(this,{direction:null});if(changed){let target=WI.assumingMainTarget();if(target.hasCommand("DOM.markUndoableState"))
target.DOMAgent.markUndoableState();}}
spreadsheetTextFieldDidBackspace(textField)
{if(textField===this._nameTextField)
this.spreadsheetTextFieldDidCommit(textField,{direction:"backward"});else if(textField===this._valueTextField)
this._nameTextField.startEditing();}
spreadsheetTextFieldDidPressEsc(textField,textBeforeEditing)
{let isNewProperty=!textBeforeEditing;if(isNewProperty)
this.remove();else if(this._delegate.spreadsheetStylePropertyDidPressEsc)
this._delegate.spreadsheetStylePropertyDidPressEsc(this);} 
willDismissPopover()
{this._valueElement.classList.remove(WI.Popover.IgnoreAutoDismissClassName);this._cssDocumentationPopover=null;} 
_toggle()
{this._property.commentOut(this.property.enabled);this.update();}
_select()
{if(this._delegate&&this._delegate.spreadsheetStylePropertySelect){let index=parseInt(this._element.dataset.propertyIndex);this._delegate.spreadsheetStylePropertySelect(index);}}
_isEditable()
{return!this._readOnly&&this._property.editable;}
_renderValue(value)
{this._hasInvalidVariableValue=false;const maxValueLength=150;let tokens=WI.tokenizeCSSValue(value);if(this._property.enabled&&!this._property.overridden&&this._property.valid&&!this._property.hasOtherVendorNameOrKeyword())
tokens=this._replaceSpecialTokens(tokens);tokens=tokens.map((token)=>{if(token instanceof Element)
return token;let className="";if(token.type){if(token.type.includes("string"))
className="token-string";else if(token.type.includes("link"))
className="token-link";else if(token.type.includes("comment"))
className="token-comment";}
if(className){let span=document.createElement("span");span.classList.add(className);span.textContent=token.value.truncateMiddle(maxValueLength);if(token.type&&token.type.includes("link"))
span.addEventListener("contextmenu",this._handleLinkContextMenu.bind(this,token));return span;}
return token.value;});this._valueElement.removeChildren();this._valueElement.append(...tokens);}
_addCSSDocumentationButton()
{if(this._hideDocumentation)
return;if(this._cssDocumentationButton){this._cssDocumentationButton.remove();this._cssDocumentationButton=null;}
if(this.property.isVariable)
return;if(!WI.CSSCompletions.cssNameCompletions.isValidPropertyName(this._property.name))
return;if(!CSSDocumentation.hasOwnProperty(this._property.name)&&!CSSDocumentation.hasOwnProperty(this._property.canonicalName))
return;this._cssDocumentationButton=this._contentElement.appendChild(document.createElement("button"));this._cssDocumentationButton.className="css-documentation-button";this._cssDocumentationButton.title=WI.UIString("Click to show documentation","Click to show documentation @ CSS Documentation Button","Tooltip to show purpose of the CSS documentation button");this._cssDocumentationButton.addEventListener("mousedown",this._handleCSSDocumentationButtonClicked.bind(this));}
_handleCSSDocumentationButtonClicked(event)
{if(event.button!==0)
return;if(this._valueTextField?.editing){event.stopPropagation();event.preventDefault();this._valueTextField.discardCompletion();}
this._presentCSSDocumentation();}
_presentCSSDocumentation()
{this._cssDocumentationPopover??=new WI.CSSDocumentationPopover(this._property,this);this._cssDocumentationPopover.show(this._nameElement);if(this._isEditable())
this._valueElement.classList.add(WI.Popover.IgnoreAutoDismissClassName);}
_createInlineSwatch(type,contents,valueObject)
{let tokenElement=document.createElement("span");let innerElement=document.createElement("span");for(let item of contents){if(item instanceof Node)
innerElement.appendChild(item);else if(typeof item==="object")
innerElement.append(item.value);else
innerElement.append(item);}
let readOnly=!this._isEditable();let swatch=new WI.InlineSwatch(type,valueObject,readOnly);swatch.addEventListener(WI.InlineSwatch.Event.ValueChanged,function(event){let value=event.data.value&&event.data.value.toString();if(!value)
return;innerElement.textContent=value;this._handleValueChange();if(type===WI.InlineSwatch.Type.Variable)
this._renderValue(this._property.rawValue);},this);if(type===WI.InlineSwatch.Type.Variable){swatch.value=()=>{return this._property.ownerStyle.nodeStyles.computedStyle.resolveVariableValue(innerElement.textContent);};}
if(this._delegate&&typeof this._delegate.stylePropertyInlineSwatchActivated==="function"){swatch.addEventListener(WI.InlineSwatch.Event.Activated,function(event){this._delegate.stylePropertyInlineSwatchActivated();},this);}
if(this._delegate&&typeof this._delegate.stylePropertyInlineSwatchDeactivated==="function"){swatch.addEventListener(WI.InlineSwatch.Event.Deactivated,function(event){this._delegate.stylePropertyInlineSwatchDeactivated();},this);}
tokenElement.append(swatch.element,innerElement);return tokenElement;}
_replaceSpecialTokens(tokens)
{if(this._property.name==="box-shadow")
return this._addBoxShadowTokens(tokens);if(this._property.isVariable||WI.CSSKeywordCompletions.isColorAwareProperty(this._property.name)){tokens=this._addGradientTokens(tokens);tokens=this._addColorTokens(tokens);}
if(this._property.isVariable||WI.CSSKeywordCompletions.isTimingFunctionAwareProperty(this._property.name)){tokens=this._addTimingFunctionTokens(tokens,"cubic-bezier");tokens=this._addTimingFunctionTokens(tokens,"spring");}
tokens=this._addVariableTokens(tokens);return tokens;}
_addGradientTokens(tokens)
{let gradientRegex=/^(repeating-)?(linear|radial)-gradient$/i;let newTokens=[];let gradientStartIndex=NaN;let openParenthesis=0;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(token.type&&token.type.includes("atom")&&gradientRegex.test(token.value)){gradientStartIndex=i;openParenthesis=0;}else if(token.value==="("&&!isNaN(gradientStartIndex))
openParenthesis++;else if(token.value===")"&&!isNaN(gradientStartIndex)){openParenthesis--;if(openParenthesis>0){continue;}
let rawTokens=tokens.slice(gradientStartIndex,i+1);let text=this._resolveVariables(rawTokens.map((token)=>token.value).join(""));rawTokens=this._addVariableTokens(rawTokens);let gradient=WI.Gradient.fromString(text);if(gradient)
newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Gradient,rawTokens,gradient));else
newTokens.pushAll(rawTokens);gradientStartIndex=NaN;}else if(isNaN(gradientStartIndex))
newTokens.push(token);}
return newTokens;}
_addColorTokens(tokens)
{let newTokens=[];let openParentheses=0;let pushPossibleColorToken=(text,...rawTokens)=>{let color=WI.Color.fromString(text);if(color)
newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Color,rawTokens,color));else
newTokens.pushAll(rawTokens);};let colorFunctionStartIndex=NaN;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(token.type&&token.type.includes("hex-color")){ pushPossibleColorToken(token.value,token);}else if(WI.Color.FunctionNames.has(token.value)&&token.type&&(token.type.includes("atom")||token.type.includes("keyword"))){ colorFunctionStartIndex=i;}else if(isNaN(colorFunctionStartIndex)&&token.type&&(token.type.includes("atom")||token.type.includes("keyword"))){ pushPossibleColorToken(token.value,token);}else if(!isNaN(colorFunctionStartIndex)){if(token.value==="("){++openParentheses;continue;}
if(token.value!==")")
continue;if(--openParentheses)
continue;let rawTokens=tokens.slice(colorFunctionStartIndex,i+1);let text=this._resolveVariables(rawTokens.map((token)=>token.value).join(""));rawTokens=this._addVariableTokens(rawTokens);pushPossibleColorToken(text,...rawTokens);colorFunctionStartIndex=NaN;}else
newTokens.push(token);}
return newTokens;}
_addTimingFunctionTokens(tokens,tokenType)
{let newTokens=[];let startIndex=NaN;let openParenthesis=0;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(token.value===tokenType&&token.type&&token.type.includes("atom")){startIndex=i;openParenthesis=0;}else if(token.value==="("&&!isNaN(startIndex))
openParenthesis++;else if(token.value===")"&&!isNaN(startIndex)){openParenthesis--;if(openParenthesis>0)
continue;let rawTokens=tokens.slice(startIndex,i+1);let text=this._resolveVariables(rawTokens.map((token)=>token.value).join(""));rawTokens=this._addVariableTokens(rawTokens);let valueObject;let inlineSwatchType;if(tokenType==="cubic-bezier"){valueObject=WI.CubicBezier.fromString(text);inlineSwatchType=WI.InlineSwatch.Type.Bezier;}else if(tokenType==="spring"){valueObject=WI.Spring.fromString(text);inlineSwatchType=WI.InlineSwatch.Type.Spring;}
if(valueObject)
newTokens.push(this._createInlineSwatch(inlineSwatchType,rawTokens,valueObject));else
newTokens.pushAll(rawTokens);startIndex=NaN;}else if(token.value in WI.CubicBezier.keywordValues)
newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Bezier,[token],WI.CubicBezier.fromString(token.value)));else if(isNaN(startIndex))
newTokens.push(token);}
return newTokens;}
_addBoxShadowTokens(tokens)
{let newTokens=[];let startIndex=0;let openParentheses=0;for(let i=0;i<=tokens.length;i++){let token=tokens[i];if(i===tokens.length||(token.value===","&&!openParentheses)){let rawTokens=tokens.slice(startIndex,i);let firstNonWhitespaceIndex=Infinity;let lastNonWhitespaceIndex=0;for(let j=0;j<rawTokens.length;++j){if(/\s/.test(rawTokens[j].value))
continue;firstNonWhitespaceIndex=Math.min(firstNonWhitespaceIndex,j);lastNonWhitespaceIndex=Math.max(lastNonWhitespaceIndex,j);}
let nonWhitespaceTokens=rawTokens.slice(firstNonWhitespaceIndex,lastNonWhitespaceIndex+1);newTokens.pushAll(rawTokens.slice(0,firstNonWhitespaceIndex));let text=this._resolveVariables(nonWhitespaceTokens.map((rawToken)=>rawToken.value).join(""));nonWhitespaceTokens=this._addVariableTokens(nonWhitespaceTokens);let boxShadow=WI.BoxShadow.fromString(text);if(boxShadow)
newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.BoxShadow,nonWhitespaceTokens,boxShadow));else
newTokens.pushAll(nonWhitespaceTokens);newTokens.pushAll(rawTokens.slice(lastNonWhitespaceIndex+1));if(token)
newTokens.push(token);startIndex=i+1;continue;}
if(token.value==="("){++openParentheses;continue;}
if(token.value===")"){--openParentheses;continue;}}
return newTokens;}
_addVariableTokens(tokens)
{let newTokens=[];let startIndex=NaN;let openParenthesis=0;for(let i=0;i<tokens.length;i++){let token=tokens[i];if(token.value==="var"&&token.type&&token.type.includes("atom")){if(isNaN(startIndex)){startIndex=i;openParenthesis=0;}}else if(token.value==="("&&!isNaN(startIndex))
++openParenthesis;else if(token.value===")"&&!isNaN(startIndex)){--openParenthesis;if(openParenthesis>0)
continue;let rawTokens=tokens.slice(startIndex,i+1);let variableNameIndex=rawTokens.findIndex((token)=>token.value.startsWith("--")&&/\bvariable-2\b/.test(token.type));if(variableNameIndex!==-1){let contents=rawTokens.slice(0,variableNameIndex+1);if(WI.settings.experimentalEnableStylesJumpToVariableDeclaration.value&&this._property.ownerStyle.type!==WI.CSSStyleDeclaration.Type.Computed&&this._delegate&&this._delegate.spreadsheetStylePropertySelectByProperty){const dontCreateIfMissing=true;let effectiveVariableProperty=this._property.ownerStyle.nodeStyles.effectivePropertyForName(rawTokens[variableNameIndex].value,dontCreateIfMissing);if(effectiveVariableProperty){let arrowElement=WI.createGoToArrowButton();arrowElement.classList.add("select-variable-property");arrowElement.title=WI.UIString("Go to variable");arrowElement.addEventListener("click",(event)=>{event.stop();this._delegate.spreadsheetStylePropertySelectByProperty(effectiveVariableProperty);});contents.push(arrowElement);}}
let fallbackStartIndex=rawTokens.findIndex((value,i)=>i>variableNameIndex+1&&/\bm-css\b/.test(value.type));if(fallbackStartIndex!==-1){contents.pushAll(rawTokens.slice(variableNameIndex+1,fallbackStartIndex));let fallbackTokens=rawTokens.slice(fallbackStartIndex);fallbackTokens=this._addBoxShadowTokens(fallbackTokens);fallbackTokens=this._addGradientTokens(fallbackTokens);fallbackTokens=this._addColorTokens(fallbackTokens);fallbackTokens=this._addTimingFunctionTokens(fallbackTokens,"cubic-bezier");fallbackTokens=this._addTimingFunctionTokens(fallbackTokens,"spring");fallbackTokens=this._addVariableTokens(fallbackTokens);contents.pushAll(fallbackTokens);}else
contents.pushAll(rawTokens.slice(variableNameIndex+1));let text=rawTokens.reduce((accumulator,token)=>accumulator+token.value,"");if(this._property.ownerStyle.nodeStyles.computedStyle.resolveVariableValue(text))
newTokens.push(this._createInlineSwatch(WI.InlineSwatch.Type.Variable,contents));else
newTokens.pushAll(contents);}else{this._hasInvalidVariableValue=true;newTokens.pushAll(rawTokens);}
startIndex=NaN;}else if(isNaN(startIndex))
newTokens.push(token);}
return newTokens;}
_resolveVariables(cssText)
{return cssText.replace(/var\(--[^\)]+\)/g,(match)=>this._property.ownerStyle.nodeStyles.computedStyle.resolveVariableValue(match)||match);}
_handleNameChange()
{this._property.name=this._nameElement.textContent.trim();}
_handleValueChange()
{let value=this._valueElement.textContent;this._property.rawValue=value.trim();this._element.classList.toggle("has-newline",value.includes("\n"));}
_handleNameBeforeInput(event)
{if(event.data!==":"||event.inputType!=="insertText")
return;event.preventDefault();this._nameTextField.discardCompletion();this._valueTextField.startEditing();}
_handleNamePaste(event)
{let text=event.clipboardData.getData("text/plain");if(!text||!text.includes(":"))
return;event.preventDefault();this.remove(text);if(this._delegate.spreadsheetStylePropertyAddBlankPropertySoon){this._delegate.spreadsheetStylePropertyAddBlankPropertySoon(this,{index:parseInt(this._element.dataset.propertyIndex)+1,});}}
_nameCompletionDataProvider(text,{allowEmptyPrefix}={})
{return WI.CSSKeywordCompletions.forPartialPropertyName(text,{allowEmptyPrefix});}
_handleValueBeforeInput(event)
{if(event.data!==";"||event.inputType!=="insertText")
return;let text=this._valueTextField.valueWithoutSuggestion();let selection=window.getSelection();if(!selection.rangeCount||selection.getRangeAt(0).endOffset!==text.length)
return;let unbalancedCharacters=WI.CSSCompletions.completeUnbalancedValue(text);if(unbalancedCharacters)
return;event.preventDefault();this._valueTextField.stopEditing();this.spreadsheetTextFieldDidCommit(this._valueTextField,{direction:"forward"});}
_valueCompletionDataProvider(text,{allowEmptyPrefix}={})
{return WI.CSSKeywordCompletions.forPartialPropertyValue(text,this._nameElement.textContent.trim(),{additionalFunctionValueCompletionsProvider:this.additionalFunctionValueCompletionsProvider.bind(this)});}
_setupJumpToSymbol(element)
{element.addEventListener("mousedown",(event)=>{if(event.button!==0)
return;if(!WI.modifierKeys.metaKey)
return;if(element.isContentEditable)
return;let sourceCodeLocation=null;if(this._property.ownerStyle.ownerRule)
sourceCodeLocation=this._property.ownerStyle.ownerRule.sourceCodeLocation;if(!sourceCodeLocation)
return;let range=this._property.styleSheetTextRange;const options={ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,};let sourceCode=sourceCodeLocation.sourceCode;WI.showSourceCodeLocation(sourceCode.createSourceCodeLocation(range.startLine,range.startColumn),options);});}
_handleLinkContextMenu(token,event)
{let contextMenu=WI.ContextMenu.createFromEvent(event);let resolveURL=(url)=>{let ownerStyle=this._property.ownerStyle;if(!ownerStyle)
return url;let ownerStyleSheet=ownerStyle.ownerStyleSheet;if(!ownerStyleSheet){let ownerRule=ownerStyle.ownerRule;if(ownerRule)
ownerStyleSheet=ownerRule.ownerStyleSheet;}
if(ownerStyleSheet){if(ownerStyleSheet.url)
return absoluteURL(url,ownerStyleSheet.url);let parentFrame=ownerStyleSheet.parentFrame;if(parentFrame)
return absoluteURL(url,parentFrame.url);}
let node=ownerStyle.node;if(!node){let nodeStyles=ownerStyle.nodeStyles;if(!nodeStyles){let ownerRule=ownerStyle.ownerRule;if(ownerRule)
nodeStyles=ownerRule.nodeStyles;}
if(nodeStyles)
node=nodeStyles.node;}
if(node){let ownerDocument=node.ownerDocument;if(ownerDocument)
return absoluteURL(url,node.ownerDocument.documentURL);}
return url;};WI.appendContextMenuItemsForURL(contextMenu,resolveURL(token.value));}};WI.SpreadsheetStyleProperty.StyleClassName="property";WI.SpreadsheetTextField=class SpreadsheetTextField
{constructor(delegate,element,completionProvider)
{this._delegate=delegate;this._element=element;this._completionProvider=completionProvider||null;if(this._completionProvider){this._suggestionHintElement=document.createElement("span");this._suggestionHintElement.contentEditable=false;this._suggestionHintElement.classList.add("completion-hint");this._suggestionsView=new WI.CompletionSuggestionsView(this,{preventBlur:true});}
this._element.classList.add("spreadsheet-text-field");this._element.addEventListener("mousedown",this._handleMouseDown.bind(this),true);this._element.addEventListener("click",this._handleClick.bind(this));this._element.addEventListener("blur",this._handleBlur.bind(this));this._element.addEventListener("keydown",this._handleKeyDown.bind(this));this._element.addEventListener("input",this._handleInput.bind(this));this._editing=false;this._valueBeforeEditing="";this._completionPrefix="";this._controlSpaceKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,WI.KeyboardShortcut.Key.Space);} 
get element(){return this._element;}
get editing(){return this._editing;}
get value(){return this._element.textContent;}
set value(value){this._element.textContent=value;}
valueWithoutSuggestion()
{let value=this._element.textContent;return value.slice(0,value.length-this.suggestionHint.length);}
get suggestionHint()
{return this._suggestionHintElement.textContent;}
set suggestionHint(value)
{this._suggestionHintElement.textContent=value;if(value)
this._reAttachSuggestionHint();else
this._suggestionHintElement.remove();}
startEditing()
{if(this._editing)
return;if(this._delegate&&typeof this._delegate.spreadsheetTextFieldWillStartEditing==="function")
this._delegate.spreadsheetTextFieldWillStartEditing(this);this._editing=true;this._valueBeforeEditing=this.value;this._element.classList.add("editing");this._element.contentEditable="plaintext-only";this._element.spellcheck=false;this._element.scrollIntoViewIfNeeded(false);this._element.focus();this._selectText();this._updateCompletions();}
stopEditing()
{if(!this._editing)
return;this._editing=false;this._valueBeforeEditing="";this._element.classList.remove("editing");this._element.contentEditable=false;this.discardCompletion();}
discardCompletion()
{if(!this._completionProvider)
return;this._suggestionsView.hide();let hadSuggestionHint=!!this.suggestionHint;this.suggestionHint="";if(hadSuggestionHint&&this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}
detached()
{this.discardCompletion();this._element.remove();} 
completionSuggestionsSelectedCompletion(suggestionsView,selectedText="")
{this.suggestionHint=selectedText.slice(this._completionPrefix.length);this._reAttachSuggestionHint();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}
completionSuggestionsClickedCompletion(suggestionsView,selectedText)
{




 let prefix=this.valueWithoutSuggestion();let newPrefix=prefix.slice(0,-this._completionPrefix.length);this._element.textContent=newPrefix+selectedText;window.getSelection().setBaseAndExtent(this._element,selectedText.length,this._element,selectedText.length);this.discardCompletion();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);} 
_selectText()
{window.getSelection().selectAllChildren(this._element);}
_discardChange()
{if(this._valueBeforeEditing!==this.value){this.value=this._valueBeforeEditing;if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}}
_handleClick(event)
{this.startEditing();}
_handleMouseDown(event)
{if(this._editing)
event.stopPropagation();}
_handleBlur(event)
{if(!this._editing)
return;if(document.activeElement===this._element)
return;this._applyCompletionHint();this.discardCompletion();let changed=this._valueBeforeEditing!==this.value;this._delegate.spreadsheetTextFieldDidBlur(this,event,changed);this.stopEditing();}
_handleKeyDown(event)
{if(!this._editing)
return;if(this._suggestionsView){let consumed=this._handleKeyDownForSuggestionView(event);if(consumed)
return;}
let isEnterKey=event.key==="Enter";if(isEnterKey&&event.shiftKey){if(this._delegate&&this._delegate.spreadsheetTextFieldAllowsNewlines(this))
return;}
let isTabKey=event.key==="Tab";if(isEnterKey||isTabKey){event.stop();this._applyCompletionHint();let direction=(isTabKey&&event.shiftKey)?"backward":"forward";if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidCommit==="function")
this._delegate.spreadsheetTextFieldDidCommit(this,{direction});this.stopEditing();return;}
if(event.key==="ArrowUp"||event.key==="ArrowDown"){let delta=1;if(event.metaKey)
delta=100;else if(event.shiftKey)
delta=10;else if(event.altKey)
delta=0.1;if(event.key==="ArrowDown")
delta=-delta;let didModify=WI.incrementElementValue(this._element,delta);if(!didModify)
return;event.stop();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}
if(event.key==="Backspace"){if(!this.value){event.stop();this.stopEditing();if(this._delegate&&this._delegate.spreadsheetTextFieldDidBackspace)
this._delegate.spreadsheetTextFieldDidBackspace(this);return;}}
if(this._controlSpaceKeyboardShortcut.matchesEvent(event)){event.stop();if(this._suggestionsView.visible)
this._suggestionsView.hide();else{const forceCompletions=true;this._updateCompletions(forceCompletions);}
return;}
if(event.key==="Escape"){event.stop();this._discardChange();window.getSelection().removeAllRanges();if(this._delegate&&this._delegate.spreadsheetTextFieldDidPressEsc)
this._delegate.spreadsheetTextFieldDidPressEsc(this,this._valueBeforeEditing);}}
_handleKeyDownForSuggestionView(event)
{if((event.key==="ArrowDown"||event.key==="ArrowUp")&&this._suggestionsView.visible){event.stop();if(event.key==="ArrowDown")
this._suggestionsView.selectNext();else
this._suggestionsView.selectPrevious();this._showSuggestionsView();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);return true;}
if(event.key==="ArrowRight"&&this.suggestionHint){let selection=window.getSelection();if(selection.isCollapsed&&(selection.focusOffset===this.valueWithoutSuggestion().length||selection.focusNode===this._suggestionHintElement)){event.stop();document.execCommand("insertText",false,this.suggestionHint);this._updateCompletions();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);return true;}}
if(event.key==="Escape"&&this._suggestionsView.visible){event.stop();let willChange=!!this.suggestionHint;this.discardCompletion();if(willChange&&this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);return true;}
if(event.key==="ArrowLeft"&&(this.suggestionHint||this._suggestionsView.visible)){this.discardCompletion();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}
return false;}
_handleInput(event)
{if(!this._editing)
return;this._updateCompletions();if(this._delegate&&typeof this._delegate.spreadsheetTextFieldDidChange==="function")
this._delegate.spreadsheetTextFieldDidChange(this);}
_updateCompletions(forceCompletions=false)
{if(!this._completionProvider)
return;let valueWithoutSuggestion=this.valueWithoutSuggestion();let{completions,prefix}=this._completionProvider(valueWithoutSuggestion,{allowEmptyPrefix:forceCompletions});this._completionPrefix=prefix;if(!completions.length){this.discardCompletion();return;}
if(completions.length===1&&completions[0]===valueWithoutSuggestion){this.discardCompletion();return;}
if(!this._element.isConnected){this._suggestionsView.hide();return;}
this._suggestionsView.update(completions);if(completions.length===1){this._suggestionsView.hide();}else
this._showSuggestionsView();this._suggestionsView.selectedIndex=NaN;if(this._completionPrefix){this._suggestionsView.selectNext();}else
this.suggestionHint="";}
_showSuggestionsView()
{let prefix=this.valueWithoutSuggestion();let startOffset=prefix.length-this._completionPrefix.length;let caretRect=this._getCaretRect(startOffset);if(!caretRect)
this._suggestionsView.hide();else{this._suggestionsView.show(caretRect);this._suggestionsView.hideWhenElementMoves(this._element);}}
_getCaretRect(startOffset)
{let selection=window.getSelection();let isHidden=(clientRect)=>{return clientRect.x===0&&clientRect.y===0;};if(selection.rangeCount){let range=selection.getRangeAt(0).cloneRange();range.setStart(range.startContainer,startOffset);let clientRect=range.getBoundingClientRect();if(!isHidden(clientRect)){
return WI.Rect.rectFromClientRect(clientRect);}}
let clientRect=this._element.getBoundingClientRect();if(isHidden(clientRect))
return null;const leftPadding=parseInt(getComputedStyle(this._element).paddingLeft)||0;return new WI.Rect(clientRect.left+leftPadding,clientRect.top,clientRect.width,clientRect.height);}
_applyCompletionHint()
{if(!this._completionProvider||!this.suggestionHint)
return;this._element.textContent=this._element.textContent;}
_reAttachSuggestionHint()
{if(this._suggestionHintElement.parentElement===this._element)
return;this._element.append(this._suggestionHintElement);}};WI.StyleOriginView=class StyleOriginView
{constructor()
{this.element=document.createElement("span");this.element.className="origin";} 
update(style)
{this.element.removeChildren();this.element.removeAttribute("title");switch(style.type){case WI.CSSStyleDeclaration.Type.Rule:if(style.ownerRule.sourceCodeLocation){let options={dontFloat:true,ignoreNetworkTab:true,ignoreSearchTab:true,};if(style.ownerStyleSheet.isInspectorStyleSheet()){options.nameStyle=WI.SourceCodeLocation.NameStyle.None;options.prefix=WI.UIString("Inspector Style Sheet")+":";}
let sourceCodeLink=WI.createSourceCodeLocationLink(style.ownerRule.sourceCodeLocation,options);this.element.appendChild(sourceCodeLink);}else{let originString="";switch(style.ownerRule.type){case WI.CSSStyleSheet.Type.Author:originString=WI.UIString("Author Style Sheet");break;case WI.CSSStyleSheet.Type.User:originString=WI.UIString("User Style Sheet");break;case WI.CSSStyleSheet.Type.UserAgent:originString=WI.UIString("User Agent Style Sheet");break;case WI.CSSStyleSheet.Type.Inspector:originString=WI.UIString("Web Inspector");break;}
if(originString)
this.element.append(originString);if(!style.editable){let styleTitle="";if(style.ownerRule&&style.ownerRule.type===WI.CSSStyleSheet.Type.UserAgent)
styleTitle=WI.UIString("User Agent Style Sheet");else
styleTitle=WI.UIString("Style rule");this.element.title=WI.UIString("%s cannot be modified").format(styleTitle);}}
break;case WI.CSSStyleDeclaration.Type.Attribute:this.element.append(WI.UIString("HTML Attributes"));break;}}};WI.SpringEditor=class SpringEditor extends WI.Object
{constructor()
{super();let boundResetPreviewAnimation=(event)=>{this._resetPreviewAnimation(event);};this._element=document.createElement("div");this._element.classList.add("spring-editor");this._previewContainer=this._element.createChild("div","spring-preview");this._previewContainer.title=WI.UIString("Restart animation");this._previewContainer.addEventListener("mousedown",boundResetPreviewAnimation);this._previewElement=this._previewContainer.createChild("div");this._previewElement.addEventListener("transitionend",boundResetPreviewAnimation);this._timingContainer=this._element.createChild("div","spring-timing");this._timingElement=this._timingContainer.createChild("div");this._numberInputContainer=this._element.createChild("div","number-input-container");function createInputsForParameter(id,title)
{let row=this._numberInputContainer.createChild("div",`number-input-row ${id}`);row.createChild("div","number-input-row-title").textContent=title;let sliderKey=`_${id}Slider`;this[sliderKey]=row.createChild("input");this[sliderKey].type="range";this[sliderKey].addEventListener("input",this._handleNumberSliderInput.bind(this));this[sliderKey].addEventListener("mousedown",this._handleNumberSliderMousedown.bind(this));this[sliderKey].addEventListener("mouseup",this._handleNumberSliderMouseup.bind(this));let inputKey=`_${id}Input`;this[inputKey]=row.createChild("input");this[inputKey].type="number";this[inputKey].addEventListener("input",this._handleNumberInputInput.bind(this));this[inputKey].addEventListener("keydown",this._handleNumberInputKeydown.bind(this));}
createInputsForParameter.call(this,"mass",WI.UIString("Mass"));this._massInput.min=this._massSlider.min=1;createInputsForParameter.call(this,"stiffness",WI.UIString("Stiffness"));this._stiffnessInput.min=this._stiffnessSlider.min=1;createInputsForParameter.call(this,"damping",WI.UIString("Damping"));this._dampingInput.min=this._dampingSlider.min=0;createInputsForParameter.call(this,"initialVelocity",WI.UIString("Initial Velocity"));this._spring=new WI.Spring(1,100,10,0);} 
get element()
{return this._element;}
get spring()
{return this._spring;}
set spring(spring)
{if(!spring)
return;let isSpring=spring instanceof WI.Spring;if(!isSpring)
return;this._spring=spring;this._massInput.value=this._massSlider.value=this._spring.mass;this._stiffnessInput.value=this._stiffnessSlider.value=this._spring.stiffness;this._dampingInput.value=this._dampingSlider.value=this._spring.damping;this._initialVelocityInput.value=this._initialVelocitySlider.value=this._spring.initialVelocity;this._resetPreviewAnimation();} 
_handleNumberInputInput(event)
{this._changeSpringForInput(event.target,event.target.value);}
_handleNumberInputKeydown(event)
{let shift=0;if(event.keyIdentifier==="Up")
shift=1;else if(event.keyIdentifier==="Down")
shift=-1;if(!shift)
return;if(event.shiftKey)
shift*=10;else if(event.altKey)
shift/=10;let value=parseFloat(event.target.value)||0;this._changeSpringForInput(event.target,value+shift);event.preventDefault();}
_handleNumberSliderInput(event)
{this._changeSpringForInput(event.target,event.target.value);}
_handleNumberSliderMousedown(event)
{this._changeSpringForInput(event.target,event.target.value);}
_handleNumberSliderMouseup(event)
{this._changeSpringForInput(event.target,event.target.value);}
_changeSpringForInput(target,value)
{value=parseFloat(value)||0;switch(target){case this._massInput:case this._massSlider:if(this._spring.mass===value)
return;this._spring.mass=Math.max(1,value);this._massInput.value=this._massSlider.value=this._spring.mass.maxDecimals(3);break;case this._stiffnessInput:case this._stiffnessSlider:if(this._spring.stiffness===value)
return;this._spring.stiffness=Math.max(1,value);this._stiffnessInput.value=this._stiffnessSlider.value=this._spring.stiffness.maxDecimals(3);break;case this._dampingInput:case this._dampingSlider:if(this._spring.damping===value)
return;this._spring.damping=Math.max(0,value);this._dampingInput.value=this._dampingSlider.value=this._spring.damping.maxDecimals(3);break;case this._initialVelocityInput:case this._initialVelocitySlider:if(this._spring.initialVelocity===value)
return;this._spring.initialVelocity=value;this._initialVelocityInput.value=this._initialVelocitySlider.value=this._spring.initialVelocity.maxDecimals(3);break;default:WI.reportInternalError("Input event fired for unrecognized element");return;}
this.dispatchEventToListeners(WI.SpringEditor.Event.SpringChanged,{spring:this._spring});this._resetPreviewAnimation();}
_resetPreviewAnimation(event)
{this._previewContainer.classList.remove("animate");this._previewElement.style.transitionTimingFunction=null;this._previewElement.style.transform=null;this._timingContainer.classList.remove("animate");this._timingElement.style.transform=null;if(!event)
this._timingContainer.dataset.duration="0";this._updatePreviewAnimation(event);}
_updatePreviewAnimation(event)
{this._previewContainer.classList.add("animate");this._previewElement.style.transitionTimingFunction=this._spring.toString();this._timingContainer.classList.add("animate");if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL){this._previewElement.style.transform="translateX(-85px)";this._timingElement.style.transform="translateX(-170px)";}else{this._previewElement.style.transform="translateX(85px)";this._timingElement.style.transform="translateX(170px)";}
if(!event){let duration=this._spring.calculateDuration();this._timingContainer.dataset.duration=duration.toFixed(2);this._timingElement.style.transitionDuration=`${duration}s`;this._previewElement.style.transitionDuration=`${duration}s`;}}};WI.SpringEditor.Event={SpringChanged:"spring-editor-spring-changed"};WI.StackTraceView=class StackTraceView extends WI.Object
{constructor(stackTrace)
{super();var element=this._element=document.createElement("div");element.classList.add("stack-trace");for(var callFrame of stackTrace.callFrames){if(!callFrame.sourceCodeLocation&&callFrame.functionName===null)
continue;if(callFrame.isConsoleEvaluation&&!WI.settings.debugShowConsoleEvaluations.value)
continue;let callFrameElement=new WI.CallFrameView(callFrame,{showFunctionName:true,indicateIfBlackboxed:true});element.appendChild(callFrameElement);}}
get element()
{return this._element;}};





WI.StackedAreaChart=class StackedAreaChart extends WI.View
{constructor()
{super();this.element.classList.add("stacked-area-chart");this._chartElement=this.element.appendChild(createSVGElement("svg"));this._chartElement.setAttribute("preserveAspectRatio","none");this._pathElements=[];this._circleElements=[];this._points=[];this._markers=[];this._size=null;} 
get size()
{return this._size;}
set size(size)
{if(this._size&&this._size.equals(size))
return;this._size=size;this._chartElement.setAttribute("viewBox",`0 0 ${size.width} ${size.height}`);this.needsLayout();}
initializeSections(sectionClassNames)
{sectionClassNames.reverse();for(let i=0;i<sectionClassNames.length;++i){let pathElement=this._chartElement.appendChild(createSVGElement("path"));pathElement.classList.add(sectionClassNames[i]);this._pathElements.push(pathElement);}
this._pathElements.reverse();}
addPointSet(x,ys)
{this._points.push({x,ys});}
clearPoints()
{this._points=[];}
addPointMarker(x,y)
{this._markers.push({x,y});}
clearPointMarkers()
{this._markers=[];}
clear()
{this.clearPoints();this.clearPointMarkers();} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;if(!this._size)
return;let pathComponents=[];let length=this._pathElements.length;for(let i=0;i<length;++i)
pathComponents[i]=[`M 0 ${this._size.height}`];for(let{x,ys}of this._points){for(let i=0;i<length;++i)
pathComponents[i].push(`L ${x} ${ys[i]}`);}
let lastX=this._points.length?this._points.lastValue.x:0;for(let i=0;i<length;++i){pathComponents[i].push(`L ${lastX} ${this._size.height}`);pathComponents[i].push("Z");let pathString=pathComponents[i].join(" ");this._pathElements[i].setAttribute("d",pathString);}
if(this._circleElements.length){for(let circle of this._circleElements)
circle.remove();this._circleElements=[];}
if(this._markers.length){for(let{x,y}of this._markers){let circle=this._chartElement.appendChild(createSVGElement("circle"));this._circleElements.push(circle);circle.setAttribute("cx",x);circle.setAttribute("cy",y);circle.setAttribute("r",3);}}}};


WI.StackedColumnChart=class StackedColumnChart extends WI.View
{constructor(size)
{super();this.element.classList.add("stacked-column-chart");this._svgElement=this.element.appendChild(createSVGElement("svg"));this._svgElement.setAttribute("preserveAspectRatio","none");this._sections=null;this._columns=[];this.size=size;} 
get size()
{return this._size;}
set size(size)
{this._size=size;this._svgElement.setAttribute("viewBox",`0 0 ${size.width} ${size.height}`);}
initializeSections(sectionClassNames)
{this._sections=sectionClassNames;}
addColumnSet(x,totalHeight,width,heights,additionalClass)
{this._columns.push({x,totalHeight,width,heights,additionalClass});}
clear()
{this._columns=[];} 
layout()
{super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize)
return;this._svgElement.removeChildren();for(let{x,totalHeight,width,heights,additionalClass}of this._columns){for(let i=heights.length-1;i>=0;--i){let height=heights[i];if(height===heights[i-1])
continue;let y=totalHeight-height;let rect=this._svgElement.appendChild(createSVGElement("rect"));rect.classList.add(this._sections[i]);if(additionalClass)
rect.classList.add(additionalClass);rect.setAttribute("width",width);rect.setAttribute("height",height);rect.setAttribute("x",x);rect.setAttribute("y",y);}}}};WI.StorageSidebarPanel=class StorageSidebarPanel extends WI.NavigationSidebarPanel
{constructor()
{super("storage",WI.UIString("Storage"));this._navigationBar=new WI.NavigationBar;this.addSubview(this._navigationBar);var scopeItemPrefix="storage-sidebar-";var scopeBarItems=[];scopeBarItems.push(new WI.ScopeBarItem(scopeItemPrefix+"type-all",WI.UIString("All Storage"),{exclusive:true}));var storageTypes=[{identifier:"application-cache",title:WI.UIString("Application Cache"),classes:[WI.ApplicationCacheFrameTreeElement,WI.ApplicationCacheManifestTreeElement]},{identifier:"cookies",title:WI.UIString("Cookies"),classes:[WI.CookieStorageTreeElement]},{identifier:"database",title:WI.UIString("Databases"),classes:[WI.DatabaseHostTreeElement,WI.DatabaseTableTreeElement,WI.DatabaseTreeElement]},{identifier:"indexed-database",title:WI.UIString("Indexed Databases"),classes:[WI.IndexedDatabaseHostTreeElement,WI.IndexedDatabaseObjectStoreTreeElement,WI.IndexedDatabaseTreeElement]},{identifier:"local-storage",title:WI.UIString("Local Storage"),classes:[WI.DOMStorageTreeElement],localStorage:true},{identifier:"session-storage",title:WI.UIString("Session Storage"),classes:[WI.DOMStorageTreeElement],localStorage:false}];storageTypes.sort(function(a,b){return a.title.extendedLocaleCompare(b.title);});for(var info of storageTypes){var scopeBarItem=new WI.ScopeBarItem(scopeItemPrefix+info.identifier,info.title);scopeBarItem.__storageTypeInfo=info;scopeBarItems.push(scopeBarItem);}
this._scopeBar=new WI.ScopeBar("storage-sidebar-scope-bar",scopeBarItems,scopeBarItems[0],true);this._scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectionDidChange,this);this._navigationBar.addNavigationItem(this._scopeBar);this._localStorageRootTreeElement=null;this._sessionStorageRootTreeElement=null;this._databaseRootTreeElement=null;this._databaseHostTreeElementMap=new Map;this._indexedDatabaseRootTreeElement=null;this._indexedDatabaseHostTreeElementMap=new Map;this._cookieStorageRootTreeElement=null;this._applicationCacheRootTreeElement=null;this._applicationCacheURLTreeElementMap=new Map;WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.CookieStorageObjectWasAdded,this._cookieStorageObjectWasAdded,this);WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasAdded,this._domStorageObjectWasAdded,this);WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasInspected,this._domStorageObjectWasInspected,this);WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.Cleared,this._domStorageCleared,this);WI.databaseManager.addEventListener(WI.DatabaseManager.Event.DatabaseWasAdded,this._databaseWasAdded,this);WI.databaseManager.addEventListener(WI.DatabaseManager.Event.DatabaseWasInspected,this._databaseWasInspected,this);WI.databaseManager.addEventListener(WI.DatabaseManager.Event.Cleared,this._databaseCleared,this);WI.indexedDBManager.addEventListener(WI.IndexedDBManager.Event.IndexedDatabaseWasAdded,this._indexedDatabaseWasAdded,this);WI.indexedDBManager.addEventListener(WI.IndexedDBManager.Event.Cleared,this._indexedDatabaseCleared,this);WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.FrameManifestAdded,this._frameManifestAdded,this);WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.FrameManifestRemoved,this._frameManifestRemoved,this);WI.applicationCacheManager.addEventListener(WI.ApplicationCacheManager.Event.Cleared,this._applicationCacheCleared,this);this.contentTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);for(var domStorageObject of WI.domStorageManager.domStorageObjects)
this._addDOMStorageObject(domStorageObject);for(var cookieStorageObject of WI.domStorageManager.cookieStorageObjects)
this._addCookieStorageObject(cookieStorageObject);for(var database of WI.databaseManager.databases)
this._addDatabase(database);for(var indexedDatabase of WI.indexedDBManager.indexedDatabases)
this._addIndexedDatabase(indexedDatabase);for(var applicationCacheObject of WI.applicationCacheManager.applicationCacheObjects)
this._addFrameManifest(applicationCacheObject);} 
get minimumWidth()
{return this._navigationBar.minimumWidth;}
showDefaultContentView()
{}
closed()
{super.closed();WI.domStorageManager.removeEventListener(WI.DOMStorageManager.Event.CookieStorageObjectWasAdded,this._cookieStorageObjectWasAdded,this);WI.domStorageManager.removeEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasAdded,this._domStorageObjectWasAdded,this);WI.domStorageManager.removeEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasInspected,this._domStorageObjectWasInspected,this);WI.domStorageManager.removeEventListener(WI.DOMStorageManager.Event.Cleared,this._domStorageCleared,this);WI.databaseManager.removeEventListener(WI.DatabaseManager.Event.DatabaseWasAdded,this._databaseWasAdded,this);WI.databaseManager.removeEventListener(WI.DatabaseManager.Event.DatabaseWasInspected,this._databaseWasInspected,this);WI.databaseManager.removeEventListener(WI.DatabaseManager.Event.Cleared,this._databaseCleared,this);WI.indexedDBManager.removeEventListener(WI.IndexedDBManager.Event.IndexedDatabaseWasAdded,this._indexedDatabaseWasAdded,this);WI.indexedDBManager.removeEventListener(WI.IndexedDBManager.Event.Cleared,this._indexedDatabaseCleared,this);WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.FrameManifestAdded,this._frameManifestAdded,this);WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.FrameManifestRemoved,this._frameManifestRemoved,this);WI.applicationCacheManager.removeEventListener(WI.ApplicationCacheManager.Event.Cleared,this._applicationCacheCleared,this);} 
resetFilter()
{this._scopeBar.resetToDefault();super.resetFilter();}
hasCustomFilters()
{var selectedScopeBarItem=this._scopeBar.selectedItems[0];return selectedScopeBarItem&&!selectedScopeBarItem.exclusive;}
matchTreeElementAgainstCustomFilters(treeElement,flags)
{var selectedScopeBarItem=this._scopeBar.selectedItems[0];if(!selectedScopeBarItem||selectedScopeBarItem.exclusive)
return true;if(treeElement instanceof WI.FolderTreeElement)
return false;function match()
{for(var constructor of selectedScopeBarItem.__storageTypeInfo.classes){if(constructor===WI.DOMStorageTreeElement&&treeElement instanceof constructor)
return treeElement.representedObject.isLocalStorage()===selectedScopeBarItem.__storageTypeInfo.localStorage;if(treeElement instanceof constructor)
return true;}
return false;}
var matched=match();if(matched)
flags.expandTreeElement=true;return matched;} 
_treeSelectionDidChange(event)
{if(!this.selected)
return;let treeElement=this.contentTreeOutline.selectedTreeElement;if(!treeElement)
return;if(treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.DatabaseHostTreeElement||treeElement instanceof WI.IndexedDatabaseHostTreeElement||treeElement instanceof WI.ApplicationCacheManifestTreeElement)
return;if(treeElement instanceof WI.StorageTreeElement||treeElement instanceof WI.DatabaseTableTreeElement||treeElement instanceof WI.DatabaseTreeElement||treeElement instanceof WI.ApplicationCacheFrameTreeElement||treeElement instanceof WI.IndexedDatabaseTreeElement||treeElement instanceof WI.IndexedDatabaseObjectStoreTreeElement||treeElement instanceof WI.IndexedDatabaseObjectStoreIndexTreeElement){WI.showRepresentedObject(treeElement.representedObject);return;}
console.error("Unknown tree element",treeElement);}
_domStorageObjectWasAdded(event)
{this._addDOMStorageObject(event.data.domStorage);}
_addDOMStorageObject(domStorage)
{var storageElement=new WI.DOMStorageTreeElement(domStorage);if(domStorage.isLocalStorage())
this._localStorageRootTreeElement=this._addStorageChild(storageElement,this._localStorageRootTreeElement,WI.UIString("Local Storage"));else
this._sessionStorageRootTreeElement=this._addStorageChild(storageElement,this._sessionStorageRootTreeElement,WI.UIString("Session Storage"));}
_domStorageObjectWasInspected(event)
{var domStorage=event.data.domStorage;var treeElement=this.treeElementForRepresentedObject(domStorage);treeElement.revealAndSelect(true);}
_databaseWasAdded(event)
{this._addDatabase(event.data.database);}
_addDatabase(database)
{let databaseHostElement=this._databaseHostTreeElementMap.get(database.host);if(!databaseHostElement){databaseHostElement=new WI.DatabaseHostTreeElement(database.host);this._databaseHostTreeElementMap.set(database.host,databaseHostElement);this._databaseRootTreeElement=this._addStorageChild(databaseHostElement,this._databaseRootTreeElement,WI.UIString("Databases"));}
let databaseElement=new WI.DatabaseTreeElement(database);databaseHostElement.appendChild(databaseElement);}
_databaseWasInspected(event)
{var database=event.data.database;var treeElement=this.treeElementForRepresentedObject(database);treeElement.revealAndSelect(true);}
_indexedDatabaseWasAdded(event)
{this._addIndexedDatabase(event.data.indexedDatabase);}
_addIndexedDatabase(indexedDatabase)
{let indexedDatabaseHostElement=this._indexedDatabaseHostTreeElementMap.get(indexedDatabase.host);if(!indexedDatabaseHostElement){indexedDatabaseHostElement=new WI.IndexedDatabaseHostTreeElement(indexedDatabase.host);this._indexedDatabaseHostTreeElementMap.set(indexedDatabase.host,indexedDatabaseHostElement);this._indexedDatabaseRootTreeElement=this._addStorageChild(indexedDatabaseHostElement,this._indexedDatabaseRootTreeElement,WI.UIString("Indexed Databases"));}
let indexedDatabaseElement=new WI.IndexedDatabaseTreeElement(indexedDatabase);indexedDatabaseHostElement.appendChild(indexedDatabaseElement);}
_cookieStorageObjectWasAdded(event)
{this._addCookieStorageObject(event.data.cookieStorage);}
_addCookieStorageObject(cookieStorage)
{var cookieElement=new WI.CookieStorageTreeElement(cookieStorage);this._cookieStorageRootTreeElement=this._addStorageChild(cookieElement,this._cookieStorageRootTreeElement,WI.UIString("Cookies"));}
_frameManifestAdded(event)
{this._addFrameManifest(event.data.frameManifest);}
_addFrameManifest(frameManifest)
{let manifest=frameManifest.manifest;let manifestURL=manifest.manifestURL;let applicationCacheManifestElement=this._applicationCacheURLTreeElementMap.get(manifestURL);if(!applicationCacheManifestElement){applicationCacheManifestElement=new WI.ApplicationCacheManifestTreeElement(manifest);this._applicationCacheURLTreeElementMap.set(manifestURL,applicationCacheManifestElement);this._applicationCacheRootTreeElement=this._addStorageChild(applicationCacheManifestElement,this._applicationCacheRootTreeElement,WI.UIString("Application Cache"));}
let frameCacheElement=new WI.ApplicationCacheFrameTreeElement(frameManifest);applicationCacheManifestElement.appendChild(frameCacheElement);}
_frameManifestRemoved(event)
{}
_compareTreeElements(a,b)
{return(a.mainTitle||"").extendedLocaleCompare(b.mainTitle||"");}
_addStorageChild(childElement,parentElement,folderName)
{if(!parentElement){childElement.flattened=true;this.contentTreeOutline.insertChild(childElement,insertionIndexForObjectInListSortedByFunction(childElement,this.contentTreeOutline.children,this._compareTreeElements));return childElement;}
if(parentElement instanceof WI.StorageTreeElement){var previousOnlyChild=parentElement;previousOnlyChild.flattened=false;this.contentTreeOutline.removeChild(previousOnlyChild);var folderElement=new WI.FolderTreeElement(folderName);this.contentTreeOutline.insertChild(folderElement,insertionIndexForObjectInListSortedByFunction(folderElement,this.contentTreeOutline.children,this._compareTreeElements));folderElement.appendChild(previousOnlyChild);folderElement.insertChild(childElement,insertionIndexForObjectInListSortedByFunction(childElement,folderElement.children,this._compareTreeElements));return folderElement;}
parentElement.insertChild(childElement,insertionIndexForObjectInListSortedByFunction(childElement,parentElement.children,this._compareTreeElements));return parentElement;}
_closeContentViewForTreeElement(treeElement)
{const onlyExisting=true;let contentView=this.contentBrowser.contentViewForRepresentedObject(treeElement.representedObject,onlyExisting);if(contentView)
this.contentBrowser.contentViewContainer.closeContentView(contentView);}
_domStorageCleared(event)
{if(this._localStorageRootTreeElement&&this._localStorageRootTreeElement.parent){this._closeContentViewForTreeElement(this._localStorageRootTreeElement);this._localStorageRootTreeElement.parent.removeChild(this._localStorageRootTreeElement);}
if(this._sessionStorageRootTreeElement&&this._sessionStorageRootTreeElement.parent){this._closeContentViewForTreeElement(this._sessionStorageRootTreeElement);this._sessionStorageRootTreeElement.parent.removeChild(this._sessionStorageRootTreeElement);}
if(this._cookieStorageRootTreeElement&&this._cookieStorageRootTreeElement.parent){this._closeContentViewForTreeElement(this._cookieStorageRootTreeElement);this._cookieStorageRootTreeElement.parent.removeChild(this._cookieStorageRootTreeElement);}
this._localStorageRootTreeElement=null;this._sessionStorageRootTreeElement=null;this._cookieStorageRootTreeElement=null;}
_applicationCacheCleared(event)
{if(this._applicationCacheRootTreeElement&&this._applicationCacheRootTreeElement.parent){this._closeContentViewForTreeElement(this._applicationCacheRootTreeElement);this._applicationCacheRootTreeElement.parent.removeChild(this._applicationCacheRootTreeElement);}
this._applicationCacheRootTreeElement=null;this._applicationCacheURLTreeElementMap.clear();}
_indexedDatabaseCleared(event)
{if(this._indexedDatabaseRootTreeElement&&this._indexedDatabaseRootTreeElement.parent){this._closeContentViewForTreeElement(this._indexedDatabaseRootTreeElement);this._indexedDatabaseRootTreeElement.parent.removeChild(this._indexedDatabaseRootTreeElement);}
this._indexedDatabaseRootTreeElement=null;this._indexedDatabaseHostTreeElementMap.clear();}
_databaseCleared(event)
{if(this._databaseRootTreeElement&&this._databaseRootTreeElement.parent){this._closeContentViewForTreeElement(this._databaseRootTreeElement);this._databaseRootTreeElement.parent.removeChild(this._databaseRootTreeElement);}
this._databaseRootTreeElement=null;this._databaseHostTreeElementMap.clear();}
_scopeBarSelectionDidChange(event)
{this.updateFilter();}};WI.SyntaxHighlightedStyleClassName="syntax-highlighted";WI.syntaxHighlightStringAsDocumentFragment=function(string,mimeType,baseURL)
{var resultFragment=document.createDocumentFragment();function appendText(text,style)
{if(!style){resultFragment.append(text);return;}
var span=document.createElement("span");span.className="cm-"+style;span.textContent=text;resultFragment.appendChild(span);}
mimeType=parseMIMEType(mimeType).type;CodeMirror.runMode(string,mimeType,appendText);return resultFragment;};WI.TextNavigationItem=class TextNavigationItem extends WI.NavigationItem
{constructor(identifier,label)
{super(identifier);this._element.classList.add("text");this._element.textContent=label||"";} 
get text()
{return this._element.textContent;}
set text(x)
{this._element.textContent=x||"";} 
get totalMargin()
{return super.totalMargin+4;}};WI.TextResourceContentView=class TextResourceContentView extends WI.ResourceContentView
{constructor(resource)
{super(resource,"text");resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._sourceCodeContentDidChange,this);var toolTip=WI.UIString("Pretty print");var activatedToolTip=WI.UIString("Original formatting");this._prettyPrintButtonNavigationItem=new WI.ActivateButtonNavigationItem("pretty-print",toolTip,activatedToolTip,"Images/NavigationItemCurleyBraces.svg",13,13);this._prettyPrintButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrettyPrint,this);this._prettyPrintButtonNavigationItem.enabled=false;this._prettyPrintButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;var toolTipTypes=WI.UIString("Show type information");var activatedToolTipTypes=WI.UIString("Hide type information");this._showTypesButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-types",toolTipTypes,activatedToolTipTypes,"Images/NavigationItemTypes.svg",13,14);this._showTypesButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleTypeAnnotations,this);this._showTypesButtonNavigationItem.enabled=false;this._showTypesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);let toolTipCodeCoverage=WI.UIString("Fade unexecuted code");let activatedToolTipCodeCoverage=WI.UIString("Do not fade unexecuted code");this._codeCoverageButtonNavigationItem=new WI.ActivateButtonNavigationItem("code-coverage",toolTipCodeCoverage,activatedToolTipCodeCoverage,"Images/NavigationItemCodeCoverage.svg",13,14);this._codeCoverageButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleUnexecutedCodeHighlights,this);this._codeCoverageButtonNavigationItem.enabled=false;this._codeCoverageButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);this._textEditor=new WI.SourceCodeTextEditor(resource);this._textEditor.addEventListener(WI.TextEditor.Event.ExecutionLineNumberDidChange,this._executionLineNumberDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,this._textEditorContentDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.FormattingDidChange,this._textEditorFormattingDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.MIMETypeChanged,this._handleTextEditorMIMETypeChanged,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentWillPopulate,this._contentWillPopulate,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentDidPopulate,this._contentDidPopulate,this);this._textEditor.readOnly=!this._shouldBeEditable();WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetsChanged,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetsChanged,this);} 
get navigationItems()
{let items=super.navigationItems;items.push(this._prettyPrintButtonNavigationItem);if(!this.resource.localResourceOverride)
items.push(this._showTypesButtonNavigationItem,this._codeCoverageButtonNavigationItem);return items;}
get managesOwnIssues()
{return true;}
get textEditor()
{return this._textEditor;}
get supplementalRepresentedObjects()
{let objects=WI.debuggerManager.probeSets.filter(function(probeSet){return!(probeSet.breakpoint instanceof WI.JavaScriptBreakpoint)||this._resource.contentIdentifier===probeSet.breakpoint.contentIdentifier;},this);
if(!isNaN(this._textEditor.executionLineNumber))
objects.push(WI.debuggerManager.activeCallFrame);return objects;}
revealPosition(position,textRangeToSelect,forceUnformatted)
{this._textEditor.revealPosition(position,textRangeToSelect,forceUnformatted);}
closed()
{super.closed();this.resource.removeEventListener(WI.SourceCode.Event.ContentDidChange,this._sourceCodeContentDidChange,this);WI.settings.showJavaScriptTypeInformation.removeEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);WI.settings.enableControlFlowProfiler.removeEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetsChanged,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetsChanged,this);}
contentAvailable(content,base64Encoded)
{}
get createLocalResourceOverrideTooltip()
{return WI.UIString("Click to create a Local Override from this content");}
requestLocalResourceOverrideInitialContent()
{return Promise.resolve({mimeType:this.resource.mimeType,base64Encoded:this.resource.base64Encoded,content:this._textEditor.string,});}
get supportsSave()
{return super.supportsSave||this.resource instanceof WI.CSSStyleSheet;}
get saveData()
{let saveData={content:this._textEditor.string,};if(this.resource instanceof WI.CSSStyleSheet){saveData.suggestedName="InspectorStyleSheet.css";saveData.forceSaveAs=true;}else{saveData.url=this.resource.url;if(this.resource.urlComponents.path==="/"){let extension=WI.fileExtensionForMIMEType(this.resource.mimeType);if(extension)
saveData.suggestedName=`index.${extension}`;}}
return saveData;}
get supportsSearch()
{return true;}
get numberOfSearchResults()
{return this._textEditor.numberOfSearchResults;}
get hasPerformedSearch()
{return this._textEditor.currentSearchQuery!==null;}
set automaticallyRevealFirstSearchResult(reveal)
{this._textEditor.automaticallyRevealFirstSearchResult=reveal;}
performSearch(query)
{this._textEditor.performSearch(query);}
searchCleared()
{this._textEditor.searchCleared();}
searchQueryWithSelection()
{return this._textEditor.searchQueryWithSelection();}
revealPreviousSearchResult(changeFocus)
{this._textEditor.revealPreviousSearchResult(changeFocus);}
revealNextSearchResult(changeFocus)
{this._textEditor.revealNextSearchResult(changeFocus);} 
_contentWillPopulate(event)
{if(this._textEditor.parentView===this)
return;this.removeLoadingIndicator();this.addSubview(this._textEditor);}
_contentDidPopulate(event)
{this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();this._showTypesButtonNavigationItem.enabled=this._textEditor.canShowTypeAnnotations();this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;this._codeCoverageButtonNavigationItem.enabled=this._textEditor.canShowCoverageHints();this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;}
_togglePrettyPrint(event)
{var activated=!this._prettyPrintButtonNavigationItem.activated;this._textEditor.updateFormattedState(activated);}
_toggleTypeAnnotations(event)
{this._showTypesButtonNavigationItem.enabled=false;this._textEditor.toggleTypeAnnotations().then(()=>{this._showTypesButtonNavigationItem.enabled=true;});}
_toggleUnexecutedCodeHighlights(event)
{this._codeCoverageButtonNavigationItem.enabled=false;this._textEditor.toggleUnexecutedCodeHighlights().then(()=>{this._codeCoverageButtonNavigationItem.enabled=true;});}
_showJavaScriptTypeInformationSettingChanged(event)
{this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;}
_enableControlFlowProfilerSettingChanged(event)
{this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;}
_textEditorFormattingDidChange(event)
{this._prettyPrintButtonNavigationItem.activated=this._textEditor.formatted;}
_handleTextEditorMIMETypeChanged(event)
{this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();}
_sourceCodeContentDidChange(event)
{if(this._ignoreSourceCodeContentDidChangeEvent)
return;this._textEditor.string=this.resource.currentRevision.content;}
_textEditorContentDidChange(event)
{this._ignoreSourceCodeContentDidChangeEvent=true;this.resource.editableRevision.updateRevisionContent(this._textEditor.string);this._ignoreSourceCodeContentDidChangeEvent=false;}
_executionLineNumberDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_numberOfSearchResultsDidChange(event)
{this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}
_probeSetsChanged(event)
{var breakpoint=event.data.probeSet.breakpoint;if(!(breakpoint instanceof WI.JavaScriptBreakpoint)||breakpoint.sourceCodeLocation.sourceCode===this.resource)
this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_shouldBeEditable()
{if(this.resource instanceof WI.CSSStyleSheet)
return true;if(this.resource.type===WI.Resource.Type.StyleSheet&&this.resource.syntheticMIMEType==="text/css")
return true;if(this.resource.urlComponents.scheme==="file")
return true;if(this.resource.localResourceOverride)
return true;return false;}};{const selectedStyleClassName="selected";WI.TextToggleButtonNavigationItem=class TextToggleButtonNavigationItem extends WI.ButtonNavigationItem
{constructor(identifier,title)
{super(identifier,title);this._title=title;} 
get title()
{return this._title;}
get activated()
{return this.element.classList.contains(selectedStyleClassName);}
set activated(flag)
{this.element.classList.toggle(selectedStyleClassName,flag);} 
get additionalClassNames()
{return["text-toggle","button"];}};}
WI.ThreadTreeElement=class ThreadTreeElement extends WI.GeneralTreeElement
{constructor(target)
{super("thread",target.displayName);this._target=target;this._idleTreeElement=new WI.IdleTreeElement;} 
get target(){return this._target;}
refresh()
{this.removeChildren();this._updateStatus();let targetData=WI.debuggerManager.dataForTarget(this._target);let callFrames=targetData.callFrames;if(targetData.pausing||!callFrames.length){this.appendChild(this._idleTreeElement);this.expand();return;}
let activeCallFrame=WI.debuggerManager.activeCallFrame;let activeCallFrameTreeElement=null;let renderCallFrames=(callFrames,shouldSelectActiveFrame)=>{if(WI.settings.experimentalCollapseBlackboxedCallFrames.value)
callFrames=callFrames.groupBy((callFrame)=>callFrame.blackboxed);for(let callFrameOrBlackboxedGroup of callFrames){if(Array.isArray(callFrameOrBlackboxedGroup)){this.appendChild(new WI.BlackboxedGroupTreeElement(callFrameOrBlackboxedGroup));continue;}
let callFrameTreeElement=new WI.CallFrameTreeElement(callFrameOrBlackboxedGroup);if(shouldSelectActiveFrame&&callFrameOrBlackboxedGroup===activeCallFrame)
activeCallFrameTreeElement=callFrameTreeElement;this.appendChild(callFrameTreeElement);}};renderCallFrames(callFrames,true);if(activeCallFrameTreeElement){activeCallFrameTreeElement.select(true,true);activeCallFrameTreeElement.isActiveCallFrame=true;}
let currentStackTrace=targetData.asyncStackTrace;while(currentStackTrace){if(!currentStackTrace.callFrames.length)
break;let boundaryCallFrame;if(currentStackTrace.topCallFrameIsBoundary){boundaryCallFrame=currentStackTrace.callFrames[0];}else{const functionName=WI.UIString("(async)");const nativeCode=true;boundaryCallFrame=new WI.CallFrame(null,null,null,functionName,null,null,nativeCode);}
const isAsyncBoundaryCallFrame=true;this.appendChild(new WI.CallFrameTreeElement(boundaryCallFrame,isAsyncBoundaryCallFrame));let startIndex=currentStackTrace.topCallFrameIsBoundary?1:0;renderCallFrames(startIndex?currentStackTrace.callFrames.slice(startIndex):currentStackTrace.callFrames);if(currentStackTrace.truncated){let truncatedTreeElement=new WI.GeneralTreeElement("truncated-call-frames",WI.UIString("Call Frames Truncated"));truncatedTreeElement.selectable=false;this.appendChild(truncatedTreeElement);}
currentStackTrace=currentStackTrace.parentStackTrace;}
this.expand();}
onattach()
{super.onattach();this.refresh();this.expand();}
populateContextMenu(contextMenu,event)
{let targetData=WI.debuggerManager.dataForTarget(this._target);contextMenu.appendItem(WI.UIString("Resume Thread"),()=>{WI.debuggerManager.continueUntilNextRunLoop(this._target);},!targetData.paused);super.populateContextMenu(contextMenu,event);} 
_updateStatus()
{this.status=null;if(!this.element)
return;let targetData=WI.debuggerManager.dataForTarget(this._target);if(!targetData.paused)
return;if(!this._statusButton){let tooltip=WI.UIString("Resume Thread");this._statusButton=new WI.TreeElementStatusButton(WI.ImageUtilities.useSVGSymbol("Images/Resume.svg","resume",tooltip));this._statusButton.addEventListener(WI.TreeElementStatusButton.Event.Clicked,function(event){WI.debuggerManager.continueUntilNextRunLoop(this._target);},this);this._statusButton.element.addEventListener("mousedown",(event)=>{event.stopPropagation();});}
this.status=this._statusButton.element;}};WI.TimelineRecordBar=class TimelineRecordBar extends WI.Object
{constructor(delegate,records,renderMode)
{super();this._delegate=delegate||null;this._element=document.createElement("div");this._element.classList.add("timeline-record-bar");this._element[WI.TimelineRecordBar.ElementReferenceSymbol]=this;this._element.addEventListener("click",this._handleClick.bind(this));this.renderMode=renderMode;this.records=records;}
static createCombinedBars(records,secondsPerPixel,graphDataSource,createBarCallback)
{if(!records.length)
return;var startTime=graphDataSource.startTime;var currentTime=graphDataSource.currentTime;var endTime=graphDataSource.endTime;var visibleRecords=[];var usesActiveStartTime=false;var lastRecordType=null;for(var i=0;i<records.length;++i){var record=records[i];if(isNaN(record.startTime))
continue;if(record.endTime<startTime)
continue;if(record.startTime>currentTime||record.startTime>endTime)
break;if(record.usesActiveStartTime)
usesActiveStartTime=true;visibleRecords.push(record);lastRecordType=record.type;}
if(!visibleRecords.length)
return;if(visibleRecords.length===1){createBarCallback(visibleRecords,WI.TimelineRecordBar.RenderMode.Normal);return;}
function compareByActiveStartTime(a,b)
{return a.activeStartTime-b.activeStartTime;}
var minimumDuration=secondsPerPixel*WI.TimelineRecordBar.MinimumWidthPixels;var minimumMargin=secondsPerPixel*WI.TimelineRecordBar.MinimumMarginPixels;if(usesActiveStartTime){var inactiveStartTime=NaN;var inactiveEndTime=NaN;var inactiveRecords=[];for(var i=0;i<visibleRecords.length;++i){var record=visibleRecords[i];if(!isNaN(inactiveStartTime)&&inactiveStartTime+Math.max(inactiveEndTime-inactiveStartTime,minimumDuration)+minimumMargin<=record.startTime){createBarCallback(inactiveRecords,WI.TimelineRecordBar.RenderMode.InactiveOnly);inactiveRecords=[];inactiveStartTime=NaN;inactiveEndTime=NaN;}
if(isNaN(inactiveStartTime))
inactiveStartTime=record.startTime;inactiveEndTime=Math.max(inactiveEndTime||0,record.activeStartTime);inactiveRecords.push(record);}
if(!isNaN(inactiveStartTime))
createBarCallback(inactiveRecords,WI.TimelineRecordBar.RenderMode.InactiveOnly);visibleRecords.sort(compareByActiveStartTime);}
var activeStartTime=NaN;var activeEndTime=NaN;var activeRecords=[];var startTimeProperty=usesActiveStartTime?"activeStartTime":"startTime";for(var i=0;i<visibleRecords.length;++i){var record=visibleRecords[i];var startTime=record[startTimeProperty];if(!isNaN(activeStartTime)&&(activeStartTime+Math.max(activeEndTime-activeStartTime,minimumDuration)+minimumMargin<=startTime||(isNaN(startTime)&&!isNaN(activeEndTime)))){createBarCallback(activeRecords,WI.TimelineRecordBar.RenderMode.ActiveOnly);activeRecords=[];activeStartTime=NaN;activeEndTime=NaN;}
if(isNaN(startTime))
continue;if(isNaN(activeStartTime))
activeStartTime=startTime;if(!isNaN(record.endTime))
activeEndTime=Math.max(activeEndTime||0,record.endTime);activeRecords.push(record);}
if(!isNaN(activeStartTime))
createBarCallback(activeRecords,WI.TimelineRecordBar.RenderMode.ActiveOnly);}
static fromElement(element)
{return element[WI.TimelineRecordBar.ElementReferenceSymbol]||null;} 
get element()
{return this._element;}
get selected()
{return this._element.classList.contains("selected");}
set selected(selected)
{this._element.classList.toggle("selected",!!selected);}
get renderMode()
{return this._renderMode;}
set renderMode(renderMode)
{this._renderMode=renderMode||WI.TimelineRecordBar.RenderMode.Normal;}
get records()
{return this._records;}
set records(records)
{let oldRecordType;let oldRecordEventType;let oldRecordUsesActiveStartTime=false;if(this._records&&this._records.length){let oldRecord=this._records[0];oldRecordType=oldRecord.type;oldRecordEventType=oldRecord.eventType;oldRecordUsesActiveStartTime=oldRecord.usesActiveStartTime;}
records=records||[];this._records=records;if(this._records.length){let newRecord=this._records[0];if(newRecord.type!==oldRecordType){this._element.classList.remove(oldRecordType);this._element.classList.add(newRecord.type);}

if(newRecord.eventType!==oldRecordEventType){this._element.classList.remove(oldRecordEventType);this._element.classList.add(newRecord.eventType);}
if(newRecord.usesActiveStartTime!==oldRecordUsesActiveStartTime){if(!this._delegate||!this._delegate.timelineRecordBarCustomChildren)
this._element.classList.toggle("has-inactive-segment",newRecord.usesActiveStartTime);}}else
this._element.classList.remove(oldRecordType,oldRecordEventType,"has-inactive-segment");}
refresh(graphDataSource)
{if(isNaN(graphDataSource.secondsPerPixel))
return false;if(!this._records||!this._records.length)
return false;var firstRecord=this._records[0];var barStartTime=firstRecord.startTime;if(isNaN(barStartTime))
return false;var graphStartTime=graphDataSource.startTime;var graphEndTime=graphDataSource.endTime;var graphCurrentTime=graphDataSource.currentTime;var barEndTime=this._records.reduce(function(previousValue,currentValue){return Math.max(previousValue,currentValue.endTime);},0);if(barStartTime>graphCurrentTime)
return false;if(barEndTime<graphStartTime||barStartTime>graphEndTime)
return false;var barUnfinished=isNaN(barEndTime)||barEndTime>=graphCurrentTime;if(barUnfinished)
barEndTime=graphCurrentTime;var barDuration=barEndTime-barStartTime;var graphDuration=graphEndTime-graphStartTime;let newBarPosition=(barStartTime-graphStartTime)/graphDuration;let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._updateElementPosition(this._element,newBarPosition,property);var newBarWidth=((barEndTime-graphStartTime)/graphDuration)-newBarPosition;this._updateElementPosition(this._element,newBarWidth,"width");if(this._delegate&&this._delegate.timelineRecordBarCustomChildren){this._element.removeChildren();this._element.classList.add("has-custom-children");this._element.classList.toggle("unfinished",barUnfinished);let children=this._delegate.timelineRecordBarCustomChildren(this);for(let child of children){let childElement;if(child.image){childElement=this._element.appendChild(document.createElement("img"));childElement.src=child.image;}else
childElement=this._element.appendChild(document.createElement("div"));childElement.classList.add(...child.classNames);childElement.title=child.title;this._updateElementPosition(childElement,(child.startTime-barStartTime)/barDuration,property);if(typeof child.endTime==="number"){let childEndTime=!isNaN(child.endTime)?child.endTime:barEndTime;this._updateElementPosition(childElement,(childEndTime-child.startTime)/barDuration,"width");}}
return true;}
this._element.classList.remove("has-custom-children");if(!this._activeBarElement&&this._renderMode!==WI.TimelineRecordBar.RenderMode.InactiveOnly){this._activeBarElement=document.createElement("div");this._activeBarElement.classList.add("segment");}
if(!firstRecord.usesActiveStartTime){this._element.classList.toggle("unfinished",barUnfinished);if(this._inactiveBarElement)
this._inactiveBarElement.remove();if(this._renderMode===WI.TimelineRecordBar.RenderMode.InactiveOnly){if(this._activeBarElement)
this._activeBarElement.remove();return false;}
this._activeBarElement.style.removeProperty(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left");this._activeBarElement.style.removeProperty("width");if(!this._activeBarElement.parentNode)
this._element.appendChild(this._activeBarElement);return true;}
if(this._renderMode===WI.TimelineRecordBar.RenderMode.ActiveOnly)
var barActiveStartTime=this._records.reduce(function(previousValue,currentValue){return Math.min(previousValue,currentValue.activeStartTime);},Infinity);else
var barActiveStartTime=this._records.reduce(function(previousValue,currentValue){return Math.max(previousValue,currentValue.activeStartTime);},0);var inactiveUnfinished=isNaN(barActiveStartTime)||barActiveStartTime>=graphCurrentTime;this._element.classList.toggle("unfinished",inactiveUnfinished);if(inactiveUnfinished)
barActiveStartTime=graphCurrentTime;else if(this._renderMode===WI.TimelineRecordBar.RenderMode.Normal){let minimumSegmentDuration=graphDataSource.secondsPerPixel*WI.TimelineRecordBar.MinimumWidthPixels;if(barActiveStartTime-barStartTime<minimumSegmentDuration){barActiveStartTime=barStartTime;if(this._inactiveBarElement)
this._inactiveBarElement.remove();}}
let showInactiveSegment=barActiveStartTime>barStartTime;this._element.classList.toggle("has-inactive-segment",showInactiveSegment);let middlePercentage=(barActiveStartTime-barStartTime)/barDuration;if(showInactiveSegment&&this._renderMode!==WI.TimelineRecordBar.RenderMode.ActiveOnly){if(!this._inactiveBarElement){this._inactiveBarElement=document.createElement("div");this._inactiveBarElement.classList.add("segment");this._inactiveBarElement.classList.add("inactive");}
let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"left":"right";this._updateElementPosition(this._inactiveBarElement,1-middlePercentage,property);this._updateElementPosition(this._inactiveBarElement,middlePercentage,"width");if(!this._inactiveBarElement.parentNode)
this._element.insertBefore(this._inactiveBarElement,this._element.firstChild);}
if(!inactiveUnfinished&&this._renderMode!==WI.TimelineRecordBar.RenderMode.InactiveOnly){let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._updateElementPosition(this._activeBarElement,middlePercentage,property);this._updateElementPosition(this._activeBarElement,1-middlePercentage,"width");if(!this._activeBarElement.parentNode)
this._element.appendChild(this._activeBarElement);}else if(this._activeBarElement)
this._activeBarElement.remove();return true;} 
_updateElementPosition(element,newPosition,property)
{newPosition*=100;let newPositionAprox=Math.round(newPosition*100);let currentPositionAprox=Math.round(parseFloat(element.style[property])*100);if(currentPositionAprox!==newPositionAprox)
element.style[property]=(newPositionAprox/100)+"%";}
_handleClick(event)
{event.__timelineRecordClickEventHandled=true;if(this._delegate&&this._delegate.timelineRecordBarClicked)
this._delegate.timelineRecordBarClicked(this);}};WI.TimelineRecordBar.ElementReferenceSymbol=Symbol("timeline-record-bar");WI.TimelineRecordBar.MinimumWidthPixels=4;WI.TimelineRecordBar.MinimumMarginPixels=1;WI.TimelineRecordBar.RenderMode={Normal:"timeline-record-bar-normal-render-mode",InactiveOnly:"timeline-record-bar-inactive-only-render-mode",ActiveOnly:"timeline-record-bar-active-only-render-mode"};WI.TimelineRecordFrame=class TimelineRecordFrame extends WI.Object
{constructor(graphDataSource,record)
{super();this._element=document.createElement("div");this._element.classList.add("timeline-record-frame");this._graphDataSource=graphDataSource;this._record=record||null;this._filtered=false;} 
get element()
{return this._element;}
get record()
{return this._record;}
set record(record)
{this._record=record;}
get selected()
{return this._element.classList.contains("selected");}
set selected(x)
{if(this.selected===x)
return;this._element.classList.toggle("selected");}
get filtered()
{return this._filtered;}
set filtered(x)
{if(this._filtered===x)
return;this._filtered=x;this._element.classList.toggle("filtered");}
refresh(graphDataSource)
{if(!this._record)
return false;var frameIndex=this._record.frameIndex;var graphStartFrameIndex=Math.floor(graphDataSource.startTime);var graphEndFrameIndex=graphDataSource.endTime;if(frameIndex<graphStartFrameIndex||frameIndex>graphEndFrameIndex)
return false;this._element.style.width=(1/graphDataSource.timelineOverview.secondsPerPixel)+"px";var graphDuration=graphDataSource.endTime-graphDataSource.startTime;let recordPosition=(frameIndex-graphDataSource.startTime)/graphDuration;let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._updateElementPosition(this._element,recordPosition,property);this._updateChildElements(graphDataSource);return true;} 
_calculateFrameDisplayData(graphDataSource)
{var secondsPerBlock=(graphDataSource.graphHeightSeconds/graphDataSource.height)*WI.TimelineRecordFrame.MinimumHeightPixels;var segments=[];var invisibleSegments=[];var currentSegment=null;function updateDurationRemainder(segment)
{if(segment.duration<=secondsPerBlock){segment.remainder=0;return;}
var roundedDuration=Math.roundTo(segment.duration,secondsPerBlock);segment.remainder=Math.max(segment.duration-roundedDuration,0);}
function pushCurrentSegment()
{updateDurationRemainder(currentSegment);segments.push(currentSegment);if(currentSegment.duration<secondsPerBlock)
invisibleSegments.push({segment:currentSegment,index:segments.length-1});currentSegment=null;}




for(var key in WI.RenderingFrameTimelineRecord.TaskType){var taskType=WI.RenderingFrameTimelineRecord.TaskType[key];var duration=this._record.durationForTask(taskType);if(duration===0)
continue;if(currentSegment&&duration>=secondsPerBlock)
pushCurrentSegment();if(!currentSegment)
currentSegment={taskType:null,longestTaskDuration:0,duration:0,remainder:0};currentSegment.duration+=duration;if(duration>currentSegment.longestTaskDuration){currentSegment.taskType=taskType;currentSegment.longestTaskDuration=duration;}
if(currentSegment.duration>=secondsPerBlock)
pushCurrentSegment();}
if(currentSegment)
pushCurrentSegment();if(segments.length===1){segments[0].duration=Math.max(segments[0].duration,secondsPerBlock);invisibleSegments=[];}



invisibleSegments.sort(function(a,b){return a.segment.duration-b.segment.duration;});for(var item of invisibleSegments){var segment=item.segment;var previousSegment=item.index>0?segments[item.index-1]:null;var nextSegment=item.index<segments.length-1?segments[item.index+1]:null;var adjacentSegments;var availableDuration;if(previousSegment&&nextSegment){adjacentSegments=previousSegment.remainder>nextSegment.remainder?[previousSegment,nextSegment]:[nextSegment,previousSegment];availableDuration=previousSegment.remainder+nextSegment.remainder;}else{adjacentSegments=[previousSegment||nextSegment];availableDuration=adjacentSegments[0].remainder;}
if(availableDuration<(secondsPerBlock-segment.duration)){var targetSegment;if(previousSegment&&nextSegment)
targetSegment=previousSegment.duration>nextSegment.duration?previousSegment:nextSegment;else
targetSegment=previousSegment||nextSegment;targetSegment.duration+=segment.duration;updateDurationRemainder(targetSegment);continue;}
adjacentSegments.forEach(function(adjacentSegment){if(segment.duration>=secondsPerBlock)
return;var remainder=Math.min(secondsPerBlock-segment.duration,adjacentSegment.remainder);segment.duration+=remainder;adjacentSegment.remainder-=remainder;});}
var frameDuration=0;segments=segments.filter(function(segment){if(segment.duration<secondsPerBlock)
return false;segment.duration=Math.roundTo(segment.duration,secondsPerBlock);frameDuration+=segment.duration;return true;});return{frameDuration,segments};}
_updateChildElements(graphDataSource)
{this._element.removeChildren();if(!this._record)
return;if(graphDataSource.graphHeightSeconds===0)
return;var frameElement=document.createElement("div");frameElement.classList.add("frame");this._element.appendChild(frameElement);if(this._record.__displayData&&this._record.__displayData.graphHeightSeconds!==graphDataSource.graphHeightSeconds)
this._record.__displayData=null;if(!this._record.__displayData){this._record.__displayData=this._calculateFrameDisplayData(graphDataSource);this._record.__displayData.graphHeightSeconds=graphDataSource.graphHeightSeconds;}
var frameHeight=this._record.__displayData.frameDuration/graphDataSource.graphHeightSeconds;if(frameHeight>=0.95)
this._element.classList.add("tall");else
this._element.classList.remove("tall");this._updateElementPosition(frameElement,frameHeight,"height");for(var segment of this._record.__displayData.segments){var element=document.createElement("div");this._updateElementPosition(element,segment.duration/this._record.__displayData.frameDuration,"height");element.classList.add("duration",segment.taskType);frameElement.insertBefore(element,frameElement.firstChild);}}
_updateElementPosition(element,newPosition,property)
{newPosition*=100;let newPositionAprox=Math.round(newPosition*100);let currentPositionAprox=Math.round(parseFloat(element.style[property])*100);if(currentPositionAprox!==newPositionAprox)
element.style[property]=(newPositionAprox/100)+"%";}};WI.TimelineRecordFrame.MinimumHeightPixels=3;WI.TimelineRecordFrame.MaximumWidthPixels=14;WI.TimelineRecordFrame.MinimumWidthPixels=4;WI.TimelineRecordingContentView=class TimelineRecordingContentView extends WI.ContentView
{constructor(recording)
{super(recording);this._recording=recording;this.element.classList.add("timeline-recording");this._timelineOverview=new WI.TimelineOverview(this._recording);this._timelineOverview.addEventListener(WI.TimelineOverview.Event.TimeRangeSelectionChanged,this._timeRangeSelectionChanged,this);this._timelineOverview.addEventListener(WI.TimelineOverview.Event.RecordSelected,this._recordSelected,this);this._timelineOverview.addEventListener(WI.TimelineOverview.Event.TimelineSelected,this._timelineSelected,this);this._timelineOverview.addEventListener(WI.TimelineOverview.Event.EditingInstrumentsDidChange,this._editingInstrumentsDidChange,this);this.addSubview(this._timelineOverview);this._timelineContentBrowser=new WI.ContentBrowser(null,this,{hideBackForwardButtons:true,disableFindBanner:true});this._timelineContentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);this._entireRecordingPathComponent=this._createTimelineRangePathComponent(WI.UIString("Entire Recording"));this._timelineSelectionPathComponent=this._createTimelineRangePathComponent();this._timelineSelectionPathComponent.previousSibling=this._entireRecordingPathComponent;this._selectedTimeRangePathComponent=this._entireRecordingPathComponent;this._filterBarNavigationItem=new WI.FilterBarNavigationItem;this._filterBarNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._filterDidChange,this);this._timelineContentBrowser.navigationBar.addNavigationItem(this._filterBarNavigationItem);this.addSubview(this._timelineContentBrowser);if(WI.sharedApp.isWebDebuggable()){this._autoStopCheckboxNavigationItem=new WI.CheckboxNavigationItem("auto-stop-recording",WI.UIString("Stop recording once page loads"),WI.settings.timelinesAutoStop.value);this._autoStopCheckboxNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._autoStopCheckboxNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,this._handleAutoStopCheckboxCheckedDidChange,this);WI.settings.timelinesAutoStop.addEventListener(WI.Setting.Event.Changed,this._handleTimelinesAutoStopSettingChanged,this);}
this._exportButtonNavigationItem=new WI.ButtonNavigationItem("export",WI.UIString("Export"),"Images/Export.svg",15,15);this._exportButtonNavigationItem.toolTip=WI.UIString("Export (%s)").format(WI.saveKeyboardShortcut.displayName);this._exportButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._exportButtonNavigationItemClicked,this);this._exportButtonNavigationItem.enabled=false;this._importButtonNavigationItem=new WI.ButtonNavigationItem("import",WI.UIString("Import"),"Images/Import.svg",15,15);this._importButtonNavigationItem.toolTip=WI.UIString("Import");this._importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._importButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._importButtonNavigationItemClicked,this);this._clearTimelineNavigationItem=new WI.ButtonNavigationItem("clear-timeline",WI.UIString("Clear Timeline (%s)").format(WI.clearKeyboardShortcut.displayName),"Images/NavigationItemTrash.svg",15,15);this._clearTimelineNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._clearTimelineNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearTimeline,this);this._overviewTimelineView=new WI.OverviewTimelineView(recording);this._overviewTimelineView.secondsPerPixel=this._timelineOverview.secondsPerPixel;this._progressView=new WI.TimelineRecordingProgressView;this._timelineContentBrowser.addSubview(this._progressView);this._timelineViewMap=new Map;this._pathComponentMap=new Map;this._updating=false;this._currentTime=NaN;this._lastUpdateTimestamp=NaN;this._startTimeNeedsReset=true;this._renderingFrameTimeline=null;this._recording.addEventListener(WI.TimelineRecording.Event.InstrumentAdded,this._instrumentAdded,this);this._recording.addEventListener(WI.TimelineRecording.Event.InstrumentRemoved,this._instrumentRemoved,this);this._recording.addEventListener(WI.TimelineRecording.Event.Reset,this._recordingReset,this);this._recording.singleFireEventListener(WI.TimelineRecording.Event.Unloaded,this._recordingUnloaded,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._debuggerPaused,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerResumed,this);WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.RecordWasFiltered,this._handleTimelineViewRecordFiltered,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.RecordWasSelected,this._handleTimelineViewRecordSelected,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.ScannerShow,this._handleTimelineViewScannerShow,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.ScannerHide,this._handleTimelineViewScannerHide,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.NeedsEntireSelectedRange,this._handleTimelineViewNeedsEntireSelectedRange,this);WI.TimelineView.addEventListener(WI.TimelineView.Event.NeedsFiltersCleared,this._handleTimelineViewNeedsFiltersCleared,this);WI.notifications.addEventListener(WI.Notification.VisibilityStateDidChange,this._inspectorVisibilityStateChanged,this);for(let instrument of this._recording.instruments)
this._instrumentAdded(instrument);this.showOverviewTimelineView();if(this._recording.imported){let{startTime,endTime}=this._recording;this._updateTimes(startTime,endTime,endTime);}} 
showOverviewTimelineView()
{this._timelineContentBrowser.showContentView(this._overviewTimelineView);}
showTimelineViewForTimeline(timeline)
{if(!this._timelineViewMap.has(timeline))
return;let contentView=this._timelineContentBrowser.showContentView(this._timelineViewMap.get(timeline));

if(!contentView.didInitialLayout)
contentView.updateLayout();}
get supportsSplitContentBrowser()
{return false;}
get selectionPathComponents()
{if(!this._timelineContentBrowser.currentContentView)
return[];let pathComponents=[];let representedObject=this._timelineContentBrowser.currentContentView.representedObject;if(representedObject instanceof WI.Timeline)
pathComponents.push(this._pathComponentMap.get(representedObject));pathComponents.push(this._selectedTimeRangePathComponent);return pathComponents;}
get supplementalRepresentedObjects()
{if(!this._timelineContentBrowser.currentContentView)
return[];return this._timelineContentBrowser.currentContentView.supplementalRepresentedObjects;}
get navigationItems()
{let navigationItems=[];if(this._autoStopCheckboxNavigationItem)
navigationItems.push(this._autoStopCheckboxNavigationItem);navigationItems.push(new WI.DividerNavigationItem);navigationItems.push(this._importButtonNavigationItem);navigationItems.push(this._exportButtonNavigationItem);navigationItems.push(new WI.DividerNavigationItem);navigationItems.push(this._clearTimelineNavigationItem);return navigationItems;}
get handleCopyEvent()
{let currentContentView=this._timelineContentBrowser.currentContentView;return currentContentView&&typeof currentContentView.handleCopyEvent==="function"?currentContentView.handleCopyEvent.bind(currentContentView):null;}
get supportsSave()
{return this._recording.canExport();}
get saveData()
{return{customSaveHandler:()=>{this._exportTimelineRecording();}};}
get currentTimelineView()
{return this._timelineContentBrowser.currentContentView;}
attached()
{super.attached();this._clearTimelineNavigationItem.enabled=!this._recording.readonly&&!isNaN(this._recording.startTime);this._exportButtonNavigationItem.enabled=this._recording.canExport();if(!this._updating&&WI.timelineManager.activeRecording===this._recording&&WI.timelineManager.isCapturing())
this._startUpdatingCurrentTime(this._currentTime);}
detached()
{if(this._updating)
this._stopUpdatingCurrentTime();super.detached();}
initialLayout()
{super.initialLayout();this._currentContentViewDidChange();}
closed()
{super.closed();this._timelineContentBrowser.contentViewContainer.closeAllContentViews();this._recording.removeEventListener(WI.TimelineRecording.Event.InstrumentAdded,this._instrumentAdded,this);this._recording.removeEventListener(WI.TimelineRecording.Event.InstrumentRemoved,this._instrumentRemoved,this);this._recording.removeEventListener(WI.TimelineRecording.Event.Reset,this._recordingReset,this);if(!this._recording.readonly)
this._recording.removeEventListener(WI.TimelineRecording.Event.Unloaded,this._recordingUnloaded,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Paused,this._debuggerPaused,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerResumed,this);WI.ContentView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.removeEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.TimelineView.removeEventListener(WI.TimelineView.Event.RecordWasFiltered,this._handleTimelineViewRecordFiltered,this);WI.TimelineView.removeEventListener(WI.TimelineView.Event.RecordWasSelected,this._handleTimelineViewRecordSelected,this);WI.TimelineView.removeEventListener(WI.TimelineView.Event.ScannerShow,this._handleTimelineViewScannerShow,this);WI.TimelineView.removeEventListener(WI.TimelineView.Event.ScannerHide,this._handleTimelineViewScannerHide,this);WI.TimelineView.removeEventListener(WI.TimelineView.Event.NeedsEntireSelectedRange,this._handleTimelineViewNeedsEntireSelectedRange,this);}
canGoBack()
{return this._timelineContentBrowser.canGoBack();}
canGoForward()
{return this._timelineContentBrowser.canGoForward();}
goBack()
{this._timelineContentBrowser.goBack();}
goForward()
{this._timelineContentBrowser.goForward();}
handleClearShortcut(event)
{this._clearTimeline();}
get canFocusFilterBar()
{return!this._filterBarNavigationItem.hidden;}
focusFilterBar()
{this._filterBarNavigationItem.filterBar.focus();} 
contentBrowserTreeElementForRepresentedObject(contentBrowser,representedObject)
{if(!(representedObject instanceof WI.Timeline)&&!(representedObject instanceof WI.TimelineRecording))
return null;let iconClassName;let title;if(representedObject instanceof WI.Timeline){iconClassName=WI.TimelineTabContentView.iconClassNameForTimelineType(representedObject.type);title=WI.UIString("Details");}else{iconClassName=WI.TimelineTabContentView.StopwatchIconStyleClass;title=WI.UIString("Overview");}
const hasChildren=false;return new WI.GeneralTreeElement(iconClassName,title,representedObject,hasChildren);} 
_currentContentViewDidChange(event)
{let newViewMode;let timelineView=this.currentTimelineView;if(timelineView&&timelineView.representedObject.type===WI.TimelineRecord.Type.RenderingFrame)
newViewMode=WI.TimelineOverview.ViewMode.RenderingFrames;else
newViewMode=WI.TimelineOverview.ViewMode.Timelines;this._timelineOverview.viewMode=newViewMode;this._updateTimelineOverviewHeight();this._updateProgressView();this._updateFilterBar();if(timelineView){this._updateTimelineViewTimes(timelineView);this._filterDidChange();let timeline=null;if(timelineView.representedObject instanceof WI.Timeline)
timeline=timelineView.representedObject;this._timelineOverview.selectedTimeline=timeline;}
this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);}
_timelinePathComponentSelected(event)
{let selectedTimeline=event.data.pathComponent.representedObject;this.showTimelineViewForTimeline(selectedTimeline);}
_timeRangePathComponentSelected(event)
{let selectedPathComponent=event.data.pathComponent;if(selectedPathComponent===this._selectedTimeRangePathComponent)
return;let timelineRuler=this._timelineOverview.timelineRuler;if(selectedPathComponent===this._entireRecordingPathComponent)
timelineRuler.selectEntireRange();else{let timelineRange=selectedPathComponent.representedObject;timelineRuler.selectionStartTime=timelineRuler.zeroTime+timelineRange.startValue;timelineRuler.selectionEndTime=timelineRuler.zeroTime+timelineRange.endValue;}}
_contentViewSelectionPathComponentDidChange(event)
{if(!this.isAttached)
return;if(event.target!==this._timelineContentBrowser.currentContentView)
return;this._updateFilterBar();this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);if(this.currentTimelineView===this._overviewTimelineView)
return;let record=null;if(this.currentTimelineView.selectionPathComponents){let recordPathComponent=this.currentTimelineView.selectionPathComponents.find((element)=>element.representedObject instanceof WI.TimelineRecord);record=recordPathComponent?recordPathComponent.representedObject:null;}
this._timelineOverview.selectRecord(event.target.representedObject,record);}
_contentViewSupplementalRepresentedObjectsDidChange(event)
{if(event.target!==this._timelineContentBrowser.currentContentView)
return;this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);}
_inspectorVisibilityStateChanged()
{if(WI.timelineManager.activeRecording!==this._recording)
return;if(!WI.visible&&this._updating){this._stopUpdatingCurrentTime();return;}
if(!WI.visible)
return;let{startTime,endTime}=this.representedObject;if(!WI.timelineManager.isCapturing()){
this._updateTimes(startTime,endTime,endTime);return;}
this._startUpdatingCurrentTime(endTime);}
_update(timestamp)
{ if(!(WI.tabBrowser.selectedTabContentView instanceof WI.TimelineTabContentView))
return;if(this._waitingToResetCurrentTime){requestAnimationFrame(this._updateCallback);return;}
var startTime=this._recording.startTime;var currentTime=this._currentTime||startTime;var endTime=this._recording.endTime;var timespanSinceLastUpdate=(timestamp-this._lastUpdateTimestamp)/1000||0;currentTime+=timespanSinceLastUpdate;this._updateTimes(startTime,currentTime,endTime);if(!this._updating&&(currentTime>=endTime||isNaN(endTime))){if(this.isAttached)
this._lastUpdateTimestamp=NaN;return;}
this._lastUpdateTimestamp=timestamp;requestAnimationFrame(this._updateCallback);}
_updateTimes(startTime,currentTime,endTime)
{if(this._startTimeNeedsReset&&!isNaN(startTime)){this._timelineOverview.startTime=startTime;this._overviewTimelineView.zeroTime=startTime;for(let timelineView of this._timelineViewMap.values())
timelineView.zeroTime=startTime;this._startTimeNeedsReset=false;}
if(WI.timelineManager.capturingState!==WI.TimelineManager.CapturingState.Stopping){this._timelineOverview.endTime=Math.max(endTime,currentTime);if(WI.timelineManager.capturingState!==WI.TimelineManager.CapturingState.Inactive){this._currentTime=currentTime;this._timelineOverview.currentTime=currentTime;}}
if(this.currentTimelineView)
this._updateTimelineViewTimes(this.currentTimelineView);this._timelineOverview.updateLayoutIfNeeded();if(this.currentTimelineView)
this.currentTimelineView.updateLayoutIfNeeded();}
_startUpdatingCurrentTime(startTime)
{if(this._updating)
return;if(!WI.visible)
return;if(typeof startTime==="number")
this._currentTime=startTime;else if(!isNaN(this._currentTime)){

this._waitingToResetCurrentTime=true;this._recording.addEventListener(WI.TimelineRecording.Event.TimesUpdated,this._recordingTimesUpdated,this);}
this._updating=true;if(!this._updateCallback)
this._updateCallback=this._update.bind(this);requestAnimationFrame(this._updateCallback);}
_stopUpdatingCurrentTime()
{this._updating=false;if(this._waitingToResetCurrentTime){this._recording.removeEventListener(WI.TimelineRecording.Event.TimesUpdated,this._recordingTimesUpdated,this);this._waitingToResetCurrentTime=false;}}
_handleTimelineCapturingStateChanged(event)
{let{startTime,endTime}=event.data;this._updateProgressView();switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Active:if(!this._updating)
this._startUpdatingCurrentTime(startTime);this._clearTimelineNavigationItem.enabled=!this._recording.readonly;this._exportButtonNavigationItem.enabled=false;break;case WI.TimelineManager.CapturingState.Inactive:if(this._updating)
this._stopUpdatingCurrentTime();if(this.currentTimelineView)
this._updateTimelineViewTimes(this.currentTimelineView);this._exportButtonNavigationItem.enabled=this._recording.canExport();break;}}
_debuggerPaused(event)
{if(this._updating)
this._stopUpdatingCurrentTime();}
_debuggerResumed(event)
{if(!this._updating)
this._startUpdatingCurrentTime();}
_recordingTimesUpdated(event)
{if(!this._waitingToResetCurrentTime)
return;
for(var timeline of this._recording.timelines.values()){var lastRecord=timeline.records.lastValue;if(!lastRecord)
continue;this._currentTime=Math.max(this._currentTime,lastRecord.startTime);}
this._recording.removeEventListener(WI.TimelineRecording.Event.TimesUpdated,this._recordingTimesUpdated,this);this._waitingToResetCurrentTime=false;}
_handleAutoStopCheckboxCheckedDidChange(event)
{WI.settings.timelinesAutoStop.value=this._autoStopCheckboxNavigationItem.checked;}
_handleTimelinesAutoStopSettingChanged(event)
{this._autoStopCheckboxNavigationItem.checked=WI.settings.timelinesAutoStop.value;}
_exportTimelineRecording()
{let json={version:WI.TimelineRecording.SerializationVersion,recording:this._recording.exportData(),overview:this._timelineOverview.exportData(),};if(!json.recording||!json.overview){InspectorFrontendHost.beep();return;}
let frameName=null;let mainFrame=WI.networkManager.mainFrame;if(mainFrame)
frameName=mainFrame.mainResource.urlComponents.host||mainFrame.mainResource.displayName;let filename=frameName?`${frameName}-recording`:this._recording.displayName;WI.FileUtilities.save({content:JSON.stringify(json),suggestedName:filename+".json",forceSaveAs:true,});}
_exportButtonNavigationItemClicked(event)
{this._exportTimelineRecording();}
_importButtonNavigationItemClicked(event)
{WI.FileUtilities.importJSON((result)=>WI.timelineManager.processJSON(result),{multiple:true});}
_clearTimeline(event)
{if(this._recording.readonly)
return;if(WI.timelineManager.activeRecording===this._recording&&WI.timelineManager.isCapturing())
WI.timelineManager.stopCapturing();this._recording.reset();}
_updateTimelineOverviewHeight()
{if(this._timelineOverview.editingInstruments)
this._timelineOverview.element.style.height="";else{const rulerHeight=23;let styleValue=(rulerHeight+this._timelineOverview.height)+"px";this._timelineOverview.element.style.height=styleValue;this._timelineContentBrowser.element.style.top=styleValue;}}
_instrumentAdded(instrumentOrEvent)
{let instrument=instrumentOrEvent instanceof WI.Instrument?instrumentOrEvent:instrumentOrEvent.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);this._timelineViewMap.set(timeline,WI.ContentView.createFromRepresentedObject(timeline,{recording:this._recording}));if(timeline.type===WI.TimelineRecord.Type.RenderingFrame)
this._renderingFrameTimeline=timeline;let displayName=WI.TimelineTabContentView.displayNameForTimelineType(timeline.type);let iconClassName=WI.TimelineTabContentView.iconClassNameForTimelineType(timeline.type);let pathComponent=new WI.HierarchicalPathComponent(displayName,iconClassName,timeline);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._timelinePathComponentSelected,this);this._pathComponentMap.set(timeline,pathComponent);this._timelineCountChanged();}
_instrumentRemoved(event)
{let instrument=event.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);let timelineView=this._timelineViewMap.take(timeline);if(this.currentTimelineView===timelineView)
this.showOverviewTimelineView();if(timeline.type===WI.TimelineRecord.Type.RenderingFrame)
this._renderingFrameTimeline=null;this._pathComponentMap.delete(timeline);this._timelineCountChanged();}
_timelineCountChanged()
{var previousPathComponent=null;for(var pathComponent of this._pathComponentMap.values()){if(previousPathComponent){previousPathComponent.nextSibling=pathComponent;pathComponent.previousSibling=previousPathComponent;}
previousPathComponent=pathComponent;}
this._updateTimelineOverviewHeight();}
_recordingReset(event)
{for(let timelineView of this._timelineViewMap.values())
timelineView.reset();this._currentTime=NaN;if(!this._updating){this._startTimeNeedsReset=true;this._updateTimes(0,0,0);}
this._lastUpdateTimestamp=NaN;this._startTimeNeedsReset=true;this._recording.removeEventListener(WI.TimelineRecording.Event.TimesUpdated,this._recordingTimesUpdated,this);this._waitingToResetCurrentTime=false;this._timelineOverview.reset();this._overviewTimelineView.reset();this._clearTimelineNavigationItem.enabled=false;this._exportButtonNavigationItem.enabled=false;}
_recordingUnloaded(event)
{WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);}
_timeRangeSelectionChanged(event)
{if(!this.currentTimelineView)
return;this._updateTimelineViewTimes(this.currentTimelineView);let selectedPathComponent;if(this._timelineOverview.timelineRuler.entireRangeSelected)
selectedPathComponent=this._entireRecordingPathComponent;else{let timelineRange=this._timelineSelectionPathComponent.representedObject;timelineRange.startValue=this.currentTimelineView.startTime;timelineRange.endValue=this.currentTimelineView.endTime;if(!(this.currentTimelineView instanceof WI.RenderingFrameTimelineView)){timelineRange.startValue-=this.currentTimelineView.zeroTime;timelineRange.endValue-=this.currentTimelineView.zeroTime;}
this._updateTimeRangePathComponents();selectedPathComponent=this._timelineSelectionPathComponent;}
if(this._selectedTimeRangePathComponent!==selectedPathComponent){this._selectedTimeRangePathComponent=selectedPathComponent;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);}}
_recordSelected(event)
{let{record}=event.data;this._selectRecordInTimelineView(record);}
_timelineSelected()
{let timeline=this._timelineOverview.selectedTimeline;if(timeline)
this.showTimelineViewForTimeline(timeline);else
this.showOverviewTimelineView();}
_updateTimeRangePathComponents()
{let timelineRange=this._timelineSelectionPathComponent.representedObject;let startValue=timelineRange.startValue;let endValue=timelineRange.endValue;if(isNaN(startValue)||isNaN(endValue)){this._entireRecordingPathComponent.nextSibling=null;return;}
this._entireRecordingPathComponent.nextSibling=this._timelineSelectionPathComponent;let displayName;if(this._timelineOverview.viewMode===WI.TimelineOverview.ViewMode.Timelines){const higherResolution=true;let selectionStart=Number.secondsToString(startValue,higherResolution);let selectionEnd=Number.secondsToString(endValue,higherResolution);const epsilon=0.0001;if(startValue<epsilon)
displayName=WI.UIString("%s \u2013 %s").format(selectionStart,selectionEnd);else{let duration=Number.secondsToString(endValue-startValue,higherResolution);displayName=WI.UIString("%s \u2013 %s (%s)").format(selectionStart,selectionEnd,duration);}}else{startValue+=1;if(startValue===endValue)
displayName=WI.UIString("Frame %d").format(startValue);else
displayName=WI.UIString("Frames %d \u2013 %d").format(startValue,endValue);}
this._timelineSelectionPathComponent.displayName=displayName;this._timelineSelectionPathComponent.title=displayName;}
_createTimelineRangePathComponent(title)
{let range=new WI.TimelineRange(NaN,NaN);let pathComponent=new WI.HierarchicalPathComponent(title||enDash,"time-icon",range);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._timeRangePathComponentSelected,this);return pathComponent;}
_updateTimelineViewTimes(timelineView)
{let timelineRuler=this._timelineOverview.timelineRuler;let entireRangeSelected=timelineRuler.entireRangeSelected;let endTime=this._timelineOverview.selectionStartTime+this._timelineOverview.selectionDuration;if(entireRangeSelected){if(timelineView instanceof WI.RenderingFrameTimelineView)
endTime=this._renderingFrameTimeline.records.length;else if(timelineView instanceof WI.HeapAllocationsTimelineView){
endTime=Number.MAX_VALUE;}else{
endTime=isNaN(this._recording.endTime)?this._recording.currentTime:this._recording.endTime;endTime+=timelineRuler.minimumSelectionDuration;}}
timelineView.startTime=this._timelineOverview.selectionStartTime;timelineView.currentTime=this._currentTime;timelineView.endTime=endTime;}
_editingInstrumentsDidChange(event)
{let editingInstruments=this._timelineOverview.editingInstruments;this.element.classList.toggle(WI.TimelineOverview.EditInstrumentsStyleClassName,editingInstruments);this._updateTimelineOverviewHeight();}
_filterDidChange()
{if(!this.currentTimelineView)
return;this.currentTimelineView.updateFilter(this._filterBarNavigationItem.filterBar.filters);}
_handleTimelineViewRecordFiltered(event)
{if(event.target!==this.currentTimelineView)
return;let timeline=this.currentTimelineView.representedObject;if(!(timeline instanceof WI.Timeline))
return;let record=event.data.record;let filtered=event.data.filtered;this._timelineOverview.recordWasFiltered(timeline,record,filtered);}
_handleTimelineViewRecordSelected(event)
{if(!this.isAttached)
return;let{record}=event.data;this._selectRecordInTimelineOverview(record);this._selectRecordInTimelineView(record);}
_selectRecordInTimelineOverview(record)
{let timeline=this._recording.timelineForRecordType(record.type);if(!timeline)
return;this._timelineOverview.selectRecord(timeline,record);}
_selectRecordInTimelineView(record)
{for(let timelineView of this._timelineViewMap.values()){let recordMatchesTimeline=record&&timelineView.representedObject.type===record.type;if(recordMatchesTimeline&&timelineView!==this.currentTimelineView)
this.showTimelineViewForTimeline(timelineView.representedObject);if(!record||recordMatchesTimeline)
timelineView.selectRecord(record);}}
_handleTimelineViewScannerShow(event)
{if(!this.isAttached)
return;let{time}=event.data;this._timelineOverview.showScanner(time);}
_handleTimelineViewScannerHide(event)
{if(!this.isAttached)
return;this._timelineOverview.hideScanner();}
_handleTimelineViewNeedsEntireSelectedRange(event)
{if(!this.isAttached)
return;this._timelineOverview.timelineRuler.selectEntireRange();}
_handleTimelineViewNeedsFiltersCleared(event)
{if(!this.isAttached)
return;this._filterBarNavigationItem.filterBar.clear();}
_updateProgressView()
{let isCapturing=WI.timelineManager.isCapturing();this._progressView.visible=isCapturing&&this.currentTimelineView&&!this.currentTimelineView.showsLiveRecordingData;}
_updateFilterBar()
{this._filterBarNavigationItem.hidden=!this.currentTimelineView||!this.currentTimelineView.showsFilterBar;}};WI.TimelineRecordingProgressView=class TimelineRecordingProgressView extends WI.View
{constructor()
{super();this.element.classList.add("recording-progress");let statusGroup=this.element.appendChild(document.createElement("div"));statusGroup.className="status";this._statusElement=statusGroup.appendChild(document.createElement("span"));let spinner=new WI.IndeterminateProgressSpinner;statusGroup.appendChild(spinner.element);this._stopRecordingButtonElement=document.createElement("button");this._stopRecordingButtonElement.textContent=WI.UIString("Stop Recording");this._stopRecordingButtonElement.addEventListener("click",()=>WI.timelineManager.stopCapturing());this.element.appendChild(this._stopRecordingButtonElement);WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);} 
get visible()
{return this._visible;}
set visible(x)
{if(this._visible===x)
return;this._visible=x;this.element.classList.toggle("hidden",!this._visible);if(this._visible)
this._updateState();} 
_updateState(){if(!this._visible)
return;switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Starting:case WI.TimelineManager.CapturingState.Active:this._statusElement.textContent=WI.UIString("Recording Timeline Data","Recording Timeline Data @ Timeline Recording Progress","Message for progress of a timeline recording.");this._stopRecordingButtonElement.disabled=false;break;case WI.TimelineManager.CapturingState.Stopping:this._statusElement.textContent=WI.UIString("Stopping Timeline Recording","Stopping Timeline Recording @ Timeline Recording Progress","Message for progress of stopping a timeline recording.");this._stopRecordingButtonElement.disabled=true;break;case WI.TimelineManager.CapturingState.Inactive:
break;}}
_handleTimelineCapturingStateChanged(event)
{this._updateState();}};WI.TimelineRuler=class TimelineRuler extends WI.View
{constructor()
{super();this.element.classList.add("timeline-ruler");this._headerElement=document.createElement("div");this._headerElement.classList.add("header");this.element.appendChild(this._headerElement);this._markersElement=document.createElement("div");this._markersElement.classList.add("markers");this.element.appendChild(this._markersElement);this._zeroTime=0;this._startTime=0;this._endTime=0;this._duration=NaN;this._secondsPerPixel=0;this._selectionStartTime=0;this._selectionEndTime=Number.MAX_VALUE;this._endTimePinned=false;this._snapInterval=0;this._allowsClippedLabels=false;this._allowsTimeRangeSelection=false;this._minimumSelectionDuration=0.01;this._formatLabelCallback=null;this._timeRangeSelectionChanged=false;this._enabled=true;this._scannerMarker=null;this._markerElementMap=new Map;this._cachedClientWidth=0;} 
get enabled()
{return this._enabled;}
set enabled(x)
{if(this._enabled===x)
return;this._enabled=x;this.element.classList.toggle(WI.TreeElementStatusButton.DisabledStyleClassName,!this._enabled);}
get allowsClippedLabels()
{return this._allowsClippedLabels;}
set allowsClippedLabels(x)
{x=!!x;if(this._allowsClippedLabels===x)
return;this._allowsClippedLabels=x;this.needsLayout();}
set formatLabelCallback(x)
{x=x||null;if(this._formatLabelCallback===x)
return;this._formatLabelCallback=x;this.needsLayout();}
get allowsTimeRangeSelection()
{return this._allowsTimeRangeSelection;}
set allowsTimeRangeSelection(x)
{x=!!x;if(this._allowsTimeRangeSelection===x)
return;this._allowsTimeRangeSelection=x;if(x){this._clickEventListener=this._handleClick.bind(this);this._doubleClickEventListener=this._handleDoubleClick.bind(this);this._mouseDownEventListener=this._handleMouseDown.bind(this);this.element.addEventListener("click",this._clickEventListener);this.element.addEventListener("dblclick",this._doubleClickEventListener);this.element.addEventListener("mousedown",this._mouseDownEventListener);this._leftShadedAreaElement=document.createElement("div");this._leftShadedAreaElement.classList.add("shaded-area");this._leftShadedAreaElement.classList.add("left");this._rightShadedAreaElement=document.createElement("div");this._rightShadedAreaElement.classList.add("shaded-area");this._rightShadedAreaElement.classList.add("right");this._leftSelectionHandleElement=document.createElement("div");this._leftSelectionHandleElement.classList.add("selection-handle");this._leftSelectionHandleElement.classList.add("left");this._leftSelectionHandleElement.addEventListener("mousedown",this._handleSelectionHandleMouseDown.bind(this));this._rightSelectionHandleElement=document.createElement("div");this._rightSelectionHandleElement.classList.add("selection-handle");this._rightSelectionHandleElement.classList.add("right");this._rightSelectionHandleElement.addEventListener("mousedown",this._handleSelectionHandleMouseDown.bind(this));this._selectionDragElement=document.createElement("div");this._selectionDragElement.classList.add("selection-drag");this._needsSelectionLayout();}else{this.element.removeEventListener("click",this._clickEventListener);this.element.removeEventListener("dblclick",this._doubleClickEventListener);this.element.removeEventListener("mousedown",this._mouseDownEventListener);this._clickEventListener=null;this._doubleClickEventListener=null;this._mouseDownEventListener=null;this._leftShadedAreaElement.remove();this._rightShadedAreaElement.remove();this._leftSelectionHandleElement.remove();this._rightSelectionHandleElement.remove();this._selectionDragElement.remove();delete this._leftShadedAreaElement;delete this._rightShadedAreaElement;delete this._leftSelectionHandleElement;delete this._rightSelectionHandleElement;delete this._selectionDragElement;}}
get minimumSelectionDuration()
{return this._minimumSelectionDuration;}
set minimumSelectionDuration(x)
{this._minimumSelectionDuration=x;}
get zeroTime()
{return this._zeroTime;}
set zeroTime(x)
{x=x||0;if(this._zeroTime===x)
return;if(this.entireRangeSelected)
this.selectionStartTime=x;this._zeroTime=x;this.needsLayout();}
get startTime()
{return this._startTime;}
set startTime(x)
{x=x||0;if(this._startTime===x)
return;this._startTime=x;if(!isNaN(this._duration))
this._endTime=this._startTime+this._duration;this._currentDividers=null;this.needsLayout();}
get duration()
{if(!isNaN(this._duration))
return this._duration;return this.endTime-this.startTime;}
get endTime()
{if(!this._endTimePinned&&this.layoutPending)
this._recalculate();return this._endTime;}
set endTime(x)
{x=x||0;if(this._endTime===x)
return;this._endTime=x;this._endTimePinned=true;this.needsLayout();}
get secondsPerPixel()
{if(this.layoutPending)
this._recalculate();return this._secondsPerPixel;}
set secondsPerPixel(x)
{x=x||0;if(this._secondsPerPixel===x)
return;this._secondsPerPixel=x;this._endTimePinned=false;this._currentDividers=null;this._currentSliceTime=0;this.needsLayout();}
get snapInterval()
{return this._snapInterval;}
set snapInterval(x)
{if(this._snapInterval===x)
return;this._snapInterval=x;}
get selectionStartTime()
{return this._selectionStartTime;}
set selectionStartTime(x)
{x=this._snapValue(x)||0;if(this._selectionStartTime===x)
return;this._selectionStartTime=x;this._timeRangeSelectionChanged=true;this._needsSelectionLayout();}
get selectionEndTime()
{return this._selectionEndTime;}
set selectionEndTime(x)
{x=this._snapValue(x)||0;if(this._selectionEndTime===x)
return;this._selectionEndTime=x;this._timeRangeSelectionChanged=true;this._needsSelectionLayout();}
get entireRangeSelected()
{return this._selectionStartTime===this._zeroTime&&this._selectionEndTime===Number.MAX_VALUE;}
selectEntireRange()
{this.selectionStartTime=this._zeroTime;this.selectionEndTime=Number.MAX_VALUE;}
addMarker(marker)
{if(this._markerElementMap.has(marker))
return;marker.addEventListener(WI.TimelineMarker.Event.TimeChanged,this._timelineMarkerTimeChanged,this);let markerTime=marker.time-this._startTime;let markerElement=document.createElement("div");markerElement.classList.add(marker.type,"marker");switch(marker.type){case WI.TimelineMarker.Type.LoadEvent:markerElement.title=WI.UIString("Load \u2014 %s").format(Number.secondsToString(markerTime));break;case WI.TimelineMarker.Type.DOMContentEvent:markerElement.title=WI.UIString("DOM Content Loaded \u2014 %s").format(Number.secondsToString(markerTime));break;case WI.TimelineMarker.Type.TimeStamp:if(marker.details)
markerElement.title=WI.UIString("%s \u2014 %s").format(marker.details,Number.secondsToString(markerTime));else
markerElement.title=WI.UIString("Timestamp \u2014 %s").format(Number.secondsToString(markerTime));break;}
this._markerElementMap.set(marker,markerElement);this._needsMarkerLayout();}
clearMarkers()
{for(let[marker,markerElement]of this._markerElementMap){marker.removeEventListener(WI.TimelineMarker.Event.TimeChanged,this._timelineMarkerTimeChanged,this);markerElement.remove();}
this._markerElementMap.clear();this._scannerMarker=null;}
elementForMarker(marker)
{return this._markerElementMap.get(marker)||null;}
showScanner(time)
{if(!this._scannerMarker){this._scannerMarker=new WI.TimelineMarker(time,WI.TimelineMarker.Type.Scanner);this.addMarker(this._scannerMarker);}
this._scannerMarker.time=time;}
hideScanner()
{if(this._scannerMarker)
this._scannerMarker.time=-1;}
updateLayoutIfNeeded(layoutReason)
{
if(this.layoutPending){super.updateLayoutIfNeeded(layoutReason);return;}
let visibleWidth=this._recalculate();if(visibleWidth<=0)
return;if(this._scheduledMarkerLayoutUpdateIdentifier)
this._updateMarkers(visibleWidth,this.duration);if(this._scheduledSelectionLayoutUpdateIdentifier)
this._updateSelection(visibleWidth,this.duration);}
needsLayout(layoutReason)
{if(this.layoutPending)
return;if(this._scheduledMarkerLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledMarkerLayoutUpdateIdentifier);this._scheduledMarkerLayoutUpdateIdentifier=undefined;}
if(this._scheduledSelectionLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledSelectionLayoutUpdateIdentifier);this._scheduledSelectionLayoutUpdateIdentifier=undefined;}
super.needsLayout(layoutReason);} 
layout()
{let visibleWidth=this._recalculate();if(visibleWidth<=0)
return;let duration=this.duration;let pixelsPerSecond=visibleWidth/duration;let dividerCount=Math.round(visibleWidth/WI.TimelineRuler.MinimumDividerSpacing);let sliceTime;if(this._endTimePinned||!this._currentSliceTime){sliceTime=duration/dividerCount;sliceTime=Math.pow(10,Math.ceil(Math.log(sliceTime)/Math.LN10));if(sliceTime*pixelsPerSecond>=5*WI.TimelineRuler.MinimumDividerSpacing)
sliceTime=sliceTime/5;if(sliceTime*pixelsPerSecond>=2*WI.TimelineRuler.MinimumDividerSpacing)
sliceTime=sliceTime/2;this._currentSliceTime=sliceTime;}else{sliceTime=this._currentSliceTime;}
dividerCount=Math.floor(visibleWidth*this.secondsPerPixel/sliceTime);let firstDividerTime=(Math.ceil((this._startTime-this._zeroTime)/sliceTime)*sliceTime)+this._zeroTime;let lastDividerTime=firstDividerTime+sliceTime*dividerCount;if(!this._endTimePinned)
++dividerCount;let dividerData={count:dividerCount,firstTime:firstDividerTime,lastTime:lastDividerTime,};if(Object.shallowEqual(dividerData,this._currentDividers)){this._updateMarkers(visibleWidth,duration);this._updateSelection(visibleWidth,duration);return;}
this._currentDividers=dividerData;let markerDividers=this._markersElement.querySelectorAll("."+WI.TimelineRuler.DividerElementStyleClassName);let dividerElement=this._headerElement.firstChild;for(var i=0;i<=dividerCount;++i){if(!dividerElement){dividerElement=document.createElement("div");dividerElement.className=WI.TimelineRuler.DividerElementStyleClassName;this._headerElement.appendChild(dividerElement);let labelElement=document.createElement("div");labelElement.className=WI.TimelineRuler.DividerLabelElementStyleClassName;dividerElement.appendChild(labelElement);}
let markerDividerElement=markerDividers[i];if(!markerDividerElement){markerDividerElement=document.createElement("div");markerDividerElement.className=WI.TimelineRuler.DividerElementStyleClassName;this._markersElement.appendChild(markerDividerElement);}
let dividerTime=firstDividerTime+(sliceTime*i);let newPosition=(dividerTime-this._startTime)/duration;if(!this._allowsClippedLabels){if(newPosition<0)
continue;if(newPosition>1)
break;if((newPosition*visibleWidth)<WI.TimelineRuler.MinimumLeftDividerSpacing)
continue;}
let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._updatePositionOfElement(dividerElement,newPosition,visibleWidth,property);this._updatePositionOfElement(markerDividerElement,newPosition,visibleWidth,property);dividerElement.firstChild.textContent=isNaN(dividerTime)?"":this._formatDividerLabelText(dividerTime-this._zeroTime);dividerElement=dividerElement.nextSibling;}
while(dividerElement){let nextDividerElement=dividerElement.nextSibling;dividerElement.remove();dividerElement=nextDividerElement;}
for(;i<markerDividers.length;++i)
markerDividers[i].remove();this._updateMarkers(visibleWidth,duration);this._updateSelection(visibleWidth,duration);}
sizeDidChange()
{this._cachedClientWidth=this.element.clientWidth;} 
_needsMarkerLayout()
{if(this.layoutPending)
return;if(this._scheduledMarkerLayoutUpdateIdentifier)
return;this._scheduledMarkerLayoutUpdateIdentifier=requestAnimationFrame(()=>{this._scheduledMarkerLayoutUpdateIdentifier=undefined;let visibleWidth=this._cachedClientWidth;if(visibleWidth<=0)
return;this._updateMarkers(visibleWidth,this.duration);});}
_needsSelectionLayout()
{if(!this._allowsTimeRangeSelection)
return;if(this.layoutPending)
return;if(this._scheduledSelectionLayoutUpdateIdentifier)
return;this._scheduledSelectionLayoutUpdateIdentifier=requestAnimationFrame(()=>{this._scheduledSelectionLayoutUpdateIdentifier=undefined;let visibleWidth=this._cachedClientWidth;if(visibleWidth<=0)
return;this._updateSelection(visibleWidth,this.duration);});}
_recalculate()
{let visibleWidth=this._cachedClientWidth;if(visibleWidth<=0)
return 0;let duration;if(this._endTimePinned)
duration=this._endTime-this._startTime;else
duration=visibleWidth*this._secondsPerPixel;this._secondsPerPixel=duration/visibleWidth;if(!this._endTimePinned)
this._endTime=this._startTime+(visibleWidth*this._secondsPerPixel);return visibleWidth;}
_updatePositionOfElement(element,newPosition,visibleWidth,property)
{newPosition*=this._endTimePinned?100:visibleWidth;let newPositionAprox=Math.round(newPosition*100);let currentPositionAprox=Math.round(parseFloat(element.style[property])*100);if(currentPositionAprox!==newPositionAprox)
element.style[property]=(newPositionAprox/100)+(this._endTimePinned?"%":"px");}
_updateMarkers(visibleWidth,duration)
{if(this._scheduledMarkerLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledMarkerLayoutUpdateIdentifier);this._scheduledMarkerLayoutUpdateIdentifier=undefined;}
for(let[marker,markerElement]of this._markerElementMap){if(marker.time<0){markerElement.remove();continue;}
let newPosition=(marker.time-this._startTime)/duration;let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._updatePositionOfElement(markerElement,newPosition,visibleWidth,property);if(!markerElement.parentNode)
this._markersElement.appendChild(markerElement);}}
_updateSelection(visibleWidth,duration)
{if(this._scheduledSelectionLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledSelectionLayoutUpdateIdentifier);this._scheduledSelectionLayoutUpdateIdentifier=undefined;}
this.element.classList.toggle("allows-time-range-selection",this._allowsTimeRangeSelection);if(!this._allowsTimeRangeSelection)
return;this.element.classList.toggle("selection-hidden",this.entireRangeSelected);if(this.entireRangeSelected){this._dispatchTimeRangeSelectionChangedEvent();return;}
let startTimeClamped=this._selectionStartTime<this._startTime||this._selectionStartTime>this._endTime;let endTimeClamped=this._selectionEndTime<this._startTime||this._selectionEndTime>this._endTime;this.element.classList.toggle("both-handles-clamped",startTimeClamped&&endTimeClamped);let formattedStartTimeText=this._formatDividerLabelText(this._selectionStartTime-this._zeroTime);let formattedEndTimeText=this._formatDividerLabelText(this._selectionEndTime-this._zeroTime);let startProperty=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";let newStartPosition=Number.constrain((this._selectionStartTime-this._startTime)/duration,0,1);this._updatePositionOfElement(this._leftShadedAreaElement,newStartPosition,visibleWidth,"width");this._updatePositionOfElement(this._leftSelectionHandleElement,newStartPosition,visibleWidth,startProperty);this._updatePositionOfElement(this._selectionDragElement,newStartPosition,visibleWidth,startProperty);this._leftSelectionHandleElement.classList.toggle("clamped",startTimeClamped);this._leftSelectionHandleElement.classList.toggle("hidden",startTimeClamped&&endTimeClamped&&this._selectionStartTime<this._startTime);this._leftSelectionHandleElement.title=formattedStartTimeText;let endProperty=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"left":"right";let newEndPosition=1-Number.constrain((this._selectionEndTime-this._startTime)/duration,0,1);this._updatePositionOfElement(this._rightShadedAreaElement,newEndPosition,visibleWidth,"width");this._updatePositionOfElement(this._rightSelectionHandleElement,newEndPosition,visibleWidth,endProperty);this._updatePositionOfElement(this._selectionDragElement,newEndPosition,visibleWidth,endProperty);this._rightSelectionHandleElement.classList.toggle("clamped",endTimeClamped);this._rightSelectionHandleElement.classList.toggle("hidden",startTimeClamped&&endTimeClamped&&this._selectionEndTime>this._endTime);this._rightSelectionHandleElement.title=formattedEndTimeText;if(!this._selectionDragElement.parentNode){this.element.appendChild(this._selectionDragElement);this.element.appendChild(this._leftShadedAreaElement);this.element.appendChild(this._leftSelectionHandleElement);this.element.appendChild(this._rightShadedAreaElement);this.element.appendChild(this._rightSelectionHandleElement);}
this._dispatchTimeRangeSelectionChangedEvent();}
_formatDividerLabelText(value)
{if(this._formatLabelCallback)
return this._formatLabelCallback(value);return Number.secondsToString(value,true);}
_snapValue(value)
{if(!value||!this.snapInterval)
return value;return Math.round(value/this.snapInterval)*this.snapInterval;}
_dispatchTimeRangeSelectionChangedEvent()
{if(!this._timeRangeSelectionChanged)
return;this._timeRangeSelectionChanged=false;this.dispatchEventToListeners(WI.TimelineRuler.Event.TimeRangeSelectionChanged);}
_timelineMarkerTimeChanged()
{this._needsMarkerLayout();}
_shouldIgnoreMicroMovement(event)
{if(this._mousePassedMicroMovementTest)
return false;let pixels=Math.abs(event.pageX-this._mouseStartX);if(pixels<=4)
return true;this._mousePassedMicroMovementTest=true;return false;}
_handleClick(event)
{if(!this._enabled)
return;if(this._mouseMoved)
return;for(let newTarget of document.elementsFromPoint(event.pageX,event.pageY)){if(!newTarget||typeof newTarget.click!=="function")
continue;if(this.element.contains(newTarget))
continue;let newEvent=new event.constructor(event.type,event);newTarget.dispatchEvent(newEvent);if(newEvent.__timelineRecordClickEventHandled)
event.stop();return;}}
_handleDoubleClick(event)
{if(this.entireRangeSelected)
return;this.selectEntireRange();}
_handleMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;this._selectionIsMove=event.target===this._selectionDragElement;this._rulerBoundingClientRect=this.element.getBoundingClientRect();if(this._selectionIsMove){this._lastMousePosition=event.pageX;var selectionDragElementRect=this._selectionDragElement.getBoundingClientRect();this._moveSelectionMaximumLeftOffset=this._rulerBoundingClientRect.left+(event.pageX-selectionDragElementRect.left);this._moveSelectionMaximumRightOffset=this._rulerBoundingClientRect.right-(selectionDragElementRect.right-event.pageX);}else{if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
this._mouseDownPosition=this._rulerBoundingClientRect.right-event.pageX;else
this._mouseDownPosition=event.pageX-this._rulerBoundingClientRect.left;}
this._mouseMoved=false;this._mousePassedMicroMovementTest=false;this._mouseStartX=event.pageX;this._mouseMoveEventListener=this._handleMouseMove.bind(this);this._mouseUpEventListener=this._handleMouseUp.bind(this);document.addEventListener("mousemove",this._mouseMoveEventListener);document.addEventListener("mouseup",this._mouseUpEventListener);event.preventDefault();event.stopPropagation();}
_handleMouseMove(event)
{if(this._shouldIgnoreMicroMovement(event))
return;this._mouseMoved=true;let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let currentMousePosition;if(this._selectionIsMove){currentMousePosition=Math.max(this._moveSelectionMaximumLeftOffset,Math.min(this._moveSelectionMaximumRightOffset,event.pageX));let positionDelta=0;if(isRTL)
positionDelta=this._lastMousePosition-currentMousePosition;else
positionDelta=currentMousePosition-this._lastMousePosition;let offsetTime=positionDelta*this.secondsPerPixel;let selectionDuration=this.selectionEndTime-this.selectionStartTime;let oldSelectionStartTime=this.selectionStartTime;this.selectionStartTime=Math.max(this.startTime,Math.min(this.selectionStartTime+offsetTime,this.endTime-selectionDuration));this.selectionEndTime=this.selectionStartTime+selectionDuration;if(this.snapInterval){

let snapOffset=this.selectionStartTime-oldSelectionStartTime;if(!snapOffset)
return;let positionDrift=(offsetTime-snapOffset*this.snapInterval)/this.secondsPerPixel;currentMousePosition-=positionDrift;}
this._lastMousePosition=currentMousePosition;}else{if(isRTL)
currentMousePosition=this._rulerBoundingClientRect.right-event.pageX;else
currentMousePosition=event.pageX-this._rulerBoundingClientRect.left;this.selectionStartTime=Math.max(this.startTime,this.startTime+(Math.min(currentMousePosition,this._mouseDownPosition)*this.secondsPerPixel));this.selectionEndTime=Math.min(this.startTime+(Math.max(currentMousePosition,this._mouseDownPosition)*this.secondsPerPixel),this.endTime);this.element.classList.add(WI.TimelineRuler.ResizingSelectionStyleClassName);}
this._updateSelection(this._cachedClientWidth,this.duration);event.preventDefault();event.stopPropagation();}
_handleMouseUp(event)
{if(!this._selectionIsMove){this.element.classList.remove(WI.TimelineRuler.ResizingSelectionStyleClassName);if(this.selectionEndTime-this.selectionStartTime<this.minimumSelectionDuration){let currentMousePosition=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
currentMousePosition=this._rulerBoundingClientRect.right-event.pageX;else
currentMousePosition=event.pageX-this._rulerBoundingClientRect.left;if(currentMousePosition>this._mouseDownPosition){this.selectionEndTime=Math.min(this.selectionStartTime+this.minimumSelectionDuration,this.endTime);this.selectionStartTime=this.selectionEndTime-this.minimumSelectionDuration;}else{this.selectionStartTime=Math.max(this.startTime,this.selectionEndTime-this.minimumSelectionDuration);this.selectionEndTime=this.selectionStartTime+this.minimumSelectionDuration;}}}
this._dispatchTimeRangeSelectionChangedEvent();document.removeEventListener("mousemove",this._mouseMoveEventListener);document.removeEventListener("mouseup",this._mouseUpEventListener);delete this._mouseMoveEventListener;delete this._mouseUpEventListener;delete this._mouseDownPosition;delete this._lastMousePosition;delete this._selectionIsMove;delete this._rulerBoundingClientRect;delete this._moveSelectionMaximumLeftOffset;delete this._moveSelectionMaximumRightOffset;event.preventDefault();event.stopPropagation();}
_handleSelectionHandleMouseDown(event)
{if(event.button!==0||event.ctrlKey)
return;this._dragHandleIsStartTime=event.target===this._leftSelectionHandleElement;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
this._mouseDownPosition=this.element.totalOffsetRight-event.pageX;else
this._mouseDownPosition=event.pageX-this.element.totalOffsetLeft;this._selectionHandleMouseMoveEventListener=this._handleSelectionHandleMouseMove.bind(this);this._selectionHandleMouseUpEventListener=this._handleSelectionHandleMouseUp.bind(this);document.addEventListener("mousemove",this._selectionHandleMouseMoveEventListener);document.addEventListener("mouseup",this._selectionHandleMouseUpEventListener);this.element.classList.add(WI.TimelineRuler.ResizingSelectionStyleClassName);event.preventDefault();event.stopPropagation();}
_handleSelectionHandleMouseMove(event)
{let currentMousePosition=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL)
currentMousePosition=this.element.totalOffsetRight-event.pageX;else
currentMousePosition=event.pageX-this.element.totalOffsetLeft;let currentTime=this.startTime+(currentMousePosition*this.secondsPerPixel);if(this.snapInterval)
currentTime=this._snapValue(currentTime);if(event.altKey&&!event.ctrlKey&&!event.metaKey&&!event.shiftKey){if(this._dragHandleIsStartTime){let timeDifference=currentTime-this.selectionStartTime;this.selectionStartTime=Math.max(this.startTime,Math.min(currentTime,this.selectionEndTime-this.minimumSelectionDuration));this.selectionEndTime=Math.min(Math.max(this.selectionStartTime+this.minimumSelectionDuration,this.selectionEndTime-timeDifference),this.endTime);}else{let timeDifference=currentTime-this.selectionEndTime;this.selectionEndTime=Math.min(Math.max(this.selectionStartTime+this.minimumSelectionDuration,currentTime),this.endTime);this.selectionStartTime=Math.max(this.startTime,Math.min(this.selectionStartTime-timeDifference,this.selectionEndTime-this.minimumSelectionDuration));}}else{if(this._dragHandleIsStartTime)
this.selectionStartTime=Math.max(this.startTime,Math.min(currentTime,this.selectionEndTime-this.minimumSelectionDuration));else
this.selectionEndTime=Math.min(Math.max(this.selectionStartTime+this.minimumSelectionDuration,currentTime),this.endTime);}
this._updateSelection(this._cachedClientWidth,this.duration);event.preventDefault();event.stopPropagation();}
_handleSelectionHandleMouseUp(event)
{this.element.classList.remove(WI.TimelineRuler.ResizingSelectionStyleClassName);document.removeEventListener("mousemove",this._selectionHandleMouseMoveEventListener);document.removeEventListener("mouseup",this._selectionHandleMouseUpEventListener);delete this._selectionHandleMouseMoveEventListener;delete this._selectionHandleMouseUpEventListener;delete this._dragHandleIsStartTime;delete this._mouseDownPosition;event.preventDefault();event.stopPropagation();}};WI.TimelineRuler.MinimumLeftDividerSpacing=48;WI.TimelineRuler.MinimumDividerSpacing=64;WI.TimelineRuler.ResizingSelectionStyleClassName="resizing-selection";WI.TimelineRuler.DividerElementStyleClassName="divider";WI.TimelineRuler.DividerLabelElementStyleClassName="label";WI.TimelineRuler.Event={TimeRangeSelectionChanged:"time-ruler-time-range-selection-changed"};WI.TitleView=class TitleView extends WI.View
{constructor(title)
{super();this.element.classList.add("title-view");this.element.textContent=title;}};WI.ToggleButtonNavigationItem=class ToggleButtonNavigationItem extends WI.ButtonNavigationItem
{constructor(identifier,defaultToolTip,alternateToolTip,defaultImage,alternateImage,imageWidth,imageHeight)
{super(identifier,defaultToolTip,defaultImage,imageWidth,imageHeight);this._toggled=false;this._defaultImage=defaultImage;this._alternateImage=alternateImage;this._defaultToolTip=defaultToolTip;this._alternateToolTip=alternateToolTip||defaultToolTip;} 
get defaultToolTip()
{return this._defaultToolTip;}
set defaultToolTip(toolTip)
{this._defaultToolTip=toolTip;if(!this._toggled)
this.tooltip=this._defaultToolTip;}
get alternateToolTip()
{return this._alternateToolTip;}
set alternateToolTip(toolTip)
{this._alternateToolTip=toolTip;if(this._toggled)
this.tooltip=this._alternateToolTip;}
get defaultImage()
{return this._defaultImage;}
get alternateImage()
{return this._alternateImage;}
set alternateImage(image)
{this._alternateImage=image;if(this._toggled)
this.image=this._alternateImage;}
get toggled()
{return this._toggled;}
set toggled(flag)
{flag=flag||false;if(this._toggled===flag)
return;this._toggled=flag;if(this._toggled){this.tooltip=this._alternateToolTip;this.image=this._alternateImage;}else{this.tooltip=this._defaultToolTip;this.image=this._defaultImage;}
if(this.buttonStyle===WI.ButtonNavigationItem.Style.Text||this.buttonStyle===WI.ButtonNavigationItem.Style.ImageAndText)
this.label=this.tooltip;} 
get additionalClassNames()
{return["toggle","button"];}};WI.TreeElementStatusButton=class TreeElementStatusButton extends WI.Object
{constructor(element)
{super();this._element=element;this._element.classList.add("status-button");this._element.addEventListener("click",this._clicked.bind(this));} 
get element()
{return this._element;}
get hidden()
{return!this._element.classList.contains(WI.TreeElementStatusButton.DisabledStyleClassName);}
set hidden(flag)
{this._element.classList.toggle("hidden",flag);}
get enabled()
{return!this._element.classList.contains(WI.TreeElementStatusButton.DisabledStyleClassName);}
set enabled(flag)
{if(flag)
this._element.classList.remove(WI.TreeElementStatusButton.DisabledStyleClassName);else
this._element.classList.add(WI.TreeElementStatusButton.DisabledStyleClassName);} 
_clicked(event)
{if(!this.enabled)
return;event.stopPropagation();this.dispatchEventToListeners(WI.TreeElementStatusButton.Event.Clicked,event);}};WI.TreeElementStatusButton.DisabledStyleClassName="disabled";WI.TreeElementStatusButton.Event={Clicked:"status-button-clicked"};WI.TypeTokenView=class TypeTokenView extends WI.Object
{constructor(tokenAnnotator,shouldHaveRightMargin,shouldHaveLeftMargin,titleType,functionOrVariableName)
{super();var span=document.createElement("span");span.classList.add("type-token");if(shouldHaveRightMargin)
span.classList.add("type-token-right-spacing");if(shouldHaveLeftMargin)
span.classList.add("type-token-left-spacing");this.element=span;this._tokenAnnotator=tokenAnnotator;this._typeDescription=null;this._colorClass=null;this._popoverTitle=WI.TypeTokenView.titleForPopover(titleType,functionOrVariableName);this._setUpMouseoverHandlers();} 
static titleForPopover(titleType,functionOrVariableName)
{if(titleType===WI.TypeTokenView.TitleType.Variable)
return WI.UIString("Type information for variable: %s").format(functionOrVariableName);if(functionOrVariableName)
return WI.UIString("Return type for function: %s").format(functionOrVariableName);return WI.UIString("Return type for anonymous function");} 
update(typeDescription)
{this._typeDescription=typeDescription;var title=this._displayTypeName();if(title===this.element.textContent)
return;this.element.textContent=title;var hashString=title[title.length-1]==="?"?title.slice(0,title.length-1):title;if(this._colorClass)
this.element.classList.remove(this._colorClass);this._colorClass=WI.TypeTokenView.ColorClassForType[hashString]||"type-token-default";this.element.classList.add(this._colorClass);} 
_setUpMouseoverHandlers()
{var timeoutID=null;this.element.addEventListener("mouseover",function(){function showPopoverAfterDelay()
{timeoutID=null;var domRect=this.element.getBoundingClientRect();var bounds=new WI.Rect(domRect.left,domRect.top,domRect.width,domRect.height);this._tokenAnnotator.sourceCodeTextEditor.showPopoverForTypes(this._typeDescription,bounds,this._popoverTitle);}
if(this._shouldShowPopover())
timeoutID=setTimeout(showPopoverAfterDelay.bind(this),WI.TypeTokenView.DelayHoverTime);}.bind(this));this.element.addEventListener("mouseout",function(){if(timeoutID)
clearTimeout(timeoutID);});}
_shouldShowPopover()
{if(!this._typeDescription.valid)
return false;if(this._typeDescription.typeSet.primitiveTypeNames.length>1)
return true;if(this._typeDescription.structures&&this._typeDescription.structures.length)
return true;return false;}
_displayTypeName()
{if(!this._typeDescription.valid)
return"";var typeSet=this._typeDescription.typeSet;if(this._typeDescription.leastCommonAncestor){if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Object))
return this._typeDescription.leastCommonAncestor;if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Object|WI.TypeSet.NullOrUndefinedTypeBits))
return this._typeDescription.leastCommonAncestor+"?";} 
if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Function))
return"Function";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Undefined))
return"Undefined";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Null))
return"Null";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Boolean))
return"Boolean";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Integer))
return"Integer";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Number|WI.TypeSet.TypeBit.Integer))
return"Number";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.String))
return"String";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Symbol))
return"Symbol";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.BigInt))
return"BigInt";if(typeSet.isContainedIn(WI.TypeSet.NullOrUndefinedTypeBits))
return"(?)";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Function|WI.TypeSet.NullOrUndefinedTypeBits))
return"Function?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Boolean|WI.TypeSet.NullOrUndefinedTypeBits))
return"Boolean?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Integer|WI.TypeSet.NullOrUndefinedTypeBits))
return"Integer?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Number|WI.TypeSet.TypeBit.Integer|WI.TypeSet.NullOrUndefinedTypeBits))
return"Number?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.String|WI.TypeSet.NullOrUndefinedTypeBits))
return"String?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Symbol|WI.TypeSet.NullOrUndefinedTypeBits))
return"Symbol?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.BigInt|WI.TypeSet.NullOrUndefinedTypeBits))
return"BigInt?";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Object|WI.TypeSet.TypeBit.Function|WI.TypeSet.TypeBit.String))
return"Object";if(typeSet.isContainedIn(WI.TypeSet.TypeBit.Object|WI.TypeSet.TypeBit.Function|WI.TypeSet.TypeBit.String|WI.TypeSet.NullOrUndefinedTypeBits))
return"Object?";return WI.UIString("(many)");}};WI.TypeTokenView.TitleType={Variable:Symbol("title-type-variable"),ReturnStatement:Symbol("title-type-return-statement")};WI.TypeTokenView.ColorClassForType={"String":"type-token-string","Symbol":"type-token-symbol","BigInt":"type-token-bigint","Function":"type-token-function","Number":"type-token-number","Integer":"type-token-number","Undefined":"type-token-empty","Null":"type-token-empty","(?)":"type-token-empty","Boolean":"type-token-boolean","(many)":"type-token-many"};WI.TypeTokenView.DelayHoverTime=350;WI.TypeTreeElement=class TypeTreeElement extends WI.GeneralTreeElement
{constructor(name,structureDescription,isPrototype)
{const classNames=null;const title=null;const subtitle=null;super(classNames,title,subtitle,structureDescription||null);this._name=name;this._structureDescription=structureDescription||null;this._isPrototype=isPrototype;this._populated=false;this._autoExpandedChildren=false;this.toggleOnClick=true;this.selectable=false;this.tooltipHandledSeparately=true;this.hasChildren=structureDescription;var displayName=this._isPrototype?WI.UIString("%s Prototype").format(name.replace(/Prototype$/,"")):name;var nameElement=document.createElement("span");nameElement.classList.add("type-name");nameElement.textContent=displayName;this.mainTitle=nameElement;this.addClassName("type-tree-element");if(this._isPrototype)
this.addClassName("prototype");} 
get name()
{return this._name;}
get isPrototype()
{return this._isPrototype;} 
onpopulate()
{if(this._populated)
return;this._populated=true;var properties=[];for(var name of this._structureDescription.fields){if(name==="")
continue;properties.push({name});}
properties.sort(WI.ObjectTreeView.comparePropertyDescriptors);var optionalProperties=[];for(var name of this._structureDescription.optionalFields){if(name==="")
continue;optionalProperties.push({name:name+"?"});}
optionalProperties.sort(WI.ObjectTreeView.comparePropertyDescriptors);for(var property of properties)
this.appendChild(new WI.TypeTreeElement(property.name,null));for(var property of optionalProperties)
this.appendChild(new WI.TypeTreeElement(property.name,null));if(this._structureDescription.imprecise){var truncatedMessageElement=WI.ObjectTreeView.createEmptyMessageElement(ellipsis);this.appendChild(new WI.TreeElement(truncatedMessageElement,null,false));}
if(!this.children.length){var emptyMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("No Properties"));this.appendChild(new WI.TreeElement(emptyMessageElement,null,false));}
var prototypeStructure=this._structureDescription.prototypeStructure;if(prototypeStructure)
this.appendChild(new WI.TypeTreeElement(prototypeStructure.constructorName,prototypeStructure,true));}
onexpand()
{if(this._autoExpandedChildren)
return;this._autoExpandedChildren=true;var lastChild=this.children[this.children.length-1];if(lastChild&&lastChild.hasChildren&&lastChild.isPrototype&&lastChild.name!=="Object")
lastChild.expand();}};WI.TypeTreeView=class TypeTreeView extends WI.Object
{constructor(typeDescription)
{super();this._typeDescription=typeDescription;this._element=document.createElement("div");this._element.className="type-tree";this._outline=new WI.TreeOutline;this._outline.customIndent=true;this._outline.element.classList.add("type");this._element.appendChild(this._outline.element);this._populate();if(this._outline.children.length===1)
this._outline.children[0].expand();} 
get typeDescription()
{return this._typeDescription;}
get element()
{return this._element;}
get treeOutline()
{return this._outline;} 
_populate()
{var types=[];for(var structure of this._typeDescription.structures)
types.push({name:structure.constructorName,structure});for(var primitiveName of this._typeDescription.typeSet.primitiveTypeNames)
types.push({name:primitiveName});types.sort(WI.ObjectTreeView.comparePropertyDescriptors);for(var type of types)
this._outline.appendChild(new WI.TypeTreeElement(type.name,type.structure,false));if(this._typeDescription.truncated){var truncatedMessageElement=WI.ObjectTreeView.createEmptyMessageElement(ellipsis);this._outline.appendChild(new WI.TreeElement(truncatedMessageElement,null,false));}
if(!this._outline.children.length){var errorMessageElement=WI.ObjectTreeView.createEmptyMessageElement(WI.UIString("No Properties"));this._outline.appendChild(new WI.TreeElement(errorMessageElement,null,false));}}};WI.URLBreakpointPopover=class URLBreakpointPopover extends WI.BreakpointPopover
{constructor(delegate,breakpoint)
{super(delegate,breakpoint);this._urlCodeMirror=null;} 
static get supportsEditing()
{return WI.URLBreakpoint.supportsEditing;} 
populateContent(contentElement)
{let typeLabelElement=document.createElement("label");typeLabelElement.textContent=WI.UIString("Type");this._typeSelectElement=document.createElement("select");this._typeSelectElement.id="edit-breakpoint-popover-content-type";let createOption=(text,value)=>{let optionElement=this._typeSelectElement.appendChild(document.createElement("option"));optionElement.textContent=text;optionElement.value=value;};createOption(WI.UIString("Containing"),WI.URLBreakpoint.Type.Text);createOption(WI.UIString("Matching"),WI.URLBreakpoint.Type.RegularExpression);this._typeSelectElement.value=WI.URLBreakpoint.Type.Text;this._typeSelectElement.addEventListener("change",(event)=>{this._updateEditor();this._urlCodeMirror.focus();});typeLabelElement.setAttribute("for",this._typeSelectElement.id);this.addRow("type",typeLabelElement,this._typeSelectElement);let urlLabelElement=document.createElement("label");urlLabelElement.textContent=WI.UIString("URL");let urlEditorElement=document.createElement("div");urlEditorElement.classList.add("editor");this._urlCodeMirror=WI.CodeMirrorEditor.create(urlEditorElement,{lineWrapping:false,matchBrackets:false,scrollbarStyle:null,});this._updateEditor();this._urlCodeMirror.addKeyMap({"Enter":()=>{this.dismiss();},"Esc":()=>{this.dismiss();},});let urlCodeMirrorInputField=this._urlCodeMirror.getInputField();urlCodeMirrorInputField.id="edit-breakpoint-popover-content-url";urlLabelElement.setAttribute("for",urlCodeMirrorInputField.id);this.addRow("url",urlLabelElement,urlEditorElement);setTimeout(()=>{this._urlCodeMirror.refresh();this._urlCodeMirror.focus();this.update();});}
createBreakpoint(options={})
{let type=this._typeSelectElement.value;if(!type)
return null;let url=this._urlCodeMirror.getValue();if(!url)
return null;return new WI.URLBreakpoint(type,url,options);} 
_updateEditor()
{let placeholder;let mimeType;if(this._typeSelectElement.value===WI.URLBreakpoint.Type.Text){placeholder=WI.UIString("Text");mimeType="text/plain";}else{placeholder=WI.UIString("Regular Expression");mimeType="text/x-regex";}
this._urlCodeMirror.setOption("mode",mimeType);this._urlCodeMirror.setOption("placeholder",placeholder);}};WI.URLBreakpointPopover.ReferencePage=WI.ReferencePage.URLBreakpoints;WI.URLBreakpointTreeElement=class URLBreakpointTreeElement extends WI.BreakpointTreeElement
{constructor(breakpoint,{classNames,title}={})
{if(!Array.isArray(classNames))
classNames=[];classNames.push("url");if(!title)
title=breakpoint.displayName;super(breakpoint,{classNames,title});}};WI.WebSocketContentView=class WebSocketContentView extends WI.ContentView
{constructor(resource)
{super(resource);this._updateFramesDebouncer=new Debouncer(()=>{this._updateFrames();});this._resource=resource;this._framesRendered=0;this._lastRenderedReadyState=null;this._showTimeColumn=InspectorBackend.hasEvent("Network.webSocketWillSendHandshakeRequest","walltime");this.element.classList.add("web-socket","resource");let columns={data:{}};columns.data.title=WI.UIString("Data");columns.data.sortable=false;columns.data.width="85%";if(this._showTimeColumn){columns.time={};columns.time.title=WI.UIString("Time");columns.time.sortable=true;}
this._dataGrid=new WI.DataGrid(columns);this._dataGrid.variableHeightRows=true;this.addSubview(this._dataGrid);this._addRow(WI.UIString("WebSocket Connection Established"),this._resource.walltime);this._dataGrid.updateLayout();} 
static textForOpcode(opcode)
{switch(opcode){case WI.WebSocketResource.OpCodes.ContinuationFrame:return WI.UIString("Continuation Frame");case WI.WebSocketResource.OpCodes.TextFrame:return WI.UIString("Text Frame");case WI.WebSocketResource.OpCodes.BinaryFrame:return WI.UIString("Binary Frame");case WI.WebSocketResource.OpCodes.ConnectionCloseFrame:return WI.UIString("Connection Close Frame");case WI.WebSocketResource.OpCodes.PingFrame:return WI.UIString("Ping Frame");case WI.WebSocketResource.OpCodes.PongFrame:return WI.UIString("Pong Frame");}} 
attached()
{super.attached();this._updateFramesDebouncer.force();this._resource.addEventListener(WI.WebSocketResource.Event.FrameAdded,this._updateFramesSoon,this);this._resource.addEventListener(WI.WebSocketResource.Event.ReadyStateChanged,this._updateFramesSoon,this);}
detached()
{this._resource.removeEventListener(WI.WebSocketResource.Event.FrameAdded,this._updateFramesSoon,this);this._resource.removeEventListener(WI.WebSocketResource.Event.ReadyStateChanged,this._updateFramesSoon,this);super.detached();} 
_updateFramesSoon()
{this._updateFramesDebouncer.delayForFrame();}
_updateFrames()
{let shouldScrollToBottom=this._dataGrid.isScrolledToLastRow();let framesLength=this._resource.frames.length;for(let index=this._framesRendered;index<framesLength;index++){let frame=this._resource.frames[index];let{data,isOutgoing,opcode,walltime}=frame;this._addFrame(data,isOutgoing,opcode,walltime);}
this._framesRendered=framesLength;if(this._lastRenderedReadyState!==this._resource.readyState){if(this._resource.readyState===WI.WebSocketResource.ReadyState.Closed)
this._dataGrid.appendChild(new WI.SpanningDataGridNode(WI.UIString("Connection Closed")));this._lastRenderedReadyState=this._resource.readyState;}
if(shouldScrollToBottom){if(!this._scrollToLastRowDebouncer){this._scrollToLastRowDebouncer=new Debouncer(()=>{this._dataGrid.scrollToLastRow();});}
this._scrollToLastRowDebouncer.delayForFrame();}}
_addFrame(data,isOutgoing,opcode,time)
{let nodeText;let isText=opcode===WI.WebSocketResource.OpCodes.TextFrame;if(isText)
nodeText=data;else
nodeText=WI.WebSocketContentView.textForOpcode(opcode);this._addRow(nodeText,time,{isOutgoing,isText});}
_addRow(data,time,attributes={})
{let node;if(this._showTimeColumn)
node=new WI.WebSocketDataGridNode({...attributes,data,time});else
node=new WI.WebSocketDataGridNode({...attributes,data});this._dataGrid.appendChild(node);if(attributes.isText)
node.element.classList.add("text-frame");else
node.element.classList.add("non-text-frame");if(attributes.isOutgoing)
node.element.classList.add("outgoing");else
node.element.classList.add("incoming");}};WI.WebSocketDataGridNode=class WebSocketDataGridNode extends WI.DataGridNode
{ createCellContent(columnIdentifier)
{if(columnIdentifier==="data"){let fragment=document.createDocumentFragment();if(this._data.isOutgoing){let iconElement=WI.ImageUtilities.useSVGSymbol("Images/ArrowUp.svg","icon",WI.UIString("Outgoing message"));fragment.appendChild(iconElement);}
fragment.appendChild(document.createTextNode(this._data.data));return fragment;}
if(columnIdentifier==="time")
return this._timeStringFromTimestamp(this._data.time);return super.createCellContent(columnIdentifier);} 
appendContextMenuItems(contextMenu)
{let logResult=(result,wasThrown,savedResultIndex)=>{const title=WI.UIString("Selected Frame");const addSpecialUserLogClass=true;const shouldRevealConsole=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(title,result,addSpecialUserLogClass,shouldRevealConsole);};if(this._data.isText){let remoteObject=WI.RemoteObject.fromPrimitiveValue(this._data.data);contextMenu.appendItem(WI.UIString("Log Frame Text"),()=>{WI.runtimeManager.saveResult(remoteObject,(savedResultIndex)=>{logResult(remoteObject,false,savedResultIndex);});});if(this._data.data.isJSON()){contextMenu.appendItem(WI.UIString("Log Frame Value"),()=>{const options={objectGroup:WI.RuntimeManager.ConsoleObjectGroup,generatePreview:true,saveResult:true,doNotPauseOnExceptionsAndMuteConsole:true,};let expression="("+this._data.data+")";WI.runtimeManager.evaluateInInspectedWindow(expression,options,logResult);});}
contextMenu.appendSeparator();}
return super.appendContextMenuItems(contextMenu);} 
_timeStringFromTimestamp(timestamp)
{return new Date(timestamp*1000).toLocaleTimeString();}};WI.WebSocketResourceTreeElement=class WebSocketResourceTreeElement extends WI.ResourceTreeElement
{ onattach()
{super.onattach();this._updateConnectionStatus();this.resource.addEventListener(WI.WebSocketResource.Event.ReadyStateChanged,this._updateConnectionStatus,this);}
ondetach()
{this.resource.removeEventListener(WI.WebSocketResource.Event.ReadyStateChanged,this._updateConnectionStatus,this);super.ondetach();}
populateContextMenu(contextMenu,event)
{contextMenu.appendItem(WI.UIString("Log WebSocket"),()=>{WI.RemoteObject.resolveWebSocket(this._resource,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject)
return;const text=WI.UIString("Selected WebSocket");const addSpecialUserLogClass=true;WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,addSpecialUserLogClass);});});contextMenu.appendSeparator();super.populateContextMenu(contextMenu,event);} 
_updateConnectionStatus()
{switch(this.resource.readyState){case WI.WebSocketResource.ReadyState.Closed:this.status="";break;case WI.WebSocketResource.ReadyState.Connecting:var connectionIndicatorElement=document.createElement("div");connectionIndicatorElement.classList.add("ready-state","connecting");connectionIndicatorElement.title=WI.UIString("Connecting");this.status=connectionIndicatorElement;break;case WI.WebSocketResource.ReadyState.Open:var connectionIndicatorElement=document.createElement("div");connectionIndicatorElement.classList.add("ready-state","open");connectionIndicatorElement.title=WI.UIString("Open");this.status=connectionIndicatorElement;break;}}};
WI.WorkerTreeElement=class WorkerTreeElement extends WI.ScriptTreeElement
{constructor(target)
{let options={};if(target instanceof WI.WorkerTarget)
options.mainTitle=target.customName;super(target.mainResource,options);this._target=target;this._target.addEventListener(WI.Target.Event.ResourceAdded,this._resourceAdded,this);this._target.addEventListener(WI.Target.Event.ScriptAdded,this._scriptAdded,this);this._expandedSetting=new WI.Setting("worker-expanded-"+this._target.name.hash,true);this.registerFolderizeSettings("scripts",null,this._target.resourceCollection.resourceCollectionForType(WI.Resource.Type.Script),WI.ResourceTreeElement);this.registerFolderizeSettings("extra-scripts",null,this._target.extraScriptCollection,WI.ScriptTreeElement);for(let[key,value]of Object.entries(WI.Resource.Type)){if(value===WI.Resource.Type.Script)
continue;let folderName=WI.Resource.displayNameForType(value,true);this.registerFolderizeSettings(key,folderName,this._target.resourceCollection.resourceCollectionForType(value),WI.ResourceTreeElement);}
this.updateParentStatus();if(this._expandedSetting.value)
this.expand();} 
get target(){return this._target;}
onexpand()
{this._expandedSetting.value=true;}
oncollapse()
{if(this.hasChildren)
this._expandedSetting.value=false;}
onpopulate()
{if(this.children.length&&!this.shouldRefreshChildren)
return;this.shouldRefreshChildren=false;this.removeChildren();this.prepareToPopulate();for(let resource of this._target.resourceCollection)
this.addChildForRepresentedObject(resource);for(let script of this._target.extraScriptCollection)
this.addChildForRepresentedObject(script);let sourceMaps=this._target.mainResource.sourceMaps;for(let sourceMap of sourceMaps){for(let resource of sourceMap.resources)
this.addChildForRepresentedObject(resource);}}
populateContextMenu(contextMenu,event)
{ WI.appendContextMenuItemsForSourceCode(contextMenu,this.script.resource?this.script.resource:this.script);super.populateContextMenu(contextMenu,event);}
updateSourceMapResources()
{if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren)
return;this.updateParentStatus();if(this._target.mainResource.sourceMaps.length){this.hasChildren=true;this.shouldRefreshChildren=true;}}
onattach()
{WI.GeneralTreeElement.prototype.onattach.call(this);} 
compareChildTreeElements(a,b)
{let aIsResource=a instanceof WI.ResourceTreeElement;let bIsResource=b instanceof WI.ResourceTreeElement;if(aIsResource&&bIsResource)
return WI.ResourceTreeElement.compareResourceTreeElements(a,b);if(!aIsResource&&!bIsResource)
return super.compareChildTreeElements(a,b);return aIsResource?1:-1;} 
_scriptAdded(event)
{let script=event.data.script;if(!script.url&&!script.sourceURL)
return;this.addRepresentedObjectToNewChildQueue(script);}
_resourceAdded(event)
{this.addRepresentedObjectToNewChildQueue(event.data.resource);}};WI.Annotator=class Annotator extends WI.Object
{constructor(sourceCodeTextEditor)
{super();this._sourceCodeTextEditor=sourceCodeTextEditor;this._timeoutIdentifier=null;this._isActive=false;} 
get sourceCodeTextEditor()
{return this._sourceCodeTextEditor;}
isActive()
{return this._isActive;}
pause()
{this._clearTimeoutIfNeeded();this._isActive=false;}
resume()
{this._clearTimeoutIfNeeded();this._isActive=true;this.insertAnnotations();}
refresh()
{if(!this._isActive)
return;this._clearTimeoutIfNeeded();this.insertAnnotations();}
reset()
{this._clearTimeoutIfNeeded();this._isActive=true;this.clearAnnotations();this.insertAnnotations();}
clear()
{this.pause();this.clearAnnotations();} 
insertAnnotations()
{}
clearAnnotations()
{} 
_clearTimeoutIfNeeded()
{if(this._timeoutIdentifier){clearTimeout(this._timeoutIdentifier);this._timeoutIdentifier=null;}}};WI.CodeMirrorEditingController=class CodeMirrorEditingController extends WI.Object
{constructor(codeMirror,marker)
{super();this._codeMirror=codeMirror;this._marker=marker;this._delegate=null;this._range=marker.range;this._value=this.initialValue;this._keyboardShortcutEsc=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape);} 
get marker()
{return this._marker;}
get range()
{return this._range;}
get value()
{return this._value;}
set value(value)
{this.text=value.toString();this._value=value;}
get delegate()
{return this._delegate;}
set delegate(delegate)
{this._delegate=delegate;}
get text()
{var from={line:this._range.startLine,ch:this._range.startColumn};var to={line:this._range.endLine,ch:this._range.endColumn};return this._codeMirror.getRange(from,to);}
set text(text)
{var from={line:this._range.startLine,ch:this._range.startColumn};var to={line:this._range.endLine,ch:this._range.endColumn};this._codeMirror.replaceRange(text,from,to);var lines=text.split("\n");var endLine=this._range.startLine+lines.length-1;var endColumn=lines.length>1?lines.lastValue.length:this._range.startColumn+text.length;this._range=new WI.TextRange(this._range.startLine,this._range.startColumn,endLine,endColumn);}
get initialValue()
{return this.text;}
get cssClassName()
{return"";}
get popover()
{return this._popover;}
get popoverPreferredEdges()
{
return[WI.RectEdge.MIN_X,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];}
popoverTargetFrameWithRects(rects)
{return WI.Rect.unionOfRects(rects);}
presentHoverMenu()
{if(!this.cssClassName)
return;this._hoverMenu=new WI.HoverMenu(this);this._hoverMenu.element.classList.add(this.cssClassName);this._rects=this._marker.rects;this._hoverMenu.present(this._rects);}
dismissHoverMenu(discrete)
{if(!this._hoverMenu)
return;this._hoverMenu.dismiss(discrete);}
popoverWillPresent(popover)
{}
popoverDidPresent(popover)
{}
popoverDidDismiss(popover)
{} 
handleKeydownEvent(event)
{if(!this._keyboardShortcutEsc.matchesEvent(event)||!this._popover.visible)
return false;this.value=this._originalValue;this._popover.dismiss();return true;}
hoverMenuButtonWasPressed(hoverMenu)
{this._popover=new WI.Popover(this);this.popoverWillPresent(this._popover);this._popover.present(this.popoverTargetFrameWithRects(this._rects).pad(2),this.popoverPreferredEdges);this.popoverDidPresent(this._popover);WI.addWindowKeydownListener(this);hoverMenu.dismiss();if(this._delegate&&typeof this._delegate.editingControllerDidStartEditing==="function")
this._delegate.editingControllerDidStartEditing(this);this._originalValue=this._value.copy();}
didDismissPopover(popover)
{delete this._popover;delete this._originalValue;WI.removeWindowKeydownListener(this);this.popoverDidDismiss();if(this._delegate&&typeof this._delegate.editingControllerDidFinishEditing==="function")
this._delegate.editingControllerDidFinishEditing(this);}};WI.AnimationManager=class AnimationManager
{constructor()
{this._enabled=false;this._animationCollection=new WI.AnimationCollection;this._animationIdMap=new Map;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleMainResourceDidChange,this);} 
get domains(){return["Animation"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasCommand("Animation.enable"))
target.AnimationAgent.enable();} 
get animationCollection(){return this._animationCollection;}
get supported()
{return InspectorBackend.hasCommand("Animation.enable");}
enable()
{this._enabled=true;for(let target of WI.targets)
this.initializeTarget(target);}
disable()
{for(let target of WI.targets){if(target.hasCommand("Animation.disable"))
target.AnimationAgent.disable();}
this._animationCollection.clear();this._animationIdMap.clear();this._enabled=false;} 
animationCreated(animationPayload)
{let animation=WI.Animation.fromPayload(animationPayload);this._animationCollection.add(animation);this._animationIdMap.set(animation.animationId,animation);}
nameChanged(animationId,name)
{let animation=this._animationIdMap.get(animationId);if(!animation)
return;animation.nameChanged(name);}
effectChanged(animationId,effect)
{let animation=this._animationIdMap.get(animationId);if(!animation)
return;animation.effectChanged(effect);}
targetChanged(animationId,effect)
{let animation=this._animationIdMap.get(animationId);if(!animation)
return;animation.targetChanged(effect);}
animationDestroyed(animationId)
{let animation=this._animationIdMap.take(animationId);if(!animation)
return;this._animationCollection.remove(animation);} 
_handleMainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;WI.Animation.resetUniqueDisplayNameNumbers();this._animationCollection.clear();this._animationIdMap.clear();}};WI.AuditManager=class AuditManager extends WI.Object
{constructor()
{super();this._tests=[];this._results=[];this._runningState=WI.AuditManager.RunningState.Inactive;this._runningTests=[];this._disabledDefaultTestsSetting=new WI.Setting("audit-disabled-default-tests",[]);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);} 
static synthesizeWarning(message)
{message=WI.UIString("Audit Warning: %s").format(message);if(window.InspectorTest){console.warn(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Warning,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);}
static synthesizeError(message)
{message=WI.UIString("Audit Error: %s").format(message);if(window.InspectorTest){console.error(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} 
get tests(){return this._tests;}
get results(){return this._results;}
get runningState(){return this._runningState;}
get editing()
{return this._runningState===WI.AuditManager.RunningState.Disabled;}
set editing(editing)
{if(this._runningState!==WI.AuditManager.RunningState.Disabled&&this._runningState!==WI.AuditManager.RunningState.Inactive)
return;let runningState=editing?WI.AuditManager.RunningState.Disabled:WI.AuditManager.RunningState.Inactive;if(runningState===this._runningState)
return;this._runningState=runningState;this.dispatchEventToListeners(WI.AuditManager.Event.EditingChanged);if(!this.editing){WI.objectStores.audits.clear();let disabledDefaultTests=[];let saveDisabledDefaultTest=(test)=>{if(test.supported&&test.disabled)
disabledDefaultTests.push(test.name);if(test instanceof WI.AuditTestGroup){for(let child of test.tests)
saveDisabledDefaultTest(child);}};for(let test of this._tests){if(test.default)
saveDisabledDefaultTest(test);else
WI.objectStores.audits.putObject(test);}
this._disabledDefaultTestsSetting.value=disabledDefaultTests;}}
async start(tests)
{if(this._runningState!==WI.AuditManager.RunningState.Inactive)
return null;if(tests&&tests.length)
tests=tests.filter((test)=>typeof test==="object"&&test instanceof WI.AuditTestBase);else
tests=this._tests;if(!tests.length)
return null;let mainResource=WI.networkManager.mainFrame.mainResource;this._runningState=WI.AuditManager.RunningState.Active;this.dispatchEventToListeners(WI.AuditManager.Event.RunningStateChanged);this._runningTests=tests;for(let test of this._runningTests)
test.clearResult();this.dispatchEventToListeners(WI.AuditManager.Event.TestScheduled);let target=WI.assumingMainTarget();await Promise.chain(this._runningTests.map((test)=>async()=>{if(this._runningState!==WI.AuditManager.RunningState.Active)
return;if(target.hasDomain("Audit"))
await target.AuditAgent.setup();let topLevelTest=test.topLevelTest;if(topLevelTest)
await topLevelTest.runSetup();await test.start();if(target.hasDomain("Audit"))
await target.AuditAgent.teardown();}));let result=this._runningTests.map((test)=>test.result).filter((result)=>!!result);this._runningState=WI.AuditManager.RunningState.Inactive;this.dispatchEventToListeners(WI.AuditManager.Event.RunningStateChanged);this._runningTests=[];this._addResult(result);if(mainResource!==WI.networkManager.mainFrame.mainResource){for(let test of this._tests)
test.clearResult();}
return this._results.lastValue===result?result:null;}
stop()
{if(this._runningState!==WI.AuditManager.RunningState.Active)
return;this._runningState=WI.AuditManager.RunningState.Stopping;this.dispatchEventToListeners(WI.AuditManager.Event.RunningStateChanged);for(let test of this._runningTests)
test.stop();}
async processJSON({json,error})
{if(error){WI.AuditManager.synthesizeError(error);return;}
if(typeof json!=="object"||json===null){WI.AuditManager.synthesizeError(WI.UIString("invalid JSON"));return;}
if(json.type!==WI.AuditTestCase.TypeIdentifier&&json.type!==WI.AuditTestGroup.TypeIdentifier&&json.type!==WI.AuditTestCaseResult.TypeIdentifier&&json.type!==WI.AuditTestGroupResult.TypeIdentifier){WI.AuditManager.synthesizeError(WI.UIString("unknown %s \u0022%s\u0022").format(WI.unlocalizedString("type"),json.type));return;}
let object=await WI.AuditTestGroup.fromPayload(json)||await WI.AuditTestCase.fromPayload(json)||await WI.AuditTestGroupResult.fromPayload(json)||await WI.AuditTestCaseResult.fromPayload(json);if(!object)
return;if(object instanceof WI.AuditTestBase)
this.addTest(object,{save:true});else if(object instanceof WI.AuditTestResultBase)
this._addResult(object);WI.showRepresentedObject(object);}
export(object)
{let filename=object.name;if(object instanceof WI.AuditTestResultBase)
filename=WI.UIString("%s Result").format(filename);WI.FileUtilities.save({content:JSON.stringify(object),suggestedName:filename+".json",forceSaveAs:true,});}
loadStoredTests()
{if(this._tests.length)
return;this._addDefaultTests();WI.objectStores.audits.getAll().then(async(tests)=>{for(let payload of tests){let test=await WI.AuditTestGroup.fromPayload(payload)||await WI.AuditTestCase.fromPayload(payload);if(!test)
continue;const key=null;WI.objectStores.audits.associateObject(test,key,payload);this.addTest(test);}});}
addTest(test,{save}={})
{this._tests.push(test);if(save)
WI.objectStores.audits.putObject(test);this.dispatchEventToListeners(WI.AuditManager.Event.TestAdded,{test});}
removeTest(test)
{if(test.default){test.clearResult();if(test.disabled){InspectorFrontendHost.beep();return;}
test.disabled=true;let disabledTests=this._disabledDefaultTestsSetting.value.slice();disabledTests.push(test.name);this._disabledDefaultTestsSetting.value=disabledTests;return;}
this._tests.remove(test);this.dispatchEventToListeners(WI.AuditManager.Event.TestRemoved,{test});WI.objectStores.audits.deleteObject(test);} 
_addResult(result)
{if(!result||(Array.isArray(result)&&!result.length))
return;this._results.push(result);this.dispatchEventToListeners(WI.AuditManager.Event.TestCompleted,{result,index:this._results.length-1,});}
_handleFrameMainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;if(this._runningState===WI.AuditManager.RunningState.Active)
this.stop();else{for(let test of this._tests)
test.clearResult();}}
_addDefaultTests()
{if(!WI.DefaultAudits)
return;const defaultTests=[new WI.AuditTestGroup(WI.UIString("Demo Audit"),[new WI.AuditTestGroup(WI.UIString("Result Levels"),[new WI.AuditTestCase("level-pass",WI.DefaultAudits.levelPass.toString(),{description:WI.UIString("This is what the result of a passing test with no data looks like.")}),new WI.AuditTestCase("level-warn",WI.DefaultAudits.levelWarn.toString(),{description:WI.UIString("This is what the result of a warning test with no data looks like.")}),new WI.AuditTestCase("level-fail",WI.DefaultAudits.levelFail.toString(),{description:WI.UIString("This is what the result of a failing test with no data looks like.")}),new WI.AuditTestCase("level-error",WI.DefaultAudits.levelError.toString(),{description:WI.UIString("This is what the result of a test that threw an error with no data looks like.")}),new WI.AuditTestCase("level-unsupported",WI.DefaultAudits.levelUnsupported.toString(),{description:WI.UIString("This is what the result of an unsupported test with no data looks like.")}),],{description:WI.UIString("These are all of the different test result levels.")}),new WI.AuditTestGroup(WI.UIString("Result Data"),[new WI.AuditTestCase("data-domNodes",WI.DefaultAudits.dataDOMNodes.toString(),{description:WI.UIString("This is an example of how result DOM nodes are shown. It will pass with the <body> element.")}),new WI.AuditTestCase("data-domAttributes",WI.DefaultAudits.dataDOMAttributes.toString(),{description:WI.UIString("This is an example of how result DOM attributes are highlighted on any returned DOM nodes. It will pass with all elements with an id attribute.")}),new WI.AuditTestCase("data-errors",WI.DefaultAudits.dataErrors.toString(),{description:WI.UIString("This is an example of how errors are shown. The error was thrown manually, but execution errors will appear in the same way.")}),new WI.AuditTestCase("data-custom",WI.DefaultAudits.dataCustom.toString(),{description:WI.UIString("This is an example of how custom result data is shown."),supports:3}),],{description:WI.UIString("These are example tests that demonstrate all of the different types of data that can be returned with the test result.")}),new WI.AuditTestGroup(WI.UIString("Specially Exposed Data"),[new WI.AuditTestGroup(WI.UIString("Accessibility"),[new WI.AuditTestCase("getElementsByComputedRole",WI.DefaultAudits.getElementsByComputedRole.toString(),{description:WI.UIString("This is an example test that uses %s to find elements with a computed role of \u0022link\u0022.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getElementsByComputedRole")),supports:1}),new WI.AuditTestCase("getActiveDescendant",WI.DefaultAudits.getActiveDescendant.toString(),{description:WI.UIString("This is an example test that uses %s to find any element that meets criteria for active descendant (\u0022%s\u0022) of the <body> element, if it exists.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getActiveDescendant"),WI.unlocalizedString("aria-activedescendant")),supports:1}),new WI.AuditTestCase("getChildNodes",WI.DefaultAudits.getChildNodes.toString(),{description:WI.UIString("This is an example test that uses %s to find child nodes of the <body> element in the accessibility tree.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getChildNodes")),supports:1}),new WI.AuditTestCase("getComputedProperties",WI.DefaultAudits.getComputedProperties.toString(),{description:WI.UIString("This is an example test that uses %s to find a variety of accessibility information about the <body> element.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getComputedProperties")),supports:3}),new WI.AuditTestCase("getControlledNodes",WI.DefaultAudits.getControlledNodes.toString(),{description:WI.UIString("This is an example test that uses %s to find all nodes controlled (\u0022%s\u0022) by the <body> element, if any exist.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getControlledNodes"),WI.unlocalizedString("aria-controls")),supports:1}),new WI.AuditTestCase("getFlowedNodes",WI.DefaultAudits.getFlowedNodes.toString(),{description:WI.UIString("This is an example test that uses %s to find all nodes flowed to (\u0022%s\u0022) from the <body> element, if any exist.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getFlowedNodes"),WI.unlocalizedString("aria-flowto")),supports:1}),new WI.AuditTestCase("getMouseEventNode",WI.DefaultAudits.getMouseEventNode.toString(),{description:WI.UIString("This is an example test that uses %s to find the node that would handle mouse events for the <body> element, if applicable.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getMouseEventNode")),supports:1}),new WI.AuditTestCase("getOwnedNodes",WI.DefaultAudits.getOwnedNodes.toString(),{description:WI.UIString("This is an example test that uses %s to find all nodes owned (\u0022%s\u0022) by the <body> element, if any exist.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getOwnedNodes"),WI.unlocalizedString("aria-owns")),supports:1}),new WI.AuditTestCase("getParentNode",WI.DefaultAudits.getParentNode.toString(),{description:WI.UIString("This is an example test that uses %s to find the parent node of the <body> element in the accessibility tree.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getParentNode")),supports:1}),new WI.AuditTestCase("getSelectedChildNodes",WI.DefaultAudits.getSelectedChildNodes.toString(),{description:WI.UIString("This is an example test that uses %s to find all child nodes that are selected (\u0022%s\u0022) of the <body> element in the accessibility tree.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getSelectedChildNodes"),WI.unlocalizedString("aria-selected")),supports:1}),],{description:WI.UIString("These are example tests that demonstrate how to use %s to get information about the accessibility tree.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility")),supports:1}),new WI.AuditTestGroup(WI.UIString("DOM"),[new WI.AuditTestCase("hasEventListeners",WI.DefaultAudits.hasEventListeners.toString(),{description:WI.UIString("This is an example test that uses %s to find data indicating whether the <body> element has any event listeners.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.hasEventListeners")),supports:3}),new WI.AuditTestCase("hasEventListeners-click",WI.DefaultAudits.hasEventListenersClick.toString(),{description:WI.UIString("This is an example test that uses %s to find data indicating whether the <body> element has any click event listeners.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.hasEventListenersClick")),supports:3}),],{description:WI.UIString("These are example tests that demonstrate how to use %s to get information about DOM nodes.").format(WI.unlocalizedString("WebInspectorAudit.DOM")),supports:1}),new WI.AuditTestGroup(WI.UIString("Resources"),[new WI.AuditTestCase("getResources",WI.DefaultAudits.getResources.toString(),{description:WI.UIString("This is an example test that uses %s to find basic information about each resource.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getResources")),supports:3}),new WI.AuditTestCase("getResourceContent",WI.DefaultAudits.getResourceContent.toString(),{description:WI.UIString("This is an example test that uses %s to find the contents of the main resource.").format(WI.unlocalizedString("WebInspectorAudit.Accessibility.getResourceContent")),supports:3}),],{description:WI.UIString("These are example tests that demonstrate how to use %s to get information about loaded resources.").format(WI.unlocalizedString("WebInspectorAudit.Resources")),supports:2}),],{description:WI.UIString("These are example tests that demonstrate how to use %s to access information not normally available to JavaScript.").format(WI.unlocalizedString("WebInspectorAudit")),supports:1}),new WI.AuditTestCase("unsupported",WI.DefaultAudits.unsupported.toString(),{description:WI.UIString("This is an example of a test that will not run because it is unsupported."),supports:Infinity}),],{description:WI.UIString("These are example tests that demonstrate the functionality and structure of audits.")}),new WI.AuditTestGroup(WI.UIString("Accessibility"),[new WI.AuditTestCase("testMenuRoleForRequiredChildren",WI.DefaultAudits.testMenuRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 and \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("menu"),WI.unlocalizedString("menubar")),supports:1}),new WI.AuditTestCase("testGridRoleForRequiredChildren",WI.DefaultAudits.testGridRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("grid")),supports:1}),new WI.AuditTestCase("testForAriaLabelledBySpelling",WI.DefaultAudits.testForAriaLabelledBySpelling.toString(),{description:WI.UIString("Ensure that \u0022%s\u0022 is spelled correctly.").format(WI.unlocalizedString("aria-labelledby")),supports:1}),new WI.AuditTestCase("testForMultipleBanners",WI.DefaultAudits.testForMultipleBanners.toString(),{description:WI.UIString("Ensure that only one banner is used on the page."),supports:1}),new WI.AuditTestCase("testForLinkLabels",WI.DefaultAudits.testForLinkLabels.toString(),{description:WI.UIString("Ensure that links have accessible labels for assistive technology."),supports:1}),new WI.AuditTestCase("testRowGroupRoleForRequiredChildren",WI.DefaultAudits.testRowGroupRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("rowgroup")),supports:1}),new WI.AuditTestCase("testTableRoleForRequiredChildren",WI.DefaultAudits.testTableRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("table")),supports:1}),new WI.AuditTestCase("testForMultipleLiveRegions",WI.DefaultAudits.testForMultipleLiveRegions.toString(),{description:WI.UIString("Ensure that only one live region is used on the page."),supports:1}),new WI.AuditTestCase("testListBoxRoleForRequiredChildren",WI.DefaultAudits.testListBoxRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("listbox")),supports:1}),new WI.AuditTestCase("testImageLabels",WI.DefaultAudits.testImageLabels.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have accessible labels for assistive technology.").format(WI.unlocalizedString("img")),supports:1}),new WI.AuditTestCase("testForAriaHiddenFalse",WI.DefaultAudits.testForAriaHiddenFalse.toString(),{description:WI.UIString("Ensure aria-hidden=\u0022%s\u0022 is not used.").format(WI.unlocalizedString("false")),supports:1}),new WI.AuditTestCase("testTreeRoleForRequiredChildren",WI.DefaultAudits.testTreeRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("tree")),supports:1}),new WI.AuditTestCase("testRadioGroupRoleForRequiredChildren",WI.DefaultAudits.testRadioGroupRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("radiogroup")),supports:1}),new WI.AuditTestCase("testFeedRoleForRequiredChildren",WI.DefaultAudits.testFeedRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("feed")),supports:1}),new WI.AuditTestCase("testTabListRoleForRequiredChildren",WI.DefaultAudits.testTabListRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("tablist")),supports:1}),new WI.AuditTestCase("testButtonLabels",WI.DefaultAudits.testButtonLabels.toString(),{description:WI.UIString("Ensure that buttons have accessible labels for assistive technology."),supports:1}),new WI.AuditTestCase("testRowRoleForRequiredChildren",WI.DefaultAudits.testRowRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("row")),supports:1}),new WI.AuditTestCase("testListRoleForRequiredChildren",WI.DefaultAudits.testListRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("list")),supports:1}),new WI.AuditTestCase("testComboBoxRoleForRequiredChildren",WI.DefaultAudits.testComboBoxRoleForRequiredChildren.toString(),{description:WI.UIString("Ensure that elements of role \u0022%s\u0022 have required owned elements in accordance with WAI-ARIA.").format(WI.unlocalizedString("combobox")),supports:1}),new WI.AuditTestCase("testForMultipleMainContentSections",WI.DefaultAudits.testForMultipleMainContentSections.toString(),{description:WI.UIString("Ensure that only one main content section is used on the page."),supports:1}),new WI.AuditTestCase("testDialogsForLabels",WI.DefaultAudits.testDialogsForLabels.toString(),{description:WI.UIString("Ensure that dialogs have accessible labels for assistive technology."),supports:1}),new WI.AuditTestCase("testForInvalidAriaHiddenValue",WI.DefaultAudits.testForInvalidAriaHiddenValue.toString(),{description:WI.UIString("Ensure that values for \u0022%s\u0022 are valid.").format(WI.unlocalizedString("aria-hidden")),supports:1})],{description:WI.UIString("Diagnoses common accessibility problems affecting screen readers and other assistive technology.")}),];let checkDisabledDefaultTest=(test)=>{test.markAsDefault();if(this._disabledDefaultTestsSetting.value.includes(test.name))
test.disabled=true;if(test instanceof WI.AuditTestGroup){for(let child of test.tests)
checkDisabledDefaultTest(child);}};for(let test of defaultTests){checkDisabledDefaultTest(test);this.addTest(test);}}};WI.AuditManager.RunningState={Disabled:"disabled",Inactive:"inactive",Active:"active",Stopping:"stopping",};WI.AuditManager.Event={EditingChanged:"audit-manager-editing-changed",RunningStateChanged:"audit-manager-running-state-changed",TestAdded:"audit-manager-test-added",TestCompleted:"audit-manager-test-completed",TestRemoved:"audit-manager-test-removed",TestScheduled:"audit-manager-test-scheduled",};WI.ApplicationCacheManager=class ApplicationCacheManager extends WI.Object
{constructor()
{super();this._enabled=false;this._reset();} 
get domains(){return["ApplicationCache"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("ApplicationCache")){target.ApplicationCacheAgent.enable();target.ApplicationCacheAgent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this));}} 
get online(){return this._online;}
get applicationCacheObjects()
{var applicationCacheObjects=[];for(var id in this._applicationCacheObjects)
applicationCacheObjects.push(this._applicationCacheObjects[id]);return applicationCacheObjects;}
enable()
{this._enabled=true;this._reset();for(let target of WI.targets)
this.initializeTarget(target);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._childFrameWasRemoved,this);}
disable()
{this._enabled=false;for(let target of WI.targets){if(target.hasCommand("ApplicationCache.disable"))
target.ApplicationCacheAgent.disable();}
WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._childFrameWasRemoved,this);this._reset();}
requestApplicationCache(frame,callback)
{function callbackWrapper(error,applicationCache)
{if(error){callback(null);return;}
callback(applicationCache);}
let target=WI.assumingMainTarget();target.ApplicationCacheAgent.getApplicationCacheForFrame(frame.id,callbackWrapper);} 
networkStateUpdated(isNowOnline)
{this._online=isNowOnline;this.dispatchEventToListeners(WI.ApplicationCacheManager.Event.NetworkStateUpdated,{online:this._online});}
applicationCacheStatusUpdated(frameId,manifestURL,status)
{let frame=WI.networkManager.frameForIdentifier(frameId);if(!frame)
return;this._frameManifestUpdated(frame,manifestURL,status);} 
_reset()
{this._online=true;this._applicationCacheObjects={};this.dispatchEventToListeners(WI.ApplicationCacheManager.Event.Cleared);}
_mainResourceDidChange(event)
{if(event.target.isMainFrame()){this._reset();return;}
let target=WI.assumingMainTarget();if(target.hasDomain("ApplicationCache"))
target.ApplicationCacheAgent.getManifestForFrame(event.target.id,this._manifestForFrameLoaded.bind(this,event.target.id));}
_childFrameWasRemoved(event)
{this._frameManifestRemoved(event.data.childFrame);}
_manifestForFrameLoaded(frameId,error,manifestURL)
{if(!this._enabled)
return;var frame=WI.networkManager.frameForIdentifier(frameId);if(!frame)
return;
if(error){WI.reportInternalError(error);return;}
if(!manifestURL)
this._frameManifestRemoved(frame);}
_framesWithManifestsLoaded(error,framesWithManifests)
{if(error){WI.reportInternalError(error);return;}
if(!this._enabled)
return;for(var i=0;i<framesWithManifests.length;++i){var frame=WI.networkManager.frameForIdentifier(framesWithManifests[i].frameId);if(!frame)
continue;this._frameManifestUpdated(frame,framesWithManifests[i].manifestURL,framesWithManifests[i].status);}}
_frameManifestUpdated(frame,manifestURL,status)
{if(status===WI.ApplicationCacheManager.Status.Uncached){this._frameManifestRemoved(frame);return;}
if(!manifestURL)
return;var manifestFrame=this._applicationCacheObjects[frame.id];if(manifestFrame&&manifestURL!==manifestFrame.manifest.manifestURL)
this._frameManifestRemoved(frame);var oldStatus=manifestFrame?manifestFrame.status:-1;var statusChanged=manifestFrame&&status!==oldStatus;if(manifestFrame)
manifestFrame.status=status;if(!this._applicationCacheObjects[frame.id]){var cacheManifest=new WI.ApplicationCacheManifest(manifestURL);this._applicationCacheObjects[frame.id]=new WI.ApplicationCacheFrame(frame,cacheManifest,status);this.dispatchEventToListeners(WI.ApplicationCacheManager.Event.FrameManifestAdded,{frameManifest:this._applicationCacheObjects[frame.id]});}
if(statusChanged)
this.dispatchEventToListeners(WI.ApplicationCacheManager.Event.FrameManifestStatusChanged,{frameManifest:this._applicationCacheObjects[frame.id]});}
_frameManifestRemoved(frame)
{if(!this._applicationCacheObjects[frame.id])
return;delete this._applicationCacheObjects[frame.id];this.dispatchEventToListeners(WI.ApplicationCacheManager.Event.FrameManifestRemoved,{frame});}};WI.ApplicationCacheManager.Event={Cleared:"application-cache-manager-cleared",FrameManifestAdded:"application-cache-manager-frame-manifest-added",FrameManifestRemoved:"application-cache-manager-frame-manifest-removed",FrameManifestStatusChanged:"application-cache-manager-frame-manifest-status-changed",NetworkStateUpdated:"application-cache-manager-network-state-updated"};WI.ApplicationCacheManager.Status={Uncached:0,Idle:1,Checking:2,Downloading:3,UpdateReady:4,Obsolete:5};WI.BasicBlockAnnotator=class BasicBlockAnnotator extends WI.Annotator
{constructor(sourceCodeTextEditor,script)
{super(sourceCodeTextEditor);this._script=script;this._basicBlockMarkers=new Map;} 
clearAnnotations()
{for(var key of this._basicBlockMarkers.keys())
this._clearRangeForBasicBlockMarker(key);}
insertAnnotations()
{if(!this.isActive())
return;this._script.requestContent().then(this._annotateBasicBlockExecutionRanges.bind(this));} 
_calculateBasicBlockPositions(basicBlocks,content)
{if(!basicBlocks||!basicBlocks.length)
return;let lineEndings=[];let lineEndingLengths=[];let pattern=/\r\n?|\n/g;let match=pattern.exec(content);while(match){lineEndings.push(match.index);lineEndingLengths.push(match[0].length);match=pattern.exec(content);}
function offsetToPosition(offset){let lineNumber=lineEndings.upperBound(offset-1);if(lineNumber){let previousLine=lineNumber-1;var columnNumber=offset-lineEndings[previousLine]-lineEndingLengths[previousLine];}else
var columnNumber=offset;return new WI.SourceCodePosition(lineNumber,columnNumber);}
for(let block of basicBlocks){block.startPosition=offsetToPosition(block.startOffset);block.endPosition=offsetToPosition(block.endOffset);}}
_annotateBasicBlockExecutionRanges()
{let content=this._script.content;if(!content)
return;var sourceID=this._script.id;var startTime=Date.now();this._script.target.RuntimeAgent.getBasicBlocks(sourceID,function(error,basicBlocks){if(error){console.error("Error in getting basic block locations: "+error);return;}
if(!this.isActive())
return;this._calculateBasicBlockPositions(basicBlocks,content);let{startPosition,endPosition}=this.sourceCodeTextEditor.visibleRangePositions();basicBlocks=basicBlocks.filter(function(block){
if(block.startPosition.isAfter(endPosition))
return false;
if(block.endPosition.isBefore(startPosition))
return false;return true;});for(var block of basicBlocks){var key=block.startOffset+":"+block.endOffset;var hasKey=this._basicBlockMarkers.has(key);var hasExecuted=block.hasExecuted;if(hasKey&&hasExecuted)
this._clearRangeForBasicBlockMarker(key);else if(!hasKey&&!hasExecuted){var marker=this._highlightTextForBasicBlock(block);this._basicBlockMarkers.set(key,marker);}}
var totalTime=Date.now()-startTime;var timeoutTime=Number.constrain(30*totalTime,500,5000);this._timeoutIdentifier=setTimeout(this.insertAnnotations.bind(this),timeoutTime);}.bind(this));}
_highlightTextForBasicBlock(basicBlock)
{let startPosition=this.sourceCodeTextEditor.originalPositionToCurrentPosition(basicBlock.startPosition);let endPosition=this.sourceCodeTextEditor.originalPositionToCurrentPosition(basicBlock.endPosition);if(this._isTextRangeOnlyClosingBrace(startPosition,endPosition))
return null;return this.sourceCodeTextEditor.addStyleToTextRange(startPosition,endPosition,WI.BasicBlockAnnotator.HasNotExecutedClassName);}
_isTextRangeOnlyClosingBrace(startPosition,endPosition)
{var isOnlyClosingBrace=/^\s*\}$/;return isOnlyClosingBrace.test(this.sourceCodeTextEditor.getTextInRange(startPosition,endPosition));}
_clearRangeForBasicBlockMarker(key)
{var marker=this._basicBlockMarkers.get(key);if(marker)
marker.clear();this._basicBlockMarkers.delete(key);}};WI.BasicBlockAnnotator.HasNotExecutedClassName="basic-block-has-not-executed";WI.BreakpointLogMessageLexer=class BreakpointLogMessageLexer extends WI.Object
{constructor()
{super();this._stateFunctions={[WI.BreakpointLogMessageLexer.State.Expression]:this._expression,[WI.BreakpointLogMessageLexer.State.PlainText]:this._plainText,[WI.BreakpointLogMessageLexer.State.PossiblePlaceholder]:this._possiblePlaceholder,[WI.BreakpointLogMessageLexer.State.RegExpOrStringLiteral]:this._regExpOrStringLiteral,};this.reset();} 
tokenize(input)
{this.reset();this._input=input;while(this._index<this._input.length){let stateFunction=this._stateFunctions[this._states.lastValue];if(!stateFunction){this.reset();return null;}
stateFunction.call(this);}
this._finishPlainText();return this._tokens;}
reset()
{this._input="";this._buffer="";this._index=0;this._states=[WI.BreakpointLogMessageLexer.State.PlainText];this._literalStartCharacter="";this._curlyBraceDepth=0;this._tokens=[];} 
_finishPlainText()
{this._appendToken(WI.BreakpointLogMessageLexer.TokenType.PlainText);}
_finishExpression()
{this._appendToken(WI.BreakpointLogMessageLexer.TokenType.Expression);}
_appendToken(type)
{if(!this._buffer)
return;this._tokens.push({type,data:this._buffer});this._buffer="";}
_consume()
{let character=this._peek();this._index++;return character;}
_peek()
{return this._input[this._index]||null;} 
_expression()
{let character=this._consume();if(character==="}"){if(this._curlyBraceDepth===0){this._finishExpression();this._states.pop();return;}
this._curlyBraceDepth--;}
this._buffer+=character;if(character==="/"||character==="\""||character==="'"){this._literalStartCharacter=character;this._states.push(WI.BreakpointLogMessageLexer.State.RegExpOrStringLiteral);}else if(character==="{")
this._curlyBraceDepth++;}
_plainText()
{let character=this._peek();if(character==="$")
this._states.push(WI.BreakpointLogMessageLexer.State.PossiblePlaceholder);else{this._buffer+=character;this._consume();}}
_possiblePlaceholder()
{let character=this._consume();let nextCharacter=this._peek();this._states.pop();if(nextCharacter==="{"){this._finishPlainText();this._consume();this._states.push(WI.BreakpointLogMessageLexer.State.Expression);}else
this._buffer+=character;}
_regExpOrStringLiteral()
{let character=this._consume();this._buffer+=character;if(character==="\\"){if(this._peek()!==null)
this._buffer+=this._consume();return;}
if(character===this._literalStartCharacter){this._states.pop();}}};WI.BreakpointLogMessageLexer.State={Expression:Symbol("expression"),PlainText:Symbol("plain-text"),PossiblePlaceholder:Symbol("possible-placeholder"),RegExpOrStringLiteral:Symbol("regexp-or-string-literal"),};WI.BreakpointLogMessageLexer.TokenType={PlainText:"token-type-plain-text",Expression:"token-type-expression",};WI.BrowserManager=class BrowserManager
{constructor()
{this._enabled=false;this._extensionNameIdentifierMap=new Map;} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Browser"))
target.BrowserAgent.enable();} 
enable()
{this._enabled=true;for(let target of WI.targetManager.allTargets)
this.initializeTarget(target);}
disable()
{for(let target of WI.targetManager.allTargets){if(target.hasDomain("Browser"))
target.BrowserAgent.disable();}
this._extensionNameIdentifierMap.clear();this._enabled=false;}
isExtensionScheme(scheme)
{return scheme&&scheme.endsWith("-extension");}
extensionNameForId(extensionId)
{return this._extensionNameIdentifierMap.get(extensionId)||null;}
extensionNameForURL(url)
{let match=url.match(/^[a-z\-]*extension:\/\/([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})\//);if(!match)
return null;return this.extensionNameForId(match[1]);}
extensionNameForExecutionContext(context)
{let match=context.name.match(/^[A-Za-z]*ExtensionWorld-([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})$/);if(!match)
return null;return this.extensionNameForId(match[1]);} 
extensionsEnabled(extensions)
{for(let{extensionId,name}of extensions){this._extensionNameIdentifierMap.set(extensionId,name);}}
extensionsDisabled(extensionIds)
{for(let extensionId of extensionIds){let name=this._extensionNameIdentifierMap.take(extensionId);}}};WI.CSSManager=class CSSManager extends WI.Object
{constructor()
{super();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceAdded,this);WI.Resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._resourceContentDidChange,this);WI.Resource.addEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.AttributeModified,this._nodeAttributesDidChange,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._nodeAttributesDidChange,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._nodePseudoClassesDidChange,this);this._colorFormatSetting=new WI.Setting("default-color-format",WI.Color.Format.Original);this._styleSheetIdentifierMap=new Map;this._styleSheetFrameURLMap=new Map;this._nodeStylesMap={};this._modifiedStyles=new Map;this._defaultAppearance=null;this._forcedAppearance=null;} 
initializeTarget(target)
{if(target.hasDomain("CSS"))
target.CSSAgent.enable();} 
static supportsInspectorStyleSheet()
{return InspectorBackend.hasCommand("CSS.createStyleSheet");}
static protocolStyleSheetOriginToEnum(origin)
{switch(origin){case InspectorBackend.Enum.CSS.StyleSheetOrigin.User:return WI.CSSStyleSheet.Type.User;case InspectorBackend.Enum.CSS.StyleSheetOrigin.UserAgent:return WI.CSSStyleSheet.Type.UserAgent;case InspectorBackend.Enum.CSS.StyleSheetOrigin.Inspector:return WI.CSSStyleSheet.Type.Inspector;}
return WI.CSSStyleSheet.Type.Author;}
static protocolGroupingTypeToEnum(type)
{if(!InspectorBackend.Enum.CSS.Grouping){switch(type){case"mediaRule":return WI.CSSGrouping.Type.MediaRule;case"importRule":return WI.CSSGrouping.Type.MediaImportRule;case"linkedSheet":return WI.CSSGrouping.Type.MediaLinkNode;case"inlineSheet":return WI.CSSGrouping.Type.MediaStyleNode;}}
return type;}
static displayNameForPseudoId(pseudoId)
{if(!InspectorBackend.Enum.CSS.PseudoId){switch(pseudoId){case 1: return WI.unlocalizedString("::first-line");case 2: return WI.unlocalizedString("::first-letter");case 3: return WI.unlocalizedString("::marker");case 4: return WI.unlocalizedString("::before");case 5: return WI.unlocalizedString("::after");case 6: return WI.unlocalizedString("::selection");case 7: return WI.unlocalizedString("::scrollbar");case 8: return WI.unlocalizedString("::scrollbar-thumb");case 9: return WI.unlocalizedString("::scrollbar-button");case 10: return WI.unlocalizedString("::scrollbar-track");case 11: return WI.unlocalizedString("::scrollbar-track-piece");case 12: return WI.unlocalizedString("::scrollbar-corner");case 13: return WI.unlocalizedString("::resizer");default:console.error("Unknown pseudo id",pseudoId);return"";}}
switch(pseudoId){case CSSManager.PseudoSelectorNames.FirstLine:return WI.unlocalizedString("::first-line");case CSSManager.PseudoSelectorNames.FirstLetter:return WI.unlocalizedString("::first-letter");case CSSManager.PseudoSelectorNames.Highlight:return WI.unlocalizedString("::highlight");case CSSManager.PseudoSelectorNames.Marker:return WI.unlocalizedString("::marker");case CSSManager.PseudoSelectorNames.Before:return WI.unlocalizedString("::before");case CSSManager.PseudoSelectorNames.After:return WI.unlocalizedString("::after");case CSSManager.PseudoSelectorNames.Selection:return WI.unlocalizedString("::selection");case CSSManager.PseudoSelectorNames.Backdrop:return WI.unlocalizedString("::backdrop");case CSSManager.PseudoSelectorNames.Scrollbar:return WI.unlocalizedString("::scrollbar");case CSSManager.PseudoSelectorNames.ScrollbarThumb:return WI.unlocalizedString("::scrollbar-thumb");case CSSManager.PseudoSelectorNames.ScrollbarButton:return WI.unlocalizedString("::scrollbar-button");case CSSManager.PseudoSelectorNames.ScrollbarTrack:return WI.unlocalizedString("::scrollbar-track");case CSSManager.PseudoSelectorNames.ScrollbarTrackPiece:return WI.unlocalizedString("::scrollbar-track-piece");case CSSManager.PseudoSelectorNames.ScrollbarCorner:return WI.unlocalizedString("::scrollbar-corner");case CSSManager.PseudoSelectorNames.Resizer:return WI.unlocalizedString("::resizer");default:console.error("Unknown pseudo id",pseudoId);return"";}} 
get preferredColorFormat()
{return this._colorFormatSetting.value;}
get styleSheets()
{return Array.from(this._styleSheetIdentifierMap.values());}
get defaultAppearance()
{return this._defaultAppearance;}
get forcedAppearance()
{return this._forcedAppearance;}
set forcedAppearance(name)
{if(!this.canForceAppearance())
return;let commandArguments={};switch(name){case WI.CSSManager.Appearance.Light:commandArguments.appearance=InspectorBackend.Enum.Page.Appearance.Light;break;case WI.CSSManager.Appearance.Dark:commandArguments.appearance=InspectorBackend.Enum.Page.Appearance.Dark;break;case null:if(!InspectorBackend.hasCommand("DOMDebugger.setDOMBreakpoint","options"))
commandArguments.appearance="";break;default:return;}
this._forcedAppearance=name||null;let target=WI.assumingMainTarget();target.PageAgent.setForcedAppearance.invoke(commandArguments).then(()=>{this.mediaQueryResultChanged();this.dispatchEventToListeners(WI.CSSManager.Event.ForcedAppearanceDidChange,{appearance:this._forcedAppearance});});}
set layoutContextTypeChangedMode(layoutContextTypeChangedMode)
{for(let target of WI.targets){if(target.hasCommand("CSS.setLayoutContextTypeChangedMode"))
target.CSSAgent.setLayoutContextTypeChangedMode(layoutContextTypeChangedMode);}}
canForceAppearance()
{return InspectorBackend.hasCommand("Page.setForcedAppearance")&&this._defaultAppearance;}
canForcePseudoClasses()
{return InspectorBackend.hasCommand("CSS.forcePseudoState");}
propertyNameHasOtherVendorPrefix(name)
{if(!name||name.length<4||name.charAt(0)!=="-")
return false;var match=name.match(/^(?:-moz-|-ms-|-o-|-epub-)/);if(!match)
return false;return true;}
propertyValueHasOtherVendorKeyword(value)
{var match=value.match(/(?:-moz-|-ms-|-o-|-epub-)[-\w]+/);if(!match)
return false;return true;}
canonicalNameForPropertyName(name)
{if(!name||name.length<8||name.charAt(0)!=="-")
return name; var match=name.match(/^(?:-webkit-|-khtml-|-apple-)(.+)/);if(!match)
return name;return match[1];}
styleSheetForIdentifier(id)
{let styleSheet=this._styleSheetIdentifierMap.get(id);if(styleSheet)
return styleSheet;styleSheet=new WI.CSSStyleSheet(id);this._styleSheetIdentifierMap.set(id,styleSheet);return styleSheet;}
stylesForNode(node)
{if(node.id in this._nodeStylesMap)
return this._nodeStylesMap[node.id];var styles=new WI.DOMNodeStyles(node);this._nodeStylesMap[node.id]=styles;return styles;}
inspectorStyleSheetsForFrame(frame)
{return this.styleSheets.filter((styleSheet)=>styleSheet.isInspectorStyleSheet()&&styleSheet.parentFrame===frame);}
preferredInspectorStyleSheetForFrame(frame,callback)
{var inspectorStyleSheets=this.inspectorStyleSheetsForFrame(frame);for(let styleSheet of inspectorStyleSheets){if(styleSheet[WI.CSSManager.PreferredInspectorStyleSheetSymbol]){callback(styleSheet);return;}}
let target=WI.assumingMainTarget();target.CSSAgent.createStyleSheet(frame.id,function(error,styleSheetId){if(error||!styleSheetId){WI.reportInternalError(error||styleSheetId);return;}
const url=null;let styleSheet=WI.cssManager.styleSheetForIdentifier(styleSheetId);styleSheet.updateInfo(url,frame,styleSheet.origin,styleSheet.isInlineStyleTag(),styleSheet.startLineNumber,styleSheet.startColumnNumber);styleSheet[WI.CSSManager.PreferredInspectorStyleSheetSymbol]=true;callback(styleSheet);});}
mediaTypeChanged()
{this.mediaQueryResultChanged();}
get modifiedStyles()
{return Array.from(this._modifiedStyles.values());}
addModifiedStyle(style)
{this._modifiedStyles.set(style.stringId,style);this.dispatchEventToListeners(WI.CSSManager.Event.ModifiedStylesChanged);}
getModifiedStyle(style)
{return this._modifiedStyles.get(style.stringId);}
removeModifiedStyle(style)
{this._modifiedStyles.delete(style.stringId);this.dispatchEventToListeners(WI.CSSManager.Event.ModifiedStylesChanged);} 
defaultAppearanceDidChange(protocolName)
{let appearance=null;switch(protocolName){case InspectorBackend.Enum.Page.Appearance.Light:appearance=WI.CSSManager.Appearance.Light;break;case InspectorBackend.Enum.Page.Appearance.Dark:appearance=WI.CSSManager.Appearance.Dark;break;default:console.error("Unknown default appearance name:",protocolName);break;}
this._defaultAppearance=appearance;this.mediaQueryResultChanged();this.dispatchEventToListeners(WI.CSSManager.Event.DefaultAppearanceDidChange,{appearance});} 
mediaQueryResultChanged()
{for(var key in this._nodeStylesMap)
this._nodeStylesMap[key].mediaQueryResultDidChange();}
styleSheetChanged(styleSheetIdentifier)
{var styleSheet=this.styleSheetForIdentifier(styleSheetIdentifier); if(styleSheet.isInlineStyleAttributeStyleSheet())
return;if(!styleSheet.noteContentDidChange())
return;this._updateResourceContent(styleSheet);}
styleSheetAdded(styleSheetInfo)
{let styleSheet=this.styleSheetForIdentifier(styleSheetInfo.styleSheetId);let parentFrame=WI.networkManager.frameForIdentifier(styleSheetInfo.frameId);let origin=WI.CSSManager.protocolStyleSheetOriginToEnum(styleSheetInfo.origin);styleSheet.updateInfo(styleSheetInfo.sourceURL,parentFrame,origin,styleSheetInfo.isInline,styleSheetInfo.startLine,styleSheetInfo.startColumn);this.dispatchEventToListeners(WI.CSSManager.Event.StyleSheetAdded,{styleSheet});}
styleSheetRemoved(styleSheetIdentifier)
{let styleSheet=this._styleSheetIdentifierMap.get(styleSheetIdentifier);if(!styleSheet)
return;this._styleSheetIdentifierMap.delete(styleSheetIdentifier);this.dispatchEventToListeners(WI.CSSManager.Event.StyleSheetRemoved,{styleSheet});} 
_nodePseudoClassesDidChange(event)
{var node=event.target;for(var key in this._nodeStylesMap){var nodeStyles=this._nodeStylesMap[key];if(nodeStyles.node!==node&&!nodeStyles.node.isDescendant(node))
continue;nodeStyles.pseudoClassesDidChange(node);}}
_nodeAttributesDidChange(event)
{var node=event.target;for(var key in this._nodeStylesMap){var nodeStyles=this._nodeStylesMap[key];if(nodeStyles.node!==node&&!nodeStyles.node.isDescendant(node))
continue;nodeStyles.attributeDidChange(node,event.data.name);}}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._styleSheetIdentifierMap.clear();this._styleSheetFrameURLMap.clear();this._modifiedStyles.clear();this._forcedAppearance=null;this._nodeStylesMap={};}
_resourceAdded(event)
{var resource=event.data.resource;if(resource.type!==WI.Resource.Type.StyleSheet)
return;this._clearStyleSheetsForResource(resource);}
_resourceTypeDidChange(event)
{var resource=event.target;if(resource.type!==WI.Resource.Type.StyleSheet)
return;this._clearStyleSheetsForResource(resource);}
_clearStyleSheetsForResource(resource)
{
this._styleSheetIdentifierMap.delete(this._frameURLMapKey(resource.parentFrame,resource.url));}
_frameURLMapKey(frame,url)
{return frame.id+":"+url;}
_lookupStyleSheetForResource(resource,callback)
{this._lookupStyleSheet(resource.parentFrame,resource.url,callback);}
_lookupStyleSheet(frame,url,callback)
{let key=this._frameURLMapKey(frame,url);function styleSheetsFetched()
{callback(this._styleSheetFrameURLMap.get(key)||null);}
let styleSheet=this._styleSheetFrameURLMap.get(key)||null;if(styleSheet)
callback(styleSheet);else
this._fetchInfoForAllStyleSheets(styleSheetsFetched.bind(this));}
_fetchInfoForAllStyleSheets(callback)
{function processStyleSheets(error,styleSheets)
{this._styleSheetFrameURLMap.clear();if(error){callback();return;}
for(let styleSheetInfo of styleSheets){let parentFrame=WI.networkManager.frameForIdentifier(styleSheetInfo.frameId);let origin=WI.CSSManager.protocolStyleSheetOriginToEnum(styleSheetInfo.origin);let styleSheet=this.styleSheetForIdentifier(styleSheetInfo.styleSheetId);styleSheet.updateInfo(styleSheetInfo.sourceURL,parentFrame,origin,styleSheetInfo.isInline,styleSheetInfo.startLine,styleSheetInfo.startColumn);let key=this._frameURLMapKey(parentFrame,styleSheetInfo.sourceURL);this._styleSheetFrameURLMap.set(key,styleSheet);}
callback();}
let target=WI.assumingMainTarget();target.CSSAgent.getAllStyleSheets(processStyleSheets.bind(this));}
_resourceContentDidChange(event)
{var resource=event.target;if(resource===this._ignoreResourceContentDidChangeEventForResource)
return;if(resource.localResourceOverride)
return;if(resource.type!==WI.Resource.Type.StyleSheet||resource.syntheticMIMEType!=="text/css")
return;function applyStyleSheetChanges()
{function styleSheetFound(styleSheet)
{resource.__pendingChangeTimeout.cancel();if(!styleSheet)
return;
resource.__ignoreNextUpdateResourceContent=true;let revision=styleSheet.editableRevision;revision.updateRevisionContent(resource.content);}
this._lookupStyleSheetForResource(resource,styleSheetFound.bind(this));}
if(!resource.__pendingChangeTimeout)
resource.__pendingChangeTimeout=new Throttler(applyStyleSheetChanges.bind(this),100);resource.__pendingChangeTimeout.fire();}
_updateResourceContent(styleSheet)
{function fetchedStyleSheetContent(parameters)
{styleSheet.__pendingChangeTimeout.cancel();let representedObject=parameters.sourceCode;if(!representedObject.url)
return;if(!styleSheet.isInspectorStyleSheet()){
representedObject=representedObject.parentFrame.resourcesForURL(representedObject.url).find((resource)=>resource.type===WI.Resource.Type.StyleSheet);if(!representedObject)
return;}
if(representedObject.__ignoreNextUpdateResourceContent){representedObject.__ignoreNextUpdateResourceContent=false;return;}
this._ignoreResourceContentDidChangeEventForResource=representedObject;let revision=representedObject.editableRevision;if(styleSheet.isInspectorStyleSheet()){revision.updateRevisionContent(representedObject.content);styleSheet.dispatchEventToListeners(WI.SourceCode.Event.ContentDidChange);}else
revision.updateRevisionContent(parameters.content);this._ignoreResourceContentDidChangeEventForResource=null;}
function styleSheetReady()
{styleSheet.requestContent().then(fetchedStyleSheetContent.bind(this));}
function applyStyleSheetChanges()
{if(styleSheet.url)
styleSheetReady.call(this);else
this._fetchInfoForAllStyleSheets(styleSheetReady.bind(this));}
if(!styleSheet.__pendingChangeTimeout)
styleSheet.__pendingChangeTimeout=new Throttler(applyStyleSheetChanges.bind(this),100);styleSheet.__pendingChangeTimeout.fire();}};WI.CSSManager.Event={StyleSheetAdded:"css-manager-style-sheet-added",StyleSheetRemoved:"css-manager-style-sheet-removed",ModifiedStylesChanged:"css-manager-modified-styles-changed",DefaultAppearanceDidChange:"css-manager-default-appearance-did-change",ForcedAppearanceDidChange:"css-manager-forced-appearance-did-change",};WI.CSSManager.Appearance={Light:Symbol("light"),Dark:Symbol("dark"),};WI.CSSManager.PseudoSelectorNames={After:"after",Before:"before",Backdrop:"backdrop",FirstLetter:"first-letter",FirstLine:"first-line",Highlight:"highlight",Marker:"marker",Resizer:"resizer",Scrollbar:"scrollbar",ScrollbarButton:"scrollbar-button",ScrollbarCorner:"scrollbar-corner",ScrollbarThumb:"scrollbar-thumb",ScrollbarTrack:"scrollbar-track",ScrollbarTrackPiece:"scrollbar-track-piece",Selection:"selection",};WI.CSSManager.LayoutContextTypeChangedMode={Observed:"observed",All:"all",};WI.CSSManager.PseudoElementNames=["before","after"];WI.CSSManager.ForceablePseudoClasses=["active","focus","hover","visited"];WI.CSSManager.PreferredInspectorStyleSheetSymbol=Symbol("css-manager-preferred-inspector-style-sheet");WI.CallFrameTreeController=class CallFrameTreeController extends WI.Object
{constructor(treeOutline)
{super();this._treeOutline=treeOutline;if(this._treeOutline.selectable)
this._treeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);else
this._treeOutline.addEventListener(WI.TreeOutline.Event.ElementClicked,this._treeElementClicked,this);} 
get treeOutline(){return this._treeOutline;}
get callFrames()
{return this._callFrames;}
set callFrames(callFrames)
{callFrames=callFrames||[];if(this._callFrames===callFrames)
return;this._callFrames=callFrames;this._treeOutline.removeChildren();for(let callFrame of this._callFrames)
this._treeOutline.appendChild(new WI.CallFrameTreeElement(callFrame));}
disconnect()
{if(this._treeOutline.selectable)
this._treeOutline.removeEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);else
this._treeOutline.removeEventListener(WI.TreeOutline.Event.ElementClicked,this._treeElementClicked,this);} 
_treeElementClicked(event)
{this._showSourceCodeLocation(event.data.treeElement);}
_treeSelectionDidChange(event)
{this._showSourceCodeLocation(this._treeOutline.selectedTreeElement);}
_showSourceCodeLocation(treeElement)
{let callFrame=treeElement.callFrame;if(!callFrame.sourceCodeLocation)
return;WI.showSourceCodeLocation(callFrame.sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});}};WI.CanvasManager=class CanvasManager extends WI.Object
{constructor()
{super();this._enabled=false;this._canvasCollection=new WI.CanvasCollection;this._canvasIdentifierMap=new Map;this._shaderProgramIdentifierMap=new Map;this._savedRecordings=new Set;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} 
get domains(){return["Canvas"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Canvas")){target.CanvasAgent.enable();if(target.hasCommand("Canvas.setRecordingAutoCaptureFrameCount")&&WI.settings.canvasRecordingAutoCaptureEnabled.value&&WI.settings.canvasRecordingAutoCaptureFrameCount.value)
target.CanvasAgent.setRecordingAutoCaptureFrameCount(WI.settings.canvasRecordingAutoCaptureFrameCount.value);}} 
static supportsRecordingAutoCapture()
{return InspectorBackend.hasCommand("Canvas.setRecordingAutoCaptureFrameCount");} 
get canvasCollection(){return this._canvasCollection;}
get savedRecordings(){return this._savedRecordings;}
get shaderPrograms()
{return Array.from(this._shaderProgramIdentifierMap.values());}
async processJSON({filename,json,error})
{if(error){WI.Recording.synthesizeError(error);return;}
if(typeof json!=="object"||json===null){WI.Recording.synthesizeError(WI.UIString("invalid JSON"));return;}
let recording=WI.Recording.fromPayload(json);if(!recording)
return;let extensionStart=filename.lastIndexOf(".");if(extensionStart!==-1)
filename=filename.substring(0,extensionStart);recording.createDisplayName(filename);this._savedRecordings.add(recording);this.dispatchEventToListeners(WI.CanvasManager.Event.RecordingSaved,{recording,imported:true,initiatedByUser:true});}
enable()
{this._enabled=true;for(let target of WI.targets)
this.initializeTarget(target);}
disable()
{for(let target of WI.targets){if(target.hasDomain("Canvas"))
target.CanvasAgent.disable();}
this._canvasCollection.clear();this._canvasIdentifierMap.clear();this._shaderProgramIdentifierMap.clear();this._savedRecordings.clear();this._enabled=false;}
setRecordingAutoCaptureFrameCount(enabled,count)
{for(let target of WI.targets){if(target.hasCommand("Canvas.setRecordingAutoCaptureFrameCount"))
target.CanvasAgent.setRecordingAutoCaptureFrameCount(enabled?count:0);}
WI.settings.canvasRecordingAutoCaptureEnabled.value=enabled&&count;WI.settings.canvasRecordingAutoCaptureFrameCount.value=count;} 
canvasAdded(canvasPayload)
{let canvas=WI.Canvas.fromPayload(canvasPayload);this._canvasCollection.add(canvas);this._canvasIdentifierMap.set(canvas.identifier,canvas);}
canvasRemoved(canvasIdentifier)
{let canvas=this._canvasIdentifierMap.take(canvasIdentifier);if(!canvas)
return;this._saveRecordings(canvas);this._canvasCollection.remove(canvas);for(let program of canvas.shaderProgramCollection)
this._shaderProgramIdentifierMap.delete(program.identifier);canvas.shaderProgramCollection.clear();}
canvasMemoryChanged(canvasIdentifier,memoryCost)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.memoryCost=memoryCost;}
clientNodesChanged(canvasIdentifier)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.clientNodesChanged();}
recordingStarted(canvasIdentifier,initiator)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.recordingStarted(initiator);}
recordingProgress(canvasIdentifier,framesPayload,bufferUsed)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.recordingProgress(framesPayload,bufferUsed);}
recordingFinished(canvasIdentifier,recordingPayload)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.recordingFinished(recordingPayload);}
extensionEnabled(canvasIdentifier,extension)
{let canvas=this._canvasIdentifierMap.get(canvasIdentifier);if(!canvas)
return;canvas.enableExtension(extension);}
programCreated(shaderProgramPayload)
{let canvas=this._canvasIdentifierMap.get(shaderProgramPayload.canvasId);if(!canvas)
return;let programId=shaderProgramPayload.programId;let programType=shaderProgramPayload.programType;if(!programType)
programType=WI.ShaderProgram.ProgramType.Render;let options={};if(shaderProgramPayload.sharesVertexFragmentShader)
options.sharesVertexFragmentShader=true;let program=new WI.ShaderProgram(programId,programType,canvas,options);this._shaderProgramIdentifierMap.set(program.identifier,program);canvas.shaderProgramCollection.add(program);}
programDeleted(programIdentifier)
{let program=this._shaderProgramIdentifierMap.take(programIdentifier);if(!program)
return;program.canvas.shaderProgramCollection.remove(program);} 
_saveRecordings(canvas)
{for(let recording of canvas.recordingCollection){recording.source=null;recording.createDisplayName(recording.displayName);this._savedRecordings.add(recording);this.dispatchEventToListeners(WI.CanvasManager.Event.RecordingSaved,{recording});}}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;WI.Canvas.resetUniqueDisplayNameNumbers();for(let canvas of this._canvasIdentifierMap.values())
this._saveRecordings(canvas);this._canvasCollection.clear();this._canvasIdentifierMap.clear();this._shaderProgramIdentifierMap.clear();}};WI.CanvasManager.Event={RecordingSaved:"canvas-manager-recording-saved",};WI.CodeMirrorColorEditingController=class CodeMirrorColorEditingController extends WI.CodeMirrorEditingController
{ get initialValue()
{return WI.Color.fromString(this.text);}
get cssClassName()
{return"color";}
popoverWillPresent(popover)
{this._colorPicker=new WI.ColorPicker;this._colorPicker.addEventListener(WI.ColorPicker.Event.ColorChanged,this._colorPickerColorChanged,this);popover.content=this._colorPicker.element;}
popoverDidPresent(popover)
{this._colorPicker.color=this._value;} 
_colorPickerColorChanged(event)
{this.value=event.target.color;}};WI.CodeMirrorCompletionController=class CodeMirrorCompletionController extends WI.Object
{constructor(mode,codeMirror,delegate,stopCharactersRegex)
{super();this._mode=mode;this._codeMirror=codeMirror;this._stopCharactersRegex=stopCharactersRegex||null;this._delegate=delegate||null;this._startOffset=NaN;this._endOffset=NaN;this._lineNumber=NaN;this._prefix="";this._noEndingSemicolon=false;this._completions=[];this._extendedCompletionProviders={};this._suggestionsView=new WI.CompletionSuggestionsView(this);this._keyMap={"Up":this._handleUpKey.bind(this),"Down":this._handleDownKey.bind(this),"Right":this._handleRightOrEnterKey.bind(this),"Esc":this._handleEscapeKey.bind(this),"Enter":this._handleRightOrEnterKey.bind(this),"Tab":this._handleTabKey.bind(this),"Cmd-A":this._handleHideKey.bind(this),"Cmd-Z":this._handleHideKey.bind(this),"Shift-Cmd-Z":this._handleHideKey.bind(this),"Cmd-Y":this._handleHideKey.bind(this)};this._handleChangeListener=this._handleChange.bind(this);this._handleCursorActivityListener=this._handleCursorActivity.bind(this);this._handleHideActionListener=this._handleHideAction.bind(this);this._codeMirror.addKeyMap(this._keyMap);this._codeMirror.on("change",this._handleChangeListener);this._codeMirror.on("cursorActivity",this._handleCursorActivityListener);this._codeMirror.on("blur",this._handleHideActionListener);this._codeMirror.on("scroll",this._handleHideActionListener);this._updatePromise=null;} 
get mode(){return this._mode;}
addExtendedCompletionProvider(modeName,provider)
{this._extendedCompletionProviders[modeName]=provider;}
updateCompletions(completions,implicitSuffix)
{if(isNaN(this._startOffset)||isNaN(this._endOffset)||isNaN(this._lineNumber))
return;if(!completions||!completions.length){this.hideCompletions();return;}
this._completions=completions;if(typeof implicitSuffix==="string")
this._implicitSuffix=implicitSuffix;var from={line:this._lineNumber,ch:this._startOffset};var to={line:this._lineNumber,ch:this._endOffset};var firstCharCoords=this._codeMirror.cursorCoords(from);var lastCharCoords=this._codeMirror.cursorCoords(to);var bounds=new WI.Rect(firstCharCoords.left,firstCharCoords.top,lastCharCoords.right-firstCharCoords.left,firstCharCoords.bottom-firstCharCoords.top);var index=this._currentCompletion?completions.indexOf(this._currentCompletion):0;if(index===-1)
index=0;if(this._forced||completions.length>1||completions[index]!==this._prefix){this._suggestionsView.update(completions,index);this._suggestionsView.show(bounds);}else if(this._implicitSuffix){this._suggestionsView.hide();}else{
this.hideCompletions();return;}
this._applyCompletionHint(completions[index]);this._resolveUpdatePromise(WI.CodeMirrorCompletionController.UpdatePromise.CompletionsFound);}
isCompletionChange(change)
{return this._ignoreChange||change.origin===WI.CodeMirrorCompletionController.CompletionOrigin||change.origin===WI.CodeMirrorCompletionController.DeleteCompletionOrigin;}
isShowingCompletions()
{return this._suggestionsView.visible||(this._completionHintMarker&&this._completionHintMarker.find());}
isHandlingClickEvent()
{return this._suggestionsView.isHandlingClickEvent();}
hideCompletions()
{this._suggestionsView.hide();this._removeCompletionHint();this._startOffset=NaN;this._endOffset=NaN;this._lineNumber=NaN;this._prefix="";this._completions=[];this._implicitSuffix="";this._forced=false;delete this._currentCompletion;delete this._ignoreNextCursorActivity;this._resolveUpdatePromise(WI.CodeMirrorCompletionController.UpdatePromise.NoCompletionsFound);}
close()
{this._codeMirror.removeKeyMap(this._keyMap);this._codeMirror.off("change",this._handleChangeListener);this._codeMirror.off("cursorActivity",this._handleCursorActivityListener);this._codeMirror.off("blur",this._handleHideActionListener);this._codeMirror.off("scroll",this._handleHideActionListener);}
completeAtCurrentPositionIfNeeded(force)
{this._resolveUpdatePromise(WI.CodeMirrorCompletionController.UpdatePromise.Canceled);var update=this._updatePromise=new WI.WrappedPromise;this._completeAtCurrentPosition(force);return update.promise;} 
completionSuggestionsSelectedCompletion(suggestionsView,completionText)
{this._applyCompletionHint(completionText);}
completionSuggestionsClickedCompletion(suggestionsView,completionText)
{this._codeMirror.focus();this._applyCompletionHint(completionText);this._commitCompletionHint();}
set noEndingSemicolon(noEndingSemicolon)
{this._noEndingSemicolon=noEndingSemicolon;} 
_resolveUpdatePromise(message)
{if(!this._updatePromise)
return;this._updatePromise.resolve(message);this._updatePromise=null;}
get _currentReplacementText()
{return this._currentCompletion+this._implicitSuffix;}
_hasPendingCompletion()
{return!isNaN(this._startOffset)&&!isNaN(this._endOffset)&&!isNaN(this._lineNumber);}
_notifyCompletionsHiddenSoon()
{function notify()
{if(this._completionHintMarker)
return;if(this._delegate&&typeof this._delegate.completionControllerCompletionsHidden==="function")
this._delegate.completionControllerCompletionsHidden(this);}
if(this._notifyCompletionsHiddenIfNeededTimeout)
clearTimeout(this._notifyCompletionsHiddenIfNeededTimeout);this._notifyCompletionsHiddenIfNeededTimeout=setTimeout(notify.bind(this),WI.CodeMirrorCompletionController.CompletionsHiddenDelay);}
_createCompletionHintMarker(position,text)
{var container=document.createElement("span");container.classList.add(WI.CodeMirrorCompletionController.CompletionHintStyleClassName);container.textContent=text;container.addEventListener("mousedown",(event)=>{event.preventDefault();this._commitCompletionHint();setTimeout(()=>{this._codeMirror.focus();},0);});this._completionHintMarker=this._codeMirror.setUniqueBookmark(position,{widget:container,insertLeft:true});}
_applyCompletionHint(completionText)
{if(!completionText)
return;function update()
{this._currentCompletion=completionText;this._removeCompletionHint(true,true);var replacementText=this._currentReplacementText;var from={line:this._lineNumber,ch:this._startOffset};var cursor={line:this._lineNumber,ch:this._endOffset};var currentText=this._codeMirror.getRange(from,cursor);this._createCompletionHintMarker(cursor,replacementText.replace(currentText,""));}
this._ignoreChange=true;this._ignoreNextCursorActivity=true;this._codeMirror.operation(update.bind(this));delete this._ignoreChange;}
_commitCompletionHint()
{function update()
{this._removeCompletionHint(true,true);var replacementText=this._currentReplacementText;var from={line:this._lineNumber,ch:this._startOffset};var cursor={line:this._lineNumber,ch:this._endOffset};var to={line:this._lineNumber,ch:this._startOffset+replacementText.length};var lastChar=this._currentCompletion.charAt(this._currentCompletion.length-1);var isClosing=")]}".indexOf(lastChar);if(isClosing!==-1)
to.ch-=1+this._implicitSuffix.length;this._codeMirror.replaceRange(replacementText,from,cursor,WI.CodeMirrorCompletionController.CompletionOrigin);this._codeMirror.setCursor(to);this.hideCompletions();}
this._ignoreChange=true;this._ignoreNextCursorActivity=true;this._codeMirror.operation(update.bind(this));delete this._ignoreChange;}
_removeLastChangeFromHistory()
{var history=this._codeMirror.getHistory();history.undone=[];history.done.pop();this._codeMirror.setHistory(history);}
_removeCompletionHint(nonatomic,dontRestorePrefix)
{if(!this._completionHintMarker)
return;this._notifyCompletionsHiddenSoon();function clearMarker(marker)
{if(!marker)
return;var range=marker.find();if(range)
marker.clear();return null;}
function update()
{this._completionHintMarker=clearMarker(this._completionHintMarker);if(dontRestorePrefix)
return;var from={line:this._lineNumber,ch:this._startOffset};var to={line:this._lineNumber,ch:this._endOffset};this._codeMirror.replaceRange(this._prefix,from,to,WI.CodeMirrorCompletionController.DeleteCompletionOrigin);this._removeLastChangeFromHistory();}
if(nonatomic){update.call(this);return;}
this._ignoreChange=true;this._codeMirror.operation(update.bind(this));delete this._ignoreChange;}
_scanStringForExpression(modeName,string,startOffset,direction,allowMiddleAndEmpty,includeStopCharacter,ignoreInitialUnmatchedOpenBracket,stopCharactersRegex)
{var stopCharactersRegex=stopCharactersRegex||this._stopCharactersRegex||WI.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap[modeName]||WI.CodeMirrorCompletionController.GenericStopCharactersRegex;function isStopCharacter(character)
{return stopCharactersRegex.test(character);}
function isOpenBracketCharacter(character)
{return WI.CodeMirrorCompletionController.OpenBracketCharactersRegex.test(character);}
function isCloseBracketCharacter(character)
{return WI.CodeMirrorCompletionController.CloseBracketCharactersRegex.test(character);}
function matchingBracketCharacter(character)
{return WI.CodeMirrorCompletionController.MatchingBrackets[character];}
var endOffset=Math.min(startOffset,string.length);var endOfLineOrWord=endOffset===string.length||isStopCharacter(string.charAt(endOffset));if(!endOfLineOrWord&&!allowMiddleAndEmpty)
return null;var bracketStack=[];var bracketOffsetStack=[];var startOffset=endOffset;var firstOffset=endOffset+direction;for(var i=firstOffset;direction>0?i<string.length:i>=0;i+=direction){var character=string.charAt(i);if(isStopCharacter(character)&&!bracketStack.length)
break;if(isCloseBracketCharacter(character)){bracketStack.push(character);bracketOffsetStack.push(i);}else if(isOpenBracketCharacter(character)){if((!ignoreInitialUnmatchedOpenBracket||i!==firstOffset)&&(!bracketStack.length||matchingBracketCharacter(character)!==bracketStack.lastValue))
break;bracketOffsetStack.pop();bracketStack.pop();}
startOffset=i+(direction>0?1:0);}
if(bracketOffsetStack.length)
startOffset=bracketOffsetStack.pop()+1;if(includeStopCharacter&&startOffset>0&&startOffset<string.length)
startOffset+=direction;if(direction>0){var tempEndOffset=endOffset;endOffset=startOffset;startOffset=tempEndOffset;}
return{string:string.substring(startOffset,endOffset),startOffset,endOffset};}
_completeAtCurrentPosition(force)
{if(this._codeMirror.somethingSelected()){this.hideCompletions();return;}
this._removeCompletionHint(true,true);var cursor=this._codeMirror.getCursor();var token=this._codeMirror.getTokenAt(cursor);if(token.type&&/\b(comment|string)\b/.test(token.type)){this.hideCompletions();return;}
var mode=this._codeMirror.getMode();var innerMode=CodeMirror.innerMode(mode,token.state).mode;var modeName=innerMode.alternateName||innerMode.name;var lineNumber=cursor.line;var lineString=this._codeMirror.getLine(lineNumber);var backwardScanResult=this._scanStringForExpression(modeName,lineString,cursor.ch,-1,force);if(!backwardScanResult){this.hideCompletions();return;}
var forwardScanResult=this._scanStringForExpression(modeName,lineString,cursor.ch,1,true,true);var suffix=forwardScanResult.string;this._ignoreNextCursorActivity=true;this._startOffset=backwardScanResult.startOffset;this._endOffset=backwardScanResult.endOffset;this._lineNumber=lineNumber;this._prefix=backwardScanResult.string;this._completions=[];this._implicitSuffix="";this._forced=force;var baseExpressionStopCharactersRegex=WI.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap[modeName];if(baseExpressionStopCharactersRegex)
var baseScanResult=this._scanStringForExpression(modeName,lineString,this._startOffset,-1,true,false,true,baseExpressionStopCharactersRegex);if(!force&&!backwardScanResult.string&&(!baseScanResult||!baseScanResult.string)){this.hideCompletions();return;}
var defaultCompletions=[];switch(modeName){case"css":defaultCompletions=this._generateCSSCompletions(token,baseScanResult?baseScanResult.string:null,suffix);break;case"javascript":defaultCompletions=this._generateJavaScriptCompletions(token,baseScanResult?baseScanResult.string:null,suffix);break;}
var extendedCompletionsProvider=this._extendedCompletionProviders[modeName];if(extendedCompletionsProvider){extendedCompletionsProvider.completionControllerCompletionsNeeded(this,defaultCompletions,baseScanResult?baseScanResult.string:null,this._prefix,suffix,force);return;}
if(this._delegate&&typeof this._delegate.completionControllerCompletionsNeeded==="function")
this._delegate.completionControllerCompletionsNeeded(this,this._prefix,defaultCompletions,baseScanResult?baseScanResult.string:null,suffix,force);else
this.updateCompletions(defaultCompletions);}
_generateCSSCompletions(mainToken,base,suffix)
{if(mainToken.state.state==="media"||mainToken.state.state==="top")
return[];if(/^[a-z]/i.test(suffix))
return[];var token=mainToken;var lineNumber=this._lineNumber;let getPreviousToken=()=>{if(!token.start){--lineNumber;if(lineNumber<0)
return null;}
return this._codeMirror.getTokenAt({line:lineNumber,ch:token.start?token.start:Number.MAX_VALUE});};if(token.state.state==="parens"){while(token&&token.state.state==="parens"&&token.string!=="(")
token=getPreviousToken();if(token)
token=getPreviousToken();if(!token)
return[];let functionName=token.string;if(!functionName)
return[];let functionCompletions=WI.CSSKeywordCompletions.forFunction(functionName).startsWith(this._prefix);if(this._delegate&&this._delegate.completionControllerCSSFunctionValuesNeeded)
functionCompletions=this._delegate.completionControllerCSSFunctionValuesNeeded(this,functionName,functionCompletions);return functionCompletions;}
while(token.state.state==="prop"){let previousToken=getPreviousToken();if(!previousToken)
break;token=previousToken;}

if(mainToken!==token&&token.type&&/\bproperty\b/.test(token.type)){var propertyName=token.string;

this._implicitSuffix=" ";if(suffix===";")
this._implicitSuffix=this._noEndingSemicolon?"":";";else if(suffix.startsWith("("))
this._implicitSuffix="";if(this._implicitSuffix===suffix)
this._implicitSuffix="";let completions=WI.CSSKeywordCompletions.forProperty(propertyName).startsWith(this._prefix);if(suffix.startsWith("("))
completions=completions.map((x)=>x.replace(/\(\)$/,""));return completions;}
this._implicitSuffix=suffix!==":"?": ":"";return WI.CSSCompletions.cssNameCompletions.startsWith(this._prefix);}
_generateJavaScriptCompletions(mainToken,base,suffix)
{
if(base&&!/[({[]$/.test(base))
return[];var matchingWords=[];var prefix=this._prefix;var localState=mainToken.state.localState?mainToken.state.localState:mainToken.state;var declaringVariable=localState.lexical.type==="vardef";var insideSwitch=localState.lexical.prev?localState.lexical.prev.info==="switch":false;var insideBlock=localState.lexical.prev?localState.lexical.prev.type==="}":false;var insideParenthesis=localState.lexical.type===")";var insideBrackets=localState.lexical.type==="]";const allKeywords=["break","case","catch","class","const","continue","debugger","default","delete","do","else","extends","false","finally","for","function","if","in","Infinity","instanceof","let","NaN","new","null","of","return","static","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"];const valueKeywords=["false","Infinity","NaN","null","this","true","undefined","globalThis"];const allowedKeywordsInsideBlocks=new Set(allKeywords);const allowedKeywordsWhenDeclaringVariable=new Set(valueKeywords);const allowedKeywordsInsideParenthesis=new Set(valueKeywords.concat(["class","function"]));const allowedKeywordsInsideBrackets=allowedKeywordsInsideParenthesis;const allowedKeywordsOnlyInsideSwitch=new Set(["case","default"]);function matchKeywords(keywords)
{for(let keyword of keywords){if(!insideSwitch&&allowedKeywordsOnlyInsideSwitch.has(keyword))
continue;if(insideBlock&&!allowedKeywordsInsideBlocks.has(keyword))
continue;if(insideBrackets&&!allowedKeywordsInsideBrackets.has(keyword))
continue;if(insideParenthesis&&!allowedKeywordsInsideParenthesis.has(keyword))
continue;if(declaringVariable&&!allowedKeywordsWhenDeclaringVariable.has(keyword))
continue;if(!keyword.startsWith(prefix))
continue;matchingWords.push(keyword);}}
function matchVariables()
{function filterVariables(variables)
{for(var variable=variables;variable;variable=variable.next){if(declaringVariable&&variable.name===prefix)
continue;if(variable.name.startsWith(prefix)&&!matchingWords.includes(variable.name))
matchingWords.push(variable.name);}}
var context=localState.context;while(context){if(context.vars)
filterVariables(context.vars);context=context.prev;}
if(localState.localVars)
filterVariables(localState.localVars);if(localState.globalVars)
filterVariables(localState.globalVars);}
switch(suffix.substring(0,1)){case"":case" ":matchVariables();matchKeywords(allKeywords);break;case".":case"[":matchVariables();matchKeywords(["false","Infinity","NaN","this","true"]);break;case"(":matchVariables();matchKeywords(["catch","else","for","function","if","return","switch","throw","while","with","yield"]);break;case"{":matchKeywords(["do","else","finally","return","try","yield"]);break;case":":if(insideSwitch)
matchKeywords(["case","default"]);break;case";":matchVariables();matchKeywords(valueKeywords);matchKeywords(["break","continue","debugger","return","void"]);break;}
return matchingWords;}
_handleUpKey(codeMirror)
{if(!this._hasPendingCompletion())
return CodeMirror.Pass;if(!this.isShowingCompletions())
return;this._suggestionsView.selectPrevious();}
_handleDownKey(codeMirror)
{if(!this._hasPendingCompletion())
return CodeMirror.Pass;if(!this.isShowingCompletions())
return;this._suggestionsView.selectNext();}
_handleRightOrEnterKey(codeMirror)
{if(!this._hasPendingCompletion())
return CodeMirror.Pass;if(!this.isShowingCompletions())
return;this._commitCompletionHint();}
_handleEscapeKey(codeMirror)
{var delegateImplementsShouldAllowEscapeCompletion=this._delegate&&typeof this._delegate.completionControllerShouldAllowEscapeCompletion==="function";if(this._hasPendingCompletion())
this.hideCompletions();else if(this._codeMirror.getOption("readOnly"))
return CodeMirror.Pass;else if(!delegateImplementsShouldAllowEscapeCompletion||this._delegate.completionControllerShouldAllowEscapeCompletion(this))
this._completeAtCurrentPosition(true);else
return CodeMirror.Pass;}
_handleTabKey(codeMirror)
{if(!this._hasPendingCompletion())
return CodeMirror.Pass;if(!this.isShowingCompletions())
return;if(!this._completions.length)
return;if(!this._currentCompletion)
return;if(this._completions.length===1){this._commitCompletionHint();return;}
var prefixLength=this._prefix.length;var commonPrefix=this._completions[0];for(var i=1;i<this._completions.length;++i){var completion=this._completions[i];var lastIndex=Math.min(commonPrefix.length,completion.length);for(var j=prefixLength;j<lastIndex;++j){if(commonPrefix[j]!==completion[j]){commonPrefix=commonPrefix.substr(0,j);break;}}}
if(commonPrefix===this._prefix){this._commitCompletionHint();return;}

this._prefix=commonPrefix;this._endOffset=this._startOffset+commonPrefix.length;this._applyCompletionHint(this._currentCompletion);}
_handleChange(codeMirror,change)
{if(this.isCompletionChange(change))
return;this._ignoreNextCursorActivity=true;if(!change.origin||change.origin.charAt(0)!=="+"){this.hideCompletions();return;}
if(change.origin==="+delete"&&!this._hasPendingCompletion())
return;this._completeAtCurrentPosition(false);}
_handleCursorActivity(codeMirror)
{if(this._ignoreChange)
return;if(this._ignoreNextCursorActivity){delete this._ignoreNextCursorActivity;return;}
this.hideCompletions();}
_handleHideKey(codeMirror)
{this.hideCompletions();return CodeMirror.Pass;}
_handleHideAction(codeMirror)
{if(this.isHandlingClickEvent())
return;this.hideCompletions();}};WI.CodeMirrorCompletionController.Mode={Basic:"basic",EventBreakpoint:"event-breakpoint",ExceptionBreakpoint:"exception-breakpoint",FullConsoleCommandLineAPI:"full-console-command-line-api",PausedConsoleCommandLineAPI:"paused-console-command-line-api",};WI.CodeMirrorCompletionController.UpdatePromise={Canceled:"code-mirror-completion-controller-canceled",CompletionsFound:"code-mirror-completion-controller-completions-found",NoCompletionsFound:"code-mirror-completion-controller-no-completions-found"};WI.CodeMirrorCompletionController.GenericStopCharactersRegex=/[\s=:;,]/;WI.CodeMirrorCompletionController.DefaultStopCharactersRegexModeMap={"css":/[\s:;,{}()]/,"javascript":/[\s=:;,!+\-*/%&|^~?<>.{}()[\]]/};WI.CodeMirrorCompletionController.BaseExpressionStopCharactersRegexModeMap={"javascript":/[\s=:;,!+\-*/%&|^~?<>]/};WI.CodeMirrorCompletionController.OpenBracketCharactersRegex=/[({[]/;WI.CodeMirrorCompletionController.CloseBracketCharactersRegex=/[)}\]]/;WI.CodeMirrorCompletionController.MatchingBrackets={"{":"}","(":")","[":"]","}":"{",")":"(","]":"["};WI.CodeMirrorCompletionController.CompletionHintStyleClassName="completion-hint";WI.CodeMirrorCompletionController.CompletionsHiddenDelay=250;WI.CodeMirrorCompletionController.CompletionTypingDelay=250;WI.CodeMirrorCompletionController.CompletionOrigin="+completion";WI.CodeMirrorCompletionController.DeleteCompletionOrigin="+delete-completion";WI.CodeMirrorBezierEditingController=class CodeMirrorBezierEditingController extends WI.CodeMirrorEditingController
{ get initialValue()
{return WI.CubicBezier.fromString(this.text);}
get cssClassName()
{return"cubic-bezier";}
popoverWillPresent(popover)
{this._bezierEditor=new WI.BezierEditor;this._bezierEditor.addEventListener(WI.BezierEditor.Event.BezierChanged,this._bezierEditorBezierChanged,this);popover.content=this._bezierEditor.element;}
popoverDidPresent(popover)
{this._bezierEditor.bezier=this.value;}
popoverDidDismiss(popover)
{this._bezierEditor.removeListeners();} 
_bezierEditorBezierChanged(event)
{this.value=event.data.bezier;}};WI.CodeMirrorDragToAdjustNumberController=class CodeMirrorDragToAdjustNumberController extends WI.Object
{constructor(codeMirror)
{super();this._codeMirror=codeMirror;this._dragToAdjustController=new WI.DragToAdjustController(this);} 
get enabled()
{return this._dragToAdjustController.enabled;}
set enabled(enabled)
{if(this.enabled===enabled)
return;this._dragToAdjustController.element=this._codeMirror.getWrapperElement();this._dragToAdjustController.enabled=enabled;} 
dragToAdjustControllerActiveStateChanged(dragToAdjustController)
{if(!dragToAdjustController.active)
this._hoveredTokenInfo=null;}
dragToAdjustControllerCanBeActivated(dragToAdjustController)
{return!this._codeMirror.getOption("readOnly");}
dragToAdjustControllerCanBeAdjusted(dragToAdjustController)
{return this._hoveredTokenInfo&&this._hoveredTokenInfo.containsNumber;}
dragToAdjustControllerWasAdjustedByAmount(dragToAdjustController,amount)
{this._codeMirror.alterNumberInRange(amount,this._hoveredTokenInfo.startPosition,this._hoveredTokenInfo.endPosition,false);}
dragToAdjustControllerDidReset(dragToAdjustController)
{this._hoveredTokenInfo=null;}
dragToAdjustControllerCanAdjustObjectAtPoint(dragToAdjustController,point)
{var position=this._codeMirror.coordsChar({left:point.x,top:point.y});var token=this._codeMirror.getTokenAt(position);if(!token||!token.type||!token.string){if(this._hoveredTokenInfo)
dragToAdjustController.reset();return false;}
if(this._hoveredTokenInfo&&this._hoveredTokenInfo.line===position.line&&this._hoveredTokenInfo.token.start===token.start&&this._hoveredTokenInfo.token.end===token.end)
return this._hoveredTokenInfo.token.type.indexOf("number")!==-1;var containsNumber=token.type.indexOf("number")!==-1;this._hoveredTokenInfo={token,line:position.line,containsNumber,startPosition:{ch:token.start,line:position.line},endPosition:{ch:token.end,line:position.line}};return containsNumber;}};CodeMirror.defineOption("dragToAdjustNumbers",true,function(codeMirror,value,oldValue){if(!codeMirror.dragToAdjustNumberController)
codeMirror.dragToAdjustNumberController=new WI.CodeMirrorDragToAdjustNumberController(codeMirror);codeMirror.dragToAdjustNumberController.enabled=value;});WI.CodeMirrorGradientEditingController=class CodeMirrorGradientEditingController extends WI.CodeMirrorEditingController
{ get initialValue()
{return WI.Gradient.fromString(this.text);}
get cssClassName()
{return"gradient";}
get popoverPreferredEdges()
{
return[WI.RectEdge.MIN_X,WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];}
popoverTargetFrameWithRects(rects)
{
return rects[0];}
popoverWillPresent(popover)
{function handleColorPickerToggled(event)
{popover.update();}
this._gradientEditor=new WI.GradientEditor;this._gradientEditor.addEventListener(WI.GradientEditor.Event.GradientChanged,this._gradientEditorGradientChanged,this);this._gradientEditor.addEventListener(WI.GradientEditor.Event.ColorPickerToggled,handleColorPickerToggled,this);popover.content=this._gradientEditor.element;}
popoverDidPresent(popover)
{this._gradientEditor.gradient=this.value;} 
_gradientEditorGradientChanged(event)
{this.value=event.data.gradient;}};WI.CodeMirrorSpringEditingController=class CodeMirrorSpringEditingController extends WI.CodeMirrorEditingController
{ get initialValue()
{return WI.Spring.fromString(this.text);}
get cssClassName()
{return"spring";}
popoverWillPresent(popover)
{this._springEditor=new WI.SpringEditor;this._springEditor.addEventListener(WI.SpringEditor.Event.SpringChanged,this._springEditorSpringChanged,this);popover.content=this._springEditor.element;}
popoverDidPresent(popover)
{this._springEditor.spring=this.value;} 
_springEditorSpringChanged(event)
{this.value=event.data.spring;}};WI.CodeMirrorTokenTrackingController=class CodeMirrorTokenTrackingController extends WI.Object
{constructor(codeMirror,delegate)
{super();this._codeMirror=codeMirror;this._delegate=delegate||null;this._mode=WI.CodeMirrorTokenTrackingController.Mode.None;this._mouseOverDelayDuration=0;this._mouseOutReleaseDelayDuration=0;this._classNameForHighlightedRange=null;this._enabled=false;this._tracking=false;this._previousTokenInfo=null;this._hoveredMarker=null;this._ignoreNextMouseMove=false;const hidePopover=this._hidePopover.bind(this);this._codeMirror.addKeyMap({"Cmd-Enter":this._handleCommandEnterKey.bind(this),"Esc":hidePopover});this._codeMirror.on("cursorActivity",hidePopover);} 
get delegate()
{return this._delegate;}
set delegate(x)
{this._delegate=x;}
get enabled()
{return this._enabled;}
set enabled(enabled)
{if(this._enabled===enabled)
return;this._enabled=enabled;var wrapper=this._codeMirror.getWrapperElement();if(enabled){wrapper.addEventListener("mouseenter",this);wrapper.addEventListener("mouseleave",this);this._updateHoveredTokenInfo({left:WI.mouseCoords.x,top:WI.mouseCoords.y});this._startTracking();}else{wrapper.removeEventListener("mouseenter",this);wrapper.removeEventListener("mouseleave",this);this._stopTracking();}}
get mode()
{return this._mode;}
set mode(mode)
{var oldMode=this._mode;this._mode=mode||WI.CodeMirrorTokenTrackingController.Mode.None;if(oldMode!==this._mode&&this._tracking&&this._previousTokenInfo)
this._processNewHoveredToken(this._previousTokenInfo);}
get mouseOverDelayDuration()
{return this._mouseOverDelayDuration;}
set mouseOverDelayDuration(x)
{this._mouseOverDelayDuration=Math.max(x,0);}
get mouseOutReleaseDelayDuration()
{return this._mouseOutReleaseDelayDuration;}
set mouseOutReleaseDelayDuration(x)
{this._mouseOutReleaseDelayDuration=Math.max(x,0);}
get classNameForHighlightedRange()
{return this._classNameForHighlightedRange;}
set classNameForHighlightedRange(x)
{this._classNameForHighlightedRange=x||null;}
get candidate()
{return this._candidate;}
get hoveredMarker()
{return this._hoveredMarker;}
set hoveredMarker(hoveredMarker)
{this._hoveredMarker=hoveredMarker;}
highlightLastHoveredRange()
{if(this._candidate)
this.highlightRange(this._candidate.hoveredTokenRange);}
highlightRange(range)
{if(this._codeMirrorMarkedText&&this._codeMirrorMarkedText.className===this._classNameForHighlightedRange){var highlightedRange=this._codeMirrorMarkedText.find();if(!highlightedRange)
return;if(WI.compareCodeMirrorPositions(highlightedRange.from,range.start)===0&&WI.compareCodeMirrorPositions(highlightedRange.to,range.end)===0)
return;}
this.removeHighlightedRange();var className=this._classNameForHighlightedRange||"";this._codeMirrorMarkedText=this._codeMirror.markText(range.start,range.end,{className});window.addEventListener("mousemove",this,true);}
removeHighlightedRange()
{if(!this._codeMirrorMarkedText)
return;this._codeMirrorMarkedText.clear();this._codeMirrorMarkedText=null;window.removeEventListener("mousemove",this,true);} 
_startTracking()
{if(this._tracking)
return;this._tracking=true;this._ignoreNextMouseMove=false;var wrapper=this._codeMirror.getWrapperElement();wrapper.addEventListener("mousemove",this,true);wrapper.addEventListener("mouseout",this,false);wrapper.addEventListener("mousedown",this,false);wrapper.addEventListener("mouseup",this,false);wrapper.addEventListener("mousewheel",this,false);window.addEventListener("blur",this,true);}
_stopTracking()
{if(!this._tracking)
return;this._tracking=false;this._candidate=null;var wrapper=this._codeMirror.getWrapperElement();wrapper.removeEventListener("mousemove",this,true);wrapper.removeEventListener("mouseout",this,false);wrapper.removeEventListener("mousedown",this,false);wrapper.removeEventListener("mouseup",this,false);wrapper.removeEventListener("mousewheel",this,false);window.removeEventListener("blur",this,true);window.removeEventListener("mousemove",this,true);this._resetTrackingStates();}
handleEvent(event)
{switch(event.type){case"mouseenter":this._mouseEntered(event);break;case"mouseleave":this._mouseLeft(event);break;case"mousemove":if(event.currentTarget===window)
this._mouseMovedWithMarkedText(event);else
this._mouseMovedOverEditor(event);break;case"mouseout":if(!event.currentTarget.contains(event.relatedTarget))
this._mouseMovedOutOfEditor(event);break;case"mousedown":this._mouseButtonWasPressedOverEditor(event);break;case"mouseup":this._mouseButtonWasReleasedOverEditor(event);break;case"mousewheel":this._ignoreNextMouseMove=true;break;case"blur":this._windowLostFocus(event);break;}}
_handleCommandEnterKey(codeMirror)
{const tokenInfo=this._getTokenInfoForPosition(codeMirror.getCursor("head"));tokenInfo.triggeredBy=WI.CodeMirrorTokenTrackingController.TriggeredBy.Keyboard;this._processNewHoveredToken(tokenInfo);}
_hidePopover()
{if(!this._candidate)
return CodeMirror.Pass;if(this._delegate&&typeof this._delegate.tokenTrackingControllerHighlightedRangeReleased==="function"){const forceHidePopover=true;this._delegate.tokenTrackingControllerHighlightedRangeReleased(this,forceHidePopover);}}
_mouseEntered(event)
{if(!this._tracking)
this._startTracking();}
_mouseLeft(event)
{this._stopTracking();}
_mouseMovedWithMarkedText(event)
{if(this._candidate&&this._candidate.triggeredBy===WI.CodeMirrorTokenTrackingController.TriggeredBy.Keyboard)
return;var shouldRelease=!event.target.classList.contains(this._classNameForHighlightedRange);if(shouldRelease&&this._delegate&&typeof this._delegate.tokenTrackingControllerCanReleaseHighlightedRange==="function")
shouldRelease=this._delegate.tokenTrackingControllerCanReleaseHighlightedRange(this,event.target);if(shouldRelease){if(!this._markedTextMouseoutTimer)
this._markedTextMouseoutTimer=setTimeout(this._markedTextIsNoLongerHovered.bind(this),this._mouseOutReleaseDelayDuration);return;}
if(this._markedTextMouseoutTimer)
clearTimeout(this._markedTextMouseoutTimer);this._markedTextMouseoutTimer=0;}
_markedTextIsNoLongerHovered()
{if(this._delegate&&typeof this._delegate.tokenTrackingControllerHighlightedRangeReleased==="function")
this._delegate.tokenTrackingControllerHighlightedRangeReleased(this);this._markedTextMouseoutTimer=0;}
_mouseMovedOverEditor(event)
{if(this._ignoreNextMouseMove){this._ignoreNextMouseMove=false;return;}
this._updateHoveredTokenInfo({left:event.pageX,top:event.pageY});}
_updateHoveredTokenInfo(mouseCoords)
{var position=this._codeMirror.coordsChar(mouseCoords);var token=this._codeMirror.getTokenAt(position);if(!token||!token.type||!token.string){if(this._hoveredMarker&&this._delegate&&typeof this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker==="function"){if(!this._codeMirror.findMarksAt(position).includes(this._hoveredMarker.codeMirrorTextMarker))
this._delegate.tokenTrackingControllerMouseOutOfHoveredMarker(this,this._hoveredMarker);}
this._resetTrackingStates();return;}
if(this._previousTokenInfo&&this._previousTokenInfo.position.line===position.line&&this._previousTokenInfo.token.start===token.start&&this._previousTokenInfo.token.end===token.end)
return;var tokenInfo=this._previousTokenInfo=this._getTokenInfoForPosition(position);if(/\bmeta\b/.test(token.type)){let nextTokenPosition=Object.shallowCopy(position);nextTokenPosition.ch=tokenInfo.token.end+1;let nextToken=this._codeMirror.getTokenAt(nextTokenPosition);if(nextToken&&nextToken.type&&!/\bmeta\b/.test(nextToken.type)){tokenInfo.token.type=nextToken.type;tokenInfo.token.string=tokenInfo.token.string+nextToken.string;tokenInfo.token.end=nextToken.end;}}else{let previousTokenPosition=Object.shallowCopy(position);previousTokenPosition.ch=tokenInfo.token.start-1;let previousToken=this._codeMirror.getTokenAt(previousTokenPosition);if(previousToken&&previousToken.type&&/\bmeta\b/.test(previousToken.type)){tokenInfo.token.string=previousToken.string+tokenInfo.token.string;tokenInfo.token.start=previousToken.start;}}
if(this._tokenHoverTimer)
clearTimeout(this._tokenHoverTimer);this._tokenHoverTimer=0;if(this._codeMirrorMarkedText||!this._mouseOverDelayDuration)
this._processNewHoveredToken(tokenInfo);else
this._tokenHoverTimer=setTimeout(this._processNewHoveredToken.bind(this,tokenInfo),this._mouseOverDelayDuration);}
_getTokenInfoForPosition(position)
{var token=this._codeMirror.getTokenAt(position);var innerMode=CodeMirror.innerMode(this._codeMirror.getMode(),token.state);var codeMirrorModeName=innerMode.mode.alternateName||innerMode.mode.name;return{token,position,innerMode,modeName:codeMirrorModeName};}
_mouseMovedOutOfEditor(event)
{if(this._tokenHoverTimer)
clearTimeout(this._tokenHoverTimer);this._tokenHoverTimer=0;this._previousTokenInfo=null;this._selectionMayBeInProgress=false;}
_mouseButtonWasPressedOverEditor(event)
{this._selectionMayBeInProgress=true;}
_mouseButtonWasReleasedOverEditor(event)
{this._selectionMayBeInProgress=false;this._mouseMovedOverEditor(event);if(this._codeMirrorMarkedText&&this._previousTokenInfo){var position=this._codeMirror.coordsChar({left:event.pageX,top:event.pageY});var marks=this._codeMirror.findMarksAt(position);for(var i=0;i<marks.length;++i){if(marks[i]===this._codeMirrorMarkedText){if(this._delegate&&typeof this._delegate.tokenTrackingControllerHighlightedRangeWasClicked==="function")
this._delegate.tokenTrackingControllerHighlightedRangeWasClicked(this);break;}}}}
_windowLostFocus(event)
{this._resetTrackingStates();}
_processNewHoveredToken(tokenInfo)
{if(this._selectionMayBeInProgress)
return;this._candidate=null;switch(this._mode){case WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens:this._candidate=this._processNonSymbolToken(tokenInfo);break;case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression:case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation:this._candidate=this._processJavaScriptExpression(tokenInfo);break;case WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens:this._candidate=this._processMarkedToken(tokenInfo);break;}
if(!this._candidate)
return;this._candidate.triggeredBy=tokenInfo.triggeredBy;if(this._markedTextMouseoutTimer)
clearTimeout(this._markedTextMouseoutTimer);this._markedTextMouseoutTimer=0;if(this._delegate&&typeof this._delegate.tokenTrackingControllerNewHighlightCandidate==="function")
this._delegate.tokenTrackingControllerNewHighlightCandidate(this,this._candidate);}
_processNonSymbolToken(tokenInfo)
{var type=tokenInfo.token.type;if(!type)
return null;var startPosition={line:tokenInfo.position.line,ch:tokenInfo.token.start};var endPosition={line:tokenInfo.position.line,ch:tokenInfo.token.end};return{hoveredToken:tokenInfo.token,hoveredTokenRange:{start:startPosition,end:endPosition},};}
_processJavaScriptExpression(tokenInfo)
{if(tokenInfo.modeName!=="javascript")
return null;var startPosition={line:tokenInfo.position.line,ch:tokenInfo.token.start};var endPosition={line:tokenInfo.position.line,ch:tokenInfo.token.end};function tokenIsInRange(token,range)
{return token.line>=range.start.line&&token.ch>=range.start.ch&&token.line<=range.end.line&&token.ch<=range.end.ch;}
if(this._codeMirror.somethingSelected()){var selectionRange={start:this._codeMirror.getCursor("start"),end:this._codeMirror.getCursor("end")};if(tokenIsInRange(startPosition,selectionRange)||tokenIsInRange(endPosition,selectionRange)){return{hoveredToken:tokenInfo.token,hoveredTokenRange:selectionRange,expression:this._codeMirror.getSelection(),expressionRange:selectionRange,};}}
var type=tokenInfo.token.type;var isProperty=type.indexOf("property")!==-1;var isKeyword=type.indexOf("keyword")!==-1;if(!isProperty&&!isKeyword&&type.indexOf("variable")===-1&&type.indexOf("def")===-1)
return null;let state=tokenInfo.innerMode.state;if(isProperty&&state.lexical&&state.lexical.type==="}"){let shorthand=false;let mode=tokenInfo.innerMode.mode;let position={line:tokenInfo.position.line,ch:tokenInfo.token.end};WI.walkTokens(this._codeMirror,mode,position,function(tokenType,string){if(tokenType)
return false;if(string==="(")
return false;if(string===","||string==="}"){shorthand=true;return false;}
return true;});if(!shorthand)
return null;}
if(isKeyword&&tokenInfo.token.string!=="this")
return null;var expression=tokenInfo.token.string;var expressionStartPosition={line:tokenInfo.position.line,ch:tokenInfo.token.start};while(true){var token=this._codeMirror.getTokenAt(expressionStartPosition);if(!token)
break;var isDot=!token.type&&token.string===".";var isExpression=token.type&&token.type.includes("m-javascript");if(!isDot&&!isExpression)
break;if(isExpression){if(token.type.includes("operator"))
break;if(token.type.includes("string-2"))
break;}
expression=token.string+expression;expressionStartPosition.ch=token.start;}
return{hoveredToken:tokenInfo.token,hoveredTokenRange:{start:startPosition,end:endPosition},expression,expressionRange:{start:expressionStartPosition,end:endPosition},};}
_processMarkedToken(tokenInfo)
{return this._processNonSymbolToken(tokenInfo);}
_resetTrackingStates()
{if(this._tokenHoverTimer)
clearTimeout(this._tokenHoverTimer);this._tokenHoverTimer=0;this._selectionMayBeInProgress=false;this._previousTokenInfo=null;this.removeHighlightedRange();}};WI.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName="jump-to-symbol-highlight";WI.CodeMirrorTokenTrackingController.Mode={None:"none",NonSymbolTokens:"non-symbol-tokens",JavaScriptExpression:"javascript-expression",JavaScriptTypeInformation:"javascript-type-information",MarkedTokens:"marked-tokens"};WI.CodeMirrorTokenTrackingController.TriggeredBy={Keyboard:"keyboard",Hover:"hover"};WI.CodeMirrorTextKillController=class CodeMirrorTextKillController extends WI.Object
{constructor(codeMirror)
{super();this._codeMirror=codeMirror;this._expectingChangeEventForKill=false;this._nextKillStartsNewSequence=true;this._shouldPrependToKillRing=false;this._handleTextChangeListener=this._handleTextChange.bind(this);this._handleEditorBlurListener=this._handleEditorBlur.bind(this);this._handleSelectionOrCaretChangeListener=this._handleSelectionOrCaretChange.bind(this);this._codeMirror.addKeyMap({"Ctrl-K":this._handleTextKillCommand.bind(this,"killLine",false),"Alt-D":this._handleTextKillCommand.bind(this,"delWordAfter",false),"Alt-Delete":this._handleTextKillCommand.bind(this,"delGroupAfter",false),"Cmd-Backspace":this._handleTextKillCommand.bind(this,"delWrappedLineLeft",true),"Cmd-Delete":this._handleTextKillCommand.bind(this,"delWrappedLineRight",false),"Alt-Backspace":this._handleTextKillCommand.bind(this,"delGroupBefore",true),"Ctrl-Alt-Backspace":this._handleTextKillCommand.bind(this,"delGroupAfter",false),});}
_handleTextKillCommand(command,prependsToKillRing,codeMirror)
{
if(this._codeMirror.getOption("readOnly"))
return;this._shouldPrependToKillRing=prependsToKillRing;
if(!this._expectingChangeEventForKill)
this._codeMirror.on("changes",this._handleTextChangeListener);this._expectingChangeEventForKill=true;this._codeMirror.execCommand(command);}
_handleTextChange(codeMirror,changes)
{this._codeMirror.off("changes",this._handleTextChangeListener);
if(!this._expectingChangeEventForKill)
return;this._expectingChangeEventForKill=false;let change=changes[0];
if(change.origin!=="+delete")
return;
let killedText;if(change.to.line===change.from.line+1&&change.removed.length===2){if(change.removed[0].length&&!change.removed[1].length)
killedText=change.removed[0]+"\n";else
killedText="\n";}else{killedText=change.removed[0];}
InspectorFrontendHost.killText(killedText,this._shouldPrependToKillRing,this._nextKillStartsNewSequence);

this._nextKillStartsNewSequence=false;this._codeMirror.on("blur",this._handleEditorBlurListener);this._codeMirror.on("cursorActivity",this._handleSelectionOrCaretChangeListener);}
_handleEditorBlur(codeMirror)
{this._nextKillStartsNewSequence=true;this._codeMirror.off("blur",this._handleEditorBlurListener);this._codeMirror.off("cursorActivity",this._handleSelectionOrCaretChangeListener);}
_handleSelectionOrCaretChange(codeMirror)
{if(this._expectingChangeEventForKill)
return;this._nextKillStartsNewSequence=true;this._codeMirror.off("blur",this._handleEditorBlurListener);this._codeMirror.off("cursorActivity",this._handleSelectionOrCaretChangeListener);}};WI.ConsoleManager=class ConsoleManager extends WI.Object
{constructor()
{super();this._warningCount=0;this._errorCount=0;this._issues=[];this._lastMessageLevel=null;this._clearMessagesRequested=false;this._isNewPageOrReload=false;this._remoteObjectsToRelease=null;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._customLoggingChannels=[];} 
static supportsLogChannels()
{return InspectorBackend.hasCommand("Console.getLoggingChannels");}
static issueMatchSourceCode(issue,sourceCode)
{if(sourceCode instanceof WI.SourceMapResource)
return issue.sourceCodeLocation&&issue.sourceCodeLocation.displaySourceCode===sourceCode;if(sourceCode instanceof WI.Resource)
return issue.url===sourceCode.url&&(!issue.sourceCodeLocation||issue.sourceCodeLocation.sourceCode===sourceCode);if(sourceCode instanceof WI.Script)
return issue.sourceCodeLocation&&issue.sourceCodeLocation.sourceCode===sourceCode;return false;} 
get warningCount(){return this._warningCount;}
get errorCount(){return this._errorCount;}
get customLoggingChannels(){return this._customLoggingChannels;}
issuesForSourceCode(sourceCode)
{var issues=[];for(var i=0;i<this._issues.length;++i){var issue=this._issues[i];if(WI.ConsoleManager.issueMatchSourceCode(issue,sourceCode))
issues.push(issue);}
return issues;}
releaseRemoteObjectWithConsoleClear(remoteObject)
{if(!this._remoteObjectsToRelease)
this._remoteObjectsToRelease=new Set;this._remoteObjectsToRelease.add(remoteObject);} 
messageWasAdded(target,source,level,text,type,url,line,column,repeatCount,parameters,stackTrace,requestId)
{if(parameters)
parameters=parameters.map((x)=>WI.RemoteObject.fromPayload(x,target));let message=new WI.ConsoleMessage(target,source,level,text,type,url,line,column,repeatCount,parameters,stackTrace,null);this._incrementMessageLevelCount(message.level,message.repeatCount);this.dispatchEventToListeners(WI.ConsoleManager.Event.MessageAdded,{message});if(message.level===WI.ConsoleMessage.MessageLevel.Warning||message.level===WI.ConsoleMessage.MessageLevel.Error){let issue=new WI.IssueMessage(message);this._issues.push(issue);this.dispatchEventToListeners(WI.ConsoleManager.Event.IssueAdded,{issue});}}
messagesCleared()
{if(this._remoteObjectsToRelease){for(let remoteObject of this._remoteObjectsToRelease)
remoteObject.release();this._remoteObjectsToRelease=null;}
WI.ConsoleCommandResultMessage.clearMaximumSavedResultIndex();if(this._clearMessagesRequested){this._clearMessagesRequested=false;this._warningCount=0;this._errorCount=0;this._issues=[];this._lastMessageLevel=null;this.dispatchEventToListeners(WI.ConsoleManager.Event.Cleared);}else{setTimeout(this._delayedMessagesCleared.bind(this),0);}}
messageRepeatCountUpdated(count)
{this._incrementMessageLevelCount(this._lastMessageLevel,1);this.dispatchEventToListeners(WI.ConsoleManager.Event.PreviousMessageRepeatCountUpdated,{count});}
requestClearMessages()
{this._clearMessagesRequested=true;for(let target of WI.targets)
target.ConsoleAgent.clearMessages();}
initializeLogChannels(target)
{if(!WI.ConsoleManager.supportsLogChannels())
return;if(this._customLoggingChannels.length)
return;target.ConsoleAgent.getLoggingChannels((error,channels)=>{if(error)
return;this._customLoggingChannels=channels.map(WI.LoggingChannel.fromPayload);});} 
_incrementMessageLevelCount(level,count)
{switch(level){case WI.ConsoleMessage.MessageLevel.Warning:this._warningCount+=count;break;case WI.ConsoleMessage.MessageLevel.Error:this._errorCount+=count;break;}
this._lastMessageLevel=level;}
_delayedMessagesCleared()
{if(this._isNewPageOrReload){this._isNewPageOrReload=false;if(!WI.settings.clearLogOnNavigate.value)
return;}
this._warningCount=0;this._errorCount=0;this._issues=[];this._lastMessageLevel=null;this.dispatchEventToListeners(WI.ConsoleManager.Event.Cleared);}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._isNewPageOrReload=true;let timestamp=Date.now();let wasReloaded=event.data.oldMainResource&&event.data.oldMainResource.url===event.target.mainResource.url;this.dispatchEventToListeners(WI.ConsoleManager.Event.SessionStarted,{timestamp,wasReloaded});WI.ConsoleCommandResultMessage.clearMaximumSavedResultIndex();}};WI.ConsoleManager.Event={SessionStarted:"console-manager-session-was-started",Cleared:"console-manager-cleared",MessageAdded:"console-manager-message-added",IssueAdded:"console-manager-issue-added",PreviousMessageRepeatCountUpdated:"console-manager-previous-message-repeat-count-updated",};WI.DOMDebuggerManager=class DOMDebuggerManager extends WI.Object
{constructor()
{super();this._domBreakpointURLMap=new Multimap;this._domBreakpointFrameIdentifierMap=new Map;this._clearingDOMBreakpointsForRemovedDOMNode=false;this._listenerBreakpoints=[];this._allAnimationFramesBreakpoint=null;this._allIntervalsBreakpoint=null;this._allListenersBreakpoint=null;this._allTimeoutsBreakpoint=null;this._urlBreakpoints=[];this._allRequestsBreakpoint=null;WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleDOMBreakpointDisabledStateChanged,this);WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange,this._handleDOMBreakpointEditablePropertyChanged,this);WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange,this._handleDOMBreakpointEditablePropertyChanged,this);WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleDOMBreakpointEditablePropertyChanged,this);WI.DOMBreakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange,this._handleDOMBreakpointActionsChanged,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleEventBreakpointDisabledStateChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange,this._handleEventBreakpointActionsChanged,this);WI.URLBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleURLBreakpointDisabledStateChanged,this);WI.URLBreakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange,this._handleURLBreakpointEditablePropertyChanged,this);WI.URLBreakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange,this._handleURLBreakpointEditablePropertyChanged,this);WI.URLBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleURLBreakpointEditablePropertyChanged,this);WI.URLBreakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange,this._handleURLBreakpointActionsChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);WI.domManager.addEventListener(WI.DOMManager.Event.NodeInserted,this._nodeInserted,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._childFrameWasRemoved,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);let loadBreakpoints=(constructor,objectStore,oldSettings,callback)=>{WI.Target.registerInitializationPromise((async()=>{for(let key of oldSettings){let existingSerializedBreakpoints=WI.Setting.migrateValue(key);if(existingSerializedBreakpoints){for(let existingSerializedBreakpoint of existingSerializedBreakpoints)
await objectStore.putObject(constructor.fromJSON(existingSerializedBreakpoint));}}
let serializedBreakpoints=await objectStore.getAll();this._restoringBreakpoints=true;for(let serializedBreakpoint of serializedBreakpoints){let breakpoint=constructor.fromJSON(serializedBreakpoint);const key=null;objectStore.associateObject(breakpoint,key,serializedBreakpoint);callback(breakpoint);}
this._restoringBreakpoints=false;})());};function loadLegacySpecialBreakpoint(shownSettingsKey,enabledSettingsKey,callback){if(!WI.Setting.migrateValue(shownSettingsKey))
return;return callback({disabled:!WI.Setting.migrateValue(enabledSettingsKey),});}
if(DOMDebuggerManager.supportsDOMBreakpoints()){loadBreakpoints(WI.DOMBreakpoint,WI.objectStores.domBreakpoints,["dom-breakpoints"],(breakpoint)=>{this.addDOMBreakpoint(breakpoint);});}
if(DOMDebuggerManager.supportsEventBreakpoints()||DOMDebuggerManager.supportsEventListenerBreakpoints()){loadBreakpoints(WI.EventBreakpoint,WI.objectStores.eventBreakpoints,["event-breakpoints"],(breakpoint)=>{this.addEventBreakpoint(breakpoint);});this._allAnimationFramesBreakpoint??=loadLegacySpecialBreakpoint("show-all-animation-frames-breakpoint","break-on-all-animation-frames",(options)=>new WI.EventBreakpoint(WI.EventBreakpoint.Type.AnimationFrame,options));this._allIntervalsBreakpoint??=loadLegacySpecialBreakpoint("show-all-inteverals-breakpoint","break-on-all-intervals",(options)=>new WI.EventBreakpoint(WI.EventBreakpoint.Type.Interval,options));this._allListenersBreakpoint??=loadLegacySpecialBreakpoint("show-all-listeners-breakpoint","break-on-all-listeners",(options)=>new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener,options));this._allTimeoutsBreakpoint??=loadLegacySpecialBreakpoint("show-all-timeouts-breakpoint","break-on-all-timeouts",(options)=>new WI.EventBreakpoint(WI.EventBreakpoint.Type.Timeout,options));}
if(DOMDebuggerManager.supportsURLBreakpoints()||DOMDebuggerManager.supportsXHRBreakpoints()){loadBreakpoints(WI.URLBreakpoint,WI.objectStores.urlBreakpoints,["xhr-breakpoints","url-breakpoints"],(breakpoint)=>{this.addURLBreakpoint(breakpoint);});this._allRequestsBreakpoint??=loadLegacySpecialBreakpoint("show-all-requests-breakpoint","break-on-all-requests",(options)=>new WI.URLBreakpoint(WI.URLBreakpoint.Type.Text,"",options));}} 
initializeTarget(target)
{if(target.hasDomain("DOMDebugger")){this._restoringBreakpoints=true;if(target===WI.assumingMainTarget()&&target.mainResource)
this._speculativelyResolveDOMBreakpointsForURL(target.mainResource.url);if(this._allAnimationFramesBreakpoint&&!this._allAnimationFramesBreakpoint.disabled)
this._setEventBreakpoint(this._allAnimationFramesBreakpoint,target);if(this._allIntervalsBreakpoint&&!this._allIntervalsBreakpoint.disabled)
this._setEventBreakpoint(this._allIntervalsBreakpoint,target);if(this._allListenersBreakpoint&&!this._allListenersBreakpoint.disabled)
this._setEventBreakpoint(this._allListenersBreakpoint,target);if(this._allTimeoutsBreakpoint&&!this._allTimeoutsBreakpoint.disabled)
this._setEventBreakpoint(this._allTimeoutsBreakpoint,target);if(this._allRequestsBreakpoint)
this._setURLBreakpoint(this._allRequestsBreakpoint,target);for(let breakpoint of this._listenerBreakpoints){if(!breakpoint.disabled)
this._setEventBreakpoint(breakpoint,target);}
for(let breakpoint of this._urlBreakpoints){if(!breakpoint.disabled)
this._setURLBreakpoint(breakpoint,target);}
this._restoringBreakpoints=false;}} 
static supportsDOMBreakpoints()
{return InspectorBackend.hasCommand("DOMDebugger.setDOMBreakpoint")&&InspectorBackend.hasCommand("DOMDebugger.removeDOMBreakpoint");}
static supportsEventBreakpoints()
{return InspectorBackend.hasCommand("DOMDebugger.setEventBreakpoint")&&InspectorBackend.hasCommand("DOMDebugger.removeEventBreakpoint");}
static supportsEventListenerBreakpoints()
{return InspectorBackend.hasCommand("DOMDebugger.setEventListenerBreakpoint")&&InspectorBackend.hasCommand("DOMDebugger.removeEventListenerBreakpoint");}
static supportsURLBreakpoints()
{return InspectorBackend.hasCommand("DOMDebugger.setURLBreakpoint")&&InspectorBackend.hasCommand("DOMDebugger.removeURLBreakpoint");}
static supportsXHRBreakpoints()
{return InspectorBackend.hasCommand("DOMDebugger.setXHRBreakpoint")&&InspectorBackend.hasCommand("DOMDebugger.removeXHRBreakpoint");}
static supportsAllListenersBreakpoint()
{return DOMDebuggerManager.supportsEventBreakpoints()&&InspectorBackend.Enum.DOMDebugger.EventBreakpointType.Interval&&InspectorBackend.Enum.DOMDebugger.EventBreakpointType.Timeout;} 
get supported()
{return InspectorBackend.hasDomain("DOMDebugger");}
get allAnimationFramesBreakpoint(){return this._allAnimationFramesBreakpoint;}
get allIntervalsBreakpoint(){return this._allIntervalsBreakpoint;}
get allListenersBreakpoint(){return this._allListenersBreakpoint;}
get allTimeoutsBreakpoint(){return this._allTimeoutsBreakpoint;}
get allRequestsBreakpoint(){return this._allRequestsBreakpoint;}
get domBreakpoints()
{let mainFrame=WI.networkManager.mainFrame;if(!mainFrame)
return[];let resolvedBreakpoints=[];let frames=[mainFrame];while(frames.length){let frame=frames.shift();let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(frame);if(domBreakpointNodeIdentifierMap)
resolvedBreakpoints.pushAll(domBreakpointNodeIdentifierMap.values());frames.pushAll(frame.childFrameCollection);}
return resolvedBreakpoints;}
get listenerBreakpoints(){return this._listenerBreakpoints;}
get urlBreakpoints(){return this._urlBreakpoints;}
domBreakpointsForNode(node)
{if(!node||!node.frame)
return[];let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(node.frame);if(!domBreakpointNodeIdentifierMap)
return[];let breakpoints=domBreakpointNodeIdentifierMap.get(node);return breakpoints?Array.from(breakpoints):[];}
domBreakpointsInSubtree(node)
{let breakpoints=[];if(node.children){let children=Array.from(node.children);while(children.length){let child=children.pop();if(child.children)
children.pushAll(child.children);breakpoints.pushAll(this.domBreakpointsForNode(child));}}
return breakpoints;}
addDOMBreakpoint(breakpoint)
{if(!breakpoint||!breakpoint.url)
return;this._domBreakpointURLMap.add(breakpoint.url,breakpoint);if(breakpoint.domNode){this._resolveDOMBreakpoint(breakpoint,breakpoint.domNode);if(!breakpoint.disabled){let target=WI.assumingMainTarget();if(target)
this._setDOMBreakpoint(breakpoint,target);}
this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,{breakpoint});WI.debuggerManager.addProbesForBreakpoint(breakpoint);}else
this._speculativelyResolveDOMBreakpoint(breakpoint);if(!this._restoringBreakpoints)
WI.objectStores.domBreakpoints.putObject(breakpoint);}
removeDOMBreakpoint(breakpoint)
{if(!breakpoint||!breakpoint.url)
return;breakpoint.disabled=true;breakpoint.clearActions();this._domBreakpointURLMap.delete(breakpoint.url);if(breakpoint.domNode){if(breakpoint.domNode.frame){let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(breakpoint.domNode.frame);domBreakpointNodeIdentifierMap.delete(breakpoint.domNode,breakpoint);if(!domBreakpointNodeIdentifierMap.size)
this._domBreakpointFrameIdentifierMap.delete(breakpoint.domNode.frame);}
this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,{breakpoint});breakpoint.domNode=null;}
if(!this._restoringBreakpoints)
WI.objectStores.domBreakpoints.deleteObject(breakpoint);}
removeDOMBreakpointsForNode(node)
{this.domBreakpointsForNode(node).forEach(this.removeDOMBreakpoint,this);}
listenerBreakpointForEventName(eventName)
{if(DOMDebuggerManager.supportsAllListenersBreakpoint()&&this._allListenersBreakpoint&&!this._allListenersBreakpoint.disabled)
return this._allListenersBreakpoint;return this._listenerBreakpoints.find((breakpoint)=>breakpoint.eventName===eventName)||null;}
addEventBreakpoint(breakpoint)
{if(!breakpoint)
return false;switch(breakpoint.type){case WI.EventBreakpoint.Type.AnimationFrame:this._allAnimationFramesBreakpoint=breakpoint;break;case WI.EventBreakpoint.Type.Interval:this._allIntervalsBreakpoint=breakpoint;break;case WI.EventBreakpoint.Type.Listener:if(breakpoint.eventName){if(this._listenerBreakpoints.find((existing)=>existing.eventName===breakpoint.eventName))
return false;this._listenerBreakpoints.push(breakpoint);}else{this._allListenersBreakpoint=breakpoint;}
break;case WI.EventBreakpoint.Type.Timeout:this._allTimeoutsBreakpoint=breakpoint;break;}
WI.debuggerManager.addProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.EventBreakpointAdded,{breakpoint});if(!breakpoint.disabled){for(let target of WI.targets)
this._setEventBreakpoint(breakpoint,target);}
if(!this._restoringBreakpoints)
WI.objectStores.eventBreakpoints.putObject(breakpoint);return true;}
removeEventBreakpoint(breakpoint)
{if(!breakpoint)
return;breakpoint.disabled=true;breakpoint.clearActions();switch(breakpoint.type){case WI.EventBreakpoint.Type.AnimationFrame:this._allAnimationFramesBreakpoint=null;break;case WI.EventBreakpoint.Type.Interval:this._allIntervalsBreakpoint=null;break;case WI.EventBreakpoint.Type.Listener:if(breakpoint.eventName){if(!this._listenerBreakpoints.includes(breakpoint))
return;this._listenerBreakpoints.remove(breakpoint);}else{this._allListenersBreakpoint=null;}
break;case WI.EventBreakpoint.Type.Timeout:this._allTimeoutsBreakpoint=null;break;}
if(!this._restoringBreakpoints)
WI.objectStores.eventBreakpoints.deleteObject(breakpoint);WI.debuggerManager.removeProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,{breakpoint});}
urlBreakpointForURL(url)
{return this._urlBreakpoints.find((breakpoint)=>breakpoint.url===url)||null;}
addURLBreakpoint(breakpoint)
{if(!breakpoint)
return false;if(breakpoint.url){if(this._urlBreakpoints.some((entry)=>entry.type===breakpoint.type&&entry.url===breakpoint.url))
return false;this._urlBreakpoints.push(breakpoint);}else{this._allRequestsBreakpoint=breakpoint;}
WI.debuggerManager.addProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.URLBreakpointAdded,{breakpoint});if(!breakpoint.disabled){for(let target of WI.targets)
this._setURLBreakpoint(breakpoint,target);}
if(!this._restoringBreakpoints)
WI.objectStores.urlBreakpoints.putObject(breakpoint);return true;}
removeURLBreakpoint(breakpoint)
{if(!breakpoint)
return;breakpoint.disabled=true;breakpoint.clearActions();if(breakpoint.url){if(!this._urlBreakpoints.includes(breakpoint))
return;this._urlBreakpoints.remove(breakpoint);}else{this._allRequestsBreakpoint=null;}
if(!this._restoringBreakpoints)
WI.objectStores.urlBreakpoints.deleteObject(breakpoint);WI.debuggerManager.removeProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DOMDebuggerManager.Event.URLBreakpointRemoved,{breakpoint});} 
_detachDOMBreakpointsForFrame(frame)
{let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(frame);if(domBreakpointNodeIdentifierMap){this._domBreakpointFrameIdentifierMap.delete(frame);this._clearingDOMBreakpointsForRemovedDOMNode=true;for(let breakpoint of domBreakpointNodeIdentifierMap.values())
breakpoint.domNode=null;this._clearingDOMBreakpointsForRemovedDOMNode=false;}
for(let childFrame of frame.childFrameCollection)
this._detachDOMBreakpointsForFrame(childFrame);}
_speculativelyResolveDOMBreakpointsForURL(url)
{let domBreakpoints=this._domBreakpointURLMap.get(url);if(!domBreakpoints)
return;for(let breakpoint of domBreakpoints)
this._speculativelyResolveDOMBreakpoint(breakpoint);}
_speculativelyResolveDOMBreakpoint(breakpoint)
{if(breakpoint.domNode)
return;WI.domManager.pushNodeByPathToFrontend(breakpoint.path,(nodeIdentifier)=>{if(!nodeIdentifier)
return;if(breakpoint.domNode){

return;}
this._restoringBreakpoints=true;this._resolveDOMBreakpoint(breakpoint,WI.domManager.nodeForId(nodeIdentifier));this._restoringBreakpoints=false;});}
_resolveDOMBreakpoint(breakpoint,node)
{if(!node.frame)
return;let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(node.frame);if(!domBreakpointNodeIdentifierMap){domBreakpointNodeIdentifierMap=new Multimap;this._domBreakpointFrameIdentifierMap.set(node.frame,domBreakpointNodeIdentifierMap);}
domBreakpointNodeIdentifierMap.add(node,breakpoint);breakpoint.domNode=node;}
_setDOMBreakpoint(breakpoint,target)
{if(!target.hasCommand("DOMDebugger.setDOMBreakpoint"))
return;if(!this._restoringBreakpoints&&!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;target.DOMDebuggerAgent.setDOMBreakpoint.invoke({nodeId:breakpoint.domNode.id,type:breakpoint.type,options:breakpoint.optionsToProtocol(),});}
_removeDOMBreakpoint(breakpoint,target)
{if(!target.hasCommand("DOMDebugger.removeDOMBreakpoint"))
return;target.DOMDebuggerAgent.removeDOMBreakpoint(breakpoint.domNode.id,breakpoint.type);}
_commandArgumentsForEventBreakpoint(breakpoint)
{let commandArguments={};switch(breakpoint){case this._allAnimationFramesBreakpoint:commandArguments.breakpointType=WI.EventBreakpoint.Type.AnimationFrame;if(!DOMDebuggerManager.supportsAllListenersBreakpoint())
commandArguments.eventName="requestAnimationFrame";break;case this._allIntervalsBreakpoint:if(DOMDebuggerManager.supportsAllListenersBreakpoint())
commandArguments.breakpointType=WI.EventBreakpoint.Type.Interval;else{commandArguments.breakpointType=WI.EventBreakpoint.Type.Timer;commandArguments.eventName="setInterval";}
break;case this._allListenersBreakpoint:if(!DOMDebuggerManager.supportsAllListenersBreakpoint())
return;commandArguments.breakpointType=WI.EventBreakpoint.Type.Listener;break;case this._allTimeoutsBreakpoint:if(DOMDebuggerManager.supportsAllListenersBreakpoint())
commandArguments.breakpointType=WI.EventBreakpoint.Type.Timeout;else{commandArguments.breakpointType=WI.EventBreakpoint.Type.Timer;commandArguments.eventName="setTimeout";}
break;default:commandArguments.breakpointType=breakpoint.type;commandArguments.eventName=breakpoint.eventName;break;}
return commandArguments;}
_setEventBreakpoint(breakpoint,target)
{if(breakpoint===this._allAnimationFramesBreakpoint&&target.type===WI.TargetType.Worker)
return;if(target.hasCommand("DOMDebugger.setEventListenerBreakpoint")){if(!this._restoringBreakpoints&&!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;target.DOMDebuggerAgent.setEventListenerBreakpoint(breakpoint.eventName);return;}
if(!target.hasCommand("DOMDebugger.setEventBreakpoint"))
return;let commandArguments=this._commandArgumentsForEventBreakpoint(breakpoint);if(!this._restoringBreakpoints&&!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;commandArguments.options=breakpoint.optionsToProtocol();target.DOMDebuggerAgent.setEventBreakpoint.invoke(commandArguments);}
_removeEventBreakpoint(breakpoint,target)
{if(breakpoint===this._allAnimationFramesBreakpoint&&target.type===WI.TargetType.Worker)
return;if(target.hasCommand("DOMDebugger.removeEventListenerBreakpoint")){target.DOMDebuggerAgent.removeEventListenerBreakpoint(breakpoint.eventName);return;}
if(!target.hasCommand("DOMDebugger.removeEventBreakpoint"))
return;let commandArguments=this._commandArgumentsForEventBreakpoint(breakpoint);target.DOMDebuggerAgent.removeEventBreakpoint.invoke(commandArguments);}
_setURLBreakpoint(breakpoint,target)
{if(target.hasCommand("DOMDebugger.setXHRBreakpoint")){if(!this._restoringBreakpoints&&!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;let isRegex=breakpoint.type===WI.URLBreakpoint.Type.RegularExpression;target.DOMDebuggerAgent.setXHRBreakpoint(breakpoint.url,isRegex);return;}
if(!target.hasCommand("DOMDebugger.setURLBreakpoint"))
return;if(!this._restoringBreakpoints&&!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;target.DOMDebuggerAgent.setURLBreakpoint.invoke({url:breakpoint.url,isRegex:breakpoint.type===WI.URLBreakpoint.Type.RegularExpression,options:breakpoint.optionsToProtocol(),});}
_removeURLBreakpoint(breakpoint,target)
{if(target.hasCommand("DOMDebugger.removeXHRBreakpoint")){target.DOMDebuggerAgent.removeXHRBreakpoint(breakpoint.url);return;}
if(!target.hasCommand("DOMDebugger.removeURLBreakpoint"))
return;target.DOMDebuggerAgent.removeURLBreakpoint.invoke({url:breakpoint.url,isRegex:breakpoint.type===WI.URLBreakpoint.Type.RegularExpression,});}
_handleDOMBreakpointDisabledStateChanged(event)
{let breakpoint=event.target;if(!this._restoringBreakpoints)
WI.objectStores.domBreakpoints.putObject(breakpoint);if(!breakpoint.domNode)
return;let target=WI.assumingMainTarget();if(target){if(breakpoint.disabled)
this._removeDOMBreakpoint(breakpoint,target);else
this._setDOMBreakpoint(breakpoint,target);}}
_handleDOMBreakpointEditablePropertyChanged(event)
{let breakpoint=event.target;if(!this._restoringBreakpoints)
WI.objectStores.domBreakpoints.putObject(breakpoint);if(!breakpoint.domNode)
return;if(breakpoint.disabled)
return;this._restoringBreakpoints=true;let target=WI.assumingMainTarget();if(target){this._removeDOMBreakpoint(breakpoint,target);this._setDOMBreakpoint(breakpoint,target);}
this._restoringBreakpoints=false;}
_handleDOMBreakpointActionsChanged(event)
{let breakpoint=event.target;this._handleDOMBreakpointEditablePropertyChanged(event);if(!breakpoint.domNode)
return;WI.debuggerManager.updateProbesForBreakpoint(breakpoint);}
_handleDOMBreakpointDOMNodeWillChange(event)
{if(this._clearingDOMBreakpointsForRemovedDOMNode)
return;let breakpoint=event.target;if(!breakpoint.domNode)
return;if(!breakpoint.disabled){let target=WI.assumingMainTarget();if(target)
this._removeDOMBreakpoint(breakpoint,target);}
WI.debuggerManager.removeProbesForBreakpoint(breakpoint);}
_handleDOMBreakpointDOMNodeDidChange(event)
{let breakpoint=event.target;if(!breakpoint.domNode)
return;if(!breakpoint.disabled){let target=WI.assumingMainTarget();if(target)
this._setDOMBreakpoint(breakpoint,target);}
WI.debuggerManager.addProbesForBreakpoint(breakpoint);}
_handleEventBreakpointDisabledStateChanged(event)
{let breakpoint=event.target;if(breakpoint.eventListener)
return;for(let target of WI.targets){if(breakpoint.disabled)
this._removeEventBreakpoint(breakpoint,target);else
this._setEventBreakpoint(breakpoint,target);}
if(!this._restoringBreakpoints)
WI.objectStores.eventBreakpoints.putObject(breakpoint);}
_handleEventBreakpointEditablePropertyChanged(event)
{let breakpoint=event.target;if(breakpoint.eventListener)
return;if(!this._restoringBreakpoints)
WI.objectStores.eventBreakpoints.putObject(breakpoint);if(breakpoint.disabled)
return;this._restoringBreakpoints=true;for(let target of WI.targets){this._removeEventBreakpoint(breakpoint,target);this._setEventBreakpoint(breakpoint,target);}
this._restoringBreakpoints=false;}
_handleEventBreakpointActionsChanged(event)
{let breakpoint=event.target;if(breakpoint.eventListener)
return;this._handleEventBreakpointEditablePropertyChanged(event);WI.debuggerManager.updateProbesForBreakpoint(breakpoint);}
_handleURLBreakpointDisabledStateChanged(event)
{let breakpoint=event.target;for(let target of WI.targets){if(breakpoint.disabled)
this._removeURLBreakpoint(breakpoint,target);else
this._setURLBreakpoint(breakpoint,target);}
if(!this._restoringBreakpoints)
WI.objectStores.urlBreakpoints.putObject(breakpoint);}
_handleURLBreakpointEditablePropertyChanged(event)
{let breakpoint=event.target;if(!this._restoringBreakpoints)
WI.objectStores.urlBreakpoints.putObject(breakpoint);if(breakpoint.disabled)
return;this._restoringBreakpoints=true;for(let target of WI.targets){this._removeURLBreakpoint(breakpoint,target)
this._setURLBreakpoint(breakpoint,target);}
this._restoringBreakpoints=false;}
_handleURLBreakpointActionsChanged(event)
{let breakpoint=event.target;this._handleURLBreakpointEditablePropertyChanged(event);WI.debuggerManager.updateProbesForBreakpoint(breakpoint);}
_childFrameWasRemoved(event)
{let frame=event.data.childFrame;this._detachDOMBreakpointsForFrame(frame);}
_mainFrameDidChange(event)
{this._speculativelyResolveDOMBreakpointsForURL(WI.networkManager.mainFrame.url);}
_mainResourceDidChange(event)
{let frame=event.target;if(frame.isMainFrame()){this._clearingDOMBreakpointsForRemovedDOMNode=true;for(let breakpoint of this._domBreakpointURLMap.values())
breakpoint.domNode=null;this._clearingDOMBreakpointsForRemovedDOMNode=false;this._domBreakpointFrameIdentifierMap.clear();}else
this._detachDOMBreakpointsForFrame(frame);this._speculativelyResolveDOMBreakpointsForURL(frame.url);}
_nodeInserted(event)
{let node=event.data.node;if(node.nodeType()!==Node.ELEMENT_NODE||!node.frame)
return;let url=node.frame.url;let breakpoints=this._domBreakpointURLMap.get(url);if(!breakpoints)
return;let resolvableBreakpoints=[];for(let breakpoint of breakpoints){if(!breakpoint.domNode)
resolvableBreakpoints.push(breakpoint);}
if(!resolvableBreakpoints.length)
return;
let stack=[node];while(stack.length){let child=stack.pop();let path=child.path();for(let i=resolvableBreakpoints.length-1;i>=0;--i){if(resolvableBreakpoints[i].path===path){this._restoringBreakpoints=true;this._resolveDOMBreakpoint(resolvableBreakpoints[i],child);this._restoringBreakpoints=false;resolvableBreakpoints.splice(i,1);}}
if(!resolvableBreakpoints.length)
break;if(child.children?.length)
stack.pushAll(child.children);}}
_nodeRemoved(event)
{let node=event.data.node;if(node.nodeType()!==Node.ELEMENT_NODE||!node.frame)
return;let domBreakpointNodeIdentifierMap=this._domBreakpointFrameIdentifierMap.get(node.frame);if(!domBreakpointNodeIdentifierMap)
return;for(let[breakpointOwner,breakpoints]of domBreakpointNodeIdentifierMap.sets()){if(breakpointOwner==node||node.isAncestor(breakpointOwner)){this._clearingDOMBreakpointsForRemovedDOMNode=true;for(let breakpoint of breakpoints)
breakpoint.domNode=null;this._clearingDOMBreakpointsForRemovedDOMNode=false;domBreakpointNodeIdentifierMap.delete(breakpointOwner);if(!domBreakpointNodeIdentifierMap.size){this._domBreakpointFrameIdentifierMap.delete(node.frame);break;}}}}};WI.DOMDebuggerManager.Event={DOMBreakpointAdded:"dom-debugger-manager-dom-breakpoint-added",DOMBreakpointRemoved:"dom-debugger-manager-dom-breakpoint-removed",EventBreakpointAdded:"dom-debugger-manager-event-breakpoint-added",EventBreakpointRemoved:"dom-debugger-manager-event-breakpoint-removed",URLBreakpointAdded:"dom-debugger-manager-url-breakpoint-added",URLBreakpointRemoved:"dom-debugger-manager-url-breakpoint-removed",};WI.DOMManager=class DOMManager extends WI.Object
{constructor()
{super();this._idToDOMNode={};this._document=null;this._documentPromise=null;this._attributeLoadNodeIds={};this._restoreSelectedNodeIsAllowed=true;this._loadNodeAttributesTimeout=0;this._inspectedNode=null;this._breakpointsForEventListeners=new Map;this._hasRequestedDocument=false;this._pendingDocumentRequestCallbacks=null;WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleEventBreakpointDisabledStateChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleEventBreakpointEditablePropertyChanged,this);WI.EventBreakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange,this._handleEventBreakpointActionsChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} 
initializeTarget(target)
{

if(target.hasDomain("DOM")){setTimeout(()=>{this.ensureDocument();});if(WI.isEngineeringBuild){if(DOMManager.supportsEditingUserAgentShadowTrees({target}))
target.DOMAgent.setAllowEditingUserAgentShadowTrees(WI.settings.engineeringAllowEditingUserAgentShadowTrees.value);}}}
transitionPageTarget()
{this._documentUpdated();} 
static buildHighlightConfig(mode)
{mode=mode||"all";let highlightConfig={showInfo:mode==="all"};if(mode==="all"||mode==="content")
highlightConfig.contentColor={r:111,g:168,b:220,a:0.66};if(mode==="all"||mode==="padding")
highlightConfig.paddingColor={r:147,g:196,b:125,a:0.66};if(mode==="all"||mode==="border")
highlightConfig.borderColor={r:255,g:229,b:153,a:0.66};if(mode==="all"||mode==="margin")
highlightConfig.marginColor={r:246,g:178,b:107,a:0.66};return highlightConfig;}
static wrapClientCallback(callback)
{if(!callback)
return null;return function(error,result){if(error)
console.error("Error during DOMAgent operation: "+error);callback(error?null:result);};}
static supportsDisablingEventListeners()
{return InspectorBackend.hasCommand("DOM.setEventListenerDisabled");}
static supportsEventListenerBreakpoints()
{return InspectorBackend.hasCommand("DOM.setBreakpointForEventListener")&&InspectorBackend.hasCommand("DOM.removeBreakpointForEventListener");}
static supportsEventListenerBreakpointConfiguration()
{return InspectorBackend.hasCommand("DOM.setBreakpointForEventListener","options");}
static supportsEditingUserAgentShadowTrees({frontendOnly,target}={})
{target=target||InspectorBackend;return WI.settings.engineeringAllowEditingUserAgentShadowTrees.value&&(frontendOnly||target.hasCommand("DOM.setAllowEditingUserAgentShadowTrees"));} 
get inspectedNode(){return this._inspectedNode;}
get eventListenerBreakpoints()
{return Array.from(this._breakpointsForEventListeners.values());}
requestDocument(callback)
{if(typeof callback!=="function")
return this._requestDocumentWithPromise();this._requestDocumentWithCallback(callback);}
ensureDocument()
{this.requestDocument(function(){});}
pushNodeToFrontend(objectId,callback)
{let target=WI.assumingMainTarget();this._dispatchWhenDocumentAvailable((callbackWrapper)=>{target.DOMAgent.requestNode(objectId,callbackWrapper);},callback);}
pushNodeByPathToFrontend(path,callback)
{let target=WI.assumingMainTarget();this._dispatchWhenDocumentAvailable((callbackWrapper)=>{target.DOMAgent.pushNodeByPathToFrontend(path,callbackWrapper);},callback);} 
willDestroyDOMNode(nodeId)
{let node=this._idToDOMNode[nodeId];node.markDestroyed();delete this._idToDOMNode[nodeId];this.dispatchEventToListeners(WI.DOMManager.Event.NodeRemoved,{node});}
didAddEventListener(nodeId)
{let node=this._idToDOMNode[nodeId];if(!node)
return;node.dispatchEventToListeners(WI.DOMNode.Event.EventListenersChanged);}
willRemoveEventListener(nodeId)
{let node=this._idToDOMNode[nodeId];if(!node)
return;node.dispatchEventToListeners(WI.DOMNode.Event.EventListenersChanged);}
didFireEvent(nodeId,eventName,timestamp,data)
{let node=this._idToDOMNode[nodeId];if(!node)
return;node.didFireEvent(eventName,timestamp,data);}
powerEfficientPlaybackStateChanged(nodeId,timestamp,isPowerEfficient)
{let node=this._idToDOMNode[nodeId];if(!node)
return;node.powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient);}
nodeLayoutContextTypeChanged(nodeId,layoutContextType)
{let domNode=this._idToDOMNode[nodeId];if(!domNode)
return;domNode.layoutContextType=layoutContextType;}
nodesWithLayoutContextType(layoutContextType)
{return Object.values(this._idToDOMNode).filter((node)=>node.layoutContextType===layoutContextType);} 
_dispatchWhenDocumentAvailable(func,callback)
{var callbackWrapper=DOMManager.wrapClientCallback(callback);function onDocumentAvailable()
{if(this._document)
func(callbackWrapper);else{if(callbackWrapper)
callbackWrapper("No document");}}
this.requestDocument(onDocumentAvailable.bind(this));}
_requestDocumentWithPromise()
{if(this._documentPromise)
return this._documentPromise.promise;this._documentPromise=new WI.WrappedPromise;if(this._document)
this._documentPromise.resolve(this._document);else{this._requestDocumentWithCallback((doc)=>{this._documentPromise.resolve(doc);});}
return this._documentPromise.promise;}
_requestDocumentWithCallback(callback)
{if(this._document){callback(this._document);return;}
if(this._pendingDocumentRequestCallbacks)
this._pendingDocumentRequestCallbacks.push(callback);else
this._pendingDocumentRequestCallbacks=[callback];if(this._hasRequestedDocument)
return;if(!WI.pageTarget)
return;if(!WI.pageTarget.hasDomain("DOM"))
return;this._hasRequestedDocument=true;WI.pageTarget.DOMAgent.getDocument((error,root)=>{if(!error)
this._setDocument(root);for(let callback of this._pendingDocumentRequestCallbacks)
callback(this._document);this._pendingDocumentRequestCallbacks=null;});}
_attributeModified(nodeId,name,value)
{var node=this._idToDOMNode[nodeId];if(!node)
return;node._setAttribute(name,value);this.dispatchEventToListeners(WI.DOMManager.Event.AttributeModified,{node,name});node.dispatchEventToListeners(WI.DOMNode.Event.AttributeModified,{name});}
_attributeRemoved(nodeId,name)
{var node=this._idToDOMNode[nodeId];if(!node)
return;node._removeAttribute(name);this.dispatchEventToListeners(WI.DOMManager.Event.AttributeRemoved,{node,name});node.dispatchEventToListeners(WI.DOMNode.Event.AttributeRemoved,{name});}
_inlineStyleInvalidated(nodeIds)
{for(var nodeId of nodeIds)
this._attributeLoadNodeIds[nodeId]=true;if(this._loadNodeAttributesTimeout)
return;this._loadNodeAttributesTimeout=setTimeout(this._loadNodeAttributes.bind(this),0);}
_loadNodeAttributes()
{function callback(nodeId,error,attributes)
{if(error){console.error("Error during DOMAgent operation: "+error);return;}
var node=this._idToDOMNode[nodeId];if(node){node._setAttributesPayload(attributes);this.dispatchEventToListeners(WI.DOMManager.Event.AttributeModified,{node,name:"style"});node.dispatchEventToListeners(WI.DOMNode.Event.AttributeModified,{name:"style"});}}
this._loadNodeAttributesTimeout=0;let target=WI.assumingMainTarget();for(var nodeId in this._attributeLoadNodeIds){if(!(nodeId in this._idToDOMNode))
continue;var nodeIdAsNumber=parseInt(nodeId);target.DOMAgent.getAttributes(nodeIdAsNumber,callback.bind(this,nodeIdAsNumber));}
this._attributeLoadNodeIds={};}
_characterDataModified(nodeId,newValue)
{var node=this._idToDOMNode[nodeId];node._nodeValue=newValue;this.dispatchEventToListeners(WI.DOMManager.Event.CharacterDataModified,{node});}
nodeForId(nodeId)
{return this._idToDOMNode[nodeId]||null;}
_documentUpdated()
{this._setDocument(null);}
_setDocument(payload)
{for(let node of Object.values(this._idToDOMNode))
node.markDestroyed();this._idToDOMNode={};for(let breakpoint of this._breakpointsForEventListeners.values())
WI.domDebuggerManager.dispatchEventToListeners(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,{breakpoint});this._breakpointsForEventListeners.clear();let newDocument=null;if(payload&&"nodeId"in payload)
newDocument=new WI.DOMNode(this,null,false,payload);if(this._document===newDocument)
return;this._document=newDocument;this._documentPromise=null;if(!this._document)
this._hasRequestedDocument=false;this.dispatchEventToListeners(WI.DOMManager.Event.DocumentUpdated,{document:this._document});}
_setDetachedRoot(payload)
{new WI.DOMNode(this,null,false,payload);}
_setChildNodes(parentId,payloads)
{if(!parentId&&payloads.length){this._setDetachedRoot(payloads[0]);return;}
var parent=this._idToDOMNode[parentId];if(parent.children){for(let node of parent.children)
this.dispatchEventToListeners(WI.DOMManager.Event.NodeRemoved,{node,parent});}
parent._setChildrenPayload(payloads);for(let node of parent.children)
this.dispatchEventToListeners(WI.DOMManager.Event.NodeInserted,{node,parent});}
_childNodeCountUpdated(nodeId,newValue)
{var node=this._idToDOMNode[nodeId];node.childNodeCount=newValue;this.dispatchEventToListeners(WI.DOMManager.Event.ChildNodeCountUpdated,node);}
_childNodeInserted(parentId,prevId,payload)
{var parent=this._idToDOMNode[parentId];var prev=this._idToDOMNode[prevId];var node=parent._insertChild(prev,payload);this._idToDOMNode[node.id]=node;this.dispatchEventToListeners(WI.DOMManager.Event.NodeInserted,{node,parent});}
_childNodeRemoved(parentId,nodeId)
{var parent=this._idToDOMNode[parentId];var node=this._idToDOMNode[nodeId];parent._removeChild(node);this._unbind(node);this.dispatchEventToListeners(WI.DOMManager.Event.NodeRemoved,{node,parent});}
_customElementStateChanged(elementId,newState)
{const node=this._idToDOMNode[elementId];node._customElementState=newState;this.dispatchEventToListeners(WI.DOMManager.Event.CustomElementStateChanged,{node});}
_pseudoElementAdded(parentId,pseudoElement)
{var parent=this._idToDOMNode[parentId];if(!parent)
return;var node=new WI.DOMNode(this,parent.ownerDocument,false,pseudoElement);node.parentNode=parent;this._idToDOMNode[node.id]=node;parent.pseudoElements().set(node.pseudoType(),node);this.dispatchEventToListeners(WI.DOMManager.Event.NodeInserted,{node,parent});}
_pseudoElementRemoved(parentId,pseudoElementId)
{var pseudoElement=this._idToDOMNode[pseudoElementId];if(!pseudoElement)
return;var parent=pseudoElement.parentNode;if(!parent)
return;parent._removeChild(pseudoElement);this._unbind(pseudoElement);this.dispatchEventToListeners(WI.DOMManager.Event.NodeRemoved,{node:pseudoElement,parent});}
_unbind(node)
{node.markDestroyed();delete this._idToDOMNode[node.id];for(let i=0;node.children&&i<node.children.length;++i)
this._unbind(node.children[i]);let templateContent=node.templateContent();if(templateContent)
this._unbind(templateContent);for(let pseudoElement of node.pseudoElements().values())
this._unbind(pseudoElement);}
get restoreSelectedNodeIsAllowed()
{return this._restoreSelectedNodeIsAllowed;}
inspectElement(nodeId,options={})
{var node=this._idToDOMNode[nodeId];if(!node||!node.ownerDocument)
return;let initiatorHint=options.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Inspect;this.dispatchEventToListeners(WI.DOMManager.Event.DOMNodeWasInspected,{node,initiatorHint});this._inspectModeEnabled=false;this.dispatchEventToListeners(WI.DOMManager.Event.InspectModeStateChanged);}
inspectNodeObject(remoteObject)
{this._restoreSelectedNodeIsAllowed=false;function nodeAvailable(nodeId)
{remoteObject.release();if(!nodeId)
return;this.inspectElement(nodeId);let domNode=this.nodeForId(nodeId);WI.RemoteObject.resolveNode(domNode,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{const specialLogStyles=true;const shouldRevealConsole=false;WI.consoleLogViewController.appendImmediateExecutionWithResult(WI.UIString("Selected Element"),remoteObject,specialLogStyles,shouldRevealConsole);});}
remoteObject.pushNodeToFrontend(nodeAvailable.bind(this));}
highlightDOMNodeList(nodes,mode)
{let target=WI.assumingMainTarget();if(!target.hasCommand("DOM.highlightNodeList"))
return;if(this._hideDOMNodeHighlightTimeout){clearTimeout(this._hideDOMNodeHighlightTimeout);this._hideDOMNodeHighlightTimeout=undefined;}
let nodeIds=[];for(let node of nodes){if(node.destroyed)
continue;nodeIds.push(node.id);}
target.DOMAgent.highlightNodeList(nodeIds,DOMManager.buildHighlightConfig(mode));}
highlightSelector(selectorText,frameId,mode)
{if(this._hideDOMNodeHighlightTimeout){clearTimeout(this._hideDOMNodeHighlightTimeout);this._hideDOMNodeHighlightTimeout=undefined;}
let target=WI.assumingMainTarget();target.DOMAgent.highlightSelector(DOMManager.buildHighlightConfig(mode),selectorText,frameId);}
highlightRect(rect,usePageCoordinates)
{let target=WI.assumingMainTarget();target.DOMAgent.highlightRect.invoke({x:rect.x,y:rect.y,width:rect.width,height:rect.height,color:{r:111,g:168,b:220,a:0.66},outlineColor:{r:255,g:229,b:153,a:0.66},usePageCoordinates});}
hideDOMNodeHighlight()
{for(let target of WI.targets){if(target.hasCommand("DOM.hideHighlight"))
target.DOMAgent.hideHighlight();}}
highlightDOMNodeForTwoSeconds(nodeId)
{let node=this._idToDOMNode[nodeId];if(!node)
return;node.highlight();this._hideDOMNodeHighlightTimeout=setTimeout(this.hideDOMNodeHighlight.bind(this),2000);}
get inspectModeEnabled()
{return this._inspectModeEnabled;}
set inspectModeEnabled(enabled)
{if(enabled===this._inspectModeEnabled)
return;let target=WI.assumingMainTarget();let commandArguments={enabled,highlightConfig:DOMManager.buildHighlightConfig(),showRulers:WI.settings.showRulersDuringElementSelection.value,};target.DOMAgent.setInspectModeEnabled.invoke(commandArguments,(error)=>{if(error){WI.reportInternalError(error);return;}
this._inspectModeEnabled=enabled;this.dispatchEventToListeners(WI.DOMManager.Event.InspectModeStateChanged);});}
setInspectedNode(node)
{if(node===this._inspectedNode)
return;if(node.destroyed)
return;let callback=(error)=>{if(error)
return;let lastInspectedNode=this._inspectedNode;this._inspectedNode=node;this.dispatchEventToListeners(WI.DOMManager.Event.InspectedNodeChanged,{lastInspectedNode});};let target=WI.assumingMainTarget();if(!target.hasCommand("DOM.setInspectedNode")){if(target.hasCommand("Console.addInspectedNode"))
target.ConsoleAgent.addInspectedNode(node.id,callback);return;}
target.DOMAgent.setInspectedNode(node.id,callback);}
getSupportedEventNames(callback)
{let target=WI.assumingMainTarget();if(!target.hasCommand("DOM.getSupportedEventNames"))
return Promise.resolve(new Set);if(!this._getSupportedEventNamesPromise){this._getSupportedEventNamesPromise=target.DOMAgent.getSupportedEventNames().then(({eventNames})=>new Set(eventNames));}
return this._getSupportedEventNamesPromise;}
setEventListenerDisabled(eventListener,disabled)
{let target=WI.assumingMainTarget();target.DOMAgent.setEventListenerDisabled(eventListener.eventListenerId,disabled);}
setBreakpointForEventListener(eventListener)
{let breakpoint=this._breakpointsForEventListeners.get(eventListener.eventListenerId);if(breakpoint){breakpoint.disabled=false;return;}
breakpoint=new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener,{eventName:eventListener.type,eventListener});this._breakpointsForEventListeners.set(eventListener.eventListenerId,breakpoint);for(let target of WI.targets){if(target.hasDomain("DOM"))
this._setEventBreakpoint(breakpoint,target);}
WI.debuggerManager.addProbesForBreakpoint(breakpoint);WI.domDebuggerManager.dispatchEventToListeners(WI.DOMDebuggerManager.Event.EventBreakpointAdded,{breakpoint});}
removeBreakpointForEventListener(eventListener)
{let breakpoint=this._breakpointsForEventListeners.take(eventListener.eventListenerId);if(!breakpoint)
return;breakpoint.disabled=true;breakpoint.clearActions();WI.debuggerManager.removeProbesForBreakpoint(breakpoint);WI.domDebuggerManager.dispatchEventToListeners(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,{breakpoint});}
removeEventListenerBreakpointsForNode(domNode)
{for(let breakpoint of Array.from(this._breakpointsForEventListeners.values())){let eventListener=breakpoint.eventListener;if(eventListener.nodeId===domNode.id)
this.removeBreakpointForEventListener(eventListener);}}
breakpointForEventListenerId(eventListenerId)
{return this._breakpointsForEventListeners.get(eventListenerId)||null;} 
_setEventBreakpoint(breakpoint,target)
{let eventListener=breakpoint.eventListener;if(!WI.debuggerManager.breakpointsDisabledTemporarily)
WI.debuggerManager.breakpointsEnabled=true;target.DOMAgent.setBreakpointForEventListener.invoke({eventListenerId:eventListener.eventListenerId,options:breakpoint.optionsToProtocol(),});}
_removeEventBreakpoint(breakpoint,target)
{let eventListener=breakpoint.eventListener;target.DOMAgent.removeBreakpointForEventListener(eventListener.eventListenerId);}
_handleEventBreakpointDisabledStateChanged(event)
{let breakpoint=event.target;if(!breakpoint.eventListener)
return;for(let target of WI.targets){if(!target.hasDomain("DOM"))
continue;if(breakpoint.disabled)
this._removeEventBreakpoint(breakpoint,target);else
this._setEventBreakpoint(breakpoint,target);}}
_handleEventBreakpointEditablePropertyChanged(event)
{let breakpoint=event.target;if(!breakpoint.eventListener)
return;if(breakpoint.disabled)
return;for(let target of WI.targets){this._removeEventBreakpoint(breakpoint,target);this._setEventBreakpoint(breakpoint,target);}}
_handleEventBreakpointActionsChanged(event)
{let breakpoint=event.target;if(!breakpoint.eventListener)
return;this._handleEventBreakpointEditablePropertyChanged(event);WI.debuggerManager.updateProbesForBreakpoint(breakpoint);}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._restoreSelectedNodeIsAllowed=true;this.ensureDocument();}};WI.DOMManager.Event={AttributeModified:"dom-manager-attribute-modified",AttributeRemoved:"dom-manager-attribute-removed",CharacterDataModified:"dom-manager-character-data-modified",NodeInserted:"dom-manager-node-inserted",NodeRemoved:"dom-manager-node-removed",CustomElementStateChanged:"dom-manager-custom-element-state-changed",DocumentUpdated:"dom-manager-document-updated",ChildNodeCountUpdated:"dom-manager-child-node-count-updated",DOMNodeWasInspected:"dom-manager-dom-node-was-inspected",InspectModeStateChanged:"dom-manager-inspect-mode-state-changed",InspectedNodeChanged:"dom-manager-inspected-node-changed",};WI.DOMStorageManager=class DOMStorageManager extends WI.Object
{constructor()
{super();this._enabled=false;this._reset();} 
get domains(){return["DOMStorage"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("DOMStorage"))
target.DOMStorageAgent.enable();} 
get domStorageObjects(){return this._domStorageObjects;}
get cookieStorageObjects()
{var cookieStorageObjects=[];for(var host in this._cookieStorageObjects)
cookieStorageObjects.push(this._cookieStorageObjects[host]);return cookieStorageObjects;}
enable()
{this._enabled=true;this._reset();for(let target of WI.targets)
this.initializeTarget(target);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.SecurityOriginDidChange,this._securityOriginDidChange,this);}
disable()
{this._enabled=false;for(let target of WI.targets){if(target.hasDomain("DOMStorage"))
target.DOMStorageAgent.disable();}
WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.SecurityOriginDidChange,this._securityOriginDidChange,this);this._reset();} 
itemsCleared(storageId)
{let domStorage=this._domStorageForIdentifier(storageId);if(domStorage)
domStorage.itemsCleared(storageId);}
itemRemoved(storageId,key)
{let domStorage=this._domStorageForIdentifier(storageId);if(domStorage)
domStorage.itemRemoved(key);}
itemAdded(storageId,key,value)
{let domStorage=this._domStorageForIdentifier(storageId);if(domStorage)
domStorage.itemAdded(key,value);}
itemUpdated(storageId,key,oldValue,newValue)
{let domStorage=this._domStorageForIdentifier(storageId);if(domStorage)
domStorage.itemUpdated(key,oldValue,newValue);} 
inspectDOMStorage(id)
{var domStorage=this._domStorageForIdentifier(id);if(!domStorage)
return;this.dispatchEventToListeners(WI.DOMStorageManager.Event.DOMStorageObjectWasInspected,{domStorage});} 
_reset()
{this._domStorageObjects=[];this._cookieStorageObjects={};this.dispatchEventToListeners(DOMStorageManager.Event.Cleared);let mainFrame=WI.networkManager.mainFrame;if(mainFrame){this._addDOMStorageIfNeeded(mainFrame);this._addCookieStorageIfNeeded(mainFrame);}}
_domStorageForIdentifier(id)
{for(var storageObject of this._domStorageObjects){if(Object.shallowEqual(storageObject.id,id))
return storageObject;}
return null;}
_addDOMStorageIfNeeded(frame)
{if(!this._enabled)
return;if(!InspectorBackend.hasDomain("DOMStorage"))
return;if(!frame.securityOrigin||frame.securityOrigin==="://")
return;let addDOMStorage=(isLocalStorage)=>{let identifier={securityOrigin:frame.securityOrigin,isLocalStorage};if(this._domStorageForIdentifier(identifier))
return;let domStorage=new WI.DOMStorageObject(identifier,frame.mainResource.urlComponents.host,identifier.isLocalStorage);this._domStorageObjects.push(domStorage);this.dispatchEventToListeners(DOMStorageManager.Event.DOMStorageObjectWasAdded,{domStorage});};addDOMStorage(true);addDOMStorage(false);}
_addCookieStorageIfNeeded(frame)
{if(!this._enabled)
return;if(!InspectorBackend.hasCommand("Page.getCookies"))
return;let host=parseURL(frame.url).host;if(!host)
return;if(this._cookieStorageObjects[host])
return;this._cookieStorageObjects[host]=new WI.CookieStorageObject(host);this.dispatchEventToListeners(WI.DOMStorageManager.Event.CookieStorageObjectWasAdded,{cookieStorage:this._cookieStorageObjects[host]});}
_mainResourceDidChange(event)
{if(event.target.isMainFrame()){this._reset();return;}
this._addCookieStorageIfNeeded(event.target);}
_securityOriginDidChange(event)
{this._addDOMStorageIfNeeded(event.target);}};WI.DOMStorageManager.Event={CookieStorageObjectWasAdded:"dom-storage-manager-cookie-storage-object-was-added",DOMStorageObjectWasAdded:"dom-storage-manager-dom-storage-object-was-added",DOMStorageObjectWasInspected:"dom-storage-manager-dom-storage-object-was-inspected",Cleared:"dom-storage-manager-cleared",};WI.DatabaseManager=class DatabaseManager extends WI.Object
{constructor()
{super();this._enabled=false;this._reset();} 
get domains(){return["Database"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Database"))
target.DatabaseAgent.enable();} 
get databases(){return this._databaseObjects;}
enable()
{this._enabled=true;this._reset();for(let target of WI.targets)
this.initializeTarget(target);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);}
disable()
{this._enabled=false;for(let target of WI.targets){if(target.hasDomain("Database"))
target.DatabaseAgent.disable();}
WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._reset();} 
databaseWasAdded(id,host,name,version)
{var database=new WI.DatabaseObject(id,host,name,version);this._databaseObjects.push(database);this.dispatchEventToListeners(WI.DatabaseManager.Event.DatabaseWasAdded,{database});} 
inspectDatabase(id)
{var database=this._databaseForIdentifier(id);if(!database)
return;this.dispatchEventToListeners(WI.DatabaseManager.Event.DatabaseWasInspected,{database});} 
_reset()
{this._databaseObjects=[];this.dispatchEventToListeners(WI.DatabaseManager.Event.Cleared);}
_mainResourceDidChange(event)
{if(event.target.isMainFrame())
this._reset();}
_databaseForIdentifier(id)
{for(var i=0;i<this._databaseObjects.length;++i){if(this._databaseObjects[i].id===id)
return this._databaseObjects[i];}
return null;}};WI.DatabaseManager.Event={DatabaseWasAdded:"database-manager-database-was-added",DatabaseWasInspected:"database-manager-database-was-inspected",Cleared:"database-manager-cleared",};WI.DebuggerManager=class DebuggerManager extends WI.Object
{constructor()
{super();WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._breakpointDisabledStateDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange,this._breakpointEditablePropertyDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange,this._breakpointEditablePropertyDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._breakpointEditablePropertyDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange,this._handleBreakpointActionsDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,this._breakpointDisplayLocationDidChange,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._targetRemoved,this);if(WI.isEngineeringBuild){WI.settings.engineeringShowInternalScripts.addEventListener(WI.Setting.Event.Changed,this._handleEngineeringShowInternalScriptsSettingChanged,this);WI.settings.engineeringPauseForInternalScripts.addEventListener(WI.Setting.Event.Changed,this._handleEngineeringPauseForInternalScriptsSettingChanged,this);}
WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._breakpointsEnabledSetting=new WI.Setting("breakpoints-enabled",true);this._asyncStackTraceDepthSetting=new WI.Setting("async-stack-trace-depth",200);this._debuggerStatementsBreakpointSetting=new WI.Setting("debugger-statements-breakpoint",{});this._debuggerStatementsBreakpoint=null;this._allExceptionsBreakpointSetting=new WI.Setting("all-exceptions-breakpoint",{disabled:true});this._allExceptionsBreakpoint=null;this._uncaughtExceptionsBreakpointSetting=new WI.Setting("uncaught-exceptions-breakpoint",{disabled:true});this._uncaughtExceptionsBreakpoint=null;this._assertionFailuresBreakpointSetting=new WI.Setting("assertion-failures-breakpoint",null);if(WI.Setting.isFirstLaunch)
this._assertionFailuresBreakpointSetting.value={disabled:true};this._assertionFailuresBreakpoint=null;this._allMicrotasksBreakpointSetting=new WI.Setting("all-microtasks-breakpoint",null);this._allMicrotasksBreakpoint=null;this._breakpoints=[];this._breakpointContentIdentifierMap=new Multimap;this._breakpointScriptIdentifierMap=new Multimap;this._breakpointIdMap=new Map;this._nextBreakpointActionIdentifier=1;this._blackboxedURLsSetting=new WI.Setting("debugger-blackboxed-urls",[]);this._blackboxedPatternsSetting=new WI.Setting("debugger-blackboxed-patterns",[]);this._blackboxedPatternDataMap=new Map;this._activeCallFrame=null;this._internalWebKitScripts=[];this._targetDebuggerDataMap=new Map;this._knownProbeIdentifiersForBreakpoint=new Map;this._probesByIdentifier=new Map;this._probeSetsByBreakpoint=new Map;
this._temporarilyDisabledBreakpointsRestoreSetting=new WI.Setting("temporarily-disabled-breakpoints-restore",null);if(this._temporarilyDisabledBreakpointsRestoreSetting.value!==null){this._breakpointsEnabledSetting.value=this._temporarilyDisabledBreakpointsRestoreSetting.value;this._temporarilyDisabledBreakpointsRestoreSetting.value=null;}
this._temporarilyDisableBreakpointsRequestCount=0;this._ignoreBreakpointDisplayLocationDidChangeEvent=false;WI.Target.registerInitializationPromise((async()=>{let existingSerializedBreakpoints=WI.Setting.migrateValue("breakpoints");if(existingSerializedBreakpoints){for(let existingSerializedBreakpoint of existingSerializedBreakpoints)
await WI.objectStores.breakpoints.putObject(WI.JavaScriptBreakpoint.fromJSON(existingSerializedBreakpoint));}
let serializedBreakpoints=await WI.objectStores.breakpoints.getAll();this._restoringBreakpoints=true;for(let serializedBreakpoint of serializedBreakpoints){let breakpoint=WI.JavaScriptBreakpoint.fromJSON(serializedBreakpoint);const key=null;WI.objectStores.breakpoints.associateObject(breakpoint,key,serializedBreakpoint);this.addBreakpoint(breakpoint);}
this._restoringBreakpoints=false;})());WI.Target.registerInitializationPromise((async()=>{await new Promise((resolve,reject)=>queueMicrotask(resolve));let loadSpecialBreakpoint=(setting,enabledSettingsKey,shownSettingsKey)=>{let serializedBreakpoint=setting.value;if(!serializedBreakpoint&&(!shownSettingsKey||WI.Setting.migrateValue(shownSettingsKey))){serializedBreakpoint=setting.value={};setting.save();}
if(WI.Setting.migrateValue(enabledSettingsKey)){if(!serializedBreakpoint)
serializedBreakpoint=setting.value={};serializedBreakpoint.disabled=false;setting.save();}
if(!serializedBreakpoint)
return null;return this._createSpecialBreakpoint(serializedBreakpoint);};this._restoringBreakpoints=true;if(WI.JavaScriptBreakpoint.supportsDebuggerStatements()){this._debuggerStatementsBreakpoint=loadSpecialBreakpoint(this._debuggerStatementsBreakpointSetting,"break-on-debugger-statements");if(this._debuggerStatementsBreakpoint)
this.addBreakpoint(this._debuggerStatementsBreakpoint);}
this._allExceptionsBreakpoint=loadSpecialBreakpoint(this._allExceptionsBreakpointSetting,"break-on-all-exceptions");if(this._allExceptionsBreakpoint)
this.addBreakpoint(this._allExceptionsBreakpoint);this._uncaughtExceptionsBreakpoint=loadSpecialBreakpoint(this._uncaughtExceptionsBreakpointSetting,"break-on-uncaught-exceptions");if(this._uncaughtExceptionsBreakpoint)
this.addBreakpoint(this._uncaughtExceptionsBreakpoint);this._assertionFailuresBreakpoint=loadSpecialBreakpoint(this._assertionFailuresBreakpointSetting,"break-on-assertion-failures","show-assertion-failures-breakpoint");if(this._assertionFailuresBreakpoint)
this.addBreakpoint(this._assertionFailuresBreakpoint);if(WI.JavaScriptBreakpoint.supportsMicrotasks()){this._allMicrotasksBreakpoint=loadSpecialBreakpoint(this._allMicrotasksBreakpointSetting,"break-on-all-microtasks","show-all-microtasks-breakpoint");if(this._allMicrotasksBreakpoint)
this.addBreakpoint(this._allMicrotasksBreakpoint);}
this._restoringBreakpoints=false;})());} 
initializeTarget(target)
{let targetData=this.dataForTarget(target);target.DebuggerAgent.enable();target.DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value);if(this._debuggerStatementsBreakpoint)
this._updateSpecialBreakpoint(this._debuggerStatementsBreakpoint,target);this._setPauseOnExceptions(target);if(this._assertionFailuresBreakpoint)
this._updateSpecialBreakpoint(this._assertionFailuresBreakpoint,target);if(this._allMicrotasksBreakpoint)
this._updateSpecialBreakpoint(this._allMicrotasksBreakpoint,target);target.DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value);if(target.hasCommand("Debugger.setShouldBlackboxURL")){const shouldBlackbox=true;{const caseSensitive=true;for(let url of this._blackboxedURLsSetting.value)
target.DebuggerAgent.setShouldBlackboxURL(url,shouldBlackbox,caseSensitive);}
{const isRegex=true;for(let data of this._blackboxedPatternsSetting.value){this._blackboxedPatternDataMap.set(new RegExp(data.url,!data.caseSensitive?"i":""),data);target.DebuggerAgent.setShouldBlackboxURL(data.url,shouldBlackbox,data.caseSensitive,isRegex);}}}
if(WI.isEngineeringBuild){if(target.hasCommand("Debugger.setPauseForInternalScripts"))
target.DebuggerAgent.setPauseForInternalScripts(WI.settings.engineeringPauseForInternalScripts.value);}
if(this.paused)
targetData.pauseIfNeeded();this._restoringBreakpoints=true;for(let breakpoint of this._breakpoints){if(breakpoint.disabled)
continue;if(!breakpoint.contentIdentifier)
continue;this._setBreakpoint(breakpoint,target);}
this._restoringBreakpoints=false;} 
static supportsBlackboxingScripts()
{return InspectorBackend.hasCommand("Debugger.setShouldBlackboxURL");}
static pauseReasonFromPayload(payload)
{switch(payload){case InspectorBackend.Enum.Debugger.PausedReason.AnimationFrame:return WI.DebuggerManager.PauseReason.AnimationFrame;case InspectorBackend.Enum.Debugger.PausedReason.Assert:return WI.DebuggerManager.PauseReason.Assertion;case InspectorBackend.Enum.Debugger.PausedReason.BlackboxedScript:return WI.DebuggerManager.PauseReason.BlackboxedScript;case InspectorBackend.Enum.Debugger.PausedReason.Breakpoint:return WI.DebuggerManager.PauseReason.Breakpoint;case InspectorBackend.Enum.Debugger.PausedReason.CSPViolation:return WI.DebuggerManager.PauseReason.CSPViolation;case InspectorBackend.Enum.Debugger.PausedReason.DOM:return WI.DebuggerManager.PauseReason.DOM;case InspectorBackend.Enum.Debugger.PausedReason.DebuggerStatement:return WI.DebuggerManager.PauseReason.DebuggerStatement;case InspectorBackend.Enum.Debugger.PausedReason.EventListener:return WI.DebuggerManager.PauseReason.EventListener;case InspectorBackend.Enum.Debugger.PausedReason.Exception:return WI.DebuggerManager.PauseReason.Exception;case InspectorBackend.Enum.Debugger.PausedReason.Fetch:return WI.DebuggerManager.PauseReason.Fetch;case InspectorBackend.Enum.Debugger.PausedReason.Interval:return WI.DebuggerManager.PauseReason.Interval;case InspectorBackend.Enum.Debugger.PausedReason.Listener:return WI.DebuggerManager.PauseReason.Listener;case InspectorBackend.Enum.Debugger.PausedReason.Microtask:return WI.DebuggerManager.PauseReason.Microtask;case InspectorBackend.Enum.Debugger.PausedReason.PauseOnNextStatement:return WI.DebuggerManager.PauseReason.PauseOnNextStatement;case InspectorBackend.Enum.Debugger.PausedReason.Timeout:return WI.DebuggerManager.PauseReason.Timeout;case InspectorBackend.Enum.Debugger.PausedReason.Timer:return WI.DebuggerManager.PauseReason.Timer;case InspectorBackend.Enum.Debugger.PausedReason.XHR:return WI.DebuggerManager.PauseReason.XHR;default:return WI.DebuggerManager.PauseReason.Other;}} 
get paused()
{for(let[target,targetData]of this._targetDebuggerDataMap){if(targetData.paused)
return true;}
return false;}
get activeCallFrame()
{return this._activeCallFrame;}
set activeCallFrame(callFrame)
{if(callFrame===this._activeCallFrame)
return;this._activeCallFrame=callFrame||null;this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);}
dataForTarget(target)
{let targetData=this._targetDebuggerDataMap.get(target);if(targetData)
return targetData;targetData=new WI.DebuggerData(target);this._targetDebuggerDataMap.set(target,targetData);return targetData;}
get debuggerStatementsBreakpoint(){return this._debuggerStatementsBreakpoint;}
get allExceptionsBreakpoint(){return this._allExceptionsBreakpoint;}
get uncaughtExceptionsBreakpoint(){return this._uncaughtExceptionsBreakpoint;}
get assertionFailuresBreakpoint(){return this._assertionFailuresBreakpoint;}
get allMicrotasksBreakpoint(){return this._allMicrotasksBreakpoint;}
get breakpoints(){return this._breakpoints;}
createAssertionFailuresBreakpoint(options={})
{this._assertionFailuresBreakpoint=this._createSpecialBreakpoint(options);this.addBreakpoint(this._assertionFailuresBreakpoint);}
createAllMicrotasksBreakpoint(options={})
{this._allMicrotasksBreakpoint=this._createSpecialBreakpoint(options);this.addBreakpoint(this._allMicrotasksBreakpoint);}
breakpointForIdentifier(id)
{return this._breakpointIdMap.get(id)||null;}
breakpointsForSourceCode(sourceCode)
{if(sourceCode instanceof WI.SourceMapResource)
return Array.from(this.breakpointsForSourceCode(sourceCode.sourceMap.originalSourceCode)).filter((breakpoint)=>breakpoint.sourceCodeLocation.displaySourceCode===sourceCode);let contentIdentifierBreakpoints=this._breakpointContentIdentifierMap.get(sourceCode.contentIdentifier);if(contentIdentifierBreakpoints){this._associateBreakpointsWithSourceCode(contentIdentifierBreakpoints,sourceCode);return contentIdentifierBreakpoints;}
if(sourceCode instanceof WI.Script){let scriptIdentifierBreakpoints=this._breakpointScriptIdentifierMap.get(sourceCode.id);if(scriptIdentifierBreakpoints){this._associateBreakpointsWithSourceCode(scriptIdentifierBreakpoints,sourceCode);return scriptIdentifierBreakpoints;}}
return[];}
breakpointForSourceCodeLocation(sourceCodeLocation)
{for(let breakpoint of this.breakpointsForSourceCode(sourceCodeLocation.sourceCode)){if(breakpoint.sourceCodeLocation.isEqual(sourceCodeLocation))
return breakpoint;}
return null;}
get breakpointsEnabled()
{return this._breakpointsEnabledSetting.value;}
set breakpointsEnabled(enabled)
{if(this._breakpointsEnabledSetting.value===enabled)
return;if(enabled&&this.breakpointsDisabledTemporarily)
return;this._breakpointsEnabledSetting.value=enabled;for(let target of WI.targets){target.DebuggerAgent.setBreakpointsActive(enabled);this._setPauseOnExceptions(target);}
this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointsEnabledDidChange);}
get breakpointsDisabledTemporarily()
{return this._temporarilyDisabledBreakpointsRestoreSetting.value!==null;}
scriptForIdentifier(id,target)
{return this.dataForTarget(target).scriptForIdentifier(id);}
scriptsForURL(url,target)
{return this.dataForTarget(target).scriptsForURL(url);}
get searchableScripts()
{return this.knownNonResourceScripts.filter((script)=>!!script.contentIdentifier);}
get knownNonResourceScripts()
{let knownScripts=[];for(let targetData of this._targetDebuggerDataMap.values()){for(let script of targetData.scripts){if(script.resource)
continue;if(!WI.settings.debugShowConsoleEvaluations.value&&isWebInspectorConsoleEvaluationScript(script.sourceURL))
continue;if(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(script.sourceURL))
continue;knownScripts.push(script);}}
return knownScripts;}
blackboxDataForSourceCode(sourceCode)
{for(let regex of this._blackboxedPatternDataMap.keys()){if(regex.test(sourceCode.contentIdentifier))
return{type:DebuggerManager.BlackboxType.Pattern,regex};}
if(this._blackboxedURLsSetting.value.includes(sourceCode.contentIdentifier))
return{type:DebuggerManager.BlackboxType.URL};return null;}
get blackboxPatterns()
{return Array.from(this._blackboxedPatternDataMap.keys());}
setShouldBlackboxScript(sourceCode,shouldBlackbox)
{this._blackboxedURLsSetting.value.toggleIncludes(sourceCode.contentIdentifier,shouldBlackbox);this._blackboxedURLsSetting.save();const caseSensitive=true;for(let target of WI.targets){if(target.hasCommand("Debugger.setShouldBlackboxURL"))
target.DebuggerAgent.setShouldBlackboxURL(sourceCode.contentIdentifier,!!shouldBlackbox,caseSensitive);}
this.dispatchEventToListeners(DebuggerManager.Event.BlackboxChanged);}
setShouldBlackboxPattern(regex,shouldBlackbox)
{if(shouldBlackbox){let data={url:regex.source,caseSensitive:!regex.ignoreCase,};this._blackboxedPatternDataMap.set(regex,data);this._blackboxedPatternsSetting.value.push(data);}else{this._blackboxedPatternsSetting.value.remove(this._blackboxedPatternDataMap.take(regex));}
this._blackboxedPatternsSetting.save();const isRegex=true;for(let target of WI.targets){if(target.hasCommand("Debugger.setShouldBlackboxURL"))
target.DebuggerAgent.setShouldBlackboxURL(regex.source,!!shouldBlackbox,!regex.ignoreCase,isRegex);}
this.dispatchEventToListeners(DebuggerManager.Event.BlackboxChanged);}
get asyncStackTraceDepth()
{return this._asyncStackTraceDepthSetting.value;}
set asyncStackTraceDepth(x)
{if(this._asyncStackTraceDepthSetting.value===x)
return;this._asyncStackTraceDepthSetting.value=x;for(let target of WI.targets)
target.DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value);}
get probeSets()
{return[...this._probeSetsByBreakpoint.values()];}
probeForIdentifier(identifier)
{return this._probesByIdentifier.get(identifier);}
pause()
{if(this.paused)
return Promise.resolve();this.dispatchEventToListeners(WI.DebuggerManager.Event.WaitingToPause);let promises=[this.awaitEvent(WI.DebuggerManager.Event.Paused,this)];for(let targetData of this._targetDebuggerDataMap.values())
promises.push(targetData.pauseIfNeeded());return Promise.all(promises);}
resume()
{if(!this.paused)
return Promise.resolve();let promises=[this.awaitEvent(WI.DebuggerManager.Event.Resumed,this)];for(let targetData of this._targetDebuggerDataMap.values())
promises.push(targetData.resumeIfNeeded());return Promise.all(promises);}
stepNext()
{if(!this.paused)
return Promise.reject(new Error("Cannot step next because debugger is not paused."));return Promise.all([this.awaitEvent(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this),this._activeCallFrame.target.DebuggerAgent.stepNext(),]);}
stepOver()
{if(!this.paused)
return Promise.reject(new Error("Cannot step over because debugger is not paused."));return Promise.all([this.awaitEvent(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this),this._activeCallFrame.target.DebuggerAgent.stepOver(),]);}
stepInto()
{if(!this.paused)
return Promise.reject(new Error("Cannot step into because debugger is not paused."));return Promise.all([this.awaitEvent(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this),this._activeCallFrame.target.DebuggerAgent.stepInto(),]);}
stepOut()
{if(!this.paused)
return Promise.reject(new Error("Cannot step out because debugger is not paused."));return Promise.all([this.awaitEvent(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this),this._activeCallFrame.target.DebuggerAgent.stepOut(),]);}
continueUntilNextRunLoop(target)
{return this.dataForTarget(target).continueUntilNextRunLoop();}
continueToLocation(script,lineNumber,columnNumber)
{return script.target.DebuggerAgent.continueToLocation({scriptId:script.id,lineNumber,columnNumber});}
addBreakpoint(breakpoint)
{if(!breakpoint)
return;if(breakpoint.special)
this._updateSpecialBreakpoint(breakpoint);else{if(breakpoint.contentIdentifier)
this._breakpointContentIdentifierMap.add(breakpoint.contentIdentifier,breakpoint);if(breakpoint.scriptIdentifier)
this._breakpointScriptIdentifierMap.add(breakpoint.scriptIdentifier,breakpoint);this._breakpoints.push(breakpoint);if(!breakpoint.disabled)
this._setBreakpoint(breakpoint);if(!this._restoringBreakpoints)
WI.objectStores.breakpoints.putObject(breakpoint);}
this.addProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointAdded,{breakpoint});}
removeBreakpoint(breakpoint)
{if(!breakpoint)
return;if(!breakpoint.removable)
return;let special=breakpoint.special;if(!special){this._breakpoints.remove(breakpoint);if(breakpoint.identifier)
this._removeBreakpoint(breakpoint);if(breakpoint.contentIdentifier)
this._breakpointContentIdentifierMap.delete(breakpoint.contentIdentifier,breakpoint);if(breakpoint.scriptIdentifier)
this._breakpointScriptIdentifierMap.delete(breakpoint.scriptIdentifier,breakpoint);}
breakpoint.disabled=true;breakpoint.clearActions();if(special){switch(breakpoint){case this._assertionFailuresBreakpoint:this._assertionFailuresBreakpointSetting.reset();this._assertionFailuresBreakpoint=null;break;case this._allMicrotasksBreakpoint:this._allMicrotasksBreakpointSetting.reset();this._allMicrotasksBreakpoint=null;break;}}else if(!this._restoringBreakpoints)
WI.objectStores.breakpoints.deleteObject(breakpoint);this.removeProbesForBreakpoint(breakpoint);this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointRemoved,{breakpoint});}
nextBreakpointActionIdentifier()
{return this._nextBreakpointActionIdentifier++;}
addProbesForBreakpoint(breakpoint)
{if(this._knownProbeIdentifiersForBreakpoint.has(breakpoint))
return;this._knownProbeIdentifiersForBreakpoint.set(breakpoint,new Set);this.updateProbesForBreakpoint(breakpoint);}
removeProbesForBreakpoint(breakpoint)
{this.updateProbesForBreakpoint(breakpoint);this._knownProbeIdentifiersForBreakpoint.delete(breakpoint);}
updateProbesForBreakpoint(breakpoint)
{let knownProbeIdentifiers=this._knownProbeIdentifiersForBreakpoint.get(breakpoint);if(!knownProbeIdentifiers){this.addProbesForBreakpoint(breakpoint);return;}
let seenProbeIdentifiers=new Set;for(let probeAction of breakpoint.probeActions){let probeIdentifier=probeAction.id;seenProbeIdentifiers.add(probeIdentifier);if(!knownProbeIdentifiers.has(probeIdentifier)){knownProbeIdentifiers.add(probeIdentifier);let probeSet=this._probeSetForBreakpoint(breakpoint);let newProbe=new WI.Probe(probeIdentifier,breakpoint,probeAction.data);this._probesByIdentifier.set(probeIdentifier,newProbe);probeSet.addProbe(newProbe);break;}
let probe=this._probesByIdentifier.get(probeIdentifier);probe.expression=probeAction.data;}
for(let probeIdentifier of knownProbeIdentifiers){if(seenProbeIdentifiers.has(probeIdentifier))
break;let probeSet=this._probeSetForBreakpoint(breakpoint);let probe=this._probesByIdentifier.get(probeIdentifier);this._probesByIdentifier.delete(probeIdentifier);knownProbeIdentifiers.delete(probeIdentifier);probeSet.removeProbe(probe);if(!probeSet.probes.length){this._probeSetsByBreakpoint.delete(probeSet.breakpoint);probeSet.willRemove();this.dispatchEventToListeners(WI.DebuggerManager.Event.ProbeSetRemoved,{probeSet});}}} 
breakpointResolved(target,breakpointIdentifier,location)
{let breakpoint=this._breakpointIdMap.get(breakpointIdentifier);if(!breakpoint)
return;if(!breakpoint.sourceCodeLocation.sourceCode){let sourceCodeLocation=this._sourceCodeLocationFromPayload(target,location);breakpoint.sourceCodeLocation.sourceCode=sourceCodeLocation.sourceCode;}
breakpoint.resolved=true;}
globalObjectCleared(target)
{let wasPaused=this.paused;WI.Script.resetUniqueDisplayNameNumbers(target);this._internalWebKitScripts=[];this._targetDebuggerDataMap.clear();this._ignoreBreakpointDisplayLocationDidChangeEvent=true;
for(let breakpoint of this._breakpoints){breakpoint.resolved=false;if(breakpoint.sourceCodeLocation.sourceCode)
breakpoint.sourceCodeLocation.sourceCode=null;}
this._ignoreBreakpointDisplayLocationDidChangeEvent=false;this.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptsCleared);if(wasPaused)
this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);}
debuggerDidPause(target,callFramesPayload,reason,data,asyncStackTracePayload)
{if(this._delayedResumeTimeout){clearTimeout(this._delayedResumeTimeout);this._delayedResumeTimeout=undefined;}
let wasPaused=this.paused;let targetData=this._targetDebuggerDataMap.get(target);let callFrames=[];let pauseReason=DebuggerManager.pauseReasonFromPayload(reason);let pauseData=data||null;for(var i=0;i<callFramesPayload.length;++i){var callFramePayload=callFramesPayload[i];var sourceCodeLocation=this._sourceCodeLocationFromPayload(target,callFramePayload.location);if(!sourceCodeLocation)
continue;if(!sourceCodeLocation.sourceCode)
continue;if(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(sourceCodeLocation.sourceCode.sourceURL))
continue;let scopeChain=this._scopeChainFromPayload(target,callFramePayload.scopeChain);let callFrame=WI.CallFrame.fromDebuggerPayload(target,callFramePayload,scopeChain,sourceCodeLocation);callFrames.push(callFrame);}
let activeCallFrame=callFrames[0];if(!activeCallFrame){
if(wasPaused)
target.DebuggerAgent.continueUntilNextRunLoop();else
target.DebuggerAgent.resume();this._didResumeInternal(target);return;}
let asyncStackTrace=WI.StackTrace.fromPayload(target,asyncStackTracePayload);targetData.updateForPause(callFrames,pauseReason,pauseData,asyncStackTrace);for(let[otherTarget,otherTargetData]of this._targetDebuggerDataMap)
otherTargetData.pauseIfNeeded();let activeCallFrameDidChange=this._activeCallFrame&&this._activeCallFrame.target===target;if(activeCallFrameDidChange)
this._activeCallFrame=activeCallFrame;else if(!wasPaused){this._activeCallFrame=activeCallFrame;activeCallFrameDidChange=true;}
if(!wasPaused)
this.dispatchEventToListeners(WI.DebuggerManager.Event.Paused);this.dispatchEventToListeners(WI.DebuggerManager.Event.CallFramesDidChange,{target});if(activeCallFrameDidChange)
this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);}
debuggerDidResume(target)
{this._didResumeInternal(target);}
playBreakpointActionSound(breakpointActionIdentifier)
{InspectorFrontendHost.beep();}
scriptDidParse(target,scriptIdentifier,url,startLine,startColumn,endLine,endColumn,isModule,isContentScript,sourceURL,sourceMapURL)
{let targetData=this.dataForTarget(target);let existingScript=targetData.scriptForIdentifier(scriptIdentifier);if(existingScript){return;}
if(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(sourceURL))
return;let range=new WI.TextRange(startLine,startColumn,endLine,endColumn);let sourceType=isModule?WI.Script.SourceType.Module:WI.Script.SourceType.Program;let script=new WI.Script(target,scriptIdentifier,range,url,sourceType,isContentScript,sourceURL,sourceMapURL);targetData.addScript(script);


if(WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker){if(target.mainResource instanceof WI.LocalScript){if(script.url===target.name)
target.mainResource=script;}}else if(!target.mainResource&&target!==WI.mainTarget){if(script.url===target.name){target.mainResource=script;if(script.resource)
target.resourceCollection.remove(script.resource);}}
if(isWebKitInternalScript(script.sourceURL)){this._internalWebKitScripts.push(script);if(!WI.settings.engineeringShowInternalScripts.value)
return;}
if(!WI.settings.debugShowConsoleEvaluations.value&&isWebInspectorConsoleEvaluationScript(script.sourceURL))
return;this.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptAdded,{script});if((target!==WI.mainTarget||WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker)&&!script.isMainResource()&&!script.resource)
target.addScript(script);}
scriptDidFail(target,url,scriptSource)
{const sourceURL=null;const sourceType=WI.Script.SourceType.Program;let script=new WI.LocalScript(target,url,sourceURL,sourceType,scriptSource);if(script.resource)
return;let targetData=this.dataForTarget(target);targetData.addScript(script);target.addScript(script);this.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptAdded,{script});}
didSampleProbe(target,sample)
{let probe=this._probesByIdentifier.get(sample.probeId);let elapsedTime=WI.timelineManager.computeElapsedTime(sample.timestamp);let object=WI.RemoteObject.fromPayload(sample.payload,target);probe.addSample(new WI.ProbeSample(sample.sampleId,sample.batchId,elapsedTime,object));} 
_sourceCodeLocationFromPayload(target,payload)
{let targetData=this.dataForTarget(target);let script=targetData.scriptForIdentifier(payload.scriptId);if(!script)
return null;return script.createSourceCodeLocation(payload.lineNumber,payload.columnNumber);}
_scopeChainFromPayload(target,payload)
{let scopeChain=[];for(let i=0;i<payload.length;++i)
scopeChain.push(this._scopeChainNodeFromPayload(target,payload[i]));return scopeChain;}
_scopeChainNodeFromPayload(target,payload)
{var type=null;switch(payload.type){case InspectorBackend.Enum.Debugger.ScopeType.Global:type=WI.ScopeChainNode.Type.Global;break;case InspectorBackend.Enum.Debugger.ScopeType.With:type=WI.ScopeChainNode.Type.With;break;case InspectorBackend.Enum.Debugger.ScopeType.Closure:type=WI.ScopeChainNode.Type.Closure;break;case InspectorBackend.Enum.Debugger.ScopeType.Catch:type=WI.ScopeChainNode.Type.Catch;break;case InspectorBackend.Enum.Debugger.ScopeType.FunctionName:type=WI.ScopeChainNode.Type.FunctionName;break;case InspectorBackend.Enum.Debugger.ScopeType.NestedLexical:type=WI.ScopeChainNode.Type.Block;break;case InspectorBackend.Enum.Debugger.ScopeType.GlobalLexicalEnvironment:type=WI.ScopeChainNode.Type.GlobalLexicalEnvironment;break;default:console.error("Unknown type: "+payload.type);break;}
let object=WI.RemoteObject.fromPayload(payload.object,target);return new WI.ScopeChainNode(type,[object],payload.name,payload.location,payload.empty);}
_setBreakpoint(breakpoint,specificTarget)
{if(breakpoint.disabled)
return;if(!this._restoringBreakpoints&&!this.breakpointsDisabledTemporarily){
this.breakpointsEnabled=true;}
function didSetBreakpoint(target,error,breakpointIdentifier,locations){if(error){WI.reportInternalError(error);return;}
this._breakpointIdMap.set(breakpointIdentifier,breakpoint);breakpoint.identifier=breakpointIdentifier;if(!(locations instanceof Array))
locations=[locations];for(let location of locations)
this.breakpointResolved(target,breakpointIdentifier,location);}
if(!specificTarget)
breakpoint.resolved=false;if(breakpoint.contentIdentifier){let targets=specificTarget?[specificTarget]:WI.targets;for(let target of targets){target.DebuggerAgent.setBreakpointByUrl.invoke({lineNumber:breakpoint.sourceCodeLocation.lineNumber,url:breakpoint.contentIdentifier,urlRegex:undefined,columnNumber:breakpoint.sourceCodeLocation.columnNumber,options:breakpoint.optionsToProtocol(),},didSetBreakpoint.bind(this,target));}}else if(breakpoint.scriptIdentifier){let target=breakpoint.target;target.DebuggerAgent.setBreakpoint.invoke({location:{scriptId:breakpoint.scriptIdentifier,lineNumber:breakpoint.sourceCodeLocation.lineNumber,columnNumber:breakpoint.sourceCodeLocation.columnNumber},options:breakpoint.optionsToProtocol(),},didSetBreakpoint.bind(this,target));}else
WI.reportInternalError("Unknown source for breakpoint.");}
_removeBreakpoint(breakpoint,callback)
{if(!breakpoint.identifier)
return;function didRemoveBreakpoint(target,error)
{if(error){WI.reportInternalError(error);return;}
this._breakpointIdMap.delete(breakpoint.identifier);breakpoint.identifier=null;
if(callback)
callback(target);}
if(breakpoint.contentIdentifier){for(let target of WI.targets)
target.DebuggerAgent.removeBreakpoint(breakpoint.identifier,didRemoveBreakpoint.bind(this,target));}else if(breakpoint.scriptIdentifier){let target=breakpoint.target;target.DebuggerAgent.removeBreakpoint(breakpoint.identifier,didRemoveBreakpoint.bind(this,target));}}
_setPauseOnExceptions(target)
{let commandArguments={state:"none",};if(this._breakpointsEnabledSetting.value){if(this._allExceptionsBreakpoint&&!this._allExceptionsBreakpoint.disabled){commandArguments.state="all";commandArguments.options=this._allExceptionsBreakpoint.optionsToProtocol();}else if(this._uncaughtExceptionsBreakpoint&&!this._uncaughtExceptionsBreakpoint.disabled){commandArguments.state="uncaught";commandArguments.options=this._uncaughtExceptionsBreakpoint.optionsToProtocol();}
if(this._uncaughtExceptionsBreakpoint)
this._uncaughtExceptionsBreakpoint.resolved=commandArguments.state!=="all";}
target.DebuggerAgent.setPauseOnExceptions.invoke(commandArguments);}
_createSpecialBreakpoint(serializedBreakpoint={})
{let location=WI.SourceCodeLocation.specialBreakpointLocation;serializedBreakpoint.lineNumber=location.lineNumber;serializedBreakpoint.columnNumber=location.columnNumber;serializedBreakpoint.resolved=true;return WI.JavaScriptBreakpoint.fromJSON(serializedBreakpoint);}
_updateSpecialBreakpoint(breakpoint,specificTarget)
{if(!breakpoint.disabled&&!this._restoringBreakpoints&&!this.breakpointsDisabledTemporarily)
this.breakpointsEnabled=true;let targets=specificTarget?[specificTarget]:WI.targets;let setting=null;let command=null;switch(breakpoint){case this._debuggerStatementsBreakpoint:setting=this._debuggerStatementsBreakpointSetting;command="setPauseOnDebuggerStatements";break;case this._allExceptionsBreakpoint:setting=this._allExceptionsBreakpointSetting;break;case this._uncaughtExceptionsBreakpoint:setting=this._uncaughtExceptionsBreakpointSetting;break;case this._assertionFailuresBreakpoint:setting=this._assertionFailuresBreakpointSetting;command="setPauseOnAssertions";break;case this._allMicrotasksBreakpoint:setting=this._allMicrotasksBreakpointSetting;command="setPauseOnMicrotasks";break;}
if(!specificTarget)
setting.value=breakpoint.toJSON();if(command){let commandArguments={enabled:!breakpoint.disabled,};if(!breakpoint.disabled)
commandArguments.options=breakpoint.optionsToProtocol();for(let target of targets)
target.DebuggerAgent[command].invoke(commandArguments);}else{for(let target of targets)
this._setPauseOnExceptions(target);}}
_breakpointDisplayLocationDidChange(event)
{if(this._ignoreBreakpointDisplayLocationDidChangeEvent)
return;let breakpoint=event.target;if(!breakpoint.identifier||breakpoint.disabled)
return;this._removeBreakpoint(breakpoint,(target)=>{this._restoringBreakpoints=true;this._setBreakpoint(breakpoint,target);this._restoringBreakpoints=false;this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointMoved,{breakpoint});});}
_breakpointDisabledStateDidChange(event)
{let breakpoint=event.target;if(breakpoint.special){this._updateSpecialBreakpoint(breakpoint);return;}
if(!this._restoringBreakpoints)
WI.objectStores.breakpoints.putObject(breakpoint);if(breakpoint.disabled)
this._removeBreakpoint(breakpoint);else
this._setBreakpoint(breakpoint);}
_breakpointEditablePropertyDidChange(event)
{let breakpoint=event.target;if(breakpoint.special){this._restoringBreakpoints=true;this._updateSpecialBreakpoint(breakpoint);this._restoringBreakpoints=false;return;}
if(!this._restoringBreakpoints)
WI.objectStores.breakpoints.putObject(breakpoint);if(breakpoint.disabled)
return;if(!breakpoint.editable)
return;this._removeBreakpoint(breakpoint,(target)=>{this._restoringBreakpoints=true;this._setBreakpoint(breakpoint,target);this._restoringBreakpoints=false;});}
_handleBreakpointActionsDidChange(event)
{this._breakpointEditablePropertyDidChange(event);this.updateProbesForBreakpoint(event.target);}
_startDisablingBreakpointsTemporarily()
{if(++this._temporarilyDisableBreakpointsRequestCount>1)
return;if(this.breakpointsDisabledTemporarily)
return;this._temporarilyDisabledBreakpointsRestoreSetting.value=this._breakpointsEnabledSetting.value;this.breakpointsEnabled=false;}
_stopDisablingBreakpointsTemporarily()
{this._temporarilyDisableBreakpointsRequestCount=Math.max(0,this._temporarilyDisableBreakpointsRequestCount-1);if(this._temporarilyDisableBreakpointsRequestCount>0)
return;if(!this.breakpointsDisabledTemporarily)
return;let restoreState=this._temporarilyDisabledBreakpointsRestoreSetting.value;this._temporarilyDisabledBreakpointsRestoreSetting.value=null;this.breakpointsEnabled=restoreState;}
_handleTimelineCapturingStateChanged(event)
{switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Starting:this._startDisablingBreakpointsTemporarily();if(this.paused)
this.resume();break;case WI.TimelineManager.CapturingState.Inactive:this._stopDisablingBreakpointsTemporarily();break;}}
_handleAuditManagerTestScheduled(event)
{this._startDisablingBreakpointsTemporarily();if(this.paused)
this.resume();}
_handleAuditManagerTestCompleted(event)
{this._stopDisablingBreakpointsTemporarily();}
_targetRemoved(event)
{let wasPaused=this.paused;this._targetDebuggerDataMap.delete(event.data.target);if(!this.paused&&wasPaused)
this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);}
_handleEngineeringShowInternalScriptsSettingChanged(event)
{let eventType=WI.settings.engineeringShowInternalScripts.value?WI.DebuggerManager.Event.ScriptAdded:WI.DebuggerManager.Event.ScriptRemoved;for(let script of this._internalWebKitScripts)
this.dispatchEventToListeners(eventType,{script});}
_handleEngineeringPauseForInternalScriptsSettingChanged(event)
{for(let target of WI.targets){if(target.hasCommand("Debugger.setPauseForInternalScripts"))
target.DebuggerAgent.setPauseForInternalScripts(WI.settings.engineeringPauseForInternalScripts.value);}}
_mainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._didResumeInternal(WI.mainTarget);}
_didResumeInternal(target)
{if(!this.paused)
return;if(this._delayedResumeTimeout){clearTimeout(this._delayedResumeTimeout);this._delayedResumeTimeout=undefined;}
let activeCallFrameDidChange=false;if(this._activeCallFrame&&this._activeCallFrame.target===target){this._activeCallFrame=null;activeCallFrameDidChange=true;}
this.dataForTarget(target).updateForResume();if(!this.paused)
this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);this.dispatchEventToListeners(WI.DebuggerManager.Event.CallFramesDidChange,{target});if(activeCallFrameDidChange)
this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);}
_associateBreakpointsWithSourceCode(breakpoints,sourceCode)
{this._ignoreBreakpointDisplayLocationDidChangeEvent=true;for(let breakpoint of breakpoints){if(!breakpoint.sourceCodeLocation.sourceCode)
breakpoint.sourceCodeLocation.sourceCode=sourceCode;}
this._ignoreBreakpointDisplayLocationDidChangeEvent=false;}
_probeSetForBreakpoint(breakpoint)
{let probeSet=this._probeSetsByBreakpoint.get(breakpoint);if(!probeSet){probeSet=new WI.ProbeSet(breakpoint);this._probeSetsByBreakpoint.set(breakpoint,probeSet);this.dispatchEventToListeners(WI.DebuggerManager.Event.ProbeSetAdded,{probeSet});}
return probeSet;}};WI.DebuggerManager.Event={BreakpointAdded:"debugger-manager-breakpoint-added",BreakpointRemoved:"debugger-manager-breakpoint-removed",BreakpointMoved:"debugger-manager-breakpoint-moved",WaitingToPause:"debugger-manager-waiting-to-pause",Paused:"debugger-manager-paused",Resumed:"debugger-manager-resumed",CallFramesDidChange:"debugger-manager-call-frames-did-change",ActiveCallFrameDidChange:"debugger-manager-active-call-frame-did-change",ScriptAdded:"debugger-manager-script-added",ScriptRemoved:"debugger-manager-script-removed",ScriptsCleared:"debugger-manager-scripts-cleared",BreakpointsEnabledDidChange:"debugger-manager-breakpoints-enabled-did-change",ProbeSetAdded:"debugger-manager-probe-set-added",ProbeSetRemoved:"debugger-manager-probe-set-removed",BlackboxChanged:"blackboxed-urls-changed",};WI.DebuggerManager.PauseReason={AnimationFrame:"animation-frame",Assertion:"assertion",BlackboxedScript:"blackboxed-script",Breakpoint:"breakpoint",CSPViolation:"CSP-violation",DebuggerStatement:"debugger-statement",DOM:"DOM",Exception:"exception",Fetch:"fetch",Interval:"interval",Listener:"listener",Microtask:"microtask",PauseOnNextStatement:"pause-on-next-statement",Timeout:"timeout",XHR:"xhr",Other:"other",Timer:"timer",EventListener:"event-listener",};WI.DebuggerManager.BlackboxType={Pattern:"pattern",URL:"url",};WI.DragToAdjustController=class DragToAdjustController
{constructor(delegate)
{this._delegate=delegate;this._element=null;this._active=false;this._enabled=false;this._dragging=false;this._tracksMouseClickAndDrag=false;} 
get element()
{return this._element;}
set element(element)
{this._element=element;}
get enabled()
{return this._enabled;}
set enabled(enabled)
{if(this._enabled===enabled)
return;if(enabled){this._element.addEventListener("mouseenter",this);this._element.addEventListener("mouseleave",this);}else{this._element.removeEventListener("mouseenter",this);this._element.removeEventListener("mouseleave",this);}}
get active()
{return this._active;}
set active(active)
{if(!this._element)
return;if(this._active===active)
return;if(active){WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._modifiersDidChange,this);this._element.addEventListener("mousemove",this);}else{WI.notifications.removeEventListener(WI.Notification.GlobalModifierKeysDidChange,this._modifiersDidChange,this);this._element.removeEventListener("mousemove",this);this._setTracksMouseClickAndDrag(false);}
this._active=active;if(this._delegate&&typeof this._delegate.dragToAdjustControllerActiveStateChanged==="function")
this._delegate.dragToAdjustControllerActiveStateChanged(this);}
reset()
{this._setTracksMouseClickAndDrag(false);this._element.classList.remove(WI.DragToAdjustController.StyleClassName);if(this._delegate&&typeof this._delegate.dragToAdjustControllerDidReset==="function")
this._delegate.dragToAdjustControllerDidReset(this);} 
handleEvent(event)
{switch(event.type){case"mouseenter":if(!this._dragging){if(this._delegate&&typeof this._delegate.dragToAdjustControllerCanBeActivated==="function")
this.active=this._delegate.dragToAdjustControllerCanBeActivated(this);else
this.active=true;}
break;case"mouseleave":if(!this._dragging)
this.active=false;break;case"mousemove":if(this._dragging)
this._mouseWasDragged(event);else
this._mouseMoved(event);break;case"mousedown":this._mouseWasPressed(event);break;case"mouseup":this._mouseWasReleased(event);break;case"contextmenu":event.preventDefault();break;}} 
_setDragging(dragging)
{if(this._dragging===dragging)
return;if(dragging)
WI.elementDragStart(this._element,this,this,window.event,"col-resize",window);else
WI.elementDragEnd(window.event);this._dragging=dragging;}
_setTracksMouseClickAndDrag(tracksMouseClickAndDrag)
{if(this._tracksMouseClickAndDrag===tracksMouseClickAndDrag)
return;if(tracksMouseClickAndDrag){this._element.classList.add(WI.DragToAdjustController.StyleClassName);window.addEventListener("mousedown",this,true);window.addEventListener("contextmenu",this,true);}else{this._element.classList.remove(WI.DragToAdjustController.StyleClassName);window.removeEventListener("mousedown",this,true);window.removeEventListener("contextmenu",this,true);this._setDragging(false);}
this._tracksMouseClickAndDrag=tracksMouseClickAndDrag;}
_modifiersDidChange(event)
{var canBeAdjusted=WI.modifierKeys.altKey;if(canBeAdjusted&&this._delegate&&typeof this._delegate.dragToAdjustControllerCanBeAdjusted==="function")
canBeAdjusted=this._delegate.dragToAdjustControllerCanBeAdjusted(this);this._setTracksMouseClickAndDrag(canBeAdjusted);}
_mouseMoved(event)
{var canBeAdjusted=event.altKey;if(canBeAdjusted&&this._delegate&&typeof this._delegate.dragToAdjustControllerCanAdjustObjectAtPoint==="function")
canBeAdjusted=this._delegate.dragToAdjustControllerCanAdjustObjectAtPoint(this,WI.Point.fromEvent(event));this._setTracksMouseClickAndDrag(canBeAdjusted);}
_mouseWasPressed(event)
{this._lastX=event.screenX;this._setDragging(true);event.preventDefault();event.stopPropagation();}
_mouseWasDragged(event)
{var x=event.screenX;var amount=x-this._lastX;if(Math.abs(amount)<1)
return;this._lastX=x;if(event.ctrlKey)
amount/=10;else if(event.shiftKey)
amount*=10;if(this._delegate&&typeof this._delegate.dragToAdjustControllerWasAdjustedByAmount==="function")
this._delegate.dragToAdjustControllerWasAdjustedByAmount(this,amount);event.preventDefault();event.stopPropagation();}
_mouseWasReleased(event)
{this._setDragging(false);event.preventDefault();event.stopPropagation();this.reset();}};WI.DragToAdjustController.StyleClassName="drag-to-adjust";WI.FormatterSourceMap=class FormatterSourceMap extends WI.Object
{constructor(originalLineEndings,formattedLineEndings,mapping)
{super();this._originalLineEndings=originalLineEndings;this._formattedLineEndings=formattedLineEndings;this._mapping=mapping;} 
static fromSourceMapData({originalLineEndings,formattedLineEndings,mapping})
{return new WI.FormatterSourceMap(originalLineEndings,formattedLineEndings,mapping);} 
originalToFormatted(lineNumber,columnNumber)
{var originalPosition=this._locationToPosition(this._originalLineEndings,lineNumber||0,columnNumber||0);return this.originalPositionToFormatted(originalPosition);}
originalPositionToFormatted(originalPosition)
{var formattedPosition=this._convertPosition(this._mapping.original,this._mapping.formatted,originalPosition);return this._positionToLocation(this._formattedLineEndings,formattedPosition);}
originalPositionToFormattedPosition(originalPosition)
{return this._convertPosition(this._mapping.original,this._mapping.formatted,originalPosition);}
formattedToOriginal(lineNumber,columnNumber)
{var originalPosition=this.formattedToOriginalOffset(lineNumber,columnNumber);return this._positionToLocation(this._originalLineEndings,originalPosition);}
formattedToOriginalOffset(lineNumber,columnNumber)
{var formattedPosition=this._locationToPosition(this._formattedLineEndings,lineNumber||0,columnNumber||0);var originalPosition=this._convertPosition(this._mapping.formatted,this._mapping.original,formattedPosition);return originalPosition;}
formattedPositionToOriginalPosition(formattedPosition)
{return this._convertPosition(this._mapping.formatted,this._mapping.original,formattedPosition);} 
_locationToPosition(lineEndings,lineNumber,columnNumber)
{var lineOffset=lineNumber?lineEndings[lineNumber-1]+1:0;return lineOffset+columnNumber;}
_positionToLocation(lineEndings,position)
{var lineNumber=lineEndings.upperBound(position-1);if(!lineNumber)
var columnNumber=position;else
var columnNumber=position-lineEndings[lineNumber-1]-1;return{lineNumber,columnNumber};}
_convertPosition(positions1,positions2,positionInPosition1)
{var index=positions1.upperBound(positionInPosition1)-1;var convertedPosition=positions2[index]+positionInPosition1-positions1[index];if(index<positions2.length-1&&convertedPosition>positions2[index+1])
convertedPosition=positions2[index+1];return convertedPosition;}};WI.GestureController=class GestureController
{constructor(target,delegate,{container,supportsScale,supportsTranslate})
{this._target=target;this._delegate=delegate;this._scale=1;this._translate={x:0,y:0};this._mouseWheelDelta=0;container||=target;this._supportsScale=supportsScale||false;if(this._supportsScale){container.addEventListener("wheel",this._handleWheel.bind(this));container.addEventListener("gesturestart",this._handleGestureStart.bind(this));container.addEventListener("gesturechange",this._handleGestureChange.bind(this));container.addEventListener("gestureend",this._handleGestureEnd.bind(this));}
this._supportsTranslate=supportsTranslate||false;if(this._supportsTranslate){container.addEventListener("mousedown",this._handleMouseDown.bind(this));}} 
get scale()
{return this._scale;}
set scale(scale)
{scale=Number.constrain(scale,0.01,100);if(scale===this._scale)
return;this._scale=scale;this._delegate.gestureControllerDidScale(this);}
get translate()
{return this._translate;}
set translate(translate)
{if(translate.x===this._translate.x&&translate.y===this._translate.y)
return;this._translate=translate;this._delegate.gestureControllerDidTranslate(this);}
reset()
{this.scale=1;this.translate={x:0,y:0};this._mouseWheelDelta=0;} 
_startScaleInteraction(event)
{this._scaleInteractionStartScale=this._scale;if(this._supportsTranslate)
this._scaleInteractionStartTranslate=this._translate;if(event.target===this._target){let elementBounds=this._target.getBoundingClientRect();this._scaleInteractionStartPosition={x:(event.pageX-elementBounds.left-(elementBounds.width/2))/this._scaleInteractionStartScale,y:(event.pageY-elementBounds.top-(elementBounds.height/2))/this._scaleInteractionStartScale,};}else
this._scaleInteractionStartPosition={x:0,y:0};}
_updateScaleInteraction(scale)
{this.scale=this._scaleInteractionStartScale*scale;if(this._supportsTranslate){this.translate={x:this._scaleInteractionStartTranslate.x-(this._scaleInteractionStartPosition.x*(this._scale-this._scaleInteractionStartScale)),y:this._scaleInteractionStartTranslate.y-(this._scaleInteractionStartPosition.y*(this._scale-this._scaleInteractionStartScale)),};}}
_endScaleInteraction(){this._scaleInteractionStartScale=NaN;if(this._supportsTranslate)
this._scaleInteractionStartTranslate=null;this._scaleInteractionStartPosition=null;}
_handleWheel(event)
{if(this._handlingGesture)
return;if(Math.abs(event.deltaX)>=Math.abs(event.deltaY)*0.5)
return;let deviceDirection=event.webkitDirectionInvertedFromDevice?-1:1;let delta=(event.deltaZ||event.deltaY||event.deltaX)*deviceDirection/1000;if(delta<0&&this._mouseWheelDelta>=0||delta>=0&&this._mouseWheelDelta<0)
this._mouseWheelDelta=0;this._mouseWheelDelta+=delta;this._startScaleInteraction(event);this._updateScaleInteraction(1-this._mouseWheelDelta);this._endScaleInteraction();event.preventDefault();event.stopPropagation();}
_handleGestureStart(event)
{this._handlingGesture=true;this._startScaleInteraction(event);event.preventDefault();event.stopPropagation();}
_handleGestureChange(event)
{this._updateScaleInteraction(event.scale);event.preventDefault();event.stopPropagation();}
_handleGestureEnd(event)
{this._handlingGesture=false;this._endScaleInteraction();}
_handleMouseDown(event)
{if(event.target.draggable)
return;if(event.button!==0)
return;this._translateInteractionStartTranslate=this._translate;this._translateInteractionStartPosition={x:event.pageX,y:event.pageY,};this._boundHandleMouseMove=this._handleMouseMove.bind(this);window.addEventListener("mousemove",this._boundHandleMouseMove,{capture:true});this._boundHandleMouseUp=this._handleMouseUp.bind(this);window.addEventListener("mouseup",this._boundHandleMouseUp,{capture:true});}
_handleMouseMove(event)
{this.translate={x:this._translateInteractionStartTranslate.x+(event.pageX-this._translateInteractionStartPosition.x),y:this._translateInteractionStartTranslate.y+(event.pageY-this._translateInteractionStartPosition.y),};}
_handleMouseUp(event)
{window.removeEventListener("mousemove",this._boundHandleMouseMove,{capture:true});this._boundHandleMouseMove=null;window.removeEventListener("mouseup",this._boundHandleMouseUp,{capture:true});this._boundHandleMouseUp=null;this._translateInteractionStartTranslate=null;this._translateInteractionStartPosition=null;}};

WI.HARBuilder=class HARBuilder
{static async buildArchive(resources)
{let promises=[];for(let resource of resources){promises.push(new Promise((resolve,reject)=>{resource.requestContent().then((x)=>resolve(x),()=>resolve(null));}));}
let contents=await Promise.all(promises);return{log:{version:"1.2",creator:HARBuilder.creator(),pages:HARBuilder.pages(),entries:resources.map((resource,index)=>HARBuilder.entry(resource,contents[index])),}};}
static creator()
{return{name:"WebKit Web Inspector",version:"1.0",};}
static pages()
{return[{startedDateTime:HARBuilder.date(WI.networkManager.mainFrame.mainResource.requestSentDate),id:"page_0",title:WI.networkManager.mainFrame.url||"",pageTimings:HARBuilder.pageTimings(),}];}
static pageTimings()
{let result={};let domContentReadyEventTimestamp=WI.networkManager.mainFrame.domContentReadyEventTimestamp;if(!isNaN(domContentReadyEventTimestamp))
result.onContentLoad=domContentReadyEventTimestamp*1000;let loadEventTimestamp=WI.networkManager.mainFrame.loadEventTimestamp;if(!isNaN(loadEventTimestamp))
result.onLoad=loadEventTimestamp*1000;return result;}
static entry(resource,content)
{let entry={pageref:"page_0",startedDateTime:HARBuilder.date(resource.requestSentDate),time:0,request:HARBuilder.request(resource),response:HARBuilder.response(resource,content),cache:HARBuilder.cache(resource),timings:HARBuilder.timings(resource),};if(resource.timingData.startTime&&resource.timingData.responseEnd)
entry.time=(resource.timingData.responseEnd-resource.timingData.startTime)*1000;if(resource.remoteAddress){entry.serverIPAddress=HARBuilder.ipAddress(resource.remoteAddress);if(entry.serverIPAddress)
entry._serverPort=HARBuilder.port(resource.remoteAddress);}
if(resource.connectionIdentifier)
entry.connection=""+resource.connectionIdentifier;if(resource.responseSource!==WI.Resource.ResponseSource.Unknown)
entry._fetchType=HARBuilder.fetchType(resource.responseSource);if(resource.priority!==WI.Resource.NetworkPriority.Unknown)
entry._priority=HARBuilder.priority(resource.priority);return entry;}
static request(resource)
{let result={method:resource.requestMethod||"",url:resource.url||"",httpVersion:WI.Resource.displayNameForProtocol(resource.protocol)||"",cookies:HARBuilder.cookies(resource.requestCookies,null),headers:HARBuilder.headers(resource.requestHeaders),queryString:resource.queryStringParameters||[],headersSize:!isNaN(resource.requestHeadersTransferSize)?resource.requestHeadersTransferSize:-1,bodySize:!isNaN(resource.requestBodyTransferSize)?resource.requestBodyTransferSize:-1,};if(resource.requestData)
result.postData=HARBuilder.postData(resource);return result;}
static response(resource,content)
{let result={status:resource.statusCode||0,statusText:resource.statusText||"",httpVersion:WI.Resource.displayNameForProtocol(resource.protocol)||"",cookies:HARBuilder.cookies(resource.responseCookies,resource.requestSentDate),headers:HARBuilder.headers(resource.responseHeaders),content:HARBuilder.content(resource,content),redirectURL:resource.responseHeaders.valueForCaseInsensitiveKey("Location")||"",headersSize:!isNaN(resource.responseHeadersTransferSize)?resource.responseHeadersTransferSize:-1,bodySize:!isNaN(resource.responseBodyTransferSize)?resource.responseBodyTransferSize:-1,};if(!isNaN(resource.networkTotalTransferSize))
result._transferSize=resource.networkTotalTransferSize;if(resource.failureReasonText)
result._error=resource.failureReasonText;return result;}
static cookies(cookies,requestSentDate)
{let result=[];for(let cookie of cookies){let json={name:cookie.name,value:cookie.value,};if(cookie.type===WI.Cookie.Type.Response){if(cookie.path)
json.path=cookie.path;if(cookie.domain)
json.domain=cookie.domain;json.expires=HARBuilder.date(cookie.expirationDate(requestSentDate));json.httpOnly=cookie.httpOnly;json.secure=cookie.secure;if(cookie.sameSite!==WI.Cookie.SameSiteType.None)
json.sameSite=cookie.sameSite;}
result.push(json);}
return result;}
static headers(headers)
{let result=[];for(let key in headers)
result.push({name:key,value:headers[key]});return result;}
static content(resource,content)
{let encodedSize=!isNaN(resource.networkEncodedSize)?resource.networkEncodedSize:resource.estimatedNetworkEncodedSize;let decodedSize=!isNaN(resource.networkDecodedSize)?resource.networkDecodedSize:resource.size;if(isNaN(decodedSize))
decodedSize=0;if(isNaN(encodedSize))
encodedSize=0;let result={size:decodedSize,compression:decodedSize-encodedSize,mimeType:resource.mimeType||"x-unknown",};if(content){if(content.rawContent)
result.text=content.rawContent;if(content.rawBase64Encoded)
result.encoding="base64";}
return result;}
static postData(resource)
{return{mimeType:resource.requestDataContentType||"",text:resource.requestData,params:resource.requestFormParameters||[],};}
static cache(resource)
{
 return{};}
static timings(resource)
{
let result={blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:0,receive:0,};if(resource.timingData.startTime&&resource.timingData.responseEnd){let{startTime,domainLookupStart,domainLookupEnd,connectStart,connectEnd,secureConnectionStart,requestStart,responseStart,responseEnd}=resource.timingData;result.blocked=((domainLookupStart||connectStart||requestStart)-startTime)*1000;if(domainLookupStart)
result.dns=((domainLookupEnd||connectStart||requestStart)-domainLookupStart)*1000;if(connectStart)
result.connect=((connectEnd||requestStart)-connectStart)*1000;if(secureConnectionStart)
result.ssl=((connectEnd||requestStart)-secureConnectionStart)*1000;

result.send=(domainLookupEnd||connectEnd)?(requestStart-(connectEnd||domainLookupEnd))*1000:0;result.wait=(responseStart-requestStart)*1000;result.receive=(responseEnd-responseStart)*1000;}
return result;} 
static ipAddress(remoteAddress)
{if(!remoteAddress)
return"";return remoteAddress.replace(/:\d+$/,"");}
static port(remoteAddress)
{if(!remoteAddress)
return undefined;let index=remoteAddress.lastIndexOf(":");if(!index)
return undefined;let portString=remoteAddress.substr(index+1);let port=parseInt(portString);if(isNaN(port))
return undefined;return port;}
static date(date)
{ if(!date)
return"";return date.toISOString();}
static fetchType(responseSource)
{switch(responseSource){case WI.Resource.ResponseSource.Network:return"Network Load";case WI.Resource.ResponseSource.MemoryCache:return"Memory Cache";case WI.Resource.ResponseSource.DiskCache:return"Disk Cache";case WI.Resource.ResponseSource.ServiceWorker:return"Service Worker";case WI.Resource.ResponseSource.InspectorOverride:return"Inspector Override";}
return undefined;}
static priority(priority)
{switch(priority){case WI.Resource.NetworkPriority.Low:return"low";case WI.Resource.NetworkPriority.Medium:return"medium";case WI.Resource.NetworkPriority.High:return"high";}
return undefined;}
static dateFromHARDate(isoString)
{return Date.parse(isoString);}
static protocolFromHARProtocol(protocol)
{switch(protocol){case"HTTP/2":return"h2";case"HTTP/1.0":return"http/1.0";case"HTTP/1.1":return"http/1.1";case"SPDY/2":return"spdy/2";case"SPDY/3":return"spdy/3";case"SPDY/3.1":return"spdy/3.1";}
if(protocol)
console.warn("Unknown HAR protocol value",protocol);return null;}
static responseSourceFromHARFetchType(fetchType)
{switch(fetchType){case"Network Load":return WI.Resource.ResponseSource.Network;case"Memory Cache":return WI.Resource.ResponseSource.MemoryCache;case"Disk Cache":return WI.Resource.ResponseSource.DiskCache;case"Service Worker":return WI.Resource.ResponseSource.ServiceWorker;case"Inspector Override":return WI.Resource.ResponseSource.InspectorOverride;}
if(fetchType)
console.warn("Unknown HAR _fetchType value",fetchType);return WI.Resource.ResponseSource.Other;}
static networkPriorityFromHARPriority(priority)
{switch(priority){case"low":return WI.Resource.NetworkPriority.Low;case"medium":return WI.Resource.NetworkPriority.Medium;case"high":return WI.Resource.NetworkPriority.High;}
if(priority)
console.warn("Unknown HAR priority value",priority);return WI.Resource.NetworkPriority.Unknown;}};WI.HeapManager=class HeapManager extends WI.Object
{constructor()
{super();this._enabled=false;} 
get domains(){return["Heap"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Heap"))
target.HeapAgent.enable();} 
enable()
{if(this._enabled)
return;this._enabled=true;for(let target of WI.targets)
this.initializeTarget(target);}
disable()
{if(!this._enabled)
return;for(let target of WI.targets){if(target.hasDomain("Heap"))
target.HeapAgent.disable();}
this._enabled=false;}
snapshot(callback)
{let target=WI.assumingMainTarget();target.HeapAgent.snapshot((error,timestamp,snapshotStringData)=>{if(error)
console.error(error);callback(error,timestamp,snapshotStringData);});}
getPreview(node,callback)
{let target=WI.assumingMainTarget();target.HeapAgent.getPreview(node.id,(error,string,functionDetails,preview)=>{if(error)
console.error(error);callback(error,string,functionDetails,preview);});}
getRemoteObject(node,objectGroup,callback)
{let target=WI.assumingMainTarget();target.HeapAgent.getRemoteObject(node.id,objectGroup,(error,result)=>{if(error)
console.error(error);callback(error,result);});} 
garbageCollected(target,payload)
{if(!this._enabled)
return; if(target!==WI.mainTarget)
return;let collection=WI.GarbageCollection.fromPayload(payload);this.dispatchEventToListeners(WI.HeapManager.Event.GarbageCollected,{collection});}};WI.HeapManager.Event={GarbageCollected:"heap-manager-garbage-collected"};WI.IndexedDBManager=class IndexedDBManager extends WI.Object
{constructor()
{super();this._enabled=false;this._requestedSecurityOrigins=new Set;this._reset();} 
get domains(){return["IndexedDB"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("IndexedDB"))
target.IndexedDBAgent.enable();} 
get indexedDatabases(){return this._indexedDatabases;}
enable()
{this._enabled=true;this._reset();for(let target of WI.targets)
this.initializeTarget(target);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.SecurityOriginDidChange,this._securityOriginDidChange,this);}
disable()
{this._enabled=false;for(let target of WI.targets){if(target.hasDomain("IndexedDB"))
target.IndexedDBAgent.disable();}
WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.SecurityOriginDidChange,this._securityOriginDidChange,this);this._reset();}
requestIndexedDatabaseData(objectStore,objectStoreIndex,startEntryIndex,maximumEntryCount,callback)
{function processData(error,entryPayloads,moreAvailable)
{if(error){callback(null,false);return;}
var entries=[];for(var entryPayload of entryPayloads){var entry={};entry.primaryKey=WI.RemoteObject.fromPayload(entryPayload.primaryKey);entry.key=WI.RemoteObject.fromPayload(entryPayload.key);entry.value=WI.RemoteObject.fromPayload(entryPayload.value);entries.push(entry);}
callback(entries,moreAvailable);}
var requestArguments={securityOrigin:objectStore.parentDatabase.securityOrigin,databaseName:objectStore.parentDatabase.name,objectStoreName:objectStore.name,indexName:objectStoreIndex&&objectStoreIndex.name||"",skipCount:startEntryIndex||0,pageSize:maximumEntryCount||100};let target=WI.assumingMainTarget();target.IndexedDBAgent.requestData.invoke(requestArguments,processData);}
clearObjectStore(objectStore)
{let securityOrigin=objectStore.parentDatabase.securityOrigin;let databaseName=objectStore.parentDatabase.name;let objectStoreName=objectStore.name;let target=WI.assumingMainTarget();target.IndexedDBAgent.clearObjectStore(securityOrigin,databaseName,objectStoreName);} 
_reset()
{this._indexedDatabases=[];this._requestedSecurityOrigins.clear();this.dispatchEventToListeners(WI.IndexedDBManager.Event.Cleared);let mainFrame=WI.networkManager.mainFrame;if(mainFrame)
this._addIndexedDBDatabasesIfNeeded(mainFrame);}
_addIndexedDBDatabasesIfNeeded(frame)
{if(!this._enabled)
return;let target=WI.assumingMainTarget();if(!target.hasDomain("IndexedDB"))
return;var securityOrigin=frame.securityOrigin;if(!securityOrigin||securityOrigin==="://")
return;if(this._requestedSecurityOrigins.has(securityOrigin))
return;this._requestedSecurityOrigins.add(securityOrigin);function processDatabaseNames(error,names)
{if(error||!names)
return;for(var name of names)
target.IndexedDBAgent.requestDatabase(securityOrigin,name,processDatabase.bind(this));}
function processDatabase(error,databasePayload)
{if(error||!databasePayload)
return;var objectStores=databasePayload.objectStores.map(processObjectStore);var indexedDatabase=new WI.IndexedDatabase(databasePayload.name,securityOrigin,databasePayload.version,objectStores);this._indexedDatabases.push(indexedDatabase);this.dispatchEventToListeners(WI.IndexedDBManager.Event.IndexedDatabaseWasAdded,{indexedDatabase});}
function processKeyPath(keyPathPayload)
{switch(keyPathPayload.type){case InspectorBackend.Enum.IndexedDB.KeyPathType.Null:return null;case InspectorBackend.Enum.IndexedDB.KeyPathType.String:return keyPathPayload.string;case InspectorBackend.Enum.IndexedDB.KeyPathType.Array:return keyPathPayload.array;default:console.error("Unknown KeyPath type:",keyPathPayload.type);return null;}}
function processObjectStore(objectStorePayload)
{var keyPath=processKeyPath(objectStorePayload.keyPath);var indexes=objectStorePayload.indexes.map(processObjectStoreIndex);return new WI.IndexedDatabaseObjectStore(objectStorePayload.name,keyPath,objectStorePayload.autoIncrement,indexes);}
function processObjectStoreIndex(objectStoreIndexPayload)
{var keyPath=processKeyPath(objectStoreIndexPayload.keyPath);return new WI.IndexedDatabaseObjectStoreIndex(objectStoreIndexPayload.name,keyPath,objectStoreIndexPayload.unique,objectStoreIndexPayload.multiEntry);}
target.IndexedDBAgent.requestDatabaseNames(securityOrigin,processDatabaseNames.bind(this));}
_mainResourceDidChange(event)
{if(event.target.isMainFrame())
this._reset();}
_securityOriginDidChange(event)
{this._addIndexedDBDatabasesIfNeeded(event.target);}};WI.IndexedDBManager.Event={IndexedDatabaseWasAdded:"indexed-db-manager-indexed-database-was-added",Cleared:"indexed-db-manager-cleared",};WI.JavaScriptLogViewController=class JavaScriptLogViewController extends WI.Object
{constructor(element,scrollElement,textPrompt,delegate,historySettingIdentifier)
{super();this._element=element;this._scrollElement=scrollElement;this._promptHistorySetting=new WI.Setting(historySettingIdentifier,null);this._prompt=textPrompt;this._prompt.delegate=this;this._prompt.history=this._promptHistorySetting.value;this.delegate=delegate;this._cleared=true;this._previousMessageView=null;this._lastCommitted="";this._repeatCountWasInterrupted=false;this._sessions=[];this._currentSessionOrGroup=null;this.messagesAlternateClearKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,"L",this.requestClearMessages.bind(this),this._element);this._messagesFindNextKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"G",this._handleFindNextShortcut.bind(this),this._element);this._messagesFindPreviousKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"G",this._handleFindPreviousShortcut.bind(this),this._element);this._promptAlternateClearKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,"L",this.requestClearMessages.bind(this),this._prompt.element);this._promptFindNextKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"G",this._handleFindNextShortcut.bind(this),this._prompt.element);this._promptFindPreviousKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"G",this._handleFindPreviousShortcut.bind(this),this._prompt.element);this._pendingMessagesForSessionOrGroup=new Map;this._scheduledRenderIdentifier=0;this.startNewSession();} 
clear()
{this._cleared=true;const clearPreviousSessions=true;this.startNewSession(clearPreviousSessions,{newSessionReason:WI.ConsoleSession.NewSessionReason.ConsoleCleared});}
startNewSession(clearPreviousSessions=false,data={})
{if(clearPreviousSessions){this._pendingMessagesForSessionOrGroup.clear();if(this._sessions.length){for(let session of this._sessions)
session.element.remove();this._sessions=[];this._currentSessionOrGroup=null;}}
if(!this._sessions.length)
data.timestamp=Date.now();let lastSession=this._sessions.lastValue;if(lastSession&&!lastSession.hasMessages()&&!this._pendingMessagesForSessionOrGroup.has(lastSession)){this._sessions.pop();lastSession.element.remove();}
let consoleSession=new WI.ConsoleSession(data);this._previousMessageView=null;this._lastCommitted="";this._repeatCountWasInterrupted=false;this._sessions.push(consoleSession);this._currentSessionOrGroup=consoleSession;this._element.appendChild(consoleSession.element);consoleSession.element.scrollIntoView();}
appendImmediateExecutionWithResult(text,result,addSpecialUserLogClass,shouldRevealConsole)
{var commandMessageView=new WI.ConsoleCommandView(text,addSpecialUserLogClass?"special-user-log":null);this._appendConsoleMessageView(commandMessageView,true);function saveResultCallback(savedResultIndex)
{let commandResultMessage=new WI.ConsoleCommandResultMessage(result.target,result,false,savedResultIndex,shouldRevealConsole);let commandResultMessageView=new WI.ConsoleMessageView(commandResultMessage);this._appendConsoleMessageView(commandResultMessageView,true);}
WI.runtimeManager.saveResult(result,saveResultCallback.bind(this));}
appendConsoleMessage(consoleMessage)
{var consoleMessageView=new WI.ConsoleMessageView(consoleMessage);this._appendConsoleMessageView(consoleMessageView);return consoleMessageView;}
updatePreviousMessageRepeatCount(count)
{if(!this._previousMessageView)
return false;var previousIgnoredCount=this._previousMessageView[WI.JavaScriptLogViewController.IgnoredRepeatCount]||0;var previousVisibleCount=this._previousMessageView.repeatCount;if(!this._repeatCountWasInterrupted){this._previousMessageView.repeatCount=count-previousIgnoredCount;return true;}
var consoleMessage=this._previousMessageView.message;var duplicatedConsoleMessageView=new WI.ConsoleMessageView(consoleMessage);duplicatedConsoleMessageView[WI.JavaScriptLogViewController.IgnoredRepeatCount]=previousIgnoredCount+previousVisibleCount;duplicatedConsoleMessageView.repeatCount=1;this._appendConsoleMessageView(duplicatedConsoleMessageView);return true;}
isScrolledToBottom()
{return this._scrollToBottomTimeout||this._scrollElement.isScrolledToBottom();}
scrollToBottom()
{if(this._scrollToBottomTimeout)
return;function delayedWork()
{this._scrollToBottomTimeout=null;this._scrollElement.scrollTop=this._scrollElement.scrollHeight;}

this._scrollToBottomTimeout=setTimeout(delayedWork.bind(this),0);}
requestClearMessages()
{WI.consoleManager.requestClearMessages();} 
consolePromptHistoryDidChange(prompt)
{this._promptHistorySetting.value=this._prompt.history;}
consolePromptShouldCommitText(prompt,text,cursorIsAtLastPosition,handler)
{if(!cursorIsAtLastPosition){handler(true);return;}
function parseFinished(error,result,message,range)
{handler(result!==InspectorBackend.Enum.Runtime.SyntaxErrorType.Recoverable);}
WI.runtimeManager.activeExecutionContext.target.RuntimeAgent.parse(text,parseFinished.bind(this));}
consolePromptTextCommitted(prompt,text)
{if(this._lastCommitted!==text){let commandMessageView=new WI.ConsoleCommandView(text);this._appendConsoleMessageView(commandMessageView,true);this._lastCommitted=text;}
function printResult(result,wasThrown,savedResultIndex)
{if(!result||this._cleared)
return;let shouldRevealConsole=true;let commandResultMessage=new WI.ConsoleCommandResultMessage(result.target,result,wasThrown,savedResultIndex,shouldRevealConsole);let commandResultMessageView=new WI.ConsoleMessageView(commandResultMessage);this._appendConsoleMessageView(commandResultMessageView,true);}
let options={objectGroup:WI.RuntimeManager.ConsoleObjectGroup,includeCommandLineAPI:true,doNotPauseOnExceptionsAndMuteConsole:false,returnByValue:false,generatePreview:true,saveResult:true,emulateUserGesture:WI.settings.emulateInUserGesture.value,sourceURLAppender:appendWebInspectorConsoleEvaluationSourceURL,};WI.runtimeManager.evaluateInInspectedWindow(text,options,printResult.bind(this));} 
_handleFindNextShortcut()
{this.delegate.highlightNextSearchMatch();}
_handleFindPreviousShortcut()
{this.delegate.highlightPreviousSearchMatch();}
_appendConsoleMessageView(messageView,repeatCountWasInterrupted)
{let pendingMessagesForSession=this._pendingMessagesForSessionOrGroup.get(this._currentSessionOrGroup);if(!pendingMessagesForSession){pendingMessagesForSession=[];this._pendingMessagesForSessionOrGroup.set(this._currentSessionOrGroup,pendingMessagesForSession);}
pendingMessagesForSession.push(messageView);this._cleared=false;this._repeatCountWasInterrupted=repeatCountWasInterrupted||false;if(!repeatCountWasInterrupted)
this._previousMessageView=messageView;if(messageView.message&&messageView.message.source!==WI.ConsoleMessage.MessageSource.JS)
this._lastCommitted="";if(WI.consoleContentView.isAttached)
this.renderPendingMessagesSoon();if(!WI.isShowingConsoleTab()&&messageView.message&&messageView.message.shouldRevealConsole)
WI.showSplitConsole();}
renderPendingMessages()
{if(this._scheduledRenderIdentifier){cancelAnimationFrame(this._scheduledRenderIdentifier);this._scheduledRenderIdentifier=0;}
if(!this._pendingMessagesForSessionOrGroup.size)
return;let wasScrolledToBottom=this.isScrolledToBottom();let savedCurrentConsoleGroup=this._currentSessionOrGroup;let lastMessageView=null;const maxMessagesPerFrame=100;let renderedMessages=0;for(let[session,messages]of this._pendingMessagesForSessionOrGroup){this._currentSessionOrGroup=session;let messagesToRender=messages.splice(0,maxMessagesPerFrame-renderedMessages);for(let message of messagesToRender){message.render();this._didRenderConsoleMessageView(message);}
lastMessageView=messagesToRender.lastValue;if(!messages.length)
this._pendingMessagesForSessionOrGroup.delete(session);renderedMessages+=messagesToRender.length;if(renderedMessages>=maxMessagesPerFrame)
break;}
this._currentSessionOrGroup=savedCurrentConsoleGroup;if(wasScrolledToBottom||lastMessageView instanceof WI.ConsoleCommandView||lastMessageView.message.type===WI.ConsoleMessage.MessageType.Result||lastMessageView.message.type===WI.ConsoleMessage.MessageType.Image)
this.scrollToBottom();WI.quickConsole.needsLayout();if(this._pendingMessagesForSessionOrGroup.size)
this.renderPendingMessagesSoon();}
renderPendingMessagesSoon()
{if(this._scheduledRenderIdentifier)
return;this._scheduledRenderIdentifier=requestAnimationFrame(()=>this.renderPendingMessages());}
_didRenderConsoleMessageView(messageView)
{var type=messageView instanceof WI.ConsoleCommandView?null:messageView.message.type;if(type===WI.ConsoleMessage.MessageType.EndGroup){var parentGroup=this._currentSessionOrGroup.parentGroup;if(parentGroup)
this._currentSessionOrGroup=parentGroup;}else{if(type===WI.ConsoleMessage.MessageType.StartGroup||type===WI.ConsoleMessage.MessageType.StartGroupCollapsed){var group=new WI.ConsoleGroup(this._currentSessionOrGroup);var groupElement=group.render(messageView);this._currentSessionOrGroup.append(groupElement);this._currentSessionOrGroup=group;}else
this._currentSessionOrGroup.addMessageView(messageView);}
if(this.delegate&&typeof this.delegate.didAppendConsoleMessageView==="function")
this.delegate.didAppendConsoleMessageView(messageView);}};WI.JavaScriptLogViewController.CachedPropertiesDuration=30_000;WI.JavaScriptLogViewController.IgnoredRepeatCount=Symbol("ignored-repeat-count");Object.defineProperty(WI,"javaScriptRuntimeCompletionProvider",{get:function()
{if(!WI.JavaScriptRuntimeCompletionProvider._instance)
WI.JavaScriptRuntimeCompletionProvider._instance=new WI.JavaScriptRuntimeCompletionProvider;return WI.JavaScriptRuntimeCompletionProvider._instance;}});WI.JavaScriptRuntimeCompletionProvider=class JavaScriptRuntimeCompletionProvider extends WI.Object
{constructor()
{super();this._ongoingCompletionRequests=0;WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._clearLastProperties,this);} 
static get _commandLineAPIKeys()
{if(!JavaScriptRuntimeCompletionProvider.__cachedCommandLineAPIKeys){JavaScriptRuntimeCompletionProvider.__cachedCommandLineAPIKeys=["$_","assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","inspect","keys","log","profile","profileEnd","queryHolders","queryInstances","queryObjects","record","recordEnd","screenshot","table","takeHeapSnapshot","time","timeEnd","timeLog","timeStamp","trace","values","warn",];}
return JavaScriptRuntimeCompletionProvider.__cachedCommandLineAPIKeys;} 
completionControllerCompletionsNeeded(completionController,defaultCompletions,base,prefix,suffix,forced)
{if(!forced&&!prefix&&!/[.[]$/.test(base)){completionController.updateCompletions(null);return;}

if(/[({]$/.test(base))
base="";var lastBaseIndex=base.length-1;var dotNotation=base[lastBaseIndex]===".";var bracketNotation=base[lastBaseIndex]==="[";if(dotNotation||bracketNotation){base=base.substring(0,lastBaseIndex);if(!base&&dotNotation){completionController.updateCompletions(defaultCompletions);return;}
if(!forced&&!prefix&&dotNotation&&base.indexOf(".")===-1&&parseInt(base,10)==base){completionController.updateCompletions(null);return;}
if(!base&&bracketNotation)
bracketNotation=false;}
this._incrementOngoingCompletionRequests();

if(this._lastMode===completionController.mode&&this._lastBase===base&&this._lastPropertyNames){receivedPropertyNames.call(this,this._lastPropertyNames);return;}
this._lastMode=completionController.mode;this._lastBase=base;this._lastPropertyNames=null;var activeCallFrame=WI.debuggerManager.activeCallFrame;if(!base&&activeCallFrame&&!this._alwaysEvaluateInWindowContext)
activeCallFrame.collectScopeChainVariableNames(receivedPropertyNames.bind(this));else{let options={objectGroup:"completion",includeCommandLineAPI:true,doNotPauseOnExceptionsAndMuteConsole:true,returnByValue:false,generatePreview:false,saveResult:false};WI.runtimeManager.evaluateInInspectedWindow(base,options,evaluated.bind(this));}
function updateLastPropertyNames(propertyNames)
{if(this._clearLastPropertiesTimeout)
clearTimeout(this._clearLastPropertiesTimeout);this._clearLastPropertiesTimeout=setTimeout(this._clearLastProperties.bind(this),WI.JavaScriptLogViewController.CachedPropertiesDuration);this._lastPropertyNames=propertyNames||[];}
function evaluated(result,wasThrown)
{if(wasThrown||!result||result.type==="undefined"||(result.type==="object"&&result.subtype==="null")){this._decrementOngoingCompletionRequests();updateLastPropertyNames.call(this,[]);completionController.updateCompletions(defaultCompletions);return;}
function inspectedPage_evalResult_getArrayCompletions(primitiveType)
{var array=this;var arrayLength;var resultSet={};for(var o=array;o;o=o.__proto__){try{if(o===array&&o.length){arrayLength=o.length;}else{var names=Object.getOwnPropertyNames(o);for(var i=0;i<names.length;++i)
resultSet[names[i]]=true;}}catch{}}
if(arrayLength)
resultSet["length"]=arrayLength;return resultSet;}
function inspectedPage_evalResult_getCompletions(primitiveType)
{var object;if(primitiveType==="string")
object=new String("");else if(primitiveType==="number")
object=new Number(0);else if(primitiveType==="boolean")
object=new Boolean(false);else if(primitiveType==="symbol")
object=Symbol();else
object=this;var resultSet={};for(var o=object;o;o=o.__proto__){try{var names=Object.getOwnPropertyNames(o);for(var i=0;i<names.length;++i)
resultSet[names[i]]=true;}catch(e){}}
return resultSet;}
if(result.subtype==="array")
result.callFunctionJSON(inspectedPage_evalResult_getArrayCompletions,undefined,receivedArrayPropertyNames.bind(this));else if(result.type==="object"||result.type==="function")
result.callFunctionJSON(inspectedPage_evalResult_getCompletions,undefined,receivedObjectPropertyNames.bind(this));else if(result.type==="string"||result.type==="number"||result.type==="boolean"||result.type==="symbol"){let options={objectGroup:"completion",includeCommandLineAPI:false,doNotPauseOnExceptionsAndMuteConsole:true,returnByValue:true,generatePreview:false,saveResult:false};WI.runtimeManager.evaluateInInspectedWindow("("+inspectedPage_evalResult_getCompletions+")(\""+result.type+"\")",options,receivedPropertyNamesFromEvaluate.bind(this));}else
console.error("Unknown result type: "+result.type);}
function receivedPropertyNamesFromEvaluate(object,wasThrown,result)
{receivedPropertyNames.call(this,result&&!wasThrown?Object.keys(result.value):null);}
function receivedObjectPropertyNames(propertyNames)
{receivedPropertyNames.call(this,Object.keys(propertyNames));}
function receivedArrayPropertyNames(propertyNames)
{if(propertyNames&&typeof propertyNames.length==="number"){ var max=Math.min(propertyNames.length,1000);for(var i=0;i<max;++i)
propertyNames[i]=true;}
receivedObjectPropertyNames.call(this,propertyNames);}
function receivedPropertyNames(propertyNames)
{propertyNames=propertyNames||[];updateLastPropertyNames.call(this,propertyNames);this._decrementOngoingCompletionRequests();if(!base){propertyNames.pushAll(JavaScriptRuntimeCompletionProvider._commandLineAPIKeys);let savedResultAlias=WI.settings.consoleSavedResultAlias.value;if(savedResultAlias)
propertyNames.push(savedResultAlias+"_");let target=WI.runtimeManager.activeExecutionContext.target;let targetData=WI.debuggerManager.paused?WI.debuggerManager.dataForTarget(target):{};function shouldExposeEvent(){switch(completionController.mode){case WI.CodeMirrorCompletionController.Mode.FullConsoleCommandLineAPI:case WI.CodeMirrorCompletionController.Mode.EventBreakpoint:return true;case WI.CodeMirrorCompletionController.Mode.PausedConsoleCommandLineAPI:return targetData.pauseReason===WI.DebuggerManager.PauseReason.Listener||targetData.pauseReason===WI.DebuggerManager.PauseReason.EventListener;}
return false;}
if(shouldExposeEvent()){propertyNames.push("$event");if(savedResultAlias)
propertyNames.push(savedResultAlias+"event");}
function shouldExposeException(){switch(completionController.mode){case WI.CodeMirrorCompletionController.Mode.FullConsoleCommandLineAPI:case WI.CodeMirrorCompletionController.Mode.ExceptionBreakpoint:return true;case WI.CodeMirrorCompletionController.Mode.PausedConsoleCommandLineAPI:return targetData.pauseReason===WI.DebuggerManager.PauseReason.Exception;}
return false;}
if(shouldExposeException()){propertyNames.push("$exception");if(savedResultAlias)
propertyNames.push(savedResultAlias+"exception");}
switch(target.type){case WI.TargetType.Page:propertyNames.push("$");propertyNames.push("$$");propertyNames.push("$0");if(savedResultAlias)
propertyNames.push(savedResultAlias+"0");propertyNames.push("$x"); case WI.TargetType.ServiceWorker:case WI.TargetType.Worker:propertyNames.push("copy");propertyNames.push("getEventListeners");propertyNames.push("monitorEvents");propertyNames.push("unmonitorEvents");break;}
for(var i=1;i<=WI.ConsoleCommandResultMessage.maximumSavedResultIndex;++i){propertyNames.push("$"+i);if(savedResultAlias)
propertyNames.push(savedResultAlias+i);}}
var implicitSuffix="";if(bracketNotation){var quoteUsed=prefix[0]==="'"?"'":"\"";if(suffix!=="]"&&suffix!==quoteUsed)
implicitSuffix="]";}
var completions=defaultCompletions;let knownCompletions=new Set(completions);for(var i=0;i<propertyNames.length;++i){var property=propertyNames[i];if(dotNotation&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property))
continue;if(bracketNotation){if(parseInt(property)!=property)
property=quoteUsed+property.escapeCharacters(quoteUsed+"\\")+(suffix!==quoteUsed?quoteUsed:"");}
if(!property.startsWith(prefix)||knownCompletions.has(property))
continue;completions.push(property);knownCompletions.add(property);}
function compare(a,b)
{let numericCompareResult=a-b;if(!isNaN(numericCompareResult))
return numericCompareResult;let aRareProperty=a.startsWith("__")&&a.endsWith("__");let bRareProperty=b.startsWith("__")&&b.endsWith("__");if(aRareProperty&&!bRareProperty)
return 1;if(!aRareProperty&&bRareProperty)
return-1;return a.extendedLocaleCompare(b);}
completions.sort(compare);completionController.updateCompletions(completions,implicitSuffix);}} 
_incrementOngoingCompletionRequests()
{this._ongoingCompletionRequests++;}
_decrementOngoingCompletionRequests()
{this._ongoingCompletionRequests--;if(this._ongoingCompletionRequests<=0)
WI.runtimeManager.activeExecutionContext.target.RuntimeAgent.releaseObjectGroup("completion");}
_clearLastProperties()
{if(this._clearLastPropertiesTimeout){clearTimeout(this._clearLastPropertiesTimeout);delete this._clearLastPropertiesTimeout;}

this._lastPropertyNames=null;}};WI.LayerTreeManager=class LayerTreeManager extends WI.Object
{constructor()
{super();this._showPaintRects=false;this._compositingBordersVisible=false;} 
initializeTarget(target)
{if(target.hasDomain("LayerTree"))
target.LayerTreeAgent.enable();if(target.hasDomain("Page")){if(target.hasCommand("Page.setShowPaintRects")&&this._showPaintRects)
target.PageAgent.setShowPaintRects(this._showPaintRects);if(this._compositingBordersVisible){if(target.hasCommand("Page.overrideSetting")&&InspectorBackend.Enum.Page.Setting.ShowDebugBorders&&InspectorBackend.Enum.Page.Setting.ShowRepaintCounter){target.PageAgent.overrideSetting(InspectorBackend.Enum.Page.Setting.ShowDebugBorders,this._compositingBordersVisible);target.PageAgent.overrideSetting(InspectorBackend.Enum.Page.Setting.ShowRepaintCounter,this._compositingBordersVisible);}else if(target.hasCommand("Page.setCompositingBordersVisible"))
target.PageAgent.setCompositingBordersVisible(this._compositingBordersVisible);}}} 
static supportsShowingPaintRects()
{return InspectorBackend.hasCommand("Page.setShowPaintRects");}
static supportsVisibleCompositingBorders()
{return InspectorBackend.hasCommand("Page.setCompositingBordersVisible")||(InspectorBackend.hasCommand("Page.overrideSetting")&&InspectorBackend.Enum.Page.Setting.ShowDebugBorders&&InspectorBackend.Enum.Page.Setting.ShowRepaintCounter);} 
get supported()
{return InspectorBackend.hasDomain("LayerTree");}
get showPaintRects()
{return this._showPaintRects;}
set showPaintRects(showPaintRects)
{if(this._showPaintRects===showPaintRects)
return;this._showPaintRects=showPaintRects;for(let target of WI.targets){if(target.hasCommand("Page.setShowPaintRects"))
target.PageAgent.setShowPaintRects(this._showPaintRects);}
this.dispatchEventToListeners(LayerTreeManager.Event.ShowPaintRectsChanged);}
get compositingBordersVisible()
{return this._compositingBordersVisible;}
set compositingBordersVisible(compositingBordersVisible)
{if(this._compositingBordersVisible===compositingBordersVisible)
return;this._compositingBordersVisible=compositingBordersVisible;for(let target of WI.targets){if(target.hasCommand("Page.overrideSetting")&&InspectorBackend.Enum.Page.Setting.ShowDebugBorders&&InspectorBackend.Enum.Page.Setting.ShowRepaintCounter){target.PageAgent.overrideSetting(InspectorBackend.Enum.Page.Setting.ShowDebugBorders,this._compositingBordersVisible);target.PageAgent.overrideSetting(InspectorBackend.Enum.Page.Setting.ShowRepaintCounter,this._compositingBordersVisible);}else if(target.hasCommand("Page.setCompositingBordersVisible"))
target.PageAgent.setCompositingBordersVisible(this._compositingBordersVisible);}
this.dispatchEventToListeners(LayerTreeManager.Event.CompositingBordersVisibleChanged);}
updateCompositingBordersVisibleFromPageIfNeeded()
{if(!WI.targetsAvailable()){WI.whenTargetsAvailable().then(()=>{this.updateCompositingBordersVisibleFromPageIfNeeded();});return;}
let target=WI.assumingMainTarget();if(!target.hasCommand("Page.getCompositingBordersVisible"))
return;target.PageAgent.getCompositingBordersVisible((error,compositingBordersVisible)=>{if(error){WI.reportInternalError(error);return;}
this.compositingBordersVisible=compositingBordersVisible;});}
layerTreeMutations(previousLayers,newLayers)
{if(isEmptyObject(previousLayers))
return{preserved:[],additions:newLayers,removals:[]};let previousLayerIds=new Set;let newLayerIds=new Set;let preserved=[];let additions=[];for(let layer of previousLayers)
previousLayerIds.add(layer.layerId);for(let layer of newLayers){newLayerIds.add(layer.layerId);if(previousLayerIds.has(layer.layerId))
preserved.push(layer);else
additions.push(layer);}
let removals=previousLayers.filter((layer)=>!newLayerIds.has(layer.layerId));return{preserved,additions,removals};}
layersForNode(node,callback)
{let target=WI.assumingMainTarget();target.LayerTreeAgent.layersForNode(node.id,(error,layers)=>{callback(error?[]:layers.map(WI.Layer.fromPayload));});}
reasonsForCompositingLayer(layer,callback)
{let target=WI.assumingMainTarget();target.LayerTreeAgent.reasonsForCompositingLayer(layer.layerId,function(error,reasons){callback(error?0:reasons);});} 
layerTreeDidChange()
{this.dispatchEventToListeners(WI.LayerTreeManager.Event.LayerTreeDidChange);}};WI.LayerTreeManager.Event={ShowPaintRectsChanged:"show-paint-rects-changed",CompositingBordersVisibleChanged:"compositing-borders-visible-changed",LayerTreeDidChange:"layer-tree-did-change",};WI.MemoryManager=class MemoryManager extends WI.Object
{constructor()
{super();this._enabled=false;} 
get domains(){return["Memory"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Memory"))
target.MemoryAgent.enable();} 
enable()
{if(this._enabled)
return;this._enabled=true;for(let target of WI.targets)
this.initializeTarget(target);}
disable()
{if(!this._enabled)
return;for(let target of WI.targets){if(target.hasDomain("Memory"))
target.MemoryAgent.disable();}
this._enabled=false;} 
memoryPressure(timestamp,protocolSeverity)
{if(!this._enabled)
return;let memoryPressureEvent=WI.MemoryPressureEvent.fromPayload(timestamp,protocolSeverity);this.dispatchEventToListeners(WI.MemoryManager.Event.MemoryPressure,{memoryPressureEvent});}};WI.MemoryManager.Event={MemoryPressure:"memory-manager-memory-pressure",};WI.NetworkManager=class NetworkManager extends WI.Object
{constructor()
{super();this._frameIdentifierMap=new Map;this._mainFrame=null;this._resourceRequestIdentifierMap=new Map;this._orphanedResources=new Map;this._webSocketIdentifierToURL=new Map;this._waitingForMainFrameResourceTreePayload=true;this._transitioningPageTarget=false;this._sourceMapURLMap=new Map;this._downloadingSourceMaps=new Set;this._localResourceOverrides=[];this._harImportLocalResourceMap=new Set;this._pendingLocalResourceOverrideSaves=null;this._saveLocalResourceOverridesDebouncer=null;this._interceptionEnabled=true; WI.notifications.addEventListener(WI.Notification.ExtraDomainsActivated,this._extraDomainsActivated,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);if(NetworkManager.supportsOverridingResponses()){WI.Resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._handleResourceContentChangedForLocalResourceOverride,this);WI.Resource.addEventListener(WI.Resource.Event.RequestDataDidChange,this._handleResourceContentChangedForLocalResourceOverride,this);WI.LocalResourceOverride.addEventListener(WI.LocalResourceOverride.Event.DisabledChanged,this._handleResourceOverrideDisabledChanged,this);WI.Target.registerInitializationPromise((async()=>{let serializedLocalResourceOverrides=await WI.objectStores.localResourceOverrides.getAll();this._restoringLocalResourceOverrides=true;for(let serializedLocalResourceOverride of serializedLocalResourceOverrides){let localResourceOverride=WI.LocalResourceOverride.fromJSON(serializedLocalResourceOverride);let supported=false;switch(localResourceOverride.type){case WI.LocalResourceOverride.InterceptType.Request:supported=WI.NetworkManager.supportsOverridingRequests();break;case WI.LocalResourceOverride.InterceptType.Response:supported=WI.NetworkManager.supportsOverridingResponses();break;case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:supported=WI.NetworkManager.supportsOverridingRequestsWithResponses();break;}
if(!supported)
continue;const key=null;WI.objectStores.localResourceOverrides.associateObject(localResourceOverride,key,serializedLocalResourceOverride);this.addLocalResourceOverride(localResourceOverride);}
this._restoringLocalResourceOverrides=false;})());}
this._bootstrapScript=null;if(NetworkManager.supportsBootstrapScript()){this._bootstrapScriptEnabledSetting=new WI.Setting("bootstrap-script-enabled",true);WI.Target.registerInitializationPromise((async()=>{let bootstrapScriptSource=await WI.objectStores.general.get(NetworkManager.bootstrapScriptSourceObjectStoreKey);if(bootstrapScriptSource!==undefined)
this.createBootstrapScript(bootstrapScriptSource);})());}} 
static supportsShowCertificate()
{return InspectorFrontendHost.supportsShowCertificate&&InspectorBackend.hasCommand("Network.getSerializedCertificate");}
static supportsOverridingRequests()
{return InspectorBackend.hasCommand("Network.interceptWithRequest");}
static supportsOverridingRequestsWithResponses()
{return InspectorBackend.hasCommand("Network.interceptRequestWithResponse");}
static supportsOverridingResponses()
{return InspectorBackend.hasCommand("Network.interceptWithResponse");}
static supportsBootstrapScript()
{return InspectorBackend.hasCommand("Page.setBootstrapScript");}
static get bootstrapScriptURL()
{return"web-inspector://bootstrap.js";}
static get bootstrapScriptSourceObjectStoreKey()
{return"bootstrap-script-source";}
static synthesizeImportError(message)
{message=WI.UIString("HAR Import Error: %s").format(message);if(window.InspectorTest){console.error(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} 
initializeTarget(target)
{if(target.hasDomain("Page")){target.PageAgent.enable();target.PageAgent.getResourceTree(this._processMainFrameResourceTreePayload.bind(this));if(target.hasCommand("Page.setBootstrapScript")&&this._bootstrapScript&&this._bootstrapScriptEnabledSetting.value)
target.PageAgent.setBootstrapScript(this._bootstrapScript.content);}
if(target.hasDomain("ServiceWorker"))
target.ServiceWorkerAgent.getInitializationInfo(this._processServiceWorkerConfiguration.bind(this));if(target.hasDomain("Network")){target.NetworkAgent.enable();if(target.hasCommand("Network.setResourceCachingDisabled"))
target.NetworkAgent.setResourceCachingDisabled(WI.settings.resourceCachingDisabled.value);if(target.hasCommand("Network.setInterceptionEnabled")){if(this._interceptionEnabled)
target.NetworkAgent.setInterceptionEnabled(this._interceptionEnabled);for(let localResourceOverride of this._localResourceOverrides){if(!localResourceOverride.disabled)
this._addInterception(localResourceOverride,target);}}}
if(target.type===WI.TargetType.Worker)
this.adoptOrphanedResourcesForTarget(target);}
transitionPageTarget()
{this._transitioningPageTarget=true;this._waitingForMainFrameResourceTreePayload=true;} 
get mainFrame(){return this._mainFrame;}
get localResourceOverrides(){return this._localResourceOverrides;}
get bootstrapScript(){return this._bootstrapScript;}
get frames()
{return Array.from(this._frameIdentifierMap.values());}
get interceptionEnabled()
{return this._interceptionEnabled;}
set interceptionEnabled(enabled)
{if(this._interceptionEnabled===enabled)
return;this._interceptionEnabled=enabled;for(let target of WI.targets){if(target.hasCommand("Network.setInterceptionEnabled"))
target.NetworkAgent.setInterceptionEnabled(this._interceptionEnabled);}}
frameForIdentifier(frameId)
{return this._frameIdentifierMap.get(frameId)||null;}
resourceForRequestIdentifier(requestIdentifier)
{return this._resourceRequestIdentifierMap.get(requestIdentifier)||null;}
downloadSourceMap(sourceMapURL,baseURL,originalSourceCode)
{if(!WI.settings.sourceMapsEnabled.value)
return;
if(WI.networkManager.mainFrame)
baseURL=absoluteURL(baseURL,WI.networkManager.mainFrame.url);if(sourceMapURL.startsWith("data:")){this._loadAndParseSourceMap(sourceMapURL,baseURL,originalSourceCode);return;}
sourceMapURL=absoluteURL(sourceMapURL,baseURL);if(!sourceMapURL)
return;if(!originalSourceCode.url)
return; if(this._sourceMapURLMap.has(sourceMapURL)||this._downloadingSourceMaps.has(sourceMapURL))
return;let loadAndParseSourceMap=()=>{this._loadAndParseSourceMap(sourceMapURL,baseURL,originalSourceCode);};if(!WI.networkManager.mainFrame){setTimeout(loadAndParseSourceMap,0);return;}
loadAndParseSourceMap();}
get bootstrapScriptEnabled()
{return this._bootstrapScriptEnabledSetting.value;}
set bootstrapScriptEnabled(enabled)
{this._bootstrapScriptEnabledSetting.value=!!enabled;let source=this._bootstrapScriptEnabledSetting.value?this._bootstrapScript.content:undefined;for(let target of WI.targets){if(target.hasCommand("Page.setBootstrapScript"))
target.PageAgent.setBootstrapScript(source);}
this.dispatchEventToListeners(NetworkManager.Event.BootstrapScriptEnabledChanged,{bootstrapScript:this._bootstrapScript});}
async createBootstrapScript(source)
{if(this._bootstrapScript)
return;if(!arguments.length)
source=await WI.objectStores.general.get(NetworkManager.bootstrapScriptSourceObjectStoreKey);if(!source){source=`
/*
 * ${WI.UIString("The Inspector Bootstrap Script is guaranteed to be the first script evaluated in any page, as well as any sub-frames.")}
 * ${WI.UIString("It is evaluated immediately after the global object is created, before any other content has loaded.")}
 * 
 * ${WI.UIString("Modifications made here will take effect on the next load of any page or sub-frame.")}
 * ${WI.UIString("The contents and enabled state will be preserved across Web Inspector sessions.")}
 * 
 * ${WI.UIString("Some examples of ways to use this script include (but are not limited to):")}
 *  - ${WI.UIString("overriding built-in functions to log call traces or add %s statements").format(WI.unlocalizedString("`debugger`"))}
 *  - ${WI.UIString("ensuring that common debugging functions are available on every page via the Console")}
 * 
 * ${WI.UIString("More information is available at <https://webkit.org/web-inspector/inspector-bootstrap-script/>.")}
 */
`.trimStart();}
const target=null;const url=null;const sourceURL=NetworkManager.bootstrapScriptURL;this._bootstrapScript=new WI.LocalScript(target,url,sourceURL,WI.Script.SourceType.Program,source,{injected:true,editable:true});this._bootstrapScript.addEventListener(WI.SourceCode.Event.ContentDidChange,this._handleBootstrapScriptContentDidChange,this);this._handleBootstrapScriptContentDidChange();this.dispatchEventToListeners(NetworkManager.Event.BootstrapScriptCreated,{bootstrapScript:this._bootstrapScript});}
destroyBootstrapScript()
{if(!this._bootstrapScript)
return;let bootstrapScript=this._bootstrapScript;this._bootstrapScript=null;WI.objectStores.general.delete(NetworkManager.bootstrapScriptSourceObjectStoreKey);for(let target of WI.targets){if(target.hasCommand("Page.setBootstrapScript"))
target.PageAgent.setBootstrapScript();}
this.dispatchEventToListeners(NetworkManager.Event.BootstrapScriptDestroyed,{bootstrapScript});}
addLocalResourceOverride(localResourceOverride)
{this._localResourceOverrides.push(localResourceOverride);if(!this._restoringLocalResourceOverrides)
WI.objectStores.localResourceOverrides.putObject(localResourceOverride);if(!localResourceOverride.disabled)
this._addInterception(localResourceOverride);this.dispatchEventToListeners(WI.NetworkManager.Event.LocalResourceOverrideAdded,{localResourceOverride});}
removeLocalResourceOverride(localResourceOverride)
{if(!this._localResourceOverrides.remove(localResourceOverride)){return;}
if(this._pendingLocalResourceOverrideSaves)
this._pendingLocalResourceOverrideSaves.delete(localResourceOverride);if(!this._restoringLocalResourceOverrides)
WI.objectStores.localResourceOverrides.deleteObject(localResourceOverride);if(!localResourceOverride.disabled)
this._removeInterception(localResourceOverride);this.dispatchEventToListeners(WI.NetworkManager.Event.LocalResourceOverrideRemoved,{localResourceOverride});}
localResourceOverridesForURL(url)
{const rankFunctions=[(localResourceOverride)=>localResourceOverride.isCaseSensitive&&!localResourceOverride.isRegex,(localResourceOverride)=>!localResourceOverride.isCaseSensitive&&!localResourceOverride.isRegex,(localResourceOverride)=>localResourceOverride.isCaseSensitive&&localResourceOverride.isRegex,(localResourceOverride)=>!localResourceOverride.isCaseSensitive&&localResourceOverride.isRegex,];return this._localResourceOverrides.filter((localResourceOverride)=>localResourceOverride.matches(url)).sort((a,b)=>{let aRank=rankFunctions.findIndex((rankFunction)=>rankFunction(a));let bRank=rankFunctions.findIndex((rankFunction)=>rankFunction(b));return aRank-bRank;});}
canBeOverridden(resource)
{if(!(resource instanceof WI.Resource))
return false;if(resource instanceof WI.SourceMapResource)
return false;if(resource.localResourceOverride)
return false;const schemes=["http:","https:","file:"];if(!schemes.some((scheme)=>resource.url.startsWith(scheme)))
return false;if(this.localResourceOverridesForURL(resource.url).length)
return false;switch(resource.type){case WI.Resource.Type.Document:case WI.Resource.Type.StyleSheet:case WI.Resource.Type.Script:case WI.Resource.Type.XHR:case WI.Resource.Type.Fetch:case WI.Resource.Type.Image:case WI.Resource.Type.Font:case WI.Resource.Type.Other:break;case WI.Resource.Type.Ping:case WI.Resource.Type.Beacon:return false;case WI.Resource.Type.WebSocket:return false;}
return true;}
resourcesForURL(url)
{let resources=new Set;if(this._mainFrame){if(this._mainFrame.mainResource.url===url)
resources.add(this._mainFrame.mainResource);const recursivelySearchChildFrames=true;resources.addAll(this._mainFrame.resourcesForURL(url,recursivelySearchChildFrames));}
return resources;}
adoptOrphanedResourcesForTarget(target)
{let resources=this._orphanedResources.take(target.identifier);if(!resources)
return;for(let resource of resources)
target.adoptResource(resource);}
processHAR({json,error})
{if(error){WI.NetworkManager.synthesizeImportError(error);return null;}
if(typeof json!=="object"||json===null){WI.NetworkManager.synthesizeImportError(WI.UIString("invalid JSON"));return null;}
if(typeof json.log!=="object"||typeof json.log.version!=="string"){WI.NetworkManager.synthesizeImportError(WI.UIString("invalid HAR"));return null;}
if(json.log.version!=="1.2"){WI.NetworkManager.synthesizeImportError(WI.UIString("unsupported HAR version"));return null;}
if(!Array.isArray(json.log.entries)||!Array.isArray(json.log.pages)||!json.log.pages[0]||!json.log.pages[0].startedDateTime){WI.NetworkManager.synthesizeImportError(WI.UIString("invalid HAR"));return null;}
let mainResourceSentWalltime=WI.HARBuilder.dateFromHARDate(json.log.pages[0].startedDateTime)/1000;if(isNaN(mainResourceSentWalltime)){WI.NetworkManager.synthesizeImportError(WI.UIString("invalid HAR"));return null;}
let localResources=[];for(let entry of json.log.entries){let localResource=WI.LocalResource.fromHAREntry(entry,mainResourceSentWalltime);this._harImportLocalResourceMap.add(localResource);localResources.push(localResource);}
return localResources;} 
frameDidNavigate(framePayload)
{if(this._waitingForMainFrameResourceTreePayload)
return;var frameWasLoadedInstantly=false;var frame=this.frameForIdentifier(framePayload.id);if(!frame){

let resourceOptions={loaderIdentifier:framePayload.loaderId,};let frameOptions={name:framePayload.name,securityOrigin:framePayload.securityOrigin,};let frameResource=this._addNewResourceToFrameOrTarget(framePayload.url,framePayload.id,resourceOptions,frameOptions);frame=frameResource.parentFrame;frameWasLoadedInstantly=true;if(!frame)
return;}
if(framePayload.loaderId===frame.provisionalLoaderIdentifier){frame.commitProvisionalLoad(framePayload.securityOrigin);}else{let mainResource=null;if(frame.mainResource.url!==framePayload.url||frame.loaderIdentifier!==framePayload.loaderId){mainResource=new WI.Resource(framePayload.url,{mimeType:framePayload.mimeType,loaderIdentifier:framePayload.loaderId,});}else{mainResource=frame.mainResource;}
frame.initialize(framePayload.name,framePayload.securityOrigin,framePayload.loaderId,mainResource);}
var oldMainFrame=this._mainFrame;if(framePayload.parentId){var parentFrame=this.frameForIdentifier(framePayload.parentId);if(frame===this._mainFrame)
this._mainFrame=null;if(frame.parentFrame!==parentFrame)
parentFrame.addChildFrame(frame);}else{if(frame.parentFrame)
frame.parentFrame.removeChildFrame(frame);this._mainFrame=frame;}
if(this._mainFrame!==oldMainFrame)
this._mainFrameDidChange(oldMainFrame);if(frameWasLoadedInstantly)
frame.mainResource.markAsFinished();}
frameDidDetach(frameId)
{if(this._waitingForMainFrameResourceTreePayload)
return;var frame=this.frameForIdentifier(frameId);if(!frame)
return;if(frame.parentFrame)
frame.parentFrame.removeChildFrame(frame);this._frameIdentifierMap.delete(frame.id);var oldMainFrame=this._mainFrame;if(frame===this._mainFrame)
this._mainFrame=null;frame.clearExecutionContexts();this.dispatchEventToListeners(WI.NetworkManager.Event.FrameWasRemoved,{frame});if(this._mainFrame!==oldMainFrame)
this._mainFrameDidChange(oldMainFrame);} 
resourceRequestWillBeSent(requestIdentifier,frameIdentifier,loaderIdentifier,request,type,redirectResponse,timestamp,walltime,initiator,targetId)
{if(this._waitingForMainFrameResourceTreePayload)
return;var elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);if(resource){resource.updateForRedirectResponse(request,redirectResponse,elapsedTime,walltime);return;}
resource=this._addNewResourceToFrameOrTarget(request.url,frameIdentifier,{type,loaderIdentifier,targetId,requestIdentifier,requestMethod:request.method,requestHeaders:request.headers,requestData:request.postData,requestSentTimestamp:elapsedTime,requestSentWalltime:walltime,initiatorCallFrames:this._initiatorCallFramesFromPayload(initiator),initiatorSourceCodeLocation:this._initiatorSourceCodeLocationFromPayload(initiator),initiatorNode:this._initiatorNodeFromPayload(initiator),});this._resourceRequestIdentifierMap.set(requestIdentifier,resource);}
webSocketCreated(requestId,url)
{this._webSocketIdentifierToURL.set(requestId,url);}
webSocketWillSendHandshakeRequest(requestId,timestamp,walltime,request)
{let url=this._webSocketIdentifierToURL.get(requestId);if(!url)
return;if(!InspectorBackend.hasEvent("Network.webSocketWillSendHandshakeRequest","walltime")){request=arguments[2];walltime=NaN;} 
let resource=new WI.WebSocketResource(url,{loaderIdentifier:WI.networkManager.mainFrame.id,requestIdentifier:requestId,requestHeaders:request.headers,timestamp,walltime,requestSentTimestamp:WI.timelineManager.computeElapsedTime(timestamp),});let frame=this.frameForIdentifier(WI.networkManager.mainFrame.id);frame.addResource(resource);this._resourceRequestIdentifierMap.set(requestId,resource);}
webSocketHandshakeResponseReceived(requestId,timestamp,response)
{let resource=this._resourceRequestIdentifierMap.get(requestId);if(!resource)
return;resource.readyState=WI.WebSocketResource.ReadyState.Open;let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp); let responseTiming=response.timing||null;resource.updateForResponse(resource.url,resource.mimeType,resource.type,response.headers,response.status,response.statusText,elapsedTime,responseTiming);resource.markAsFinished(elapsedTime);}
webSocketFrameReceived(requestId,timestamp,response)
{this._webSocketFrameReceivedOrSent(requestId,timestamp,response);}
webSocketFrameSent(requestId,timestamp,response)
{this._webSocketFrameReceivedOrSent(requestId,timestamp,response);}
webSocketClosed(requestId,timestamp)
{let resource=this._resourceRequestIdentifierMap.get(requestId);if(!resource)
return;resource.readyState=WI.WebSocketResource.ReadyState.Closed;let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);resource.markAsFinished(elapsedTime);this._webSocketIdentifierToURL.delete(requestId);this._resourceRequestIdentifierMap.delete(requestId);}
_webSocketFrameReceivedOrSent(requestId,timestamp,response)
{let resource=this._resourceRequestIdentifierMap.get(requestId);if(!resource)
return;let isOutgoing=!!response.mask;let{payloadData,payloadLength,opcode}=response;let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);resource.addFrame(payloadData,payloadLength,isOutgoing,opcode,timestamp,elapsedTime);}
markResourceRequestAsServedFromMemoryCache(requestIdentifier)
{if(this._waitingForMainFrameResourceTreePayload)
return;let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);
if(!resource)
return;resource.legacyMarkServedFromMemoryCache();}
resourceRequestWasServedFromMemoryCache(requestIdentifier,frameIdentifier,loaderIdentifier,cachedResourcePayload,timestamp,initiator)
{if(this._waitingForMainFrameResourceTreePayload)
return;let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);let response=cachedResourcePayload.response;const responseSource=InspectorBackend.Enum.Network.ResponseSource.MemoryCache;let resource=this._addNewResourceToFrameOrTarget(cachedResourcePayload.url,frameIdentifier,{type:cachedResourcePayload.type,loaderIdentifier,requestIdentifier,requestMethod:"GET",requestSentTimestamp:elapsedTime,initiatorCallFrames:this._initiatorCallFramesFromPayload(initiator),initiatorSourceCodeLocation:this._initiatorSourceCodeLocationFromPayload(initiator),initiatorNode:this._initiatorNodeFromPayload(initiator),});resource.updateForResponse(cachedResourcePayload.url,response.mimeType,cachedResourcePayload.type,response.headers,response.status,response.statusText,elapsedTime,response.timing,responseSource,response.security);resource.increaseSize(cachedResourcePayload.bodySize,elapsedTime);resource.increaseTransferSize(cachedResourcePayload.bodySize);resource.setCachedResponseBodySize(cachedResourcePayload.bodySize);resource.markAsFinished(elapsedTime);if(cachedResourcePayload.sourceMapURL)
this.downloadSourceMap(cachedResourcePayload.sourceMapURL,resource.url,resource);
}
resourceRequestDidReceiveResponse(requestIdentifier,frameIdentifier,loaderIdentifier,type,response,timestamp)
{if(this._waitingForMainFrameResourceTreePayload)
return;var elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);
if(!resource){var frame=this.frameForIdentifier(frameIdentifier);if(frame)
resource=frame.resourcesForURL(response.url).firstValue;if(resource){this._resourceRequestIdentifierMap.set(requestIdentifier,resource);resource.revertMarkAsFinished();}}

if(!resource){resource=this._addNewResourceToFrameOrTarget(response.url,frameIdentifier,{type,loaderIdentifier,requestIdentifier,requestHeaders:response.requestHeaders,requestSentTimestamp:elapsedTime,});this._resourceRequestIdentifierMap.set(requestIdentifier,resource);}
if(response.fromDiskCache)
resource.legacyMarkServedFromDiskCache();resource.updateForResponse(response.url,response.mimeType,type,response.headers,response.status,response.statusText,elapsedTime,response.timing,response.source,response.security);}
resourceRequestDidReceiveData(requestIdentifier,dataLength,encodedDataLength,timestamp)
{if(this._waitingForMainFrameResourceTreePayload)
return;let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);var elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);
if(!resource)
return;resource.increaseSize(dataLength,elapsedTime);if(encodedDataLength!==-1)
resource.increaseTransferSize(encodedDataLength);}
resourceRequestDidFinishLoading(requestIdentifier,timestamp,sourceMapURL,metrics)
{if(this._waitingForMainFrameResourceTreePayload)
return;
let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);if(!resource)
return;if(metrics)
resource.updateWithMetrics(metrics);let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);resource.markAsFinished(elapsedTime);if(sourceMapURL)
this.downloadSourceMap(sourceMapURL,resource.url,resource);this._resourceRequestIdentifierMap.delete(requestIdentifier);}
resourceRequestDidFailLoading(requestIdentifier,canceled,timestamp,errorText)
{if(this._waitingForMainFrameResourceTreePayload)
return;
let resource=this._resourceRequestIdentifierMap.get(requestIdentifier);if(!resource)
return;let elapsedTime=WI.timelineManager.computeElapsedTime(timestamp);resource.markAsFailed(canceled,elapsedTime,errorText);if(resource.parentFrame&&resource===resource.parentFrame.provisionalMainResource)
resource.parentFrame.clearProvisionalLoad();this._resourceRequestIdentifierMap.delete(requestIdentifier);}
requestIntercepted(target,requestId,request)
{let url=WI.urlWithoutFragment(request.url);for(let localResourceOverride of this.localResourceOverridesForURL(url)){if(localResourceOverride.disabled)
continue;let localResource=localResourceOverride.localResource;let revision=localResource.currentRevision;switch(localResourceOverride.type){case WI.LocalResourceOverride.InterceptType.Request:{target.NetworkAgent.interceptWithRequest.invoke({requestId,url:localResource.url||undefined,method:localResource.requestMethod??undefined,headers:localResource.requestHeaders,postData:(WI.HTTPUtilities.RequestMethodsWithBody.has(localResource.requestMethod)&&localResource.requestData)?btoa(localResource.requestData):undefined,});return;}
case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:target.NetworkAgent.interceptRequestWithResponse.invoke({requestId,content:revision.content,base64Encoded:!!revision.base64Encoded,mimeType:revision.mimeType??undefined,status:!isNaN(localResource.statusCode)?localResource.statusCode:200,statusText:!isNaN(localResource.statusCode)?(localResource.statusText??""):WI.HTTPUtilities.statusTextForStatusCode(200),headers:localResource.responseHeaders,});return;}}


target.NetworkAgent.interceptContinue.invoke({requestId,stage:InspectorBackend.Enum.Network.NetworkStage.Request,});}
responseIntercepted(target,requestId,response)
{let url=WI.urlWithoutFragment(response.url);for(let localResourceOverride of this.localResourceOverridesForURL(url)){if(localResourceOverride.disabled)
continue;let localResource=localResourceOverride.localResource;let revision=localResource.currentRevision;switch(localResourceOverride.type){case WI.LocalResourceOverride.InterceptType.Response:target.NetworkAgent.interceptWithResponse.invoke({requestId,content:revision.content,base64Encoded:!!revision.base64Encoded,mimeType:revision.mimeType??undefined,status:!isNaN(localResource.statusCode)?localResource.statusCode:undefined,statusText:!isNaN(localResource.statusCode)?(localResource.statusText??""):undefined,headers:localResource.responseHeaders,});return;}}


target.NetworkAgent.interceptContinue.invoke({requestId,stage:InspectorBackend.Enum.Network.NetworkStage.Response,});} 
executionContextCreated(payload)
{let frame=this.frameForIdentifier(payload.frameId);if(!frame)
return;let type=WI.ExecutionContext.typeFromPayload(payload);let target=frame.mainResource.target;let executionContext=new WI.ExecutionContext(target,payload.id,type,payload.name,frame);frame.addExecutionContext(executionContext);} 
_addNewResourceToFrameOrTarget(url,frameIdentifier,resourceOptions={},frameOptions={})
{let resource=null;if(!frameIdentifier&&resourceOptions.targetId){resource=new WI.Resource(url,resourceOptions);resource.target.addResource(resource);return resource;}
let frame=this.frameForIdentifier(frameIdentifier);if(frame){if(resourceOptions.type===InspectorBackend.Enum.Page.ResourceType.Document&&frame.provisionalMainResource&&frame.provisionalMainResource.url===url&&frame.provisionalLoaderIdentifier===resourceOptions.loaderIdentifier)
resource=frame.provisionalMainResource;else{resource=new WI.Resource(url,resourceOptions);if(resource.target===WI.pageTarget)
this._addResourceToFrame(frame,resource);else if(resource.target)
resource.target.addResource(resource);else
this._addOrphanedResource(resource,resourceOptions.targetId);}}else{resource=new WI.Resource(url,resourceOptions);frame=new WI.Frame(frameIdentifier,frameOptions.name,frameOptions.securityOrigin,resourceOptions.loaderIdentifier,resource);this._frameIdentifierMap.set(frame.id,frame);
if(!this._mainFrame){this._mainFrame=frame;this._mainFrameDidChange(null);}
this._dispatchFrameWasAddedEvent(frame);}
return resource;}
_addResourceToFrame(frame,resource)
{if(this._waitingForMainFrameResourceTreePayload)
return;if(resource.loaderIdentifier!==frame.loaderIdentifier&&!frame.provisionalLoaderIdentifier){frame.startProvisionalLoad(resource);return;}
frame.addResource(resource);}
_addResourceToTarget(target,resource)
{target.addResource(resource);}
_initiatorCallFramesFromPayload(initiatorPayload)
{if(!initiatorPayload)
return null;let callFrames=initiatorPayload.stackTrace;if(!callFrames)
return null;return callFrames.map((payload)=>WI.CallFrame.fromPayload(WI.assumingMainTarget(),payload));}
_initiatorSourceCodeLocationFromPayload(initiatorPayload)
{if(!initiatorPayload)
return null;var url=null;var lineNumber=NaN;var columnNumber=0;if(initiatorPayload.stackTrace&&initiatorPayload.stackTrace.length){var stackTracePayload=initiatorPayload.stackTrace;for(var i=0;i<stackTracePayload.length;++i){var callFramePayload=stackTracePayload[i];if(!callFramePayload.url||callFramePayload.url==="[native code]")
continue;url=callFramePayload.url;lineNumber=callFramePayload.lineNumber-1;columnNumber=callFramePayload.columnNumber;break;}}else if(initiatorPayload.url){url=initiatorPayload.url;lineNumber=initiatorPayload.lineNumber-1;}
if(!url||isNaN(lineNumber)||lineNumber<0)
return null;let sourceCode=WI.networkManager.resourcesForURL(url).firstValue;if(!sourceCode)
sourceCode=WI.debuggerManager.scriptsForURL(url,WI.mainTarget)[0];if(!sourceCode)
return null;return sourceCode.createSourceCodeLocation(lineNumber,columnNumber);}
_initiatorNodeFromPayload(initiatorPayload)
{return WI.domManager.nodeForId(initiatorPayload.nodeId);}
_processServiceWorkerConfiguration(error,initializationPayload)
{this._waitingForMainFrameResourceTreePayload=false;if(error){console.error(JSON.stringify(error));return;}
WI.mainTarget.identifier=initializationPayload.targetId;WI.mainTarget.name=initializationPayload.url;const sourceURL=null;const sourceType=WI.Script.SourceType.Program;let script=new WI.LocalScript(WI.mainTarget,initializationPayload.url,sourceURL,sourceType,initializationPayload.content);WI.mainTarget.mainResource=script;InspectorBackend.runAfterPendingDispatches(()=>{if(WI.mainTarget.mainResource===script){WI.debuggerManager.dataForTarget(WI.mainTarget).addScript(script);WI.debuggerManager.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptAdded,{script});}});}
_processMainFrameResourceTreePayload(error,mainFramePayload)
{this._waitingForMainFrameResourceTreePayload=false;if(error){console.error(JSON.stringify(error));return;}
this._resourceRequestIdentifierMap=new Map;this._frameIdentifierMap=new Map;var oldMainFrame=this._mainFrame;this._mainFrame=this._addFrameTreeFromFrameResourceTreePayload(mainFramePayload,true);if(this._mainFrame!==oldMainFrame)
this._mainFrameDidChange(oldMainFrame);if(this._transitioningPageTarget){this._transitioningPageTarget=false;this._mainFrame._dispatchMainResourceDidChangeEvent(oldMainFrame.mainResource);}}
_createFrame(payload)
{
let mainResource=new WI.Resource(payload.url||"about:blank",{mimeType:payload.mimeType,loaderIdentifier:payload.loaderId,});var frame=new WI.Frame(payload.id,payload.name,payload.securityOrigin,payload.loaderId,mainResource);this._frameIdentifierMap.set(frame.id,frame);mainResource.markAsFinished();return frame;}
_createResource(payload,framePayload)
{let resource=new WI.Resource(payload.url,{mimeType:payload.mimeType,type:payload.type,loaderIdentifier:framePayload.loaderId,targetId:payload.targetId,});if(payload.sourceMapURL)
this.downloadSourceMap(payload.sourceMapURL,resource.url,resource);return resource;}
_addFrameTreeFromFrameResourceTreePayload(payload,isMainFrame)
{var frame=this._createFrame(payload.frame);if(isMainFrame)
frame.markAsMainFrame();for(var i=0;payload.childFrames&&i<payload.childFrames.length;++i)
frame.addChildFrame(this._addFrameTreeFromFrameResourceTreePayload(payload.childFrames[i],false));for(var i=0;payload.resources&&i<payload.resources.length;++i){var resourcePayload=payload.resources[i];

if(resourcePayload.type==="Document"&&resourcePayload.url===payload.frame.url)
continue;var resource=this._createResource(resourcePayload,payload);if(resource.target===WI.pageTarget)
frame.addResource(resource);else if(resource.target)
resource.target.addResource(resource);else
this._addOrphanedResource(resource,resourcePayload.targetId);if(resourcePayload.failed||resourcePayload.canceled)
resource.markAsFailed(resourcePayload.canceled);else
resource.markAsFinished();}
this._dispatchFrameWasAddedEvent(frame);return frame;}
_addOrphanedResource(resource,targetId)
{let resources=this._orphanedResources.get(targetId);if(!resources){resources=[];this._orphanedResources.set(targetId,resources);}
resources.push(resource);}
_commandArgumentsForInterception(localResourceOverride)
{return{url:localResourceOverride.url,stage:localResourceOverride.type===WI.LocalResourceOverride.InterceptType.Response?InspectorBackend.Enum.Network.NetworkStage.Response:InspectorBackend.Enum.Network.NetworkStage.Request,caseSensitive:localResourceOverride.isCaseSensitive,isRegex:localResourceOverride.isRegex,};}
_addInterception(localResourceOverride,specificTarget)
{let targets=specificTarget?[specificTarget]:WI.targets;for(let target of targets){if(!target.hasCommand("Network.addInterception"))
continue;target.NetworkAgent.addInterception.invoke(this._commandArgumentsForInterception(localResourceOverride));}}
_removeInterception(localResourceOverride,specificTarget)
{let targets=specificTarget?[specificTarget]:WI.targets;for(let target of targets){if(!target.hasCommand("Network.removeInterception"))
continue;target.NetworkAgent.removeInterception.invoke(this._commandArgumentsForInterception(localResourceOverride));}}
_dispatchFrameWasAddedEvent(frame)
{this.dispatchEventToListeners(WI.NetworkManager.Event.FrameWasAdded,{frame});}
_mainFrameDidChange(oldMainFrame)
{if(oldMainFrame)
oldMainFrame.unmarkAsMainFrame();if(this._mainFrame)
this._mainFrame.markAsMainFrame();this.dispatchEventToListeners(WI.NetworkManager.Event.MainFrameDidChange,{oldMainFrame});}
_loadAndParseSourceMap(sourceMapURL,baseURL,originalSourceCode)
{this._downloadingSourceMaps.add(sourceMapURL);let sourceMapLoaded=(error,content,mimeType,statusCode)=>{if(error||statusCode>=400){this._sourceMapLoadAndParseFailed(sourceMapURL);return;}
if(content.slice(0,3)===")]}"){let firstNewlineIndex=content.indexOf("\n");if(firstNewlineIndex===-1){this._sourceMapLoadAndParseFailed(sourceMapURL);return;}
content=content.substring(firstNewlineIndex);}
try{let payload=JSON.parse(content);let baseURL=sourceMapURL.startsWith("data:")?originalSourceCode.url:sourceMapURL;let sourceMap=new WI.SourceMap(baseURL,payload,originalSourceCode);this._sourceMapLoadAndParseSucceeded(sourceMapURL,sourceMap);}catch{this._sourceMapLoadAndParseFailed(sourceMapURL);}};if(sourceMapURL.startsWith("data:")){let{mimeType,base64,data}=parseDataURL(sourceMapURL);let content=base64?atob(data):data;sourceMapLoaded(null,content,mimeType,0);return;}
let target=WI.assumingMainTarget();if(!target.hasCommand("Network.loadResource")){this._sourceMapLoadAndParseFailed(sourceMapURL);return;}
let frameIdentifier=null;if(originalSourceCode instanceof WI.Resource&&originalSourceCode.parentFrame)
frameIdentifier=originalSourceCode.parentFrame.id;if(!frameIdentifier)
frameIdentifier=WI.networkManager.mainFrame?WI.networkManager.mainFrame.id:"";target.NetworkAgent.loadResource(frameIdentifier,sourceMapURL,sourceMapLoaded);}
_sourceMapLoadAndParseFailed(sourceMapURL)
{this._downloadingSourceMaps.delete(sourceMapURL);}
_sourceMapLoadAndParseSucceeded(sourceMapURL,sourceMap)
{if(!this._downloadingSourceMaps.has(sourceMapURL))
return;this._downloadingSourceMaps.delete(sourceMapURL);this._sourceMapURLMap.set(sourceMapURL,sourceMap);for(let source of sourceMap.sources())
sourceMap.addResource(new WI.SourceMapResource(source,sourceMap));sourceMap.originalSourceCode.addSourceMap(sourceMap);if(!(sourceMap.originalSourceCode instanceof WI.Resource)){let resource=sourceMap.originalSourceCode.resource;if(resource)
resource.addSourceMap(sourceMap);}}
_handleResourceContentChangedForLocalResourceOverride(event)
{let localResourceOverride=event.target.localResourceOverride;if(!localResourceOverride)
return;if(!this._saveLocalResourceOverridesDebouncer){this._pendingLocalResourceOverrideSaves=new Set;this._saveLocalResourceOverridesDebouncer=new Debouncer(()=>{for(let localResourceOverride of this._pendingLocalResourceOverrideSaves){WI.objectStores.localResourceOverrides.putObject(localResourceOverride);}});}
this._pendingLocalResourceOverrideSaves.add(localResourceOverride);this._saveLocalResourceOverridesDebouncer.delayForTime(500);}
_handleResourceOverrideDisabledChanged(event)
{let localResourceOverride=event.target;WI.objectStores.localResourceOverrides.putObject(localResourceOverride);if(localResourceOverride.disabled)
this._removeInterception(localResourceOverride);else
this._addInterception(localResourceOverride);}
_handleBootstrapScriptContentDidChange(event)
{let source=this._bootstrapScript.content||"";WI.objectStores.general.put(source,NetworkManager.bootstrapScriptSourceObjectStoreKey);if(!this._bootstrapScriptEnabledSetting.value)
return;for(let target of WI.targets){if(target.hasCommand("Page.setBootstrapScript"))
target.PageAgent.setBootstrapScript(source);}}
_extraDomainsActivated(event)
{ let target=WI.assumingMainTarget();if(target.hasDomain("Page")&&event.data.domains.includes("Page"))
target.PageAgent.getResourceTree(this._processMainFrameResourceTreePayload.bind(this));}
_handleFrameMainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;this._sourceMapURLMap.clear();this._downloadingSourceMaps.clear();}};WI.NetworkManager.Event={FrameWasAdded:"network-manager-frame-was-added",FrameWasRemoved:"network-manager-frame-was-removed",MainFrameDidChange:"network-manager-main-frame-did-change",BootstrapScriptCreated:"network-manager-bootstrap-script-created",BootstrapScriptEnabledChanged:"network-manager-bootstrap-script-enabled-changed",BootstrapScriptDestroyed:"network-manager-bootstrap-script-destroyed",LocalResourceOverrideAdded:"network-manager-local-resource-override-added",LocalResourceOverrideRemoved:"network-manager-local-resource-override-removed",};WI.OverlayManager=class OverlayManager extends WI.Object
{constructor()
{super();this._gridOverlayForNodeMap=new Map;this._nextDefaultGridColorIndex=0;this._gridColorForNodeMap=new WeakMap;this._gridColorSettingForNodeMap=new WeakMap;WI.settings.gridOverlayShowExtendedGridLines.addEventListener(WI.Setting.Event.Changed,this._handleGridSettingChanged,this);WI.settings.gridOverlayShowLineNames.addEventListener(WI.Setting.Event.Changed,this._handleGridSettingChanged,this);WI.settings.gridOverlayShowLineNumbers.addEventListener(WI.Setting.Event.Changed,this._handleGridSettingChanged,this);WI.settings.gridOverlayShowTrackSizes.addEventListener(WI.Setting.Event.Changed,this._handleGridSettingChanged,this);WI.settings.gridOverlayShowAreaNames.addEventListener(WI.Setting.Event.Changed,this._handleGridSettingChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleMainResourceDidChange,this);} 
showGridOverlay(domNode,{color,initiator}={})
{if(domNode.destroyed)
return;color||=this.getGridColorForNode(domNode);let target=WI.assumingMainTarget();let commandArguments={nodeId:domNode.id,gridColor:color.toProtocol(),showLineNames:WI.settings.gridOverlayShowLineNames.value,showLineNumbers:WI.settings.gridOverlayShowLineNumbers.value,showExtendedGridLines:WI.settings.gridOverlayShowExtendedGridLines.value,showTrackSizes:WI.settings.gridOverlayShowTrackSizes.value,showAreaNames:WI.settings.gridOverlayShowAreaNames.value,};target.DOMAgent.showGridOverlay.invoke(commandArguments);let overlay={domNode,...commandArguments,initiator}; if(!this._gridOverlayForNodeMap.has(domNode))
domNode.addEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);this._gridOverlayForNodeMap.set(domNode,overlay);this.dispatchEventToListeners(WI.OverlayManager.Event.GridOverlayShown,overlay);}
hideGridOverlay(domNode)
{if(domNode.destroyed)
return;let overlay=this._gridOverlayForNodeMap.take(domNode);if(!overlay)
return;let target=WI.assumingMainTarget();target.DOMAgent.hideGridOverlay(domNode.id);domNode.removeEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);this.dispatchEventToListeners(WI.OverlayManager.Event.GridOverlayHidden,overlay);}
hasVisibleGridOverlays()
{return this._gridOverlayForNodeMap.size>0;}
isGridOverlayVisible(domNode)
{return this._gridOverlayForNodeMap.has(domNode);}
toggleGridOverlay(domNode,options)
{if(this.isGridOverlayVisible(domNode))
this.hideGridOverlay(domNode);else
this.showGridOverlay(domNode,options);}
getGridColorForNode(domNode)
{let color=this._gridColorForNodeMap.get(domNode);if(color)
return color;const defaultGridHSLColors=[[329,91,70],[207,96,69],[92,90,64],[291,73,68],[40,97,57],];let colorSetting=this._gridColorSettingForNodeMap.get(domNode);if(!colorSetting){let defaultColor=defaultGridHSLColors[this._nextDefaultGridColorIndex];this._nextDefaultGridColorIndex=(this._nextDefaultGridColorIndex+1)%defaultGridHSLColors.length;let url=domNode.ownerDocument.documentURL||WI.networkManager.mainFrame.url;colorSetting=new WI.Setting(`grid-overlay-color-${url.hash}-${domNode.path().hash}`,defaultColor);this._gridColorSettingForNodeMap.set(domNode,colorSetting);}
color=new WI.Color(WI.Color.Format.HSL,colorSetting.value);this._gridColorForNodeMap.set(domNode,color);return color;}
setGridColorForNode(domNode,color)
{let colorSetting=this._gridColorSettingForNodeMap.get(domNode);colorSetting.value=color.hsl;this._gridColorForNodeMap.set(domNode,color);} 
_handleLayoutContextTypeChanged(event)
{let domNode=event.target;domNode.removeEventListener(WI.DOMNode.Event.LayoutContextTypeChanged,this._handleLayoutContextTypeChanged,this);let overlay=this._gridOverlayForNodeMap.take(domNode);this.dispatchEventToListeners(WI.OverlayManager.Event.GridOverlayHidden,overlay);}
_handleGridSettingChanged(event)
{for(let[domNode,overlay]of this._gridOverlayForNodeMap){this.showGridOverlay(domNode,{color:overlay.color,initiator:overlay.initiator});}}
_handleMainResourceDidChange(event)
{this._nextDefaultGridColorIndex=0;}};WI.OverlayManager.Event={GridOverlayShown:"overlay-manager-grid-overlay-shown",GridOverlayHidden:"overlay-manager-grid-overlay-hidden",};WI.ResourceQueryController=class ResourceQueryController extends WI.Object
{constructor()
{super();this._resourceDataMap=new Map;} 
addResource(resource)
{this._resourceDataMap.set(resource,{});}
removeResource(resource)
{this._resourceDataMap.delete(resource);}
reset()
{this._resourceDataMap.clear();}
executeQuery(query)
{if(!query||!this._resourceDataMap.size)
return[];query=query.removeWhitespace().toLowerCase();let cookie=null;if(query.includes(":")){let[newQuery,lineNumber,columnNumber]=query.split(":");query=newQuery;lineNumber=lineNumber?parseInt(lineNumber,10)-1:0;columnNumber=columnNumber?parseInt(columnNumber,10)-1:0;cookie={lineNumber,columnNumber};}
let results=[];for(let[resource,cachedData]of this._resourceDataMap){if(!cachedData.searchString){let displayName=resource.displayName;cachedData.searchString=displayName.toLowerCase();cachedData.specialCharacterIndices=this._findSpecialCharacterIndices(displayName);}
let matches=this._findQueryMatches(query,cachedData.searchString,cachedData.specialCharacterIndices);if(matches.length)
results.push(new WI.ResourceQueryResult(resource,matches,cookie));}

return results.sort((a,b)=>{if(a.rank===b.rank)
return a.resource.displayName.extendedLocaleCompare(b.resource.displayName);return b.rank-a.rank;});} 
_findQueryMatches(query,searchString,specialCharacterIndices)
{if(query.length>searchString.length)
return[];let matches=[];let queryIndex=0;let searchIndex=0;let specialIndex=0;let deadBranches=new Array(query.length).fill(Infinity);let type=WI.ResourceQueryMatch.Type.Special;function pushMatch(index)
{matches.push(new WI.ResourceQueryMatch(type,index,queryIndex));searchIndex=index+1;queryIndex++;}
function matchNextSpecialCharacter()
{if(specialIndex>=specialCharacterIndices.length)
return false;let originalSpecialIndex=specialIndex;while(specialIndex<specialCharacterIndices.length){
let index=specialCharacterIndices[specialIndex++];if(index<searchIndex)
continue;if(query[queryIndex]===searchString[index]){pushMatch(index);return true;}}
specialIndex=originalSpecialIndex;return false;}
function backtrack()
{while(matches.length){queryIndex--;let lastMatch=matches.pop();if(lastMatch.type!==WI.ResourceQueryMatch.Type.Special)
continue;deadBranches[lastMatch.queryIndex]=lastMatch.index;searchIndex=matches.lastValue?matches.lastValue.index+1:0;return true;}
return false;}
while(queryIndex<query.length&&searchIndex<=searchString.length){if(type===WI.ResourceQueryMatch.Type.Special&&!matchNextSpecialCharacter())
type=WI.ResourceQueryMatch.Type.Normal;if(type===WI.ResourceQueryMatch.Type.Normal){let index=searchString.indexOf(query[queryIndex],searchIndex);if(index>=0&&index<deadBranches[queryIndex]){pushMatch(index);type=WI.ResourceQueryMatch.Type.Special;}else if(!backtrack())
return[];}}
if(queryIndex<query.length)
return[];return matches;}
_findSpecialCharacterIndices(string)
{if(!string.length)
return[];const filenameSeparators="_.-";let indices=[0];for(let i=1;i<string.length;++i){let character=string[i];let isSpecial=false;if(filenameSeparators.includes(character))
isSpecial=true;else{let previousCharacter=string[i-1];let previousCharacterIsSeparator=filenameSeparators.includes(previousCharacter);if(previousCharacterIsSeparator)
isSpecial=true;else if(character.isUpperCase()&&previousCharacter.isLowerCase())
isSpecial=true;}
if(isSpecial)
indices.push(i);}
return indices;}};WI.RuntimeManager=class RuntimeManager extends WI.Object
{constructor()
{super();this._activeExecutionContext=null;WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,function(event){for(let target of WI.targets){if(target.hasCommand("Runtime.setSavedResultAlias"))
target.RuntimeAgent.setSavedResultAlias(WI.settings.consoleSavedResultAlias.value);}},this);} 
static supportsAwaitPromise()
{return InspectorBackend.hasCommand("Runtime.awaitPromise");}
static preferredSavedResultPrefix()
{if(!InspectorBackend.hasCommand("Runtime.setSavedResultAlias"))
return"$";return WI.settings.consoleSavedResultAlias.value||"$";} 
initializeTarget(target)
{target.RuntimeAgent.enable();if(WI.settings.showJavaScriptTypeInformation.value)
target.RuntimeAgent.enableTypeProfiler();if(WI.settings.enableControlFlowProfiler.value)
target.RuntimeAgent.enableControlFlowProfiler();if(target.hasCommand("Runtime.setSavedResultAlias")&&WI.settings.consoleSavedResultAlias.value)
target.RuntimeAgent.setSavedResultAlias(WI.settings.consoleSavedResultAlias.value);} 
get activeExecutionContext()
{return this._activeExecutionContext;}
set activeExecutionContext(executionContext)
{if(this._activeExecutionContext===executionContext)
return;this._activeExecutionContext=executionContext;this.dispatchEventToListeners(WI.RuntimeManager.Event.ActiveExecutionContextChanged);}
evaluateInInspectedWindow(expression,options,callback)
{if(!this._activeExecutionContext){callback(null,false);return;}
let{objectGroup,includeCommandLineAPI,doNotPauseOnExceptionsAndMuteConsole,returnByValue,generatePreview,saveResult,emulateUserGesture,sourceURLAppender}=options;includeCommandLineAPI=includeCommandLineAPI||false;doNotPauseOnExceptionsAndMuteConsole=doNotPauseOnExceptionsAndMuteConsole||false;returnByValue=returnByValue||false;generatePreview=generatePreview||false;saveResult=saveResult||false;emulateUserGesture=emulateUserGesture||false;sourceURLAppender=sourceURLAppender||appendWebInspectorSourceURL;if(!expression){expression="this";}else if(/^\s*\{/.test(expression)&&/\}\s*$/.test(expression)){expression="("+expression+")";}else if(/\bawait\b/.test(expression)){expression=this._tryApplyAwaitConvenience(expression);}
expression=sourceURLAppender(expression);let target=this._activeExecutionContext.target;let executionContextId=this._activeExecutionContext.id;if(WI.debuggerManager.activeCallFrame){target=WI.debuggerManager.activeCallFrame.target;executionContextId=target.executionContext.id;}
function evalCallback(error,result,wasThrown,savedResultIndex)
{this.dispatchEventToListeners(WI.RuntimeManager.Event.DidEvaluate,{objectGroup});if(error){console.error(error);callback(null,false);return;}
if(returnByValue)
callback(null,wasThrown,wasThrown?null:result,savedResultIndex);else
callback(WI.RemoteObject.fromPayload(result,target),wasThrown,savedResultIndex);}
if(WI.debuggerManager.activeCallFrame){target.DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId:WI.debuggerManager.activeCallFrame.id,expression,objectGroup,includeCommandLineAPI,doNotPauseOnExceptionsAndMuteConsole,returnByValue,generatePreview,saveResult,emulateUserGesture,},evalCallback.bind(this));return;}
target.RuntimeAgent.evaluate.invoke({expression,objectGroup,includeCommandLineAPI,doNotPauseOnExceptionsAndMuteConsole,contextId:executionContextId,returnByValue,generatePreview,saveResult,emulateUserGesture,},evalCallback.bind(this));}
saveResult(remoteObject,callback)
{let target=this._activeExecutionContext.target;let executionContextId=this._activeExecutionContext.id;function mycallback(error,savedResultIndex)
{callback(savedResultIndex);}
if(remoteObject.objectId)
target.RuntimeAgent.saveResult(remoteObject.asCallArgument(),mycallback);else
target.RuntimeAgent.saveResult(remoteObject.asCallArgument(),executionContextId,mycallback);} 
_tryApplyAwaitConvenience(originalExpression)
{let esprimaSyntaxTree;try{esprima.parse(originalExpression);return originalExpression;}catch{}
try{esprimaSyntaxTree=esprima.parse("(async function(){"+originalExpression+"})");}catch{return originalExpression;}
let asyncFunctionBlock=esprimaSyntaxTree.body[0].expression.body;if(asyncFunctionBlock.body.length!==1)
return originalExpression;let variableName;let anonymous=false;let declarationKind="var";let awaitPortion;let statement=asyncFunctionBlock.body[0];if(statement.type==="ExpressionStatement"&&statement.expression.type==="AwaitExpression"){anonymous=true;}else if(statement.type==="ExpressionStatement"&&statement.expression.type==="AssignmentExpression"&&statement.expression.right.type==="AwaitExpression"&&statement.expression.left.type==="Identifier"){variableName=statement.expression.left.name;awaitPortion=originalExpression.substring(originalExpression.indexOf("await"));}else if(statement.type==="VariableDeclaration"&&statement.declarations.length===1&&statement.declarations[0].init.type==="AwaitExpression"&&statement.declarations[0].id.type==="Identifier"){variableName=statement.declarations[0].id.name;declarationKind=statement.kind;awaitPortion=originalExpression.substring(originalExpression.indexOf("await"));}else{return originalExpression;}
if(anonymous){return`
(async function() {
    try {
        let result = ${originalExpression};
        console.info("%o", result);
    } catch (e) {
        console.error(e);
    }
})();
undefined`;}
return`${declarationKind} ${variableName};
(async function() {
    try {
        ${variableName} = ${awaitPortion};
        console.info("%o", ${variableName});
    } catch (e) {
        console.error(e);
    }
})();
undefined;`;}};WI.RuntimeManager.ConsoleObjectGroup="console";WI.RuntimeManager.TopLevelExecutionContextIdentifier=undefined;WI.RuntimeManager.Event={DidEvaluate:"runtime-manager-did-evaluate",DefaultExecutionContextChanged:"runtime-manager-default-execution-context-changed",ActiveExecutionContextChanged:"runtime-manager-active-execution-context-changed",};WI.TargetManager=class TargetManager extends WI.Object
{constructor()
{super();this._targets=new Map;this._cachedTargetsList=null;this._seenPageTarget=false;this._transitionTimeoutIdentifier=undefined;} 
initializeTarget(target)
{if(target.hasCommand("Target.setPauseOnStart"))
target.TargetAgent.setPauseOnStart(true);} 
get targets()
{if(!this._cachedTargetsList)
this._cachedTargetsList=Array.from(this._targets.values()).filter((target)=>!(target instanceof WI.MultiplexingBackendTarget));return this._cachedTargetsList;}
get workerTargets()
{return this.targets.filter((target)=>target.type===WI.TargetType.Worker);}
get allTargets()
{return Array.from(this._targets.values());}
targetForIdentifier(targetId)
{if(!targetId)
return null;for(let target of this._targets.values()){if(target.identifier===targetId)
return target;}
return null;}
addTarget(target)
{this._cachedTargetsList=null;this._targets.set(target.identifier,target);this.dispatchEventToListeners(WI.TargetManager.Event.TargetAdded,{target});}
removeTarget(target)
{this._cachedTargetsList=null;this._targets.delete(target.identifier);target.destroy();this.dispatchEventToListeners(WI.TargetManager.Event.TargetRemoved,{target});}
createMultiplexingBackendTarget()
{let target=new WI.MultiplexingBackendTarget;target.initialize();this._initializeBackendTarget(target);this._targets.set(target.identifier,target);}
createDirectBackendTarget()
{let target=new WI.DirectBackendTarget;target.initialize();this._initializeBackendTarget(target);if(WI.sharedApp.debuggableType===WI.DebuggableType.ITML||WI.sharedApp.debuggableType===WI.DebuggableType.Page)
this._initializePageTarget(target);this.addTarget(target);} 
targetCreated(parentTarget,targetInfo)
{let connection=new InspectorBackend.TargetConnection(parentTarget,targetInfo.targetId);let subTarget=this._createTarget(parentTarget,targetInfo,connection);this._checkAndHandlePageTargetTransition(subTarget);subTarget.initialize();this.addTarget(subTarget);}
didCommitProvisionalTarget(parentTarget,previousTargetId,newTargetId)
{this.targetDestroyed(previousTargetId);let target=this._targets.get(newTargetId);if(!target)
return;target.didCommitProvisionalTarget();this._checkAndHandlePageTargetTransition(target);target.connection.dispatchProvisionalMessages();this.dispatchEventToListeners(WI.TargetManager.Event.DidCommitProvisionalTarget,{previousTargetId,target});}
targetDestroyed(targetId)
{let target=this._targets.get(targetId);if(!target)
return;this._checkAndHandlePageTargetTermination(target);this.removeTarget(target);}
dispatchMessageFromTarget(targetId,message)
{let target=this._targets.get(targetId);if(!target)
return;if(target.isProvisional)
target.connection.addProvisionalMessage(message);else
target.connection.dispatch(message);} 
_createTarget(parentTarget,targetInfo,connection)
{let{targetId,type,isProvisional,isPaused}=targetInfo;switch(type){case InspectorBackend.Enum.Target.TargetInfoType.Page:return new WI.PageTarget(parentTarget,targetId,WI.UIString("Page"),connection,{isProvisional,isPaused});case InspectorBackend.Enum.Target.TargetInfoType.Worker:return new WI.WorkerTarget(parentTarget,targetId,WI.UIString("Worker"),connection,{isPaused});case"serviceworker":case InspectorBackend.Enum.Target.TargetInfoType.ServiceWorker:return new WI.WorkerTarget(parentTarget,targetId,WI.UIString("ServiceWorker"),connection,{isPaused});}
throw"Unknown Target type: "+type;}
_checkAndHandlePageTargetTransition(target)
{if(target.type!==WI.TargetType.Page)
return;if(target.isProvisional)
return;if(!WI.pageTarget&&!this._seenPageTarget){this._seenPageTarget=true;this._initializePageTarget(target);return;}
this._transitionPageTarget(target);}
_checkAndHandlePageTargetTermination(target)
{if(target.type!==WI.TargetType.Page)
return;if(target.isProvisional)
return;this._terminatePageTarget(target);const timeToTransition=2000;clearTimeout(this._transitionTimeoutIdentifier);this._transitionTimeoutIdentifier=setTimeout(()=>{this._transitionTimeoutIdentifier=undefined;if(WI.pageTarget)
return;if(WI.isEngineeringBuild)
throw new Error("Error: No new pageTarget some time after last page target was terminated. Failed transition?");WI.close();},timeToTransition);}
_initializeBackendTarget(target)
{WI.backendTarget=target;this._resetMainExecutionContext();WI._backendTargetAvailablePromise.resolve();}
_initializePageTarget(target)
{WI.pageTarget=target;this._resetMainExecutionContext();WI._pageTargetAvailablePromise.resolve();}
_transitionPageTarget(target)
{WI.pageTarget=target;this._resetMainExecutionContext();WI.notifications.dispatchEventToListeners(WI.Notification.TransitionPageTarget);WI.domManager.transitionPageTarget();WI.networkManager.transitionPageTarget();WI.timelineManager.transitionPageTarget();}
_terminatePageTarget(target)
{for(let workerTarget of this.workerTargets)
WI.workerManager.workerTerminated(workerTarget.identifier);WI.pageTarget=null;}
_resetMainExecutionContext()
{if(WI.mainTarget instanceof WI.MultiplexingBackendTarget)
return;if(WI.mainTarget.executionContext)
WI.runtimeManager.activeExecutionContext=WI.mainTarget.executionContext;}};WI.TargetManager.Event={TargetAdded:"target-manager-target-added",TargetRemoved:"target-manager-target-removed",DidCommitProvisionalTarget:"target-manager-provisional-target-committed",};WI.TimelineManager=class TimelineManager extends WI.Object
{constructor()
{super();this._enabled=false;WI.Frame.addEventListener(WI.Frame.Event.ProvisionalLoadStarted,this._provisionalLoadStarted,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._enabledTimelineTypesSetting=new WI.Setting("enabled-instrument-types",WI.TimelineManager.defaultTimelineTypes());this._capturingState=TimelineManager.CapturingState.Inactive;this._capturingInstrumentCount=0;this._capturingStartTime=NaN;this._capturingEndTime=NaN;this._initiatedByBackendStart=false;this._initiatedByBackendStop=false;this._isCapturingPageReload=false;this._autoCaptureOnPageLoad=false;this._mainResourceForAutoCapturing=null;this._shouldSetAutoCapturingMainResource=false;this._transitioningPageTarget=false;this._webTimelineScriptRecordsExpectingScriptProfilerEvents=null;this._scriptProfilerRecords=null;this._boundStopCapturing=this.stopCapturing.bind(this);this._stopCapturingTimeout=undefined;this._deadTimeTimeout=undefined;this._lastDeadTimeTickle=0;} 
get domains(){return["Timeline"];}
activateExtraDomain(domain)
{ for(let target of WI.targets)
this.initializeTarget(target);} 
initializeTarget(target)
{if(!this._enabled)
return;if(target.hasDomain("Timeline")){if(target.hasCommand("Timeline.enable"))
target.TimelineAgent.enable();this._updateAutoCaptureInstruments([target]);target.TimelineAgent.setAutoCaptureEnabled(this._autoCaptureOnPageLoad);}}
transitionPageTarget()
{this._transitioningPageTarget=true;} 
static defaultTimelineTypes()
{if(WI.sharedApp.debuggableType===WI.DebuggableType.JavaScript||WI.sharedApp.debuggableType===WI.DebuggableType.ITML){return[WI.TimelineRecord.Type.Script,WI.TimelineRecord.Type.HeapAllocations,];}
if(WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker){return[WI.TimelineRecord.Type.Script,WI.TimelineRecord.Type.HeapAllocations,];}
let defaultTypes=[WI.TimelineRecord.Type.Network,WI.TimelineRecord.Type.Layout,WI.TimelineRecord.Type.Script,WI.TimelineRecord.Type.RenderingFrame,];if(WI.CPUInstrument.supported())
defaultTypes.push(WI.TimelineRecord.Type.CPU);return defaultTypes;}
static availableTimelineTypes()
{let types=WI.TimelineManager.defaultTimelineTypes();if(WI.sharedApp.debuggableType===WI.DebuggableType.JavaScript||WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker||WI.sharedApp.debuggableType===WI.DebuggableType.ITML)
return types;types.push(WI.TimelineRecord.Type.Memory);types.push(WI.TimelineRecord.Type.HeapAllocations);if(WI.MediaInstrument.supported()){let insertionIndex=types.indexOf(WI.TimelineRecord.Type.Layout)+1;types.insertAtIndex(WI.TimelineRecord.Type.Media,insertionIndex||types.length);}
return types;}
static synthesizeImportError(message)
{message=WI.UIString("Timeline Recording Import Error: %s").format(message);if(window.InspectorTest){console.error(message);return;}
let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} 
get capturingState(){return this._capturingState;}
reset()
{if(this._capturingState===TimelineManager.CapturingState.Starting||this._capturingState===TimelineManager.CapturingState.Active)
this.stopCapturing();this._recordings=[];this._activeRecording=null;this._nextRecordingIdentifier=1;this._loadNewRecording();}
get activeRecording()
{return this._activeRecording;}
get autoCaptureOnPageLoad()
{return this._autoCaptureOnPageLoad;}
set autoCaptureOnPageLoad(autoCapture)
{autoCapture=!!autoCapture;if(this._autoCaptureOnPageLoad===autoCapture)
return;this._autoCaptureOnPageLoad=autoCapture;for(let target of WI.targets){if(target.hasCommand("Timeline.setAutoCaptureEnabled"))
target.TimelineAgent.setAutoCaptureEnabled(this._autoCaptureOnPageLoad);}}
get enabledTimelineTypes()
{let availableTimelineTypes=WI.TimelineManager.availableTimelineTypes();return this._enabledTimelineTypesSetting.value.filter((type)=>availableTimelineTypes.includes(type));}
set enabledTimelineTypes(x)
{this._enabledTimelineTypesSetting.value=x||[];this._updateAutoCaptureInstruments(WI.targets);}
isCapturing()
{return this._capturingState!==TimelineManager.CapturingState.Inactive;}
isCapturingPageReload()
{return this._isCapturingPageReload;}
willAutoStop()
{return!!this._stopCapturingTimeout;}
relaxAutoStop()
{if(this._stopCapturingTimeout){clearTimeout(this._stopCapturingTimeout);this._stopCapturingTimeout=undefined;}
if(this._deadTimeTimeout){clearTimeout(this._deadTimeTimeout);this._deadTimeTimeout=undefined;}}
enable()
{if(this._enabled)
return;this._enabled=true;this.reset();for(let target of WI.targets)
this.initializeTarget(target);}
disable()
{if(!this._enabled)
return;this.reset();for(let target of WI.targets){if(target.hasCommand("Timeline.disable"))
target.TimelineAgent.disable();}
this._enabled=false;}
startCapturing(shouldCreateRecording)
{if(this._capturingState!==TimelineManager.CapturingState.Stopping&&this._capturingState!==TimelineManager.CapturingState.Inactive)
return;if(!this._activeRecording||shouldCreateRecording)
this._loadNewRecording();this._updateCapturingState(TimelineManager.CapturingState.Starting);this._capturingStartTime=NaN;this._activeRecording.start(this._initiatedByBackendStart);}
stopCapturing()
{if(this._capturingState!==TimelineManager.CapturingState.Starting&&this._capturingState!==TimelineManager.CapturingState.Active)
return;this._updateCapturingState(TimelineManager.CapturingState.Stopping);this._capturingEndTime=NaN;this._activeRecording.stop(this._initiatedByBackendStop);}
async processJSON({filename,json,error})
{if(error){WI.TimelineManager.synthesizeImportError(error);return;}
if(typeof json!=="object"||json===null){WI.TimelineManager.synthesizeImportError(WI.UIString("invalid JSON"));return;}
if(!json.recording||typeof json.recording!=="object"||!json.overview||typeof json.overview!=="object"||typeof json.version!=="number"){WI.TimelineManager.synthesizeImportError(WI.UIString("invalid JSON"));return;}
if(json.version!==WI.TimelineRecording.SerializationVersion){WI.NetworkManager.synthesizeImportError(WI.UIString("unsupported version"));return;}
let recordingData=json.recording;let overviewData=json.overview;let identifier=this._nextRecordingIdentifier++;let newRecording=await WI.TimelineRecording.import(identifier,recordingData,filename);this._recordings.push(newRecording);this.dispatchEventToListeners(WI.TimelineManager.Event.RecordingCreated,{recording:newRecording});if(this._capturingState===TimelineManager.CapturingState.Starting||this._capturingState===TimelineManager.CapturingState.Active)
this.stopCapturing();let oldRecording=this._activeRecording;if(oldRecording){const importing=true;oldRecording.unloaded(importing);}
this._activeRecording=newRecording;this.dispatchEventToListeners(WI.TimelineManager.Event.RecordingLoaded,{oldRecording});this.dispatchEventToListeners(WI.TimelineManager.Event.RecordingImported,{overviewData});}
computeElapsedTime(timestamp)
{if(!this._activeRecording)
return 0;return this._activeRecording.computeElapsedTime(timestamp);}
scriptProfilerIsTracking()
{return this._scriptProfilerRecords!==null;} 
heapSnapshotAdded(timestamp,snapshot)
{if(!this._enabled)
return;this._addRecord(new WI.HeapAllocationsTimelineRecord(timestamp,snapshot));} 
capturingStarted(startTime)
{if(this._capturingState===TimelineManager.CapturingState.Inactive){this._initiatedByBackendStart=true;this._activeRecording.addScriptInstrumentForProgrammaticCapture();this.startCapturing();}
if(!isNaN(startTime)){if(isNaN(this._capturingStartTime)||startTime<this._capturingStartTime)
this._capturingStartTime=startTime;this._activeRecording.initializeTimeBoundsIfNecessary(startTime);}
this._capturingInstrumentCount++;if(this._capturingInstrumentCount>1)
return;if(this._capturingState===TimelineManager.CapturingState.Active)
return;this._lastDeadTimeTickle=0;this._webTimelineScriptRecordsExpectingScriptProfilerEvents=[];this._activeRecording.capturingStarted(this._capturingStartTime);WI.settings.timelinesAutoStop.addEventListener(WI.Setting.Event.Changed,this._handleTimelinesAutoStopSettingChanged,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceWasAdded,this);WI.Target.addEventListener(WI.Target.Event.ResourceAdded,this._resourceWasAdded,this);WI.heapManager.addEventListener(WI.HeapManager.Event.GarbageCollected,this._garbageCollected,this);WI.memoryManager.addEventListener(WI.MemoryManager.Event.MemoryPressure,this._memoryPressure,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.DidFireEvent,this._handleDOMNodeDidFireEvent,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.PowerEfficientPlaybackStateChanged,this._handleDOMNodePowerEfficientPlaybackStateChanged,this);this._updateCapturingState(TimelineManager.CapturingState.Active,{startTime:this._capturingStartTime});}
capturingStopped(endTime)
{if(this._capturingState===TimelineManager.CapturingState.Active){this._initiatedByBackendStop=true;this.stopCapturing();}
if(!isNaN(endTime)){if(isNaN(this._capturingEndTime)||endTime>this._capturingEndTime)
this._capturingEndTime=endTime;}
this._capturingInstrumentCount--;if(this._capturingInstrumentCount)
return;if(this._capturingState===TimelineManager.CapturingState.Inactive)
return;WI.DOMNode.removeEventListener(WI.DOMNode.Event.DidFireEvent,this._handleDOMNodeDidFireEvent,this);WI.DOMNode.removeEventListener(WI.DOMNode.Event.PowerEfficientPlaybackStateChanged,this._handleDOMNodePowerEfficientPlaybackStateChanged,this);WI.heapManager.removeEventListener(WI.HeapManager.Event.GarbageCollected,this._garbageCollected,this);WI.memoryManager.removeEventListener(WI.MemoryManager.Event.MemoryPressure,this._memoryPressure,this);WI.Target.removeEventListener(WI.Target.Event.ResourceAdded,this._resourceWasAdded,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasAdded,this._resourceWasAdded,this);WI.settings.timelinesAutoStop.removeEventListener(WI.Setting.Event.Changed,this._handleTimelinesAutoStopSettingChanged,this);this._activeRecording.capturingStopped(this._capturingEndTime);this.relaxAutoStop();this._isCapturingPageReload=false;this._shouldSetAutoCapturingMainResource=false;this._mainResourceForAutoCapturing=null;this._initiatedByBackendStart=false;this._initiatedByBackendStop=false;this._updateCapturingState(TimelineManager.CapturingState.Inactive,{endTime:this._capturingEndTime});}
autoCaptureStarted()
{let waitingForCapturingStartedEvent=this._capturingState===TimelineManager.CapturingState.Starting;if(this._capturingState===TimelineManager.CapturingState.Starting||this._capturingState===TimelineManager.CapturingState.Active)
this.stopCapturing();this._initiatedByBackendStart=true;
if(!waitingForCapturingStartedEvent){const createNewRecording=true;this.startCapturing(createNewRecording);}
this._shouldSetAutoCapturingMainResource=true;}
eventRecorded(recordPayload)
{if(!this._enabled)
return;if(!this.isCapturing())
return;var records=[];
 var stack=[{array:[recordPayload],parent:null,parentRecord:null,index:0}];while(stack.length){var entry=stack.lastValue;var recordPayloads=entry.array;if(entry.index<recordPayloads.length){var recordPayload=recordPayloads[entry.index];var record=this._processEvent(recordPayload,entry.parent);if(record){record.parent=entry.parentRecord;records.push(record);if(entry.parentRecord)
entry.parentRecord.children.push(record);}
if(recordPayload.children&&recordPayload.children.length)
stack.push({array:recordPayload.children,parent:recordPayload,parentRecord:record||entry.parentRecord,index:0});++entry.index;}else
stack.pop();}
for(var record of records){if(record.type===WI.TimelineRecord.Type.RenderingFrame){if(!record.children.length)
continue;record.setupFrameIndex();}
this._addRecord(record);}} 
pageDOMContentLoadedEventFired(timestamp)
{if(!this._enabled)
return;let computedTimestamp=this._activeRecording.computeElapsedTime(timestamp);if(WI.networkManager.mainFrame)
WI.networkManager.mainFrame.markDOMContentReadyEvent(computedTimestamp);let eventMarker=new WI.TimelineMarker(computedTimestamp,WI.TimelineMarker.Type.DOMContentEvent);this._activeRecording.addEventMarker(eventMarker);}
pageLoadEventFired(timestamp)
{if(!this._enabled)
return;let computedTimestamp=this._activeRecording.computeElapsedTime(timestamp);if(WI.networkManager.mainFrame)
WI.networkManager.mainFrame.markLoadEvent(computedTimestamp);let eventMarker=new WI.TimelineMarker(computedTimestamp,WI.TimelineMarker.Type.LoadEvent);this._activeRecording.addEventMarker(eventMarker);this._stopAutoRecordingSoon();} 
cpuProfilerTrackingStarted(timestamp)
{this.capturingStarted(timestamp);}
cpuProfilerTrackingUpdated(event)
{if(!this._enabled)
return;if(!this.isCapturing())
return;this._addRecord(new WI.CPUTimelineRecord(event));}
cpuProfilerTrackingCompleted(timestamp)
{this.capturingStopped(timestamp);} 
scriptProfilerTrackingStarted(timestamp)
{this._scriptProfilerRecords=[];this.capturingStarted(timestamp);}
scriptProfilerTrackingUpdated(event)
{if(!this._enabled)
return;let{startTime,endTime,type}=event;let scriptRecordType=this._scriptProfilerTypeToScriptTimelineRecordType(type);let record=new WI.ScriptTimelineRecord(scriptRecordType,startTime,endTime,null,null,null,null);record.__scriptProfilerType=type;this._scriptProfilerRecords.push(record);


if(type!==InspectorBackend.Enum.ScriptProfiler.EventType.Other)
this._addRecord(record);}
scriptProfilerTrackingCompleted(timestamp,samples)
{if(this._enabled){if(samples){let{stackTraces}=samples;let topDownCallingContextTree=this._activeRecording.topDownCallingContextTree;let timestampIndex=0;let timestampCount=stackTraces.length;let sampleDurations=new Array(timestampCount);let sampleDurationIndex=0;const defaultDuration=1/1000;for(let i=0;i<this._scriptProfilerRecords.length;++i){let record=this._scriptProfilerRecords[i];while(timestampIndex<timestampCount&&stackTraces[timestampIndex].timestamp<record.startTime){sampleDurations[sampleDurationIndex++]=defaultDuration;timestampIndex++;}
let samplesInRecord=0;while(timestampIndex<timestampCount&&stackTraces[timestampIndex].timestamp<record.endTime){timestampIndex++;samplesInRecord++;}
if(samplesInRecord){let averageDuration=(record.endTime-record.startTime)/samplesInRecord;sampleDurations.fill(averageDuration,sampleDurationIndex,sampleDurationIndex+samplesInRecord);sampleDurationIndex+=samplesInRecord;}}
if(timestampIndex<timestampCount)
sampleDurations.fill(defaultDuration,sampleDurationIndex);this._activeRecording.initializeCallingContextTrees(stackTraces,sampleDurations); for(let i=0;i<this._scriptProfilerRecords.length;++i){let record=this._scriptProfilerRecords[i];record.profilePayload=topDownCallingContextTree.toCPUProfilePayload(record.startTime,record.endTime);}}
if(WI.sharedApp.debuggableType!==WI.DebuggableType.JavaScript&&WI.sharedApp.debuggableType!==WI.DebuggableType.ITML){this._scriptProfilerRecords=this._scriptProfilerRecords.filter((x)=>x.__scriptProfilerType===InspectorBackend.Enum.ScriptProfiler.EventType.Other);this._mergeScriptProfileRecords();}
this._scriptProfilerRecords=null;let timeline=this._activeRecording.timelineForRecordType(WI.TimelineRecord.Type.Script);timeline.refresh();}
this.capturingStopped(timestamp);} 
memoryTrackingStarted(timestamp)
{this.capturingStarted(timestamp);}
memoryTrackingUpdated(event)
{if(!this._enabled)
return;if(!this.isCapturing())
return;this._addRecord(new WI.MemoryTimelineRecord(event.timestamp,event.categories));}
memoryTrackingCompleted(timestamp)
{this.capturingStopped(timestamp);} 
heapTrackingStarted(timestamp,snapshot)
{this.capturingStarted(timestamp);if(this._enabled)
this._addRecord(new WI.HeapAllocationsTimelineRecord(timestamp,snapshot));}
heapTrackingCompleted(timestamp,snapshot)
{if(this._enabled)
this._addRecord(new WI.HeapAllocationsTimelineRecord(timestamp,snapshot));this.capturingStopped();} 
animationTrackingStarted(timestamp)
{this.capturingStarted(timestamp);}
animationTrackingUpdated(timestamp,event)
{if(!this._enabled)
return;if(!this.isCapturing())
return;let mediaTimeline=this._activeRecording.timelineForRecordType(WI.TimelineRecord.Type.Media);let record=mediaTimeline.recordForTrackingAnimationId(event.trackingAnimationId);if(!record){let details={trackingAnimationId:event.trackingAnimationId,};let eventType;if(event.animationName){eventType=WI.MediaTimelineRecord.EventType.CSSAnimation;details.animationName=event.animationName;}else if(event.transitionProperty){eventType=WI.MediaTimelineRecord.EventType.CSSTransition;details.transitionProperty=event.transitionProperty;}else{WI.reportInternalError(`Unknown event type for event '${JSON.stringify(event)}'`);return;}
let domNode=WI.domManager.nodeForId(event.nodeId);record=new WI.MediaTimelineRecord(eventType,domNode,details);this._addRecord(record);}
record.updateAnimationState(timestamp,event.animationState);}
animationTrackingCompleted(timestamp)
{this.capturingStopped(timestamp);} 
_updateCapturingState(state,data={})
{if(this._capturingState===state)
return;this._capturingState=state;this.dispatchEventToListeners(TimelineManager.Event.CapturingStateChanged,data);}
_processRecord(recordPayload,parentRecordPayload)
{var startTime=this._activeRecording.computeElapsedTime(recordPayload.startTime);var endTime=this._activeRecording.computeElapsedTime(recordPayload.endTime);var callFrames=this._callFramesFromPayload(recordPayload.stackTrace);var significantCallFrame=null;if(callFrames){for(var i=0;i<callFrames.length;++i){if(callFrames[i].nativeCode)
continue;significantCallFrame=callFrames[i];break;}}
var sourceCodeLocation=significantCallFrame&&significantCallFrame.sourceCodeLocation;switch(recordPayload.type){case InspectorBackend.Enum.Timeline.EventType.ScheduleStyleRecalculation:return new WI.LayoutTimelineRecord(WI.LayoutTimelineRecord.EventType.InvalidateStyles,startTime,startTime,callFrames,sourceCodeLocation);case InspectorBackend.Enum.Timeline.EventType.RecalculateStyles:return new WI.LayoutTimelineRecord(WI.LayoutTimelineRecord.EventType.RecalculateStyles,startTime,endTime,callFrames,sourceCodeLocation);case InspectorBackend.Enum.Timeline.EventType.InvalidateLayout:return new WI.LayoutTimelineRecord(WI.LayoutTimelineRecord.EventType.InvalidateLayout,startTime,startTime,callFrames,sourceCodeLocation);case InspectorBackend.Enum.Timeline.EventType.Layout:var layoutRecordType=sourceCodeLocation?WI.LayoutTimelineRecord.EventType.ForcedLayout:WI.LayoutTimelineRecord.EventType.Layout;var quad=new WI.Quad(recordPayload.data.root);return new WI.LayoutTimelineRecord(layoutRecordType,startTime,endTime,callFrames,sourceCodeLocation,quad);case InspectorBackend.Enum.Timeline.EventType.Paint:var quad=new WI.Quad(recordPayload.data.clip);return new WI.LayoutTimelineRecord(WI.LayoutTimelineRecord.EventType.Paint,startTime,endTime,callFrames,sourceCodeLocation,quad);case InspectorBackend.Enum.Timeline.EventType.Composite:return new WI.LayoutTimelineRecord(WI.LayoutTimelineRecord.EventType.Composite,startTime,endTime,callFrames,sourceCodeLocation);case InspectorBackend.Enum.Timeline.EventType.RenderingFrame:if(!recordPayload.children||!recordPayload.children.length)
return null;return new WI.RenderingFrameTimelineRecord(startTime,endTime,recordPayload.data.name);case InspectorBackend.Enum.Timeline.EventType.EvaluateScript:if(!sourceCodeLocation){var mainFrame=WI.networkManager.mainFrame;const recursivelySearchChildFrames=true;let scriptResource=mainFrame.url===recordPayload.data.url?mainFrame.mainResource:mainFrame.resourcesForURL(recordPayload.data.url,recursivelySearchChildFrames).lastValue;if(scriptResource){let lineNumber=recordPayload.data.lineNumber-1;let columnNumber="columnNumber"in recordPayload.data?recordPayload.data.columnNumber-1:0;sourceCodeLocation=scriptResource.createSourceCodeLocation(lineNumber,columnNumber);}}
var profileData=recordPayload.data.profile;var record;switch(parentRecordPayload&&parentRecordPayload.type){case InspectorBackend.Enum.Timeline.EventType.TimerFire:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.TimerFired,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.timerId,profileData);break;case InspectorBackend.Enum.Timeline.EventType.ObserverCallback:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ObserverCallback,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.type,profileData);break;case InspectorBackend.Enum.Timeline.EventType.FireAnimationFrame:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.AnimationFrameFired,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.id,profileData);break;default:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ScriptEvaluated,startTime,endTime,callFrames,sourceCodeLocation,null,profileData);break;}
this._webTimelineScriptRecordsExpectingScriptProfilerEvents.push(record);return record;case InspectorBackend.Enum.Timeline.EventType.ConsoleProfile:return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded,startTime,endTime,callFrames,sourceCodeLocation,recordPayload.data.title);case InspectorBackend.Enum.Timeline.EventType.TimerFire:case InspectorBackend.Enum.Timeline.EventType.EventDispatch:case InspectorBackend.Enum.Timeline.EventType.FireAnimationFrame:case InspectorBackend.Enum.Timeline.EventType.ObserverCallback:break;case InspectorBackend.Enum.Timeline.EventType.FunctionCall:
if(!parentRecordPayload){console.warn("Unexpectedly received a FunctionCall timeline record without a parent record");break;}
if(!sourceCodeLocation){var mainFrame=WI.networkManager.mainFrame;const recursivelySearchChildFrames=true;let scriptResource=mainFrame.url===recordPayload.data.scriptName?mainFrame.mainResource:mainFrame.resourcesForURL(recordPayload.data.scriptName,recursivelySearchChildFrames).lastValue;if(scriptResource){let lineNumber=recordPayload.data.scriptLine-1;let columnNumber="scriptColumn"in recordPayload.data?recordPayload.data.scriptColumn-1:0;sourceCodeLocation=scriptResource.createSourceCodeLocation(lineNumber,columnNumber);}}
var profileData=recordPayload.data.profile;var record;switch(parentRecordPayload.type){case InspectorBackend.Enum.Timeline.EventType.TimerFire:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.TimerFired,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.timerId,profileData);break;case InspectorBackend.Enum.Timeline.EventType.EventDispatch:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.EventDispatched,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.type,profileData,parentRecordPayload.data);break;case InspectorBackend.Enum.Timeline.EventType.ObserverCallback:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ObserverCallback,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.type,profileData);break;case InspectorBackend.Enum.Timeline.EventType.FireAnimationFrame:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.AnimationFrameFired,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.id,profileData);break;case InspectorBackend.Enum.Timeline.EventType.FunctionCall:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ScriptEvaluated,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.id,profileData);break;case InspectorBackend.Enum.Timeline.EventType.RenderingFrame:record=new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ScriptEvaluated,startTime,endTime,callFrames,sourceCodeLocation,parentRecordPayload.data.id,profileData);break;default:break;}
if(record){this._webTimelineScriptRecordsExpectingScriptProfilerEvents.push(record);return record;}
break;case InspectorBackend.Enum.Timeline.EventType.ProbeSample:{let probe=WI.debuggerManager.probeForIdentifier(recordPayload.data.probeId);if(probe.breakpoint instanceof WI.JavaScriptBreakpoint)
sourceCodeLocation=probe.breakpoint.sourceCodeLocation;return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded,startTime,startTime,callFrames,sourceCodeLocation,recordPayload.data.probeId);}
case InspectorBackend.Enum.Timeline.EventType.TimerInstall:var timerDetails={timerId:recordPayload.data.timerId,timeout:recordPayload.data.timeout,repeating:!recordPayload.data.singleShot};return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.TimerInstalled,startTime,startTime,callFrames,sourceCodeLocation,timerDetails);case InspectorBackend.Enum.Timeline.EventType.TimerRemove:return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.TimerRemoved,startTime,startTime,callFrames,sourceCodeLocation,recordPayload.data.timerId);case InspectorBackend.Enum.Timeline.EventType.RequestAnimationFrame:return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.AnimationFrameRequested,startTime,startTime,callFrames,sourceCodeLocation,recordPayload.data.id);case InspectorBackend.Enum.Timeline.EventType.CancelAnimationFrame:return new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled,startTime,startTime,callFrames,sourceCodeLocation,recordPayload.data.id);default:console.error("Missing handling of Timeline Event Type: "+recordPayload.type);}
return null;}
_processEvent(recordPayload,parentRecordPayload)
{switch(recordPayload.type){case InspectorBackend.Enum.Timeline.EventType.TimeStamp:var timestamp=this._activeRecording.computeElapsedTime(recordPayload.startTime);var eventMarker=new WI.TimelineMarker(timestamp,WI.TimelineMarker.Type.TimeStamp,recordPayload.data.message);this._activeRecording.addEventMarker(eventMarker);break;case InspectorBackend.Enum.Timeline.EventType.Time:case InspectorBackend.Enum.Timeline.EventType.TimeEnd:
break;default:return this._processRecord(recordPayload,parentRecordPayload);}
return null;}
_loadNewRecording()
{if(this._activeRecording&&this._activeRecording.isEmpty())
return;let instruments=this.enabledTimelineTypes.map((type)=>WI.Instrument.createForTimelineType(type));let identifier=this._nextRecordingIdentifier++;let newRecording=new WI.TimelineRecording(identifier,WI.UIString("Timeline Recording %d").format(identifier),instruments);this._recordings.push(newRecording);this.dispatchEventToListeners(WI.TimelineManager.Event.RecordingCreated,{recording:newRecording});if(this._capturingState===TimelineManager.CapturingState.Starting||this._capturingState===TimelineManager.CapturingState.Active)
this.stopCapturing();var oldRecording=this._activeRecording;if(oldRecording)
oldRecording.unloaded();this._activeRecording=newRecording;this.dispatchEventToListeners(WI.TimelineManager.Event.RecordingLoaded,{oldRecording});}
_callFramesFromPayload(payload)
{if(!payload)
return null;return payload.map((x)=>WI.CallFrame.fromPayload(WI.assumingMainTarget(),x));}
_addRecord(record)
{this._activeRecording.addRecord(record);if(WI.networkManager.mainFrame&&isNaN(WI.networkManager.mainFrame.loadEventTimestamp))
this._resetAutoRecordingDeadTimeTimeout();}
_attemptAutoCapturingForFrame(frame)
{if(!this._autoCaptureOnPageLoad)
return false;if(!frame.isMainFrame())
return false;if(!InspectorBackend.hasDomain("Timeline"))
return false;if(!this._shouldSetAutoCapturingMainResource)
return false;let mainResource=frame.provisionalMainResource||frame.mainResource;if(mainResource===this._mainResourceForAutoCapturing)
return false;let oldMainResource=frame.mainResource||null;this._isCapturingPageReload=oldMainResource!==null&&oldMainResource.url===mainResource.url;this._mainResourceForAutoCapturing=mainResource;this._addRecord(new WI.ResourceTimelineRecord(mainResource));this._resetAutoRecordingMaxTimeTimeout();this._shouldSetAutoCapturingMainResource=false;return true;}
_legacyAttemptStartAutoCapturingForFrame(frame)
{if(this.isCapturing()&&!this._mainResourceForAutoCapturing)
return false;let mainResource=frame.provisionalMainResource||frame.mainResource;if(mainResource===this._mainResourceForAutoCapturing)
return false;let oldMainResource=frame.mainResource||null;this._isCapturingPageReload=oldMainResource!==null&&oldMainResource.url===mainResource.url;if(this._capturingState===TimelineManager.CapturingState.Starting||this._capturingState===TimelineManager.CapturingState.Active)
this.stopCapturing();this._mainResourceForAutoCapturing=mainResource;this._loadNewRecording();this.startCapturing();this._addRecord(new WI.ResourceTimelineRecord(mainResource));this._resetAutoRecordingMaxTimeTimeout();return true;}
_stopAutoRecordingSoon()
{if(!WI.settings.timelinesAutoStop.value)
return;if(!this.isCapturing()||!this._mainResourceForAutoCapturing)
return;if(this._stopCapturingTimeout)
clearTimeout(this._stopCapturingTimeout);this._stopCapturingTimeout=setTimeout(this._boundStopCapturing,WI.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent);}
_resetAutoRecordingMaxTimeTimeout()
{if(!WI.settings.timelinesAutoStop.value)
return;if(this._stopCapturingTimeout)
clearTimeout(this._stopCapturingTimeout);this._stopCapturingTimeout=setTimeout(this._boundStopCapturing,WI.TimelineManager.MaximumAutoRecordDuration);}
_resetAutoRecordingDeadTimeTimeout()
{if(!WI.settings.timelinesAutoStop.value)
return;if(!this.isCapturing()||!this._mainResourceForAutoCapturing)
return;let now=Date.now();if(now<=this._lastDeadTimeTickle)
return;this._lastDeadTimeTickle=now+10;if(this._deadTimeTimeout)
clearTimeout(this._deadTimeTimeout);this._deadTimeTimeout=setTimeout(this._boundStopCapturing,WI.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly);}
_provisionalLoadStarted(event)
{if(!this._enabled)
return;this._attemptAutoCapturingForFrame(event.target);}
_mainResourceDidChange(event)
{if(!this._enabled)
return;
if(!WI.networkManager.mainFrame)
return;let frame=event.target;
if(this._transitioningPageTarget){this._transitioningPageTarget=false;if(this._autoCaptureOnPageLoad)
this._legacyAttemptStartAutoCapturingForFrame(frame);return;}
if(this._attemptAutoCapturingForFrame(frame))
return;if(!this.isCapturing())
return;let mainResource=frame.mainResource;if(mainResource===this._mainResourceForAutoCapturing)
return;this._addRecord(new WI.ResourceTimelineRecord(mainResource));}
_resourceWasAdded(event)
{if(!this._enabled)
return;
if(!WI.networkManager.mainFrame)
return;this._addRecord(new WI.ResourceTimelineRecord(event.data.resource));}
_garbageCollected(event)
{if(!this._enabled)
return;let{collection}=event.data;this._addRecord(new WI.ScriptTimelineRecord(WI.ScriptTimelineRecord.EventType.GarbageCollected,collection.startTime,collection.endTime,null,null,collection));}
_memoryPressure(event)
{if(!this._enabled)
return;this._activeRecording.addMemoryPressureEvent(event.data.memoryPressureEvent);}
_handleTimelinesAutoStopSettingChanged(event)
{if(WI.settings.timelinesAutoStop.value){if(this._mainResourceForAutoCapturing&&!isNaN(this._mainResourceForAutoCapturing.parentFrame.loadEventTimestamp))
this._stopAutoRecordingSoon();else
this._resetAutoRecordingMaxTimeTimeout();this._resetAutoRecordingDeadTimeTimeout();}else
this.relaxAutoStop();}
_scriptProfilerTypeToScriptTimelineRecordType(type)
{switch(type){case InspectorBackend.Enum.ScriptProfiler.EventType.API:return WI.ScriptTimelineRecord.EventType.APIScriptEvaluated;case InspectorBackend.Enum.ScriptProfiler.EventType.Microtask:return WI.ScriptTimelineRecord.EventType.MicrotaskDispatched;case InspectorBackend.Enum.ScriptProfiler.EventType.Other:return WI.ScriptTimelineRecord.EventType.ScriptEvaluated;}}
_mergeScriptProfileRecords()
{let nextRecord=function(list){return list.shift()||null;};let nextWebTimelineRecord=nextRecord.bind(null,this._webTimelineScriptRecordsExpectingScriptProfilerEvents);let nextScriptProfilerRecord=nextRecord.bind(null,this._scriptProfilerRecords);let recordEnclosesRecord=function(record1,record2){return record1.startTime<=record2.startTime&&record1.endTime>=record2.endTime;};let webRecord=nextWebTimelineRecord();let profilerRecord=nextScriptProfilerRecord();while(webRecord&&profilerRecord){if(webRecord.parent instanceof WI.ScriptTimelineRecord){webRecord=nextWebTimelineRecord();continue;}
if(recordEnclosesRecord(webRecord,profilerRecord)){webRecord.profilePayload=profilerRecord.profilePayload;profilerRecord=nextScriptProfilerRecord();

 while(profilerRecord&&recordEnclosesRecord(webRecord,profilerRecord)){this._addRecord(profilerRecord);profilerRecord=nextScriptProfilerRecord();}
webRecord=nextWebTimelineRecord();continue;}
if(profilerRecord.startTime>webRecord.endTime){console.warn("Unexpected case of a Timeline record not containing a ScriptProfiler event and profile data");webRecord=nextWebTimelineRecord();continue;}
console.warn("Unexpected case of a ScriptProfiler event not being contained by a Timeline record");this._addRecord(profilerRecord);profilerRecord=nextScriptProfilerRecord();}
}
_updateAutoCaptureInstruments(targets)
{let enabledTimelineTypes=this.enabledTimelineTypes;for(let target of targets){if(!target.hasCommand("Timeline.setInstruments"))
continue;let instrumentSet=new Set;for(let timelineType of enabledTimelineTypes){switch(timelineType){case WI.TimelineRecord.Type.Script:instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.ScriptProfiler);break;case WI.TimelineRecord.Type.HeapAllocations:instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.Heap);break;case WI.TimelineRecord.Type.Network:case WI.TimelineRecord.Type.RenderingFrame:case WI.TimelineRecord.Type.Layout:instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.Timeline);break;case WI.TimelineRecord.Type.CPU:instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.CPU);break;case WI.TimelineRecord.Type.Memory:instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.Memory);break;case WI.TimelineRecord.Type.Media:if(InspectorBackend.hasDomain("Animation"))
instrumentSet.add(InspectorBackend.Enum.Timeline.Instrument.Animation);break;}}
target.TimelineAgent.setInstruments(Array.from(instrumentSet));}}
_handleDOMNodeDidFireEvent(event)
{if(!this._enabled)
return;let domNode=event.target;if(!domNode.isMediaElement())
return;let{domEvent}=event.data;let mediaTimeline=this._activeRecording.timelineForRecordType(WI.TimelineRecord.Type.Media);let record=mediaTimeline.recordForMediaElementEvents(domNode);if(!record){record=new WI.MediaTimelineRecord(WI.MediaTimelineRecord.EventType.MediaElement,domNode);this._addRecord(record);}
record.addDOMEvent(domEvent.timestamp,domEvent);}
_handleDOMNodePowerEfficientPlaybackStateChanged(event)
{if(!this._enabled)
return;let domNode=event.target;let{timestamp,isPowerEfficient}=event.data;let mediaTimeline=this._activeRecording.timelineForRecordType(WI.TimelineRecord.Type.Media);let record=mediaTimeline.recordForMediaElementEvents(domNode);if(!record){record=new WI.MediaTimelineRecord(WI.MediaTimelineRecord.EventType.MediaElement,domNode);this._addRecord(record);}
record.powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient);}};WI.TimelineManager.CapturingState={Inactive:"inactive",Starting:"starting",Active:"active",Stopping:"stopping",};WI.TimelineManager.Event={CapturingStateChanged:"timeline-manager-capturing-started",RecordingCreated:"timeline-manager-recording-created",RecordingLoaded:"timeline-manager-recording-loaded",RecordingImported:"timeline-manager-recording-imported",};WI.TimelineManager.MaximumAutoRecordDuration=90_000;WI.TimelineManager.MaximumAutoRecordDurationAfterLoadEvent=10_000;WI.TimelineManager.DeadTimeRequiredToStopAutoRecordingEarly=2_000;WI.TypeTokenAnnotator=class TypeTokenAnnotator extends WI.Annotator
{constructor(sourceCodeTextEditor,script)
{super(sourceCodeTextEditor);this._script=script;this._typeTokenNodes=[];this._typeTokenBookmarks=[];} 
insertAnnotations()
{if(!this.isActive())
return;var scriptSyntaxTree=this._script.scriptSyntaxTree;if(!scriptSyntaxTree){this._script.requestScriptSyntaxTree((syntaxTree)=>{if(syntaxTree)
this.insertAnnotations();});return;}
if(!scriptSyntaxTree.parsedSuccessfully)
return;let{startPosition,endPosition}=this.sourceCodeTextEditor.visibleRangePositions();let startTime=Date.now();let allNodesInRange=scriptSyntaxTree.filterByRange(startPosition,endPosition);scriptSyntaxTree.updateTypes(allNodesInRange,(nodesWithUpdatedTypes)=>{if(!this.isActive())
return;nodesWithUpdatedTypes.forEach(this._insertTypeToken,this);let totalTime=Date.now()-startTime;let timeoutTime=Number.constrain(8*totalTime,500,2000);this._timeoutIdentifier=setTimeout(()=>{this._timeoutIdentifier=null;this.insertAnnotations();},timeoutTime);});}
clearAnnotations()
{this._clearTypeTokens();} 
_insertTypeToken(node)
{if(node.type===WI.ScriptSyntaxTree.NodeType.Identifier){if(!node.attachments.__typeToken&&node.attachments.types&&node.attachments.types.valid)
this._insertToken(node,false,WI.TypeTokenView.TitleType.Variable,node.name);if(node.attachments.__typeToken)
node.attachments.__typeToken.update(node.attachments.types);return;}
var functionReturnType=node.attachments.returnTypes;if(!functionReturnType||!functionReturnType.valid)
return;
var scriptSyntaxTree=this._script._scriptSyntaxTree;if(!node.attachments.__typeToken&&(scriptSyntaxTree.containsNonEmptyReturnStatement(node.body)||!functionReturnType.typeSet.isContainedIn(WI.TypeSet.TypeBit.Undefined))){var functionName=node.id?node.id.name:null;this._insertToken(node,true,WI.TypeTokenView.TitleType.ReturnStatement,functionName);}
if(node.attachments.__typeToken)
node.attachments.__typeToken.update(node.attachments.returnTypes);}
_insertToken(node,shouldTranslateOffsetToAfterParameterList,typeTokenTitleType,functionOrVariableName)
{let tokenPosition=this.sourceCodeTextEditor.originalPositionToCurrentPosition(node.startPosition);let currentOffset=this.sourceCodeTextEditor.currentPositionToCurrentOffset(tokenPosition);let sourceString=this.sourceCodeTextEditor.string;if(shouldTranslateOffsetToAfterParameterList){currentOffset=this._translateToOffsetAfterFunctionParameterList(node,currentOffset,sourceString);tokenPosition=this.sourceCodeTextEditor.currentOffsetToCurrentPosition(currentOffset);}
var isSpaceRegexp=/\s/;var shouldHaveLeftMargin=currentOffset!==0&&!isSpaceRegexp.test(sourceString[currentOffset-1]);var shouldHaveRightMargin=!isSpaceRegexp.test(sourceString[currentOffset]);var typeToken=new WI.TypeTokenView(this,shouldHaveRightMargin,shouldHaveLeftMargin,typeTokenTitleType,functionOrVariableName);var bookmark=this.sourceCodeTextEditor.setInlineWidget(tokenPosition,typeToken.element);node.attachments.__typeToken=typeToken;this._typeTokenNodes.push(node);this._typeTokenBookmarks.push(bookmark);}
_translateToOffsetAfterFunctionParameterList(node,offset,sourceString)
{var isMultiLineComment=false;var isSingleLineComment=false;var shouldIgnore=false;const isArrowFunction=node.type===WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression;function isLineTerminator(char)
{
 return char==="\n"||char==="\r"||char==="\u2028"||char==="\u2029";}
while(((!isArrowFunction&&sourceString[offset]!==")")||(isArrowFunction&&sourceString[offset]!==">")||shouldIgnore)&&offset<sourceString.length){if(isSingleLineComment&&isLineTerminator(sourceString[offset])){isSingleLineComment=false;shouldIgnore=false;}else if(isMultiLineComment&&sourceString[offset]==="*"&&sourceString[offset+1]==="/"){isMultiLineComment=false;shouldIgnore=false;offset++;}else if(!shouldIgnore&&sourceString[offset]==="/"){offset++;if(sourceString[offset]==="*")
isMultiLineComment=true;else if(sourceString[offset]==="/")
isSingleLineComment=true;else
throw new Error("Bad parsing. Couldn't parse comment preamble.");shouldIgnore=true;}
offset++;}
return offset+1;}
_clearTypeTokens()
{this._typeTokenNodes.forEach(function(node){node.attachments.__typeToken=null;});this._typeTokenBookmarks.forEach(function(bookmark){bookmark.clear();});this._typeTokenNodes=[];this._typeTokenBookmarks=[];}};WI.WebInspectorExtensionController=class WebInspectorExtensionController extends WI.Object
{constructor()
{super();this._extensionForExtensionIDMap=new Map;this._extensionTabContentViewForExtensionTabIDMap=new Map;this._tabIDsForExtensionIDMap=new Multimap;this._nextExtensionTabID=1;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleMainResourceDidChange,this);} 
get registeredExtensionIDs()
{return new Set(this._extensionForExtensionIDMap.keys());}
registerExtension(extensionID,displayName)
{if(this._extensionForExtensionIDMap.has(extensionID)){WI.reportInternalError("Unable to register extension, it's already registered: "+extensionID);return WI.WebInspectorExtension.ErrorCode.RegistrationFailed;}
let extension=new WI.WebInspectorExtension(extensionID,displayName);this._extensionForExtensionIDMap.set(extensionID,extension);this.dispatchEventToListeners(WI.WebInspectorExtensionController.Event.ExtensionAdded,{extension});}
unregisterExtension(extensionID)
{let extension=this._extensionForExtensionIDMap.take(extensionID);if(!extension){WI.reportInternalError("Unable to unregister extension with unknown ID: "+extensionID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
let extensionTabIDsToRemove=this._tabIDsForExtensionIDMap.take(extensionID)||[];for(let extensionTabID of extensionTabIDsToRemove){let tabContentView=this._extensionTabContentViewForExtensionTabIDMap.take(extensionTabID);WI.tabBrowser.closeTabForContentView(tabContentView,{suppressAnimations:true});tabContentView.dispose();}
this.dispatchEventToListeners(WI.WebInspectorExtensionController.Event.ExtensionRemoved,{extension});}
createTabForExtension(extensionID,tabName,tabIconURL,sourceURL)
{let extension=this._extensionForExtensionIDMap.get(extensionID);if(!extension){WI.reportInternalError("Unable to create tab for extension with unknown ID: "+extensionID+" sourceURL: "+sourceURL);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
let extensionTabID=`WebExtensionTab-${extensionID}-${this._nextExtensionTabID++}`;let tabContentView=new WI.WebInspectorExtensionTabContentView(extension,extensionTabID,tabName,tabIconURL,sourceURL);this._tabIDsForExtensionIDMap.add(extensionID,extensionTabID);this._extensionTabContentViewForExtensionTabIDMap.set(extensionTabID,tabContentView);WI.tabBrowser.addTabForContentView(tabContentView,{suppressAnimations:true});return{extensionTabID};}
evaluateScriptForExtension(extensionID,scriptSource,{frameURL,contextSecurityOrigin,useContentScriptContext}={})
{let extension=this._extensionForExtensionIDMap.get(extensionID);if(!extension){WI.reportInternalError("Unable to evaluate script for extension with unknown ID: "+extensionID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;} 
if(frameURL){WI.reportInternalError("evaluateScriptForExtension: the 'frameURL' option is not yet implemented.");return WI.WebInspectorExtension.ErrorCode.NotImplemented;}
if(contextSecurityOrigin){WI.reportInternalError("evaluateScriptForExtension: the 'contextSecurityOrigin' option is not yet implemented.");return WI.WebInspectorExtension.ErrorCode.NotImplemented;}
if(useContentScriptContext){WI.reportInternalError("evaluateScriptForExtension: the 'useContentScriptContext' option is not yet implemented.");return WI.WebInspectorExtension.ErrorCode.NotImplemented;}
let evaluationContext=WI.runtimeManager.activeExecutionContext;return evaluationContext.target.RuntimeAgent.evaluate.invoke({expression:scriptSource,objectGroup:"extension-evaluation",includeCommandLineAPI:true,returnByValue:true,generatePreview:false,saveResult:false,contextId:evaluationContext.id,}).then((payload)=>{let resultOrError=payload.result;let wasThrown=payload.wasThrown;let{type,value}=resultOrError;return wasThrown?{"error":resultOrError.description}:{"result":value};}).catch((error)=>error.description);}
reloadForExtension(extensionID,{ignoreCache,userAgent,injectedScript}={})
{let extension=this._extensionForExtensionIDMap.get(extensionID);if(!extension){WI.reportInternalError("Unable to evaluate script for extension with unknown ID: "+extensionID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;} 
if(userAgent){WI.reportInternalError("reloadForExtension: the 'userAgent' option is not yet implemented.");return WI.WebInspectorExtension.ErrorCode.NotImplemented;}
if(injectedScript){WI.reportInternalError("reloadForExtension: the 'injectedScript' option is not yet implemented.");return WI.WebInspectorExtension.ErrorCode.NotImplemented;}
let target=WI.assumingMainTarget();if(!target.hasCommand("Page.reload"))
return WI.WebInspectorExtension.ErrorCode.InvalidRequest;return target.PageAgent.reload.invoke({ignoreCache});}
showExtensionTab(extensionTabID,options={})
{let tabContentView=this._extensionTabContentViewForExtensionTabIDMap.get(extensionTabID);if(!tabContentView){WI.reportInternalError("Unable to show extension tab with unknown extensionTabID: "+extensionTabID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
tabContentView.visible=true;let success=WI.tabBrowser.showTabForContentView(tabContentView,{...options,initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});if(!success){WI.reportInternalError("Unable to show extension tab with extensionTabID: "+extensionTabID);return WI.WebInspectorExtension.ErrorCode.InternalError;}
tabContentView.visible=true;}
hideExtensionTab(extensionTabID,options={})
{let tabContentView=this._extensionTabContentViewForExtensionTabIDMap.get(extensionTabID);if(!tabContentView){WI.reportInternalError("Unable to show extension tab with unknown extensionTabID: "+extensionTabID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
tabContentView.visible=false;WI.tabBrowser.closeTabForContentView(tabContentView,options);}
addContextMenuItemsForClosedExtensionTabs(contextMenu)
{contextMenu.appendSeparator();for(let tabContentView of this._extensionTabContentViewForExtensionTabIDMap.values()){
let shouldIncludeTab=!tabContentView.visible||!tabContentView.tabBarItem.parentTabBar;if(!shouldIncludeTab)
continue;contextMenu.appendItem(tabContentView.tabInfo().displayName,()=>{this.showExtensionTab(tabContentView.extensionTabID);});}}
addContextMenuItemsForAllExtensionTabs(contextMenu)
{contextMenu.appendSeparator();for(let tabContentView of this._extensionTabContentViewForExtensionTabIDMap.values()){let checked=tabContentView.visible||!!tabContentView.tabBarItem.parentTabBar;contextMenu.appendCheckboxItem(tabContentView.tabInfo().displayName,()=>{if(!checked)
this.showExtensionTab(tabContentView.extensionTabID);else
this.hideExtensionTab(tabContentView.extensionTabID);},checked);}}
evaluateScriptInExtensionTab(extensionTabID,scriptSource)
{let tabContentView=this._extensionTabContentViewForExtensionTabIDMap.get(extensionTabID);if(!tabContentView){WI.reportInternalError("Unable to evaluate with unknown extensionTabID: "+extensionTabID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
let iframe=tabContentView.iframeElement;if(!(iframe instanceof HTMLIFrameElement)){WI.reportInternalError("Unable to evaluate without an <iframe> for extensionTabID: "+extensionTabID);return WI.WebInspectorExtension.ErrorCode.InvalidRequest;}
return new Promise((resolve,reject)=>{try{let result=InspectorFrontendHost.evaluateScriptInExtensionTab(iframe,scriptSource);if(result?.then){result.then((resolvedValue)=>resolve({result:resolvedValue}),(errorValue)=>reject({error:errorValue}));return;}
resolve({result});}catch(error){const stackIndent="  ";let stackLines=(error.stack?.split("\n")||[]).map((line)=>`${stackIndent}${line}`);let formattedMessage=[`Caught Exception: ${error.name}`,`at ${error.sourceURL || "(unknown)"}:${error.line || 0}:${error.column || 0}:`,error.message,"","Backtrace:",...stackLines,].join("\n");reject({error:formattedMessage});}});} 
_handleMainResourceDidChange(event)
{if(!event.target.isMainFrame())
return;if(!this._extensionForExtensionIDMap.size)
return;InspectorFrontendHost.inspectedPageDidNavigate(WI.networkManager.mainFrame.url);}};WI.WebInspectorExtensionController.Event={ExtensionAdded:"extension-added",ExtensionRemoved:"extension-removed",};WI.WorkerManager=class WorkerManager extends WI.Object
{constructor()
{super();this._connections=new Map;} 
initializeTarget(target)
{if(target.hasDomain("Worker"))
target.WorkerAgent.enable();} 
workerCreated(target,workerId,url,name)
{let connection=new InspectorBackend.WorkerConnection;let workerTarget=new WI.WorkerTarget(target,workerId,url,name,connection);workerTarget.initialize();WI.targetManager.addTarget(workerTarget);this._connections.set(workerId,connection);target.WorkerAgent.initialized(workerId).catch(function(){});}
workerTerminated(workerId)
{let connection=this._connections.take(workerId);WI.targetManager.removeTarget(connection.target);}
dispatchMessageFromWorker(workerId,message)
{let connection=this._connections.get(workerId);if(!connection)
return;connection.dispatch(message);}};WI.DiagnosticController=class DiagnosticController
{constructor()
{this._diagnosticLoggingAvailable=false;this._recorders=new Set;this._autoLogDiagnosticEventsToConsole=WI.settings.debugAutoLogDiagnosticEvents.value;this._logToConsoleMethod=window.InspectorTest?InspectorTest.log.bind(InspectorTest):console.log;WI.settings.debugEnableDiagnosticLogging.addEventListener(WI.Setting.Event.Changed,this._debugEnableDiagnosticLoggingSettingDidChange,this);WI.settings.debugAutoLogDiagnosticEvents.addEventListener(WI.Setting.Event.Changed,this._debugAutoLogDiagnosticEventsSettingDidChange,this);} 
get diagnosticLoggingAvailable()
{return this._diagnosticLoggingAvailable;}
set diagnosticLoggingAvailable(available)
{if(this._diagnosticLoggingAvailable===available)
return;this._diagnosticLoggingAvailable=available;this._updateRecorderStates();}
addRecorder(recorder)
{this._recorders.add(recorder);this._updateRecorderStates();}
logDiagnosticEvent(eventName,payload)
{if(window.InspectorTest){this._logToConsoleMethod(`Received diagnostic event: ${eventName} => ${JSON.stringify(payload)}`);return;}
if(this._autoLogDiagnosticEventsToConsole)
this._logToConsoleMethod(eventName,payload);InspectorFrontendHost.logDiagnosticEvent(eventName,JSON.stringify(payload));} 
_debugEnableDiagnosticLoggingSettingDidChange()
{this._updateRecorderStates();}
_debugAutoLogDiagnosticEventsSettingDidChange()
{this._autoLogDiagnosticEventsToConsole=WI.settings.debugAutoLogDiagnosticEvents.value;}
_updateRecorderStates()
{let isActive=this._diagnosticLoggingAvailable&&WI.settings.debugEnableDiagnosticLogging.value;for(let recorder of this._recorders)
recorder.active=isActive;}};WI.DiagnosticEventRecorder=class DiagnosticEventRecorder
{constructor(name,controller)
{this._name=name;this._active=false;this._controller=controller;} 
get name(){return this._name;}
get active()
{return this._active;}
set active(value)
{if(this._active===value)
return;this._active=value;if(this._active)
this.setup();else
this.teardown();} 
logDiagnosticEvent(eventName,payload)
{if(this._active)
this._controller.logDiagnosticEvent(eventName,payload);}
setup()
{throw WI.NotImplementedError.subclassMustOverride();}
teardown()
{throw WI.NotImplementedError.subclassMustOverride();}};WI.GridOverlayConfigurationDiagnosticEventRecorder=class GridOverlayConfigurationDiagnosticEventRecorder extends WI.DiagnosticEventRecorder
{constructor(controller)
{super("GridOverlayConfiguration",controller);this._inspectorHasFocus=true;this._lastUserInteractionTimestamp=undefined;this._eventSamplingTimerIdentifier=undefined;this._overlayOptions={};}

static get eventSamplingInterval(){return 60*1000;} 
setup()
{const options={capture:true,};window.addEventListener("focus",this,options);window.addEventListener("blur",this,options);window.addEventListener("keydown",this,options);window.addEventListener("mousedown",this,options);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayShown,this);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._handleGridOverlayHidden,this);}
teardown()
{const options={capture:true,};window.removeEventListener("focus",this,options);window.removeEventListener("blur",this,options);window.removeEventListener("keydown",this,options);window.removeEventListener("mousedown",this,options);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayShown,this);WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayHidden,this._handleGridOverlayHidden,this);this._stopEventSamplingTimerIfNeeded();}
_handleGridOverlayShown(event)
{this._overlayOptions.showTrackSizes=event.data.showTrackSizes;this._overlayOptions.showLineNumbers=event.data.showLineNumbers;this._overlayOptions.showLineNames=event.data.showLineNames;this._overlayOptions.showAreaNames=event.data.showAreaNames;this._overlayOptions.showExtendedGridLines=event.data.showExtendedGridLines;if(!this._eventSamplingTimerIdentifier)
this._startEventSamplingTimer();}
_handleGridOverlayHidden()
{if(WI.overlayManager.hasVisibleGridOverlays())
return;this._stopEventSamplingTimerIfNeeded();this._overlayOptions={};} 
handleEvent(event)
{switch(event.type){case"focus":this._handleWindowFocus(event);break;case"blur":this._handleWindowBlur(event);break;case"keydown":this._handleWindowKeyDown(event);break;case"mousedown":this._handleWindowMouseDown(event);break;}} 
_startEventSamplingTimer()
{this._stopEventSamplingTimerIfNeeded();this._eventSamplingTimerIdentifier=setTimeout(this._sampleCurrentOverlayConfiguration.bind(this),WI.GridOverlayConfigurationDiagnosticEventRecorder.eventSamplingInterval);}
_stopEventSamplingTimerIfNeeded()
{if(this._eventSamplingTimerIdentifier){clearTimeout(this._eventSamplingTimerIdentifier);this._eventSamplingTimerIdentifier=undefined;}}
_sampleCurrentOverlayConfiguration()
{this._stopEventSamplingTimerIfNeeded();this._startEventSamplingTimer();let intervalSinceLastUserInteraction=performance.now()-this._lastUserInteractionTimestamp;if(intervalSinceLastUserInteraction>WI.GridOverlayConfigurationDiagnosticEventRecorder.eventSamplingInterval){if(WI.settings.debugAutoLogDiagnosticEvents.valueRespectingDebugUIAvailability)
console.log("GridOverlayConfiguration: sample not reported, last user interaction was %.1f seconds ago.".format(intervalSinceLastUserInteraction/1000));return;}
let selectedTabContentView=WI.tabBrowser.selectedTabContentView;if(!selectedTabContentView)
return;let interval=WI.GridOverlayConfigurationDiagnosticEventRecorder.eventSamplingInterval/1000;let{showTrackSizes,showLineNumbers,showLineNames,showAreaNames,showExtendedGridLines}=this._overlayOptions;let configuration=0;configuration+=showTrackSizes?10000:0;configuration+=showLineNumbers?1000:0;configuration+=showLineNames?100:0;configuration+=showAreaNames?10:0;configuration+=showExtendedGridLines?1:0;configuration=configuration.toString().padStart(5,"0");this.logDiagnosticEvent(this.name,{interval,configuration,showTrackSizes,showLineNumbers,showLineNames,showAreaNames,showExtendedGridLines});}
_didObserveUserInteraction()
{if(!this._inspectorHasFocus)
return;this._lastUserInteractionTimestamp=performance.now();}
_handleWindowFocus(event)
{if(event.target!==window)
return;this._inspectorHasFocus=true;}
_handleWindowBlur(event)
{if(event.target!==window)
return;this._inspectorHasFocus=false;}
_handleWindowKeyDown(event)
{this._didObserveUserInteraction();}
_handleWindowMouseDown(event)
{this._didObserveUserInteraction();}};WI.GridOverlayDiagnosticEventRecorder=class GridOverlayDiagnosticEventRecorder extends WI.DiagnosticEventRecorder
{constructor(controller)
{super("GridOverlay",controller);this._initiators=Object.values(WI.GridOverlayDiagnosticEventRecorder.Initiator);} 
setup()
{WI.overlayManager.addEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayShown,this);}
teardown()
{WI.overlayManager.removeEventListener(WI.OverlayManager.Event.GridOverlayShown,this._handleGridOverlayShown,this);} 
_handleGridOverlayShown(event)
{let initiator=event.data.initiator;if(!initiator||!this._initiators.includes(initiator))
return;let showTrackSizes=event.data.showTrackSizes?1:0;let showLineNumbers=event.data.showLineNumbers?1:0;let showLineNames=event.data.showLineNames?1:0;let showAreaNames=event.data.showAreaNames?1:0;let showExtendedGridLines=event.data.showExtendedGridLines?1:0;this.logDiagnosticEvent(this.name,{initiator,showTrackSizes,showLineNumbers,showLineNames,showAreaNames,showExtendedGridLines});}};WI.GridOverlayDiagnosticEventRecorder.Initiator={Badge:"badge",Panel:"panel"};WI.InspectedTargetTypesDiagnosticEventRecorder=class InspectedTargetTypesDiagnosticEventRecorder extends WI.DiagnosticEventRecorder
{constructor(controller)
{super("InspectedTargetTypes",controller);this._initialDelayBeforeSamplingTimerIdentifier=undefined;} 
static get initialDelayBeforeSamplingInterval()
{return 5*1000;} 
setup()
{if(performance.now()-WI.frontendCompletedLoadTimestamp<InspectedTargetTypesDiagnosticEventRecorder.initialDelayBeforeSamplingInterval)
this._startInitialDelayBeforeSamplingTimer();else
this._sampleInspectedTarget();}
teardown()
{this._stopInitialDelayBeforeSamplingTimer();} 
_startInitialDelayBeforeSamplingTimer()
{if(this._initialDelayBeforeSamplingTimerIdentifier){clearTimeout(this._initialDelayBeforeSamplingTimerIdentifier);this._initialDelayBeforeSamplingTimerIdentifier=undefined;}
let maximumInitialDelay=InspectedTargetTypesDiagnosticEventRecorder.initialDelayBeforeSamplingInterval;let elapsedTime=performance.now()-WI.frontendCompletedLoadTimestamp;let remainingTime=maximumInitialDelay-elapsedTime;let initialDelay=Number.constrain(remainingTime,0,maximumInitialDelay);this._initialDelayBeforeSamplingTimerIdentifier=setTimeout(this._sampleInspectedTarget.bind(this),initialDelay);}
_stopInitialDelayBeforeSamplingTimer()
{if(this._initialDelayBeforeSamplingTimerIdentifier){clearTimeout(this._initialDelayBeforeSamplingTimerIdentifier);this._initialDelayBeforeSamplingTimerIdentifier=undefined;}}
_sampleInspectedTarget()
{this._stopInitialDelayBeforeSamplingTimer();this.logDiagnosticEvent(this.name,{debuggableType:this._determineDebuggableType(),targetPlatformName:this._determineTargetPlatformName(),targetBuildVersion:this._determineTargetBuildVersion(),targetProductVersion:this._determineTargetProductVersion(),targetIsSimulator:this._determineTargetIsSimulator(),});}
_determineDebuggableType()
{this._ensureCachedDebuggableInfo();return this._cachedDebuggableInfo.debuggableType;}
_determineTargetPlatformName()
{this._ensureCachedDebuggableInfo();return this._cachedDebuggableInfo.targetPlatformName;}
_determineTargetBuildVersion()
{this._ensureCachedDebuggableInfo();return this._cachedDebuggableInfo.targetBuildVersion;}
_determineTargetProductVersion()
{this._ensureCachedDebuggableInfo();return this._cachedDebuggableInfo.targetProductVersion;}
_determineTargetIsSimulator()
{this._ensureCachedDebuggableInfo();return!!this._cachedDebuggableInfo.targetIsSimulator;}
_ensureCachedDebuggableInfo()
{if(this._cachedDebuggableInfo)
return;let debuggableInfo=InspectorFrontendHost.debuggableInfo;this._cachedDebuggableInfo={debuggableType:WI.DebuggableType.fromString(debuggableInfo.debuggableType)||WI.DebuggableType.JavaScript,targetPlatformName:debuggableInfo.targetPlatformName||"Unknown",targetBuildVersion:debuggableInfo.targetBuildVersion||"Unknown",targetProductVersion:debuggableInfo.targetProductVersion||"Unknown",targetIsSimulator:debuggableInfo.targetIsSimulator,};}};WI.TabActivityDiagnosticEventRecorder=class TabActivityDiagnosticEventRecorder extends WI.DiagnosticEventRecorder
{constructor(controller)
{super("TabActivity",controller);this._inspectorHasFocus=true;this._lastUserInteractionTimestamp=undefined;this._eventSamplingTimerIdentifier=undefined;this._initialDelayBeforeSamplingTimerIdentifier=undefined;}

static get eventSamplingInterval(){return 60*1000;}
static get initialDelayBeforeSamplingInterval(){return 10*1000;} 
setup()
{const options={capture:true,};window.addEventListener("focus",this,options);window.addEventListener("blur",this,options);window.addEventListener("keydown",this,options);window.addEventListener("mousedown",this,options);if(performance.now()-WI.frontendCompletedLoadTimestamp<TabActivityDiagnosticEventRecorder.initialDelayBeforeSamplingInterval)
this._startInitialDelayBeforeSamplingTimer();else
this._startEventSamplingTimer();}
teardown()
{const options={capture:true,};window.removeEventListener("focus",this,options);window.removeEventListener("blur",this,options);window.removeEventListener("keydown",this,options);window.removeEventListener("mousedown",this,options);this._stopInitialDelayBeforeSamplingTimer();this._stopEventSamplingTimer();} 
handleEvent(event)
{switch(event.type){case"focus":this._handleWindowFocus(event);break;case"blur":this._handleWindowBlur(event);break;case"keydown":this._handleWindowKeyDown(event);break;case"mousedown":this._handleWindowMouseDown(event);break;}} 
_startInitialDelayBeforeSamplingTimer()
{if(this._initialDelayBeforeSamplingTimerIdentifier){clearTimeout(this._initialDelayBeforeSamplingTimerIdentifier);this._initialDelayBeforeSamplingTimerIdentifier=undefined;}
let maximumInitialDelay=TabActivityDiagnosticEventRecorder.initialDelayBeforeSamplingInterval;let elapsedTime=performance.now()-WI.frontendCompletedLoadTimestamp;let remainingTime=maximumInitialDelay-elapsedTime;let initialDelay=Number.constrain(remainingTime,0,maximumInitialDelay);this._initialDelayBeforeSamplingTimerIdentifier=setTimeout(this._sampleCurrentTabActivity.bind(this),initialDelay);}
_stopInitialDelayBeforeSamplingTimer()
{if(this._initialDelayBeforeSamplingTimerIdentifier){clearTimeout(this._initialDelayBeforeSamplingTimerIdentifier);this._initialDelayBeforeSamplingTimerIdentifier=undefined;}}
_startEventSamplingTimer()
{if(this._eventSamplingTimerIdentifier){clearTimeout(this._eventSamplingTimerIdentifier);this._eventSamplingTimerIdentifier=undefined;}
this._eventSamplingTimerIdentifier=setTimeout(this._sampleCurrentTabActivity.bind(this),TabActivityDiagnosticEventRecorder.eventSamplingInterval);}
_stopEventSamplingTimer()
{if(this._eventSamplingTimerIdentifier){clearTimeout(this._eventSamplingTimerIdentifier);this._eventSamplingTimerIdentifier=undefined;}}
_sampleCurrentTabActivity()
{this._stopEventSamplingTimer();this._stopInitialDelayBeforeSamplingTimer();this._startEventSamplingTimer();let intervalSinceLastUserInteraction=performance.now()-this._lastUserInteractionTimestamp;if(intervalSinceLastUserInteraction>TabActivityDiagnosticEventRecorder.eventSamplingInterval){if(WI.settings.debugAutoLogDiagnosticEvents.valueRespectingDebugUIAvailability)
console.log("TabActivity: sample not reported, last user interaction was %.1f seconds ago.".format(intervalSinceLastUserInteraction/1000));return;}
let selectedTabContentView=WI.tabBrowser.selectedTabContentView;if(!selectedTabContentView)
return;let tabType=selectedTabContentView.type;let interval=TabActivityDiagnosticEventRecorder.eventSamplingInterval/1000;this.logDiagnosticEvent(this.name,{tabType,interval});}
_didObserveUserInteraction()
{if(!this._inspectorHasFocus)
return;this._lastUserInteractionTimestamp=performance.now();}
_handleWindowFocus(event)
{if(event.target!==window)
return;this._inspectorHasFocus=true;}
_handleWindowBlur(event)
{if(event.target!==window)
return;this._inspectorHasFocus=false;}
_handleWindowKeyDown(event)
{this._didObserveUserInteraction();}
_handleWindowMouseDown(event)
{this._didObserveUserInteraction();}};WI.TabNavigationDiagnosticEventRecorder=class TabNavigationDiagnosticEventRecorder extends WI.DiagnosticEventRecorder
{constructor(controller)
{super("TabNavigation",controller);} 
setup()
{WI.tabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._selectedTabContentViewDidChange,this);}
teardown()
{WI.tabBrowser.removeEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._selectedTabContentViewDidChange,this);} 
_selectedTabContentViewDidChange(event)
{let outgoingTabType=event.data.outgoingTab.identifier;let incomingTabType=event.data.incomingTab.identifier;let initiator=WI.TabNavigationDiagnosticEventRecorder.tabBrowserInitiatorToEventInitiator(event.data.initiator||WI.TabBrowser.TabNavigationInitiator.Unknown);if(!initiator){WI.reportInternalError("Value of 'initiator' could not be parsed: "+event.data.initiator);return;}
this.logDiagnosticEvent(this.name,{outgoingTabType,incomingTabType,initiator});}
static tabBrowserInitiatorToEventInitiator(tabBrowserInitiator)
{switch(tabBrowserInitiator){case WI.TabBrowser.TabNavigationInitiator.TabClick:return"tab-click";case WI.TabBrowser.TabNavigationInitiator.LinkClick:return"link-click";case WI.TabBrowser.TabNavigationInitiator.ButtonClick:return"button-click";case WI.TabBrowser.TabNavigationInitiator.ContextMenu:return"context-menu";case WI.TabBrowser.TabNavigationInitiator.Dashboard:return"dashboard";case WI.TabBrowser.TabNavigationInitiator.Breakpoint:return"breakpoint";case WI.TabBrowser.TabNavigationInitiator.Inspect:return"inspect";case WI.TabBrowser.TabNavigationInitiator.KeyboardShortcut:return"keyboard-shortcut";case WI.TabBrowser.TabNavigationInitiator.FrontendAPI:return"frontend-api";case WI.TabBrowser.TabNavigationInitiator.Unknown:return"unknown";}
console.error("Unhandled initiator type: "+tabBrowserInitiator);return null;}};WI.ContentViewCookieType={ApplicationCache:"application-cache",CookieStorage:"cookie-storage",Database:"database",DatabaseTable:"database-table",DOMStorage:"dom-storage",Resource:"resource",Timelines:"timelines"};WI.SelectedSidebarPanelCookieKey="selected-sidebar-panel";WI.TypeIdentifierCookieKey="represented-object-type";WI.StateRestorationType={Load:"state-restoration-load",Navigation:"state-restoration-navigation",Delayed:"state-restoration-delayed",};WI.LayoutDirection={System:"system",LTR:"ltr",RTL:"rtl",};WI.loaded=function()
{if(InspectorBackend.registerAnimationDispatcher)
InspectorBackend.registerAnimationDispatcher(WI.AnimationObserver);if(InspectorBackend.registerApplicationCacheDispatcher)
InspectorBackend.registerApplicationCacheDispatcher(WI.ApplicationCacheObserver);if(InspectorBackend.registerBrowserDispatcher)
InspectorBackend.registerBrowserDispatcher(WI.BrowserObserver);if(InspectorBackend.registerCPUProfilerDispatcher)
InspectorBackend.registerCPUProfilerDispatcher(WI.CPUProfilerObserver);if(InspectorBackend.registerCSSDispatcher)
InspectorBackend.registerCSSDispatcher(WI.CSSObserver);if(InspectorBackend.registerCanvasDispatcher)
InspectorBackend.registerCanvasDispatcher(WI.CanvasObserver);if(InspectorBackend.registerConsoleDispatcher)
InspectorBackend.registerConsoleDispatcher(WI.ConsoleObserver);if(InspectorBackend.registerDOMDispatcher)
InspectorBackend.registerDOMDispatcher(WI.DOMObserver);if(InspectorBackend.registerDOMStorageDispatcher)
InspectorBackend.registerDOMStorageDispatcher(WI.DOMStorageObserver);if(InspectorBackend.registerDatabaseDispatcher)
InspectorBackend.registerDatabaseDispatcher(WI.DatabaseObserver);if(InspectorBackend.registerDebuggerDispatcher)
InspectorBackend.registerDebuggerDispatcher(WI.DebuggerObserver);if(InspectorBackend.registerHeapDispatcher)
InspectorBackend.registerHeapDispatcher(WI.HeapObserver);if(InspectorBackend.registerInspectorDispatcher)
InspectorBackend.registerInspectorDispatcher(WI.InspectorObserver);if(InspectorBackend.registerLayerTreeDispatcher)
InspectorBackend.registerLayerTreeDispatcher(WI.LayerTreeObserver);if(InspectorBackend.registerMemoryDispatcher)
InspectorBackend.registerMemoryDispatcher(WI.MemoryObserver);if(InspectorBackend.registerNetworkDispatcher)
InspectorBackend.registerNetworkDispatcher(WI.NetworkObserver);if(InspectorBackend.registerPageDispatcher)
InspectorBackend.registerPageDispatcher(WI.PageObserver);if(InspectorBackend.registerRuntimeDispatcher)
InspectorBackend.registerRuntimeDispatcher(WI.RuntimeObserver);if(InspectorBackend.registerScriptProfilerDispatcher)
InspectorBackend.registerScriptProfilerDispatcher(WI.ScriptProfilerObserver);if(InspectorBackend.registerTargetDispatcher)
InspectorBackend.registerTargetDispatcher(WI.TargetObserver);if(InspectorBackend.registerTimelineDispatcher)
InspectorBackend.registerTimelineDispatcher(WI.TimelineObserver);if(InspectorBackend.registerWorkerDispatcher)
InspectorBackend.registerWorkerDispatcher(WI.WorkerObserver);WI.Frame.addEventListener(WI.Frame.Event.ProvisionalLoadStarted,WI._provisionalLoadStarted,WI);WI.KeyboardShortcut.Key.Space._displayName=WI.UIString("Space");
WI.managers=[WI.browserManager=new WI.BrowserManager,WI.targetManager=new WI.TargetManager,WI.networkManager=new WI.NetworkManager,WI.domStorageManager=new WI.DOMStorageManager,WI.databaseManager=new WI.DatabaseManager,WI.indexedDBManager=new WI.IndexedDBManager,WI.domManager=new WI.DOMManager,WI.cssManager=new WI.CSSManager,WI.consoleManager=new WI.ConsoleManager,WI.runtimeManager=new WI.RuntimeManager,WI.heapManager=new WI.HeapManager,WI.memoryManager=new WI.MemoryManager,WI.applicationCacheManager=new WI.ApplicationCacheManager,WI.timelineManager=new WI.TimelineManager,WI.auditManager=new WI.AuditManager,WI.debuggerManager=new WI.DebuggerManager,WI.layerTreeManager=new WI.LayerTreeManager,WI.workerManager=new WI.WorkerManager,WI.domDebuggerManager=new WI.DOMDebuggerManager,WI.canvasManager=new WI.CanvasManager,WI.animationManager=new WI.AnimationManager,WI.overlayManager=new WI.OverlayManager,];WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,WI._debuggerDidPause,WI);WI.domManager.addEventListener(WI.DOMManager.Event.InspectModeStateChanged,WI._inspectModeStateChanged,WI);WI.domManager.addEventListener(WI.DOMManager.Event.DOMNodeWasInspected,WI._domNodeWasInspected,WI);WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasInspected,WI._domStorageWasInspected,WI);WI.databaseManager.addEventListener(WI.DatabaseManager.Event.DatabaseWasInspected,WI._databaseWasInspected,WI);WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange,WI._mainFrameDidChange,WI);WI.networkManager.addEventListener(WI.NetworkManager.Event.FrameWasAdded,WI._frameWasAdded,WI);WI.browserManager.enable();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,WI._mainResourceDidChange,WI);document.addEventListener("DOMContentLoaded",WI.contentLoaded);WI._showingSplitConsoleSetting=new WI.Setting("showing-split-console",false);WI._openTabsSetting=new WI.Setting("open-tab-types",[WI.ElementsTabContentView.Type,WI.ConsoleTabContentView.Type,WI.SourcesTabContentView.Type,WI.NetworkTabContentView.Type,WI.TimelineTabContentView.Type,WI.StorageTabContentView.Type,WI.GraphicsTabContentView.Type,WI.LayersTabContentView.Type,WI.AuditTabContentView.Type,]);WI._selectedTabIndexSetting=new WI.Setting("selected-tab-index",0);WI.printStylesEnabled=false;WI.setZoomFactor(WI.settings.zoomFactor.value);InspectorFrontendHost.setForcedAppearance(WI.settings.frontendAppearance.value);InspectorFrontendHost.setAllowsInspectingInspector(WI.settings.experimentalAllowInspectingInspector.value);WI.mouseCoords={x:0,y:0};WI.modifierKeys={altKey:false,metaKey:false,shiftKey:false};WI.visible=false;WI._windowKeydownListeners=[];WI._overridenDeviceUserAgent=null;WI._overridenDeviceScreenSize=null;WI._overridenDeviceSettings=new Map;WI.backendTarget=null;WI._backendTargetAvailablePromise=new WI.WrappedPromise;WI.pageTarget=null;WI._pageTargetAvailablePromise=new WI.WrappedPromise;
if(InspectorBackend.hasDomain("Target")){if(InspectorBackend.hasCommand("Target.exists")){InspectorBackend.invokeCommand("Target.exists",WI.TargetType.WebPage,InspectorBackend.backendConnection,{},(error)=>{if(error){WI.sharedApp._debuggableType=WI.DebuggableType.Page;WI.targetManager.createDirectBackendTarget();}});}else
WI.targetManager.createMultiplexingBackendTarget();}else
WI.targetManager.createDirectBackendTarget();};WI.contentLoaded=function()
{
if(window.__uncaughtExceptions)
return;document.addEventListener("beforecopy",WI._beforecopy);document.addEventListener("copy",WI._copy);document.addEventListener("paste",WI._paste);document.addEventListener("click",WI._mouseWasClicked);document.addEventListener("dragover",WI._handleDragOver);document.addEventListener("focus",WI._focusChanged,true);window.addEventListener("focus",WI._windowFocused);window.addEventListener("blur",WI._windowBlurred);window.addEventListener("resize",WI._windowResized);window.addEventListener("keydown",WI._windowKeyDown);window.addEventListener("keyup",WI._windowKeyUp);window.addEventListener("mousemove",WI._mouseMoved,true);window.addEventListener("pagehide",WI._pageHidden);window.addEventListener("contextmenu",WI._contextMenuRequested);document.body.classList.add(WI.Platform.name+"-platform");if(WI.Platform.version.name)
document.body.classList.add(WI.Platform.version.name);document.body.classList.add(WI.sharedApp.debuggableType);document.body.setAttribute("dir",WI.resolvedLayoutDirection());WI.layoutMeasurementContainer=document.body.appendChild(document.createElement("div"));WI.layoutMeasurementContainer.id="layout-measurement-container";WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed,WI._showJavaScriptTypeInformationSettingChanged,WI);WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed,WI._enableControlFlowProfilerSettingChanged,WI);WI.settings.resourceCachingDisabled.addEventListener(WI.Setting.Event.Changed,WI._resourceCachingDisabledSettingChanged,WI);WI.settings.experimentalAllowInspectingInspector.addEventListener(WI.Setting.Event.Changed,WI._allowInspectingInspectorSettingChanged,WI);function setTabSize(){document.body.style.tabSize=WI.settings.tabSize.value;}
WI.settings.tabSize.addEventListener(WI.Setting.Event.Changed,setTabSize,WI);setTabSize();function setInvisibleCharacterClassName(){document.body.classList.toggle("show-invisible-characters",WI.settings.showInvisibleCharacters.value);}
WI.settings.showInvisibleCharacters.addEventListener(WI.Setting.Event.Changed,setInvisibleCharacterClassName,WI);setInvisibleCharacterClassName();function setWhitespaceCharacterClassName(){document.body.classList.toggle("show-whitespace-characters",WI.settings.showWhitespaceCharacters.value);}
WI.settings.showWhitespaceCharacters.addEventListener(WI.Setting.Event.Changed,setWhitespaceCharacterClassName,WI);setWhitespaceCharacterClassName();WI.tabBar=new WI.TabBar(document.getElementById("tab-bar"));WI._contentElement=document.getElementById("content");WI._contentElement.role="tabpanel";WI.clearKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"K",WI._clear);WI.findString="";WI.populateFindKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"E",WI._populateFind);WI.populateFindKeyboardShortcut.implicitlyPreventsDefault=false;WI.findNextKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"G",WI._findNext);WI.findPreviousKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift|WI.KeyboardShortcut.Modifier.CommandOrControl,"G",WI._findPrevious);WI.consoleDrawer=new WI.ConsoleDrawer(document.getElementById("console-drawer"));WI.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged,WI._consoleDrawerCollapsedStateDidChange,WI);WI.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.Resized,WI._consoleDrawerDidResize,WI);WI.quickConsole=new WI.QuickConsole(document.getElementById("quick-console"));WI._consoleRepresentedObject=new WI.LogObject;WI.consoleContentView=WI.consoleDrawer.contentViewForRepresentedObject(WI._consoleRepresentedObject);WI.consoleLogViewController=WI.consoleContentView.logViewController;WI.navigationSidebar=new WI.SingleSidebar(document.getElementById("navigation-sidebar"),WI.Sidebar.Sides.Leading,WI.UIString("Navigation","Navigation @ Sidebar","Label for the navigation sidebar."));WI.navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,WI._sidebarWidthDidChange,WI);WI.navigationSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,WI._sidebarWidthDidChange,WI);WI.detailsSidebar=new WI.MultiSidebar(document.getElementById("details-sidebar"),WI.Sidebar.Sides.Trailing,WI.UIString("Details","Details @ Sidebar","Label for the details sidebar."));WI.detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,WI._sidebarWidthDidChange,WI);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,WI._sidebarWidthDidChange,WI);WI.detailsSidebar.addEventListener(WI.MultiSidebar.Event.MultipleSidebarsVisibleChanged,WI._sidebarWidthDidChange,WI);WI.searchKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"F",WI._focusSearchField);WI._findKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"F",WI._find);WI.saveKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"S",WI._save);WI._saveAsKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift|WI.KeyboardShortcut.Modifier.CommandOrControl,"S",WI._saveAs);WI.openResourceKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"O",WI._showOpenResourceDialog);new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"P",WI._showOpenResourceDialog);WI.navigationSidebarKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"0",WI.toggleNavigationSidebar);WI.detailsSidebarKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Option,"0",WI.toggleDetailsSidebar);let boundIncreaseZoom=WI._increaseZoom;let boundDecreaseZoom=WI._decreaseZoom;WI._increaseZoomKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Plus,boundIncreaseZoom);WI._decreaseZoomKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Minus,boundDecreaseZoom);WI._increaseZoomKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Plus,boundIncreaseZoom);WI._decreaseZoomKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Minus,boundDecreaseZoom);WI._resetZoomKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"0",WI._resetZoom);WI._showTabAtIndexKeyboardShortcuts=[1,2,3,4,5,6,7,8,9].map((i)=>new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Option,`${i}`,(event)=>{WI._showTabAtIndexFromShortcut(i);}));WI.tabBrowser=new WI.TabBrowser(document.getElementById("tab-browser"),WI.tabBar,WI.navigationSidebar,WI.detailsSidebar);WI.tabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,WI._tabBrowserSelectedTabContentViewDidChange,WI);WI._reloadPageKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"R",WI._reloadPage);WI._reloadPageFromOriginKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Option,"R",WI._reloadPageFromOrigin);WI._reloadPageKeyboardShortcut.implicitlyPreventsDefault=WI._reloadPageFromOriginKeyboardShortcut.implicitlyPreventsDefault=false;WI._consoleTabKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Option|WI.KeyboardShortcut.Modifier.CommandOrControl,"C",WI._showConsoleTab);WI._quickConsoleKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,WI.KeyboardShortcut.Key.Apostrophe,WI._focusConsolePrompt);WI._inspectModeKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"C",WI._toggleInspectMode);WI._undoKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"Z",WI._undoKeyboardShortcut);WI._redoKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"Z",WI._redoKeyboardShortcut);WI._undoKeyboardShortcut.implicitlyPreventsDefault=WI._redoKeyboardShortcut.implicitlyPreventsDefault=false;WI.toggleBreakpointsKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,"Y",WI.debuggerToggleBreakpoints);WI.pauseOrResumeKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control|WI.KeyboardShortcut.Modifier.CommandOrControl,"Y",WI.debuggerPauseResumeToggle);WI.stepOverKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.F6,WI.debuggerStepOver);WI.stepIntoKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.F7,WI.debuggerStepInto);WI.stepOutKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.F8,WI.debuggerStepOut);WI.pauseOrResumeAlternateKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Backslash,WI.debuggerPauseResumeToggle);WI.stepOverAlternateKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.SingleQuote,WI.debuggerStepOver);WI.stepIntoAlternateKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Semicolon,WI.debuggerStepInto);WI.stepOutAlternateKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift|WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Semicolon,WI.debuggerStepOut);if(InspectorBackend.hasCommand("Debugger.stepNext")){WI.stepNextKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.F9,WI.debuggerStepNext);WI.stepNextAlternateKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift|WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.SingleQuote,WI.debuggerStepNext);}
WI.settingsKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl,WI.KeyboardShortcut.Key.Comma,WI._handleSettingsKeyboardShortcut);WI._togglePreviousDockConfigurationKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,"D",WI._togglePreviousDockConfiguration);let dockingConfigurationNavigationItems=[];let supportsDockRight=InspectorFrontendHost.supportsDockSide(WI.DockConfiguration.Right);let supportsDockLeft=InspectorFrontendHost.supportsDockSide(WI.DockConfiguration.Left);let supportsDockBottom=InspectorFrontendHost.supportsDockSide(WI.DockConfiguration.Bottom);let supportsUndocked=InspectorFrontendHost.supportsDockSide(WI.DockConfiguration.Undocked);if(supportsDockRight||supportsDockLeft||supportsDockBottom){WI._closeTabBarButton=new WI.ButtonNavigationItem("dock-close",WI.UIString("Close"),"Images/CloseLarge.svg");WI._closeTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.close,WI);dockingConfigurationNavigationItems.push(WI._closeTabBarButton);}
if((supportsDockRight||supportsDockLeft)&&(supportsDockBottom||supportsUndocked)){WI._dockToSideTabBarButton=new WI.ButtonNavigationItem("dock-right",WI.UIString("Dock to side of window"),WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"Images/DockLeft.svg":"Images/DockRight.svg",16,16);WI._dockToSideTabBarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);WI._dockToSideTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?WI._dockLeft:WI._dockRight,WI);dockingConfigurationNavigationItems.push(WI._dockToSideTabBarButton);}
if(supportsDockBottom&&(supportsDockRight||supportsDockLeft||supportsUndocked)){WI._dockBottomTabBarButton=new WI.ButtonNavigationItem("dock-bottom",WI.UIString("Dock to bottom of window"),"Images/DockBottom.svg",16,16);WI._dockBottomTabBarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);WI._dockBottomTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._dockBottom,WI);dockingConfigurationNavigationItems.push(WI._dockBottomTabBarButton);}
if(supportsUndocked&&(supportsDockRight||supportsDockLeft||supportsDockBottom)){WI._undockTabBarButton=new WI.ButtonNavigationItem("undock",WI.UIString("Detach into separate window"),"Images/Undock.svg",16,16);WI._undockTabBarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);WI._undockTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._undock,WI);dockingConfigurationNavigationItems.push(WI._undockTabBarButton);}
let inspectedPageControlNavigationItems=[];let elementSelectionToolTip=WI.UIString("Start element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);let activatedElementSelectionToolTip=WI.UIString("Stop element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);WI._inspectModeTabBarButton=new WI.ActivateButtonNavigationItem("inspect",elementSelectionToolTip,activatedElementSelectionToolTip,"Images/Crosshair.svg");WI._inspectModeTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._toggleInspectMode,WI);inspectedPageControlNavigationItems.push(WI._inspectModeTabBarButton);if(InspectorFrontendHost.isRemote||WI.isDebugUIEnabled()){if(InspectorBackend.hasCommand("Page.overrideUserAgent")&&InspectorBackend.hasCommand("Page.overrideSetting")){const deviceSettingsTooltip=WI.UIString("Device Settings");WI._deviceSettingsTabBarButton=new WI.ActivateButtonNavigationItem("device-settings",deviceSettingsTooltip,deviceSettingsTooltip,"Images/Device.svg");WI._deviceSettingsTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._handleDeviceSettingsTabBarButtonClicked,WI);inspectedPageControlNavigationItems.push(WI._deviceSettingsTabBarButton);WI._deviceSettingsPopover=null;}
let reloadToolTip;if(WI.sharedApp.debuggableType===WI.DebuggableType.JavaScript||WI.sharedApp.debuggableType===WI.DebuggableType.ITML)
reloadToolTip=WI.UIString("Restart (%s)").format(WI._reloadPageKeyboardShortcut.displayName);else
reloadToolTip=WI.UIString("Reload page (%s)\nReload page ignoring cache (%s)").format(WI._reloadPageKeyboardShortcut.displayName,WI._reloadPageFromOriginKeyboardShortcut.displayName);WI._reloadTabBarButton=new WI.ButtonNavigationItem("reload",reloadToolTip,"Images/ReloadToolbar.svg");WI._reloadTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._reloadTabBarButtonClicked,WI);inspectedPageControlNavigationItems.push(WI._reloadTabBarButton);WI._downloadTabBarButton=new WI.ButtonNavigationItem("download",WI.UIString("Download Web Archive"),"Images/DownloadArrow.svg");WI._downloadTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI._downloadWebArchive,WI);inspectedPageControlNavigationItems.push(WI._downloadTabBarButton);}
WI.tabBar.addNavigationItemBefore(new WI.GroupNavigationItem([...dockingConfigurationNavigationItems,...inspectedPageControlNavigationItems,]));WI._consoleDividerNavigationItem=new WI.DividerNavigationItem;WI.tabBar.addNavigationItemBefore(WI._consoleDividerNavigationItem);WI._consoleWarningsTabBarButton=new WI.ButtonNavigationItem("console-warnings",WI.UIString("0 Console warnings"),"Images/IssuesEnabled.svg");WI._consoleWarningsTabBarButton.imageType=WI.ButtonNavigationItem.ImageType.IMG;WI._consoleWarningsTabBarButton.hidden=true;WI._consoleWarningsTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.showConsoleTab(WI.LogContentView.Scopes.Warnings,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.Dashboard,});},WI);WI._consoleErrorsTabBarButton=new WI.ButtonNavigationItem("console-errors",WI.UIString("0 Console errors"),"Images/ErrorsEnabled.svg");WI._consoleErrorsTabBarButton.imageType=WI.ButtonNavigationItem.ImageType.IMG;WI._consoleErrorsTabBarButton.hidden=true;WI._consoleErrorsTabBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.showConsoleTab(WI.LogContentView.Scopes.Errors,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.Dashboard,});},WI);WI.tabBar.addNavigationItemBefore(new WI.GroupNavigationItem([WI._consoleWarningsTabBarButton,WI._consoleErrorsTabBarButton,]));WI._updateInspectModeTabBarButton();WI._updateDownloadTabBarButton();WI._updateReloadTabBarButton();WI.consoleManager.addEventListener(WI.ConsoleManager.Event.MessageAdded,WI._updateConsoleTabBarButtons,WI);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.PreviousMessageRepeatCountUpdated,WI._updateConsoleTabBarButtons,WI);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,WI._updateConsoleTabBarButtons,WI);WI._updateConsoleTabBarButtons();if(supportsDockRight||supportsDockLeft||supportsDockBottom){WI._dockedResizerElement=document.getElementById("docked-resizer");WI._dockedResizerElement.classList.add(WI.Popover.IgnoreAutoDismissClassName);WI._dockedResizerElement.addEventListener("mousedown",WI._handleDockedResizerMouseDown);}
if(supportsUndocked){let undockedTitleAreaElement=document.getElementById("undocked-title-area");undockedTitleAreaElement.addEventListener("mousedown",WI._handleUndockedTitleAreaMouseDown);}
WI._dockingAvailable=false;WI._updateDockNavigationItems();WI._setupViewHierarchy();let productionTabClasses=[WI.ElementsTabContentView,WI.NetworkTabContentView,WI.SourcesTabContentView,WI.TimelineTabContentView,WI.StorageTabContentView,WI.GraphicsTabContentView,WI.LayersTabContentView,WI.AuditTabContentView,WI.ConsoleTabContentView,WI.SearchTabContentView,WI.SettingsTabContentView,];WI._knownTabClassesByType=new Map;
for(let tabClass of productionTabClasses)
WI._knownTabClassesByType.set(tabClass.Type,tabClass);WI._pendingOpenTabs=[];WI._searchTabContentView=new WI.SearchTabContentView;WI.tabBrowser.addTabForContentView(WI._searchTabContentView,{suppressAnimations:true});WI._settingsTabContentView=new WI.SettingsTabContentView;WI.tabBrowser.addTabForContentView(WI._settingsTabContentView,{suppressAnimations:true});let openTabTypes=WI._openTabsSetting.value;let seenTabTypes=new Set;for(let i=0;i<openTabTypes.length;++i){let tabType=openTabTypes[i];if(seenTabTypes.has(tabType))
continue;seenTabTypes.add(tabType);if(!WI.isTabTypeAllowed(tabType)){WI._pendingOpenTabs.push({tabType,index:i});continue;}
if(!WI.isNewTabWithTypeAllowed(tabType))
continue;let tabContentView=WI._createTabContentViewForType(tabType);if(!tabContentView)
continue;WI.tabBrowser.addTabForContentView(tabContentView,{suppressAnimations:true});}
WI._restoreCookieForOpenTabs(WI.StateRestorationType.Load);if(WI.tabBar.normalTabCount)
WI.tabBar.selectedTabBarItem=WI._selectedTabIndexSetting.value;else{for(let tabType of WI._openTabsSetting.defaultValue){if(WI.isNewTabWithTypeAllowed(tabType))
WI.createNewTabWithType(tabType)}
WI.tabBar.selectedTabBarItem=0;}
WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded,WI._rememberOpenTabs,WI);WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved,WI._rememberOpenTabs,WI);WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemsReordered,WI._rememberOpenTabs,WI);function updateConsoleSavedResultPrefixCSSVariable(){document.body.style.setProperty("--console-saved-result-prefix","\""+WI.RuntimeManager.preferredSavedResultPrefix()+"\"");}
WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,updateConsoleSavedResultPrefixCSSVariable,WI);updateConsoleSavedResultPrefixCSSVariable();function updateZoomFactorCSSVariable(){document.body.style.setProperty("--zoom-factor",WI.settings.zoomFactor.value);}
WI.settings.zoomFactor.addEventListener(WI.Setting.Event.Changed,updateZoomFactorCSSVariable,WI);updateZoomFactorCSSVariable();WI.settings.frontendAppearance.addEventListener(WI.Setting.Event.Changed,function(event){InspectorFrontendHost.setForcedAppearance(WI.settings.frontendAppearance.value);},WI);WI._backendTargetAvailablePromise.promise.then(()=>{InspectorFrontendAPI.loadCompleted();});WI._updateSheetRect();
InspectorFrontendHost.loaded();if(WI._showingSplitConsoleSetting.value)
WI.showSplitConsole();window.__frontendCompletedLoad=true;WI.frontendCompletedLoadTimestamp=performance.now();if(WI.runBootstrapOperations)
WI.runBootstrapOperations();if(InspectorFrontendHost.supportsDiagnosticLogging){WI.diagnosticController=new WI.DiagnosticController;WI.diagnosticController.addRecorder(new WI.InspectedTargetTypesDiagnosticEventRecorder(WI.diagnosticController));WI.diagnosticController.addRecorder(new WI.TabActivityDiagnosticEventRecorder(WI.diagnosticController));WI.diagnosticController.addRecorder(new WI.TabNavigationDiagnosticEventRecorder(WI.diagnosticController));if(InspectorBackend.hasCommand("DOM.showGridOverlay")){WI.diagnosticController.addRecorder(new WI.GridOverlayDiagnosticEventRecorder(WI.diagnosticController));WI.diagnosticController.addRecorder(new WI.GridOverlayConfigurationDiagnosticEventRecorder(WI.diagnosticController));}}};WI.performOneTimeFrontendInitializationsUsingTarget=function(target)
{if(!WI.__didPerformConsoleInitialization&&target.hasDomain("Console")){WI.__didPerformConsoleInitialization=true;WI.consoleManager.initializeLogChannels(target);}
if(!WI.__didPerformCSSInitialization&&target.hasDomain("CSS")){WI.__didPerformCSSInitialization=true;WI.CSSCompletions.initializeCSSCompletions(target);}};WI.initializeTarget=function(target)
{if(target.hasDomain("Page")){if(target.hasCommand("Page.overrideUserAgent")&&WI._overridenDeviceUserAgent)
target.PageAgent.overrideUserAgent(WI._overridenDeviceUserAgent);if(target.hasCommand("Page.overrideSetting")){for(let[setting,value]of WI._overridenDeviceSettings)
target.PageAgent.overrideSetting(setting,value);}
if(target.hasCommand("Page.setShowRulers")&&WI.settings.showRulers.value)
target.PageAgent.setShowRulers(true);}};WI.targetsAvailable=function()
{return WI._pageTargetAvailablePromise.settled;};WI.whenTargetsAvailable=function()
{return WI._pageTargetAvailablePromise.promise;};WI.isTabTypeAllowed=function(tabType)
{let tabClass=WI._knownTabClassesByType.get(tabType);if(!tabClass)
return false;return tabClass.isTabAllowed();};WI.knownTabClasses=function()
{return new Set(WI._knownTabClassesByType.values());};WI._showOpenResourceDialog=function()
{if(!WI._openResourceDialog)
WI._openResourceDialog=new WI.OpenResourceDialog(WI);if(WI._openResourceDialog.visible)
return;WI._openResourceDialog.present(WI._contentElement);};WI._createTabContentViewForType=function(tabType)
{let tabClass=WI._knownTabClassesByType.get(tabType);if(!tabClass){console.error("Unknown tab type",tabType);return null;}
if(tabClass===WI.WebInspectorExtensionTabContentView)
return null;return new tabClass;};WI._rememberOpenTabs=function()
{let seenTabTypes=new Set;let openTabs=[];for(let tabBarItem of WI.tabBar.tabBarItems){let tabContentView=tabBarItem.representedObject;if(!(tabContentView instanceof WI.TabContentView))
continue;if(!tabContentView.constructor.shouldSaveTab())
continue;openTabs.push(tabContentView.type);seenTabTypes.add(tabContentView.type);}
for(let{tabType,index}of WI._pendingOpenTabs){if(seenTabTypes.has(tabType))
continue;openTabs.insertAtIndex(tabType,index);seenTabTypes.add(tabType);}
WI._openTabsSetting.value=openTabs;};WI._handleSettingsKeyboardShortcut=function(event)
{if(event.keyIdentifier==="U+002C"){WI.tabBrowser.showTabForContentView(WI._settingsTabContentView,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.KeyboardShortcut,});}};WI._tryToRestorePendingTabs=function()
{let stillPendingOpenTabs=[];for(let{tabType,index}of WI._pendingOpenTabs){if(!WI.isTabTypeAllowed(tabType)){stillPendingOpenTabs.push({tabType,index});continue;}
let tabContentView=WI._createTabContentViewForType(tabType);if(!tabContentView)
continue;WI.tabBrowser.addTabForContentView(tabContentView,{suppressAnimations:true,insertionIndex:index,});tabContentView.restoreStateFromCookie(WI.StateRestorationType.Load);}
WI._pendingOpenTabs=stillPendingOpenTabs;};WI.isNewTabWithTypeAllowed=function(tabType)
{if(tabType===WI.WebInspectorExtensionTabContentView.Type)
return false;let tabClass=WI._knownTabClassesByType.get(tabType);if(!tabClass||!tabClass.isTabAllowed())
return false;for(let tabBarItem of WI.tabBar.tabBarItems){let tabContentView=tabBarItem.representedObject;if(!(tabContentView instanceof WI.TabContentView))
continue;if(tabContentView.constructor===tabClass)
return false;}
return true;};WI.createNewTabWithType=function(tabType,options={})
{let{referencedView,shouldReplaceTab,shouldShowNewTab}=options;let tabContentView=WI._createTabContentViewForType(tabType);const suppressAnimations=true;WI.tabBrowser.addTabForContentView(tabContentView,{suppressAnimations,insertionIndex:referencedView?WI.tabBar.tabBarItems.indexOf(referencedView.tabBarItem):undefined,});if(shouldReplaceTab)
WI.tabBrowser.closeTabForContentView(referencedView,{...options,suppressAnimations});if(shouldShowNewTab)
WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.activateExtraDomains=function(domains)
{WI.notifications.dispatchEventToListeners(WI.Notification.ExtraDomainsActivated,{domains});if(WI.mainTarget){if(!WI.pageTarget&&WI.mainTarget.hasDomain("DOM"))
WI.pageTarget=WI.mainTarget;if(WI.mainTarget.hasDomain("CSS"))
WI.CSSCompletions.initializeCSSCompletions(WI.assumingMainTarget());if(WI.mainTarget.hasDomain("DOM"))
WI.domManager.ensureDocument();if(WI.mainTarget.hasDomain("Page"))
WI.networkManager.initializeTarget(WI.mainTarget);}
WI._updateInspectModeTabBarButton();WI._updateDownloadTabBarButton();WI._updateReloadTabBarButton();WI._tryToRestorePendingTabs();};WI.updateWindowTitle=function()
{var mainFrame=WI.networkManager.mainFrame;if(!mainFrame)
return;var urlComponents=mainFrame.mainResource.urlComponents;var lastPathComponent;try{lastPathComponent=decodeURIComponent(urlComponents.lastPathComponent||"");}catch{lastPathComponent=urlComponents.lastPathComponent;}
if(urlComponents.host&&lastPathComponent)
var title=WI.displayNameForHost(urlComponents.host)+" \u2014 "+lastPathComponent;else if(urlComponents.host)
var title=WI.displayNameForHost(urlComponents.host);else if(lastPathComponent)
var title=lastPathComponent;else
var title=mainFrame.url;
InspectorFrontendHost.inspectedURLChanged(title);};WI.updateDockingAvailability=function(available)
{WI._dockingAvailable=available;WI._updateDockNavigationItems();if(!WI._dockingAvailable)
WI.updateDockedState(WI.DockConfiguration.Undocked);};WI.updateDockedState=function(side)
{if(WI.dockConfiguration===side)
return;WI._previousDockConfiguration=WI.dockConfiguration;if(!WI._previousDockConfiguration){if(side===WI.DockConfiguration.Right||side===WI.DockConfiguration.Left)
WI._previousDockConfiguration=WI.DockConfiguration.Bottom;else
WI._previousDockConfiguration=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?WI.DockConfiguration.Left:WI.DockConfiguration.Right;}
WI.dockConfiguration=side;switch(WI.dockConfiguration){case WI.DockConfiguration.Bottom:document.body.classList.add("docked",WI.DockConfiguration.Bottom);document.body.classList.remove("window-inactive",WI.DockConfiguration.Right,WI.DockConfiguration.Left);break;case WI.DockConfiguration.Right:document.body.classList.add("docked",WI.DockConfiguration.Right);document.body.classList.remove("window-inactive",WI.DockConfiguration.Bottom,WI.DockConfiguration.Left);break;case WI.DockConfiguration.Left:document.body.classList.add("docked",WI.DockConfiguration.Left);document.body.classList.remove("window-inactive",WI.DockConfiguration.Bottom,WI.DockConfiguration.Right);break;default:document.body.classList.remove("docked",WI.DockConfiguration.Right,WI.DockConfiguration.Left,WI.DockConfiguration.Bottom);break;}
WI._updateDockNavigationItems();if(!WI.dockedConfigurationSupportsSplitContentBrowser()&&!WI.doesCurrentTabSupportSplitContentBrowser())
WI.hideSplitConsole();if(side===WI.DockConfiguration.Undocked&&WI.Platform.name==="mac"){document.body.addEventListener("focusin",function(event){let firstFocusableElement=document.querySelector("[tabindex='0']:not(.hidden)");if(firstFocusableElement===event.target){if(WI.previousFocusElement)
WI.previousFocusElement.focus();else
event.target.blur();}},{once:true,capture:true});}};WI.resizeDockedFrameMouseDown=function(event)
{if(event.button!==0||event.ctrlKey)
return;event[WI.Popover.EventPreventDismissSymbol]=true;let isDockedBottom=WI.dockConfiguration===WI.DockConfiguration.Bottom;let windowProperty=isDockedBottom?"innerHeight":"innerWidth";let eventScreenProperty=isDockedBottom?"screenY":"screenX";let eventClientProperty=isDockedBottom?"clientY":"clientX";let resizerElement=event.target;let firstClientPosition=event[eventClientProperty];let lastScreenPosition=event[eventScreenProperty];function dividerDrag(event)
{if(event.button!==0)
return;let position=event[eventScreenProperty];let delta=position-lastScreenPosition;let clientPosition=event[eventClientProperty];lastScreenPosition=position;if(WI.dockConfiguration===WI.DockConfiguration.Left){if(delta>0&&clientPosition<firstClientPosition)
return;if(delta<0&&clientPosition>window[windowProperty])
return;
delta*=-1;}else{if(delta>0&&clientPosition<firstClientPosition)
return;if(delta<0&&clientPosition>firstClientPosition)
return;}
let dimension=Math.max(0,window[windowProperty]-delta);
dimension*=WI.getZoomFactor();if(isDockedBottom)
InspectorFrontendHost.setAttachedWindowHeight(dimension);else
InspectorFrontendHost.setAttachedWindowWidth(dimension);}
function elementDragEnd(event)
{if(event.button!==0)
return;WI.elementDragEnd(event);}
let cursor=isDockedBottom?"row-resize":"col-resize";WI.elementDragStart(resizerElement,dividerDrag,elementDragEnd,event,cursor);};WI.moveUndockedWindowMouseDown=function(event)
{if(event.button!==0||event.ctrlKey)
return;event[WI.Popover.EventPreventDismissSymbol]=true;if(WI.Platform.name==="mac"){InspectorFrontendHost.startWindowDrag();event.preventDefault();return;}
let lastScreenX=event.screenX;let lastScreenY=event.screenY;function dividerDrag(event){if(event.button!==0)
return;let x=event.screenX-lastScreenX;let y=event.screenY-lastScreenY;InspectorFrontendHost.moveWindowBy(x,y);lastScreenX=event.screenX;lastScreenY=event.screenY;}
function elementDragEnd(event){if(event.button!==0)
return;WI.elementDragEnd(event);}
const cursor="default";WI.elementDragStart(event.target,dividerDrag,elementDragEnd,event,cursor);};WI.updateVisibilityState=function(visible)
{WI.visible=visible;WI.notifications.dispatchEventToListeners(WI.Notification.VisibilityStateDidChange);};WI.updateFindString=function(findString)
{if(!findString||WI.findString===findString)
return false;WI.findString=findString;return true;};WI.handlePossibleLinkClick=function(event,frame,options={})
{let anchorElement=event.target.closest("a");if(!anchorElement||!anchorElement.href)
return false;if(WI.isBeingEdited(anchorElement)){return false;}
event.preventDefault();event.stopPropagation();WI.openURL(anchorElement.href,frame,{...options,lineNumber:anchorElement.lineNumber,ignoreSearchTab:!WI.isShowingSearchTab(),});return true;};WI.openURL=function(url,frame,options={})
{if(!url)
return;if(options.alwaysOpenExternally===undefined||options.alwaysOpenExternally===null)
options.alwaysOpenExternally=window.event?window.event.metaKey:false;if(options.alwaysOpenExternally){InspectorFrontendHost.openURLExternally(url);return;}
let searchChildFrames=false;if(!frame){frame=WI.networkManager.mainFrame;searchChildFrames=true;}
let resource;let simplifiedURL=removeURLFragment(url);if(frame){resource=frame.url===simplifiedURL?frame.mainResource:frame.resourcesForURL(simplifiedURL,searchChildFrames).firstValue;}else if(WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker)
resource=WI.mainTarget.resourceCollection.resourcesForURL(removeURLFragment(url)).firstValue;if(resource){if(!options.initiatorHint)
options.initiatorHint=WI.TabBrowser.TabNavigationInitiator.LinkClick;let positionToReveal=new WI.SourceCodePosition(options.lineNumber,0);WI.showSourceCode(resource,{...options,positionToReveal});return;}
InspectorFrontendHost.openURLExternally(url);};WI.close=function()
{if(WI._isClosing)
return;WI._isClosing=true;InspectorFrontendHost.closeWindow();};WI.isContentAreaFocused=function()
{return WI._contentElement.contains(document.activeElement);}
WI.isConsoleFocused=function()
{return!WI._didAutofocusConsolePrompt&&WI.quickConsole.prompt.focused;};WI.isShowingSplitConsole=function()
{return!WI.consoleDrawer.collapsed;};WI.dockedConfigurationSupportsSplitContentBrowser=function()
{return!WI.dockConfiguration||WI.dockConfiguration!==WI.DockConfiguration.Bottom;};WI.doesCurrentTabSupportSplitContentBrowser=function()
{var currentContentView=WI.tabBrowser.selectedTabContentView;return!currentContentView||currentContentView.supportsSplitContentBrowser;};WI.toggleSplitConsole=function()
{if(!WI.doesCurrentTabSupportSplitContentBrowser()){WI.showConsoleTab();return;}
if(WI.isShowingSplitConsole())
WI.hideSplitConsole();else
WI.showSplitConsole();};WI.showSplitConsole=function()
{if(!WI.doesCurrentTabSupportSplitContentBrowser()){WI.showConsoleTab();return;}
WI.consoleDrawer.collapsed=false;if(WI.consoleDrawer.currentContentView===WI.consoleContentView)
return;WI.consoleDrawer.showContentView(WI.consoleContentView);};WI.hideSplitConsole=function()
{if(!WI.isShowingSplitConsole())
return;WI.consoleDrawer.collapsed=true;};WI.showConsoleTab=function(requestedScope,options={})
{requestedScope=requestedScope||WI.LogContentView.Scopes.All;WI.hideSplitConsole();WI.consoleContentView.scopeBar.item(requestedScope).selected=true;const cookie=null;WI.showRepresentedObject(WI._consoleRepresentedObject,cookie,options);};WI.isShowingConsoleTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.ConsoleTabContentView;};WI.showElementsTab=function(options={})
{var tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.ElementsTabContentView);if(!tabContentView)
tabContentView=new WI.ElementsTabContentView;WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.isShowingElementsTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.ElementsTabContentView;};WI.showSourcesTab=function(options={})
{let tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.SourcesTabContentView);if(!tabContentView)
tabContentView=new WI.SourcesTabContentView;if(options.representedObjectToSelect)
tabContentView.revealAndSelectRepresentedObject(options.representedObjectToSelect);if(options.showScopeChainSidebar)
tabContentView.showScopeChainDetailsSidebarPanel();WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.isShowingSourcesTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.SourcesTabContentView;};WI.showStorageTab=function(options={})
{var tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.StorageTabContentView);if(!tabContentView)
tabContentView=new WI.StorageTabContentView;WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.showNetworkTab=function(options={})
{let tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.NetworkTabContentView);if(!tabContentView)
tabContentView=new WI.NetworkTabContentView;WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.isShowingNetworkTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.NetworkTabContentView;};WI.isShowingSearchTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView;};WI.showTimelineTab=function(options={})
{var tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.TimelineTabContentView);if(!tabContentView)
tabContentView=new WI.TimelineTabContentView;WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.isShowingTimelineTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.TimelineTabContentView;};WI.isShowingAuditTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.AuditTabContentView;}
WI.showLayersTab=function(options={})
{let tabContentView=WI.tabBrowser.bestTabContentViewForClass(WI.LayersTabContentView);if(!tabContentView)
tabContentView=new WI.LayersTabContentView;if(options.nodeToSelect)
tabContentView.selectLayerForNode(options.nodeToSelect);WI.tabBrowser.showTabForContentView(tabContentView,options);};WI.isShowingLayersTab=function()
{return WI.tabBrowser.selectedTabContentView instanceof WI.LayersTabContentView;};WI.showSettingsTab=function(options={})
{WI.tabBrowser.showTabForContentView(WI._settingsTabContentView,options);if(options.blackboxPatternToSelect)
WI._settingsTabContentView.selectBlackboxPattern(options.blackboxPatternToSelect);};WI.indentString=function()
{if(WI.settings.indentWithTabs.value)
return"\t";return" ".repeat(WI.settings.indentUnit.value);};WI.restoreFocusFromElement=function(element)
{if(element&&element.contains(WI.currentFocusElement))
WI.previousFocusElement.focus();};WI.toggleNavigationSidebar=function(event)
{if(!WI.navigationSidebar.collapsed||!WI.navigationSidebar.sidebarPanels.length){WI.navigationSidebar.collapsed=true;return;}
if(!WI.navigationSidebar.selectedSidebarPanel)
WI.navigationSidebar.selectedSidebarPanel=WI.navigationSidebar.sidebarPanels[0];WI.navigationSidebar.collapsed=false;};WI.toggleDetailsSidebar=function(event)
{if(!WI.detailsSidebar.collapsed||!WI.detailsSidebar.sidebarPanels.length){WI.detailsSidebar.collapsed=true;return;}
if(!WI.detailsSidebar.selectedSidebarPanel)
WI.detailsSidebar.selectedSidebarPanel=WI.detailsSidebar.sidebarPanels[0];WI.detailsSidebar.collapsed=false;};WI.getMaximumSidebarWidth=function(sidebar)
{const minimumContentBrowserWidth=200;let minimumWidth=window.innerWidth-minimumContentBrowserWidth;let tabContentView=WI.tabBrowser.selectedTabContentView;if(!tabContentView)
return minimumWidth;if(tabContentView.navigationSidebarPanel&&sidebar!==WI.navigationSidebar)
minimumWidth-=WI.navigationSidebar.width;if(tabContentView.detailsSidebarPanels&&sidebar!==WI.detailsSidebar){for(let singleDetailsSidebar of WI.detailsSidebar.sidebars){if(sidebar!==singleDetailsSidebar)
minimumWidth-=singleDetailsSidebar.width;}}
return minimumWidth;};WI.tabContentViewClassForRepresentedObject=function(representedObject)
{if(representedObject instanceof WI.DOMTree)
return WI.ElementsTabContentView;if(representedObject instanceof WI.TimelineRecording)
return WI.TimelineTabContentView;if(representedObject===WI._consoleRepresentedObject)
return WI.ConsoleTabContentView;if(representedObject instanceof WI.Frame||representedObject instanceof WI.FrameCollection||representedObject instanceof WI.Resource||representedObject instanceof WI.ResourceCollection||representedObject instanceof WI.Script||representedObject instanceof WI.ScriptCollection||representedObject instanceof WI.CSSStyleSheet||representedObject instanceof WI.CSSStyleSheetCollection)
return WI.SourcesTabContentView;if(representedObject instanceof WI.DOMStorageObject||representedObject instanceof WI.CookieStorageObject||representedObject instanceof WI.DatabaseTableObject||representedObject instanceof WI.DatabaseObject||representedObject instanceof WI.ApplicationCacheFrame||representedObject instanceof WI.IndexedDatabaseObjectStore||representedObject instanceof WI.IndexedDatabase||representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
return WI.StorageTabContentView;if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult)
return WI.AuditTabContentView;if(representedObject instanceof WI.CanvasCollection||representedObject instanceof WI.Canvas||representedObject instanceof WI.Recording||representedObject instanceof WI.ShaderProgram||representedObject instanceof WI.AnimationCollection||representedObject instanceof WI.Animation)
return WI.GraphicsTabContentView;return null;};WI.tabContentViewForRepresentedObject=function(representedObject,options={})
{let tabContentView=WI.tabBrowser.bestTabContentViewForRepresentedObject(representedObject,options);if(tabContentView)
return tabContentView;var tabContentViewClass=WI.tabContentViewClassForRepresentedObject(representedObject);if(!tabContentViewClass){console.error("Unknown representedObject, couldn't create TabContentView.",representedObject);return null;}
tabContentView=new tabContentViewClass;WI.tabBrowser.addTabForContentView(tabContentView);return tabContentView;};WI.showRepresentedObject=function(representedObject,cookie,options={})
{let tabContentView=WI.tabContentViewForRepresentedObject(representedObject,options);if(!tabContentView)
return;WI.tabBrowser.showTabForContentView(tabContentView,options);tabContentView.showRepresentedObject(representedObject,cookie);};WI.showLocalResourceOverride=function(localResourceOverride,options={})
{const cookie=null;WI.showRepresentedObject(localResourceOverride,cookie,{...options,ignoreNetworkTab:true,ignoreSearchTab:true});};WI.showMainFrameDOMTree=function(nodeToSelect,options={})
{if(!WI.networkManager.mainFrame)
return;WI.showRepresentedObject(WI.networkManager.mainFrame.domTree,{nodeToSelect},options);};WI.showSourceCodeForFrame=function(frameIdentifier,options={})
{var frame=WI.networkManager.frameForIdentifier(frameIdentifier);if(!frame){WI._frameIdentifierToShowSourceCodeWhenAvailable=frameIdentifier;return;}
WI._frameIdentifierToShowSourceCodeWhenAvailable=undefined;const cookie=null;WI.showRepresentedObject(frame,cookie,options);};WI.showSourceCode=function(sourceCode,options={})
{const positionToReveal=options.positionToReveal;var representedObject=sourceCode;if(representedObject instanceof WI.Script){representedObject=representedObject.resource||representedObject;}
var cookie=positionToReveal?{lineNumber:positionToReveal.lineNumber,columnNumber:positionToReveal.columnNumber}:{};WI.showRepresentedObject(representedObject,cookie,options);};WI.showSourceCodeLocation=function(sourceCodeLocation,options={})
{WI.showSourceCode(sourceCodeLocation.displaySourceCode,{...options,positionToReveal:sourceCodeLocation.displayPosition(),});};WI.showOriginalUnformattedSourceCodeLocation=function(sourceCodeLocation,options={})
{WI.showSourceCode(sourceCodeLocation.sourceCode,{...options,positionToReveal:sourceCodeLocation.position(),forceUnformatted:true,});};WI.showOriginalOrFormattedSourceCodeLocation=function(sourceCodeLocation,options={})
{WI.showSourceCode(sourceCodeLocation.sourceCode,{...options,positionToReveal:sourceCodeLocation.formattedPosition(),});};WI.showOriginalOrFormattedSourceCodeTextRange=function(sourceCodeTextRange,options={})
{var textRangeToSelect=sourceCodeTextRange.formattedTextRange;WI.showSourceCode(sourceCodeTextRange.sourceCode,{...options,positionToReveal:textRangeToSelect.startPosition(),textRangeToSelect,});};WI.showResourceRequest=function(resource,options={})
{WI.showRepresentedObject(resource,{[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]:WI.ResourceClusterContentView.Identifier.Request},options);};WI.debuggerToggleBreakpoints=function(event)
{WI.debuggerManager.breakpointsEnabled=!WI.debuggerManager.breakpointsEnabled;};WI.debuggerPauseResumeToggle=function(event)
{if(WI.debuggerManager.paused)
WI.debuggerManager.resume();else
WI.debuggerManager.pause();};WI.debuggerStepNext=function(event)
{WI.debuggerManager.stepNext();};WI.debuggerStepOver=function(event)
{WI.debuggerManager.stepOver();};WI.debuggerStepInto=function(event)
{WI.debuggerManager.stepInto();};WI.debuggerStepOut=function(event)
{WI.debuggerManager.stepOut();};WI._focusSearchField=function(event)
{let searchQuery="";if(WI.settings.searchFromSelection.value){let selection=window.getSelection();if(selection.type==="Range"||!selection.isCollapsed)
searchQuery=selection.toString().removeWordBreakCharacters();}
WI.tabBrowser.showTabForContentView(WI._searchTabContentView,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.KeyboardShortcut,});WI._searchTabContentView.focusSearchField();if(searchQuery)
WI._searchTabContentView.performSearch(searchQuery);};WI._focusChanged=function(event)
{WI._didAutofocusConsolePrompt=false;
if(WI.isEventTargetAnEditableField(event)){let newFocusElement=null;if(event.target instanceof HTMLInputElement||event.target instanceof HTMLTextAreaElement)
newFocusElement=event.target;else{let codeMirror=WI.enclosingCodeMirror(event.target);if(codeMirror){let codeMirrorElement=codeMirror.getWrapperElement();if(codeMirrorElement&&codeMirrorElement!==WI.currentFocusElement)
newFocusElement=codeMirrorElement;}}
if(newFocusElement){WI.previousFocusElement=WI.currentFocusElement;WI.currentFocusElement=newFocusElement;}



if(!WI.isBeingEdited(event.target))
return;}
var selection=window.getSelection();if(!selection.isCollapsed)
return;var element=event.target;if(element!==WI.currentFocusElement){WI.previousFocusElement=WI.currentFocusElement;WI.currentFocusElement=element;}
if(element.isInsertionCaretInside())
return;var selectionRange=element.ownerDocument.createRange();selectionRange.setStart(element,0);selectionRange.setEnd(element,0);selection.removeAllRanges();selection.addRange(selectionRange);};WI._mouseWasClicked=function(event)
{WI.handlePossibleLinkClick(event);};WI._handleDragOver=function(event)
{if(event.defaultPrevented)
return;if(WI.isEventTargetAnEditableField(event))
return;event.dataTransfer.dropEffect="none";event.preventDefault();};WI._debuggerDidPause=function(event)
{WI.showSourcesTab({showScopeChainSidebar:WI.settings.showScopeChainOnPause.value});InspectorFrontendHost.bringToFront();};WI._frameWasAdded=function(event)
{if(!WI._frameIdentifierToShowSourceCodeWhenAvailable)
return;var frame=event.data.frame;if(frame.id!==WI._frameIdentifierToShowSourceCodeWhenAvailable)
return;function delayedWork()
{const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.showSourceCodeForFrame(frame.id,options);}
setTimeout(delayedWork);};WI._mainFrameDidChange=function(event)
{WI._updateDownloadTabBarButton();WI.updateWindowTitle();};WI._mainResourceDidChange=function(event)
{if(!event.target.isMainFrame())
return;
setTimeout(()=>{WI._restoreCookieForOpenTabs(WI.StateRestorationType.Navigation);});WI._updateDownloadTabBarButton();WI.updateWindowTitle();};WI._provisionalLoadStarted=function(event)
{if(!event.target.isMainFrame())
return;WI._saveCookieForOpenTabs();};WI._restoreCookieForOpenTabs=function(restorationType)
{for(var tabBarItem of WI.tabBar.tabBarItems){var tabContentView=tabBarItem.representedObject;if(!(tabContentView instanceof WI.TabContentView))
continue;if(!tabContentView.constructor.shouldSaveTab())
continue;tabContentView.restoreStateFromCookie(restorationType);}
if(WI._didAutofocusConsolePrompt===undefined){window.requestAnimationFrame(()=>{if(WI.isContentAreaFocused()||WI.isShowingTimelineTab()||WI.isShowingAuditTab())
return;WI.quickConsole.prompt.focus();WI._didAutofocusConsolePrompt=true;});}};WI._saveCookieForOpenTabs=function()
{for(var tabBarItem of WI.tabBar.tabBarItems){var tabContentView=tabBarItem.representedObject;if(!(tabContentView instanceof WI.TabContentView))
continue;if(!tabContentView.constructor.shouldSaveTab())
continue;tabContentView.saveStateToCookie();}};WI._windowFocused=function(event)
{if(event.target.document.nodeType!==Node.DOCUMENT_NODE)
return;document.body.classList.remove(WI.dockConfiguration===WI.DockConfiguration.Undocked?"window-inactive":"window-docked-inactive");};WI._windowBlurred=function(event)
{if(event.target.document.nodeType!==Node.DOCUMENT_NODE)
return;document.body.classList.add(WI.dockConfiguration===WI.DockConfiguration.Undocked?"window-inactive":"window-docked-inactive");};WI._windowResized=function(event)
{WI.tabBar.updateLayout(WI.View.LayoutReason.Resize);WI._tabBrowserSizeDidChange();WI._updateSheetRect();};WI._updateSheetRect=function()
{let mainElementRect=document.getElementById("main").getBoundingClientRect();InspectorFrontendHost.setSheetRect(mainElementRect.x,mainElementRect.y,mainElementRect.width,mainElementRect.height);};WI._updateModifierKeys=function(event)
{let keys={altKey:event.altKey,metaKey:event.metaKey,ctrlKey:event.ctrlKey,shiftKey:event.shiftKey,};let changed=!Object.shallowEqual(WI.modifierKeys,keys);WI.modifierKeys=keys;document.body.classList.toggle("alt-key-pressed",WI.modifierKeys.altKey);document.body.classList.toggle("ctrl-key-pressed",WI.modifierKeys.ctrlKey);document.body.classList.toggle("meta-key-pressed",WI.modifierKeys.metaKey);document.body.classList.toggle("shift-key-pressed",WI.modifierKeys.shiftKey);if(changed)
WI.notifications.dispatchEventToListeners(WI.Notification.GlobalModifierKeysDidChange,event);};WI._windowKeyDown=function(event)
{WI._updateModifierKeys(event);};WI._windowKeyUp=function(event)
{WI._updateModifierKeys(event);};WI._mouseMoved=function(event)
{WI._updateModifierKeys(event);WI.mouseCoords={x:event.pageX,y:event.pageY};};WI._pageHidden=function(event)
{WI._saveCookieForOpenTabs();};WI._contextMenuRequested=function(event)
{let proposedContextMenu;if(WI.isDebugUIEnabled()){proposedContextMenu=WI.ContextMenu.createFromEvent(event);proposedContextMenu.appendSeparator();proposedContextMenu.appendItem(WI.unlocalizedString("Reload Web Inspector"),()=>{InspectorFrontendHost.reopen();});let protocolSubMenu=proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"),null,false);let isCapturingTraffic=InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"),()=>{if(isCapturingTraffic)
InspectorBackend.activeTracer=null;else
InspectorBackend.activeTracer=new WI.CapturingProtocolTracer;},isCapturingTraffic);protocolSubMenu.appendSeparator();protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"),()=>{const forceSaveAs=true;WI.FileUtilities.save(InspectorBackend.activeTracer.trace.saveData,forceSaveAs);},!isCapturingTraffic);}else{const onlyExisting=true;proposedContextMenu=WI.ContextMenu.createFromEvent(event,onlyExisting);}
if(proposedContextMenu)
proposedContextMenu.show();};WI.isDebugUIEnabled=function()
{return WI.showDebugUISetting&&WI.showDebugUISetting.value;};WI._undock=function(event)
{InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);};WI._dockBottom=function(event)
{InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);};WI._dockRight=function(event)
{InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);};WI._dockLeft=function(event)
{InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);};WI._togglePreviousDockConfiguration=function(event)
{InspectorFrontendHost.requestSetDockSide(WI._previousDockConfiguration);};WI._updateDockNavigationItems=function()
{let docked=WI.dockedConfigurationSupportsSplitContentBrowser&&WI.dockConfiguration!==WI.DockConfiguration.Undocked;if(WI._dockingAvailable||docked){if(WI._closeTabBarButton)
WI._closeTabBarButton.hidden=!docked;if(WI._dockToSideTabBarButton)
WI._dockToSideTabBarButton.hidden=WI.dockConfiguration===WI.DockConfiguration.Right||WI.dockConfiguration===WI.DockConfiguration.Left;if(WI._dockBottomTabBarButton)
WI._dockBottomTabBarButton.hidden=WI.dockConfiguration===WI.DockConfiguration.Bottom;if(WI._undockTabBarButton)
WI._undockTabBarButton.hidden=WI.dockConfiguration===WI.DockConfiguration.Undocked;}else{if(WI._closeTabBarButton)
WI._closeTabBarButton.hidden=true;if(WI._dockToSideTabBarButton)
WI._dockToSideTabBarButton.hidden=true;if(WI._dockBottomTabBarButton)
WI._dockBottomTabBarButton.hidden=true;if(WI._undockTabBarButton)
WI._undockTabBarButton.hidden=true;}
WI._updateTabBarDividers();WI.tabBar.resetCachedWidths();};WI._tabBrowserSizeDidChange=function()
{WI.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);WI.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);WI.quickConsole.updateLayout(WI.View.LayoutReason.Resize);};WI._consoleDrawerCollapsedStateDidChange=function(event)
{WI._showingSplitConsoleSetting.value=WI.isShowingSplitConsole();WI._consoleDrawerDidResize();};WI._consoleDrawerDidResize=function(event)
{WI.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);};WI._sidebarWidthDidChange=function(event)
{WI._tabBrowserSizeDidChange();};WI._setupViewHierarchy=function()
{let rootView=WI.View.rootView();rootView.addSubview(WI.tabBar);rootView.addSubview(WI.navigationSidebar);rootView.addSubview(WI.tabBrowser);rootView.addSubview(WI.consoleDrawer);rootView.addSubview(WI.quickConsole);rootView.addSubview(WI.detailsSidebar);};WI._tabBrowserSelectedTabContentViewDidChange=function(event)
{let selectedTabBarItem=WI.tabBar.selectedTabBarItem;if(selectedTabBarItem){WI._contentElement.ariaLabel=selectedTabBarItem.displayName||"";if(selectedTabBarItem.representedObject.constructor.shouldSaveTab())
WI._selectedTabIndexSetting.value=WI.tabBar.tabBarItems.indexOf(selectedTabBarItem);}
if(WI.doesCurrentTabSupportSplitContentBrowser()){if(WI._shouldRevealSpitConsoleIfSupported){WI._shouldRevealSpitConsoleIfSupported=false;WI.showSplitConsole();}
return;}
WI._shouldRevealSpitConsoleIfSupported=WI.isShowingSplitConsole();WI.hideSplitConsole();};WI._handleDockedResizerMouseDown=function(event)
{WI.resizeDockedFrameMouseDown(event);};WI._handleUndockedTitleAreaMouseDown=function(event)
{WI.moveUndockedWindowMouseDown(event);};WI._domStorageWasInspected=function(event)
{WI.showStorageTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.Inspect});WI.showRepresentedObject(event.data.domStorage,null,{ignoreSearchTab:true});};WI._databaseWasInspected=function(event)
{WI.showStorageTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.Inspect});WI.showRepresentedObject(event.data.database,null,{ignoreSearchTab:true});};WI._domNodeWasInspected=function(event)
{WI.domManager.highlightDOMNodeForTwoSeconds(event.data.node.id);InspectorFrontendHost.bringToFront();let options={initiatorHint:event.data.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Inspect,};WI.showElementsTab(options);WI.showMainFrameDOMTree(event.data.node,{...options,ignoreSearchTab:true});};WI._inspectModeStateChanged=function(event)
{WI._inspectModeTabBarButton.activated=WI.domManager.inspectModeEnabled;};WI._toggleInspectMode=function(event)
{WI.domManager.inspectModeEnabled=!WI.domManager.inspectModeEnabled;};WI._handleDeviceSettingsTabBarButtonClicked=function(event)
{if(WI._deviceSettingsPopover){WI._deviceSettingsPopover.dismiss();WI._deviceSettingsPopover=null;return;}
let target=WI.assumingMainTarget();function updateActivatedState(){WI._deviceSettingsTabBarButton.activated=WI._overridenDeviceUserAgent||WI._overridenDeviceSettings.size>0;}
function applyOverriddenUserAgent(value,force){if(value===WI._overridenDeviceUserAgent)
return;if(!force&&(!value||value==="default")){target.PageAgent.overrideUserAgent((error)=>{if(error){console.error(error);return;}
WI._overridenDeviceUserAgent=null;updateActivatedState();target.PageAgent.reload();});}else{target.PageAgent.overrideUserAgent(value,(error)=>{if(error){console.error(error);return;}
WI._overridenDeviceUserAgent=value;updateActivatedState();target.PageAgent.reload();});}}
function applyOverriddenSetting(setting,value,callback){if(WI._overridenDeviceSettings.has(setting)){target.PageAgent.overrideSetting(setting,(error)=>{if(error){console.error(error);return;}
WI._overridenDeviceSettings.delete(setting);callback(false);updateActivatedState();});}else{target.PageAgent.overrideSetting(setting,value,(error)=>{if(error){console.error(error);return;}
WI._overridenDeviceSettings.set(setting,value);callback(true);updateActivatedState();});}}
function createCheckbox(container,label,setting,value){if(!setting)
return;let labelElement=container.appendChild(document.createElement("label"));let checkboxElement=labelElement.appendChild(document.createElement("input"));checkboxElement.type="checkbox";checkboxElement.checked=WI._overridenDeviceSettings.has(setting);checkboxElement.addEventListener("change",(event)=>{applyOverriddenSetting(setting,value,(enabled)=>{checkboxElement.checked=enabled;});});labelElement.append(label);}
function calculateTargetFrame(){return WI.Rect.rectFromClientRect(WI._deviceSettingsTabBarButton.element.getBoundingClientRect()).pad(2);}
const preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];WI._deviceSettingsPopover=new WI.Popover(WI);WI._deviceSettingsPopover.windowResizeHandler=function(event){WI._deviceSettingsPopover.present(calculateTargetFrame(),preferredEdges);};let contentElement=document.createElement("div");contentElement.classList.add("device-settings-content");let table=contentElement.appendChild(document.createElement("table"));let userAgentRow=table.appendChild(document.createElement("tr"));let userAgentTitle=userAgentRow.appendChild(document.createElement("td"));userAgentTitle.textContent=WI.UIString("User Agent:");let userAgentValue=userAgentRow.appendChild(document.createElement("td"));userAgentValue.classList.add("user-agent");let userAgentValueSelect=userAgentValue.appendChild(document.createElement("select"));let userAgentValueInput=null;const userAgents=[[{name:WI.UIString("Default"),value:"default"},],[{name:"Safari 13.0",value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15"},],[{name:`Safari ${emDash} iOS 12.1.3 ${emDash} iPhone`,value:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"},{name:`Safari ${emDash} iOS 12.1.3 ${emDash} iPod touch`,value:"Mozilla/5.0 (iPod; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"},{name:`Safari ${emDash} iOS 12.1.3 ${emDash} iPad`,value:"Mozilla/5.0 (iPad; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"},],[{name:`Microsoft Edge`,value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"},],[{name:`Google Chrome ${emDash} macOS`,value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"},{name:`Google Chrome ${emDash} Windows`,value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"},],[{name:`Firefox ${emDash} macOS`,value:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:63.0) Gecko/20100101 Firefox/63.0"},{name:`Firefox ${emDash} Windows`,value:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0"},],[{name:WI.UIString("Other\u2026"),value:"other"},],];let selectedOptionElement=null;for(let group of userAgents){for(let{name,value}of group){let optionElement=userAgentValueSelect.appendChild(document.createElement("option"));optionElement.value=value;optionElement.textContent=name;if(value===WI._overridenDeviceUserAgent)
selectedOptionElement=optionElement;}
if(group!==userAgents.lastValue)
userAgentValueSelect.appendChild(document.createElement("hr"));}
function showUserAgentInput(){if(userAgentValueInput)
return;userAgentValueInput=userAgentValue.appendChild(document.createElement("input"));userAgentValueInput.spellcheck=false;userAgentValueInput.value=userAgentValueInput.placeholder=WI._overridenDeviceUserAgent||navigator.userAgent;userAgentValueInput.addEventListener("click",(clickEvent)=>{clickEvent.preventDefault();});userAgentValueInput.addEventListener("change",(inputEvent)=>{applyOverriddenUserAgent(userAgentValueInput.value,true);});WI._deviceSettingsPopover.update();}
if(selectedOptionElement)
userAgentValueSelect.value=selectedOptionElement.value;else if(WI._overridenDeviceUserAgent){userAgentValueSelect.value="other";showUserAgentInput();}
userAgentValueSelect.addEventListener("change",()=>{let value=userAgentValueSelect.value;if(value==="other"){showUserAgentInput();userAgentValueInput.select();}else{if(userAgentValueInput){userAgentValueInput.remove();userAgentValueInput=null;WI._deviceSettingsPopover.update();}
applyOverriddenUserAgent(value);}});if(InspectorBackend.hasCommand("Page.setScreenSizeOverride")){function applyOverriddenScreenSize(value,force){if(value===WI._overridenDeviceScreenSize)
return;if(!force&&(!value||value==="default")){target.PageAgent.setScreenSizeOverride((error)=>{if(error){WI.reportInternalError(error);return;}
WI._overridenDeviceScreenSize=null;updateActivatedState();target.PageAgent.reload();});}else{let tokens=value.split("x");let width=parseInt(tokens[0]);let height=parseInt(tokens[1]);target.PageAgent.setScreenSizeOverride(width,height,(error)=>{if(error){WI.reportInternalError(error);return;}
WI._overridenDeviceScreenSize=value;updateActivatedState();target.PageAgent.reload();});}}
let screenSizeRow=table.appendChild(document.createElement("tr"));let screenSizeTitle=screenSizeRow.appendChild(document.createElement("td"));screenSizeTitle.textContent=WI.UIString("Screen size:");let screenSizeValue=screenSizeRow.appendChild(document.createElement("td"));screenSizeValue.classList.add("screen-size");let screenSizeValueSelect=screenSizeValue.appendChild(document.createElement("select"));let screenSizeValueInput=null;const screenSizes=[[{name:WI.UIString("Default"),value:"default"},],[{name:WI.UIString("1080p"),value:"1920x1080"},{name:WI.UIString("720p"),value:"1280x720"},],[{name:WI.UIString("Other\u2026"),value:"other"},],];let selectedScreenSizeOptionElement=null;for(let group of screenSizes){for(let{name,value}of group){let optionElement=screenSizeValueSelect.appendChild(document.createElement("option"));optionElement.value=value;optionElement.textContent=name;if(value===WI._overridenDeviceScreenSize)
selectedScreenSizeOptionElement=optionElement;}
if(group!==screenSizes.lastValue)
screenSizeValueSelect.appendChild(document.createElement("hr"));}
function showScreenSizeInput(){if(screenSizeValueInput)
return;screenSizeValueInput=screenSizeValue.appendChild(document.createElement("input"));screenSizeValueInput.spellcheck=false;screenSizeValueInput.value=screenSizeValueInput.placeholder=WI._overridenDeviceScreenSize||(window.screen.width+"x"+window.screen.height);screenSizeValueInput.addEventListener("click",(clickEvent)=>{clickEvent.preventDefault();});screenSizeValueInput.addEventListener("change",(inputEvent)=>{applyOverriddenScreenSize(screenSizeValueInput.value,true);});WI._deviceSettingsPopover.update();}
if(selectedScreenSizeOptionElement)
screenSizeValueSelect.value=selectedScreenSizeOptionElement.value;else if(WI._overridenDeviceScreenSize){screenSizeValueSelect.value="other";showScreenSizeInput();}
screenSizeValueSelect.addEventListener("change",()=>{let value=screenSizeValueSelect.value;if(value==="other"){showScreenSizeInput();screenSizeValueInput.select();}else{if(screenSizeValueInput){screenSizeValueInput.remove();screenSizeValueInput=null;WI._deviceSettingsPopover.update();}
applyOverriddenScreenSize(value);}});}
const settings=[{name:WI.UIString("Disable:"),columns:[[{name:WI.UIString("Images"),setting:InspectorBackend.Enum.Page.Setting.ImagesEnabled,value:false},{name:WI.UIString("Styles"),setting:InspectorBackend.Enum.Page.Setting.AuthorAndUserStylesEnabled,value:false},{name:WI.UIString("JavaScript"),setting:InspectorBackend.Enum.Page.Setting.ScriptEnabled,value:false},],[{name:WI.UIString("Site-specific Hacks"),setting:InspectorBackend.Enum.Page.Setting.NeedsSiteSpecificQuirks,value:false},{name:WI.UIString("Cross-Origin Restrictions"),setting:InspectorBackend.Enum.Page.Setting.WebSecurityEnabled,value:false},]],},{name:WI.UIString("Enable:"),columns:[[{name:WI.UIString("ITP Debug Mode"),setting:InspectorBackend.Enum.Page.Setting.ITPDebugModeEnabled,value:true},{name:WI.UIString("Private Click Measurement Debug Mode"),setting:InspectorBackend.Enum.Page.Setting.PrivateClickMeasurementDebugModeEnabled,value:true},{name:WI.UIString("Ad Click Attribution Debug Mode"),setting:InspectorBackend.Enum.Page.Setting.AdClickAttributionDebugModeEnabled,value:true},],],},{name:WI.UIString("%s:").format(WI.unlocalizedString("WebRTC")),columns:[[{name:WI.UIString("Allow Media Capture on Insecure Sites"),setting:InspectorBackend.Enum.Page.Setting.MediaCaptureRequiresSecureConnection,value:false},{name:WI.UIString("Disable ICE Candidate Restrictions"),setting:InspectorBackend.Enum.Page.Setting.ICECandidateFilteringEnabled,value:false},{name:WI.UIString("Use Mock Capture Devices"),setting:InspectorBackend.Enum.Page.Setting.MockCaptureDevicesEnabled,value:true},{name:WI.UIString("Disable Encryption"),setting:InspectorBackend.Enum.Page.Setting.WebRTCEncryptionEnabled,value:false},],],},];for(let group of settings){if(!group.columns.some((column)=>column.some((item)=>item.setting)))
continue;let settingsGroupRow=table.appendChild(document.createElement("tr"));let settingsGroupTitle=settingsGroupRow.appendChild(document.createElement("td"));settingsGroupTitle.textContent=group.name;let settingsGroupValue=settingsGroupRow.appendChild(document.createElement("td"));let settingsGroupItemContainer=settingsGroupValue.appendChild(document.createElement("div"));settingsGroupItemContainer.classList.add("container");for(let column of group.columns){let columnElement=settingsGroupItemContainer.appendChild(document.createElement("div"));columnElement.classList.add("column");for(let item of column)
createCheckbox(columnElement,item.name,item.setting,item.value);}}
contentElement.appendChild(WI.createReferencePageLink("device-settings"));WI._deviceSettingsPopover.presentNewContentWithFrame(contentElement,calculateTargetFrame(),preferredEdges);};WI._downloadWebArchive=function(event)
{WI.archiveMainFrame();};WI._reloadInspectedInspector=function()
{const options={};WI.runtimeManager.evaluateInInspectedWindow(`InspectorFrontendHost.reopen()`,options,function(){});};WI._reloadPage=function(event)
{let target=WI.assumingMainTarget();if(!target.hasDomain("Page"))
return;event.preventDefault();if(InspectorFrontendHost.inspectionLevel>1){WI._reloadInspectedInspector();return;}
target.PageAgent.reload();};WI._reloadPageFromOrigin=function(event)
{let target=WI.assumingMainTarget();if(!target.hasDomain("Page"))
return;event.preventDefault();if(InspectorFrontendHost.inspectionLevel>1){WI._reloadInspectedInspector();return;}
target.PageAgent.reload.invoke({ignoreCache:true});};WI._reloadTabBarButtonClicked=function(event)
{if(InspectorFrontendHost.inspectionLevel>1){WI._reloadInspectedInspector();return;}
let target=WI.assumingMainTarget();target.PageAgent.reload.invoke({ignoreCache:WI.modifierKeys.shiftKey});};WI._updateReloadTabBarButton=function()
{if(!WI._reloadTabBarButton)
return;WI._reloadTabBarButton.hidden=!InspectorBackend.hasDomain("Page");WI._updateTabBarDividers();};WI._updateDownloadTabBarButton=function()
{if(!WI._reloadTabBarButton)
return;if(!InspectorBackend.hasCommand("Page.archive")){WI._downloadTabBarButton.hidden=true;WI._updateTabBarDividers();return;}
if(WI._downloadingPage){WI._downloadTabBarButton.enabled=false;return;}
WI._downloadTabBarButton.enabled=WI.canArchiveMainFrame();};WI._updateInspectModeTabBarButton=function()
{WI._inspectModeTabBarButton.hidden=!InspectorBackend.hasDomain("DOM");WI._updateTabBarDividers();};WI._updateTabBarDividers=function()
{function isHidden(navigationItem){return!navigationItem||navigationItem.hidden;}
let closeHidden=isHidden(WI._closeTabBarButton);let dockToSideHidden=isHidden(WI._dockToSideTabBarButton);let dockBottomHidden=isHidden(WI._dockBottomTabBarButton);let undockHidden=isHidden(WI._undockTabBarButton);let inspectModeHidden=isHidden(WI._inspectModeTabBarButton);let deviceSettingsHidden=isHidden(WI._deviceSettingsTabBarButton);let reloadHidden=isHidden(WI._reloadTabBarButton);let downloadHidden=isHidden(WI._downloadTabBarButton);let warningsHidden=WI._consoleWarningsTabBarButton.hidden;let errorsHidden=WI._consoleErrorsTabBarButton.hidden;WI._consoleDividerNavigationItem.hidden=(closeHidden&&dockToSideHidden&&dockBottomHidden&&undockHidden&&inspectModeHidden&&deviceSettingsHidden&&reloadHidden&&downloadHidden)||(warningsHidden&&errorsHidden);WI.tabBar.needsLayout();};WI._updateConsoleTabBarButtons=function()
{function pulse(element){
if(element.classList.contains("pulsing")){element.classList.remove("pulsing");element.recalculateStyles();}else{element.addEventListener("animationend",()=>{element.classList.remove("pulsing");},{once:true});}
element.classList.add("pulsing");}
let warningCount=WI.consoleManager.warningCount;if(warningCount){let warningFormat=(warningCount===1)?WI.UIString("Click to show %d warning in the Console"):WI.UIString("Click to show %d warnings in the Console");WI._consoleWarningsTabBarButton.tooltip=warningFormat.format(warningCount);WI._consoleWarningsTabBarButton.hidden=false;if(warningCount!==WI._consoleWarningsTabBarButton.__lastWarningCount)
pulse(WI._consoleWarningsTabBarButton.element);}else
WI._consoleWarningsTabBarButton.hidden=true;let errorCount=WI.consoleManager.errorCount;if(errorCount){let errorFormat=(errorCount===1)?WI.UIString("Click to show %d error in the Console"):WI.UIString("Click to show %d errors in the Console");WI._consoleErrorsTabBarButton.tooltip=errorFormat.format(errorCount);WI._consoleErrorsTabBarButton.hidden=false;if(errorCount!==WI._consoleErrorsTabBarButton.__lastErrorCount)
pulse(WI._consoleErrorsTabBarButton.element);}else
WI._consoleErrorsTabBarButton.hidden=true;WI._updateTabBarDividers();WI._consoleWarningsTabBarButton.__lastWarningCount=warningCount;WI._consoleErrorsTabBarButton.__lastErrorCount=errorCount;};WI._showConsoleTab=function(event)
{WI.showConsoleTab();};WI._focusConsolePrompt=function(event)
{WI.quickConsole.prompt.focus();};WI._focusedContentBrowser=function()
{if(WI.currentFocusElement){let contentBrowserElement=WI.currentFocusElement.closest(".content-browser");if(contentBrowserElement&&contentBrowserElement.__view&&contentBrowserElement.__view instanceof WI.ContentBrowser)
return contentBrowserElement.__view;}
if(WI.tabBrowser.element.contains(WI.currentFocusElement)||document.activeElement===document.body){let tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView.contentBrowser)
return tabContentView.contentBrowser;return null;}
if(WI.consoleDrawer.element.contains(WI.currentFocusElement)||(WI.isShowingSplitConsole()&&WI.quickConsole.element.contains(WI.currentFocusElement)))
return WI.consoleDrawer;return null;};WI._focusedContentView=function()
{if(WI.tabBrowser.element.contains(WI.currentFocusElement)||document.activeElement===document.body){var tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView.contentBrowser)
return tabContentView.contentBrowser.currentContentView;return tabContentView;}
if(WI.consoleDrawer.element.contains(WI.currentFocusElement)||(WI.isShowingSplitConsole()&&WI.quickConsole.element.contains(WI.currentFocusElement)))
return WI.consoleDrawer.currentContentView;return null;};WI._focusedOrVisibleContentBrowser=function()
{let focusedContentBrowser=WI._focusedContentBrowser();if(focusedContentBrowser)
return focusedContentBrowser;var tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView.contentBrowser)
return tabContentView.contentBrowser;return null;};WI.focusedOrVisibleContentView=function()
{let focusedContentView=WI._focusedContentView();if(focusedContentView)
return focusedContentView;var tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView.contentBrowser)
return tabContentView.contentBrowser.currentContentView;return tabContentView;};WI._beforecopy=function(event)
{var selection=window.getSelection();if(selection.isCollapsed&&!WI.isEventTargetAnEditableField(event)){var focusedCopyHandler=WI.currentFocusElement&&WI.currentFocusElement.copyHandler;if(focusedCopyHandler&&typeof focusedCopyHandler.handleBeforeCopyEvent==="function"){focusedCopyHandler.handleBeforeCopyEvent(event);if(event.defaultPrevented)
return;}
var focusedContentView=WI._focusedContentView();if(focusedContentView&&typeof focusedContentView.handleCopyEvent==="function"){event.preventDefault();return;}
return;}
if(selection.isCollapsed)
return;event.preventDefault();};WI._find=function(event)
{let tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView&&tabContentView.canHandleFindEvent){tabContentView.handleFindEvent(event);return;}
let contentBrowser=WI._focusedOrVisibleContentBrowser();if(!contentBrowser)
return;contentBrowser.showFindBanner();};WI._save=function(event)
{var contentView=WI.focusedOrVisibleContentView();if(!contentView||!contentView.supportsSave)
return;WI.FileUtilities.save(contentView.saveData);};WI._saveAs=function(event)
{var contentView=WI.focusedOrVisibleContentView();if(!contentView||!contentView.supportsSave)
return;WI.FileUtilities.save(contentView.saveData,true);};WI._clear=function(event)
{let contentView=WI.focusedOrVisibleContentView();if(!contentView||typeof contentView.handleClearShortcut!=="function"){
WI.consoleManager.requestClearMessages();return;}
contentView.handleClearShortcut(event);};WI._populateFind=function(event)
{let focusedContentView=WI._focusedContentView();if(focusedContentView&&focusedContentView.supportsCustomFindBanner){focusedContentView.handlePopulateFindShortcut();return;}
let contentBrowser=WI._focusedOrVisibleContentBrowser();if(contentBrowser){contentBrowser.handlePopulateFindShortcut();return;}};WI._findNext=function(event)
{let focusedContentView=WI._focusedContentView();if(focusedContentView?.supportsCustomFindBanner){focusedContentView.handleFindNextShortcut();return;}
let contentBrowser=WI._focusedOrVisibleContentBrowser();if(contentBrowser){contentBrowser.handleFindNextShortcut();return;}};WI._findPrevious=function(event)
{let focusedContentView=WI._focusedContentView();if(focusedContentView?.supportsCustomFindBanner){focusedContentView.handleFindPreviousShortcut();return;}
let contentBrowser=WI._focusedOrVisibleContentBrowser();if(contentBrowser){contentBrowser.handleFindPreviousShortcut();return;}};WI._copy=function(event)
{var selection=window.getSelection();if(selection.isCollapsed&&!WI.isEventTargetAnEditableField(event)){var focusedCopyHandler=WI.currentFocusElement&&WI.currentFocusElement.copyHandler;if(focusedCopyHandler&&typeof focusedCopyHandler.handleCopyEvent==="function"){focusedCopyHandler.handleCopyEvent(event);if(event.defaultPrevented)
return;}
var focusedContentView=WI._focusedContentView();if(focusedContentView&&typeof focusedContentView.handleCopyEvent==="function"){focusedContentView.handleCopyEvent(event);return;}
let tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView&&typeof tabContentView.handleCopyEvent==="function"){tabContentView.handleCopyEvent(event);return;}
return;}
if(selection.isCollapsed)
return;var selectionString=selection.toString().removeWordBreakCharacters();event.clipboardData.setData("text/plain",selectionString);event.preventDefault();};WI._paste=function(event)
{if(event.defaultPrevented)
return;let selection=window.getSelection();if(!selection.isCollapsed||WI.isEventTargetAnEditableField(event))
return;let focusedPasteHandler=WI.currentFocusElement&&WI.currentFocusElement.pasteHandler;if(focusedPasteHandler&&focusedPasteHandler.handlePasteEvent){focusedPasteHandler.handlePasteEvent(event);if(event.defaultPrevented)
return;}
let focusedContentView=WI._focusedContentView();if(focusedContentView&&focusedContentView.handlePasteEvent){focusedContentView.handlePasteEvent(event);return;}
let tabContentView=WI.tabBrowser.selectedTabContentView;if(tabContentView&&tabContentView.handlePasteEvent){tabContentView.handlePasteEvent(event);return;}};WI._increaseZoom=function(event)
{const epsilon=0.0001;const maximumZoom=2.4;let currentZoom=WI.getZoomFactor();if(currentZoom+epsilon>=maximumZoom){InspectorFrontendHost.beep();return;}
WI.setZoomFactor(Math.min(maximumZoom,currentZoom+0.2));};WI._decreaseZoom=function(event)
{const epsilon=0.0001;const minimumZoom=0.6;let currentZoom=WI.getZoomFactor();if(currentZoom-epsilon<=minimumZoom){InspectorFrontendHost.beep();return;}
WI.setZoomFactor(Math.max(minimumZoom,currentZoom-0.2));};WI._resetZoom=function(event)
{WI.setZoomFactor(1);};WI.getZoomFactor=function()
{return WI.settings.zoomFactor.value;};WI.setZoomFactor=function(factor)
{InspectorFrontendHost.setZoomFactor(factor);WI.settings.zoomFactor.value=InspectorFrontendHost.zoomFactor();};WI.resolvedLayoutDirection=function()
{let layoutDirection=WI.settings.debugLayoutDirection.value;if(layoutDirection===WI.LayoutDirection.System)
layoutDirection=InspectorFrontendHost.userInterfaceLayoutDirection();return layoutDirection;};WI.resolveLayoutDirectionForElement=function(element)
{let layoutDirection=WI.resolvedLayoutDirection();if(layoutDirection===WI.LayoutDirection.LTR)
return layoutDirection;let style=getComputedStyle(element);return style.direction;};WI.setLayoutDirection=function(value)
{if(!Object.values(WI.LayoutDirection).includes(value))
WI.reportInternalError("Unknown layout direction requested: "+value);if(value===WI.settings.debugLayoutDirection.value)
return;WI.settings.debugLayoutDirection.value=value;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL&&WI.dockConfiguration===WI.DockConfiguration.Right)
WI._dockLeft();if(WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR&&WI.dockConfiguration===WI.DockConfiguration.Left)
WI._dockRight();InspectorFrontendHost.reopen();};WI.undockedTitleAreaHeight=function()
{if(WI.dockConfiguration!==WI.DockConfiguration.Undocked)
return 0;if(WI.Platform.name==="mac"){switch(WI.Platform.version.name){case"monterey":case"big-sur":return 27/WI.getZoomFactor();case"catalina":case"mojave":return 22/WI.getZoomFactor();}}
return 0;};WI._showTabAtIndexFromShortcut=function(i)
{if(i<=WI.tabBar.tabCount){WI.tabBar.selectTabBarItem(i-1,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.KeyboardShortcut,});}};WI._showJavaScriptTypeInformationSettingChanged=function(event)
{if(WI.settings.showJavaScriptTypeInformation.value){for(let target of WI.targets)
target.RuntimeAgent.enableTypeProfiler();}else{for(let target of WI.targets)
target.RuntimeAgent.disableTypeProfiler();}};WI._enableControlFlowProfilerSettingChanged=function(event)
{if(WI.settings.enableControlFlowProfiler.value){for(let target of WI.targets)
target.RuntimeAgent.enableControlFlowProfiler();}else{for(let target of WI.targets)
target.RuntimeAgent.disableControlFlowProfiler();}};WI._resourceCachingDisabledSettingChanged=function(event)
{for(let target of WI.targets)
target.NetworkAgent.setResourceCachingDisabled(WI.settings.resourceCachingDisabled.value);};WI._allowInspectingInspectorSettingChanged=function(event)
{InspectorFrontendHost.setAllowsInspectingInspector(WI.settings.experimentalAllowInspectingInspector.value);}
WI.measureElement=function(element)
{WI.layoutMeasurementContainer.appendChild(element.cloneNode(true));let rect=WI.layoutMeasurementContainer.getBoundingClientRect();WI.layoutMeasurementContainer.removeChildren();return rect;};WI.elementDragStart=function(element,dividerDrag,elementDragEnd,event,cursor,eventTarget)
{if(WI._elementDraggingEventListener||WI._elementEndDraggingEventListener)
WI.elementDragEnd(event);if(element){ if(WI._elementDraggingGlassPane)
WI._elementDraggingGlassPane.remove();var glassPane=document.createElement("div");glassPane.style.cssText="position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";glassPane.id="glass-pane-for-drag";element.ownerDocument.body.appendChild(glassPane);WI._elementDraggingGlassPane=glassPane;}
WI._elementDraggingEventListener=dividerDrag;WI._elementEndDraggingEventListener=elementDragEnd;var targetDocument=event.target.ownerDocument;WI._elementDraggingEventTarget=eventTarget||targetDocument;WI._elementDraggingEventTarget.addEventListener("mousemove",dividerDrag,true);WI._elementDraggingEventTarget.addEventListener("mouseup",elementDragEnd,true);targetDocument.body.style.cursor=cursor;event.preventDefault();};WI.elementDragEnd=function(event)
{WI._elementDraggingEventTarget.removeEventListener("mousemove",WI._elementDraggingEventListener,true);WI._elementDraggingEventTarget.removeEventListener("mouseup",WI._elementEndDraggingEventListener,true);event.target.ownerDocument.body.style.removeProperty("cursor");if(WI._elementDraggingGlassPane)
WI._elementDraggingGlassPane.remove();delete WI._elementDraggingGlassPane;delete WI._elementDraggingEventTarget;delete WI._elementDraggingEventListener;delete WI._elementEndDraggingEventListener;event.preventDefault();};WI.createMessageTextView=function(message,isError)
{let messageElement=document.createElement("div");messageElement.className="message-text-view";if(isError)
messageElement.classList.add("error");let textElement=messageElement.appendChild(document.createElement("div"));textElement.className="message";textElement.textContent=message;return messageElement;};WI.createNavigationItemHelp=function(formatString,navigationItem)
{function append(a,b){a.append(b);return a;}
let containerElement=document.createElement("div");containerElement.className="navigation-item-help";containerElement.__navigationItem=navigationItem;let wrapperElement=document.createElement("div");wrapperElement.className="navigation-bar";wrapperElement.appendChild(navigationItem.element);String.format(formatString,[wrapperElement],String.standardFormatters,containerElement,append);return containerElement;};WI.createReferencePageLink=function(page,fragment)
{let url="https://webkit.org/web-inspector/"+page+"/";if(fragment)
url+="#"+fragment;let wrapper=document.createElement("span");wrapper.className="reference-page-link-container";let link=wrapper.appendChild(document.createElement("a"));link.className="reference-page-link";link.href=link.title=url;link.textContent="?";return wrapper;};WI.createGoToArrowButton=function()
{var button=document.createElement("button");button.addEventListener("mousedown",(event)=>{event.stopPropagation();},true);button.className="go-to-arrow";button.tabIndex=-1;return button;};WI.createSourceCodeLocationLink=function(sourceCodeLocation,options={})
{if(!sourceCodeLocation)
return null;var linkElement=document.createElement("a");linkElement.className="go-to-link";WI.linkifyElement(linkElement,sourceCodeLocation,options);sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);if(options.useGoToArrowButton)
linkElement.appendChild(WI.createGoToArrowButton());else
sourceCodeLocation.populateLiveDisplayLocationString(linkElement,"textContent",options.columnStyle,options.nameStyle,options.prefix);if(options.dontFloat)
linkElement.classList.add("dont-float");return linkElement;};WI.linkifyLocation=function(url,sourceCodePosition,options={})
{var sourceCode=WI.sourceCodeForURL(url);if(sourceCode)
return WI.linkifySourceCode(sourceCode,sourceCodePosition,options);var anchor=document.createElement("a");anchor.href=url;anchor.lineNumber=sourceCodePosition.lineNumber;if(options.className)
anchor.className=options.className;anchor.append(WI.displayNameForURL(url)+":"+sourceCodePosition.lineNumber);return anchor;};WI.linkifySourceCode=function(sourceCode,sourceCodePosition,options={})
{let sourceCodeLocation=sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber,sourceCodePosition.columnNumber);let linkElement=WI.createSourceCodeLocationLink(sourceCodeLocation,{...options,dontFloat:true,});if(options.className)
linkElement.classList.add(options.className);return linkElement;};WI.linkifyElement=function(linkElement,sourceCodeLocation,options={}){if(!options.initiatorHint)
options.initiatorHint=WI.TabBrowser.TabNavigationInitiator.LinkClick;function showSourceCodeLocation(event)
{event.stopPropagation();event.preventDefault();if(event.metaKey)
WI.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation,options);else
WI.showSourceCodeLocation(sourceCodeLocation,options);}
linkElement.addEventListener("click",showSourceCodeLocation);linkElement.addEventListener("contextmenu",(event)=>{let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForSourceCode(contextMenu,sourceCodeLocation);});};WI.sourceCodeForURL=function(url)
{let sourceCode=WI.networkManager.resourcesForURL(url).firstValue;if(!sourceCode){sourceCode=WI.debuggerManager.scriptsForURL(url,WI.assumingMainTarget())[0];if(sourceCode)
sourceCode=sourceCode.resource||sourceCode;}
return sourceCode||null;};WI.linkifyURLAsNode=function(url,linkText,className)
{let a=document.createElement("a");a.href=url;a.className=className||"";a.textContent=linkText||url;a.style.maxWidth="100%";return a;};WI.linkifyStringAsFragmentWithCustomLinkifier=function(string,linkifier)
{var container=document.createDocumentFragment();var linkStringRegEx=/(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;var lineColumnRegEx=/:(\d+)(:(\d+))?$/;while(string){var linkString=linkStringRegEx.exec(string);if(!linkString)
break;linkString=linkString[0];var linkIndex=string.indexOf(linkString);var nonLink=string.substring(0,linkIndex);container.append(nonLink);if(linkString.startsWith("data:")||linkString.startsWith("javascript:")||linkString.startsWith("mailto:")){container.append(linkString);string=string.substring(linkIndex+linkString.length,string.length);continue;}
var title=linkString;var realURL=linkString.startsWith("www.")?"http://"+linkString:linkString;var lineColumnMatch=lineColumnRegEx.exec(realURL);if(lineColumnMatch)
realURL=realURL.substring(0,realURL.length-lineColumnMatch[0].length);var lineNumber;if(lineColumnMatch)
lineNumber=parseInt(lineColumnMatch[1])-1;var linkNode=linkifier(title,realURL,lineNumber);container.appendChild(linkNode);string=string.substring(linkIndex+linkString.length,string.length);}
if(string)
container.append(string);return container;};WI.linkifyStringAsFragment=function(string)
{function linkifier(title,url,lineNumber)
{var urlNode=WI.linkifyURLAsNode(url,title,undefined);if(lineNumber!==undefined)
urlNode.lineNumber=lineNumber;return urlNode;}
return WI.linkifyStringAsFragmentWithCustomLinkifier(string,linkifier);};WI.createResourceLink=function(resource,className)
{function handleClick(event)
{event.stopPropagation();event.preventDefault();WI.showRepresentedObject(resource);}
let linkNode=document.createElement("a");linkNode.classList.add("resource-link",className);linkNode.title=resource.url;linkNode.textContent=(resource.urlComponents.lastPathComponent||resource.displayURL).insertWordBreakCharacters();linkNode.addEventListener("click",handleClick);return linkNode;};WI._undoKeyboardShortcut=function(event)
{if(!WI.isEditingAnyField()&&!WI.isEventTargetAnEditableField(event)){WI.undo();event.preventDefault();}};WI._redoKeyboardShortcut=function(event)
{if(!WI.isEditingAnyField()&&!WI.isEventTargetAnEditableField(event)){WI.redo();event.preventDefault();}};WI.undo=function()
{let target=WI.assumingMainTarget();if(target.hasCommand("DOM.undo"))
target.DOMAgent.undo();};WI.redo=function()
{let target=WI.assumingMainTarget();if(target.hasCommand("DOM.redo"))
target.DOMAgent.redo();};WI.highlightRangesWithStyleClass=function(element,resultRanges,styleClass,changes)
{changes=changes||[];var highlightNodes=[];var lineText=element.textContent;var ownerDocument=element.ownerDocument;var textNodeSnapshot=ownerDocument.evaluate(".//text()",element,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);var snapshotLength=textNodeSnapshot.snapshotLength;if(snapshotLength===0)
return highlightNodes;var nodeRanges=[];var rangeEndOffset=0;for(var i=0;i<snapshotLength;++i){var range={};range.offset=rangeEndOffset;range.length=textNodeSnapshot.snapshotItem(i).textContent.length;rangeEndOffset=range.offset+range.length;nodeRanges.push(range);}
var startIndex=0;for(var i=0;i<resultRanges.length;++i){var startOffset=resultRanges[i].offset;var endOffset=startOffset+resultRanges[i].length;while(startIndex<snapshotLength&&nodeRanges[startIndex].offset+nodeRanges[startIndex].length<=startOffset)
startIndex++;var endIndex=startIndex;while(endIndex<snapshotLength&&nodeRanges[endIndex].offset+nodeRanges[endIndex].length<endOffset)
endIndex++;if(endIndex===snapshotLength)
break;var highlightNode=ownerDocument.createElement("span");highlightNode.className=styleClass;highlightNode.textContent=lineText.substring(startOffset,endOffset);var lastTextNode=textNodeSnapshot.snapshotItem(endIndex);var 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);var 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{var firstTextNode=textNodeSnapshot.snapshotItem(startIndex);var firstText=firstTextNode.textContent;var 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(var j=startIndex+1;j<endIndex;j++){var textNode=textNodeSnapshot.snapshotItem(j);var 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;};WI.revertDOMChanges=function(domChanges)
{for(var i=domChanges.length-1;i>=0;--i){var entry=domChanges[i];switch(entry.type){case"added":entry.node.remove();break;case"changed":entry.node.textContent=entry.oldText;break;}}};WI.archiveMainFrame=function()
{WI._downloadingPage=true;WI._updateDownloadTabBarButton();let target=WI.assumingMainTarget();target.PageAgent.archive((error,data)=>{WI._downloadingPage=false;WI._updateDownloadTabBarButton();if(error)
return;let mainFrame=WI.networkManager.mainFrame;let archiveName=mainFrame.mainResource.urlComponents.host||mainFrame.mainResource.displayName||"Archive";let url=WI.FileUtilities.inspectorURLForFilename(archiveName+".webarchive");InspectorFrontendHost.save(url,data,true,true);});};WI.canArchiveMainFrame=function()
{if(!InspectorBackend.hasCommand("Page.archive"))
return false;if(!WI.networkManager.mainFrame||!WI.networkManager.mainFrame.mainResource)
return false;return WI.Resource.typeFromMIMEType(WI.networkManager.mainFrame.mainResource.mimeType)===WI.Resource.Type.Document;};WI.addWindowKeydownListener=function(listener)
{if(typeof listener.handleKeydownEvent!=="function")
return;WI._windowKeydownListeners.push(listener);WI._updateWindowKeydownListener();};WI.removeWindowKeydownListener=function(listener)
{WI._windowKeydownListeners.remove(listener);WI._updateWindowKeydownListener();};WI._updateWindowKeydownListener=function()
{if(WI._windowKeydownListeners.length===1)
window.addEventListener("keydown",WI._sharedWindowKeydownListener,true);else if(!WI._windowKeydownListeners.length)
window.removeEventListener("keydown",WI._sharedWindowKeydownListener,true);};WI._sharedWindowKeydownListener=function(event)
{for(var i=WI._windowKeydownListeners.length-1;i>=0;--i){if(WI._windowKeydownListeners[i].handleKeydownEvent(event)){event.stopImmediatePropagation();event.preventDefault();break;}}};WI.reportInternalError=function(errorOrString,details={})
{
let error=errorOrString instanceof Error?errorOrString:new Error(errorOrString);error.details=details;if(WI.isDebugUIEnabled()){
handleInternalException(error);}else
console.error(error);};

Object.defineProperty(WI,"mainTarget",{get(){return WI.pageTarget||WI.backendTarget;}});

Object.defineProperty(WI,"targets",{get(){return WI.targetManager.targets;}});


WI.assumingMainTarget=function()
{return WI.mainTarget;};WI.reset=async function()
{await WI.ObjectStore.reset();WI.Setting.reset();InspectorFrontendHost.reset();};WI.isEngineeringBuild=false;WI.isExperimentalBuild=InspectorFrontendHost.isExperimentalBuild();WI.dialogWasDismissedWithRepresentedObject=function(dialog,representedObject)
{if(!representedObject)
return;WI.showRepresentedObject(representedObject,dialog.cookie,{ignoreSearchTab:true,ignoreNetworkTab:true,});};WI.didDismissPopover=function(popover)
{if(popover===WI._deviceSettingsPopover)
WI._deviceSettingsPopover=null;};WI.DockConfiguration={Right:"right",Left:"left",Bottom:"bottom",Undocked:"undocked",};WI.DockConfigurationChangedLayoutReason=Symbol("dock-configuration-changed");WI.NotImplementedError=class NotImplementedError extends Error
{constructor(message="This method is not implemented.")
{super(message);}
static subclassMustOverride()
{return new WI.NotImplementedError("This method must be overridden by a subclass.");}};WI.AppControllerBase=class AppControllerBase
{constructor()
{this._initialized=false;this._extensionController=new WI.WebInspectorExtensionController;} 
get debuggableType(){throw WI.NotImplementedError.subclassMustOverride();}
get extensionController(){return this._extensionController;}
initialize()
{if(this._initialized)
throw new Error("App controller is already initialized.");this._initialized=true;WI.loaded();}
isWebDebuggable()
{return this.debuggableType===WI.DebuggableType.Page||this.debuggableType===WI.DebuggableType.WebPage;}};WI.AppController=class AppController extends WI.AppControllerBase
{constructor()
{super();this._debuggableType=WI.DebuggableType.fromString(InspectorFrontendHost.debuggableInfo.debuggableType);if(!this._debuggableType)
this._debuggableType=WI.DebuggableType.JavaScript;}
get debuggableType(){return this._debuggableType;}
activateExtraDomains(domains)
{ let target=WI.mainTarget;if(this._debuggableType===WI.DebuggableType.ITML||target.type===WI.TargetType.ITML)
throw new Error("Extra domains have already been activated, cannot activate again.");this._debuggableType=WI.DebuggableType.ITML;target._type=WI.TargetType.ITML;for(let domain of domains){InspectorBackend.activateDomain(domain);target.activateExtraDomain(domain);let manager=WI.managers.find((manager)=>manager.domains&&manager.domains.includes(domain));if(manager)
manager.activateExtraDomain(domain);else if(target.hasCommand(domain+".enable"))
target._agents[domain].enable();}
WI.activateExtraDomains(domains);}};
/* NonMinified/DefaultAudits.js */

/*
 * Copyright (C) 2021 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

WI.DefaultAudits = {};

WI.DefaultAudits.levelPass = function() {
    return {level: "pass"};
};

WI.DefaultAudits.levelWarn = function() {
    return {level: "warn"};
};

WI.DefaultAudits.levelFail = function() {
    return {level: "fail"};
};

WI.DefaultAudits.levelError = function() {
    return {level: "error"};
};

WI.DefaultAudits.levelUnsupported = function() {
    return {level: "unsupported"};
};

WI.DefaultAudits.dataDOMNodes = function() {
    return {level: "pass", domNodes: [document.body]};
};

WI.DefaultAudits.dataDOMAttributes = function() {
    return {level: "pass", domNodes: Array.from(document.querySelectorAll("[id]")), domAttributes: ["id"]};
};

WI.DefaultAudits.dataErrors = function() {
    throw Error("this error was thrown from inside the audit test code.");
};

WI.DefaultAudits.dataCustom = function() {
    return {level: "pass", a: 1, b: [2], c: {key: 3}};
};

WI.DefaultAudits.getElementsByComputedRole = function() {
    return {level: "pass", domNodes: WebInspectorAudit.Accessibility.getElementsByComputedRole("link"), domAttributes: ["role"]};
};

WI.DefaultAudits.getActiveDescendant = function() {
    let result = {level: "pass"};
    let activeDescendant = WebInspectorAudit.Accessibility.getActiveDescendant(document.body);
    if (activeDescendant)
        result.domNodes = [activeDescendant];
    return result;
};

WI.DefaultAudits.getChildNodes = function() {
    let childNodes = WebInspectorAudit.Accessibility.getChildNodes(document.body);
    return {level: "pass", domNodes: childNodes || []};
};

WI.DefaultAudits.getComputedProperties = function() {
    let domAttributes = ["alt", "aria-atomic", "aria-busy", "aria-checked", "aria-current", "aria-disabled", "aria-expanded", "aria-haspopup", "aria-hidden", "aria-invalid", "aria-label", "aria-labelledby", "aria-level", "aria-live", "aria-pressed", "aria-readonly", "aria-relevant", "aria-required", "aria-selected", "role", "title"].filter((attribute) => document.body.hasAttribute(attribute));
    let computedProperties = WebInspectorAudit.Accessibility.getComputedProperties(document.body);
    return {level: "pass", domNodes: [document.body], domAttributes, ...(computedProperties || {})};
};

WI.DefaultAudits.getControlledNodes = function() {
    let controlledNodes = WebInspectorAudit.Accessibility.getControlledNodes(document.body);
    return {level: "pass", domNodes: controlledNodes || []};
};

WI.DefaultAudits.getFlowedNodes = function() {
    let flowedNodes = WebInspectorAudit.Accessibility.getFlowedNodes(document.body);
    return {level: "pass", domNodes: flowedNodes || []};
};

WI.DefaultAudits.getMouseEventNode = function() {
    let result = {level: "pass"};
    let mouseEventNode = WebInspectorAudit.Accessibility.getMouseEventNode(document.body);
    if (mouseEventNode)
        result.domNodes = [mouseEventNode];
    return result;
};

WI.DefaultAudits.getOwnedNodes = function() {
    let ownedNodes = WebInspectorAudit.Accessibility.getOwnedNodes(document.body);
    return {level: "pass", domNodes: ownedNodes || []};
};

WI.DefaultAudits.getParentNode = function() {
    let result = {level: "pass"};
    let parentNode = WebInspectorAudit.Accessibility.getParentNode(document.body);
    if (parentNode)
        result.domNodes = [parentNode];
    return result;
};

WI.DefaultAudits.getSelectedChildNodes = function() {
    let selectedChildNodes = WebInspectorAudit.Accessibility.getSelectedChildNodes(document.body);
    return {level: "pass", domNodes: selectedChildNodes || []};
};

WI.DefaultAudits.hasEventListeners = function() {
    let domAttributes = Array.from(document.body.attributes).filter((attribute) => attribute.name.startsWith("on"));
    return {level: "pass", domNodes: [document.body], domAttributes, hasEventListeners: WebInspectorAudit.DOM.hasEventListeners(document.body)};
};

WI.DefaultAudits.hasEventListenersClick = function() {
    let domAttributes = ["onclick"].filter((attribute) => document.body.hasAttribute(attribute));
    return {level: "pass", domNodes: [document.body], domAttributes, hasClickEventListener: WebInspectorAudit.DOM.hasEventListeners(document.body, "click")};
};

WI.DefaultAudits.getResources = function() {
    return {level: "pass", resources: WebInspectorAudit.Resources.getResources()};
};

WI.DefaultAudits.getResourceContent = function() {
    let resources = WebInspectorAudit.Resources.getResources();
    let mainResource = resources.find((resource) => resource.url === window.location.href);
    return {level: "pass", mainResource, resourceContent: WebInspectorAudit.Resources.getResourceContent(mainResource.id)};
};

WI.DefaultAudits.unsupported = function() {
    throw Error("this test should not be supported.");
};

WI.DefaultAudits.testMenuRoleForRequiredChildren = function() {
    const relationships = {
        menu: ["menuitem", "menuitemcheckbox", "menuitemradio"],
        menubar: ["menuitem", "menuitemcheckbox", "menuitemradio"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testGridRoleForRequiredChildren = function() {
    const relationships = {
        grid: ["row", "rowgroup"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testForAriaLabelledBySpelling = function() {
    let domNodes = Array.from(document.querySelectorAll("[aria-labeledby]"));
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-labeledby"]};
};

WI.DefaultAudits.testForMultipleBanners = function() {
    let domNodes = [];
    let banners = WebInspectorAudit.Accessibility.getElementsByComputedRole("banner");
    if (banners.length > 1)
        domNodes = banners;
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testForLinkLabels = function() {
    let links = WebInspectorAudit.Accessibility.getElementsByComputedRole("link");
    let domNodes = links.filter((link) => {
        let properties = WebInspectorAudit.Accessibility.getComputedProperties(link);
        return !properties.label && !properties.hidden;
    });
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-label", "aria-labelledby", "title"]};
};

WI.DefaultAudits.testRowGroupRoleForRequiredChildren = function() {
    const relationships = {
        rowgroup: ["row"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testTableRoleForRequiredChildren = function() {
    const relationships = {
        table: ["row", "rowgroup"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testForMultipleLiveRegions = function() {
    const liveRegionRoles = ["alert", "log", "status", "marquee", "timer"];
    let domNodes = [];
    let liveRegions = liveRegionRoles.reduce((a, b) => {
        return a.concat(WebInspectorAudit.Accessibility.getElementsByComputedRole(b));
    }, []);
    liveRegions = liveRegions.concat(Array.from(document.querySelectorAll(`[aria-live="polite"], [aria-live="assertive"]`)));
    if (liveRegions.length > 1)
        domNodes = liveRegions;
    return {level: domNodes.length ? "warn" : "pass", domNodes, domAttributes: ["aria-live"]};
};

WI.DefaultAudits.testListBoxRoleForRequiredChildren = function() {
    const relationships = {
        listbox: ["option"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testImageLabels = function() {
    let images = WebInspectorAudit.Accessibility.getElementsByComputedRole("img");
    let domNodes = images.filter((image) => !WebInspectorAudit.Accessibility.getComputedProperties(image).label);
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-label", "aria-labelledby", "title", "alt"]};
};

WI.DefaultAudits.testForAriaHiddenFalse = function() {
    let domNodes = Array.from(document.querySelectorAll(`[aria-hidden="false"]`));
    return {level: domNodes.length ? "warn" : "pass", domNodes, domAttributes: ["aria-hidden"]};
};

WI.DefaultAudits.testTreeRoleForRequiredChildren = function() {
    const relationships = {
        tree: ["treeitem", "group"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testRadioGroupRoleForRequiredChildren = function() {
    const relationships = {
        radiogroup: ["radio"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testFeedRoleForRequiredChildren = function() {
    const relationships = {
        feed: ["article"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testTabListRoleForRequiredChildren = function() {
    const relationships = {
        tablist: ["tab"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testButtonLabels = function() {
    let buttons = WebInspectorAudit.Accessibility.getElementsByComputedRole("button");
    let domNodes = buttons.filter((button) => !WebInspectorAudit.Accessibility.getComputedProperties(button).label);
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-label", "aria-labelledby", "title"]};
};

WI.DefaultAudits.testRowRoleForRequiredChildren = function() {
    const relationships = {
        row: ["cell", "gridcell", "columnheader", "rowheader"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testListRoleForRequiredChildren = function() {
    const relationships = {
        list: ["listitem", "group"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "warn" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testComboBoxRoleForRequiredChildren = function() {
    const relationships = {
        combobox: ["textbox", "listbox", "tree", "grid", "dialog"],
    };
    let domNodes = [];
    let visitedParents = new Set;
    function hasChildWithRole(node, expectedRoles) {
        let childNode = node;
        if (!childNode)
            return false;

        if (childNode.parentNode)
            visitedParents.add(childNode.parentNode);

        while (childNode) {
            let properties = WebInspectorAudit.Accessibility.getComputedProperties(childNode);
            if (childNode.nodeType === Node.ELEMENT_NODE && properties) {
                if (expectedRoles.includes(properties.role))
                    return true;

                if (childNode.hasChildNodes() && hasChildWithRole(childNode.firstChild, expectedRoles))
                    return true;
            }
            childNode = childNode.nextSibling;
        }
        return false;
    }
    for (let role in relationships) {
        for (let parentNode of WebInspectorAudit.Accessibility.getElementsByComputedRole(role)) {
            if (visitedParents.has(parentNode))
                continue;

            if (!hasChildWithRole(parentNode.firstChild, relationships[role]))
                domNodes.push(parentNode);
        }
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};

WI.DefaultAudits.testForMultipleMainContentSections = function() {
    let domNodes = [];
    let mainContentElements = WebInspectorAudit.Accessibility.getElementsByComputedRole("main");
    if (mainContentElements.length > 1) {
        domNodes = mainContentElements;
    }
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["role"]};
};
WI.DefaultAudits.testDialogsForLabels = function() {
    let dialogs = WebInspectorAudit.Accessibility.getElementsByComputedRole("dialog");
    let domNodes = dialogs.filter((dialog) => !WebInspectorAudit.Accessibility.getComputedProperties(dialog).label);
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-label", "aria-labelledby", "title"]};
};

WI.DefaultAudits.testForInvalidAriaHiddenValue = function() {
    let domNodes = Array.from(document.querySelectorAll(`[aria-hidden]:not([aria-hidden="true"], [aria-hidden="false"])`));
    return {level: domNodes.length ? "fail" : "pass", domNodes, domAttributes: ["aria-hidden"]};
};

WI.DefaultAudits.newAuditPlaceholder = function() {
    let result = {
        level: "pass",
    };
    return result;
};
