"use strict";(self.webpackChunkgrafana_pyroscope_app=self.webpackChunkgrafana_pyroscope_app||[]).push([[715],{7132:(e,t,n)=>{n.r(t),n.d(t,{App:()=>np});var r=n(6089),o=n(7781),a=n(8531),i=n(2007);const s=new(n(9398).E)({defaultOptions:{queries:{networkMode:"always",retry:!1,refetchOnWindowFocus:!1}}});var l=n(9094),c=n(4812);const u=JSON.parse('{"id":"grafana-pyroscope-app"}'),d=u.id,p=`/a/${d}`;var m=function(e){return e.EXPLORE="/explore",e.ADHOC="/ad-hoc",e.SETTINGS="/settings",e.RECORDING_RULES="/recording-rules",e}({});const f="697f3c77f6fdf6d46ff6470073198939e5b37186",h=[{regExp:/localhost/,environment:"local"},{regExp:/grafana-dev\.net/,environment:"dev"},{regExp:/grafana-ops\.net/,environment:"ops"},{regExp:/grafana\.net/,environment:"prod"}];function g(){var e,t;if(!(null===(t=window)||void 0===t||null===(e=t.location)||void 0===e?void 0:e.host))return null;const n=h.find((({regExp:e})=>e.test(window.location.host)));return n?n.environment:null}const y=new Map([["dev",{environment:"dev",appName:"grafana-pyroscope-dev",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/48e03a2647389f2f6494af7f975b4084"}],["ops",{environment:"ops",appName:"grafana-pyroscope-ops",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/b5cfd5eeb412cf5e74bd828b4ddd17ff"}],["prod",{environment:"prod",appName:"grafana-pyroscope-prod",faroUrl:"https://faro-collector-ops-eu-south-0.grafana-ops.net/collect/6cbe17b3af4b72ce5936bf4d15a5c393"}]]);let b=null;const v=()=>b;var E=n(3715),w=n(5959),S=n.n(w),O=n(5438);function P(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function x(e,t,n){if(!t.has(e))throw new TypeError("attempted to "+n+" private field on non-instance");return t.get(e)}function T(e,t,n){return function(e,t,n){if(t.set)t.set.call(e,n);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=n}}(e,x(e,t,"set"),n),n}function C(e,t,n){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return n}var N=new WeakMap,k=new WeakSet;function j(e,t){var n;"prod"!==function(e,t){return t.get?t.get.call(e):t.value}(n=this,x(n,N,"get"))&&console[e](...t)}const A=new class{trace(){var e;C(this,k,j).call(this,"trace",[]),null===(e=v())||void 0===e||e.api.pushLog([],{level:O.$b.TRACE})}debug(...e){var t;C(this,k,j).call(this,"debug",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.DEBUG})}info(...e){var t;C(this,k,j).call(this,"info",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.INFO})}log(...e){var t;C(this,k,j).call(this,"log",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.LOG})}warn(...e){var t;C(this,k,j).call(this,"warn",e),null===(t=v())||void 0===t||t.api.pushLog(e,{level:O.$b.WARN})}error(e,t){var n;C(this,k,j).call(this,"error",[e]),t&&C(this,k,j).call(this,"error",["Error context",t]),null===(n=v())||void 0===n||n.api.pushError(e,{context:t})}constructor(){var e,t;P(e=this,t=k),t.add(e),function(e,t,n){P(e,t),t.set(e,n)}(this,N,{writable:!0,value:void 0}),T(this,N,g())}};function I(e,t){var n=function(e,t,n){if(!t.has(e))throw new TypeError("attempted to "+n+" private field on non-instance");return t.get(e)}(e,t,"get");return function(e,t){return t.get?t.get.call(e):t.value}(e,n)}function R(e,t,n){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.set(e,n)}var _=new WeakMap;const D=new class{has(e){return I(this,_).hasOwnProperty(e)}get(e){if(!this.has(e))return null;try{return JSON.parse(I(this,_).getItem(e))}catch(t){return A.error(t,{info:`Error parsing JSON for storage item "${e}"!`}),null}}set(e,t){try{I(this,_).setItem(e,JSON.stringify(t))}catch(t){A.error(t,{info:`Error setting storage item "${e}"!`})}}constructor(){var e,t,n;R(this,_,{writable:!0,value:window.localStorage}),e=this,t="KEYS",n={SETTINGS:`${u.id}.userSettings`,GITHUB_INTEGRATION:`${u.id}.gitHubIntegration`,PROFILES_EXPLORER:`${u.id}.profilesExplorer`},t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}},L=()=>{};function F(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class $ extends Error{constructor(e,t){let n=`HTTP ${e.status} (${e.statusText||"?"})`;(null==t?void 0:t.message)&&(n=`${n} → ${t.message}`),super(n),F(this,"response",void 0),F(this,"reason",void 0),this.response=e}}function B(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function M(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function U(e){for(var t=1;t"grafana-pyroscope-datasource"===e.type))}static selectDefaultDataSource(){var e;const t=G.getPyroscopeDataSources(),n=new URL(window.location.href).searchParams.get("var-dataSource"),r=null===(e=D.get(D.KEYS.PROFILES_EXPLORER))||void 0===e?void 0:e.dataSource,o=t.find((e=>e.uid===n))||t.find((e=>e.uid===r))||t.find((e=>e.jsonData.overridesDefault))||t.find((e=>e.isDefault))||t[0];return o||(A.warn("Cannot find any Pyroscope data source! Please add and configure a Pyroscope data source to your Grafana instance."),{uid:"no-data-source-configured"})}static getBaseUrl(){const e=G.selectDefaultDataSource();let t=a.config.appSubUrl||"";return"/"!==t.at(-1)&&(t+="/"),`${t}api/datasources/proxy/uid/${e.uid}`}constructor(){var e,t;super(G.getBaseUrl().toString(),{"content-type":"application/json","X-Grafana-Org-Id":String((null===(t=a.config.bootData)||void 0===t||null===(e=t.user)||void 0===e?void 0:e.orgId)||"")})}}var K=n(7616);function H(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const z=new class extends G{get(){var e,t=this;return(e=function*(){const e=yield t.fetch("/querier.v1.QuerierService/GetProfileStats",{method:"POST",body:JSON.stringify({})}),n=yield e.json();return{hasIngestedData:n.dataIngested,oldestProfileTime:Number(n.oldestProfileTime),newestProfileTime:Number(n.newestProfileTime)}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){H(a,r,o,i,s,"next",e)}function s(e){H(a,r,o,i,s,"throw",e)}i(void 0)}))})()}};function Y(){const[e,t]=(0,w.useState)(!1),n=G.getPyroscopeDataSources().length,{isFetching:r,error:o,stats:a}=function({enabled:e}){const{isFetching:t,error:n,data:r,refetch:o}=(0,K.I)({enabled:e,placeholderData:()=>({hasIngestedData:!0,oldestProfileTime:0,newestProfileTime:0}),queryKey:["tenant-stats"],queryFn:()=>(z.abort(),z.get())});return{isFetching:t,error:z.isAbortError(n)?null:n,stats:r,refetch:o}}({enabled:n>0}),i=!r&&!(null==a?void 0:a.hasIngestedData);return{data:{shouldShowLoadingPage:!o&&r,shouldShowOnboardingPage:(o||!n||i)&&!e,shouldShowNoDataSourceBanner:!n},actions:{closeModal(){t(!0)}}}}const W=e=>({row:(0,r.css)({display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start"}),headerColumn:(0,r.css)({display:"flex",flexDirection:"column",minWidth:"120px",alignItems:"start"}),column:(0,r.css)({display:"flex",flexDirection:"column",minWidth:"120px",alignItems:"end"}),tooltip:(0,r.css)({display:"flex",color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize}),contentWithIcon:(0,r.css)({display:"none",[`@media ${i.styleMixins.mediaUp(e.v1.breakpoints.sm)}`]:{display:"block"}})}),Q=e=>(0,o.formattedValueToString)((0,o.getValueFormat)("decbytes")(e)),J=e=>(0,o.formattedValueToString)((0,o.getValueFormat)("short")(e));function X(e){const t=(0,i.useStyles2)(W),{data:n}=e,r=Q(n.queryImpact.totalBytesInTimeRange),o=(0,w.useMemo)((()=>S().createElement("div",{"data-testid":"queryAnalysis-popup"},S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Data in time range"),S().createElement("div",{className:t.column},r),S().createElement("div",{className:t.column}," ")),void 0!==n.queryImpact.totalQueriedSeries&&S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Series in query"),S().createElement("div",{className:t.column},J(n.queryImpact.totalQueriedSeries)),S().createElement("div",{className:t.column}," ")),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Deduplication"),S().createElement("div",{className:t.column},n.queryImpact.deduplicationNeeded?"yes":"no"),S().createElement("div",{className:t.column}," ")),S().createElement(i.Divider,null),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn}," "),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},S().createElement("strong",null,e.componentType))))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Replicas"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},e.componentCount||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Blocks"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},J(e.blockCount)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Series"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},J(e.seriesCount)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Profiles"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},J(e.profileCount)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Samples"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},J(e.sampleCount)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn}," "),S().createElement("div",{className:t.column}," "),S().createElement("div",{className:t.column}," ")),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Index Store"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},Q(e.indexBytes)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Profiles Store"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},Q(e.profileBytes)||"/")))),S().createElement("div",{className:t.row},S().createElement("div",{className:t.headerColumn},"Symbols Store"),n.queryScopes.map(((e,n)=>S().createElement("div",{key:n,className:t.column},Q(e.symbolBytes)||"/")))))),[n,t,r]);return S().createElement(S().Fragment,null,void 0!==n.queryImpact.totalBytesInTimeRange?S().createElement(i.Toggletip,{content:o,fitContent:!0},S().createElement("div",{className:t.tooltip,"data-testid":"queryAnalysis-tooltip"},S().createElement("span",{className:t.contentWithIcon},"Stored data in time range: ",r)," ",S().createElement(i.IconButton,{name:"database","aria-label":"Query info"}))):null)}var Z=n(9814);function ee({size:e}){const t=(0,i.useStyles2)(ne);return S().createElement("img",{className:(0,r.cx)(t.logo,e),src:"public/plugins/grafana-pyroscope-app/img/logo.svg"})}const te=S().memo(ee),ne=()=>({logo:r.css` &.small { width: 16px; height: 16px; margin-right: 4px; position: relative; top: -2px; } &.large { width: 40px; height: 40px; } `}),re=f,oe=`https://github.com/grafana/profiles-drilldown/commit/${re}`,{buildInfo:ae}=a.config;function ie(){const e=(0,i.useStyles2)(ce),{meta:{info:{version:t,updated:n}}}=(0,o.usePluginContext)()||{meta:{info:{version:"?.?.?",updated:"?"}}};return S().createElement("div",{className:e.menuHeader},S().createElement("h5",null,S().createElement(te,{size:"small"}),"Grafana Profiles Drilldown v",t),S().createElement("div",{className:e.subTitle},"Last update: ",n))}function se(){const e="dev"===re,t=e?re:re.slice(0,8);return S().createElement(i.Menu,{header:S().createElement(ie,null)},S().createElement(i.Menu.Item,{label:`Commit SHA: ${t}`,icon:"github",onClick:()=>window.open(oe),disabled:e}),S().createElement(i.Menu.Item,{label:"Changelog",icon:"list-ul",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/CHANGELOG.md")}),S().createElement(i.Menu.Item,{label:"Contribute",icon:"external-link-alt",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/blob/main/docs/CONTRIBUTING.md")}),S().createElement(i.Menu.Item,{label:"Documentation",icon:"document-info",onClick:()=>window.open("https://grafana.com/docs/grafana/latest/explore/simplified-exploration/profiles")}),S().createElement(i.Menu.Item,{label:"Report an issue",icon:"bug",onClick:()=>window.open("https://github.com/grafana/profiles-drilldown/issues/new?template=bug_report.md")}),S().createElement(i.Menu.Divider,null),S().createElement(i.Menu.Item,{label:`Grafana ${ae.edition} v${ae.version} (${ae.env})`,icon:"github",onClick:()=>window.open(`https://github.com/grafana/grafana/commit/${ae.commit}`)}))}function le(){return S().createElement(i.Dropdown,{overlay:()=>S().createElement(se,null),placement:"bottom-end"},S().createElement(i.IconButton,{name:"info-circle","aria-label":"Plugin info",title:"Plugin info"}))}const ce=e=>({menuHeader:r.css` padding: ${e.spacing(.5,1)}; white-space: nowrap; `,subTitle:r.css` color: ${e.colors.text.secondary}; font-size: ${e.typography.bodySmall.fontSize}; `});function ue({title:e,queryAnalysis:t}){const n=(0,i.useStyles2)(de),r="string"==typeof e?`${e} | Pyroscope`:"Pyroscope";return S().createElement(S().Fragment,null,S().createElement(Z.m,null,S().createElement("title",null,r)),S().createElement("div",{className:n.titleContainer},S().createElement(i.Stack,{justifyContent:"space-between"},S().createElement("div",null,S().createElement(te,{size:"large"}),S().createElement("h1",{className:n.title,"data-testid":"page-title"},e)),S().createElement("div",{className:n.infoArea},S().createElement(le,null),t?S().createElement(X,{data:t}):null))))}const de=e=>({titleContainer:r.css` height: ${e.spacing(5)}; line-height: ${e.spacing(5)}; margin-bottom: ${e.spacing(3)}; `,title:r.css` font-size: ${e.typography.h2.fontSize}; display: inline-block; margin: 0; position: relative; top: 10px; left: ${e.spacing(1)}; `,infoArea:r.css` align-self: end; margin-bottom: 0; line-height: 20px; text-align: right; `}),pe=(0,w.memo)(ue);function me(){return S().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},S().createElement(pe,{title:S().createElement("span",null,"Loading... ",S().createElement(i.Icon,{name:"fa fa-spinner"}))}))}const fe=e=>({link:r.css` color: ${e.colors.text.link}; &:hover { text-decoration: underline; } `});function he({href:e,children:t}){const n=(0,i.useStyles2)(fe);return S().createElement("a",{className:n.link,href:e,target:"_blank",rel:"noreferrer"},t," ",S().createElement(i.Icon,{name:"external-link-alt"}))}function ge(){return S().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},S().createElement(pe,{title:"Grafana Profiles Drilldown"}),S().createElement(i.Alert,{severity:"error",title:"Missing Pyroscope data source!"},"This plugin requires a Pyroscope data source. Please"," ",S().createElement(he,{href:"/connections/datasources/new"},"add and configure a Pyroscope data source")," to your Grafana instance."))}const ye="public/plugins/grafana-pyroscope-app/img/61b4cf746a6f58780f27.png",be="public/plugins/grafana-pyroscope-app/img/58f0b0e1cfa063e4b662.png",ve="public/plugins/grafana-pyroscope-app/img/9c9cdd5175734d579007.png",Ee="public/plugins/grafana-pyroscope-app/img/bafee50693eb02088442.png";function we(){const{instances:e}=function(){const{isFetching:e,error:t,data:n}=(0,K.I)({queryKey:["instances"],queryFn:()=>fetch("/api/plugin-proxy/cloud-home-app/grafanacom-api/instances").then((e=>e.json()))});return{isFetching:e,error:t,instances:n}}(),[t,n]=(0,w.useState)("https://grafana.com/auth/sign-in/"),r=/grafana(-dev|-ops)?\.net/.test(window.location.host);if(e&&e.orgSlug&&e.hpInstanceId){const r=`https://grafana.com/orgs/${e.orgSlug}/hosted-profiles/${e.hpInstanceId}`;t!==r&&n(r)}return{data:{settingsUrl:t,isCloud:r},actions:{}}}const Se=e=>({onboardingRow:r.css` background: ${e.colors.background.secondary}; display: flex; margin-top: 16px; gap: 20px; padding: 20px; margin-bottom: 2.5rem; `,onboardingParagraph:r.css` padding: 20px 64px; text-align: center; line-height: 2; flex: 1; margin: 0; `,onboardingPanel:r.css` flex: 1; display: flex; flex-flow: column wrap; -webkit-box-align: center; align-items: center; margin-top: 16px; text-align: center; `,onboardingPanelHeader:r.css` line-height: 1.5; margin-bottom: 1em; `,onboardingPanelImage:r.css` width: 5rem; margin-bottom: 1em; `,hero:r.css` display: flex; flex-direction: row; `,heroTitles:r.css` flex: 1; `,heroImage:r.css` width: 40%; margin-left: 16px; margin-top: 16px; margin-bottom: 16px; border-radius: 3px; `,onboardingPanelNumber:r.css` color: rgb(236, 109, 19); text-align: center; display: grid; place-items: center; background-image: linear-gradient(135deg, currentcolor, 75%, rgb(204, 204, 220)); border-radius: 100%; font-size: 2.5rem; line-height: 5rem; height: 5rem; width: 5rem; margin-bottom: 1em; `,color2:r.css` color: rgb(190, 85, 190); `,color3:r.css` color: rgb(126, 108, 218); `,onboardingPanelNumberSpan:r.css` color: rgb(220, 220, 220); `,onboardingPanelDescription:r.css` text-align: justify; text-align: center; line-height: 1.66; margin-top: 0; `,title:r.css` margin-bottom: 0.5em; line-height: 1.5; `,subtitle:r.css` margin-bottom: 1em; line-height: 1.5; font-size: 1.25rem; `});function Oe(){const e=(0,i.useStyles2)(Se),{data:t}=we();return S().createElement("div",{"data-testid":"onboarding-modal"},S().createElement("div",{className:e.hero,"data-testid":"hero"},S().createElement("div",{className:e.heroTitles},S().createElement("h1",{className:e.title},"Welcome to Grafana Profiles Drilldown"),S().createElement("h2",{className:e.subtitle},"Optimize infrastructure spend, simplify debugging, and enhance application performance")),S().createElement("img",{src:be,className:e.heroImage})),S().createElement("div",{"data-testid":"what-you-can-do"},S().createElement("h3",null,"What You Can Do"),S().createElement("div",{className:e.onboardingRow},S().createElement("div",{className:e.onboardingPanel},S().createElement("img",{className:e.onboardingPanelImage,src:ve}),S().createElement("h3",{className:e.onboardingPanelHeader},"Reduce Costs"),S().createElement("p",{className:e.onboardingPanelDescription},"Spot CPU spikes, memory leaks, and other inefficiencies with code-level visibility into resource usage. Teams can then optimize their code and lower infrastructure costs.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("img",{className:e.onboardingPanelImage,src:ye}),S().createElement("h3",{className:e.onboardingPanelHeader},"Decrease Latency"),S().createElement("p",{className:e.onboardingPanelDescription},"Maintain high speed and efficiency and improve application performance. In a competitive digital world, decreasing latency translates to increasing revenue.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("img",{className:e.onboardingPanelImage,src:Ee}),S().createElement("h3",{className:e.onboardingPanelHeader},"Resolve Incidents Faster"),S().createElement("p",{className:e.onboardingPanelDescription},"Cut down the mean time to resolution (MTTR) by correlating continuous profiling data with metrics, logs, and traces to quickly identify the root cause of any issue.")))),S().createElement("div",{"data-testid":"how-to-get-started"},S().createElement("h3",null,"How to Get Started"),S().createElement("div",{className:e.onboardingRow},t.isCloud?S().createElement(S().Fragment,null,S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:e.onboardingPanelNumber},S().createElement("span",{className:e.onboardingPanelNumberSpan},"1")),S().createElement("h3",{className:e.onboardingPanelHeader},"Add Profiling to Your Application"),S().createElement("p",{className:e.onboardingPanelDescription},"Use"," ",S().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/configure-client/grafana-alloy/"},"Grafana Alloy")," ","or"," ",S().createElement(he,{href:"https://grafana.com/docs/pyroscope/next/configure-client/language-sdks/"},"Pyroscope SDKs")," ","to push profiles from your applications to Grafana Cloud.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color2)},S().createElement("span",{className:e.onboardingPanelNumberSpan},"2")),S().createElement("h3",{className:e.onboardingPanelHeader},"Configure Your Applications"),S().createElement("p",{className:e.onboardingPanelDescription},"Go to ",S().createElement(he,{href:t.settingsUrl},"Grafana Cloud Stack settings")," to find your Grafana Cloud Credentials.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color3)},S().createElement("span",{className:e.onboardingPanelNumberSpan},"3")),S().createElement("h3",{className:e.onboardingPanelHeader},"Start Getting Performance Insights"),S().createElement("p",{className:e.onboardingPanelDescription},"Once you're done with initial setup, refresh this page to see your profiling data."))):S().createElement(S().Fragment,null,S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:e.onboardingPanelNumber},S().createElement("span",{className:e.onboardingPanelNumberSpan},"1")),S().createElement("h3",{className:e.onboardingPanelHeader},"Set Up Your Pyroscope Server"),S().createElement("p",{className:e.onboardingPanelDescription},"Install ",S().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/"},"Pyroscope Server")," on your infrastructure. Or if you want to use a hosted service, go to"," ",S().createElement(he,{href:t.settingsUrl},"Grafana Cloud Stack settings")," to find your Grafana Cloud Credentials.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color2)},S().createElement("span",{className:e.onboardingPanelNumberSpan},"2")),S().createElement("h3",{className:e.onboardingPanelHeader},"Configure Grafana"),S().createElement("p",{className:e.onboardingPanelDescription},"Add a new ",S().createElement(he,{href:"/connections/datasources/new"},"Pyroscope datasource"),". Use your Pyroscope server URL and appropriate security credentials if you use Grafana Cloud Profiles.")),S().createElement("div",{className:e.onboardingPanel},S().createElement("div",{className:(0,r.cx)(e.onboardingPanelNumber,e.color3)},S().createElement("span",{className:e.onboardingPanelNumberSpan},"3")),S().createElement("h3",{className:e.onboardingPanelHeader},"Add Profiling to Your Application"),S().createElement("p",{className:e.onboardingPanelDescription},"Use"," ",S().createElement(he,{href:"https://grafana.com/docs/pyroscope/latest/configure-client/grafana-alloy/"},"Grafana Alloy")," ","or"," ",S().createElement(he,{href:"https://grafana.com/docs/pyroscope/next/configure-client/language-sdks/"},"Pyroscope SDKs")," ","to push profiles from your applications to Grafana Cloud."))))),t.isCloud&&S().createElement("div",{"data-testid":"how-billing-works"},S().createElement("h3",null,"How Billing Works"),S().createElement("div",{className:e.onboardingRow},S().createElement("p",{className:e.onboardingParagraph},"Usage of Grafana Cloud Profiles is subject to"," ",S().createElement(he,{href:"https://grafana.com/pricing/"},"Grafana Cloud Pricing")," for Profiles.",S().createElement("br",null),"For additional information, read the announcement ",S().createElement(he,{href:"https://grafana.com/blog/2023/08/09/grafana-cloud-profiles-for-continuous-profiling/"},"blog post"),"."))))}const Pe=e=>({onboardingPage:r.css` padding: 16px; margin: 64px; position: relative; background-color: ${e.colors.background.primary}; `,closeButton:r.css` position: absolute; top: -30px; opacity: 0.8; right: -32px; border: none; border-radius: 50%; width: 40px; height: 40px; line-height: 40px; display: block; padding: 0; margin: 0; font-size: 22px; `}),xe={text:"Onboarding"};function Te({onCloseModal:e}){const t=(0,i.useStyles2)(Pe);return S().createElement(a.PluginPage,{pageNav:xe,layout:o.PageLayoutType.Custom},S().createElement("div",{className:t.onboardingPage},S().createElement("button",{className:t.closeButton,onClick:e,title:"Close","data-testid":"close-onboarding-modal"},"×"),S().createElement(Oe,null)))}function Ce({children:e}){const{data:t,actions:n}=Y();return t.shouldShowLoadingPage?S().createElement(me,null):t.shouldShowOnboardingPage?S().createElement(Te,{onCloseModal:n.closeModal}):t.shouldShowNoDataSourceBanner?S().createElement(ge,null):S().createElement(S().Fragment,null,e)}var Ne=n(1159);function ke({onClick:e}){const t=e||(()=>history.back());return S().createElement(i.Button,{variant:"secondary",onClick:t,"aria-label":"Back to Profiles Drilldown"},"Back to Profiles Drilldown")}const je=m.EXPLORE.slice(1);function Ae(){const{pathname:e}=new URL(window.location.toString());return e.split("/").pop()||""}function Ie(){const e={appRelease:a.config.apps[d].version,appVersion:f,page:Ae()};return e.page===je&&(e.view=new URLSearchParams(window.location.search).get("explorationType")||""),e}function Re(e,t){(0,a.reportInteraction)(e,{props:t,meta:Ie()})}function _e(e){const[t,n]=(0,w.useState)(!1);(0,w.useEffect)((()=>{t||(n(!0),Re("g_pyroscope_app_page_initialized",{page:e}))}),[e,t])}const De=e=>({container:r.css` display: flex; justify-content: space-between; align-items: flex-start; gap: ${e.spacing(1)}; width: 100%; `,column:r.css` width: 50%; `});function Le({left:e,right:t}){const n=(0,i.useStyles2)(De);return S().createElement("div",{className:n.container},S().createElement("div",{className:n.column},e),S().createElement("div",{className:n.column},t))}function Fe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $e(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Be(e,t){const n=t.reduce(((e,t,n)=>$e(function(e){for(var t=1;t{const r=new FileReader;r.addEventListener("load",(()=>{try{t(function(e){const[,t]=e.split(";base64,");if(!t)throw new Error("No content after stripping the base64 prefix.");if(e===t)throw new Error("No base64 prefix?!");return t}(r.result))}catch(e){n(e)}})),r.addEventListener("error",(()=>{n(new Error(`Error while reading file "${e.name}"!`))})),r.readAsDataURL(e)}))}))()}};function Ke(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function He(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Ke(a,r,o,i,s,"next",e)}function s(e){Ke(a,r,o,i,s,"throw",e)}i(void 0)}))}}function ze(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ye(e){for(var t=1;t()=>{Ge.abort()}),[]);const o=(0,w.useCallback)((()=>{Ge.abort(),t(!1),r(Qe)}),[]),a=(0,w.useCallback)(function(){var e=He((function*(e){o();try{t(!0);const n=yield Ge.uploadSingle(e);r(n)}catch(e){r(Qe),Ge.isAbortError(e)||Be(e,["Error while uploading profile!",e.message])}t(!1)}));return function(t){return e.apply(this,arguments)}}(),[o]),i=(0,w.useCallback)(function(){var e=He((function*(e){const o=e.value;if(o&&n.id&&n.profileTypes.includes(o)){Ge.abort(),t(!1),r((e=>We(Ye({},e),{profile:null}))),t(!0);try{const e=yield Ge.get(n.id,o);r((t=>We(Ye({},t),{profile:e.profile})))}catch(e){Ge.isAbortError(e)||Be(e,["Error while fetching profile!",e.message])}t(!1)}}));return function(t){return e.apply(this,arguments)}}(),[n.id,n.profileTypes]);return{processFile:a,profileTypes:n.profileTypes,selectProfileType:i,profile:n.profile,removeFile:o,isLoading:e}}function Xe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ze(e){for(var t=1;t(e[t]=n,e)),{});return`${t.year}-${t.month}-${t.day}_${t.hour}${t.minute}`}function dt(e){const t=new Date(Math.round(1e3*e.from.unix())),n=new Date(Math.round(1e3*e.to.unix()));return`${ut(t)}-to-${ut(n)}`}function pt(e){const[t,n]=e===lt.BASELINE?["diffFrom","diffTo"]:["diffFrom-2","diffTo-2"],r=new URLSearchParams(window.location.search),a=r.get(t),i=r.get(n);return{raw:{from:a,to:i},from:(0,o.dateTimeParse)(a),to:(0,o.dateTimeParse)(i)}}function mt(e){const t=["baseline",dt(pt(lt.BASELINE)),"comparison",dt(pt(lt.COMPARISON))];return e?[e,...t].join("_"):["flamegraph",...t].join("_")}function ft(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ht({profile:e,enableFlameGraphDotComExport:t}){const n=function(){var t,n=(t=function*(){Re("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const t=mt(e.metadata.appName);let n;try{n=yield st.upload(t,e)}catch(e){return void Be(e,["Failed to export to flamegraph.com!",e.message])}const r=document.createElement("a");r.target="_blank",r.href=n.url,document.body.appendChild(r),r.click(),document.body.removeChild(r)},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){ft(a,r,o,i,s,"next",e)}function s(e){ft(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(){return n.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(t)},actions:{downloadPng:()=>{Re("g_pyroscope_app_export_profile",{format:"png"});const t=`${mt(e.metadata.appName)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)at()(e,t);else{const e=new Error("No Blob, the image cannot be created.");Be(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:()=>{Re("g_pyroscope_app_export_profile",{format:"json"});const t=`${mt(e.metadata.appName)}.json`,n=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(e))}`;try{at()(n,t)}catch(e){return void Be(e,["Failed to export to JSON!",e.message])}},uploadToFlamegraphDotCom:n}}}function gt(e){const{actions:t}=ht(e);return S().createElement(i.Menu,null,S().createElement(i.Menu.Item,{label:"png",onClick:t.downloadPng}),S().createElement(i.Menu.Item,{label:"json",onClick:t.downloadJson}))}function yt(e){const{profile:t,enableFlameGraphDotComExport:n}=e;return S().createElement(i.Dropdown,{overlay:S().createElement(gt,{profile:t,enableFlameGraphDotComExport:n})},S().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}const bt=(0,w.memo)(yt);function vt(e,t,n){const r=[],o=n?7:4;for(let a=0;afunction(e,t,n,r){if(!e.length)return;const a=[];for(let n=0;n0){const e=a[n].slice(0,-1).reduce(((e,t)=>t.offsetTotal+t.valTotal+e),0)+o.offsetTotal,t=a[n-1];let r=0;for(const n of t){const t=r+n.offsetTotal,a=t+n.valTotal;if(t<=e&&a>e){n.children.push(o);break}r+=n.offsetTotal+n.valTotal}}}const i=[a[0][0]],s=[],l=[],c=[],u=[],d=[],p=[];for(;i.length;){const e=i.shift();s.push(e.label),l.push(e.level),c.push(e.self),u.push(e.val),d.push(e.selfRight),p.push(e.valRight),i.unshift(...e.children)}let m="short";switch(n){case"samples":case"trace_samples":case"lock_nanoseconds":case"nanoseconds":m="ns";break;case"bytes":m="bytes"}const f=[{name:"level",values:l},{name:"label",values:s,type:o.FieldType.string},{name:"self",values:c,config:{unit:m}},{name:"value",values:u,config:{unit:m}}];r&&f.push({name:"selfRight",values:d,config:{unit:m}},{name:"valueRight",values:p,config:{unit:m}});const h={name:"response",meta:{preferredVisualisationType:"flamegraph"},fields:f};return(0,o.createDataFrame)(h)}(e.flamebearer.levels,e.flamebearer.names,e.metadata.units,Boolean(t))),[e,t]);return S().createElement(rt.A,{data:c,disableCollapsing:!a,extraHeaderElements:S().createElement(bt,{profile:e,enableFlameGraphDotComExport:r}),vertical:n,getTheme:()=>(0,o.createTheme)({colors:{mode:l?"light":"dark"}}),getExtraContextMenuButtons:s,keepFocusOnDataChange:!0})}const wt=(0,w.memo)(Et),St=e=>({flamegraph:r.css` margin-top: ${e.spacing(2)}; `});function Ot({profile:e,diff:t}){const n=(0,i.useStyles2)(St);return S().createElement("div",{className:n.flamegraph,"data-testid":"flamegraph"},S().createElement(wt,{profile:e,diff:t}))}const Pt=e=>({selectorContainer:r.css` display: flex; justify-content: center; margin-bottom: ${e.spacing(2)}; `});function xt({profileTypes:e,onChange:t}){const n=(0,i.useStyles2)(Pt),r=(0,w.useMemo)((()=>e.map((e=>({value:e,label:e})))),[e]),[o,a]=(0,w.useState)(),s=(0,w.useCallback)((e=>{a(e),t(e)}),[t]);return(0,w.useEffect)((()=>{a(r[0])}),[r]),S().createElement("div",{className:n.selectorContainer},S().createElement(i.InlineFieldRow,null,S().createElement(i.InlineField,{label:"Profile",disabled:!r.length,"data-testid":"profile-types-dropdown"},S().createElement(i.Select,{key:null==o?void 0:o.value,value:o,options:r,onChange:s,width:16}))))}const Tt=e=>({spinner:r.css` text-align: center; margin-top: ${e.spacing(2)}; `});function Ct(){const e=(0,i.useStyles2)(Tt);return S().createElement("div",{className:e.spinner},S().createElement(i.Spinner,{size:36}))}function Nt(){const{processFile:e,profileTypes:t,selectProfileType:n,profile:r,removeFile:o,isLoading:a}=Je();return S().createElement("div",null,S().createElement(xt,{profileTypes:t,onChange:e=>{Re("g_pyroscope_app_ad_hoc_profile_metric_selected"),n(e)}}),S().createElement(nt,{onFileDropped:t=>{Re("g_pyroscope_app_ad_hoc_file_dropped",{fileType:t.type}),e(t)},onFileRemove:()=>{Re("g_pyroscope_app_ad_hoc_file_removed"),o()}}),a&&!r?S().createElement(Ct,null):null,r&&S().createElement(Ot,{profile:r}))}const kt=(0,w.memo)(Nt);function jt(){return S().createElement(Le,{left:S().createElement(kt,null),right:S().createElement(kt,null)})}const At=e=>({tabContent:r.css` padding: ${e.spacing(2)}; margin: ${e.spacing(2)}; `});function It(){const e=(0,i.useStyles2)(At),[t,n]=(0,w.useState)(0);return S().createElement("div",null,S().createElement(i.TabsBar,null,S().createElement(i.Tab,{label:" Single view",active:0===t,onChangeTab:()=>n(0)}),S().createElement(i.Tab,{label:" Comparison view",active:1===t,onChangeTab:()=>n(1)})),S().createElement(i.TabContent,{className:e.tabContent},0===t&&S().createElement(kt,null),1===t&&S().createElement(jt,null)))}function Rt(){return _e("ad_hoc"),S().createElement(S().Fragment,null,S().createElement(pe,{title:"Ad hoc view"}),S().createElement(It,null),S().createElement(ke,null))}var _t=n(3342);function Dt(){history.pushState(null,"")}var Lt,Ft,$t,Bt=n(3241);class Mt extends o.BusEventWithPayload{}$t="timeseries-data-received",(Ft="type")in(Lt=Mt)?Object.defineProperty(Lt,Ft,{value:$t,enumerable:!0,configurable:!0,writable:!0}):Lt[Ft]=$t;var Ut=function(e){return e.partial="partial",e["attribute-operator-value"]="attribute-operator-value",e["attribute-operator"]="attribute-operator",e}({}),Vt=function(e){return e["="]="=",e["!="]="!=",e.in="in",e["not-in"]="not-in",e["is-empty"]="is-empty",e["=~"]="=~",e["!~"]="!~",e}({}),qt=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({}),Gt=function(e){return e.attribute="attribute",e.operator="operator",e.value="value",e}({});var Kt=n(1015),Ht=n(7268),zt=n(8987),Yt=n(9221);class Wt extends q{constructor(e){var t;const{dataSourceUid:n}=e;let{appSubUrl:r="",bootData:o}=a.config;"/"!==(null==r?void 0:r.at(-1))&&(r+="/"),super(`${r}api/datasources/proxy/uid/${n}`,{"content-type":"application/json","X-Grafana-Org-Id":String((null==o||null===(t=o.user)||void 0===t?void 0:t.orgId)||"")}),function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"dataSourceUid",void 0),this.dataSourceUid=e.dataSourceUid}}function Qt(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Jt(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Qt(a,r,o,i,s,"next",e)}function s(e){Qt(a,r,o,i,s,"throw",e)}i(void 0)}))}}class Xt extends Wt{static queryToMatchers(e){const t=e.indexOf("{");if(t>0){return[`{__profile_type__="${e.substring(0,t)}", ${e.substring(t+1,e.length)}`]}return 0===t?[e]:[`{__profile_type__="${e}"}`]}fetchLabels(e,t,n){var r=this;return Jt((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:Xt.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return Jt((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:Xt.queryToMatchers(t),start:n,end:r}).then((e=>e.json()))}))()}_post(e,t){return super.fetch(e,{method:"POST",body:JSON.stringify(t)})}constructor(e){super(e)}}class Zt{static buildCacheKey(e){let t="";for(const n of e)t+=String(n);return t}get(e){return this.store.get(Zt.buildCacheKey(e))}set(e,t){this.store.set(Zt.buildCacheKey(e),t)}delete(e){this.store.delete(Zt.buildCacheKey(e))}constructor(){!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"store",new Map)}}function en(e,t){if(!e)throw new Error(t)}function tn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class nn{setApiClient(e){this.apiClient=e}setCacheClient(e){this.cacheClient=e}cancel(e){this.apiClient.abort(e)}constructor(e){tn(this,"apiClient",void 0),tn(this,"cacheClient",void 0),this.apiClient=e.apiClient,this.cacheClient=null==e?void 0:e.cacheClient}}function rn(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function on(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){rn(a,r,o,i,s,"next",e)}function s(e){rn(a,r,o,i,s,"throw",e)}i(void 0)}))}}class an extends G{static queryToMatchers(e){const t=e.indexOf("{");if(t>0){return[`{__profile_type__="${e.substring(0,t)}", ${e.substring(t+1,e.length)}`]}return 0===t?[e]:[`{__profile_type__="${e}"}`]}fetchLabels(e,t,n){var r=this;return on((function*(){return r._post("/querier.v1.QuerierService/LabelNames",{matchers:an.queryToMatchers(e),start:t,end:n}).then((e=>e.json()))}))()}fetchLabelValues(e,t,n,r){var o=this;return on((function*(){return o._post("/querier.v1.QuerierService/LabelValues",{name:e,matchers:an.queryToMatchers(t),start:n,end:r}).then((e=>e.json()))}))()}_post(e,t){return super.fetch(e,{method:"POST",body:JSON.stringify(t)})}}function sn(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ln(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){sn(a,r,o,i,s,"next",e)}function s(e){sn(a,r,o,i,s,"throw",e)}i(void 0)}))}}function cn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class un extends nn{static parseLabelsResponse(e){if(!Array.isArray(e.names))return[];return Array.from(new Set(e.names.filter(un.isNotMetaLabelOrServiceName))).map((e=>({value:e,label:e})))}static parseLabelValuesResponse(e){if(!Array.isArray(e.names))return[];return e.names.map((e=>({value:e,label:e})))}static assertParams(e,t,n){en(Boolean(e),'Missing "query" parameter!'),en(t>0&&n>0&&n>t,"Invalid timerange!")}listLabels({query:e,from:t,to:n}){var r=this;return ln((function*(){un.assertParams(e,t,n);const o=[r.apiClient.baseUrl,e,t,n],a=r.cacheClient.get(o);if(a){const e=yield a,t=un.parseLabelsResponse(e);return t.length||r.cacheClient.delete(o),t}const i=r.apiClient.fetchLabels(e,t,n);r.cacheClient.set(o,i);try{const e=yield i;return un.parseLabelsResponse(e)}catch(e){throw r.cacheClient.delete(o),e}}))()}listLabelValues({label:e,query:t,from:n,to:r}){var o=this;return ln((function*(){un.assertParams(t,n,r),en(Boolean(e),"Missing label value!");const a=[o.apiClient.baseUrl,e,t,n,r],i=o.cacheClient.get(a);if(i){const e=yield i,t=un.parseLabelsResponse(e);return t.length||o.cacheClient.delete(a),t}const s=o.apiClient.fetchLabelValues(e,t,n,r);o.cacheClient.set(a,s);try{const e=yield s;return un.parseLabelValuesResponse(e)}catch(e){throw o.cacheClient.delete(a),e}}))()}constructor(e){super({apiClient:e.apiClient}),cn(this,"cacheClient",void 0),this.cacheClient=e.cacheClient}}cn(un,"isNotMetaLabelOrServiceName",(e=>!/^(__.+__|service_name)$/.test(e)));const dn=new un({apiClient:new an,cacheClient:new Zt});function pn(e,t){const n=e.filter((({type:e})=>e!==Ut.partial)),r=t.filter((({type:e})=>e!==Ut.partial));return n.length===r.length&&n.every((e=>r.find((({type:t,attribute:n,operator:r,value:o})=>{var a,i;return t===e.type&&n.value===e.attribute.value&&(null==r?void 0:r.value)===(null===(a=e.operator)||void 0===a?void 0:a.value)&&(null==o?void 0:o.value)===(null===(i=e.value)||void 0===i?void 0:i.value)}))))}function mn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const fn={type:Ut["attribute-operator"],operator:{value:Vt["is-empty"],label:"is empty"},value:{value:Vt["is-empty"],label:""}},hn=e=>function(e){for(var t=1;te!==Ut.partial)).map((e=>{const{attribute:t,operator:n,value:r}=e;switch(n.value){case Vt.in:return`${t.value}=~"${r.value}"`;case Vt["not-in"]:return`${t.value}!~"${r.value}"`;case Vt["is-empty"]:return`${t.value}=""`;default:return`${t.value}${n.value}"${r.value}"`}}));var r;const[,o]=null!==(r=e.match(/{.*(service_name="[^"]*").*}/))&&void 0!==r?r:[];return o&&n.unshift(o),e.replace(/{(.*)}$/,`{${n.join(",")}}`)}const yn=e=>e.at(-1)||null,bn=e=>e===Vt.in||e===Vt["not-in"],vn=e=>(en(Boolean(e),"The filter is falsy!"),e.type===Ut.partial);function En(e,t){return e!==t&&(t!==Vt["is-empty"]&&([Vt["=~"],Vt["!~"],Vt.in,Vt["not-in"],Vt["is-empty"]].includes(e)||[Vt["=~"],Vt["!~"],Vt.in,Vt["not-in"]].includes(t)))}function wn(e,t){en(void 0!==e.operator,"No operator for the filter under edition!");return En(e.operator.value,t)}function Sn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function On(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const Pn=e=>{const t=e.matchAll(/(\w+)(=|!=|=~|!~)"([^"]*)"/g);return Array.from(t).map((([,e,t,n])=>[e,t,n]))},xn=/.+:[^{]+\{(.+)\}$/,Tn=/.*(\^|\$|\*|\+|\{|\}|\?).*/;function Cn(e){if(!e)return[];const t=e.match(xn);if(!t)return[];return Pn(t[1]).filter((([e])=>"service_name"!==e)).map((([e,t,n])=>{const r={id:(0,zt.Ak)(10),type:Ut["attribute-operator-value"],active:!0,attribute:{value:e,label:e},operator:{value:t,label:t},value:{value:n,label:n}};if(t===Vt["="]&&""===n)return hn(r);return[Vt["=~"],Vt["!~"]].includes(t)&&!Tn.test(n)?On(function(e){for(var t=1;te.trim())).join(", ")}}):r}))}function Nn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const jn=(e,t)=>e.map((e=>e.type!==Ut.partial?kn(function(e){for(var t=1;t{dn.cancel("Discarded by user")},setFilterAttribute:(0,Yt.kp)(((e,t)=>{const n=[...e.filters,{id:(0,zt.Ak)(10),type:Ut.partial,active:!1,attribute:t.data}];return Rn(In({},e),{filters:n,isQueryUpToDate:pn(n,Cn(e.inputParams.query))})})),editFilterAttribute:(0,Yt.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter attribute without edition data!");const{filterId:n}=e.edition,r=e.filters.map((e=>e.id===n?Rn(In({},e),{attribute:t.data,operator:void 0,value:void 0}):e));return Rn(In({},e),{filters:r,isQueryUpToDate:pn(r,Cn(e.inputParams.query)),edition:null})})),setFilterOperator:(0,Yt.kp)(((e,t)=>{const n=e.filters.map((e=>{if(!vn(e))return e;const n=t.data;return n.value===Vt["is-empty"]?hn(e):Rn(In({},e),{operator:n,value:void 0})}));return In({},e,_n(n,e))})),editFilterOperator:(0,Yt.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter operator without edition data!");const{filterId:n}=e.edition,r=t.data;let o=null;const a=e.filters.map((t=>{const a=t.operator.value;return t.id!==n||a===r.value?t:r.value===Vt["is-empty"]?hn(Rn(In({},t),{active:!1})):(a===Vt["is-empty"]&&(t.value={value:"(no value)",label:"(no value)"}),!vn(t)&&En(a,r.value)&&(o=Rn(In({},e.edition),{part:qt.value})),Rn(In({},t),{operator:r,value:bn(a)&&!bn(r.value)&&t.value?{value:t.value.value.split("|").shift(),label:t.value.label.split(", ").shift()}:t.value,active:!1}))}));return Rn(In({},e,_n(a,e)),{edition:o})})),setFilterValue:(0,Yt.kp)(((e,t)=>{const n=e.filters.map((e=>vn(e)?Rn(In({},e),{type:Ut["attribute-operator-value"],active:!1,value:t.data}):e));return In({},e,_n(n,e))})),editFilterValue:(0,Yt.kp)(((e,t)=>{if(null===e.edition)throw new Error("Cannot edit filter value without edition data!");const{filterId:n}=e.edition,r=e.filters.map((e=>e.id===n?Rn(In({},e),{type:Ut["attribute-operator-value"],active:!1,value:t.data}):e));return Rn(In({},e,_n(r,e)),{edition:null})})),removeFilter:(0,Yt.kp)(((e,t)=>{const n=t.data,r=jn(e.filters.filter((({id:e})=>e!==n)),!1);return In({},e,_n(r,e))})),removeLastFilter:(0,Yt.kp)((e=>{const{filters:t}=e,n=yn(t);if(!n)return e;if(vn(n)&&n.operator){const r=t.slice(0,t.length-1).concat(Rn(In({},n),{operator:void 0}));return Rn(In({},e),{filters:r,isQueryUpToDate:!0})}const r=t.slice(0,t.length-1).map((e=>Rn(In({},e),{active:!1})));return In({},e,_n(r,e))})),setEdition:(0,Yt.kp)({edition:(e,t)=>t.data}),changeInputParams:(0,Yt.kp)(((e,t)=>(t.data.dataSourceUid&&dn.setApiClient(new Xt({dataSourceUid:t.data.dataSourceUid})),{inputParams:t.data,query:t.data.query,filters:Cn(t.data.query),isQueryUpToDate:!0}))),activateFilters:(0,Yt.kp)((e=>In({},e,_n(e.filters,e))))};function Ln(e){const{edition:t,filters:n}=e;en(null!==t,'"edition" is null!');const r=n.find((({id:e})=>e===t.filterId));return en(void 0!==r,"Cannot find the filter under edition!"),r}const Fn={shouldSuggestAttributes:e=>{const t=yn(e.filters);return!t||!vn(t)},shouldSuggestOperators:e=>{var t;return!(null===(t=yn(e.filters))||void 0===t?void 0:t.operator)},shouldSuggestValues:e=>{const t=yn(e.filters);return Boolean((null==t?void 0:t.operator)&&!(null==t?void 0:t.value))},isEditing:e=>null!==e.edition,shouldSuggestValuesAfterOperatorEdition:(e,t)=>!!e.edition&&wn(Ln(e),t.data.value),shouldNotSuggestValuesAfterOperatorEdition:(e,t)=>!!e.edition&&!wn(Ln(e),t.data.value),hasPartialFilter:e=>{const t=yn(e.filters);return Boolean(t&&vn(t))},shouldEditAttribute:(e,t)=>t.data.part===qt.attribute,shouldEditOperator:(e,t)=>t.data.part===qt.operator,shouldEditValue:(e,t)=>t.data.part===qt.value};function $n(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const Bn=new class{list(){return(e=function*(){return[{value:"=",label:"="},{value:"!=",label:"!="},{value:"is-empty",label:"is empty"},{value:"in",label:"in",description:"Is one of"},{value:"not-in",label:"not in",description:"Is not one of"},{value:"=~",label:"=~",description:"Matches regex"},{value:"!~",label:"!~",description:"Does not match regex"}]},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){$n(a,r,o,i,s,"next",e)}function s(e){$n(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e}},Mn=e=>e.startsWith("__");function Un(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Vn(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Un(a,r,o,i,s,"next",e)}function s(e){Un(a,r,o,i,s,"throw",e)}i(void 0)}))}}function qn(e,t){if(e instanceof DOMException&&"AbortError"===e.name)return[];throw A.error(e,{info:t}),e}const Gn={fetchLabels:function(){var e=Vn((function*(e){const{from:t,to:n}=e.inputParams;try{const r=yield dn.listLabels({query:e.query,from:t,to:n}),o=[],a=[];return r.forEach((e=>{Mn(e.value)?a.push(e):o.push(e)})),[...o,...a]}catch(e){return qn(e,"Error while fetching labels!")}}));return function(t){return e.apply(this,arguments)}}(),fetchOperators:Vn((function*(){try{return yield Bn.list()}catch(e){return qn(e,"Error while fetching operators!")}})),fetchLabelValues:function(){var e=Vn((function*(e){let t,{query:n,edition:r,suggestions:o}=e;try{if(r){const o=e.filters.filter((e=>e.id!==r.filterId||(t=e,!1)));if(!t)throw new Error(`Impossible to edit filter id="${r.filterId}": no filter found!`);n=gn(n,o)}else if(t=yn(e.filters),(null==t?void 0:t.type)!==Ut.partial)throw new Error("Impossible to load label values: no partial filter found!");if(o.disabled)return[];const a=t.attribute.value,{from:i,to:s}=e.inputParams;return yield dn.listLabelValues({label:a,query:n,from:i,to:s})}catch(e){return qn(e,"Error while fetching label values!")}}));return function(t){return e.apply(this,arguments)}}()},Kn={always:[{cond:"shouldSuggestOperators",target:"loadOperators"},{cond:"shouldSuggestValues",target:"loadLabelValues"},{target:"idle"}]},Hn={FILTER_ADD:"Filter by label values...",SELECT_LABEL:"Select a label...",SELECT_OPERATOR:"Select an operator...",SELECT_VALUE:"Select a value...",SELECT_VALUES:"Select values...",TYPE_VALUE:"Type a regex...",LOADING:"Loading...",ERROR_LOAD:"An unexpected error occurred while loading! Please try again.",SUGGESTIONS_NONE:"No suggestions available.",SUGGESTIONS_DISABLED:"Suggestions are disabled for this label."},zn=e=>e===Vt["=~"]||e===Vt["!~"];function Yn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const Qn={entry:["cancelAllLoad",(0,Yt.kp)({suggestions:e=>{let t=Hn.FILTER_ADD,n=!1;const r=yn(e.filters);return r&&vn(r)&&(r.operator?(n=zn(r.operator.value),t=bn(r.operator.value)?Hn.SELECT_VALUES:n?Hn.TYPE_VALUE:Hn.SELECT_VALUE):t=Hn.SELECT_OPERATOR),Wn(function(e){for(var t=1;tZn(Xn({},fr.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchLabels",src:"fetchLabels",onDone:{target:"displayLabels",actions:(0,Yt.kp)({suggestions:(e,t)=>Zn(Xn({},e.suggestions),{items:t.data.filter((({value:t})=>!e.filters.some((e=>{var n;return(null===(n=e.attribute)||void 0===n?void 0:n.value)===t})))),isLoading:!1})})},onError:{target:"displayLabels",actions:(0,Yt.kp)({suggestions:(e,t)=>Zn(Xn({},e.suggestions),{isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},tr={entry:(0,Yt.kp)({suggestions:e=>Zn(Xn({},e.suggestions),{type:Gt.attribute,isVisible:!0,placeholder:Hn.SELECT_LABEL})}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"isEditing",target:"loadOperators",actions:["editFilterAttribute"]},{target:"loadOperators",actions:["setFilterAttribute"]}],REMOVE_LAST_FILTER:{target:"idle",actions:["removeLastFilter"]}}};function nr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rr(e){for(var t=1;t{const t=e.edition?Ln(e):yn(e.filters);return en(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!"),or(rr({},fr.suggestions),{disabled:["=~","!~"].includes(t.operator.value)||Mn(t.attribute.value),isVisible:!0,isLoading:!0})}}),invoke:{id:"fetchLabelValues",src:"fetchLabelValues",onDone:{target:"displayLabelValues",actions:(0,Yt.kp)({suggestions:(e,t)=>or(rr({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayLabelValues",actions:(0,Yt.kp)({suggestions:(e,t)=>or(rr({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},ir={entry:(0,Yt.kp)({suggestions:e=>{const t=e.edition?Ln(e):yn(e.filters);en(void 0!==typeof(null==t?void 0:t.operator),"No operator for the target filter!");const n=t.operator.value,r=zn(n)||e.suggestions.disabled,o=bn(n);let a,i;return a=r?Hn.TYPE_VALUE:o?Hn.SELECT_VALUES:Hn.SELECT_VALUE,i=e.suggestions.error?Hn.ERROR_LOAD:e.suggestions.disabled?Hn.SUGGESTIONS_DISABLED:Hn.SUGGESTIONS_NONE,or(rr({},e.suggestions),{type:Gt.value,isVisible:!0,placeholder:a,noOptionsMessage:i,allowCustomValue:r,multiple:o})}}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"isEditing",target:"autoSuggestProxy",actions:["editFilterValue"]},{target:"idle",actions:["setFilterValue"]}],REMOVE_LAST_FILTER:{target:"loadOperators",actions:["removeLastFilter"]}}};function sr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lr(e){for(var t=1;tcr(lr({},fr.suggestions),{isVisible:!0,isLoading:!0})}),invoke:{id:"fetchOperators",src:"fetchOperators",onDone:{target:"displayOperators",actions:(0,Yt.kp)({suggestions:(e,t)=>cr(lr({},e.suggestions),{items:t.data,isLoading:!1})})},onError:{target:"displayOperators",actions:(0,Yt.kp)({suggestions:(e,t)=>cr(lr({},e.suggestions),{items:[],isLoading:!1,error:t.data})})}},on:{DISCARD_SUGGESTIONS:"idle"}},dr={entry:(0,Yt.kp)({suggestions:e=>cr(lr({},e.suggestions),{type:Gt.operator,isVisible:!0,placeholder:Hn.SELECT_OPERATOR,allowCustomValue:!1,multiple:!1})}),on:{DISCARD_SUGGESTIONS:"idle",SELECT_SUGGESTION:[{cond:"shouldSuggestValuesAfterOperatorEdition",target:"loadLabelValues",actions:["editFilterOperator"]},{cond:"shouldNotSuggestValuesAfterOperatorEdition",target:"autoSuggestProxy",actions:["editFilterOperator"]},{cond:"hasPartialFilter",target:"autoSuggestProxy",actions:["setFilterOperator"]},{target:"loadLabelValues",actions:["setFilterOperator"]}],REMOVE_LAST_FILTER:{target:"loadLabels",actions:["removeLastFilter"]}}};function pr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mr(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}const fr=Object.freeze({inputParams:{query:"",from:0,to:0},query:"",filters:[],isQueryUpToDate:!0,edition:null,suggestions:{type:null,items:[],isVisible:!1,isLoading:!1,error:null,placeholder:"",noOptionsMessage:"",allowCustomValue:!1,multiple:!1,disabled:!1}}),hr=e=>({id:"query-builder",initial:"idle",context:e,predictableActionArguments:!0,states:{idle:Qn,loadLabels:er,displayLabels:tr,loadOperators:ur,displayOperators:dr,loadLabelValues:ar,displayLabelValues:ir,autoSuggestProxy:Kn}}),gr={guards:Fn,services:Gn,actions:Dn};function yr(e){const{query:t}=e,n=mr(function(e){for(var t=1;t(t,n)=>{const r=e.some((e=>e.value===t.value)),o=e.some((e=>e.value===n.value));return r&&o?br(t.value,n.value):o?1:r?-1:0};function Er({selection:e,suggestions:t,onCloseMenu:n}){const r=(0,i.useStyles2)(wr),o=(0,w.useMemo)((()=>{const t=e.value.split("|"),n=e.label.split(", ");return t.map(((e,t)=>({value:e,label:n[t]})))}),[e]),[a,s]=(0,w.useState)(o),l=(0,w.useMemo)((()=>t.items.sort(vr(a))),[t.items]),c=(0,w.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),u=(0,w.useCallback)((()=>{n(a)}),[n,a]);return S().createElement(i.MultiSelect,{className:r.editionSelect,placeholder:t.placeholder,loadingMessage:Hn.LOADING,closeMenuOnSelect:!1,hideSelectedOptions:!1,backspaceRemovesValue:!0,autoFocus:!0,value:a,onChange:c,onCloseMenu:u,options:l,isOpen:!0,isLoading:t.isLoading,invalid:Boolean(t.error),noOptionsMessage:t.noOptionsMessage})}const wr=()=>({editionSelect:r.css` position: absolute; z-index: 1; [aria-label='Remove'] svg { display: none; } `});function Sr({placeholder:e,defaultValue:t,onFocus:n,onChange:o,onBlur:a}){const s=(0,i.useStyles2)(Or),l=(0,w.useRef)(null),[c,u]=(0,w.useState)(!1);return(0,w.useEffect)((()=>{l.current&&l.current.focus()}),[]),S().createElement(i.Input,{ref:l,className:(0,r.cx)(t&&s.edition),invalid:c,placeholder:e,defaultValue:t,onFocus:n,onKeyUp:e=>{const t=e.target.value.trim();"Enter"===e.code&&(t?o({value:t,label:t}):u(!0))},onBlur:e=>{const t=e.target.value.trim();t?o({value:t,label:t}):a()}})}const Or=()=>({edition:r.css` position: absolute; z-index: 1; `}),Pr=()=>({editionSelect:r.css` position: absolute; z-index: 1; min-width: 160px; box-shadow: none; & input:focus { outline: none !important; } `});function xr({selection:e,suggestions:t,onChange:n,onCloseMenu:r}){const o=(0,i.useStyles2)(Pr);return t.allowCustomValue?S().createElement(Sr,{defaultValue:e.value,placeholder:t.placeholder,onChange:n,onBlur:r}):S().createElement(i.Select,{className:o.editionSelect,placeholder:t.placeholder,loadingMessage:Hn.LOADING,closeMenuOnSelect:!1,autoFocus:!0,value:e.value,onChange:n,onCloseMenu:r,options:t.items,isOpen:!0,isLoading:t.isLoading,invalid:Boolean(t.error),noOptionsMessage:t.noOptionsMessage})}const Tr=()=>{},Cr=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(Rr),{attribute:a,operator:s,active:l}=e,c=l?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return S().createElement("div",{className:c,"aria-label":"Filter"},S().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:Tr}),S().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,qt.operator),tabIndex:0}),S().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},Nr=()=>{},kr=({filter:e,onClick:t,onRemove:n})=>{const o=(0,i.useStyles2)(Rr),{attribute:a,operator:s,value:l,active:c}=e,u=c?o.chiclet:(0,r.cx)(o.chiclet,o.inactiveChiclet);return S().createElement("div",{className:u,"aria-label":"Filter"},S().createElement(i.Tag,{"aria-label":"Filter label",className:o.chicletAttribute,name:a.label,onClick:Nr}),S().createElement(i.Tag,{"aria-label":"Filter operator",className:o.chicletOperator,name:s.label,onClick:(n,r)=>t(r,e,qt.operator),tabIndex:0}),S().createElement(i.Tooltip,{content:l.label},S().createElement(i.Tag,{"aria-label":"Filter value",name:l.label,className:o.chicletValue,onClick:(n,r)=>t(r,e,qt.value),tabIndex:0})),S().createElement(i.Tag,{"aria-label":"Remove filter",className:o.chicletRemoveButton,icon:"times",name:"",onClick:(t,r)=>n(r,e),tabIndex:0}))},jr=({filter:e,onClick:t})=>{const n=(0,i.useStyles2)(Rr),{attribute:o,operator:a}=e;return o||a?S().createElement("div",{className:(0,r.cx)(n.chiclet,n.partialChiclet),"aria-label":"Partial filter"},S().createElement(i.Tag,{colorIndex:9,name:o.label,title:`Edit "${o.label}"`,onClick:(n,r)=>t(r,e,qt.attribute),tabIndex:0}),a&&S().createElement(i.Tag,{colorIndex:9,name:a.label,title:`Edit "${a.label}"`,className:n.chicletOperator,onClick:(n,r)=>t(r,e,qt.operator),tabIndex:0})):null},Ar="rgb(61, 113, 217)",Ir="#4a4b52",Rr=e=>({chiclet:r.css` display: flex; align-items: center; border: 1px solid ${Ar}; border-radius: 2px; & > button { height: 30px; background-color: ${e.colors.background.primary}; color: ${e.colors.text.maxContrast}; } & > :first-child { background-color: ${Ar}; color: ${"#fff"}; border-radius: 0; &:hover { cursor: not-allowed !important; } } & > :last-child { border-left: 1px solid ${Ar}; border-top-left-radius: 0; border-bottom-left-radius: 0; } `,partialChiclet:r.css` border-color: ${Ir}; border-right: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; & > :first-child { background-color: ${e.colors.background.secondary}; color: ${e.colors.text.maxContrast}; border-radius: 0; border-left: 0; &:hover { cursor: pointer !important; } } & > :last-child { border-color: ${Ir}; color: ${e.colors.text.maxContrast}; } `,inactiveChiclet:r.css` border-color: ${Ir}; & > button { color: ${e.colors.text.maxContrast}; } & > :first-child { background-color: ${e.colors.background.secondary}; color: ${e.colors.text.maxContrast}; } & > :last-child { border-color: ${Ir}; } `,chicletAttribute:r.css` &:hover { opacity: 1 !important; } `,chicletOperator:r.css` &:hover { background-color: ${e.colors.background.secondary}; } `,chicletValue:r.css` flex-grow: 1; text-align: left; max-width: 420px; text-overflow: ellipsis; text-wrap: nowrap; overflow: hidden; &:hover { background-color: ${e.colors.background.secondary}; } `,chicletRemoveButton:r.css` &:hover { background-color: ${e.colors.background.secondary}; } & svg { width: 12px; height: 12px; } `}),_r=({filter:e,onClick:t,onRemove:n})=>{switch(e.type){case Ut.partial:return S().createElement(jr,{filter:e,onClick:t});case Ut["attribute-operator-value"]:return S().createElement(kr,{filter:e,onClick:t,onRemove:n});case Ut["attribute-operator"]:return S().createElement(Cr,{filter:e,onClick:t,onRemove:n});default:throw new TypeError(`Unsupported filter type "${e.type}" (${JSON.stringify(e)})!`)}},Dr=(0,w.memo)(_r,((e,t)=>JSON.stringify(e.filter)===JSON.stringify(t.filter))),Lr=()=>({chicletsList:r.css` display: flex; align-items: center; flex-wrap: wrap; gap: 4px; `,editChicletContainer:r.css` position: relative; `});function Fr({filters:e,onClickChiclet:t,onRemoveChiclet:n,edition:r,suggestions:o,onChangeSingleSuggestion:a,onCloseSingleSuggestionsMenu:s,onCloseMultipleSuggestionsMenu:l}){const c=(0,i.useStyles2)(Lr);return S().createElement("div",{className:c.chicletsList,"data-testid":"filtersList"},e.map((e=>S().createElement("div",{key:e.id,className:c.editChicletContainer},S().createElement(Dr,{filter:e,onClick:t,onRemove:n}),(null==r?void 0:r.filterId)===e.id?o.multiple?S().createElement(Er,{selection:e[r.part],suggestions:o,onCloseMenu:l}):S().createElement(xr,{key:r.part,selection:e[r.part],suggestions:o,onChange:a,onCloseMenu:s}):null))))}const $r=(0,w.memo)(Fr),Br=()=>({select:r.css` border-top-right-radius: 0; border-bottom-right-radius: 0; `});function Mr({suggestions:e,onFocus:t,onChange:n,onKeyDown:r,onCloseMenu:o}){const a=(0,i.useStyles2)(Br),s=function(e){const[t,n]=(0,w.useState)(!1);return(0,w.useEffect)((()=>{!e||t?e!==t&&n(e):setTimeout((()=>n(!0)),0)}),[t,e]),t}(e.isVisible);return e.allowCustomValue?S().createElement(Sr,{placeholder:e.placeholder,onFocus:t,onChange:n,onBlur:o}):S().createElement(i.Select,{className:a.select,placeholder:e.placeholder,loadingMessage:Hn.LOADING,closeMenuOnSelect:!1,value:null,onFocus:t,onKeyDown:r,onChange:n,onCloseMenu:o,options:e.items,isOpen:s,isLoading:e.isLoading,invalid:Boolean(e.error),noOptionsMessage:e.noOptionsMessage})}const Ur=()=>{};function Vr(){const e=(0,i.useStyles2)(Br);return S().createElement(i.Select,{disabled:!0,className:e.select,placeholder:Hn.FILTER_ADD,onChange:Ur})}function qr({suggestions:e,onFocus:t,onKeyDown:n,onCloseMenu:r}){const o=(0,i.useStyles2)(Gr),[a,s]=(0,w.useState)([]),l=(0,w.useCallback)((e=>{s(e.map((({value:e="",label:t=""})=>({value:e,label:t}))))}),[]),c=(0,w.useCallback)((e=>{n(e,a)}),[n,a]),u=(0,w.useCallback)((()=>{r(a)}),[r,a]);return S().createElement(i.MultiSelect,{className:o.select,placeholder:e.placeholder,loadingMessage:Hn.LOADING,closeMenuOnSelect:!1,hideSelectedOptions:!1,backspaceRemovesValue:!0,autoFocus:!0,value:a,onFocus:t,onKeyDown:c,onChange:l,onCloseMenu:u,options:e.items,isOpen:e.isVisible,isLoading:e.isLoading,invalid:Boolean(e.error),noOptionsMessage:e.noOptionsMessage})}const Gr=()=>({select:r.css` [aria-label='Remove'] svg { display: none; } `}),Kr=()=>({queryBuilder:r.css` display: flex; justify-content: flex-start; align-items: flex-end; flex-wrap: wrap; gap: 4px; width: 100%; `,controls:r.css` display: flex; align-self: flex-start; flex-grow: 1; `,executeButton:r.css` border-top-left-radius: 0; border-bottom-left-radius: 0; `});function Hr(e){const t=(0,i.useStyles2)(Kr),{actor:n,internalProps:o}=function({dataSourceUid:e,query:t,from:n,to:r,onChangeQuery:o}){const{actor:a,initialContext:i}=(0,w.useMemo)((()=>yr({query:t,from:n,to:r})),[]);(0,w.useEffect)((()=>{a.send({type:"CHANGE_INPUT_PARAMS",data:{dataSourceUid:e,query:t,from:n,to:r}})}),[a,e,t,n,r]);const[s,l]=(0,w.useState)(i);return(0,w.useEffect)((()=>(a.start(),a.subscribe((({event:e,context:t})=>{"EXECUTE_QUERY"===e.type&&o(t.query,t.filters),l(t)})),()=>{a.stop()})),[a]),{actor:a,internalProps:s}}(e),{filters:a,edition:s,isQueryUpToDate:l,suggestions:c}=o,{onClickChiclet:u,onRemoveChiclet:d}=function(e){const t=(0,w.useCallback)(((t,n,r)=>{e.send({type:"EDIT_FILTER",data:{filterId:n.id,part:r}})}),[e]),n=(0,w.useCallback)(((t,n)=>{e.send({type:"REMOVE_FILTER",data:n.id})}),[e]);return{onClickChiclet:t,onRemoveChiclet:n}}(n),{onFocus:p,onChangeSingleSuggestion:m,onSingleSelectKeyDown:f,onCloseSingleMenu:h,onMultipleSelectKeyDown:g,onCloseMultipleMenu:y}=function(e,t,n){const r=(0,w.useCallback)((()=>{e.send({type:"START_INPUT"})}),[e]),o=(0,w.useCallback)((t=>{const{value:n="",label:r=""}=t;e.send({type:"SELECT_SUGGESTION",data:{value:n,label:r}})}),[e]),a=(0,w.useCallback)((t=>{"Backspace"!==t.code||t.target.value||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),i=(0,w.useCallback)((()=>{e.send({type:"DISCARD_SUGGESTIONS"})}),[e]),s=(0,w.useCallback)(((t,n)=>{"Backspace"!==t.code||t.target.value||n.length||e.send({type:"REMOVE_LAST_FILTER"})}),[e]),l=(0,w.useCallback)((t=>{t.length?e.send({type:"SELECT_SUGGESTION",data:{value:t.map((e=>e.value)).join("|"),label:t.map((e=>e.label)).join(", ")}}):e.send({type:"DISCARD_SUGGESTIONS"})}),[e]),c=function(e){const t=(0,w.useRef)();return(0,w.useEffect)((()=>{t.current=e})),t.current}(t.isVisible);return(0,w.useEffect)((()=>{var e;!t.isVisible&&c&&(null===(e=document.querySelector(`#${n} input`))||void 0===e||e.blur())}),[t.isVisible,c,n]),{onFocus:r,onChangeSingleSuggestion:o,onSingleSelectKeyDown:a,onMultipleSelectKeyDown:s,onCloseSingleMenu:i,onCloseMultipleMenu:l}}(n,c,e.id),b=(0,w.useCallback)((()=>{n.send({type:"EXECUTE_QUERY"})}),[n]);return(0,w.useEffect)((()=>{if(!e.autoExecute)return;const t=({value:e,context:t,event:r})=>{"idle"!==e||t.isQueryUpToDate||"EXECUTE_QUERY"===r.type||n.send({type:"EXECUTE_QUERY"})};return n.onTransition(t),()=>{n.off(t)}}),[n,e.autoExecute]),S().createElement("div",{id:e.id,className:(0,r.cx)(t.queryBuilder,e.className)},a.length>0?S().createElement($r,{filters:a,onClickChiclet:u,onRemoveChiclet:d,edition:s,suggestions:c,onChangeSingleSuggestion:m,onCloseSingleSuggestionsMenu:h,onCloseMultipleSuggestionsMenu:y}):null,S().createElement("div",{className:t.controls},s?S().createElement(Vr,null):c.multiple?S().createElement(qr,{suggestions:c,onFocus:p,onKeyDown:g,onCloseMenu:y}):S().createElement(Mr,{suggestions:c,onFocus:p,onChange:m,onKeyDown:f,onCloseMenu:h}),!e.autoExecute&&S().createElement(i.Button,{onClick:b,tooltip:l?"Nothing to execute, all filters applied":"Execute new query",className:t.executeButton,disabled:l},"Execute")))}const zr=(0,w.memo)(Hr),Yr=JSON.parse('{"block:contentions:count:contentions:count":{"id":"block:contentions:count:contentions:count","description":"Number of blocking contentions","type":"contentions","group":"block","unit":"short"},"block:delay:nanoseconds:contentions:count":{"id":"block:delay:nanoseconds:contentions:count","description":"Time spent in blocking delays","type":"delay","group":"block","unit":"ns"},"goroutine:goroutine:count:goroutine:count":{"id":"goroutine:goroutine:count:goroutine:count","description":"Number of goroutines","type":"goroutine","group":"goroutine","unit":"short"},"goroutines:goroutine:count:goroutine:count":{"id":"goroutines:goroutine:count:goroutine:count","description":"Number of goroutines","type":"goroutine","group":"goroutine","unit":"short"},"memory:alloc_in_new_tlab_bytes:bytes::":{"id":"memory:alloc_in_new_tlab_bytes:bytes::","description":"Size of memory allocated inside Thread-Local Allocation Buffers (TLAB)","type":"alloc_in_new_tlab_bytes","group":"memory","unit":"bytes"},"memory:alloc_in_new_tlab_objects:count::":{"id":"memory:alloc_in_new_tlab_objects:count::","description":"Number of objects allocated inside Thread-Local Allocation Buffers (TLAB)","type":"alloc_in_new_tlab_objects","group":"memory","unit":"short"},"memory:alloc_objects:count:space:bytes":{"id":"memory:alloc_objects:count:space:bytes","description":"Number of objects allocated","type":"alloc_objects","group":"memory","unit":"short"},"memory:alloc_space:bytes:space:bytes":{"id":"memory:alloc_space:bytes:space:bytes","description":"Size of memory allocated in the heap","type":"alloc_space","group":"memory","unit":"bytes"},"memory:inuse_objects:count:space:bytes":{"id":"memory:inuse_objects:count:space:bytes","description":"Number of objects currently in use","type":"inuse_objects","group":"memory","unit":"short"},"memory:inuse_space:bytes:space:bytes":{"id":"memory:inuse_space:bytes:space:bytes","description":"Size of memory currently in use","type":"inuse_space","group":"memory","unit":"bytes"},"mutex:contentions:count:contentions:count":{"id":"mutex:contentions:count:contentions:count","description":"Number of observed mutex contentions","type":"contentions","group":"mutex","unit":"short"},"mutex:delay:nanoseconds:contentions:count":{"id":"mutex:delay:nanoseconds:contentions:count","description":"Time spent waiting due to mutex contentions","type":"delay","group":"mutex","unit":"ns"},"process_cpu:alloc_samples:count:cpu:nanoseconds":{"id":"process_cpu:alloc_samples:count:cpu:nanoseconds","description":"Number of memory allocation samples during CPU time","type":"alloc_samples","group":"memory","unit":"short"},"process_cpu:alloc_size:bytes:cpu:nanoseconds":{"id":"process_cpu:alloc_size:bytes:cpu:nanoseconds","description":"Size of memory allocated during CPU time","type":"alloc_size","group":"alloc_size","unit":"bytes"},"process_cpu:cpu:nanoseconds:cpu:nanoseconds":{"id":"process_cpu:cpu:nanoseconds:cpu:nanoseconds","description":"CPU time consumed","type":"cpu","group":"process_cpu","unit":"ns"},"process_cpu:exception:count:cpu:nanoseconds":{"id":"process_cpu:exception:count:cpu:nanoseconds","description":"Number of exceptions within the sampled CPU time","type":"exceptions","group":"exceptions","unit":"short"},"process_cpu:lock_count:count:cpu:nanoseconds":{"id":"process_cpu:lock_count:count:cpu:nanoseconds","description":"Number of lock acquisitions attempted during CPU time","type":"lock_count","group":"locks","unit":"short"},"process_cpu:lock_time:nanoseconds:cpu:nanoseconds":{"id":"process_cpu:lock_time:nanoseconds:cpu:nanoseconds","description":"Cumulative time spent acquiring locks","type":"lock_time","group":"locks","unit":"ns"},"process_cpu:samples:count::milliseconds":{"id":"process_cpu:samples:count::milliseconds","description":"Number of process samples collected","type":"samples","group":"process_cpu","unit":"short"},"process_cpu:samples:count:cpu:nanoseconds":{"id":"process_cpu:samples:count:cpu:nanoseconds","description":"Number of samples collected over CPU time","type":"samples","group":"process_cpu","unit":"short"}}');function Wr(e){if(Yr[e])return Yr[e];const[t="?",n="?"]=e?e.split(":"):[];return{id:e,description:"",type:n,group:t,unit:"short"}}var Qr=n(1269);const Jr=Object.freeze({type:"grafana-pyroscope-datasource",uid:"$dataSource"}),Xr=Object.freeze({type:"grafana-pyroscope-series-datasource",uid:"grafana-pyroscope-series-datasource"}),Zr=Object.freeze({type:"grafana-pyroscope-favorites-datasource",uid:"grafana-pyroscope-favorites-datasource"}),eo=Object.freeze({type:"grafana-pyroscope-labels-datasource",uid:"grafana-pyroscope-labels-datasource"});function to(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function no(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class ro extends _t.fS{onActivate(){this.state.value||this.setState({value:ro.DEFAULT_VALUE})}update(e=!1){var t,n=this;return(t=function*(){if(!e&&n.state.loading)return;let t=[],r=null;n.setState({loading:!0,options:[],error:null});try{t=yield(0,Qr.lastValueFrom)(n.getValueOptions({}))}catch(e){r=e}finally{n.setState({loading:!1,options:t,error:r})}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){to(a,r,o,i,s,"next",e)}function s(e){to(a,r,o,i,s,"throw",e)}i(void 0)}))})()}static buildCascaderOptions(e){const t=new Map;for(const{value:n}of e){const e=Wr(n),{group:r,type:o}=e,a=t.get(r)||{value:r,label:r,items:[]},i=a.items||[];i.push({value:n,label:o}),a.items=i,t.set(r,a)}return Array.from(t.values()).sort(((e,t)=>br(t.label,e.label)))}constructor(e){super(function(e){for(var t=1;t{Re("g_pyroscope_app_profile_metric_selected"),this.state.skipUrlSync||Dt(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}no(ro,"DEFAULT_VALUE","process_cpu:cpu:nanoseconds:cpu:nanoseconds"),no(ro,"QUERY_DEFAULT","$dataSource and all profile metrics"),no(ro,"QUERY_SERVICE_NAME_DEPENDENT","$dataSource and only $serviceName profile metrics"),no(ro,"Component",(({model:e})=>{const t=(0,i.useStyles2)(oo),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,w.useMemo)((()=>ro.buildCascaderOptions(o)),[o]);return a?S().createElement(i.Tooltip,{theme:"error",content:a.toString()},S().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):S().createElement(i.Cascader,{key:(0,zt.Ak)(5),"aria-label":"Profile metrics list",width:24,separator:"/",displayAllSelectedLevels:!0,placeholder:n?"Loading...":`Select a profile metric (${o.length})`,options:s,initialValue:r,changeOnSelect:!1,onSelect:e.onSelect})}));const oo=e=>({iconError:r.css` height: 32px; align-self: center; color: ${e.colors.error.text}; `});function ao(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function io(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class so extends _t.fS{onActivate(){const{serviceName:e}=D.get(D.KEYS.PROFILES_EXPLORER)||{};e&&!this.state.value&&this.setState({value:e}),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=D.get(D.KEYS.PROFILES_EXPLORER)||{};t.serviceName=e.value,D.set(D.KEYS.PROFILES_EXPLORER,t)}}))}update(){var e,t=this;return(e=function*(){if(t.state.loading)return;let e=[],n=null;t.setState({loading:!0,options:[],error:null});try{e=yield(0,Qr.lastValueFrom)(t.getValueOptions({}))}catch(e){n=e}finally{t.setState({loading:!1,options:e,error:n})}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ao(a,r,o,i,s,"next",e)}function s(e){ao(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(function(e){for(var t=1;t{Re("g_pyroscope_app_service_name_selected"),this.state.skipUrlSync||Dt(),this.changeValueTo(e)})),this.addActivationHandler(this.onActivate.bind(this))}}io(so,"QUERY_DEFAULT","$dataSource and all services"),io(so,"QUERY_PROFILE_METRIC_DEPENDENT","$dataSource and only $profileMetricId services"),io(so,"Component",(({model:e})=>{const t=(0,i.useStyles2)(lo),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,w.useMemo)((()=>function(e){const t=[...e].sort(),n=[],r=new Map;for(const e of t){const t=e.split("/");let o="";for(let e=0;ee)))),[o]);return a?S().createElement(i.Tooltip,{theme:"error",content:a.toString()},S().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})):S().createElement(i.Cascader,{key:(0,zt.Ak)(5),"aria-label":"Services list",width:32,separator:"/",displayAllSelectedLevels:!0,placeholder:n?"Loading services...":`Select a service (${o.length})`,options:s,initialValue:r,changeOnSelect:!1,onSelect:e.selectNewValue})}));const lo=e=>({iconError:r.css` height: 32px; align-self: center; color: ${e.colors.error.text}; `});function co(e,t){const{value:n}=_t.jh.findByKeyAndType(e,"serviceName",so).useState(),{value:r}=_t.jh.findByKeyAndType(e,"profileMetricId",ro).useState(),{filterExpression:o}=_t.jh.findByKeyAndType(e,t,Oo).useState();return(0,w.useMemo)((()=>`${r}{service_name="${n}",${o}}`),[o,r,n])}class uo extends _t.mI{onActivate(){this.setState({skipUrlSync:!1}),this.subscribeToState(((e,t)=>{if(e.value&&e.value!==t.value){const t=D.get(D.KEYS.PROFILES_EXPLORER)||{};t.dataSource=e.value,D.set(D.KEYS.PROFILES_EXPLORER,t)}}))}constructor(){super({pluginId:"grafana-pyroscope-datasource",key:"dataSource",name:"dataSource",label:"Data source",skipUrlSync:!0,value:G.selectDefaultDataSource().uid}),this.addActivationHandler(this.onActivate.bind(this))}}function po(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mo(e){for(var t=1;t{let t=e.operator.value;return e.operator.value===Vt.in?t=Vt["=~"]:e.operator.value===Vt["not-in"]&&(t=Vt["!~"]),{key:e.attribute.value,operator:t,value:e.value.value}};function go(e,t){let n;const r=e.filter((e=>e.key!==t||(n=e,!1)));return{found:n,filtersWithoutFound:r}}const yo=(e,t)=>[...e,t];function bo(e,t){const{found:n,filtersWithoutFound:r}=go(e,t.key);if(!n)return yo(e,fo(mo({},t),{operator:"=~"}));if(["!~","!="].includes(n.operator))return yo(r,fo(mo({},t),{operator:"=~"}));const o=new Set(n.value.split("|"));return"=~"===n.operator?yo(r,fo(mo({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:yo(r,fo(mo({},t),{operator:"=~",value:Array.from(o.add(t.value)).join("|")}))}function vo(e,t){const{found:n,filtersWithoutFound:r}=go(e,t.key);if(!n)return yo(e,fo(mo({},t),{operator:"!~"}));if(["=~","="].includes(n.operator))return yo(r,fo(mo({},t),{operator:"!~"}));const o=new Set(n.value.split("|"));return"!~"===n.operator?yo(r,fo(mo({},n),{value:Array.from(o.add(t.value)).join("|")})):n.value===t.value?e:yo(r,fo(mo({},t),{operator:"!~",value:Array.from(o.add(t.value)).join("|")}))}function Eo(e,t){const{found:n,filtersWithoutFound:r}=go(e,t.key);if(!n)return e;const o=n.value.split("|").filter((e=>e!==t.value));return o.length>0?yo(r,fo(mo({},n),{value:o.join("|")})):[...r]}const wo=e=>e.operator in Vt;function So(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Oo extends _t.H9{reset(){this.setState({filters:Oo.DEFAULT_VALUE})}static resetAll(e){["filters","filtersBaseline","filtersComparison"].forEach((t=>{_t.jh.findByKeyAndType(e,t,Oo).reset()}))}onActivate(){const e=_t.jh.findByKeyAndType(this,"dataSource",uo).subscribeToState((()=>{this.reset()}));return()=>{e.unsubscribe()}}constructor({key:e}){super({key:e,name:e,label:"Filters",filters:Oo.DEFAULT_VALUE,expressionBuilder:e=>e.filter(wo).map((({key:e,operator:t,value:n})=>t===Vt["is-empty"]?`${e}=""`:`${e}${t}"${n}"`)).join(",")}),So(this,"onChangeQuery",((e,t)=>{Re("g_pyroscope_app_filters_changed",{name:this.state.name,count:t.length,operators:(0,Bt.uniq)(t.map((e=>e.operator.label)))}),this.setState({filters:t.map(ho)})})),this.addActivationHandler(this.onActivate.bind(this))}}function Po(e,t){var n;return null===(n=_t.jh.lookupVariable(t,e))||void 0===n?void 0:n.getValue()}function xo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}So(Oo,"DEFAULT_VALUE",[]),So(Oo,"Component",(({model:e})=>{const{key:t}=e.useState(),n=co(e,t),{value:r}=_t.jh.findByKeyAndType(e,"dataSource",uo).useState(),{from:o,to:a}=_t.jh.getTimeRange(e).state.value;return S().createElement(zr,{id:`query-builder-${t}`,autoExecute:!0,dataSourceUid:r,query:n,from:1e3*o.unix(),to:1e3*a.unix(),onChangeQuery:e.onChangeQuery})}));var To=function(e){return e.TIMESERIES="time-series",e.BARGAUGE="bar-gauge",e.TABLE="table",e.HISTOGRAM="histogram",e}({});class Co extends _t.Bs{getUrlState(){return{panelType:this.state.panelType}}updateFromUrl(e){const t={};"string"==typeof e.panelType&&e.panelType!==this.state.panelType&&(t.panelType=Object.values(To).includes(e.panelType)?e.panelType:Co.DEFAULT_PANEL_TYPE),this.setState(t)}reset(){this.setState({panelType:Co.DEFAULT_PANEL_TYPE})}constructor(){super({key:"panel-type-switcher",panelType:Co.DEFAULT_PANEL_TYPE}),xo(this,"_urlSync",new _t.So(this,{keys:["panelType"]})),xo(this,"onChange",(e=>{Re("g_pyroscope_app_panel_type_changed",{panelType:e}),this.setState({panelType:e})}))}}xo(Co,"OPTIONS",[{label:"Time series",value:"time-series",icon:"heart-rate"},{label:"Totals",value:"bar-gauge",icon:"align-left"},{label:"Maxima",value:"table",icon:"angle-double-up"},{label:"Histograms",value:"histogram",icon:"graph-bar"}]),xo(Co,"DEFAULT_PANEL_TYPE","time-series"),xo(Co,"Component",(({model:e})=>{const{panelType:t}=e.useState();return S().createElement(i.RadioButtonGroup,{"aria-label":"Panel type switcher",options:Co.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));var No=n(1625);function ko(e){const t=a.config.theme2.visualization;return t.getColorByName(t.palette[e%8])}const jo=(e,t)=>{var n;return(null===(n=e.labels)||void 0===n?void 0:n[t])||"(no value)"},Ao=(e,t)=>{var n,r,o;return null===(o=e.meta)||void 0===o||null===(r=o.stats)||void 0===r||null===(n=r.find((e=>e.displayName===t)))||void 0===n?void 0:n.value};function Io(e){const[,t=""]=e.match(/.+\{.*service_name="([^"]+)".*\}/)||[],[,n=""]=e.match(/([^{]+)\{.*}/)||[],r=e.substring(e.indexOf("{")),o=r.replace(/(\{|\})/,"").split(",").map((e=>{var t;return null===(t=e.match(/\W*([^=!~]+)(=|!=|=~|!~)"(.*)"/))||void 0===t?void 0:t[0]})).filter((e=>e&&!e.includes("service_name")));return{serviceId:t,profileMetricId:n,labelsSelector:r,labels:o}}function Ro(e){return e.addActivationHandler((()=>{const{profileTypeId:t,labelSelector:n}=e.state.queries[0];if(!t)return void e.setState({queries:[{refId:"null"}],data:_o(e,"Missing profile type!")});if(!n)return void e.setState({queries:[{refId:"null"}],data:_o(e,"Missing label selector!")});if(!_t.jh.interpolate(e,"$profileMetricId"))return void e.setState({queries:[{refId:"null"}],data:_o(e,"Missing profile type!")});Io(_t.jh.interpolate(e,`$profileTypeId${n})`)).serviceId||e.setState({queries:[{refId:"null"}],data:_o(e,"Missing service name!")})})),e}function _o(e,t){const n=new Error(t);return A.error(n),{state:o.LoadingState.Error,errors:[n],series:[],timeRange:_t.jh.getTimeRange(e).state.value}}function Do({serviceName:e,profileMetricId:t,groupBy:n,filters:r},o){const a=r?[...r]:[];a.unshift({key:"service_name",operator:"=",value:e||"$serviceName"});const i=a.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(",");return Ro(new _t.dt({datasource:Jr,queries:[{refId:`${t||"$profileMetricId"}-${i}-${(null==n?void 0:n.label)||"no-group-by"}`,queryType:"metrics",profileTypeId:t||"$profileMetricId",labelSelector:`{${i},$filters}`,groupBy:(null==n?void 0:n.label)?[n.label]:[],limit:o}]}))}const Lo=()=>e=>e.pipe((0,Qr.map)((e=>null==e?void 0:e.map(((e,t)=>(0,Bt.merge)(e,{refId:`${e.refId}-${t}`})))))),Fo=()=>e=>e.pipe((0,Qr.map)((e=>{const t=null==e?void 0:e.length;return null==e?void 0:e.map((e=>{var n,r;let o=Number.NEGATIVE_INFINITY;const a=null===(r=e.fields)||void 0===r||null===(n=r.find((e=>"number"===e.type)))||void 0===n?void 0:n.values.reduce(((e,t)=>(t>o&&(o=t),e+t)),0);return(0,Bt.merge)(e,{meta:{stats:[{displayName:"totalSeriesCount",value:t},{displayName:"allValuesSum",value:a},{displayName:"maxValue",value:o}]}})}))})));class $o extends _t.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Mt({series:a}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){var n;let r=Number.NEGATIVE_INFINITY;for(const e of t){const t=Ao(e,"allValuesSum")||0;t>r&&(r=t)}const a=null===(n=e.queryRunnerParams.groupBy)||void 0===n?void 0:n.label,i=a?"This panel displays aggregate values over the current time period":void 0;return{title:t.length>1?`${e.label} (${t.length})`:e.label,description:i,options:{reduceOptions:{values:!1,calcs:["sum"]},orientation:o.VizOrientation.Horizontal,displayMode:No.eX.Gradient,valueMode:No.$l.Text,showUnfilled:!0,sizing:No.T6.Manual,text:{titleSize:13,valueSize:13},namePlacement:No.TZ.Top,minVizHeight:36,maxVizHeight:36,legend:{showLegend:!1}},fieldConfig:{defaults:{displayName:1===t.length?a:void 0,min:0,max:r,thresholds:{mode:o.ThresholdsMode.Percentage,steps:[]}},overrides:this.getOverrides(e,t)}}}getOverrides(e,t){var n;const{index:r,queryRunnerParams:a}=e,i=null===(n=a.groupBy)||void 0===n?void 0:n.label;return t.map(((e,t)=>({matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:jo(e.fields[1],i)},{id:"color",value:{mode:"fixed",fixedColor:ko(r+t)}}]})))}static Component({model:e}){const{body:t}=e.useState();return S().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t}){super({key:"bar-gauge-label-values",body:_t.d0.bargauge().setTitle(e.label).setData(new _t.Es({$data:Do(e.queryRunnerParams),transformations:[Lo,Fo]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}function Bo(e,t){const n=t.fields[1].config.unit,r=Ao(t,"allValuesSum")||0,a=(0,o.getValueFormat)(n)(r),i=Ao(t,"maxValue")||0,s=(0,o.getValueFormat)(n)(i);return`total ${e} = ${a.text}${a.suffix} / max = ${s.text}${s.suffix}`}class Mo extends _t.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Mt({series:a}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){var n;const{legendPlacement:r}=this.state,o=null===(n=e.queryRunnerParams.groupBy)||void 0===n?void 0:n.label;return{title:t.length>1?`${e.label} (${t.length})`:e.label,options:{tooltip:{mode:i.TooltipDisplayMode.Single,sort:No.xB.None},legend:{showLegend:!0,displayMode:i.LegendDisplayMode.List,placement:r,calcs:[]}},fieldConfig:{defaults:{displayName:1===t.length?o:void 0,custom:{lineWidth:1}},overrides:this.getOverrides(e,t)}}}getOverrides(e,t){var n;const{index:r,queryRunnerParams:a}=e,i=null===(n=a.groupBy)||void 0===n?void 0:n.label;return t.map(((e,n)=>{const a=e.fields[1];let s=i?jo(a,i):a.name;return 1===t.length&&(s=Bo(s,e)),{matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:s},{id:"color",value:{mode:"fixed",fixedColor:ko(r+n)}}]}}))}static Component({model:e}){const{body:t}=e.useState();return S().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,legendPlacement:n}){super({key:"histogram-label-values",legendPlacement:n||"bottom",body:_t.d0.histogram().setTitle(e.label).setData(new _t.Es({$data:Do(e.queryRunnerParams),transformations:[Lo,Fo]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Uo extends _t.Bs{onActivate(e){const{body:t}=this.state,n=t.state.$data.subscribeToState((n=>{var r;if((null===(r=n.data)||void 0===r?void 0:r.state)!==o.LoadingState.Done)return;const{series:a}=n.data;(null==a?void 0:a.length)&&t.setState(this.getConfig(e,a)),this.publishEvent(new Mt({series:a}),!0)}));return()=>{n.unsubscribe()}}getConfig(e,t){const n=t[0].fields[0].values.length,r=Wr(_t.jh.findByKeyAndType(this,"profileMetricId",ro).state.value).unit;return{title:n>1?`${e.label} (${n})`:e.label,fieldConfig:{defaults:{custom:{filterable:!0,cellOptions:{}}},overrides:[{matcher:{id:"byName",options:"max"},properties:[{id:"unit",value:r},{id:"custom.width",value:100}]}]}}}static Component({model:e}){const t=(0,i.useStyles2)(Vo),{body:n}=e.useState();return S().createElement("span",{className:t.container},S().createElement(n.Component,{model:n}))}constructor({item:e,headerActions:t}){super({key:"table-label-values",body:_t.d0.table().setTitle(e.label).setData(new _t.Es({$data:Do(e.queryRunnerParams),transformations:[{id:o.DataTransformerID.reduce,options:{reducers:["max"],labelsToFields:!0}},{id:o.DataTransformerID.filterFieldsByName,options:{exclude:{names:["Field"]}}},{id:o.DataTransformerID.renameByRegex,options:{regex:"Max",renamePattern:"max"}},{id:o.DataTransformerID.sortBy,options:{sort:[{field:"max",desc:!0}]}}]})).setHeaderActions(t(e)).build()}),this.addActivationHandler(this.onActivate.bind(this,e))}}const Vo=()=>({container:r.css` [data-testid='data-testid table body'] [role='row']:first-child { color: ${ko(3)}; font-weight: 500; } `});function qo(e){return{from:1e4*Math.floor((e.from.valueOf()||0)/1e4),to:1e4*Math.floor((e.to.valueOf()||0)/1e4)}}function Go(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ko(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Go(a,r,o,i,s,"next",e)}function s(e){Go(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Ho(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zo(e){for(var t=1;t-1?i:"?"})`,count:i}}))()}metricFindQuery(e,t){var n=this;return Ko((function*(){var e,r,o;if(!(null===(r=t.scopedVars)||void 0===r||null===(e=r.__sceneObject)||void 0===e?void 0:e.value).isActive)return[];const{dataSourceUid:a,serviceName:i,profileMetricId:s,query:l,from:c,to:u}=n.getParams(t);if(!i||!s)return A.warn('LabelsDataSource: either serviceName="%s" and/or profileMetricId="%s" is empty! Discarding request.',i,s),[];const d=yield n.fetchLabels(a,l,c,u,null===(o=t.variable)||void 0===o?void 0:o.name),p=yield Promise.all(d.filter((({value:e})=>!Mn(e))).map((({value:e},r)=>Wo((()=>{var o;return n.fetchLabelValues(r,l,c,u,e,null===(o=t.variable)||void 0===o?void 0:o.name)}))))),m=p.sort(((e,t)=>t.count-e.count)).map((({value:e,text:t},n)=>({value:JSON.stringify(Yo(zo({},e),{index:n})),text:t})));return[{value:"all",text:"All"},...m]}))()}testDatasource(){return Ko((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(eo.type,eo.uid)}}Ho(Qo,"MAX_TIMESERIES_LABEL_VALUES",10);const Jo=n.p+"e6c722427cfa8715e19d.svg";function Xo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zo(e){for(var t=1;t({text:`${n===e.scaleDistribution.type?"✔ ":""}${e.text}`,onClick:()=>this.onClickScaleOption(e)})))},{type:"divider",text:""},{iconClassName:"compass",text:"Open in Explore",onClick:()=>this.onClickExplore()}];if(e)r.push({iconClassName:"plus-square",text:"Add to investigation (beta)",onClick:()=>{e.onClick()}});else{const e=null==t?void 0:t.find((e=>e.text.includes("Add to investigation")));e&&r.push(ra({},e))}return r}onClickScaleOption(e){const{scaleDistribution:t,text:n}=e;(0,a.reportInteraction)("g_pyroscope_app_timeseries_scale_changed",{scale:t.type});_t.jh.getAncestor(this,sa).changeScale(t,n),this.setState({scaleType:t.type,items:this.buildMenuItems()})}onClickExplore(){(0,a.reportInteraction)("g_pyroscope_app_open_in_explore_clicked");const e=function(e,t,n){const r=JSON.stringify({"pyroscope-explore":{range:(0,o.toURLRange)(e),queries:[ea(Zo({},t),{datasource:n})],panelsState:{},datasource:n}});var i;const s=null!==(i=a.config.appSubUrl)&&void 0!==i?i:"";return o.urlUtil.renderUrl(`${s}/explore`,{panes:r,schemaVersion:1})}(_t.jh.getTimeRange(this).state.value.raw,this.getInterpolatedQuery(),_t.jh.interpolate(this,"${dataSource}"));window.open(e,"_blank")}getInterpolatedQuery(){var e;const t=null===(e=_t.jh.getAncestor(this,sa).state.body.state.$data)||void 0===e?void 0:e.state.$data,n=null==t?void 0:t.state.queries[0];return Object.entries(n).map((([e,t])=>[e,"string"==typeof t?_t.jh.interpolate(this,t):t])).reduce(((e,[t,n])=>oa(ra({},e),{[t]:n})),{})}useGetInvestigationPluginLinkContext(){const{refId:e,queryType:t,profileTypeId:n,labelSelector:r,groupBy:o}=this.getInterpolatedQuery(),a=Io(`${n}${r}`),i=[a.serviceId,ta(a.profileMetricId)];(null==o?void 0:o.length)&&i.push(o[0]),a.labels.length&&i.push(a.labels.join(", "));const s=i.join(" · "),l=_t.jh.interpolate(this,"${dataSource}"),c=_t.jh.getTimeRange(this).state.value;return(0,w.useMemo)((()=>({id:(0,zt.Ak)(),origin:"Grafana Profiles Drilldown",url:window.location.href,logoPath:Jo,title:s,type:"timeseries",timeRange:ra({},c),queries:[{refId:e,queryType:t,profileTypeId:n,labelSelector:r,groupBy:o}],datasource:l})),[l,o,r,n,t,e,c,s])}useUpdateMenuItems(){const e=function({extensionPointId:e,context:t,pluginId:n}){const r=(0,a.usePluginLinks)({extensionPointId:e,context:t}),[o]=r.links.filter((e=>e.pluginId===n));return o}({extensionPointId:"grafana-pyroscope-app/investigation/v1",context:this.useGetInvestigationPluginLinkContext(),pluginId:"grafana-investigations-app"});(0,w.useEffect)((()=>{e&&this.setState({items:this.buildMenuItems(e)})}),[e])}static Component({model:e}){return e.useUpdateMenuItems(),S().createElement(_t.Lw.Component,{model:e})}constructor(e){super(ra({scaleType:No.L4.Linear},e)),this.addActivationHandler(this.onActivate.bind(this))}}class sa extends _t.Bs{onActivate(){const{body:e}=this.state,t=e.state.$data.subscribeToState(((t,n)=>{var r,a,i,s;if((null===(r=t.data)||void 0===r?void 0:r.state)!==o.LoadingState.Done)return;!(null===(a=t.data.annotations)||void 0===a?void 0:a.length)&&(null===(s=n.data)||void 0===s||null===(i=s.annotations)||void 0===i?void 0:i.length)&&(t.data.annotations=n.data.annotations);const{series:l}=t.data;if(null==l?void 0:l.length){const t=this.state.displayAllValues?this.getAllValuesConfig(l):this.getConfig(l);e.setState((0,Bt.merge)({},e.state,t))}this.publishEvent(new Mt({series:l}),!0)}));return()=>{t.unsubscribe()}}getConfig(e){var t;const{body:n,item:r,legendPlacement:o}=this.state;let a,{title:i}=n.state;return(null===(t=r.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)&&(i=e.length>1?`${r.label} (${e.length})`:r.label,a=this.buildDescription(r.queryRunnerParams.groupBy)),{title:i,description:a,options:{tooltip:{mode:"single",sort:"none"},legend:{showLegend:!0,displayMode:"list",placement:o}},fieldConfig:{defaults:{min:0,custom:{fillOpacity:e.length>=Qo.MAX_TIMESERIES_LABEL_VALUES?0:9,gradientMode:1===e.length?No.on.None:No.on.Opacity,pointSize:3}},overrides:this.getOverrides(e)}}}buildDescription(e){return e?e.values?e.values.length>Qo.MAX_TIMESERIES_LABEL_VALUES?`Showing only ${Qo.MAX_TIMESERIES_LABEL_VALUES} out of ~${e.values.length} series to preserve readability. To view all the series for the current filters, click on the expand icon on this panel.`:"":`Showing only ${Qo.MAX_TIMESERIES_LABEL_VALUES} series to preserve readability. To view all the series, click on the expand icon on this panel.`:""}getAllValuesConfig(e){const{legendPlacement:t}=this.state;return{options:{tooltip:{mode:i.TooltipDisplayMode.Single,sort:No.xB.None},legend:{showLegend:!0,displayMode:i.LegendDisplayMode.List,placement:t,calcs:[]}},fieldConfig:{defaults:{min:0,custom:{fillOpacity:0,pointSize:5}},overrides:this.getOverrides(e)}}}getOverrides(e){var t;if(this.state.overrides)return this.state.overrides(e);const{item:n}=this.state,r=null===(t=n.queryRunnerParams.groupBy)||void 0===t?void 0:t.label;return e.map(((t,a)=>{const i=t.fields[1];let s=r?jo(i,r):i.name;return 1===e.length&&(s=Bo(s,t)),{matcher:{id:o.FieldMatcherID.byFrameRefID,options:t.refId},properties:[{id:"displayName",value:s},{id:"color",value:{mode:"fixed",fixedColor:ko(n.index+a)}}]}}))}updateItem(e){var t,n;const{item:r,headerActions:o,body:a}=this.state,i=(0,Bt.merge)({},r,e);if((null===(t=e.queryRunnerParams)||void 0===t?void 0:t.hasOwnProperty("groupBy"))&&(void 0===e.queryRunnerParams.groupBy?delete i.queryRunnerParams.groupBy:i.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy),(null===(n=e.queryRunnerParams)||void 0===n?void 0:n.hasOwnProperty("filters"))&&void 0===e.queryRunnerParams.filters&&delete i.queryRunnerParams.filters,this.setState({item:i}),a.setState({title:e.label,description:this.buildDescription(i.queryRunnerParams.groupBy),headerActions:o(i)}),!(0,Bt.isEqual)(r.queryRunnerParams,i.queryRunnerParams)){var s;const{queries:e}=Do(i.queryRunnerParams,Qo.MAX_TIMESERIES_LABEL_VALUES).state,t=null===(s=a.state.$data)||void 0===s?void 0:s.state.$data;null==t||t.setState({queries:e}),null==t||t.runQueries()}}changeScale(e,t){const{body:n}=this.state;n.clearFieldConfigCache(),n.setState({fieldConfig:(0,Bt.merge)({},n.state.fieldConfig,{defaults:{custom:{scaleDistribution:e,axisLabel:e.type!==No.L4.Linear?t:""}}})})}static Component({model:e}){const{body:t}=e.useState();return S().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,displayAllValues:n,legendPlacement:r,data:o,overrides:a}){super({key:"timeseries-label-values",item:e,headerActions:t,displayAllValues:Boolean(n),legendPlacement:r||"bottom",overrides:a,body:_t.d0.timeseries().setTitle(e.label).setData(o||new _t.Es({$data:Do(e.queryRunnerParams,n?void 0:Qo.MAX_TIMESERIES_LABEL_VALUES),transformations:[Lo,Fo]})).setHeaderActions(t(e)).setMenu(new ia({})).build()}),this.addActivationHandler(this.onActivate.bind(this))}}function la(e,t){switch(e){case To.BARGAUGE:return new $o(t);case To.TABLE:return new Uo(t);case To.HISTOGRAM:return new Mo(t);case To.TIMESERIES:default:return new sa(t)}}var ca=n(9488);const ua=n.p+"944c737f589d02ecf603.svg",da=n.p+"e79edcfbe2068fae2364.svg",pa=(e=50)=>{const[t,n]=(0,w.useState)({x:null,y:null});return(0,w.useEffect)((()=>{const t=(0,Bt.throttle)((e=>{n({x:e.clientX,y:e.clientY})}),e);return window.addEventListener("mousemove",t),()=>{window.removeEventListener("mousemove",t)}}),[e]),t},ma=({width:e="auto",height:t,show404:n=!1})=>{const r=(0,i.useTheme2)(),{x:o,y:a}=pa(),s=(0,i.useStyles2)(fa,o,a,n);return S().createElement(ca.A,{src:r.isDark?ua:da,className:s.svg,height:t,width:e})};ma.displayName="GrotNotFound";const fa=(e,t,n,o)=>{const{innerWidth:a,innerHeight:i}=window,s=n&&n/i,l=t&&t/a,c=null!==s?ha(s,-20,5):0,u=null!==l?ha(l,-5,5):0;return{svg:(0,r.css)({"#grot-404-arm, #grot-404-magnifier":{transform:`rotate(${c}deg) translateX(${u}%)`,transformOrigin:"center",transition:"transform 50ms linear"},"#grot-404-text":{display:o?"block":"none"}})}},ha=(e,t,n)=>e*(n-t)+t,ga=({message:e})=>{const t=(0,i.useStyles2)(ya);return S().createElement("div",{className:t.container},S().createElement(i.Box,{paddingY:8},S().createElement(i.Stack,{direction:"column",alignItems:"center",gap:3},S().createElement(ma,{width:300}),S().createElement(i.Text,{variant:"h5"},e))))};function ya(){return{container:(0,r.css)({width:"100%",display:"flex",justifyContent:"space-evenly",flexDirection:"column"})}}ga.displayName="EmptyState";class ba extends _t.Bs{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ba,"Component",(({model:e})=>{const{message:t}=e.useState();return S().createElement(ga,{message:t})}));class va extends _t.Bs{}function Ea(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(va,"Component",(({model:e})=>{const{message:t}=e.useState();return S().createElement(i.Alert,{title:"Query error!",severity:"error"},t)}));var wa=function(e){return e.GRID="grid",e.ROWS="rows",e}({});class Sa extends _t.Bs{getUrlState(){return{layout:this.state.layout}}updateFromUrl(e){const t={};"string"==typeof e.layout&&e.layout!==this.state.layout&&(t.layout=Object.values(wa).includes(e.layout)?e.layout:Sa.DEFAULT_LAYOUT),this.setState(t)}constructor(){super({key:"layout-switcher",layout:Sa.DEFAULT_LAYOUT}),Ea(this,"_urlSync",new _t.So(this,{keys:["layout"]})),Ea(this,"onChange",(e=>{Re("g_pyroscope_app_layout_changed",{layout:e}),this.setState({layout:e})}))}}function Oa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Ea(Sa,"OPTIONS",[{label:"Grid",value:"grid"},{label:"Rows",value:"rows"}]),Ea(Sa,"DEFAULT_LAYOUT","grid"),Ea(Sa,"Component",(({model:e})=>{const{layout:t}=e.useState();return S().createElement(i.RadioButtonGroup,{"aria-label":"Layout switcher",options:Sa.OPTIONS,value:t,onChange:e.onChange,fullWidth:!1})}));class Pa extends _t.Bs{getUrlState(){return{hideNoData:this.state.hideNoData}}updateFromUrl(e){const t={};"string"==typeof e.hideNoData&&e.hideNoData!==this.state.hideNoData&&(t.hideNoData=["on","off"].includes(e.hideNoData)?e.hideNoData:Pa.DEFAULT_VALUE),this.setState(t)}constructor(){super({key:"no-data-switcher",hideNoData:Pa.DEFAULT_VALUE}),Oa(this,"_urlSync",new _t.So(this,{keys:["hideNoData"]})),Oa(this,"onChange",(e=>{Re("g_pyroscope_app_hide_no_data_changed",{hideNoData:e}),this.setState({hideNoData:e})}))}}function xa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Oa(Pa,"DEFAULT_VALUE","off"),Oa(Pa,"Component",(({model:e})=>{const{hideNoData:t}=e.useState();return S().createElement(i.InlineSwitch,{"data-testid":"noDataSwitcher",showLabel:!0,label:"Hide panels without data",value:"on"===t,onChange:t=>e.onChange(t.target.checked?"on":"off")})}));class Ta extends _t.Bs{setPlaceholder(e){this.setState({placeholder:e})}setResultsCount(e){this.setState({resultsCount:String(e)})}getUrlState(){return{searchText:this.state.searchText}}updateFromUrl(e){const t={};"string"==typeof e.searchText&&e.searchText!==this.state.searchText&&(t.searchText=e.searchText),this.setState(t)}reset(){this.setState({placeholder:"",searchText:"",resultsCount:""})}constructor({placeholder:e}){super({key:"quick-filter",placeholder:e,searchText:Ta.DEFAULT_SEARCH_TEXT,resultsCount:""}),xa(this,"_urlSync",new _t.So(this,{keys:["searchText"]})),xa(this,"onChange",(e=>{this.setState({searchText:e.target.value})})),xa(this,"clearSearchText",(()=>{this.setState({searchText:""})})),xa(this,"onFocus",(()=>{Re("g_pyroscope_app_quick_filter_focused")}))}}xa(Ta,"DEFAULT_SEARCH_TEXT",""),xa(Ta,"DEBOUNCE_DELAY",250),xa(Ta,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Ca),{placeholder:n,searchText:r,resultsCount:o}=e.useState();return S().createElement(i.Input,{type:"text",className:"quick-filter","aria-label":"Quick filter",placeholder:n,value:r,prefix:S().createElement(i.Icon,{name:"search"}),suffix:S().createElement(S().Fragment,null,""!==o&&S().createElement(i.Tag,{className:t.resultsCount,name:o,colorIndex:9,"data-testid":"quick-filter-results-count"}),S().createElement(i.IconButton,{name:"times","aria-label":"Clear search",onClick:e.clearSearchText})),onChange:e.onChange,onKeyDown:t=>{"Escape"===t.key&&e.clearSearchText()},onFocus:e.onFocus})}));const Ca=e=>({resultsCount:r.css` margin-right: ${e.spacing(1)}; border-radius: 11px; padding: 2px 8px; color: ${e.colors.text.primary}; background-color: ${e.colors.background.secondary}; `});function Na(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ka(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Na(a,r,o,i,s,"next",e)}function s(e){Na(a,r,o,i,s,"throw",e)}i(void 0)}))}}function ja(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Aa(e){for(var t=1;tIa.areFavoritesEqual(t,e)))}static addFavorite(e){const t=D.get(D.KEYS.PROFILES_EXPLORER);t.favorites.push(e),D.set(D.KEYS.PROFILES_EXPLORER,t)}static removeFavorite(e){const t=D.get(D.KEYS.PROFILES_EXPLORER);t.favorites=t.favorites.filter((t=>!Ia.areFavoritesEqual(t,e))),D.set(D.KEYS.PROFILES_EXPLORER,t)}query(){return ka((function*(){return{state:o.LoadingState.Done,data:[{name:"Favories",fields:[{name:null,type:o.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(){return ka((function*(){return Ia.getAllFavorites().map((e=>{const{serviceName:t,profileMetricId:n,groupBy:r,filters:o}=e.queryRunnerParams||{},a=[t,ta(n)];return(null==r?void 0:r.label)&&a.push(r.label),(null==o?void 0:o.length)&&a.push(o.map((({key:e,operator:t,value:n})=>`${e}${t}"${n}"`)).join(", ")),{value:JSON.stringify(Aa({value:JSON.stringify(e)},e)),text:a.join(" · ")}}))}))()}testDatasource(){return ka((function*(){return{status:"success",message:"OK"}}))()}constructor(){var e;super(Zr.type,Zr.uid);const t=D.get(D.KEYS.PROFILES_EXPLORER)||{};(e=t).favorites||(e.favorites=[]),t.favorites=t.favorites.map((e=>Aa({panelType:To.TIMESERIES},e))),D.set(D.KEYS.PROFILES_EXPLORER,t)}}function Ra(e,t){const{queryRunnerParams:n}=t,r=(0,Bt.defaults)((0,Bt.clone)(n),{serviceName:Po(e,"serviceName"),profileMetricId:Po(e,"profileMetricId")}),o=_t.jh.lookupVariable("filters",e).state.filters.map((({key:e,operator:t,value:n})=>({key:e,operator:t,value:n})));return r.filters=(0,Bt.uniqBy)([...r.filters||[],...o],(({key:e,operator:t,value:n})=>`${e}${t}${n}`)),r}function _a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Da extends _t.Bs{update(){this.setState({isFav:this.isStored()})}isStored(){return Ia.exists(this.buildFavorite())}static buildFavorite(e){var t;const{index:n,queryRunnerParams:r,panelType:o}=e,a={index:n,queryRunnerParams:{serviceName:r.serviceName,profileMetricId:r.profileMetricId},panelType:o};return r.groupBy&&(a.queryRunnerParams.groupBy={label:r.groupBy.label}),(null===(t=r.filters)||void 0===t?void 0:t.length)&&(a.queryRunnerParams.filters=r.filters),a}buildFavorite(){const{item:e,skipVariablesInterpolation:t}=this.state;return Da.buildFavorite({index:e.index,queryRunnerParams:t?e.queryRunnerParams:Ra(this,e),panelType:e.panelType})}constructor(e){super(e),_a(this,"_variableDependency",new _t.Sh(this,{variableNames:["serviceName","profileMetricId","filters"],onReferencedVariableValueChanged:()=>{this.update()}})),_a(this,"onClick",(()=>{Re("g_pyroscope_app_fav_action_clicked",{favAfterClick:!this.state.isFav}),this.state.isFav?Ia.removeFavorite(this.buildFavorite()):Ia.addFavorite(this.buildFavorite()),this.setState({isFav:!this.state.isFav})})),this.addActivationHandler((()=>this.update()))}}_a(Da,"Component",(({model:e})=>{const t=(0,i.useStyles2)(La),{isFav:n}=e.useState();return S().createElement(i.IconButton,{className:n?t.favedButton:t.notFavedbutton,name:n?"favorite":"star",variant:"secondary",size:"sm","aria-label":n?"Unfavorite":"Favorite",tooltip:n?"Unfavorite":"Favorite",tooltipPlacement:"top",onClick:e.onClick})}));const La=()=>({favedButton:r.css` color: #f2cc0d; margin: 0; `,notFavedbutton:r.css` margin: 0; `}),Fa=function(e,t){const n=Ia.exists(Da.buildFavorite(e)),r=Ia.exists(Da.buildFavorite(t));return n&&r?br(e.label,t.label):r?1:n?-1:0},$a="240px";class Ba extends _t.Bs{static buildGridItemKey(e){return`grid-item-${e.index}-${e.value}`}static getGridColumnsTemplate(e){return e===wa.ROWS?"1fr":"repeat(auto-fit, minmax(400px, 1fr))"}onActivate(){const e=_t.jh.lookupVariable(this.state.variableName,this),t=e.subscribeToState(((e,t)=>{!e.loading&&t.loading&&this.renderGridItems()}));e.update();const n=this.subscribeToRefreshClick(),r=this.subscribeToQuickFilterChange(),o=this.subscribeToLayoutChange(),a=this.subscribeToHideNoDataChange(),i=this.subscribeToFiltersChange();return()=>{i.unsubscribe(),a.unsubscribe(),o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe()}}subscribeToRefreshClick(){const e=_t.jh.lookupVariable(this.state.variableName,this),t=e.state.refresh;e.setState({refresh:o.VariableRefresh.never});const n=()=>{e.update()},r=document.querySelector('[data-testid="data-testid RefreshPicker run button"]');return r||A.error(new Error("SceneByVariableRepeaterGrid: Refresh button not found! The list of items will never be updated.")),null==r||r.addEventListener("click",n),null==r||r.setAttribute("title","Click to completely refresh all the panels present on the screen"),{unsubscribe(){null==r||r.removeAttribute("title"),null==r||r.removeEventListener("click",n),e.setState({refresh:t})}}}subscribeToQuickFilterChange(){const e=_t.jh.findByKeyAndType(this,"quick-filter",Ta);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,Bt.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),Ta.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=_t.jh.findByKeyAndType(this,"layout-switcher",Sa),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:Ba.getGridColumnsTemplate(e.layout)})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=_t.jh.findByKeyAndType(this,"no-data-switcher",Pa);if(!e.isActive)return this.setState({hideNoData:!1}),{unsubscribe:L};const t=(e,t)=>{e.hideNoData!==(null==t?void 0:t.hideNoData)&&(this.setState({hideNoData:"on"===e.hideNoData}),this.renderGridItems(!0))};return t(e.state),e.subscribeToState(t)}subscribeToFiltersChange(){const e=_t.jh.findByKeyAndType(this,"filters",Oo),t=_t.jh.findByKeyAndType(this,"no-data-switcher",Pa);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.renderGridItems(!0)}))}buildItemsData(e){const{mapOptionToItem:t}=this.state,n={serviceName:Po(this,"serviceName"),profileMetricId:Po(this,"profileMetricId"),panelType:_t.jh.findByKeyAndType(this,"panel-type-switcher",Co).state.panelType},r=e.state.options.map(((e,r)=>t(e,r,n))).filter(Boolean);return this.filterItems(r).sort(this.state.sortItemsFn)}shouldRenderItems(e){const{items:t}=this.state;return!e.length||t.length!==e.length||!(0,Bt.isEqual)(t,e)}renderGridItems(e=!1){const t=_t.jh.lookupVariable(this.state.variableName,this);if(t.state.loading)return;if(t.state.error)return void this.renderErrorState(t.state.error);const n=this.buildItemsData(t);if(!e&&!this.shouldRenderItems(n))return;if(this.setState({items:n}),!this.state.items.length)return void this.renderEmptyState();const r=this.state.items.map((e=>{const t=la(e.panelType,{item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)});return this.state.hideNoData&&this.setupHideNoData(t),new _t.xK({key:Ba.buildGridItemKey(e),body:t})}));this.state.body.setState({autoRows:$a,children:r})}setupHideNoData(e){const t=e.subscribeToEvent(Mt,(t=>{var n;if(null===(n=t.payload.series)||void 0===n?void 0:n.length)return;const r=_t.jh.getAncestor(e,_t.xK),{key:o}=r.state,a=_t.jh.getAncestor(r,_t.gF),i=a.state.children.filter((e=>e.state.key!==o));i.length?a.setState({children:i}):this.renderEmptyState()}));e.addActivationHandler((()=>()=>{t.unsubscribe()}))}filterItems(e){const t=_t.jh.findByKeyAndType(this,"quick-filter",Ta),{searchText:n}=t.state;if(!n)return e;const r=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{try{return new RegExp(e)}catch(e){return null}})).filter(Boolean);return e.filter((({label:e})=>r.some((t=>t.test(e)))))}renderEmptyState(){this.state.body.setState({autoRows:"480px",children:[new _t.xK({body:new ba({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new _t.xK({body:new va({message:e.message||e.toString()})})]})}static Component({model:e}){var t;const{body:n,variableName:r}=e.useState(),{loading:o}=null===(t=_t.jh.lookupVariable(r,e))||void 0===t?void 0:t.useState();return o?S().createElement(i.Spinner,null):S().createElement(n.Component,{model:n})}constructor({key:e,variableName:t,headerActions:n,mapOptionToItem:r,sortItemsFn:a}){super({key:e,variableName:t,items:[],headerActions:n,mapOptionToItem:r,sortItemsFn:a||Fa,hideNoData:!1,body:new _t.gF({templateColumns:Ba.getGridColumnsTemplate(Sa.DEFAULT_LAYOUT),autoRows:$a,isLazy:!0,$behaviors:[new _t.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class Ma extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ma,"type","expand-panel");class Ua extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ua,"type","select-label");class Va extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Va,"type","view-service-flame-graph");class qa extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(qa,"type","view-service-labels");class Ga extends o.BusEventWithPayload{}function Ka(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ha(e){for(var t=1;t"Expand this panel to view all the data for the current filters",EventConstructor:Ma})],["select-label",Object.freeze({label:"Select",tooltip:({queryRunnerParams:e})=>{var t;return`View "${null===(t=e.groupBy)||void 0===t?void 0:t.label}" values breakdown`},EventConstructor:Ua})],["view-flame-graph",Object.freeze({label:"Flame graph",tooltip:({queryRunnerParams:e},t)=>{const n=e.serviceName||Po(t,"serviceName");return`View the "${Wr(e.profileMetricId||Po(t,"profileMetricId")).type}" flame graph of ${n}`},EventConstructor:Va})],["view-labels",Object.freeze({label:"Labels",tooltip:({queryRunnerParams:e},t)=>`Explore the labels of ${e.serviceName||Po(t,"serviceName")}`,EventConstructor:qa})],["view-profiles",Object.freeze({label:"Profile types",tooltip:({queryRunnerParams:e},t)=>`View the profile types of ${e.serviceName||Po(t,"serviceName")}`,EventConstructor:Ga})]]);class Wa extends _t.Bs{buildEvent(){const{EventConstructor:e,item:t,skipVariablesInterpolation:n}=this.state;return new e({item:za(Ha({},t),{queryRunnerParams:n?t.queryRunnerParams:Ra(this,t)})})}constructor({type:e,item:t,tooltip:n,skipVariablesInterpolation:r}){const o=Ya.get(e);if(!o)throw new TypeError(`Unknown event type="${e}"!`);super(Ha({type:e,item:t},(0,Bt.merge)({},o,{tooltip:n,skipVariablesInterpolation:r}))),Ka(this,"onClick",(()=>{Re("g_pyroscope_app_select_action_clicked",{type:this.state.type}),this.publishEvent(this.buildEvent(),!0)}))}}Ka(Wa,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Qa),{ariaLabel:n,label:r,icon:o,tooltip:a,item:s}=e.useState();return S().createElement(i.Button,{className:t.selectButton,"aria-label":n||r,variant:"primary",size:"sm",fill:"text",onClick:e.onClick,icon:o,tooltip:null==a?void 0:a(s,e),tooltipPlacement:"top"},r)}));const Qa=()=>({selectButton:r.css` margin: 0; padding: 0; `});class Ja extends _t.Bs{onActivate(){_t.jh.findByKeyAndType(this,"quick-filter",Ta).setPlaceholder("Search services (comma-separated regexes are supported)")}getVariablesAndGridControls(){return{variables:[_t.jh.findByKeyAndType(this,"profileMetricId",ro)],gridControls:[_t.jh.findByKeyAndType(this,"quick-filter",Ta),_t.jh.findByKeyAndType(this,"layout-switcher",Sa)]}}static Component({model:e}){const{body:t}=e.useState();return S().createElement(t.Component,{model:t})}constructor(){super({key:"explore-all-services",$variables:new _t.Pj({variables:[new so({query:so.QUERY_PROFILE_METRIC_DEPENDENT,skipUrlSync:!0})]}),body:new Ba({key:"all-services-grid",variableName:"serviceName",mapOptionToItem:(e,t,{profileMetricId:n})=>({index:t,value:e.value,label:e.label,queryRunnerParams:{serviceName:e.value,profileMetricId:n},panelType:To.TIMESERIES}),headerActions:e=>[new Wa({type:"view-profiles",item:e}),new Wa({type:"view-labels",item:e}),new Wa({type:"view-flame-graph",item:e}),new Da({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this))}}function Xa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Za(e){for(var t=1;t{this.setState(ei(Za({},this.state),{isOpen:!0,title:e,subTitle:t,body:n}))})),Xa(this,"close",(()=>{this.setState({isOpen:!1})}))}}function ni(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}Xa(ti,"Component",(({model:e})=>{const{isOpen:t,title:n,subTitle:r,body:o}=e.useState();return S().createElement(S().Fragment,null,o&&t&&S().createElement(i.Drawer,{size:"lg",title:n,subtitle:r,closeOnMaskClick:!0,onClose:e.close},S().createElement(o.Component,{model:o})))}));class ri extends _t.fS{update(){var e,t=this;return(e=function*(){if(t.state.loading)return;let e=[],n=null;t.setState({loading:!0,options:[],error:null});try{e=yield(0,Qr.lastValueFrom)(t.getValueOptions({}))}catch(e){n=e}finally{t.setState({loading:!1,options:e,error:n})}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ni(a,r,o,i,s,"next",e)}function s(e){ni(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(){super({name:"favorite",label:"🔖 Favorite",datasource:Zr,query:"$dataSource",loading:!0,refresh:o.VariableRefresh.never,skipUrlSync:!0})}}function oi(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class ai extends _t.Bs{onActivate(){_t.jh.findByKeyAndType(this,"quick-filter",Ta).setPlaceholder("Search favorites (comma-separated regexes are supported)");var e=this;const t=this.subscribeToEvent(Ma,function(){var t,n=(t=function*(t){e.openExpandedPanelDrawer(t.payload.item)},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){oi(a,r,o,i,s,"next",e)}function s(e){oi(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}());return()=>{t.unsubscribe()}}getVariablesAndGridControls(){return{variables:[],gridControls:[_t.jh.findByKeyAndType(this,"quick-filter",Ta),_t.jh.findByKeyAndType(this,"layout-switcher",Sa),_t.jh.findByKeyAndType(this,"no-data-switcher",Pa)]}}openExpandedPanelDrawer(e){this.state.drawer.open({title:e.label,body:la(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:e,headerActions:()=>[new Wa({type:"view-labels",item:e}),new Wa({type:"view-flame-graph",item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return S().createElement(S().Fragment,null,S().createElement(t.Component,{model:t}),S().createElement(n.Component,{model:n}))}constructor(){super({key:"explore-favorites",$variables:new _t.Pj({variables:[new ri]}),body:new Ba({key:"favorites-grid",variableName:"favorite",mapOptionToItem:e=>{const{index:t,value:n,panelType:r,queryRunnerParams:o}=JSON.parse(e.value);return{index:t,value:n,label:e.label,queryRunnerParams:o,panelType:r}},sortItemsFn:(e,t)=>br(e.label,t.label),headerActions:e=>{const t=[new Wa({type:"view-labels",item:e,skipVariablesInterpolation:!0}),new Wa({type:"view-flame-graph",item:e,skipVariablesInterpolation:!0})];return e.queryRunnerParams.groupBy&&t.push(new Wa({type:"expand-panel",item:e,tooltip:()=>"Expand panel to view all the data",skipVariablesInterpolation:!0})),t.push(new Da({item:e,skipVariablesInterpolation:!0})),t}}),drawer:new ti}),this.addActivationHandler(this.onActivate.bind(this))}}var ii=n(5540);function si({options:e,mainLabels:t,value:n,onChange:r,onRefresh:o}){const a=(0,i.useStyles2)(li),s=(0,i.useTheme2)(),[l,c]=(0,w.useState)(0),[u,d]=(0,w.useState)(0),p=u>l,m=(0,w.useRef)(null);(0,ii.w)({ref:m,onResize:()=>{const e=m.current;e&&d(e.clientWidth)}});const f=e.filter((e=>t.includes(e.value))),h=e.filter((e=>!t.includes(e.value)));return(0,w.useEffect)((()=>{const{fontSize:e}=s.typography,t=f.map((e=>e.label||e.text||"")).join(" "),n=(0,i.measureText)(t,e).width;c(n+70*f.length)}),[f,s]),S().createElement(i.Field,{label:"Group by labels"},S().createElement("div",{ref:m,className:a.container},p?S().createElement(S().Fragment,null,S().createElement(i.RadioButtonGroup,{"aria-label":"Labels selector",options:f,value:n,onChange:r}),S().createElement(i.Select,{"aria-label":"Other labels selector",className:a.select,placeholder:"Other labels",options:h,value:n&&h.some((e=>e.value===n))?n:null,onChange:e=>{var t;return r(null!==(t=null==e?void 0:e.value)&&void 0!==t?t:"all")},isClearable:!0})):S().createElement(i.Select,{"aria-label":"Labels selector",className:a.select,value:n,placeholder:"Select label",options:e,onChange:e=>r((null==e?void 0:e.value)||pi.DEFAULT_VALUE),isClearable:!0}),S().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:o,isOnCanvas:!1,onIntervalChanged:L,tooltip:"Click to refresh all labels"})))}const li=e=>({container:r.css` display: flex; gap: ${e.spacing(1)}; `,select:r.css` max-width: ${e.spacing(22)}; `});function ci(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ui(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ci(a,r,o,i,s,"next",e)}function s(e){ci(a,r,o,i,s,"throw",e)}i(void 0)}))}}function di(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class pi extends _t.fS{onActivate(){this.state.value||this.setState({value:pi.DEFAULT_VALUE})}findCurrentOption(){const{value:e}=this.state,t=this.state.options.filter((e=>"all"!==e.value)).find((t=>JSON.parse(t.value).value===e));if(t){const e=JSON.parse(t.value);return{index:e.index,value:e.value,label:e.value,groupBy:e.groupBy}}return{index:0,value:e,label:e,groupBy:void 0}}constructor(){var e;super({key:"groupBy",name:"groupBy",label:"Group by labels",datasource:eo,query:'$dataSource and $profileMetricId{service_name="$serviceName"}',loading:!0}),e=this,di(this,"update",ui((function*(){if(e.state.loading)return;let t=[],n=null;e.setState({loading:!0,options:[],error:null});try{t=yield(0,Qr.lastValueFrom)(e.getValueOptions({}))}catch(e){n=e}finally{e.setState({loading:!1,options:t,error:n})}}))),di(this,"onChange",(e=>{Re("g_pyroscope_app_group_by_label_clicked"),Dt(),this.changeValueTo(e)})),this.changeValueTo=this.changeValueTo.bind(this),this.addActivationHandler(this.onActivate.bind(this))}}di(pi,"DEFAULT_VALUE","all"),di(pi,"MAX_MAIN_LABELS",8),di(pi,"Component",(({model:e})=>{const t=(0,i.useStyles2)(mi),{loading:n,value:r,options:o,error:a}=e.useState(),s=(0,w.useMemo)((()=>o.map((({label:e,value:t})=>"all"===t?{label:e,value:t}:{label:e,value:JSON.parse(String(t)).value}))),[o]);if(n)return S().createElement(i.Field,{label:"Group by labels"},S().createElement(i.Spinner,{className:t.spinner}));if(a)return S().createElement(i.Field,{label:"Group by labels"},S().createElement("div",{className:t.groupByErrorContainer},S().createElement(i.Tooltip,{theme:"error",content:a.toString()},S().createElement(i.Icon,{className:t.iconError,name:"exclamation-triangle",size:"xl"})),S().createElement(i.RefreshPicker,{noIntervalPicker:!0,onRefresh:e.update,isOnCanvas:!1,onIntervalChanged:L})));return S().createElement(si,{options:s,value:r,mainLabels:(e=>e.slice(0,pi.MAX_MAIN_LABELS).map((({value:e})=>e)))(s),onChange:e.onChange,onRefresh:e.update})}));const mi=e=>({spinner:r.css` height: 32px; line-height: 32px; `,groupByErrorContainer:r.css` display: flex; `,iconError:r.css` height: 32px; align-self: center; color: ${e.colors.error.text}; `});function fi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class hi extends _t.Bs{onActivate(e,t){e&&this.initVariables(e),this.setState({body:this.buildTimeseries(e,t)}),t&&this.subscribeToGroupByStateChanges(e)}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){_t.jh.findByKeyAndType(this,"serviceName",so).changeValueTo(t)}if(n){_t.jh.findByKeyAndType(this,"profileMetricId",ro).changeValueTo(n)}if(r){_t.jh.findByKeyAndType(this,"filters",Oo).setState({filters:r})}}buildTimeseries(e,t){const{headerActions:n}=this.state,r={index:0,value:"",queryRunnerParams:{},label:this.buildTitle(),panelType:To.TIMESERIES};e&&t&&(r.queryRunnerParams.groupBy=e.queryRunnerParams.groupBy);const o=_t.jh.findByKeyAndType(this,"groupBy",pi).state.value;return new sa({item:r,headerActions:n,data:!e&&t&&o&&"all"!==o?new _t.Es({$data:new _t.dt({datasource:Jr,queries:[]}),transformations:[Lo,Fo]}):void 0})}subscribeToGroupByStateChanges(e){const t=_t.jh.findByKeyAndType(this,"groupBy",pi);this._subs.add(t.subscribeToState(((n,r)=>{!n.loading&&n.options.length&&(e||!r.loading?n.value!==r.value&&this.onGroupByChanged(t):this.onGroupByChanged(t))})))}onGroupByChanged(e){var t;if(!e.state.value||"all"===e.state.value)return void this.resetTimeseries();const{index:n,value:r,groupBy:o}=e.findCurrentOption();null===(t=this.state.body)||void 0===t||t.updateItem({index:n,label:`${this.buildTitle()}, grouped by ${r}`,queryRunnerParams:{groupBy:o}})}resetTimeseries(e=!1){var t;e&&_t.jh.findByKeyAndType(this,"filters",Oo).reset(),null===(t=this.state.body)||void 0===t||t.updateItem({index:0,label:this.buildTitle(),queryRunnerParams:{groupBy:void 0}})}buildTitle(){const e=Po(this,"profileMetricId"),{description:t}=Wr(e);return t||ta(e)}static Component({model:e}){const{body:t}=e.useState();return t&&S().createElement(t.Component,{model:t})}constructor({item:e,headerActions:t,supportGroupBy:n}){super({headerActions:t,body:void 0}),fi(this,"_variableDependency",new _t.Sh(this,{variableNames:["serviceName","profileMetricId"],onReferencedVariableValueChanged:e=>{this.resetTimeseries("serviceName"===e.state.name)}})),this.addActivationHandler(this.onActivate.bind(this,e,n))}}fi(hi,"MIN_HEIGHT",240);class gi extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(gi,"type","view-diff-flame-graph");class yi extends o.BusEventWithPayload{}function bi({option:e,checked:t,onChange:n}){var o;const a=(0,i.useStyles2)(vi),[s,l]=(0,w.useState)(!1),c=(0,w.useRef)(null),u=null===(o=c.current)||void 0===o?void 0:o.closest("label");return(0,w.useEffect)((()=>{if(!u||t)return void l(!1);const e=()=>{l(!0)},n=()=>{l(!1)};return u.addEventListener("mouseenter",e),u.addEventListener("mouseleave",n),()=>{u.removeEventListener("mouseleave",n),u.removeEventListener("mouseenter",e)}}),[t,u]),S().createElement(S().Fragment,null,S().createElement(i.Tooltip,{content:e.description,show:!t&&s,placement:"top"},S().createElement("span",{className:a.tooltipAnchor})),S().createElement(i.Checkbox,{ref:c,className:(0,r.cx)(a.checkbox,"checkbox",t&&"checked"),checked:t,label:e.label,onChange:()=>n(e.value)}))}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(yi,"type","select-for-compare");const vi=e=>({tooltipAnchor:r.css` position: relative; left: 42px; `,checkbox:r.css` column-gap: 4px; &:last-child { & :nth-child(1) { grid-column-start: 2; } & :nth-child(2) { grid-column-start: 1; } } span { color: ${e.colors.text.secondary}; } span:hover { color: ${e.colors.text.primary}; } &.checked span { color: ${e.colors.text.primary}; } `});function Ei({item:e,itemStats:t,statsDescription:n,compareActionChecks:r,onChangeCompareTarget:a}){const s=(0,i.useStyles2)(wi),{index:l,value:c}=e,u=ko(l),d=(0,w.useMemo)((()=>{if(!t)return S().createElement(i.Spinner,{inline:!0});const{allValuesSum:e,unit:n}=t,{text:r,suffix:a}=(0,o.getValueFormat)(n)(e);return`${r}${a}`}),[t]),p=(0,w.useMemo)((()=>[{label:"Baseline",value:lt.BASELINE,description:r[0]?"":`Click to select "${c}" as baseline for comparison`},{label:"Comparison",value:lt.COMPARISON,description:r[1]?"":`Click to select "${c}" as target for comparison`}]),[r,c]);return S().createElement("div",{className:s.container,"data-testid":`stats-panel-${c}`},S().createElement("h1",{style:{color:u},className:s.title,title:`${n}: ${d}`},d),S().createElement("div",{className:s.compareActions},S().createElement(bi,{option:p[0],checked:r[0],onChange:a}),S().createElement(bi,{option:p[1],checked:r[1],onChange:a})))}const wi=e=>({container:r.css` display: flex; flex-direction: column; justify-content: space-between; width: 100%; background-color: ${e.colors.background.canvas}; padding: ${e.spacing(1)}; border: 1px solid ${e.colors.border.weak}; border-right: none; border-radius: 2px 0 0 2px; `,title:r.css` font-size: 24px; width: 100%; text-align: center; margin-top: ${e.spacing(5)}; `,compareActions:r.css` display: flex; justify-content: space-between; font-size: 11px; border-top: 1px solid ${e.colors.border.weak}; padding: ${e.spacing(1)} 0 0 0; & .checkbox:nth-child(2) { padding-right: 4px; border-right: 1px solid ${e.colors.border.strong}; } & .checkbox:nth-child(4) { padding-left: 4px; } `});function Si(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Oi extends _t.Bs{onActivate(){const e=_t.jh.findByKeyAndType(this,"group-by-labels",Ui).getCompare();this.updateCompareActions(e.get(lt.BASELINE),e.get(lt.COMPARISON)),this.setState({statsDescription:this.getStatsDescription()})}updateCompareActions(e,t){const{item:n}=this.state;this.setState({compareActionChecks:[(null==e?void 0:e.value)===n.value,(null==t?void 0:t.value)===n.value]})}getStatsDescription(){const e=Po(this,"profileMetricId"),{description:t}=Wr(e);return t||ta(e)}getStats(){return this.state.itemStats}updateStats(e){this.setState({itemStats:e})}static Component({model:e}){const{item:t,itemStats:n,statsDescription:r,compareActionChecks:o}=e.useState();return S().createElement(Ei,{item:t,itemStats:n,statsDescription:r,compareActionChecks:o,onChangeCompareTarget:e.onChangeCompareTarget})}constructor({item:e}){super({item:e,itemStats:void 0,compareActionChecks:[!1,!1],statsDescription:""}),Si(this,"onChangeCompareTarget",(e=>{this.publishEvent(new yi({compareTarget:e,item:this.state.item}),!0)})),this.addActivationHandler(this.onActivate.bind(this))}}Si(Oi,"WIDTH_IN_PIXELS",186);class Pi extends _t.Bs{static buildPanelKey(e){return`compare-panel-${e.value}`}onActivate(){const{statsPanel:e,timeseriesPanel:t}=this.state,n=t.subscribeToEvent(Mt,(t=>{var n,r;const o=null===(n=t.payload.series)||void 0===n?void 0:n[0];if(!o)return void e.updateStats({allValuesSum:0,unit:"short"});const a=Ao(o,"allValuesSum")||0;(null===(r=e.getStats())||void 0===r?void 0:r.allValuesSum)!==a&&e.updateStats({allValuesSum:a,unit:o.fields[1].config.unit||"short"})}));return()=>{n.unsubscribe()}}static Component({model:e}){const t=(0,i.useStyles2)(xi),{statsPanel:n,timeseriesPanel:o}=e.useState(),{compareActionChecks:a}=n.useState(),s=a[0]||a[1];return S().createElement("div",{className:(0,r.cx)(t.container,s&&"selected")},S().createElement("div",{className:t.statsPanel},S().createElement(n.Component,{model:n})),S().createElement("div",{className:t.timeseriesPanel},S().createElement(o.Component,{model:o})))}constructor({item:e,headerActions:t}){super({key:"label-value-panel",statsPanel:new Oi({item:e}),timeseriesPanel:new sa({item:e,headerActions:t})}),this.addActivationHandler(this.onActivate.bind(this))}}const xi=e=>({container:r.css` display: flex; min-width: 0px; min-height: ${Ci}; flex-flow: row; box-sizing: border-box; border: 1px solid transparent; &.selected { border: 1px solid ${e.colors.primary.main}; } & > div { display: flex; position: relative; flex-direction: row; align-self: stretch; min-height: ${Ci}; } `,statsPanel:r.css` width: ${Oi.WIDTH_IN_PIXELS}px; `,timeseriesPanel:r.css` flex-grow: 1; & [data-viz-panel-key] > * { border-top-left-radius: 0; border-bottom-left-radius: 0; } `});function Ti({label:e}){const t='service_name="$serviceName"';return new _t.dt({datasource:Jr,queries:[{refId:`$profileMetricId-${t}-${e}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{${t}}`,groupBy:[e]}]})}const Ci="160px";class Ni extends _t.Bs{static buildGridItemKey(e){return`grid-item-${e.index}-${e.value}`}onActivate(){this.subscribeOnceToDataChange();const e=this.subscribeToGroupByChange(),t=this.subscribeToRefreshClick(),n=this.subscribeToQuickFilterChange(),r=this.subscribeToLayoutChange(),o=this.subscribeToHideNoDataChange(),a=this.subscribeToFiltersChange();return()=>{a.unsubscribe(),o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe()}}subscribeOnceToDataChange(e=!1){const t=this.state.$data.subscribeToState((n=>{var r;(null===(r=n.data)||void 0===r?void 0:r.state)!==o.LoadingState.Loading&&(t.unsubscribe(),this.renderGridItems(e),this.setState({isLoading:!1}))}))}subscribeToGroupByChange(){return _t.jh.findByKeyAndType(this,"groupBy",pi).subscribeToState(((e,t)=>{!e.loading&&t.loading&&this.refetchData()}))}subscribeToRefreshClick(){const e=()=>{this.refetchData()},t=document.querySelector('[data-testid="data-testid RefreshPicker run button"]');return t||A.error(new Error("SceneByVariableRepeaterGrid: Refresh button not found! The list of items will never be updated.")),null==t||t.addEventListener("click",e),null==t||t.setAttribute("title","Click to completely refresh all the panels present on the screen"),{unsubscribe(){null==t||t.removeAttribute("title"),null==t||t.removeEventListener("click",e)}}}subscribeToQuickFilterChange(){const e=_t.jh.findByKeyAndType(this,"quick-filter",Ta);this.subscribeToState(((t,n)=>{t.items.length!==n.items.length&&e.setResultsCount(t.items.length)}));return e.subscribeToState((0,Bt.debounce)(((e,t)=>{e.searchText!==(null==t?void 0:t.searchText)&&this.renderGridItems()}),Ta.DEBOUNCE_DELAY))}subscribeToLayoutChange(){const e=_t.jh.findByKeyAndType(this,"layout-switcher",Sa),t=this.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:e.layout===wa.ROWS?"1fr":"repeat(auto-fit, minmax(600px, 1fr))"})};return n(e.state),e.subscribeToState(n)}subscribeToHideNoDataChange(){const e=_t.jh.findByKeyAndType(this,"no-data-switcher",Pa);this.setState({hideNoData:"on"===e.state.hideNoData});return e.subscribeToState(((e,t)=>{e.hideNoData!==(null==t?void 0:t.hideNoData)&&(this.setState({hideNoData:"on"===e.hideNoData}),this.refetchData(!0))}))}subscribeToFiltersChange(){const e=_t.jh.findByKeyAndType(this,"filters",Oo),t=_t.jh.findByKeyAndType(this,"no-data-switcher",Pa);return e.subscribeToState((()=>{"on"===t.state.hideNoData&&this.refetchData()}))}refetchData(e=!1){this.setState({isLoading:!0,$data:new _t.Es({$data:Ti({label:this.state.label}),transformations:[Lo,Fo]})}),this.subscribeOnceToDataChange(e)}shouldRenderItems(e){const{items:t}=this.state;return!e.length||t.length!==e.length||!(0,Bt.isEqual)(t,e)}buildItemsData(e){const t=Po(this,"serviceName"),n=Po(this,"profileMetricId"),{label:r,startColorIndex:o,sortItemsFn:a}=this.state,i=e.map(((e,a)=>{var i;const s=e.fields[1],l=(null===(i=s.labels)||void 0===i?void 0:i[r])||"",c=jo(s,r);return{index:o+a,value:l,label:c,queryRunnerParams:{serviceName:t,profileMetricId:n,filters:[{key:r,operator:"=",value:l}]},panelType:To.TIMESERIES}}));return this.filterItems(i).sort(a)}renderGridItems(e=!1){if(!this.state.$data.state.data)return;const{state:t,series:n,errors:r}=this.state.$data.state.data;if(t===o.LoadingState.Loading)return;if(t===o.LoadingState.Error)return void this.renderErrorState(null==r?void 0:r[0]);const a=this.buildItemsData(n);if(!e&&!this.shouldRenderItems(a))return;if(this.setState({items:a}),!this.state.items.length)return void this.renderEmptyState();const i=a.map((e=>new _t.xK({key:Ni.buildGridItemKey(e),body:this.buildVizPanel(e)})));this.state.body.setState({autoRows:Ci,children:i})}buildVizPanel(e){const t=new Pi({item:e,headerActions:this.state.headerActions.bind(null,e,this.state.items)}),n=t.subscribeToEvent(Mt,(e=>{var n;if(!this.state.hideNoData||(null===(n=e.payload.series)||void 0===n?void 0:n.length))return;const r=_t.jh.getAncestor(t,_t.xK),{key:o}=r.state,a=_t.jh.getAncestor(r,_t.gF),i=a.state.children.filter((e=>e.state.key!==o));i.length?a.setState({children:i}):this.renderEmptyState()}));return t.addActivationHandler((()=>()=>{n.unsubscribe()})),t}filterItems(e){const t=_t.jh.findByKeyAndType(this,"quick-filter",Ta),{searchText:n}=t.state;if(!n)return e;const r=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{try{return new RegExp(e)}catch(e){return null}})).filter(Boolean);return e.filter((({label:e})=>r.some((t=>t.test(e)))))}renderEmptyState(){this.state.body.setState({autoRows:"480px",children:[new _t.xK({body:new ba({message:"No results"})})]})}renderErrorState(e){this.state.body.setState({autoRows:"480px",children:[new _t.xK({body:new va({message:e.message||e.toString()})})]})}static Component({model:e}){const{body:t,isLoading:n}=e.useState();return n?S().createElement(i.Spinner,null):S().createElement("div",{style:{marginBottom:"2px"}},S().createElement(t.Component,{model:t}))}constructor({key:e,label:t,startColorIndex:n,headerActions:r}){super({key:e,label:t,startColorIndex:n,items:[],isLoading:!0,$data:new _t.Es({$data:Ti({label:t}),transformations:[Lo,Fo]}),hideNoData:!1,headerActions:r,sortItemsFn:Fa,body:new _t.gF({templateColumns:"1fr",autoRows:Ci,isLazy:!0,$behaviors:[new _t.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[]})}),this.addActivationHandler(this.onActivate.bind(this))}}class ki extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ki,"type","clear-label-from-filters");class ji extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ji,"type","exclude-label-from-filters");class Ai extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ai,"type","include-label-in-filters");const Ii=e=>{const t=(0,i.useStyles2)(_i),{include:n,exclude:o}=function({status:e,label:t,onInclude:n,onExclude:r,onClear:o}){const a="included"===e,i="excluded"===e;return{include:{isSelected:a,tooltip:a?`Clear "${t}" from the filters`:`Include "${t}" in the filters`,onClick:a?o:n},exclude:{isSelected:i,tooltip:i?`Clear "${t}" from the filters`:`Exclude "${t}" in the filters`,onClick:i?o:r}}}(e);return S().createElement("div",{className:t.container},S().createElement(i.Button,{size:"sm",fill:"outline",variant:n.isSelected?"primary":"secondary","aria-selected":n.isSelected,className:(0,r.cx)(t.includeButton,n.isSelected&&"selected"),onClick:n.onClick,tooltip:n.tooltip,tooltipPlacement:"top","data-testid":"filter-button-include"},"Include"),S().createElement(i.Button,{size:"sm",fill:"outline",variant:o.isSelected?"primary":"secondary","aria-selected":o.isSelected,className:(0,r.cx)(t.excludeButton,o.isSelected&&"selected"),onClick:o.onClick,tooltip:o.tooltip,tooltipPlacement:"top","data-testid":"filter-button-exclude"},"Exclude"))},Ri=(0,w.memo)(Ii),_i=e=>({container:r.css` display: flex; justify-content: center; `,includeButton:r.css` border-radius: ${e.shape.radius.default} 0 0 ${e.shape.radius.default}; &:not(.selected) { border-right: none; } `,excludeButton:r.css` border-radius: 0 ${e.shape.radius.default} ${e.shape.radius.default} 0; &:not(.selected) { border-left: none; } `});function Di(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Li extends _t.Bs{getStatus(e){const{key:t,value:n}=this.state.item.queryRunnerParams.filters[0],r=e.find((e=>e.key===t));return r?zn(r.operator)&&r.value.split("|").includes(n)?"=~"===r.operator?"included":"excluded":r.value===n?"="===r.operator?"included":"excluded":"clear":"clear"}constructor({item:e}){super({item:e}),Di(this,"onInclude",(()=>{Re("g_pyroscope_app_include_action_clicked"),this.publishEvent(new Ai({item:this.state.item}),!0)})),Di(this,"onExclude",(()=>{Re("g_pyroscope_app_exclude_action_clicked"),this.publishEvent(new ji({item:this.state.item}),!0)})),Di(this,"onClear",(()=>{this.publishEvent(new ki({item:this.state.item}),!0)}))}}function Fi({compare:e,onClickCompare:t,onClickClear:n}){const o=(0,i.useStyles2)($i),a=e.size<2,s=e.size>0,l=(0,w.useMemo)((()=>{var t,n,r,o;return 2===e.size?`Compare "${null===(r=e.get(lt.BASELINE))||void 0===r?void 0:r.label}" vs "${null===(o=e.get(lt.COMPARISON))||void 0===o?void 0:o.label}"`:0===e.size?"Select both a baseline and a comparison panel to compare their flame graphs":e.has(lt.BASELINE)?`Select another panel to compare against "${null===(t=e.get(lt.BASELINE))||void 0===t?void 0:t.label}"`:`Select another panel to compare against "${null===(n=e.get(lt.COMPARISON))||void 0===n?void 0:n.label}"`}),[e]);return S().createElement("div",{className:o.container},S().createElement(i.Button,{"arial-label":"Compare",className:o.compareButton,variant:"primary",disabled:a,onClick:a?L:t,tooltip:l},"Compare (",e.size,"/2)"),S().createElement(i.Button,{"data-testid":"clearComparison",className:(0,r.cx)(o.clearButton,a?void 0:o.clearButtonActive),icon:"times",variant:"secondary",tooltip:s?"Clear comparison selection":"",disabled:!s,onClick:s?n:L}))}Di(Li,"Component",(({model:e})=>{const{item:t}=e.useState(),{filters:n}=_t.jh.findByKeyAndType(e,"filters",Oo).useState(),r=(0,w.useMemo)((()=>e.getStatus(n)),[n,e]);return S().createElement(Ri,{label:t.value,status:r,onInclude:e.onInclude,onExclude:e.onExclude,onClear:e.onClear})}));const $i=e=>({container:r.css` display: flex; align-items: center; width: ${Oi.WIDTH_IN_PIXELS}px; `,compareButton:r.css` width: ${Oi.WIDTH_IN_PIXELS-32}px; border-right: none; border-top-right-radius: 0; border-bottom-right-radius: 0; `,clearButton:r.css` box-sizing: border-box; width: 32px !important; height: 32px !important; color: ${e.colors.text.secondary}; background-color: transparent; border-left: none !important; border-top-left-radius: 0; border-bottom-left-radius: 0; &:not([disabled]), &:not([disabled]):hover { background-color: transparent; box-shadow: none; } `,clearButtonActive:r.css` border-color: ${e.colors.border.medium}; &:hover { border-color: ${e.colors.border.medium}; } `});function Bi(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Mi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Ui extends _t.Bs{onActivate(e){var t,n=this;return(t=function*(){const t=_t.jh.findByKeyAndType(n,"groupBy",pi);yield t.update(),e&&n.initVariablesAndControls(e),n.renderBody(t);const r=n.subscribeToGroupByChange(),o=n.subscribeToPanelEvents();return()=>{var e;o.unsubscribe(),r.unsubscribe(),null===(e=n.state.panelTypeChangeSub)||void 0===e||e.unsubscribe()}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){Bi(a,r,o,i,s,"next",e)}function s(e){Bi(a,r,o,i,s,"throw",e)}i(void 0)}))})()}initVariablesAndControls(e){const{queryRunnerParams:t,panelType:n}=e,{groupBy:r}=t;if(null==r?void 0:r.label){_t.jh.findByKeyAndType(this,"groupBy",pi).changeValueTo(r.label)}if(n){_t.jh.findByKeyAndType(this,"panel-type-switcher",Co).setState({panelType:n})}}subscribeToGroupByChange(){const e=_t.jh.findByKeyAndType(this,"groupBy",pi),t=_t.jh.findByKeyAndType(this,"quick-filter",Ta);return e.subscribeToState(((n,r)=>{n.value!==(null==r?void 0:r.value)&&(t.clearSearchText(),this.renderBody(e))}))}subscribeToPanelEvents(){const e=this.subscribeToEvent(Ua,(e=>{this.selectLabel(e.payload.item)})),t=this.subscribeToEvent(yi,(e=>{const{compareTarget:t,item:n}=e.payload;this.selectForCompare(t,n)})),n=this.subscribeToEvent(Ai,(e=>{this.includeLabelValueInFilters(e.payload.item)})),r=this.subscribeToEvent(ji,(e=>{this.excludeLabelValueFromFilters(e.payload.item)})),o=this.subscribeToEvent(ki,(e=>{this.clearLabelValueFromFilters(e.payload.item)}));return{unsubscribe(){o.unsubscribe(),r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe()}}}subscribeToPanelTypeChange(){return _t.jh.findByKeyAndType(this,"panel-type-switcher",Co).subscribeToState(((e,t)=>{var n;e.panelType!==(null==t?void 0:t.panelType)&&(null===(n=this.state.body)||void 0===n||n.renderGridItems())}))}renderBody(e){var t;null===(t=this.state.panelTypeChangeSub)||void 0===t||t.unsubscribe(),"all"===e.state.value?(this.setState({panelTypeChangeSub:this.subscribeToPanelTypeChange()}),this.switchToLabelNamesGrid()):this.switchToLabelValuesGrid(e)}switchToLabelNamesGrid(){_t.jh.findByKeyAndType(this,"quick-filter",Ta).setPlaceholder("Search labels (comma-separated regexes are supported)"),this.setState({body:this.buildSceneLabelNamesGrid()})}buildSceneLabelNamesGrid(){return new Ba({key:"service-labels-grid",variableName:"groupBy",mapOptionToItem:(e,t,{serviceName:n,profileMetricId:r,panelType:o})=>{if("all"===e.value)return null;const{value:a,groupBy:i}=JSON.parse(e.value);return{index:t-1,value:a,label:a,queryRunnerParams:{serviceName:n,profileMetricId:r,groupBy:i,filters:[]},panelType:o}},headerActions:e=>[new Wa({type:"select-label",item:e}),new Wa({type:"expand-panel",item:e}),new Da({item:e})]})}switchToLabelValuesGrid(e){_t.jh.findByKeyAndType(this,"quick-filter",Ta).setPlaceholder("Search label values (comma-separated regexes are supported)"),this.clearCompare();const{index:t,value:n}=e.findCurrentOption();this.setState({body:this.buildSceneLabelValuesGrid(n,t)})}buildSceneLabelValuesGrid(e,t){return new Ni({key:"service-label-values-grid",startColorIndex:t,label:e,headerActions:e=>[new Wa({type:"view-flame-graph",item:e,tooltip:(e,t)=>{const{queryRunnerParams:n,label:r}=e,o=n.profileMetricId||Po(t,"profileMetricId"),a=Po(t,"groupBy");return`View the "${Wr(o).type}" flame graph for "${a}=${r}"`}}),new Li({item:e}),new Da({item:e})]})}selectLabel({queryRunnerParams:e}){const t=e.groupBy.label,n=_t.jh.findByKeyAndType(this,"groupBy",pi);Dt(),n.changeValueTo(t)}includeLabelValueInFilters(e){const[t]=e.queryRunnerParams.filters,n=_t.jh.findByKeyAndType(this,"filters",Oo);n.setState({filters:bo(n.state.filters,t)})}excludeLabelValueFromFilters(e){const t=_t.jh.findByKeyAndType(this,"filters",Oo),[n]=e.queryRunnerParams.filters;t.setState({filters:vo(t.state.filters,n)})}clearLabelValueFromFilters(e){const t=_t.jh.findByKeyAndType(this,"filters",Oo),[n]=e.queryRunnerParams.filters;t.setState({filters:Eo(t.state.filters,n)})}selectForCompare(e,t){var n;const r=new Map(this.state.compare);(null===(n=r.get(e))||void 0===n?void 0:n.value)===t.value?r.delete(e):r.set(e,t),this.setState({compare:r}),this.updateStatsPanels()}updateStatsPanels(){const{compare:e}=this.state,t=e.get(lt.BASELINE),n=e.get(lt.COMPARISON),r=_t.jh.findAllObjects(this,(e=>e instanceof Oi));for(const e of r)e.updateCompareActions(t,n)}getCompare(){return this.state.compare}clearCompare(){this.setState({compare:new Map})}constructor({item:e}){super({key:"group-by-labels",body:void 0,compare:new Map,panelTypeChangeSub:void 0}),Mi(this,"onClickCompareButton",(()=>{Re("g_pyroscope_app_compare_link_clicked");const{compare:e}=this.state,{filters:t}=Ra(this,e.get(lt.BASELINE)),{filters:n}=Ra(this,e.get(lt.COMPARISON));this.publishEvent(new gi({useAncestorTimeRange:!0,clearDiffRange:!0,baselineFilters:t,comparisonFilters:n}),!0)})),Mi(this,"onClickClearCompareButton",(()=>{this.clearCompare(),this.updateStatsPanels()})),this.addActivationHandler((()=>{this.onActivate(e)}))}}Mi(Ui,"Component",(({model:e})=>{const t=(0,i.useStyles2)(Vi),{body:n,compare:r}=e.useState(),o=_t.jh.findByKeyAndType(e,"groupBy",pi),{value:a}=o.useState(),s=(0,w.useMemo)((()=>"all"===a?_t.jh.findByKeyAndType(e,"profiles-explorer",Id).state.gridControls:[_t.jh.findByKeyAndType(e,"quick-filter",Ta),_t.jh.findByKeyAndType(e,"layout-switcher",Sa),_t.jh.findByKeyAndType(e,"no-data-switcher",Pa)]),[a,e]);return S().createElement("div",{className:t.container,"data-testid":"groupByLabelsContainer"},S().createElement(o.Component,{model:o}),S().createElement("div",{className:t.sceneControls},S().createElement(i.Stack,{wrap:"wrap"},"all"!==a&&S().createElement(Fi,{compare:r,onClickCompare:e.onClickCompareButton,onClickClear:e.onClickClearCompareButton}),s.map((e=>S().createElement(e.Component,{key:e.state.key,model:e}))))),n&&S().createElement(n.Component,{model:n}))}));const Vi=e=>({container:r.css` margin-top: ${e.spacing(1)}; `,sceneControls:r.css` margin-bottom: ${e.spacing(1)}; & .quick-filter { flex: 1; min-width: 112px; } `});function qi(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Gi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ki(e){for(var t=1;t{n.unsubscribe(),t.setState({query:ro.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{queryRunnerParams:t}=e,{serviceName:n,profileMetricId:r,filters:o}=t;if(n){_t.jh.findByKeyAndType(this,"serviceName",so).changeValueTo(n)}if(r){_t.jh.findByKeyAndType(this,"profileMetricId",ro).changeValueTo(r)}if(o){_t.jh.findByKeyAndType(this,"filters",Oo).setState({filters:o})}}subscribeToPanelEvents(){var e=this;const t=this.subscribeToEvent(Ma,function(){var t,n=(t=function*(t){e.openExpandedPanelDrawer(t.payload.item)},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){qi(a,r,o,i,s,"next",e)}function s(e){qi(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}()),n=this.subscribeToEvent(Ua,(()=>{this.state.drawer.close()}));return{unsubscribe(){n.unsubscribe(),t.unsubscribe()}}}getVariablesAndGridControls(){return{variables:[_t.jh.findByKeyAndType(this,"serviceName",so),_t.jh.findByKeyAndType(this,"profileMetricId",ro),_t.jh.findByKeyAndType(this,"filters",Oo)],gridControls:[]}}openExpandedPanelDrawer(e){var t;const n=Po(this,"serviceName"),r=Po(this,"profileMetricId"),o=`${Wr(r).description||ta(r)}, grouped by ${(null===(t=e.queryRunnerParams.groupBy)||void 0===t?void 0:t.label)||"?"}`;this.state.drawer.open({title:n,body:la(e.panelType,{displayAllValues:!0,legendPlacement:"right",item:Hi(Ki({},e),{label:o}),headerActions:()=>[new Wa({type:"select-label",item:e}),new Da({item:e})]})})}static Component({model:e}){const{body:t,drawer:n}=e.useState();return S().createElement(S().Fragment,null,S().createElement(t.Component,{model:t}),S().createElement(n.Component,{model:n}))}constructor({item:e}){super({key:"explore-service-labels",body:new _t.G1({direction:"column",$behaviors:[new _t.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair})],children:[new _t.vA({minHeight:hi.MIN_HEIGHT,body:new hi({item:e,headerActions:e=>e.queryRunnerParams.groupBy?[new Wa({type:"view-flame-graph",item:e}),new Wa({type:"expand-panel",item:e}),new Da({item:e})]:[new Wa({type:"view-flame-graph",item:e}),new Da({item:e})],supportGroupBy:!0})}),new _t.vA({body:new Ui({item:e})})]}),drawer:new ti}),this.addActivationHandler(this.onActivate.bind(this,e))}}class Yi extends _t.Bs{onActivate(e){_t.jh.findByKeyAndType(this,"quick-filter",Ta).setPlaceholder("Search profile types (comma-separated regexes are supported)"),e&&this.initVariables(e)}initVariables(e){if(e.queryRunnerParams.serviceName){_t.jh.findByKeyAndType(this,"serviceName",so).changeValueTo(e.queryRunnerParams.serviceName)}}getVariablesAndGridControls(){return{variables:[_t.jh.findByKeyAndType(this,"serviceName",so)],gridControls:[_t.jh.findByKeyAndType(this,"quick-filter",Ta),_t.jh.findByKeyAndType(this,"layout-switcher",Sa)]}}static Component({model:e}){const{body:t}=e.useState();return S().createElement(t.Component,{model:t})}constructor({item:e}){super({key:"explore-service-profile-types",$variables:new _t.Pj({variables:[new ro({query:ro.QUERY_SERVICE_NAME_DEPENDENT,skipUrlSync:!0})]}),body:new Ba({key:"profile-metrics-grid",variableName:"profileMetricId",mapOptionToItem:(e,t,{serviceName:n})=>({index:t,value:e.value,label:e.label,queryRunnerParams:{serviceName:n,profileMetricId:e.value},panelType:To.TIMESERIES}),headerActions:e=>[new Wa({type:"view-labels",item:e}),new Wa({type:"view-flame-graph",item:e}),new Da({item:e})]})}),this.addActivationHandler(this.onActivate.bind(this,e))}}function Wi(e,t){return{from:e,to:t,value:{from:(0,o.dateTimeParse)(e),to:(0,o.dateTimeParse)(t),raw:{from:e,to:t}}}}const Qi=()=>Wi("now-30m","now");class Ji extends _t.yP{reset(){this.setState({value:void 0})}constructor(){super({key:"spanSelector",name:"spanSelector",label:"Span selector",value:void 0})}}function Xi(e,t){if(t){const n=e.services.get(t)||new Map;return Array.from(n.values()).sort(((e,t)=>br(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}return Array.from(e.profileMetrics.keys()).map((e=>Wr(e))).sort(((e,t)=>br(t.group,e.group))).map((({id:e,type:t,group:n})=>({value:e,text:`${t} (${n})`})))}function Zi(e,t){if(t){const n=e.profileMetrics.get(t)||new Set;return Array.from(n).sort(br).map((e=>({text:e,value:e})))}return Array.from(e.services.keys()).sort(br).map((e=>({text:e,value:e})))}class es{static build(e,t){const n=`${e}-${t.name}`,r=es.cache.get(n);if(r instanceof t)return r;const o=new t({dataSourceUid:e});return es.cache.set(n,o),o}}function ts(e){let t,n;for(const{name:r,value:o}of e)if("service_name"===r&&(t=o),"__profile_type__"===r&&(n=o),t&&n)return[t,n];return[]}function ns(e){const t=new Map,n=new Map;if(!e.labelsSet)return A.warn("Pyroscope SeriesApiClient: no data received!"),{services:t,profileMetrics:n};for(const{labels:r}of e.labelsSet){const[e,o]=ts(r);if(!e||!o){A.warn('Pyroscope ServicesApiClient: "service_name" and/or "__profile_type__" are missing in the labels received!',r);continue}const a=t.get(e)||new Map;a.set(o,Wr(o)),t.set(e,a);const i=n.get(o)||new Set;i.add(e),n.set(o,i)}return{services:t,profileMetrics:n}}function rs(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(es,"cache",new Map);class os extends Wt{list(e){var t,n=this;return(t=function*(){const{from:t,to:r}=e;return n.fetch("/querier.v1.QuerierService/Series",{method:"POST",body:JSON.stringify({start:t,end:r,labelNames:["service_name","__profile_type__"],matchers:[]})}).then((e=>e.json())).then(ns)},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){rs(a,r,o,i,s,"next",e)}function s(e){rs(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function as(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const is=new class extends nn{list(e){var t,n=this;return(t=function*(){const{from:t,to:r}=qo(e.timeRange),o=[n.apiClient.baseUrl,t,r],a=n.cacheClient.get(o);if(a){const{services:e,profileMetrics:t}=yield a;return e.size||t.size||n.cacheClient.delete(o),{services:e,profileMetrics:t}}const i=n.apiClient.list({from:t,to:r});n.cacheClient.set(o,i);try{const{services:e,profileMetrics:t}=yield i;return{services:e,profileMetrics:t}}catch(e){throw n.cacheClient.delete(o),e}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){as(a,r,o,i,s,"next",e)}function s(e){as(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}({cacheClient:new Zt});function ss(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ls(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ss(a,r,o,i,s,"next",e)}function s(e){ss(a,r,o,i,s,"throw",e)}i(void 0)}))}}class cs extends _t.UU{fetchSeries(e,t,n){return ls((function*(){is.setApiClient(es.build(e,os));try{return yield is.list({timeRange:t})}catch(e){throw A.error(e,{info:"Error while loading Pyroscope series!",variableName:n||""}),e}}))()}query(){return ls((function*(){return{state:o.LoadingState.Done,data:[{name:"PyroscopeSeries",fields:[{name:"PyroscopeSeries",type:o.FieldType.other,values:[],config:{}}],length:0}]}}))()}metricFindQuery(e,t){var n=this;return ls((function*(){var r,o,a;const i=null===(o=t.scopedVars)||void 0===o||null===(r=o.__sceneObject)||void 0===r?void 0:r.value,s=_t.jh.interpolate(i,"$dataSource"),l=_t.jh.interpolate(i,"$serviceName"),c=_t.jh.interpolate(i,"$profileMetricId"),u=yield n.fetchSeries(s,t.range,null===(a=t.variable)||void 0===a?void 0:a.name);switch(e){case"$dataSource and all services":return Zi(u);case"$dataSource and all profile metrics":return Xi(u);case"$dataSource and only $profileMetricId services":return Zi(u,c);case"$dataSource and only $serviceName profile metrics":return Xi(u,l);default:throw new TypeError(`Unsupported query "${e}"!`)}}))()}testDatasource(){return ls((function*(){return{status:"success",message:"OK"}}))()}constructor(){super(Xr.type,Xr.uid)}}class us extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(us,"type","enable-sync-timeranges");class ds extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ds,"type","sync-refresh");class ps extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ps,"type","sync-timeranges");class ms extends _t.KE{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ms,"Component",(function({model:e}){const{hidePicker:t,isOnCanvas:n}=e.useState(),r=_t.jh.getTimeRange(e),o=r.getTimeZone(),a=r.useState();return t?null:S().createElement(i.TimeRangePicker,{isOnCanvas:null==n||n,value:a.value,onChange:r.onTimeRangeChange,timeZone:o,fiscalYearStartMonth:a.fiscalYearStartMonth,onMoveBackward:e.onMoveBackward,onMoveForward:e.onMoveForward,onZoom:e.onZoom,onChangeTimeZone:r.onTimeZoneChange,onChangeFiscalYearStartMonth:e.onChangeFiscalYearStartMonth,isSynced:!1})}));const fs=/^\d+[yYmMsSwWhHdD]$/;function hs(e){if("string"!=typeof e)return null;if(-1!==e.indexOf("now"))return e;if(fs.test(e))return e;if(8===e.length){const t=(0,o.toUtc)(e,"YYYYMMDD");if(t.isValid())return t.toISOString()}else if(15===e.length){const t=(0,o.toUtc)(e,"YYYYMMDDTHHmmss");if(t.isValid())return t.toISOString()}else if(24===e.length){return(0,o.toUtc)(e).toISOString()}const t=parseInt(e,10);return isNaN(t)?null:(0,o.toUtc)(t).toISOString()}function gs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ys(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}class bs extends o.MutableDataFrame{addRange(e){this.add(ys(function(e){for(var t=1;tthis.addField(e)))}}function vs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Es(e){for(var t=1;t{this.setState((0,Bt.omit)(e,"key"))}))),this._subs.add(null===(e=this.getTimeseries().state.$data)||void 0===e?void 0:e.subscribeToState(((e,t)=>{var n,r,a,i,s,l;e.data&&e.data.state===o.LoadingState.Done&&((null===(n=e.data.annotations)||void 0===n?void 0:n.length)||(null===(a=t.data)||void 0===a||null===(r=a.annotations)||void 0===r?void 0:r.length)?!(null===(i=e.data.annotations)||void 0===i?void 0:i.length)&&(null===(l=t.data)||void 0===l||null===(s=l.annotations)||void 0===s?void 0:s.length)&&(e.data.annotations=t.data.annotations):this.updateTimeseriesAnnotation())})))}getAncestorTimeRange(){if(!this.parent||!this.parent.parent)throw new Error(typeof this+" must be used within $timeRange scope");return _t.jh.getTimeRange(this.parent.parent)}getTimeseries(){try{const e=_t.jh.getAncestor(this,_t.Eb);if("timeseries"!==e.state.pluginId)throw new TypeError("Incorrect VizPanel type!");return e}catch(e){throw new Error("Ancestor timeseries panel not found!")}}updateTimeseriesAnnotation(){const{annotationTimeRange:e,annotationColor:t,annotationTitle:n}=this.state,{$data:r}=this.getTimeseries().state,o=null==r?void 0:r.state.data;if(!o)return;const a=new bs;a.addRange({color:t,text:n,time:1e3*e.from.unix(),timeEnd:1e3*e.to.unix()}),null==r||r.setState({data:ws(Es({},o),{annotations:[a]})})}setAnnotationTimeRange(e,t=!1){this.setState({annotationTimeRange:e}),t&&this.updateTimeseriesAnnotation()}nullifyAnnotationTimeRange(){this.setAnnotationTimeRange(Os)}getUrlState(){const{annotationTimeRange:e}=this.state;return{diffFrom:"string"==typeof e.raw.from?e.raw.from:e.raw.from.toISOString(),diffTo:"string"==typeof e.raw.to?e.raw.to:e.raw.to.toISOString()}}updateFromUrl(e){const{diffFrom:t,diffTo:n}=e;if(!n&&!t)return;const{annotationTimeRange:r}=this.state;var o,a;this.setAnnotationTimeRange(this.buildAnnotationTimeRange(null!==(o=hs(t))&&void 0!==o?o:r.from,null!==(a=hs(n))&&void 0!==a?a:r.to))}buildAnnotationTimeRange(e,t){return function(e,t,n,r,a){const i=a&&"now"===t;return{from:o.dateMath.parse(e,!1,n,r),to:o.dateMath.parse(i?"now-"+a:t,!0,n,r),raw:{from:e,to:t}}}(e,t,this.getTimeZone(),this.state.fiscalYearStartMonth,this.state.UNSAFE_nowDelay)}onTimeRangeChange(e){const{mode:t}=this.state;"default"!==t?this.setAnnotationTimeRange(e,!0):this.getAncestorTimeRange().onTimeRangeChange(e)}onTimeZoneChange(e){this.getAncestorTimeRange().onTimeZoneChange(e)}getTimeZone(){return this.getAncestorTimeRange().getTimeZone()}onRefresh(){this.getAncestorTimeRange().onRefresh()}constructor(e){super(Es({from:Os.raw.from,to:Os.raw.to,value:Os,annotationTimeRange:Os},e)),vs(this,"_variableDependency",new _t.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.nullifyAnnotationTimeRange(),this.updateTimeseriesAnnotation()}})),vs(this,"_urlSync",new _t.So(this,{keys:["diffFrom","diffTo"]})),this.addActivationHandler(this.onActivate.bind(this))}}class xs extends o.BusEventWithPayload{}function Ts(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(xs,"type","switch-timerange-selection-mode");var Cs=function(e){return e.TIMEPICKER="timepicker",e.FLAMEGRAPH="flame-graph",e}({});class Ns extends _t.Bs{constructor(){super({mode:"flame-graph"}),Ts(this,"onChange",(e=>{this.setState({mode:e}),this.publishEvent(new xs({mode:e}),!0)}))}}Ts(Ns,"OPTIONS",[{label:"Time picker",value:"timepicker"},{label:"Flame graph",value:"flame-graph"}]),Ts(Ns,"Component",(({model:e})=>{const t=(0,i.useStyles2)(ks),{mode:n}=e.useState();return S().createElement("div",{className:t.container},S().createElement("label",{className:t.label},S().createElement("span",null,"Range selection mode "),S().createElement(i.Tooltip,{content:S().createElement("div",{className:t.tooltip},S().createElement("div",null,"Use these buttons to change the behaviour when selecting a range with the mouse on the time series:"),S().createElement("dl",null,S().createElement("dt",null,"Time picker"),S().createElement("dd",null,"Time range zoom in (default behaviour)"),S().createElement("dt",null,"Flame graph"),S().createElement("dd",null,"Time range for building the flame graph (the stack traces will be retrieved only for the selected range)"))),placement:"top"},S().createElement(i.Icon,{name:"question-circle"}))),S().createElement(i.RadioButtonGroup,{size:"sm",options:Ns.OPTIONS,value:n,onChange:e.onChange,"aria-label":"Range selection mode"}))}));const ks=e=>({container:r.css` display: flex; flex-direction: column; `,tooltip:r.css` padding: ${e.spacing(1)}; & dl { margin-top: ${e.spacing(2)}; display: grid; grid-gap: ${e.spacing(1)} ${e.spacing(2)}; grid-template-columns: max-content; } & dt { font-weight: bold; } & dd { margin: 0; grid-column-start: 2; } `,label:r.css` font-size: 12px; text-align: right; margin-bottom: 2px; color: ${e.colors.text.secondary}; `});function js({filterKey:e}){return Ro(new _t.dt({datasource:Jr,queries:[{refId:`$profileMetricId-$serviceName-${e}}`,queryType:"metrics",profileTypeId:"$profileMetricId",labelSelector:`{service_name="$serviceName",$${e}}`}]}))}var As=n(4308),Is=n.n(As);const Rs={COLOR:Is()("#d066d4"),OVERLAY:Is()("#d066d4").alpha(.3)},_s={COLOR:Is()("#1398f6"),OVERLAY:Is()("#1398f6").alpha(.3)};function Ds(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ls(e){for(var t=1;t{i.unsubscribe()}}static buildTimeSeriesPanel({target:e,filterKey:t,title:n,color:r}){const a=new sa({item:{index:0,value:e,label:"",queryRunnerParams:{},panelType:To.TIMESERIES},data:new _t.Es({$data:js({filterKey:t}),transformations:[Lo,Fo]}),overrides:e=>e.map((e=>{const t=e.fields[1],n=Ao(e,"allValuesSum")||0,i=(0,o.getValueFormat)(t.config.unit)(n),s=`${i.text}${i.suffix}`,[l,c,u]=Fs.getDiffRange(a),d=l&&c?`Total = ${s} / Flame graph range = ${(0,o.dateTimeFormat)(l,{format:o.systemDateFormats.fullDate,timeZone:u})} → ${(0,o.dateTimeFormat)(c,{format:o.systemDateFormats.fullDate,timeZone:u})}`:`Total = ${s}`;return{matcher:{id:o.FieldMatcherID.byFrameRefID,options:e.refId},properties:[{id:"displayName",value:d},{id:"color",value:{mode:"fixed",fixedColor:r}}]}})),headerActions:()=>[new Ns]});return a.state.body.setState({$timeRange:new Ps({key:`${e}-annotation-timerange`,mode:Ss.ANNOTATIONS,annotationColor:e===lt.BASELINE?Rs.OVERLAY.toString():_s.OVERLAY.toString(),annotationTitle:`${n} flame graph range`})}),a}static getDiffRange(e){var t,n,r,o;let a,i;const s=null===(r=e.state.body.state.$data)||void 0===r||null===(n=r.state.data)||void 0===n||null===(t=n.annotations)||void 0===t?void 0:t[0];return null==s||s.fields.some((({name:e,values:t})=>(a="time"===e?t[0]:a,i="timeEnd"===e?t[0]:i,a&&i))),[a,i,null===(o=e.state.$timeRange)||void 0===o?void 0:o.state.timeZone]}getAncestorTimeRange(){if(!this.parent||!this.parent.parent)throw new Error(typeof this+" must be used within $timeRange scope");return _t.jh.getTimeRange(this.parent.parent)}subscribeToEvents(){const{target:e,timeseriesPanel:t,$timeRange:n}=this.state,r=t.state.body.state.$timeRange,o=this.subscribeToEvent(xs,(e=>{r.setState({mode:e.payload.mode===Cs.FLAMEGRAPH?Ss.ANNOTATIONS:Ss.DEFAULT})})),a=r.subscribeToState(((t,n)=>{this.state.timeRangeSyncEnabled&&t.annotationTimeRange!==n.annotationTimeRange&&this.publishEvent(new ps({source:e,annotationTimeRange:t.annotationTimeRange}),!0)})),i=n.subscribeToState(((t,n)=>{t.from===n.from&&t.to===n.to||(this.updateTitle(""),this.state.timeRangeSyncEnabled&&this.publishEvent(new ps({source:e,timeRange:t}),!0))}));return{unsubscribe(){i.unsubscribe(),a.unsubscribe(),o.unsubscribe()}}}buildTimeseriesTitle(){const e=Po(this,"profileMetricId"),{description:t}=Wr(e);return t||ta(e)}useDiffTimeRange(){return this.state.timeseriesPanel.state.body.state.$timeRange.useState()}applyPreset({from:e,to:t,diffFrom:n,diffTo:r,label:o}){this.setDiffRange({from:n,to:r}),this.setTimeRange(Wi(e,t)),this.updateTitle(o)}setTimeRange(e){const{from:t,to:n}=this.state.$timeRange.state.value;t.isSame(e.value.from)&&n.isSame(e.value.to)||this.state.$timeRange.setState({from:e.from,to:e.to,value:e.value})}setDiffRange(e){const t=this.state.timeseriesPanel.state.body.state.$timeRange;if(null===e)return void t.nullifyAnnotationTimeRange();const{annotationTimeRange:n}=t.state,r=t.buildAnnotationTimeRange(e.from,e.to);n.from.isSame(r.from)&&n.to.isSame(r.to)||t.setAnnotationTimeRange(r,!0)}autoSelectDiffRange(e){const{$timeRange:t,target:n}=this.state,{from:r,to:a}=t.state.value;if(this.updateTitle(""),e)return void this.setDiffRange({from:r.toISOString(),to:a.toISOString()});const i=a.diff(r),s=Math.min(Math.round(.25*i),864e5);n===lt.BASELINE?this.setDiffRange({from:r.toISOString(),to:(0,o.dateTime)(r).add(s).toISOString()}):this.setDiffRange({from:(0,o.dateTime)(a).subtract(s).toISOString(),to:a.toISOString()})}updateTitle(e=""){const t=this.state.target===lt.BASELINE?"Baseline":"Comparison",n=e?`${t} (${e})`:t;this.setState({title:n})}toggleTimeRangeSync(e){this.setState({timeRangeSyncEnabled:e})}refreshTimeseries(){this.state.$timeRange.onRefresh()}constructor({target:e,useAncestorTimeRange:t,clearDiffRange:n,filters:r}){const o=e===lt.BASELINE?"filtersBaseline":"filtersComparison",a=e===lt.BASELINE?"Baseline":"Comparison",i=e===lt.BASELINE?Rs.COLOR.toString():_s.COLOR.toString();super({key:`${e}-panel`,target:e,filterKey:o,title:a,color:i,$timeRange:new _t.JZ(Ls({key:`${e}-panel-timerange`},Wi("now-1h","now"))),timePicker:new ms({isOnCanvas:!0}),refreshPicker:new _t.WM({isOnCanvas:!0}),timeseriesPanel:Fs.buildTimeSeriesPanel({target:e,filterKey:o,title:a,color:i}),timeRangeSyncEnabled:!1}),Ds(this,"_variableDependency",new _t.Sh(this,{variableNames:["profileMetricId"],onReferencedVariableValueChanged:()=>{this.state.timeseriesPanel.updateItem({label:this.buildTimeseriesTitle()})}})),Ds(this,"onClickTimeRangeSync",(()=>{const{target:e,timeRangeSyncEnabled:t,$timeRange:n,timeseriesPanel:r}=this.state,o=r.state.body.state.$timeRange;this.publishEvent(new us({source:e,enable:!t,timeRange:n.state,annotationTimeRange:o.state.annotationTimeRange}),!0)})),Ds(this,"onClickRefresh",(()=>{this.publishEvent(new ds({source:this.state.target}),!0)})),this.addActivationHandler(this.onActivate.bind(this,t,n,r))}}Ds(Fs,"Component",(({model:e})=>{const{target:t,color:n,title:o,timeseriesPanel:a,timePicker:s,refreshPicker:l,filterKey:c,timeRangeSyncEnabled:u}=e.useState(),d=(0,i.useStyles2)($s,n),p=_t.jh.findByKey(e,c);return S().createElement("div",{className:d.panel,"data-testid":`panel-${t}`},S().createElement("div",{className:d.panelHeader},S().createElement("h6",null,S().createElement("div",{className:d.colorCircle}),o),S().createElement("div",{className:d.timeControls},S().createElement(s.Component,{model:s}),S().createElement("div",{onClick:e.onClickRefresh},S().createElement(l.Component,{model:l})),S().createElement(i.IconButton,{className:(0,r.cx)(d.syncButton,u&&"active"),name:"link","aria-label":u?"Unsync time ranges":"Sync time ranges",tooltip:u?"Unsync time ranges":"Sync time ranges",onClick:e.onClickTimeRangeSync}))),S().createElement("div",{className:d.filter},S().createElement(p.Component,{model:p})),S().createElement("div",{className:d.timeseries},a&&S().createElement(a.Component,{model:a})))}));const $s=(e,t)=>({panel:r.css` background-color: ${e.colors.background.primary}; padding: ${e.spacing(1)} ${e.spacing(1)} 0 ${e.spacing(1)}; border: 1px solid ${e.colors.border.weak}; border-radius: 2px; `,panelHeader:r.css` display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: ${e.spacing(2)}; flex-wrap: wrap; & > h6 { font-size: 15px; height: 32px; line-height: 32px; margin: 0 ${e.spacing(1)} 0 0; } `,colorCircle:r.css` display: inline-block; background-color: ${t}; border-radius: 50%; width: 9px; height: 9px; margin-right: 6px; `,timeControls:r.css` display: flex; justify-content: flex-end; gap: 4px; `,syncButton:r.css` z-index: unset; padding: ${e.spacing(0,1)}; margin: 0; background: ${e.colors.secondary.main}; border: 1px solid ${e.colors.secondary.border}; border-radius: ${e.shape.radius.default}; &:hover { background: ${e.colors.secondary.shade}; } &.active { color: ${e.colors.primary.text}; border: 1px solid ${e.colors.primary.text}; } `,filter:r.css` display: flex; margin-bottom: ${e.spacing(3)}; `,timeseries:r.css` height: 200px; & [data-viz-panel-key] > * { border: 0 none; } & [data-viz-panel-key] [data-testid='uplot-main-div'] { cursor: crosshair; } `});function Bs(){const[e,t]=(0,w.useState)(null),[n,r]=(0,w.useState)();return{onOpen(e){r((()=>e))},isOpen:t=>t===e,open(e){t(e),null==n||n()},close(){t(null)}}}var Ms=n(6667);const Us=Object.freeze({collapsedFlamegraphs:!1,maxNodes:16384,enableFlameGraphDotComExport:!0,enableFunctionDetails:!0,enableMetricsFromProfiles:!1});function Vs(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function qs(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Vs(a,r,o,i,s,"next",e)}function s(e){Vs(a,r,o,i,s,"throw",e)}i(void 0)}))}}class Gs extends G{get(){var e=this,t=()=>super.fetch;return qs((function*(){return t().call(e,"/settings.v1.SettingsService/Get",{method:"POST",body:JSON.stringify({})}).then((e=>e.json())).then((e=>{var t;const n=null===(t=e.settings)||void 0===t?void 0:t.find((({name:e})=>e===Gs.PLUGIN_SETTING_NAME));return n?JSON.parse(n.value):{}}))}))()}set(e){var t=this,n=()=>super.fetch;return qs((function*(){return n().call(t,"/settings.v1.SettingsService/Set",{method:"POST",body:JSON.stringify({setting:{name:Gs.PLUGIN_SETTING_NAME,value:JSON.stringify(e)}})}).then((e=>e.json()))}))()}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Gs,"PLUGIN_SETTING_NAME","pluginSettings");const Ks=()=>new Gs;function Hs({enabled:e}={}){const t=Ks(),{isFetching:n,error:r,data:o}=(0,K.I)({enabled:e,queryKey:["settings","ds-uid-"+G.selectDefaultDataSource().uid],queryFn:()=>t.get().then((e=>Object.keys(Us).reduce(((e,t)=>{var n,r,o;return null!==(o=(n=e)[r=t])&&void 0!==o||(n[r]=Us[t]),e}),e)))}),{mutateAsync:a}=(0,Ms.n)({mutationFn:e=>t.set(e),networkMode:"always"});return{isFetching:n,error:t.isAbortError(r)?null:r,settings:o,mutate:a}}function zs({severity:e,title:t,message:n,error:r,errorContext:o}){return r&&A.error(r,o),S().createElement(i.Alert,{title:t,severity:e},r&&S().createElement(S().Fragment,null,r.message,S().createElement("br",null)),n)}var Ys=n(7945);function Ws({children:e,delay:t}){const[n,r]=(0,w.useState)(!1);return(0,w.useEffect)((()=>{window.setTimeout((()=>{r(!0)}),t)}),[e,t]),S().createElement(S().Fragment,null,n?e:null)}function Qs({menu:e,title:t,placement:n="bottom",offset:o,dragClassCancel:a,menuButtonClass:s,onVisibleChange:l,onOpenMenu:c}){const u=t?Ys.Tp.components.Panels.Panel.menu(t):"panel-menu-button",d=(0,w.useCallback)((e=>(e&&c&&c(),l)),[c,l]),p=t?`Menu for panel with title ${t}`:"Menu for panel with no title";return S().createElement(i.Dropdown,{overlay:e,placement:n,offset:o,onVisibleChange:d},S().createElement(i.ToolbarButton,{"aria-label":p,title:"Menu",icon:"ellipsis-v",iconSize:"md",narrow:!0,"data-testid":u,className:(0,r.cx)(s,a)}))}function Js({menu:e,title:t,dragClass:n,children:o,offset:a=-32,onOpenMenu:s}){const l=(0,i.useStyles2)(Xs),c=(0,w.useRef)(null),u=Ys.Tp.components.Panels.Panel.HoverWidget,d=(0,w.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.setPointerCapture(e.pointerId)}),[]),p=(0,w.useCallback)((e=>{var t;null===(t=c.current)||void 0===t||t.releasePointerCapture(e.pointerId)}),[]),[m,f]=(0,w.useState)(!1);return void 0===o||0===S().Children.count(o)?null:S().createElement("div",{className:(0,r.cx)(l.container,{"show-on-hover":!m}),style:{top:`${a}px`},"data-testid":u.container},n&&S().createElement("div",{className:(0,r.cx)(l.square,l.draggable,n),onPointerDown:d,onPointerUp:p,ref:c,"data-testid":u.dragIcon},S().createElement(i.Icon,{name:"expand-arrows",className:l.draggableIcon})),!t&&S().createElement("h6",{className:(0,r.cx)(l.untitled,{[l.draggable]:!!n},n)},"Untitled"),o,e&&S().createElement(Qs,{menu:e,title:t,placement:"bottom",menuButtonClass:l.menuButton,onVisibleChange:f,onOpenMenu:s}))}function Xs(e){return{hidden:(0,r.css)({visibility:"hidden",opacity:"0"}),container:(0,r.css)({label:"hover-container-widget",transition:"all .1s linear",display:"flex",position:"absolute",zIndex:1,right:0,boxSizing:"content-box",alignItems:"center",background:e.colors.background.secondary,color:e.colors.text.primary,border:`1px solid ${e.colors.border.weak}`,borderRadius:e.shape.radius.default,height:e.spacing(4),boxShadow:e.shadows.z1}),square:(0,r.css)({display:"flex",justifyContent:"center",alignItems:"center",width:e.spacing(4),height:"100%"}),draggable:(0,r.css)({cursor:"move",[e.breakpoints.down("md")]:{display:"none"}}),menuButton:(0,r.css)({background:"inherit",border:"none","&:hover":{background:e.colors.secondary.main}}),untitled:(0,r.css)({color:e.colors.text.disabled,fontStyle:"italic",padding:e.spacing(0,1),marginBottom:0}),draggableIcon:(0,r.css)({transform:"rotate(45deg)",color:e.colors.text.secondary,"&:hover":{color:e.colors.text.primary}})}}function Zs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function el(e){for(var t=1;t=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}const rl=(0,w.forwardRef)(((e,t)=>{var{className:n,children:o,href:a,onClick:s,target:l,title:c}=e,u=nl(e,["className","children","href","onClick","target","title"]);const d=(0,i.useStyles2)(ol);return a?S().createElement("a",el({ref:t,href:a,onClick:s,target:l,title:c,className:(0,r.cx)(d.linkItem,n)},u),o):s?S().createElement(i.Button,{ref:t,className:(0,r.cx)(d.item,n),variant:"secondary",fill:"text",onClick:s},o):S().createElement("span",el({ref:t,className:(0,r.cx)(d.item,n)},u),o)}));rl.displayName="TitleItem";const ol=e=>{const t=(0,r.css)({color:`${e.colors.text.secondary}`,label:"panel-header-item",cursor:"auto",border:"none",borderRadius:`${e.shape.radius.default}`,padding:`${e.spacing(0,1)}`,height:`${e.spacing(e.components.panel.headerHeight)}`,display:"flex",alignItems:"center",justifyContent:"center","&:focus, &:focus-visible":tl(el({},al(e)),{zIndex:1}),"&: focus:not(:focus-visible)":{outline:"none",boxShadow:"none"},"&:hover ":{boxShadow:`${e.shadows.z1}`,background:`${e.colors.background.secondary}`,color:`${e.colors.text.primary}`}});return{item:t,linkItem:(0,r.cx)(t,(0,r.css)({cursor:"pointer"}))}};function al(e){return{outline:"2px dotted transparent",outlineOffset:"2px",boxShadow:`0 0 0 2px ${e.colors.background.canvas}, 0 0 0px 4px ${e.colors.primary.main}`,transitionTimingFunction:"cubic-bezier(0.19, 1, 0.22, 1)",transitionDuration:"0.2s",transitionProperty:"outline, outline-offset, box-shadow"}}function il({description:e,className:t}){const n=(0,i.useStyles2)(sl);return""!==e?S().createElement(i.Tooltip,{interactive:!0,content:()=>{const t="function"==typeof e?e():e;return S().createElement("div",{className:"panel-info-content markdown-html"},S().createElement("div",{dangerouslySetInnerHTML:{__html:t}}))}},S().createElement(rl,{className:(0,r.cx)(t,n.description)},S().createElement(i.Icon,{name:"info-circle",size:"md"}))):null}const sl=()=>({description:(0,r.css)({code:{whiteSpace:"normal",wordWrap:"break-word"},"pre > code":{display:"block"}})});function ll({message:e,onClick:t,ariaLabel:n="status"}){const r=(0,i.useStyles2)(cl);return S().createElement(i.ToolbarButton,{className:r.buttonStyles,onClick:t,variant:"destructive",icon:"exclamation-triangle",iconSize:"md",tooltip:e||"","aria-label":n})}const cl=e=>{const{headerHeight:t,padding:n}=e.components.panel;return{buttonStyles:(0,r.css)({label:"panel-header-state-button",display:"flex",alignItems:"center",justifyContent:"center",padding:e.spacing(n),width:e.spacing(t),height:e.spacing(t),borderRadius:e.shape.radius.default})}};function ul({children:e,padding:t="md",title:n="",description:a="",displayMode:s="default",titleItems:l,menu:c,dragClass:u,dragClassCancel:d,hoverHeader:p=!1,hoverHeaderOffset:m,loadingState:f,statusMessage:h,statusMessageOnClick:g,actions:y,onCancelQuery:b,onOpenMenu:v}){const E=(0,i.useTheme2)(),O=(0,i.useStyles2)(fl),[P,x]=(0,w.useState)(0),T=(0,w.useRef)(null);(0,w.useEffect)((()=>{T.current&&x(T.current.offsetWidth)}),[T]);const C=!p,N=pl(E,C),{contentStyle:k}=ml(t,E),j={height:N,cursor:u?"move":"auto"},A={};"transparent"===s&&(A.backgroundColor="transparent",A.border="none");const I=n?Ys.Tp.components.Panels.Panel.title(n):"Panel",R=S().createElement(S().Fragment,null,n&&S().createElement("h6",{title:n,className:O.title},n),S().createElement("div",{className:(0,r.cx)(O.titleItems,d),"data-testid":"title-items-container"},S().createElement(il,{description:a,className:d}),l),f===o.LoadingState.Streaming&&S().createElement(i.Tooltip,{content:b?"Stop streaming":"Streaming"},S().createElement(rl,{className:d,"data-testid":"panel-streaming",onClick:b},S().createElement(i.Icon,{name:"circle-mono",size:"md",className:O.streaming}))),f===o.LoadingState.Loading&&b&&S().createElement(Ws,{delay:2e3},S().createElement(i.Tooltip,{content:"Cancel query"},S().createElement(rl,{className:(0,r.cx)(d,O.pointer),"data-testid":"panel-cancel-query",onClick:b},S().createElement(i.Icon,{name:"sync-slash",size:"md"})))),S().createElement("div",{className:O.rightAligned},y&&S().createElement("div",{className:O.rightActions},dl(y,(e=>e)))));return S().createElement("div",{className:O.container,style:A,"data-testid":I},S().createElement("div",{className:O.loadingBarContainer},f===o.LoadingState.Loading?S().createElement(i.LoadingBar,{width:P,ariaLabel:"Panel loading bar"}):null),p&&S().createElement(S().Fragment,null,S().createElement(Js,{menu:c,title:n,offset:m,dragClass:u,onOpenMenu:v},R),h&&S().createElement("div",{className:O.errorContainerFloating},S().createElement(ll,{message:h,onClick:g,ariaLabel:"Panel status"}))),C&&S().createElement("div",{className:(0,r.cx)(O.headerContainer,u),style:j,"data-testid":"header-container"},h&&S().createElement("div",{className:d},S().createElement(ll,{message:h,onClick:g,ariaLabel:"Panel status"})),R,c&&S().createElement(Qs,{menu:c,title:n,placement:"bottom-end",menuButtonClass:(0,r.cx)(O.menuItem,d,"show-on-hover"),onOpenMenu:v})),S().createElement("div",{className:O.content,style:k,ref:T},e))}const dl=(e,t)=>{const n=S().Children.toArray(e).filter(Boolean);return n.length>0?t(n):null},pl=(e,t)=>t?e.spacing.gridSize*e.components.panel.headerHeight:0,ml=(e,t)=>({contentStyle:{padding:("md"===e?t.components.panel.padding:0)*t.spacing.gridSize}}),fl=e=>{const{background:t,borderColor:n,padding:o}=e.components.panel;return{container:(0,r.css)({label:"panel-container",backgroundColor:t,border:`1px solid ${n}`,position:"relative",borderRadius:e.shape.radius.default,height:"100%",display:"flex",flexDirection:"column",".show-on-hover":{visibility:"hidden",opacity:"0"},"&:focus-visible, &:hover":{".show-on-hover":{visibility:"visible",opacity:"1"}},"&:focus-visible":{outline:`1px solid ${e.colors.action.focus}`},"&:focus-within":{".show-on-hover":{visibility:"visible",opacity:"1"}}}),loadingBarContainer:(0,r.css)({label:"panel-loading-bar-container",position:"absolute",top:0,width:"100%",overflow:"hidden"}),content:(0,r.css)({label:"panel-content",flexGrow:1}),headerContainer:(0,r.css)({label:"panel-header",display:"flex",alignItems:"center"}),pointer:(0,r.css)({cursor:"pointer"}),streaming:(0,r.css)({label:"panel-streaming",marginRight:0,color:e.colors.success.text,"&:hover":{color:e.colors.success.text}}),title:(0,r.css)({label:"panel-title",marginBottom:0,padding:e.spacing(0,o),textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",fontSize:e.typography.h6.fontSize,fontWeight:e.typography.h6.fontWeight}),items:(0,r.css)({display:"flex"}),item:(0,r.css)({display:"flex",justifyContent:"center",alignItems:"center"}),hiddenMenu:(0,r.css)({visibility:"hidden"}),menuItem:(0,r.css)({label:"panel-menu",border:"none",background:e.colors.secondary.main,"&:hover":{background:e.colors.secondary.shade}}),errorContainerFloating:(0,r.css)({label:"error-container",position:"absolute",left:0,top:0,zIndex:e.zIndex.tooltip}),rightActions:(0,r.css)({display:"flex",padding:e.spacing(0,o),gap:e.spacing(1)}),rightAligned:(0,r.css)({label:"right-aligned-container",marginLeft:"auto",display:"flex",alignItems:"center"}),titleItems:(0,r.css)({display:"flex",height:"100%"})}},hl=e=>({panelWrap:r.css` margin-bottom: ${e.spacing(1)}; `});function gl({isLoading:e,title:t,description:n,children:r,className:a="",headerActions:s,dataTestId:l}){const c=(0,i.useStyles2)(hl),u=e?o.LoadingState.Loading:o.LoadingState.Done;return S().createElement("div",{className:`${a} ${c.panelWrap}`,"data-testid":l||"panel"},S().createElement(ul,{loadingState:u,title:t,description:n,actions:s},r))}var yl=n(6030);function bl({children:e,onClick:t,disabled:n,interactionName:r}){const o=(0,i.useStyles2)(vl),{isEnabled:a,error:s,isFetching:l}=function(){const{data:e,isFetching:t,error:n}=(0,K.I)({queryKey:["llm"],queryFn:()=>yl.Sn()});return n&&A.error(n,{info:"Error while checking the status of the Grafana LLM plugin!"}),{isEnabled:Boolean(e),isFetching:t,error:n}}();let c="ai",u="";return l?(c="fa fa-spinner",u="Checking the status of the Grafana LLM plugin..."):s?(c="exclamation-triangle",u="Error while checking the status of the Grafana LLM plugin!"):a||(c="shield-exclamation",u="Grafana LLM plugin missing or not configured! Please check the plugins administration page."),S().createElement(i.Button,{className:o.aiButton,size:"md",fill:"text",icon:c,disabled:!a||n,tooltip:u,tooltipPlacement:"top",onClick:e=>{Re(r),t(e)}},e)}const vl=()=>({aiButton:r.css` padding: 0 4px; `});var El=n(7879);const wl=e=>{const t=document.querySelector('[placeholder^="Search"]');if(null===t)return void A.error(new Error("Cannot find search input element!"));((e,t)=>{const n=Object.getOwnPropertyDescriptor(e,"value").set,r=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),"value").set;n&&n!==r?r.call(e,t):n.call(e,t)})(t,e.target.textContent.trim()),t.dispatchEvent(new Event("input",{bubbles:!0}))},Sl={overrides:{code:{component:({children:e})=>{const t=(0,i.useStyles2)(Pl);return"string"==typeof e&&e.includes("\n")?S().createElement("code",null,e):S().createElement("code",{className:t.searchLink,title:"Search for this node",onClick:wl},e)}}}};function Ol({reply:e}){var t;const n=(0,i.useStyles2)(Pl);return S().createElement("div",{className:n.container},null==e||null===(t=e.messages)||void 0===t?void 0:t.filter((e=>"system"!==e.role)).map((e=>S().createElement(S().Fragment,null,S().createElement("div",{className:n.reply},S().createElement(El.Ay,{options:Sl},e.content||"")),S().createElement("hr",null)))),S().createElement("div",{className:n.reply},S().createElement(El.Ay,{options:Sl},e.text)))}const Pl=()=>({container:r.css` width: 100%; height: 100%; `,reply:r.css` font-size: 13px; & ol, & ul { margin: 0 0 16px 24px; } `,searchLink:r.css` color: rgb(255, 136, 51); border: 1px solid transparent; padding: 2px 4px; cursor: pointer; font-size: 13px; &:hover, &:focus, &:active { box-sizing: border-box; border: 1px solid rgb(255, 136, 51, 0.8); border-radius: 4px; } `}),xl=()=>({textarea:r.css` margin-bottom: 8px; `,sendButton:r.css` float: right; border-top-left-radius: 0; border-bottom-left-radius: 0; `});function Tl({onSubmit:e}){const t=(0,i.useStyles2)(xl),{question:n,onChangeInput:r,onClickSend:o}=function(e){const[t,n]=(0,w.useState)(""),r=(0,w.useCallback)((e=>{n(e.target.value)}),[]),o=(0,w.useCallback)((()=>{const r=t.trim();r&&(e(r),n(""))}),[t,e]);return{question:t,onChangeInput:r,onClickSend:o}}(e);return S().createElement("div",null,S().createElement(i.TextArea,{className:t.textarea,placeholder:"Ask a follow-up question...",value:n,onChange:r,onKeyDown:e=>{"Enter"!==e.code||e.shiftKey||o()}}),S().createElement(i.Button,{className:t.sendButton,onClick:o},"Send"))}var Cl=n(3752);const Nl={system:{empty:()=>"\n You are a performance profiling expert and excel at analyzing profiles in the DOT format.\n In the DOT format, a row like N47 -> N61 means the function from N47 called the function from N61.\n"},user:{single:(e,t)=>`\n Analyze this flamegraph in DOT format and address these key aspects:\n - **Performance Bottleneck**: Identify the primary factors slowing down the process, consuming excessive memory, or causing a bottleneck in the system.\n - **Root Cause**: Explain clearly why these bottlenecks are occurring.\n - **Recommended Fix**: Suggest practical solutions for these issues.\n\n Guidelines:\n - Always use full function names without splitting them from package names.\n - Exclude numeric values, percentages, and node names (e.g., N1, N3, Node 1, Node 2).\n - Focus on user code over low-level runtime optimizations.\n - For standard library or runtime functions, explain their presence/function and link them to user code functions calling them. Avoid repetitive mentions from the same call chain.\n - Do not mention that the flamegraph profile is in DOT format.\n - Only use h5 and h6 markdown headers (e.g., ##### Performance Bottleneck, ###### Recommended Fix)\n - Do not use h1,h2,h3,h4 headers (e.g., ## Bottleneck, ### Root Cause, #### Recommended Fix)\n\n Format the response using markdown headers for each section corresponding to the key aspects.\n\n The profile type is: ${e}\n Profile in DOT format:\n ${t[0]}\n`,anton:(e,t)=>`\nGive me actionable feedback and suggestions on how I improve the application performance.\n\nDo not break function names.\nDo not show any numeric values, absolute or percents.\nDo not show node names like N1, N3, or Node 1, Node 2.\nDo not suggest low-level runtime optimisations, focus on the user code.\n\nAlways use full function names.\nNever split function and package name.\n\nRemove any numeric values, absolute or percents, from the output.\nRemove node names like N1, N3, or Node 1, Node 2 from the output.\n\nIf the function is widely known (e.g., a runtime or stdlib function), provide me concise explanation why the function is present in the profile and what could be the cause.\nIf a function is defined in the runtime or in the standard library, tell me which function in the user code calls it.\nAvoid mentioning functions from the same call-chain.\n\n5 suggestions is enough.\nThe profile type is ${e}\nBelow is the performance profile in DOT format:\n${t[0]}\n`,diff:(e,t)=>`\nAnalyze the differences between these two performance profiles presented in DOT format. Provide a detailed comparison focusing on the following aspects:\n\n- Performance Change: Determine how the performance has changed from the first profile to the second. Identify if there are new bottlenecks, improved or worsened performance areas, or significant changes in resource consumption.\n- Function Impact: Highlight no more than 3 specific functions that have undergone notable changes in their performance impact. Discuss any new functions that have appeared in the second profile or any existing functions that have significantly increased or decreased in resource usage.\n- Potential Causes: Discuss the possible reasons for these changes in performance, linking them to the differences in function execution or resource usage between the two profiles.\n\nGuidelines for Analysis:\n- Use full function names without separating them from their package names\n- Focus on user code rather than low-level runtime optimizations or standard library functions unless they are directly relevant to the user code's performance changes\n- Exclude numeric values, percentages, and node names (e.g., N1, N3, Node 1, Node 2) from the analysis\n- Format the response using markdown headers for each section to structure the analysis clearly\n\nThe profile type is: ${e}\n\nFirst performance profile in DOT format:\n${t[0]}\n\nSecond performance profile in DOT format:\n${t[1]}\n`}},kl=({system:e,user:t,profileType:n,profiles:r})=>{const o=Nl.system[e];if("function"!=typeof o)throw new Error(`Cannot find system prompt "${e}"!`);const a=Nl.user[t];if("function"!=typeof a)throw new Error(`Cannot find user prompt "${t}"!`);return{system:o(n,r),user:a(n,r)}};function jl(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}class Al extends Wt{get(e){var t,n=this;return(t=function*(){const t=new URLSearchParams({query:e.query,from:String(1e3*e.timeRange.from.unix()),until:String(1e3*e.timeRange.to.unix()),format:e.format});e.maxNodes&&t.set("max-nodes",String(e.maxNodes));const r=yield n.fetch(`/pyroscope/render?${t.toString()}`);switch(e.format){case"dot":return r.text();case"json":return r.json();default:throw new TypeError(`Unknown format "${e.format}"!`)}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){jl(a,r,o,i,s,"next",e)}function s(e){jl(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function Il(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Rl extends _t.Bs{validateFetchParams(e,t){let n,r=t;return e&&2!==t.length?(n=new Error(`Invalid number of fetch parameters for analyzing the diff flame graph (${t.length})!`),r=[]):e||1===t.length||(n=new Error(`Invalid number of fetch parameters for analyzing the flame graph (${t.length})!`),r=[]),{params:r,error:n}}constructor(){super({key:"ai-panel"}),Il(this,"useSceneAiPanel",((e,t)=>{const n=_t.jh.findByKeyAndType(this,"dataSource",uo).useState().value,{params:r,error:o}=this.validateFetchParams(e,t),{error:a,isFetching:i,profiles:s}=function(e,t){const n=es.build(e,Al),{isFetching:r,error:o,data:a}=(0,K.I)({queryKey:["dot-profiles",e,...t.flatMap((({query:e,timeRange:t})=>[e,t.from.unix(),t.to.unix()])),100],queryFn:()=>Promise.all(t.map((({query:e,timeRange:t})=>n.get({query:e,timeRange:t,format:"dot",maxNodes:100}).then((e=>e.replace(/fontsize=\d+ /g,"").replace(/id="node\d+" /g,"").replace(/labeltooltip=".*\)" /g,"").replace(/tooltip=".*\)" /g,"").replace(/(N\d+ -> N\d+).*/g,"$1").replace(/N\d+ \[label="other.*\n/,"").replace(/shape=box /g,"").replace(/fillcolor="#\w{6}"/g,"").replace(/color="#\w{6}" /g,""))))))});return{isFetching:r,error:o,profiles:a||[]}}(n,r),l=Wr(Po(this,"profileMetricId")).type,{reply:c,error:u,retry:d}=function(e,t){const[n,r]=(0,w.useState)(""),[o,a]=(0,w.useState)(!1),[i,s]=(0,w.useState)(!1),[l,c]=(0,w.useState)([]),[u,d]=(0,w.useState)(null),[p,m]=(0,w.useState)(),f=(0,w.useCallback)((e=>{c(e),d(null),r(""),a(!0),s(!1);const t=Cl.qH({model:"gpt-4-1106-preview",messages:e}).pipe(Cl.qA()).subscribe({next:r,error(e){d(e),a(!1),s(!0),m(void 0)},complete(){a(!1),s(!0),m(void 0)}});m(t)}),[]),h=(0,w.useCallback)((e=>{const t=[{role:"assistant",content:n},{role:"user",content:e}];try{f([...l,...t])}catch(e){d(e)}}),[l,n,f]);return(0,w.useEffect)((()=>{if(!t.length||l.length>0)return;const n=kl({system:"empty",user:2===t.length?"diff":"single",profileType:e,profiles:t});try{f([{role:"system",content:n.system},{role:"system",content:n.user}])}catch(e){d(e)}}),[l.length,e,t,t.length,f]),(0,w.useEffect)((()=>()=>{p&&(p.unsubscribe(),m(void 0))}),[p]),{reply:{text:n,hasStarted:o,hasFinished:i,messages:l,askFollowupQuestion:h},retry(){if(l.length>0)try{f(l)}catch(e){d(e)}},error:u}}(l,s);return{data:{validationError:o,isLoading:i||!i&&!a&&!u&&!c.text.trim(),fetchError:a,llmError:u,reply:c,shouldDisplayReply:Boolean((null==c?void 0:c.hasStarted)||(null==c?void 0:c.hasFinished)),shouldDisplayFollowUpForm:!a&&!u&&Boolean(null==c?void 0:c.hasFinished)},actions:{retry:d,submitFollowupQuestion(e){c.askFollowupQuestion(e)}}}}))}}Il(Rl,"Component",(({model:e,isDiff:t,fetchParams:n,onClose:r})=>{const o=(0,i.useStyles2)(_l),{data:a,actions:s}=e.useSceneAiPanel(t,n);return S().createElement(gl,{className:o.sidePanel,title:"Flame graph analysis",isLoading:a.isLoading,headerActions:S().createElement(i.IconButton,{title:"Close panel",name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"ai-panel"},S().createElement("div",{className:o.content},a.validationError&&S().createElement(zs,{severity:"error",title:"Validation error!",error:a.validationError}),a.fetchError&&S().createElement(zs,{severity:"error",title:"Error while loading profile data!",message:"Sorry for any inconvenience, please try again later.",error:a.fetchError}),a.shouldDisplayReply&&S().createElement(Ol,{reply:a.reply}),a.isLoading&&S().createElement(S().Fragment,null,S().createElement(i.Spinner,{inline:!0})," Analyzing..."),a.llmError&&S().createElement(i.Alert,{title:"An error occured while generating content using OpenAI!",severity:"warning"},S().createElement("div",null,S().createElement("div",null,S().createElement("p",null,a.llmError.message),S().createElement("p",null,"Sorry for any inconvenience, please retry or if the problem persists, contact your organization admin."))),S().createElement(i.Button,{className:o.retryButton,variant:"secondary",fill:"outline",onClick:()=>s.retry()},"Retry")),a.shouldDisplayFollowUpForm&&S().createElement(Tl,{onSubmit:s.submitFollowupQuestion})))}));const _l=e=>({sidePanel:r.css` flex: 1 0 50%; margin-left: 8px; max-width: calc(50% - 4px); `,title:r.css` margin: -4px 0 4px 0; `,content:r.css` padding: ${e.spacing(1)}; `,retryButton:r.css` float: right; `});class Dl extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Dl,"type","diff-auto-select");class Ll extends o.BusEventWithPayload{}function Fl(){const{searchParams:e,pushNewUrl:t}=function(){const e=(0,Ne.useNavigate)(),t=(0,Ne.useLocation)();return{searchParams:new URLSearchParams(t.search),pushNewUrl:t=>{const n=new URLSearchParams(window.location.search);for(const[e,r]of Object.entries(t))n.set(e,r);e({search:n.toString()},{replace:!0})}}}();var n;const r=Number(null!==(n=e.get("maxNodes"))&&void 0!==n?n:""),o=e=>{t({maxNodes:String(e)})};return function(e,t){const{isFetching:n,error:r,settings:o}=Hs({enabled:!e});if(!e&&!n)r?(Me(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. flame graph max nodes). Please try to reload the page, sorry for the inconvenience."]),A.error(r),t(Us.maxNodes)):t(o.maxNodes)}(r>0,o),[r,o]}function $l(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ll,"type","diff-choose-preset");class Bl extends Wt{get(e){var t,n=this;return(t=function*(){const t=new URLSearchParams({leftQuery:e.leftQuery,leftFrom:String(1e3*e.leftTimeRange.from.unix()),leftUntil:String(1e3*e.leftTimeRange.to.unix()),rightQuery:e.rightQuery,rightFrom:String(1e3*e.rightTimeRange.from.unix()),rightUntil:String(1e3*e.rightTimeRange.to.unix())});e.maxNodes&&t.set("max-nodes",String(e.maxNodes));const r=yield n.fetch(`/pyroscope/render-diff?${t.toString()}`);return yield r.json()},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){$l(a,r,o,i,s,"next",e)}function s(e){$l(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(e){super(e)}}function Ml(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ul(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Vl({enabled:e,dataSourceUid:t,baselineTimeRange:n,baselineQuery:r,comparisonTimeRange:o,comparisonQuery:a}){const[i]=Fl(),s=es.build(t,Bl),{isFetching:l,error:c,data:u,refetch:d}=(0,K.I)({placeholderData:e=>e,enabled:Boolean(e&&i),queryKey:["diff-profile",t,r,n.from.unix(),n.to.unix(),a,o.from.unix(),o.to.unix(),i],queryFn:()=>{s.abort();const e={leftQuery:r,leftTimeRange:n,rightQuery:a,rightTimeRange:o,maxNodes:i};return s.get(e).then((e=>({profile:{version:e.version,flamebearer:e.flamebearer,metadata:e.metadata}})))}});return Ul(function(e){for(var t=1;t{o||n(),a(!o)}},S().createElement("div",{className:r.collapseContent},S().createElement("ol",null,S().createElement("li",null,"Ensure that the “Flame graph” range selection mode is selected"),S().createElement("li",null,"Use your mouse to select the desired time ranges on both the baseline and the comparison time series")),S().createElement("img",{src:"public/plugins/grafana-pyroscope-app/img/8cdf4d2e2df8326311ab.gif",alt:"How to view the diff flame graph"}))))})}const Gl=e=>({infoMsg:r.css` padding: ${e.spacing(2)} 0 0 0; `,textButton:r.css` padding: 0; `,collapse:r.css` background: transparent; border: 0; `,collapseContent:r.css` padding: 0 ${e.spacing(5)}; & img { max-width: 100%; width: auto; margin-top: ${e.spacing(2)}; } `});function Kl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Hl extends _t.Bs{buildTitle(){const e=Po(this,"serviceName"),t=Wr(Po(this,"profileMetricId")).type;return S().createElement(S().Fragment,null,S().createElement(te,{size:"small"}),"Diff flame graph for ",e," (",t,")")}constructor(){super({key:"diff-flame-graph",aiPanel:new Rl}),Kl(this,"useSceneDiffFlameGraph",(()=>{const{aiPanel:e}=this.useState(),{baselineTimeRange:t,comparisonTimeRange:n}=this.parent.useDiffTimeRanges(),r=co(this,"filtersBaseline"),o=co(this,"filtersComparison"),{settings:a,error:i}=Hs(),s=_t.jh.findByKeyAndType(this,"dataSource",uo).useState().value,l=Boolean(r&&o&&t.from.unix()&&t.to.unix()&&n.from.unix()&&n.to.unix()),{isFetching:c,error:u,profile:d}=Vl({enabled:l,dataSourceUid:s,baselineTimeRange:t,baselineQuery:r,comparisonTimeRange:n,comparisonQuery:o}),p=l&&!c&&!u&&0===(null==d?void 0:d.flamebearer.numTicks),m=Boolean(l&&!u&&!p&&d),f=!l;return{data:{title:this.buildTitle(),isLoading:c,fetchProfileError:u,noProfileDataAvailable:p,shouldDisplayFlamegraph:m,hasMissingSelections:f,profile:d,settings:a,fetchSettingsError:i,ai:{panel:e,fetchParams:[{query:r,timeRange:t},{query:o,timeRange:n}]}},actions:{}}})),Kl(this,"onClickAutoSelect",(()=>{Re("g_pyroscope_app_diff_auto_select_clicked"),this.publishEvent(new Dl({wholeRange:!1}),!0)})),Kl(this,"onClickChoosePreset",(()=>{Re("g_pyroscope_app_diff_choose_preset_clicked"),this.publishEvent(new Ll({}),!0)})),Kl(this,"onOpenLearnHow",(()=>{Re("g_pyroscope_app_diff_learn_how_clicked")}))}}Kl(Hl,"Component",(({model:e})=>{var t,n;const r=(0,i.useStyles2)(zl),{data:o}=e.useSceneDiffFlameGraph(),a=Bs(),s=o.isLoading||o.hasMissingSelections||o.noProfileDataAvailable;(0,w.useEffect)((()=>{s&&a.close()}),[s,a]),o.fetchSettingsError&&Me(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. flamegraph export options). Please try to reload the page, sorry for the inconvenience."]);const l=(0,w.useMemo)((()=>S().createElement(S().Fragment,null,o.title,o.isLoading&&S().createElement(i.Spinner,{inline:!0,className:r.spinner}))),[o.isLoading,o.title,r.spinner]);return S().createElement("div",{className:r.flex},S().createElement(gl,{dataTestId:"diff-flame-graph-panel",className:r.flamegraphPanel,title:l,isLoading:o.isLoading,headerActions:S().createElement(bl,{disabled:s||a.isOpen("ai"),onClick:()=>a.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Flame Graph")},o.hasMissingSelections&&S().createElement(ql,{onClickAutoSelect:e.onClickAutoSelect,onClickChoosePreset:e.onClickChoosePreset,onOpenLearnHow:e.onOpenLearnHow}),o.fetchProfileError&&S().createElement(zs,{severity:"error",title:"Error while loading profile data!",error:o.fetchProfileError}),o.noProfileDataAvailable&&S().createElement(zs,{severity:"warning",title:"No profile data available",message:"Please verify that you've selected adequate filters and time ranges."}),o.shouldDisplayFlamegraph&&S().createElement(wt,{diff:!0,profile:o.profile,enableFlameGraphDotComExport:null===(t=o.settings)||void 0===t?void 0:t.enableFlameGraphDotComExport,collapsedFlamegraphs:null===(n=o.settings)||void 0===n?void 0:n.collapsedFlamegraphs})),a.isOpen("ai")&&S().createElement(o.ai.panel.Component,{model:o.ai.panel,isDiff:!0,fetchParams:o.ai.fetchParams,onClose:a.close}))}));const zl=e=>({flex:r.css` display: flex; `,flamegraphPanel:r.css` min-width: 0; flex-grow: 1; `,sidePanel:r.css` flex: 1 0 50%; margin-left: 8px; max-width: calc(50% - 4px); `,spinner:r.css` margin-left: ${e.spacing(1)}; `,aiButton:r.css` margin-top: ${e.spacing(1)}; `}),Yl="https://grafana.qualtrics.com/jfe/form/SV_6Gav4IUU6jcYfd4",Wl=()=>{const e=(0,i.useStyles2)(Ql);return S().createElement("div",{className:e.wrapper},S().createElement("a",{href:Yl,className:e.feedback,title:"Share your thoughts about Profiles in Grafana.",target:"_blank",rel:"noreferrer noopener"},S().createElement(i.Icon,{name:"comment-alt-message"})," Give feedback"))},Ql=e=>({wrapper:(0,r.css)({display:"flex",gap:e.spacing(1),justifyContent:"flex-end",paddingTop:"4px"}),feedback:(0,r.css)({alignSelf:"center",color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize,"&:hover":{color:e.colors.text.link}})});function Jl(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Xl extends _t.Bs{onActivate(){[lt.BASELINE,lt.COMPARISON].forEach((e=>{this._subs.add(_t.jh.findByKeyAndType(this,`${e}-panel`,Fs).state.$timeRange.subscribeToState(((e,t)=>{e.from===t.from&&e.to===t.to||this.setState({value:null})})))}))}openSelect(){this.setState({isSelectOpen:!0})}closeSelect(){this.setState({isSelectOpen:!1})}reset(){this.setState({value:null,isSelectOpen:!1,isModalOpen:!1})}static Component({model:e}){const t=(0,i.useStyles2)(Zl),{value:n,isSelectOpen:r,isModalOpen:o}=e.useState();return S().createElement(S().Fragment,null,S().createElement("div",{className:t.presetsContainer},S().createElement(i.Select,{className:t.select,placeholder:"Choose a preset",value:n,options:Xl.PRESETS,onChange:e.onChangePreset,isOpen:r,onOpenMenu:e.onOpenSelect,onCloseMenu:e.onCloseSelect}),S().createElement(i.Button,{icon:"save",variant:"secondary",tooltip:"Save the current time ranges and filters as a custom preset",onClick:e.onClickSave})),S().createElement(i.Modal,{title:"Custom user presets",isOpen:o,closeOnEscape:!0,closeOnBackdropClick:!0,onDismiss:e.closeModal},S().createElement("p",null,"This feature, which would allow you to save the current time ranges and filters, is currently not implemented."),S().createElement("p",null,"Please let us know if you would be interested to use it by"," ",S().createElement("a",{href:Yl,target:"_blank",rel:"noreferrer noopener",className:t.link},"leaving us your feedback.")),S().createElement("p",null,"Thank you!"),S().createElement(i.Modal.ButtonRow,null,S().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:e.closeModal},"Cancel"),S().createElement(i.Button,{onClick:e.closeModal,disabled:!0},"Save"))))}constructor(){super({name:"compare-presets",label:"Comparison presets",value:null,isModalOpen:!1,isSelectOpen:!1}),Jl(this,"_variableDependency",new _t.Sh(this,{variableNames:["dataSource","serviceName"],onReferencedVariableValueChanged:()=>{this.reset()}})),Jl(this,"onChangePreset",(e=>{var t;if(Re("g_pyroscope_app_diff_preset_selected",{value:e.value}),this.closeSelect(),"dummy"!==e.value){if(null===(t=e.value)||void 0===t?void 0:t.startsWith("auto-select-"))return this.setState({value:null}),void this.publishEvent(new Dl({wholeRange:"auto-select-whole"===e.value}),!0);[lt.BASELINE,lt.COMPARISON].forEach((t=>{const n=_t.jh.findByKeyAndType(this,`${t}-panel`,Fs);n.toggleTimeRangeSync(!1),n.applyPreset(e[t])})),this.setState({value:e.value})}else this.setState({value:null,isModalOpen:!0})})),Jl(this,"onClickSave",(()=>{Re("g_pyroscope_app_diff_preset_save_clicked"),this.setState({isModalOpen:!0})})),Jl(this,"closeModal",(()=>{this.setState({isModalOpen:!1})})),Jl(this,"onOpenSelect",(()=>{setTimeout((()=>this.openSelect()),0)})),Jl(this,"onCloseSelect",(()=>{this.closeSelect()})),this.addActivationHandler(this.onActivate.bind(this))}}Jl(Xl,"PRESETS",[{label:"Built-in presets",value:"built-in",options:[{value:"last hour (30m-window)",label:"Last hour (30m-window)",baseline:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now-30m",label:"last hour"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"last hour (1h-window)",label:"Last hour (1h-window)",baseline:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now",label:"last hour"},comparison:{from:"now-1h",to:"now",diffFrom:"now-1h",diffTo:"now",label:"last hour"}},{value:"6h ago vs now",label:"6h ago vs now (30m-window)",baseline:{from:"now-375m",to:"now-315m",diffFrom:"now-375m",diffTo:"now-345m",label:"6h ago"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"24h ago vs now",label:"24h ago vs now (30m-window)",baseline:{from:"now-1455m",to:"now-1395m",diffFrom:"now-1455m",diffTo:"now-1425m",label:"24h ago"},comparison:{from:"now-1h",to:"now",diffFrom:"now-30m",diffTo:"now",label:"last hour"}},{value:"auto-select-25",label:"Auto-select (25% range)"},{value:"auto-select-whole",label:"Auto-select (whole range)"}]},{label:"My presets",value:"custom",options:[{label:"Dummy preset saved earlier",value:"dummy"}]}]);const Zl=e=>({presetsContainer:r.css` display: flex; `,select:r.css` min-width: ${e.spacing(24)}; text-align: left; `,link:r.css` color: ${e.colors.text.link}; `});function ec(){return e=>{const t=new Map,n=e.subscribeToEvent(Mt,(n=>{var r;const o=null===(r=n.payload.series)||void 0===r?void 0:r[0];(null==o?void 0:o.refId)?(t.set(o.refId,Math.max(...o.fields[1].values)),function(e,t){const n=_t.jh.findAllObjects(e,(e=>e instanceof _t.Eb&&"timeseries"===e.state.pluginId));for(const e of n)e.clearFieldConfigCache(),e.setState({fieldConfig:(0,Bt.merge)((0,Bt.cloneDeep)(e.state.fieldConfig),{defaults:{max:t}})})}(e,Math.max(...t.values()))):A.warn("Missing refId! Cannot sync y-axis on the timeseries.",n.payload.series)}));return()=>{n.unsubscribe()}}}class tc extends _t.Bs{onActivate(){a.locationService.partial({},!0);const e=_t.jh.findByKeyAndType(this,"profileMetricId",ro);return e.setState({query:ro.QUERY_SERVICE_NAME_DEPENDENT}),e.update(!0),this.subscribeToEvents(),()=>{e.setState({query:ro.QUERY_DEFAULT}),e.update(!0)}}subscribeToEvents(){this._subs.add(this.subscribeToEvent(Dl,(e=>{const t=e.payload.wholeRange,{baselinePanel:n,comparisonPanel:r}=this.state;n.toggleTimeRangeSync(!1),r.toggleTimeRangeSync(!1),n.autoSelectDiffRange(t),r.autoSelectDiffRange(t)}))),this._subs.add(this.subscribeToEvent(Ll,(()=>{this.state.presetsPicker.openSelect()}))),this._subs.add(this.subscribeToEvent(us,(e=>{const{source:t,enable:n,timeRange:r,annotationTimeRange:o}=e.payload,{baselinePanel:a,comparisonPanel:i}=this.state,s=t===lt.BASELINE?i:a;n&&this.syncTimeRanges(s,r,o),i.toggleTimeRangeSync(n),a.toggleTimeRangeSync(n)}))),this._subs.add(this.subscribeToEvent(ps,(e=>{const{source:t,timeRange:n,annotationTimeRange:r}=e.payload,{baselinePanel:o,comparisonPanel:a}=this.state,i=t===lt.BASELINE?a:o;this.syncTimeRanges(i,n,r)}))),this._subs.add(this.subscribeToEvent(ds,(e=>{const{source:t}=e.payload,{baselinePanel:n,comparisonPanel:r}=this.state;(t===lt.BASELINE?r:n).refreshTimeseries()})))}syncTimeRanges(e,t,n){t&&e.setTimeRange(t),n&&e.setDiffRange({from:n.from.toISOString(),to:n.to.toISOString()})}getVariablesAndGridControls(){return{variables:[_t.jh.findByKeyAndType(this,"serviceName",so),_t.jh.findByKeyAndType(this,"profileMetricId",ro),this.state.presetsPicker],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(nc),{baselinePanel:n,comparisonPanel:r,body:o}=e.useState();return S().createElement("div",{className:t.container},S().createElement("div",{className:t.columns},S().createElement(n.Component,{model:n}),S().createElement(r.Component,{model:r})),S().createElement(o.Component,{model:o}))}constructor({useAncestorTimeRange:e,clearDiffRange:t,baselineFilters:n,comparisonFilters:r}){super({key:"explore-diff-flame-graph",baselinePanel:new Fs({target:lt.BASELINE,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:n||[]}),comparisonPanel:new Fs({target:lt.COMPARISON,useAncestorTimeRange:Boolean(e),clearDiffRange:Boolean(t),filters:r||[]}),$behaviors:[new _t.Gg.K2({key:"metricCrosshairSync",sync:o.DashboardCursorSync.Crosshair}),ec()],body:new Hl,presetsPicker:new Xl}),function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"useDiffTimeRanges",(()=>{const{baselinePanel:e,comparisonPanel:t}=this.state,{annotationTimeRange:n}=e.useDiffTimeRange(),{annotationTimeRange:r}=t.useDiffTimeRange();return{baselineTimeRange:n,comparisonTimeRange:r}})),this.addActivationHandler(this.onActivate.bind(this))}}const nc=e=>({container:r.css` width: 100%; display: flex; flex-direction: column; `,columns:r.css` display: flex; flex-direction: row; gap: ${e.spacing(1)}; margin-bottom: ${e.spacing(1)}; & > div { flex: 1 1 0; } `});function rc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function oc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){rc(a,r,o,i,s,"next",e)}function s(e){rc(a,r,o,i,s,"throw",e)}i(void 0)}))}}class ac extends Wt{githubLogin(e){var t=this;return oc((function*(){const n=yield t.fetch("/vcs.v1.VCSService/GithubLogin",{method:"POST",body:JSON.stringify({authorizationCode:e})});return yield n.json()}))()}githubApp(){var e=this;return oc((function*(){const t=yield e.fetch("/vcs.v1.VCSService/GithubApp",{method:"POST",body:JSON.stringify({})});return(yield t.json()).clientID}))()}}function ic(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class sc{isUserTokenExpired(e=0){return Date.now()>=this.expiry.getTime()-e}static decode(e){if(void 0===e||""===e)return;let t;try{t=atob(e)}catch(e){return void A.error(e,{info:"Failed to base64 decode GitSession value"})}const{payload:n,isLegacy:r}=sc.tryDecode(t);return r?new sc(e,864e13):new sc(n.metadata,Number(n.expiry))}static tryDecode(e){try{return{payload:JSON.parse(e),isLegacy:!1}}catch(e){return{payload:void 0,isLegacy:!0}}}constructor(e,t){ic(this,"oauthTokenMetadata",void 0),ic(this,"expiry",void 0),this.oauthTokenMetadata=e,this.expiry=new Date(t)}}function lc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const cc="pyroscope_git_session";class uc{getCookie(){return this.syncCookieWithBrowser(),this.sessionCookie}setCookie(e){e.startsWith(`${cc}=`)||(e=`${cc}=${e}`);const t=uc.getCookieFromJar(e,cc);void 0!==t&&(this.deleteLegacyCookie(),this.rawCookie=t,this.sessionCookie=sc.decode(t.value),document.cookie=`${e}; path=/`)}deleteCookie(){document.cookie=`${cc}=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`,this.deleteLegacyCookie(),this.rawCookie=void 0,this.sessionCookie=void 0}deleteLegacyCookie(){document.cookie="GitSession=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;"}syncCookieWithBrowser(){var e,t;const n=uc.getCookieFromJar(document.cookie,cc);(null==n?void 0:n.key)===(null===(e=this.rawCookie)||void 0===e?void 0:e.key)&&(null==n?void 0:n.value)===(null===(t=this.rawCookie)||void 0===t?void 0:t.value)||(void 0!==n?this.setCookie(`${n.key}=${n.value}`):this.deleteCookie())}static getCookieFromJar(e,t){return e.split(";").map((e=>{const[t,...n]=e.trim().split("="),r=n.join("=");return{key:t.trim(),value:null==r?void 0:r.trim()}})).find((({key:e})=>e===t))}constructor(){lc(this,"rawCookie",void 0),lc(this,"sessionCookie",void 0)}}const dc=new uc;const pc=800,mc=950;function fc(e,t){const n=function(e,t){const n=new URL("/login/oauth/authorize","https://github.com");return n.searchParams.set("client_id",e),n.searchParams.set("scope","repo"),n.searchParams.set("state",btoa(JSON.stringify({redirect_uri:window.location.origin,nonce:t}))),n.toString()}(e,t),{top:r}=window;var o,a;const i=(null!==(o=null==r?void 0:r.outerWidth)&&void 0!==o?o:0)/2+(null!==(a=null==r?void 0:r.screenX)&&void 0!==a?a:0)-pc/2;var s,l;const c=(null!==(s=null==r?void 0:r.outerHeight)&&void 0!==s?s:0)/2+(null!==(l=null==r?void 0:r.screenY)&&void 0!==l?l:0)-mc/2;return window.open(n,"GitHub Login",`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${pc}, height=${mc}, top=${c}, left=${i}`)}function hc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function gc(){var e;return e=function*(e,t,n,r,o){if(r&&r.close(),null==n?void 0:n.isUserTokenExpired())try{return void(yield t.refresh())}catch(e){A.error(e,{info:"Failed to refresh GitHub user token"}),dc.deleteCookie()}try{o(fc(yield e.githubApp(),Ic))}catch(e){Be(e,["Failed to start login flow.",e.message])}},gc=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){hc(a,r,o,i,s,"next",e)}function s(e){hc(a,r,o,i,s,"throw",e)}i(void 0)}))},gc.apply(this,arguments)}function yc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function bc(){var e;return e=function*(e,t,n){const r=t.get("code");if(!r)return"";const o=t.get("state");if(!o)throw new Error("Invalid state parameter!");let a;try{a=JSON.parse(atob(o))}catch(e){throw new Error("Invalid state parameter!")}if(a.nonce!==n)throw new Error("Invalid nonce parameter!");return(yield e.githubLogin(r)).cookie},bc=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){yc(a,r,o,i,s,"next",e)}function s(e){yc(a,r,o,i,s,"throw",e)}i(void 0)}))},bc.apply(this,arguments)}function vc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ec({vcsClient:e,externalWindow:t,setExternalWindow:n,setSessionCookie:r,nonce:o}){(0,w.useEffect)((()=>{const a=function(){var i,s=(i=function*(){if(t&&!t.closed){try{const a=function(e){try{return new URL(e.location.href).searchParams}catch(e){return null}}(t);if(null!==a){const i=yield function(e,t,n){return bc.apply(this,arguments)}(e,a,o);if(i)return r(i),t.close(),void n(null)}}catch(e){return Be(e,["Error while login in with GitHub!",e.message]),t.close(),void n(null)}window.setTimeout(a,700)}else n(null)},function(){var e=this,t=arguments;return new Promise((function(n,r){var o=i.apply(e,t);function a(e){vc(o,n,r,a,s,"next",e)}function s(e){vc(o,n,r,a,s,"throw",e)}a(void 0)}))});return function(){return s.apply(this,arguments)}}();return t&&a(),()=>{t&&(t.close(),n(null))}}),[t,n,r,o,e])}function wc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Sc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){wc(a,r,o,i,s,"next",e)}function s(e){wc(a,r,o,i,s,"throw",e)}i(void 0)}))}}const Oc={isLoginInProgress:!1,isLoggedIn:!1,isSessionExpired:!1,login:Sc((function*(){}))},Pc=(0,w.createContext)(Oc);function xc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Tc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){xc(a,r,o,i,s,"next",e)}function s(e){xc(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Cc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const Nc=Object.freeze({sha:"",date:void 0,author:{login:"unknown author",avatarURL:""},message:"",URL:""});class kc extends Wt{getFile(e,t,n,r){var o=this;return Tc((function*(){return(yield o.postWithRefresh("/vcs.v1.VCSService/GetFile",JSON.stringify({repositoryURL:e,ref:t,localPath:n,rootPath:r}))).json()}))()}getCommits(e){var t=this;return Tc((function*(){return yield Promise.all(e.map((({repositoryUrl:e,gitRef:n})=>e&&n?t.getCommit(e,n).catch((t=>(A.error(t,{info:`Error while fetching commit from repo "${e}" (${n})!'`}),Nc))):Nc)))}))()}refresh(){var e=this;return Tc((function*(){return e.refreshSession()}))()}getCommit(e,t){var n=this;return Tc((function*(){var r;const o=yield n.postWithRefresh("/vcs.v1.VCSService/GetCommit",JSON.stringify({repositoryURL:e,ref:t})),a=yield o.json();return(r=a).date&&(r.date=new Date(a.date)),a}))()}postWithRefresh(e,t){var n=this;return Tc((function*(){var r;if(n.isRefreshing)return n.queueRequest(e,t);if(null===(r=n.sessionManager.getCookie())||void 0===r?void 0:r.isUserTokenExpired(kc.BIAS_MS)){n.isRefreshing=!0;try{yield n.refreshSession()}catch(e){n.sessionManager.deleteCookie(),n.flushQueue(e)}n.flushQueue(),n.isRefreshing=!1}return n.post(e,t)}))()}post(e,t){var n=this;return Tc((function*(){return n.fetch(e,{method:"POST",body:t})}))()}refreshSession(){var e=this;return Tc((function*(){const t=yield e.fetch("/vcs.v1.VCSService/GithubRefresh",{method:"POST",body:JSON.stringify({})}),n=yield t.json();e.sessionManager.setCookie(n.cookie)}))()}queueRequest(e,t){var n=this;return Tc((function*(){return new Promise(((r,o)=>{n.pendingQueue.push((a=>{a?o(a):r(n.post(e,t))}))}))}))()}flushQueue(e=void 0){this.pendingQueue.forEach((t=>t(e))),this.pendingQueue=[]}constructor(e){super(e),Cc(this,"sessionManager",void 0),Cc(this,"pendingQueue",void 0),Cc(this,"isRefreshing",void 0),this.sessionManager=dc,this.isRefreshing=!1,this.pendingQueue=[]}}function jc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Ac(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){jc(a,r,o,i,s,"next",e)}function s(e){jc(a,r,o,i,s,"throw",e)}i(void 0)}))}}Cc(kc,"BIAS_MS",3e5);const Ic=btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));function Rc({dataSourceUid:e,children:t}){const n=es.build(e,ac),r=es.build(e,kc),[o,a]=(0,w.useState)(Oc.isLoginInProgress),[i,s]=function(){const[e,t]=(0,w.useState)(dc.getCookie());return[e,e=>{e?(dc.setCookie(e),t(dc.getCookie())):(dc.deleteCookie(),t(void 0))}]}(),[l,c]=(0,w.useState)();(0,w.useEffect)((()=>{s("")}),[e]),Ec({vcsClient:n,externalWindow:l,setExternalWindow:c,setSessionCookie:s,nonce:Ic});const u=!!l&&!l.closed;u!==o&&a(u);const d=(0,w.useCallback)(Ac((function*(){try{yield function(e,t,n,r,o){return gc.apply(this,arguments)}(n,r,i,l,c)}catch(e){Be(e,["Failed to login to GitHub",e.message])}})),[n,r,i,l]);return S().createElement(Pc.Provider,{value:{isLoginInProgress:o,isLoggedIn:Boolean(i&&!i.isUserTokenExpired()),isSessionExpired:Boolean(null==i?void 0:i.isUserTokenExpired()),login:d}},t)}class _c extends o.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(_c,"type","remove-span-selector");const Dc={metricsFromProfiles:!!a.config.featureToggles.metricsFromProfiles};function Lc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fc(e){for(var t=1;t`${e}${t}"${n}"`)).join(",");return Ro(new _t.dt({datasource:Jr,queries:[Fc({refId:"profile",queryType:"profile",profileTypeId:"$profileMetricId",labelSelector:`{${o},$filters}`,maxNodes:t},n&&{spanSelector:[n]})]}))}function Bc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Mc(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Bc(a,r,o,i,s,"next",e)}function s(e){Bc(a,r,o,i,s,"throw",e)}i(void 0)}))}}const Uc=new class extends G{get(){var e=this,t=()=>super.fetch;return Mc((function*(){return t().call(e,"/settings.v1.RecordingRulesService/ListRecordingRules",{method:"POST",body:JSON.stringify({})}).then((e=>e.json())).then((e=>e.rules?e.rules.map((e=>function(e){let t="";for(let r of e.matchers||[])if(r.includes("service_name=")){var n;t=(null==r||null===(n=r.match(/service_name="([^"]+)"/))||void 0===n?void 0:n[1])||"";break}return{id:e.id,metricName:e.metricName,serviceName:t,profileType:e.profileType,matchers:e.matchers,groupBy:e.groupBy||[]}}(e))):[]))}))()}create(e){var t=this,n=()=>super.fetch;return Mc((function*(){return n().call(t,"/settings.v1.RecordingRulesService/UpsertRecordingRule",{method:"POST",body:JSON.stringify({metricName:e.metricName,matchers:[`{ service_name="${e.serviceName}" }`,`{ __profile_type__="${e.profileType}"}`,...e.matchers||[]],groupBy:e.groupBy||[]})}).then((e=>e.json()))}))()}remove(e){var t=this,n=()=>super.fetch;return Mc((function*(){return n().call(t,"/settings.v1.RecordingRulesService/DeleteRecordingRule",{method:"POST",body:JSON.stringify({id:e.id})}).then((e=>e.json()))}))()}};function Vc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function qc({enabled:e}={}){const t=(0,E.jE)(),{isFetching:n,error:r,data:o}=(0,K.I)({enabled:e,queryKey:["recording_rules"],queryFn:()=>Uc.get()}),{mutateAsync:a}=(0,Ms.n)({mutationFn:e=>Uc.create(e),networkMode:"always"}),{mutateAsync:i}=(0,Ms.n)({mutationFn:function(){var e,n=(e=function*(e){yield Uc.remove(e),yield t.invalidateQueries({queryKey:["recording_rules"]})},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Vc(a,r,o,i,s,"next",e)}function s(e){Vc(a,r,o,i,s,"throw",e)}i(void 0)}))});return function(e){return n.apply(this,arguments)}}(),networkMode:"always"});return{isFetching:n,error:Uc.isAbortError(r)?null:r,recordingRules:o,mutate:a,remove:i}}function Gc(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Kc(){const{recordingRules:e,error:t,mutate:n}=qc();return{data:{recordingRules:e,fetchError:t},actions:{save(e){return(t=function*(){try{yield n(e),Ue([`Recording rule ${e.metricName} created successfully!`])}catch(t){Be(t,[`Failed to save recording rule ${e.metricName}.`])}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){Gc(a,r,o,i,s,"next",e)}function s(e){Gc(a,r,o,i,s,"throw",e)}i(void 0)}))})();var t}}}}var Hc=n(9215);function zc(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yc(e){for(var t=1;t{const{register:o,handleSubmit:a,control:s,formState:{errors:l}}=(0,Hc.mN)({mode:"onChange",shouldUnregister:!0}),[c,u]=(0,w.useState)([]),d=Wr(_t.jh.findByKeyAndType(e,"profileMetricId",ro).state.value),p=_t.jh.findByKeyAndType(e,"serviceName",so).state.value,m=_t.jh.findByKeyAndType(e,"filters",Oo).state.filters,f=m.map((e=>`${e.key}${e.operator}"${e.value}"`)).join(", ");return(0,w.useEffect)((()=>{const t=_t.jh.getTimeRange(e).state.value;dn.listLabels({query:`{${f}}`,from:1e3*t.from.unix(),to:1e3*t.to.unix()}).then((e=>{u(e.map((e=>e.value)))}))}),[f,e]),S().createElement(i.Modal,{title:"Create recording rule",isOpen:t,onDismiss:n},S().createElement("form",{onSubmit:a((e=>r({id:"",metricName:e.metricName,serviceName:e.serviceName,profileType:e.profileType,matchers:[`{${f}}`],groupBy:e.labels?e.labels.map((e=>{var t;return null!==(t=e.value)&&void 0!==t?t:""})):[]})))},S().createElement(i.Field,{label:"Metric name",description:"The name of the Prometheus metric",error:Jc(l.metricName),invalid:!!l.metricName},S().createElement(i.Input,Yc({placeholder:`pyroscope_metric_${d.type}_${p.toString().replace(/[^a-zA-Z0-9_]/g,"_")}`,required:!0,autoFocus:!0},o("metricName",{required:"Metric name is required.",pattern:{value:/^[a-zA-Z_][a-zA-Z0-9_]*$/,message:"Invalid metric name."}})))),S().createElement(i.Field,{label:"Additional labels",description:"Additional profiling labels to forward to the metric"},S().createElement(Hc.xI,{name:"labels",control:s,render:({field:e})=>S().createElement(i.MultiSelect,Wc(Yc({},e),{options:c.map((e=>({label:e,value:e}))),toggleAllOptions:{enabled:!0},closeMenuOnSelect:!1,hideSelectedOptions:!1}))})),S().createElement(i.Divider,null),S().createElement(i.Field,{label:"Service name"},S().createElement("div",null,`${p}`)),S().createElement("input",Yc({type:"text",value:p.toString(),hidden:!0},o("serviceName"))),S().createElement(i.Field,{label:"Profile type"},S().createElement("div",null,`${d.group}/${d.type}`)),S().createElement("input",Yc({type:"text",value:d.id,hidden:!0},o("profileType"))),S().createElement(i.Field,{label:"Filters",description:"Filters selected in the main view will be applied to this rule"},S().createElement("div",null,0===m.length?"No filters selected":f)),S().createElement(i.Modal.ButtonRow,null,S().createElement(i.Button,{variant:"secondary",fill:"outline",onClick:n},"Cancel"),S().createElement(i.Button,{variant:"primary",type:"submit"},"Create"))))}));const Jc=e=>{const t=(0,i.useStyles2)(Xc);if(void 0!==e&&void 0!==e.message)return"pattern"===e.type?S().createElement("span",null,S().createElement("span",null,"Metric name is invalid, it must have the following properties:"),S().createElement("ul",{className:t.errorList},S().createElement("li",null,"Only contain alphanumeric characters or underscores"),S().createElement("li",null,"Must not begin with a number"))):S().createElement("span",null,e.message)},Xc=e=>({errorList:r.css` padding-left: ${e.spacing(2)}; `});var Zc=n(585);function eu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tu(e,t,n,r){var o,a=arguments.length,i=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(a<3?o(i):a>3?o(t,n,i):o(t,n))||i);return a>3&&i&&Object.defineProperty(t,n,i),i}class nu extends Zc.Message{constructor(e,t,n,r,o){super(),eu(this,"profile_typeID",void 0),eu(this,"label_selector",void 0),eu(this,"start",void 0),eu(this,"end",void 0),eu(this,"max_nodes",void 0),this.profile_typeID=e,this.label_selector=t,this.start=n,this.end=r,this.max_nodes=o}}function ru(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function ou(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){ru(a,r,o,i,s,"next",e)}function s(e){ru(a,r,o,i,s,"throw",e)}i(void 0)}))}}tu([Zc.Field.d(1,"string")],nu.prototype,"profile_typeID",void 0),tu([Zc.Field.d(2,"string")],nu.prototype,"label_selector",void 0),tu([Zc.Field.d(3,"int64")],nu.prototype,"start",void 0),tu([Zc.Field.d(4,"int64")],nu.prototype,"end",void 0),tu([Zc.Field.d(5,"int64")],nu.prototype,"max_nodes",void 0);class au extends Wt{static buildPprofRequest(e,t,n){const{profileMetricId:r,labelsSelector:o}=Io(e),a=1e3*t.from.unix(),i=1e3*t.to.unix(),s=new nu(r,o,a,i,n);return nu.encode(s).finish()}selectMergeProfile({query:e,timeRange:t,maxNodes:n}){var r=this;return ou((function*(){return(yield r.fetch("/querier.v1.QuerierService/SelectMergeProfile",{method:"POST",headers:{"content-type":"application/proto"},body:new Blob([au.buildPprofRequest(e,t,n)])})).blob()}))()}selectMergeProfileJson({profileMetricId:e,labelsSelector:t,start:n,end:r,stackTrace:o,maxNodes:a}){var i=this;return ou((function*(){return(yield i.fetch("/querier.v1.QuerierService/SelectMergeProfile",{method:"POST",body:JSON.stringify({profile_typeID:e,label_selector:t,start:1e3*n,end:1e3*r,stackTraceSelector:{call_site:o.map((e=>({name:e})))},maxNodes:a})})).json()}))()}}function iu(e,t){const{serviceId:n,profileMetricId:r}=Io(e),o=`${t.from.format("YYYY-MM-DD_HHmm")}-to-${t.to.format("YYYY-MM-DD_HHmm")}`;return`${n.replace(/\//g,"-")}_${r}_${o}`}function su(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}const lu=new class extends q{upload(e,t){var n,r=this;return(n=function*(){const n=yield r.fetch("/upload/v1",{method:"POST",body:JSON.stringify({name:e,profile:btoa(JSON.stringify(t)),fileTypeData:{units:t.metadata.units,spyName:t.metadata.spyName},type:"json"})});return yield n.json()},function(){var e=this,t=arguments;return new Promise((function(r,o){var a=n.apply(e,t);function i(e){su(a,r,o,i,s,"next",e)}function s(e){su(a,r,o,i,s,"throw",e)}i(void 0)}))})()}constructor(){super("https://flamegraph.com/api",{"content-type":"application/json"})}};function cu(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function uu(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){cu(a,r,o,i,s,"next",e)}function s(e){cu(a,r,o,i,s,"throw",e)}i(void 0)}))}}function du(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class pu extends _t.Bs{fetchFlamebearerProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return uu((function*(){const o=es.build(e,Al);let a;try{a=yield o.get({query:t,timeRange:n,format:"json",maxNodes:r||Us.maxNodes})}catch(e){return Be(e,["Error while loading flamebearer profile data!",e.message]),null}return a}))()}fetchPprofProfile({dataSourceUid:e,query:t,timeRange:n,maxNodes:r}){return uu((function*(){const o=es.build(e,au);let a;try{const e=yield o.selectMergeProfile({query:t,timeRange:n,maxNodes:r||Us.maxNodes});a=yield new Response(e.stream().pipeThrough(new CompressionStream("gzip"))).blob()}catch(e){return Be(e,["Failed to export to pprof!",e.message]),null}return a}))()}constructor(){super({key:"export-flame-graph-menu"}),du(this,"useSceneExportMenu",(({query:e,timeRange:t})=>{const n=_t.jh.findByKeyAndType(this,"dataSource",uo).useState().value,[r]=Fl(),{settings:o}=Hs();var a=this;const i=function(){var o=uu((function*(){Re("g_pyroscope_app_export_profile",{format:"json"});const o=yield a.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const i=`${iu(e,t)}.json`,s=`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(o))}`;at()(s,i)}));return function(){return o.apply(this,arguments)}}();var s=this;const l=function(){var o=uu((function*(){Re("g_pyroscope_app_export_profile",{format:"pprof"});const o=yield s.fetchPprofProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(!o)return;const a=`${iu(e,t)}.pb.gz`;at()(o,a)}));return function(){return o.apply(this,arguments)}}();var c=this;const u=function(){var o=uu((function*(){Re("g_pyroscope_app_export_profile",{format:"flamegraph.com"});const o=yield c.fetchFlamebearerProfile({dataSourceUid:n,query:e,timeRange:t,maxNodes:r});if(o)try{const n=yield lu.upload(iu(e,t),o);if(!n.url)throw new Error("Empty URL received.");const r=document.createElement("a");r.target="_blank",r.href=n.url,document.body.appendChild(r),r.click(),document.body.removeChild(r)}catch(e){return void Be(e,["Failed to export to flamegraph.com!",e.message])}}));return function(){return o.apply(this,arguments)}}();return{data:{shouldDisplayFlamegraphDotCom:Boolean(null==o?void 0:o.enableFlameGraphDotComExport)},actions:{downloadPng:()=>{Re("g_pyroscope_app_export_profile",{format:"png"});const n=`${iu(e,t)}.png`;document.querySelector('canvas[data-testid="flameGraph"]').toBlob((e=>{if(e)at()(e,n);else{const e=new Error("Error while creating the image, no blob.");Be(e,["Failed to export to png!",e.message])}}),"image/png")},downloadJson:i,downloadPprof:l,uploadToFlamegraphDotCom:u}}}))}}function mu(){return(0,w.useContext)(Pc)}function fu(e){const{login:t,isSessionExpired:n}=mu(),{settings:r}=Hs(),a=null==r?void 0:r.enableFunctionDetails,[i,s]=(0,w.useState)([]),l=(0,w.useCallback)((({item:r},i)=>a&&0!==r.level?[{label:"Function details",icon:"info-circle",onClick:()=>{Re("g_pyroscope_app_function_details_clicked"),s(function(e,t){let n=[];const r=t.fields.find((({name:e})=>"label"===e));if(!r)return n;const a=(0,o.getDisplayProcessor)({field:r,theme:(0,o.createTheme)()});let i=e;for(;i&&i.level>0;){var s;for(const e of i.itemIndexes)n.unshift(a(r.values[e]).text);i=null===(s=i.parents)||void 0===s?void 0:s[0]}return n}(r,i)),e.open("function-details"),n&&t()}}]:[]),[a,n,t,e]);return{data:{stacktrace:i},actions:{getExtraFlameGraphMenuItems:l}}}du(pu,"Component",(({model:e,query:t,timeRange:n})=>{const{actions:r}=e.useSceneExportMenu({query:t,timeRange:n});return S().createElement(i.Dropdown,{overlay:S().createElement(i.Menu,null,S().createElement(i.Menu.Item,{label:"png",onClick:r.downloadPng}),S().createElement(i.Menu.Item,{label:"json",onClick:r.downloadJson}),S().createElement(i.Menu.Item,{label:"pprof",onClick:r.downloadPprof}))},S().createElement(i.Button,{icon:"download-alt",size:"sm",variant:"secondary",fill:"outline","aria-label":"Export profile data",tooltip:"Export profile data"}))}));const hu="gpt-4-1106-preview",gu=({functionDetails:e,lines:t})=>{const n=`\nYou are a code optimization expert. I will give you source code file where each line is annotated with profiling information. The annotation has the following format:\n\n\`\`\`\n() \n\`\`\`\n\nThe \`\`\`\`\`\` is the exact line of source code.\n\nThe \`\`\`\`\`\` field will contain the resource cost of the given resource cost. This field will also contain the unit of the cost (e.g. seconds, bytes, etc). If \`\`\`\`\`\` is \`-\` that means there is no profiling data available.\n\nI want you to write back a new improved code for this function and explain why you made changes.\n\nMake sure to take annotations into strong consideration. If a suggested performance improvement isn't backed up by information from the annotations, do not include it. Prioritize lines annotated with a higher cost.\n\nDo not mention the actual numbers from the annotations, users can already see how much time was spent on each line. Do not list various lines and their time spent. When you mention functions or lines, do not mention the time spent on them.\n\nIf you can't find any meaningful performance optimizations, say so. Ask for context if you think other context might help make decisions. If you think the problem is with user input and not the actual code itself, say so.\n\nWhen you output code in markdown, please don't specify language after 3 backticks (e.g instead of saying "\`\`\`go" say "\`\`\`"), and always add a new line after 3 backticks.\n\nFunction name is \`${e.name}\`. Do not mention the function name, users can already see it.\n\nWhen posting a response, follow the outline below:\n* give a brief explanation of things that could be improve\n* print new code if it's possible\n* explain each change in more details\n\n\nAnnotated code is below:\n\`\`\`\n${function(e,t){return t.map((t=>0===t.cum?`(-) ${t.line}`:`(${t.cum} ${e.unit}) ${t.line}`)).join("\n")}(e,t)}\n\`\`\`\n`;return{user:n}};function yu(e){const{reply:t,error:n}=function(e){const[t,n]=(0,w.useState)(""),[r,o]=(0,w.useState)(!1),[a,i]=(0,w.useState)(!1),[s,l]=(0,w.useState)([]),[c,u]=(0,w.useState)(null),d=(0,w.useCallback)((e=>{l(e),u(null),n(""),o(!0),i(!1),Cl.qH({model:hu,messages:e}).pipe(Cl.qA()).subscribe({next:n,error(e){u(e),o(!1),i(!0)},complete(){o(!1),i(!0)}})}),[]),p=(0,w.useCallback)((e=>{const n=[{role:"assistant",content:t},{role:"user",content:e}];try{d([...s,...n])}catch(e){u(e)}}),[s,t,d]);return(0,w.useEffect)((()=>{if(s.length>0)return;const t=gu(e);try{d([{role:"system",content:t.user}])}catch(e){u(e)}}),[s.length,e,d]),{reply:{text:t,hasStarted:r,hasFinished:a,messages:s,askFollowupQuestion:p},error:c}}(e);return{data:{isLoading:!n&&!t.text.trim(),llmError:n,reply:t,shouldDisplayReply:Boolean((null==t?void 0:t.hasStarted)||(null==t?void 0:t.hasFinished)),shouldDisplayFollowUpForm:!n&&Boolean(null==t?void 0:t.hasFinished)},actions:{submitFollowupQuestion(e){t.askFollowupQuestion(e)}}}}const bu=()=>({title:r.css` margin: -4px 0 4px 0; `,content:r.css``});function vu({suggestionPromptInputs:e}){const t=(0,i.useStyles2)(bu),{data:n,actions:r}=yu(e);return S().createElement(S().Fragment,null,S().createElement("h6",{className:t.title},"Code Optimization Suggestions"),S().createElement("div",{className:t.content},n.isLoading&&S().createElement(S().Fragment,null,S().createElement(i.Spinner,{inline:!0})," Analyzing..."),n.fetchError&&S().createElement(zs,{severity:"error",title:"Error while fetching profiles!",message:"Sorry for any inconvenience, please try again later."}),n.llmError&&S().createElement(zs,{severity:"error",title:"Failed to generate content using OpenAI!",error:n.llmError,message:"Sorry for any inconvenience, please try again later or if the problem persists, contact your organization admin."}),n.shouldDisplayReply&&S().createElement(Ol,{reply:n.reply}),n.shouldDisplayFollowUpForm&&S().createElement(Tl,{onSubmit:r.submitFollowupQuestion})))}const Eu=5;function wu(e,t){let n=e;const r=e.match(/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(.+)/);if(r){const[,e,t,o]=r;n=`https://github.com/${e}/${t}/blob/${o}`}return void 0===t||e.includes("#")||(n+=`#L${t}`),n}function Su(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ou(e){for(var t=1;ti.getFile(n,r,o,a).then((e=>({content:e.content,URL:e.URL}))).then((e=>({URL:e.URL,content:atob(e.content)})))});return{isFetching:s,error:i.isAbortError(l)?null:l,fileInfo:c}}({enabled:n,dataSourceUid:e,localPath:t.fileName,repository:null!==(i=null==r?void 0:r.repository)&&void 0!==i?i:"",gitRef:null!==(s=null==r?void 0:r.git_ref)&&void 0!==s?s:"",rootPath:null!==(l=null==r?void 0:r.root_path)&&void 0!==l?l:""}),{snippetLines:p,allLines:m}=(0,w.useMemo)((()=>(null==c?void 0:c.content)?function(e,t){const n=Array.from(t.values()).sort(((e,t)=>e.line-t.line)),r=e.split("\n"),o=r.map(((e,n)=>{const r=n+1,o=t.get(r);var a,i;return{line:e,number:r,cum:null!==(a=null==o?void 0:o.cum)&&void 0!==a?a:0,flat:null!==(i=null==o?void 0:o.flat)&&void 0!==i?i:0}}));if(0===t.size)return{snippetLines:[],allLines:o};const a=Math.max(0,n[0].line-Eu-1),i=Math.min(r.length,n[n.length-1].line+Eu);return{snippetLines:o.slice(a,i),allLines:o}}(c.content,t.callSites):function(e){if(!e.size)return{snippetLines:[],allLines:[]};const t=Array.from(e.values()).sort(((e,t)=>e.line-t.line)),n=Math.max(0,t[0].line-Eu-1),r=t[t.length-1].line+Eu+1,o=[];for(let t=n+1;t{var t;return Pu(Ou({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),allLines:m.map((e=>{var t;return Pu(Ou({},e),{line:null!==(t=e.line)&&void 0!==t?t:"???"})})),noCodeAvailable:Boolean(u)||!m.some((e=>e.line))},actions:{setOpenAiSuggestions:a}}}function Tu(e){switch(e){case"nanoseconds":return(0,o.getValueFormat)("ns");case"microseconds":return(0,o.getValueFormat)("µs");case"milliseconds":return(0,o.getValueFormat)("ms");case"seconds":return(0,o.getValueFormat)("s");case"count":return(0,o.getValueFormat)("short");default:return(0,o.getValueFormat)(e)}}const Cu=({lines:e,unit:t,githubUrl:n,isLoadingCode:o,noCodeAvailable:a,onOptimizeCodeClick:s})=>{const l=(0,i.useStyles2)(Iu),c=Tu(t),u=e=>{if(e<=0)return".";const t=c(e);return t.suffix?t.text+t.suffix:t.text};ku(e);const[d,p]=e.reduce((([e,t],{flat:n,cum:r})=>[e+n,t+r]),[0,0]);return S().createElement("div",{"data-testid":"function-details-code-container"},S().createElement("div",{className:l.container},S().createElement("div",{className:l.header},S().createElement("div",{className:l.breakdownLabel},S().createElement("h6",null,"Breakdown per line"),S().createElement("span",null,o&&S().createElement(i.Spinner,{inline:!0}),!o&&a&&"(file information unavailable)")),S().createElement("div",{className:l.buttons},S().createElement(i.LinkButton,{disabled:Boolean(o||!n),href:n,target:"_blank",icon:"github",fill:"text"},"View on GitHub"),S().createElement(bl,{onClick:s,disabled:o||a,interactionName:"g_pyroscope_app_optimize_code_clicked"},"Optimize Code")))),S().createElement("pre",{className:l.codeBlock,"data-testid":"function-details-code"},S().createElement("div",{className:(0,r.cx)(l.highlighted,l.codeBlockHeader)},Nu("Total:",u(d),u(p)," (self, total)")),e.map((({line:e,number:t,cum:n,flat:r})=>S().createElement("div",{key:e+t+n+r,className:r+n>0?l.highlighted:""},Nu(`${t} `,u(r),u(n),e))))))},Nu=(e,t,n,r)=>{const o=e.padStart(7," ")+t.padStart(12," ")+n.padStart(12," ");return r?`${o} ${r}`:o},ku=e=>{if(0===e.length)return;let t=ju(e[0].line);for(let n=1;n{const t=e.match(/^[ \t]*/);var n;return null!==(n=null==t?void 0:t[0])&&void 0!==n?n:""},Au=(e,t)=>{let n=0;for(let r=0;r({container:r.css` display: flex; flex-direction: row; align-items: flex-start; width: 100%; `,header:r.css` display: flex; justify-content: space-between; align-items: end; width: 100%; `,breakdownLabel:r.css` & > h6 { display: inline-block; margin-top: ${e.spacing(1)}; } & > span { margin-left: ${e.spacing(1)}; font-size: ${e.typography.bodySmall.fontSize}; } & > svg { margin-left: ${e.spacing(1)}; } `,buttons:r.css` display: flex; flex-wrap: no-wrap; `,codeBlock:r.css` position: relative; min-height: 240px; font-size: 12px; overflow-x: auto; white-space: pre; color: ${e.colors.text.secondary}; `,highlighted:r.css` color: ${e.colors.text.maxContrast}; `,codeBlockHeader:r.css` margin-bottom: 8px; `});function Ru({dataSourceUid:e,functionDetails:t}){var n,r;const{data:o,actions:a}=xu(e,t);return o.fetchError&&404!==(null===(r=o.fetchError)||void 0===r||null===(n=r.response)||void 0===n?void 0:n.status)&&Be(o.fetchError,["Failed to fetch file information!",o.fetchError.message]),S().createElement(S().Fragment,null,S().createElement(Cu,{lines:o.snippetLines,unit:o.unit,githubUrl:o.githubUrl,isLoadingCode:o.isLoadingCode,noCodeAvailable:o.noCodeAvailable,onOptimizeCodeClick:()=>{var e;a.setOpenAiSuggestions(!0),null===(e=document.getElementById("ai-suggestions-panel"))||void 0===e||e.scrollIntoView({behavior:"smooth"})}}),S().createElement("h6",{id:"ai-suggestions-panel",style:{height:0,marginBottom:0}}),o.openAiSuggestions?S().createElement(vu,{suggestionPromptInputs:{functionDetails:t,lines:o.allLines}}):null)}const _u=e=>({ellipsis:r.css` color: ${e.colors.primary.text}; text-overflow: ellipsis; overflow: hidden; direction: rtl; white-space: nowrap; `}),Du=({enableIntegration:e,repository:t})=>{const n=(0,i.useStyles2)(_u),{isLoginInProgress:r,isLoggedIn:o,login:a}=mu();return e?r?S().createElement(S().Fragment,null,S().createElement(i.Spinner,null),S().createElement("span",null,"Connecting to GitHub...")):o?S().createElement(S().Fragment,null,S().createElement(i.Icon,{name:"github",size:"lg"}),S().createElement("a",{className:n.ellipsis,href:t.commitUrl,target:"_blank",rel:"noreferrer",title:"View commit"},S().createElement(i.Icon,{name:"external-link-alt"})," ",t.commitName)):S().createElement(i.Button,{icon:"github",variant:"primary",onClick:a,tooltip:"Once connected, the GitHub code will be accessible only from this browser session.",tooltipPlacement:"top"},"Connect to ",t.name):S().createElement(S().Fragment,null,"-")};function Lu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fu(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function $u(e,t){const n=e.map((e=>{var n;return Fu(function(e){for(var t=1;te+t),0),total:t}})}));return n}const Bu="https://github.com/";function Mu(e,t){if(!(null==t?void 0:t.repository))return null;const n=t.repository,r=n.replace(Bu,""),o=t.git_ref;return{isGitHub:e,url:n,name:r,commitUrl:o?`${n}/commit/${o}`:n,commitName:o?`${r}@${o.substring(0,7)}`:r}}const Uu=(e,t,n)=>{let r;try{r=n?JSON.parse(e.stringTable[Number(n.buildId)]):void 0}catch(e){}return{name:e.stringTable[Number(t.name)],version:r,startLine:Number.isNaN(Number(t.startLine))?void 0:Number(t.startLine),fileName:e.stringTable[Number(t.filename)],callSites:new Map,unit:e.stringTable[Number(e.sampleType[0].unit)],commit:Nc}};function Vu(e,t,n,r,o,a,i){const s=new Set;a.locationId.forEach(((l,c)=>{const u=n.get(l);u&&u.line.forEach((n=>{const d=r.get(n.functionId);if(!d)return;if(t.stringTable[Number(d.name)]!==e)return;if(s.has(l))return;s.add(l);const p=i.get(u.mappingId)||Uu(t,d,o.get(u.mappingId));i.set(u.mappingId,function(e,t,n,r){const o=Number(t.line),a=e.callSites.get(o)||{line:Number(t.line),flat:0,cum:0},i=0===r?n:0,s=n;return a.flat+=i,a.cum+=s,e.callSites.set(o,a),e}(p,n,Number(a.value[0]),c))}))}))}function qu(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Gu(){var e;return e=function*(e,t){const n=es.build(e,kc),r=t.map((e=>{var t,n,r;return{repositoryUrl:(null==e||null===(t=e.version)||void 0===t?void 0:t.repository)||"",gitRef:(null==e||null===(n=e.version)||void 0===n?void 0:n.git_ref)||"HEAD",rootPath:(null==e||null===(r=e.version)||void 0===r?void 0:r.root_path)||""}}));return(yield n.getCommits(r)).forEach(((e,n)=>{t[n].commit=e})),t},Gu=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){qu(a,r,o,i,s,"next",e)}function s(e){qu(a,r,o,i,s,"throw",e)}i(void 0)}))},Gu.apply(this,arguments)}const Ku=e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0),Hu=(e,t)=>Ku(t)-Ku(e);function zu(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Yu(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){zu(a,r,o,i,s,"next",e)}function s(e){zu(a,r,o,i,s,"throw",e)}i(void 0)}))}}function Wu({dataSourceUid:e,query:t,timeRange:n,stackTrace:r}){const{profileMetricId:o,labelsSelector:a}=Io(t),[i,s]=[n.from.unix(),n.to.unix()],{isLoggedIn:l}=mu(),c=es.build(e,au),{isFetching:u,error:d,data:p}=(0,K.I)({enabled:Boolean(o&&a&&r.length>0&&i>0&&s>0),queryKey:["function-details",o,a,i,s,r,l],queryFn:Yu((function*(){const t=yield c.selectMergeProfileJson({profileMetricId:o,labelsSelector:a,start:i,end:s,stackTrace:r,maxNodes:500}),n=function(e,t){var n,r,o,a;const i=new Map,s=new Map(null===(n=t.location)||void 0===n?void 0:n.map((e=>[e.id,e]))),l=new Map(null===(r=t.function)||void 0===r?void 0:r.map((e=>[e.id,e]))),c=new Map(null===(o=t.mapping)||void 0===o?void 0:o.map((e=>[e.id,e])));return null===(a=t.sample)||void 0===a||a.filter((e=>void 0!==e.locationId)).forEach((n=>Vu(e,t,s,l,c,n,i))),Array.from(i.values())}(r[r.length-1],t).sort(Hu);return l?function(e,t){return Gu.apply(this,arguments)}(e,n):n}))}),m=(0,w.useMemo)((()=>(null==p?void 0:p.length)?p:[{name:r.at(-1),startLine:void 0,fileName:"",callSites:new Map,unit:"",commit:Nc}]),[p,r]);return{isFetching:u,error:c.isAbortError(d)?null:d,functionsDetails:m}}const Qu=[60,3600,86400,604800,2592e3,31536e3,1/0],Ju=["second","minute","hour","day","week","month","year"],Xu=new Intl.RelativeTimeFormat("en-US",{numeric:"auto"});const Zu=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"2-digit"});function ed(e){return e?`${Zu.format(e)} (${function(e){const t=e.getTime(),n=Math.round((t-Date.now())/1e3),r=Qu.findIndex((e=>e>Math.abs(n))),o=r?Qu[r-1]:1;return Xu.format(Math.floor(n/o),Ju[r])}(e)})`:"?"}const td=e=>({container:r.css` display: flex; flex-direction: column; justify-content: flex-start; `,firstLine:r.css` display: flex; flex-direction: row; align-items: center; gap: 1em; `,sha:r.css` font-family: monospace; `,sample:r.css` font-size: 12px; `,secondLine:r.css` display: flex; flex-direction: row; align-items: center; font-size: 12px; color: ${e.colors.text.secondary}; `,avatar:r.css` display: inline-block; margin-right: 4px; border-radius: 50%; background: grey; width: 16px; height: 16px; `,message:r.css` font-size: 12px; color: ${e.colors.text.secondary}; `});function nd({commit:e}){const t=(0,i.useStyles2)(td),{author:n,samples:r}=e,o=n.login,a=n.avatarURL,s=Tu(r.unit)(r.current),l=Math.round(r.current/r.total*100);return S().createElement("div",{className:t.container},S().createElement("div",{className:t.firstLine},S().createElement("span",{className:t.sha},sd(e.sha)),S().createElement("span",{className:t.sample},s.text,s.suffix," (",l,"%)")),S().createElement("div",{className:t.secondLine},a&&S().createElement("img",{className:t.avatar,src:a,alt:o}),S().createElement("span",null,o," on ",ed(e.date))),S().createElement("span",{className:t.message},ld(e.message)))}const rd=e=>({container:r.css` display: flex; flex-direction: row; justify-content: flex-start; align-items: center; gap: 1em; `,sha:r.css` font-family: monospace; `,message:r.css` color: ${e.colors.text.secondary}; `});function od({commit:e}){const t=(0,i.useStyles2)(rd);return S().createElement("div",{className:t.container},S().createElement("span",{className:t.sha},sd(e.sha)),S().createElement("div",{className:t.message},S().createElement("span",null,ld(e.message))))}function ad({commits:e,selectedCommit:t,onChange:n}){return S().createElement(i.Select,{options:e.map((e=>({label:e.sha,value:e}))),value:{label:t.sha,value:t},hideSelectedOptions:!0,isSearchable:!1,noOptionsMessage:"No commits found",formatOptionLabel:id,onChange:e=>{e.value&&n(e.value)}})}function id(e,t){var n;const{value:r}=e;if(!r)return null;return(null===(n=t.selectValue[0])||void 0===n?void 0:n.value)===r?S().createElement(od,{commit:r}):S().createElement(nd,{commit:r})}const sd=e=>e===Nc.sha?e:e.substring(0,7),ld=e=>e.split("\n")[0],cd=({onDismiss:e})=>S().createElement(i.Alert,{severity:"info",title:"Integrate with Github",buttonContent:"Dismiss",onRemove:e},S().createElement("p",null,"This language supports integration with ",S().createElement(i.Icon,{name:"github"})," GitHub."),S().createElement("p",null,"To activate this feature, you will need to add two new labels when sending profiles"," ",S().createElement("code",null,"service_repository")," and ",S().createElement("code",null,"service_git_ref"),"."," "),S().createElement("p",null,"They should respectively be set to the full repository GitHub URL and the current"," ",S().createElement(i.TextLink,{href:"https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#about-git-references",external:!0},"git ref")," ","of the running service."),S().createElement(i.Icon,{name:"document-info"})," ",S().createElement(i.TextLink,{href:"https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/pyroscope-github-integration/",external:!0},"Learn more"));function ud({isLoading:e,children:t}){return e?S().createElement(i.Spinner,{inline:!0}):S().createElement(S().Fragment,null,t)}const dd=(0,w.memo)(ud);function pd(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function md(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class fd extends _t.Bs{constructor(){super({key:"function-details-panel"}),md(this,"useSceneFunctionDetailsPanel",((e,t)=>{var n,r;const o=_t.jh.findByKeyAndType(this,"dataSource",uo).useState().value,a=co(this,"filters"),{functionsDetails:i,error:s,isFetching:l}=Wu({dataSourceUid:o,query:a,timeRange:t,stackTrace:e}),[c,u]=(0,w.useState)(),[d,p]=(0,w.useState)(i[0]),[m,f]=(0,w.useState)(D.has(D.KEYS.GITHUB_INTEGRATION));i&&c!==i&&(u(i),d!==i[0]&&p(i[0]));const h=((null==d||null===(n=d.version)||void 0===n?void 0:n.repository)||"").startsWith(Bu);const g=null==d||null===(r=d.fileName)||void 0===r?void 0:r.endsWith(".go"),y=!m&&!h&&g,b=(0,w.useMemo)((()=>i.map((e=>Array.from(e.callSites.values()).reduce(((e,{cum:t})=>e+t),0))).reduce(((e,t)=>e+t),0)),[i]),v=$u(i,b),E=v.find((({sha:e})=>{var t;return e===(null==d||null===(t=d.commit)||void 0===t?void 0:t.sha)}));return{data:{isLoading:l,fetchFunctionDetailsError:s,functionDetails:d,repository:Mu(h,null==d?void 0:d.version),commits:v,selectedCommit:E,isGitHubSupported:g,shouldDisplayGitHubBanner:y,dataSourceUid:o},actions:{selectCommit(e){const t=i.find((({commit:t})=>t.sha===e.sha));p(t)},copyFilePathToClipboard(){return(e=function*(){try{(null==d?void 0:d.fileName)&&(yield navigator.clipboard.writeText(d.fileName),Ue(["File path copied to clipboard!"]))}catch(e){}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){pd(a,r,o,i,s,"next",e)}function s(e){pd(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e},dismissGitHubBanner(){D.set(D.KEYS.GITHUB_INTEGRATION,{}),f(!0)}}}}))}}md(fd,"LABEL_WIDTH",16),md(fd,"Component",(({model:e,timeRange:t,stackTrace:n,onClose:r})=>{const o=(0,i.useStyles2)(hd),{data:a,actions:s}=e.useSceneFunctionDetailsPanel(n,t);return S().createElement(gl,{className:o.sidePanel,title:"Function Details",isLoading:!1,headerActions:S().createElement(i.IconButton,{name:"times-circle",variant:"secondary","aria-label":"close",onClick:r}),dataTestId:"function-details-panel"},S().createElement("div",{className:o.content},a.fetchFunctionDetailsError&&S().createElement(zs,{severity:"error",title:"Error while fetching function details!",error:a.fetchFunctionDetailsError}),S().createElement("div",{className:o.container},S().createElement("div",{className:o.row,"data-testid":"row-function-name"},S().createElement(i.InlineLabel,{width:fd.LABEL_WIDTH},"Function name"),S().createElement(i.Tooltip,{content:a.functionDetails.name,placement:"top"},S().createElement("span",{className:o.textValue},a.functionDetails.name))),S().createElement("div",{className:o.row,"data-testid":"row-start-line"},S().createElement(i.InlineLabel,{tooltip:"The line where this function definition starts",width:fd.LABEL_WIDTH},"Start line"),S().createElement("span",{className:o.textValue},S().createElement(dd,{isLoading:a.isLoading},void 0!==a.functionDetails.startLine?a.functionDetails.startLine:"-"))),S().createElement("div",{className:o.row,"data-testid":"row-file-path"},S().createElement(i.InlineLabel,{tooltip:"File path where that function is defined",width:fd.LABEL_WIDTH},"File"),S().createElement(dd,{isLoading:a.isLoading},a.functionDetails.fileName?S().createElement(S().Fragment,null,S().createElement(i.Tooltip,{content:a.functionDetails.fileName,placement:"top"},S().createElement("span",{className:o.textValue},"‎","/"===(null==(l=a.functionDetails.fileName)?void 0:l[0])?l.substring(1)+"/":l)),S().createElement(i.IconButton,{name:"clipboard-alt",tooltip:"Copy to clipboard",onClick:s.copyFilePathToClipboard})):"-")),a.shouldDisplayGitHubBanner&&S().createElement("div",{className:o.row,"data-testid":"row-github-banner"},S().createElement(cd,{onDismiss:s.dismissGitHubBanner})),S().createElement("div",{className:o.row,"data-testid":"row-repository"},S().createElement(i.InlineLabel,{tooltip:"The repository configured for the selected service",width:fd.LABEL_WIDTH},"Repository"),S().createElement(dd,{isLoading:a.isLoading},a.repository?a.repository.isGitHub?S().createElement(Du,{enableIntegration:a.isGitHubSupported,repository:a.repository}):S().createElement(i.TextLink,{href:a.repository,external:!0},a.repository):"-")),S().createElement("div",{className:o.row,"data-testid":"row-commit"},S().createElement(i.InlineLabel,{width:fd.LABEL_WIDTH,tooltip:"The version of the application (commit) where the function is defined. Use the dropdown menu to target a specific commit."},"Commit"),S().createElement(dd,{isLoading:a.isLoading},S().createElement(ad,{commits:a.commits,selectedCommit:a.selectedCommit,onChange:s.selectCommit})))),S().createElement(Ru,{dataSourceUid:a.dataSourceUid,functionDetails:a.functionDetails})));var l}));const hd=e=>({sidePanel:r.css` flex: 1 0 50%; margin-left: 8px; max-width: calc(50% - 4px); `,title:r.css` margin: -4px 0 4px 0; `,content:r.css` padding: ${e.spacing(1)}; `,container:r.css` width: 100%; display: flex; flex-direction: column; align-items: flex-start; `,row:r.css` width: 100%; display: flex; flex-direction: row; align-items: center; padding-bottom: 10px; > * { margin-right: 10px !important; } `,textValue:r.css` // hack to have the ellipsis appear at the start of the string direction: rtl; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; `});function gd(e){const{spanSelector:t,removeSpanSelector:n}=e,r=(0,i.useStyles2)(yd);return S().createElement("div",{className:r.container},S().createElement(i.Tooltip,{content:`You have added a span selector to the flamegraph query (${t}).`,placement:"top"},S().createElement("span",null,"Span selector added")),S().createElement(i.Button,{size:"md",fill:"text",variant:"secondary",icon:"times",tooltip:"Remove span selector from query",tooltipPlacement:"top",onClick:()=>{n()}}))}const yd=()=>({container:r.css` padding: 0 4px; `});function bd(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class vd extends _t.Bs{onActivate(){let e;const t=this.subscribeToState(((t,n)=>{var r;t.$data!==n.$data&&(e&&e.unsubscribe(),e=null===(r=t.$data)||void 0===r?void 0:r.subscribeToState((e=>{var t;(null===(t=e.data)||void 0===t?void 0:t.state)===o.LoadingState.Done&&this.setState({lastTimeRange:e.data.timeRange})})))}));return()=>{t.unsubscribe(),null==e||e.unsubscribe()}}buildTitle(){const e=Po(this,"serviceName"),t=Wr(Po(this,"profileMetricId")).type;return S().createElement(S().Fragment,null,S().createElement(te,{size:"small"}),"Flame graph for ",e," (",t,")")}removeSpanSelector(){this.publishEvent(new _c({}),!0)}constructor(){super({key:"flame-graph",$data:new _t.dt({datasource:Jr,queries:[]}),lastTimeRange:void 0,exportMenu:new pu,aiPanel:new Rl,functionDetailsPanel:new fd,createRecordingRuleModal:new Qc}),bd(this,"useSceneFlameGraph",(e=>{var t,n,r,a,s;const{isLight:l}=(0,i.useTheme2)(),c=(0,w.useMemo)((()=>()=>(0,o.createTheme)({colors:{mode:l?"light":"dark"}})),[l]),[u]=Fl(),{settings:d,error:p}=Hs(),{$data:m,lastTimeRange:f,exportMenu:h,aiPanel:g,functionDetailsPanel:y,createRecordingRuleModal:b}=this.useState();p&&Me(["Error while retrieving the plugin settings!","Some features might not work as expected (e.g. collapsed flame graphs). Please try to reload the page, sorry for the inconvenience."]),(0,w.useEffect)((()=>{u&&this.setState({$data:$c({maxNodes:u,spanSelector:e})})}),[u,e]);const v=m.useState(),E=null==v||null===(t=v.data)||void 0===t?void 0:t.state,S=E===o.LoadingState.Error?(null==v||null===(r=v.data)||void 0===r||null===(n=r.errors)||void 0===n?void 0:n[0])||new Error("Unknown error!"):null,O=E===o.LoadingState.Loading,P=null==v||null===(s=v.data)||void 0===s||null===(a=s.series)||void 0===a?void 0:a[0],x=Number(null==P?void 0:P.length)>1,T=co(this,"filters");return{data:{title:this.buildTitle(),isLoading:O,isFetchingProfileData:O,hasProfileData:x,profileData:P,spanSelector:e,fetchProfileError:S,settings:d,export:{menu:h,query:T,timeRange:f},ai:{panel:g,fetchParams:[{query:T,timeRange:f}]},gitHub:{panel:y,timeRange:f},recordingRules:{modal:b}},actions:{getTheme:c}}})),this.addActivationHandler(this.onActivate.bind(this))}}bd(vd,"Component",(({model:e})=>{var t;const n=(0,i.useStyles2)(Ed),r=Po(e,"spanSelector"),{data:o,actions:a}=e.useSceneFlameGraph(r),s=Bs(),l=fu(s),{settings:c}=Hs(),{actions:u}=Kc(),[d,p]=(0,w.useState)(!1),m=(f=()=>p(!0),{data:{},actions:{getExtraFlameGraphMenuItems:(0,w.useCallback)((({item:e})=>0!==e.level?[]:[{label:"Create recording rule",icon:"download-alt",onClick:f}]),[f])}});var f;const h=o.isLoading||!o.hasProfileData;(0,w.useEffect)((()=>{h&&s.close()}),[h,s]);const g=(0,w.useMemo)((()=>S().createElement(S().Fragment,null,o.title,o.isLoading&&S().createElement(i.Spinner,{inline:!0,className:n.spinner}))),[o.isLoading,o.title,n.spinner]);return S().createElement("div",{className:n.flex},S().createElement(gl,{dataTestId:"flame-graph-panel",className:n.flamegraphPanel,title:g,isLoading:o.isLoading,headerActions:S().createElement(S().Fragment,null,r&&S().createElement(gd,{spanSelector:r,removeSpanSelector:()=>e.removeSpanSelector()}),S().createElement(bl,{disabled:h||s.isOpen("ai"),onClick:()=>s.open("ai"),interactionName:"g_pyroscope_app_explain_flamegraph_clicked"},"Explain Flame Graph"))},o.fetchProfileError&&S().createElement(zs,{severity:"error",title:"Error while loading profile data!",error:o.fetchProfileError}),!o.fetchProfileError&&S().createElement(rt.A,{data:o.profileData,disableCollapsing:!(null===(t=o.settings)||void 0===t?void 0:t.collapsedFlamegraphs),getTheme:a.getTheme,getExtraContextMenuButtons:(e,t)=>[...l.actions.getExtraFlameGraphMenuItems(e,t),...(null==c?void 0:c.enableMetricsFromProfiles)&&Dc.metricsFromProfiles?m.actions.getExtraFlameGraphMenuItems(e,t):[]],extraHeaderElements:S().createElement(o.export.menu.Component,{model:o.export.menu,query:o.export.query,timeRange:o.export.timeRange}),keepFocusOnDataChange:!0})),s.isOpen("ai")&&S().createElement(o.ai.panel.Component,{model:o.ai.panel,fetchParams:o.ai.fetchParams,onClose:s.close}),s.isOpen("function-details")&&S().createElement(o.gitHub.panel.Component,{model:o.gitHub.panel,timeRange:o.gitHub.timeRange,stackTrace:l.data.stacktrace,onClose:s.close}),S().createElement(o.recordingRules.modal.Component,{model:o.recordingRules.modal,isModalOpen:d,onDismiss:()=>p(!1),onCreate:e=>{u.save(e),p(!1)}}))}));const Ed=e=>({flex:r.css` display: flex; `,flamegraphPanel:r.css` min-width: 0; flex-grow: 1; `,spinner:r.css` margin-left: ${e.spacing(1)}; `});class wd extends _t.Bs{onActivate(e){e&&this.initVariables(e);const t=_t.jh.findByKeyAndType(this,"profileMetricId",ro);return t.setState({query:ro.QUERY_SERVICE_NAME_DEPENDENT}),t.update(!0),()=>{t.setState({query:ro.QUERY_DEFAULT}),t.update(!0)}}initVariables(e){const{serviceName:t,profileMetricId:n,filters:r}=e.queryRunnerParams;if(t){_t.jh.findByKeyAndType(this,"serviceName",so).changeValueTo(t)}if(n){_t.jh.findByKeyAndType(this,"profileMetricId",ro).changeValueTo(n)}if(r){_t.jh.findByKeyAndType(this,"filters",Oo).setState({filters:r})}}getVariablesAndGridControls(){return{variables:[_t.jh.findByKeyAndType(this,"serviceName",so),_t.jh.findByKeyAndType(this,"profileMetricId",ro),_t.jh.findByKeyAndType(this,"filters",Oo)],gridControls:[]}}static Component({model:e}){const t=(0,i.useStyles2)(Sd),{mainTimeseries:n,body:r}=e.useState();return S().createElement("div",{className:t.flex},S().createElement("div",{className:t.mainTimeseries},S().createElement(n.Component,{model:n})),S().createElement(r.Component,{model:r}))}constructor({item:e}){super({key:"explore-service-flame-graph",mainTimeseries:new hi({item:e,headerActions:e=>[new Wa({type:"view-labels",item:e}),new Da({item:e})]}),body:new vd}),this.addActivationHandler(this.onActivate.bind(this,e))}}const Sd=e=>({flex:r.css` display: flex; flex-direction: column; width: 100%; gap: ${e.spacing(1)}; `,mainTimeseries:r.css` height: ${hi.MIN_HEIGHT}px; `});function Od(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Pd(){return xd.apply(this,arguments)}function xd(){var e;return e=function*(){Re("g_pyroscope_app_share_link_clicked");try{yield navigator.clipboard.writeText(function(){const e=new URL(window.location.toString()),{searchParams:t}=e;return t.get("from")||t.set("from",Qi().from),t.get("to")||t.set("to",Qi().to),["from","to","from-2","to-2","from-3","to-3","diffFrom","diffTo","diffFrom-2","diffTo-2"].forEach((e=>{const n=t.get(e);n&&t.set(e,String(o.dateMath.parse(n).valueOf()))})),e}().toString()),Ue(["Link copied to clipboard!"])}catch(e){A.error(e,{info:"Error while creating the shareable link!"})}},xd=function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Od(a,r,o,i,s,"next",e)}function s(e){Od(a,r,o,i,s,"throw",e)}i(void 0)}))},xd.apply(this,arguments)}function Td({options:e,value:t,onChange:n}){const o=(0,i.useStyles2)(Cd),a=e.findIndex((e=>e.value===t));return S().createElement("div",{className:o.explorationTypeContainer,"data-testid":"exploration-types"},S().createElement("div",{className:o.label},"Exploration"),S().createElement("div",{className:o.breadcrumb},e.map(((s,l)=>{const c=t===s.value,u=(d=l,a===e.length-1?d===a?"primary":"secondary":d<=a?"primary":"secondary");var d;const p=[c&&"active","primary"===u&&"primary"];return S().createElement(w.Fragment,{key:s.value},S().createElement(i.Button,{className:(0,r.cx)(o.button,...p),variant:u,size:"sm","aria-label":s.label,icon:s.icon,onClick:c?L:()=>n(s.value),tooltip:s.description,tooltipPlacement:"top","data-testid":c?"is-active":void 0},s.label),l({explorationTypeContainer:r.css` display: flex; align-items: center; `,label:r.css` display: flex; gap: 2px; align-items: center; font-size: 14px; margin-right: ${e.spacing(1)}; ${e.breakpoints.down("xxl")} { display: none; } `,breadcrumb:r.css` display: flex; align-items: center; height: 32px; line-height: 32px; .active { background-color: ${e.colors.primary.main}; } .arrow.primary { background-color: ${e.colors.primary.main}; } & button.primary:not(.active), & .arrow.primary:not(.active) { opacity: 0.7; } & button.primary:not(.active):hover { opacity: 1; background-color: ${e.colors.primary.main}; } `,button:r.css` height: 27px; line-height: 27px; border-radius: 15px; &:hover { border-color: ${e.colors.primary.main}; } &.active:hover { cursor: default; background-color: ${e.colors.primary.main}; } &:nth-last-child(2) { margin-left: ${e.spacing(1)}; } &:nth-last-child(1) { margin-left: ${e.spacing(2)}; } `,arrow:r.css` background-color: ${e.colors.text.disabled}; width: 10px; height: 2px; `});function Nd(e){const t=null===a.useChromeHeaderHeight||void 0===a.useChromeHeaderHeight?void 0:(0,a.useChromeHeaderHeight)(),n=(0,i.useStyles2)(kd,null!=t?t:0),{data:o,actions:s}=function({explorationType:e,controls:t,body:n,$variables:r,onChangeExplorationType:o}){const[a,i]=e===Ad.DIFF_FLAME_GRAPH?[]:t,s=r.state.variables[0],l=null==n?void 0:n.state.primary;if("function"!=typeof l.getVariablesAndGridControls)throw new Error(`Error while rendering "${l.constructor.name}": the "getVariablesAndGridControls" method is missing! Please implement it.`);const{variables:c,gridControls:u}=l.getVariablesAndGridControls(),d=s.useState().value,f=(0,Ne.useNavigate)();return{data:{explorationType:e,dataSourceVariable:s,timePickerControl:a,refreshPickerControl:i,sceneVariables:c,gridControls:u,body:n,dataSourceUid:d},actions:{onChangeExplorationType:o,onClickShareLink:Pd,onClickRecordingRules:(0,w.useCallback)((()=>{Re("g_pyroscope_app_open_recording_rules_view"),f(`${p}${m.RECORDING_RULES}`,{state:{referrer:window.location.href}})}),[f]),onClickAdHoc:(0,w.useCallback)((()=>{Re("g_pyroscope_app_upload_ad_hoc_clicked"),f(`${p}${m.ADHOC}`,{state:{referrer:window.location.href}})}),[f]),onClickUserSettings:(0,w.useCallback)((()=>{Re("g_pyroscope_app_user_settings_clicked"),f(`${p}${m.SETTINGS}`,{state:{referrer:window.location.href}})}),[f])}}}(e),{settings:l}=Hs(),{explorationType:c,dataSourceVariable:u,timePickerControl:d,refreshPickerControl:f,sceneVariables:h,gridControls:g}=o;return S().createElement("div",{className:n.header,"data-testid":"allControls"},S().createElement(Wl,null),S().createElement("div",{className:n.appControls,"data-testid":"appControls"},S().createElement("div",{className:n.appControlsLeft},S().createElement(Td,{options:Id.EXPLORATION_TYPE_OPTIONS,value:c,onChange:s.onChangeExplorationType})),S().createElement("div",{className:n.appControlsRight},d&&S().createElement(d.Component,{key:d.state.key,model:d}),f&&S().createElement(f.Component,{key:f.state.key,model:f}),S().createElement("div",{className:n.appMiscButtons},(null==l?void 0:l.enableMetricsFromProfiles)&&Dc.metricsFromProfiles&&S().createElement(i.IconButton,{name:"gf-prometheus",tooltip:"View recording rules","aria-label":"View recording rules",onClick:s.onClickRecordingRules}),S().createElement(i.IconButton,{name:"upload",tooltip:"Upload ad hoc profiles",onClick:s.onClickAdHoc}),S().createElement(i.IconButton,{name:"cog",tooltip:"View/edit tenant settings",onClick:s.onClickUserSettings}),S().createElement(i.IconButton,{name:"share-alt",tooltip:"Copy shareable link to the clipboard",onClick:s.onClickShareLink}),S().createElement(le,null)))),S().createElement("div",{id:`scene-controls-${c}`,className:n.sceneControls,"data-testid":"sceneControls"},S().createElement(i.Field,{label:u.state.label,className:(0,r.cx)(n.sceneVariable,u.state.name),"data-testid":u.state.name},S().createElement(u.Component,{model:u})),h.map((e=>S().createElement(i.Field,{key:e.state.name,label:"Filters"===e.state.label?S().createElement("div",{className:n.sceneVariableLabel},S().createElement(i.Icon,{name:"filter",className:n.icon}),e.state.label):e.state.label,className:(0,r.cx)(n.sceneVariable,e.state.name),"data-testid":e.state.name},S().createElement(e.Component,{model:e})))),g.map((e=>S().createElement(i.Field,{key:e.state.key,id:e.state.key,className:n.gridControl,label:""},S().createElement(e.Component,{model:e}))))))}const kd=(e,t)=>({header:r.css` background-color: ${e.colors.background.canvas}; position: sticky; top: ${t}px; z-index: 1; padding-bottom: ${e.spacing(2)}; `,appControls:r.css` display: flex; padding: ${e.spacing(1)} 0; justify-content: space-between; gap: ${e.spacing(2)}; `,appControlsLeft:r.css` display: flex; gap: ${e.spacing(1)}; `,appControlsRight:r.css` display: flex; gap: ${e.spacing(1)}; `,appMiscButtons:r.css` display: flex; align-items: center; gap: 4px; border: 1px solid ${e.colors.border.weak}; background-color: ${e.colors.background.secondary}; height: 32px; padding: 0 ${e.spacing(1)}; & svg { width: 18px; height: 18px; } `,sceneControls:r.css` display: flex; flex-wrap: wrap; gap: ${e.spacing(1)}; padding: 0; margin-top: 20px; `,sceneVariable:r.css` display: flex; margin-bottom: 0; & #dataSource { width: ${e.spacing(32)}; } &.filters { flex-grow: 1; } &.compare-presets { margin-left: auto; text-align: right; } `,sceneVariableLabel:r.css` font-size: 12px; font-weight: 500; line-height: 15px; height: 15px; margin-bottom: 4px; color: ${e.colors.text.primary}; max-width: 480px; `,icon:r.css` display: inline-block; margin-right: 4px; `,gridControl:r.css` margin-bottom: 0; &#quick-filter { flex: 1; min-width: 112px; } `});function jd(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Ad=function(e){return e.ALL_SERVICES="all",e.PROFILE_TYPES="profiles",e.LABELS="labels",e.FLAME_GRAPH="flame-graph",e.DIFF_FLAME_GRAPH="diff-flame-graph",e.FAVORITES="favorites",e}({});class Id extends _t.Bs{onActivate(){const e=this.subscribeToVariableChanges(),t=this.subscribeToEvents();return this.state.explorationType||this.setExplorationType({type:Id.DEFAULT_EXPLORATION_TYPE}),()=>{t.unsubscribe(),e.unsubscribe()}}getUrlState(){return{explorationType:this.state.explorationType}}updateFromUrl(e){if("string"==typeof e.explorationType&&e.explorationType!==this.state.explorationType){const t=e.explorationType;this.setExplorationType({type:Object.values(Ad).includes(t)?t:Id.DEFAULT_EXPLORATION_TYPE})}}registerRuntimeDataSources(){try{_t.Go.registerRuntimeDataSource({dataSource:new cs}),_t.Go.registerRuntimeDataSource({dataSource:new Ia}),_t.Go.registerRuntimeDataSource({dataSource:new Qo})}catch(e){const{message:t}=e;/A runtime data source with uid (.+) has already been registered/.test(t)||Be(e,["Fail to register all the runtime data sources!","The application cannot work as expected, please try reloading the page or if the problem persists, contact your organization admin."])}}subscribeToVariableChanges(){const e=_t.jh.findByKeyAndType(this,"dataSource",uo).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(Oo.resetAll(this),this.resetSpanSelector())})),t=_t.jh.findByKeyAndType(this,"serviceName",so).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&(Oo.resetAll(this),e.options.some((e=>e.value===t.value))&&this.resetSpanSelector())})),n=_t.jh.findByKeyAndType(this,"profileMetricId",ro).subscribeToState(((e,t)=>{e.value&&e.value!==t.value&&this.resetSpanSelector()})),r=_t.jh.findByKeyAndType(this,"filters",Oo).subscribeToState(((e,t)=>{JSON.stringify(e.filters)!==JSON.stringify(t.filters)&&this.resetSpanSelector()}));return{unsubscribe(){t.unsubscribe(),e.unsubscribe(),r.unsubscribe(),n.unsubscribe()}}}subscribeToEvents(){const e=this.subscribeToEvent(Ga,(e=>{this.setExplorationType({type:"profiles",comesFromUserAction:!0,item:e.payload.item})})),t=this.subscribeToEvent(qa,(e=>{this.setExplorationType({type:"labels",comesFromUserAction:!0,item:e.payload.item})})),n=this.subscribeToEvent(Va,(e=>{this.setExplorationType({type:"flame-graph",comesFromUserAction:!0,item:e.payload.item})})),r=this.subscribeToEvent(gi,(e=>{const{useAncestorTimeRange:t,clearDiffRange:n,baselineFilters:r,comparisonFilters:o}=e.payload;this.setExplorationType({type:"diff-flame-graph",comesFromUserAction:!0,bodySceneOptions:{useAncestorTimeRange:t,clearDiffRange:n,baselineFilters:r,comparisonFilters:o}})})),o=this.subscribeToEvent(_c,(()=>{this.resetSpanSelector()}));return{unsubscribe(){r.unsubscribe(),n.unsubscribe(),t.unsubscribe(),e.unsubscribe(),o.unsubscribe()}}}setExplorationType({type:e,comesFromUserAction:t,item:n,bodySceneOptions:r}){t&&(Dt(),this.resetVariables(e)),this.setState({explorationType:e,body:this.buildBodyScene(e,n,r)})}resetSpanSelector(){_t.jh.findByKeyAndType(this,"spanSelector",Ji).reset()}resetVariables(e){_t.jh.findByKeyAndType(this,"quick-filter",Ta).reset(),_t.jh.findByKeyAndType(this,"groupBy",pi).changeValueTo(pi.DEFAULT_VALUE),_t.jh.findByKeyAndType(this,"panel-type-switcher",Co).reset(),this.resetSpanSelector(),["labels","flame-graph","diff-flame-graph"].includes(e)||_t.jh.findByKeyAndType(this,"filters",Oo).reset()}buildBodyScene(e,t,n){let r;switch(e){case"profiles":r=new Yi({item:t});break;case"labels":r=new zi({item:t});break;case"flame-graph":r=new wd({item:t});break;case"diff-flame-graph":r=new tc(n||{});break;case"favorites":r=new ai;break;default:r=new Ja}return new _t.n1({direction:"column",primary:r})}static Component({model:e}){const t=(0,i.useStyles2)(Rd),{data:n,actions:r}=e.useProfilesExplorer(),{explorationType:o,controls:a,body:s,$variables:l,dataSourceUid:c}=n;return S().createElement(Rc,{dataSourceUid:c},S().createElement(Nd,{explorationType:o,controls:a,body:s,$variables:l,onChangeExplorationType:r.onChangeExplorationType}),S().createElement("div",{className:t.body,"data-testid":"sceneBody"},s&&S().createElement(s.Component,{model:s})))}constructor(){super({key:"profiles-explorer",explorationType:void 0,body:void 0,$timeRange:new _t.JZ(Qi()),$variables:new _t.Pj({variables:[new uo,new so,new ro,new Oo({key:"filters"}),new Oo({key:"filtersBaseline"}),new Oo({key:"filtersComparison"}),new pi,new Ji]}),controls:[new _t.KE({isOnCanvas:!0}),new _t.WM({isOnCanvas:!0})],gridControls:[new Ta({placeholder:""}),new Co,new Sa,new Pa]}),jd(this,"_urlSync",new _t.So(this,{keys:["explorationType"]})),jd(this,"onChangeExplorationType",(e=>{Re("g_pyroscope_app_exploration_type_clicked",{explorationType:e}),this.setExplorationType({type:e,comesFromUserAction:!0})})),jd(this,"useProfilesExplorer",(()=>{const{explorationType:e,controls:t,body:n,$variables:r}=this.useState();return{data:{explorationType:e,controls:t,body:n,$variables:r,dataSourceUid:r.state.variables[0].useState().value},actions:{onChangeExplorationType:this.onChangeExplorationType}}})),(0,_t.Is)().initSync(this),this.registerRuntimeDataSources(),this.addActivationHandler(this.onActivate.bind(this))}}jd(Id,"EXPLORATION_TYPE_OPTIONS",[{value:"all",label:"All services",description:"Overview of all services, for any given profile type"},{value:"profiles",label:"Profile types",description:"Overview of all the profile types for a single service"},{value:"labels",label:"Labels",description:"Single service label exploration and filtering"},{value:"flame-graph",label:"Flame graph",description:"Single service flame graph"},{value:"diff-flame-graph",label:"Diff flame graph",description:"Compare the differences between two flame graphs"},{value:"favorites",label:"Favorites",description:"Overview of favorited visualizations",icon:"favorite"}]),jd(Id,"DEFAULT_EXPLORATION_TYPE",Id.EXPLORATION_TYPE_OPTIONS[0].value);const Rd=()=>({body:r.css` position: relative; z-index: 0; background: transparent; `});function _d(){const e=(0,w.useMemo)((()=>new Id),[]);return _e("explore"),S().createElement(e.Component,{model:e})}function Dd({rule:e,confirm:t}){const[n,r]=S().useState(!1);return S().createElement(S().Fragment,null,S().createElement(i.IconButton,{name:"trash-alt",onClick:()=>r(!0),variant:"destructive","aria-label":"Delete recording rule"}),S().createElement(i.ConfirmModal,{isOpen:n,title:"Delete recording rule",body:`Are you sure you want to delete ${e.metricName} recording rule?`,confirmText:"Yes",onConfirm:()=>{t(),r(!1)},onDismiss:()=>r(!1)}))}function Ld(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Fd(){const{recordingRules:e,error:t,remove:n,isFetching:r}=qc();return{data:{recordingRules:e,fetchError:t,isFetching:r},actions:{removeRecordingRule(e){return(t=function*(){try{yield n(e),Ue([`Recording rule ${e.metricName} deleted!`])}catch(t){Be(t,[`Failed to delete recording rule ${e.metricName}.`])}},function(){var e=this,n=arguments;return new Promise((function(r,o){var a=t.apply(e,n);function i(e){Ld(a,r,o,i,s,"next",e)}function s(e){Ld(a,r,o,i,s,"throw",e)}i(void 0)}))})();var t}}}}function $d(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bd(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))})),e}function Md(){const e=(0,i.useStyles2)(Ud),{data:t,actions:n}=Fd(),{recordingRules:o}=t;if(t.isFetching)return S().createElement(me,null);const a=[{id:"metricName",header:"Name",sortType:"alphanumeric"},{id:"serviceName",header:"Service Name",sortType:"alphanumeric"},{id:"profileType",header:"Profile Type",sortType:"alphanumeric"},{id:"groupBy",header:"Labels",cell:t=>{var n;const r=null===(n=t.row.original.groupBy)||void 0===n?void 0:n.filter((e=>!e.match(/^__\S+__$/)));return r&&0!==r.length?S().createElement(i.TagList,{className:e.tagList,displayMax:4,tags:r}):S().createElement(i.Text,{element:"span",color:"secondary"},"None")}},{id:"actions",header:"Actions",disableGrow:!0,cell:e=>{const t=e.row.original;return S().createElement(Dd,{rule:t,confirm:()=>n.removeRecordingRule(t)})}}],s=(o||[]).map((e=>{const t=Wr(e.profileType);return Bd(function(e){for(var t=1;te.metricName}),S().createElement(ke,null)),S().createElement(S().Fragment,null,S().createElement(pe,{title:"Recording rules"}),c)}const Ud=()=>({tagList:r.css` flex-direction: row; justify-content: start; `});function Vd({error:e}){var t;let n="Error while retrieving recording rules";return 404===(null===(t=e.response)||void 0===t?void 0:t.status)?n="This feature requires Pyroscope with recording_rules flag enabled.":e.message&&(n=e.message),S().createElement(i.EmptyState,{message:"Error while retrieving recording rules",variant:"not-found",button:S().createElement(ke,null)},n)}function qd(e,t,n,r,o,a,i){try{var s=e[a](i),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,o)}function Gd(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kd(e){for(var t=1;t{e&&a(e)}),[e]),{data:Hd(Kd({},o),{fetchError:t}),actions:{toggleCollapsedFlamegraphs(){a((e=>Hd(Kd({},e),{collapsedFlamegraphs:!e.collapsedFlamegraphs})))},updateMaxNodes(e){a((t=>Hd(Kd({},t),{maxNodes:Number(e.target.value)})))},toggleEnableFlameGraphDotComExport(){a((e=>Hd(Kd({},e),{enableFlameGraphDotComExport:!e.enableFlameGraphDotComExport})))},toggleEnableFunctionDetails(){a((e=>Hd(Kd({},e),{enableFunctionDetails:!e.enableFunctionDetails})))},toggleEnableMetricsFromProfiles(){a((e=>Hd(Kd({},e),{enableMetricsFromProfiles:!e.enableMetricsFromProfiles})))},saveSettings(){return(e=function*(){r(o.maxNodes);try{yield n(o),Ue(["Plugin settings successfully saved!"])}catch(e){Be(e,["Error while saving the plugin settings!","Please try again later, sorry for the inconvenience."])}},function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){qd(a,r,o,i,s,"next",e)}function s(e){qd(a,r,o,i,s,"throw",e)}i(void 0)}))})();var e}}}}function Yd({children:e}){const t=(0,i.useStyles2)(Wd),{data:n,actions:r}=zd();return n.fetchError&&Be(n.fetchError,["Error while retrieving the plugin settings!","Please try to reload the page, sorry for the inconvenience."]),S().createElement("form",{className:t.settingsForm,onSubmit:function(e){e.preventDefault(),r.saveSettings()}},S().createElement(i.FieldSet,{label:"Flame graph","data-testid":"flamegraph-settings"},S().createElement(i.InlineFieldRow,null,S().createElement(i.InlineField,{label:"Collapsed flame graphs",labelWidth:24},S().createElement(i.InlineSwitch,{label:"Toggle collapsed flame graphs",name:"collapsed-flamegraphs",value:n.collapsedFlamegraphs,onChange:r.toggleCollapsedFlamegraphs}))),S().createElement(i.InlineFieldRow,null,S().createElement(i.InlineField,{label:"Maximum number of nodes",tooltip:"",labelWidth:24},S().createElement(i.Input,{name:"max-nodes",type:"number",min:"1",value:n.maxNodes,onChange:r.updateMaxNodes})))),S().createElement(i.FieldSet,{label:"Function details","data-testid":"function-details-settings"},S().createElement(i.InlineFieldRow,null,S().createElement(i.InlineField,{label:"Enable function details",labelWidth:24,tooltip:S().createElement("div",{className:t.tooltip},S().createElement("p",null,"The function details feature enables mapping of resource usage to lines of source code. If the GitHub integration is configured, then the source code will be downloaded from GitHub."),S().createElement("p",null,S().createElement("a",{href:"https://grafana.com/docs/grafana-cloud/monitor-applications/profiles/pyroscope-github-integration/",target:"_blank",rel:"noreferrer noopener"},"Learn more"))),interactive:!0},S().createElement(i.InlineSwitch,{label:"Toggle function details",name:"function-details-feature",value:n.enableFunctionDetails,onChange:r.toggleEnableFunctionDetails})))),Dc.metricsFromProfiles&&S().createElement(i.FieldSet,{label:"Experimental features","data-testid":"experimental-features"},S().createElement(i.InlineFieldRow,null,S().createElement(i.InlineField,{label:"Metrics from profiles",tooltip:"Allows creating Prometheus recording rules from profiles",labelWidth:24},S().createElement(i.InlineSwitch,{label:"Enable metrics from profiles",name:"metrics-from-profiles",value:n.enableMetricsFromProfiles,onChange:r.toggleEnableMetricsFromProfiles})))),e)}const Wd=e=>({settingsForm:r.css` & > fieldset { border: 0 none; border-bottom: 1px solid ${e.colors.border.weak}; padding-left: 0; } & > fieldset > legend { font-size: ${e.typography.h4.fontSize}; } `,buttons:r.css` display: flex; gap: ${e.spacing(1)}; margin-top: ${e.spacing(3)}; `,tooltip:r.css` p { margin: ${e.spacing(1)}; } a { color: ${e.colors.text.link}; } em { font-style: normal; font-weight: ${e.typography.fontWeightBold}; } `}),Qd="grafana-pyroscope-app/settings/v1";function Jd(){var e;const[t]=Fl(),[n,r]=(0,w.useState)(0),o=(0,Ne.useNavigate)(),i=(0,Ne.useLocation)(),s=(0,w.useRef)(null===(e=i.state)||void 0===e?void 0:e.referrer),{components:l,isLoading:c}=(0,a.usePluginComponents)({extensionPointId:Qd});return{data:{activeTab:n,components:l,isLoading:c},actions:{setActiveTab(e){r(e)},goBack(){if(!s.current)return void o(`${p}${m.EXPLORE}`);const e=new URL(s.current);t&&e.searchParams.set("maxNodes",String(t)),o(`${e.pathname}${e.search}`)}}}}function Xd(){const e=(0,i.useStyles2)(Zd),{data:t,actions:n}=Jd();if(_e("settings"),t.isLoading)return S().createElement("div",null,"Loading...");const r=[{title:"UI Settings",content:S().createElement(Yd,null,S().createElement("div",{className:e.buttons},S().createElement(i.Button,{variant:"primary",type:"submit"},"Save settings"),S().createElement(ke,{onClick:n.goBack})))}],o={datasourceUid:G.selectDefaultDataSource().uid,backButton:S().createElement("div",{className:e.buttons},S().createElement(ke,{onClick:n.goBack}))},a=[...r,...t.components.map((e=>{var t;return{title:(null===(t=e.meta)||void 0===t?void 0:t.title)||"Unknown Extension",content:S().createElement(e,o)}}))];return S().createElement(S().Fragment,null,S().createElement(pe,{title:"Profiles settings (tenant)"}),a.length>1&&S().createElement(S().Fragment,null,S().createElement(i.TabsBar,null,a.map(((e,r)=>S().createElement(i.Tab,{key:`settings-tab-${r}`,label:e.title,active:t.activeTab===r,onChangeTab:()=>n.setActiveTab(r)})))),S().createElement(i.Space,{v:2})),a[t.activeTab].content)}const Zd=e=>({buttons:r.css` display: flex; gap: ${e.spacing(1)}; margin-top: ${e.spacing(3)}; `});function ep(){return S().createElement(Ne.Routes,null,S().createElement(Ne.Route,{path:m.EXPLORE,element:S().createElement(_d,null)}),S().createElement(Ne.Route,{path:m.ADHOC,element:S().createElement(Rt,null)}),S().createElement(Ne.Route,{path:m.SETTINGS,element:S().createElement(Xd,null)}),S().createElement(Ne.Route,{path:m.RECORDING_RULES,element:S().createElement(Md,null)}),S().createElement(Ne.Route,{path:"/*",element:S().createElement(Ne.Navigate,{to:`${p}${m.EXPLORE}`,replace:!0})}))}function tp({error:e}){return S().createElement(a.PluginPage,{layout:o.PageLayoutType.Canvas},S().createElement("div",{className:"pyroscope-app"},S().createElement(pe,{title:"Grafana Profiles Drilldown"}),S().createElement(zs,{severity:"error",title:"Fatal error!",message:"Please try reloading the page or, if the problem persists, contact your organization admin. Sorry for the inconvenience.",error:e,errorContext:{handheldBy:"React error boundary"}})))}function np(){const e=(0,i.useStyles2)(rp),[t,n]=(0,w.useState)();return t?S().createElement(tp,{error:t}):S().createElement(i.ErrorBoundary,{onError:n},(()=>S().createElement(E.Ht,{client:s},S().createElement(Ce,null,S().createElement("div",{className:e.pageContainer},S().createElement(a.PluginPage,{layout:o.PageLayoutType.Custom},S().createElement("div",{className:"pyroscope-app"},S().createElement(ep,null))))))))}!function(){if(v())return;const e=function(){const e=g();if(e&&y.has(e))return y.get(e)}();if(!e)return;const{environment:t,faroUrl:n,appName:r}=e,{apps:o,bootData:i,buildInfo:s}=a.config,u=o[d].version,m=i.user.email,h=`v${s.version} (${s.edition})`;var E;E=(0,l.p)({url:n,app:{name:r,release:u,version:f,environment:t,namespace:h},user:{email:m},instrumentations:[...(0,c.w)({captureConsole:!1})],isolate:!0,beforeSend:e=>{var t,n,r;return(null!==(n=null===(t=e.meta.page)||void 0===t?void 0:t.url)&&void 0!==n?n:"").includes(p)?(e.meta.view={name:new URLSearchParams(null===(r=e.meta.page)||void 0===r?void 0:r.url).get("explorationType")||""},e):null}}),b=E}();const rp=e=>({pageContainer:r.css` display: flex; flex-direction: column; padding: ${e.spacing(1)} ${e.spacing(2)} ${e.spacing(2)} ${e.spacing(2)}; flex-basis: 100%; flex-grow: 1; `})},5847:(e,t,n)=>{n.d(t,{A:()=>r});const r=n(9800).A},2293:(e,t,n)=>{n.d(t,{A:()=>r});const r=n(4720).A}}]); //# sourceMappingURL=715.js.map