"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[7978],{75429:(q,F,c)=>{c.d(F,{x:()=>k});var e=c(27702),w=c(18771),b=c(92071);function k(S){const M=(0,w.useDispatch)(),C=(0,e.useRef)(S);C.current=S,(0,e.useEffect)(()=>()=>{M((0,b.e)({cleanupAction:C.current}))},[M])}},98164:(q,F,c)=>{c.d(F,{V:()=>S});var e=c(33555),w=c(16881),b=c(8014);const k=w.C.injectEndpoints({endpoints:M=>({contactPointsState:M.query({queryFn:async({amSourceName:C})=>{try{return{data:await(0,b.QE)(C)}}catch(U){return{error:U}}}})})}),S=M=>{const C={receivers:{},errorCount:0},{currentData:U}=k.useContactPointsStateQuery({amSourceName:M??""},{skip:!M,pollingInterval:e.m4});return U??C}},89439:(q,F,c)=>{c.d(F,{q:()=>b});var e=c(27702),w=c(91368);const b=({actions:k,children:S,fallback:M=!0})=>k.some(C=>w.contextSrv.hasAccess(C,M))?e.createElement(e.Fragment,null,S):null},80118:(q,F,c)=>{c.d(F,{u:()=>U});var e=c(42844),w=c(27702),b=c(66310),k=c(63439),S=c(62862),M=c(52646),C=c(22513);function U({currentAlertmanager:D}){const te=(0,b.wW)(j),{useGetAlertmanagerChoiceStatusQuery:se}=M.alertmanagerApi,{currentData:W}=se(),G=D===C.GC;if(!(W?.alertmanagersChoice&&[S.TE.External,S.TE.All].includes(W?.alertmanagersChoice))||!G)return null;const u=W.numExternalAlertmanagers>0;return W.alertmanagersChoice===S.TE.External?w.createElement(k.b,{title:"Grafana alerts are not delivered to Grafana Alertmanager"},"Grafana is configured to send alerts to external Alertmanagers only. Changing Grafana Alertmanager configuration will not affect delivery of your alerts.",w.createElement("div",{className:te.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):W.alertmanagersChoice===S.TE.All&&u?w.createElement(k.b,{title:"You have additional Alertmanagers to configure",severity:"warning"},"Ensure you make configuration changes in the correct Alertmanagers; both internal and external. Changing one will not affect the others.",w.createElement("div",{className:te.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const j=D=>({adminHint:(0,e.css)`
    font-size: ${D.typography.bodySmall.fontSize};
    font-weight: ${D.typography.bodySmall.fontWeight};
  `})},18629:(q,F,c)=>{c.d(F,{C0:()=>M,Uv:()=>k,Xq:()=>S});var e=c(27702),w=c(63439),b=c(25357),k=(C=>(C.ContactPoint="contact point",C.Template="template",C.MuteTiming="mute timing",C.AlertRule="alert rule",C.RootNotificationPolicy="root notification policy",C))(k||{});const S=({resource:C})=>e.createElement(w.b,{title:`This ${C} cannot be edited through the UI`,severity:"info"},"This ",C," has been provisioned, that means it was created by config. Please contact your server admin to update this ",C,"."),M=()=>e.createElement(b.C,{text:"Provisioned",color:"purple"})},17978:(q,F,c)=>{c.r(F),c.d(F,{default:()=>ar});var e=c(27702),w=c(7662),b=c(63439),k=c(52419),S=c(18771),M=c(97529),C=c(10027),U=c(1469),j=c(47702),D=c(22513),te=c(80118),se=c(42481),W=c(89949);function G(t,n){let a=n.trim();if(!a.match(/\{\{\s*define/)){const r=a.split(`
