"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[5372],{"./public/app/core/hooks/useCleanup.ts":(e,t,s)=>{s.d(t,{x:()=>i});var n=s("./node_modules/react/index.js"),r=s("./node_modules/react-redux/es/index.js"),a=s("./public/app/core/actions/cleanUp.ts");function i(e){const t=(0,r.useDispatch)(),s=(0,n.useRef)(e);s.current=e,(0,n.useEffect)((()=>()=>{t((0,a.e)({stateSelector:s.current}))}),[t])}},"./public/app/core/hooks/useQueryParams.ts":(e,t,s)=>{s.d(t,{K:()=>i});var n=s("./packages/grafana-runtime/src/index.ts"),r=s("./node_modules/react/index.js"),a=s("./node_modules/react-router/esm/react-router.js");function i(){const{search:e}=(0,a.TH)();return[(0,r.useMemo)((()=>(0,n.locationSearchToObject)(e||"")),[e]),(0,r.useCallback)(((e,t)=>setImmediate((()=>n.locationService.partial(e,t)))),[])]}},"./public/app/features/alerting/unified/RuleEditor.tsx":(e,t,s)=>{s.r(t),s.d(t,{default:()=>_t});var n=s("./node_modules/@emotion/css/dist/emotion-css.esm.js"),r=s("./packages/grafana-ui/src/index.ts"),a=s("./public/app/core/components/Page/Page.tsx"),i=s("./public/app/core/services/context_srv.ts"),o=s("./public/app/core/hooks/useCleanup.ts"),l=s("./node_modules/react/index.js"),u=s("./node_modules/react-redux/es/index.js"),d=s("./packages/grafana-data/src/index.ts"),c=s("./node_modules/react/jsx-runtime.js");const p=({title:e,stepNo:t,children:s,description:n})=>{const a=(0,r.useStyles2)(g);return(0,c.jsxs)("div",{className:a.parent,children:[(0,c.jsx)("div",{children:(0,c.jsx)("span",{className:a.stepNo,children:t})}),(0,c.jsx)("div",{className:a.content,children:(0,c.jsxs)(r.FieldSet,{label:e,className:a.fieldset,children:[n&&(0,c.jsx)("p",{className:a.description,children:n}),s]})})]})},g=e=>({fieldset:n.css`
    legend {
      font-size: 16px;
      padding-top: ${e.spacing(.5)};
    }
  `,parent:n.css`
    display: flex;
    flex-direction: row;
    max-width: ${e.breakpoints.values.xl};
    & + & {
      margin-top: ${e.spacing(4)};
    }
  `,description:n.css`
    margin-top: -${e.spacing(2)};
  `,stepNo:n.css`
    display: inline-block;
    width: ${e.spacing(4)};
    height: ${e.spacing(4)};
    line-height: ${e.spacing(4)};
    border-radius: ${e.spacing(4)};
    text-align: center;
    color: ${e.colors.text.maxContrast};
    background-color: ${e.colors.background.canvas};
    font-size: ${e.typography.size.lg};
    margin-right: ${e.spacing(2)};
  `,content:n.css`
    flex: 1;
  `});var h=s("./node_modules/react-hook-form/dist/index.esm.js"),f=s("./public/app/features/alerting/unified/types/rule-form.ts"),m=s("./public/app/features/alerting/unified/components/rule-editor/RuleFolderPicker.tsx"),v=s("./public/app/features/alerting/unified/hooks/useUnifiedAlertingSelector.ts"),x=s("./public/app/features/alerting/unified/state/actions.ts");const b=({value:e,onChange:t,options:s,className:n,placeholder:a,width:i,custom:o,onCustomChange:u,disabled:d=!1,addLabel:p="+ Add new"})=>{const[g,h]=(0,l.useState)(o);(0,l.useEffect)((()=>{o&&h(o)}),[o]);const f=(0,l.useMemo)((()=>[...s,{value:"__add__",label:p}]),[s,p]);return g?(0,c.jsx)(r.Input,{width:i,autoFocus:!o,value:e||"",placeholder:a,className:n,disabled:d,onChange:e=>t(e.target.value)}):(0,c.jsx)(r.Select,{menuShouldPortal:!0,width:i,options:f,value:e,className:n,placeholder:a,disabled:d,onChange:e=>{const s=null==e?void 0:e.value;"__add__"===s?(h(!0),u&&u(!0),t("")):t(s)}})},j=["onChange","ref"],y=["ref"];function w(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}const C=({dataSourceName:e})=>{var t,s,n,a,i;const{control:o,watch:d,formState:{errors:p},setValue:g}=(0,h.Gc)(),f=(0,r.useStyles2)(R),[m,C]=(0,l.useState)(!1),S=(0,v._)((e=>e.rulerRules)),k=(0,u.useDispatch)();(0,l.useEffect)((()=>{k((0,x.UR)(e))}),[e,k]);const O=null===(t=S[e])||void 0===t?void 0:t.result,N=d("namespace"),$=(0,l.useMemo)((()=>O?Object.keys(O).map((e=>({label:e,value:e}))):[]),[O]),I=(0,l.useMemo)((()=>{var e;return N&&(null==O||null===(e=O[N])||void 0===e?void 0:e.map((e=>({label:e.name,value:e.name}))))||[]}),[N,O]);return(0,c.jsxs)("div",{className:f.flexRow,children:[(0,c.jsx)(r.Field,{"data-testid":"namespace-picker",label:"Namespace",error:null===(s=p.namespace)||void 0===s?void 0:s.message,invalid:!(null===(n=p.namespace)||void 0===n||!n.message),children:(0,c.jsx)(r.InputControl,{render:e=>{let{field:{onChange:t}}=e,s=w(e.field,j);return(0,c.jsx)(b,Object.assign({},s,{className:f.input,onChange:e=>{g("group",""),t(e)},onCustomChange:e=>{e&&C(!0)},options:$,width:42}))},name:"namespace",control:o,rules:{required:{value:!0,message:"Required."}}})}),(0,c.jsx)(r.Field,{"data-testid":"group-picker",label:"Group",error:null===(a=p.group)||void 0===a?void 0:a.message,invalid:!(null===(i=p.group)||void 0===i||!i.message),children:(0,c.jsx)(r.InputControl,{render:e=>{let{}=e,t=w(e.field,y);return(0,c.jsx)(b,Object.assign({},t,{options:I,width:42,custom:m,className:f.input}))},name:"group",control:o,rules:{required:{value:!0,message:"Required."}}})})]})},R=e=>({flexRow:n.css`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;

    & > * + * {
      margin-left: ${e.spacing(3)};
    }
  `,input:n.css`
    width: 330px !important;
  `});var S=s("./packages/grafana-runtime/src/index.ts"),k=s("./public/app/features/alerting/unified/utils/datasource.ts");const O=["value"];function N(e){let{value:t}=e,s=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e,O);const n=function(){const e=(0,v._)((e=>e.lotexSupportsRuleEditing)),t=(0,u.useDispatch)();return(0,l.useEffect)((()=>{(0,k.Eu)().filter((t=>void 0===e[t.name])).forEach((e=>t((0,x.Yb)(e.name))))}),[t,e]),(0,l.useMemo)((()=>(0,k.Eu)().filter((t=>{var s;return null===(s=e[t.name])||void 0===s?void 0:s.result}))),[e])}(),r=(0,l.useCallback)((e=>!!n.find((({id:t})=>t===e.id))),[n]);return(0,c.jsx)(S.DataSourcePicker,Object.assign({noDefault:!0,alerting:!0,filter:r,current:t},s))}const $=["onChange","ref"],I=["onChange","ref"],q=["ref"];function Q(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}const D={message:"Recording rule name must be valid metric name. It may only contain letters, numbers, and colons. It may not contain whitespace.",value:/^[a-zA-Z_:][a-zA-Z0-9_:]*$/},E=({editingExistingRule:e})=>{var t,s,n,a,o,u,d,g;const v=(0,r.useStyles2)(T),{register:x,control:b,watch:j,formState:{errors:y},setValue:w}=(0,h.Gc)(),R=j("type"),S=j("dataSourceName"),k=(0,l.useMemo)((()=>{const e=[{label:"Grafana managed alert",value:f.$.grafana,description:"Classic Grafana alerts based on thresholds."}];return i.Vt.isEditor&&(e.push({label:"Cortex/Loki managed alert",value:f.$.cloudAlerting,description:"Alert based on a system or application behavior. Based on Prometheus."}),e.push({label:"Cortex/Loki managed recording rule",value:f.$.cloudRecording,description:"Recording rule to pre-compute frequently needed or expensive calculations. Based on Prometheus."})),e}),[]);return(0,c.jsxs)(p,{stepNo:1,title:"Rule type",children:[(0,c.jsx)(r.Field,{className:v.formInput,label:"Rule name",error:null==y||null===(t=y.name)||void 0===t?void 0:t.message,invalid:!(null===(s=y.name)||void 0===s||!s.message),children:(0,c.jsx)(r.Input,Object.assign({id:"name"},x("name",{required:{value:!0,message:"Must enter an alert name"},pattern:R===f.$.cloudRecording?D:void 0}),{autoFocus:!0}))}),(0,c.jsxs)("div",{className:v.flexRow,children:[(0,c.jsx)(r.Field,{disabled:e,label:"Rule type",className:v.formInput,error:null===(n=y.type)||void 0===n?void 0:n.message,invalid:!(null===(a=y.type)||void 0===a||!a.message),"data-testid":"alert-type-picker",children:(0,c.jsx)(r.InputControl,{render:e=>{let{field:{onChange:t}}=e,s=Q(e.field,$);return(0,c.jsx)(r.Select,Object.assign({menuShouldPortal:!0},s,{options:k,onChange:e=>t(null==e?void 0:e.value)}))},name:"type",control:b,rules:{required:{value:!0,message:"Please select alert type"}}})}),(R===f.$.cloudRecording||R===f.$.cloudAlerting)&&(0,c.jsx)(r.Field,{className:v.formInput,label:"Select data source",error:null===(o=y.dataSourceName)||void 0===o?void 0:o.message,invalid:!(null===(u=y.dataSourceName)||void 0===u||!u.message),"data-testid":"datasource-picker",children:(0,c.jsx)(r.InputControl,{render:e=>{let{field:{onChange:t}}=e,s=Q(e.field,I);return(0,c.jsx)(N,Object.assign({},s,{onChange:e=>{var s;w("location",void 0),t(null!==(s=null==e?void 0:e.name)&&void 0!==s?s:null)}}))},name:"dataSourceName",control:b,rules:{required:{value:!0,message:"Please select a data source"}}})})]}),(R===f.$.cloudRecording||R===f.$.cloudAlerting)&&S&&(0,c.jsx)(C,{dataSourceName:S}),R===f.$.grafana&&(0,c.jsx)(r.Field,{label:"Folder",className:v.formInput,error:null===(d=y.folder)||void 0===d?void 0:d.message,invalid:!(null===(g=y.folder)||void 0===g||!g.message),"data-testid":"folder-picker",children:(0,c.jsx)(r.InputControl,{render:e=>{let{}=e,t=Q(e.field,q);return(0,c.jsx)(m.W,Object.assign({},t,{enableCreateNew:!0,enableReset:!0}))},name:"folder",rules:{required:{value:!0,message:"Please select a folder"}}})})]})},T=e=>({formInput:n.css`
    width: 330px;
    & + & {
      margin-left: ${e.spacing(3)};
    }
  `,flexRow:n.css`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
  `});var F,_;const A=e=>({wrapper:n.css`
      margin-top: ${e.spacing.md};
    `,flexColumn:n.css`
      display: flex;
      flex-direction: column;
    `,flexRow:n.css`
      display: flex;
      flex-direction: row;
      justify-content: flex-start;

      & + button {
        margin-left: ${e.spacing.xs};
      }
    `,deleteLabelButton:n.css`
      margin-left: ${e.spacing.xs};
      align-self: flex-start;
    `,addLabelButton:n.css`
      flex-grow: 0;
      align-self: flex-start;
    `,centerAlignRow:n.css`
      align-items: baseline;
    `,equalSign:n.css`
      align-self: flex-start;
      width: 28px;
      justify-content: center;
      margin-left: ${e.spacing.xs};
    `,labelInput:n.css`
      width: 183px;
      margin-bottom: ${e.spacing.sm};
      & + & {
        margin-left: ${e.spacing.sm};
      }
    `}),P=({className:e})=>{const t=(0,r.useStyles)(A),{register:s,control:a,watch:i,formState:{errors:o}}=(0,h.Gc)(),l=i("labels");return(0,c.jsxs)("div",{className:(0,n.cx)(e,t.wrapper),children:[F||(F=(0,c.jsx)(r.Label,{children:"Custom Labels"})),(0,c.jsx)(r.FieldArray,{control:a,name:"labels",children:({fields:e,append:a,remove:i})=>(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{className:t.flexRow,children:[_||(_=(0,c.jsx)(r.InlineLabel,{width:18,children:"Labels"})),(0,c.jsxs)("div",{className:t.flexColumn,children:[e.map(((e,a)=>{var u,d,p,g,h,f,m,v,x,b,j,y,w,C;return(0,c.jsx)("div",{children:(0,c.jsxs)("div",{className:(0,n.cx)(t.flexRow,t.centerAlignRow),children:[(0,c.jsx)(r.Field,{className:t.labelInput,invalid:!(null===(u=o.labels)||void 0===u||null===(d=u[a])||void 0===d||null===(p=d.key)||void 0===p||!p.message),error:null===(g=o.labels)||void 0===g||null===(h=g[a])||void 0===h||null===(f=h.key)||void 0===f?void 0:f.message,children:(0,c.jsx)(r.Input,Object.assign({},s(`labels[${a}].key`,{required:{value:!(null===(m=l[a])||void 0===m||!m.value),message:"Required."}}),{placeholder:"key","data-testid":`label-key-${a}`,defaultValue:e.key}))}),(0,c.jsx)(r.InlineLabel,{className:t.equalSign,children:"="}),(0,c.jsx)(r.Field,{className:t.labelInput,invalid:!(null===(v=o.labels)||void 0===v||null===(x=v[a])||void 0===x||null===(b=x.value)||void 0===b||!b.message),error:null===(j=o.labels)||void 0===j||null===(y=j[a])||void 0===y||null===(w=y.value)||void 0===w?void 0:w.message,children:(0,c.jsx)(r.Input,Object.assign({},s(`labels[${a}].value`,{required:{value:!(null===(C=l[a])||void 0===C||!C.key),message:"Required."}}),{placeholder:"value","data-testid":`label-value-${a}`,defaultValue:e.value}))}),(0,c.jsx)(r.Button,{className:t.deleteLabelButton,"aria-label":"delete label",icon:"trash-alt",variant:"secondary",onClick:()=>{i(a)}})]})},e.id)})),(0,c.jsx)(r.Button,{className:t.addLabelButton,icon:"plus-circle",type:"button",variant:"secondary",onClick:()=>{a({})},children:"Add label"})]})]})})})]})};var L=s("./public/app/features/alerting/unified/utils/constants.ts");const B=["value","existingKeys"];const M=e=>{let{value:t,existingKeys:s}=e,n=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e,B);const r=(0,l.useMemo)((()=>Object.values(L.q6).filter((e=>!s.includes(e))).map((e=>({value:e,label:L.vY[e]})))),[s]);return(0,c.jsx)(b,Object.assign({value:t,options:r,custom:!!t&&!Object.values(L.q6).includes(t)},n))},U=["ref"];var G;const z=e=>({annotationValueInput:n.css`
    width: 426px;
  `,textarea:n.css`
    height: 76px;
  `,addAnnotationsButton:n.css`
    flex-grow: 0;
    align-self: flex-start;
    margin-left: 148px;
  `,flexColumn:n.css`
    display: flex;
    flex-direction: column;
  `,field:n.css`
    margin-bottom: ${e.spacing.xs};
  `,flexRow:n.css`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
  `,flexRowItemMargin:n.css`
    margin-left: ${e.spacing.xs};
  `}),V=()=>{const e=(0,r.useStyles)(z),{control:t,register:s,watch:a,formState:{errors:i}}=(0,h.Gc)(),o=a("annotations"),u=(0,l.useCallback)((e=>o.filter(((t,s)=>s!==e)).map((({key:e})=>e))),[o]);return(0,c.jsxs)(c.Fragment,{children:[G||(G=(0,c.jsx)(r.Label,{children:"Summary and annotations"})),(0,c.jsx)(r.FieldArray,{name:"annotations",control:t,children:({fields:a,append:l,remove:d})=>(0,c.jsxs)("div",{className:e.flexColumn,children:[a.map(((a,l)=>{var p,g,h,f,m,v,x,b,j,y,w,C,R,S,k;const O=null===(p=o[l])||void 0===p||null===(g=p.key)||void 0===g?void 0:g.toLocaleLowerCase().endsWith("url"),N=O?r.Input:r.TextArea;return(0,c.jsxs)("div",{className:e.flexRow,children:[(0,c.jsx)(r.Field,{className:e.field,invalid:!(null===(h=i.annotations)||void 0===h||null===(f=h[l])||void 0===f||null===(m=f.key)||void 0===m||!m.message),error:null===(v=i.annotations)||void 0===v||null===(x=v[l])||void 0===x||null===(b=x.key)||void 0===b?void 0:b.message,"data-testid":`annotation-key-${l}`,children:(0,c.jsx)(r.InputControl,{name:`annotations[${l}].key`,render:e=>{let{}=e,t=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e.field,U);return(0,c.jsx)(M,Object.assign({},t,{existingKeys:u(l),width:18}))},control:t,rules:{required:{value:!(null===(j=o[l])||void 0===j||!j.value),message:"Required."}}})}),(0,c.jsx)(r.Field,{className:(0,n.cx)(e.flexRowItemMargin,e.field),invalid:!(null===(y=i.annotations)||void 0===y||null===(w=y[l])||void 0===w||null===(C=w.value)||void 0===C||!C.message),error:null===(R=i.annotations)||void 0===R||null===(S=R[l])||void 0===S||null===(k=S.value)||void 0===k?void 0:k.message,children:(0,c.jsx)(N,Object.assign({"data-testid":`annotation-value-${l}`,className:(0,n.cx)(e.annotationValueInput,{[e.textarea]:!O})},s(`annotations[${l}].value`),{placeholder:O?"https://":"Text",defaultValue:a.value}))}),(0,c.jsx)(r.Button,{type:"button",className:e.flexRowItemMargin,"aria-label":"delete annotation",icon:"trash-alt",variant:"secondary",onClick:()=>d(l)})]},a.id)})),(0,c.jsx)(r.Button,{className:e.addAnnotationsButton,icon:"plus-circle",type:"button",variant:"secondary",onClick:()=>{l({key:"",value:""})},children:"Add info"})]})})]})};var K,W;const Z=()=>{const{watch:e}=(0,h.Gc)(),t=e("type");return(0,c.jsxs)(p,{stepNo:t===f.$.cloudRecording?3:4,title:t===f.$.cloudRecording?"Add details for your recording rule":"Add details for your alert",description:t===f.$.cloudRecording?"Add labels to help you better manage your rules":"Write a summary and add labels to help you better manage your alerts",children:[t!==f.$.cloudRecording&&(K||(K=(0,c.jsx)(V,{}))),W||(W=(0,c.jsx)(P,{}))]})};var H=s("./node_modules/lodash/lodash.js"),Y=s("./node_modules/react-use/esm/useAsync.js");const J=({value:e,onChange:t,dataSourceName:s})=>{var n,r;const{mapToValue:a,mapToQuery:i}=function(e){return(0,l.useMemo)((()=>{const t=(0,S.getDataSourceSrv)().getInstanceSettings(e);switch(null==t?void 0:t.type){case"loki":case"prometheus":return{mapToValue:e=>e.expr,mapToQuery:(e,t)=>Object.assign({},e,{expr:t})};default:throw new Error(`${e} is not supported as an expression editor`)}}),[e])}(s),[o,u]=(0,l.useState)(i({refId:"A",hide:!1},e)),{error:p,loading:g,value:h}=(0,Y.Z)((()=>(0,S.getDataSourceSrv)().get(s)),[s]),f=(0,l.useCallback)((e=>{u(e),t(a(e))}),[t,a]);if(g||(null==h?void 0:h.name)!==s)return null;if(p||!h||null==h||null===(n=h.components)||void 0===n||!n.QueryEditor){const e=(null==p?void 0:p.message)||"Data source plugin does not export any Query Editor component";return(0,c.jsxs)("div",{children:["Could not load query editor due to: ",e]})}const m=null==h||null===(r=h.components)||void 0===r?void 0:r.QueryEditor;return(0,c.jsx)(m,{query:o,queries:[o],app:d.CoreApp.CloudAlerting,onChange:f,onRunQuery:H.noop,datasource:h})};var X=s("./packages/grafana-e2e-selectors/src/index.ts"),ee=s("./node_modules/react-beautiful-dnd/dist/react-beautiful-dnd.esm.js"),te=s("./public/app/features/query/components/QueryEditorRow.tsx"),se=s("./node_modules/react-virtualized-auto-sizer/dist/index.esm.js");var ne=s("./public/app/features/alerting/unified/components/PanelPluginsButtonGroup.tsx"),re=s("./public/app/core/app_events.ts");const ae=({data:e,currentPanel:t,changePanel:s,onThresholdsChange:n,thresholds:a})=>{const[i,o]=(0,l.useState)({frameIndex:0,showHeader:!0}),u=function(e,t,s){const n=(0,r.useTheme2)();if(t===L.GC||t===L.Kd||function(e){return!(e&&e.series[0]&&e.series[0].fields[0]&&e.series[0].fields[0].values)}(e))return 200;const a=e.series[s].fields[0].values.length,i=5*n.spacing.gridSize,o=a*i+i;return o>=200?200:o}(e,t,i.frameIndex),d=(0,r.useStyles2)(ie(u)),[p,g]=(0,l.useState)(function(e){if(!e)return{defaults:{},overrides:[]};return{defaults:{thresholds:e,custom:{thresholdsStyle:{mode:"line"}}},overrides:[]}}(a));(0,l.useEffect)((()=>{g((e=>Object.assign({},e,{defaults:Object.assign({},e.defaults,{thresholds:a,custom:Object.assign({},e.defaults.custom,{thresholdsStyle:{mode:"line"}})})})))}),[a,g]);const h=(0,l.useMemo)((()=>({eventBus:re.Z,canEditThresholds:!0,onThresholdsChange:n})),[n]);return i&&e?(0,c.jsxs)("div",{className:d.wrapper,children:[(0,c.jsx)("div",{className:d.buttonGroup,children:(0,c.jsx)(ne.j,{onChange:s,value:t})}),(0,c.jsx)(se.Z,{children:({width:s})=>0===s?null:(0,c.jsx)("div",{style:{height:`${u}px`,width:`${s}px`},children:(0,c.jsx)(r.PanelContextProvider,{value:h,children:(0,c.jsx)(S.PanelRenderer,{height:u,width:s,data:e,pluginId:t,title:"title",onOptionsChange:o,options:i,fieldConfig:p})})})})]}):null},ie=e=>t=>({wrapper:n.css`
    padding: 0 ${t.spacing(2)};
    height: ${e+4*t.spacing.gridSize}px;
  `,buttonGroup:n.css`
    display: flex;
    justify-content: flex-end;
  `});var oe=s("./public/app/features/expressions/guards.ts");const le=({data:e,dsSettings:t,index:s,onChangeDataSource:n,onChangeQuery:a,onChangeTimeRange:i,onRunQueries:o,onRemoveQuery:u,onDuplicateQuery:p,query:g,queries:h,thresholds:f,onChangeThreshold:m})=>{const v=(0,r.useStyles2)(ue),x=(0,oe.j)(g.model),[b,j]=(0,l.useState)(x?L.Fe:L.GC);return(0,c.jsx)("div",{className:v.wrapper,children:(0,c.jsx)(te.x,{dataSource:t,onChangeDataSource:x?void 0:e=>n(e,s),id:g.refId,index:s,data:e,query:(0,H.cloneDeep)(g.model),onChange:e=>a(e,s),onRemoveQuery:u,onAddQuery:p,onRunQuery:o,queries:h,renderHeaderExtras:()=>((e,t)=>{var s;return(0,oe.j)(e.model)||!i?null:(0,c.jsx)(r.RelativeTimeRangePicker,{timeRange:null!==(s=e.relativeTimeRange)&&void 0!==s?s:(0,d.getDefaultRelativeTimeRange)(),onChange:e=>i(e,t)})})(g,s),visualization:e?(0,c.jsx)(ae,{data:e,changePanel:j,currentPanel:b,thresholds:f,onThresholdsChange:e=>m(e,s)}):null,hideDisableQuery:!0},g.refId)})},ue=e=>({wrapper:n.css`
    label: AlertingQueryWrapper;
    margin-bottom: ${e.spacing(1)};
    border: 1px solid ${e.colors.border.medium};
    border-radius: ${e.shape.borderRadius(1)};
    padding-bottom: ${e.spacing(1)};
  `});function de(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class ce extends l.PureComponent{constructor(e){super(e),de(this,"onRemoveQuery",(e=>{this.props.onQueriesChange(this.props.queries.filter((t=>t.model.refId!==e.refId)))})),de(this,"onChangeTimeRange",((e,t)=>{const{queries:s,onQueriesChange:n}=this.props;n(s.map(((s,n)=>n!==t?s:Object.assign({},s,{relativeTimeRange:e}))))})),de(this,"onChangeThreshold",((e,t)=>{const{queries:s,onQueriesChange:n}=this.props,r=s[t].refId;n(s.map((t=>(0,oe.j)(t.model)&&t.model.conditions&&t.model.conditions[0].query.params[0]===r?Object.assign({},t,{model:Object.assign({},t.model,{conditions:t.model.conditions.map(((t,s)=>t.query.params[0]===r&&0===s?Object.assign({},t,{evaluator:Object.assign({},t.evaluator,{params:[parseFloat(e.steps[1].value.toPrecision(3))]})}):t))})}):t)))})),de(this,"onChangeDataSource",((e,t)=>{const{queries:s,onQueriesChange:n}=this.props;n(s.map(((s,n)=>{if(n!==t)return s;const r=(0,S.getDataSourceSrv)().getInstanceSettings(s.datasourceUid);if((null==r?void 0:r.type)===e.uid)return Object.assign({},s,{datasourceUid:e.uid});const{refId:a,hide:i}=s.model;return Object.assign({},s,{datasourceUid:e.uid,model:{refId:a,hide:i}})})))})),de(this,"onChangeQuery",((e,t)=>{const{queries:s,onQueriesChange:n}=this.props;n(s.map(((s,n)=>n!==t?s:Object.assign({},s,{refId:e.refId,model:Object.assign({},s.model,e,{datasource:e.datasource})}))))})),de(this,"onDragEnd",(e=>{const{queries:t,onQueriesChange:s}=this.props;if(!e||!e.destination)return;const n=e.source.index,r=e.destination.index;if(n===r)return;const a=Array.from(t),[i]=a.splice(n,1);a.splice(r,0,i),s(a)})),de(this,"onDuplicateQuery",((e,t)=>{this.props.onDuplicateQuery(Object.assign({},t,{model:e}))})),de(this,"getDataSourceSettings",(e=>(0,S.getDataSourceSrv)().getInstanceSettings(e.datasourceUid))),de(this,"getThresholdsForQueries",(e=>{const t={};for(const s of e)(0,oe.j)(s.model)&&Array.isArray(s.model.conditions)&&s.model.conditions.forEach(((e,s)=>{if(s>0)return;const n=e.evaluator.params[0],r=e.query.params[0];"outside_range"!==e.evaluator.type&&"within_range"!==e.evaluator.type&&(t[r]||(t[r]={mode:d.ThresholdsMode.Absolute,steps:[{value:-1/0,color:"green"}]}),t[r].steps.push({value:n,color:"red"}))}));return t})),this.state={dataPerQuery:{}}}render(){const{onDuplicateQuery:e,onRunQueries:t,queries:s}=this.props,n=this.getThresholdsForQueries(s);return(0,c.jsx)(ee.Z5,{onDragEnd:this.onDragEnd,children:(0,c.jsx)(ee.bK,{droppableId:"alerting-queries",direction:"vertical",children:r=>(0,c.jsxs)("div",Object.assign({ref:r.innerRef},r.droppableProps,{children:[s.map(((r,a)=>{const i=this.props.data?this.props.data[r.refId]:{},o=this.getDataSourceSettings(r);return o?(0,c.jsx)(le,{index:a,dsSettings:o,data:i,query:r,onChangeQuery:this.onChangeQuery,onRemoveQuery:this.onRemoveQuery,queries:s,onChangeDataSource:this.onChangeDataSource,onDuplicateQuery:e,onRunQueries:t,onChangeTimeRange:this.onChangeTimeRange,thresholds:n[r.refId],onChangeThreshold:this.onChangeThreshold},`${r.refId}-${a}`):null})),r.placeholder]}))})})}}var pe,ge,he=s("./public/app/features/expressions/ExpressionDatasource.ts"),fe=s("./public/app/core/utils/query.ts"),me=s("./public/app/features/expressions/utils/expressionTypes.ts"),ve=s("./public/app/features/expressions/types.ts"),xe=s("./public/app/features/alerting/unified/state/AlertingQueryRunner.ts"),be=s("./public/app/features/plugins/datasource_srv.ts");function je(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class ye extends l.PureComponent{constructor(e){var t;super(e),je(this,"runner",void 0),je(this,"queries",void 0),je(this,"onRunQueries",(()=>{const{queries:e}=this;this.runner.run(e)})),je(this,"onCancelQueries",(()=>{this.runner.cancel()})),je(this,"onChangeQueries",(e=>{this.queries=e,this.props.onChange(e)})),je(this,"onDuplicateQuery",(e=>{const{queries:t}=this;this.onChangeQueries(we(t,e))})),je(this,"onNewAlertingQuery",(()=>{const{queries:e}=this,t=(0,be.ak)().getInstanceSettings("default");t&&this.onChangeQueries(we(e,{datasourceUid:t.uid,model:{refId:"",datasource:t.name}}))})),je(this,"onNewExpressionQuery",(()=>{const{queries:e}=this;this.onChangeQueries(we(e,{datasourceUid:he.Yq,model:he.mV.newQuery({type:ve.Us.classic,conditions:[me.R]})}))})),this.state={panelDataByRefId:{}},this.runner=new xe.v,this.queries=null!==(t=e.value)&&void 0!==t?t:[]}componentDidMount(){this.runner.get().subscribe((e=>{this.setState({panelDataByRefId:e})}))}componentWillUnmount(){this.runner.destroy()}renderAddQueryRow(e){return(0,c.jsxs)(r.HorizontalGroup,{spacing:"md",align:"flex-start",children:[(0,c.jsx)(r.Button,{type:"button",icon:"plus",onClick:this.onNewAlertingQuery,variant:"secondary","aria-label":X.wl.components.QueryTab.addQuery,children:"Query"}),S.config.expressionsEnabled&&(0,c.jsx)(r.Tooltip,{content:"Beta feature: queries could stop working in next version",placement:"right",children:(0,c.jsxs)(r.Button,{type:"button",icon:"plus",onClick:this.onNewExpressionQuery,variant:"secondary",className:e.expressionButton,children:[pe||(pe=(0,c.jsx)("span",{children:"Expression "})),ge||(ge=(0,c.jsx)(r.Icon,{name:"exclamation-triangle",className:"muted",size:"sm"}))]})})]})}isRunning(){const e=Object.values(this.state.panelDataByRefId).find((e=>Boolean(e)));return(null==e?void 0:e.state)===d.LoadingState.Loading}renderRunQueryButton(){const e=this.isRunning(),t=Re(S.config.theme2);return e?(0,c.jsx)("div",{className:t.runWrapper,children:(0,c.jsx)(r.Button,{icon:"fa fa-spinner",type:"button",variant:"destructive",onClick:this.onCancelQueries,children:"Cancel"})}):(0,c.jsx)("div",{className:t.runWrapper,children:(0,c.jsx)(r.Button,{icon:"sync",type:"button",onClick:this.onRunQueries,children:"Run queries"})})}render(){const{value:e=[]}=this.props,{panelDataByRefId:t}=this.state,s=Re(S.config.theme2);return(0,c.jsxs)("div",{className:s.container,children:[(0,c.jsx)(ce,{data:t,queries:e,onQueriesChange:this.onChangeQueries,onDuplicateQuery:this.onDuplicateQuery,onRunQueries:this.onRunQueries}),this.renderAddQueryRow(s),this.renderRunQueryButton()]})}}const we=(e,t)=>{const s=(0,fe.Hs)(e),n=Object.assign({},t,{refId:s,queryType:"",model:Object.assign({},t.model,{hide:!1,refId:s}),relativeTimeRange:Ce(t.model)});return[...e,n]},Ce=e=>{if(!(0,oe.j)(e))return(0,d.getDefaultRelativeTimeRange)()},Re=(0,r.stylesFactory)((e=>({container:n.css`
      background-color: ${e.colors.background.primary};
      height: 100%;
      max-width: ${e.breakpoints.values.xxl}px;
    `,runWrapper:n.css`
      margin-top: ${e.spacing(1)};
    `,editorWrapper:n.css`
      border: 1px solid ${e.colors.border.medium};
      border-radius: ${e.shape.borderRadius()};
    `,expressionButton:n.css`
      margin-right: ${e.spacing(.5)};
    `}))),Se=["ref"],ke=["ref"];function Oe(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}const Ne=()=>{var e,t;const{control:s,watch:n,formState:{errors:a}}=(0,h.Gc)(),i=n("type"),o=n("dataSourceName");return(0,c.jsxs)(p,{stepNo:2,title:i===f.$.cloudRecording?"Create a query to be recorded":"Create a query to be alerted on",children:[(i===f.$.cloudRecording||i===f.$.cloudAlerting)&&o&&(0,c.jsx)(r.Field,{error:null===(e=a.expression)||void 0===e?void 0:e.message,invalid:!(null===(t=a.expression)||void 0===t||!t.message),children:(0,c.jsx)(r.InputControl,{name:"expression",render:e=>{let{}=e,t=Oe(e.field,Se);return(0,c.jsx)(J,Object.assign({},t,{dataSourceName:o}))},control:s,rules:{required:{value:!0,message:"A valid expression is required"}}})}),i===f.$.grafana&&(0,c.jsx)(r.Field,{invalid:!!a.queries,error:!a.queries?void 0:"Must provide at least one valid query.",children:(0,c.jsx)(r.InputControl,{name:"queries",render:e=>{let{}=e,t=Oe(e.field,ke);return(0,c.jsx)(ye,Object.assign({},t))},control:s,rules:{validate:e=>Array.isArray(e)&&!!e.length}})})]})};var $e,Ie=s("./public/app/features/alerting/unified/utils/redux.ts"),qe=s("./public/app/features/alerting/unified/utils/rule-form.ts"),Qe=s("./node_modules/react-router-dom/esm/react-router-dom.js"),De=s("./public/app/core/hooks/useQueryParams.ts"),Ee=s("./public/app/core/core.ts"),Te=s("./public/app/features/alerting/unified/utils/time.ts"),Fe=s("./node_modules/rxjs/dist/esm5/internal/operators/takeWhile.js"),_e=s("./node_modules/react-use/esm/useMountedState.js"),Ae=s("./node_modules/rxjs/dist/esm5/internal/observable/of.js"),Pe=s("./node_modules/rxjs/dist/esm5/internal/operators/map.js"),Le=s("./node_modules/rxjs/dist/esm5/internal/operators/catchError.js"),Be=s("./node_modules/rxjs/dist/esm5/internal/operators/share.js");function Me(e){if(function(e){return"expr"in e}(e))return function(e){throw new Error("preview for cloud alerting rules is not implemented")}();if(function(e){return"grafana_condition"in e}(e))return function(e){const t=f.$.grafana;return(0,d.withLoadingIndicator)({whileLoading:Ue(t),source:(0,S.getBackendSrv)().fetch({method:"POST",url:"/api/v1/rule/test/grafana",data:e}).pipe((0,Pe.U)((({data:e})=>Ue(t,{state:d.LoadingState.Done,series:e.instances.map(d.dataFrameFromJSON)}))),(0,Le.K)((e=>(0,Ae.of)(Ue(t,{state:d.LoadingState.Error,error:(0,S.toDataQueryError)(e)})))),(0,Be.B)())})}(e);throw new Error("unsupported preview rule request")}function Ue(e,t={}){return{ruleType:e,data:Object.assign({state:d.LoadingState.Loading,series:[],timeRange:(0,d.getDefaultTimeRange)()},t)}}function Ge(e){const{preview:t}=e,s=(0,r.useStyles2)(ze);if(!t)return null;const{data:n,ruleType:a}=t;return n.state===d.LoadingState.Loading?(0,c.jsx)("div",{className:s.container,children:$e||($e=(0,c.jsx)("span",{children:"Loading preview..."}))}):n.state===d.LoadingState.Error?(0,c.jsx)("div",{className:s.container,children:n.error?(0,Ie.kk)(n.error):"Failed to preview alert rule"}):(0,c.jsxs)("div",{className:s.container,children:[(0,c.jsxs)("span",{children:["Preview based on the result of running the query, for this moment."," ",a===f.$.grafana?"Configuration for `no data` and `error handling` is not applied.":null]}),(0,c.jsx)("div",{className:s.table,children:(0,c.jsx)(se.Z,{children:({width:e,height:t})=>(0,c.jsx)("div",{style:{width:`${e}px`,height:`${t}px`},children:(0,c.jsx)(S.PanelRenderer,{title:"",width:e,height:t,pluginId:"table",data:n})})})})]})}function ze(e){return{container:n.css`
      margin: ${e.spacing(2)} 0;
    `,table:n.css`
      flex: 1 1 auto;
      height: 135px;
      margin-top: ${e.spacing(2)};
      border: 1px solid ${e.colors.border.medium};
      border-radius: ${e.shape.borderRadius(1)};
    `}}const Ve=["type","dataSourceName","condition","queries","expression"];function Ke(){const e=(0,r.useStyles2)(We),[t,s]=function(){const[e,t]=(0,l.useState)(),{getValues:s}=(0,h.Gc)(),n=(0,_e.Z)(),r=(0,l.useCallback)((()=>{Me(function(e){const[t,s,n,r,a]=e;switch(t){case f.$.cloudAlerting:return{dataSourceName:s,expr:a};case f.$.grafana:return{grafana_condition:{condition:n,data:r,now:(0,d.dateTimeFormatISO)(Date.now())}};default:throw new Error(`Alert type ${t} not supported by preview.`)}}(s(Ve))).pipe((0,Fe.o)((e=>!function(e){switch(e.data.state){case d.LoadingState.Done:case d.LoadingState.Error:return!0;default:return!1}}(e)),!0)).subscribe((e=>{n()&&t(e)}))}),[s,n]);return[e,r]}(),{watch:n}=(0,h.Gc)(),[a,i]=n(["type","condition"]);return a===f.$.cloudRecording||a===f.$.cloudAlerting?null:(0,c.jsxs)("div",{className:e.container,children:[(0,c.jsx)(r.HorizontalGroup,{children:(0,c.jsx)(r.Button,{disabled:!i,type:"button",variant:"primary",onClick:s,children:"Preview alerts"})}),(0,c.jsx)(Ge,{preview:t})]})}function We(e){return{container:n.css`
      margin-top: ${e.spacing(2)};
    `}}var Ze;const He=["onChange","ref"];const Ye=()=>{var e,t;const s=(0,r.useStyles)(Je),{register:n,control:a,watch:i,formState:{errors:o}}=(0,h.Gc)();return i("type")===f.$.cloudRecording?null:(0,c.jsxs)(p,{stepNo:3,title:"Define alert conditions",children:[(0,c.jsx)(r.Field,{label:"For",description:"Expression has to be true for this long for the alert to be fired.",children:(0,c.jsxs)("div",{className:s.flexRow,children:[(0,c.jsx)(r.Field,{invalid:!(null===(e=o.forTime)||void 0===e||!e.message),error:null===(t=o.forTime)||void 0===t?void 0:t.message,className:s.inlineField,children:(0,c.jsx)(r.Input,Object.assign({},n("forTime",{pattern:{value:/^\d+$/,message:"Must be a positive integer."}}),{width:8}))}),(0,c.jsx)(r.InputControl,{name:"forTimeUnit",render:e=>{let{field:{onChange:t}}=e,n=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e.field,He);return(0,c.jsx)(r.Select,Object.assign({menuShouldPortal:!0},n,{options:Te.qr,onChange:e=>t(null==e?void 0:e.value),width:15,className:s.timeUnit}))},control:a})]})}),Ze||(Ze=(0,c.jsx)(Ke,{}))]})},Je=e=>({inlineField:n.css`
    margin-bottom: 0;
  `,flexRow:n.css`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
  `,timeUnit:n.css`
    margin-left: ${e.spacing.xs};
  `}),Xe=["onChange","ref"];const et=()=>{var e,t;const{watch:s,setValue:n,formState:{errors:a}}=(0,h.Gc)(),i=s("queries"),o=s("condition"),u=(0,l.useMemo)((()=>i.filter((e=>!!e.refId)).map((e=>({value:e.refId,label:e.refId})))),[i]);return(0,l.useEffect)((()=>{const e=i.filter((e=>e.model.datasource===he.DB));o&&!u.find((({value:e})=>e===o))?n("condition",e.length?e[e.length-1].refId:null):!o&&e.length&&n("condition",e[e.length-1].refId)}),[o,u,i,n]),(0,c.jsx)(r.Field,{label:"Condition",description:"The query or expression that will be alerted on",error:null===(e=a.condition)||void 0===e?void 0:e.message,invalid:!(null===(t=a.condition)||void 0===t||!t.message),children:(0,c.jsx)(r.InputControl,{name:"condition",render:e=>{let{field:{onChange:t}}=e,s=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e.field,Xe);return(0,c.jsx)(r.Select,Object.assign({menuShouldPortal:!0},s,{width:42,options:u,onChange:e=>{var s;return t(null!==(s=null==e?void 0:e.value)&&void 0!==s?s:null)},noOptionsMessage:"No queries defined"}))},rules:{required:{value:!0,message:"Please select the condition to alert on"}}})})};var tt=s("./public/app/types/unified-alerting-dto.ts");const st=["includeNoData"];const nt=[{value:tt.g0.Alerting,label:"Alerting"},{value:tt.g0.NoData,label:"No Data"},{value:tt.g0.OK,label:"OK"}],rt=e=>{let{includeNoData:t}=e,s=function(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}(e,st);const n=(0,l.useMemo)((()=>t?nt:nt.filter((e=>e.value!==tt.g0.NoData))),[t]);return(0,c.jsx)(r.Select,Object.assign({menuShouldPortal:!0,options:n},s))};var at;const it=()=>{const{watch:e}=(0,h.Gc)(),t=e("evaluateFor"),s=e("evaluateEvery");if("0"===t)return null;const n=(0,d.parseDuration)(t),a=(0,d.parseDuration)(s);if((0,H.isEmpty)(n)||(0,H.isEmpty)(a))return null;const i=(0,d.durationToMilliseconds)(n),o=(0,d.durationToMilliseconds)(a);return i&&o&&i<=o?at||(at=(0,c.jsx)(r.Alert,{severity:"warning",title:"",children:'Setting a "for" duration that is less than or equal to the evaluation interval will result in the evaluation interval being used to calculate when an alert that has stopped receiving data will be closed.'})):null};var ot=s("./public/app/features/alerting/unified/components/CollapseToggle.tsx");const lt=["onChange","ref"],ut=["onChange","ref"];var dt,ct,pt,gt,ht;function ft(e,t){if(null==e)return{};var s,n,r={},a=Object.keys(e);for(n=0;n<a.length;n++)s=a[n],t.indexOf(s)>=0||(r[s]=e[s]);return r}const mt={required:{value:!0,message:"Required."},pattern:Te.lR},vt={required:{value:!0,message:"Required."},pattern:Te.O8,validate:e=>{const t=(0,d.parseDuration)(e);if(Object.keys(t).length){const e=(0,d.durationToMilliseconds)(t);if(e<1e4)return"Cannot be less than 10 seconds.";if(e%1e4!=0)return"Must be a multiple of 10 seconds."}return!0}},xt=()=>{var e,t,s,n;const a=(0,r.useStyles2)(bt),[i,o]=(0,l.useState)(!1),{register:u,formState:{errors:d}}=(0,h.Gc)();return(0,c.jsxs)(p,{stepNo:3,title:"Define alert conditions",children:[dt||(dt=(0,c.jsx)(et,{})),(0,c.jsx)(r.Field,{label:"Evaluate",children:(0,c.jsxs)("div",{className:a.flexRow,children:[ct||(ct=(0,c.jsx)(r.InlineLabel,{width:16,tooltip:"How often the alert will be evaluated to see if it fires",children:"Evaluate every"})),(0,c.jsx)(r.Field,{className:a.inlineField,error:null===(e=d.evaluateEvery)||void 0===e?void 0:e.message,invalid:!(null===(t=d.evaluateEvery)||void 0===t||!t.message),validationMessageHorizontalOverflow:!0,children:(0,c.jsx)(r.Input,Object.assign({width:8},u("evaluateEvery",vt)))}),pt||(pt=(0,c.jsx)(r.InlineLabel,{width:7,tooltip:'Once condition is breached, alert will go into pending state. If it is pending for longer than the "for" value, it will become a firing alert.',children:"for"})),(0,c.jsx)(r.Field,{className:a.inlineField,error:null===(s=d.evaluateFor)||void 0===s?void 0:s.message,invalid:!(null===(n=d.evaluateFor)||void 0===n||!n.message),validationMessageHorizontalOverflow:!0,children:(0,c.jsx)(r.Input,Object.assign({width:8},u("evaluateFor",mt)))})]})}),gt||(gt=(0,c.jsx)(it,{})),(0,c.jsx)(ot.U,{isCollapsed:!i,onToggle:e=>o(!e),text:"Configure no data and error handling",className:a.collapseToggle}),i&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(r.Field,{label:"Alert state if no data or all values are null",children:(0,c.jsx)(r.InputControl,{render:e=>{let{field:{onChange:t}}=e,s=ft(e.field,lt);return(0,c.jsx)(rt,Object.assign({},s,{width:42,includeNoData:!0,onChange:e=>t(null==e?void 0:e.value)}))},name:"noDataState"})}),(0,c.jsx)(r.Field,{label:"Alert state if execution error or timeout",children:(0,c.jsx)(r.InputControl,{render:e=>{let{field:{onChange:t}}=e,s=ft(e.field,ut);return(0,c.jsx)(rt,Object.assign({},s,{width:42,includeNoData:!1,onChange:e=>t(null==e?void 0:e.value)}))},name:"execErrState"})})]}),ht||(ht=(0,c.jsx)(Ke,{}))]})},bt=e=>({inlineField:n.css`
    margin-bottom: 0;
  `,flexRow:n.css`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: flex-start;
  `,collapseToggle:n.css`
    margin: ${e.spacing(2,0,2,-1)};
  `});var jt,yt,wt,Ct;const Rt=({existing:e})=>{var t;const s=(0,r.useStyles2)(St),n=(0,u.useDispatch)(),[a]=(0,De.K)(),i=null!==(t=a.returnTo)&&void 0!==t?t:"/alerting/list",p=(0,l.useMemo)((()=>e?(0,qe.DQ)(e):Object.assign({},(0,qe.uZ)(),{queries:(0,qe.s0)()},a.defaults?JSON.parse(a.defaults):{})),[e,a]),g=(0,h.cI)({mode:"onSubmit",defaultValues:p,shouldFocusError:!0}),{handleSubmit:m,watch:b}=g,j=b("type"),y=b("dataSourceName"),w=Boolean(j&&(j===f.$.grafana||!!y)),C=(0,v._)((e=>e.ruleForm.saveRule))||Ie.oq;(0,o.x)((e=>e.unifiedAlerting.ruleForm.saveRule));const R=(t,s)=>{var r,a,o,l;n((0,x.wy)({values:Object.assign({},p,t,{annotations:null!==(r=null===(a=t.annotations)||void 0===a?void 0:a.map((({key:e,value:t})=>({key:e.trim(),value:t.trim()}))).filter((({key:e,value:t})=>!!e&&!!t)))&&void 0!==r?r:[],labels:null!==(o=null===(l=t.labels)||void 0===l?void 0:l.map((({key:e,value:t})=>({key:e.trim(),value:t.trim()}))).filter((({key:e})=>!!e)))&&void 0!==o?o:[]}),existing:e,redirectOnSave:s?i:void 0}))},S=()=>{Ee.h$.emit(d.AppEvents.alertError,["There are errors in the form. Please correct them and try again!"])};return(0,c.jsx)(h.RV,Object.assign({},g,{children:(0,c.jsxs)("form",{onSubmit:e=>e.preventDefault(),className:s.form,children:[(0,c.jsxs)(r.PageToolbar,{title:"Create alert rule",pageIcon:"bell",children:[(0,c.jsx)(Qe.Link,{to:i,children:(0,c.jsx)(r.Button,{variant:"secondary",disabled:C.loading,type:"button",fill:"outline",children:"Cancel"})}),(0,c.jsxs)(r.Button,{variant:"secondary",type:"button",onClick:m((e=>R(e,!1)),S),disabled:C.loading,children:[C.loading&&(0,c.jsx)(r.Spinner,{className:s.buttonSpinner,inline:!0}),"Save"]}),(0,c.jsxs)(r.Button,{variant:"primary",type:"button",onClick:m((e=>R(e,!0)),S),disabled:C.loading,children:[C.loading&&(0,c.jsx)(r.Spinner,{className:s.buttonSpinner,inline:!0}),"Save and exit"]})]}),(0,c.jsx)("div",{className:s.contentOuter,children:(0,c.jsx)(r.CustomScrollbar,{autoHeightMin:"100%",hideHorizontalTrack:!0,children:(0,c.jsxs)("div",{className:s.contentInner,children:[(0,c.jsx)(E,{editingExistingRule:!!e}),w&&(0,c.jsxs)(c.Fragment,{children:[jt||(jt=(0,c.jsx)(Ne,{})),j===f.$.grafana?yt||(yt=(0,c.jsx)(xt,{})):wt||(wt=(0,c.jsx)(Ye,{})),Ct||(Ct=(0,c.jsx)(Z,{}))]})]})})})]})}))},St=e=>({buttonSpinner:n.css`
      margin-right: ${e.spacing(1)};
    `,form:n.css`
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
    `,contentInner:n.css`
      flex: 1;
      padding: ${e.spacing(2)};
    `,contentOuter:n.css`
      background: ${e.colors.background.primary};
      border: 1px solid ${e.colors.border.weak};
      border-radius: ${e.shape.borderRadius()};
      margin: ${e.spacing(0,2,2)};
      overflow: hidden;
      flex: 1;
    `,flexRow:n.css`
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
    `});var kt,Ot,Nt,$t,It,qt,Qt=s("./public/app/features/alerting/unified/hooks/useIsRuleEditable.ts"),Dt=s("./public/app/features/alerting/unified/utils/rule-id.ts");const Et=({identifier:e})=>{(0,o.x)((e=>e.unifiedAlerting.ruleForm.existingRule));const{loading:t,result:s,error:n,dispatched:i}=(0,v._)((e=>e.ruleForm.existingRule)),d=(0,u.useDispatch)(),{isEditable:p}=(0,Qt.M)(Dt.s0(e),null==s?void 0:s.rule);return(0,l.useEffect)((()=>{i||d((0,x.on)(e))}),[i,d,e]),t||void 0===p?kt||(kt=(0,c.jsx)(a.Z.Contents,{children:(0,c.jsx)(r.LoadingPlaceholder,{text:"Loading rule..."})})):n?(0,c.jsx)(a.Z.Contents,{children:(0,c.jsx)(r.Alert,{severity:"error",title:"Failed to load rule",children:n.message})}):s?!1===p?Nt||(Nt=(0,c.jsx)(Tt,{title:"Cannot edit rule",children:"Sorry! You do not have permission to edit this rule."})):(0,c.jsx)(Rt,{existing:s}):Ot||(Ot=(0,c.jsx)(Tt,{title:"Rule not found",children:"Sorry! This rule does not exist."}))},Tt=({title:e,children:t})=>(0,c.jsxs)(r.Alert,{className:(0,r.useStyles2)(Ft).warning,severity:"warning",title:e,children:[(0,c.jsx)("p",{children:t}),qt||(qt=(0,c.jsx)(r.LinkButton,{href:"alerting/list",children:"To rule list"}))]}),Ft=e=>({warning:n.css`
    margin: ${e.spacing(4)};
  `}),_t=(0,r.withErrorBoundary)((({match:e})=>{const{id:t}=e.params,s=Dt.OA(t,!0);return s?(0,c.jsx)(Et,{identifier:s},t):i.Vt.hasEditPermissionInFolders||i.Vt.isEditor?It||(It=(0,c.jsx)(Rt,{})):$t||($t=(0,c.jsx)(Tt,{title:"Cannot create rules",children:"Sorry! You are not allowed to create rules."}))}),{style:"page"})},"./public/app/features/alerting/unified/components/PanelPluginsButtonGroup.tsx":(e,t,s)=>{s.d(t,{j:()=>l});var n=s("./packages/grafana-runtime/src/index.ts"),r=s("./packages/grafana-ui/src/index.ts"),a=s("./node_modules/react/index.js"),i=s("./public/app/features/alerting/unified/utils/constants.ts"),o=s("./node_modules/react/jsx-runtime.js");function l(e){const{value:t,onChange:s,size:l="md"}=e,u=(0,a.useMemo)((()=>Object.values(n.config.panels).reduce(((e,t)=>(function(e){switch(e){case i.GC:case i.Fe:case i.Kd:return!0;default:return!1}}(t.id)&&e.push({value:t.id,label:t.name,imgUrl:t.info.logos.small}),e)),[])),[]);return(0,o.jsx)(r.RadioButtonGroup,{options:u,value:t,onChange:s,size:l})}},"./public/app/features/alerting/unified/hooks/useFolder.ts":(e,t,s)=>{s.d(t,{W:()=>l});var n=s("./node_modules/react-redux/es/index.js"),r=s("./public/app/features/alerting/unified/hooks/useUnifiedAlertingSelector.ts"),a=s("./node_modules/react/index.js"),i=s("./public/app/features/alerting/unified/state/actions.ts"),o=s("./public/app/features/alerting/unified/utils/redux.ts");function l(e){const t=(0,n.useDispatch)(),s=(0,r._)((e=>e.folders));if((0,a.useEffect)((()=>{e&&t((0,i.sw)(e))}),[t,e]),e){const t=s[e]||o.oq;return{folder:t.result,loading:t.loading}}return{loading:!1}}},"./public/app/features/alerting/unified/hooks/useIsRuleEditable.ts":(e,t,s)=>{s.d(t,{M:()=>c});var n=s("./public/app/core/services/context_srv.ts"),r=s("./public/app/features/alerting/unified/utils/rules.ts"),a=s("./public/app/features/alerting/unified/hooks/useFolder.ts"),i=s("./public/app/features/alerting/unified/hooks/useUnifiedAlertingSelector.ts"),o=s("./node_modules/react-redux/es/index.js"),l=s("./node_modules/react/index.js"),u=s("./public/app/features/alerting/unified/state/actions.ts"),d=s("./public/app/features/alerting/unified/utils/datasource.ts");function c(e,t){var s,c;const p=(0,i._)((e=>e.lotexSupportsRuleEditing)),g=(0,o.useDispatch)(),h=t&&(0,r.Pc)(t)?t.grafana_alert.namespace_uid:void 0,{folder:f,loading:m}=(0,a.W)(h);if((0,l.useEffect)((()=>{void 0===p[e]&&e!==d.GC&&g((0,u.Yb)(e))}),[e,p,g]),!t)return{isEditable:!1,loading:!1};if((0,r.Pc)(t)){if(!h)throw new Error(`Rule ${t.grafana_alert.title} does not have a folder uid, cannot determine if it is editable.`);return{isEditable:null==f?void 0:f.canSave,loading:m}}return{isEditable:n.Vt.isEditor&&!(null===(s=p[e])||void 0===s||!s.result),loading:!(null===(c=p[e])||void 0===c||!c.loading)}}},"./public/app/features/alerting/unified/state/AlertingQueryRunner.ts":(e,t,s)=>{s.d(t,{v:()=>R});var n=s("./node_modules/rxjs/dist/esm5/internal/ReplaySubject.js"),r=s("./node_modules/rxjs/dist/esm5/internal/observable/of.js"),a=s("./node_modules/rxjs/dist/esm5/internal/operators/catchError.js"),i=s("./node_modules/rxjs/dist/esm5/internal/operators/share.js"),o=s("./node_modules/rxjs/dist/esm5/internal/operators/map.js"),l=s("./node_modules/uuid/dist/esm-browser/v4.js"),u=s("./packages/grafana-data/src/index.ts"),d=s("./packages/grafana-runtime/src/index.ts"),c=s("./public/app/core/services/backend_srv.ts"),p=s("./public/app/features/query/state/runRequest.ts"),g=s("./public/app/features/expressions/types.ts");const h={from:21600,to:0},f=(e,t)=>{switch(e.type){case g.Us.classic:return m(e);case g.Us.math:return x(e,t);case g.Us.resample:case g.Us.reduce:return b(e)}},m=e=>{var t;return null===(t=e.conditions)||void 0===t?void 0:t.map((e=>e.query.params[0]))},v=(e,t)=>{let s=[],n=[h.to];for(const r of e){const e=t.find((e=>e.refId===r));e&&e.relativeTimeRange&&(s.push(e.relativeTimeRange.from),n.push(e.relativeTimeRange.to))}return{from:s,to:n}},x=(e,t)=>t.filter((t=>{var s;return"query"===t.queryType&&(null===(s=e.expression)||void 0===s?void 0:s.includes(t.refId))})).map((e=>e.refId)),b=e=>e.expression?[e.expression]:void 0;var j=s("./public/app/features/expressions/guards.ts"),y=s("./public/app/features/query/state/processing/revision.ts"),w=s("./public/app/features/query/state/processing/canceler.ts");function C(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class R{constructor(e=(0,c.i)()){C(this,"subject",void 0),C(this,"subscription",void 0),C(this,"lastResult",void 0),this.backendSrv=e,this.subject=new n.t(1),this.lastResult={}}get(){return this.subject.asObservable()}run(e){if(0===e.length){const t=k(e,u.LoadingState.Done);return this.subject.next(t)}this.subscription=S(this.backendSrv,e).subscribe({next:e=>{const t=I(e,((e,t)=>{const s=this.lastResult[e],n=(0,p.zR)(t,s);return(0,y.C)(n,s)}));this.lastResult=t,this.subject.next(this.lastResult)},error:e=>{this.lastResult=$(this.lastResult,e),this.subject.next(this.lastResult)}})}cancel(){if(!this.subscription)return;this.subscription.unsubscribe();let e=!1;const t=I(this.lastResult,((t,s)=>(s.state===u.LoadingState.Loading&&(e=!0),Object.assign({},s,{state:u.LoadingState.Done}))));e&&this.subject.next(t)}destroy(){this.subject&&this.subject.complete(),this.cancel()}}const S=(e,t)=>{const s=k(t,u.LoadingState.Loading),n={data:{data:t},url:"/api/v1/eval",method:"POST",requestId:(0,l.Z)()};return(0,u.withLoadingIndicator)({whileLoading:s,source:e.fetch(n).pipe(N(s),(0,a.K)((e=>(0,r.of)($(s,e)))),(0,w.V)(e,n.requestId),(0,i.B)())})},k=(e,t)=>e.reduce(((s,n)=>(s[n.refId]={state:t,series:[],timeRange:O(n,e)},s)),{}),O=(e,t)=>{if((0,j.j)(e.model)){const s=((e,t)=>{const s=f(e,t);if(!s)return h;const{from:n,to:r}=v(s,t);return n.length||r.length?{from:Math.max(...n),to:Math.min(...r)}:h})(e.model,t);return u.rangeUtil.relativeToTimeRange(s)}return e.relativeTimeRange?u.rangeUtil.relativeToTimeRange(e.relativeTimeRange):(console.warn(`Query with refId: ${e.refId} did not have any relative time range, using default.`),(0,u.getDefaultTimeRange)())},N=e=>(0,o.U)((t=>{const{data:s}=t,n={};for(const[t,r]of Object.entries(s.results))n[t]={timeRange:e[t].timeRange,state:u.LoadingState.Done,series:r.frames.map(u.dataFrameFromJSON)};return n})),$=(e,t)=>{const s=(0,d.toDataQueryError)(t);return I(e,((e,t)=>Object.assign({},t,{state:u.LoadingState.Error,error:s})))},I=(e,t)=>{const s={};for(const[n,r]of Object.entries(e))s[n]=t(n,r);return s}},"./public/app/features/expressions/guards.ts":(e,t,s)=>{s.d(t,{j:()=>a});var n=s("./public/app/features/expressions/ExpressionDatasource.ts"),r=s("./public/app/features/expressions/types.ts");const a=e=>{if(!e)return!1;if(e.datasource===n.DB)return!0;const t=e;return"string"==typeof t.type&&Object.values(r.Us).includes(t.type)}}}]);
//# sourceMappingURL=AlertingRuleForm.8128b05ac04b15cbf98d.js.map