import{UIString,Settings,Throttler,EventTarget,ParsedURL,Color,ObjectWrapper,ResourceType,Console}from'../common/common.js';import{DataGrid,SortableDataGrid}from'../data_grid/data_grid.js';import{NumberUtilities,StringUtilities,ArrayUtilities}from'../platform/platform.js';import{View,Toolbar,EmptyWidget,Widget,ReportView,UIUtils,XLink,SplitWidget,ThrottledWidget,SettingsUI,Icon,TextPrompt,ARIAUtils,TabbedPane,Utils,TreeOutline,ContextMenu,Panel,ViewManager}from'../ui/ui.js';import{SDKModel,ResourceTreeModel,ServiceWorkerManager,SecurityOriginManager,RuntimeModel,CookieModel,ServiceWorkerCacheModel,NetworkRequest,OverlayModel,NetworkManager,Cookie,Resource}from'../sdk/sdk.js';import{InspectorFrontendHost}from'../host/host.js';import{PreviewFactory,ResourceSourceFrame,ImageView,FontView}from'../source_frame/source_frame.js';import{Linkifier}from'../components/components.js';import{ColorSwatch}from'../inline_editor/inline_editor.js';import{FileUtils}from'../bindings/bindings.js';import{InspectorBackend}from'../protocol_client/protocol_client.js';import{ObjectPropertiesSection}from'../object_ui/object_ui.js';import{RequestHeadersView,RequestPreviewView}from'../network/network.js';import{ThrottlingManager}from'../mobile_throttling/mobile_throttling.js';import{RelatedIssue}from'../browser_sdk/browser_sdk.js';import{CookiesTable}from'../cookie_table/cookie_table.js';import{Runtime}from'../root/root.js';import{StaticContentProvider}from'../text_utils/text_utils.js';class ApplicationCacheModel extends SDKModel.SDKModel{constructor(target){super(target);target.registerApplicationCacheDispatcher(new ApplicationCacheDispatcher(this));this._agent=target.applicationCacheAgent();this._agent.enable();const resourceTreeModel=target.model(ResourceTreeModel.ResourceTreeModel);resourceTreeModel.addEventListener(ResourceTreeModel.Events.FrameNavigated,event=>{this._frameNavigated(event);},this);resourceTreeModel.addEventListener(ResourceTreeModel.Events.FrameDetached,this._frameDetached,this);this._statuses={};this._manifestURLsByFrame={};this._mainFrameNavigated();this._onLine=true;}
async _frameNavigated(event){const frame=(event.data);if(frame.isMainFrame()){this._mainFrameNavigated();return;}
const frameId=frame.id;const manifestURL=await this._agent.getManifestForFrame(frameId);if(manifestURL!==null&&!manifestURL){this._frameManifestRemoved(frameId);}}
_frameDetached(event){const frame=(event.data);this._frameManifestRemoved(frame.id);}
reset(){this._statuses={};this._manifestURLsByFrame={};this.dispatchEventToListeners(Events.FrameManifestsReset);}
async _mainFrameNavigated(){const framesWithManifests=await this._agent.getFramesWithManifests();for(const frame of framesWithManifests||[]){this._frameManifestUpdated(frame.frameId,frame.manifestURL,frame.status);}}
_frameManifestUpdated(frameId,manifestURL,status){if(status===UNCACHED){this._frameManifestRemoved(frameId);return;}
if(!manifestURL){return;}
if(this._manifestURLsByFrame[frameId]&&manifestURL!==this._manifestURLsByFrame[frameId]){this._frameManifestRemoved(frameId);}
const statusChanged=this._statuses[frameId]!==status;this._statuses[frameId]=status;if(!this._manifestURLsByFrame[frameId]){this._manifestURLsByFrame[frameId]=manifestURL;this.dispatchEventToListeners(Events.FrameManifestAdded,frameId);}
if(statusChanged){this.dispatchEventToListeners(Events.FrameManifestStatusUpdated,frameId);}}
_frameManifestRemoved(frameId){if(!this._manifestURLsByFrame[frameId]){return;}
delete this._manifestURLsByFrame[frameId];delete this._statuses[frameId];this.dispatchEventToListeners(Events.FrameManifestRemoved,frameId);}
frameManifestURL(frameId){return this._manifestURLsByFrame[frameId]||'';}
frameManifestStatus(frameId){return this._statuses[frameId]||UNCACHED;}
get onLine(){return this._onLine;}
_statusUpdated(frameId,manifestURL,status){this._frameManifestUpdated(frameId,manifestURL,status);}
requestApplicationCache(frameId){return this._agent.getApplicationCacheForFrame(frameId);}
_networkStateUpdated(isNowOnline){this._onLine=isNowOnline;this.dispatchEventToListeners(Events.NetworkStateChanged,isNowOnline);}}
SDKModel.SDKModel.register(ApplicationCacheModel,SDKModel.Capability.DOM,false);const Events={FrameManifestStatusUpdated:Symbol('FrameManifestStatusUpdated'),FrameManifestAdded:Symbol('FrameManifestAdded'),FrameManifestRemoved:Symbol('FrameManifestRemoved'),FrameManifestsReset:Symbol('FrameManifestsReset'),NetworkStateChanged:Symbol('NetworkStateChanged')};class ApplicationCacheDispatcher{constructor(applicationCacheModel){this._applicationCacheModel=applicationCacheModel;}
applicationCacheStatusUpdated(frameId,manifestURL,status){this._applicationCacheModel._statusUpdated(frameId,manifestURL,status);}
networkStateUpdated(isNowOnline){this._applicationCacheModel._networkStateUpdated(isNowOnline);}}
const UNCACHED=0;const IDLE=1;const CHECKING=2;const DOWNLOADING=3;const UPDATEREADY=4;const OBSOLETE=5;var ApplicationCacheModel$1=Object.freeze({__proto__:null,ApplicationCacheModel:ApplicationCacheModel,Events:Events,ApplicationCacheDispatcher:ApplicationCacheDispatcher,UNCACHED:UNCACHED,IDLE:IDLE,CHECKING:CHECKING,DOWNLOADING:DOWNLOADING,UPDATEREADY:UPDATEREADY,OBSOLETE:OBSOLETE});class ApplicationCacheItemsView extends View.SimpleView{constructor(model,frameId){super(UIString.UIString('AppCache'));this._model=model;this.element.classList.add('storage-view','table');this._deleteButton=new Toolbar.ToolbarButton(UIString.UIString('Delete'),'largeicon-delete');this._deleteButton.setVisible(false);this._deleteButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._deleteButtonClicked,this);this._connectivityIcon=createElement('span','dt-icon-label');this._connectivityIcon.style.margin='0 2px 0 5px';this._statusIcon=createElement('span','dt-icon-label');this._statusIcon.style.margin='0 2px 0 5px';this._frameId=frameId;this._emptyWidget=new EmptyWidget.EmptyWidget(UIString.UIString('No Application Cache information available.'));this._emptyWidget.show(this.element);this._markDirty();const status=this._model.frameManifestStatus(frameId);this.updateStatus(status);this.updateNetworkState(this._model.onLine);this._deleteButton.element.style.display='none';}
async toolbarItems(){return[this._deleteButton,new Toolbar.ToolbarItem(this._connectivityIcon),new Toolbar.ToolbarSeparator(),new Toolbar.ToolbarItem(this._statusIcon)];}
wasShown(){this._maybeUpdate();}
willHide(){this._deleteButton.setVisible(false);}
_maybeUpdate(){if(!this.isShowing()||!this._viewDirty){return;}
this._update();this._viewDirty=false;}
_markDirty(){this._viewDirty=true;}
updateStatus(status){const oldStatus=this._status;this._status=status;const statusInformation={};statusInformation[UNCACHED]={type:'smallicon-red-ball',text:'UNCACHED'};statusInformation[IDLE]={type:'smallicon-green-ball',text:'IDLE'};statusInformation[CHECKING]={type:'smallicon-orange-ball',text:'CHECKING'};statusInformation[DOWNLOADING]={type:'smallicon-orange-ball',text:'DOWNLOADING'};statusInformation[UPDATEREADY]={type:'smallicon-green-ball',text:'UPDATEREADY'};statusInformation[OBSOLETE]={type:'smallicon-red-ball',text:'OBSOLETE'};const info=statusInformation[status]||statusInformation[UNCACHED];this._statusIcon.type=info.type;this._statusIcon.textContent=info.text;if(this.isShowing()&&this._status===IDLE&&(oldStatus===UPDATEREADY||!this._resources)){this._markDirty();}
this._maybeUpdate();}
updateNetworkState(isNowOnline){if(isNowOnline){this._connectivityIcon.type='smallicon-green-ball';this._connectivityIcon.textContent=UIString.UIString('Online');}else{this._connectivityIcon.type='smallicon-red-ball';this._connectivityIcon.textContent=UIString.UIString('Offline');}}
async _update(){const applicationCache=await this._model.requestApplicationCache(this._frameId);if(!applicationCache||!applicationCache.manifestURL){delete this._manifest;delete this._creationTime;delete this._updateTime;delete this._size;delete this._resources;this._emptyWidget.show(this.element);this._deleteButton.setVisible(false);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._emptyWidget.detach();this._deleteButton.setVisible(true);}
_createDataGrid(){const columns=([{id:'resource',title:UIString.UIString('Resource'),sort:DataGrid.Order.Ascending,sortable:true},{id:'type',title:UIString.UIString('Type'),sortable:true},{id:'size',title:UIString.UIString('Size'),align:DataGrid.Align.Right,sortable:true}]);this._dataGrid=new DataGrid.DataGridImpl({displayName:ls`Application Cache`,columns});this._dataGrid.setStriped(true);this._dataGrid.asWidget().show(this.element);this._dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._populateDataGrid,this);}
_populateDataGrid(){const selectedResource=this._dataGrid.selectedNode?this._dataGrid.selectedNode.resource:null;const sortDirection=this._dataGrid.isSortOrderAscending()?1:-1;function numberCompare(field,resource1,resource2){return sortDirection*(resource1[field]-resource2[field]);}
function localeCompare(field,resource1,resource2){return sortDirection*(resource1[field]+'').localeCompare(resource2[field]+'');}
let comparator;switch(this._dataGrid.sortColumnId()){case'resource':comparator=localeCompare.bind(null,'url');break;case'type':comparator=localeCompare.bind(null,'type');break;case'size':comparator=numberCompare.bind(null,'size');break;default:localeCompare.bind(null,'resource');}
this._resources.sort(comparator);this._dataGrid.rootNode().removeChildren();let nodeToSelect;for(let i=0;i<this._resources.length;++i){const data={};const resource=this._resources[i];data.resource=resource.url;data.type=resource.type;data.size=NumberUtilities.bytesToString(resource.size);const node=new DataGrid.DataGridNode(data);node.resource=resource;node.selectable=true;this._dataGrid.rootNode().appendChild(node);if(resource===selectedResource){nodeToSelect=node;nodeToSelect.selected=true;}}
if(!nodeToSelect&&this._dataGrid.rootNode().children.length){this._dataGrid.rootNode().children[0].selected=true;}}
_deleteButtonClicked(event){if(!this._dataGrid||!this._dataGrid.selectedNode){return;}
this._deleteCallback(this._dataGrid.selectedNode);}
_deleteCallback(node){}}
var ApplicationCacheItemsView$1=Object.freeze({__proto__:null,ApplicationCacheItemsView:ApplicationCacheItemsView});class AppManifestView extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('resources/appManifestView.css');Settings.Settings.instance().moduleSetting('colorFormat').addChangeListener(this._updateManifest.bind(this,true));this._emptyView=new EmptyWidget.EmptyWidget(UIString.UIString('No manifest detected'));this._emptyView.appendLink('https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/?utm_source=devtools');this._emptyView.show(this.contentElement);this._emptyView.hideWidget();this._reportView=new ReportView.ReportView(UIString.UIString('App Manifest'));this._reportView.show(this.contentElement);this._reportView.hideWidget();this._errorsSection=this._reportView.appendSection(UIString.UIString('Errors and warnings'));this._installabilitySection=this._reportView.appendSection(UIString.UIString('Installability'));this._identitySection=this._reportView.appendSection(UIString.UIString('Identity'));this._presentationSection=this._reportView.appendSection(UIString.UIString('Presentation'));this._iconsSection=this._reportView.appendSection(UIString.UIString('Icons'),'report-section-icons');this._shortcutSections=[];this._nameField=this._identitySection.appendField(UIString.UIString('Name'));this._shortNameField=this._identitySection.appendField(UIString.UIString('Short name'));this._startURLField=this._presentationSection.appendField(UIString.UIString('Start URL'));const themeColorField=this._presentationSection.appendField(UIString.UIString('Theme color'));this._themeColorSwatch=ColorSwatch.ColorSwatch.create();themeColorField.appendChild(this._themeColorSwatch);const backgroundColorField=this._presentationSection.appendField(UIString.UIString('Background color'));this._backgroundColorSwatch=ColorSwatch.ColorSwatch.create();backgroundColorField.appendChild(this._backgroundColorSwatch);this._orientationField=this._presentationSection.appendField(UIString.UIString('Orientation'));this._displayField=this._presentationSection.appendField(UIString.UIString('Display'));this._throttler=new Throttler.Throttler(1000);SDKModel.TargetManager.instance().observeTargets(this);}
targetAdded(target){if(this._target){return;}
this._target=target;this._resourceTreeModel=target.model(ResourceTreeModel.ResourceTreeModel);this._serviceWorkerManager=target.model(ServiceWorkerManager.ServiceWorkerManager);if(!this._resourceTreeModel||!this._serviceWorkerManager){return;}
this._updateManifest(true);this._registeredListeners=[this._resourceTreeModel.addEventListener(ResourceTreeModel.Events.DOMContentLoaded,event=>{this._updateManifest(true);}),this._serviceWorkerManager.addEventListener(ServiceWorkerManager.Events.RegistrationUpdated,event=>{this._updateManifest(false);})];}
targetRemoved(target){if(this._target!==target){return;}
if(!this._resourceTreeModel||!this._serviceWorkerManager){return;}
delete this._resourceTreeModel;delete this._serviceWorkerManager;EventTarget.EventTarget.removeEventListeners(this._registeredListeners);}
async _updateManifest(immediately){const{url,data,errors}=await this._resourceTreeModel.fetchAppManifest();const installabilityErrors=await this._resourceTreeModel.getInstallabilityErrors();const manifestIcons=await this._resourceTreeModel.getManifestIcons();this._throttler.schedule(()=>this._renderManifest(url,data,errors,installabilityErrors,manifestIcons),immediately);}
async _renderManifest(url,data,errors,installabilityErrors,manifestIcons){if(!data&&!errors.length){this._emptyView.showWidget();this._reportView.hideWidget();return;}
this._emptyView.hideWidget();this._reportView.showWidget();const link=Linkifier.Linkifier.linkifyURL(url);link.tabIndex=0;this._reportView.setURL(link);this._errorsSection.clearContent();this._errorsSection.element.classList.toggle('hidden',!errors.length);for(const error of errors){this._errorsSection.appendRow().appendChild(UIUtils.createIconLabel(error.message,error.critical?'smallicon-error':'smallicon-warning'));}
if(!data){return;}
if(data.charCodeAt(0)===0xFEFF){data=data.slice(1);}
const parsedManifest=JSON.parse(data);this._nameField.textContent=stringProperty('name');this._shortNameField.textContent=stringProperty('short_name');this._startURLField.removeChildren();const startURL=stringProperty('start_url');if(startURL){const completeURL=(ParsedURL.ParsedURL.completeURL(url,startURL));const link=Linkifier.Linkifier.linkifyURL(completeURL,{text:startURL});link.tabIndex=0;this._startURLField.appendChild(link);}
this._themeColorSwatch.classList.toggle('hidden',!stringProperty('theme_color'));const themeColor=Color.Color.parse(stringProperty('theme_color')||'white')||Color.Color.parse('white');this._themeColorSwatch.setColor((themeColor));this._themeColorSwatch.setFormat(Settings.detectColorFormat(this._themeColorSwatch.color()));this._backgroundColorSwatch.classList.toggle('hidden',!stringProperty('background_color'));const backgroundColor=Color.Color.parse(stringProperty('background_color')||'white')||Color.Color.parse('white');this._backgroundColorSwatch.setColor((backgroundColor));this._backgroundColorSwatch.setFormat(Settings.detectColorFormat(this._backgroundColorSwatch.color()));this._orientationField.textContent=stringProperty('orientation');const displayType=stringProperty('display');this._displayField.textContent=displayType;const icons=parsedManifest['icons']||[];this._iconsSection.clearContent();const shortcuts=parsedManifest['shortcuts']||[];for(const shortcutsSection of this._shortcutSections){shortcutsSection.detach(true);}
const imageErrors=[];const setIconMaskedCheckbox=UIUtils.CheckboxLabel.create(UIString.UIString('Show only the minimum safe area for maskable icons'));setIconMaskedCheckbox.classList.add('mask-checkbox');setIconMaskedCheckbox.addEventListener('click',()=>{this._iconsSection.setIconMasked(setIconMaskedCheckbox.checkboxElement.checked);});this._iconsSection.appendRow().appendChild(setIconMaskedCheckbox);const documentationLink=XLink.XLink.create('https://web.dev/maskable-icon/',ls`documentation on maskable icons`);this._iconsSection.appendRow().appendChild(UIUtils.formatLocalized('Need help? Read our %s.',[documentationLink]));if(manifestIcons&&manifestIcons.primaryIcon){const wrapper=createElement('div');wrapper.classList.add('image-wrapper');const image=createElement('img');image.style.maxWidth='200px';image.style.maxHeight='200px';image.src='data:image/png;base64,'+manifestIcons.primaryIcon;image.alt=ls`Primary manifest icon from ${url}`;const title=ls`Primary icon\nas used by Chrome`;const field=this._iconsSection.appendFlexedField(title);wrapper.appendChild(image);field.appendChild(wrapper);}
for(const icon of icons){const iconErrors=await this._appendIconResourceToSection(url,icon,this._iconsSection);imageErrors.push(...iconErrors);}
let shortcutIndex=1;for(const shortcut of shortcuts){const shortcutSection=this._reportView.appendSection(ls`Shortcut #${shortcutIndex}`);this._shortcutSections.push(shortcutSection);shortcutSection.appendFlexedField('Name',shortcut.name);if(shortcut.short_name){shortcutSection.appendFlexedField('Short name',shortcut.short_name);}
if(shortcut.description){shortcutSection.appendFlexedField('Description',shortcut.description);}
const urlField=shortcutSection.appendFlexedField('URL');const shortcutUrl=(ParsedURL.ParsedURL.completeURL(url,shortcut.url));const link=Linkifier.Linkifier.linkifyURL(shortcutUrl,{text:shortcut.url});link.tabIndex=0;urlField.appendChild(link);const shortcutIcons=shortcut.icons||[];for(const shortcutIcon of shortcutIcons){const shortcutIconErrors=await this._appendIconResourceToSection(url,shortcutIcon,shortcutSection);imageErrors.push(...shortcutIconErrors);}
shortcutIndex++;}
this._installabilitySection.clearContent();this._installabilitySection.element.classList.toggle('hidden',!installabilityErrors.length);const errorMessages=this.getInstallabilityErrorMessages(installabilityErrors);for(const error of errorMessages){this._installabilitySection.appendRow().appendChild(UIUtils.createIconLabel(error,'smallicon-warning'));}
this._errorsSection.element.classList.toggle('hidden',!errors.length&&!imageErrors.length);for(const error of imageErrors){this._errorsSection.appendRow().appendChild(UIUtils.createIconLabel(error,'smallicon-warning'));}
function stringProperty(name){const value=parsedManifest[name];if(typeof value!=='string'){return'';}
return value;}}
getInstallabilityErrorMessages(installabilityErrors){const errorMessages=[];for(const installabilityError of installabilityErrors){let errorMessage;switch(installabilityError.errorId){case'not-in-main-frame':errorMessage=ls`Page is not loaded in the main frame`;break;case'not-from-secure-origin':errorMessage=ls`Page is not served from a secure origin`;break;case'no-manifest':errorMessage=ls`Page has no manifest <link> URL`;break;case'manifest-empty':errorMessage=ls`Manifest could not be fetched, is empty, or could not be parsed`;break;case'start-url-not-valid':errorMessage=ls`Manifest start URL is not valid`;break;case'manifest-missing-name-or-short-name':errorMessage=ls`Manifest does not contain a 'name' or 'short_name' field`;break;case'manifest-display-not-supported':errorMessage=ls`Manifest 'display' property must be one of 'standalone', 'fullscreen', or 'minimal-ui'`;break;case'manifest-missing-suitable-icon':if(installabilityError.errorArguments.length!==1||installabilityError.errorArguments[0].name!=='minimum-icon-size-in-pixels'){console.error('Installability error does not have the correct errorArguments');break;}
errorMessage=ls`Manifest does not contain a suitable icon - PNG, SVG or WebP format of at least ${
              installabilityError.errorArguments[0]
                  .value}px is required, the sizes attribute must be set, and the purpose attribute, if set, must include "any" or "maskable".`;break;case'no-matching-service-worker':errorMessage=ls`No matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest.`;break;case'no-acceptable-icon':if(installabilityError.errorArguments.length!==1||installabilityError.errorArguments[0].name!=='minimum-icon-size-in-pixels'){console.error('Installability error does not have the correct errorArguments');break;}
errorMessage=ls`No supplied icon is at least ${
              installabilityError.errorArguments[0].value}px square in PNG, SVG or WebP format`;break;case'cannot-download-icon':errorMessage=ls`Could not download a required icon from the manifest`;break;case'no-icon-available':errorMessage=ls`Downloaded icon was empty or corrupted`;break;case'platform-not-supported-on-android':errorMessage=ls`The specified application platform is not supported on Android`;break;case'no-id-specified':errorMessage=ls`No Play store ID provided`;break;case'ids-do-not-match':errorMessage=ls`The Play Store app URL and Play Store ID do not match`;break;case'already-installed':errorMessage=ls`The app is already installed`;break;case'url-not-supported-for-webapk':errorMessage=ls`A URL in the manifest contains a username, password, or port`;break;case'in-incognito':errorMessage=ls`Page is loaded in an incognito window`;break;case'not-offline-capable':errorMessage=ls`Page does not work offline`;break;case'no-url-for-service-worker':errorMessage=ls`Could not check service worker without a 'start_url' field in the manifest`;break;case'prefer-related-applications':errorMessage=ls`Manifest specifies prefer_related_applications: true`;break;default:console.error(`Installability error id '${installabilityError.errorId}' is not recognized`);break;}
if(errorMessages){errorMessages.push(errorMessage);}}
return errorMessages;}
async _loadImage(url){const wrapper=createElement('div');wrapper.classList.add('image-wrapper');const image=createElement('img');const result=new Promise((resolve,reject)=>{image.onload=resolve;image.onerror=reject;});image.src=url;image.alt=ls`Image from ${url}`;wrapper.appendChild(image);try{await result;return{wrapper,image};}catch(e){}
return null;}
async _appendIconResourceToSection(baseUrl,icon,section){const iconErrors=[];const iconUrl=ParsedURL.ParsedURL.completeURL(baseUrl,icon['src']);const result=await this._loadImage(iconUrl);if(!result){iconErrors.push(ls`Icon ${iconUrl} failed to load`);return iconErrors;}
const{wrapper,image}=result;const sizes=icon['sizes']?icon['sizes'].replace('x','×')+'px':'';const title=sizes+'\n'+(icon['type']||'');const field=section.appendFlexedField(title);if(!icon.sizes){iconErrors.push(ls`Icon ${iconUrl} does not specify its size in the manifest`);}else if(!/^\d+x\d+$/.test(icon.sizes)){iconErrors.push(ls`Icon ${iconUrl} should specify its size as \`{width}x{height}\``);}else{const[width,height]=icon.sizes.split('x').map(x=>parseInt(x,10));if(image.naturalWidth!==width&&image.naturalHeight!==height){iconErrors.push(ls`Actual size (${image.naturalWidth}×${image.naturalHeight})px of icon ${
            iconUrl} does not match specified size (${width}×${height}px)`);}else if(image.naturalWidth!==width){iconErrors.push(ls`Actual width (${image.naturalWidth}px) of icon ${iconUrl} does not match specified width (${width}px)`);}else if(image.naturalHeight!==height){iconErrors.push(ls`Actual height (${image.naturalHeight}px) of icon ${
            iconUrl} does not match specified height (${height}px)`);}}
field.appendChild(wrapper);return iconErrors;}}
var AppManifestView$1=Object.freeze({__proto__:null,AppManifestView:AppManifestView});class BackgroundServiceModel extends SDKModel.SDKModel{constructor(target){super(target);this._backgroundServiceAgent=target.backgroundServiceAgent();target.registerBackgroundServiceDispatcher(this);this._events=new Map();}
enable(serviceName){this._events.set(serviceName,[]);this._backgroundServiceAgent.startObserving(serviceName);}
setRecording(shouldRecord,serviceName){this._backgroundServiceAgent.setRecording(shouldRecord,serviceName);}
clearEvents(serviceName){this._events.set(serviceName,[]);this._backgroundServiceAgent.clearEvents(serviceName);}
getEvents(serviceName){return this._events.get(serviceName)||[];}
recordingStateChanged(isRecording,serviceName){this.dispatchEventToListeners(Events$1.RecordingStateChanged,{isRecording,serviceName});}
backgroundServiceEventReceived(backgroundServiceEvent){this._events.get(backgroundServiceEvent.service).push(backgroundServiceEvent);this.dispatchEventToListeners(Events$1.BackgroundServiceEventReceived,backgroundServiceEvent);}}
SDKModel.SDKModel.register(BackgroundServiceModel,SDKModel.Capability.Browser,false);const Events$1={RecordingStateChanged:Symbol('RecordingStateChanged'),BackgroundServiceEventReceived:Symbol('BackgroundServiceEventReceived'),};var BackgroundServiceModel$1=Object.freeze({__proto__:null,BackgroundServiceModel:BackgroundServiceModel,Events:Events$1});class BackgroundServiceView extends Widget.VBox{static getUIString(serviceName){switch(serviceName){case Protocol.BackgroundService.ServiceName.BackgroundFetch:return ls`Background Fetch`;case Protocol.BackgroundService.ServiceName.BackgroundSync:return ls`Background Sync`;case Protocol.BackgroundService.ServiceName.PushMessaging:return ls`Push Messaging`;case Protocol.BackgroundService.ServiceName.Notifications:return ls`Notifications`;case Protocol.BackgroundService.ServiceName.PaymentHandler:return ls`Payment Handler`;case Protocol.BackgroundService.ServiceName.PeriodicBackgroundSync:return ls`Periodic Background Sync`;default:return'';}}
constructor(serviceName,model){super(true);this.registerRequiredCSS('resources/backgroundServiceView.css');this.registerRequiredCSS('ui/emptyWidget.css');this._serviceName=serviceName;this._model=model;this._model.addEventListener(Events$1.RecordingStateChanged,this._onRecordingStateChanged,this);this._model.addEventListener(Events$1.BackgroundServiceEventReceived,this._onEventReceived,this);this._model.enable(this._serviceName);this._serviceWorkerManager=this._model.target().model(ServiceWorkerManager.ServiceWorkerManager);this._securityOriginManager=this._model.target().model(SecurityOriginManager.SecurityOriginManager);this._securityOriginManager.addEventListener(SecurityOriginManager.Events.MainSecurityOriginChanged,()=>this._onOriginChanged());this._recordAction=(self.UI.actionRegistry.action('background-service.toggle-recording'));this._recordButton=null;this._originCheckbox=null;this._saveButton=null;this._toolbar=new Toolbar.Toolbar('background-service-toolbar',this.contentElement);this._setupToolbar();this._splitWidget=new SplitWidget.SplitWidget(false,true);this._splitWidget.show(this.contentElement);this._dataGrid=this._createDataGrid();this._previewPanel=new Widget.VBox();this._selectedEventNode=null;this._preview=null;this._splitWidget.setMainWidget(this._dataGrid.asWidget());this._splitWidget.setSidebarWidget(this._previewPanel);this._showPreview(null);}
async _setupToolbar(){this._recordButton=Toolbar.Toolbar.createActionButton(this._recordAction);this._toolbar.appendToolbarItem(this._recordButton);const clearButton=new Toolbar.ToolbarButton(ls`Clear`,'largeicon-clear');clearButton.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>this._clearEvents());this._toolbar.appendToolbarItem(clearButton);this._toolbar.appendSeparator();this._saveButton=new Toolbar.ToolbarButton(ls`Save events`,'largeicon-download');this._saveButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._saveToFile();});this._saveButton.setEnabled(false);this._toolbar.appendToolbarItem(this._saveButton);this._toolbar.appendSeparator();this._originCheckbox=new Toolbar.ToolbarCheckbox(ls`Show events from other domains`,ls`Show events from other domains`,()=>this._refreshView());this._toolbar.appendToolbarItem(this._originCheckbox);}
_refreshView(){this._clearView();const events=this._model.getEvents(this._serviceName).filter(event=>this._acceptEvent(event));for(const event of events){this._addEvent(event);}}
_clearView(){this._selectedEventNode=null;this._dataGrid.rootNode().removeChildren();this._saveButton.setEnabled(false);this._showPreview(null);}
_toggleRecording(){this._model.setRecording(!this._recordButton.toggled(),this._serviceName);}
_clearEvents(){this._model.clearEvents(this._serviceName);this._clearView();}
_onRecordingStateChanged(event){const state=(event.data);if(state.serviceName!==this._serviceName){return;}
if(state.isRecording===this._recordButton.toggled()){return;}
this._recordButton.setToggled(state.isRecording);this._showPreview(this._selectedEventNode);}
_onEventReceived(event){const serviceEvent=(event.data);if(!this._acceptEvent(serviceEvent)){return;}
this._addEvent(serviceEvent);}
_onOriginChanged(){if(this._originCheckbox.checked()){return;}
this._refreshView();}
_addEvent(serviceEvent){const data=this._createEventData(serviceEvent);const dataNode=new EventDataNode(data,serviceEvent.eventMetadata);this._dataGrid.rootNode().appendChild(dataNode);if(this._dataGrid.rootNode().children.length===1){this._saveButton.setEnabled(true);this._showPreview(this._selectedEventNode);}}
_createDataGrid(){const columns=([{id:'id',title:ls`#`,weight:1},{id:'timestamp',title:ls`Timestamp`,weight:8},{id:'eventName',title:ls`Event`,weight:10},{id:'origin',title:ls`Origin`,weight:10},{id:'swScope',title:ls`SW Scope`,weight:2},{id:'instanceId',title:ls`Instance ID`,weight:10},]);const dataGrid=new DataGrid.DataGridImpl({displayName:ls`Background Services`,columns});dataGrid.setStriped(true);dataGrid.addEventListener(DataGrid.Events.SelectedNode,event=>this._showPreview((event.data)));return dataGrid;}
_createEventData(serviceEvent){let swScope='';const registration=this._serviceWorkerManager.registrations().get(serviceEvent.serviceWorkerRegistrationId);if(registration){swScope=registration.scopeURL.substr(registration.securityOrigin.length);}
return{id:this._dataGrid.rootNode().children.length+1,timestamp:UIUtils.formatTimestamp(serviceEvent.timestamp*1000,true),origin:serviceEvent.origin,swScope,eventName:serviceEvent.eventName,instanceId:serviceEvent.instanceId,};}
_acceptEvent(event){if(event.service!==this._serviceName){return false;}
if(this._originCheckbox.checked()){return true;}
const origin=event.origin.substr(0,event.origin.length-1);return this._securityOriginManager.securityOrigins().includes(origin);}
_createLearnMoreLink(){let url='https://developers.google.com/web/tools/chrome-devtools/javascript/background-services?utm_source=devtools';switch(this._serviceName){case Protocol.BackgroundService.ServiceName.BackgroundFetch:url+='#fetch';break;case Protocol.BackgroundService.ServiceName.BackgroundSync:url+='#sync';break;case Protocol.BackgroundService.ServiceName.PushMessaging:url+='#push';break;case Protocol.BackgroundService.ServiceName.Notifications:url+='#notifications';break;default:break;}
return XLink.XLink.create(url,ls`Learn more`);}
_showPreview(dataNode){if(this._selectedEventNode&&this._selectedEventNode===dataNode){return;}
this._selectedEventNode=dataNode;if(this._preview){this._preview.detach();}
if(this._selectedEventNode){this._preview=this._selectedEventNode.createPreview();this._preview.show(this._previewPanel.contentElement);return;}
this._preview=new Widget.VBox();this._preview.contentElement.classList.add('background-service-preview','fill');const centered=this._preview.contentElement.createChild('div');if(this._dataGrid.rootNode().children.length){centered.createChild('p').textContent=ls`Select an entry to view metadata`;}else if(this._recordButton.toggled()){const featureName=BackgroundServiceView.getUIString(this._serviceName);centered.createChild('p').textContent=ls`Recording ${featureName} activity...`;centered.createChild('p').textContent=ls`DevTools will record all ${featureName} activity for up to 3 days, even when closed.`;}else{const landingRecordButton=Toolbar.Toolbar.createActionButton(this._recordAction);const recordKey=document.createElement('b');recordKey.classList.add('background-service-shortcut');recordKey.textContent=self.UI.shortcutRegistry.shortcutsForAction('background-service.toggle-recording')[0].title();const inlineButton=UIUtils.createInlineButton(landingRecordButton);inlineButton.classList.add('background-service-record-inline-button');centered.createChild('p').appendChild(UIUtils.formatLocalized('Click the record button %s or hit %s to start recording.',[inlineButton,recordKey]));centered.appendChild(this._createLearnMoreLink());}
this._preview.show(this._previewPanel.contentElement);}
async _saveToFile(){const fileName=`${this._serviceName}-${new Date().toISO8601Compact()}.json`;const stream=new FileUtils.FileOutputStream();const accepted=await stream.open(fileName);if(!accepted){return;}
const events=this._model.getEvents(this._serviceName).filter(event=>this._acceptEvent(event));await stream.write(JSON.stringify(events,undefined,2));stream.close();}}
class EventDataNode extends DataGrid.DataGridNode{constructor(data,eventMetadata){super(data);this._eventMetadata=eventMetadata.sort((m1,m2)=>m1.key.compareTo(m2.key));}
createPreview(){const preview=new Widget.VBox();preview.element.classList.add('background-service-metadata');for(const entry of this._eventMetadata){const div=document.createElement('div');div.classList.add('background-service-metadata-entry');div.createChild('div','background-service-metadata-name').textContent=entry.key+': ';if(entry.value){div.createChild('div','background-service-metadata-value source-code').textContent=entry.value;}else{div.createChild('div','background-service-metadata-value background-service-empty-value').textContent=ls`empty`;}
preview.element.appendChild(div);}
if(!preview.element.children.length){const div=document.createElement('div');div.classList.add('background-service-metadata-entry');div.createChild('div','background-service-metadata-name').textContent=ls`No metadata for this event`;preview.element.appendChild(div);}
return preview;}}
class ActionDelegate{handleAction(context,actionId){const view=context.flavor(BackgroundServiceView);switch(actionId){case'background-service.toggle-recording':view._toggleRecording();return true;}
return false;}}
let RecordingState;let EventData;var BackgroundServiceView$1=Object.freeze({__proto__:null,BackgroundServiceView:BackgroundServiceView,EventDataNode:EventDataNode,ActionDelegate:ActionDelegate,RecordingState:RecordingState,EventData:EventData});class Database{constructor(model,id,domain,name,version){this._model=model;this._id=id;this._domain=domain;this._name=name;this._version=version;}
get id(){return this._id;}
get name(){return this._name;}
set name(x){this._name=x;}
get version(){return this._version;}
set version(x){this._version=x;}
get domain(){return this._domain;}
set domain(x){this._domain=x;}
async tableNames(){const names=await this._model._agent.getDatabaseTableNames(this._id)||[];return names.sort();}
async executeSql(query,onSuccess,onError){const response=await this._model._agent.invoke_executeSQL({'databaseId':this._id,'query':query});const error=response[InspectorBackend.ProtocolError];if(error){onError(error);return;}
const sqlError=response.sqlError;if(!sqlError){onSuccess(response.columnNames,response.values);return;}
let message;if(sqlError.message){message=sqlError.message;}else if(sqlError.code===2){message=UIString.UIString('Database no longer has expected version.');}else{message=UIString.UIString('An unexpected error %s occurred.',sqlError.code);}
onError(message);}}
class DatabaseModel extends SDKModel.SDKModel{constructor(target){super(target);this._databases=[];this._agent=target.databaseAgent();this.target().registerDatabaseDispatcher(new DatabaseDispatcher(this));}
enable(){if(this._enabled){return;}
this._agent.enable();this._enabled=true;}
disable(){if(!this._enabled){return;}
this._enabled=false;this._databases=[];this._agent.disable();this.dispatchEventToListeners(Events$2.DatabasesRemoved);}
databases(){const result=[];for(const database of this._databases){result.push(database);}
return result;}
_addDatabase(database){this._databases.push(database);this.dispatchEventToListeners(Events$2.DatabaseAdded,database);}}
SDKModel.SDKModel.register(DatabaseModel,SDKModel.Capability.DOM,false);const Events$2={DatabaseAdded:Symbol('DatabaseAdded'),DatabasesRemoved:Symbol('DatabasesRemoved'),};class DatabaseDispatcher{constructor(model){this._model=model;}
addDatabase(payload){this._model._addDatabase(new Database(this._model,payload.id,payload.domain,payload.name,payload.version));}}
var DatabaseModel$1=Object.freeze({__proto__:null,Database:Database,DatabaseModel:DatabaseModel,Events:Events$2,DatabaseDispatcher:DatabaseDispatcher});class DOMStorage extends ObjectWrapper.ObjectWrapper{constructor(model,securityOrigin,isLocalStorage){super();this._model=model;this._securityOrigin=securityOrigin;this._isLocalStorage=isLocalStorage;}
static storageId(securityOrigin,isLocalStorage){return{securityOrigin:securityOrigin,isLocalStorage:isLocalStorage};}
get id(){return DOMStorage.storageId(this._securityOrigin,this._isLocalStorage);}
get securityOrigin(){return this._securityOrigin;}
get isLocalStorage(){return this._isLocalStorage;}
getItems(){return this._model._agent.getDOMStorageItems(this.id);}
setItem(key,value){this._model._agent.setDOMStorageItem(this.id,key,value);}
removeItem(key){this._model._agent.removeDOMStorageItem(this.id,key);}
clear(){this._model._agent.clear(this.id);}}
DOMStorage.Events={DOMStorageItemsCleared:Symbol('DOMStorageItemsCleared'),DOMStorageItemRemoved:Symbol('DOMStorageItemRemoved'),DOMStorageItemAdded:Symbol('DOMStorageItemAdded'),DOMStorageItemUpdated:Symbol('DOMStorageItemUpdated')};class DOMStorageModel extends SDKModel.SDKModel{constructor(target){super(target);this._securityOriginManager=target.model(SecurityOriginManager.SecurityOriginManager);this._storages={};this._agent=target.domstorageAgent();}
enable(){if(this._enabled){return;}
this.target().registerDOMStorageDispatcher(new DOMStorageDispatcher(this));this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins()){this._addOrigin(securityOrigin);}
this._agent.enable();this._enabled=true;}
clearForOrigin(origin){if(!this._enabled){return;}
for(const isLocal of[true,false]){const key=this._storageKey(origin,isLocal);const storage=this._storages[key];storage.clear();}
this._removeOrigin(origin);this._addOrigin(origin);}
_securityOriginAdded(event){this._addOrigin((event.data));}
_addOrigin(securityOrigin){const parsed=new ParsedURL.ParsedURL(securityOrigin);if(!parsed.isValid||parsed.scheme==='data'||parsed.scheme==='about'||parsed.scheme==='javascript'){return;}
for(const isLocal of[true,false]){const key=this._storageKey(securityOrigin,isLocal);console.assert(!this._storages[key]);const storage=new DOMStorage(this,securityOrigin,isLocal);this._storages[key]=storage;this.dispatchEventToListeners(Events$3.DOMStorageAdded,storage);}}
_securityOriginRemoved(event){this._removeOrigin((event.data));}
_removeOrigin(securityOrigin){for(const isLocal of[true,false]){const key=this._storageKey(securityOrigin,isLocal);const storage=this._storages[key];if(!storage){continue;}
delete this._storages[key];this.dispatchEventToListeners(Events$3.DOMStorageRemoved,storage);}}
_storageKey(securityOrigin,isLocalStorage){return JSON.stringify(DOMStorage.storageId(securityOrigin,isLocalStorage));}
_domStorageItemsCleared(storageId){const domStorage=this.storageForId(storageId);if(!domStorage){return;}
const eventData={};domStorage.dispatchEventToListeners(DOMStorage.Events.DOMStorageItemsCleared,eventData);}
_domStorageItemRemoved(storageId,key){const domStorage=this.storageForId(storageId);if(!domStorage){return;}
const eventData={key:key};domStorage.dispatchEventToListeners(DOMStorage.Events.DOMStorageItemRemoved,eventData);}
_domStorageItemAdded(storageId,key,value){const domStorage=this.storageForId(storageId);if(!domStorage){return;}
const eventData={key:key,value:value};domStorage.dispatchEventToListeners(DOMStorage.Events.DOMStorageItemAdded,eventData);}
_domStorageItemUpdated(storageId,key,oldValue,value){const domStorage=this.storageForId(storageId);if(!domStorage){return;}
const eventData={key:key,oldValue:oldValue,value:value};domStorage.dispatchEventToListeners(DOMStorage.Events.DOMStorageItemUpdated,eventData);}
storageForId(storageId){return this._storages[JSON.stringify(storageId)];}
storages(){const result=[];for(const id in this._storages){result.push(this._storages[id]);}
return result;}}
SDKModel.SDKModel.register(DOMStorageModel,SDKModel.Capability.DOM,false);const Events$3={DOMStorageAdded:Symbol('DOMStorageAdded'),DOMStorageRemoved:Symbol('DOMStorageRemoved')};class DOMStorageDispatcher{constructor(model){this._model=model;}
domStorageItemsCleared(storageId){this._model._domStorageItemsCleared(storageId);}
domStorageItemRemoved(storageId,key){this._model._domStorageItemRemoved(storageId,key);}
domStorageItemAdded(storageId,key,value){this._model._domStorageItemAdded(storageId,key,value);}
domStorageItemUpdated(storageId,key,oldValue,value){this._model._domStorageItemUpdated(storageId,key,oldValue,value);}}
var DOMStorageModel$1=Object.freeze({__proto__:null,DOMStorage:DOMStorage,DOMStorageModel:DOMStorageModel,Events:Events$3,DOMStorageDispatcher:DOMStorageDispatcher});class IndexedDBModel extends SDKModel.SDKModel{constructor(target){super(target);target.registerStorageDispatcher(this);this._securityOriginManager=target.model(SecurityOriginManager.SecurityOriginManager);this._indexedDBAgent=target.indexedDBAgent();this._storageAgent=target.storageAgent();this._databases=new Map();this._databaseNamesBySecurityOrigin={};this._originsUpdated=new Set();this._throttler=new Throttler.Throttler(1000);}
static keyFromIDBKey(idbKey){if(typeof(idbKey)==='undefined'||idbKey===null){return undefined;}
let type;const key={};switch(typeof(idbKey)){case'number':key.number=idbKey;type=KeyTypes.NumberType;break;case'string':key.string=idbKey;type=KeyTypes.StringType;break;case'object':if(idbKey instanceof Date){key.date=idbKey.getTime();type=KeyTypes.DateType;}else if(Array.isArray(idbKey)){key.array=[];for(let i=0;i<idbKey.length;++i){key.array.push(IndexedDBModel.keyFromIDBKey(idbKey[i]));}
type=KeyTypes.ArrayType;}
break;default:return undefined;}
key.type=(type);return key;}
static _keyRangeFromIDBKeyRange(idbKeyRange){const keyRange={};keyRange.lower=IndexedDBModel.keyFromIDBKey(idbKeyRange.lower);keyRange.upper=IndexedDBModel.keyFromIDBKey(idbKeyRange.upper);keyRange.lowerOpen=!!idbKeyRange.lowerOpen;keyRange.upperOpen=!!idbKeyRange.upperOpen;return keyRange;}
static idbKeyPathFromKeyPath(keyPath){let idbKeyPath;switch(keyPath.type){case KeyPathTypes.NullType:idbKeyPath=null;break;case KeyPathTypes.StringType:idbKeyPath=keyPath.string;break;case KeyPathTypes.ArrayType:idbKeyPath=keyPath.array;break;}
return idbKeyPath;}
static keyPathStringFromIDBKeyPath(idbKeyPath){if(typeof idbKeyPath==='string'){return'"'+idbKeyPath+'"';}
if(idbKeyPath instanceof Array){return'["'+idbKeyPath.join('", "')+'"]';}
return null;}
enable(){if(this._enabled){return;}
this._indexedDBAgent.enable();this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginAdded,this._securityOriginAdded,this);this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginRemoved,this._securityOriginRemoved,this);for(const securityOrigin of this._securityOriginManager.securityOrigins()){this._addOrigin(securityOrigin);}
this._enabled=true;}
clearForOrigin(origin){if(!this._enabled||!this._databaseNamesBySecurityOrigin[origin]){return;}
this._removeOrigin(origin);this._addOrigin(origin);}
async deleteDatabase(databaseId){if(!this._enabled){return;}
await this._indexedDBAgent.deleteDatabase(databaseId.securityOrigin,databaseId.name);this._loadDatabaseNames(databaseId.securityOrigin);}
async refreshDatabaseNames(){for(const securityOrigin in this._databaseNamesBySecurityOrigin){await this._loadDatabaseNames(securityOrigin);}
this.dispatchEventToListeners(Events$4.DatabaseNamesRefreshed);}
refreshDatabase(databaseId){this._loadDatabase(databaseId,true);}
clearObjectStore(databaseId,objectStoreName){return this._indexedDBAgent.clearObjectStore(databaseId.securityOrigin,databaseId.name,objectStoreName);}
deleteEntries(databaseId,objectStoreName,idbKeyRange){const keyRange=IndexedDBModel._keyRangeFromIDBKeyRange(idbKeyRange);return this._indexedDBAgent.deleteObjectStoreEntries(databaseId.securityOrigin,databaseId.name,objectStoreName,keyRange);}
_securityOriginAdded(event){const securityOrigin=(event.data);this._addOrigin(securityOrigin);}
_securityOriginRemoved(event){const securityOrigin=(event.data);this._removeOrigin(securityOrigin);}
_addOrigin(securityOrigin){console.assert(!this._databaseNamesBySecurityOrigin[securityOrigin]);this._databaseNamesBySecurityOrigin[securityOrigin]=[];this._loadDatabaseNames(securityOrigin);if(this._isValidSecurityOrigin(securityOrigin)){this._storageAgent.trackIndexedDBForOrigin(securityOrigin);}}
_removeOrigin(securityOrigin){console.assert(this._databaseNamesBySecurityOrigin[securityOrigin]);for(let i=0;i<this._databaseNamesBySecurityOrigin[securityOrigin].length;++i){this._databaseRemoved(securityOrigin,this._databaseNamesBySecurityOrigin[securityOrigin][i]);}
delete this._databaseNamesBySecurityOrigin[securityOrigin];if(this._isValidSecurityOrigin(securityOrigin)){this._storageAgent.untrackIndexedDBForOrigin(securityOrigin);}}
_isValidSecurityOrigin(securityOrigin){const parsedURL=ParsedURL.ParsedURL.fromString(securityOrigin);return!!parsedURL&&parsedURL.scheme.startsWith('http');}
_updateOriginDatabaseNames(securityOrigin,databaseNames){const newDatabaseNames=new Set(databaseNames);const oldDatabaseNames=new Set(this._databaseNamesBySecurityOrigin[securityOrigin]);this._databaseNamesBySecurityOrigin[securityOrigin]=databaseNames;for(const databaseName of oldDatabaseNames){if(!newDatabaseNames.has(databaseName)){this._databaseRemoved(securityOrigin,databaseName);}}
for(const databaseName of newDatabaseNames){if(!oldDatabaseNames.has(databaseName)){this._databaseAdded(securityOrigin,databaseName);}}}
databases(){const result=[];for(const securityOrigin in this._databaseNamesBySecurityOrigin){const databaseNames=this._databaseNamesBySecurityOrigin[securityOrigin];for(let i=0;i<databaseNames.length;++i){result.push(new DatabaseId(securityOrigin,databaseNames[i]));}}
return result;}
_databaseAdded(securityOrigin,databaseName){const databaseId=new DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Events$4.DatabaseAdded,{model:this,databaseId:databaseId});}
_databaseRemoved(securityOrigin,databaseName){const databaseId=new DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Events$4.DatabaseRemoved,{model:this,databaseId:databaseId});}
async _loadDatabaseNames(securityOrigin){const databaseNames=await this._indexedDBAgent.requestDatabaseNames(securityOrigin);if(!databaseNames){return[];}
if(!this._databaseNamesBySecurityOrigin[securityOrigin]){return[];}
this._updateOriginDatabaseNames(securityOrigin,databaseNames);return databaseNames;}
async _loadDatabase(databaseId,entriesUpdated){const databaseWithObjectStores=await this._indexedDBAgent.requestDatabase(databaseId.securityOrigin,databaseId.name);if(!databaseWithObjectStores){return;}
if(!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]){return;}
const databaseModel=new Database$1(databaseId,databaseWithObjectStores.version);this._databases.set(databaseId,databaseModel);for(const objectStore of databaseWithObjectStores.objectStores){const objectStoreIDBKeyPath=IndexedDBModel.idbKeyPathFromKeyPath(objectStore.keyPath);const objectStoreModel=new ObjectStore(objectStore.name,objectStoreIDBKeyPath,objectStore.autoIncrement);for(let j=0;j<objectStore.indexes.length;++j){const index=objectStore.indexes[j];const indexIDBKeyPath=IndexedDBModel.idbKeyPathFromKeyPath(index.keyPath);const indexModel=new Index(index.name,indexIDBKeyPath,index.unique,index.multiEntry);objectStoreModel.indexes[indexModel.name]=indexModel;}
databaseModel.objectStores[objectStoreModel.name]=objectStoreModel;}
this.dispatchEventToListeners(Events$4.DatabaseLoaded,{model:this,database:databaseModel,entriesUpdated:entriesUpdated});}
loadObjectStoreData(databaseId,objectStoreName,idbKeyRange,skipCount,pageSize,callback){this._requestData(databaseId,databaseId.name,objectStoreName,'',idbKeyRange,skipCount,pageSize,callback);}
loadIndexData(databaseId,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback){this._requestData(databaseId,databaseId.name,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback);}
async _requestData(databaseId,databaseName,objectStoreName,indexName,idbKeyRange,skipCount,pageSize,callback){const keyRange=idbKeyRange?IndexedDBModel._keyRangeFromIDBKeyRange(idbKeyRange):undefined;const response=await this._indexedDBAgent.invoke_requestData({securityOrigin:databaseId.securityOrigin,databaseName,objectStoreName,indexName,skipCount,pageSize,keyRange});if(response[InspectorBackend.ProtocolError]){console.error('IndexedDBAgent error: '+response[InspectorBackend.ProtocolError]);return;}
const runtimeModel=this.target().model(RuntimeModel.RuntimeModel);if(!runtimeModel||!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]){return;}
const dataEntries=response.objectStoreDataEntries;const entries=[];for(const dataEntry of dataEntries){const key=runtimeModel.createRemoteObject(dataEntry.key);const primaryKey=runtimeModel.createRemoteObject(dataEntry.primaryKey);const value=runtimeModel.createRemoteObject(dataEntry.value);entries.push(new Entry(key,primaryKey,value));}
callback(entries,response.hasMore);}
async getMetadata(databaseId,objectStore){const databaseOrigin=databaseId.securityOrigin;const databaseName=databaseId.name;const objectStoreName=objectStore.name;const response=await this._indexedDBAgent.invoke_getMetadata({securityOrigin:databaseOrigin,databaseName,objectStoreName});if(response[InspectorBackend.ProtocolError]){console.error('IndexedDBAgent error: '+response[InspectorBackend.ProtocolError]);return null;}
return{entriesCount:response.entriesCount,keyGeneratorValue:response.keyGeneratorValue};}
async _refreshDatabaseList(securityOrigin){const databaseNames=await this._loadDatabaseNames(securityOrigin);for(const databaseName of databaseNames){this._loadDatabase(new DatabaseId(securityOrigin,databaseName),false);}}
indexedDBListUpdated(securityOrigin){this._originsUpdated.add(securityOrigin);this._throttler.schedule(()=>{const promises=Array.from(this._originsUpdated,securityOrigin=>{this._refreshDatabaseList(securityOrigin);});this._originsUpdated.clear();return Promise.all(promises);});}
indexedDBContentUpdated(securityOrigin,databaseName,objectStoreName){const databaseId=new DatabaseId(securityOrigin,databaseName);this.dispatchEventToListeners(Events$4.IndexedDBContentUpdated,{databaseId:databaseId,objectStoreName:objectStoreName,model:this});}
cacheStorageListUpdated(securityOrigin){}
cacheStorageContentUpdated(securityOrigin){}}
SDKModel.SDKModel.register(IndexedDBModel,SDKModel.Capability.Storage,false);const KeyTypes={NumberType:'number',StringType:'string',DateType:'date',ArrayType:'array'};const KeyPathTypes={NullType:'null',StringType:'string',ArrayType:'array'};const Events$4={DatabaseAdded:Symbol('DatabaseAdded'),DatabaseRemoved:Symbol('DatabaseRemoved'),DatabaseLoaded:Symbol('DatabaseLoaded'),DatabaseNamesRefreshed:Symbol('DatabaseNamesRefreshed'),IndexedDBContentUpdated:Symbol('IndexedDBContentUpdated')};class Entry{constructor(key,primaryKey,value){this.key=key;this.primaryKey=primaryKey;this.value=value;}}
class DatabaseId{constructor(securityOrigin,name){this.securityOrigin=securityOrigin;this.name=name;}
equals(databaseId){return this.name===databaseId.name&&this.securityOrigin===databaseId.securityOrigin;}}
class Database$1{constructor(databaseId,version){this.databaseId=databaseId;this.version=version;this.objectStores={};}}
class ObjectStore{constructor(name,keyPath,autoIncrement){this.name=name;this.keyPath=keyPath;this.autoIncrement=autoIncrement;this.indexes={};}
get keyPathString(){return(IndexedDBModel.keyPathStringFromIDBKeyPath((this.keyPath)));}}
class Index{constructor(name,keyPath,unique,multiEntry){this.name=name;this.keyPath=keyPath;this.unique=unique;this.multiEntry=multiEntry;}
get keyPathString(){return(IndexedDBModel.keyPathStringFromIDBKeyPath((this.keyPath)));}}
let ObjectStoreMetadata;var IndexedDBModel$1=Object.freeze({__proto__:null,IndexedDBModel:IndexedDBModel,KeyTypes:KeyTypes,KeyPathTypes:KeyPathTypes,Events:Events$4,Entry:Entry,DatabaseId:DatabaseId,Database:Database$1,ObjectStore:ObjectStore,Index:Index,ObjectStoreMetadata:ObjectStoreMetadata});class ClearStorageView extends ThrottledWidget.ThrottledWidget{constructor(){super(true,1000);const types=Protocol.Storage.StorageType;this._pieColors=new Map([[types.Appcache,'rgb(110, 161, 226)'],[types.Cache_storage,'rgb(229, 113, 113)'],[types.Cookies,'rgb(239, 196, 87)'],[types.Indexeddb,'rgb(155, 127, 230)'],[types.Local_storage,'rgb(116, 178, 102)'],[types.Service_workers,'rgb(255, 167, 36)'],[types.Websql,'rgb(203, 220, 56)'],]);this._reportView=new ReportView.ReportView(UIString.UIString('Clear storage'));this._reportView.registerRequiredCSS('resources/clearStorageView.css');this._reportView.element.classList.add('clear-storage-header');this._reportView.show(this.contentElement);this._target=null;this._securityOrigin=null;this._settings=new Map();for(const type of AllStorageTypes){this._settings.set(type,Settings.Settings.instance().createSetting('clear-storage-'+type,true));}
const quota=this._reportView.appendSection(UIString.UIString('Usage'));this._quotaRow=quota.appendSelectableRow();const learnMoreRow=quota.appendRow();const learnMore=XLink.XLink.create('https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps#opaque-responses',ls`Learn more`);learnMoreRow.appendChild(learnMore);this._quotaUsage=null;this._pieChart=new PerfUI.PieChart({chartName:ls`Storage Usage`,size:110,formatter:NumberUtilities.bytesToString,showLegend:true});const usageBreakdownRow=quota.appendRow();usageBreakdownRow.classList.add('usage-breakdown-row');usageBreakdownRow.appendChild(this._pieChart.element);const clearButtonSection=this._reportView.appendSection('','clear-storage-button').appendRow();this._clearButton=UIUtils.createTextButton(ls`Clear site data`,this._clear.bind(this));clearButtonSection.appendChild(this._clearButton);const application=this._reportView.appendSection(UIString.UIString('Application'));this._appendItem(application,UIString.UIString('Unregister service workers'),'service_workers');application.markFieldListAsGroup();const storage=this._reportView.appendSection(UIString.UIString('Storage'));this._appendItem(storage,UIString.UIString('Local and session storage'),'local_storage');this._appendItem(storage,UIString.UIString('IndexedDB'),'indexeddb');this._appendItem(storage,UIString.UIString('Web SQL'),'websql');this._appendItem(storage,UIString.UIString('Cookies'),'cookies');storage.markFieldListAsGroup();const caches=this._reportView.appendSection(UIString.UIString('Cache'));this._appendItem(caches,UIString.UIString('Cache storage'),'cache_storage');this._appendItem(caches,UIString.UIString('Application cache'),'appcache');caches.markFieldListAsGroup();SDKModel.TargetManager.instance().observeTargets(this);}
_appendItem(section,title,settingName){const row=section.appendRow();row.appendChild(SettingsUI.createSettingCheckbox(title,this._settings.get(settingName),true));}
targetAdded(target){if(this._target){return;}
this._target=target;const securityOriginManager=target.model(SecurityOriginManager.SecurityOriginManager);this._updateOrigin(securityOriginManager.mainSecurityOrigin(),securityOriginManager.unreachableMainSecurityOrigin());securityOriginManager.addEventListener(SecurityOriginManager.Events.MainSecurityOriginChanged,this._originChanged,this);}
targetRemoved(target){if(this._target!==target){return;}
const securityOriginManager=target.model(SecurityOriginManager.SecurityOriginManager);securityOriginManager.removeEventListener(SecurityOriginManager.Events.MainSecurityOriginChanged,this._originChanged,this);}
_originChanged(event){const mainOrigin=(event.data.mainSecurityOrigin);const unreachableMainOrigin=(event.data.unreachableMainSecurityOrigin);this._updateOrigin(mainOrigin,unreachableMainOrigin);}
_updateOrigin(mainOrigin,unreachableMainOrigin){if(unreachableMainOrigin){this._securityOrigin=unreachableMainOrigin;this._reportView.setSubtitle(ls`${unreachableMainOrigin} (failed to load)`);}else{this._securityOrigin=mainOrigin;this._reportView.setSubtitle(mainOrigin);}
this.doUpdate();}
_clear(){if(!this._securityOrigin){return;}
const selectedStorageTypes=[];for(const type of this._settings.keys()){if(this._settings.get(type).get()){selectedStorageTypes.push(type);}}
if(this._target){ClearStorageView.clear(this._target,this._securityOrigin,selectedStorageTypes);}
this._clearButton.disabled=true;const label=this._clearButton.textContent;this._clearButton.textContent=UIString.UIString('Clearing...');setTimeout(()=>{this._clearButton.disabled=false;this._clearButton.textContent=label;this._clearButton.focus();},500);}
static clear(target,securityOrigin,selectedStorageTypes){target.storageAgent().clearDataForOrigin(securityOrigin,selectedStorageTypes.join(','));const set=new Set(selectedStorageTypes);const hasAll=set.has(Protocol.Storage.StorageType.All);if(set.has(Protocol.Storage.StorageType.Cookies)||hasAll){const cookieModel=target.model(CookieModel.CookieModel);if(cookieModel){cookieModel.clear();}}
if(set.has(Protocol.Storage.StorageType.Indexeddb)||hasAll){for(const target of SDKModel.TargetManager.instance().targets()){const indexedDBModel=target.model(IndexedDBModel);if(indexedDBModel){indexedDBModel.clearForOrigin(securityOrigin);}}}
if(set.has(Protocol.Storage.StorageType.Local_storage)||hasAll){const storageModel=target.model(DOMStorageModel);if(storageModel){storageModel.clearForOrigin(securityOrigin);}}
if(set.has(Protocol.Storage.StorageType.Websql)||hasAll){const databaseModel=target.model(DatabaseModel);if(databaseModel){databaseModel.disable();databaseModel.enable();}}
if(set.has(Protocol.Storage.StorageType.Cache_storage)||hasAll){const target=SDKModel.TargetManager.instance().mainTarget();const model=target&&target.model(ServiceWorkerCacheModel.ServiceWorkerCacheModel);if(model){model.clearForOrigin(securityOrigin);}}
if(set.has(Protocol.Storage.StorageType.Appcache)||hasAll){const appcacheModel=target.model(ApplicationCacheModel);if(appcacheModel){appcacheModel.reset();}}}
async doUpdate(){if(!this._securityOrigin){return;}
const securityOrigin=(this._securityOrigin);const response=await this._target.storageAgent().invoke_getUsageAndQuota({origin:securityOrigin});if(response[InspectorBackend.ProtocolError]){this._quotaRow.textContet='';this._resetPieChart(0);return;}
this._quotaRow.textContent=UIString.UIString('%s used out of %s storage quota.\xA0',NumberUtilities.bytesToString(response.usage),NumberUtilities.bytesToString(response.quota));if(response.quota<125829120){this._quotaRow.title=ls`Storage quota is limited in Incognito mode`;this._quotaRow.appendChild(Icon.Icon.create('smallicon-info'));}
if(this._quotaUsage===null||this._quotaUsage!==response.usage){this._quotaUsage=response.usage;this._resetPieChart(response.usage);for(const usageForType of response.usageBreakdown.sort((a,b)=>b.usage-a.usage)){const value=usageForType.usage;if(!value){continue;}
const title=this._getStorageTypeName(usageForType.storageType);const color=this._pieColors.get(usageForType.storageType)||'#ccc';this._pieChart.addSlice(value,color,title);}}
this._usageUpdatedForTest(response.usage,response.quota,response.usageBreakdown);this.update();}
_resetPieChart(total){this._pieChart.initializeWithTotal(total);}
_getStorageTypeName(type){switch(type){case Protocol.Storage.StorageType.File_systems:return UIString.UIString('File System');case Protocol.Storage.StorageType.Websql:return UIString.UIString('Web SQL');case Protocol.Storage.StorageType.Appcache:return UIString.UIString('Application Cache');case Protocol.Storage.StorageType.Indexeddb:return UIString.UIString('IndexedDB');case Protocol.Storage.StorageType.Cache_storage:return UIString.UIString('Cache Storage');case Protocol.Storage.StorageType.Service_workers:return UIString.UIString('Service Workers');default:return UIString.UIString('Other');}}
_usageUpdatedForTest(usage,quota,usageBreakdown){}}
const AllStorageTypes=[Protocol.Storage.StorageType.Appcache,Protocol.Storage.StorageType.Cache_storage,Protocol.Storage.StorageType.Cookies,Protocol.Storage.StorageType.Indexeddb,Protocol.Storage.StorageType.Local_storage,Protocol.Storage.StorageType.Service_workers,Protocol.Storage.StorageType.Websql];class ActionDelegate$1{handleAction(context,actionId){switch(actionId){case'resources.clear':return this._handleClear();}
return false;}
_handleClear(){const target=SDKModel.TargetManager.instance().mainTarget();if(!target){return false;}
const resourceTreeModel=target.model(ResourceTreeModel.ResourceTreeModel);if(!resourceTreeModel){return false;}
const securityOrigin=resourceTreeModel.getMainSecurityOrigin();if(!securityOrigin){return false;}
ClearStorageView.clear(target,securityOrigin,AllStorageTypes);return true;}}
var ClearStorageView$1=Object.freeze({__proto__:null,ClearStorageView:ClearStorageView,AllStorageTypes:AllStorageTypes,ActionDelegate:ActionDelegate$1});class DatabaseQueryView extends Widget.VBox{constructor(database){super();this.database=database;this.element.classList.add('storage-view','query','monospace');this.element.addEventListener('selectstart',this._selectStart.bind(this),false);this._queryWrapper=this.element.createChild('div','database-query-group-messages');this._queryWrapper.addEventListener('focusin',this._onFocusIn.bind(this));this._queryWrapper.addEventListener('focusout',this._onFocusOut.bind(this));this._queryWrapper.addEventListener('keydown',this._onKeyDown.bind(this));this._queryWrapper.tabIndex=-1;this._promptContainer=this.element.createChild('div','database-query-prompt-container');this._promptContainer.appendChild(Icon.Icon.create('smallicon-text-prompt','prompt-icon'));this._promptElement=this._promptContainer.createChild('div');this._promptElement.className='database-query-prompt';this._promptElement.addEventListener('keydown',this._promptKeyDown.bind(this));this._prompt=new TextPrompt.TextPrompt();this._prompt.initialize(this.completions.bind(this),' ');this._proxyElement=this._prompt.attach(this._promptElement);this.element.addEventListener('click',this._messagesClicked.bind(this),true);this._queryResults=[];this._virtualSelectedIndex=-1;this._lastSelectedElement;this._selectionTimeout=0;}
_messagesClicked(){this._prompt.focus();if(!this._prompt.isCaretInsidePrompt()&&!this.element.hasSelection()){this._prompt.moveCaretToEndOfPrompt();}}
_onKeyDown(event){if(UIUtils.isEditing()||!this._queryResults.length||event.shiftKey){return;}
switch(event.key){case'ArrowUp':if(this._virtualSelectedIndex>0){this._virtualSelectedIndex--;}else{return;}
break;case'ArrowDown':if(this._virtualSelectedIndex<this._queryResults.length-1){this._virtualSelectedIndex++;}else{return;}
break;case'Home':this._virtualSelectedIndex=0;break;case'End':this._virtualSelectedIndex=this._queryResults.length-1;break;default:return;}
event.consume(true);this._updateFocusedItem();}
_onFocusIn(event){if(this._virtualSelectedIndex===-1&&this._isOutsideViewport((event.relatedTarget))&&event.target===this._queryWrapper&&this._queryResults.length){this._virtualSelectedIndex=this._queryResults.length-1;}
this._updateFocusedItem();}
_onFocusOut(event){if(this._isOutsideViewport((event.relatedTarget))){this._virtualSelectedIndex=-1;}
this._updateFocusedItem();this._queryWrapper.scrollTop=10000000;}
_isOutsideViewport(element){return!!element&&!element.isSelfOrDescendant(this._queryWrapper);}
_updateFocusedItem(){let index=this._virtualSelectedIndex;if(this._queryResults.length&&this._virtualSelectedIndex<0){index=this._queryResults.length-1;}
const selectedElement=index>=0?this._queryResults[index]:null;const changed=this._lastSelectedElement!==selectedElement;const containerHasFocus=this._queryWrapper===this.element.ownerDocument.deepActiveElement();if(selectedElement&&(changed||containerHasFocus)&&this.element.hasFocus()){if(!selectedElement.hasFocus()){selectedElement.focus();}}
if(this._queryResults.length&&!this._queryWrapper.hasFocus()){this._queryWrapper.tabIndex=0;}else{this._queryWrapper.tabIndex=-1;}
this._lastSelectedElement=selectedElement;}
async completions(expression,prefix,force){if(!prefix){return[];}
prefix=prefix.toLowerCase();const tableNames=await this.database.tableNames();return tableNames.map(name=>name+' ').concat(SQL_BUILT_INS).filter(proposal=>proposal.toLowerCase().startsWith(prefix)).map(completion=>({text:completion}));}
_selectStart(event){if(this._selectionTimeout){clearTimeout(this._selectionTimeout);}
this._prompt.clearAutocomplete();function moveBackIfOutside(){delete this._selectionTimeout;if(!this._prompt.isCaretInsidePrompt()&&!this.element.hasSelection()){this._prompt.moveCaretToEndOfPrompt();}
this._prompt.autoCompleteSoon();}
this._selectionTimeout=setTimeout(moveBackIfOutside.bind(this),100);}
_promptKeyDown(event){if(isEnterKey(event)){this._enterKeyPressed(event);return;}}
async _enterKeyPressed(event){event.consume(true);const query=this._prompt.textWithCurrentSuggestion();this._prompt.clearAutocomplete();if(!query.length){return;}
this._prompt.setEnabled(false);try{const result=await new Promise((resolve,reject)=>{this.database.executeSql(query,(columnNames,values)=>resolve({columnNames,values}),errorText=>reject(errorText));});this._queryFinished(query,result.columnNames,result.values);}catch(e){this._appendErrorQueryResult(query,e);}
this._prompt.setEnabled(true);this._prompt.setText('');this._prompt.focus();}
_queryFinished(query,columnNames,values){const dataGrid=SortableDataGrid.SortableDataGrid.create(columnNames,values,ls`Database Query`);const trimmedQuery=query.trim();let view=null;if(dataGrid){dataGrid.setStriped(true);dataGrid.renderInline();dataGrid.autoSizeColumns(5);view=dataGrid.asWidget();dataGrid.setFocusable(false);}
this._appendViewQueryResult(trimmedQuery,view);if(trimmedQuery.match(/^create /i)||trimmedQuery.match(/^drop table /i)){this.dispatchEventToListeners(Events$5.SchemaUpdated,this.database);}}
_appendViewQueryResult(query,view){const resultElement=this._appendQueryResult(query);if(view){view.show(resultElement);}else{resultElement.remove();}
this._scrollResultIntoView();}
_appendErrorQueryResult(query,errorText){const resultElement=this._appendQueryResult(query);resultElement.classList.add('error');resultElement.appendChild(Icon.Icon.create('smallicon-error','prompt-icon'));resultElement.createTextChild(errorText);this._scrollResultIntoView();}
_scrollResultIntoView(){this._queryResults[this._queryResults.length-1].scrollIntoView(false);this._promptElement.scrollIntoView(false);}
_appendQueryResult(query){const element=createElement('div');element.className='database-user-query';element.tabIndex=-1;ARIAUtils.setAccessibleName(element,ls`Query: ${query}`);this._queryResults.push(element);this._updateFocusedItem();element.appendChild(Icon.Icon.create('smallicon-user-command','prompt-icon'));const commandTextElement=createElement('span');commandTextElement.className='database-query-text';commandTextElement.textContent=query;element.appendChild(commandTextElement);const resultElement=createElement('div');resultElement.className='database-query-result';element.appendChild(resultElement);this._queryWrapper.appendChild(element);return resultElement;}}
const Events$5={SchemaUpdated:Symbol('SchemaUpdated')};const SQL_BUILT_INS=['SELECT ','FROM ','WHERE ','LIMIT ','DELETE FROM ','CREATE ','DROP ','TABLE ','INDEX ','UPDATE ','INSERT INTO ','VALUES ('];var DatabaseQueryView$1=Object.freeze({__proto__:null,DatabaseQueryView:DatabaseQueryView,Events:Events$5,SQL_BUILT_INS:SQL_BUILT_INS});class DatabaseTableView extends View.SimpleView{constructor(database,tableName){super(UIString.UIString('Database'));this.database=database;this.tableName=tableName;this.element.classList.add('storage-view','table');this._visibleColumnsSetting=Settings.Settings.instance().createSetting('databaseTableViewVisibleColumns',{});this.refreshButton=new Toolbar.ToolbarButton(UIString.UIString('Refresh'),'largeicon-refresh');this.refreshButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._refreshButtonClicked,this);this._visibleColumnsInput=new Toolbar.ToolbarInput(UIString.UIString('Visible columns'),'',1);this._visibleColumnsInput.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,this._onVisibleColumnsChanged,this);this._dataGrid;}
wasShown(){this.update();}
async toolbarItems(){return[this.refreshButton,this._visibleColumnsInput];}
_escapeTableName(tableName){return tableName.replace(/\"/g,'""');}
update(){this.database.executeSql('SELECT rowid, * FROM "'+this._escapeTableName(this.tableName)+'"',this._queryFinished.bind(this),this._queryError.bind(this));}
_queryFinished(columnNames,values){this.detachChildWidgets();this.element.removeChildren();this._dataGrid=SortableDataGrid.SortableDataGrid.create(columnNames,values,ls`Database`);this._visibleColumnsInput.setVisible(!!this._dataGrid);if(!this._dataGrid){this._emptyWidget=new EmptyWidget.EmptyWidget(ls`The "${this.tableName}"\ntable is empty.`);this._emptyWidget.show(this.element);return;}
this._dataGrid.setStriped(true);this._dataGrid.asWidget().show(this.element);this._dataGrid.autoSizeColumns(5);this._columnsMap=new Map();for(let i=1;i<columnNames.length;++i){this._columnsMap.set(columnNames[i],String(i));}
this._lastVisibleColumns='';const visibleColumnsText=this._visibleColumnsSetting.get()[this.tableName]||'';this._visibleColumnsInput.setValue(visibleColumnsText);this._onVisibleColumnsChanged();}
_onVisibleColumnsChanged(){if(!this._dataGrid){return;}
const text=this._visibleColumnsInput.value();const parts=text.split(/[\s,]+/);const matches=new Set();const columnsVisibility={};columnsVisibility['0']=true;for(let i=0;i<parts.length;++i){const part=parts[i];if(this._columnsMap.has(part)){matches.add(part);columnsVisibility[this._columnsMap.get(part)]=true;}}
const newVisibleColumns=[...matches].sort().join(', ');if(newVisibleColumns.length===0){for(const v of this._columnsMap.values()){columnsVisibility[v]=true;}}
if(newVisibleColumns===this._lastVisibleColumns){return;}
const visibleColumnsRegistry=this._visibleColumnsSetting.get();visibleColumnsRegistry[this.tableName]=text;this._visibleColumnsSetting.set(visibleColumnsRegistry);this._dataGrid.setColumnsVisiblity(columnsVisibility);this._lastVisibleColumns=newVisibleColumns;}
_queryError(error){this.detachChildWidgets();this.element.removeChildren();const errorMsgElement=createElement('div');errorMsgElement.className='storage-table-error';errorMsgElement.textContent=ls`An error occurred trying to\nread the "${this.tableName}" table.`;this.element.appendChild(errorMsgElement);}
_refreshButtonClicked(event){this.update();}}
var DatabaseTableView$1=Object.freeze({__proto__:null,DatabaseTableView:DatabaseTableView});class IDBDatabaseView extends Widget.VBox{constructor(model,database){super();this._model=model;const databaseName=database?database.databaseId.name:ls`Loading…`;this._reportView=new ReportView.ReportView(databaseName);this._reportView.show(this.contentElement);const bodySection=this._reportView.appendSection('');this._securityOriginElement=bodySection.appendField(ls`Security origin`);this._versionElement=bodySection.appendField(ls`Version`);this._objectStoreCountElement=bodySection.appendField(ls`Object stores`);const footer=this._reportView.appendSection('').appendRow();this._clearButton=UIUtils.createTextButton(ls`Delete database`,()=>this._deleteDatabase(),ls`Delete database`);footer.appendChild(this._clearButton);this._refreshButton=UIUtils.createTextButton(ls`Refresh database`,()=>this._refreshDatabaseButtonClicked(),ls`Refresh database`);footer.appendChild(this._refreshButton);if(database){this.update(database);}}
_refreshDatabase(){this._securityOriginElement.textContent=this._database.databaseId.securityOrigin;this._versionElement.textContent=this._database.version;this._objectStoreCountElement.textContent=Object.keys(this._database.objectStores).length;}
_refreshDatabaseButtonClicked(){this._model.refreshDatabase(this._database.databaseId);}
update(database){this._database=database;this._reportView.setTitle(this._database.databaseId.name);this._refreshDatabase();this._updatedForTests();}
_updatedForTests(){}
async _deleteDatabase(){const ok=await UIUtils.ConfirmDialog.show(UIString.UIString('Please confirm delete of "%s" database.',this._database.databaseId.name),this.element);if(ok){this._model.deleteDatabase(this._database.databaseId);}}}
class IDBDataView extends View.SimpleView{constructor(model,databaseId,objectStore,index,refreshObjectStoreCallback){super(UIString.UIString('IDB'));this.registerRequiredCSS('resources/indexedDBViews.css');this._model=model;this._databaseId=databaseId;this._isIndex=!!index;this._refreshObjectStoreCallback=refreshObjectStoreCallback;this.element.classList.add('indexed-db-data-view','storage-view');this._refreshButton=new Toolbar.ToolbarButton(UIString.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._refreshButtonClicked,this);this._deleteSelectedButton=new Toolbar.ToolbarButton(UIString.UIString('Delete selected'),'largeicon-delete');this._deleteSelectedButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._deleteButtonClicked(null);});this._clearButton=new Toolbar.ToolbarButton(UIString.UIString('Clear object store'),'largeicon-clear');this._clearButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._clearButtonClicked(event);},this);this._needsRefresh=new Toolbar.ToolbarItem(UIUtils.createIconLabel(UIString.UIString('Data may be stale'),'smallicon-warning'));this._needsRefresh.setVisible(false);this._needsRefresh.setTitle(UIString.UIString('Some entries may have been modified'));this._createEditorToolbar();this._pageSize=50;this._skipCount=0;this.update(objectStore,index);this._entries=[];}
_createDataGrid(){const keyPath=this._isIndex?this._index.keyPath:this._objectStore.keyPath;const columns=([]);columns.push({id:'number',title:UIString.UIString('#'),sortable:false,width:'50px'});columns.push({id:'key',titleDOMFragment:this._keyColumnHeaderFragment(UIString.UIString('Key'),keyPath),sortable:false});if(this._isIndex){columns.push({id:'primaryKey',titleDOMFragment:this._keyColumnHeaderFragment(UIString.UIString('Primary key'),this._objectStore.keyPath),sortable:false});}
columns.push({id:'value',title:UIString.UIString('Value'),sortable:false});const dataGrid=new DataGrid.DataGridImpl({displayName:ls`Indexed DB`,columns,deleteCallback:this._deleteButtonClicked.bind(this),refreshCallback:this._updateData.bind(this,true)});dataGrid.setStriped(true);dataGrid.addEventListener(DataGrid.Events.SelectedNode,event=>this._updateToolbarEnablement(),this);return dataGrid;}
_keyColumnHeaderFragment(prefix,keyPath){const keyColumnHeaderFragment=createDocumentFragment();keyColumnHeaderFragment.createTextChild(prefix);if(keyPath===null){return keyColumnHeaderFragment;}
keyColumnHeaderFragment.createTextChild(' ('+UIString.UIString('Key path: '));if(Array.isArray(keyPath)){keyColumnHeaderFragment.createTextChild('[');for(let i=0;i<keyPath.length;++i){if(i!==0){keyColumnHeaderFragment.createTextChild(', ');}
keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPath[i]));}
keyColumnHeaderFragment.createTextChild(']');}else{const keyPathString=(keyPath);keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPathString));}
keyColumnHeaderFragment.createTextChild(')');return keyColumnHeaderFragment;}
_keyPathStringFragment(keyPathString){const keyPathStringFragment=createDocumentFragment();keyPathStringFragment.createTextChild('"');const keyPathSpan=keyPathStringFragment.createChild('span','source-code indexed-db-key-path');keyPathSpan.textContent=keyPathString;keyPathStringFragment.createTextChild('"');return keyPathStringFragment;}
_createEditorToolbar(){const editorToolbar=new Toolbar.Toolbar('data-view-toolbar',this.element);editorToolbar.appendToolbarItem(this._refreshButton);editorToolbar.appendToolbarItem(new Toolbar.ToolbarSeparator());this._pageBackButton=new Toolbar.ToolbarButton(UIString.UIString('Show previous page'),'largeicon-play-back');this._pageBackButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._pageBackButtonClicked,this);editorToolbar.appendToolbarItem(this._pageBackButton);this._pageForwardButton=new Toolbar.ToolbarButton(UIString.UIString('Show next page'),'largeicon-play');this._pageForwardButton.setEnabled(false);this._pageForwardButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._pageForwardButtonClicked,this);editorToolbar.appendToolbarItem(this._pageForwardButton);this._keyInput=new Toolbar.ToolbarInput(ls`Start from key`,'',0.5);this._keyInput.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,this._updateData.bind(this,false));editorToolbar.appendToolbarItem(this._keyInput);editorToolbar.appendToolbarItem(new Toolbar.ToolbarSeparator());editorToolbar.appendToolbarItem(this._clearButton);editorToolbar.appendToolbarItem(this._deleteSelectedButton);editorToolbar.appendToolbarItem(this._needsRefresh);}
_pageBackButtonClicked(event){this._skipCount=Math.max(0,this._skipCount-this._pageSize);this._updateData(false);}
_pageForwardButtonClicked(event){this._skipCount=this._skipCount+this._pageSize;this._updateData(false);}
_populateContextMenu(contextMenu,gridNode){const node=(gridNode);if(node.valueObjectPresentation){contextMenu.revealSection().appendItem(ls`Expand Recursively`,()=>{node.valueObjectPresentation.objectTreeElement().expandRecursively();});contextMenu.revealSection().appendItem(ls`Collapse`,()=>{node.valueObjectPresentation.objectTreeElement().collapse();});}}
refreshData(){this._updateData(true);}
update(objectStore,index){this._objectStore=objectStore;this._index=index;if(this._dataGrid){this._dataGrid.asWidget().detach();}
this._dataGrid=this._createDataGrid();this._dataGrid.setRowContextMenuCallback(this._populateContextMenu.bind(this));this._dataGrid.asWidget().show(this.element);this._skipCount=0;this._updateData(true);}
_parseKey(keyString){let result;try{result=JSON.parse(keyString);}catch(e){result=keyString;}
return result;}
_updateData(force){const key=this._parseKey(this._keyInput.value());const pageSize=this._pageSize;let skipCount=this._skipCount;let selected=this._dataGrid.selectedNode?this._dataGrid.selectedNode.data['number']:0;selected=Math.max(selected,this._skipCount);this._refreshButton.setEnabled(false);this._clearButton.setEnabled(!this._isIndex);if(!force&&this._lastKey===key&&this._lastPageSize===pageSize&&this._lastSkipCount===skipCount){return;}
if(this._lastKey!==key||this._lastPageSize!==pageSize){skipCount=0;this._skipCount=0;}
this._lastKey=key;this._lastPageSize=pageSize;this._lastSkipCount=skipCount;function callback(entries,hasMore){this._refreshButton.setEnabled(true);this.clear();this._entries=entries;let selectedNode=null;for(let i=0;i<entries.length;++i){const data={};data['number']=i+skipCount;data['key']=entries[i].key;data['primaryKey']=entries[i].primaryKey;data['value']=entries[i].value;const node=new IDBDataGridNode(data);this._dataGrid.rootNode().appendChild(node);if(data['number']<=selected){selectedNode=node;}}
if(selectedNode){selectedNode.select();}
this._pageBackButton.setEnabled(!!skipCount);this._pageForwardButton.setEnabled(hasMore);this._needsRefresh.setVisible(false);this._updateToolbarEnablement();this._updatedDataForTests();}
const idbKeyRange=key?window.IDBKeyRange.lowerBound(key):null;if(this._isIndex){this._model.loadIndexData(this._databaseId,this._objectStore.name,this._index.name,idbKeyRange,skipCount,pageSize,callback.bind(this));}else{this._model.loadObjectStoreData(this._databaseId,this._objectStore.name,idbKeyRange,skipCount,pageSize,callback.bind(this));}
this._model.getMetadata(this._databaseId,this._objectStore).then(this._updateSummaryBar.bind(this));}
_updateSummaryBar(metadata){if(!this._summaryBarElement){this._summaryBarElement=this.element.createChild('div','object-store-summary-bar');}
this._summaryBarElement.removeChildren();if(!metadata){return;}
const separator='\u2002\u2758\u2002';const span=this._summaryBarElement.createChild('span');span.textContent=ls`Total entries: ${String(metadata.entriesCount)}`;if(this._objectStore.autoIncrement){span.textContent+=separator;span.textContent+=ls`Key generator value: ${String(metadata.keyGeneratorValue)}`;}}
_updatedDataForTests(){}
_refreshButtonClicked(event){this._updateData(true);}
async _clearButtonClicked(event){this._clearButton.setEnabled(false);await this._model.clearObjectStore(this._databaseId,this._objectStore.name);this._clearButton.setEnabled(true);this._updateData(true);}
markNeedsRefresh(){this._needsRefresh.setVisible(true);}
async _deleteButtonClicked(node){if(!node){node=this._dataGrid.selectedNode;if(!node){return;}}
const key=(this._isIndex?node.data.primaryKey:node.data.key);const keyValue=(key.value);await this._model.deleteEntries(this._databaseId,this._objectStore.name,window.IDBKeyRange.only(keyValue));this._refreshObjectStoreCallback();}
clear(){this._dataGrid.rootNode().removeChildren();this._entries=[];}
_updateToolbarEnablement(){const empty=!this._dataGrid||this._dataGrid.rootNode().children.length===0;this._deleteSelectedButton.setEnabled(!empty&&this._dataGrid.selectedNode!==null);}}
class IDBDataGridNode extends DataGrid.DataGridNode{constructor(data){super(data,false);this.selectable=true;this.valueObjectPresentation=null;}
createCell(columnIdentifier){const cell=super.createCell(columnIdentifier);const value=(this.data[columnIdentifier]);switch(columnIdentifier){case'value':{cell.removeChildren();const objectPropSection=ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPropertiesSection(value,undefined,true,true);cell.appendChild(objectPropSection.element);this.valueObjectPresentation=objectPropSection;break;}
case'key':case'primaryKey':{cell.removeChildren();const objectElement=ObjectPropertiesSection.ObjectPropertiesSection.defaultObjectPresentation(value,undefined,true,true);cell.appendChild(objectElement);break;}
default:{}}
return cell;}}
var IndexedDBViews=Object.freeze({__proto__:null,IDBDatabaseView:IDBDatabaseView,IDBDataView:IDBDataView,IDBDataGridNode:IDBDataGridNode});class ServiceWorkerCacheView extends View.SimpleView{constructor(model,cache){super(UIString.UIString('Cache'));this.registerRequiredCSS('resources/serviceWorkerCacheViews.css');this._model=model;this._entriesForTest=null;this.element.classList.add('service-worker-cache-data-view');this.element.classList.add('storage-view');const editorToolbar=new Toolbar.Toolbar('data-view-toolbar',this.element);this._splitWidget=new SplitWidget.SplitWidget(false,false);this._splitWidget.show(this.element);this._previewPanel=new Widget.VBox();const resizer=this._previewPanel.element.createChild('div','cache-preview-panel-resizer');this._splitWidget.setMainWidget(this._previewPanel);this._splitWidget.installResizer(resizer);this._preview=null;this._cache=cache;this._dataGrid=null;this._refreshThrottler=new Throttler.Throttler(300);this._refreshButton=new Toolbar.ToolbarButton(UIString.UIString('Refresh'),'largeicon-refresh');this._refreshButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._refreshButtonClicked,this);editorToolbar.appendToolbarItem(this._refreshButton);this._deleteSelectedButton=new Toolbar.ToolbarButton(UIString.UIString('Delete Selected'),'largeicon-delete');this._deleteSelectedButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._deleteButtonClicked(null);});editorToolbar.appendToolbarItem(this._deleteSelectedButton);const entryPathFilterBox=new Toolbar.ToolbarInput(ls`Filter by Path`,'',1);editorToolbar.appendToolbarItem(entryPathFilterBox);const entryPathFilterThrottler=new Throttler.Throttler(300);this._entryPathFilter='';entryPathFilterBox.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,()=>{entryPathFilterThrottler.schedule(()=>{this._entryPathFilter=entryPathFilterBox.value();return this._updateData(true);});});this._returnCount=(null);this._summaryBarElement=(null);this._loadingPromise=(null);this.update(cache);}
_resetDataGrid(){if(this._dataGrid){this._dataGrid.asWidget().detach();}
this._dataGrid=this._createDataGrid();const dataGridWidget=this._dataGrid.asWidget();this._splitWidget.setSidebarWidget(dataGridWidget);dataGridWidget.setMinimumSize(0,250);}
wasShown(){this._model.addEventListener(ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this._cacheContentUpdated,this);this._updateData(true);}
willHide(){this._model.removeEventListener(ServiceWorkerCacheModel.Events.CacheStorageContentUpdated,this._cacheContentUpdated,this);}
_showPreview(preview){if(preview&&this._preview===preview){return;}
if(this._preview){this._preview.detach();}
if(!preview){preview=new EmptyWidget.EmptyWidget(UIString.UIString('Select a cache entry above to preview'));}
this._preview=preview;this._preview.show(this._previewPanel.element);}
_createDataGrid(){const columns=([{id:'number',title:'#',sortable:false,width:'3px'},{id:'name',title:UIString.UIString('Name'),weight:4,sortable:true},{id:'responseType',title:ls`Response-Type`,weight:1,align:DataGrid.Align.Right,sortable:true},{id:'contentType',title:UIString.UIString('Content-Type'),weight:1,sortable:true},{id:'contentLength',title:UIString.UIString('Content-Length'),weight:1,align:DataGrid.Align.Right,sortable:true},{id:'responseTime',title:UIString.UIString('Time Cached'),width:'12em',weight:1,align:DataGrid.Align.Right,sortable:true}]);const dataGrid=new DataGrid.DataGridImpl({displayName:ls`Service Worker Cache`,columns,deleteCallback:this._deleteButtonClicked.bind(this),refreshCallback:this._updateData.bind(this,true)});dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortingChanged,this);dataGrid.addEventListener(DataGrid.Events.SelectedNode,event=>{this._previewCachedResponse(event.data.data);},this);dataGrid.setStriped(true);return dataGrid;}
_sortingChanged(){if(!this._dataGrid){return;}
const accending=this._dataGrid.isSortOrderAscending();const columnId=this._dataGrid.sortColumnId();let comparator;if(columnId==='name'){comparator=(a,b)=>a._name.localeCompare(b._name);}else if(columnId==='contentType'){comparator=(a,b)=>a.data.mimeType.localeCompare(b.data.mimeType);}else if(columnId==='contentLength'){comparator=(a,b)=>a.data.resourceSize-b.data.resourceSize;}else if(columnId==='responseTime'){comparator=(a,b)=>a.data.endTime-b.data.endTime;}else if(columnId==='responseType'){comparator=(a,b)=>a._responseType.localeCompare(b._responseType);}
const children=this._dataGrid.rootNode().children.slice();this._dataGrid.rootNode().removeChildren();children.sort((a,b)=>{const result=comparator(a,b);return accending?result:-result;});children.forEach(child=>this._dataGrid.rootNode().appendChild(child));}
async _deleteButtonClicked(node){if(!node){node=this._dataGrid&&this._dataGrid.selectedNode;if(!node){return;}}
await this._model.deleteCacheEntry(this._cache,(node.data.url()));node.remove();}
update(cache){this._cache=cache;this._resetDataGrid();this._updateData(true);}
_updateSummaryBar(){if(!this._summaryBarElement){this._summaryBarElement=this.element.createChild('div','cache-storage-summary-bar');}
this._summaryBarElement.removeChildren();const span=this._summaryBarElement.createChild('span');if(this._entryPathFilter){span.textContent=ls`Matching entries: ${this._returnCount}`;}else{span.textContent=ls`Total entries: ${this._returnCount}`;}}
_updateDataCallback(skipCount,entries,returnCount){const selected=this._dataGrid.selectedNode&&this._dataGrid.selectedNode.data.url();this._refreshButton.setEnabled(true);this._entriesForTest=entries;this._returnCount=returnCount;this._updateSummaryBar();const oldEntries=new Map();const rootNode=this._dataGrid.rootNode();for(const node of rootNode.children){oldEntries.set(node.data.url,node);}
rootNode.removeChildren();let selectedNode=null;for(let i=0;i<entries.length;++i){const entry=entries[i];let node=oldEntries.get(entry.requestURL);if(!node||node.data.responseTime!==entry.responseTime){node=new DataGridNode(i,this._createRequest(entry),entry.responseType);node.selectable=true;}else{node.data.number=i;}
rootNode.appendChild(node);if(entry.requestURL===selected){selectedNode=node;}}
if(!selectedNode){this._showPreview(null);}else{selectedNode.revealAndSelect();}
this._updatedForTest();}
async _updateData(force){if(!force&&this._loadingPromise){return this._loadingPromise;}
this._refreshButton.setEnabled(false);if(this._loadingPromise){return this._loadingPromise;}
this._loadingPromise=new Promise(resolve=>{this._model.loadAllCacheData(this._cache,this._entryPathFilter,(entries,returnCount)=>{resolve([entries,returnCount]);});});const[entries,returnCount]=await this._loadingPromise;this._updateDataCallback(0,entries,returnCount);this._loadingPromise=null;}
_refreshButtonClicked(event){this._updateData(true);}
_cacheContentUpdated(event){const nameAndOrigin=event.data;if(this._cache.securityOrigin!==nameAndOrigin.origin||this._cache.cacheName!==nameAndOrigin.cacheName){return;}
this._refreshThrottler.schedule(()=>Promise.resolve(this._updateData(true)),true);}
async _previewCachedResponse(request){let preview=request[ServiceWorkerCacheView._previewSymbol];if(!preview){preview=new RequestView(request);request[ServiceWorkerCacheView._previewSymbol]=preview;}
if(request===this._dataGrid.selectedNode.data){this._showPreview(preview);}}
_createRequest(entry){const request=new NetworkRequest.NetworkRequest('cache-storage-'+entry.requestURL,entry.requestURL,'','','',null);request.requestMethod=entry.requestMethod;request.setRequestHeaders(entry.requestHeaders);request.statusCode=entry.responseStatus;request.statusText=entry.responseStatusText;request.protocol=new ParsedURL.ParsedURL(entry.requestURL).scheme;request.responseHeaders=entry.responseHeaders;request.setRequestHeadersText('');request.endTime=entry.responseTime;let header=entry.responseHeaders.find(header=>header.name.toLowerCase()==='content-type');const contentType=header?header.value:NetworkRequest.MIME_TYPE.PLAIN;request.mimeType=(contentType);header=entry.responseHeaders.find(header=>header.name.toLowerCase()==='content-length');request.resourceSize=(header&&header.value)|0;let resourceType=ResourceType.ResourceType.fromMimeType(contentType);if(!resourceType){resourceType=ResourceType.ResourceType.fromURL(entry.requestURL)||ResourceType.resourceTypes.Other;}
request.setResourceType(resourceType);request.setContentDataProvider(this._requestContent.bind(this,request));return request;}
async _requestContent(request){const isText=request.resourceType().isTextType();const contentData={error:null,content:null,encoded:!isText};const response=await this._cache.requestCachedResponse(request.url(),request.requestHeaders());if(response){contentData.content=isText?window.atob(response.body):response.body;}
return contentData;}
_updatedForTest(){}}
ServiceWorkerCacheView._previewSymbol=Symbol('preview');class DataGridNode extends DataGrid.DataGridNode{constructor(number,request,responseType){super(request);this._number=number;const parsed=new ParsedURL.ParsedURL(request.url());if(parsed.isValid){this._name=StringUtilities.trimURL(request.url(),parsed.domain());}else{this._name=request.url();}
this._request=request;this._responseType=responseType;}
createCell(columnId){const cell=this.createTD(columnId);let value;if(columnId==='number'){value=String(this._number);}else if(columnId==='name'){value=this._name;}else if(columnId==='responseType'){if(this._responseType==='opaqueResponse'){value='opaque';}else if(this._responseType==='opaqueRedirect'){value='opaqueredirect';}else{value=this._responseType;}}else if(columnId==='contentType'){value=this._request.mimeType;}else if(columnId==='contentLength'){value=(this._request.resourceSize|0).toLocaleString('en-US');}else if(columnId==='responseTime'){value=new Date(this._request.endTime*1000).toLocaleString();}
DataGrid.DataGridImpl.setElementText(cell,value||'',true);cell.title=this._request.url();return cell;}}
class RequestView extends Widget.VBox{constructor(request){super();this._tabbedPane=new TabbedPane.TabbedPane();this._tabbedPane.addEventListener(TabbedPane.Events.TabSelected,this._tabSelected,this);this._resourceViewTabSetting=Settings.Settings.instance().createSetting('cacheStorageViewTab','preview');this._tabbedPane.appendTab('headers',UIString.UIString('Headers'),new RequestHeadersView.RequestHeadersView(request));this._tabbedPane.appendTab('preview',UIString.UIString('Preview'),new RequestPreviewView.RequestPreviewView(request));this._tabbedPane.show(this.element);}
wasShown(){super.wasShown();this._selectTab();}
_selectTab(tabId){if(!tabId){tabId=this._resourceViewTabSetting.get();}
if(!this._tabbedPane.selectTab(tabId)){this._tabbedPane.selectTab('headers');}}
_tabSelected(event){if(!event.data.isUserGesture){return;}
this._resourceViewTabSetting.set(event.data.tabId);}}
var ServiceWorkerCacheViews=Object.freeze({__proto__:null,ServiceWorkerCacheView:ServiceWorkerCacheView,DataGridNode:DataGridNode,RequestView:RequestView});class ServiceWorkersView extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('resources/serviceWorkersView.css');this._currentWorkersView=new ReportView.ReportView(UIString.UIString('Service Workers'));this._currentWorkersView.setBodyScrollable(false);this.contentElement.classList.add('service-worker-list');this._currentWorkersView.show(this.contentElement);this._currentWorkersView.element.classList.add('service-workers-this-origin');this._toolbar=this._currentWorkersView.createToolbar();this._toolbar.makeWrappable(true);this._sections=new Map();this._registrationSymbol=Symbol('Resources.ServiceWorkersView');this._manager=null;this._securityOriginManager=null;this._filterThrottler=new Throttler.Throttler(300);this._otherWorkers=this.contentElement.createChild('div','service-workers-other-origin');this._otherSWFilter=this._otherWorkers.createChild('div','service-worker-filter');this._otherSWFilter.setAttribute('tabindex',0);this._otherSWFilter.setAttribute('role','switch');this._otherSWFilter.setAttribute('aria-checked',false);const filterLabel=this._otherSWFilter.createChild('label','service-worker-filter-label');filterLabel.textContent=UIString.UIString('Service workers from other origins');self.onInvokeElement(this._otherSWFilter,event=>{if(event.target===this._otherSWFilter||event.target===filterLabel){this._toggleFilter();}});const toolbar=new Toolbar.Toolbar('service-worker-filter-toolbar',this._otherSWFilter);this._filter=new Toolbar.ToolbarInput(ls`Filter service worker`,'',1);this._filter.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,()=>this._filterChanged());toolbar.appendToolbarItem(this._filter);this._otherWorkersView=new ReportView.ReportView();this._otherWorkersView.setBodyScrollable(false);this._otherWorkersView.show(this._otherWorkers);this._otherWorkersView.element.classList.add('service-workers-for-other-origins');this._updateCollapsedStyle();this._toolbar.appendToolbarItem(ThrottlingManager.throttlingManager().createOfflineToolbarCheckbox());const updateOnReloadSetting=Settings.Settings.instance().createSetting('serviceWorkerUpdateOnReload',false);updateOnReloadSetting.setTitle(UIString.UIString('Update on reload'));const forceUpdate=new Toolbar.ToolbarSettingCheckbox(updateOnReloadSetting,ls`On page reload, force the service worker to update, and activate it`);this._toolbar.appendToolbarItem(forceUpdate);const bypassServiceWorkerSetting=Settings.Settings.instance().createSetting('bypassServiceWorker',false);bypassServiceWorkerSetting.setTitle(UIString.UIString('Bypass for network'));const fallbackToNetwork=new Toolbar.ToolbarSettingCheckbox(bypassServiceWorkerSetting,ls`Bypass the service worker and load resources from the network`);this._toolbar.appendToolbarItem(fallbackToNetwork);this._eventListeners=new Map();SDKModel.TargetManager.instance().observeModels(ServiceWorkerManager.ServiceWorkerManager,this);this._updateListVisibility();}
modelAdded(serviceWorkerManager){if(this._manager){return;}
this._manager=serviceWorkerManager;this._securityOriginManager=serviceWorkerManager.target().model(SecurityOriginManager.SecurityOriginManager);for(const registration of this._manager.registrations().values()){this._updateRegistration(registration);}
this._eventListeners.set(serviceWorkerManager,[this._manager.addEventListener(ServiceWorkerManager.Events.RegistrationUpdated,this._registrationUpdated,this),this._manager.addEventListener(ServiceWorkerManager.Events.RegistrationDeleted,this._registrationDeleted,this),this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginAdded,this._updateSectionVisibility,this),this._securityOriginManager.addEventListener(SecurityOriginManager.Events.SecurityOriginRemoved,this._updateSectionVisibility,this),]);}
modelRemoved(serviceWorkerManager){if(!this._manager||this._manager!==serviceWorkerManager){return;}
EventTarget.EventTarget.removeEventListeners(this._eventListeners.get(serviceWorkerManager));this._eventListeners.delete(serviceWorkerManager);this._manager=null;this._securityOriginManager=null;}
_getTimeStamp(registration){const versions=registration.versionsByMode();let timestamp=0;const active=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Active);const installing=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing);const waiting=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting);const redundant=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant);if(active){timestamp=active.scriptResponseTime;}else if(waiting){timestamp=waiting.scriptResponseTime;}else if(installing){timestamp=installing.scriptResponseTime;}else if(redundant){timestamp=redundant.scriptResponseTime;}
return timestamp;}
_updateSectionVisibility(){let hasOthers=false;let hasThis=false;const movedSections=[];for(const section of this._sections.values()){const expectedView=this._getReportViewForOrigin(section._registration.securityOrigin);hasOthers|=expectedView===this._otherWorkersView;hasThis|=expectedView===this._currentWorkersView;if(section._section.parentWidget()!==expectedView){movedSections.push(section);}}
for(const section of movedSections){const registration=section._registration;this._removeRegistrationFromList(registration);this._updateRegistration(registration,true);}
this._currentWorkersView.sortSections((a,b)=>{const aTimestamp=this._getTimeStamp(a[this._registrationSymbol]);const bTimestamp=this._getTimeStamp(b[this._registrationSymbol]);return bTimestamp-aTimestamp;});const scorer=new Sources.FilePathScoreFunction(this._filter.value());this._otherWorkersView.sortSections((a,b)=>{const cmp=scorer.score(b.title(),null)-scorer.score(a.title(),null);return cmp===0?a.title().localeCompare(b.title()):cmp;});for(const section of this._sections.values()){if(section._section.parentWidget()===this._currentWorkersView||this._isRegistrationVisible(section._registration)){section._section.showWidget();}else{section._section.hideWidget();}}
this.contentElement.classList.toggle('service-worker-has-current',!!hasThis);this._otherWorkers.classList.toggle('hidden',!hasOthers);this._updateListVisibility();}
_registrationUpdated(event){const registration=(event.data);this._updateRegistration(registration);this._gcRegistrations();}
_gcRegistrations(){let hasNonDeletedRegistrations=false;const securityOrigins=new Set(this._securityOriginManager.securityOrigins());for(const registration of this._manager.registrations().values()){if(!securityOrigins.has(registration.securityOrigin)&&!this._isRegistrationVisible(registration)){continue;}
if(!registration.canBeRemoved()){hasNonDeletedRegistrations=true;break;}}
if(!hasNonDeletedRegistrations){return;}
for(const registration of this._manager.registrations().values()){const visible=securityOrigins.has(registration.securityOrigin)||this._isRegistrationVisible(registration);if(!visible&&registration.canBeRemoved()){this._removeRegistrationFromList(registration);}}}
_getReportViewForOrigin(origin){if(this._securityOriginManager.securityOrigins().includes(origin)||this._securityOriginManager.unreachableMainSecurityOrigin()===origin){return this._currentWorkersView;}
return this._otherWorkersView;}
_updateRegistration(registration,skipUpdate){let section=this._sections.get(registration);if(!section){const title=registration.scopeURL;const uiSection=this._getReportViewForOrigin(registration.securityOrigin).appendSection(title);uiSection.setUiGroupTitle(ls`Service worker for ${title}`);uiSection[this._registrationSymbol]=registration;section=new Section((this._manager),uiSection,registration);this._sections.set(registration,section);}
if(skipUpdate){return;}
this._updateSectionVisibility();section._scheduleUpdate();}
_registrationDeleted(event){const registration=(event.data);this._removeRegistrationFromList(registration);}
_removeRegistrationFromList(registration){const section=this._sections.get(registration);if(section){section._section.detach();}
this._sections.delete(registration);this._updateSectionVisibility();}
_isRegistrationVisible(registration){const filterString=this._filter.value();if(!filterString||!registration.scopeURL){return true;}
const regex=String.filterRegex(filterString);return registration.scopeURL.match(regex);}
_filterChanged(){this._updateCollapsedStyle();this._filterThrottler.schedule(()=>Promise.resolve(this._updateSectionVisibility()));}
_updateCollapsedStyle(){const expanded=this._otherSWFilter.getAttribute('aria-checked')==='true';this._otherWorkers.classList.toggle('service-worker-filter-collapsed',!expanded);if(expanded){this._otherWorkersView.showWidget();}else{this._otherWorkersView.hideWidget();}
this._otherWorkersView.setHeaderVisible(false);}
_updateListVisibility(){this.contentElement.classList.toggle('service-worker-list-empty',this._sections.size===0);}
_toggleFilter(){const expanded=this._otherSWFilter.getAttribute('aria-checked')==='true';this._otherSWFilter.setAttribute('aria-checked',!expanded);this._filterChanged();}}
class Section{constructor(manager,section,registration){this._manager=manager;this._section=section;this._registration=registration;this._fingerprint=null;this._pushNotificationDataSetting=Settings.Settings.instance().createLocalSetting('pushData',UIString.UIString('Test push message from DevTools.'));this._syncTagNameSetting=Settings.Settings.instance().createLocalSetting('syncTagName','test-tag-from-devtools');this._periodicSyncTagNameSetting=Settings.Settings.instance().createLocalSetting('periodicSyncTagName','test-tag-from-devtools');this._toolbar=section.createToolbar();this._toolbar.renderAsLinks();this._updateButton=new Toolbar.ToolbarButton(UIString.UIString('Update'),undefined,UIString.UIString('Update'));this._updateButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._updateButtonClicked,this);this._toolbar.appendToolbarItem(this._updateButton);this._deleteButton=new Toolbar.ToolbarButton(UIString.UIString('Unregister service worker'),undefined,UIString.UIString('Unregister'));this._deleteButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._unregisterButtonClicked,this);this._toolbar.appendToolbarItem(this._deleteButton);this._sourceField=this._wrapWidget(this._section.appendField(UIString.UIString('Source')));this._statusField=this._wrapWidget(this._section.appendField(UIString.UIString('Status')));this._clientsField=this._wrapWidget(this._section.appendField(UIString.UIString('Clients')));this._createSyncNotificationField(UIString.UIString('Push'),this._pushNotificationDataSetting.get(),UIString.UIString('Push data'),this._push.bind(this));this._createSyncNotificationField(UIString.UIString('Sync'),this._syncTagNameSetting.get(),UIString.UIString('Sync tag'),this._sync.bind(this));this._createSyncNotificationField(ls`Periodic Sync`,this._periodicSyncTagNameSetting.get(),ls`Periodic Sync tag`,tag=>this._periodicSync(tag));this._linkifier=new Linkifier.Linkifier();this._clientInfoCache=new Map();this._throttler=new Throttler.Throttler(500);}
_createSyncNotificationField(label,initialValue,placeholder,callback){const form=this._wrapWidget(this._section.appendField(label)).createChild('form','service-worker-editor-with-button');const editor=form.createChild('input','source-code service-worker-notification-editor');const button=UIUtils.createTextButton(label);button.type='submit';form.appendChild(button);editor.value=initialValue;editor.placeholder=placeholder;ARIAUtils.setAccessibleName(editor,label);form.addEventListener('submit',e=>{callback(editor.value||'');e.consume(true);});}
_scheduleUpdate(){if(ServiceWorkersView._noThrottle){this._update();return;}
this._throttler.schedule(this._update.bind(this));}
_targetForVersionId(versionId){const version=this._manager.findVersion(versionId);if(!version||!version.targetId){return null;}
return SDKModel.TargetManager.instance().targetById(version.targetId);}
_addVersion(versionsStack,icon,label){const installingEntry=versionsStack.createChild('div','service-worker-version');installingEntry.createChild('div',icon);installingEntry.createChild('span').textContent=label;return installingEntry;}
_updateClientsField(version){this._clientsField.removeChildren();this._section.setFieldVisible(UIString.UIString('Clients'),version.controlledClients.length);for(const client of version.controlledClients){const clientLabelText=this._clientsField.createChild('div','service-worker-client');if(this._clientInfoCache.has(client)){this._updateClientInfo(clientLabelText,(this._clientInfoCache.get(client)));}
this._manager.target().targetAgent().getTargetInfo(client).then(this._onClientInfo.bind(this,clientLabelText));}}
_updateSourceField(version){this._sourceField.removeChildren();const fileName=ParsedURL.ParsedURL.extractName(version.scriptURL);const name=this._sourceField.createChild('div','report-field-value-filename');const link=Linkifier.Linkifier.linkifyURL(version.scriptURL,{text:fileName});link.tabIndex=0;name.appendChild(link);if(this._registration.errors.length){const errorsLabel=UIUtils.createIconLabel(String(this._registration.errors.length),'smallicon-error');errorsLabel.classList.add('link');errorsLabel.tabIndex=0;ARIAUtils.setAccessibleName(errorsLabel,ls`${this._registration.errors.length} registration errors`);self.onInvokeElement(errorsLabel,()=>Console.Console.instance().show());name.appendChild(errorsLabel);}
this._sourceField.createChild('div','report-field-value-subtitle').textContent=UIString.UIString('Received %s',new Date(version.scriptResponseTime*1000).toLocaleString());}
_update(){const fingerprint=this._registration.fingerprint();if(fingerprint===this._fingerprint){return Promise.resolve();}
this._fingerprint=fingerprint;this._toolbar.setEnabled(!this._registration.isDeleted);const versions=this._registration.versionsByMode();const scopeURL=this._registration.scopeURL;const title=this._registration.isDeleted?UIString.UIString('%s - deleted',scopeURL):scopeURL;this._section.setTitle(title);const active=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Active);const waiting=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting);const installing=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing);const redundant=versions.get(ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant);this._statusField.removeChildren();const versionsStack=this._statusField.createChild('div','service-worker-version-stack');versionsStack.createChild('div','service-worker-version-stack-bar');if(active){this._updateSourceField(active);const localizedRunningStatus=ServiceWorkerManager.ServiceWorkerVersion.RunningStatus[active.runningStatus];const activeEntry=this._addVersion(versionsStack,'service-worker-active-circle',ls`#${active.id} activated and is ${localizedRunningStatus}`);if(active.isRunning()||active.isStarting()){this._createLink(activeEntry,UIString.UIString('stop'),this._stopButtonClicked.bind(this,active.id));if(!this._targetForVersionId(active.id)){this._createLink(activeEntry,UIString.UIString('inspect'),this._inspectButtonClicked.bind(this,active.id));}}else if(active.isStartable()){this._createLink(activeEntry,UIString.UIString('start'),this._startButtonClicked.bind(this));}
this._updateClientsField(active);}else if(redundant){this._updateSourceField(redundant);this._addVersion(versionsStack,'service-worker-redundant-circle',UIString.UIString('#%s is redundant',redundant.id));this._updateClientsField(redundant);}
if(waiting){const waitingEntry=this._addVersion(versionsStack,'service-worker-waiting-circle',UIString.UIString('#%s waiting to activate',waiting.id));this._createLink(waitingEntry,UIString.UIString('skipWaiting'),this._skipButtonClicked.bind(this));waitingEntry.createChild('div','service-worker-subtitle').textContent=UIString.UIString('Received %s',new Date(waiting.scriptResponseTime*1000).toLocaleString());if(!this._targetForVersionId(waiting.id)&&(waiting.isRunning()||waiting.isStarting())){this._createLink(waitingEntry,UIString.UIString('inspect'),this._inspectButtonClicked.bind(this,waiting.id));}}
if(installing){const installingEntry=this._addVersion(versionsStack,'service-worker-installing-circle',UIString.UIString('#%s trying to install',installing.id));installingEntry.createChild('div','service-worker-subtitle').textContent=UIString.UIString('Received %s',new Date(installing.scriptResponseTime*1000).toLocaleString());if(!this._targetForVersionId(installing.id)&&(installing.isRunning()||installing.isStarting())){this._createLink(installingEntry,UIString.UIString('inspect'),this._inspectButtonClicked.bind(this,installing.id));}}
return Promise.resolve();}
_createLink(parent,title,listener,className,useCapture){const button=parent.createChild('button',className);button.classList.add('link');button.textContent=title;button.tabIndex=0;button.addEventListener('click',listener,useCapture);return button;}
_unregisterButtonClicked(event){this._manager.deleteRegistration(this._registration.id);}
_updateButtonClicked(event){this._manager.updateRegistration(this._registration.id);}
_push(data){this._pushNotificationDataSetting.set(data);this._manager.deliverPushMessage(this._registration.id,data);}
_sync(tag){this._syncTagNameSetting.set(tag);this._manager.dispatchSyncEvent(this._registration.id,tag,true);}
_periodicSync(tag){this._periodicSyncTagNameSetting.set(tag);this._manager.dispatchPeriodicSyncEvent(this._registration.id,tag);}
_onClientInfo(element,targetInfo){if(!targetInfo){return;}
this._clientInfoCache.set(targetInfo.targetId,targetInfo);this._updateClientInfo(element,targetInfo);}
_updateClientInfo(element,targetInfo){if(targetInfo.type!=='page'&&targetInfo.type==='iframe'){const clientString=element.createChild('span','service-worker-client-string');clientString.createTextChild(ls`Worker: ${targetInfo.url}`);return;}
element.removeChildren();const clientString=element.createChild('span','service-worker-client-string');clientString.createTextChild(targetInfo.url);this._createLink(element,ls`focus`,this._activateTarget.bind(this,targetInfo.targetId),'service-worker-client-focus-link');}
_activateTarget(targetId){this._manager.target().targetAgent().activateTarget(targetId);}
_startButtonClicked(){this._manager.startWorker(this._registration.scopeURL);}
_skipButtonClicked(){this._manager.skipWaiting(this._registration.scopeURL);}
_stopButtonClicked(versionId){this._manager.stopWorker(versionId);}
_inspectButtonClicked(versionId){this._manager.inspectWorker(versionId);}
_wrapWidget(container){const shadowRoot=Utils.createShadowRootWithCoreStyles(container);Utils.appendStyle(shadowRoot,'resources/serviceWorkersView.css');const contentElement=createElement('div');shadowRoot.appendChild(contentElement);return contentElement;}}
var ServiceWorkersView$1=Object.freeze({__proto__:null,ServiceWorkersView:ServiceWorkersView,Section:Section});class ApplicationPanelSidebar extends Widget.VBox{constructor(panel){super();this._panel=panel;this._sidebarTree=new TreeOutline.TreeOutlineInShadow();this._sidebarTree.element.classList.add('resources-sidebar');this._sidebarTree.registerRequiredCSS('resources/resourcesSidebar.css');this._sidebarTree.element.classList.add('filter-all');this._sidebarTree.addEventListener(TreeOutline.Events.ElementAttached,this._treeElementAdded,this);this.contentElement.appendChild(this._sidebarTree.element);this._applicationTreeElement=this._addSidebarSection(UIString.UIString('Application'));const manifestTreeElement=new AppManifestTreeElement(panel);this._applicationTreeElement.appendChild(manifestTreeElement);this.serviceWorkersTreeElement=new ServiceWorkersTreeElement(panel);this._applicationTreeElement.appendChild(this.serviceWorkersTreeElement);const clearStorageTreeElement=new ClearStorageTreeElement(panel);this._applicationTreeElement.appendChild(clearStorageTreeElement);const storageTreeElement=this._addSidebarSection(UIString.UIString('Storage'));this.localStorageListTreeElement=new StorageCategoryTreeElement(panel,UIString.UIString('Local Storage'),'LocalStorage');this.localStorageListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/localstorage?utm_source=devtools');const localStorageIcon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.localStorageListTreeElement.setLeadingIcons([localStorageIcon]);storageTreeElement.appendChild(this.localStorageListTreeElement);this.sessionStorageListTreeElement=new StorageCategoryTreeElement(panel,UIString.UIString('Session Storage'),'SessionStorage');this.sessionStorageListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/sessionstorage?utm_source=devtools');const sessionStorageIcon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.sessionStorageListTreeElement.setLeadingIcons([sessionStorageIcon]);storageTreeElement.appendChild(this.sessionStorageListTreeElement);this.indexedDBListTreeElement=new IndexedDBTreeElement(panel);this.indexedDBListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/indexeddb?utm_source=devtools');storageTreeElement.appendChild(this.indexedDBListTreeElement);this.databasesListTreeElement=new StorageCategoryTreeElement(panel,UIString.UIString('Web SQL'),'Databases');this.databasesListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/websql?utm_source=devtools');const databaseIcon=Icon.Icon.create('mediumicon-database','resource-tree-item');this.databasesListTreeElement.setLeadingIcons([databaseIcon]);storageTreeElement.appendChild(this.databasesListTreeElement);this.cookieListTreeElement=new StorageCategoryTreeElement(panel,UIString.UIString('Cookies'),'Cookies');this.cookieListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/cookies?utm_source=devtools');const cookieIcon=Icon.Icon.create('mediumicon-cookie','resource-tree-item');this.cookieListTreeElement.setLeadingIcons([cookieIcon]);storageTreeElement.appendChild(this.cookieListTreeElement);const cacheTreeElement=this._addSidebarSection(UIString.UIString('Cache'));this.cacheStorageListTreeElement=new ServiceWorkerCacheTreeElement(panel);cacheTreeElement.appendChild(this.cacheStorageListTreeElement);this.applicationCacheListTreeElement=new StorageCategoryTreeElement(panel,UIString.UIString('Application Cache'),'ApplicationCache');this.applicationCacheListTreeElement.setLink('https://developers.google.com/web/tools/chrome-devtools/storage/applicationcache?utm_source=devtools');const applicationCacheIcon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.applicationCacheListTreeElement.setLeadingIcons([applicationCacheIcon]);cacheTreeElement.appendChild(this.applicationCacheListTreeElement);if(Root.Runtime.experiments.isEnabled('backgroundServices')){const backgroundServiceTreeElement=this._addSidebarSection(ls`Background Services`);this.backgroundFetchTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.BackgroundFetch);backgroundServiceTreeElement.appendChild(this.backgroundFetchTreeElement);this.backgroundSyncTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.BackgroundSync);backgroundServiceTreeElement.appendChild(this.backgroundSyncTreeElement);if(Root.Runtime.experiments.isEnabled('backgroundServicesNotifications')){this.notificationsTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.Notifications);backgroundServiceTreeElement.appendChild(this.notificationsTreeElement);}
if(Root.Runtime.experiments.isEnabled('backgroundServicesPaymentHandler')){this.paymentHandlerTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.PaymentHandler);backgroundServiceTreeElement.appendChild(this.paymentHandlerTreeElement);}
this.periodicBackgroundSyncTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.PeriodicBackgroundSync);backgroundServiceTreeElement.appendChild(this.periodicBackgroundSyncTreeElement);if(Root.Runtime.experiments.isEnabled('backgroundServicesPushMessaging')){this.pushMessagingTreeElement=new BackgroundServiceTreeElement(panel,Protocol.BackgroundService.ServiceName.PushMessaging);backgroundServiceTreeElement.appendChild(this.pushMessagingTreeElement);}}
this._resourcesSection=new ResourcesSection(panel,this._addSidebarSection(UIString.UIString('Frames')));this._databaseTableViews=new Map();this._databaseQueryViews=new Map();this._databaseTreeElements=new Map();this._domStorageTreeElements=new Map();this._domains={};this._sidebarTree.contentElement.addEventListener('mousemove',this._onmousemove.bind(this),false);this._sidebarTree.contentElement.addEventListener('mouseleave',this._onmouseleave.bind(this),false);SDKModel.TargetManager.instance().observeTargets(this);SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);const selection=this._panel.lastSelectedItemPath();if(!selection.length){manifestTreeElement.select();}}
_addSidebarSection(title){const treeElement=new TreeOutline.TreeElement(title,true);treeElement.listItemElement.classList.add('storage-group-list-item');treeElement.setCollapsible(false);treeElement.selectable=false;this._sidebarTree.appendChild(treeElement);return treeElement;}
targetAdded(target){if(this._target){return;}
this._target=target;this._databaseModel=target.model(DatabaseModel);if(this._databaseModel){this._databaseModel.addEventListener(Events$2.DatabaseAdded,this._databaseAdded,this);this._databaseModel.addEventListener(Events$2.DatabasesRemoved,this._resetWebSQL,this);}
const resourceTreeModel=target.model(ResourceTreeModel.ResourceTreeModel);if(!resourceTreeModel){return;}
if(resourceTreeModel.cachedResourcesLoaded()){this._initialize();}
resourceTreeModel.addEventListener(ResourceTreeModel.Events.CachedResourcesLoaded,this._initialize,this);resourceTreeModel.addEventListener(ResourceTreeModel.Events.WillLoadCachedResources,this._resetWithFrames,this);}
targetRemoved(target){if(target!==this._target){return;}
delete this._target;const resourceTreeModel=target.model(ResourceTreeModel.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.removeEventListener(ResourceTreeModel.Events.CachedResourcesLoaded,this._initialize,this);resourceTreeModel.removeEventListener(ResourceTreeModel.Events.WillLoadCachedResources,this._resetWithFrames,this);}
if(this._databaseModel){this._databaseModel.removeEventListener(Events$2.DatabaseAdded,this._databaseAdded,this);this._databaseModel.removeEventListener(Events$2.DatabasesRemoved,this._resetWebSQL,this);this._databaseModel=null;}
this._resetWithFrames();}
focus(){this._sidebarTree.focus();}
_initialize(){for(const frame of ResourceTreeModel.ResourceTreeModel.frames()){this._addCookieDocument(frame);}
if(this._databaseModel){this._databaseModel.enable();}
const cacheStorageModel=this._target.model(ServiceWorkerCacheModel.ServiceWorkerCacheModel);if(cacheStorageModel){cacheStorageModel.enable();}
const resourceTreeModel=this._target.model(ResourceTreeModel.ResourceTreeModel);if(resourceTreeModel){this._populateApplicationCacheTree(resourceTreeModel);}
SDKModel.TargetManager.instance().observeModels(DOMStorageModel,({modelAdded:model=>this._domStorageModelAdded(model),modelRemoved:model=>this._domStorageModelRemoved(model)}));this.indexedDBListTreeElement._initialize();SDKModel.TargetManager.instance().observeModels(IndexedDBModel,({modelAdded:model=>model.enable(),modelRemoved:model=>this.indexedDBListTreeElement.removeIndexedDBForModel(model)}));const serviceWorkerCacheModel=this._target.model(ServiceWorkerCacheModel.ServiceWorkerCacheModel);this.cacheStorageListTreeElement._initialize(serviceWorkerCacheModel);const backgroundServiceModel=this._target.model(BackgroundServiceModel);if(Root.Runtime.experiments.isEnabled('backgroundServices')){this.backgroundFetchTreeElement._initialize(backgroundServiceModel);this.backgroundSyncTreeElement._initialize(backgroundServiceModel);if(Root.Runtime.experiments.isEnabled('backgroundServicesNotifications')){this.notificationsTreeElement._initialize(backgroundServiceModel);}
if(Root.Runtime.experiments.isEnabled('backgroundServicesPaymentHandler')){this.paymentHandlerTreeElement._initialize(backgroundServiceModel);}
this.periodicBackgroundSyncTreeElement._initialize(backgroundServiceModel);if(Root.Runtime.experiments.isEnabled('backgroundServicesPushMessaging')){this.pushMessagingTreeElement._initialize(backgroundServiceModel);}}}
_domStorageModelAdded(model){model.enable();model.storages().forEach(this._addDOMStorage.bind(this));model.addEventListener(Events$3.DOMStorageAdded,this._domStorageAdded,this);model.addEventListener(Events$3.DOMStorageRemoved,this._domStorageRemoved,this);}
_domStorageModelRemoved(model){model.storages().forEach(this._removeDOMStorage.bind(this));model.removeEventListener(Events$3.DOMStorageAdded,this._domStorageAdded,this);model.removeEventListener(Events$3.DOMStorageRemoved,this._domStorageRemoved,this);}
_resetWithFrames(){this._resourcesSection.reset();this._reset();}
_resetWebSQL(){for(const queryView of this._databaseQueryViews.values()){queryView.removeEventListener(Events$5.SchemaUpdated,event=>{this._updateDatabaseTables(event);},this);}
this._databaseTableViews.clear();this._databaseQueryViews.clear();this._databaseTreeElements.clear();this.databasesListTreeElement.removeChildren();this.databasesListTreeElement.setExpandable(false);}
_resetAppCache(){for(const frameId of Object.keys(this._applicationCacheFrameElements)){this._applicationCacheFrameManifestRemoved({data:frameId});}
this.applicationCacheListTreeElement.setExpandable(false);}
_treeElementAdded(event){const selection=this._panel.lastSelectedItemPath();if(!selection.length){return;}
const element=event.data;const index=selection.indexOf(element.itemURL);if(index<0){return;}
for(let parent=element.parent;parent;parent=parent.parent){parent.expand();}
if(index>0){element.expand();}
element.select();}
_reset(){this._domains={};this._resetWebSQL();this.cookieListTreeElement.removeChildren();}
_frameNavigated(event){const frame=(event.data);if(frame.isTopFrame()){this._reset();}
const applicationCacheFrameTreeElement=this._applicationCacheFrameElements[frame.id];if(applicationCacheFrameTreeElement){applicationCacheFrameTreeElement.frameNavigated(frame);}
this._addCookieDocument(frame);}
_databaseAdded(event){const database=(event.data);const databaseTreeElement=new DatabaseTreeElement(this,database);this._databaseTreeElements.set(database,databaseTreeElement);this.databasesListTreeElement.appendChild(databaseTreeElement);}
_addCookieDocument(frame){const urlToParse=frame.unreachableUrl()||frame.url;const parsedURL=ParsedURL.ParsedURL.fromString(urlToParse);if(!parsedURL||(parsedURL.scheme!=='http'&&parsedURL.scheme!=='https'&&parsedURL.scheme!=='file')){return;}
const domain=parsedURL.securityOrigin();if(!this._domains[domain]){this._domains[domain]=true;const cookieDomainTreeElement=new CookieTreeElement(this._panel,frame,domain);this.cookieListTreeElement.appendChild(cookieDomainTreeElement);}}
_domStorageAdded(event){const domStorage=(event.data);this._addDOMStorage(domStorage);}
_addDOMStorage(domStorage){console.assert(!this._domStorageTreeElements.get(domStorage));const domStorageTreeElement=new DOMStorageTreeElement(this._panel,domStorage);this._domStorageTreeElements.set(domStorage,domStorageTreeElement);if(domStorage.isLocalStorage){this.localStorageListTreeElement.appendChild(domStorageTreeElement);}else{this.sessionStorageListTreeElement.appendChild(domStorageTreeElement);}}
_domStorageRemoved(event){const domStorage=(event.data);this._removeDOMStorage(domStorage);}
_removeDOMStorage(domStorage){const treeElement=this._domStorageTreeElements.get(domStorage);if(!treeElement){return;}
const wasSelected=treeElement.selected;const parentListTreeElement=treeElement.parent;parentListTreeElement.removeChild(treeElement);if(wasSelected){parentListTreeElement.select();}
this._domStorageTreeElements.delete(domStorage);}
selectDatabase(database){if(database){this._showDatabase(database);this._databaseTreeElements.get(database).select();}}
async showResource(resource,line,column){await this._resourcesSection.revealResource(resource,line,column);}
_showDatabase(database,tableName){if(!database){return;}
let view;if(tableName){let tableViews=this._databaseTableViews.get(database);if(!tableViews){tableViews=({});this._databaseTableViews.set(database,tableViews);}
view=tableViews[tableName];if(!view){view=new DatabaseTableView(database,tableName);tableViews[tableName]=view;}}else{view=this._databaseQueryViews.get(database);if(!view){view=new DatabaseQueryView(database);this._databaseQueryViews.set(database,view);view.addEventListener(Events$5.SchemaUpdated,event=>{this._updateDatabaseTables(event);},this);}}
this._innerShowView(view);}
_showApplicationCache(frameId){if(!this._applicationCacheViews[frameId]){this._applicationCacheViews[frameId]=new ApplicationCacheItemsView(this._applicationCacheModel,frameId);}
this._innerShowView(this._applicationCacheViews[frameId]);}
showFileSystem(view){this._innerShowView(view);}
_innerShowView(view){this._panel.showView(view);}
async _updateDatabaseTables(event){const database=(event.data);if(!database){return;}
const databasesTreeElement=this._databaseTreeElements.get(database);if(!databasesTreeElement){return;}
databasesTreeElement.invalidateChildren();const tableViews=this._databaseTableViews.get(database);if(!tableViews){return;}
const tableNamesHash={};const panel=this._panel;const tableNames=await database.tableNames();const tableNamesLength=tableNames.length;for(let i=0;i<tableNamesLength;++i){tableNamesHash[tableNames[i]]=true;}
for(const tableName in tableViews){if(!(tableName in tableNamesHash)){if(panel.visibleView===tableViews[tableName]){panel.showView(null);}
delete tableViews[tableName];}}
await databasesTreeElement.updateChildren();}
_populateApplicationCacheTree(resourceTreeModel){this._applicationCacheModel=this._target.model(ApplicationCacheModel);this._applicationCacheViews={};this._applicationCacheFrameElements={};this._applicationCacheManifestElements={};this._applicationCacheModel.addEventListener(Events.FrameManifestAdded,this._applicationCacheFrameManifestAdded,this);this._applicationCacheModel.addEventListener(Events.FrameManifestRemoved,this._applicationCacheFrameManifestRemoved,this);this._applicationCacheModel.addEventListener(Events.FrameManifestsReset,this._resetAppCache,this);this._applicationCacheModel.addEventListener(Events.FrameManifestStatusUpdated,this._applicationCacheFrameManifestStatusChanged,this);this._applicationCacheModel.addEventListener(Events.NetworkStateChanged,this._applicationCacheNetworkStateChanged,this);}
_applicationCacheFrameManifestAdded(event){const frameId=event.data;const manifestURL=this._applicationCacheModel.frameManifestURL(frameId);let manifestTreeElement=this._applicationCacheManifestElements[manifestURL];if(!manifestTreeElement){manifestTreeElement=new ApplicationCacheManifestTreeElement(this._panel,manifestURL);this.applicationCacheListTreeElement.appendChild(manifestTreeElement);this._applicationCacheManifestElements[manifestURL]=manifestTreeElement;}
const model=this._target.model(ResourceTreeModel.ResourceTreeModel);const frameTreeElement=new ApplicationCacheFrameTreeElement(this,model.frameForId(frameId),manifestURL);manifestTreeElement.appendChild(frameTreeElement);manifestTreeElement.expand();this._applicationCacheFrameElements[frameId]=frameTreeElement;}
_applicationCacheFrameManifestRemoved(event){const frameId=event.data;const frameTreeElement=this._applicationCacheFrameElements[frameId];if(!frameTreeElement){return;}
const manifestURL=frameTreeElement.manifestURL;delete this._applicationCacheFrameElements[frameId];delete this._applicationCacheViews[frameId];frameTreeElement.parent.removeChild(frameTreeElement);const manifestTreeElement=this._applicationCacheManifestElements[manifestURL];if(manifestTreeElement.childCount()){return;}
delete this._applicationCacheManifestElements[manifestURL];manifestTreeElement.parent.removeChild(manifestTreeElement);}
_applicationCacheFrameManifestStatusChanged(event){const frameId=event.data;const status=this._applicationCacheModel.frameManifestStatus(frameId);if(this._applicationCacheViews[frameId]){this._applicationCacheViews[frameId].updateStatus(status);}}
_applicationCacheNetworkStateChanged(event){const isNowOnline=event.data;for(const manifestURL in this._applicationCacheViews){this._applicationCacheViews[manifestURL].updateNetworkState(isNowOnline);}}
showView(view){if(view){this.showResource(view.resource);}}
_onmousemove(event){const nodeUnderMouse=event.target;if(!nodeUnderMouse){return;}
const listNode=nodeUnderMouse.enclosingNodeOrSelfWithNodeName('li');if(!listNode){return;}
const element=listNode.treeElement;if(this._previousHoveredElement===element){return;}
if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;}
if(element instanceof FrameTreeElement){this._previousHoveredElement=element;element.hovered=true;}}
_onmouseleave(event){if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;delete this._previousHoveredElement;}}}
class BaseStorageTreeElement extends TreeOutline.TreeElement{constructor(storagePanel,title,expandable){super(title,expandable);this._storagePanel=storagePanel;ARIAUtils.setAccessibleName(this.listItemElement,title);}
onselect(selectedByUser){if(!selectedByUser){return false;}
const path=[];for(let el=this;el;el=el.parent){const url=el.itemURL;if(!url){break;}
path.push(url);}
this._storagePanel.setLastSelectedItemPath(path);return false;}
showView(view){this._storagePanel.showView(view);}}
class StorageCategoryTreeElement extends BaseStorageTreeElement{constructor(storagePanel,categoryName,settingsKey){super(storagePanel,categoryName,false);this._expandedSetting=Settings.Settings.instance().createSetting('resources'+settingsKey+'Expanded',settingsKey==='Frames');this._categoryName=categoryName;this._categoryLink=null;}
get itemURL(){return'category://'+this._categoryName;}
setLink(link){this._categoryLink=link;}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCategoryView(this._categoryName,this._categoryLink);return false;}
onattach(){super.onattach();if(this._expandedSetting.get()){this.expand();}}
onexpand(){this._expandedSetting.set(true);}
oncollapse(){this._expandedSetting.set(false);}}
class BackgroundServiceTreeElement extends BaseStorageTreeElement{constructor(storagePanel,serviceName){super(storagePanel,BackgroundServiceView.getUIString(serviceName),false);this._serviceName=serviceName;this._selected=false;this._view=null;this._model=null;const backgroundServiceIcon=Icon.Icon.create(this._getIconType(),'resource-tree-item');this.setLeadingIcons([backgroundServiceIcon]);}
_getIconType(){switch(this._serviceName){case Protocol.BackgroundService.ServiceName.BackgroundFetch:return'mediumicon-fetch';case Protocol.BackgroundService.ServiceName.BackgroundSync:return'mediumicon-sync';case Protocol.BackgroundService.ServiceName.PushMessaging:return'mediumicon-cloud';case Protocol.BackgroundService.ServiceName.Notifications:return'mediumicon-bell';case Protocol.BackgroundService.ServiceName.PaymentHandler:return'mediumicon-payment';case Protocol.BackgroundService.ServiceName.PeriodicBackgroundSync:return'mediumicon-schedule';default:console.error(`Service ${this._serviceName} does not have a dedicated icon`);return'mediumicon-table';}}
_initialize(model){this._model=model;if(this._selected&&!this._view){this.onselect(false);}}
get itemURL(){return`background-service://${this._serviceName}`;}
onselect(selectedByUser){super.onselect(selectedByUser);this._selected=true;if(!this._model){return false;}
if(!this._view){this._view=new BackgroundServiceView(this._serviceName,this._model);}
this.showView(this._view);self.UI.context.setFlavor(BackgroundServiceView,this._view);return false;}}
class DatabaseTreeElement extends BaseStorageTreeElement{constructor(sidebar,database){super(sidebar._panel,database.name,true);this._sidebar=sidebar;this._database=database;const icon=Icon.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'database://'+encodeURI(this._database.name);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showDatabase(this._database);return false;}
onexpand(){this.updateChildren();}
async updateChildren(){this.removeChildren();const tableNames=await this._database.tableNames();for(const tableName of tableNames){this.appendChild(new DatabaseTableTreeElement(this._sidebar,this._database,tableName));}}}
class DatabaseTableTreeElement extends BaseStorageTreeElement{constructor(sidebar,database,tableName){super(sidebar._panel,tableName,false);this._sidebar=sidebar;this._database=database;this._tableName=tableName;const icon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'database://'+encodeURI(this._database.name)+'/'+encodeURI(this._tableName);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showDatabase(this._database,this._tableName);return false;}}
class ServiceWorkerCacheTreeElement extends StorageCategoryTreeElement{constructor(storagePanel){super(storagePanel,UIString.UIString('Cache Storage'),'CacheStorage');const icon=Icon.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);this._swCacheModel=null;}
_initialize(model){this._swCacheTreeElements=new Set();this._swCacheModel=model;if(model){for(const cache of model.caches()){this._addCache(model,cache);}}
SDKModel.TargetManager.instance().addModelListener(ServiceWorkerCacheModel.ServiceWorkerCacheModel,ServiceWorkerCacheModel.Events.CacheAdded,this._cacheAdded,this);SDKModel.TargetManager.instance().addModelListener(ServiceWorkerCacheModel.ServiceWorkerCacheModel,ServiceWorkerCacheModel.Events.CacheRemoved,this._cacheRemoved,this);}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Refresh Caches'),this._refreshCaches.bind(this));contextMenu.show();}
_refreshCaches(){if(this._swCacheModel){this._swCacheModel.refreshCacheNames();}}
_cacheAdded(event){const cache=(event.data.cache);const model=(event.data.model);this._addCache(model,cache);}
_addCache(model,cache){const swCacheTreeElement=new SWCacheTreeElement(this._storagePanel,model,cache);this._swCacheTreeElements.add(swCacheTreeElement);this.appendChild(swCacheTreeElement);}
_cacheRemoved(event){const cache=(event.data.cache);const model=(event.data.model);const swCacheTreeElement=this._cacheTreeElement(model,cache);if(!swCacheTreeElement){return;}
this.removeChild(swCacheTreeElement);this._swCacheTreeElements.delete(swCacheTreeElement);this.setExpandable(this.childCount()>0);}
_cacheTreeElement(model,cache){for(const cacheTreeElement of this._swCacheTreeElements){if(cacheTreeElement._cache.equals(cache)&&cacheTreeElement._model===model){return cacheTreeElement;}}
return null;}}
class SWCacheTreeElement extends BaseStorageTreeElement{constructor(storagePanel,model,cache){super(storagePanel,cache.cacheName+' - '+cache.securityOrigin,false);this._model=model;this._cache=cache;this._view=null;const icon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'cache://'+this._cache.cacheId;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Delete'),this._clearCache.bind(this));contextMenu.show();}
_clearCache(){this._model.deleteCache(this._cache);}
update(cache){this._cache=cache;if(this._view){this._view.update(cache);}}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new ServiceWorkerCacheView(this._model,this._cache);}
this.showView(this._view);return false;}}
class ServiceWorkersTreeElement extends BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,UIString.UIString('Service Workers'),false);const icon=Icon.Icon.create('mediumicon-service-worker','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'service-workers://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new ServiceWorkersView();}
this.showView(this._view);return false;}}
class AppManifestTreeElement extends BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,UIString.UIString('Manifest'),false);const icon=Icon.Icon.create('mediumicon-manifest','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'manifest://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new AppManifestView();}
this.showView(this._view);return false;}}
class ClearStorageTreeElement extends BaseStorageTreeElement{constructor(storagePanel){super(storagePanel,UIString.UIString('Clear storage'),false);const icon=Icon.Icon.create('mediumicon-clear-storage','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'clear-storage://';}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new ClearStorageView();}
this.showView(this._view);return false;}}
class IndexedDBTreeElement extends StorageCategoryTreeElement{constructor(storagePanel){super(storagePanel,UIString.UIString('IndexedDB'),'IndexedDB');const icon=Icon.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);}
_initialize(){SDKModel.TargetManager.instance().addModelListener(IndexedDBModel,Events$4.DatabaseAdded,this._indexedDBAdded,this);SDKModel.TargetManager.instance().addModelListener(IndexedDBModel,Events$4.DatabaseRemoved,this._indexedDBRemoved,this);SDKModel.TargetManager.instance().addModelListener(IndexedDBModel,Events$4.DatabaseLoaded,this._indexedDBLoaded,this);SDKModel.TargetManager.instance().addModelListener(IndexedDBModel,Events$4.IndexedDBContentUpdated,this._indexedDBContentUpdated,this);this._idbDatabaseTreeElements=[];for(const indexedDBModel of SDKModel.TargetManager.instance().models(IndexedDBModel)){const databases=indexedDBModel.databases();for(let j=0;j<databases.length;++j){this._addIndexedDB(indexedDBModel,databases[j]);}}}
removeIndexedDBForModel(model){const idbDatabaseTreeElements=this._idbDatabaseTreeElements.filter(element=>element._model===model);for(const idbDatabaseTreeElement of idbDatabaseTreeElements){this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement);}}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Refresh IndexedDB'),this.refreshIndexedDB.bind(this));contextMenu.show();}
refreshIndexedDB(){for(const indexedDBModel of SDKModel.TargetManager.instance().models(IndexedDBModel)){indexedDBModel.refreshDatabaseNames();}}
_indexedDBAdded(event){const databaseId=(event.data.databaseId);const model=(event.data.model);this._addIndexedDB(model,databaseId);}
_addIndexedDB(model,databaseId){const idbDatabaseTreeElement=new IDBDatabaseTreeElement(this._storagePanel,model,databaseId);this._idbDatabaseTreeElements.push(idbDatabaseTreeElement);this.appendChild(idbDatabaseTreeElement);model.refreshDatabase(databaseId);}
_indexedDBRemoved(event){const databaseId=(event.data.databaseId);const model=(event.data.model);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,databaseId);if(!idbDatabaseTreeElement){return;}
this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement);}
_removeIDBDatabaseTreeElement(idbDatabaseTreeElement){idbDatabaseTreeElement.clear();this.removeChild(idbDatabaseTreeElement);ArrayUtilities.removeElement(this._idbDatabaseTreeElements,idbDatabaseTreeElement);this.setExpandable(this.childCount()>0);}
_indexedDBLoaded(event){const database=(event.data.database);const model=(event.data.model);const entriesUpdated=(event.data.entriesUpdated);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,database.databaseId);if(!idbDatabaseTreeElement){return;}
idbDatabaseTreeElement.update(database,entriesUpdated);this._indexedDBLoadedForTest();}
_indexedDBLoadedForTest(){}
_indexedDBContentUpdated(event){const databaseId=(event.data.databaseId);const objectStoreName=(event.data.objectStoreName);const model=(event.data.model);const idbDatabaseTreeElement=this._idbDatabaseTreeElement(model,databaseId);if(!idbDatabaseTreeElement){return;}
idbDatabaseTreeElement.indexedDBContentUpdated(objectStoreName);}
_idbDatabaseTreeElement(model,databaseId){return this._idbDatabaseTreeElements.find(x=>x._databaseId.equals(databaseId)&&x._model===model)||null;}}
class IDBDatabaseTreeElement extends BaseStorageTreeElement{constructor(storagePanel,model,databaseId){super(storagePanel,databaseId.name+' - '+databaseId.securityOrigin,false);this._model=model;this._databaseId=databaseId;this._idbObjectStoreTreeElements={};const icon=Icon.Icon.create('mediumicon-database','resource-tree-item');this.setLeadingIcons([icon]);this._model.addEventListener(Events$4.DatabaseNamesRefreshed,this._refreshIndexedDB,this);}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Refresh IndexedDB'),this._refreshIndexedDB.bind(this));contextMenu.show();}
_refreshIndexedDB(){this._model.refreshDatabase(this._databaseId);}
indexedDBContentUpdated(objectStoreName){if(this._idbObjectStoreTreeElements[objectStoreName]){this._idbObjectStoreTreeElements[objectStoreName].markNeedsRefresh();}}
update(database,entriesUpdated){this._database=database;const objectStoreNames={};const objectStoreNamesSorted=Object.keys(this._database.objectStores).sort();for(const objectStoreName of objectStoreNamesSorted){const objectStore=this._database.objectStores[objectStoreName];objectStoreNames[objectStore.name]=true;if(!this._idbObjectStoreTreeElements[objectStore.name]){const idbObjectStoreTreeElement=new IDBObjectStoreTreeElement(this._storagePanel,this._model,this._databaseId,objectStore);this._idbObjectStoreTreeElements[objectStore.name]=idbObjectStoreTreeElement;this.appendChild(idbObjectStoreTreeElement);}
this._idbObjectStoreTreeElements[objectStore.name].update(objectStore,entriesUpdated);}
for(const objectStoreName in this._idbObjectStoreTreeElements){if(!objectStoreNames[objectStoreName]){this._objectStoreRemoved(objectStoreName);}}
if(this._view){this._view.update(database);}
this._updateTooltip();}
_updateTooltip(){if(Object.keys(this._idbObjectStoreTreeElements).length===0){this.tooltip=ls`Version: ${this._database.version} (empty)`;}else{this.tooltip=ls`Version: ${this._database.version}`;}}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new IDBDatabaseView(this._model,this._database);}
this.showView(this._view);return false;}
_objectStoreRemoved(objectStoreName){const objectStoreTreeElement=this._idbObjectStoreTreeElements[objectStoreName];objectStoreTreeElement.clear();this.removeChild(objectStoreTreeElement);delete this._idbObjectStoreTreeElements[objectStoreName];this._updateTooltip();}
clear(){for(const objectStoreName in this._idbObjectStoreTreeElements){this._objectStoreRemoved(objectStoreName);}}}
class IDBObjectStoreTreeElement extends BaseStorageTreeElement{constructor(storagePanel,model,databaseId,objectStore){super(storagePanel,objectStore.name,false);this._model=model;this._databaseId=databaseId;this._idbIndexTreeElements={};this._objectStore=objectStore;this._view=null;const icon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name+'/'+
this._objectStore.name;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
markNeedsRefresh(){if(this._view){this._view.markNeedsRefresh();}
for(const indexName in this._idbIndexTreeElements){this._idbIndexTreeElements[indexName].markNeedsRefresh();}}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Clear'),this._clearObjectStore.bind(this));contextMenu.show();}
_refreshObjectStore(){if(this._view){this._view.refreshData();}
for(const indexName in this._idbIndexTreeElements){this._idbIndexTreeElements[indexName].refreshIndex();}}
async _clearObjectStore(){await this._model.clearObjectStore(this._databaseId,this._objectStore.name);this.update(this._objectStore,true);}
update(objectStore,entriesUpdated){this._objectStore=objectStore;const indexNames={};for(const indexName in this._objectStore.indexes){const index=this._objectStore.indexes[indexName];indexNames[index.name]=true;if(!this._idbIndexTreeElements[index.name]){const idbIndexTreeElement=new IDBIndexTreeElement(this._storagePanel,this._model,this._databaseId,this._objectStore,index,this._refreshObjectStore.bind(this));this._idbIndexTreeElements[index.name]=idbIndexTreeElement;this.appendChild(idbIndexTreeElement);}
this._idbIndexTreeElements[index.name].update(this._objectStore,index,entriesUpdated);}
for(const indexName in this._idbIndexTreeElements){if(!indexNames[indexName]){this._indexRemoved(indexName);}}
for(const indexName in this._idbIndexTreeElements){if(!indexNames[indexName]){this.removeChild(this._idbIndexTreeElements[indexName]);delete this._idbIndexTreeElements[indexName];}}
if(this.childCount()){this.expand();}
if(this._view&&entriesUpdated){this._view.update(this._objectStore,null);}
this._updateTooltip();}
_updateTooltip(){const keyPathString=this._objectStore.keyPathString;let tooltipString=keyPathString!==null?ls`Key path: ${keyPathString}`:'';if(this._objectStore.autoIncrement){tooltipString+='\n'+UIString.UIString('autoIncrement');}
this.tooltip=tooltipString;}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new IDBDataView(this._model,this._databaseId,this._objectStore,null,this._refreshObjectStore.bind(this));}
this.showView(this._view);return false;}
_indexRemoved(indexName){const indexTreeElement=this._idbIndexTreeElements[indexName];indexTreeElement.clear();this.removeChild(indexTreeElement);delete this._idbIndexTreeElements[indexName];}
clear(){for(const indexName in this._idbIndexTreeElements){this._indexRemoved(indexName);}
if(this._view){this._view.clear();}}}
class IDBIndexTreeElement extends BaseStorageTreeElement{constructor(storagePanel,model,databaseId,objectStore,index,refreshObjectStore){super(storagePanel,index.name,false);this._model=model;this._databaseId=databaseId;this._objectStore=objectStore;this._index=index;this._refreshObjectStore=refreshObjectStore;}
get itemURL(){return'indexedDB://'+this._databaseId.securityOrigin+'/'+this._databaseId.name+'/'+
this._objectStore.name+'/'+this._index.name;}
markNeedsRefresh(){if(this._view){this._view.markNeedsRefresh();}}
refreshIndex(){if(this._view){this._view.refreshData();}}
update(objectStore,index,entriesUpdated){this._objectStore=objectStore;this._index=index;if(this._view&&entriesUpdated){this._view.update(this._objectStore,this._index);}
this._updateTooltip();}
_updateTooltip(){const tooltipLines=[];const keyPathString=this._index.keyPathString;tooltipLines.push(ls`Key path: ${keyPathString}`);if(this._index.unique){tooltipLines.push(UIString.UIString('unique'));}
if(this._index.multiEntry){tooltipLines.push(UIString.UIString('multiEntry'));}
this.tooltip=tooltipLines.join('\n');}
onselect(selectedByUser){super.onselect(selectedByUser);if(!this._view){this._view=new IDBDataView(this._model,this._databaseId,this._objectStore,this._index,this._refreshObjectStore);}
this.showView(this._view);return false;}
clear(){if(this._view){this._view.clear();}}}
class DOMStorageTreeElement extends BaseStorageTreeElement{constructor(storagePanel,domStorage){super(storagePanel,domStorage.securityOrigin?domStorage.securityOrigin:UIString.UIString('Local Files'),false);this._domStorage=domStorage;const icon=Icon.Icon.create('mediumicon-table','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'storage://'+this._domStorage.securityOrigin+'/'+
(this._domStorage.isLocalStorage?'local':'session');}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showDOMStorage(this._domStorage);return false;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Clear'),()=>this._domStorage.clear());contextMenu.show();}}
class CookieTreeElement extends BaseStorageTreeElement{constructor(storagePanel,frame,cookieDomain){super(storagePanel,cookieDomain?cookieDomain:UIString.UIString('Local Files'),false);this._target=frame.resourceTreeModel().target();this._cookieDomain=cookieDomain;this.tooltip=ls`Cookies used by frames from ${cookieDomain}`;const icon=Icon.Icon.create('mediumicon-cookie','resource-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'cookies://'+this._cookieDomain;}
onattach(){super.onattach();this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.defaultSection().appendItem(UIString.UIString('Clear'),()=>this._storagePanel.clearCookies(this._target,this._cookieDomain));contextMenu.show();}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCookies(this._target,this._cookieDomain);return false;}}
class ApplicationCacheManifestTreeElement extends BaseStorageTreeElement{constructor(storagePanel,manifestURL){const title=new ParsedURL.ParsedURL(manifestURL).displayName;super(storagePanel,title,false);this.tooltip=manifestURL;this._manifestURL=manifestURL;}
get itemURL(){return'appcache://'+this._manifestURL;}
get manifestURL(){return this._manifestURL;}
onselect(selectedByUser){super.onselect(selectedByUser);this._storagePanel.showCategoryView(this._manifestURL,null);return false;}}
class ApplicationCacheFrameTreeElement extends BaseStorageTreeElement{constructor(sidebar,frame,manifestURL){super(sidebar._panel,'',false);this._sidebar=sidebar;this._frameId=frame.id;this._manifestURL=manifestURL;this._refreshTitles(frame);const icon=Icon.Icon.create('largeicon-navigator-folder','navigator-tree-item');icon.classList.add('navigator-folder-tree-item');this.setLeadingIcons([icon]);}
get itemURL(){return'appcache://'+this._manifestURL+'/'+encodeURI(this.titleAsText());}
get frameId(){return this._frameId;}
get manifestURL(){return this._manifestURL;}
_refreshTitles(frame){this.title=frame.displayName();}
frameNavigated(frame){this._refreshTitles(frame);}
onselect(selectedByUser){super.onselect(selectedByUser);this._sidebar._showApplicationCache(this._frameId);return false;}}
class StorageCategoryView extends Widget.VBox{constructor(){super();this.element.classList.add('storage-view');this._emptyWidget=new EmptyWidget.EmptyWidget('');this._linkElement=null;this._emptyWidget.show(this.element);}
setText(text){this._emptyWidget.text=text;}
setLink(link){if(link&&!this._linkElement){this._linkElement=this._emptyWidget.appendLink(link);}
if(!link&&this._linkElement){this._linkElement.classList.add('hidden');}
if(link&&this._linkElement){this._linkElement.setAttribute('href',link);this._linkElement.classList.remove('hidden');}}}
class ResourcesSection{constructor(storagePanel,treeElement){this._panel=storagePanel;this._treeElement=treeElement;this._treeElementForFrameId=new Map();function addListener(eventType,handler,target){SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,eventType,event=>handler.call(target,event.data));}
addListener(ResourceTreeModel.Events.FrameAdded,this._frameAdded,this);addListener(ResourceTreeModel.Events.FrameNavigated,this._frameNavigated,this);addListener(ResourceTreeModel.Events.FrameDetached,this._frameDetached,this);addListener(ResourceTreeModel.Events.ResourceAdded,this._resourceAdded,this);const mainTarget=SDKModel.TargetManager.instance().mainTarget();const resourceTreeModel=mainTarget&&mainTarget.model(ResourceTreeModel.ResourceTreeModel);const mainFrame=resourceTreeModel&&resourceTreeModel.mainFrame;if(mainFrame){this._frameAdded(mainFrame);}}
static _getParentFrame(frame){const parentFrame=frame.parentFrame;if(parentFrame){return parentFrame;}
const parentTarget=frame.resourceTreeModel().target().parentTarget();if(!parentTarget){return null;}
return parentTarget.model(ResourceTreeModel.ResourceTreeModel).mainFrame;}
_expandFrame(frame){if(!frame){return false;}
let treeElement=this._treeElementForFrameId.get(frame.id);if(!treeElement&&!this._expandFrame(ResourcesSection._getParentFrame(frame))){return false;}
treeElement=this._treeElementForFrameId.get(frame.id);if(!treeElement){return false;}
treeElement.expand();return true;}
async revealResource(resource,line,column){if(!this._expandFrame(resource.frame())){return;}
const resourceTreeElement=FrameResourceTreeElement.forResource(resource);if(resourceTreeElement){await resourceTreeElement.revealResource(line,column);}}
_frameAdded(frame){const parentFrame=ResourcesSection._getParentFrame(frame);const parentTreeElement=parentFrame?this._treeElementForFrameId.get(parentFrame.id):this._treeElement;if(!parentTreeElement){return;}
const frameTreeElement=new FrameTreeElement(this,frame);this._treeElementForFrameId.set(frame.id,frameTreeElement);parentTreeElement.appendChild(frameTreeElement);}
_frameDetached(frame){const frameTreeElement=this._treeElementForFrameId.get(frame.id);if(!frameTreeElement){return;}
this._treeElementForFrameId.delete(frame.id);if(frameTreeElement.parent){frameTreeElement.parent.removeChild(frameTreeElement);}}
_frameNavigated(frame){const frameTreeElement=this._treeElementForFrameId.get(frame.id);if(frameTreeElement){frameTreeElement.frameNavigated(frame);}}
_resourceAdded(resource){const frameTreeElement=this._treeElementForFrameId.get(resource.frameId);if(!frameTreeElement){return;}
frameTreeElement.appendResource(resource);}
reset(){this._treeElement.removeChildren();this._treeElementForFrameId.clear();}}
class FrameTreeElement extends BaseStorageTreeElement{constructor(section,frame){super(section._panel,'',false);this._populated=false;this._section=section;this._frame=frame;this._frameId=frame.id;this._categoryElements={};this._treeElementForResource={};this.setExpandable(true);this.frameNavigated(frame);const icon=Icon.Icon.create('largeicon-navigator-frame','navigator-tree-item');icon.classList.add('navigator-frame-tree-item');this.setLeadingIcons([icon]);}
frameNavigated(frame){this.invalidateChildren();this._frameId=frame.id;this.title=frame.displayName();this._categoryElements={};this._treeElementForResource={};}
get itemURL(){return'frame://'+encodeURI(this.titleAsText());}
onselect(selectedByUser){super.onselect(selectedByUser);this._section._panel.showCategoryView(this.titleAsText(),null);this.listItemElement.classList.remove('hovered');OverlayModel.OverlayModel.hideDOMNodeHighlight();return false;}
set hovered(hovered){if(hovered){this.listItemElement.classList.add('hovered');this._frame.resourceTreeModel().domModel().overlayModel().highlightFrame(this._frameId);}else{this.listItemElement.classList.remove('hovered');OverlayModel.OverlayModel.hideDOMNodeHighlight();}}
appendResource(resource){if(!this._populated){return;}
const statusCode=resource['statusCode'];if(statusCode>=301&&statusCode<=303){return;}
const resourceType=resource.resourceType();const categoryName=resourceType.name();let categoryElement=resourceType===ResourceType.resourceTypes.Document?this:this._categoryElements[categoryName];if(!categoryElement){categoryElement=new StorageCategoryTreeElement(this._section._panel,resource.resourceType().category().title,categoryName);this._categoryElements[resourceType.name()]=categoryElement;this._insertInPresentationOrder(this,categoryElement);}
const resourceTreeElement=new FrameResourceTreeElement(this._section._panel,resource);this._insertInPresentationOrder(categoryElement,resourceTreeElement);this._treeElementForResource[resource.url]=resourceTreeElement;}
resourceByURL(url){const treeElement=this._treeElementForResource[url];return treeElement?treeElement._resource:null;}
appendChild(treeElement){if(!this._populated){return;}
this._insertInPresentationOrder(this,treeElement);}
_insertInPresentationOrder(parentTreeElement,childTreeElement){function typeWeight(treeElement){if(treeElement instanceof StorageCategoryTreeElement){return 2;}
if(treeElement instanceof FrameTreeElement){return 1;}
return 3;}
function compare(treeElement1,treeElement2){const typeWeight1=typeWeight(treeElement1);const typeWeight2=typeWeight(treeElement2);let result;if(typeWeight1>typeWeight2){result=1;}else if(typeWeight1<typeWeight2){result=-1;}else{result=treeElement1.titleAsText().localeCompare(treeElement2.titleAsText());}
return result;}
const childCount=parentTreeElement.childCount();let i;for(i=0;i<childCount;++i){if(compare(childTreeElement,parentTreeElement.childAt(i))<0){break;}}
parentTreeElement.insertChild(childTreeElement,i);}
async onpopulate(){this._populated=true;for(const child of this._frame.childFrames){this._section._frameAdded(child);}
for(const resource of this._frame.resources()){this.appendResource(resource);}}}
class FrameResourceTreeElement extends BaseStorageTreeElement{constructor(storagePanel,resource){super(storagePanel,resource.displayName,false);this._panel=storagePanel;this._resource=resource;this._previewPromise=null;this.tooltip=resource.url;this._resource[FrameResourceTreeElement._symbol]=this;const icon=Icon.Icon.create('largeicon-navigator-file','navigator-tree-item');icon.classList.add('navigator-file-tree-item');icon.classList.add('navigator-'+resource.resourceType().name()+'-tree-item');this.setLeadingIcons([icon]);}
static forResource(resource){return resource[FrameResourceTreeElement._symbol];}
get itemURL(){return this._resource.url;}
_preparePreview(){if(this._previewPromise){return this._previewPromise;}
const viewPromise=PreviewFactory.PreviewFactory.createPreview(this._resource,this._resource.mimeType);this._previewPromise=viewPromise.then(view=>{if(view){return view;}
return new EmptyWidget.EmptyWidget(this._resource.url);});return this._previewPromise;}
onselect(selectedByUser){super.onselect(selectedByUser);this._panel.scheduleShowView(this._preparePreview());return false;}
ondblclick(event){InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(this._resource.url);return false;}
onattach(){super.onattach();this.listItemElement.draggable=true;this.listItemElement.addEventListener('dragstart',this._ondragstart.bind(this),false);this.listItemElement.addEventListener('contextmenu',this._handleContextMenuEvent.bind(this),true);}
_ondragstart(event){event.dataTransfer.setData('text/plain',this._resource.content||'');event.dataTransfer.effectAllowed='copy';return true;}
_handleContextMenuEvent(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.appendApplicableItems(this._resource);contextMenu.show();}
async revealResource(line,column){this.revealAndSelect(true);const view=await this._panel.scheduleShowView(this._preparePreview());if(!(view instanceof ResourceSourceFrame.ResourceSourceFrame)||typeof line!=='number'){return;}
view.revealPosition(line,column,true);}}
FrameResourceTreeElement._symbol=Symbol('treeElement');var ApplicationPanelSidebar$1=Object.freeze({__proto__:null,ApplicationPanelSidebar:ApplicationPanelSidebar,BaseStorageTreeElement:BaseStorageTreeElement,StorageCategoryTreeElement:StorageCategoryTreeElement,BackgroundServiceTreeElement:BackgroundServiceTreeElement,DatabaseTreeElement:DatabaseTreeElement,DatabaseTableTreeElement:DatabaseTableTreeElement,ServiceWorkerCacheTreeElement:ServiceWorkerCacheTreeElement,SWCacheTreeElement:SWCacheTreeElement,ServiceWorkersTreeElement:ServiceWorkersTreeElement,AppManifestTreeElement:AppManifestTreeElement,ClearStorageTreeElement:ClearStorageTreeElement,IndexedDBTreeElement:IndexedDBTreeElement,IDBDatabaseTreeElement:IDBDatabaseTreeElement,IDBObjectStoreTreeElement:IDBObjectStoreTreeElement,IDBIndexTreeElement:IDBIndexTreeElement,DOMStorageTreeElement:DOMStorageTreeElement,CookieTreeElement:CookieTreeElement,ApplicationCacheManifestTreeElement:ApplicationCacheManifestTreeElement,ApplicationCacheFrameTreeElement:ApplicationCacheFrameTreeElement,StorageCategoryView:StorageCategoryView,ResourcesSection:ResourcesSection,FrameTreeElement:FrameTreeElement,FrameResourceTreeElement:FrameResourceTreeElement});class StorageItemsView extends Widget.VBox{constructor(title,filterName){super(false);this._filterRegex=null;this._refreshButton=this._addButton(UIString.UIString('Refresh'),'largeicon-refresh',this.refreshItems);this._mainToolbar=new Toolbar.Toolbar('top-resources-toolbar',this.element);this._filterItem=new Toolbar.ToolbarInput(UIString.UIString('Filter'),'',0.4);this._filterItem.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,this._filterChanged,this);const toolbarSeparator=new Toolbar.ToolbarSeparator();this._deleteAllButton=this._addButton(UIString.UIString('Clear All'),'largeicon-clear',this.deleteAllItems);this._deleteSelectedButton=this._addButton(UIString.UIString('Delete Selected'),'largeicon-delete',this.deleteSelectedItem);const toolbarItems=[this._refreshButton,this._filterItem,toolbarSeparator,this._deleteAllButton,this._deleteSelectedButton];for(const item of toolbarItems){this._mainToolbar.appendToolbarItem(item);}}
appendToolbarItem(item){this._mainToolbar.appendToolbarItem(item);}
_addButton(label,glyph,callback){const button=new Toolbar.ToolbarButton(label,glyph);button.addEventListener(Toolbar.ToolbarButton.Events.Click,callback,this);return button;}
_filterChanged(event){const text=(event.data);this._filterRegex=text?new RegExp(text.escapeForRegExp(),'i'):null;this.refreshItems();}
filter(items,keyFunction){if(this._filterRegex){const regExp=this._filterRegex;return items.filter(item=>regExp.test(keyFunction(item)));}
return items;}
wasShown(){this.refreshItems();}
setCanDeleteAll(enabled){this._deleteAllButton.setEnabled(enabled);}
setCanDeleteSelected(enabled){this._deleteSelectedButton.setEnabled(enabled);}
setCanRefresh(enabled){this._refreshButton.setEnabled(enabled);}
setCanFilter(enabled){this._filterItem.setEnabled(enabled);}
deleteAllItems(){}
deleteSelectedItem(){}
refreshItems(){}}
var StorageItemsView$1=Object.freeze({__proto__:null,StorageItemsView:StorageItemsView});class CookieItemsView extends StorageItemsView{constructor(model,cookieDomain){super(UIString.UIString('Cookies'),'cookiesPanel');this.registerRequiredCSS('resources/cookieItemsView.css');this.element.classList.add('storage-view');this._model=model;this._cookieDomain=cookieDomain;this._totalSize=0;this._cookiesTable=new CookiesTable.CookiesTable(false,this._saveCookie.bind(this),this.refreshItems.bind(this),this._handleCookieSelected.bind(this),this._deleteCookie.bind(this));this._cookiesTable.setMinimumSize(0,50);this._splitWidget=new SplitWidget.SplitWidget(false,true,'cookieItemsSplitViewState');this._splitWidget.show(this.element);this._previewPanel=new Widget.VBox();const resizer=this._previewPanel.element.createChild('div','preview-panel-resizer');this._splitWidget.setMainWidget(this._cookiesTable);this._splitWidget.setSidebarWidget(this._previewPanel);this._splitWidget.installResizer(resizer);this._onlyIssuesFilterUI=new Toolbar.ToolbarCheckbox(ls`Only show cookies with an issue`,ls`Only show cookies which have an associated issue`,()=>{this._updateWithCookies(this._allCookies);});if(Runtime.experiments.isEnabled('issuesPane')){this.appendToolbarItem(this._onlyIssuesFilterUI);}else{this._onlyIssuesFilterUI.setChecked(false);}
this._refreshThrottler=new Throttler.Throttler(300);this._eventDescriptors=[];this._preview=null;this._previewValue=null;this._allCookies=[];this.setCookiesDomain(model,cookieDomain);}
setCookiesDomain(model,domain){this._model=model;this._cookieDomain=domain;this.refreshItems();EventTarget.EventTarget.removeEventListeners(this._eventDescriptors);const networkManager=model.target().model(NetworkManager.NetworkManager);this._eventDescriptors=[networkManager.addEventListener(NetworkManager.Events.ResponseReceived,this._onResponseReceived,this),networkManager.addEventListener(NetworkManager.Events.LoadingFinished,this._onLoadingFinished,this),];this._showPreview(null,null);}
_showPreview(preview,value){if(this._preview&&this._previewValue===value){return;}
if(this._preview){this._preview.detach();}
if(!preview){preview=new EmptyWidget.EmptyWidget(ls`Select a cookie to preview its value`);}
this._previewValue=value;this._preview=preview;preview.show(this._previewPanel.contentElement);}
_handleCookieSelected(){const cookie=this._cookiesTable.selectedCookie();this.setCanDeleteSelected(!!cookie);if(!cookie){this._showPreview(null,null);return;}
const value=document.createElement('div');value.classList.add('cookie-value');value.textContent=cookie.value();value.addEventListener('dblclick',handleDblClickOnCookieValue);const preview=new Widget.VBox();preview.contentElement.appendChild(value);this._showPreview(preview,cookie);function handleDblClickOnCookieValue(){const range=document.createRange();range.selectNode(value);window.getSelection().removeAllRanges();window.getSelection().addRange(range);}}
_saveCookie(newCookie,oldCookie){if(!this._model){return Promise.resolve(false);}
if(oldCookie&&newCookie.key()!==oldCookie.key()){this._model.deleteCookie(oldCookie);}
return this._model.saveCookie(newCookie);}
_deleteCookie(cookie,callback){this._model.deleteCookie(cookie,callback);}
_updateWithCookies(allCookies){this._allCookies=allCookies;this._totalSize=allCookies.reduce((size,cookie)=>size+cookie.size(),0);const parsedURL=ParsedURL.ParsedURL.fromString(this._cookieDomain);const host=parsedURL?parsedURL.host:'';this._cookiesTable.setCookieDomain(host);const shownCookies=this.filter(allCookies,cookie=>`${cookie.name()} ${cookie.value()} ${cookie.domain()}`);this._cookiesTable.setCookies(shownCookies,this._model.getCookieToBlockedReasonsMap());this.setCanFilter(true);this.setCanDeleteAll(true);this.setCanDeleteSelected(!!this._cookiesTable.selectedCookie());}
filter(items,keyFunction){const predicate=object=>{if(!this._onlyIssuesFilterUI.checked()){return true;}
if(object instanceof Cookie.Cookie){return RelatedIssue.hasIssues(object);}
return false;};return super.filter(items,keyFunction).filter(predicate);}
deleteAllItems(){this._model.clear(this._cookieDomain,()=>this.refreshItems());}
deleteSelectedItem(){const selectedCookie=this._cookiesTable.selectedCookie();if(selectedCookie){this._model.deleteCookie(selectedCookie,()=>this.refreshItems());}}
refreshItems(){this._model.getCookiesForDomain(this._cookieDomain).then(this._updateWithCookies.bind(this));}
refreshItemsThrottled(){this._refreshThrottler.schedule(()=>Promise.resolve(this.refreshItems()));}
_onResponseReceived(){this.refreshItemsThrottled();}
_onLoadingFinished(){this.refreshItemsThrottled();}}
var CookieItemsView$1=Object.freeze({__proto__:null,CookieItemsView:CookieItemsView});class DOMStorageItemsView extends StorageItemsView{constructor(domStorage){super(UIString.UIString('DOM Storage'),'domStoragePanel');this._domStorage=domStorage;this.element.classList.add('storage-view','table');const columns=([{id:'key',title:UIString.UIString('Key'),sortable:false,editable:true,longText:true,weight:50},{id:'value',title:UIString.UIString('Value'),sortable:false,editable:true,longText:true,weight:50}]);this._dataGrid=new DataGrid.DataGridImpl({displayName:ls`DOM Storage Items`,columns,editCallback:this._editingCallback.bind(this),deleteCallback:this._deleteCallback.bind(this),refreshCallback:this.refreshItems.bind(this)});this._dataGrid.addEventListener(DataGrid.Events.SelectedNode,event=>{this._previewEntry((event.data));});this._dataGrid.addEventListener(DataGrid.Events.DeselectedNode,event=>{this._previewEntry(null);});this._dataGrid.setStriped(true);this._dataGrid.setName('DOMStorageItemsView');this._splitWidget=new SplitWidget.SplitWidget(false,true,'domStorageSplitViewState');this._splitWidget.show(this.element);this._previewPanel=new Widget.VBox();this._previewPanel.setMinimumSize(0,50);const resizer=this._previewPanel.element.createChild('div','preview-panel-resizer');const dataGridWidget=this._dataGrid.asWidget();dataGridWidget.setMinimumSize(0,50);this._splitWidget.setMainWidget(dataGridWidget);this._splitWidget.setSidebarWidget(this._previewPanel);this._splitWidget.installResizer(resizer);this._preview=null;this._previewValue=null;this._showPreview(null,null);this._eventListeners=[];this.setStorage(domStorage);}
setStorage(domStorage){EventTarget.EventTarget.removeEventListeners(this._eventListeners);this._domStorage=domStorage;this._eventListeners=[this._domStorage.addEventListener(DOMStorage.Events.DOMStorageItemsCleared,this._domStorageItemsCleared,this),this._domStorage.addEventListener(DOMStorage.Events.DOMStorageItemRemoved,this._domStorageItemRemoved,this),this._domStorage.addEventListener(DOMStorage.Events.DOMStorageItemAdded,this._domStorageItemAdded,this),this._domStorage.addEventListener(DOMStorage.Events.DOMStorageItemUpdated,this._domStorageItemUpdated,this),];this.refreshItems();}
_domStorageItemsCleared(){if(!this.isShowing()||!this._dataGrid){return;}
this._dataGrid.rootNode().removeChildren();this._dataGrid.addCreationNode(false);this.setCanDeleteSelected(false);}
_domStorageItemRemoved(event){if(!this.isShowing()||!this._dataGrid){return;}
const storageData=event.data;const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=0;i<children.length;++i){const childNode=children[i];if(childNode.data.key===storageData.key){rootNode.removeChild(childNode);this.setCanDeleteSelected(children.length>1);return;}}}
_domStorageItemAdded(event){if(!this.isShowing()||!this._dataGrid){return;}
const storageData=event.data;const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=0;i<children.length;++i){if(children[i].data.key===storageData.key){return;}}
const childNode=new DataGrid.DataGridNode({key:storageData.key,value:storageData.value},false);rootNode.insertChild(childNode,children.length-1);}
_domStorageItemUpdated(event){if(!this.isShowing()||!this._dataGrid){return;}
const storageData=event.data;const childNode=this._dataGrid.rootNode().children.find(child=>child.data.key===storageData.key);if(!childNode||childNode.data.value===storageData.value){return;}
childNode.data.value=storageData.value;childNode.refresh();if(!childNode.selected){return;}
this._previewEntry(childNode);this.setCanDeleteSelected(true);}
_showDOMStorageItems(items){const rootNode=this._dataGrid.rootNode();let selectedKey=null;for(const node of rootNode.children){if(!node.selected){continue;}
selectedKey=node.data.key;break;}
rootNode.removeChildren();let selectedNode=null;const filteredItems=item=>`${item[0]} ${item[1]}`;for(const item of this.filter(items,filteredItems)){const key=item[0];const value=item[1];const node=new DataGrid.DataGridNode({key:key,value:value},false);node.selectable=true;rootNode.appendChild(node);if(!selectedNode||key===selectedKey){selectedNode=node;}}
if(selectedNode){selectedNode.selected=true;}
this._dataGrid.addCreationNode(false);this.setCanDeleteSelected(!!selectedNode);}
deleteSelectedItem(){if(!this._dataGrid||!this._dataGrid.selectedNode){return;}
this._deleteCallback(this._dataGrid.selectedNode);}
refreshItems(){this._domStorage.getItems().then(items=>items&&this._showDOMStorageItems(items));}
deleteAllItems(){this._domStorage.clear();this._domStorageItemsCleared();}
_editingCallback(editingNode,columnIdentifier,oldText,newText){const domStorage=this._domStorage;if(columnIdentifier==='key'){if(typeof oldText==='string'){domStorage.removeItem(oldText);}
domStorage.setItem(newText,editingNode.data.value||'');this._removeDupes(editingNode);}else{domStorage.setItem(editingNode.data.key||'',newText);}}
_removeDupes(masterNode){const rootNode=this._dataGrid.rootNode();const children=rootNode.children;for(let i=children.length-1;i>=0;--i){const childNode=children[i];if((childNode.data.key===masterNode.data.key)&&(masterNode!==childNode)){rootNode.removeChild(childNode);}}}
_deleteCallback(node){if(!node||node.isCreationNode){return;}
if(this._domStorage){this._domStorage.removeItem(node.data.key);}}
_showPreview(preview,value){if(this._preview&&this._previewValue===value){return;}
if(this._preview){this._preview.detach();}
if(!preview){preview=new EmptyWidget.EmptyWidget(UIString.UIString('Select a value to preview'));}
this._previewValue=value;this._preview=preview;preview.show(this._previewPanel.contentElement);}
async _previewEntry(entry){const value=entry&&entry.data&&entry.data.value;if(!value){this._showPreview(null,value);return;}
const protocol=this._domStorage.isLocalStorage?'localstorage':'sessionstorage';const url=`${protocol}://${entry.key}`;const provider=StaticContentProvider.StaticContentProvider.fromString(url,ResourceType.resourceTypes.XHR,(value));const preview=await PreviewFactory.PreviewFactory.createPreview(provider,'text/plain');if(!entry.selected){return;}
this._showPreview(preview,value);}}
var DOMStorageItemsView$1=Object.freeze({__proto__:null,DOMStorageItemsView:DOMStorageItemsView});class ResourcesPanel extends Panel.PanelWithSidebar{constructor(){super('resources');this.registerRequiredCSS('resources/resourcesPanel.css');this._resourcesLastSelectedItemSetting=Settings.Settings.instance().createSetting('resourcesLastSelectedElementPath',[]);this.visibleView=null;this._pendingViewPromise=null;this._categoryView=null;const mainContainer=new Widget.VBox();this.storageViews=mainContainer.element.createChild('div','vbox flex-auto');this._storageViewToolbar=new Toolbar.Toolbar('resources-toolbar',mainContainer.element);this.splitWidget().setMainWidget(mainContainer);this._domStorageView=null;this._cookieView=null;this._emptyWidget=null;this._sidebar=new ApplicationPanelSidebar(this);this._sidebar.show(this.panelSidebarElement());}
static _instance(){return(self.runtime.sharedInstance(ResourcesPanel));}
static _shouldCloseOnReset(view){const viewClassesToClose=[ResourceSourceFrame.ResourceSourceFrame,ImageView.ImageView,FontView.FontView,StorageItemsView,DatabaseQueryView,DatabaseTableView];return viewClassesToClose.some(type=>view instanceof type);}
focus(){this._sidebar.focus();}
lastSelectedItemPath(){return this._resourcesLastSelectedItemSetting.get();}
setLastSelectedItemPath(path){this._resourcesLastSelectedItemSetting.set(path);}
resetView(){if(this.visibleView&&ResourcesPanel._shouldCloseOnReset(this.visibleView)){this.showView(null);}}
showView(view){this._pendingViewPromise=null;if(this.visibleView===view){return;}
if(this.visibleView){this.visibleView.detach();}
if(view){view.show(this.storageViews);}
this.visibleView=view;this._storageViewToolbar.removeToolbarItems();if(view instanceof View.SimpleView){view.toolbarItems().then(items=>{items.map(item=>this._storageViewToolbar.appendToolbarItem(item));this._storageViewToolbar.element.classList.toggle('hidden',!items.length);});}}
async scheduleShowView(viewPromise){this._pendingViewPromise=viewPromise;const view=await viewPromise;if(this._pendingViewPromise!==viewPromise){return null;}
this.showView(view);return view;}
showCategoryView(categoryName,categoryLink){if(!this._categoryView){this._categoryView=new StorageCategoryView();}
this._categoryView.setText(categoryName);this._categoryView.setLink(categoryLink);this.showView(this._categoryView);}
showDOMStorage(domStorage){if(!domStorage){return;}
if(!this._domStorageView){this._domStorageView=new DOMStorageItemsView(domStorage);}else{this._domStorageView.setStorage(domStorage);}
this.showView(this._domStorageView);}
showCookies(cookieFrameTarget,cookieDomain){const model=cookieFrameTarget.model(CookieModel.CookieModel);if(!model){return;}
if(!this._cookieView){this._cookieView=new CookieItemsView(model,cookieDomain);}else{this._cookieView.setCookiesDomain(model,cookieDomain);}
this.showView(this._cookieView);}
clearCookies(target,cookieDomain){const model=target.model(CookieModel.CookieModel);if(!model){return;}
model.clear(cookieDomain,()=>{if(this._cookieView){this._cookieView.refreshItems();}});}}
class ResourceRevealer{async reveal(resource){if(!(resource instanceof Resource.Resource)){return Promise.reject(new Error('Internal error: not a resource'));}
const sidebar=ResourcesPanel._instance()._sidebar;await ViewManager.ViewManager.instance().showView('resources');await sidebar.showResource(resource);}}
class CookieReferenceRevealer{async reveal(cookie){if(!(cookie instanceof Cookie.CookieReference)){throw new Error('Internal error: not a cookie reference');}
const sidebar=ResourcesPanel._instance()._sidebar;await ViewManager.ViewManager.instance().showView('resources');await sidebar.cookieListTreeElement.select();const contextUrl=cookie.contextUrl();if(contextUrl&&await this._revealByDomain(sidebar,contextUrl)){return;}
this._revealByDomain(sidebar,cookie.domain());}
async _revealByDomain(sidebar,domain){const item=sidebar.cookieListTreeElement.children().find(c=>c._cookieDomain.endsWith(domain));if(item){await item.revealAndSelect();return true;}
return false;}}
var ResourcesPanel$1=Object.freeze({__proto__:null,ResourcesPanel:ResourcesPanel,ResourceRevealer:ResourceRevealer,CookieReferenceRevealer:CookieReferenceRevealer});export{AppManifestView$1 as AppManifestView,ApplicationCacheItemsView$1 as ApplicationCacheItemsView,ApplicationCacheModel$1 as ApplicationCacheModel,ApplicationPanelSidebar$1 as ApplicationPanelSidebar,BackgroundServiceModel$1 as BackgroundServiceModel,BackgroundServiceView$1 as BackgroundServiceView,ClearStorageView$1 as ClearStorageView,CookieItemsView$1 as CookieItemsView,DOMStorageItemsView$1 as DOMStorageItemsView,DOMStorageModel$1 as DOMStorageModel,DatabaseModel$1 as DatabaseModel,DatabaseQueryView$1 as DatabaseQueryView,DatabaseTableView$1 as DatabaseTableView,IndexedDBModel$1 as IndexedDBModel,IndexedDBViews,ResourcesPanel$1 as ResourcesPanel,ServiceWorkerCacheViews,ServiceWorkersView$1 as ServiceWorkersView,StorageItemsView$1 as StorageItemsView};