import{UIString,Revealer,Console,JavaScriptMetaData}from'../common/common.js';import{RemoteObject,RuntimeModel,OverlayModel,ConsoleModel,SDKModel,DebuggerModel}from'../sdk/sdk.js';import{TreeOutline,Utils,Fragment,UIUtils,ContextMenu,TextPrompt,ARIAUtils,Icon,Geometry,GlassPane}from'../ui/ui.js';import{Linkifier}from'../components/components.js';import{InspectorFrontendHost}from'../host/host.js';import{StringUtilities,NumberUtilities}from'../platform/platform.js';import{TextRange}from'../text_utils/text_utils.js';import{FormatterWorkerPool}from'../formatter/formatter.js';class RemoteObjectPreviewFormatter{static _objectPropertyComparator(a,b){return sortValue(a)-sortValue(b);function sortValue(property){const internalName=_internalName;if(property.name===internalName.PromiseStatus){return 1;}
if(property.name===internalName.PromiseValue){return 2;}
if(property.name===internalName.GeneratorStatus||property.name===internalName.PrimitiveValue){return 3;}
if(property.type!=='function'&&!property.name.startsWith('#')){return 4;}
return 5;}}
appendObjectPreview(parentElement,preview,isEntry){const description=preview.description;const subTypesWithoutValuePreview=new Set(['null','regexp','error','internal#entry']);if(preview.type!=='object'||subTypesWithoutValuePreview.has(preview.subtype)||isEntry){parentElement.appendChild(this.renderPropertyPreview(preview.type,preview.subtype,description));return;}
const isArrayOrTypedArray=preview.subtype==='array'||preview.subtype==='typedarray';if(description){let text;if(isArrayOrTypedArray){const arrayLength=RemoteObject.RemoteObject.arrayLength(preview);const arrayLengthText=arrayLength>1?('('+arrayLength+')'):'';const arrayName=RemoteObject.RemoteObject.arrayNameFromDescription(description);text=arrayName==='Array'?arrayLengthText:(arrayName+arrayLengthText);}else{const hideDescription=description==='Object';text=hideDescription?'':description;}
if(text.length>0){parentElement.createChild('span','object-description').textContent=text+'\xA0';}}
const propertiesElement=parentElement.createChild('span','object-properties-preview');propertiesElement.createTextChild(isArrayOrTypedArray?'[':'{');if(preview.entries){this._appendEntriesPreview(propertiesElement,preview);}else if(isArrayOrTypedArray){this._appendArrayPropertiesPreview(propertiesElement,preview);}else{this._appendObjectPropertiesPreview(propertiesElement,preview);}
if(preview.overflow){const ellipsisText=propertiesElement.textContent.length>1?',\xA0…':'…';propertiesElement.createChild('span').textContent=ellipsisText;}
propertiesElement.createTextChild(isArrayOrTypedArray?']':'}');}
_abbreviateFullQualifiedClassName(description){const abbreviatedDescription=description.split('.');for(let i=0;i<abbreviatedDescription.length-1;++i){abbreviatedDescription[i]=abbreviatedDescription[i].trimMiddle(3);}
return abbreviatedDescription.join('.');}
_appendObjectPropertiesPreview(parentElement,preview){const internalName=_internalName;const properties=preview.properties.filter(p=>p.type!=='accessor').sort(RemoteObjectPreviewFormatter._objectPropertyComparator);for(let i=0;i<properties.length;++i){if(i>0){parentElement.createTextChild(', ');}
const property=properties[i];const name=property.name;if(preview.subtype==='promise'&&name===internalName.PromiseStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));const nextProperty=i+1<properties.length?properties[i+1]:null;if(nextProperty&&nextProperty.name===internalName.PromiseValue){if(property.value!=='pending'){parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([nextProperty]));}
i++;}}else if(preview.subtype==='generator'&&name===internalName.GeneratorStatus){parentElement.appendChild(this._renderDisplayName('<'+property.value+'>'));}else if(name===internalName.PrimitiveValue){parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}else{parentElement.appendChild(this._renderDisplayName(name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));}}}
_appendArrayPropertiesPreview(parentElement,preview){const arrayLength=RemoteObject.RemoteObject.arrayLength(preview);const indexProperties=preview.properties.filter(p=>toArrayIndex(p.name)!==-1).sort(arrayEntryComparator);const otherProperties=preview.properties.filter(p=>toArrayIndex(p.name)===-1).sort(RemoteObjectPreviewFormatter._objectPropertyComparator);function arrayEntryComparator(a,b){return toArrayIndex(a.name)-toArrayIndex(b.name);}
function toArrayIndex(name){const index=name>>>0;if(String(index)===name&&index<arrayLength){return index;}
return-1;}
const canShowGaps=!preview.overflow;let lastNonEmptyArrayIndex=-1;let elementsAdded=false;for(let i=0;i<indexProperties.length;++i){if(elementsAdded){parentElement.createTextChild(', ');}
const property=indexProperties[i];const index=toArrayIndex(property.name);if(canShowGaps&&index-lastNonEmptyArrayIndex>1){appendUndefined(index);parentElement.createTextChild(', ');}
if(!canShowGaps&&i!==index){parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');}
parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));lastNonEmptyArrayIndex=index;elementsAdded=true;}
if(canShowGaps&&arrayLength-lastNonEmptyArrayIndex>1){if(elementsAdded){parentElement.createTextChild(', ');}
appendUndefined(arrayLength);}
for(let i=0;i<otherProperties.length;++i){if(elementsAdded){parentElement.createTextChild(', ');}
const property=otherProperties[i];parentElement.appendChild(this._renderDisplayName(property.name));parentElement.createTextChild(': ');parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property]));elementsAdded=true;}
function appendUndefined(index){const span=parentElement.createChild('span','object-value-undefined');const count=index-lastNonEmptyArrayIndex-1;span.textContent=count!==1?UIString.UIString('empty × %d',count):UIString.UIString('empty');elementsAdded=true;}}
_appendEntriesPreview(parentElement,preview){for(let i=0;i<preview.entries.length;++i){if(i>0){parentElement.createTextChild(', ');}
const entry=preview.entries[i];if(entry.key){this.appendObjectPreview(parentElement,entry.key,true);parentElement.createTextChild(' => ');}
this.appendObjectPreview(parentElement,entry.value,true);}}
_renderDisplayName(name){const result=document.createElement('span');result.classList.add('name');const needsQuotes=/^\s|\s$|^$|\n/.test(name);result.textContent=needsQuotes?'"'+name.replace(/\n/g,'\u21B5')+'"':name;return result;}
_renderPropertyPreviewOrAccessor(propertyPath){const property=propertyPath.peekLast();return this.renderPropertyPreview(property.type,(property.subtype),property.value);}
renderPropertyPreview(type,subtype,description){const span=document.createElement('span');span.classList.add('object-value-'+(subtype||type));description=description||'';if(type==='accessor'){span.textContent='(...)';span.title=UIString.UIString('The property is computed with a getter');return span;}
if(type==='function'){span.textContent='\u0192';return span;}
if(type==='object'&&subtype==='node'&&description){createSpansForNodeTitle(span,description);return span;}
if(type==='string'){span.createTextChildren('"',description.replace(/\n/g,'\u21B5'),'"');return span;}
if(type==='object'&&!subtype){let preview=this._abbreviateFullQualifiedClassName(description);if(preview==='Object'){preview='{…}';}
span.textContent=preview;span.title=description;return span;}
span.textContent=description;return span;}}
const _internalName={GeneratorStatus:'[[GeneratorStatus]]',PrimitiveValue:'[[PrimitiveValue]]',PromiseStatus:'[[PromiseStatus]]',PromiseValue:'[[PromiseValue]]'};const createSpansForNodeTitle=function(container,nodeTitle){const match=nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/);container.createChild('span','webkit-html-tag-name').textContent=match[1];if(match[2]){container.createChild('span','webkit-html-attribute-value').textContent=match[2];}
if(match[3]){container.createChild('span','webkit-html-attribute-name').textContent=match[3];}};var RemoteObjectPreviewFormatter$1=Object.freeze({__proto__:null,RemoteObjectPreviewFormatter:RemoteObjectPreviewFormatter,createSpansForNodeTitle:createSpansForNodeTitle});class JavaScriptREPL{static wrapObjectLiteral(code){if(!(/^\s*\{/.test(code)&&/\}\s*$/.test(code))){return code;}
const parse=(async()=>0).constructor;try{parse('return '+code+';');const wrappedCode='('+code+')';parse(wrappedCode);return wrappedCode;}catch(e){return code;}}
static preprocessExpression(text){return JavaScriptREPL.wrapObjectLiteral(text);}
static async evaluateAndBuildPreview(text,throwOnSideEffect,timeout,allowErrors,objectGroup){const executionContext=self.UI.context.flavor(RuntimeModel.ExecutionContext);const maxLength=typeof self.ObjectUI.JavaScriptREPL._MaxLengthForEvaluation!=='undefined'?self.ObjectUI.JavaScriptREPL._MaxLengthForEvaluation:MaxLengthForEvaluation;const isTextLong=text.length>maxLength;if(!text||!executionContext||(throwOnSideEffect&&isTextLong)){return{preview:createDocumentFragment(),result:null};}
const expression=JavaScriptREPL.preprocessExpression(text);const options={expression:expression,generatePreview:true,includeCommandLineAPI:true,throwOnSideEffect:throwOnSideEffect,timeout:timeout,objectGroup:objectGroup,disableBreaks:true,replMode:true};const result=await executionContext.evaluate(options,false,false);const preview=JavaScriptREPL._buildEvaluationPreview(result,allowErrors);return{preview,result};}
static _buildEvaluationPreview(result,allowErrors){const fragment=createDocumentFragment();if(result.error){return fragment;}
if(result.exceptionDetails&&result.exceptionDetails.exception&&result.exceptionDetails.exception.description){const exception=result.exceptionDetails.exception.description;if(exception.startsWith('TypeError: ')||allowErrors){fragment.createChild('span').textContent=result.exceptionDetails.text+' '+exception;}
return fragment;}
const formatter=new RemoteObjectPreviewFormatter();const{preview,type,subtype,description}=result.object;if(preview&&type==='object'&&subtype!=='node'){formatter.appendObjectPreview(fragment,preview,false);}else{const nonObjectPreview=formatter.renderPropertyPreview(type,subtype,description.trimEndWithMaxLength(400));fragment.appendChild(nonObjectPreview);}
return fragment;}}
const MaxLengthForEvaluation=2000;var JavaScriptREPL$1=Object.freeze({__proto__:null,JavaScriptREPL:JavaScriptREPL,MaxLengthForEvaluation:MaxLengthForEvaluation});class ObjectPropertiesSection extends TreeOutline.TreeOutlineInShadow{constructor(object,title,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties,showOverflow){super();this._object=object;this._editable=true;if(!showOverflow){this.hideOverflow();}
this.setFocusable(true);this.setShowSelectionOnKeyboardFocus(true);this._objectTreeElement=new RootElement(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties);this.appendChild(this._objectTreeElement);if(typeof title==='string'||!title){this.titleElement=this.element.createChild('span');this.titleElement.textContent=title||'';}else{this.titleElement=title;this.element.appendChild(title);}
if(!this.titleElement.hasAttribute('tabIndex')){this.titleElement.tabIndex=-1;}
this.element._section=this;this.registerRequiredCSS('object_ui/objectValue.css');this.registerRequiredCSS('object_ui/objectPropertiesSection.css');this.rootElement().childrenListElement.classList.add('source-code','object-properties-section');}
static defaultObjectPresentation(object,linkifier,skipProto,readOnly){const objectPropertiesSection=ObjectPropertiesSection.defaultObjectPropertiesSection(object,linkifier,skipProto,readOnly);if(!object.hasChildren){return objectPropertiesSection.titleElement;}
return objectPropertiesSection.element;}
static defaultObjectPropertiesSection(object,linkifier,skipProto,readOnly){const titleElement=document.createElement('span');titleElement.classList.add('source-code');const shadowRoot=Utils.createShadowRootWithCoreStyles(titleElement,'object_ui/objectValue.css');const propertyValue=ObjectPropertiesSection.createPropertyValue(object,false,true);shadowRoot.appendChild(propertyValue.element);const objectPropertiesSection=new ObjectPropertiesSection(object,titleElement,linkifier);objectPropertiesSection.editable=false;if(skipProto){objectPropertiesSection.skipProto();}
if(readOnly){objectPropertiesSection.setEditable(false);}
return objectPropertiesSection;}
static CompareProperties(propertyA,propertyB){const a=propertyA.name;const b=propertyB.name;if(a==='__proto__'){return 1;}
if(b==='__proto__'){return-1;}
if(!propertyA.enumerable&&propertyB.enumerable){return 1;}
if(!propertyB.enumerable&&propertyA.enumerable){return-1;}
if(a.startsWith('_')&&!b.startsWith('_')){return 1;}
if(b.startsWith('_')&&!a.startsWith('_')){return-1;}
if(propertyA.symbol&&!propertyB.symbol){return 1;}
if(propertyB.symbol&&!propertyA.symbol){return-1;}
if(propertyA.private&&!propertyB.private){return 1;}
if(propertyB.private&&!propertyA.private){return-1;}
return String.naturalOrderComparator(a,b);}
static createNameElement(name,isPrivate){if(name===null){return Fragment.html`<span class="name"></span>`;}
if(/^\s|\s$|^$|\n/.test(name)){return Fragment.html`<span class="name">"${name.replace(/\n/g, '\u21B5')}"</span>`;}
if(isPrivate){return Fragment.html`<span class="name">
        <span class="private-property-hash">${name[0]}</span>${name.substring(1)}
      </span>`;}
return Fragment.html`<span class="name">${name}</span>`;}
static valueElementForFunctionDescription(description,includePreview,defaultName){const valueElement=document.createElement('span');valueElement.classList.add('object-value-function');description=description||'';const text=description.replace(/^function [gs]et /,'function ').replace(/^function [gs]et\(/,'function\(').replace(/^[gs]et /,'');defaultName=defaultName||'';const asyncMatch=text.match(/^(async\s+function)/);const isGenerator=text.startsWith('function*');const isGeneratorShorthand=text.startsWith('*');const isBasic=!isGenerator&&text.startsWith('function');const isClass=text.startsWith('class ')||text.startsWith('class{');const firstArrowIndex=text.indexOf('=>');const isArrow=!asyncMatch&&!isGenerator&&!isBasic&&!isClass&&firstArrowIndex>0;let textAfterPrefix;if(isClass){textAfterPrefix=text.substring('class'.length);const classNameMatch=/^[^{\s]+/.exec(textAfterPrefix.trim());let className=defaultName;if(classNameMatch){className=classNameMatch[0].trim()||defaultName;}
addElements('class',textAfterPrefix,className);}else if(asyncMatch){textAfterPrefix=text.substring(asyncMatch[1].length);addElements('async \u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGenerator){textAfterPrefix=text.substring('function*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isGeneratorShorthand){textAfterPrefix=text.substring('*'.length);addElements('\u0192*',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isBasic){textAfterPrefix=text.substring('function'.length);addElements('\u0192',textAfterPrefix,nameAndArguments(textAfterPrefix));}else if(isArrow){const maxArrowFunctionCharacterLength=60;let abbreviation=text;if(defaultName){abbreviation=defaultName+'()';}else if(text.length>maxArrowFunctionCharacterLength){abbreviation=text.substring(0,firstArrowIndex+2)+' {…}';}
addElements('',text,abbreviation);}else{addElements('\u0192',text,nameAndArguments(text));}
valueElement.title=description.trimEndWithMaxLength(500);return valueElement;function nameAndArguments(contents){const startOfArgumentsIndex=contents.indexOf('(');const endOfArgumentsMatch=contents.match(/\)\s*{/);if(startOfArgumentsIndex!==-1&&endOfArgumentsMatch&&endOfArgumentsMatch.index>startOfArgumentsIndex){const name=contents.substring(0,startOfArgumentsIndex).trim()||defaultName;const args=contents.substring(startOfArgumentsIndex,endOfArgumentsMatch.index+1);return name+args;}
return defaultName+'()';}
function addElements(prefix,body,abbreviation){const maxFunctionBodyLength=200;if(prefix.length){valueElement.createChild('span','object-value-function-prefix').textContent=prefix+' ';}
if(includePreview){valueElement.createTextChild(body.trim().trimEndWithMaxLength(maxFunctionBodyLength));}else{valueElement.createTextChild(abbreviation.replace(/\n/g,' '));}}}
static createPropertyValueWithCustomSupport(value,wasThrown,showPreview,parentElement,linkifier){if(value.customPreview()){const result=(new CustomPreviewComponent(value)).element;result.classList.add('object-properties-section-custom-section');return new ObjectPropertyValue(result);}
return ObjectPropertiesSection.createPropertyValue(value,wasThrown,showPreview,parentElement,linkifier);}
static createPropertyValue(value,wasThrown,showPreview,parentElement,linkifier){let propertyValue;const type=value.type;const subtype=value.subtype;const description=value.description;if(type==='object'&&subtype==='internal#location'){const rawLocation=value.debuggerModel().createRawLocationByScriptId(value.value.scriptId,value.value.lineNumber,value.value.columnNumber);if(rawLocation&&linkifier){return new ObjectPropertyValue(linkifier.linkifyRawLocation(rawLocation,''));}
propertyValue=new ObjectPropertyValue(createUnknownInternalLocationElement());}else if(type==='string'&&typeof description==='string'){propertyValue=createStringElement();}else if(type==='function'){propertyValue=new ObjectPropertyValue(ObjectPropertiesSection.valueElementForFunctionDescription(description));}else if(type==='object'&&subtype==='node'&&description){propertyValue=new ObjectPropertyValue(createNodeElement());}else if(type==='number'&&description&&description.indexOf('e')!==-1){propertyValue=new ObjectPropertyValue(createNumberWithExponentElement());if(parentElement)
{parentElement.classList.add('hbox');}}else{const valueElement=document.createElement('span');valueElement.classList.add('object-value-'+(subtype||type));if(value.preview&&showPreview){const previewFormatter=new RemoteObjectPreviewFormatter();previewFormatter.appendObjectPreview(valueElement,value.preview,false);propertyValue=new ObjectPropertyValue(valueElement);propertyValue.element.title=description||'';}else if(description.length>(self.ObjectUI.ObjectPropertiesSection._maxRenderableStringLength||maxRenderableStringLength)){propertyValue=new ExpandableTextPropertyValue(valueElement,description,50);}else{propertyValue=new ObjectPropertyValue(valueElement);propertyValue.element.textContent=description;propertyValue.element.title=description||'';}}
if(wasThrown){const wrapperElement=document.createElement('span');wrapperElement.classList.add('error');wrapperElement.classList.add('value');wrapperElement.appendChild(UIUtils.formatLocalized('[Exception: %s]',[propertyValue.element]));propertyValue.element=wrapperElement;}
propertyValue.element.classList.add('value');return propertyValue;function createUnknownInternalLocationElement(){const valueElement=document.createElement('span');valueElement.textContent='<'+UIString.UIString('unknown')+'>';valueElement.title=description||'';return valueElement;}
function createStringElement(){const valueElement=document.createElement('span');valueElement.classList.add('object-value-string');const text=description.replace(/\n/g,'\u21B5');let propertyValue;valueElement.createChild('span','object-value-string-quote').textContent='"';if(description.length>(self.ObjectUI.ObjectPropertiesSection._maxRenderableStringLength||maxRenderableStringLength)){propertyValue=new ExpandableTextPropertyValue(valueElement,text,50);}else{valueElement.createTextChild(text);propertyValue=new ObjectPropertyValue(valueElement);valueElement.title=description||'';}
valueElement.createChild('span','object-value-string-quote').textContent='"';return propertyValue;}
function createNodeElement(){const valueElement=document.createElement('span');valueElement.classList.add('object-value-node');createSpansForNodeTitle(valueElement,(description));valueElement.addEventListener('click',event=>{Revealer.reveal(value);event.consume(true);},false);valueElement.addEventListener('mousemove',()=>OverlayModel.OverlayModel.highlightObjectAsDOMNode(value),false);valueElement.addEventListener('mouseleave',()=>OverlayModel.OverlayModel.hideDOMNodeHighlight(),false);return valueElement;}
function createNumberWithExponentElement(){const valueElement=document.createElement('span');valueElement.classList.add('object-value-number');const numberParts=description.split('e');valueElement.createChild('span','object-value-scientific-notation-mantissa').textContent=numberParts[0];valueElement.createChild('span','object-value-scientific-notation-exponent').textContent='e'+numberParts[1];valueElement.classList.add('object-value-scientific-notation-number');valueElement.title=description||'';return valueElement;}}
static formatObjectAsFunction(func,element,linkify,includePreview){return func.debuggerModel().functionDetailsPromise(func).then(didGetDetails);function didGetDetails(response){if(linkify&&response&&response.location){element.classList.add('linkified');element.addEventListener('click',()=>Revealer.reveal(response.location)&&false);}
let defaultName=includePreview?'':'anonymous';if(response&&response.functionName){defaultName=response.functionName;}
const valueElement=ObjectPropertiesSection.valueElementForFunctionDescription(func.description,includePreview,defaultName);element.appendChild(valueElement);}}
static _isDisplayableProperty(property,parentProperty){if(!parentProperty||!parentProperty.synthetic){return true;}
const name=property.name;const useless=(parentProperty.name==='[[Entries]]'&&(name==='length'||name==='__proto__'));return!useless;}
skipProto(){this._skipProto=true;}
expand(){this._objectTreeElement.expand();}
setEditable(value){this._editable=value;}
objectTreeElement(){return this._objectTreeElement;}
enableContextMenu(){this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);}
_contextMenuEventFired(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.appendApplicableItems(this._object);if(this._object instanceof RemoteObject.LocalJSONObject){contextMenu.viewSection().appendItem(ls`Expand recursively`,this._objectTreeElement.expandRecursively.bind(this._objectTreeElement,Number.MAX_VALUE));contextMenu.viewSection().appendItem(ls`Collapse children`,this._objectTreeElement.collapseChildren.bind(this._objectTreeElement));}
contextMenu.show();}
titleLessMode(){this._objectTreeElement.listItemElement.classList.add('hidden');this._objectTreeElement.childrenListElement.classList.add('title-less-mode');this._objectTreeElement.expand();}}
const _arrayLoadThreshold=100;const maxRenderableStringLength=10000;class ObjectPropertiesSectionsTreeOutline extends TreeOutline.TreeOutlineInShadow{constructor(options){super();this.registerRequiredCSS('object_ui/objectValue.css');this.registerRequiredCSS('object_ui/objectPropertiesSection.css');this._editable=!(options&&options.readOnly);this.contentElement.classList.add('source-code');this.contentElement.classList.add('object-properties-section');this.hideOverflow();}}
class RootElement extends TreeOutline.TreeElement{constructor(object,linkifier,emptyPlaceholder,ignoreHasOwnProperty,extraProperties){const contentElement=createElement('slot');super(contentElement);this._object=object;this._extraProperties=extraProperties||[];this._ignoreHasOwnProperty=!!ignoreHasOwnProperty;this._emptyPlaceholder=emptyPlaceholder;this.setExpandable(true);this.selectable=true;this.toggleOnClick=true;this.listItemElement.classList.add('object-properties-section-root-element');this._linkifier=linkifier;}
onexpand(){if(this.treeOutline){this.treeOutline.element.classList.add('expanded');}}
oncollapse(){if(this.treeOutline){this.treeOutline.element.classList.remove('expanded');}}
ondblclick(e){return true;}
async onpopulate(){return ObjectPropertyTreeElement._populate(this,this._object,!!this.treeOutline._skipProto,this._linkifier,this._emptyPlaceholder,this._ignoreHasOwnProperty,this._extraProperties);}}
class ObjectPropertyTreeElement extends TreeOutline.TreeElement{constructor(property,linkifier){super();this.property=property;this.toggleOnClick=true;this._highlightChanges=[];this._linkifier=linkifier;this.listItemElement.addEventListener('contextmenu',this._contextMenuFired.bind(this),false);}
static async _populate(treeElement,value,skipProto,linkifier,emptyPlaceholder,flattenProtoChain,extraProperties,targetValue){if(value.arrayLength()>_arrayLoadThreshold){treeElement.removeChildren();ArrayGroupingTreeElement._populateArray(treeElement,value,0,value.arrayLength()-1,linkifier);return;}
let allProperties;if(flattenProtoChain){allProperties=await value.getAllProperties(false,true);}else{allProperties=await RemoteObject.RemoteObject.loadFromObjectPerProto(value,true);}
const properties=allProperties.properties;const internalProperties=allProperties.internalProperties;treeElement.removeChildren();if(!properties){return;}
extraProperties=extraProperties||[];for(let i=0;i<extraProperties.length;++i){properties.push(extraProperties[i]);}
ObjectPropertyTreeElement.populateWithProperties(treeElement,properties,internalProperties,skipProto,targetValue||value,linkifier,emptyPlaceholder);}
static populateWithProperties(treeNode,properties,internalProperties,skipProto,value,linkifier,emptyPlaceholder){properties.sort(ObjectPropertiesSection.CompareProperties);internalProperties=internalProperties||[];const entriesProperty=internalProperties.find(property=>property.name==='[[Entries]]');if(entriesProperty){entriesProperty.parentObject=value;const treeElement=new ObjectPropertyTreeElement(entriesProperty,linkifier);treeElement.setExpandable(true);treeElement.expand();treeNode.appendChild(treeElement);}
const tailProperties=[];let protoProperty=null;for(let i=0;i<properties.length;++i){const property=properties[i];property.parentObject=value;if(!ObjectPropertiesSection._isDisplayableProperty(property,treeNode.property)){continue;}
if(property.name==='__proto__'&&!property.isAccessorProperty()){protoProperty=property;continue;}
if(property.isOwn&&property.getter){const getterProperty=new RemoteObject.RemoteObjectProperty('get '+property.name,property.getter,false);getterProperty.parentObject=value;tailProperties.push(getterProperty);}
if(property.isOwn&&property.setter){const setterProperty=new RemoteObject.RemoteObjectProperty('set '+property.name,property.setter,false);setterProperty.parentObject=value;tailProperties.push(setterProperty);}
const canShowProperty=property.getter||!property.isAccessorProperty();if(canShowProperty&&property.name!=='__proto__'){treeNode.appendChild(new ObjectPropertyTreeElement(property,linkifier));}}
for(let i=0;i<tailProperties.length;++i){treeNode.appendChild(new ObjectPropertyTreeElement(tailProperties[i],linkifier));}
if(!skipProto&&protoProperty){treeNode.appendChild(new ObjectPropertyTreeElement(protoProperty,linkifier));}
for(const property of internalProperties){property.parentObject=value;const treeElement=new ObjectPropertyTreeElement(property,linkifier);if(property.name==='[[Entries]]'){continue;}
treeNode.appendChild(treeElement);}
ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder);}
static _appendEmptyPlaceholderIfNeeded(treeNode,emptyPlaceholder){if(treeNode.childCount()){return;}
const title=document.createElement('div');title.classList.add('gray-info-message');title.textContent=emptyPlaceholder||UIString.UIString('No properties');const infoElement=new TreeOutline.TreeElement(title);treeNode.appendChild(infoElement);}
static createRemoteObjectAccessorPropertySpan(object,propertyPath,callback){const rootElement=createElement('span');const element=rootElement.createChild('span');element.textContent=UIString.UIString('(...)');if(!object){return rootElement;}
element.classList.add('object-value-calculate-value-button');element.title=UIString.UIString('Invoke property getter');element.addEventListener('click',onInvokeGetterClick,false);function onInvokeGetterClick(event){event.consume();object.callFunction(invokeGetter,[{value:JSON.stringify(propertyPath)}]).then(callback);}
function invokeGetter(arrayStr){let result=this;const properties=JSON.parse(arrayStr);for(let i=0,n=properties.length;i<n;++i){result=result[properties[i]];}
return result;}
return rootElement;}
setSearchRegex(regex,additionalCssClassName){let cssClasses=UIUtils.highlightedSearchResultClassName;if(additionalCssClassName){cssClasses+=' '+additionalCssClassName;}
this.revertHighlightChanges();this._applySearch(regex,this.nameElement,cssClasses);const valueType=this.property.value.type;if(valueType!=='object'){this._applySearch(regex,this.valueElement,cssClasses);}
return!!this._highlightChanges.length;}
_applySearch(regex,element,cssClassName){const ranges=[];const content=element.textContent;regex.lastIndex=0;let match=regex.exec(content);while(match){ranges.push(new TextRange.SourceRange(match.index,match[0].length));match=regex.exec(content);}
if(ranges.length){UIUtils.highlightRangesWithStyleClass(element,ranges,cssClassName,this._highlightChanges);}}
revertHighlightChanges(){UIUtils.revertDomChanges(this._highlightChanges);this._highlightChanges=[];}
async onpopulate(){const propertyValue=(this.property.value);console.assert(propertyValue);const skipProto=this.treeOutline?this.treeOutline._skipProto:true;const targetValue=this.property.name!=='__proto__'?propertyValue:this.property.parentObject;await ObjectPropertyTreeElement._populate(this,propertyValue,skipProto,this._linkifier,undefined,undefined,undefined,targetValue);}
ondblclick(event){const inEditableElement=event.target.isSelfOrDescendant(this.valueElement)||(this.expandedValueElement&&event.target.isSelfOrDescendant(this.expandedValueElement));if(this.property.value&&!this.property.value.customPreview()&&inEditableElement&&(this.property.writable||this.property.setter)){this._startEditing();}
return false;}
onenter(){if(!this.property.value.customPreview()&&(this.property.writable||this.property.setter)){this._startEditing();return true;}
return false;}
onattach(){this.update();this._updateExpandable();}
onexpand(){this._showExpandedValueElement(true);}
oncollapse(){this._showExpandedValueElement(false);}
_showExpandedValueElement(value){if(!this.expandedValueElement){return;}
if(value){this._rowContainer.replaceChild(this.expandedValueElement,this.valueElement);}else{this._rowContainer.replaceChild(this.valueElement,this.expandedValueElement);}}
_createExpandedValueElement(value){const needsAlternateValue=value.hasChildren&&!value.customPreview()&&value.subtype!=='node'&&value.type!=='function'&&(value.type!=='object'||value.preview);if(!needsAlternateValue){return null;}
const valueElement=document.createElement('span');valueElement.classList.add('value');if(value.description==='Object'){valueElement.textContent='';}else{valueElement.setTextContentTruncatedIfNeeded(value.description||'');}
valueElement.classList.add('object-value-'+(value.subtype||value.type));valueElement.title=value.description||'';return valueElement;}
update(){this.nameElement=ObjectPropertiesSection.createNameElement(this.property.name,this.property.private);if(!this.property.enumerable){this.nameElement.classList.add('object-properties-section-dimmed');}
if(this.property.synthetic){this.nameElement.classList.add('synthetic-property');}
this._updatePropertyPath();const isInternalEntries=this.property.synthetic&&this.property.name==='[[Entries]]';if(isInternalEntries){this.valueElement=document.createElement('span');this.valueElement.classList.add('value');}else if(this.property.value){const showPreview=this.property.name!=='__proto__';this.propertyValue=ObjectPropertiesSection.createPropertyValueWithCustomSupport(this.property.value,this.property.wasThrown,showPreview,this.listItemElement,this._linkifier);this.valueElement=this.propertyValue.element;}else if(this.property.getter){this.valueElement=ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(this.property.parentObject,[this.property.name],this._onInvokeGetterClick.bind(this));}else{this.valueElement=document.createElement('span');this.valueElement.classList.add('object-value-undefined');this.valueElement.textContent=UIString.UIString('<unreadable>');this.valueElement.title=UIString.UIString('No property getter');}
const valueText=this.valueElement.textContent;if(this.property.value&&valueText&&!this.property.wasThrown){this.expandedValueElement=this._createExpandedValueElement(this.property.value);}
this.listItemElement.removeChildren();if(isInternalEntries){this._rowContainer=Fragment.html`<span class='name-and-value'>${this.nameElement}</span>`;}else{this._rowContainer=Fragment.html`<span class='name-and-value'>${this.nameElement}: ${this.valueElement}</span>`;}
this.listItemElement.appendChild(this._rowContainer);}
_updatePropertyPath(){if(this.nameElement.title){return;}
const name=this.property.name;if(this.property.synthetic){this.nameElement.title=name;return;}
const useDotNotation=/^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;const isInteger=/^(?:0|[1-9]\d*)$/;const parentPath=(this.parent.nameElement&&!this.parent.property.synthetic)?this.parent.nameElement.title:'';if(this.property.private||useDotNotation.test(name)){this.nameElement.title=parentPath?`${parentPath}.${name}`:name;}else if(isInteger.test(name)){this.nameElement.title=`${parentPath}[${name}]`;}else{this.nameElement.title=`${parentPath}[${JSON.stringify(name)}]`;}}
_contextMenuFired(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.appendApplicableItems(this);if(this.property.symbol){contextMenu.appendApplicableItems(this.property.symbol);}
if(this.property.value){contextMenu.appendApplicableItems(this.property.value);}
if(!this.property.synthetic&&this.nameElement&&this.nameElement.title){const copyPathHandler=InspectorFrontendHost.InspectorFrontendHostInstance.copyText.bind(InspectorFrontendHost.InspectorFrontendHostInstance,this.nameElement.title);contextMenu.clipboardSection().appendItem(ls`Copy property path`,copyPathHandler);}
if(this.property.parentObject instanceof RemoteObject.LocalJSONObject){contextMenu.viewSection().appendItem(ls`Expand recursively`,this.expandRecursively.bind(this,Number.MAX_VALUE));contextMenu.viewSection().appendItem(ls`Collapse children`,this.collapseChildren.bind(this));}
if(this.propertyValue){this.propertyValue.appendApplicableItems(event,contextMenu);}
contextMenu.show();}
_startEditing(){if(this._prompt||!this.treeOutline._editable||this._readOnly){return;}
this._editableDiv=this._rowContainer.createChild('span','editable-div');let text=this.property.value.description;if(this.property.value.type==='string'&&typeof text==='string'){text=`"${text}"`;}
this._editableDiv.setTextContentTruncatedIfNeeded(text,UIString.UIString('<string is too large to edit>'));const originalContent=this._editableDiv.textContent;this.setExpandable(false);this.listItemElement.classList.add('editing-sub-part');this.valueElement.classList.add('hidden');this._prompt=new ObjectPropertyPrompt();const proxyElement=this._prompt.attachAndStartEditing(this._editableDiv,this._editingCommitted.bind(this,originalContent));proxyElement.classList.add('property-prompt');this.listItemElement.getComponentSelection().selectAllChildren(this._editableDiv);proxyElement.addEventListener('keydown',this._promptKeyDown.bind(this,originalContent),false);}
_editingEnded(){this._prompt.detach();delete this._prompt;this._editableDiv.remove();this._updateExpandable();this.listItemElement.scrollLeft=0;this.listItemElement.classList.remove('editing-sub-part');this.select();}
_editingCancelled(){this.valueElement.classList.remove('hidden');this._editingEnded();}
async _editingCommitted(originalContent){const userInput=this._prompt.text();if(userInput===originalContent){this._editingCancelled();return;}
this._editingEnded();await this._applyExpression(userInput);}
_promptKeyDown(originalContent,event){if(isEnterKey(event)){event.consume();this._editingCommitted(originalContent);return;}
if(event.key==='Escape'){event.consume();this._editingCancelled();return;}}
async _applyExpression(expression){const property=RemoteObject.RemoteObject.toCallArgument(this.property.symbol||this.property.name);expression=JavaScriptREPL.wrapObjectLiteral(expression.trim());if(this.property.synthetic){let invalidate=false;if(expression){invalidate=await this.property.setSyntheticValue(expression);}
if(invalidate){const parent=this.parent;parent.invalidateChildren();parent.onpopulate();}else{this.update();}
return;}
const errorPromise=expression?this.property.parentObject.setPropertyValue(property,expression):this.property.parentObject.deleteProperty(property);const error=await errorPromise;if(error){this.update();return;}
if(!expression){this.parent.removeChild(this);}else{const parent=this.parent;parent.invalidateChildren();parent.onpopulate();}}
_onInvokeGetterClick(result){if(!result.object){return;}
this.property.value=result.object;this.property.wasThrown=result.wasThrown;this.update();this.invalidateChildren();this._updateExpandable();}
_updateExpandable(){if(this.property.value){this.setExpandable(!this.property.value.customPreview()&&this.property.value.hasChildren&&!this.property.wasThrown);}else{this.setExpandable(false);}}
path(){return this.nameElement.title;}}
class ArrayGroupingTreeElement extends TreeOutline.TreeElement{constructor(object,fromIndex,toIndex,propertyCount,linkifier){super(StringUtilities.sprintf('[%d … %d]',fromIndex,toIndex),true);this.toggleOnClick=true;this._fromIndex=fromIndex;this._toIndex=toIndex;this._object=object;this._readOnly=true;this._propertyCount=propertyCount;this._linkifier=linkifier;}
static async _populateArray(treeNode,object,fromIndex,toIndex,linkifier){await ArrayGroupingTreeElement._populateRanges(treeNode,object,fromIndex,toIndex,true,linkifier);}
static async _populateRanges(treeNode,object,fromIndex,toIndex,topLevel,linkifier){const jsonValue=await object.callFunctionJSON(packRanges,[{value:fromIndex},{value:toIndex},{value:ArrayGroupingTreeElement._bucketThreshold},{value:ArrayGroupingTreeElement._sparseIterationThreshold},{value:ArrayGroupingTreeElement._getOwnPropertyNamesThreshold}]);await callback(jsonValue);function packRanges(fromIndex,toIndex,bucketThreshold,sparseIterationThreshold,getOwnPropertyNamesThreshold){let ownPropertyNames=null;const consecutiveRange=(toIndex-fromIndex>=sparseIterationThreshold)&&ArrayBuffer.isView(this);const skipGetOwnPropertyNames=consecutiveRange&&(toIndex-fromIndex>=getOwnPropertyNamesThreshold);function*arrayIndexes(object){if(toIndex-fromIndex<sparseIterationThreshold){for(let i=fromIndex;i<=toIndex;++i){if(i in object){yield i;}}}else{ownPropertyNames=ownPropertyNames||Object.getOwnPropertyNames(object);for(let i=0;i<ownPropertyNames.length;++i){const name=ownPropertyNames[i];const index=name>>>0;if((''+index)===name&&fromIndex<=index&&index<=toIndex){yield index;}}}}
let count=0;if(consecutiveRange){count=toIndex-fromIndex+1;}else{for(const i of arrayIndexes(this))
++count;}
let bucketSize=count;if(count<=bucketThreshold){bucketSize=count;}else{bucketSize=Math.pow(bucketThreshold,Math.ceil(Math.log(count)/Math.log(bucketThreshold))-1);}
const ranges=[];if(consecutiveRange){for(let i=fromIndex;i<=toIndex;i+=bucketSize){const groupStart=i;let groupEnd=groupStart+bucketSize-1;if(groupEnd>toIndex){groupEnd=toIndex;}
ranges.push([groupStart,groupEnd,groupEnd-groupStart+1]);}}else{count=0;let groupStart=-1;let groupEnd=0;for(const i of arrayIndexes(this)){if(groupStart===-1){groupStart=i;}
groupEnd=i;if(++count===bucketSize){ranges.push([groupStart,groupEnd,count]);count=0;groupStart=-1;}}
if(count>0){ranges.push([groupStart,groupEnd,count]);}}
return{ranges:ranges,skipGetOwnPropertyNames:skipGetOwnPropertyNames};}
async function callback(result){if(!result){return;}
const ranges=(result.ranges);if(ranges.length===1){await ArrayGroupingTreeElement._populateAsFragment(treeNode,object,ranges[0][0],ranges[0][1],linkifier);}else{for(let i=0;i<ranges.length;++i){const fromIndex=ranges[i][0];const toIndex=ranges[i][1];const count=ranges[i][2];if(fromIndex===toIndex){await ArrayGroupingTreeElement._populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier);}else{treeNode.appendChild(new ArrayGroupingTreeElement(object,fromIndex,toIndex,count,linkifier));}}}
if(topLevel){await ArrayGroupingTreeElement._populateNonIndexProperties(treeNode,object,result.skipGetOwnPropertyNames,linkifier);}}}
static async _populateAsFragment(treeNode,object,fromIndex,toIndex,linkifier){const result=await object.callFunction(buildArrayFragment,[{value:fromIndex},{value:toIndex},{value:ArrayGroupingTreeElement._sparseIterationThreshold}]);if(!result.object||result.wasThrown){return;}
const arrayFragment=result.object;const allProperties=await arrayFragment.getAllProperties(false,true);arrayFragment.release();const properties=allProperties.properties;if(!properties){return;}
properties.sort(ObjectPropertiesSection.CompareProperties);for(let i=0;i<properties.length;++i){properties[i].parentObject=this._object;const childTreeElement=new ObjectPropertyTreeElement(properties[i],linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}
function buildArrayFragment(fromIndex,toIndex,sparseIterationThreshold){const result=Object.create(null);if(toIndex-fromIndex<sparseIterationThreshold){for(let i=fromIndex;i<=toIndex;++i){if(i in this){result[i]=this[i];}}}else{const ownPropertyNames=Object.getOwnPropertyNames(this);for(let i=0;i<ownPropertyNames.length;++i){const name=ownPropertyNames[i];const index=name>>>0;if(String(index)===name&&fromIndex<=index&&index<=toIndex){result[index]=this[index];}}}
return result;}}
static async _populateNonIndexProperties(treeNode,object,skipGetOwnPropertyNames,linkifier){const result=await object.callFunction(buildObjectFragment,[{value:skipGetOwnPropertyNames}]);if(!result.object||result.wasThrown){return;}
const allProperties=await result.object.getOwnProperties(true);result.object.release();if(!allProperties.properties){return;}
const properties=allProperties.properties;properties.sort(ObjectPropertiesSection.CompareProperties);for(const property of properties){property.parentObject=this._object;if(!ObjectPropertiesSection._isDisplayableProperty(property,treeNode.property)){continue;}
const childTreeElement=new ObjectPropertyTreeElement(property,linkifier);childTreeElement._readOnly=true;treeNode.appendChild(childTreeElement);}
function buildObjectFragment(skipGetOwnPropertyNames){const result={__proto__:this.__proto__};if(skipGetOwnPropertyNames){return result;}
const names=Object.getOwnPropertyNames(this);for(let i=0;i<names.length;++i){const name=names[i];if(String(name>>>0)===name&&name>>>0!==0xffffffff){continue;}
const descriptor=Object.getOwnPropertyDescriptor(this,name);if(descriptor){Object.defineProperty(result,name,descriptor);}}
return result;}}
async onpopulate(){if(this._propertyCount>=ArrayGroupingTreeElement._bucketThreshold){await ArrayGroupingTreeElement._populateRanges(this,this._object,this._fromIndex,this._toIndex,false,this._linkifier);return;}
await ArrayGroupingTreeElement._populateAsFragment(this,this._object,this._fromIndex,this._toIndex,this._linkifier);}
onattach(){this.listItemElement.classList.add('object-properties-section-name');}}
ArrayGroupingTreeElement._bucketThreshold=100;ArrayGroupingTreeElement._sparseIterationThreshold=250000;ArrayGroupingTreeElement._getOwnPropertyNamesThreshold=500000;class ObjectPropertyPrompt extends TextPrompt.TextPrompt{constructor(){super();this.initialize(ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext.bind(ObjectUI.javaScriptAutocomplete));}}
class ObjectPropertiesSectionsTreeExpandController{constructor(treeOutline){this._expandedProperties=new Set();treeOutline.addEventListener(TreeOutline.Events.ElementAttached,this._elementAttached,this);treeOutline.addEventListener(TreeOutline.Events.ElementExpanded,this._elementExpanded,this);treeOutline.addEventListener(TreeOutline.Events.ElementCollapsed,this._elementCollapsed,this);}
watchSection(id,section){section[ObjectPropertiesSectionsTreeExpandController._treeOutlineId]=id;if(this._expandedProperties.has(id)){section.expand();}}
stopWatchSectionsWithId(id){for(const property of this._expandedProperties){if(property.startsWith(id+':')){this._expandedProperties.delete(property);}}}
_elementAttached(event){const element=(event.data);if(element.isExpandable()&&this._expandedProperties.has(this._propertyPath(element))){element.expand();}}
_elementExpanded(event){const element=(event.data);this._expandedProperties.add(this._propertyPath(element));}
_elementCollapsed(event){const element=(event.data);this._expandedProperties.delete(this._propertyPath(element));}
_propertyPath(treeElement){const cachedPropertyPath=treeElement[ObjectPropertiesSectionsTreeExpandController._cachedPathSymbol];if(cachedPropertyPath){return cachedPropertyPath;}
let current=treeElement;let sectionRoot=current;const rootElement=treeElement.treeOutline.rootElement();let result;while(current!==rootElement){let currentName='';if(current.property){currentName=current.property.name;}else{currentName=typeof current.title==='string'?current.title:current.title.textContent;}
result=currentName+(result?'.'+result:'');sectionRoot=current;current=current.parent;}
const treeOutlineId=sectionRoot[ObjectPropertiesSectionsTreeExpandController._treeOutlineId];result=treeOutlineId+(result?':'+result:'');treeElement[ObjectPropertiesSectionsTreeExpandController._cachedPathSymbol]=result;return result;}}
ObjectPropertiesSectionsTreeExpandController._cachedPathSymbol=Symbol('cachedPath');ObjectPropertiesSectionsTreeExpandController._treeOutlineId=Symbol('treeOutlineId');class Renderer{render(object,options){if(!(object instanceof RemoteObject.RemoteObject)){return Promise.reject(new Error('Can\'t render '+object));}
options=options||{};const title=options.title;const section=new ObjectPropertiesSection(object,title);if(!title){section.titleLessMode();}
section.editable=!!options.editable;return Promise.resolve(({node:section.element,tree:section}));}}
class ObjectPropertyValue{constructor(element){this.element=element;}
appendApplicableItems(event,contextMenu,object){}}
class ExpandableTextPropertyValue extends ObjectPropertyValue{constructor(element,text,maxLength){super(element);const container=element.createChild('span');this._text=text;this._maxLength=maxLength;container.textContent=text.slice(0,maxLength);container.title=`${text.slice(0, maxLength)}…`;this._expandElement=container.createChild('span');this._maxDisplayableTextLength=10000000;const byteCount=StringUtilities.countWtf8Bytes(text);const totalBytesText=NumberUtilities.bytesToString(byteCount);if(this._text.length<this._maxDisplayableTextLength){this._expandElementText=ls`Show more (${totalBytesText})`;this._expandElement.setAttribute('data-text',this._expandElementText);this._expandElement.classList.add('expandable-inline-button');this._expandElement.addEventListener('click',this._expandText.bind(this));this._expandElement.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){this._expandText();}});ARIAUtils.markAsButton(this._expandElement);}else{this._expandElement.setAttribute('data-text',ls`long text was truncated (${totalBytesText})`);this._expandElement.classList.add('undisplayable-text');}
this._copyButtonText=ls`Copy`;const copyButton=container.createChild('span','expandable-inline-button');copyButton.setAttribute('data-text',this._copyButtonText);copyButton.addEventListener('click',this._copyText.bind(this));copyButton.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){this._copyText();}});ARIAUtils.markAsButton(copyButton);}
appendApplicableItems(event,contextMenu,object){if(this._text.length<this._maxDisplayableTextLength&&this._expandElement){contextMenu.clipboardSection().appendItem(this._expandElementText,this._expandText.bind(this));}
contextMenu.clipboardSection().appendItem(this._copyButtonText,this._copyText.bind(this));}
_expandText(){if(!this._expandElement){return;}
if(this._expandElement.parentElement){this._expandElement.parentElement.insertBefore(createTextNode(this._text.slice(this._maxLength)),this._expandElement);}
this._expandElement.remove();this._expandElement=null;}
_copyText(){InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this._text);}}
let TreeOutlineOptions;var ObjectPropertiesSection$1=Object.freeze({__proto__:null,ObjectPropertiesSection:ObjectPropertiesSection,maxRenderableStringLength:maxRenderableStringLength,ObjectPropertiesSectionsTreeOutline:ObjectPropertiesSectionsTreeOutline,RootElement:RootElement,ObjectPropertyTreeElement:ObjectPropertyTreeElement,ArrayGroupingTreeElement:ArrayGroupingTreeElement,ObjectPropertyPrompt:ObjectPropertyPrompt,ObjectPropertiesSectionsTreeExpandController:ObjectPropertiesSectionsTreeExpandController,Renderer:Renderer,ObjectPropertyValue:ObjectPropertyValue,ExpandableTextPropertyValue:ExpandableTextPropertyValue,TreeOutlineOptions:TreeOutlineOptions});class CustomPreviewSection{constructor(object){this._sectionElement=document.createElement('span');this._sectionElement.classList.add('custom-expandable-section');this._object=object;this._expanded=false;this._cachedContent=null;const customPreview=object.customPreview();let headerJSON;try{headerJSON=JSON.parse(customPreview.header);}catch(e){Console.Console.instance().error('Broken formatter: header is invalid json '+e);return;}
this._header=this._renderJSONMLTag(headerJSON);if(this._header.nodeType===Node.TEXT_NODE){Console.Console.instance().error('Broken formatter: header should be an element node.');return;}
if(customPreview.hasBody||customPreview.bodyGetterId){this._header.classList.add('custom-expandable-section-header');this._header.addEventListener('click',this._onClick.bind(this),false);this._expandIcon=Icon.Icon.create('smallicon-triangle-right','custom-expand-icon');this._header.insertBefore(this._expandIcon,this._header.firstChild);}
this._sectionElement.appendChild(this._header);}
element(){return this._sectionElement;}
_renderJSONMLTag(jsonML){if(!Array.isArray(jsonML)){return createTextNode(jsonML+'');}
const array=(jsonML);return array[0]==='object'?this._layoutObjectTag(array):this._renderElement(array);}
_renderElement(object){const tagName=object.shift();if(!CustomPreviewSection._tagsWhiteList.has(tagName)){Console.Console.instance().error('Broken formatter: element '+tagName+' is not allowed!');return createElement('span');}
const element=createElement((tagName));if((typeof object[0]==='object')&&!Array.isArray(object[0])){const attributes=object.shift();for(const key in attributes){const value=attributes[key];if((key!=='style')||(typeof value!=='string')){continue;}
element.setAttribute(key,value);}}
this._appendJsonMLTags(element,object);return element;}
_layoutObjectTag(objectTag){objectTag.shift();const attributes=objectTag.shift();const remoteObject=this._object.runtimeModel().createRemoteObject((attributes));if(remoteObject.customPreview()){return(new CustomPreviewSection(remoteObject)).element();}
const sectionElement=ObjectPropertiesSection.defaultObjectPresentation(remoteObject);sectionElement.classList.toggle('custom-expandable-section-standard-section',remoteObject.hasChildren);return sectionElement;}
_appendJsonMLTags(parentElement,jsonMLTags){for(let i=0;i<jsonMLTags.length;++i){parentElement.appendChild(this._renderJSONMLTag(jsonMLTags[i]));}}
_onClick(event){event.consume(true);if(this._cachedContent){this._toggleExpand();}else{this._loadBody();}}
_toggleExpand(){this._expanded=!this._expanded;this._header.classList.toggle('expanded',this._expanded);this._cachedContent.classList.toggle('hidden',!this._expanded);if(this._expanded){this._expandIcon.setIconType('smallicon-triangle-down');}else{this._expandIcon.setIconType('smallicon-triangle-right');}}
_loadBody(){function load(bindRemoteObject,formatter,config){function substituteObjectTagsInCustomPreview(jsonMLObject){if(!jsonMLObject||(typeof jsonMLObject!=='object')||(typeof jsonMLObject.splice!=='function')){return;}
const obj=jsonMLObject.length;if(!(typeof obj==='number'&&obj>>>0===obj&&(obj>0||1/obj>0))){return;}
let startIndex=1;if(jsonMLObject[0]==='object'){const attributes=jsonMLObject[1];const originObject=attributes['object'];const config=attributes['config'];if(typeof originObject==='undefined'){throw'Illegal format: obligatory attribute "object" isn\'t specified';}
jsonMLObject[1]=bindRemoteObject(originObject,config);startIndex=2;}
for(let i=startIndex;i<jsonMLObject.length;++i){substituteObjectTagsInCustomPreview(jsonMLObject[i]);}}
try{const body=formatter.body(this,config);substituteObjectTagsInCustomPreview(body);return body;}catch(e){console.error('Custom Formatter Failed: '+e);return null;}}
const customPreview=this._object.customPreview();if(customPreview.bindRemoteObjectFunctionId&&customPreview.formatterObjectId){const args=[{objectId:customPreview.bindRemoteObjectFunctionId},{objectId:customPreview.formatterObjectId}];if(customPreview.configObjectId){args.push({objectId:customPreview.configObjectId});}
this._object.callFunctionJSON(load,args).then(onBodyLoaded.bind(this));}else if(customPreview.bodyGetterId){this._object.callFunctionJSON(bodyGetter=>bodyGetter(),[{objectId:customPreview.bodyGetterId}]).then(onBodyLoaded.bind(this));}
function onBodyLoaded(bodyJsonML){if(!bodyJsonML){return;}
this._cachedContent=this._renderJSONMLTag(bodyJsonML);this._sectionElement.appendChild(this._cachedContent);this._toggleExpand();}}}
class CustomPreviewComponent{constructor(object){this._object=object;this._customPreviewSection=new CustomPreviewSection(object);this.element=document.createElement('span');this.element.classList.add('source-code');const shadowRoot=Utils.createShadowRootWithCoreStyles(this.element,'object_ui/customPreviewComponent.css');this.element.addEventListener('contextmenu',this._contextMenuEventFired.bind(this),false);shadowRoot.appendChild(this._customPreviewSection.element());}
expandIfPossible(){if((this._object.customPreview().hasBody||this._object.customPreview().bodyGetterId)&&this._customPreviewSection){this._customPreviewSection._loadBody();}}
_contextMenuEventFired(event){const contextMenu=new ContextMenu.ContextMenu(event);if(this._customPreviewSection){contextMenu.revealSection().appendItem(UIString.UIString('Show as JavaScript object'),this._disassemble.bind(this));}
contextMenu.appendApplicableItems(this._object);contextMenu.show();}
_disassemble(){this.element.shadowRoot.textContent='';this._customPreviewSection=null;this.element.shadowRoot.appendChild(ObjectPropertiesSection.defaultObjectPresentation(this._object));}}
CustomPreviewSection._tagsWhiteList=new Set(['span','div','ol','li','table','tr','td']);var CustomPreviewComponent$1=Object.freeze({__proto__:null,CustomPreviewSection:CustomPreviewSection,CustomPreviewComponent:CustomPreviewComponent});const DEFAULT_TIMEOUT=500;class JavaScriptAutocomplete{constructor(){this._expressionCache=new Map();ConsoleModel.ConsoleModel.instance().addEventListener(ConsoleModel.Events.CommandEvaluated,this._clearCache,this);self.UI.context.addFlavorChangeListener(RuntimeModel.ExecutionContext,this._clearCache,this);SDKModel.TargetManager.instance().addModelListener(DebuggerModel.DebuggerModel,DebuggerModel.Events.DebuggerResumed,this._clearCache,this);SDKModel.TargetManager.instance().addModelListener(DebuggerModel.DebuggerModel,DebuggerModel.Events.DebuggerPaused,this._clearCache,this);}
_clearCache(){this._expressionCache.clear();}
async completionsForTextInCurrentContext(fullText,query,force){const trimmedText=fullText.trim();const[mapCompletions,expressionCompletions]=await Promise.all([this._mapCompletions(trimmedText,query),this._completionsForExpression(trimmedText,query,force)]);return mapCompletions.concat(expressionCompletions);}
async argumentsHint(fullText){const functionCall=await FormatterWorkerPool.formatterWorkerPool().findLastFunctionCall(fullText);if(!functionCall){return null;}
const executionContext=self.UI.context.flavor(RuntimeModel.ExecutionContext);if(!executionContext){return null;}
const result=await executionContext.evaluate({expression:functionCall.baseExpression,objectGroup:'argumentsHint',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:true,timeout:DEFAULT_TIMEOUT},false,false);if(!result||result.exceptionDetails||!result.object||result.object.type!=='function'){executionContext.runtimeModel.releaseObjectGroup('argumentsHint');return null;}
const args=await this._argumentsForFunction(result.object,async()=>{const result=await executionContext.evaluate({expression:functionCall.receiver,objectGroup:'argumentsHint',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:true,timeout:DEFAULT_TIMEOUT},false,false);return(result&&!result.exceptionDetails&&result.object)?result.object:null;},functionCall.functionName);executionContext.runtimeModel.releaseObjectGroup('argumentsHint');if(!args.length||(args.length===1&&!args[0].length)){return null;}
return{args,argumentIndex:functionCall.argumentIndex};}
async _argumentsForFunction(functionObject,receiverObjGetter,parsedFunctionName){const description=functionObject.description;if(!description.endsWith('{ [native code] }')){return[await FormatterWorkerPool.formatterWorkerPool().argumentsList(description)];}
if(description==='function () { [native code] }'){const properties=await functionObject.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const targetProperty=internalProperties.find(property=>property.name==='[[TargetFunction]]');const argsProperty=internalProperties.find(property=>property.name==='[[BoundArgs]]');const thisProperty=internalProperties.find(property=>property.name==='[[BoundThis]]');if(thisProperty&&targetProperty&&argsProperty){const originalSignatures=await this._argumentsForFunction(targetProperty.value,()=>Promise.resolve(thisProperty.value));const boundArgsLength=RemoteObject.RemoteObject.arrayLength(argsProperty.value);const clippedArgs=[];for(const signature of originalSignatures){const restIndex=signature.slice(0,boundArgsLength).findIndex(arg=>arg.startsWith('...'));if(restIndex!==-1){clippedArgs.push(signature.slice(restIndex));}else{clippedArgs.push(signature.slice(boundArgsLength));}}
return clippedArgs;}}
const javaScriptMetadata=await self.runtime.extension(JavaScriptMetaData.JavaScriptMetaData).instance();const name=/^function ([^(]*)\(/.exec(description)[1]||parsedFunctionName;if(!name){return[];}
const uniqueSignatures=javaScriptMetadata.signaturesForNativeFunction(name);if(uniqueSignatures){return uniqueSignatures;}
const receiverObj=await receiverObjGetter();const className=receiverObj.className;if(javaScriptMetadata.signaturesForInstanceMethod(name,className)){return javaScriptMetadata.signaturesForInstanceMethod(name,className);}
if(receiverObj.type==='function'&&receiverObj.description.endsWith('{ [native code] }')){const receiverName=/^function ([^(]*)\(/.exec(receiverObj.description)[1];const staticSignatures=javaScriptMetadata.signaturesForStaticMethod(name,receiverName);if(staticSignatures){return staticSignatures;}}
let protoNames;if(receiverObj.type==='number'){protoNames=['Number','Object'];}else if(receiverObj.type==='string'){protoNames=['String','Object'];}else if(receiverObj.type==='symbol'){protoNames=['Symbol','Object'];}else if(receiverObj.type==='bigint'){protoNames=['BigInt','Object'];}else if(receiverObj.type==='boolean'){protoNames=['Boolean','Object'];}else if(receiverObj.type==='undefined'||receiverObj.subtype==='null'){protoNames=[];}else{protoNames=await receiverObj.callFunctionJSON(function(){const result=[];for(let object=this;object;object=Object.getPrototypeOf(object)){if(typeof object==='object'&&object.constructor&&object.constructor.name){result[result.length]=object.constructor.name;}}
return result;},[]);}
if(!protoNames){return[];}
for(const proto of protoNames){const instanceSignatures=javaScriptMetadata.signaturesForInstanceMethod(name,proto);if(instanceSignatures){return instanceSignatures;}}
return[];}
async _mapCompletions(text,query){const mapMatch=text.match(/\.\s*(get|set|delete)\s*\(\s*$/);const executionContext=self.UI.context.flavor(RuntimeModel.ExecutionContext);if(!executionContext||!mapMatch){return[];}
const expression=await FormatterWorkerPool.formatterWorkerPool().findLastExpression(text.substring(0,mapMatch.index));if(!expression){return[];}
const result=await executionContext.evaluate({expression,objectGroup:'mapCompletion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:true,timeout:DEFAULT_TIMEOUT,},false,false);if(result.error||!!result.exceptionDetails||result.object.subtype!=='map'){return[];}
const properties=await result.object.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const entriesProperty=internalProperties.find(property=>property.name==='[[Entries]]');if(!entriesProperty){return[];}
const keysObj=await entriesProperty.value.callFunctionJSON(getEntries);executionContext.runtimeModel.releaseObjectGroup('mapCompletion');return gotKeys(Object.keys(keysObj));function getEntries(){const result={__proto__:null};for(let i=0;i<this.length;i++){if(typeof this[i].key==='string'){result[this[i].key]=true;}}
return result;}
function gotKeys(rawKeys){const caseSensitivePrefix=[];const caseInsensitivePrefix=[];const caseSensitiveAnywhere=[];const caseInsensitiveAnywhere=[];let quoteChar='"';if(query.startsWith('\'')){quoteChar='\'';}
let endChar=')';if(mapMatch[0].indexOf('set')!==-1){endChar=', ';}
const sorter=rawKeys.length<1000?String.naturalOrderComparator:undefined;const keys=rawKeys.sort(sorter).map(key=>quoteChar+key+quoteChar);for(const key of keys){if(key.length<query.length){continue;}
if(query.length&&key.toLowerCase().indexOf(query.toLowerCase())===-1){continue;}
const title=key.split('\n').join('\\n');const text=title+endChar;if(key.startsWith(query)){caseSensitivePrefix.push({text:text,title:title,priority:4});}else if(key.toLowerCase().startsWith(query.toLowerCase())){caseInsensitivePrefix.push({text:text,title:title,priority:3});}else if(key.indexOf(query)!==-1){caseSensitiveAnywhere.push({text:text,title:title,priority:2});}else{caseInsensitiveAnywhere.push({text:text,title:title,priority:1});}}
const suggestions=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(suggestions.length){suggestions[0].subtitle=UIString.UIString('Keys');}
return suggestions;}}
async _completionsForExpression(fullText,query,force){const executionContext=self.UI.context.flavor(RuntimeModel.ExecutionContext);if(!executionContext){return[];}
let expression;if(fullText.endsWith('.')||fullText.endsWith('[')){expression=await FormatterWorkerPool.formatterWorkerPool().findLastExpression(fullText.substring(0,fullText.length-1));}
if(!expression){if(fullText.endsWith('.')){return[];}
expression='';}
const expressionString=expression;const dotNotation=fullText.endsWith('.');const bracketNotation=!!expressionString&&fullText.endsWith('[');if((expressionString&&!isNaN(expressionString))||(!expressionString&&query&&!isNaN(query))){return[];}
if(!query&&!expressionString&&!force){return[];}
const selectedFrame=executionContext.debuggerModel.selectedCallFrame();let completionGroups;const TEN_SECONDS=10000;let cache=this._expressionCache.get(expressionString);if(cache&&cache.date+TEN_SECONDS>Date.now()){completionGroups=await cache.value;}else if(!expressionString&&selectedFrame){cache={date:Date.now(),value:completionsOnPause(selectedFrame)};this._expressionCache.set(expressionString,cache);completionGroups=await cache.value;}else{const resultPromise=executionContext.evaluate({expression:expressionString,objectGroup:'completion',includeCommandLineAPI:true,silent:true,returnByValue:false,generatePreview:false,throwOnSideEffect:true,timeout:DEFAULT_TIMEOUT},false,false);cache={date:Date.now(),value:resultPromise.then(result=>completionsOnGlobal.call(this,result))};this._expressionCache.set(expressionString,cache);completionGroups=await cache.value;}
return this._receivedPropertyNames(completionGroups.slice(0),dotNotation,bracketNotation,expressionString,query);async function completionsOnGlobal(result){if(result.error||!!result.exceptionDetails||!result.object){return[];}
let object=result.object;while(object&&object.type==='object'&&object.subtype==='proxy'){const properties=await object.getOwnProperties(false);const internalProperties=properties.internalProperties||[];const target=internalProperties.find(property=>property.name==='[[Target]]');object=target?target.value:null;}
if(!object){return[];}
let completions=[];if(object.type==='object'||object.type==='function'){completions=await object.callFunctionJSON(getCompletions,[RemoteObject.RemoteObject.toCallArgument(object.subtype)])||[];}else if(object.type==='string'||object.type==='number'||object.type==='boolean'||object.type==='bigint'){const evaluateResult=await executionContext.evaluate({expression:'('+getCompletions+')("'+object.type+'")',objectGroup:'completion',includeCommandLineAPI:false,silent:true,returnByValue:true,generatePreview:false},false,false);if(evaluateResult.object&&!evaluateResult.exceptionDetails){completions=(evaluateResult.object.value)||[];}}
executionContext.runtimeModel.releaseObjectGroup('completion');if(!expressionString){const globalNames=await executionContext.globalLexicalScopeNames();if(completions.length){completions[0].items=completions[0].items.concat(globalNames);}else{completions.push({items:globalNames.sort(),title:UIString.UIString('Lexical scope variables')});}}
for(const group of completions){for(let i=0;i<group.items.length;i++){group.items[i]=group.items[i].replace(/\n/g,'\\n');}
group.items.sort(group.items.length<1000?this._itemComparator:undefined);}
return completions;function getCompletions(type){let object;if(type==='string'){object=new String('');}else if(type==='number'){object=new Number(0);}
else if(type==='bigint'){object=Object(BigInt(0));}else if(type==='boolean'){object=new Boolean(false);}else{object=this;}
const result=[];try{for(let o=object;o;o=Object.getPrototypeOf(o)){if((type==='array'||type==='typedarray')&&o===object&&o.length>9999){continue;}
const group={items:[],__proto__:null};try{if(typeof o==='object'&&Object.prototype.hasOwnProperty.call(o,'constructor')&&o.constructor&&o.constructor.name){group.title=o.constructor.name;}}catch(ee){}
result[result.length]=group;const names=Object.getOwnPropertyNames(o);const isArray=Array.isArray(o);for(let i=0;i<names.length&&group.items.length<10000;++i){if(isArray&&/^[0-9]/.test(names[i])){continue;}
group.items[group.items.length]=names[i];}}}catch(e){}
return result;}}
async function completionsOnPause(callFrame){const result=[{items:['this']}];const scopeChain=callFrame.scopeChain();const groupPromises=[];for(const scope of scopeChain){groupPromises.push(scope.object().getAllProperties(false,false).then(result=>({properties:result.properties,name:scope.name()})));}
const fullScopes=await Promise.all(groupPromises);executionContext.runtimeModel.releaseObjectGroup('completion');for(const scope of fullScopes){result.push({title:scope.name,items:scope.properties.map(property=>property.name).sort()});}
return result;}}
_receivedPropertyNames(propertyGroups,dotNotation,bracketNotation,expressionString,query){if(!propertyGroups){return[];}
const includeCommandLineAPI=(!dotNotation&&!bracketNotation);if(includeCommandLineAPI){const commandLineAPI=['dir','dirxml','keys','values','profile','profileEnd','monitorEvents','unmonitorEvents','inspect','copy','clear','getEventListeners','debug','undebug','monitor','unmonitor','table','queryObjects','$','$$','$x','$0','$_'];propertyGroups.push({items:commandLineAPI});}
return this._completionsForQuery(dotNotation,bracketNotation,expressionString,query,propertyGroups);}
_completionsForQuery(dotNotation,bracketNotation,expressionString,query,propertyGroups){const quoteUsed=(bracketNotation&&query.startsWith('\''))?'\'':'"';if(!expressionString){const keywords=['await','break','case','catch','class','const','continue','debugger','default','delete','do','else','exports','extends','finally','for','function','if','import','in','instanceof','new','return','super','switch','this','throw','try','typeof','var','void','while','with','yield','let','static','async','of'];propertyGroups.push({title:ls`keywords`,items:keywords.sort()});}
const allProperties=new Set();let result=[];let lastGroupTitle;const regex=/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/;const lowerCaseQuery=query.toLowerCase();for(const group of propertyGroups){const caseSensitivePrefix=[];const caseInsensitivePrefix=[];const caseSensitiveAnywhere=[];const caseInsensitiveAnywhere=[];for(let i=0;i<group.items.length;i++){let property=group.items[i];if(!bracketNotation&&!regex.test(property)){continue;}
if(bracketNotation){if(!/^[0-9]+$/.test(property)){property=quoteUsed+StringUtilities.escapeCharacters(property,quoteUsed+'\\')+quoteUsed;}
property+=']';}
if(allProperties.has(property)){continue;}
if(property.length<query.length){continue;}
const lowerCaseProperty=property.toLowerCase();if(query.length&&lowerCaseProperty.indexOf(lowerCaseQuery)===-1){continue;}
allProperties.add(property);if(property.startsWith(query)){caseSensitivePrefix.push({text:property,priority:property===query?5:4});}else if(lowerCaseProperty.startsWith(lowerCaseQuery)){caseInsensitivePrefix.push({text:property,priority:3});}else if(property.indexOf(query)!==-1){caseSensitiveAnywhere.push({text:property,priority:2});}else{caseInsensitiveAnywhere.push({text:property,priority:1});}}
const structuredGroup=caseSensitivePrefix.concat(caseInsensitivePrefix,caseSensitiveAnywhere,caseInsensitiveAnywhere);if(structuredGroup.length&&group.title!==lastGroupTitle){structuredGroup[0].subtitle=group.title;lastGroupTitle=group.title;}
result=result.concat(structuredGroup);result.forEach(item=>{if(item.text.endsWith(']')){item.title=item.text.substring(0,item.text.length-1);}});}
return result;}
_itemComparator(a,b){const aStartsWithUnderscore=a.startsWith('_');const bStartsWithUnderscore=b.startsWith('_');if(aStartsWithUnderscore&&!bStartsWithUnderscore){return 1;}
if(bStartsWithUnderscore&&!aStartsWithUnderscore){return-1;}
return String.naturalOrderComparator(a,b);}
static async isExpressionComplete(expression){const currentExecutionContext=self.UI.context.flavor(RuntimeModel.ExecutionContext);if(!currentExecutionContext){return true;}
const result=await currentExecutionContext.runtimeModel.compileScript(expression,'',false,currentExecutionContext.id);if(!result||!result.exceptionDetails){return true;}
const description=result.exceptionDetails.exception.description;return!description.startsWith('SyntaxError: Unexpected end of input')&&!description.startsWith('SyntaxError: Unterminated template literal');}}
class JavaScriptAutocompleteConfig{constructor(editor){this._editor=editor;}
static createConfigForEditor(editor){const autocomplete=new JavaScriptAutocompleteConfig(editor);return{substituteRangeCallback:autocomplete._substituteRange.bind(autocomplete),suggestionsCallback:autocomplete._suggestionsCallback.bind(autocomplete),tooltipCallback:autocomplete._tooltipCallback.bind(autocomplete),};}
_substituteRange(lineNumber,columnNumber){const token=this._editor.tokenAtTextPosition(lineNumber,columnNumber);if(token&&token.type==='js-string'){return new TextRange.TextRange(lineNumber,token.startColumn,lineNumber,columnNumber);}
const lineText=this._editor.line(lineNumber);let index;for(index=columnNumber-1;index>=0;index--){if(' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index))!==-1){break;}}
return new TextRange.TextRange(lineNumber,index+1,lineNumber,columnNumber);}
async _suggestionsCallback(queryRange,substituteRange,force){const query=this._editor.text(queryRange);const before=this._editor.text(new TextRange.TextRange(0,0,queryRange.startLine,queryRange.startColumn));const token=this._editor.tokenAtTextPosition(substituteRange.startLine,substituteRange.startColumn);if(token){const excludedTokens=new Set(['js-comment','js-string-2','js-def']);const trimmedBefore=before.trim();if(!trimmedBefore.endsWith('[')&&!trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/)){excludedTokens.add('js-string');}
if(!trimmedBefore.endsWith('.')){excludedTokens.add('js-property');}
if(excludedTokens.has(token.type)){return[];}}
const queryAndAfter=this._editor.line(queryRange.startLine).substring(queryRange.startColumn);const words=await ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext(before,query,force);if(!force&&queryAndAfter&&queryAndAfter!==query&&words.some(word=>queryAndAfter.startsWith(word.text)&&query.length!==word.text.length)){return[];}
return words;}
async _tooltipCallback(lineNumber,columnNumber){const before=this._editor.text(new TextRange.TextRange(0,0,lineNumber,columnNumber));const result=await ObjectUI.javaScriptAutocomplete.argumentsHint(before);if(!result){return null;}
const argumentIndex=result.argumentIndex;const tooltip=createElement('div');for(const args of result.args){const argumentsElement=createElement('span');for(let i=0;i<args.length;i++){if(i===argumentIndex||(i<argumentIndex&&args[i].startsWith('...'))){argumentsElement.appendChild(Fragment.html`<b>${args[i]}</b>`);}else{argumentsElement.createTextChild(args[i]);}
if(i<args.length-1){argumentsElement.createTextChild(', ');}}
tooltip.appendChild(Fragment.html`<div class='source-code'>\u0192(${argumentsElement})</div>`);}
return tooltip;}}
let CompletionGroup;var JavaScriptAutocomplete$1=Object.freeze({__proto__:null,JavaScriptAutocomplete:JavaScriptAutocomplete,JavaScriptAutocompleteConfig:JavaScriptAutocompleteConfig,CompletionGroup:CompletionGroup});class ObjectPopoverHelper{constructor(linkifier,resultHighlightedAsDOM){this._linkifier=linkifier;this._resultHighlightedAsDOM=resultHighlightedAsDOM;}
dispose(){if(this._resultHighlightedAsDOM){OverlayModel.OverlayModel.hideDOMNodeHighlight();}
if(this._linkifier){this._linkifier.dispose();}}
static async buildObjectPopover(result,popover){const description=result.description.trimEndWithMaxLength(MaxPopoverTextLength);let popoverContentElement=null;if(result.type==='object'){let linkifier=null;let resultHighlightedAsDOM=false;if(result.subtype==='node'){OverlayModel.OverlayModel.highlightObjectAsDOMNode(result);resultHighlightedAsDOM=true;}
if(result.customPreview()){const customPreviewComponent=new CustomPreviewComponent(result);customPreviewComponent.expandIfPossible();popoverContentElement=customPreviewComponent.element;}else{popoverContentElement=document.createElement('div');popoverContentElement.classList.add('object-popover-content');Utils.appendStyle(popoverContentElement,'object_ui/objectPopover.css');const titleElement=popoverContentElement.createChild('div','monospace object-popover-title');titleElement.createChild('span').textContent=description;linkifier=new Linkifier.Linkifier();const section=new ObjectPropertiesSection(result,'',linkifier,undefined,undefined,undefined,true);section.element.classList.add('object-popover-tree');section.titleLessMode();popoverContentElement.appendChild(section.element);}
popover.setMaxContentSize(new Geometry.Size(300,250));popover.setSizeBehavior(GlassPane.SizeBehavior.SetExactSize);popover.contentElement.appendChild(popoverContentElement);return new ObjectPopoverHelper(linkifier,resultHighlightedAsDOM);}
popoverContentElement=createElement('span');Utils.appendStyle(popoverContentElement,'object_ui/objectValue.css');Utils.appendStyle(popoverContentElement,'object_ui/objectPopover.css');const valueElement=popoverContentElement.createChild('span','monospace object-value-'+result.type);valueElement.style.whiteSpace='pre';if(result.type==='string'){valueElement.createTextChildren(`"${description}"`);}else if(result.type!=='function'){valueElement.textContent=description;}
if(result.type!=='function'){popover.contentElement.appendChild(popoverContentElement);return new ObjectPopoverHelper(null,false);}
ObjectPropertiesSection.formatObjectAsFunction(result,valueElement,true);const response=await result.debuggerModel().functionDetailsPromise(result);if(!response){return null;}
const container=document.createElement('div');container.classList.add('object-popover-container');const title=container.createChild('div','function-popover-title source-code');const functionName=title.createChild('span','function-name');functionName.textContent=UIUtils.beautifyFunctionName(response.functionName);const rawLocation=response.location;const linkContainer=title.createChild('div','function-title-link-container');const sourceURL=rawLocation&&rawLocation.script()&&rawLocation.script().sourceURL;let linkifier=null;if(sourceURL){linkifier=new Linkifier.Linkifier();linkContainer.appendChild(linkifier.linkifyRawLocation((rawLocation),sourceURL));}
container.appendChild(popoverContentElement);popover.contentElement.appendChild(container);return new ObjectPopoverHelper(linkifier,false);}}
const MaxPopoverTextLength=10000;var ObjectPopoverHelper$1=Object.freeze({__proto__:null,ObjectPopoverHelper:ObjectPopoverHelper});const javaScriptAutocomplete=new JavaScriptAutocomplete();export{CustomPreviewComponent$1 as CustomPreviewComponent,JavaScriptAutocomplete$1 as JavaScriptAutocomplete,JavaScriptREPL$1 as JavaScriptREPL,ObjectPopoverHelper$1 as ObjectPopoverHelper,ObjectPropertiesSection$1 as ObjectPropertiesSection,RemoteObjectPreviewFormatter$1 as RemoteObjectPreviewFormatter,javaScriptAutocomplete};