import{ObjectWrapper as e,EventTarget as t,ParsedURL as s,UIString as i,Settings as n,Linkifier as r}from"../common/common.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 m,InspectedPagePlaceholder as g}from"../emulation/emulation.js";import{userMetrics as _}from"../host/host.js";import{Runtime as f}from"../root/root.js";import{UIUtils as b,InspectorView as v,Toolbar as y,ARIAUtils as w,Fragment as C,Tooltip as S,Widget as T,XLink as x,Dialog as E,Utils as L,GlassPane as k,Geometry as A,Panel as R,DropTarget as P}from"../ui/ui.js";import{Linkifier as M}from"../components/components.js";import{DateUtilities as D}from"../platform/platform.js";import{ThemeSupport as U}from"../theme_support/theme_support.js";import{TimelinePanel as I}from"../timeline/timeline.js";import{FileManager as N}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 O={label:"pass",minScore:.9},B={label:"average",minScore:.5},F={label:"fail"},$={label:"error"},H=["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 j{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 s=t.audits[e.id];e.result=s,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)>=O.minScore}}static calculateRating(e,t){if("manual"===t||"notApplicable"===t)return O.label;if("error"===t)return $.label;if(null===e)return F.label;let s=F.label;return e>=O.minScore?s=O.label:e>=B.minScore&&(s=B.label),s}static splitMarkdownCodeSpans(e){const t=[],s=e.split(/`(.*?)`/g);for(let e=0;e<s.length;e++){const i=s[e];if(!i)continue;const n=e%2!=0;t.push({isCode:n,text:i})}return t}static splitMarkdownLink(e){const t=[],s=e.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);for(;s.length;){const[e,i,n]=s.splice(0,3);e&&t.push({isLink:!1,text:e}),i&&n&&t.push({isLink:!0,text:i,linkHref:n})}return t}static getURLDisplayName(e,t){const s=void 0!==(t=t||{numPathParts:void 0,preserveQuery:void 0,preserveHost:void 0}).numPathParts?t.numPathParts:2,i=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);s&&t.length>s&&(r="…"+t.slice(-1*s).join("/")),n&&(r=`${e.host}/${r.replace(/^\//,"")}`),i&&(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:j.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 H.includes(t[0])?"."+t.join("."):"."+t[t.length-1]}static getRootDomain(e){const t=j.createOrReturnURL(e).hostname,s=j.getTld(t).split(".");return t.split(".").slice(-s.length).join(".")}static getEnvironmentDisplayValues(e){const t=j.getEmulationDescriptions(e);return[{name:j.i18n.strings.runtimeSettingsDevice,description:t.deviceEmulation},{name:j.i18n.strings.runtimeSettingsNetworkThrottling,description:t.networkThrottling},{name:j.i18n.strings.runtimeSettingsCPUThrottling,description:t.cpuThrottling}]}static getEmulationDescriptions(e){let t,s;const i=e.throttling;switch(e.throttlingMethod){case"provided":t=j.i18n.strings.throttlingProvided,s=j.i18n.strings.throttlingProvided;break;case"devtools":{const{cpuSlowdownMultiplier:e,requestLatencyMs:n}=i;t=j.i18n.formatNumber(e)+"x slowdown (DevTools)",s=j.i18n.formatNumber(n)+" ms HTTP RTT, "+j.i18n.formatNumber(i.downloadThroughputKbps)+" Kbps down, "+j.i18n.formatNumber(i.uploadThroughputKbps)+" Kbps up (DevTools)";break}case"simulate":{const{cpuSlowdownMultiplier:e,rttMs:n,throughputKbps:r}=i;t=j.i18n.formatNumber(e)+"x slowdown (Simulated)",s=j.i18n.formatNumber(n)+" ms TCP RTT, "+j.i18n.formatNumber(r)+" Kbps throughput (Simulated)";break}default:t=j.i18n.strings.runtimeUnknown,s=j.i18n.strings.runtimeUnknown}let n=j.i18n.strings.runtimeNoEmulation;return"mobile"===e.emulatedFormFactor?n=j.i18n.strings.runtimeMobileEmulation:"desktop"===e.emulatedFormFactor&&(n=j.i18n.strings.runtimeDesktopEmulation),{deviceEmulation:n,cpuThrottling:t,networkThrottling:s}}static filterRelevantLines(e,t,s){if(0===t.length)return e.slice(0,2*s+1);const i=new Set;return(t=t.sort((e,t)=>(e.lineNumber||0)-(t.lineNumber||0))).forEach(({lineNumber:e})=>{let t=e-s,n=e+s;for(;t<1;)t++,n++;i.has(t-3-1)&&(t-=3);for(let e=t;e<=n;e++){const t=e;i.add(t)}}),e.filter(e=>i.has(e.lineNumber))}static isPluginCategory(e){return e.startsWith("lighthouse-plugin-")}}j.reportJson=null,j.getUniqueSuffix=(()=>{let e=0;return function(){return e++}})(),j.i18n=null,j.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=j:self.Util=j;class G{constructor(e){this._document=e,this._lighthouseChannel="unknown"}createElement(e,t,s={}){const i=this._document.createElement(e);return t&&(i.className=t),Object.keys(s).forEach(e=>{const t=s[e];void 0!==t&&i.setAttribute(e,t)}),i}createElementNS(e,t,s,i={}){const n=this._document.createElementNS(e,t);return s&&(n.className=s),Object.keys(i).forEach(e=>{const t=i[e];void 0!==t&&n.setAttribute(e,t)}),n}createFragment(){return this._document.createDocumentFragment()}createChildOf(e,t,s,i){const n=this.createElement(t,s,i);return e.appendChild(n),n}cloneTemplate(e,t){const s=t.querySelector(e);if(!s)throw new Error("Template not found: template"+e);const i=this._document.importNode(s.content,!0);return s.hasAttribute("data-stamped")&&this.findAll("style",i).forEach(e=>e.remove()),s.setAttribute("data-stamped","true"),i}resetTemplates(){this.findAll("template[data-stamped]",this._document).forEach(e=>{e.removeAttribute("data-stamped")})}convertMarkdownLinkSnippets(e){const t=this.createElement("span");for(const s of j.splitMarkdownLink(e)){if(!s.isLink){t.appendChild(this._document.createTextNode(s.text));continue}const e=new URL(s.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 i=this.createElement("a");i.rel="noopener",i.target="_blank",i.textContent=s.text,i.href=e.href,t.appendChild(i)}return t}convertMarkdownCodeSnippets(e){const t=this.createElement("span");for(const s of j.splitMarkdownCodeSpans(e))if(s.isCode){const e=this.createElement("code");e.textContent=s.text,t.appendChild(e)}else t.appendChild(this._document.createTextNode(s.text));return t}setLighthouseChannel(e){this._lighthouseChannel=e}document(){return this._document}isDevTools(){return!!this._document.querySelector(".lh-devtools")}find(e,t){const s=t.querySelector(e);if(null===s)throw new Error(`query ${e} not found`);return s}findAll(e,t){return Array.from(t.querySelectorAll(e))}}"undefined"!=typeof module&&module.exports?module.exports=G:self.DOM=G,function(){var e,t,s,i,n=document.createElement("details"),r="undefined"!=typeof HTMLDetailsElement&&n instanceof HTMLDetailsElement,o="open"in n||r,a="ontoggle"in n,l=[],d=l.forEach,h=l.slice;function c(e){(function(e,t){return(e.tagName==t?[e]:[]).concat("function"==typeof e.getElementsByTagName?h.call(e.getElementsByTagName(t)):[])})(e,"SUMMARY").forEach((function(e){var t=g(e,"DETAILS");e.setAttribute("aria-expanded",t.hasAttribute("open")),e.hasAttribute("tabindex")||e.setAttribute("tabindex","0"),e.hasAttribute("role")||e.setAttribute("role","button")}))}function u(e){return!(e.defaultPrevented||e.ctrlKey||e.metaKey||e.shiftKey||e.target.isContentEditable)}function p(e){addEventListener("click",(function(t){if(u(t)&&t.which<=1){var s=g(t.target,"SUMMARY");s&&s.parentNode&&"DETAILS"==s.parentNode.tagName&&e(s.parentNode)}}),!1),addEventListener("keydown",(function(t){if(u(t)&&(13==t.keyCode||32==t.keyCode)){var s=g(t.target,"SUMMARY");s&&s.parentNode&&"DETAILS"==s.parentNode.tagName&&(e(s.parentNode),t.preventDefault())}}),!1)}function m(e){var t=document.createEvent("Event");t.initEvent("toggle",!1,!1),e.dispatchEvent(t)}function g(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>\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</style>'),e=document.createElement("details").constructor.prototype,t=e.setAttribute,s=e.removeAttribute,i=Object.getOwnPropertyDescriptor(e,"open"),Object.defineProperties(e,{open:{get:function(){return"DETAILS"==this.tagName?this.hasAttribute("open"):i&&i.get?i.get.call(this):void 0},set:function(e){return"DETAILS"==this.tagName?e?this.setAttribute("open",""):this.removeAttribute("open"):i&&i.set?i.set.call(this,e):void 0}},setAttribute:{value:function(e,s){var i=this,n=function(){return t.call(i,e,s)};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,i=function(){return s.call(t,e)};if("open"==e&&"DETAILS"==this.tagName){var n=this.hasAttribute("open"),r=i();if(n){var o=this.querySelector("summary");o&&o.setAttribute("aria-expanded",!1),m(this)}return r}return i()}}}),p((function(e){e.hasAttribute("open")?e.removeAttribute("open"):e.setAttribute("open","")})),c(document),window.MutationObserver?new MutationObserver((function(e){d.call(e,(function(e){d.call(e.addedNodes,c)}))})).observe(document.documentElement,{subtree:!0,childList:!0}):document.addEventListener("DOMNodeInserted",(function(e){c(e.target)}))),o&&!a&&(window.MutationObserver?new MutationObserver((function(e){d.call(e,(function(e){var t=e.target,s=e.attributeName;"DETAILS"==t.tagName&&"open"==s&&m(t)}))})).observe(document.documentElement,{attributes:!0,subtree:!0}):p((function(e){var t=e.getAttribute("open");setTimeout((function(){var s=e.getAttribute("open");t!=s&&m(e)}),1)})))}();const V=["http://","https://","data:"];class W{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 q.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=j.i18n.formatBytesToKiB(e.value,e.granularity),s=this._renderText(t);return s.title=j.i18n.formatBytes(e.value),s}_renderMilliseconds(e){let t=j.i18n.formatMilliseconds(e.value,e.granularity);return"duration"===e.displayUnit&&(t=j.i18n.formatDuration(e.value)),this._renderText(t)}renderTextURL(e){const t=e;let s,i,n;try{const e=j.parseURL(t);s="/"===e.file?e.origin:e.file,i="/"===e.file||""===e.hostname?"":`(${e.hostname})`,n=t}catch(e){s=t}const r=this._dom.createElement("div","lh-text__url");if(r.appendChild(this._renderLink({text:s,url:t})),i){const e=this._renderText(i);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 s=this._dom.createElement("a");return s.rel="noopener",s.target="_blank",s.textContent=e.text,s.href=t.href,s.classList.add("lh-link"),s}_renderText(e){const t=this._dom.createElement("div","lh-text");return t.textContent=e,t}_renderNumeric(e){const t=j.i18n.formatNumber(e.value,e.granularity),s=this._dom.createElement("div","lh-numeric");return s.textContent=t,s}_renderThumbnail(e){const t=this._dom.createElement("img","lh-thumbnail"),s=e;return t.src=s,t.title=s,t.alt="",t}_renderUnknown(e,t){console.error("Unknown details type: "+e,t);const s=this._dom.createElement("details","lh-unknown");return this._dom.createChildOf(s,"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(s,"pre").textContent=JSON.stringify(t,null,2),s}_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 s=Number(e);return this._renderBytes({value:s,granularity:t.granularity})}case"code":{const t=String(e);return this._renderCode(t)}case"ms":{const s={value:Number(e),granularity:t.granularity,displayUnit:t.displayUnit};return this._renderMilliseconds(s)}case"numeric":{const s=Number(e);return this._renderNumeric({value:s,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 V.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 s=this._dom.createElement("tr");for(const i of t){if(!i||!i.key){this._dom.createChildOf(s,"td","lh-table-column--empty");continue}const t=e[i.key];let n;if(null!=t&&(n=this._renderTableValue(t,i)),n){const e="lh-table-column--"+i.valueType;this._dom.createChildOf(s,"td",e).appendChild(n)}else this._dom.createChildOf(s,"td","lh-table-column--empty")}return s}_renderTableRowsFromItem(e,t){const s=this._dom.createFragment();if(s.append(this._renderTableRow(e,t)),!e.subItems)return s;const i=t.map(this._getDerivedsubItemsHeading);if(!i.some(Boolean))return s;for(const t of e.subItems.items){const e=this._renderTableRow(t,i);e.classList.add("lh-sub-item-row"),s.append(e)}return s}_renderTable(e){if(!e.items.length)return this._dom.createElement("span");const t=this._dom.createElement("table","lh-table"),s=this._dom.createChildOf(t,"thead"),i=this._dom.createChildOf(s,"tr"),n=this._getCanonicalizedHeadingsFromTable(e);for(const e of n){const t="lh-table-column--"+(e.valueType||"text"),s=this._dom.createElement("div","lh-text");s.textContent=e.label,this._dom.createChildOf(i,"th",t).appendChild(s)}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 s=re.render(this._dom,this._templateContext,e,this);t.appendChild(s)}),t}renderNode(e){const t=this._dom.createElement("span","lh-node");if(e.nodeLabel){const s=this._dom.createElement("div");s.textContent=e.nodeLabel,t.appendChild(s)}if(e.snippet){const s=this._dom.createElement("div");s.classList.add("lh-node__snippet"),s.textContent=e.snippet,t.appendChild(s)}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 s=ae.render(this._dom,this._templateContext,this._fullPageScreenshot,e.boundingRect,{width:147,height:100});return t.prepend(s),t}renderSourceLocation(e){if(!e.url)return null;const t=e.line+1,s=e.column;let i;return"network"===e.urlProvider?(i=this.renderTextURL(e.url),this._dom.find(".lh-link",i).textContent+=`:${t}:${s}`):i=this._renderText(`${e.url}:${t}:${s} (from sourceURL)`),i.classList.add("lh-source-location"),i.setAttribute("data-source-url",e.url),i.setAttribute("data-source-line",String(e.line)),i.setAttribute("data-source-column",String(e.column)),i}_renderFilmstrip(e){const t=this._dom.createElement("div","lh-filmstrip");for(const s of e.items){const e=this._dom.createChildOf(t,"div","lh-filmstrip__frame");this._dom.createChildOf(e,"img","lh-filmstrip__thumbnail",{src:s.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=W:self.DetailsRenderer=W;class q{static initTree(e){let t=0;const s=Object.keys(e);if(s.length>0){t=e[s[0]].request.startTime}return{tree:e,startTime:t,transferSize:0}}static createSegment(e,t,s,i,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:s,transferSize:i+o.request.transferSize,treeMarkers:h}}static createChainNode(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-crc__chains",t);e.find(".crc-node",n).setAttribute("title",s.node.request.url);const r=e.find(".crc-node__tree-marker",n);s.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")))}),s.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"))),s.hasChildren?r.appendChild(e.createElement("span","tree-marker horiz-down")):r.appendChild(e.createElement("span","tree-marker right"));const o=s.node.request.url,a=i.renderTextURL(o),l=e.find(".crc-node__tree-value",n);if(l.appendChild(a),!s.hasChildren){const{startTime:t,endTime:i,transferSize:n}=s.node.request,r=e.createElement("span","crc-node__chain-duration");r.textContent=" - "+j.i18n.formatMilliseconds(1e3*(i-t))+", ";const o=e.createElement("span","crc-node__chain-duration");o.textContent=j.i18n.formatBytesToKiB(n,.01),l.appendChild(r),l.appendChild(o)}return n}static buildTree(e,t,s,i,n,r){if(i.appendChild(z.createChainNode(e,t,s,r)),s.node.children)for(const o of Object.keys(s.node.children)){const a=z.createSegment(s.node.children,o,s.startTime,s.transferSize,s.treeMarkers,s.isLastChild);z.buildTree(e,t,a,i,n,r)}}static render(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-crc",t),r=e.find(".lh-crc",n);e.find(".crc-initial-nav",n).textContent=j.i18n.strings.crcInitialNavigation,e.find(".lh-crc__longest_duration_label",n).textContent=j.i18n.strings.crcLongestDurationLabel,e.find(".lh-crc__longest_duration",n).textContent=j.i18n.formatMilliseconds(s.longestChain.duration);const o=z.initTree(s.chains);for(const t of Object.keys(o.tree)){const a=z.createSegment(o.tree,t,o.startTime,o.transferSize);z.buildTree(e,n,a,r,s,i)}return e.find(".lh-crc-container",n)}}const z=q;"undefined"!=typeof module&&module.exports?module.exports=q:self.CriticalRequestChainRenderer=q;const J=0,K=1,Q=2,Y=0,Z=1,X=2,ee=3,te={[Y]:["lh-snippet__line--content"],[Z]:["lh-snippet__line--content","lh-snippet__line--content-highlighted"],[X]:["lh-snippet__line--placeholder"],[ee]:["lh-snippet__line--message"]};function se(e,t){return{line:e.find(e=>e.lineNumber===t),previousLine:e.find(e=>e.lineNumber===t-1)}}function ie(e,t){return e.filter(e=>e.lineNumber===t)}function ne(e){return j.filterRelevantLines(e.lines,e.lineMessages,2)}class re{static renderHeader(e,t,s,i,n){const r=ne(s).length<s.lines.length,o=e.cloneTemplate("#tmpl-lh-snippet__header",t);e.find(".lh-snippet__title",o).textContent=s.title;const{snippetCollapseButtonLabel:a,snippetExpandButtonLabel:l}=j.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(),s.node&&e.isDevTools()){e.find(".lh-snippet__node",o).appendChild(i.renderNode(s.node))}return o}static renderSnippetLine(e,t,{content:s,lineNumber:i,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;te[r].forEach(e=>d.add(e)),o===K?d.add("lh-snippet__show-if-collapsed"):o===Q&&d.add("lh-snippet__show-if-expanded");const h=s+(n?"…":""),c=e.find(".lh-snippet__line code",l);return r===ee?c.appendChild(e.convertMarkdownLinkSnippets(h)):c.textContent=h,e.find(".lh-snippet__line-number",l).textContent=i.toString(),l}static renderMessage(e,t,s){return re.renderSnippetLine(e,t,{lineNumber:" ",content:s.message,contentType:ee})}static renderOmittedLinesPlaceholder(e,t,s){return re.renderSnippetLine(e,t,{lineNumber:"…",content:"",visibility:s,contentType:X})}static renderSnippetContent(e,t,s){const i=e.cloneTemplate("#tmpl-lh-snippet__content",t),n=e.find(".lh-snippet__snippet-inner",i);return s.generalMessages.forEach(s=>n.append(re.renderMessage(e,t,s))),n.append(re.renderSnippetLines(e,t,s)),i}static renderSnippetLines(e,t,s){const{lineMessages:i,generalMessages:n,lineCount:r,lines:o}=s,a=ne(s),l=n.length>0&&0===i.length,d=e.createFragment();let h=!1;for(let s=1;s<=r;s++){const{line:n,previousLine:r}=se(o,s),{line:c,previousLine:u}=se(a,s),p=!!c;!!u&&!p&&(h=!0),p&&h&&(d.append(re.renderOmittedLinesPlaceholder(e,t,K)),h=!1);const m=!n&&1===s;if(!n&&!!r||m){const i=!a.some(e=>e.lineNumber>s)||1===s;d.append(re.renderOmittedLinesPlaceholder(e,t,i?Q:J)),h=!1}if(!n)continue;const g=ie(i,s),_=g.length>0||l,f=Object.assign({},n,{contentType:_?Z:Y,visibility:c?J:Q});d.append(re.renderSnippetLine(e,t,f)),g.forEach(s=>{d.append(re.renderMessage(e,t,s))})}return d}static render(e,t,s,i){const n=e.cloneTemplate("#tmpl-lh-snippet",t),r=e.find(".lh-snippet",n),o=re.renderHeader(e,n,s,i,()=>r.classList.toggle("lh-snippet--expanded")),a=re.renderSnippetContent(e,n,s);return r.append(o,a),r}}function oe(e,t,s){return e<t?t:e>s?s:e}"undefined"!=typeof module&&module.exports?module.exports=re:self.SnippetRenderer=re;class ae{static getScreenshotPositions(e,t,s){const i={x:(n=e).left+n.width/2,y:n.top+n.height/2};var n;const r=oe(i.x-t.width/2,0,s.width-t.width),o=oe(i.y-t.height/2,0,s.height-t.height);return{screenshot:{left:r,top:o},clip:{left:e.left-r,top:e.top-o}}}static renderClipPathInScreenshot(e,t,s,i,n){const r=e.find("clipPath",t),o="clip-"+j.getUniqueSuffix();r.id=o,t.style.clipPath=`url(#${o})`;const a=s.top/n.height,l=a+i.height/n.height,d=s.left/n.width,h=d+i.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 s=e.createElement("style");return s.id="full-page-screenshot-style",s.textContent=`\n      .lh-element-screenshot__image {\n        background-image: url(${t.data})\n      }`,s}static installOverlayFeature(e,t,s){const i=e.find(".lh-report",e.document());if(i.classList.contains("lh-feature-screenshot-overlay"))return;i.classList.add("lh-feature-screenshot-overlay");const n={width:e.document().documentElement.clientWidth,height:.75*e.document().documentElement.clientHeight};e.document().addEventListener("click",r=>{const o=r.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(ae.render(e,t,s,d,n)),l.addEventListener("click",()=>{l.remove()}),i.appendChild(l)})}static _computeZoomFactor(e,t){const s={x:t.width/e.width,y:t.height/e.height},i=.75*Math.min(s.x,s.y);return Math.min(1,i)}static render(e,t,s,i,n){const r=e.cloneTemplate("#tmpl-lh-element-screenshot",t),o=e.find(".lh-element-screenshot",r);o.dataset.rectWidth=i.width.toString(),o.dataset.rectHeight=i.height.toString(),o.dataset.rectLeft=i.left.toString(),o.dataset.rectTop=i.top.toString();const a=this._computeZoomFactor(i,n),l={width:n.width/a,height:n.height/a};l.width=Math.min(s.width,l.width);const d=l.width*a,h=l.height*a,c=ae.getScreenshotPositions(i,l,{width:s.width,height:s.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=`${s.width*a}px ${s.height*a}px`;const p=e.find(".lh-element-screenshot__element-marker",o);p.style.width=i.width*a+"px",p.style.height=i.height*a+"px",p.style.left=c.clip.left*a+"px",p.style.top=c.clip.top*a+"px";const m=e.find(".lh-element-screenshot__mask",o);return m.style.width=d+"px",m.style.height=h+"px",ae.renderClipPathInScreenshot(e,m,c.clip,i,l),o}}function le(e){const t=new URL(e.finalUrl).hostname,s=e.fetchTime&&new Date(e.fetchTime)||new Date,i=s.toLocaleTimeString("en-US",{hour12:!1}),n=s.toLocaleDateString("en-US",{year:"numeric",month:"2-digit",day:"2-digit"}).split("/");n.unshift(n.pop());return`${t}_${n.join("-")}_${i}`.replace(/[/?<>\\:*|"]/g,"-")}"undefined"!=typeof module&&module.exports?module.exports=ae:self.ElementScreenshotRenderer=ae,"undefined"!=typeof module&&module.exports&&(module.exports={getFilenamePrefix:le});class de{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=de);class he{constructor(e){this.json,this._dom=e,this._document=this._dom.document(),this._templateContext=this._dom.document(),this._dropDown=new ce(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 s=e.categories[t];return s&&1===s.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=j.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,s){const i=new CustomEvent(e,s?{detail:s}:void 0);t.dispatchEvent(i)}_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 s=t.closest(".lh-audit");if(!s)throw new Error(".lh-table not within audit");return!e.includes(s.id)}).forEach((e,s)=>{const i=function(e){return Array.from(e.tBodies[0].rows)}(e),n=this._getThirdPartyRows(i,this.json.finalUrl),r=this._dom.cloneTemplate("#tmpl-lh-3p-filter",this._templateContext),o=this._dom.find("input",r),a="lh-3p-filter-label--"+s;o.id=a,o.addEventListener("change",e=>{const t=e.target instanceof HTMLInputElement&&!e.target.checked;let s=!0,r=i[0];for(;r;){const e=t&&n.includes(r);do{r.classList.toggle("lh-row--hidden",e),r.classList.toggle("lh-row--even",!e&&s),r.classList.toggle("lh-row--odd",!e&&!s),r=r.nextElementSibling}while(r&&r.classList.contains("lh-sub-item-row"));e||(s=!s)}}),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=j.i18n.strings.thirdPartyResourcesLabel;const l=n.length===i.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&&ae.installOverlayFeature(this._dom,this._templateContext,e)}_getThirdPartyRows(e,t){const s=[],i=j.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;j.getRootDomain(n)!==i&&s.push(t)}return s}_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/";he.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 s="https://googlechrome.github.io",i=e;window.addEventListener("message",(function e(t){t.origin===s&&a&&t.data.opened&&(a.postMessage({lhresults:i},s),window.removeEventListener("message",e))}));const n=i.generatedTime,r=i.fetchTime||n,o=`${i.lighthouseVersion}-${i.requestedUrl}-${r}`,a=window.open(`${s}${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=le({finalUrl:this.json.finalUrl,fetchTime:this.json.fetchTime}),s=e.type.match("json")?".json":".html",i=URL.createObjectURL(e),n=this._dom.createElement("a");n.download=`${t}${s}`,n.href=i,this._document.body.appendChild(n),n.click(),this._document.body.removeChild(n),setTimeout(e=>URL.revokeObjectURL(i),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),s=t.length>0?t.length-1:0,i=this.stickyHeaderEl.querySelectorAll(".lh-gauge__wrapper"),n=i[s],r=i[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 ce{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 s=e.filter(e=>e instanceof HTMLElement&&(!e.hasAttribute("disabled")&&"none"!==window.getComputedStyle(e).display));let i=t?s.indexOf(t)+1:0;return i>=s.length&&(i=0),s[i]}_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=he:self.ReportUIFeatures=he;class ue{constructor(e,t){this.dom=e,this.detailsRenderer=t,this.templateContext=this.dom.document(),this.detailsRenderer.setTemplateContext(this.templateContext)}get _clumpTitles(){return{warning:j.i18n.strings.warningAuditsGroupTitle,manual:j.i18n.strings.manualAuditsGroupTitle,passed:j.i18n.strings.passedAuditsGroupTitle,notApplicable:j.i18n.strings.notApplicableAuditsGroupTitle}}renderAudit(e){const t=this.dom.cloneTemplate("#tmpl-lh-audit",this.templateContext);return this.populateAuditValues(e,t)}populateAuditValues(e,t){const s=j.i18n.strings,i=this.dom.find(".lh-audit",t);i.id=e.result.id;const n=e.result.scoreDisplayMode;e.result.displayValue&&(this.dom.find(".lh-audit__display-text",i).textContent=e.result.displayValue);const r=this.dom.find(".lh-audit__title",i);r.appendChild(this.dom.convertMarkdownCodeSnippets(e.result.title)),this.dom.find(".lh-audit__description",i).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 s=this.dom.createElement("img");s.classList.add("lh-audit__stackpack__img"),s.src=e.iconDataURL,s.alt=e.title,t.appendChild(s),t.appendChild(this.dom.convertMarkdownLinkSnippets(e.description)),this.dom.find(".lh-audit__stackpacks",i).appendChild(t)});const o=this.dom.find("details",i);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",i).appendChild(this._createChevron()),this._setRatingClass(i,e.result.score,n),"error"===e.result.scoreDisplayMode){i.classList.add("lh-audit--error");const t=this.dom.find(".lh-audit__display-text",i);t.textContent=s.errorLabel,t.classList.add("tooltip-boundary");this.dom.createChildOf(t,"div","tooltip tooltip--error").textContent=e.result.errorMessage||s.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 i;const l=this.dom.find("summary",o),d=this.dom.createChildOf(l,"div","lh-warnings");if(this.dom.createChildOf(d,"span").textContent=s.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 i}_createChevron(){const e=this.dom.cloneTemplate("#tmpl-lh-chevron",this.templateContext);return this.dom.find(".lh-chevron",e)}_setRatingClass(e,t,s){const i=j.calculateRating(t,s);return e.classList.add("lh-audit--"+s.toLowerCase()),"informative"!==s&&e.classList.add("lh-audit--"+i),e}renderCategoryHeader(e,t){const s=this.dom.cloneTemplate("#tmpl-lh-category-header",this.templateContext),i=this.dom.find(".lh-score__gauge",s),n=this.renderScoreGauge(e,t);if(i.appendChild(n),e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);this.dom.find(".lh-category-header__description",s).appendChild(t)}return s.firstElementChild}renderAuditGroup(e){const t=this.dom.createElement("div","lh-audit-group"),s=this.dom.createElement("div","lh-audit-group__header");if(this.dom.createChildOf(s,"span","lh-audit-group__title").textContent=e.title,e.description){const t=this.dom.convertMarkdownLinkSnippets(e.description);t.classList.add("lh-audit-group__description"),s.appendChild(t)}return t.appendChild(s),t}_renderGroupedAudits(e,t){const s=new Map;s.set("NotAGroup",[]);for(const t of e){const e=t.group||"NotAGroup",i=s.get(e)||[];i.push(t),s.set(e,i)}const i=[];for(const[e,n]of s){if("NotAGroup"===e){for(const e of n)i.push(this.renderAudit(e));continue}const s=t[e],r=this.renderAuditGroup(s);for(const e of n)r.appendChild(this.renderAudit(e));r.classList.add("lh-audit-group--"+e),i.push(r)}return i}renderUnexpandableClump(e,t){const s=this.dom.createElement("div");return this._renderGroupedAudits(e,t).forEach(e=>s.appendChild(e)),s}renderClump(e,{auditRefs:t,description:s}){const i=this.dom.cloneTemplate("#tmpl-lh-clump",this.templateContext),n=this.dom.find(".lh-clump",i);"warning"===e&&n.setAttribute("open","");this.dom.find(".lh-audit-group__summary",n).appendChild(this._createChevron()).title=j.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,s){const e=this.dom.convertMarkdownLinkSnippets(s);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 s=this.dom.cloneTemplate("#tmpl-lh-gauge",this.templateContext),i=this.dom.find(".lh-gauge__wrapper",s);i.href="#"+e.id,j.isPluginCategory(e.id)&&i.classList.add("lh-gauge__wrapper--plugin");const n=Number(e.score),r=this.dom.find(".lh-gauge",s).querySelector(".lh-gauge-arc");r&&this._setGaugeArc(r,n);const o=Math.round(100*n),a=this.dom.find(".lh-gauge__percentage",s);return a.textContent=o.toString(),null===e.score&&(a.textContent="?",a.title=j.i18n.strings.errorLabel),0===e.auditRefs.length||this.hasApplicableAudits(e)?i.classList.add("lh-gauge__wrapper--"+j.calculateRating(e.score)):(i.classList.add("lh-gauge__wrapper--not-applicable"),a.textContent="-",a.title=j.i18n.strings.notApplicableAuditsGroupTitle),this.dom.find(".lh-gauge__label",s).textContent=e.title,s}hasApplicableAudits(e){return e.auditRefs.some(e=>"notApplicable"!==e.result.scoreDisplayMode)}_setGaugeArc(e,t){const s=2*Math.PI*Number(e.getAttribute("r")),i=Number(e.getAttribute("stroke-width")),n=.25*i/s;e.style.transform=`rotate(${360*n-90}deg)`;let r=t*s-i/2;0===t&&(e.style.opacity="0"),1===t&&(r=s),e.style.strokeDasharray=`${Math.max(r,0)} ${s}`}_auditHasWarning(e){return Boolean(e.result.warnings&&e.result.warnings.length)}_getClumpIdForAuditRef(e){const t=e.result.scoreDisplayMode;return"manual"===t||"notApplicable"===t?t:j.showAsPassed(e.result)?this._auditHasWarning(e)?"warning":"passed":"failed"}render(e,t={}){const s=this.dom.createElement("div","lh-category");this.createPermalinkSpan(s,e.id),s.appendChild(this.renderCategoryHeader(e,t));const i=new Map;i.set("failed",[]),i.set("warning",[]),i.set("manual",[]),i.set("passed",[]),i.set("notApplicable",[]);for(const t of e.auditRefs){const e=this._getClumpIdForAuditRef(t),s=i.get(e);s.push(t),i.set(e,s)}for(const[n,r]of i){if(0===r.length)continue;if("failed"===n){const e=this.renderUnexpandableClump(r,t);e.classList.add("lh-clump--failed"),s.appendChild(e);continue}const i="manual"===n?e.manualDescription:void 0,o=this.renderClump(n,{auditRefs:r,description:i});s.appendChild(o)}return s}createPermalinkSpan(e,t){this.dom.createChildOf(e,"span","lh-permalink").id=t}}"undefined"!=typeof module&&module.exports?module.exports=ue:self.CategoryRenderer=ue;class pe extends ue{_renderMetric(e){const t=this.dom.cloneTemplate("#tmpl-lh-metric",this.templateContext),s=this.dom.find(".lh-metric",t);s.id=e.result.id;const i=j.calculateRating(e.result.score,e.result.scoreDisplayMode);s.classList.add("lh-metric--"+i);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 s}_renderOpportunity(e,t){const s=this.dom.cloneTemplate("#tmpl-lh-opportunity",this.templateContext),i=this.populateAuditValues(e,s);if(i.id=e.result.id,!e.result.details||"error"===e.result.scoreDisplayMode)return i;const n=e.result.details;if("opportunity"!==n.type)return i;const r=this.dom.find(".lh-audit__display-text",i),o=n.overallSavingsMs/t*100+"%";if(this.dom.find(".lh-sparkline__bar",i).style.width=o,r.textContent=j.i18n.formatSeconds(n.overallSavingsMs,.01),e.result.displayValue){const t=e.result.displayValue;this.dom.find(".lh-load-opportunity__sparkline",i).title=t,r.title=t}return i}_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),s=e.find(e=>"first-cpu-idle"===e.id),i=e.find(e=>"first-meaningful-paint"===e.id);s&&t.push(s),i&&t.push(i);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 s;return"number"==typeof e.result.numericValue?(t="cumulative-layout-shift"===e.id?(s=e.result.numericValue,Math.round(100*s)/100):Math.round(e.result.numericValue),t=t.toString()):t="null",[n[e.id]||e.id,t]})];j.reportJson&&(r.push(["device",j.reportJson.configSettings.emulatedFormFactor]),r.push(["version",j.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,s){const i=j.i18n.strings,n=this.dom.createElement("div","lh-category");if("PSI"===s){const s=this.dom.createElement("div","lh-score__gauge");s.appendChild(this.renderScoreGauge(e,t)),n.appendChild(s)}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(i.varianceDisclaimer);h.appendChild(c);const u=this.dom.createChildOf(h,"a","lh-calclink");u.target="_blank",u.textContent=i.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"),m=e.auditRefs.find(e=>"screenshot-thumbnails"===e.id),g=m&&m.result;if(g&&g.details){p.id=g.id;const e=this.detailsRenderer.render(g.details);e&&p.appendChild(e)}const _=[];if(["performance-budget","timing-budget"].forEach(t=>{const s=e.auditRefs.find(e=>e.id===t);if(s&&s.result.details){const e=this.detailsRenderer.render(s.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&&!j.showAsPassed(e.result)).sort((e,t)=>this._getWastedMs(t)-this._getWastedMs(e));if(f.length){const e=2e3,s=f.map(e=>this._getWastedMs(e)),r=Math.max(...s),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=i.opportunityResourceColumnLabel,this.dom.find(".lh-load-opportunity__col--two",l).textContent=i.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&&!j.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 v=e.auditRefs.filter(e=>("load-opportunities"===e.group||"diagnostics"===e.group)&&j.showAsPassed(e.result));if(!v.length)return n;const y={auditRefs:v,groupDefinitions:t},w=this.renderClump("passed",y);return n.appendChild(w),n}}"undefined"!=typeof module&&module.exports?module.exports=pe:self.PerformanceCategoryRenderer=pe;class me extends ue{render(e,t={}){const s=this.dom.createElement("div","lh-category");this.createPermalinkSpan(s,e.id),s.appendChild(this.renderCategoryHeader(e,t));const i=e.auditRefs,n=i.filter(e=>"manual"!==e.result.scoreDisplayMode),r=this._renderAudits(n,t);s.appendChild(r);const o=i.filter(e=>"manual"===e.result.scoreDisplayMode),a=this.renderClump("manual",{auditRefs:o,description:e.manualDescription});return s.appendChild(a),s}renderScoreGauge(e,t){if(null===e.score)return super.renderScoreGauge(e,t);const s=this.dom.cloneTemplate("#tmpl-lh-gauge--pwa",this.templateContext),i=this.dom.find(".lh-gauge--pwa__wrapper",s);i.href="#"+e.id;const n=s.querySelector("svg");if(!n)throw new Error("no SVG element found in PWA score gauge template");me._makeSvgReferencesUnique(n);const r=this._getGroupIds(e.auditRefs),o=this._getPassingGroupIds(e.auditRefs);if(o.size===r.size)i.classList.add("lh-badged--all");else for(const e of o)i.classList.add("lh-badged--"+e);return this.dom.find(".lh-gauge__label",s).textContent=e.title,i.title=this._getGaugeTooltip(e.auditRefs,t),s}_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 s of e)!j.showAsPassed(s.result)&&s.group&&t.delete(s.group);return t}_getGaugeTooltip(e,t){const s=this._getGroupIds(e),i=[];for(const n of s){const s=e.filter(e=>e.group===n),r=s.length,o=s.filter(e=>j.showAsPassed(e.result)).length,a=t[n].title;i.push(`${a}: ${o}/${r}`)}return i.join(", ")}_renderAudits(e,t){const s=this.renderUnexpandableClump(e,t),i=this._getPassingGroupIds(e);for(const e of i){this.dom.find(".lh-audit-group--"+e,s).classList.add("lh-badged")}return s}static _makeSvgReferencesUnique(e){const t=e.querySelector("defs");if(!t)return;const s=j.getUniqueSuffix(),i=t.querySelectorAll("[id]");for(const t of i){const i=t.id,n=`${i}-${s}`;t.id=n;const r=e.querySelectorAll(`use[href="#${i}"]`);for(const e of r)e.setAttribute("href","#"+n);const o=e.querySelectorAll(`[fill="url(#${i})"]`);for(const e of o)e.setAttribute("fill",`url(#${n})`)}}}"undefined"!=typeof module&&module.exports?module.exports=me:self.PwaCategoryRenderer=me;class ge{constructor(e){this._dom=e,this._templateContext=this._dom.document()}renderReport(e,t){this._dom.setLighthouseChannel(e.configSettings.channel||"unknown");const s=j.prepareReportResult(e);return t.textContent="",t.appendChild(this._renderReport(s)),t}setTemplateContext(e){this._templateContext=e}_renderReportTopbar(e){const t=this._dom.cloneTemplate("#tmpl-lh-topbar",this._templateContext),s=this._dom.find(".lh-topbar__url",t);return s.href=s.textContent=e.finalUrl,s.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),s=this._dom.find(".lh-scores-wrapper-placeholder",e);return s.parentNode.replaceChild(t,s),e}_renderReportFooter(e){const t=this._dom.cloneTemplate("#tmpl-lh-footer",this._templateContext),s=this._dom.find(".lh-env__items",t);s.id="runtime-settings",this._dom.find(".lh-env__title",t).textContent=j.i18n.strings.runtimeSettingsTitle;const i=j.getEnvironmentDisplayValues(e.configSettings||{}),n=[{name:j.i18n.strings.runtimeSettingsUrl,description:e.finalUrl},{name:j.i18n.strings.runtimeSettingsFetchTime,description:j.i18n.formatDateTime(e.fetchTime)},...i,{name:j.i18n.strings.runtimeSettingsChannel,description:e.configSettings.channel},{name:j.i18n.strings.runtimeSettingsUA,description:e.userAgent},{name:j.i18n.strings.runtimeSettingsUANetwork,description:e.environment&&e.environment.networkUserAgent},{name:j.i18n.strings.runtimeSettingsBenchmark,description:e.environment&&e.environment.benchmarkIndex.toFixed(0)}];e.environment.credits&&e.environment.credits["axe-core"]&&n.push({name:j.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",s);this._dom.find(".lh-env__name",t).textContent=e.name,this._dom.find(".lh-env__description",t).textContent=e.description,s.appendChild(t)}return this._dom.find(".lh-footer__version_issue",t).textContent=j.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=j.i18n.strings.toplevelWarningsMessage;const s=this._dom.find("ul",t);for(const t of e.runWarnings){s.appendChild(this._dom.createElement("li")).textContent=t}return t}_renderScoreGauges(e,t,s){const i=[],n=[],r=[];for(const o of Object.values(e.categories)){const a=s[o.id]||t,l=a.renderScoreGauge(o,e.categoryGroups||{});j.isPluginCategory(o.id)?r.push(l):a.renderScoreGauge===t.renderScoreGauge?i.push(l):n.push(l)}return[...i,...n,...r]}_renderReport(e){const t=new _e(e.configSettings.locale,{...j.UIStrings,...e.i18n.rendererFormattedStrings});j.i18n=t,j.reportJson=e;const s=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,i=new W(this._dom,{fullPageScreenshot:s}),n=s&&ae.createBackgroundImageStyle(this._dom,s),r=new ue(this._dom,i);r.setTemplateContext(this._templateContext);const o={performance:new pe(this._dom,i),pwa:new me(this._dom,i)};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),s=this._dom.find(".lh-scores-container",a);h.append(...this._renderScoreGauges(e,r,o)),s.appendChild(h),s.appendChild(t);const i=this._dom.createElement("div","lh-sticky-header");i.append(...this._renderScoreGauges(e,r,o)),l.appendChild(i)}const c=d.appendChild(this._dom.createElement("div","lh-categories"));for(const t of Object.values(e.categories)){const s=o[t.id]||r;s.dom.createChildOf(c,"div","lh-category-wrapper").appendChild(s.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=ge:self.ReportRenderer=ge;class _e{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 s=Math.round(e/t)*t;return this._numberFormatter.format(s)}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 s=Math.round(e/t)*t;return 0===s?this._numberFormatter.format(0)+" ms":this._numberFormatter.format(s)+" ms"}formatSeconds(e,t=.1){const s=Math.round(e/1e3/t)*t;return this._numberFormatter.format(s)+" s"}formatDateTime(e){const t={month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"numeric",timeZoneName:"short"};let s;try{s=new Intl.DateTimeFormat(this._numberDateLocale,t)}catch(e){t.timeZone="UTC",s=new Intl.DateTimeFormat(this._numberDateLocale,t)}return s.format(new Date(e))}formatDuration(e){let t=e/1e3;if(0===Math.round(t))return"None";const s=[],i={d:86400,h:3600,m:60,s:1};return Object.keys(i).forEach(e=>{const n=i[e],r=Math.floor(t/n);r>0&&(t-=r*n,s.push(`${r} ${e}`))}),s.join(" ")}}"undefined"!=typeof module&&module.exports?module.exports=_e:self.I18n=_e,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,s,i){function n(o,a){if(!s[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=s[o]={exports:{}};t[o][0].call(h.exports,(function(e){return n(t[o][1][e]||e)}),h,h.exports,e,t,s,i)}return s[o].exports}for(var r="function"==typeof require&&require,o=0;o<i.length;o++)n(i[o]);return n}({"./html/html-report-assets.js":[function(e,t,s){const i=globalThis.EXPORTED_CACHED_RESOURCES_ONLY_FOR_LIGHTHOUSE;t.exports={get REPORT_CSS(){return i.get("third_party/lighthouse/report-assets/report.css")},get REPORT_JAVASCRIPT(){return i.get("third_party/lighthouse/report-assets/report.js")},get REPORT_TEMPLATE(){return i.get("third_party/lighthouse/report-assets/template.html")},get REPORT_TEMPLATES(){return i.get("third_party/lighthouse/report-assets/templates.html")}}},{}],1:[function(e,t,s){const i=e("./html/html-report-assets.js");class n{static replaceStrings(e,t){if(0===t.length)return e;const s=t[0],i=t.slice(1);return e.split(s.search).map(e=>n.replaceStrings(e,i)).join(s.replacement)}static generateReportHtml(e){const t=JSON.stringify(e).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),s=i.REPORT_JAVASCRIPT.replace(/<\//g,"\\u003c/");return n.replaceStrings(i.REPORT_TEMPLATE,[{search:"%%LIGHTHOUSE_JSON%%",replacement:t},{search:"%%LIGHTHOUSE_JAVASCRIPT%%",replacement:s},{search:"/*%%LIGHTHOUSE_CSS%%*/",replacement:i.REPORT_CSS},{search:"%%LIGHTHOUSE_TEMPLATES%%",replacement:i.REPORT_TEMPLATES}])}static generateReportCSV(e){const t=e=>`"${e.replace(/"/g,'""')}"`,s=e=>e.map(e=>e.toString()).map(t),i=Object.keys(e.categories).map(t=>{const i=[],n=e.categories[t],r=null===n.score?-1:n.score;return i.push(s([e.requestedUrl,e.finalUrl,n.title,t+"-score",`Overall ${n.title} Category Score`,"numeric",r])),i.concat(n.auditRefs.map(t=>{const i=e.audits[t.id],r=null===i.score?-1:i.score;return s([e.requestedUrl,e.finalUrl,n.title,i.id,i.title,i.scoreDisplayMode,r])}))});return[["requestedUrl","finalUrl","category","name","title","type","score"]].concat(...i).map(e=>e.join(",")).join("\r\n")}static generateReport(e,t){const s=Array.isArray(t);"string"==typeof t&&(t=[t]);const i=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 s?i:i[0]}}t.exports=n},{"./html/html-report-assets.js":"./html/html-report-assets.js"}]},{},[1])(1)}));class fe extends e.ObjectWrapper{constructor(e){super(),e.registerStatusCallback(e=>this.dispatchEventToListeners(we.AuditProgressChanged,{message:e}));for(const e of ve)e.setting.addChangeListener(this.recomputePageAuditability.bind(this));for(const e of ye)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=s.ParsedURL.fromString(e.inspectedURL()),i=t&&t.securityOrigin();for(const e of this._manager.registrations().values())if(e.securityOrigin===i)for(const t of e.versions.values())if(t.controlledClients.length>1)return!0;return!1}_hasAtLeastOneCategory(){return ve.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)?i.UIString("Can only audit HTTP/HTTPS pages and Chrome extensions. Navigate to a different page to start an audit."):null}async _hasImportantResourcesNotCleared(){const e=ye.find(e=>"lighthouse.clear_storage"===e.setting.name);if(e&&!e.setting.get())return"";if(!this._manager)return"";const t=this._manager.target(),s=(await t.storageAgent().invoke_getUsageAndQuota({origin:t.inspectedURL()})).usageBreakdown.filter(e=>e.usage).map(e=>be.get(e.storageType)).filter(Boolean);return 1===s.length?i.UIString("There may be stored data affecting loading performance in this location: %s. Audit this page in an incognito window to prevent those resources from affecting your scores.",s.join(", ")):s.length>1?i.UIString("There may be stored data affecting loading performance in these locations: %s. Audit this page in an incognito window to prevent those resources from affecting your scores.",s.join(", ")):""}async _evaluateInspectedURL(){if(!this._manager)return"";const e=this._manager.target(),t=e.model(l.RuntimeModel),s=t&&t.defaultExecutionContext();let i=e.inspectedURL();if(!s)return i;try{const e=await s.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||(i=e.object.value,e.object.release())}catch(e){console.error(e)}return i}getFlags(){const e={internalDisableDeviceScreenEmulation:!0};for(const t of ye)t.setFlags(e,t.setting.get());return e}getCategoryIDs(){const e=[];for(const t of ve)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(),s=this._unauditablePageMessage();let n="";e?n=i.UIString("Multiple tabs are being controlled by the same service worker. Close your other tabs on the same origin to audit this page."):t?s&&(n=s):n=i.UIString("At least one category must be selected."),this.dispatchEventToListeners(we.PageAuditabilityChanged,{helpText:n}),this._hasImportantResourcesNotCleared().then(e=>{this.dispatchEventToListeners(we.PageWarningsChanged,{warning:e})})}}const be=new Map([[Protocol.Storage.StorageType.Local_storage,i.UIString("Local Storage")],[Protocol.Storage.StorageType.Indexeddb,i.UIString("IndexedDB")],[Protocol.Storage.StorageType.Websql,i.UIString("Web SQL")]]),ve=[{setting:n.Settings.instance().createSetting("lighthouse.cat_perf",!0),configID:"performance",title:ls`Performance`,description:ls`How long does this app take to show content and become usable`,plugin:!1},{setting:n.Settings.instance().createSetting("lighthouse.cat_pwa",!0),configID:"pwa",title:ls`Progressive Web App`,description:ls`Does this page meet the standard of a Progressive Web App`,plugin:!1},{setting:n.Settings.instance().createSetting("lighthouse.cat_best_practices",!0),configID:"best-practices",title:ls`Best practices`,description:ls`Does this page follow best practices for modern web development`,plugin:!1},{setting:n.Settings.instance().createSetting("lighthouse.cat_a11y",!0),configID:"accessibility",title:ls`Accessibility`,description:ls`Is this page usable by people with disabilities or impairments`,plugin:!1},{setting:n.Settings.instance().createSetting("lighthouse.cat_seo",!0),configID:"seo",title:ls`SEO`,description:ls`Is this page optimized for search engine results ranking`,plugin:!1},{setting:n.Settings.instance().createSetting("lighthouse.cat_pubads",!1),plugin:!0,configID:"lighthouse-plugin-publisher-ads",title:ls`Publisher Ads`,description:ls`Is this page optimized for ad speed and quality`}],ye=[{setting:n.Settings.instance().createSetting("lighthouse.device_type","mobile"),title:ls`Apply mobile emulation`,description:ls`Apply mobile emulation during auditing`,setFlags:(e,t)=>{e.emulatedFormFactor=t},options:[{label:ls`Mobile`,value:"mobile"},{label:ls`Desktop`,value:"desktop"}],learnMore:void 0},{setting:n.Settings.instance().createSetting("lighthouse.throttling",!0),title:ls`Simulated throttling`,learnMore:"https://github.com/GoogleChrome/lighthouse/blob/master/docs/throttling.md#devtools-lighthouse-panel-throttling",description:ls`Simulate a slower page load, based on data from an initial unthrottled load. If disabled, the page is actually slowed with applied throttling.`,setFlags:(e,t)=>{e.throttlingMethod=t?"simulate":"devtools"},options:void 0},{setting:n.Settings.instance().createSetting("lighthouse.clear_storage",!0),title:ls`Clear storage`,description:ls`Reset storage (localStorage, IndexedDB, etc) before auditing. (Good for performance & PWA testing)`,setFlags:(e,t)=>{e.disableStorageReset=!t},options:void 0,learnMore:void 0}],we={PageAuditabilityChanged:Symbol("PageAuditabilityChanged"),PageWarningsChanged:Symbol("PageWarningsChanged"),AuditProgressChanged:Symbol("AuditProgressChanged"),RequestLighthouseStart:Symbol("RequestLighthouseStart"),RequestLighthouseCancel:Symbol("RequestLighthouseCancel")};var Ce=Object.freeze({__proto__:null,LighthouseController:fe,Presets:ve,RuntimeSettings:ye,Events:we,Preset:void 0,RuntimeSetting:void 0});class Se 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().model(d.ChildTargetManager);this._rawConnection=await e.createParallelConnection(this._dispatchProtocolMessage.bind(this))}getLocales(){return navigator.languages}startLighthouse(e,t,s){const i=this.getLocales();return this._send("start",{url:e,categoryIDs:t,flags:s,locales:i})}async detach(){await this._send("stop"),await this._backend.dispose(),delete this._backend,delete this._backendPromise,await this._rawConnection.disconnect(),await o.TargetManager.instance().resumeAllTargets()}registerStatusCallback(e){this._status=e}_dispatchProtocolMessage(e){this._send("dispatchProtocolMessage",{message:JSON.stringify(e)})}_initWorker(){this._backendPromise=Services.serviceManager.createAppService("lighthouse_worker","LighthouseService").then(e=>{this._backend||(this._backend=e,this._backend.on("statusUpdate",e=>this._status(e.message)),this._backend.on("sendProtocolMessage",e=>this._sendProtocolMessage(e.message)))})}_sendProtocolMessage(e){this._rawConnection.sendRawMessage(e)}_send(e,t){return this._backendPromise||this._initWorker(),this._backendPromise.then(s=>this._backend.send(e,t))}}var Te=Object.freeze({__proto__:null,ProtocolService:Se});class xe extends self.ReportRenderer{static addViewTraceButton(e,t){if(!t||!t.traces||!t.traces.defaultPass)return;const s="simulate"===t.settings.throttlingMethod,n=e.querySelector(".lh-audit-group"),r=n.querySelector(".lh-metrics__disclaimer");if(!r)return;const o=t.traces.defaultPass,a=s?i.UIString("View Original Trace"):i.UIString("View Trace"),l=b.createTextButton(a,(async function(){_.actionTaken(Host.UserMetrics.Action.LighthouseViewTrace),await v.InspectorView.instance().showPanel("timeline"),I.TimelinePanel.instance().loadFromEvents(o.traceEvents)}),"view-trace");s&&(l.title=i.UIString('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.')),n.insertBefore(l,r.nextSibling)}static async linkifyNodeDetails(e){const t=o.TargetManager.instance().mainTarget().model(h.DOMModel);for(const s of e.getElementsByClassName("lh-node")){const e=s.dataset;if(!e.path)continue;const i=await t.pushNodeByPathToFrontend(e.path);if(!i)continue;const n=t.nodeForId(i);if(!n)continue;const o=await r.Linkifier.linkify(n,{tooltip:e.snippet});s.title="",s.textContent="",s.appendChild(o)}}static async linkifySourceLocationDetails(e){for(const t of e.getElementsByClassName("lh-source-location")){const e=t.dataset;if(!e.sourceUrl||!e.sourceLine||!e.sourceColumn)continue;const s=e.sourceUrl,i=Number(e.sourceLine),n=Number(e.sourceColumn),r=await M.Linkifier.linkifyURL(s,{lineNumber:i,column:n,maxLength:40});t.title="",t.textContent="",t.appendChild(r)}}static handleDarkMode(e){"dark"===U.instance().themeName()&&e.classList.add("dark")}}class Ee 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 s.ParsedURL(this.json.finalUrl).domain().replace(/[^a-z0-9.-]+/gi,"_")}-${D.toISO8601Compact(new Date(this.json.fetchTime))}${e.type.match("json")?".json":".html"}`,i=await e.text();N.FileManager.instance().save(t,i,!0)}async _print(){const e=this.getDocument().querySelector(".lh-root").cloneNode(!0),t=window.open("","_blank","channelmode=1,status=1,resizable=1"),s=t.document.createElement("style");s.textContent=f.cachedResources.get("third_party/lighthouse/report-assets/report.css"),t.document.head.appendChild(s),t.document.body.replaceWith(e),await xe.linkifyNodeDetails(e),this._beforePrint&&this._beforePrint(),t.focus(),t.print(),t.close(),this._afterPrint&&this._afterPrint()}getDocument(){return this._document}resetUIState(){this._resetUIState()}}var Le=Object.freeze({__proto__:null,LighthouseReportRenderer:xe,LighthouseReportUIFeatures:Ee});class ke{constructor(e){this._renderNewLighthouseView=e,this._newLighthouseItem=document.createElement("option"),this._comboBox=new y.ToolbarComboBox(this._handleChange.bind(this),ls`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=i.UIString("(new report)"),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(),s=this._comboBox.selectElement();this._itemByOptionElement.set(t,e),s.insertBefore(t,s.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 Ae{constructor(e,t,i){this._lighthouseResult=e,this._renderReport=t,this._showLandingCallback=i;const n=new s.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 Re=Object.freeze({__proto__:null,ReportSelector:ke,Item:Ae});class Pe{constructor(e,t,s){this._setting=t,this._options=e,this.element=document.createElement("div"),w.setDescription(this.element,s),w.markAsRadioGroup(this.element),this._radioElements=[];for(const e of this._options){const i=C.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(i.element()),s&&(S.Tooltip.install(i.$("input"),s),S.Tooltip.install(i.$("span"),s));const n=i.$("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 Me=Object.freeze({__proto__:null,RadioSetting:Pe});class De extends T.Widget{constructor(e){super(),this.registerRequiredCSS("lighthouse/lighthouseStartView.css"),this._controller=e,this._settingsToolbar=new y.Toolbar(""),this._render()}settingsToolbar(){return this._settingsToolbar}_populateRuntimeSettingAsRadio(e,t,s){const i=ye.find(t=>t.setting.name===e);if(!i||!i.options)throw new Error(e+" is not a setting with options");const n=new Pe(i.options,i.setting,i.description);s.appendChild(n.element),w.setAccessibleName(n.element,t)}_populateRuntimeSettingAsToolbarCheckbox(e,t){const s=ye.find(t=>t.setting.name===e);if(!s||!s.title)throw new Error(e+" is not a setting with a title");s.setting.setTitle(s.title);const i=new y.ToolbarSettingCheckbox(s.setting,s.description);if(t.appendToolbarItem(i),s.learnMore){const e=x.XLink.create(s.learnMore,ls`Learn more`,"lighthouse-learn-more");e.style.padding="5px",i.element.appendChild(e)}}_populateFormControls(e){const t=e.$("device-type-form-elements");this._populateRuntimeSettingAsRadio("lighthouse.device_type",ls`Device`,t);const s=e.$("categories-form-elements"),i=e.$("plugins-form-elements");for(const e of ve){const t=e.plugin?i:s;e.setting.setTitle(e.title);const n=new y.ToolbarSettingCheckbox(e.setting,e.description);t.createChild("div","vbox lighthouse-launcher-row").appendChild(n.element)}w.markAsGroup(s),w.setAccessibleName(s,ls`Categories`),w.markAsGroup(i),w.setAccessibleName(i,ls`Community Plugins (beta)`)}_render(){this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.clear_storage",this._settingsToolbar),this._populateRuntimeSettingAsToolbarCheckbox("lighthouse.throttling",this._settingsToolbar),this._startButton=b.createTextButton(ls`Generate report`,()=>this._controller.dispatchEventToListeners(we.RequestLighthouseStart,this._startButton.matches(":focus-visible")),"",!0),this.setDefaultFocusedElement(this._startButton);const e=ls`Identify and fix common problems that affect your site's performance, accessibility, and user experience.`,t=C.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>
            ${x.XLink.create("https://developers.google.com/web/tools/lighthouse/",ls`Learn more`)}
          </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">
                ${ls`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">${ls`Community Plugins (beta)`}</div>
              </div>
              <div class="lighthouse-form-elements" $="plugins-form-elements"></div>
            </div>
          </div>
          <div class="lighthouse-form-section">
            <div class="lighthouse-form-section-label">
              ${ls`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.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 Ue=Object.freeze({__proto__:null,StartView:De});class Ie{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=He.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=L.createShadowRootWithCoreStyles(this._dialog.contentElement,"lighthouse/lighthouseDialog.css").createChild("div","lighthouse-view vbox"),t=b.createTextButton(ls`Cancel`,this._cancel.bind(this)),s=C.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(s.element()),this._statusView=s.$("status-view"),this._statusHeader=s.$("status-header"),this._progressWrapper=s.$("progress-wrapper"),this._progressBar=s.$("progress-bar"),this._statusText=s.$("status-text"),w.markAsProgressBar(this._progressBar,0,Fe.length-1),this._cancelButton=t,w.markAsStatus(this._statusText),this._dialog.setDefaultFocusedElement(t),this._dialog.setSizeBehavior(k.SizeBehavior.SetExactWidthMaxHeight),this._dialog.setMaxContentSize(new A.Size(500,400))}_reset(){this._resetProgressBarClasses(),clearTimeout(this._scheduledFastFactTimeout),this._textChangedAt=0,this._fastFactsQueued=He.slice(),this._currentPhase=null,this._scheduledTextChangeTimeout=null,this._scheduledFastFactTimeout=null}show(e){this._reset(),this.updateStatus(ls`Loading…`);const t=s.ParsedURL.fromString(this._inspectedURL),i=t&&t.host,n=i?ls`Auditing ${i}`:ls`Auditing your web page`;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(i.UIString("Cancelling…")),void clearTimeout(this._scheduledFastFactTimeout);const t=this._getPhaseForMessage(e),s=Fe.indexOf(t),n=Fe.indexOf(this._currentPhase);if(t||this._currentPhase){if(t&&(!this._currentPhase||n<s)){this._currentPhase=t;const e=this._getMessageForPhase(t);this._scheduleTextChange(e),this._scheduleFastFactCheck(),this._resetProgressBarClasses(),this._progressBar&&(this._progressBar.classList.add(t.progressBarClass),w.setProgressBarValue(this._progressBar,s,e))}}else this._commitTextChange(i.UIString("Lighthouse is warming up…")),clearTimeout(this._scheduledFastFactTimeout)}_cancel(){this._controller.dispatchEventToListeners(we.RequestLighthouseCancel)}_getMessageForPhase(e){if(e.message)return e.message;const t=ye.find(e=>"lighthouse.device_type"===e.setting.name),s=ye.find(e=>"lighthouse.throttling"===e.setting.name),i=t?t.setting.get():"",n=s?s.setting.get():"",r=$e.find(e=>e.deviceType===i&&e.throttling===n);return r?r.message:ls`Lighthouse is loading your page`}_getPhaseForMessage(e){return Fe.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<Ne)return;if(!this._fastFactsQueued.length)return;const e=Math.floor(Math.random()*this._fastFactsQueued.length);this._scheduleTextChange(ls`\ud83d\udca1 ${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,s=Oe-t;this._scheduledTextChangeTimeout=setTimeout(()=>{this._commitTextChange(e)},Math.max(s,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(""),b.createTextChild(this._statusText.createChild("p"),i.UIString("Ah, sorry! We ran into an error.")),Be.some(t=>t.test(e.message))){const e=i.UIString("Try to navigate to the URL in a fresh Chrome profile without any other tabs or extensions open and try again.");b.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 s=navigator.userAgent.match(/Chrome\/(\S+)/)||["","Unknown"],i=`\n${e.friendlyMessage||e.message}\n\`\`\`\nChannel: DevTools\nInitial URL: ${t}\nChrome Version: ${s[1]}\nStack Trace: ${e.stack}\n\`\`\`\n`;this._statusText&&(b.createTextChild(this._statusText.createChild("p"),ls`If this issue is reproducible, please report it at the Lighthouse GitHub repo.`),b.createTextChild(this._statusText.createChild("code","monospace"),i.trim()))}}const Ne=6e3,Oe=3e3,Be=[/PARSING_PROBLEM/,/DOCUMENT_REQUEST/,/READ_FAILED/,/TRACING_ALREADY_STARTED/,/^You must provide a url to the runner/,/^You probably have multiple tabs open/],Fe=[{id:"loading",progressBarClass:"loading",message:ls`Lighthouse is loading the page.`,statusMessagePrefix:"Loading page"},{id:"gathering",progressBarClass:"gathering",message:ls`Lighthouse is gathering information about the page to compute your score.`,statusMessagePrefix:"Gathering"},{id:"auditing",progressBarClass:"auditing",message:ls`Almost there! Lighthouse is now generating your report.`,statusMessagePrefix:"Auditing"}],$e=[{deviceType:"mobile",throttling:"on",message:ls`Lighthouse is loading your page with throttling to measure performance on a mobile device on 3G.`},{deviceType:"desktop",throttling:"on",message:ls`Lighthouse is loading your page with throttling to measure performance on a slow desktop on 3G.`},{deviceType:"mobile",throttling:"off",message:ls`Lighthouse is loading your page with mobile emulation.`},{deviceType:"desktop",throttling:"off",message:ls`Lighthouse is loading your page.`}],He=[ls`1MB takes a minimum of 5 seconds to download on a typical 3G connection [Source: WebPageTest and DevTools 3G definition].`,ls`Rebuilding Pinterest pages for performance increased conversion rates by 15% [Source: WPO Stats]`,ls`By reducing the response size of JSON needed for displaying comments, Instagram saw increased impressions [Source: WPO Stats]`,ls`Walmart saw a 1% increase in revenue for every 100ms improvement in page load [Source: WPO Stats]`,ls`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]`,ls`75% of global mobile users in 2016 were on 2G or 3G [Source: GSMA Mobile]`,ls`The average user device costs less than 200 USD. [Source: International Data Corporation]`,ls`19 seconds is the average time a mobile web page takes to load on a 3G connection [Source: Google DoubleClick blog]`,ls`70% of mobile pages take nearly 7 seconds for the visual content above the fold to display on the screen. [Source: Think with Google]`,ls`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]`,ls`As the number of elements on a page increases from 400 to 6,000, the probability of conversion drops 95%. [Source: Think with Google]`,ls`70% of mobile pages weigh over 1MB, 36% over 2MB, and 12% over 4MB. [Source: Think with Google]`,ls`Lighthouse only simulates mobile performance; to measure performance on a real device, try WebPageTest.org [Source: Lighthouse team]`];var je=Object.freeze({__proto__:null,StatusView:Ie,fastFactRotationInterval:Ne,minimumTextVisibilityDuration:Oe,StatusPhases:Fe});class Ge extends R.Panel{constructor(){super("lighthouse"),this.registerRequiredCSS("third_party/lighthouse/report-assets/report.css"),this.registerRequiredCSS("lighthouse/lighthousePanel.css"),this._protocolService=new Se,this._controller=new fe(this._protocolService),this._startView=new De(this._controller),this._statusView=new Ie(this._controller),this._warningText=null,this._unauditableExplanation=null,this._cachedRenderedReports=new Map,this._dropTarget=new P.DropTarget(this.contentElement,[P.Type.File],i.UIString("Drop Lighthouse JSON here"),this._handleDrop.bind(this)),this._controller.addEventListener(we.PageAuditabilityChanged,this._refreshStartAuditUI.bind(this)),this._controller.addEventListener(we.PageWarningsChanged,this._refreshWarningsUI.bind(this)),this._controller.addEventListener(we.AuditProgressChanged,this._refreshStatusUI.bind(this)),this._controller.addEventListener(we.RequestLighthouseStart,e=>{this._startLighthouse(e)}),this._controller.addEventListener(we.RequestLighthouseCancel,e=>{this._cancelLighthouse()}),this._renderToolbar(),this._auditResultsElement=this.contentElement.createChild("div","lighthouse-results-container"),this._renderStartView(),this._controller.recomputePageAuditability()}static getEvents(){return we}_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 y.Toolbar("",e);this._newButton=new y.ToolbarButton(i.UIString("Perform an audit…"),"largeicon-add"),t.appendToolbarItem(this._newButton),this._newButton.addEventListener(y.ToolbarButton.Events.Click,this._renderStartView.bind(this)),t.appendSeparator(),this._reportSelector=new ke(()=>this._renderStartView()),t.appendToolbarItem(this._reportSelector.comboBox()),this._clearButton=new y.ToolbarButton(i.UIString("Clear all"),"largeicon-clear"),t.appendToolbarItem(this._clearButton),this._clearButton.addEventListener(y.ToolbarButton.Events.Click,this._clearAll.bind(this)),this._settingsPane=new T.HBox,this._settingsPane.show(this.contentElement),this._settingsPane.element.classList.add("lighthouse-settings-pane"),this._settingsPane.element.appendChild(this._startView.settingsToolbar().element),this._showSettingsPaneSetting=n.Settings.instance().createSetting("lighthouseShowSettingsToolbar",!1),this._rightToolbar=new y.Toolbar("",e),this._rightToolbar.appendSeparator(),this._rightToolbar.appendToolbarItem(new y.ToolbarSettingToggle(this._showSettingsPaneSetting,"largeicon-settings-gear",ls`Lighthouse settings`)),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(ls`Printing`,ls`The print popup window is open. Please close it to continue.`)}_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 s=this._cachedRenderedReports.get(e);if(s)return void this._auditResultsElement.appendChild(s);const i=this._auditResultsElement.createChild("div","lh-vars lh-root lh-devtools"),n=new DOM(this._auditResultsElement.ownerDocument),r=new xe(n),o=f.cachedResources.get("third_party/lighthouse/report-assets/templates.html"),a=(new DOMParser).parseFromString(o,"text/html");if(!a)return;r.setTemplateContext(a);const l=r.renderReport(e,i);xe.addViewTraceButton(l,t),this._waitForMainTargetLoad().then(()=>{xe.linkifyNodeDetails(l),xe.linkifySourceLocationDetails(l)}),xe.handleDarkMode(l);const d=new Ee(n);d.setBeforePrint(this._beforePrint.bind(this)),d.setAfterPrint(this._afterPrint.bind(this)),d.setTemplateContext(a),d.initFeatures(e),this._cachedRenderedReports.set(e,i)}_waitForMainTargetLoad(){return o.TargetManager.instance().mainTarget().model(c.ResourceTreeModel).once(c.Events.Load)}_buildReportUI(e,t){if(null===e)return;const s=new Ae(e,()=>this._renderReport(e,t),this._renderStartView.bind(this));this._reportSelector.prepend(s),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(Host.UserMetrics.Action.LighthouseStarted);try{const e=await this._controller.getInspectedURL({force:!0}),t=this._controller.getCategoryIDs(),s=this._controller.getFlags();await this._setupEmulationAndProtocolConnection(),this._renderStatusView(e);const i=await this._protocolService.startLighthouse(e,t,s);if(i&&i.fatal){const e=new Error(i.message);throw e.stack=i.stack,e}if(!i)throw new Error("Auditing failed to produce a result");_.actionTaken(Host.UserMetrics.Action.LighthouseFinished),await this._resetEmulationAndProtocolConnection(),this._buildReportUI(i.lhr,i.artifacts),this._newButton.element.focus()}catch(e){await this._resetEmulationAndProtocolConnection(),e instanceof Error&&this._statusView.renderBugReport(e)}}async _cancelLighthouse(){this._statusView.updateStatus(ls`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),"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 m.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}g.InspectedPagePlaceholder.instance().update(!0);const e=o.TargetManager.instance().mainTarget().model(c.ResourceTreeModel),t=await this._controller.getInspectedURL();await e.navigate(t)}}var Ve=Object.freeze({__proto__:null,LighthousePanel:Ge});self.ReportRenderer;self.ReportUIFeatures;var We=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(){}},CategoryRenderer:class{constructor(e,t){}},DetailsRenderer:class{constructor(e){}renderNode(e){throw new Error("Not implemented yet!")}},LighthouseReportGenerator:class{generateReportHtml(e){return""}},AuditResultJSON:void 0,AuditJSON:void 0,CategoryJSON:void 0,GroupJSON:void 0,ReportJSON:void 0,DetailsJSON:void 0,RunnerResultArtifacts:void 0,RunnerResult:void 0,NodeDetailsJSON:void 0,SourceLocationDetailsJSON:void 0,OpportunitySummary:void 0});export{Ce as LighthouseController,Ve as LighthousePanel,Te as LighthouseProtocolService,Le as LighthouseReportRenderer,Re as LighthouseReportSelector,We as LighthouseReporterTypes,Ue as LighthouseStartView,je as LighthouseStatusView,Me as RadioSetting};
