import{ObjectWrapper as e,EventTarget as t,ParsedURL as i,Settings as s,Linkifier as n}from"../common/common.js";import{i18n as r}from"../i18n/i18n.js";import{SDKModel as o,ServiceWorkerManager as a,RuntimeModel as l,ChildTargetManager as d,DOMModel as h,ResourceTreeModel as c,NetworkManager as u}from"../sdk/sdk.js";import{DeviceModeModel as p,EmulatedDevices as g,InspectedPagePlaceholder as m}from"../emulation/emulation.js";import{userMetrics as _,UserMetrics as f}from"../host/host.js";import{Runtime as b}from"../root/root.js";import{UIUtils as y,Tooltip as v,InspectorView as w,Toolbar as C,ARIAUtils as S,Fragment as T,Widget as x,XLink as L,Dialog as E,Utils as A,GlassPane as k,Geometry as P,Panel as R,DropTarget as M}from"../ui/ui.js";import{serviceManager as I}from"../services/services.js";import{Linkifier as D}from"../components/components.js";import{DateUtilities as O}from"../platform/platform.js";import{ThemeSupport as U}from"../theme_support/theme_support.js";import{TimelinePanel as N}from"../timeline/timeline.js";import{FileManager as B}from"../workspace/workspace.js";
/**
 * @license
 * Copyright 2017 The Lighthouse Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const F={label:"pass",minScore:.9},H={label:"average",minScore:.5},$={label:"fail"},j={label:"error"},G=["com","co","gov","edu","ac","org","go","gob","or","net","in","ne","nic","gouv","web","spb","blog","jus","kiev","mil","wi","qc","ca","bel","on"];class V{static get PASS_THRESHOLD(){return.9}static get MS_DISPLAY_VALUE(){return"%10d ms"}static prepareReportResult(e){const t=JSON.parse(JSON.stringify(e));t.configSettings.locale||(t.configSettings.locale="en");for(const e of Object.values(t.audits))if("not_applicable"!==e.scoreDisplayMode&&"not-applicable"!==e.scoreDisplayMode||(e.scoreDisplayMode="notApplicable"),e.details&&(void 0!==e.details.type&&"diagnostic"!==e.details.type||(e.details.type="debugdata"),"filmstrip"===e.details.type))for(const t of e.details.items)t.data.startsWith("data:image/jpeg;base64,")||(t.data="data:image/jpeg;base64,"+t.data);if("object"!=typeof t.categories)throw new Error("No categories provided.");for(const e of Object.values(t.categories))e.auditRefs.forEach((e=>{const i=t.audits[e.id];e.result=i,t.stackPacks&&t.stackPacks.forEach((t=>{t.descriptions[e.id]&&(e.stackPacks=e.stackPacks||[],e.stackPacks.push({title:t.title,iconDataURL:t.iconDataURL,description:t.descriptions[e.id]}))}))}));return t}static showAsPassed(e){switch(e.scoreDisplayMode){case"manual":case"notApplicable":return!0;case"error":case"informative":return!1;case"numeric":case"binary":default:return Number(e.score)>=F.minScore}}static calculateRating(e,t){if("manual"===t||"notApplicable"===t)return F.label;if("error"===t)return j.label;if(null===e)return $.label;let i=$.label;return e>=F.minScore?i=F.label:e>=H.minScore&&(i=H.label),i}static splitMarkdownCodeSpans(e){const t=[],i=e.split(/`(.*?)`/g);for(let e=0;e<i.length;e++){const s=i[e];if(!s)continue;const n=e%2!=0;t.push({isCode:n,text:s})}return t}static splitMarkdownLink(e){const t=[],i=e.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);for(;i.length;){const[e,s,n]=i.splice(0,3);e&&t.push({isLink:!1,text:e}),s&&n&&t.push({isLink:!0,text:s,linkHref:n})}return t}static getURLDisplayName(e,t){const i=void 0!==(t=t||{numPathParts:void 0,preserveQuery:void 0,preserveHost:void 0}).numPathParts?t.numPathParts:2,s=void 0===t.preserveQuery||t.preserveQuery,n=t.preserveHost||!1;let r;if("about:"===e.protocol||"data:"===e.protocol)r=e.href;else{r=e.pathname;const t=r.split("/").filter((e=>e.length));i&&t.length>i&&(r="…"+t.slice(-1*i).join("/")),n&&(r=`${e.host}/${r.replace(/^\//,"")}`),s&&(r=`${r}${e.search}`)}if(r=r.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g,"$1…"),r=r.replace(/([a-zA-Z0-9-_]{9})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9-_]{10,}/g,"$1…"),r=r.replace(/(\d{3})\d{6,}/g,"$1…"),r=r.replace(/\u2026+/g,"…"),r.length>64&&r.includes("?")&&(r=r.replace(/\?([^=]*)(=)?.*/,"?$1$2…"),r.length>64&&(r=r.replace(/\?.*/,"?…"))),r.length>64){const e=r.lastIndexOf(".");r=e>=0?r.slice(0,63-(r.length-e))+"…"+r.slice(e):r.slice(0,63)+"…"}return r}static parseURL(e){const t=new URL(e);return{file:V.getURLDisplayName(t),hostname:t.hostname,origin:t.origin}}static createOrReturnURL(e){return e instanceof URL?e:new URL(e)}static getTld(e){const t=e.split(".").slice(-2);return G.includes(t[0])?"."+t.join("."):"."+t[t.length-1]}static getRootDomain(e){const t=V.createOrReturnURL(e).hostname,i=V.getTld(t).split(".");return t.split(".").slice(-i.length).join(".")}static getEnvironmentDisplayValues(e){const t=V.getEmulationDescriptions(e);return[{name:V.i18n.strings.runtimeSettingsDevice,description:t.deviceEmulation},{name:V.i18n.strings.runtimeSettingsNetworkThrottling,description:t.networkThrottling},{name:V.i18n.strings.runtimeSettingsCPUThrottling,description:t.cpuThrottling}]}static getEmulationDescriptions(e){let t,i;const s=e.throttling;switch(e.throttlingMethod){case"provided":t=V.i18n.strings.throttlingProvided,i=V.i18n.strings.throttlingProvided;break;case"devtools":{const{cpuSlowdownMultiplier:e,requestLatencyMs:n}=s;t=V.i18n.formatNumber(e)+"x slowdown (DevTools)",i=V.i18n.formatNumber(n)+" ms HTTP RTT, "+V.i18n.formatNumber(s.downloadThroughputKbps)+" Kbps down, "+V.i18n.formatNumber(s.uploadThroughputKbps)+" Kbps up (DevTools)";break}case"simulate":{const{cpuSlowdownMultiplier:e,rttMs:n,throughputKbps:r}=s;t=V.i18n.formatNumber(e)+"x slowdown (Simulated)",i=V.i18n.formatNumber(n)+" ms TCP RTT, "+V.i18n.formatNumber(r)+" Kbps throughput (Simulated)";break}default:t=V.i18n.strings.runtimeUnknown,i=V.i18n.strings.runtimeUnknown}let n=V.i18n.strings.runtimeNoEmulation;return"mobile"===e.emulatedFormFactor?n=V.i18n.strings.runtimeMobileEmulation:"desktop"===e.emulatedFormFactor&&(n=V.i18n.strings.runtimeDesktopEmulation),{deviceEmulation:n,cpuThrottling:t,networkThrottling:i}}static filterRelevantLines(e,t,i){if(0===t.length)return e.slice(0,2*i+1);const s=new Set;return(t=t.sort(((e,t)=>(e.lineNumber||0)-(t.lineNumber||0)))).forEach((({lineNumber:e})=>{let t=e-i,n=e+i;for(;t<1;)t++,n++;s.has(t-3-1)&&(t-=3);for(let e=t;e<=n;e++){const t=e;s.add(t)}})),e.filter((e=>s.has(e.lineNumber)))}static isPluginCategory(e){return e.startsWith("lighthouse-plugin-")}}V.reportJson=null,V.getUniqueSuffix=(()=>{let e=0;return function(){return e++}})(),V.i18n=null,V.UIStrings={varianceDisclaimer:"Values are estimated and may vary. The [performance score is calculated](https://web.dev/performance-scoring/) directly from these metrics.",calculatorLink:"See calculator.",opportunityResourceColumnLabel:"Opportunity",opportunitySavingsColumnLabel:"Estimated Savings",errorMissingAuditInfo:"Report error: no audit information",errorLabel:"Error!",warningHeader:"Warnings: ",auditGroupExpandTooltip:"Show audits",warningAuditsGroupTitle:"Passed audits but with warnings",passedAuditsGroupTitle:"Passed audits",notApplicableAuditsGroupTitle:"Not applicable",manualAuditsGroupTitle:"Additional items to manually check",toplevelWarningsMessage:"There were issues affecting this run of Lighthouse:",crcInitialNavigation:"Initial Navigation",crcLongestDurationLabel:"Maximum critical path latency:",snippetExpandButtonLabel:"Expand snippet",snippetCollapseButtonLabel:"Collapse snippet",lsPerformanceCategoryDescription:"[Lighthouse](https://developers.google.com/web/tools/lighthouse/) analysis of the current page on an emulated mobile network. Values are estimated and may vary.",labDataTitle:"Lab Data",thirdPartyResourcesLabel:"Show 3rd-party resources",dropdownPrintSummary:"Print Summary",dropdownPrintExpanded:"Print Expanded",dropdownCopyJSON:"Copy JSON",dropdownSaveHTML:"Save as HTML",dropdownSaveJSON:"Save as JSON",dropdownViewer:"Open in Viewer",dropdownSaveGist:"Save as Gist",dropdownDarkTheme:"Toggle Dark Theme",runtimeSettingsTitle:"Runtime Settings",runtimeSettingsUrl:"URL",runtimeSettingsFetchTime:"Fetch Time",runtimeSettingsDevice:"Device",runtimeSettingsNetworkThrottling:"Network throttling",runtimeSettingsCPUThrottling:"CPU throttling",runtimeSettingsChannel:"Channel",runtimeSettingsUA:"User agent (host)",runtimeSettingsUANetwork:"User agent (network)",runtimeSettingsBenchmark:"CPU/Memory Power",runtimeSettingsAxeVersion:"Axe version",footerIssue:"File an issue",runtimeNoEmulation:"No emulation",runtimeMobileEmulation:"Emulated Moto G4",runtimeDesktopEmulation:"Emulated Desktop",runtimeUnknown:"Unknown",throttlingProvided:"Provided by environment"},"undefined"!=typeof module&&module.exports?module.exports=V:self.Util=V;class W{constructor(e){this._document=e,this._lighthouseChannel="unknown"}createElement(e,t,i={}){const s=this._document.createElement(e);return t&&(s.className=t),Object.keys(i).forEach((e=>{const t=i[e];void 0!==t&&s.setAttribute(e,t)})),s}createElementNS(e,t,i,s={}){const n=this._document.createElementNS(e,t);return i&&(n.className=i),Object.keys(s).forEach((e=>{const t=s[e];void 0!==t&&n.setAttribute(e,t)})),n}createFragment(){return this._document.createDocumentFragment()}createChildOf(e,t,i,s){const n=this.createElement(t,i,s);return e.appendChild(n),n}cloneTemplate(e,t){const i=t.querySelector(e);if(!i)throw new Error("Template not found: template"+e);const s=this._document.importNode(i.content,!0);return i.hasAttribute("data-stamped")&&this.findAll("style",s).forEach((e=>e.remove())),i.setAttribute("data-stamped","true"),s}resetTemplates(){this.findAll("template[data-stamped]",this._document).forEach((e=>{e.removeAttribute("data-stamped")}))}convertMarkdownLinkSnippets(e){const t=this.createElement("span");for(const i of V.splitMarkdownLink(e)){if(!i.isLink){t.appendChild(this._document.createTextNode(i.text));continue}const e=new URL(i.linkHref);["https://developers.google.com","https://web.dev"].includes(e.origin)&&(e.searchParams.set("utm_source","lighthouse"),e.searchParams.set("utm_medium",this._lighthouseChannel));const s=this.createElement("a");s.rel="noopener",s.target="_blank",s.textContent=i.text,s.href=e.href,t.appendChild(s)}return t}convertMarkdownCodeSnippets(e){const t=this.createElement("span");for(const i of V.splitMarkdownCodeSpans(e))if(i.isCode){const e=this.createElement("code");e.textContent=i.text,t.appendChild(e)}else t.appendChild(this._document.createTextNode(i.text));return t}setLighthouseChannel(e){this._lighthouseChannel=e}document(){return this._document}isDevTools(){return!!this._document.querySelector(".lh-devtools")}find(e,t){const i=t.querySelector(e);if(null===i)throw new Error(`query ${e} not found`);return i}findAll(e,t){return Array.from(t.querySelectorAll(e))}}"undefined"!=typeof module&&module.exports?module.exports=W:self.DOM=W,function(){var e,t,i,s,n=document.createElement("details"),r="undefined"!=typeof HTMLDetailsElement&&n instanceof HTMLDetailsElement,o="open"in n||r,a="ontoggle"in n,l='\ndetails, summary {\n  display: block;\n}\ndetails:not([open]) > *:not(summary) {\n  display: none;\n}\nsummary::before {\n  content: "►";\n  padding-right: 0.3rem;\n  font-size: 0.6rem;\n  cursor: default;\n}\n[open] > summary::before {\n  content: "▼";\n}\n',d=[],h=d.forEach,c=d.slice;function u(e){(function(e,t){return(e.tagName==t?[e]:[]).concat("function"==typeof e.getElementsByTagName?c.call(e.getElementsByTagName(t)):[])})(e,"SUMMARY").forEach((function(e){var t=_(e,"DETAILS");e.setAttribute("aria-expanded",t.hasAttribute("open")),e.hasAttribute("tabindex")||e.setAttribute("tabindex","0"),e.hasAttribute("role")||e.setAttribute("role","button")}))}function p(e){return!(e.defaultPrevented||e.ctrlKey||e.metaKey||e.shiftKey||e.target.isContentEditable)}function g(e){addEventListener("click",(function(t){if(p(t)&&t.which<=1){var i=_(t.target,"SUMMARY");i&&i.parentNode&&"DETAILS"==i.parentNode.tagName&&e(i.parentNode)}}),!1),addEventListener("keydown",(function(t){if(p(t)&&(13==t.keyCode||32==t.keyCode)){var i=_(t.target,"SUMMARY");i&&i.parentNode&&"DETAILS"==i.parentNode.tagName&&(e(i.parentNode),t.preventDefault())}}),!1)}function m(e){var t=document.createEvent("Event");t.initEvent("toggle",!1,!1),e.dispatchEvent(t)}function _(e,t){if("function"==typeof e.closest)return e.closest(t);for(;e;){if(e.tagName==t)return e;e=e.parentNode}}o||(document.head.insertAdjacentHTML("afterbegin","<style>"+l+"</style>"),e=document.createElement("details").constructor.prototype,t=e.setAttribute,i=e.removeAttribute,s=Object.getOwnPropertyDescriptor(e,"open"),Object.defineProperties(e,{open:{get:function(){return"DETAILS"==this.tagName?this.hasAttribute("open"):s&&s.get?s.get.call(this):void 0},set:function(e){return"DETAILS"==this.tagName?e?this.setAttribute("open",""):this.removeAttribute("open"):s&&s.set?s.set.call(this,e):void 0}},setAttribute:{value:function(e,i){var s=this,n=function(){return t.call(s,e,i)};if("open"==e&&"DETAILS"==this.tagName){var r=this.hasAttribute("open"),o=n();if(!r){var a=this.querySelector("summary");a&&a.setAttribute("aria-expanded",!0),m(this)}return o}return n()}},removeAttribute:{value:function(e){var t=this,s=function(){return i.call(t,e)};if("open"==e&&"DETAILS"==this.tagName){var n=this.hasAttribute("open"),r=s();if(n){var o=this.querySelector("summary");o&&o.setAttribute("aria-expanded",!1),m(this)}return r}return s()}}}),g((function(e){e.hasAttribute("open")?e.removeAttribute("open"):e.setAttribute("open","")})),u(document),window.MutationObserver?new MutationObserver((function(e){h.call(e,(function(e){h.call(e.addedNodes,u)}))})).observe(document.documentElement,{subtree:!0,childList:!0}):document.addEventListener("DOMNodeInserted",(function(e){u(e.target)}))),o&&!a&&(window.MutationObserver?new MutationObserver((function(e){h.call(e,(function(e){var t=e.target,i=e.attributeName;"DETAILS"==t.tagName&&"open"==i&&m(t)}))})).observe(document.documentElement,{attributes:!0,subtree:!0}):g((function(e){var t=e.getAttribute("open");setTimeout((function(){var i=e.getAttribute("open");t!=i&&m(e)}),1)})))}();const q=["http://","https://","data:"];class z{constructor(e,t={}){this._dom=e,this._fullPageScreenshot=t.fullPageScreenshot,this._templateContext}setTemplateContext(e){this._templateContext=e}render(e){switch(e.type){case"filmstrip":return this._renderFilmstrip(e);case"list":return this._renderList(e);case"table":return this._renderTable(e);case"criticalrequestchain":return J.render(this._dom,this._templateContext,e,this);case"opportunity":return this._renderTable(e);case"screenshot":case"debugdata":case"full-page-screenshot":return null;default:return this._renderUnknown(e.type,e)}}_renderBytes(e){const t=V.i18n.formatBytesToKiB(e.value,e.granularity),i=this._renderText(t);return i.title=V.i18n.formatBytes(e.value),i}_renderMilliseconds(e){let t=V.i18n.formatMilliseconds(e.value,e.granularity);return"duration"===e.displayUnit&&(t=V.i18n.formatDuration(e.value)),this._renderText(t)}renderTextURL(e){const t=e;let i,s,n;try{const e=V.parseURL(t);i="/"===e.file?e.origin:e.file,s="/"===e.file||""===e.hostname?"":`(${e.hostname})`,n=t}catch(e){i=t}const r=this._dom.createElement("div","lh-text__url");if(r.appendChild(this._renderLink({text:i,url:t})),s){const e=this._renderText(s);e.classList.add("lh-text__url-host"),r.appendChild(e)}return n&&(r.title=t,r.dataset.url=t),r}_renderLink(e){let t;try{t=new URL(e.url)}catch(e){}if(!t||!["https:","http:"].includes(t.protocol)){const t=this._renderText(e.text);return t.classList.add("lh-link"),t}const i=this._dom.createElement("a");return i.rel="noopener",i.target="_blank",i.textContent=e.text,i.href=t.href,i.classList.add("lh-link"),i}_renderText(e){const t=this._dom.createElement("div","lh-text");return t.textContent=e,t}_renderNumeric(e){const t=V.i18n.formatNumber(e.value,e.granularity),i=this._dom.createElement("div","lh-numeric");return i.textContent=t,i}_renderThumbnail(e){const t=this._dom.createElement("img","lh-thumbnail"),i=e;return t.src=i,t.title=i,t.alt="",t}_renderUnknown(e,t){console.error("Unknown details type: "+e,t);const i=this._dom.createElement("details","lh-unknown");return this._dom.createChildOf(i,"summary").textContent=`We don't know how to render audit details of type \`${e}\`. The Lighthouse version that collected this data is likely newer than the Lighthouse version of the report renderer. Expand for the raw JSON.`,this._dom.createChildOf(i,"pre").textContent=JSON.stringify(t,null,2),i}_renderTableValue(e,t){if(null==e)return null;if("object"==typeof e)switch(e.type){case"code":return this._renderCode(e.value);case"link":return this._renderLink(e);case"node":return this.renderNode(e);case"numeric":return this._renderNumeric(e);case"source-location":return this.renderSourceLocation(e);case"url":return this.renderTextURL(e.value);default:return this._renderUnknown(e.type,e)}switch(t.valueType){case"bytes":{const i=Number(e);return this._renderBytes({value:i,granularity:t.granularity})}case"code":{const t=String(e);return this._renderCode(t)}case"ms":{const i={value:Number(e),granularity:t.granularity,displayUnit:t.displayUnit};return this._renderMilliseconds(i)}case"numeric":{const i=Number(e);return this._renderNumeric({value:i,granularity:t.granularity})}case"text":{const t=String(e);return this._renderText(t)}case"thumbnail":{const t=String(e);return this._renderThumbnail(t)}case"timespanMs":{const t=Number(e);return this._renderMilliseconds({value:t})}case"url":{const t=String(e);return q.some((e=>t.startsWith(e)))?this.renderTextURL(t):this._renderCode(t)}default:return this._renderUnknown(t.valueType,e)}}_getCanonicalizedHeadingsFromTable(e){return"opportunity"===e.type?e.headings:e.headings.map((e=>this._getCanonicalizedHeading(e)))}_getCanonicalizedHeading(e){let t;return e.subItemsHeading&&(t=this._getCanonicalizedsubItemsHeading(e.subItemsHeading,e)),{key:e.key,valueType:e.itemType,subItemsHeading:t,label:e.text,displayUnit:e.displayUnit,granularity:e.granularity}}_getCanonicalizedsubItemsHeading(e,t){return e.key||console.warn("key should not be null"),{key:e.key||"",valueType:e.itemType||t.itemType,granularity:e.granularity||t.granularity,displayUnit:e.displayUnit||t.displayUnit}}_getDerivedsubItemsHeading(e){return e.subItemsHeading?{key:e.subItemsHeading.key||"",valueType:e.subItemsHeading.valueType||e.valueType,granularity:e.subItemsHeading.granularity||e.granularity,displayUnit:e.subItemsHeading.displayUnit||e.displayUnit,label:""}:null}_renderTableRow(e,t){const i=this._dom.createElement("tr");for(const s of t){if(!s||!s.key){this._dom.createChildOf(i,"td","lh-table-column--empty");continue}const t=e[s.key];let n;if(null!=t&&(n=this._renderTableValue(t,s)),n){const e="lh-table-column--"+s.valueType;this._dom.createChildOf(i,"td",e).appendChild(n)}else this._dom.createChildOf(i,"td","lh-table-column--empty")}return i}_renderTableRowsFromItem(e,t){const i=this._dom.createFragment();if(i.append(this._renderTableRow(e,t)),!e.subItems)return i;const s=t.map(this._getDerivedsubItemsHeading);if(!s.some(Boolean))return i;for(const t of e.subItems.items){const e=this._renderTableRow(t,s);e.classList.add("lh-sub-item-row"),i.append(e)}return i}_renderTable(e){if(!e.items.length)return this._dom.createElement("span");const t=this._dom.createElement("table","lh-table"),i=this._dom.createChildOf(t,"thead"),s=this._dom.createChildOf(i,"tr"),n=this._getCanonicalizedHeadingsFromTable(e);for(const e of n){const t="lh-table-column--"+(e.valueType||"text"),i=this._dom.createElement("div","lh-text");i.textContent=e.label,this._dom.createChildOf(s,"th",t).appendChild(i)}const r=this._dom.createChildOf(t,"tbody");let o=!0;for(const t of e.items){const e=this._renderTableRowsFromItem(t,n);for(const t of this._dom.findAll("tr",e))t.classList.add(o?"lh-row--even":"lh-row--odd");o=!o,r.append(e)}return t}_renderList(e){const t=this._dom.createElement("div","lh-list");return e.items.forEach((e=>{const i=ae.render(this._dom,this._templateContext,e,this);t.appendChild(i)})),t}renderNode(e){const t=this._dom.createElement("span","lh-node");if(e.nodeLabel){const i=this._dom.createElement("div");i.textContent=e.nodeLabel,t.appendChild(i)}if(e.snippet){const i=this._dom.createElement("div");i.classList.add("lh-node__snippet"),i.textContent=e.snippet,t.appendChild(i)}if(e.selector&&(t.title=e.selector),e.path&&t.setAttribute("data-path",e.path),e.selector&&t.setAttribute("data-selector",e.selector),e.snippet&&t.setAttribute("data-snippet",e.snippet),!e.boundingRect||!this._fullPageScreenshot)return t;const i=de.render(this._dom,this._templateContext,this._fullPageScreenshot,e.boundingRect,{width:147,height:100});return t.prepend(i),t}renderSourceLocation(e){if(!e.url)return null;const t=e.line+1,i=e.column;let s;return"network"===e.urlProvider?(s=this.renderTextURL(e.url),this._dom.find(".lh-link",s).textContent+=`:${t}:${i}`):s=this._renderText(`${e.url}:${t}:${i} (from sourceURL)`),s.classList.add("lh-source-location"),s.setAttribute("data-source-url",e.url),s.setAttribute("data-source-line",String(e.line)),s.setAttribute("data-source-column",String(e.column)),s}_renderFilmstrip(e){const t=this._dom.createElement("div","lh-filmstrip");for(const i of e.items){const e=this._dom.createChildOf(t,"div","lh-filmstrip__frame");this._dom.createChildOf(e,"img","lh-filmstrip__thumbnail",{src:i.data,alt:"Screenshot"})}return t}_renderCode(e){const t=this._dom.createElement("pre","lh-code");return t.textContent=e,t}}"undefined"!=typeof module&&module.exports?module.exports=z:self.DetailsRenderer=z;class J{static initTree(e){let t=0;const i=Object.keys(e);if(i.length>0){t=e[i[0]].request.startTime}return{tree:e,startTime:t,transferSize:0}}static createSegment(e,t,i,s,n,r){const o=e[t],a=Object.keys(e),l=a.indexOf(t)===a.length-1,d=!!o.children&&Object.keys(o.children).length>0,h=Array.isArray(n)?n.slice(0):[];return void 0!==r&&h.push(!r),{node:o,isLastChild:l,hasChildren:d,startTime:i,transferSize:s+o.request.transferSize,treeMarkers:h}}static createChainNode(e,t,i,s){const n=e.cloneTemplate("#tmpl-lh-crc__chains",t);e.find(".crc-node",n).setAttribute("title",i.node.request.url);const r=e.find(".crc-node__tree-marker",n);i.treeMarkers.forEach((t=>{t?(r.appendChild(e.createElement("span","tree-marker vert")),r.appendChild(e.createElement("span","tree-marker"))):(r.appendChild(e.createElement("span","tree-marker")),r.appendChild(e.createElement("span","tree-marker")))})),i.isLastChild?(r.appendChild(e.createElement("span","tree-marker up-right")),r.appendChild(e.createElement("span","tree-marker right"))):(r.appendChild(e.createElement("span","tree-marker vert-right")),r.appendChild(e.createElement("span","tree-marker right"))),i.hasChildren?r.appendChild(e.createElement("span","tree-marker horiz-down")):r.appendChild(e.createElement("span","tree-marker right"));const o=i.node.request.url,a=s.renderTextURL(o),l=e.find(".crc-node__tree-value",n);if(l.appendChild(a),!i.hasChildren){const{startTime:t,endTime:s,transferSize:n}=i.node.request,r=e.createElement("span","crc-node__chain-duration");r.textContent=" - "+V.i18n.formatMilliseconds(1e3*(s-t))+", ";const o=e.createElement("span","crc-node__chain-duration");o.textContent=V.i18n.formatBytesToKiB(n,.01),l.appendChild(r),l.appendChild(o)}return n}static buildTree(e,t,i,s,n,r){if(s.appendChild(K.createChainNode(e,t,i,r)),i.node.children)for(const o of Object.keys(i.node.children)){const a=K.createSegment(i.node.children,o,i.startTime,i.transferSize,i.treeMarkers,i.isLastChild);K.buildTree(e,t,a,s,n,r)}}static render(e,t,i,s){const n=e.cloneTemplate("#tmpl-lh-crc",t),r=e.find(".lh-crc",n);e.find(".crc-initial-nav",n).textContent=V.i18n.strings.crcInitialNavigation,e.find(".lh-crc__longest_duration_label",n).textContent=V.i18n.strings.crcLongestDurationLabel,e.find(".lh-crc__longest_duration",n).textContent=V.i18n.formatMilliseconds(i.longestChain.duration);const o=K.initTree(i.chains);for(const t of Object.keys(o.tree)){const a=K.createSegment(o.tree,t,o.startTime,o.transferSize);K.buildTree(e,n,a,r,i,s)}return e.find(".lh-crc-container",n)}}const K=J;"undefined"!=typeof module&&module.exports?module.exports=J:self.CriticalRequestChainRenderer=J;const Y=0,Q=1,Z=2,X=0,ee=1,te=2,ie=3,se={[X]:["lh-snippet__line--content"],[ee]:["lh-snippet__line--content","lh-snippet__line--content-highlighted"],[te]:["lh-snippet__line--placeholder"],[ie]:["lh-snippet__line--message"]};function ne(e,t){return{line:e.find((e=>e.lineNumber===t)),previousLine:e.find((e=>e.lineNumber===t-1))}}function re(e,t){return e.filter((e=>e.lineNumber===t))}function oe(e){return V.filterRelevantLines(e.lines,e.lineMessages,2)}class ae{static renderHeader(e,t,i,s,n){const r=oe(i).length<i.lines.length,o=e.cloneTemplate("#tmpl-lh-snippet__header",t);e.find(".lh-snippet__title",o).textContent=i.title;const{snippetCollapseButtonLabel:a,snippetExpandButtonLabel:l}=V.i18n.strings;e.find(".lh-snippet__btn-label-collapse",o).textContent=a,e.find(".lh-snippet__btn-label-expand",o).textContent=l;const d=e.find(".lh-snippet__toggle-expand",o);if(r?d.addEventListener("click",(()=>n())):d.remove(),i.node&&e.isDevTools()){e.find(".lh-snippet__node",o).appendChild(s.renderNode(i.node))}return o}static renderSnippetLine(e,t,{content:i,lineNumber:s,truncated:n,contentType:r,visibility:o}){const a=e.cloneTemplate("#tmpl-lh-snippet__line",t),l=e.find(".lh-snippet__line",a),{classList:d}=l;se[r].forEach((e=>d.add(e))),o===Q?d.add("lh-snippet__show-if-collapsed"):o===Z&&d.add("lh-snippet__show-if-expanded");const h=i+(n?"…":""),c=e.find(".lh-snippet__line code",l);return r===ie?c.appendChild(e.convertMarkdownLinkSnippets(h)):c.textContent=h,e.find(".lh-snippet__line-number",l).textContent=s.toString(),l}static renderMessage(e,t,i){return ae.renderSnippetLine(e,t,{lineNumber:" ",content:i.message,contentType:ie})}static renderOmittedLinesPlaceholder(e,t,i){return ae.renderSnippetLine(e,t,{lineNumber:"…",content:"",visibility:i,contentType:te})}static renderSnippetContent(e,t,i){const s=e.cloneTemplate("#tmpl-lh-snippet__content",t),n=e.find(".lh-snippet__snippet-inner",s);return i.generalMessages.forEach((i=>n.append(ae.renderMessage(e,t,i)))),n.append(ae.renderSnippetLines(e,t,i)),s}static renderSnippetLines(e,t,i){const{lineMessages:s,generalMessages:n,lineCount:r,lines:o}=i,a=oe(i),l=n.length>0&&0===s.length,d=e.createFragment();let h=!1;for(let i=1;i<=r;i++){const{line:n,previousLine:r}=ne(o,i),{line:c,previousLine:u}=ne(a,i),p=!!c;!!u&&!p&&(h=!0),p&&h&&(d.append(ae.renderOmittedLinesPlaceholder(e,t,Q)),h=!1);const g=!n&&1===i;if(!n&&!!r||g){const s=!a.some((e=>e.lineNumber>i))||1===i;d.append(ae.renderOmittedLinesPlaceholder(e,t,s?Z:Y)),h=!1}if(!n)continue;const m=re(s,i),_=m.length>0||l,f=Object.assign({},n,{contentType:_?ee:X,visibility:c?Y:Z});d.append(ae.renderSnippetLine(e,t,f)),m.forEach((i=>{d.append(ae.renderMessage(e,t,i))}))}return d}static render(e,t,i,s){const n=e.cloneTemplate("#tmpl-lh-snippet",t),r=e.find(".lh-snippet",n),o=ae.renderHeader(e,n,i,s,(()=>r.classList.toggle("lh-snippet--expanded"))),a=ae.renderSnippetContent(e,n,i);return r.append(o,a),r}}function le(e,t,i){return e<t?t:e>i?i:e}"undefined"!=typeof module&&module.exports?module.exports=ae:self.SnippetRenderer=ae;class de{static getScreenshotPositions(e,t,i){const s={x:(n=e).left+n.width/2,y:n.top+n.height/2};var n;const r=le(s.x-t.width/2,0,i.width-t.width),o=le(s.y-t.height/2,0,i.height-t.height);return{screenshot:{left:r,top:o},clip:{left:e.left-r,top:e.top-o}}}static renderClipPathInScreenshot(e,t,i,s,n){const r=e.find("clipPath",t),o="clip-"+V.getUniqueSuffix();r.id=o,t.style.clipPath=`url(#${o})`;const a=i.top/n.height,l=a+s.height/n.height,d=i.left/n.width,h=d+s.width/n.width,c=[`0,0             1,0            1,${a}          0,${a}`,`0,${l}     1,${l}    1,1               0,1`,`0,${a}        ${d},${a} ${d},${l} 0,${l}`,`${h},${a} 1,${a}       1,${l}       ${h},${l}`];for(const t of c)r.append(e.createElementNS("http://www.w3.org/2000/svg","polygon",void 0,{points:t}))}static createBackgroundImageStyle(e,t){const i=e.createElement("style");return i.id="full-page-screenshot-style",i.textContent=`\n      .lh-element-screenshot__image {\n        background-image: url(${t.data})\n      }`,i}static installOverlayFeature(e,t,i){const s=e.find(".lh-report",e.document()),n="lh-feature-screenshot-overlay";if(s.classList.contains(n))return;s.classList.add(n);const r={width:e.document().documentElement.clientWidth,height:.75*e.document().documentElement.clientHeight};e.document().addEventListener("click",(n=>{const o=n.target;if(!o)return;const a=o.closest(".lh-element-screenshot");if(!a)return;const l=e.createElement("div");l.classList.add("lh-element-screenshot__overlay");const d={width:Number(a.dataset.rectWidth),height:Number(a.dataset.rectHeight),left:Number(a.dataset.rectLeft),right:Number(a.dataset.rectLeft)+Number(a.dataset.rectWidth),top:Number(a.dataset.rectTop),bottom:Number(a.dataset.rectTop)+Number(a.dataset.rectHeight)};l.appendChild(de.render(e,t,i,d,r)),l.addEventListener("click",(()=>{l.remove()})),s.appendChild(l)}))}static _computeZoomFactor(e,t){const i={x:t.width/e.width,y:t.height/e.height},s=.75*Math.min(i.x,i.y);return Math.min(1,s)}static render(e,t,i,s,n){const r=e.cloneTemplate("#tmpl-lh-element-screenshot",t),o=e.find(".lh-element-screenshot",r);o.dataset.rectWidth=s.width.toString(),o.dataset.rectHeight=s.height.toString(),o.dataset.rectLeft=s.left.toString(),o.dataset.rectTop=s.top.toString();const a=this._computeZoomFactor(s,n),l={width:n.width/a,height:n.height/a};l.width=Math.min(i.width,l.width);const d=l.width*a,h=l.height*a,c=de.getScreenshotPositions(s,l,{width:i.width,height:i.height});e.find(".lh-element-screenshot__content",o).style.top=`-${h}px`;const u=e.find(".lh-element-screenshot__image",o);u.style.width=d+"px",u.style.height=h+"px",u.style.backgroundPositionY=-c.screenshot.top*a+"px",u.style.backgroundPositionX=-c.screenshot.left*a+"px",u.style.backgroundSize=`${i.width*a}px ${i.height*a}px`;const p=e.find(".lh-element-screenshot__element-marker",o);p.style.width=s.width*a+"px",p.style.height=s.height*a+"px",p.style.left=c.clip.left*a+"px",p.style.top=c.clip.top*a+"px";const g=e.find(".lh-element-screenshot__mask",o);return g.style.width=d+"px",g.style.height=h+"px",de.renderClipPathInScreenshot(e,g,c.clip,s,l),o}}function he(e){const t=new URL(e.finalUrl).hostname,i=e.fetchTime&&new Date(e.fetchTime)||new Date,s=i.toLocaleTimeString("en-US",{hour12:!1}),n=i.toLocaleDateString("en-US",{year:"numeric",month:"2-digit",day:"2-digit"}).split("/");n.unshift(n.pop());return`${t}_${n.join("-")}_${s}`.replace(/[/?<>\\:*|"]/g,"-")}"undefined"!=typeof module&&module.exports?module.exports=de:self.ElementScreenshotRenderer=de,"undefined"!=typeof module&&module.exports&&(module.exports={getFilenamePrefix:he});class ce{constructor(e){this.el=e,this._id=void 0}log(e,t=!0){this._id&&clearTimeout(this._id),this.el.textContent=e,this.el.classList.add("show"),t&&(this._id=setTimeout((e=>{this.el.classList.remove("show")}),7e3))}warn(e){this.log("Warning: "+e)}error(e){this.log(e),setTimeout((t=>{throw new Error(e)}),0)}hide(){this._id&&clearTimeout(this._id),this.el.classList.remove("show")}}"undefined"!=typeof module&&module.exports&&(module.exports=ce);class ue{constructor(e){this.json,this._dom=e,this._document=this._dom.document(),this._templateContext=this._dom.document(),this._dropDown=new pe(this._dom),this._copyAttempt=!1,this.topbarEl,this.scoreScaleEl,this.stickyHeaderEl,this.highlightEl,this.onMediaQueryChange=this.onMediaQueryChange.bind(this),this.onCopy=this.onCopy.bind(this),this.onDropDownMenuClick=this.onDropDownMenuClick.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.collapseAllDetails=this.collapseAllDetails.bind(this),this.expandAllDetails=this.expandAllDetails.bind(this),this._toggleDarkTheme=this._toggleDarkTheme.bind(this),this._updateStickyHeaderOnScroll=this._updateStickyHeaderOnScroll.bind(this)}initFeatures(e){this.json=e,this._setupMediaQueryListeners(),this._dropDown.setup(this.onDropDownMenuClick),this._setupThirdPartyFilter(),this._setupElementScreenshotOverlay(),this._setUpCollapseDetailsAfterPrinting(),this._resetUIState(),this._document.addEventListener("keyup",this.onKeyUp),this._document.addEventListener("copy",this.onCopy);this._dom.find(".lh-topbar__logo",this._document).addEventListener("click",(()=>this._toggleDarkTheme()));let t=!1;!this._dom.isDevTools()&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(t=!0);if(["performance","accessibility","best-practices","seo"].every((t=>{const i=e.categories[t];return i&&1===i.score}))&&(t=!0,this._enableFireworks()),t&&this._toggleDarkTheme(!0),Object.keys(this.json.categories).length>=2){this._setupStickyHeaderElements();const e=this._dom.find(".lh-container",this._document);if(this._getScrollParent(e).addEventListener("scroll",this._updateStickyHeaderOnScroll),this._dom.isDevTools()){new window.ResizeObserver(this._updateStickyHeaderOnScroll).observe(e)}else window.addEventListener("resize",this._updateStickyHeaderOnScroll)}if(e.categories.performance&&e.categories.performance.auditRefs.some((t=>Boolean("metrics"===t.group&&e.audits[t.id].errorMessage)))){this._dom.find(".lh-metrics-toggle__input",this._document).checked=!0}for(const e of this._dom.findAll("[data-i18n]",this._dom.document())){const t=e.getAttribute("data-i18n");e.textContent=V.i18n.strings[t]}}setTemplateContext(e){this._templateContext=e}_getScrollParent(e){const{overflowY:t}=window.getComputedStyle(e);return"visible"!==t&&"hidden"!==t?e:e.parentElement?this._getScrollParent(e.parentElement):document}_enableFireworks(){const e=this._dom.find(".lh-scores-container",this._document);e.classList.add("score100"),e.addEventListener("click",(t=>{e.classList.toggle("fireworks-paused")}))}_fireEventOn(e,t=this._document,i){const s=new CustomEvent(e,i?{detail:i}:void 0);t.dispatchEvent(s)}_setupMediaQueryListeners(){const e=self.matchMedia("(max-width: 500px)");e.addListener(this.onMediaQueryChange),this.onMediaQueryChange(e)}onMediaQueryChange(e){this._dom.find(".lh-root",this._document).classList.toggle("lh-narrow",e.matches)}_setupThirdPartyFilter(){const e=["uses-rel-preconnect"],t=["legacy-javascript"];Array.from(this._document.querySelectorAll(".lh-table")).filter((e=>e.querySelector("td.lh-table-column--url, td.lh-table-column--source-location"))).filter((t=>{const i=t.closest(".lh-audit");if(!i)throw new Error(".lh-table not within audit");return!e.includes(i.id)})).forEach(((e,i)=>{const s=function(e){return Array.from(e.tBodies[0].rows)}(e),n=this._getThirdPartyRows(s,this.json.finalUrl),r=this._dom.cloneTemplate("#tmpl-lh-3p-filter",this._templateContext),o=this._dom.find("input",r),a="lh-3p-filter-label--"+i;o.id=a,o.addEventListener("change",(e=>{const t=e.target instanceof HTMLInputElement&&!e.target.checked;let i=!0,r=s[0];for(;r;){const e=t&&n.includes(r);do{r.classList.toggle("lh-row--hidden",e),r.classList.toggle("lh-row--even",!e&&i),r.classList.toggle("lh-row--odd",!e&&!i),r=r.nextElementSibling}while(r&&r.classList.contains("lh-sub-item-row"));e||(i=!i)}})),this._dom.find("label",r).setAttribute("for",a),this._dom.find(".lh-3p-filter-count",r).textContent=""+n.length,this._dom.find(".lh-3p-ui-string",r).textContent=V.i18n.strings.thirdPartyResourcesLabel;const l=n.length===s.length,d=!n.length;if((l||d)&&(o.disabled=!0,o.checked=l),!e.parentNode)return;e.parentNode.insertBefore(r,e);const h=e.closest(".lh-audit");if(!h)throw new Error(".lh-table not within audit");t.includes(h.id)&&!l&&o.click()}))}_setupElementScreenshotOverlay(){const e=this.json.audits["full-page-screenshot"]&&this.json.audits["full-page-screenshot"].details;e&&"full-page-screenshot"===e.type&&de.installOverlayFeature(this._dom,this._templateContext,e)}_getThirdPartyRows(e,t){const i=[],s=V.getRootDomain(t);for(const t of e){if(t.classList.contains("lh-sub-item-row"))continue;const e=t.querySelector(".lh-text__url");if(!e)continue;const n=e.dataset.url;if(!n)continue;V.getRootDomain(n)!==s&&i.push(t)}return i}_getUrlItems(e){return this._dom.findAll(".lh-text__url",e)}_setupStickyHeaderElements(){this.topbarEl=this._dom.find(".lh-topbar",this._document),this.scoreScaleEl=this._dom.find(".lh-scorescale",this._document),this.stickyHeaderEl=this._dom.find(".lh-sticky-header",this._document),this.highlightEl=this._dom.createChildOf(this.stickyHeaderEl,"div","lh-highlighter")}onCopy(e){this._copyAttempt&&e.clipboardData&&(e.preventDefault(),e.clipboardData.setData("text/plain",JSON.stringify(this.json,null,2)),this._fireEventOn("lh-log",this._document,{cmd:"log",msg:"Report JSON copied to clipboard"})),this._copyAttempt=!1}onCopyButtonClick(){this._fireEventOn("lh-analytics",this._document,{cmd:"send",fields:{hitType:"event",eventCategory:"report",eventAction:"copy"}});try{this._document.queryCommandSupported("copy")&&(this._copyAttempt=!0,this._document.execCommand("copy")||(this._copyAttempt=!1,this._fireEventOn("lh-log",this._document,{cmd:"warn",msg:"Your browser does not support copy to clipboard."})))}catch(e){this._copyAttempt=!1,this._fireEventOn("lh-log",this._document,{cmd:"log",msg:e.message})}}_resetUIState(){this._dropDown.close(),this._dom.resetTemplates()}onDropDownMenuClick(e){e.preventDefault();const t=e.target;if(t&&t.hasAttribute("data-action")){switch(t.getAttribute("data-action")){case"copy":this.onCopyButtonClick();break;case"print-summary":this.collapseAllDetails(),this._print();break;case"print-expanded":this.expandAllDetails(),this._print();break;case"save-json":{const e=JSON.stringify(this.json,null,2);this._saveFile(new Blob([e],{type:"application/json"}));break}case"save-html":{const t=this.getReportHtml();try{this._saveFile(new Blob([t],{type:"text/html"}))}catch(e){this._fireEventOn("lh-log",this._document,{cmd:"error",msg:"Could not export as HTML. "+e.message})}break}case"open-viewer":{const e="/lighthouse/viewer/";ue.openTabAndSendJsonReport(this.json,e);break}case"save-gist":this.saveAsGist();break;case"toggle-dark":this._toggleDarkTheme()}this._dropDown.close()}}_print(){self.print()}onKeyUp(e){(e.ctrlKey||e.metaKey)&&80===e.keyCode&&this._dropDown.close()}static openTabAndSendJsonReport(e,t){const i="https://googlechrome.github.io",s=e;window.addEventListener("message",(function e(t){t.origin===i&&a&&t.data.opened&&(a.postMessage({lhresults:s},i),window.removeEventListener("message",e))}));const n=s.generatedTime,r=s.fetchTime||n,o=`${s.lighthouseVersion}-${s.requestedUrl}-${r}`,a=window.open(`${i}${t}`,o)}expandAllDetails(){this._dom.findAll(".lh-categories details",this._document).map((e=>e.open=!0))}collapseAllDetails(){this._dom.findAll(".lh-categories details",this._document).map((e=>e.open=!1))}_setUpCollapseDetailsAfterPrinting(){if("onbeforeprint"in self)self.addEventListener("afterprint",this.collapseAllDetails);else{self.matchMedia("print").addListener((e=>{e.matches?this.expandAllDetails():this.collapseAllDetails()}))}}getReportHtml(){return this._resetUIState(),this._document.documentElement.outerHTML}saveAsGist(){throw new Error("Cannot save as gist from base report")}_saveFile(e){const t=he({finalUrl:this.json.finalUrl,fetchTime:this.json.fetchTime}),i=e.type.match("json")?".json":".html",s=URL.createObjectURL(e),n=this._dom.createElement("a");n.download=`${t}${i}`,n.href=s,this._document.body.appendChild(n),n.click(),this._document.body.removeChild(n),setTimeout((e=>URL.revokeObjectURL(s)),500)}_toggleDarkTheme(e){const t=this._dom.find(".lh-vars",this._document);void 0===e?t.classList.toggle("dark"):t.classList.toggle("dark",e)}_updateStickyHeaderOnScroll(){const e=this.topbarEl.getBoundingClientRect().bottom>=this.scoreScaleEl.getBoundingClientRect().top,t=Array.from(this._document.querySelectorAll(".lh-category")).filter((e=>e.getBoundingClientRect().top-window.innerHeight/2<0)),i=t.length>0?t.length-1:0,s=this.stickyHeaderEl.querySelectorAll(".lh-gauge__wrapper"),n=s[i],r=s[0].getBoundingClientRect().left,o=n.getBoundingClientRect().left-r;this.highlightEl.style.transform=`translate(${o}px)`,this.stickyHeaderEl.classList.toggle("lh-sticky-header--visible",e)}}class pe{constructor(e){this._dom=e,this._toggleEl,this._menuEl,this.onDocumentKeyDown=this.onDocumentKeyDown.bind(this),this.onToggleClick=this.onToggleClick.bind(this),this.onToggleKeydown=this.onToggleKeydown.bind(this),this.onMenuFocusOut=this.onMenuFocusOut.bind(this),this.onMenuKeydown=this.onMenuKeydown.bind(this),this._getNextMenuItem=this._getNextMenuItem.bind(this),this._getNextSelectableNode=this._getNextSelectableNode.bind(this),this._getPreviousMenuItem=this._getPreviousMenuItem.bind(this)}setup(e){this._toggleEl=this._dom.find(".lh-tools__button",this._dom.document()),this._toggleEl.addEventListener("click",this.onToggleClick),this._toggleEl.addEventListener("keydown",this.onToggleKeydown),this._menuEl=this._dom.find(".lh-tools__dropdown",this._dom.document()),this._menuEl.addEventListener("keydown",this.onMenuKeydown),this._menuEl.addEventListener("click",e)}close(){this._toggleEl.classList.remove("active"),this._toggleEl.setAttribute("aria-expanded","false"),this._menuEl.contains(this._dom.document().activeElement)&&this._toggleEl.focus(),this._menuEl.removeEventListener("focusout",this.onMenuFocusOut),this._dom.document().removeEventListener("keydown",this.onDocumentKeyDown)}open(e){this._toggleEl.classList.contains("active")?e.focus():this._menuEl.addEventListener("transitionend",(()=>{e.focus()}),{once:!0}),this._toggleEl.classList.add("active"),this._toggleEl.setAttribute("aria-expanded","true"),this._menuEl.addEventListener("focusout",this.onMenuFocusOut),this._dom.document().addEventListener("keydown",this.onDocumentKeyDown)}onToggleClick(e){e.preventDefault(),e.stopImmediatePropagation(),this._toggleEl.classList.contains("active")?this.close():this.open(this._getNextMenuItem())}onToggleKeydown(e){switch(e.code){case"ArrowUp":e.preventDefault(),this.open(this._getPreviousMenuItem());break;case"ArrowDown":case"Enter":case" ":e.preventDefault(),this.open(this._getNextMenuItem())}}onMenuKeydown(e){const t=e.target;switch(e.code){case"ArrowUp":e.preventDefault(),this._getPreviousMenuItem(t).focus();break;case"ArrowDown":e.preventDefault(),this._getNextMenuItem(t).focus();break;case"Home":e.preventDefault(),this._getNextMenuItem().focus();break;case"End":e.preventDefault(),this._getPreviousMenuItem().focus()}}onDocumentKeyDown(e){27===e.keyCode&&this.close()}onMenuFocusOut(e){const t=e.relatedTarget;this._menuEl.contains(t)||this.close()}_getNextSelectableNode(e,t){const i=e.filter((e=>e instanceof HTMLElement&&(!e.hasAttribute("disabled")&&"none"!==window.getComputedStyle(e).display)));let s=t?i.indexOf(t)+1:0;return s>=i.length&&(s=0),i[s]}_getNextMenuItem(e){const t=Array.from(this._menuEl.childNodes);return this._getNextSelectableNode(t,e)}_getPreviousMenuItem(e){const t=Array.from(this._menuEl.childNodes).reverse();return this._getNextSelectableNode(t,e)}}"undefined"!=typeof module&&module.exports?module.exports=ue:self.ReportUIFeatures=ue;class ge{constructor(e,t){this.dom=e,this.detailsRenderer=t,this.templateContext=this.dom.document(),this.detailsRenderer.setTemplateContext(this.templateContext)}get _clumpTitles(){return{warning:V.i18n.strings.warningAuditsGroupTitle,manual:V.i18n.strings.manualAuditsGroupTitle,passed:V.i18n.strings.passedAuditsGroupTitle,notApplicable:V.i18n.strings.notApplicableAuditsGroupTitle}}renderAudit(e){const t=this.dom.cloneTemplate("#tmpl-lh-audit",this.templateContext);return this.populateAuditValues(e,t)}populateAuditValues(e,t){const i=V.i18n.strings,s=this.dom.find(".lh-audit",t);s.id=e.result.id;const n=e.result.scoreDisplayMode;e.result.displayValue&&(this.dom.find(".lh-audit__display-text",s).textContent=e.result.displayValue);const r=this.dom.find(".lh-audit__title",s);r.appendChild(this.dom.convertMarkdownCodeSnippets(e.result.title)),this.dom.find(".lh-audit__description",s).appendChild(this.dom.convertMarkdownLinkSnippets(e.result.description)),e.stackPacks&&e.stackPacks.forEach((e=>{const t=this.dom.createElement("div");t.classList.add("lh-audit__stackpack");const i=this.dom.createElement("img");i.classList.add("lh-audit__stackpack__img"),i.src=e.iconDataURL,i.alt=e.title,t.appendChild(i),t.appendChild(this.dom.convertMarkdownLinkSnippets(e.description)),this.dom.find(".lh-audit__stackpacks",s).appendChild(t)}));const o=this.dom.find("details",s);if(e.result.details){const t=this.detailsRenderer.render(e.result.details);t&&(t.classList.add("lh-details"),o.appendChild(t))}if(this.dom.find(".lh-chevron-container",s).appendChild(this._createChevron()),this._setRatingClass(s,e.result.score,n),"error"===e.result.scoreDisplayMode){s.classList.add("lh-audit--error");const t=this.dom.find(".lh-audit__display-text",s);t.textContent=i.errorLabel,t.classList.add("tooltip-boundary");this.dom.createChildOf(t,"div","tooltip tooltip--error").textContent=e.result.errorMessage||i.errorMissingAuditInfo}else if(e.result.explanation){this.dom.createChildOf(r,"div","lh-audit-explanation").textContent=e.result.explanation}const a=e.result.warnings;if(!a||0===a.length)return s;const l=this.dom.find("summary",o),d=this.dom.createChildOf(l,"div","lh-warnings");if(this.dom.createChildOf(d,"span").textContent=i.warningHeader,1===a.length)d.appendChild(this.dom.document().createTextNode(a.join("")));else{const e=this.dom.createChildOf(d,"ul");for(const t of a){this.dom.createChildOf(e,"li").textContent=t}}return s}_createChevron(){const e=this.dom.cloneTemplate("#tmpl-lh-chevron",this.templateContext);return this.dom.find(".lh-chevron",e)}_setRatingClass(e,t,i){const s=V.calculateRating(t,i);return e.classList.add("lh-audit--"+i.toLowerCase()),"informative"!==i&&e.classList.add("lh-audit--"+s),e}renderCategoryHeader(e,t){const i=this.dom.cloneTemplate("#tmpl-lh-category-header",this.templateContext),s=this.dom.find(".lh-score__gauge",i),n=this.renderScoreGauge(e,t);if(s.appendChild(n),e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);this.dom.find(".lh-category-header__description",i).appendChild(t)}return i.firstElementChild}renderAuditGroup(e){const t=this.dom.createElement("div","lh-audit-group"),i=this.dom.createElement("div","lh-audit-group__header");if(this.dom.createChildOf(i,"span","lh-audit-group__title").textContent=e.title,e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);t.classList.add("lh-audit-group__description"),i.appendChild(t)}return t.appendChild(i),t}_renderGroupedAudits(e,t){const i=new Map,s="NotAGroup";i.set(s,[]);for(const t of e){const e=t.group||s,n=i.get(e)||[];n.push(t),i.set(e,n)}const n=[];for(const[e,r]of i){if(e===s){for(const e of r)n.push(this.renderAudit(e));continue}const i=t[e],o=this.renderAuditGroup(i);for(const e of r)o.appendChild(this.renderAudit(e));o.classList.add("lh-audit-group--"+e),n.push(o)}return n}renderUnexpandableClump(e,t){const i=this.dom.createElement("div");return this._renderGroupedAudits(e,t).forEach((e=>i.appendChild(e))),i}renderClump(e,{auditRefs:t,description:i}){const s=this.dom.cloneTemplate("#tmpl-lh-clump",this.templateContext),n=this.dom.find(".lh-clump",s);"warning"===e&&n.setAttribute("open","");this.dom.find(".lh-audit-group__summary",n).appendChild(this._createChevron()).title=V.i18n.strings.auditGroupExpandTooltip;const r=this.dom.find(".lh-audit-group__header",n),o=this._clumpTitles[e];if(this.dom.find(".lh-audit-group__title",r).textContent=o,i){const e=this.dom.convertMarkdownLinkSnippets(i);e.classList.add("lh-audit-group__description"),r.appendChild(e)}this.dom.find(".lh-audit-group__itemcount",n).textContent=`(${t.length})`;const a=t.map(this.renderAudit.bind(this));return n.append(...a),n.classList.add("lh-clump--"+e.toLowerCase()),n}setTemplateContext(e){this.templateContext=e,this.detailsRenderer.setTemplateContext(e)}renderScoreGauge(e,t){const i=this.dom.cloneTemplate("#tmpl-lh-gauge",this.templateContext),s=this.dom.find(".lh-gauge__wrapper",i);s.href="#"+e.id,V.isPluginCategory(e.id)&&s.classList.add("lh-gauge__wrapper--plugin");const n=Number(e.score),r=this.dom.find(".lh-gauge",i).querySelector(".lh-gauge-arc");r&&this._setGaugeArc(r,n);const o=Math.round(100*n),a=this.dom.find(".lh-gauge__percentage",i);return a.textContent=o.toString(),null===e.score&&(a.textContent="?",a.title=V.i18n.strings.errorLabel),0===e.auditRefs.length||this.hasApplicableAudits(e)?s.classList.add("lh-gauge__wrapper--"+V.calculateRating(e.score)):(s.classList.add("lh-gauge__wrapper--not-applicable"),a.textContent="-",a.title=V.i18n.strings.notApplicableAuditsGroupTitle),this.dom.find(".lh-gauge__label",i).textContent=e.title,i}hasApplicableAudits(e){return e.auditRefs.some((e=>"notApplicable"!==e.result.scoreDisplayMode))}_setGaugeArc(e,t){const i=2*Math.PI*Number(e.getAttribute("r")),s=Number(e.getAttribute("stroke-width")),n=.25*s/i;e.style.transform=`rotate(${360*n-90}deg)`;let r=t*i-s/2;0===t&&(e.style.opacity="0"),1===t&&(r=i),e.style.strokeDasharray=`${Math.max(r,0)} ${i}`}_auditHasWarning(e){return Boolean(e.result.warnings&&e.result.warnings.length)}_getClumpIdForAuditRef(e){const t=e.result.scoreDisplayMode;return"manual"===t||"notApplicable"===t?t:V.showAsPassed(e.result)?this._auditHasWarning(e)?"warning":"passed":"failed"}render(e,t={}){const i=this.dom.createElement("div","lh-category");this.createPermalinkSpan(i,e.id),i.appendChild(this.renderCategoryHeader(e,t));const s=new Map;s.set("failed",[]),s.set("warning",[]),s.set("manual",[]),s.set("passed",[]),s.set("notApplicable",[]);for(const t of e.auditRefs){const e=this._getClumpIdForAuditRef(t),i=s.get(e);i.push(t),s.set(e,i)}for(const[n,r]of s){if(0===r.length)continue;if("failed"===n){const e=this.renderUnexpandableClump(r,t);e.classList.add("lh-clump--failed"),i.appendChild(e);continue}const s="manual"===n?e.manualDescription:void 0,o=this.renderClump(n,{auditRefs:r,description:s});i.appendChild(o)}return i}createPermalinkSpan(e,t){this.dom.createChildOf(e,"span","lh-permalink").id=t}}"undefined"!=typeof module&&module.exports?module.exports=ge:self.CategoryRenderer=ge;class me extends ge{_renderMetric(e){const t=this.dom.cloneTemplate("#tmpl-lh-metric",this.templateContext),i=this.dom.find(".lh-metric",t);i.id=e.result.id;const s=V.calculateRating(e.result.score,e.result.scoreDisplayMode);i.classList.add("lh-metric--"+s);this.dom.find(".lh-metric__title",t).textContent=e.result.title;const n=this.dom.find(".lh-metric__value",t);n.textContent=e.result.displayValue||"";const r=this.dom.find(".lh-metric__description",t);if(r.appendChild(this.dom.convertMarkdownLinkSnippets(e.result.description)),"error"===e.result.scoreDisplayMode){r.textContent="",n.textContent="Error!";this.dom.createChildOf(r,"span").textContent=e.result.errorMessage||"Report error: no metric information"}return i}_renderOpportunity(e,t){const i=this.dom.cloneTemplate("#tmpl-lh-opportunity",this.templateContext),s=this.populateAuditValues(e,i);if(s.id=e.result.id,!e.result.details||"error"===e.result.scoreDisplayMode)return s;const n=e.result.details;if("opportunity"!==n.type)return s;const r=this.dom.find(".lh-audit__display-text",s),o=n.overallSavingsMs/t*100+"%";if(this.dom.find(".lh-sparkline__bar",s).style.width=o,r.textContent=V.i18n.formatSeconds(n.overallSavingsMs,.01),e.result.displayValue){const t=e.result.displayValue;this.dom.find(".lh-load-opportunity__sparkline",s).title=t,r.title=t}return s}_getWastedMs(e){if(e.result.details&&"opportunity"===e.result.details.type){const t=e.result.details;if("number"!=typeof t.overallSavingsMs)throw new Error("non-opportunity details passed to _getWastedMs");return t.overallSavingsMs}return Number.MIN_VALUE}_getScoringCalculatorHref(e){const t=e.filter((e=>"metrics"===e.group)),i=e.find((e=>"first-cpu-idle"===e.id)),s=e.find((e=>"first-meaningful-paint"===e.id));i&&t.push(i),s&&t.push(s);const n={"cumulative-layout-shift":"CLS","first-contentful-paint":"FCP","first-cpu-idle":"FCI","first-meaningful-paint":"FMP",interactive:"TTI","largest-contentful-paint":"LCP","speed-index":"SI","total-blocking-time":"TBT"},r=[...t.map((e=>{let t;var i;return"number"==typeof e.result.numericValue?(t="cumulative-layout-shift"===e.id?(i=e.result.numericValue,Math.round(100*i)/100):Math.round(e.result.numericValue),t=t.toString()):t="null",[n[e.id]||e.id,t]}))];V.reportJson&&(r.push(["device",V.reportJson.configSettings.emulatedFormFactor]),r.push(["version",V.reportJson.lighthouseVersion]));const o=new URLSearchParams(r),a=new URL("https://googlechrome.github.io/lighthouse/scorecalc/");return a.hash=o.toString(),a.href}render(e,t,i){const s=V.i18n.strings,n=this.dom.createElement("div","lh-category");if("PSI"===i){const i=this.dom.createElement("div","lh-score__gauge");i.appendChild(this.renderScoreGauge(e,t)),n.appendChild(i)}else this.createPermalinkSpan(n,e.id),n.appendChild(this.renderCategoryHeader(e,t));const r=this.renderAuditGroup(t.metrics),o=this.dom.cloneTemplate("#tmpl-lh-metrics-toggle",this.templateContext),a=this.dom.find(".lh-metrics-toggle",o);r.append(...a.childNodes);const l=e.auditRefs.filter((e=>"metrics"===e.group)),d=this.dom.createChildOf(r,"div","lh-metrics-container");l.forEach((e=>{d.appendChild(this._renderMetric(e))}));const h=this.dom.createChildOf(r,"div","lh-metrics__disclaimer"),c=this.dom.convertMarkdownLinkSnippets(s.varianceDisclaimer);h.appendChild(c);const u=this.dom.createChildOf(h,"a","lh-calclink");u.target="_blank",u.textContent=s.calculatorLink,u.href=this._getScoringCalculatorHref(e.auditRefs),r.classList.add("lh-audit-group--metrics"),n.appendChild(r);const p=this.dom.createChildOf(n,"div","lh-filmstrip-container"),g=e.auditRefs.find((e=>"screenshot-thumbnails"===e.id)),m=g&&g.result;if(m&&m.details){p.id=m.id;const e=this.detailsRenderer.render(m.details);e&&p.appendChild(e)}const _=[];if(["performance-budget","timing-budget"].forEach((t=>{const i=e.auditRefs.find((e=>e.id===t));if(i&&i.result.details){const e=this.detailsRenderer.render(i.result.details);e&&(e.id=t,e.classList.add("lh-audit"),_.push(e))}})),_.length>0){const e=this.renderAuditGroup(t.budgets);_.forEach((t=>e.appendChild(t))),e.classList.add("lh-audit-group--budgets"),n.appendChild(e)}const f=e.auditRefs.filter((e=>"load-opportunities"===e.group&&!V.showAsPassed(e.result))).sort(((e,t)=>this._getWastedMs(t)-this._getWastedMs(e)));if(f.length){const e=2e3,i=f.map((e=>this._getWastedMs(e))),r=Math.max(...i),o=Math.max(1e3*Math.ceil(r/1e3),e),a=this.renderAuditGroup(t["load-opportunities"]),l=this.dom.cloneTemplate("#tmpl-lh-opportunity-header",this.templateContext);this.dom.find(".lh-load-opportunity__col--one",l).textContent=s.opportunityResourceColumnLabel,this.dom.find(".lh-load-opportunity__col--two",l).textContent=s.opportunitySavingsColumnLabel;const d=this.dom.find(".lh-load-opportunity__header",l);a.appendChild(d),f.forEach((e=>a.appendChild(this._renderOpportunity(e,o)))),a.classList.add("lh-audit-group--load-opportunities"),n.appendChild(a)}const b=e.auditRefs.filter((e=>"diagnostics"===e.group&&!V.showAsPassed(e.result))).sort(((e,t)=>("informative"===e.result.scoreDisplayMode?100:Number(e.result.score))-("informative"===t.result.scoreDisplayMode?100:Number(t.result.score))));if(b.length){const e=this.renderAuditGroup(t.diagnostics);b.forEach((t=>e.appendChild(this.renderAudit(t)))),e.classList.add("lh-audit-group--diagnostics"),n.appendChild(e)}const y=e.auditRefs.filter((e=>("load-opportunities"===e.group||"diagnostics"===e.group)&&V.showAsPassed(e.result)));if(!y.length)return n;const v={auditRefs:y,groupDefinitions:t},w=this.renderClump("passed",v);return n.appendChild(w),n}}"undefined"!=typeof module&&module.exports?module.exports=me:self.PerformanceCategoryRenderer=me;class _e extends ge{render(e,t={}){const i=this.dom.createElement("div","lh-category");this.createPermalinkSpan(i,e.id),i.appendChild(this.renderCategoryHeader(e,t));const s=e.auditRefs,n=s.filter((e=>"manual"!==e.result.scoreDisplayMode)),r=this._renderAudits(n,t);i.appendChild(r);const o=s.filter((e=>"manual"===e.result.scoreDisplayMode)),a=this.renderClump("manual",{auditRefs:o,description:e.manualDescription});return i.appendChild(a),i}renderScoreGauge(e,t){if(null===e.score)return super.renderScoreGauge(e,t);const i=this.dom.cloneTemplate("#tmpl-lh-gauge--pwa",this.templateContext),s=this.dom.find(".lh-gauge--pwa__wrapper",i);s.href="#"+e.id;const n=i.querySelector("svg");if(!n)throw new Error("no SVG element found in PWA score gauge template");_e._makeSvgReferencesUnique(n);const r=this._getGroupIds(e.auditRefs),o=this._getPassingGroupIds(e.auditRefs);if(o.size===r.size)s.classList.add("lh-badged--all");else for(const e of o)s.classList.add("lh-badged--"+e);return this.dom.find(".lh-gauge__label",i).textContent=e.title,s.title=this._getGaugeTooltip(e.auditRefs,t),i}_getGroupIds(e){const t=e.map((e=>e.group)).filter((e=>!!e));return new Set(t)}_getPassingGroupIds(e){const t=this._getGroupIds(e);for(const i of e)!V.showAsPassed(i.result)&&i.group&&t.delete(i.group);return t}_getGaugeTooltip(e,t){const i=this._getGroupIds(e),s=[];for(const n of i){const i=e.filter((e=>e.group===n)),r=i.length,o=i.filter((e=>V.showAsPassed(e.result))).length,a=t[n].title;s.push(`${a}: ${o}/${r}`)}return s.join(", ")}_renderAudits(e,t){const i=this.renderUnexpandableClump(e,t),s=this._getPassingGroupIds(e);for(const e of s){this.dom.find(".lh-audit-group--"+e,i).classList.add("lh-badged")}return i}static _makeSvgReferencesUnique(e){const t=e.querySelector("defs");if(!t)return;const i=V.getUniqueSuffix(),s=t.querySelectorAll("[id]");for(const t of s){const s=t.id,n=`${s}-${i}`;t.id=n;const r=e.querySelectorAll(`use[href="#${s}"]`);for(const e of r)e.setAttribute("href","#"+n);const o=e.querySelectorAll(`[fill="url(#${s})"]`);for(const e of o)e.setAttribute("fill",`url(#${n})`)}}}"undefined"!=typeof module&&module.exports?module.exports=_e:self.PwaCategoryRenderer=_e;class fe{constructor(e){this._dom=e,this._templateContext=this._dom.document()}renderReport(e,t){this._dom.setLighthouseChannel(e.configSettings.channel||"unknown");const i=V.prepareReportResult(e);return t.textContent="",t.appendChild(this._renderReport(i)),t}setTemplateContext(e){this._templateContext=e}_renderReportTopbar(e){const t=this._dom.cloneTemplate("#tmpl-lh-topbar",this._templateContext),i=this._dom.find(".lh-topbar__url",t);return i.href=i.textContent=e.finalUrl,i.title=e.finalUrl,t}_renderReportHeader(){const e=this._dom.cloneTemplate("#tmpl-lh-heading",this._templateContext),t=this._dom.cloneTemplate("#tmpl-lh-scores-wrapper",this._templateContext),i=this._dom.find(".lh-scores-wrapper-placeholder",e);return i.parentNode.replaceChild(t,i),e}_renderReportFooter(e){const t=this._dom.cloneTemplate("#tmpl-lh-footer",this._templateContext),i=this._dom.find(".lh-env__items",t);i.id="runtime-settings",this._dom.find(".lh-env__title",t).textContent=V.i18n.strings.runtimeSettingsTitle;const s=V.getEnvironmentDisplayValues(e.configSettings||{}),n=[{name:V.i18n.strings.runtimeSettingsUrl,description:e.finalUrl},{name:V.i18n.strings.runtimeSettingsFetchTime,description:V.i18n.formatDateTime(e.fetchTime)},...s,{name:V.i18n.strings.runtimeSettingsChannel,description:e.configSettings.channel},{name:V.i18n.strings.runtimeSettingsUA,description:e.userAgent},{name:V.i18n.strings.runtimeSettingsUANetwork,description:e.environment&&e.environment.networkUserAgent},{name:V.i18n.strings.runtimeSettingsBenchmark,description:e.environment&&e.environment.benchmarkIndex.toFixed(0)}];e.environment.credits&&e.environment.credits["axe-core"]&&n.push({name:V.i18n.strings.runtimeSettingsAxeVersion,description:e.environment.credits["axe-core"]});for(const e of n){if(!e.description)continue;const t=this._dom.cloneTemplate("#tmpl-lh-env__items",i);this._dom.find(".lh-env__name",t).textContent=e.name,this._dom.find(".lh-env__description",t).textContent=e.description,i.appendChild(t)}return this._dom.find(".lh-footer__version_issue",t).textContent=V.i18n.strings.footerIssue,this._dom.find(".lh-footer__version",t).textContent=e.lighthouseVersion,t}_renderReportWarnings(e){if(!e.runWarnings||0===e.runWarnings.length)return this._dom.createElement("div");const t=this._dom.cloneTemplate("#tmpl-lh-warnings--toplevel",this._templateContext);this._dom.find(".lh-warnings__msg",t).textContent=V.i18n.strings.toplevelWarningsMessage;const i=this._dom.find("ul",t);for(const t of e.runWarnings){i.appendChild(this._dom.createElement("li")).textContent=t}return t}_renderScoreGauges(e,t,i){const s=[],n=[],r=[];for(const o of Object.values(e.categories)){const a=i[o.id]||t,l=a.renderScoreGauge(o,e.categoryGroups||{});V.isPluginCategory(o.id)?r.push(l):a.renderScoreGauge===t.renderScoreGauge?s.push(l):n.push(l)}return[...s,...n,...r]}_renderReport(e){const t=new be(e.configSettings.locale,{...V.UIStrings,...e.i18n.rendererFormattedStrings});V.i18n=t,V.reportJson=e;const i=e.audits["full-page-screenshot"]&&e.audits["full-page-screenshot"].details&&"full-page-screenshot"===e.audits["full-page-screenshot"].details.type?e.audits["full-page-screenshot"].details:void 0,s=new z(this._dom,{fullPageScreenshot:i}),n=i&&de.createBackgroundImageStyle(this._dom,i),r=new ge(this._dom,s);r.setTemplateContext(this._templateContext);const o={performance:new me(this._dom,s),pwa:new _e(this._dom,s)};Object.values(o).forEach((e=>{e.setTemplateContext(this._templateContext)}));const a=this._dom.createElement("div");a.appendChild(this._renderReportHeader());const l=this._dom.createElement("div","lh-container"),d=this._dom.createElement("div","lh-report");let h;d.appendChild(this._renderReportWarnings(e));if(1===Object.keys(e.categories).length?a.classList.add("lh-header--solo-category"):h=this._dom.createElement("div","lh-scores-header"),h){const t=this._dom.cloneTemplate("#tmpl-lh-scorescale",this._templateContext),i=this._dom.find(".lh-scores-container",a);h.append(...this._renderScoreGauges(e,r,o)),i.appendChild(h),i.appendChild(t);const s=this._dom.createElement("div","lh-sticky-header");s.append(...this._renderScoreGauges(e,r,o)),l.appendChild(s)}const c=d.appendChild(this._dom.createElement("div","lh-categories"));for(const t of Object.values(e.categories)){const i=o[t.id]||r;i.dom.createChildOf(c,"div","lh-category-wrapper").appendChild(i.render(t,e.categoryGroups))}const u=this._dom.createFragment(),p=this._renderReportTopbar(e);return u.appendChild(p),u.appendChild(l),l.appendChild(a),l.appendChild(d),n&&l.appendChild(n),d.appendChild(this._renderReportFooter(e)),u}}"undefined"!=typeof module&&module.exports?module.exports=fe:self.ReportRenderer=fe;class be{constructor(e,t){"en-XA"===e&&(e="de"),this._numberDateLocale=e,this._numberFormatter=new Intl.NumberFormat(e),this._strings=t||{}}get strings(){return this._strings}formatNumber(e,t=.1){const i=Math.round(e/t)*t;return this._numberFormatter.format(i)}formatBytesToKiB(e,t=.1){return this._numberFormatter.format(Math.round(e/1024/t)*t)+" KiB"}formatBytes(e,t=1){return this._numberFormatter.format(Math.round(e/t)*t)+" bytes"}formatMilliseconds(e,t=10){const i=Math.round(e/t)*t;return 0===i?this._numberFormatter.format(0)+" ms":this._numberFormatter.format(i)+" ms"}formatSeconds(e,t=.1){const i=Math.round(e/1e3/t)*t;return this._numberFormatter.format(i)+" s"}formatDateTime(e){const t={month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",timeZoneName:"short"};let i;try{i=new Intl.DateTimeFormat(this._numberDateLocale,t)}catch(e){t.timeZone="UTC",i=new Intl.DateTimeFormat(this._numberDateLocale,t)}return i.format(new Date(e))}formatDuration(e){let t=e/1e3;if(0===Math.round(t))return"None";const i=[],s={d:86400,h:3600,m:60,s:1};return Object.keys(s).forEach((e=>{const n=s[e],r=Math.floor(t/n);r>0&&(t-=r*n,i.push(`${r} ${e}`))})),i.join(" ")}}"undefined"!=typeof module&&module.exports?module.exports=be:self.I18n=be,function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;((t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Lighthouse||(t.Lighthouse={})).ReportGenerator=e()}}((function(){return function e(t,i,s){function n(o,a){if(!i[o]){if(!t[o]){var l="function"==typeof require&&require;if(!a&&l)return l(o,!0);if(r)return r(o,!0);var d=new Error("Cannot find module '"+o+"'");throw d.code="MODULE_NOT_FOUND",d}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return n(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;o<s.length;o++)n(s[o]);return n}({"./html/html-report-assets.js":[function(e,t,i){const s=globalThis.EXPORTED_CACHED_RESOURCES_ONLY_FOR_LIGHTHOUSE;t.exports={get REPORT_CSS(){return s.get("third_party/lighthouse/report-assets/report.css")},get REPORT_JAVASCRIPT(){return s.get("third_party/lighthouse/report-assets/report.js")},get REPORT_TEMPLATE(){return s.get("third_party/lighthouse/report-assets/template.html")},get REPORT_TEMPLATES(){return s.get("third_party/lighthouse/report-assets/templates.html")}}},{}],1:[function(e,t,i){const s=e("./html/html-report-assets.js");class n{static replaceStrings(e,t){if(0===t.length)return e;const i=t[0],s=t.slice(1);return e.split(i.search).map((e=>n.replaceStrings(e,s))).join(i.replacement)}static generateReportHtml(e){const t=JSON.stringify(e).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),i=s.REPORT_JAVASCRIPT.replace(/<\//g,"\\u003c/");return n.replaceStrings(s.REPORT_TEMPLATE,[{search:"%%LIGHTHOUSE_JSON%%",replacement:t},{search:"%%LIGHTHOUSE_JAVASCRIPT%%",replacement:i},{search:"/*%%LIGHTHOUSE_CSS%%*/",replacement:s.REPORT_CSS},{search:"%%LIGHTHOUSE_TEMPLATES%%",replacement:s.REPORT_TEMPLATES}])}static generateReportCSV(e){const t=e=>`"${e.replace(/"/g,'""')}"`,i=e=>e.map((e=>e.toString())).map(t),s=Object.keys(e.categories).map((t=>{const s=[],n=e.categories[t],r=null===n.score?-1:n.score;return s.push(i([e.requestedUrl,e.finalUrl,n.title,t+"-score",`Overall ${n.title} Category Score`,"numeric",r])),s.concat(n.auditRefs.map((t=>{const s=e.audits[t.id],r=null===s.score?-1:s.score;return i([e.requestedUrl,e.finalUrl,n.title,s.id,s.title,s.scoreDisplayMode,r])})))}));return[["requestedUrl","finalUrl","category","name","title","type","score"]].concat(...s).map((e=>e.join(","))).join("\r\n")}static generateReport(e,t){const i=Array.isArray(t);"string"==typeof t&&(t=[t]);const s=t.map((t=>{if("html"===t)return n.generateReportHtml(e);if("csv"===t)return n.generateReportCSV(e);if("json"===t)return JSON.stringify(e,null,2);throw new Error("Invalid output mode: "+t)}));return i?s:s[0]}}t.exports=n},{"./html/html-report-assets.js":"./html/html-report-assets.js"}]},{},[1])(1)}));const ye={canOnlyAuditHttphttpsPagesAnd:"Can only audit HTTP/HTTPS pages and `Chrome` extensions. Navigate to a different page to start an audit.",thereMayBeStoredDataAffectingSingular:"There may be stored data affecting loading performance in this location: {PH1}. Audit this page in an incognito window to prevent those resources from affecting your scores.",thereMayBeStoredDataAffectingLoadingPlural:"There may be stored data affecting loading performance in these locations: {PH1}. Audit this page in an incognito window to prevent those resources from affecting your scores.",multipleTabsAreBeingControlledBy:"Multiple tabs are being controlled by the same `service worker`. Close your other tabs on the same origin to audit this page.",atLeastOneCategoryMustBeSelected:"At least one category must be selected.",localStorage:"Local Storage",indexeddb:"IndexedDB",webSql:"Web SQL",performance:"Performance",howLongDoesThisAppTakeToShow:"How long does this app take to show content and become usable",progressiveWebApp:"Progressive Web App",doesThisPageMeetTheStandardOfA:"Does this page meet the standard of a Progressive Web App",bestPractices:"Best practices",doesThisPageFollowBestPractices:"Does this page follow best practices for modern web development",accessibility:"Accessibility",isThisPageUsableByPeopleWith:"Is this page usable by people with disabilities or impairments",seo:"SEO",isThisPageOptimizedForSearch:"Is this page optimized for search engine results ranking",publisherAds:"Publisher Ads",isThisPageOptimizedForAdSpeedAnd:"Is this page optimized for ad speed and quality",applyMobileEmulation:"Apply mobile emulation",applyMobileEmulationDuring:"Apply mobile emulation during auditing",mobile:"Mobile",desktop:"Desktop",simulatedThrottling:"Simulated throttling",simulateASlowerPageLoadBasedOn:"Simulate a slower page load, based on data from an initial unthrottled load. If disabled, the page is actually slowed with applied throttling.",clearStorage:"Clear storage",resetStorageLocalstorage:"Reset storage (localStorage, IndexedDB, etc) before auditing. (Good for performance & PWA testing)"},ve=r.registerUIStrings("lighthouse/LighthouseController.js",ye),we=r.getLocalizedString.bind(void 0,ve);class Ce extends e.ObjectWrapper{constructor(e){super(),e.registerStatusCallback((e=>this.dispatchEventToListeners(Le.AuditProgressChanged,{message:e})));for(const e of Te)e.setting.addChangeListener(this.recomputePageAuditability.bind(this));for(const e of xe)e.setting.addChangeListener(this.recomputePageAuditability.bind(this));o.TargetManager.instance().observeModels(a.ServiceWorkerManager,this),o.TargetManager.instance().addEventListener(o.Events.InspectedURLChanged,this.recomputePageAuditability,this)}modelAdded(e){this._manager||(this._manager=e,this._serviceWorkerListeners=[this._manager.addEventListener(a.Events.RegistrationUpdated,this.recomputePageAuditability,this),this._manager.addEventListener(a.Events.RegistrationDeleted,this.recomputePageAuditability,this)],this.recomputePageAuditability())}modelRemoved(e){this._manager===e&&(this._serviceWorkerListeners&&t.EventTarget.removeEventListeners(this._serviceWorkerListeners),this._manager=null,this.recomputePageAuditability())}_hasActiveServiceWorker(){if(!this._manager)return!1;const e=this._manager.target();if(!e)return!1;const t=i.ParsedURL.fromString(e.inspectedURL()),s=t&&t.securityOrigin();for(const e of this._manager.registrations().values())if(e.securityOrigin===s)for(const t of e.versions.values())if(t.controlledClients.length>1)return!0;return!1}_hasAtLeastOneCategory(){return Te.some((e=>e.setting.get()))}_unauditablePageMessage(){if(!this._manager)return null;const e=this._manager.target(),t=e&&e.inspectedURL();return t&&!/^(http|chrome-extension)/.test(t)?we(ye.canOnlyAuditHttphttpsPagesAnd):null}async _hasImportantResourcesNotCleared(){const e=xe.find((e=>"lighthouse.clear_storage"===e.setting.name));if(e&&!e.setting.get())return"";if(!this._manager)return"";const t=this._manager.target(),i=(await t.storageAgent().invoke_getUsageAndQuota({origin:t.inspectedURL()})).usageBreakdown.filter((e=>e.usage)).map((e=>Se.get(e.storageType))).filter(Boolean);return 1===i.length?we(ye.thereMayBeStoredDataAffectingSingular,{PH1:i[0]}):i.length>1?we(ye.thereMayBeStoredDataAffectingLoadingPlural,{PH1:i.join(", ")}):""}async _evaluateInspectedURL(){if(!this._manager)return"";const e=this._manager.target(),t=e.model(l.RuntimeModel),i=t&&t.defaultExecutionContext();let s=e.inspectedURL();if(!i)return s;try{const e=await i.evaluate({expression:"window.location.href",objectGroup:"lighthouse",includeCommandLineAPI:!1,silent:!1,returnByValue:!0,generatePreview:!1,allowUnsafeEvalBlockedByCSP:void 0,disableBreaks:void 0,replMode:void 0,throwOnSideEffect:void 0,timeout:void 0},!1,!1);"exceptionDetails"in e&&e.exceptionDetails||!("object"in e)||!e.object||(s=e.object.value,e.object.release())}catch(e){console.error(e)}return s}getFlags(){const e={internalDisableDeviceScreenEmulation:!0};for(const t of xe)t.setFlags(e,t.setting.get());return e}getCategoryIDs(){const e=[];for(const t of Te)t.setting.get()&&e.push(t.configID);return e}async getInspectedURL(e){return(e&&e.force||!this._inspectedURL)&&(this._inspectedURL=await this._evaluateInspectedURL()),this._inspectedURL}recomputePageAuditability(){const e=this._hasActiveServiceWorker(),t=this._hasAtLeastOneCategory(),i=this._unauditablePageMessage();let s="";e?s=we(ye.multipleTabsAreBeingControlledBy):t?i&&(s=i):s=we(ye.atLeastOneCategoryMustBeSelected),this.dispatchEventToListeners(Le.PageAuditabilityChanged,{helpText:s}),this._hasImportantResourcesNotCleared().then((e=>{this.dispatchEventToListeners(Le.PageWarningsChanged,{warning:e})}))}}const Se=new Map([[Protocol.Storage.StorageType.Local_storage,we(ye.localStorage)],[Protocol.Storage.StorageType.Indexeddb,we(ye.indexeddb)],[Protocol.Storage.StorageType.Websql,we(ye.webSql)]]),Te=[{setting:s.Settings.instance().createSetting("lighthouse.cat_perf",!0),configID:"performance",title:we(ye.performance),description:we(ye.howLongDoesThisAppTakeToShow),plugin:!1},{setting:s.Settings.instance().createSetting("lighthouse.cat_pwa",!0),configID:"pwa",title:we(ye.progressiveWebApp),description:we(ye.doesThisPageMeetTheStandardOfA),plugin:!1},{setting:s.Settings.instance().createSetting("lighthouse.cat_best_practices",!0),configID:"best-practices",title:we(ye.bestPractices),description:we(ye.doesThisPageFollowBestPractices),plugin:!1},{setting:s.Settings.instance().createSetting("lighthouse.cat_a11y",!0),configID:"accessibility",title:we(ye.accessibility),description:we(ye.isThisPageUsableByPeopleWith),plugin:!1},{setting:s.Settings.instance().createSetting("lighthouse.cat_seo",!0),configID:"seo",title:we(ye.seo),description:we(ye.isThisPageOptimizedForSearch),plugin:!1},{setting:s.Settings.instance().createSetting("lighthouse.cat_pubads",!1),plugin:!0,configID:"lighthouse-plugin-publisher-ads",title:we(ye.publisherAds),description:we(ye.isThisPageOptimizedForAdSpeedAnd)}],xe=[{setting:s.Settings.instance().createSetting("lighthouse.device_type","mobile"),title:we(ye.applyMobileEmulation),description:we(ye.applyMobileEmulationDuring),setFlags:(e,t)=>{e.emulatedFormFactor=t},options:[{label:we(ye.mobile),value:"mobile"},{label:we(ye.desktop),value:"desktop"}],learnMore:void 0},{setting:s.Settings.instance().createSetting("lighthouse.throttling",!0),title:we(ye.simulatedThrottling),learnMore:"https://github.com/GoogleChrome/lighthouse/blob/master/docs/throttling.md#devtools-lighthouse-panel-throttling",description:we(ye.simulateASlowerPageLoadBasedOn),setFlags:(e,t)=>{e.throttlingMethod=t?"simulate":"devtools"},options:void 0},{setting:s.Settings.instance().createSetting("lighthouse.clear_storage",!0),title:we(ye.clearStorage),description:we(ye.resetStorageLocalstorage),setFlags:(e,t)=>{e.disableStorageReset=!t},options:void 0,learnMore:void 0}],Le={PageAuditabilityChanged:Symbol("PageAuditabilityChanged"),PageWarningsChanged:Symbol("PageWarningsChanged"),AuditProgressChanged:Symbol("AuditProgressChanged"),RequestLighthouseStart:Symbol("RequestLighthouseStart"),RequestLighthouseCancel:Symbol("RequestLighthouseCancel")};var Ee=Object.freeze({__proto__:null,UIStrings:ye,LighthouseController:Ce,Presets:Te,RuntimeSettings:xe,Events:Le,Preset:undefined,RuntimeSetting:undefined});class Ae extends e.ObjectWrapper{constructor(){super(),this._rawConnection=null,this._backend=null,this._backendPromise=null,this._status=null}async attach(){await o.TargetManager.instance().suspendAllTargets();const e=o.TargetManager.instance().mainTarget();if(!e)throw new Error("Unable to find main target required for LightHouse");const t=e.model(d.ChildTargetManager);if(!t)throw new Error("Unable to find child target manager required for LightHouse");this._rawConnection=await t.createParallelConnection(this._dispatchProtocolMessage.bind(this))}getLocales(){return navigator.languages}startLighthouse(e,t,i){const s=this.getLocales();return this._send("start",{url:e,categoryIDs:t,flags:i,locales:s})}async detach(){await this._send("stop"),this._backend&&(await this._backend.dispose(),this._backend=null),this._backendPromise=null,this._rawConnection&&await this._rawConnection.disconnect(),await o.TargetManager.instance().resumeAllTargets()}registerStatusCallback(e){this._status=e}_dispatchProtocolMessage(e){this._send("dispatchProtocolMessage",{message:JSON.stringify(e)})}_initWorker(){const e=I.createAppService("lighthouse_worker","LighthouseService").then((e=>{this._backend||(this._backend=e,e&&(e.on("statusUpdate",(e=>{this._status&&e&&"message"in e&&this._status(e.message)})),e.on("sendProtocolMessage",(e=>{e&&"message"in e&&this._sendProtocolMessage(e.message)}))))}));return this._backendPromise=e,e}_sendProtocolMessage(e){this._rawConnection&&this._rawConnection.sendRawMessage(e)}async _send(e,t){let i=this._backendPromise;if(i||(i=this._initWorker()),await i,!this._backend)throw new Error("Backend is missing to send LightHouse message to");return this._backend.send(e,t)}}var ke=Object.freeze({__proto__:null,ProtocolService:Ae});self.ReportRenderer;self.ReportUIFeatures;var Pe=Object.freeze({__proto__:null,ReportRenderer:class{constructor(e){}renderReport(e,t){throw new Error("Not implemented yet!")}setTemplateContext(e){}},ReportUIFeatures:class{constructor(e){this.json,this._document}setTemplateContext(e){}initFeatures(e){}_resetUIState(){}setBeforePrint(e){}setAfterPrint(e){}},CategoryRenderer:class{constructor(e,t){}},DetailsRenderer:class{constructor(e){}renderNode(e){throw new Error("Not implemented yet!")}},LighthouseReportGenerator:class{generateReportHtml(e){return""}},AuditResultJSON:undefined,AuditJSON:undefined,CategoryJSON:undefined,GroupJSON:undefined,ReportJSON:undefined,DetailsJSON:undefined,RunnerResultArtifacts:undefined,RunnerResult:undefined,NodeDetailsJSON:undefined,SourceLocationDetailsJSON:undefined,OpportunitySummary:undefined});const Re={viewOriginalTrace:"View Original Trace",viewTrace:"View Trace",thePerformanceMetricsAboveAre:'The performance metrics above are simulated and won\'t match the timings found in this trace. Disable simulated throttling in "Lighthouse Settings" if you want the timings to match.'},Me=r.registerUIStrings("lighthouse/LighthouseReportRenderer.js",Re),Ie=r.getLocalizedString.bind(void 0,Me);class De extends self.ReportRenderer{constructor(e){super(e)}static addViewTraceButton(e,t){if(!t||!t.traces||!t.traces.defaultPass)return;const i="simulate"===t.settings.throttlingMethod,s=e.querySelector(".lh-audit-group");if(!s)return;const n=s.querySelector(".lh-metrics__disclaimer");if(!n)return;const r=t.traces.defaultPass,o=Ie(i?Re.viewOriginalTrace:Re.viewTrace),a=y.createTextButton(o,(async function(){_.actionTaken(f.Action.LighthouseViewTrace),await w.InspectorView.instance().showPanel("timeline"),N.TimelinePanel.instance().loadFromEvents(r.traceEvents)}),"view-trace");i&&v.Tooltip.install(a,Ie(Re.thePerformanceMetricsAboveAre)),s.insertBefore(a,n.nextSibling)}static async linkifyNodeDetails(e){const t=o.TargetManager.instance().mainTarget();if(!t)return;const i=t.model(h.DOMModel);if(i)for(const t of e.getElementsByClassName("lh-node")){const e=t,s=e.dataset;if(!s.path)continue;const r=await i.pushNodeByPathToFrontend(s.path);if(!r)continue;const o=i.nodeForId(r);if(!o)continue;const a=await n.Linkifier.linkify(o,{tooltip:s.snippet,preventKeyboardFocus:void 0});v.Tooltip.install(e,""),e.textContent="",e.appendChild(a)}}static async linkifySourceLocationDetails(e){for(const t of e.getElementsByClassName("lh-source-location")){const e=t,i=e.dataset;if(!i.sourceUrl||!i.sourceLine||!i.sourceColumn)continue;const s=i.sourceUrl,n=Number(i.sourceLine),r=Number(i.sourceColumn),o=await D.Linkifier.linkifyURL(s,{lineNumber:n,columnNumber:r,maxLength:40,bypassURLTrimming:void 0,className:void 0,preventClick:void 0,tabStop:void 0,text:void 0});v.Tooltip.install(e,""),e.textContent="",e.appendChild(o)}}static handleDarkMode(e){"dark"===U.instance().themeName()&&e.classList.add("dark")}}class Oe extends self.ReportUIFeatures{constructor(e){super(e),this._beforePrint=null,this._afterPrint=null}setBeforePrint(e){this._beforePrint=e}setAfterPrint(e){this._afterPrint=e}getReportHtml(){return this.resetUIState(),Lighthouse.ReportGenerator.generateReportHtml(this.json)}async _saveFile(e){const t=`${new i.ParsedURL(this.json.finalUrl).domain().replace(/[^a-z0-9.-]+/gi,"_")}-${O.toISO8601Compact(new Date(this.json.fetchTime))}${e.type.match("json")?".json":".html"}`,s=await e.text();B.FileManager.instance().save(t,s,!0)}async _print(){const e=this.getDocument().querySelector(".lh-root").cloneNode(!0),t=window.open("","_blank","channelmode=1,status=1,resizable=1");if(!t)return;const i=t.document.createElement("style");i.textContent=b.cachedResources.get("third_party/lighthouse/report-assets/report.css")||"",t.document.head.appendChild(i),t.document.body.replaceWith(e),await De.linkifyNodeDetails(e),this._beforePrint&&this._beforePrint(),t.focus(),t.print(),t.close(),this._afterPrint&&this._afterPrint()}getDocument(){return this._document}resetUIState(){this._resetUIState()}}var Ue=Object.freeze({__proto__:null,UIStrings:Re,LighthouseReportRenderer:De,LighthouseReportUIFeatures:Oe});const Ne={reports:"Reports",newReport:"(new report)"},Be=r.registerUIStrings("lighthouse/LighthouseReportSelector.js",Ne),Fe=r.getLocalizedString.bind(void 0,Be);class He{constructor(e){this._renderNewLighthouseView=e,this._newLighthouseItem=document.createElement("option"),this._comboBox=new C.ToolbarComboBox(this._handleChange.bind(this),Fe(Ne.reports),"lighthouse-report"),this._comboBox.setMaxWidth(180),this._comboBox.setMinWidth(140),this._itemByOptionElement=new Map,this._setEmptyState()}_setEmptyState(){this._comboBox.selectElement().removeChildren(),this._comboBox.setEnabled(!1),this._newLighthouseItem=document.createElement("option"),this._newLighthouseItem.label=Fe(Ne.newReport),this._comboBox.selectElement().appendChild(this._newLighthouseItem),this._comboBox.select(this._newLighthouseItem)}_handleChange(e){const t=this._selectedItem();t?t.select():this._renderNewLighthouseView()}_selectedItem(){const e=this._comboBox.selectedOption();return this._itemByOptionElement.get(e)}hasCurrentSelection(){return!!this._selectedItem()}hasItems(){return this._itemByOptionElement.size>0}comboBox(){return this._comboBox}prepend(e){const t=e.optionElement(),i=this._comboBox.selectElement();this._itemByOptionElement.set(t,e),i.insertBefore(t,i.firstElementChild),this._comboBox.setEnabled(!0),this._comboBox.select(t),e.select()}clearAll(){for(const e of this._comboBox.options())e!==this._newLighthouseItem&&(this._itemByOptionElement.get(e).delete(),this._itemByOptionElement.delete(e));this._setEmptyState()}selectNewReport(){this._comboBox.select(this._newLighthouseItem)}}class $e{constructor(e,t,s){this._lighthouseResult=e,this._renderReport=t,this._showLandingCallback=s;const n=new i.ParsedURL(e.finalUrl),r=e.fetchTime;this._element=document.createElement("option"),this._element.label=`${new Date(r).toLocaleTimeString()} - ${n.domain()}`}select(){this._renderReport()}optionElement(){return this._element}delete(){this._element&&this._element.remove(),this._showLandingCallback()}}var je=Object.freeze({__proto__:null,UIStrings:Ne,ReportSelector:He,Item:$e});class Ge{constructor(e,t,i){this._setting=t,this._options=e,this.element=document.createElement("div"),S.setDescription(this.element,i),S.markAsRadioGroup(this.element),this._radioElements=[];for(const e of this._options){const s=T.Fragment.build`
        <label $="label" class="lighthouse-radio">
          <input $="input" type="radio" value=${e.value} name=${t.name}>
          <span $="span" class="lighthouse-radio-text">${e.label}</span>
        </label>
      `;this.element.appendChild(s.element()),i&&(v.Tooltip.install(s.$("input"),i),v.Tooltip.install(s.$("span"),i));const n=s.$("input");n.addEventListener("change",this._valueChanged.bind(this)),this._radioElements.push(n)}this._ignoreChangeEvents=!1,this._selectedIndex=-1,t.addChangeListener(this._settingChanged,this),this._settingChanged()}_updateUI(){this._ignoreChangeEvents=!0,this._radioElements[this._selectedIndex].checked=!0,this._ignoreChangeEvents=!1}_settingChanged(){const e=this._setting.get();this._selectedIndex=this._options.findIndex((t=>t.value===e)),this._updateUI()}_valueChanged(e){if(this._ignoreChangeEvents)return;const t=this._radioElements.find((e=>e.checked));t&&this._setting.set(t.value)}}var Ve=Object.freeze({__proto__:null,RadioSetting:Ge});const We={learnMore:"Learn more",device:"Device",categories:"Categories",communityPluginsBeta:"Community Plugins (beta)",generateReport:"Generate report",identifyAndFixCommonProblemsThat:"Identify and fix common problems that affect your site's performance, accessibility, and user experience."},qe=r.registerUIStrings("lighthouse/LighthouseStartView.js",We),ze=r.getLocalizedString.bind(void 0,qe);class Je extends x.Widget{constructor(e){super(),this.registerRequiredCSS("lighthouse/lighthouseStartView.css",{enableLegacyPatching:!1}),this._controller=e,this._settingsToolbar=new C.Toolbar(""),this._render()}settingsToolbar(){return this._settingsToolbar}_populateRuntimeSettingAsRadio(e,t,i){const s=xe.find((t=>t.setting.name===e));if(!s||!s.options)throw new Error(e+" is not a setting with options");const n=new Ge(s.options,s.setting,s.description);i.appendChild(n.element),S.setAccessibleName(n.element,t)}_populateRuntimeSettingAsToolbarCheckbox(e,t){const i=xe.find((t=>t.setting.name===e));if(!i||!i.title)throw new Error(e+" is not a setting with a title");i.setting.setTitle(i.title);const s=new C.ToolbarSettingCheckbox(i.setting,i.description);if(t.appendToolbarItem(s),i.learnMore){const e=L.XLink.create(i.learnMore,ze(We.learnMore),"lighthouse-learn-more");e.style.padding="5px",s.element.appendChild(e)}}_populateFormControls(e){const t=e.$("device-type-form-elements");this._populateRuntimeSettingAsRadio("lighthouse.device_type",ze(We.device),t);const i=e.$("categories-form-elements"),s=e.$("plugins-form-elements");for(const e of Te){const t=e.plugin?s:i;e.setting.setTitle(e.title);const n=new C.ToolbarSettingCheckbox(e.setting,e.description);t.createChild("div","vbox lighthouse-launcher-row").appendChild(n.element)}S.markAsGroup(i),S.setAccessibleName(i,ze(We.categories)),S.markAsGroup(s),S.setAccessibleName(s,ze(We.communityPluginsBeta))}_render(){this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.clear_storage",this._settingsToolbar),this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.throttling",this._settingsToolbar),this._startButton=y.createTextButton(ze(We.generateReport),(()=>this._controller.dispatchEventToListeners(Le.RequestLighthouseStart,this._startButton.matches(":focus-visible"))),"",!0),this.setDefaultFocusedElement(this._startButton);const e=ze(We.identifyAndFixCommonProblemsThat),t=T.Fragment.build`
      <div class="vbox lighthouse-start-view">
        <header>
          <div class="lighthouse-logo"></div>
          <div class="lighthouse-start-button-container hbox">
            ${this._startButton}
            </div>
          <div $="help-text" class="lighthouse-help-text hidden"></div>
          <div class="lighthouse-start-view-text">
            <span>${e}</span>
            ${L.XLink.create("https://developers.google.com/web/tools/lighthouse/",ze(We.learnMore))}
          </div>
          <div $="warning-text" class="lighthouse-warning-text hidden"></div>
        </header>
        <form>
          <div class="lighthouse-form-categories">
            <div class="lighthouse-form-section">
              <div class="lighthouse-form-section-label">
                ${ze(We.categories)}
              </div>
              <div class="lighthouse-form-elements" $="categories-form-elements"></div>
            </div>
            <div class="lighthouse-form-section">
              <div class="lighthouse-form-section-label">
                <div class="lighthouse-icon-label">${ze(We.communityPluginsBeta)}</div>
              </div>
              <div class="lighthouse-form-elements" $="plugins-form-elements"></div>
            </div>
          </div>
          <div class="lighthouse-form-section">
            <div class="lighthouse-form-section-label">
              ${ze(We.device)}
            </div>
            <div class="lighthouse-form-elements" $="device-type-form-elements"></div>
          </div>
        </form>
      </div>
    `;this._helpText=t.$("help-text"),this._warningText=t.$("warning-text"),this._populateFormControls(t),this.contentElement.appendChild(t.element()),this.contentElement.style.overflow="auto"}onResize(){const e=this.contentElement.offsetWidth<560,t=this.contentElement.querySelector(".lighthouse-start-view");t&&(t.classList.toggle("hbox",!e),t.classList.toggle("vbox",e))}focusStartButton(){this._startButton.focus()}setStartButtonEnabled(e){this._helpText&&this._helpText.classList.toggle("hidden",e),this._startButton&&(this._startButton.disabled=!e)}setUnauditableExplanation(e){this._helpText&&(this._helpText.textContent=e)}setWarningText(e){this._warningText&&(this._warningText.textContent=e,this._warningText.classList.toggle("hidden",!e),this._shouldConfirm=!!e)}}var Ke=Object.freeze({__proto__:null,UIStrings:We,StartView:Je});const Ye={cancel:"Cancel",loading:"Loading…",auditingS:"Auditing {PH1}",auditingYourWebPage:"Auditing your web page",cancelling:"Cancelling…",lighthouseIsWarmingUp:"`Lighthouse` is warming up…",lighthouseIsLoadingYourPage:"`Lighthouse` is loading your page",fastFactMessageWithPlaceholder:"💡 {PH1}",ahSorryWeRanIntoAnError:"Ah, sorry! We ran into an error.",tryToNavigateToTheUrlInAFresh:"Try to navigate to the URL in a fresh `Chrome` profile without any other tabs or extensions open and try again.",ifThisIssueIsReproduciblePlease:"If this issue is reproducible, please report it at the `Lighthouse` `GitHub` repo.",lighthouseIsLoadingThePage:"Lighthouse is loading the page.",lighthouseIsGatheringInformation:"`Lighthouse` is gathering information about the page to compute your score.",almostThereLighthouseIsNow:"Almost there! `Lighthouse` is now generating your report.",lighthouseIsLoadingYourPageWith:"`Lighthouse` is loading your page with throttling to measure performance on a mobile device on 3G.",lighthouseIsLoadingYourPageWithThrottling:"`Lighthouse` is loading your page with throttling to measure performance on a slow desktop on 3G.",lighthouseIsLoadingYourPageWithMobile:"`Lighthouse` is loading your page with mobile emulation.",mbTakesAMinimumOfSecondsTo:"1MB takes a minimum of 5 seconds to download on a typical 3G connection [Source: `WebPageTest` and `DevTools` 3G definition].",rebuildingPinterestPagesFor:"Rebuilding Pinterest pages for performance increased conversion rates by 15% [Source: `WPO Stats`]",byReducingTheResponseSizeOfJson:"By reducing the response size of JSON needed for displaying comments, Instagram saw increased impressions [Source: `WPO Stats`]",walmartSawAIncreaseInRevenueFor:"Walmart saw a 1% increase in revenue for every 100ms improvement in page load [Source: `WPO Stats`]",ifASiteTakesSecondToBecome:"If a site takes >1 second to become interactive, users lose attention, and their perception of completing the page task is broken [Source: `Google Developers Blog`]",OfGlobalMobileUsersInWereOnGOrG:"75% of global mobile users in 2016 were on 2G or 3G [Source: `GSMA Mobile`]",theAverageUserDeviceCostsLess:"The average user device costs less than 200 USD. [Source: `International Data Corporation`]",SecondsIsTheAverageTimeAMobile:"19 seconds is the average time a mobile web page takes to load on a 3G connection [Source: `Google DoubleClick blog`]",OfMobilePagesTakeNearlySeconds:"70% of mobile pages take nearly 7 seconds for the visual content above the fold to display on the screen. [Source: `Think with Google`]",asPageLoadTimeIncreasesFromOne:"As page load time increases from one second to seven seconds, the probability of a mobile site visitor bouncing increases 113%. [Source: `Think with Google`]",asTheNumberOfElementsOnAPage:"As the number of elements on a page increases from 400 to 6,000, the probability of conversion drops 95%. [Source: `Think with Google`]",lighthouseOnlySimulatesMobile:"`Lighthouse` only simulates mobile performance; to measure performance on a real device, try WebPageTest.org [Source: `Lighthouse` team]"},Qe=r.registerUIStrings("lighthouse/LighthouseStatusView.js",Ye),Ze=r.getLocalizedString.bind(void 0,Qe);class Xe{constructor(e){this._controller=e,this._statusView=null,this._statusHeader=null,this._progressWrapper=null,this._progressBar=null,this._statusText=null,this._cancelButton=null,this._inspectedURL="",this._textChangedAt=0,this._fastFactsQueued=rt.slice(),this._currentPhase=null,this._scheduledTextChangeTimeout=null,this._scheduledFastFactTimeout=null,this._dialog=new E.Dialog,this._dialog.setDimmed(!0),this._dialog.setCloseOnEscape(!1),this._dialog.setOutsideClickCallback((e=>e.consume(!0))),this._render()}_render(){const e=A.createShadowRootWithCoreStyles(this._dialog.contentElement,{cssFile:"lighthouse/lighthouseDialog.css",enableLegacyPatching:!1,delegatesFocus:void 0}).createChild("div","lighthouse-view vbox"),t=y.createTextButton(Ze(Ye.cancel),this._cancel.bind(this)),i=T.Fragment.build`
      <div class="lighthouse-view vbox">
        <h2 $="status-header">Auditing your web page…</h2>
        <div class="lighthouse-status vbox" $="status-view">
          <div class="lighthouse-progress-wrapper" $="progress-wrapper">
            <div class="lighthouse-progress-bar" $="progress-bar"></div>
          </div>
          <div class="lighthouse-status-text" $="status-text"></div>
        </div>
        ${t}
      </div>
    `;e.appendChild(i.element()),this._statusView=i.$("status-view"),this._statusHeader=i.$("status-header"),this._progressWrapper=i.$("progress-wrapper"),this._progressBar=i.$("progress-bar"),this._statusText=i.$("status-text"),S.markAsProgressBar(this._progressBar,0,st.length-1),this._cancelButton=t,S.markAsStatus(this._statusText),this._dialog.setDefaultFocusedElement(t),this._dialog.setSizeBehavior(k.SizeBehavior.SetExactWidthMaxHeight),this._dialog.setMaxContentSize(new P.Size(500,400))}_reset(){this._resetProgressBarClasses(),clearTimeout(this._scheduledFastFactTimeout),this._textChangedAt=0,this._fastFactsQueued=rt.slice(),this._currentPhase=null,this._scheduledTextChangeTimeout=null,this._scheduledFastFactTimeout=null}show(e){this._reset(),this.updateStatus(Ze(Ye.loading));const t=i.ParsedURL.fromString(this._inspectedURL),s=t&&t.host,n=s?Ze(Ye.auditingS,{PH1:s}):Ze(Ye.auditingYourWebPage);this._renderStatusHeader(n),this._dialog.show(e)}_renderStatusHeader(e){this._statusHeader&&(this._statusHeader.textContent=e+"…")}hide(){this._dialog.isShowing()&&this._dialog.hide()}setInspectedURL(e=""){this._inspectedURL=e}updateStatus(e){if(!e||!this._statusText)return;if(e.startsWith("Cancel"))return this._commitTextChange(Ze(Ye.cancelling)),void clearTimeout(this._scheduledFastFactTimeout);const t=this._getPhaseForMessage(e),i=st.indexOf(t),s=st.indexOf(this._currentPhase);if(t||this._currentPhase){if(t&&(!this._currentPhase||s<i)){this._currentPhase=t;const e=this._getMessageForPhase(t);this._scheduleTextChange(e),this._scheduleFastFactCheck(),this._resetProgressBarClasses(),this._progressBar&&(this._progressBar.classList.add(t.progressBarClass),S.setProgressBarValue(this._progressBar,i,e))}}else this._commitTextChange(Ze(Ye.lighthouseIsWarmingUp)),clearTimeout(this._scheduledFastFactTimeout)}_cancel(){this._controller.dispatchEventToListeners(Le.RequestLighthouseCancel)}_getMessageForPhase(e){if(e.message)return e.message;const t=xe.find((e=>"lighthouse.device_type"===e.setting.name)),i=xe.find((e=>"lighthouse.throttling"===e.setting.name)),s=t?t.setting.get():"",n=i?i.setting.get():"",r=nt.find((e=>e.deviceType===s&&e.throttling===n));return r?r.message:Ze(Ye.lighthouseIsLoadingYourPage)}_getPhaseForMessage(e){return st.find((t=>e.startsWith(t.statusMessagePrefix)))||null}_resetProgressBarClasses(){this._progressBar&&(this._progressBar.className="lighthouse-progress-bar")}_scheduleFastFactCheck(){this._currentPhase&&!this._scheduledFastFactTimeout&&(this._scheduledFastFactTimeout=setTimeout((()=>{this._updateFastFactIfNecessary(),this._scheduledFastFactTimeout=null,this._scheduleFastFactCheck()}),100))}_updateFastFactIfNecessary(){if(performance.now()-this._textChangedAt<et)return;if(!this._fastFactsQueued.length)return;const e=Math.floor(Math.random()*this._fastFactsQueued.length);this._scheduleTextChange(Ze(Ye.fastFactMessageWithPlaceholder,{PH1:this._fastFactsQueued[e]})),this._fastFactsQueued.splice(e,1)}_commitTextChange(e){this._statusText&&(this._textChangedAt=performance.now(),this._statusText.textContent=e)}_scheduleTextChange(e){this._scheduledTextChangeTimeout&&clearTimeout(this._scheduledTextChangeTimeout);const t=performance.now()-this._textChangedAt,i=tt-t;this._scheduledTextChangeTimeout=setTimeout((()=>{this._commitTextChange(e)}),Math.max(i,0))}renderBugReport(e){if(console.error(e),this._scheduledFastFactTimeout&&window.clearTimeout(this._scheduledFastFactTimeout),this._scheduledTextChangeTimeout&&window.clearTimeout(this._scheduledTextChangeTimeout),this._resetProgressBarClasses(),this._progressBar&&this._progressBar.classList.add("errored"),this._statusText)if(this._commitTextChange(""),y.createTextChild(this._statusText.createChild("p"),Ze(Ye.ahSorryWeRanIntoAnError)),it.some((t=>t.test(e.message)))){const e=Ze(Ye.tryToNavigateToTheUrlInAFresh);y.createTextChild(this._statusText.createChild("p"),e)}else this._renderBugReportBody(e,this._inspectedURL)}renderText(e,t){this._renderStatusHeader(e),this._commitTextChange(t)}toggleCancelButton(e){this._cancelButton&&(this._cancelButton.style.visibility=e?"visible":"hidden")}_renderBugReportBody(e,t){const i=navigator.userAgent.match(/Chrome\/(\S+)/)||["","Unknown"],s=`\n${e.friendlyMessage||e.message}\n\`\`\`\nChannel: DevTools\nInitial URL: ${t}\nChrome Version: ${i[1]}\nStack Trace: ${e.stack}\n\`\`\`\n`;this._statusText&&(y.createTextChild(this._statusText.createChild("p"),Ze(Ye.ifThisIssueIsReproduciblePlease)),y.createTextChild(this._statusText.createChild("code","monospace"),s.trim()))}}const et=6e3,tt=3e3,it=[/PARSING_PROBLEM/,/DOCUMENT_REQUEST/,/READ_FAILED/,/TRACING_ALREADY_STARTED/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/],st=[{id:"loading",progressBarClass:"loading",message:Ze(Ye.lighthouseIsLoadingThePage),statusMessagePrefix:"Loading page"},{id:"gathering",progressBarClass:"gathering",message:Ze(Ye.lighthouseIsGatheringInformation),statusMessagePrefix:"Gathering"},{id:"auditing",progressBarClass:"auditing",message:Ze(Ye.almostThereLighthouseIsNow),statusMessagePrefix:"Auditing"}],nt=[{deviceType:"mobile",throttling:"on",message:Ze(Ye.lighthouseIsLoadingYourPageWith)},{deviceType:"desktop",throttling:"on",message:Ze(Ye.lighthouseIsLoadingYourPageWithThrottling)},{deviceType:"mobile",throttling:"off",message:Ze(Ye.lighthouseIsLoadingYourPageWithMobile)},{deviceType:"desktop",throttling:"off",message:Ze(Ye.lighthouseIsLoadingThePage)}],rt=[Ze(Ye.mbTakesAMinimumOfSecondsTo),Ze(Ye.rebuildingPinterestPagesFor),Ze(Ye.byReducingTheResponseSizeOfJson),Ze(Ye.walmartSawAIncreaseInRevenueFor),Ze(Ye.ifASiteTakesSecondToBecome),Ze(Ye.OfGlobalMobileUsersInWereOnGOrG),Ze(Ye.theAverageUserDeviceCostsLess),Ze(Ye.SecondsIsTheAverageTimeAMobile),Ze(Ye.OfMobilePagesTakeNearlySeconds),Ze(Ye.asPageLoadTimeIncreasesFromOne),Ze(Ye.asTheNumberOfElementsOnAPage),Ze(Ye.OfMobilePagesTakeNearlySeconds),Ze(Ye.lighthouseOnlySimulatesMobile)];var ot=Object.freeze({__proto__:null,UIStrings:Ye,StatusView:Xe,fastFactRotationInterval:et,minimumTextVisibilityDuration:tt,StatusPhases:st});const at={dropLighthouseJsonHere:"Drop `Lighthouse` JSON here",performAnAudit:"Perform an audit…",clearAll:"Clear all",lighthouseSettings:"`Lighthouse` settings",printing:"Printing",thePrintPopupWindowIsOpenPlease:"The print popup window is open. Please close it to continue.",cancelling:"Cancelling"},lt=r.registerUIStrings("lighthouse/LighthousePanel.js",at),dt=r.getLocalizedString.bind(void 0,lt);class ht extends R.Panel{constructor(){super("lighthouse"),this.registerRequiredCSS("third_party/lighthouse/report-assets/report.css",{enableLegacyPatching:!0}),this.registerRequiredCSS("lighthouse/lighthousePanel.css",{enableLegacyPatching:!1}),this._protocolService=new Ae,this._controller=new Ce(this._protocolService),this._startView=new Je(this._controller),this._statusView=new Xe(this._controller),this._warningText=null,this._unauditableExplanation=null,this._cachedRenderedReports=new Map,this._dropTarget=new M.DropTarget(this.contentElement,[M.Type.File],dt(at.dropLighthouseJsonHere),this._handleDrop.bind(this)),this._controller.addEventListener(Le.PageAuditabilityChanged,this._refreshStartAuditUI.bind(this)),this._controller.addEventListener(Le.PageWarningsChanged,this._refreshWarningsUI.bind(this)),this._controller.addEventListener(Le.AuditProgressChanged,this._refreshStatusUI.bind(this)),this._controller.addEventListener(Le.RequestLighthouseStart,(e=>{this._startLighthouse(e)})),this._controller.addEventListener(Le.RequestLighthouseCancel,(e=>{this._cancelLighthouse()})),this._renderToolbar(),this._auditResultsElement=this.contentElement.createChild("div","lighthouse-results-container"),this._renderStartView(),this._controller.recomputePageAuditability(),this._clearButton,this._newButton,this._reportSelector,this._settingsPane,this._rightToolbar,this._showSettingsPaneSetting}static getEvents(){return Le}_refreshWarningsUI(e){this._isLHAttached||(this._warningText=e.data.warning,this._startView.setWarningText(e.data.warning))}_refreshStartAuditUI(e){this._isLHAttached||(this._unauditableExplanation=e.data.helpText,this._startView.setUnauditableExplanation(e.data.helpText),this._startView.setStartButtonEnabled(!e.data.helpText))}_refreshStatusUI(e){this._statusView.updateStatus(e.data.message)}_refreshToolbarUI(){this._clearButton.setEnabled(this._reportSelector.hasItems())}_clearAll(){this._reportSelector.clearAll(),this._renderStartView(),this._refreshToolbarUI()}_renderToolbar(){const e=this.element.createChild("div","lighthouse-toolbar-container"),t=new C.Toolbar("",e);this._newButton=new C.ToolbarButton(dt(at.performAnAudit),"largeicon-add"),t.appendToolbarItem(this._newButton),this._newButton.addEventListener(C.ToolbarButton.Events.Click,this._renderStartView.bind(this)),t.appendSeparator(),this._reportSelector=new He((()=>this._renderStartView())),t.appendToolbarItem(this._reportSelector.comboBox()),this._clearButton=new C.ToolbarButton(dt(at.clearAll),"largeicon-clear"),t.appendToolbarItem(this._clearButton),this._clearButton.addEventListener(C.ToolbarButton.Events.Click,this._clearAll.bind(this)),this._settingsPane=new x.HBox,this._settingsPane.show(this.contentElement),this._settingsPane.element.classList.add("lighthouse-settings-pane"),this._settingsPane.element.appendChild(this._startView.settingsToolbar().element),this._showSettingsPaneSetting=s.Settings.instance().createSetting("lighthouseShowSettingsToolbar",!1),this._rightToolbar=new C.Toolbar("",e),this._rightToolbar.appendSeparator(),this._rightToolbar.appendToolbarItem(new C.ToolbarSettingToggle(this._showSettingsPaneSetting,"largeicon-settings-gear",dt(at.lighthouseSettings))),this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this)),this._updateSettingsPaneVisibility(),this._refreshToolbarUI()}_updateSettingsPaneVisibility(){this._settingsPane.element.classList.toggle("hidden",!this._showSettingsPaneSetting.get())}_toggleSettingsDisplay(e){this._rightToolbar.element.classList.toggle("hidden",!e),this._settingsPane.element.classList.toggle("hidden",!e),this._updateSettingsPaneVisibility()}_renderStartView(){this._auditResultsElement.removeChildren(),this._statusView.hide(),this._reportSelector.selectNewReport(),this.contentElement.classList.toggle("in-progress",!1),this._startView.show(this.contentElement),this._toggleSettingsDisplay(!0),this._startView.setUnauditableExplanation(this._unauditableExplanation),this._startView.setStartButtonEnabled(!this._unauditableExplanation),this._unauditableExplanation||this._startView.focusStartButton(),this._startView.setWarningText(this._warningText),this._newButton.setEnabled(!1),this._refreshToolbarUI(),this.setDefaultFocusedChild(this._startView)}_renderStatusView(e){this.contentElement.classList.toggle("in-progress",!0),this._statusView.setInspectedURL(e),this._statusView.show(this.contentElement)}_beforePrint(){this._statusView.show(this.contentElement),this._statusView.toggleCancelButton(!1),this._statusView.renderText(dt(at.printing),dt(at.thePrintPopupWindowIsOpenPlease))}_afterPrint(){this._statusView.hide(),this._statusView.toggleCancelButton(!0)}_renderReport(e,t){this._toggleSettingsDisplay(!1),this.contentElement.classList.toggle("in-progress",!1),this._startView.hideWidget(),this._statusView.hide(),this._auditResultsElement.removeChildren(),this._newButton.setEnabled(!0),this._refreshToolbarUI();const i=this._cachedRenderedReports.get(e);if(i)return void this._auditResultsElement.appendChild(i);const s=this._auditResultsElement.createChild("div","lh-vars lh-root lh-devtools"),n=new DOM(this._auditResultsElement.ownerDocument),r=new De(n),o=b.cachedResources.get("third_party/lighthouse/report-assets/templates.html");if(!o)return;const a=(new DOMParser).parseFromString(o,"text/html");if(!a)return;r.setTemplateContext(a);const l=r.renderReport(e,s);De.addViewTraceButton(l,t),this._waitForMainTargetLoad().then((()=>{De.linkifyNodeDetails(l),De.linkifySourceLocationDetails(l)})),De.handleDarkMode(l);const d=new Oe(n);d.setBeforePrint(this._beforePrint.bind(this)),d.setAfterPrint(this._afterPrint.bind(this)),d.setTemplateContext(a),d.initFeatures(e),this._cachedRenderedReports.set(e,s)}async _waitForMainTargetLoad(){const e=o.TargetManager.instance().mainTarget();if(!e)return;const t=e.model(c.ResourceTreeModel);return t?t.once(c.Events.Load):void 0}_buildReportUI(e,t){if(null===e)return;const i=new $e(e,(()=>this._renderReport(e,t)),this._renderStartView.bind(this));this._reportSelector.prepend(i),this._refreshToolbarUI(),this._renderReport(e)}_handleDrop(e){const t=e.items;if(!t.length)return;if("file"===t[0].kind){const e=t[0].webkitGetAsEntry();if(!e.isFile)return;e.file((e=>{const t=new FileReader;t.onload=()=>this._loadedFromFile(t.result),t.readAsText(e)}))}}_loadedFromFile(e){const t=JSON.parse(e);t.lighthouseVersion&&this._buildReportUI(t)}async _startLighthouse(e){_.actionTaken(f.Action.LighthouseStarted);try{const e=await this._controller.getInspectedURL({force:!0}),t=this._controller.getCategoryIDs(),i=this._controller.getFlags();await this._setupEmulationAndProtocolConnection(),this._renderStatusView(e);const s=await this._protocolService.startLighthouse(e,t,i);if(s&&s.fatal){const e=new Error(s.message);throw e.stack=s.stack,e}if(!s)throw new Error("Auditing failed to produce a result");_.actionTaken(f.Action.LighthouseFinished),await this._resetEmulationAndProtocolConnection(),this._buildReportUI(s.lhr,s.artifacts),this._newButton.element.focus()}catch(e){await this._resetEmulationAndProtocolConnection(),e instanceof Error&&this._statusView.renderBugReport(e)}}async _cancelLighthouse(){this._statusView.updateStatus(dt(at.cancelling)),await this._resetEmulationAndProtocolConnection(),this._renderStartView()}async _setupEmulationAndProtocolConnection(){const e=this._controller.getFlags(),t=p.DeviceModeModel.instance();if(this._stateBefore={emulation:{enabled:t.enabledSetting().get(),outlineEnabled:t.deviceOutlineSetting().get(),toolbarControlsEnabled:t.toolbarControlsEnabledSetting().get()},network:{conditions:u.MultitargetNetworkManager.instance().networkConditions()}},t.toolbarControlsEnabledSetting().set(!1),"emulatedFormFactor"in e&&"desktop"===e.emulatedFormFactor)t.enabledSetting().set(!1),t.emulate(p.Type.None,null,null);else if("mobile"===e.emulatedFormFactor){t.enabledSetting().set(!0),t.deviceOutlineSetting().set(!0);for(const e of g.EmulatedDevicesList.instance().standard())"Moto G4"===e.title&&t.emulate(p.Type.Device,e,e.modes[0],1)}await this._protocolService.attach(),this._isLHAttached=!0}async _resetEmulationAndProtocolConnection(){if(!this._isLHAttached)return;if(this._isLHAttached=!1,await this._protocolService.detach(),this._stateBefore){const e=p.DeviceModeModel.instance();e.enabledSetting().set(this._stateBefore.emulation.enabled),e.deviceOutlineSetting().set(this._stateBefore.emulation.outlineEnabled),e.toolbarControlsEnabledSetting().set(this._stateBefore.emulation.toolbarControlsEnabled),u.MultitargetNetworkManager.instance().setNetworkConditions(this._stateBefore.network.conditions),delete this._stateBefore}m.InspectedPagePlaceholder.instance().update(!0);const e=o.TargetManager.instance().mainTarget();if(!e)return;const t=e.model(c.ResourceTreeModel);if(!t)return;const i=await this._controller.getInspectedURL();await t.navigate(i)}}var ct=Object.freeze({__proto__:null,UIStrings:at,LighthousePanel:ht});export{Ee as LighthouseController,ct as LighthousePanel,ke as LighthouseProtocolService,Ue as LighthouseReportRenderer,je as LighthouseReportSelector,Pe as LighthouseReporterTypes,Ke as LighthouseStartView,ot as LighthouseStatusView,Ve as RadioSetting};