`).map(s=>"  "+s).join(`
`);a=`{{ define "${t}" }}
${r}
{{ end }}`}return a}function J(t){const n=(a,r)=>`{{ define "${r}_NEW_${(0,W.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var u=c(42844),ee=c(84925),Te=c(55434),Rt=c(48335);function Me(t,n){(0,Te.Z)(2,arguments);var a=(0,Rt.Z)(n);return(0,ee.Z)(t,-a)}var z=c(46089),ve=c(55925),oe=c(23852),V=c(66310),xt=c(5229),le=c(22209),me=c(1128),wt=c(15372),ke=c(54281),x=c(66670),Pt=c(62499),Nt=c(62108),Re=c(75429),It=c(16881);const Ot="/api/alertmanager/grafana/config/api/v1/templates/test",Lt=It.C.injectEndpoints({endpoints:t=>({previewTemplate:t.mutation({query:({template:n,alerts:a,name:r})=>({url:Ot,data:{template:n,alerts:a,name:r},method:"POST"})})})}),{usePreviewTemplateMutation:Dt}=Lt;var _=c(39036),xe=c(84369),ue=c(18629),We=c(80011),Ee=c(73453),Fe=c(11649),ge=c(25357),Ve=c(25472),$t=c(65333),ie=c(13741),Mt=c(33716),kt=c(52646),fe=c(77328),Ue=c(57117);function Wt({onSelect:t,isOpen:n,onClose:a}){const r=(0,V.wW)(Ft),[s,i]=(0,e.useState)(),[l,d]=(0,e.useState)(null),{useGetAlertmanagerAlertsQuery:g}=kt.alertmanagerApi,{currentData:m=[],isFetching:p,isError:f}=g({amSourceName:D.GC,filter:{inhibited:!0,silenced:!0,active:!0}}),[h,y]=(0,e.useState)(""),A=(0,e.useMemo)(()=>{const N={};return!p&&m&&m.forEach(T=>{N[T.labels.alertname]||(N[T.labels.alertname]=[]),N[T.labels.alertname].push(T)}),N},[p,m]),R=(0,e.useCallback)(N=>{i(N),d(null)},[]),I=(0,e.useMemo)(()=>{const N=Object.keys(A).filter(v=>v.toLowerCase().includes(h.toLowerCase())),T={};return N.forEach(v=>{T[v]=A[v]}),T},[A,h]);if(f)return null;const E=Object.keys(I||[]),P=({index:N,style:T})=>{if(!I)return null;const v=E[N],O=v===s;return e.createElement("button",{type:"button",title:v,style:T,className:(0,u.cx)(r.rowButton,{[r.rowOdd]:N%2===1,[r.rowSelected]:O}),onClick:()=>R(v)},e.createElement("div",{className:(0,u.cx)(r.ruleTitle,r.rowButtonTitle)},v),e.createElement("div",{className:r.alertFolder},e.createElement(e.Fragment,null,e.createElement(Ee.J,{name:"folder"})," ",I[v][0].labels.grafana_folder??"")))},H=(N,T)=>{const O=N.map(re=>re.labels).map(fe.cH),Q=(0,Ue.z)(O),L=(0,Ue.r)((0,fe.cH)(T.labels),Q);return L.length?(0,fe.P3)((0,fe.nW)(L)):(0,fe.P3)(T.labels)},$=({index:N,style:T})=>{const v=(0,e.useMemo)(()=>s?A[s]:[],[]),O=v[N],Q=l?.includes(O),L=(0,e.useMemo)(()=>H(v,O),[v,O]),B=()=>{if(Q&&l){d(l.filter(re=>re!==O));return}d([...l||[],O])};return e.createElement("button",{type:"button",style:T,className:(0,u.cx)(r.rowButton,r.instanceButton,{[r.rowOdd]:N%2===1,[r.rowSelected]:Q}),onClick:B},e.createElement("div",{className:r.rowButtonTitle,title:O.labels.alertname},e.createElement(We.u,{placement:"bottom",content:e.createElement("pre",null,JSON.stringify(O,null,2)),theme:"info"},e.createElement("div",null,L.map((re,$e)=>e.createElement($t.V,{key:$e,name:re,className:r.tag}))))))},K=()=>{const N=l?.map(T=>({annotations:T.annotations,labels:T.labels,startsAt:T.startsAt,endsAt:T.endsAt}))||[];t(N),Z()},Z=()=>{i(void 0),d(null),y(""),de("")},ae=()=>{Z(),a()},de=N=>{y(N)};return e.createElement("div",null,e.createElement(ie.u,{title:"Select alert instances",className:r.modal,closeOnEscape:!0,isOpen:n,onDismiss:ae,contentClassName:r.modalContent},e.createElement("div",{className:r.container},e.createElement(Mt.H,{value:h,onChange:de,title:"Search alert rule",placeholder:"Search alert rule",autoFocus:!0}),e.createElement("div",null,s&&"Select one or more instances from the list below"||""),e.createElement("div",{className:r.column},p&&e.createElement(k.u,{text:"Loading rules...",className:r.loadingPlaceholder}),!p&&e.createElement(ve.Z,null,({height:N,width:T})=>e.createElement(Ve.t7,{itemSize:50,height:N,width:T,itemCount:E.length},P))),e.createElement("div",{className:r.column},!s&&!p&&e.createElement("div",{className:r.selectedRulePlaceholder},e.createElement("div",null,"Select an alert rule to get a list of available instances")),p&&e.createElement(k.u,{text:"Loading rule...",className:r.loadingPlaceholder}),s&&A[s].length&&!p&&e.createElement(ve.Z,null,({width:N,height:T})=>e.createElement(Ve.t7,{itemSize:32,height:T,width:N,itemCount:A[s].length||0},$)))),e.createElement(ie.u.ButtonRow,null,e.createElement(x.zx,{type:"button",variant:"secondary",onClick:ae},"Cancel"),e.createElement(x.zx,{type:"button",variant:"primary",disabled:!(s&&l),onClick:()=>{s&&l&&K()}},"Add alert data to payload"))))}const Ft=t=>{const n=(0,x.gN)(t);return{container:(0,u.css)`
      display: grid;
      grid-template-columns: 1fr 1.5fr;
      grid-template-rows: min-content auto;
      gap: ${t.spacing(2)};
      flex: 1;
    `,tag:(0,u.css)`
      margin: 5px;
    `,column:(0,u.css)`
      flex: 1 1 auto;
    `,alertLabels:(0,u.css)`
      overflow-x: auto;
      height: 32px;
    `,ruleTitle:(0,u.css)`
      height: 22px;
      font-weight: ${t.typography.fontWeightBold};
    `,rowButton:(0,u.css)`
      ${n};
      padding: ${t.spacing(.5)};
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: left;
      white-space: nowrap;
      cursor: pointer;
      border: 2px solid transparent;

      &:disabled {
        cursor: not-allowed;
        color: ${t.colors.text.disabled};
      }
    `,rowButtonTitle:(0,u.css)`
      overflow-x: auto;
    `,rowSelected:(0,u.css)`
      border-color: ${t.colors.primary.border};
    `,rowOdd:(0,u.css)`
      background-color: ${t.colors.background.secondary};
    `,instanceButton:(0,u.css)`
      display: flex;
      gap: ${t.spacing(1)};
      justify-content: space-between;
      align-items: center;
    `,loadingPlaceholder:(0,u.css)`
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    `,selectedRulePlaceholder:(0,u.css)`
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      font-weight: ${t.typography.fontWeightBold};
    `,modal:(0,u.css)`
      height: 100%;
    `,modalContent:(0,u.css)`
      flex: 1;
      display: flex;
      flex-direction: column;
    `,modalAlert:(0,u.css)`
      flex-grow: 0;
    `,warnIcon:(0,u.css)`
      fill: ${t.colors.warning.main};
    `,labels:(0,u.css)`
      justify-content: flex-start;
    `,alertFolder:(0,u.css)`
      height: 20px;
      font-size: ${t.typography.bodySmall.fontSize};
      color: ${t.colors.text.secondary};
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      column-gap: ${t.spacing(1)};
      align-items: center;
    `}},Vt=[{name:"Receiver",type:"string",notes:"Name of the contact point that the notification is being sent to."},{name:"Status",type:"string",notes:"firing if at least one alert is firing, otherwise resolved"},{name:"Alerts",type:"[]Alert",notes:"List of alert objects that are included in this notification."},{name:"Alerts.Firing",type:"[]Alert",notes:"List of firing alerts"},{name:"Alerts.Resolved",type:"[]Alert",notes:"List of resolved alerts"},{name:"GroupLabels",type:"KeyValue",notes:"Labels these alerts were grouped by."},{name:"CommonLabels",type:"KeyValue",notes:"Labels common to all the alerts included in this notification."},{name:"CommonAnnotations",type:"KeyValue",notes:"Annotations common to all the alerts included in this notification."},{name:"ExternalURL",type:"string",notes:"Back link to the Grafana that sent the notification."}],Ut=[{name:"Labels",type:"KeyValue",notes:"Set of labels attached to the alert."},{name:"Annotations",type:"KeyValue",notes:"Set of annotations attached to the alert."},{name:"StartsAt",type:"time.Time",notes:"Time the alert started firing."},{name:"EndsAt",type:"time.Time",notes:"Time the alert ends firing."}],Gt=[{name:"Status",type:"string",notes:"firing or resolved."},{name:"Labels",type:"KeyValue",notes:"Set of labels attached to the alert."},{name:"Annotations",type:"KeyValue",notes:"Set of annotations attached to the alert."},{name:"Values",type:"KeyValue",notes:"The values of all instant queries, reduce and math expressions, and classic conditions for the alert. It does not contain time series data."},{name:"StartsAt",type:"time.Time",notes:"Time the alert started firing."},{name:"EndsAt",type:"time.Time",notes:"Only set if the end time of an alert is known. Otherwise set to a configurable timeout period from the time since the last alert was received."},{name:"GeneratorURL",type:"string",notes:"A back link to Grafana or external Alertmanager."},{name:"SilenceURL",type:"string",notes:"Link to Grafana silence for with labels for this alert pre-filled. Only for Grafana managed alerts."},{name:"DashboardURL",type:"string",notes:"Link to Grafana dashboard, if alert rule belongs to one. Only for Grafana managed alerts."},{name:"PanelURL",type:"string",notes:"Link to Grafana dashboard panel, if alert rule belongs to one. Only for Grafana managed alerts."},{name:"Fingerprint",type:"string",notes:"Fingerprint that can be used to identify the alert."},{name:"ValueString",type:"string",notes:"String that contains the labels and value of each reduced expression in the alert."}],Bt=[{name:"SortedPairs",returns:"KeyValue",notes:"Returns sorted list of key & value string pairs"},{name:"Remove",args:"[]string",returns:"KeyValue",notes:"Returns a copy of the Key/Value map without the given keys."},{name:"Names",returns:"[]string",notes:"List of label names"},{name:"Values",returns:"[]string",notes:"List of label values"}],zt=`{
  "summary": "alert summary",
  "description": "alert description"
}
`;var Ge=c(51453);function Kt(){const t=(0,V.wW)(jt),n=e.createElement(we,{caption:e.createElement("h4",{className:t.header},"Alert template data ",e.createElement("span",null,"Available only when in the context of an Alert (e.g. inside .Alerts loop)")),dataItems:Gt});return e.createElement(oe.K,{gap:2,flexGrow:1},e.createElement(we,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:Vt,typeRenderer:a=>a==="[]Alert"?e.createElement(Ge.z,{content:n},e.createElement("div",{className:t.interactiveType},a)):a==="KeyValue"?e.createElement(Ge.z,{content:e.createElement(Ht,null)},e.createElement("div",{className:t.interactiveType},a)):a}))}const jt=t=>({header:(0,u.css)`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `,interactiveType:(0,u.css)`
    color: ${t.colors.text.link};
  `});function we({dataItems:t,caption:n,typeRenderer:a}){const r=(0,V.wW)(Be);return e.createElement("table",{className:r.table},e.createElement("caption",null,n),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Type"),e.createElement("th",null,"Notes"))),e.createElement("tbody",null,t.map(({name:s,type:i,notes:l},d)=>e.createElement("tr",{key:d},e.createElement("td",null,s),e.createElement("td",null,a?a(i):i),e.createElement("td",null,l)))))}function Ht(){const t=(0,V.wW)(Be);return e.createElement("div",null,"KeyValue is a set of key/value string pairs that represent labels and annotations.",e.createElement("pre",null,e.createElement("code",null,zt)),e.createElement("table",{className:t.table},e.createElement("caption",null,"Key-value methods"),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Arguments"),e.createElement("th",null,"Returns"),e.createElement("th",null,"Notes"))),e.createElement("tbody",null,Bt.map(({name:n,args:a,returns:r,notes:s})=>e.createElement("tr",{key:n},e.createElement("td",null,n),e.createElement("td",null,a),e.createElement("td",null,r),e.createElement("td",null,s))))))}const Be=t=>({table:(0,u.css)`
    border-collapse: collapse;
    width: 100%;

    caption {
      caption-side: top;
    }

    td,
    th {
      padding: ${t.spacing(1,1)};
    }

    thead {
      font-weight: ${t.typography.fontWeightBold};
    }

    tbody tr:nth-child(2n + 1) {
      background-color: ${t.colors.background.secondary};
    }

    tbody td:nth-child(1) {
      font-weight: ${t.typography.fontWeightBold};
    }

    tbody td:nth-child(2) {
      font-style: italic;
    }
  `});var Jt=c(50230),ze=c(40705),Ke=c(98321),je=c(50115);const Qt={annotations:[{key:"",value:""}],labels:[{key:"",value:""}],status:"firing"},_t=({isOpen:t,onDismiss:n,onAccept:a})=>{const r=(0,V.wW)(Yt),[s,i]=(0,e.useState)([]),l=(0,z.cI)({defaultValues:Qt,mode:"onBlur"}),d=l.watch("annotations"),g=l.watch("labels"),[m,p]=(0,e.useState)("firing"),f=()=>{const R={annotations:d.filter(({key:I,value:E})=>!!I&&!!E).reduce((I,{key:E,value:P})=>({...I,[E]:P}),{}),labels:g.filter(({key:I,value:E})=>!!I&&!!E).reduce((I,{key:E,value:P})=>({...I,[E]:P}),{}),startsAt:"2023-04-01T00:00:00Z",endsAt:m==="firing"?(0,ee.Z)(new Date,1).toISOString():Me(new Date,1).toISOString()};i(I=>[...I,R]),l.reset()},h=()=>{a(s),i([]),l.reset(),p("firing")},y=()=>{const R=g.some(E=>E.key!==""&&E.value!==""),I=d.some(E=>E.key!==""&&E.value!=="");return R||I},A=[{label:"Firing",value:"firing"},{label:"Resolved",value:"resolved"}];return e.createElement(ie.u,{onDismiss:n,isOpen:t,title:"Add custom alerts"},e.createElement(z.RV,{...l},e.createElement("form",{onSubmit:R=>{R.preventDefault(),R.stopPropagation(),l.reset(),p("firing")}},e.createElement(e.Fragment,null,e.createElement(Jt.Z,null,e.createElement(oe.K,{direction:"column",gap:1},e.createElement("div",{className:r.section},e.createElement(Ke.Z,null)),e.createElement("div",{className:r.section},e.createElement(je.Z,null)),e.createElement("div",{className:r.flexWrapper},e.createElement(ze.S,{value:m,options:A,onChange:R=>p(R)}),e.createElement(x.zx,{onClick:f,className:r.onAddButton,icon:"plus-circle",type:"button",variant:"secondary",disabled:!y()},"Add alert data"))))),e.createElement("div",{className:r.onSubmitWrapper}),s.length>0&&e.createElement(oe.K,{direction:"column",gap:1},e.createElement("h5",null," Review alert data to add to the payload:"),e.createElement("pre",{className:r.result,"data-testid":"payloadJSON"},JSON.stringify(s,null,2))),e.createElement("div",{className:r.onSubmitWrapper},e.createElement(ie.u.ButtonRow,null,e.createElement(x.zx,{onClick:h,disabled:s.length===0,className:r.onSubmitButton},"Add alert data to payload"))))))},Yt=t=>({section:(0,u.css)`
    margin-bottom: ${t.spacing(2)};
  `,onAddButton:(0,u.css)`
    flex: none;
    width: fit-content;
    padding-right: ${t.spacing(1)};
    margin-left: auto;
  `,flexWrapper:(0,u.css)`
    display: flex;
    flex-direction: row,
    justify-content: space-between;
  `,onSubmitWrapper:(0,u.css)`
    display: flex;
    flex-direction: row;
    align-items: baseline;
    justify-content: flex-end;
  `,onSubmitButton:(0,u.css)`
    margin-left: ${t.spacing(2)};
  `,result:(0,u.css)`
    width: 570px;
    height: 363px;
  `}),Zt="Reset to default";function Xt({payload:t,setPayload:n,defaultPayload:a,setPayloadFormatError:r,payloadFormatError:s,onPayloadError:i}){const l=(0,V.wW)(He),d=()=>{n(a)},[g,m]=(0,e.useState)(!1),p=()=>{m(!1)},f=s!==null,h=()=>{try{const P=JSON.parse(t);JSON.stringify([...P]),r(null)}catch(P){throw r(P instanceof Error?P.message:"Invalid JSON."),i(),P}},y=()=>{try{h(),m(!0)}catch{}},A=()=>{try{h(),E(!0)}catch{}},R=P=>{p(),E(!1),n(H=>{const $=JSON.parse(H);return JSON.stringify([...$,...P],void 0,2)})},[I,E]=(0,e.useState)(!1);return e.createElement("div",{className:l.wrapper},e.createElement("div",{className:l.editor},e.createElement("div",{className:l.title},"Payload data",e.createElement(We.u,{placement:"top",content:e.createElement(qt,null),theme:"info"},e.createElement(Ee.J,{name:"info-circle",className:l.tooltip,size:"xl"}))),e.createElement(ve.Z,{disableHeight:!0},({width:P})=>e.createElement("div",{className:l.editorWrapper},e.createElement(Fe.p,{width:P,height:362,language:"json",showLineNumbers:!0,showMiniMap:!1,value:t,readOnly:!1,onBlur:n}))),e.createElement("div",{className:l.buttonsWrapper},e.createElement(x.zx,{type:"button",variant:"secondary",className:l.button,icon:"bell",disabled:f,onClick:A},"Select alert instances"),e.createElement(x.zx,{onClick:y,className:l.button,icon:"plus-circle",type:"button",variant:"secondary",disabled:f},"Add custom alerts"),e.createElement(x.zx,{onClick:d,className:l.button,icon:"arrow-up",type:"button",variant:"destructive"},Zt),s!==null&&e.createElement(ge.C,{color:"orange",icon:"exclamation-triangle",text:"JSON Error",tooltip:"Fix errors in payload, and click Refresh preview button"}))),e.createElement(_t,{isOpen:g,onDismiss:p,onAccept:R}),e.createElement(Wt,{onSelect:R,isOpen:I,onClose:()=>E(!1)}))}const qt=()=>{const t=(0,V.wW)(He);return e.createElement(we,{caption:e.createElement("h4",{className:t.templateDataDocsHeader},"Alert template data ",e.createElement("span",null,"This is the list of alert data fields used in the preview.")),dataItems:Ut})},He=t=>({jsonEditor:(0,u.css)`
    width: 100%;
    height: 100%;
  `,buttonsWrapper:(0,u.css)`
    margin-top: ${t.spacing(1)};
    display: flex;
    flex-wrap: wrap;
  `,button:(0,u.css)`
    flex: none;
    width: fit-content;
    padding-right: ${t.spacing(1)};
    margin-right: ${t.spacing(1)};
    margin-bottom: ${t.spacing(1)};
  `,title:(0,u.css)`
    font-weight: ${t.typography.fontWeightBold};
    heigth: 41px;
    padding-top: 10px;
    padding-left: ${t.spacing(2)};
    margin-top: 19px;
  `,wrapper:(0,u.css)`
    flex: 1;
    min-width: 450px;
  `,tooltip:(0,u.css)`
    padding-left: ${t.spacing(1)};
  `,editorWrapper:(0,u.css)`
    width: min-content;
    padding-top: 7px;
  `,editor:(0,u.css)`
    display: flex;
    flex-direction: column;
    margin-top: ${t.spacing(-1)};
  `,templateDataDocsHeader:(0,u.css)`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `});var ce=c(21475);function en(t){const n=t.languages.CompletionItemKind.Function;return[{label:ce.AlertmanagerTemplateFunction.toUpper,detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.toLower,detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.title,documentation:"Capitalizes the first letter of each word",detail:"function(s string)",kind:n},{label:ce.AlertmanagerTemplateFunction.join,documentation:{value:"Joins an array of strings using the separator provided."},detail:"function(separator string, s []string)",kind:n},{label:ce.AlertmanagerTemplateFunction.match,detail:"function",kind:n},{label:ce.AlertmanagerTemplateFunction.safeHtml,detail:"function(pattern, repl, text)",kind:n},{label:ce.AlertmanagerTemplateFunction.reReplaceAll,detail:"function(pattern, repl, text)",kind:n},{label:ce.AlertmanagerTemplateFunction.stringSlice,detail:"function(s ...string)",kind:n}]}const tn=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,nn=`
[{{.Status}}] {{ .Labels.alertname }}

Labels:
{{ range .Labels.SortedPairs }}
  {{ .Name }}: {{ .Value }}
{{ end }}

{{ if gt (len .Annotations) 0 }}
Annotations:
{{ range .Annotations.SortedPairs }}
  {{ .Name }}: {{ .Value }}
{{ end }}
{{ end }}

{{ if gt (len .SilenceURL ) 0 }}
  Silence alert: {{ .SilenceURL }}
{{ end }}
{{ if gt (len .DashboardURL ) 0 }}
  Go to dashboard: {{ .DashboardURL }}
{{ end }}
`,an=he("GroupLabels"),rn=he("CommonLabels"),sn=he("CommonAnnotations"),on=he("Labels"),ln=he("Annotations");function he(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function cn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Alerts",kind:n,detail:"Alert[]",documentation:{value:"An Array containing all alerts"}},{label:"Receiver",kind:n,detail:"string"},{label:"Status",kind:n,detail:"string"},{label:"GroupLabels",kind:n,detail:"[]KeyValue"},{label:"CommonLabels",kind:n,detail:"[]KeyValue"},{label:"CommonAnnotations",kind:n,detail:"[]KeyValue"},{label:"ExternalURL",kind:n,detail:"string"}]}function dn(t){const n=t.languages.CompletionItemKind.Field;return[{label:{label:"Status",detail:"(Alert)",description:"string"},kind:n,detail:"string",documentation:{value:"Status of the alert. It can be `firing` or `resolved`"}},{label:{label:"Labels",detail:"(Alert)"},kind:n,detail:"[]KeyValue",documentation:{value:"A set of labels attached to the alert."}},{label:{label:"Annotations",detail:"(Alert)"},kind:n,detail:"[]KeyValue",documentation:"A set of annotations attached to the alert."},{label:{label:"StartsAt",detail:"(Alert)"},kind:n,detail:"time.Time",documentation:"Time the alert started firing."},{label:{label:"EndsAt",detail:"(Alert)"},kind:n,detail:"time.Time",documentation:"Only set if the end time of an alert is known. Otherwise set to a configurable timeout period from the time since the last alert was received."},{label:{label:"GeneratorURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Back link to Grafana or external Alertmanager."},{label:{label:"SilenceURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana silence for with labels for this alert pre-filled. Only for Grafana managed alerts."},{label:{label:"DashboardURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana dashboard, if alert rule belongs to one. Only for Grafana managed alerts."},{label:{label:"PanelURL",detail:"(Alert)"},kind:n,detail:"string",documentation:"Link to Grafana dashboard panel, if alert rule belongs to one. Only for Grafana managed alerts."},{label:{label:"Fingerprint",detail:"(Alert)"},kind:n,detail:"string",documentation:"Fingerprint that can be used to identify the alert."},{label:{label:"ValueString",detail:"(Alert)"},kind:n,detail:"string",documentation:"String that contains labels and values of each reduced expression in the alert."}]}function mn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function un(t){const n=t.languages.CompletionItemKind.Field;return[{label:"SortedPairs",kind:n,detail:"[]KeyValue"},{label:"Names",kind:n,detail:"[]string"},{label:"Values",kind:n,detail:"[]string"},{label:"Remove",detail:"KeyValue[] function(keys []string)",kind:t.languages.CompletionItemKind.Method}]}const Je={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:tn},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:nn},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:an},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:rn},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:sn},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:on},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:ln}};function pn(t){const n=t.languages.CompletionItemKind.Snippet,a=t.languages.CompletionItemInsertTextRule.InsertAsSnippet,{alerts:r,alertDetails:s,groupLabels:i,commonLabels:l,commonAnnotations:d,labels:g,annotations:m}=Je;return[{label:r.label,documentation:r.description,kind:n,insertText:r.snippet,insertTextRules:a},{label:{label:s.label,detail:"(Alert)"},documentation:s.description,kind:n,insertText:s.snippet,insertTextRules:a},{label:i.label,documentation:i.description,kind:n,insertText:i.snippet,insertTextRules:a},{label:l.label,documentation:l.description,kind:n,insertText:l.snippet,insertTextRules:a},{label:d.label,documentation:d.description,kind:n,insertText:d.snippet,insertTextRules:a},{label:{label:g.label,detail:"(Alert)"},documentation:g.description,kind:n,insertText:g.snippet,insertTextRules:a},{label:{label:m.label,detail:"(Alert)"},documentation:m.description,kind:n,insertText:m.snippet,insertTextRules:a}]}function gn(t){const n={triggerCharacters:["."],provideCompletionItems(a,r,s){const i=a.getWordUntilPosition(r),l={startLineNumber:r.lineNumber,endLineNumber:r.lineNumber,startColumn:i.startColumn,endColumn:i.endColumn},d=new hn(t,l);if(!fn(a,r))return d.getSnippetsSuggestions();if(s.triggerKind===t.languages.CompletionTriggerKind.Invoke&&!s.triggerCharacter)return d.getFunctionsSuggestions();const m=a.getWordUntilPosition({lineNumber:r.lineNumber,column:r.column-1});return d.getTemplateDataSuggestions(m.word)}};return t.languages.registerCompletionItemProvider("go-template",n)}function fn(t,n){const a={startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:t.getLineMinColumn(n.lineNumber),endColumn:t.getLineMaxColumn(n.lineNumber)},r='\\{\\{[a-zA-Z0-9._() "]+\\}\\}';return t.findMatches(r,a,!0,!1,null,!0).some(i=>i.range.containsPosition(n))}class hn{constructor(n,a){this.monaco=n,this.range=a,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(pn(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(en(this.monaco)),this.getTemplateDataSuggestions=r=>{switch(r){case"":return this.getCompletionsFromDefinitions(cn(this.monaco),dn(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(mn(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(un(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...r)=>({suggestions:(0,W.concat)(...r).map(i=>yn(i,this.range))})}}function yn({label:t,detail:n,documentation:a,kind:r,insertText:s},i){const l=typeof t=="string"?t:t.label,d=typeof t=="string"?{label:t,description:n}:{...t};return d.description??=n,{label:d,kind:r,insertText:s??l,range:i,documentation:a,detail:n}}const Qe="go-template",vn={id:Qe,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(c.bind(c,21475))},En=(t,n)=>{const{id:a,loader:r}=n;t.languages.getLanguages().find(i=>i.id===a)||(t.languages.register({id:a}),r().then(i=>{t.languages.setMonarchTokensProvider(a,i.language),t.languages.setLanguageConfiguration(a,i.conf)}))},_e=t=>{const n=!!t.autoHeight,a=(0,e.useRef)(null),r=s=>{if(n){const i=s.getContentHeight();try{s.layout({height:i,width:NaN})}catch{}}};return(0,e.useEffect)(()=>()=>{a.current?.dispose()},[]),e.createElement(Fe.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:r,onBeforeEditorMount:s=>{En(s,vn),a.current=gn(s)},language:Qe})},bn=Object.freeze({name:"",content:""}),An=t=>t.pathname.endsWith("/duplicate"),Ye=`[
  {
    "annotations": {
      "summary": "Instance instance1 has been down for more than 5 minutes"
    },
    "labels": {
      "instance": "instance1"
    },
    "startsAt": "${Me(new Date,1).toISOString()}"
  }]
`,Pe=({existing:t,alertManagerSourceName:n,config:a,provenance:r})=>{const s=(0,V.wW)(Ne),i=(0,S.useDispatch)();(0,Re.x)(v=>v.unifiedAlerting.saveAMConfig=xe.oq);const{loading:l,error:d}=(0,C._)(v=>v.saveAMConfig),g=(0,w.TH)(),m=An(g),[p,f]=(0,e.useState)(Ye),[h,y]=(0,e.useState)(null),[A,R]=(0,e.useState)("content"),I=()=>R("preview"),E=v=>{const O=G(v.name,v.content),Q={...a.template_files,[v.name]:O};t&&t.name!==v.name&&delete Q[t.name];const L=[...(a.alertmanager_config.templates??[]).filter(re=>re!==t?.name),v.name],B={template_files:Q,alertmanager_config:{...a.alertmanager_config,templates:L}};i((0,j.mM)({alertManagerSourceName:n,newConfig:B,oldConfig:a,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},P=(0,z.cI)({mode:"onSubmit",defaultValues:t??bn}),{handleSubmit:H,register:$,formState:{errors:K},getValues:Z,setValue:ae,watch:de}=P,N=v=>!a.template_files[v]||t?.name===v?!0:"Another template with this name already exists.",T=n===D.GC;return e.createElement(z.RV,{...P},e.createElement("form",{onSubmit:H(E)},e.createElement("h4",null,t&&!m?"Edit notification template":"Create notification template"),d&&e.createElement(b.b,{severity:"error",title:"Error saving template"},d.message||d?.data?.message||String(d)),r&&e.createElement(ue.Xq,{resource:ue.Uv.Template}),e.createElement(xt.C,{disabled:!!r},e.createElement(le.g,{label:"Template name",error:K?.name?.message,invalid:!!K.name?.message,required:!0},e.createElement(me.I,{...$("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:N}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Cn,null),e.createElement("div",{className:s.editorsWrapper},e.createElement("div",{className:s.contentContainer},e.createElement(wt.J,null,e.createElement(ke.O,{label:"Content",active:A==="content",onChangeTab:()=>R("content")}),T&&e.createElement(ke.O,{label:"Preview",active:A==="preview",onChangeTab:()=>R("preview")})),e.createElement("div",{className:s.contentContainerEditor},e.createElement(ve.Z,null,({width:v})=>e.createElement(e.Fragment,null,A==="content"?e.createElement("div",null,e.createElement(le.g,{error:K?.content?.message,invalid:!!K.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(_e,{value:Z("content"),width:v,height:363,onBlur:O=>ae("content",O)}))),e.createElement("div",{className:s.buttons},l&&e.createElement(x.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!l&&e.createElement(x.zx,{type:"submit",variant:"primary"},"Save template"),e.createElement(x.Qj,{disabled:l,href:(0,_.eQ)("alerting/notifications",n),variant:"secondary",type:"button"},"Cancel"))):e.createElement(wn,{width:v,payload:p,templateName:de("name"),setPayloadFormatError:y,payloadFormatError:h}))))),T&&e.createElement(Xt,{payload:p,setPayload:f,defaultPayload:Ye,setPayloadFormatError:y,payloadFormatError:h,onPayloadError:I}))),e.createElement(Pt.s,{label:"Data cheat sheet",isOpen:!1,className:s.collapsableSection},e.createElement(Kt,null))))};function Cn(){const t=(0,V.wW)(Ne);return e.createElement(b.b,{title:"Templating guideline",severity:"info"},e.createElement(oe.K,{direction:"row"},e.createElement("div",null,"Grafana uses Go templating language to create notification messages.",e.createElement("br",null),"To find out more about templating please visit our documentation."),e.createElement("div",null,e.createElement(x.Qj,{href:"https://grafana.com/docs/grafana/latest/alerting/manage-notifications/template-notifications/",target:"_blank",icon:"external-link-alt",variant:"secondary"},"Templating documentation"))),e.createElement("div",{className:t.snippets},"To make templating easier, we provide a few snippets in the content editor to help you speed up your workflow.",e.createElement("div",{className:t.code},Object.values(Je).map(n=>n.label).join(", "))))}function Sn(t){const n=t.filter(s=>s.text.trim().length>0),a=n.length>1,r=s=>{const i=`Preview for ${s.name}:`,l="=".repeat(i.length).concat(">"),d="<".concat("=".repeat(i.length));return a?`${i}
${l}${s.text}${d}
`:`${l}${s.text}${d}
`};return n.map(s=>r(s)).join(`
`)}function Tn(t){return t.map(n=>n.name?`ERROR in ${n.name}:
`.concat(`${n.kind}
${n.message}
`):`ERROR:
${n.kind}
${n.message}
`).join(`
`)}const Rn="Preview request failed. Check if the payload data has the correct structure.";function xn(t,n,a){const r=t?Rn:void 0,s=t||!!n,i=n||r,l=a?.results,d=a?.errors,g=l?Sn(l):"",m=d?Tn(d):"";return s?i:`${g}
${m}`}function wn({payload:t,templateName:n,payloadFormatError:a,setPayloadFormatError:r,width:s}){const i=(0,V.wW)(Ne),{watch:l}=(0,z.Gc)(),d=l("content"),[g,{data:m,isError:p,isLoading:f}]=Dt(),h=xn(p,a,m),y=(0,e.useCallback)(()=>{try{const A=JSON.parse(t);JSON.stringify([...A]),g({template:d,alerts:A,name:n}),r(null)}catch(A){r(A instanceof Error?A.message:"Invalid JSON.")}},[d,n,t,r,g]);return(0,e.useEffect)(()=>y(),[y]),e.createElement("div",{style:{width:`${s}px`},className:i.preview.wrapper},f&&e.createElement(e.Fragment,null,e.createElement(Nt.$,{inline:!0})," Loading preview..."),e.createElement("pre",{className:i.preview.result,"data-testid":"payloadJSON"},h),e.createElement(x.zx,{onClick:y,className:i.preview.button,icon:"arrow-up",type:"button",variant:"secondary"},"Refresh preview"))}const Ne=t=>({contentContainer:(0,u.css)`
    flex: 1;
    margin-bottom: ${t.spacing(6)};
  `,contentContainerEditor:(0,u.css)`
      flex:1;
      display: flex;
      padding-top: 10px;
      gap: ${t.spacing(2)};
      flex-direction: row;
      align-items: flex-start;
      flex-wrap: wrap;
      ${t.breakpoints.up("xxl")} {
        flex - wrap: nowrap;
    }
      min-width: 450px;
      height: 363px;
      `,snippets:(0,u.css)`
    margin-top: ${t.spacing(2)};
    font-size: ${t.typography.bodySmall.fontSize};
  `,code:(0,u.css)`
    color: ${t.colors.text.secondary};
    font-weight: ${t.typography.fontWeightBold};
  `,buttons:(0,u.css)`
    display: flex;
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
    margin-top: -7px;
  `,textarea:(0,u.css)`
    max-width: 758px;
  `,editWrapper:(0,u.css)`
      display: flex;
      width: 100%
      heigth:100%;
      position: relative;
      `,toggle:(0,u.css)`
      color: theme.colors.text.secondary,
      marginRight: ${t.spacing(1)}`,preview:{wrapper:(0,u.css)`
      display: flex;
      width: 100%
      heigth:100%;
      position: relative;
      flex-direction: column;
      `,result:(0,u.css)`
      width: 100%;
      height: 363px;
    `,button:(0,u.css)`
      flex: none;
      width: fit-content;
      margin-top: -6px;
    `},collapsableSection:(0,u.css)`
    width: fit-content;
  `,editorsWrapper:(0,u.css)`
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    gap: ${t.spacing(1)};
  `}),Pn=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n];if(!r)return e.createElement(b.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,se.G)(n,Object.keys(t.template_files));return e.createElement(Pe,{alertManagerSourceName:a,config:t,existing:{name:s,content:J(r)}})};function o(t,n,a,r={}){return{propertyName:t,label:n,description:a,element:"input",inputType:"",required:!1,secure:!1,placeholder:"",validationRule:"",showWhen:{field:"",is:""},dependsOn:"",...r}}const Nn=o("basic_auth","Basic auth","Sets the `Authorization` header with the configured username and password. Password and password_file are mutually exclusive.",{element:"subform",subformOptions:[o("username","Username",""),o("password","Password",""),o("password_file","Password file","")]}),Ze=o("tls_config","TLS config","Configures the TLS settings.",{element:"subform",subformOptions:[o("ca_file","CA file","CA certificate to validate the server certificate with."),o("cert_file","Cert file","Certificate for client cert authentication to the server."),o("key_file","Key file","Key file for client cert authentication to the server."),o("server_name","Server name","ServerName extension to indicate the name of the server."),o("insecure_skip_verify","Skip verify","Disable validation of the server certificate.",{element:"checkbox"})]}),X=o("http_config","HTTP Config","Note that `basic_auth`, `bearer_token` and `bearer_token_file` options are mutually exclusive.",{element:"subform",subformOptions:[o("bearer_token","Bearer token","Sets the `Authorization` header with the configured bearer token."),o("bearer_token_file","Bearer token file","Sets the `Authorization` header with the bearer token read from the configured file."),o("proxy_url","Proxy URL","Optional proxy URL."),Nn,Ze]}),Xe=[{name:"Email",description:"Send notification over SMTP",type:"email",info:"",heading:"Email settings",options:[o("to","To",'The email address to send notifications to. You can enter multiple addresses using a "," separator',{required:!0}),o("from","From","The sender address."),o("smarthost","SMTP host","The SMTP host through which emails are sent."),o("hello","Hello","The hostname to identify to the SMTP server."),o("auth_username","Username","SMTP authentication information"),o("auth_password","Password","SMTP authentication information"),o("auth_secret","Secret","SMTP authentication information"),o("auth_identity","Identity","SMTP authentication information"),o("require_tls","Require TLS","The SMTP TLS requirement",{element:"checkbox"}),o("html","Email HTML body","The HTML body of the email notification.",{placeholder:'{{ template "email.default.html" . }}',element:"textarea"}),o("text","Email text body","The text body of the email notification.",{element:"textarea"}),o("headers","Headers","Further headers email header key/value pairs. Overrides any headers previously set by the notification implementation.",{element:"key_value_map"}),Ze]},{name:"PagerDuty",description:"Send notifications to PagerDuty",type:"pagerduty",info:"",heading:"PagerDuty settings",options:[o("routing_key","Routing key","The PagerDuty integration key (when using PagerDuty integration type `Events API v2`)"),o("service_key","Service key","The PagerDuty integration key (when using PagerDuty integration type `Prometheus`)."),o("url","URL","The URL to send API requests to"),o("client","Client","The client identification of the Alertmanager.",{placeholder:'{{ template "pagerduty.default.client" . }}'}),o("client_url","Client URL","A backlink to the sender of the notification.",{placeholder:'{{ template "pagerduty.default.clientURL" . }}'}),o("description","Description","A description of the incident.",{placeholder:'{{ template "pagerduty.default.description" .}}'}),o("severity","Severity","Severity of the incident.",{placeholder:"error"}),o("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),o("images","Images","Images to attach to the incident.",{element:"subform_array",subformOptions:[o("href","URL","",{required:!0}),o("source","Source","",{required:!0}),o("alt","Alt","",{required:!0})]}),o("links","Links","Links to attach to the incident.",{element:"subform_array",subformOptions:[o("href","URL","",{required:!0}),o("text","Text","",{required:!0})]}),X]},{name:"Pushover",description:"Send notifications to Pushover",type:"pushover",info:"",heading:"Pushover settings",options:[o("user_key","User key","The recipient user\u2019s user key.",{required:!0}),o("token","Token","Your registered application\u2019s API token, see https://pushover.net/app",{required:!0}),o("title","Title","Notification title.",{placeholder:'{{ template "pushover.default.title" . }}'}),o("message","Message","Notification message.",{placeholder:'{{ template "pushover.default.message" . }}'}),o("url","URL","A supplementary URL shown alongside the message.",{placeholder:'{{ template "pushover.default.url" . }}'}),o("priority","Priority","Priority, see https://pushover.net/api#priority",{placeholder:'{{ if eq .Status "firing" }}2{{ else }}0{{ end }}'}),o("retry","Retry","How often the Pushover servers will send the same notification to the user. Must be at least 30 seconds.",{placeholder:"1m"}),o("expire","Expire","How long your notification will continue to be retried for, unless the user acknowledges the notification.",{placeholder:"1h"}),X]},{name:"Slack",description:"Send notifications to Slack",type:"slack",info:"",heading:"Slack settings",options:[o("api_url","Webhook URL","The Slack webhook URL."),o("channel","Channel","The #channel or @user to send notifications to.",{required:!0}),o("icon_emoji","Emoji icon",""),o("icon_url","Icon URL",""),o("link_names","Names link","",{element:"checkbox"}),o("username","Username","",{placeholder:'{{ template "slack.default.username" . }}'}),o("callback_id","Callback ID","",{placeholder:'{{ template "slack.default.callbackid" . }}'}),o("color","Color","",{placeholder:'{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}'}),o("fallback","Fallback","",{placeholder:'{{ template "slack.default.fallback" . }}'}),o("footer","Footer","",{placeholder:'{{ template "slack.default.footer" . }}'}),o("mrkdwn_in","Mrkdwn fields","An array of field names that should be formatted by mrkdwn syntax.",{element:"string_array"}),o("pretext","Pre-text","",{placeholder:'{{ template "slack.default.pretext" . }}'}),o("short_fields","Short fields","",{element:"checkbox"}),o("text","Message body","",{element:"textarea",placeholder:'{{ template "slack.default.text" . }}'}),o("title","Title","",{placeholder:'{{ template "slack.default.title" . }}'}),o("title_link","Title link","",{placeholder:'{{ template "slack.default.titlelink" . }}'}),o("image_url","Image URL",""),o("thumb_url","Thumbnail URL",""),o("actions","Actions","",{element:"subform_array",subformOptions:[o("text","Text","",{required:!0}),o("type","Type","",{required:!0}),o("url","URL","Either url or name and value are mandatory."),o("name","Name",""),o("value","Value",""),o("confirm","Confirm","",{element:"subform",subformOptions:[o("text","Text","",{required:!0}),o("dismiss_text","Dismiss text",""),o("ok_text","OK text",""),o("title","Title","")]}),o("style","Style","")]}),o("fields","Fields","",{element:"subform_array",subformOptions:[o("title","Title","",{required:!0}),o("value","Value","",{required:!0}),o("short","Short","",{element:"checkbox"})]}),X]},{name:"OpsGenie",description:"Send notifications to OpsGenie",type:"opsgenie",info:"",heading:"OpsGenie settings",options:[o("api_key","API key","The API key to use when talking to the OpsGenie API."),o("api_url","API URL","The host to send OpsGenie API requests to."),o("message","Message","Alert text limited to 130 characters."),o("description","Description","A description of the incident.",{placeholder:'{{ template "opsgenie.default.description" . }}'}),o("source","Source","A backlink to the sender of the notification.",{placeholder:'{{ template "opsgenie.default.source" . }}'}),o("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),o("tags","Tags","Comma separated list of tags attached to the notifications."),o("note","Note","Additional alert note."),o("priority","Priority","Priority level of alert. Possible values are P1, P2, P3, P4, and P5."),o("responders","Responders","List of responders responsible for notifications.",{element:"subform_array",subformOptions:[o("type","Type",'"team", "user", "escalation" or schedule".',{required:!0}),o("id","ID","Exactly one of these fields should be defined."),o("name","Name","Exactly one of these fields should be defined."),o("username","Username","Exactly one of these fields should be defined.")]}),X]},{name:"VictorOps",description:"Send notifications to VictorOps",type:"victorops",info:"",heading:"VictorOps settings",options:[o("api_key","API key","The API key to use when talking to the VictorOps API."),o("api_url","API URL","The VictorOps API URL."),o("routing_key","Routing key","A key used to map the alert to a team.",{required:!0}),o("message_type","Message type","Describes the behavior of the alert (CRITICAL, WARNING, INFO)."),o("entity_display_name","Entity display name","Contains summary of the alerted problem.",{placeholder:'{{ template "victorops.default.entity_display_name" . }}'}),o("state_message","State message","Contains long explanation of the alerted problem.",{placeholder:'{{ template "victorops.default.state_message" . }}'}),o("monitoring_tool","Monitoring tool","The monitoring tool the state message is from.",{placeholder:'{{ template "victorops.default.monitoring_tool" . }}'}),X]},{name:"Webhook",description:"Send notifications to a webhook",type:"webhook",info:"",heading:"Webhook settings",options:[o("url","URL","The endpoint to send HTTP POST requests to.",{required:!0}),o("max_alerts","Max alerts","The maximum number of alerts to include in a single webhook message. Alerts above this threshold are truncated. When leaving this at its default value of 0, all alerts are included.",{placeholder:"0",validationRule:"(^\\d+$|^$)"}),X]},{name:"Discord",description:"Sends notifications to Discord",type:"discord",info:"",heading:"Discord settings",options:[o("title","Title","Templated title of the message",{placeholder:'{{ template "discord.default.title" . }}'}),o("message","Message Content","Mention a group using @ or a user using <@ID> when notifying in a channel",{placeholder:'{{ template "discord.default.message" . }}'}),o("webhook_url","Webhook URL","",{placeholder:"Discord webhook URL",required:!0}),X]},{name:"Cisco Webex Teams",description:"Sends notifications to Cisco Webex Teams",type:"webex",info:"",heading:"Cisco Webex Teams settings",options:[o("api_url","API URL","The Webex Teams API URL",{placeholder:"https://webexapis.com/v1/messages"}),o("room_id","Room ID","ID of the Webex Teams room where to send the messages",{required:!0}),o("message","Message","Message template",{placeholder:'{{ template "webex.default.message" .}}'}),{...X,required:!0}]},{name:"Telegram",description:"Sends notifications to Telegram",type:"telegram",info:"",heading:"Telegram settings",options:[o("api_url","API URL","The Telegram API URL",{placeholder:"https://api.telegram.org"}),o("bot_token","Bot token","Telegram bot token",{required:!0}),o("chat_id","Chat ID","ID of the chat where to send the messages",{required:!0,setValueAs:t=>typeof t=="string"?parseInt(t,10):0}),o("message","Message","Message template",{placeholder:'{{ template "webex.default.message" .}}'}),o("disable_notifications","Disable notifications","Disable telegram notifications",{element:"checkbox"}),o("parse_mode","Parse mode","Parse mode for telegram message",{element:"select",defaultValue:{label:"MarkdownV2",value:"MarkdownV2"},selectOptions:[{label:"MarkdownV2",value:"MarkdownV2"},{label:"Markdown",value:"Markdown"},{label:"HTML",value:"HTML"},{label:"plain text",value:""}]}),X]},{name:"Amazon SNS",description:"Sends notifications to Amazon SNS",type:"sns",info:"",heading:"Amazon SNS settings",options:[o("api_url","API URL","The Amazon SNS API URL"),o("sigv4","SigV4 authentication","Configures AWS's Signature Verification 4 signing process to sign requests",{element:"subform",subformOptions:[o("region","Region","The AWS region. If blank, the region from the default credentials chain is used"),o("access_key","Access key",'The AWS API access_key. If blank the environment variable "AWS_ACCESS_KEY_ID" is used'),o("secret_key","Secret key",'The AWS API secret_key. If blank the environment variable "AWS_ACCESS_SECRET_ID" is used'),o("profile","Profile","Named AWS profile used to authenticate"),o("role_arn","Rule ARN","AWS Role ARN, an alternative to using AWS API keys")]}),o("topic_arn","SNS topic ARN","If you don't specify this value, you must specify a value for the phone_number or target_arn. If you are using a FIFO SNS topic you should set a message group interval longer than 5 minutes to prevent messages with the same group key being deduplicated by the SNS default deduplication window"),o("phone_number","Phone number","Phone number if message is delivered via SMS in E.164 format. If you don't specify this value, you must specify a value for the topic_arn or target_arn"),o("target_arn","Target ARN","The  mobile platform endpoint ARN if message is delivered via mobile notifications. If you don't specify this value, you must specify a value for the topic_arn or phone_number"),o("subject","Subject","Subject line when the message is delivered to email endpoints",{placeholder:'{{ template "sns.default.subject" .}}'}),o("message","Message","The message content of the SNS notification",{placeholder:'{{ template "sns.default.message" .}}'}),o("attributes","Attributes","SNS message attributes",{element:"key_value_map"}),X]},{name:"WeChat",description:"Sends notifications to WeChat",type:"wechat",info:"",heading:"WeChat settings",options:[o("api_url","API URL","The WeChat API URL"),o("api_secret","API Secret","The API key to use when talking to the WeChat API"),o("corp_id","Corp ID","The corp id for authentication"),o("message","Message","API request data as defined by the WeChat API",{placeholder:'{{ template "wechat.default.message" . }}'}),o("message_type","Message type","Type of the message type",{element:"select",defaultValue:{label:"Text",value:"text"},selectOptions:[{label:"Text",value:"text"},{label:"Markdown",value:"markdown"}]}),o("agent_id","Agent ID","",{placeholder:'{{ template "wechat.default.agent_id" . }}'}),o("to_user","to user","",{placeholder:'{{ template "wechat.default.to_user" . }}'}),o("to_party","to party","",{placeholder:'{{ template "wechat.default.to_party" . }}'}),o("to_tag","to tag","",{placeholder:'{{ template "wechat.default.to_tag" . }}'})]}],In=[o("smtp_from","SMTP from","The default SMTP From header field."),o("smtp_smarthost","SMTP smarthost","The default SMTP smarthost used for sending emails, including port number. Port number usually is 25, or 587 for SMTP over TLS (sometimes referred to as STARTTLS). Example: smtp.example.org:587"),o("smtp_hello","SMTP hello","The default hostname to identify to the SMTP server.",{placeholder:"localhost"}),o("smtp_auth_username","SMTP auth username","SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server."),o("smtp_auth_password","SMTP auth password","SMTP Auth using LOGIN and PLAIN."),o("smtp_auth_identity","SMTP auth identity","SMTP Auth using PLAIN."),o("smtp_auth_secret","SMTP auth secret","SMTP Auth using CRAM-MD5."),o("smtp_require_tls","SMTP require TLS","The default SMTP TLS requirement. Note that Go does not support unencrypted connections to remote SMTP endpoints.",{element:"checkbox"}),o("slack_api_url","Slack API URL",""),o("victorops_api_key","VictorOps API key",""),o("victorops_api_url","VictorOps API URL","",{placeholder:"https://alert.victorops.com/integrations/generic/20131114/alert/"}),o("pagerduty_url","PagerDuty URL","https://events.pagerduty.com/v2/enqueue"),o("opsgenie_api_key","OpsGenie API key",""),o("opsgenie_api_url","OpsGenie API URL","",{placeholder:"https://api.opsgenie.com/"}),o("wechat_api_url","WeChat API URL","",{placeholder:"https://qyapi.weixin.qq.com/cgi-bin/"}),o("wechat_api_secret","WeChat API secret",""),o("wechat_api_corp_id","WeChat API corp id",""),o("webex_api_url","Cisco Webex Teams API URL",""),o("telegram_api_url","The Telegram API URL",""),X,o("resolve_timeout","Resolve timeout","ResolveTimeout is the default value used by alertmanager if the alert does not include EndsAt, after this time passes it can declare the alert as resolved if it has not been updated. This has no impact on alerts from Prometheus, as they always include EndsAt.",{placeholder:"5m"})];function On(t,n){const a={};let r=1;return[{name:t.name,items:t.grafana_managed_receiver_configs?.map(i=>{const l=String(r++);a[l]=i;const d=n.find(({type:g})=>g===i.type);return kn(l,i,d)})??[]},a]}function Ln(t,n){const a={};let r=1;const s=Object.entries(t).filter(([l])=>l.endsWith("_configs")&&l!=="grafana_managed_receiver_configs").map(([l,d])=>[l.replace("_configs",""),d]).map(([l,d])=>d.map(g=>{const m=String(r++);if(a[m]={type:l,config:g},!n.find(f=>f.type===l))throw new Error(`unknown cloud notifier: ${l}`);return Mn(m,l,g)})).flat();return[{name:t.name,items:s},a]}function Dn(t,n,a){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(r=>{const s=n[r.__id];return tt(r,a,t.name,s)})}}function $n(t,n){const a={name:t.name};return t.items.forEach(({__id:r,type:s,settings:i,sendResolved:l})=>{const d=ye({...i,send_resolved:l??n.sendResolved}),g=`${s}_configs`;a[g]?a[g].push(d):a[g]=[d]}),a}function qe(t,n,a){const r=t.alertmanager_config.receivers??[];if(n.name!==a&&r.find(({name:i})=>i===n.name))throw new Error(`Duplicate receiver name ${n.name}`);if(a&&!r.find(({name:i})=>i===a))throw new Error(`Expected receiver ${a} to exist, but did not find it in the config`);const s={...t,alertmanager_config:{...t.alertmanager_config,receivers:a?r.map(i=>i.name===a?n:i):[...r,n]}};return s.alertmanager_config.route&&a&&n.name!==a&&(s.alertmanager_config.route=et(s.alertmanager_config.route,a,n.name)),s}function et(t,n,a){const r={...t};return r.receiver===n&&(r.receiver=a),r.routes&&(r.routes=r.routes.map(s=>et(s,n,a))),r}function Mn(t,n,a){return{__id:t,type:n,settings:{...a},secureFields:{},secureSettings:{},sendResolved:a.send_resolved}}function kn(t,n,a){const r={__id:t,type:n.type,provenance:n.provenance,secureSettings:{},settings:{...n.settings},secureFields:{...n.secureFields},disableResolveMessage:n.disableResolveMessage};return a?.options.forEach(s=>{s.secure&&r.settings[s.propertyName]&&(delete r.settings[s.propertyName],r.secureFields[s.propertyName]=!0)}),r}function tt(t,n,a,r){const s={settings:ye({...r&&r.type===t.type?r.settings??{}:{},...t.settings??{}}),secureSettings:Wn(t.secureSettings,r?.secureFields),type:t.type,name:a,disableResolveMessage:t.disableResolveMessage??r?.disableResolveMessage??n.disableResolveMessage};return r&&(s.uid=r.uid),s}const nt=t=>(0,W.isNil)(t)||t==="";function ye(t){return(0,W.isArray)(t)?t.forEach(ye):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,a])=>{nt(a)?delete t[n]:ye(a)}),t}function Wn(t={},n={}){return(0,W.omitBy)(t,(a,r)=>nt(a)&&!(r in n))}var Ie=c(83967);const Fn=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,z.Gc)();return e.createElement("div",{className:n},e.createElement(le.g,{disabled:a},e.createElement(Ie.X,{...r(`${t}sendResolved`),label:"Send resolved",disabled:a,description:"Whether or not to notify about resolved alerts."})))};var Vn=c(73807);const Un=[];function at(t){const{name:n,formAPI:a,defaults:r,softDelete:s}=t,{watch:i,getValues:l,reset:d,setValue:g}=a,m=i(n)??r??Un,p=(0,e.useCallback)(f=>{const h=JSON.parse(JSON.stringify(l())),y=f(m??[]);d((0,W.set)(h,n,y))},[l,n,d,m]);return{fields:m,append:(0,e.useCallback)(f=>p(h=>[...h,f]),[p]),remove:(0,e.useCallback)(f=>{s?g(`${n}.${f}.__deleted`,!0):p(h=>{const y=h.slice();return y.splice(f,1),y})},[p,n,g,s])}}var be=c(16310),rt=c(28580),Gn=c(60105),Y=c(18686);const Bn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,V.wW)(zn),[s,i]=(0,e.useState)(st(t));(0,e.useEffect)(()=>i(st(t)),[t]);const l=m=>{n(Kn(m))},d=m=>{const p=s.slice(),f=p.splice(m,1)[0];i(p),f[0]&&l(p)},g=(m,p)=>{const f=s[p],h=s.map((y,A)=>A===p?m:y);i(h),(m[0]||f[0])&&l(h)};return e.createElement("div",null,!!s.length&&e.createElement("table",{className:r.table},e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Value"),!a&&e.createElement("th",null))),e.createElement("tbody",null,s.map(([m,p],f)=>e.createElement("tr",{key:f},e.createElement("td",null,e.createElement(me.I,{readOnly:a,value:m,onChange:h=>g([h.currentTarget.value,p],f)})),e.createElement("td",null,e.createElement(me.I,{readOnly:a,value:p,onChange:h=>g([m,h.currentTarget.value],f)})),!a&&e.createElement("td",null,e.createElement(Y.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>d(f)})))))),!a&&e.createElement(x.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>i([...s,["",""]])},"Add"))},zn=t=>({addButton:(0,u.css)`
    margin-top: ${t.spacing(1)};
  `,table:(0,u.css)`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),Kn=t=>{const n={};for(const[a,r]of t)a&&(n[a]=r);return n},st=t=>Object.entries(t??{}),jn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,V.wW)(Hn),s=l=>{if(!t)return;const d=t.slice();d.splice(l,1),n(d)},i=(l,d)=>{t&&n(t.map((g,m)=>m===d?l:g))};return e.createElement("div",null,!!t?.length&&t.map((l,d)=>e.createElement("div",{key:d,className:r.row},e.createElement(me.I,{readOnly:a,value:l,onChange:g=>i(g.currentTarget.value,d)}),!a&&e.createElement(Y.A,{className:r.deleteIcon,icon:"trash-alt",tooltip:"delete",onClick:()=>s(d)}))),!a&&e.createElement(x.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},Hn=t=>({row:(0,u.css)`
    display: flex;
    flex-direction: row;
    margin-bottom: ${t.spacing(1)};
    align-items: center;
  `,deleteIcon:(0,u.css)`
    margin-left: ${t.spacing(1)};
  `,addButton:(0,u.css)`
    margin-top: ${t.spacing(1)};
  `});var ot=c(10759);const Oe=({label:t,description:n,children:a,className:r,size:s="xl"})=>{const i=(0,V.wW)(Jn),[l,d]=(0,e.useState)(!0),g=()=>d(!l);return e.createElement("div",{className:(0,u.cx)(i.wrapper,r)},e.createElement(ot.U,{className:i.toggle,size:s,onToggle:g,isCollapsed:l,text:t}),n&&e.createElement("p",{className:i.description},n),e.createElement("div",{className:l?i.hidden:i.content},a))},Jn=t=>({wrapper:(0,u.css)`
    margin-top: ${t.spacing(1)};
    padding-bottom: ${t.spacing(1)};
  `,toggle:(0,u.css)`
    margin: ${t.spacing(1,0)};
    padding: 0;
  `,hidden:(0,u.css)`
    display: none;
  `,description:(0,u.css)`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,content:(0,u.css)`
    padding-left: ${t.spacing(3)};
  `}),lt=t=>({collapsibleSection:(0,u.css)`
    margin: 0;
    padding: 0;
  `,wrapper:(0,u.css)`
    margin: ${t.spacing(2,0)};
    padding: ${t.spacing(1)};
    border: solid 1px ${t.colors.border.medium};
    border-radius: ${t.shape.borderRadius(1)};
    position: relative;
  `,description:(0,u.css)`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,deleteIcon:(0,u.css)`
    position: absolute;
    right: ${t.spacing(1)};
    top: ${t.spacing(1)};
  `,addButton:(0,u.css)`
    margin-top: ${t.spacing(1)};
  `}),Qn=({option:t,pathPrefix:n,errors:a,defaultValues:r,readOnly:s=!1})=>{const i=(0,V.wW)(lt),l=`${n}${t.propertyName}`,d=(0,z.Gc)(),{fields:g,append:m,remove:p}=at({name:l,formAPI:d,defaults:r});return e.createElement("div",{className:i.wrapper},e.createElement(Oe,{className:i.collapsibleSection,label:`${t.label} (${g.length})`,description:t.description},(g??r??[]).map((f,h)=>e.createElement("div",{key:h,className:i.wrapper},!s&&e.createElement(Y.A,{"data-testid":`${l}.${h}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>p(h),className:i.deleteIcon}),t.subformOptions?.map(y=>e.createElement(Ae,{readOnly:s,defaultValue:f?.[y.propertyName],key:y.propertyName,option:y,pathPrefix:`${l}.${h}.`,error:a?.[h]?.[y.propertyName]})))),!s&&e.createElement(x.zx,{"data-testid":`${l}.add-button`,className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>m({__id:String(Math.random())})},"Add")))},_n=({option:t,pathPrefix:n,errors:a,defaultValue:r,readOnly:s=!1})=>{const i=(0,V.wW)(lt),l=`${n}${t.propertyName}`,{watch:d}=(0,z.Gc)(),g=d(l),m=g===void 0?r:g,[p,f]=(0,e.useState)(!!m);return e.createElement("div",{className:i.wrapper,"data-testid":`${l}.container`},e.createElement("h6",null,t.label),t.description&&e.createElement("p",{className:i.description},t.description),p&&e.createElement(e.Fragment,null,!s&&e.createElement(Y.A,{"data-testid":`${l}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>f(!1),className:i.deleteIcon}),(t.subformOptions??[]).map(h=>e.createElement(Ae,{readOnly:s,defaultValue:r?.[h.propertyName],key:h.propertyName,option:h,pathPrefix:`${l}.`,error:a?.[h.propertyName]}))),!p&&!s&&e.createElement(x.zx,{className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>f(!0),"data-testid":`${l}.add-button`},"Add"))},Ae=({option:t,invalid:n,pathPrefix:a,pathSuffix:r="",error:s,defaultValue:i,readOnly:l=!1})=>{const d=`${a}${r}`;return t.element==="subform"?e.createElement(_n,{readOnly:l,defaultValue:i,option:t,errors:s,pathPrefix:d}):t.element==="subform_array"?e.createElement(Qn,{readOnly:l,defaultValues:i,option:t,pathPrefix:d,errors:s}):e.createElement(le.g,{label:t.element!=="checkbox"?t.label:void 0,description:t.description||void 0,invalid:!!s,error:s?.message},e.createElement(Yn,{id:`${d}${t.propertyName}`,defaultValue:i,option:t,invalid:n,pathPrefix:d,readOnly:l,pathIndex:a}))},Yn=({option:t,invalid:n,id:a,pathPrefix:r="",pathIndex:s="",readOnly:i=!1})=>{const{control:l,register:d,unregister:g,getValues:m}=(0,z.Gc)(),p=`${r}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{g(p,{keepValue:!1})},[g,p]),t.element){case"checkbox":return e.createElement(Ie.X,{id:a,readOnly:i,disabled:i,className:Zn.checkbox,...d(p),label:t.label,description:t.description});case"input":return e.createElement(me.I,{id:a,readOnly:i||qn(t,m,s),invalid:n,type:t.inputType,...d(p,{required:Xn(t,m,s),validate:f=>t.validationRule!==""?it(f,t.validationRule):!0,setValueAs:t.setValueAs}),placeholder:t.placeholder});case"select":return e.createElement(be.g,{render:({field:{onChange:f,ref:h,...y}})=>e.createElement(rt.Ph,{disabled:i,...y,defaultValue:t.defaultValue,options:t.selectOptions??void 0,invalid:n,onChange:A=>f(A.value)}),control:l,name:p});case"textarea":return e.createElement(Gn.K,{id:a,readOnly:i,invalid:n,placeholder:t.placeholder,...d(p,{required:t.required?"Required":!1,validate:f=>t.validationRule!==""?it(f,t.validationRule):!0})});case"string_array":return e.createElement(be.g,{render:({field:{value:f,onChange:h}})=>e.createElement(jn,{readOnly:i,value:f,onChange:h}),control:l,name:p});case"key_value_map":return e.createElement(be.g,{render:({field:{value:f,onChange:h}})=>e.createElement(Bn,{readOnly:i,value:f,onChange:h}),control:l,name:p});default:return console.error("Element not supported",t.element),null}},Zn={checkbox:(0,u.css)`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},it=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",Xn=(t,n,a)=>t.dependsOn?(0,W.isEmpty)(n(`${a}secureFields`))?!n(`${a}secureSettings.${t.dependsOn}`)&&t.required?"Required":!1:!n(`${a}secureFields.${t.dependsOn}`)&&t.required?"Required":!1:t.required?"Required":!1,qn=(t,n,a)=>t.dependsOn?(0,W.isEmpty)(n(`${a}secureFields`))?n(`${a}secureSettings.${t.dependsOn}`):n(`${a}secureFields.${t.dependsOn}`):!1;function ct({defaultValues:t,selectedChannelOptions:n,onResetSecureField:a,secureFields:r,errors:s,pathPrefix:i="",readOnly:l=!1}){const{watch:d}=(0,z.Gc)(),g=d();return e.createElement(e.Fragment,null,n.map((m,p)=>{const f=`${m.label}-${p}`,h=i.split("."),y=h.length>=2?g.items[Number(h[1])].settings[m.showWhen.field]:void 0;if(m.showWhen.field&&y!==m.showWhen.is)return null;if(r&&r[m.propertyName])return e.createElement(le.g,{key:f,label:m.label,description:m.description||void 0},e.createElement(me.I,{readOnly:!0,value:"Configured",suffix:l?null:e.createElement(x.zx,{onClick:()=>a(m.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const A=(m.secure?s?.secureSettings:s?.settings)?.[m.propertyName],R=t?.settings?.[m.propertyName];return e.createElement(Ae,{defaultValue:R,readOnly:l,key:f,error:A,pathPrefix:i,pathSuffix:m.secure?"secureSettings.":"settings.",option:m})}))}function ea({defaultValues:t,pathPrefix:n,onDuplicate:a,onDelete:r,onTest:s,notifiers:i,errors:l,secureFields:d,commonSettingsComponent:g,isEditable:m=!0,isTestable:p}){const f=(0,V.wW)(ta),h=L=>`${n}${L}`,{control:y,watch:A,register:R,trigger:I,formState:E,setValue:P}=(0,z.Gc)(),H=A(h("type"))??t.type,{loading:$}=(0,C._)(L=>L.testReceivers);(0,e.useEffect)(()=>{R(`${n}.__id`),R(`${n}.secureFields`)},[R,n]);const[K,Z]=(0,e.useState)(d??{}),ae=L=>{if(K[L]){const B={...d};delete B[L],Z(B),P(`${n}.secureFields`,B)}},de=(0,e.useMemo)(()=>i.map(({name:L,type:B})=>({label:L,value:B})).sort((L,B)=>L.label.localeCompare(B.label)),[i]),N=async()=>{await I(),Object.keys(E.errors).length===0&&s&&s()},T=i.find(({type:L})=>L===H),v=T?.options.filter(L=>L.required),O=T?.options.filter(L=>!L.required),Q=`contact-point-type-${n}`;return e.createElement("div",{className:f.wrapper,"data-testid":"item-container"},e.createElement("div",{className:f.topRow},e.createElement("div",null,e.createElement(le.g,{label:"Integration",htmlFor:Q,"data-testid":`${n}type`},e.createElement(be.g,{name:h("type"),defaultValue:t.type,render:({field:{ref:L,onChange:B,...re}})=>e.createElement(rt.Ph,{disabled:!m,inputId:Q,...re,width:37,options:de,onChange:$e=>B($e?.value)}),control:y,rules:{required:!0}}))),e.createElement("div",{className:f.buttons},p&&s&&e.createElement(x.zx,{disabled:$,size:"xs",variant:"secondary",type:"button",onClick:()=>N(),icon:$?"fa fa-spinner":"message"},"Test"),m&&e.createElement(e.Fragment,null,e.createElement(x.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"copy"},"Duplicate"),r&&e.createElement(x.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"trash-alt"},"Delete")))),T&&e.createElement("div",{className:f.innerContent},e.createElement(ct,{defaultValues:t,selectedChannelOptions:v?.length?v:O,secureFields:K,errors:l,onResetSecureField:ae,pathPrefix:n,readOnly:!m}),!!(v?.length&&O?.length)&&e.createElement(Oe,{label:`Optional ${T.name} settings`},T.info!==""&&e.createElement(b.b,{title:"",severity:"info"},T.info),e.createElement(ct,{defaultValues:t,selectedChannelOptions:O,secureFields:K,onResetSecureField:ae,errors:l,pathPrefix:n,readOnly:!m})),e.createElement(Oe,{label:"Notification settings"},e.createElement(g,{pathPrefix:n,readOnly:!m}))))}const ta=t=>({buttons:(0,u.css)`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,innerContent:(0,u.css)`
    max-width: 536px;
  `,wrapper:(0,u.css)`
    margin: ${t.spacing(2,0)};
    padding: ${t.spacing(1)};
    border: solid 1px ${t.colors.border.medium};
    border-radius: ${t.shape.borderRadius(1)};
    max-width: ${t.breakpoints.values.xl}${t.breakpoints.unit};
  `,topRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  `,channelSettingsHeader:(0,u.css)`
    margin-top: ${t.spacing(2)};
  `});function na({pathPrefix:t}){const{register:n}=(0,z.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function aa(t){if(t)return{...t,items:t.items.map(n=>({...n,settings:{...n.settings,http_config:n.settings?.http_config?ra(n.settings?.http_config):void 0}}))}}function ra(t){return sa(t)?t:{...(0,W.omit)(t,"authorization"),bearer_token:t.authorization?.credentials,bearer_token_file:t.authorization?.credentials_file}}function sa(t){return["bearer_token","bearer_token_file"].some(n=>n in t)}function dt({config:t,initialValues:n,defaultItem:a,notifiers:r,alertManagerSourceName:s,onSubmit:i,onTestChannel:l,takenReceiverNames:d,commonSettingsComponent:g,isEditable:m,isTestable:p}){const f=(0,Vn.iG)(),h=(0,V.wW)(oa),A=aa(n)??{name:"",items:[{...a,__id:String(Math.random())}]},R=(0,z.cI)({defaultValues:JSON.parse(JSON.stringify(A))});(0,Re.x)(v=>v.unifiedAlerting.saveAMConfig=xe.oq);const{loading:I}=(0,C._)(v=>v.saveAMConfig),{handleSubmit:E,register:P,formState:{errors:H},getValues:$}=R,{fields:K,append:Z,remove:ae}=at({name:"items",formAPI:R,softDelete:!0}),de=(0,e.useCallback)(v=>d.map(O=>O.trim().toLowerCase()).includes(v.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[d]),N=v=>{i({...v,items:v.items.filter(O=>!O.__deleted)})},T=()=>{f.error("There are errors in the form. Please correct them and try again!")};return e.createElement(z.RV,{...R},!t.alertmanager_config.route&&e.createElement(b.b,{severity:"warning",title:"Attention"},"Because there is no default policy configured yet, this contact point will automatically be set as default."),e.createElement("form",{onSubmit:E(N,T)},e.createElement("h4",{className:h.heading},m?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(le.g,{label:"Name",invalid:!!H.name,error:H.name&&H.name.message,required:!0},e.createElement(me.I,{readOnly:!m,id:"name",...P("name",{required:"Name is required",validate:{nameIsAvailable:de}}),width:39,placeholder:"Name"})),K.map((v,O)=>{const Q=`items.${O}.`;if(v.__deleted)return e.createElement(na,{key:v.__id,pathPrefix:Q});const L=n?.items.find(({__id:B})=>B===v.__id);return e.createElement(ea,{defaultValues:v,key:v.__id,onDuplicate:()=>{const B=$().items[O];Z({...B,__id:String(Math.random())})},onTest:l?()=>{const B=$().items[O];l(B)}:void 0,onDelete:()=>ae(O),pathPrefix:Q,notifiers:r,secureFields:L?.secureFields,errors:H?.items?.[O],commonSettingsComponent:g,isEditable:m,isTestable:p})}),e.createElement(e.Fragment,null,m&&e.createElement(x.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>Z({...a,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:h.buttons},m&&e.createElement(e.Fragment,null,I&&e.createElement(x.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!I&&e.createElement(x.zx,{type:"submit"},"Save contact point")),e.createElement(x.Qj,{disabled:I,variant:"secondary","data-testid":"cancel-button",href:(0,_.eQ)("alerting/notifications",s)},"Cancel")))))}const oa=t=>({heading:(0,u.css)`
    margin: ${t.spacing(4,0)};
  `,buttons:(0,u.css)`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),mt=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),ut=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,S.useDispatch)(),s=(0,D.RY)(n),[i]=(0,e.useMemo)(()=>t?Ln(t,Xe):[void 0,{}],[t]),l=m=>{const p=$n(m,mt);r((0,j.mM)({newConfig:qe(a,p,t?.name),oldConfig:a,alertManagerSourceName:n,successMessage:t?"Contact point updated.":"Contact point created.",redirectPath:"/alerting/notifications"}))},d=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:m})=>m).filter(m=>m!==t?.name)??[],[a,t]),g=!(0,D.RY)(n);return e.createElement(e.Fragment,null,!s&&e.createElement(b.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(dt,{isEditable:g,isTestable:g,config:a,onSubmit:l,initialValues:i,notifiers:Xe,alertManagerSourceName:n,defaultItem:mt,takenReceiverNames:d,commonSettingsComponent:Fn}))},la=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,z.Gc)();return e.createElement("div",{className:n},e.createElement(le.g,null,e.createElement(Ie.X,{...r(`${t}disableResolveMessage`),label:"Disable resolved message",description:"Disable the resolve message [OK] that is sent when alerting state returns to false",disabled:a})))};var ia=c(79978),ca=c(33555),pt=(t=>(t.predefined="Predefined",t.custom="Custom",t))(pt||{});const da=Object.values(pt).map(t=>({label:t,value:t})),ma={annotations:[...ca.eY],labels:[{key:"",value:""}]},ua=({isOpen:t,onDismiss:n,onTest:a})=>{const[r,s]=(0,e.useState)("Predefined"),i=(0,V.wW)(pa),l=(0,z.cI)({defaultValues:ma,mode:"onBlur"}),d=g=>{if(r==="Custom"){const m={annotations:g.annotations.filter(({key:p,value:f})=>!!p&&!!f).reduce((p,{key:f,value:h})=>({...p,[f]:h}),{}),labels:g.labels.filter(({key:p,value:f})=>!!p&&!!f).reduce((p,{key:f,value:h})=>({...p,[f]:h}),{})};a(m)}else a()};return e.createElement(ie.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:i.section},e.createElement(ia._,null,"Notification message"),e.createElement(ze.S,{options:da,value:r,onChange:g=>s(g)})),e.createElement(z.RV,{...l},e.createElement("form",{onSubmit:l.handleSubmit(d)},r==="Predefined"&&e.createElement("div",{className:i.section},"You will send a test notification that uses a predefined alert. If you have defined a custom template or message, for better results switch to ",e.createElement("strong",null,"custom")," notification message, from above."),r==="Custom"&&e.createElement(e.Fragment,null,e.createElement("div",{className:i.section},"You will send a test notification that uses the annotations defined below. This is a good option if you use custom templates and messages."),e.createElement("div",{className:i.section},e.createElement(Ke.Z,null)),e.createElement("div",{className:i.section},e.createElement(je.Z,null))),e.createElement(ie.u.ButtonRow,null,e.createElement(x.zx,{type:"submit"},"Send test notification")))))},pa=t=>({flexRow:(0,u.css)`
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: ${t.spacing(1)};
  `,section:(0,u.css)`
    margin-bottom: ${t.spacing(2)};
  `}),Le=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),gt=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,C._)(E=>E.grafanaNotifiers),[s,i]=(0,e.useState)(),l=(0,S.useDispatch)();(0,e.useEffect)(()=>{r.result||r.loading||l((0,j.Vj)())},[r,l]);const[d,g]=(0,e.useMemo)(()=>!t||!r.result?[void 0,{}]:On(t,r.result),[t,r.result]),m=E=>{const P=Dn(E,g,Le);l((0,j.mM)({newConfig:qe(a,P,t?.name),oldConfig:a,alertManagerSourceName:D.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},p=E=>{i(E)},f=E=>{if(s){const P=g[s.__id],H=tt(s,Le,"test",P),$={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[H]}],alert:E};l((0,j.D8)($))}},h=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:E})=>E).filter(E=>E!==t?.name)??[],[a,t]),y=t?(t.grafana_managed_receiver_configs??[]).some(E=>!!E.provenance):!1,A=!(0,D.RY)(n),R=A&&!y,I=A||y;return r.result?e.createElement(e.Fragment,null,y&&e.createElement(ue.Xq,{resource:ue.Uv.ContactPoint}),e.createElement(dt,{isEditable:R,isTestable:I,config:a,onSubmit:m,initialValues:d,onTestChannel:p,notifiers:r.result,alertManagerSourceName:n,defaultItem:Le,takenReceiverNames:h,commonSettingsComponent:la}),e.createElement(ua,{onDismiss:()=>i(void 0),isOpen:!!s,onTest:E=>f(E)})):e.createElement(k.u,{text:"Loading notifiers..."})},ga=({config:t,receiverName:n,alertManagerSourceName:a})=>{const r=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return r?a===D.GC?e.createElement(gt,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(ut,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(b.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},fa=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n],s=t.template_file_provenances?.[n];return r?e.createElement(Pe,{alertManagerSourceName:a,config:t,existing:{name:n,content:r},provenance:s}):e.createElement(b.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var ft=c(64022);const ht={smtp_require_tls:!0},ha=({config:t,alertManagerSourceName:n})=>{const a=(0,S.useDispatch)();(0,Re.x)(p=>p.unifiedAlerting.saveAMConfig=xe.oq);const{loading:r,error:s}=(0,C._)(p=>p.saveAMConfig),i=(0,D.RY)(n),l=(0,z.cI)({defaultValues:JSON.parse(JSON.stringify({...ht,...t.alertmanager_config.global??{}}))}),{handleSubmit:d,formState:{errors:g}}=l,m=p=>{a((0,j.mM)({newConfig:{...t,alertmanager_config:{...t.alertmanager_config,global:ye(p)}},oldConfig:t,alertManagerSourceName:n,successMessage:"Global config updated.",redirectPath:(0,_.eQ)("/alerting/notifications",n)}))};return e.createElement(z.RV,{...l},e.createElement("form",{onSubmit:d(m)},s&&e.createElement(b.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),In.map(p=>e.createElement(Ae,{readOnly:i,defaultValue:ht[p.propertyName],key:p.propertyName,option:p,error:g[p.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(ft.Lh,null,!i&&e.createElement(e.Fragment,null,r&&e.createElement(x.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!r&&e.createElement(x.zx,{type:"submit"},"Save global config")),e.createElement(x.Qj,{disabled:r,fill:"outline",variant:"secondary",href:(0,_.eQ)("alerting/notifications",n)},"Cancel")))))},ya=({alertManagerSourceName:t,config:n})=>t===D.GC?e.createElement(gt,{alertManagerSourceName:t,config:n}):e.createElement(ut,{alertManagerSourceName:t,config:n}),va=({config:t,alertManagerSourceName:n})=>e.createElement(Pe,{config:t,alertManagerSourceName:n});var ne=c(89439),Ea=c(6772),ba=c.n(Ea),Aa=c(99633),Ca=c(60956),yt=c(3613),Ce=c(91368),pe=c(309),Sa=c(98164),vt=c(38338),Et=c(2082),Ta=c(76658);const Ra={pagerduty:"PagerDuty",pushover:"Pushover",slack:"Slack",opsgenie:"OpsGenie",webhook:"Webhook",victorops:"VictorOps",wechat:"WeChat",discord:"Discord",webex:"Cisco Webex Teams",sns:"Amazon SNS",telegram:"Telegram"};function xa(t,n){return t.grafana_managed_receiver_configs?Pa(t.grafana_managed_receiver_configs??[],n):wa(t)}function wa(t){return Object.entries(t).filter(([n])=>n!=="grafana_managed_receiver_configs"&&n.endsWith("_configs")).filter(([n,a])=>Array.isArray(a)&&!!a.length).reduce((n,[a,r])=>{const s=a.replace("_configs",""),i=Ra[s]??(0,W.capitalize)(s);return{...n,[i]:(n[i]??0)+(Array.isArray(r)?r.length:1)}},{})}function Pa(t,n){return t.map(a=>a.type).map(a=>n.find(r=>r.type===a)?.name??(0,W.capitalize)(a)).reduce((a,r)=>({...a,[r]:(a[r]??0)+1}),{})}var bt=c(59597),At=c(45986),Na=c(85014),Ia=c(89746),Oa=c(79655),La=c(80434);const Ct=({className:t,title:n,description:a,addButtonLabel:r,addButtonTo:s,children:i,showButton:l=!0,exportLink:d})=>{const g=(0,V.wW)(Da),m=!!d,p=e.createElement(Ia.v,null,d&&e.createElement(Oa.s,{url:d,label:"Export all",target:"_blank"}));return e.createElement(oe.K,{direction:"column",gap:2},e.createElement("div",{className:(0,u.cx)(g.heading,t)},e.createElement("div",null,e.createElement("h4",null,n),e.createElement("div",{className:g.description},a)),e.createElement(oe.K,{direction:"row",gap:.5},l&&e.createElement(Na.Link,{to:s},e.createElement(x.zx,{type:"button",icon:"plus"},r)),m&&e.createElement(La.L,{overlay:p},e.createElement(x.zx,{variant:"secondary"},"More",e.createElement(Ee.J,{name:"angle-down"}))))),i)},Da=t=>({heading:(0,u.css)`
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  `,description:(0,u.css)`
    color: ${t.colors.text.secondary};
  `});var De=c(62401);const $a={[De.W.OnCall]:"public/img/alerting/oncall_logo.svg",[De.W.Incident]:"",[De.W.MachineLearning]:""},Ma=({grafanaAppType:t})=>{const n=(0,V.wW)(ka);return e.createElement("div",{className:n.wrapper},e.createElement(ft.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:$a[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},ka=t=>({wrapper:(0,u.css)`
    text-align: left;
    height: 22px;
    display: inline-flex;
    padding: 1px 4px;
    border-radius: ${t.shape.borderRadius()};
    border: 1px solid rgba(245, 95, 62, 1);
    color: rgba(245, 95, 62, 1);
    font-weight: ${t.typography.fontWeightRegular};
  `});var Wa=c(74023);function Fa(t){if(!t.receivers)return{contactPoints:{}};if(!t.route)return{contactPoints:Object.fromEntries(t.receivers.map(l=>[l.name,{matchingRoutes:0}]))};const n=t.receivers?.map(l=>l.name)??[],a=St(t.route),r=(0,W.countBy)(a),s={},i={contactPoints:s};return n.forEach(l=>{s[l]={matchingRoutes:r[l]??0}}),i}function St(t){const n=t.routes?.flatMap(a=>St(a))??[];return t.receiver?[t.receiver,...n]:n}function Va({permissions:t,alertManagerName:n,receiverName:a,onClickDeleteReceiver:r}){return e.createElement(e.Fragment,null,e.createElement(ne.q,{actions:[t.update]},e.createElement(Y.A,{"aria-label":"Edit","data-testid":"edit",to:(0,_.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"Edit contact point",icon:"pen"})),e.createElement(ne.q,{actions:[t.delete]},e.createElement(Y.A,{onClick:()=>r(a),tooltip:"Delete contact point",icon:"trash-alt"})))}function Ua({permissions:t,alertManagerName:n,receiverName:a}){return e.createElement(ne.q,{actions:[t.update]},e.createElement(Y.A,{"data-testid":"view",to:(0,_.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function Ga({permissions:t,receiverName:n}){return e.createElement(ne.q,{actions:[t.provisioning.read],fallback:(0,pe.RN)()},e.createElement(Y.A,{"data-testid":"export",to:(0,bt.u)("/api/v1/provisioning/contact-points/export/",{download:"true",format:"yaml",decrypt:(0,pe.RN)().toString(),name:n}),tooltip:(0,pe.RN)()?"Export contact point":"Export redacted contact point",icon:"download-alt",target:"_blank"}))}function Tt({errorCount:t,errorDetail:n,showErrorCount:a,tooltip:r}){const s=a?`${t} ${ba()("error",t)}`:"Error",i=r??n??"Error";return e.createElement(ge.C,{color:"red",icon:"exclamation-circle",text:s,tooltip:i})}function Ba({errorsByNotifier:t,errorDetail:n,lastNotify:a}){const r=t>0,s=Se(a);return r?e.createElement(Tt,{errorCount:t,errorDetail:n,showErrorCount:!1}):s?e.createElement(e.Fragment,null,"No attempts"):e.createElement(ge.C,{color:"green",text:"OK"})}function za({errorsByReceiver:t,someWithNoAttempt:n}){return t>0?e.createElement(Tt,{errorCount:t,showErrorCount:!0,tooltip:"Expand the contact point to see error details."}):n?e.createElement(e.Fragment,null,"No attempts"):e.createElement(ge.C,{color:"green",text:"OK"})}const Ka=t=>{const n=(0,Sa.V)(t),a=n?.receivers??{},r=Object.keys(a).length>0;return{contactPointsState:n,errorStateAvailable:r}},Se=t=>t==="0001-01-01T00:00:00.000Z";function ja({lastNotifyDate:t}){return Se(t)?e.createElement(e.Fragment,null,"-"):e.createElement(oe.K,{alignItems:"center"},e.createElement("div",null,`${(0,Aa.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(Ee.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,Ca.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const Ha=["","0","0ms","0s","0m","0h","0d","0w","0y"],Ja=t=>Ha.includes(t);function Qa({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:r,lastNotify:s}})=>e.createElement(Ba,{errorsByNotifier:r?1:0,errorDetail:r??void 0,lastNotify:s}),size:.5},{id:"name",label:"Name",renderCell:({data:{type:r},id:s})=>e.createElement(e.Fragment,null,`${r}[${s}]`),size:1},{id:"lastNotify",label:"Last delivery attempt",renderCell:({data:{lastNotify:r}})=>e.createElement(ja,{lastNotifyDate:r}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:r,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,Se(r)&&Ja(s)?"-":s),size:1},{id:"sendResolved",label:"Send resolved",renderCell:({data:{sendResolved:r}})=>e.createElement(e.Fragment,null,String(!!r)),size:1}]}const a=Object.entries(t).flatMap(r=>r[1].map((s,i)=>({id:i,data:{type:r[0],lastError:s.lastNotifyAttemptError,lastNotify:s.lastNotifyAttempt,lastNotifyDuration:s.lastNotifyAttemptDuration,sendResolved:s.sendResolved}})));return e.createElement(At.t,{items:a,cols:n()})}const _a=({config:t,alertManagerName:n})=>{const a=(0,S.useDispatch)(),r=(0,D.RY)(n),s=(0,Et.Ko)(n),i=(0,C._)($=>$.grafanaNotifiers),l=Fa(t.alertmanager_config),{contactPointsState:d,errorStateAvailable:g}=Ka(n),[m,p]=(0,e.useState)(),[f,h]=(0,e.useState)(!1),A=n===D.GC&&Ce.contextSrv.hasAccess(s.provisioning.read,(0,pe.RN)()),R=$=>{(0,Ta.nv)($,t)?h(!0):p($)},I=()=>{m&&a((0,j.X4)(m,n)),p(void 0)},E=(0,Wa.HU)(t.alertmanager_config.receivers??[]),P=(0,e.useMemo)(()=>E?.map($=>({id:$.name,data:{name:$.name,types:Object.entries(xa($,i.result??[])).map(([K,Z])=>Z>1?`${K} (${Z})`:K),grafanaAppReceiverType:$.grafanaAppReceiverType,provisioned:$.grafana_managed_receiver_configs?.some(K=>K.provenance)}}))??[],[i.result,E]),H=Xa(n,g,d,l,R,s,r);return e.createElement(Ct,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!r&&Ce.contextSrv.hasPermission(s.create),addButtonLabel:"Add contact point",addButtonTo:(0,_.eQ)("/alerting/notifications/receivers/new",n),exportLink:A?(0,bt.u)("/api/v1/provisioning/contact-points/export",{download:"true",format:"yaml",decrypt:(0,pe.RN)().toString()}):void 0},e.createElement(At.t,{items:P,cols:H,isExpandable:g,renderExpandedContent:g?({data:{name:$}})=>e.createElement(Qa,{notifiersState:d?.receivers[$]?.notifiers??{}}):void 0}),!!f&&e.createElement(ie.u,{isOpen:!0,title:"Cannot delete contact point",onDismiss:()=>h(!1)},e.createElement("p",null,"Contact point cannot be deleted because it is used in more policies. Please update or delete these policies first."),e.createElement(ie.u.ButtonRow,null,e.createElement(x.zx,{variant:"secondary",onClick:()=>h(!1),fill:"outline"},"Close"))),!!m&&e.createElement(yt.s,{isOpen:!0,title:"Delete contact point",body:`Are you sure you want to delete contact point "${m}"?`,confirmText:"Yes, delete",onConfirm:I,onDismiss:()=>p(void 0)}))},Ya=(t,n)=>t?.receivers[n]?.errorCount??0,Za=(t,n)=>{const a=Object.values(t?.receivers[n]?.notifiers??{});return a.length===0?!1:a.flat().some(s=>Se(s.lastNotifyAttempt))};function Xa(t,n,a,r,s,i,l){const d=(0,V.wW)(vt.D),g=n||Object.values(r.contactPoints).some(h=>h.matchingRoutes===0),m=t===D.GC,p=[{id:"name",label:"Contact point name",renderCell:({data:{name:h,provisioned:y}})=>e.createElement(e.Fragment,null,e.createElement("div",null,h),y&&e.createElement(ue.C0,null)),size:3,className:d.nameCell},{id:"type",label:"Type",renderCell:({data:{types:h,grafanaAppReceiverType:y}})=>e.createElement(e.Fragment,null,y?e.createElement(Ma,{grafanaAppType:y}):h.join(", ")),size:2}],f={id:"health",label:"Health",renderCell:({data:{name:h}})=>r.contactPoints[h]?.matchingRoutes===0?e.createElement(qa,null):a&&Object.entries(a.receivers).length>0&&e.createElement(za,{errorsByReceiver:Ya(a,h),someWithNoAttempt:Za(a,h)}),size:"160px"};return[...p,...g?[f]:[],{id:"actions",label:"Actions",renderCell:({data:{provisioned:h,name:y}})=>e.createElement(ne.q,{actions:[i.update,i.delete,i.provisioning.read],fallback:(0,pe.RN)()},e.createElement("div",{className:d.actionsCell},!l&&!h&&e.createElement(Va,{permissions:i,alertManagerName:t,receiverName:y,onClickDeleteReceiver:s}),(l||h)&&e.createElement(Ua,{permissions:i,alertManagerName:t,receiverName:y}),m&&e.createElement(Ga,{permissions:i,alertManagerName:t,receiverName:y}))),size:"100px"}]}function qa(){return e.createElement(ge.C,{text:"Unused",color:"orange",icon:"exclamation-triangle",tooltip:"This contact point is not used in any notification policy and it will not receive any alerts"})}var er=c(1333);const tr=({config:t,alertManagerName:n})=>{const a=(0,S.useDispatch)(),[r,s]=(0,e.useState)({}),i=(0,V.wW)(vt.D),l=(0,Et.Ko)(n),d=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([h,y])=>({name:h,template:y,provenance:(t.template_file_provenances??{})[h]})),[t]),[g,m]=(0,e.useState)(),p=()=>{g&&a((0,j.S6)(g,n)),m(void 0)};return e.createElement(Ct,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,_.eQ)("/alerting/notifications/templates/new",n),showButton:Ce.contextSrv.hasPermission(l.create)},e.createElement("table",{className:i.table,"data-testid":"templates-table"},e.createElement("colgroup",null,e.createElement("col",{className:i.colExpand}),e.createElement("col",null),e.createElement("col",null)),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null),e.createElement("th",null,"Template"),e.createElement(ne.q,{actions:[l.update,l.delete]},e.createElement("th",null,"Actions")))),e.createElement("tbody",null,!d.length&&e.createElement("tr",{className:i.evenRow},e.createElement("td",{colSpan:3},"No templates defined.")),d.map(({name:f,template:h,provenance:y},A)=>{const R=!!r[f];return e.createElement(e.Fragment,{key:f},e.createElement("tr",{key:f,className:A%2===0?i.evenRow:void 0},e.createElement("td",null,e.createElement(ot.U,{isCollapsed:!r[f],onToggle:()=>s({...r,[f]:!R})})),e.createElement("td",null,f," ",y&&e.createElement(ue.C0,null)),e.createElement("td",{className:i.actionsCell},y&&e.createElement(Y.A,{to:(0,_.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!y&&e.createElement(ne.q,{actions:[l.update]},e.createElement(Y.A,{to:(0,_.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/edit`,n),tooltip:"edit template",icon:"pen"})),Ce.contextSrv.hasPermission(l.create)&&e.createElement(Y.A,{to:(0,_.eQ)(`/alerting/notifications/templates/${encodeURIComponent(f)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!y&&e.createElement(ne.q,{actions:[l.delete]},e.createElement(Y.A,{onClick:()=>m(f),tooltip:"delete template",icon:"trash-alt"})))),R&&e.createElement("tr",{className:A%2===0?i.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(er.C,{label:"Description",horizontal:!0},e.createElement(_e,{width:"auto",height:"auto",autoHeight:!0,value:h,showLineNumbers:!1,monacoOptions:{readOnly:!0,scrollBeyondLastLine:!1}})))))}))),!!g&&e.createElement(yt.s,{isOpen:!0,title:"Delete template",body:`Are you sure you want to delete template "${g}"?`,confirmText:"Yes, delete",onConfirm:p,onDismiss:()=>m(void 0)}))},nr=({config:t,alertManagerName:n})=>{const a=n!==D.GC,r=(0,D.RY)(n);return e.createElement(oe.K,{direction:"column",gap:4},e.createElement(_a,{config:t,alertManagerName:n}),!r&&e.createElement(tr,{config:t,alertManagerName:n}),a&&e.createElement(ne.q,{actions:[S.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(b.b,{severity:"info",title:"Global config for contact points"},e.createElement("p",null,"For each external Alertmanager you can define global settings, like server addresses, usernames and password, for all the supported contact points."),e.createElement(x.Qj,{href:(0,_.eQ)("alerting/notifications/global-config",n),variant:"secondary"},r?"View global config":"Edit global config"))))},ar=()=>{const{selectedAlertmanager:t}=(0,U.Z)(),n=(0,S.useDispatch)(),{currentData:a,isLoading:r,error:s}=(0,M.W)(t),i=(0,C._)(l=>l.grafanaNotifiers);return(0,e.useEffect)(()=>{t===D.GC&&!(i.result||i.loading||i.error)&&n((0,j.Vj)())},[t,n,i]),t?e.createElement(e.Fragment,null,s&&!r&&e.createElement(b.b,{severity:"error",title:"Error loading Alertmanager config"},s.message||"Unknown error."),e.createElement(te.u,{currentAlertmanager:t}),r&&!a&&e.createElement(k.u,{text:"loading configuration..."}),a&&!s&&e.createElement(w.rs,null,e.createElement(w.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(nr,{config:a,alertManagerName:t})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(va,{config:a,alertManagerSourceName:t})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:l})=>l?.params.name&&e.createElement(Pn,{alertManagerSourceName:t,config:a,templateName:decodeURIComponent(l?.params.name)})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:l})=>l?.params.name&&e.createElement(fa,{alertManagerSourceName:t,config:a,templateName:decodeURIComponent(l?.params.name)})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(ya,{config:a,alertManagerSourceName:t})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:l})=>l?.params.name&&e.createElement(ga,{alertManagerSourceName:t,config:a,receiverName:decodeURIComponent(l?.params.name)})),e.createElement(w.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(ha,{config:a,alertManagerSourceName:t})))):null}},74023:(q,F,c)=>{c.d(F,{Kt:()=>se,HU:()=>W});var e=c(78209),w=c(73289),b=c(16881);const k=b.C.injectEndpoints({endpoints:G=>({getOnCallIntegrations:G.query({queryFn:async()=>({data:await S()})})})});async function S(){try{return(await(0,e.n)((0,w.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(J=>J.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:M}=k;var C=c(76393),U=c(62401);const j=(G,J)=>J.includes(G),D=(G,J)=>{if(!G.grafana_managed_receiver_configs)return!1;const u=G.grafana_managed_receiver_configs.length===1,ee=j(G.grafana_managed_receiver_configs[0]?.settings?.url??"",J);return u&&ee},te=()=>{const{installed:G}=(0,C.n)(U.W.OnCall),{data:J}=M(void 0,{skip:!G});return ee=>{if(G&&D(ee,J??[]))return U.W.OnCall}},se=G=>{const J=te(),u=ee=>({label:ee.name,value:ee.name,grafanaAppReceiverType:J(ee)});return G.map(u)},W=G=>{const J=te();return G.map(u=>({...u,grafanaAppReceiverType:J(u)}))}},18686:(q,F,c)=>{c.d(F,{A:()=>k});var e=c(27702),w=c(80011),b=c(66670);const k=({tooltip:S,icon:M,to:C,target:U,onClick:j,className:D,tooltipPlacement:te="top",...se})=>{const W=typeof S=="string"?S:void 0;return e.createElement(w.u,{content:S,placement:te},C?e.createElement(b.Qj,{variant:"secondary",fill:"text",icon:M,href:C,size:"sm",target:U,...se,"aria-label":W}):e.createElement(b.zx,{className:D,variant:"secondary",fill:"text",size:"sm",icon:M,type:"button",onClick:j,...se,"aria-label":W}))}},57117:(q,F,c)=>{c.d(F,{r:()=>b,z:()=>k});var e=c(89949),w=c.n(e);function b(S,M){return S.filter(C=>!M.find(U=>JSON.stringify(U)===JSON.stringify(C)))}function k(S){const M=S.flatMap(U=>U);return(0,e.uniqBy)(M.filter(U=>M.filter(D=>(0,e.isEqual)(U,D)).length===Object.keys(S).length),U=>JSON.stringify(U))}},97529:(q,F,c)=>{c.d(F,{W:()=>w});var e=c(52646);function w(b,k){const S=e.alertmanagerApi.endpoints.getAlertmanagerConfiguration.useQuery(b??"",{...k,skip:!b});return{...S,error:S.error}}},38338:(q,F,c)=>{c.d(F,{D:()=>w});var e=c(42844);const w=b=>({table:(0,e.css)`
    width: 100%;
    border-radius: ${b.shape.borderRadius()};
    border: solid 1px ${b.colors.border.weak};
    background-color: ${b.colors.background.secondary};

    th {
      padding: ${b.spacing(1)};
    }

    td {
      padding: 0 ${b.spacing(1)};
    }

    tr {
      height: 38px;
    }
  `,evenRow:(0,e.css)`
    background-color: ${b.colors.background.primary};
  `,colExpand:(0,e.css)`
    width: 36px;
  `,nameCell:(0,e.css)`
    gap: ${b.spacing(1)};
  `,actionsCell:(0,e.css)`
    text-align: right;
    width: 1%;
    white-space: nowrap;

    & > * + * {
      margin-left: ${b.spacing(.5)};
    }
  `})}}]);

//# sourceMappingURL=7978.5026d00430d51eb27e26.js.map