"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[6618],{5906:(Q,M,l)=>{l.r(M),l.d(M,{default:()=>F});var i=l(66111),D=l(13821),T=l(54899),e=l(31403),A=l(52081),S=l(69142),E=l(8412),P=l(77582),W=l(76770),V=l(45984);const F=()=>{const G=(0,W.q)("channels"),[I,B]=(0,i.useState)([]),Y=async()=>await(0,T.i)().get("/api/alert-notifications"),[Z,ge]=(0,D.Z)(Y);(0,i.useEffect)(()=>{ge().then(J=>{B(J)})},[ge]);const te=J=>{P.h$.publish(new V.VJ({title:"Delete",text:"Do you want to delete this notification channel?",text2:"Deleting this notification channel will not delete from alerts any references to it",icon:"trash-alt",confirmText:"Delete",yesText:"Delete",onConfirm:async()=>{Pe(J)}}))},Pe=async J=>{await(0,T.i)().delete(`/api/alert-notifications/${J}`);const be=await ge();B(be)};return i.createElement(E.T,{navModel:G},i.createElement(E.T.Contents,null,Z.error&&i.createElement("p",null,Z.error.message),!!I.length&&i.createElement(i.Fragment,null,i.createElement("div",{className:"page-action-bar"},i.createElement("div",{className:"page-action-bar__spacer"}),i.createElement(e.Qj,{icon:"channel-add",href:"alerting/notification/new"},"New channel")),i.createElement("table",{className:"filter-table filter-table--hover"},i.createElement("thead",null,i.createElement("tr",null,i.createElement("th",{style:{minWidth:"200px"}},i.createElement("strong",null,"Name")),i.createElement("th",{style:{minWidth:"100px"}},"Type"),i.createElement("th",{style:{width:"1%"}}))),i.createElement("tbody",null,I.map(J=>i.createElement("tr",{key:J.id},i.createElement("td",{className:"link-td"},i.createElement("a",{href:`alerting/notification/${J.id}/edit`},J.name)),i.createElement("td",{className:"link-td"},i.createElement("a",{href:`alerting/notification/${J.id}/edit`},J.type)),i.createElement("td",{className:"text-right"},i.createElement(A.Lh,{justify:"flex-end"},J.isDefault&&i.createElement(e.zx,{disabled:!0,variant:"secondary",size:"sm"},"default"),i.createElement(e.zx,{variant:"destructive",icon:"times",size:"sm",onClick:()=>{te(J.id)}})))))))),!(I.length||Z.loading)&&i.createElement(S.Z,{title:"There are no notification channels defined yet",buttonIcon:"channel-add",buttonLink:"alerting/notification/new",buttonTitle:"Add channel",proTip:"You can include images in your alert notifications.",proTipLink:"http://docs.grafana.org/alerting/notifications/",proTipLinkTitle:"Learn more",proTipTarget:"_blank"})))}},79070:(Q,M,l)=>{l.r(M),l.d(M,{default:()=>qa});var i=l(9892),D=l(64681),T=l.n(D),e=l(66111),A=l(56895),S=l(26418),E=l(72648),P=l(39904),W=l(45253),V=l(61744),_=l(53546),F=l(27876),G=l(96678),I=l(94984),B=l(45524),Y=l(731),Z=l(88331),ge=l(35918),te=l(82897);function Pe(t,n){let r=n.trim();if(!r.match(/\{\{\s*define/)){const a=r.split(`
`).map(s=>"  "+s).join(`
`);r=`{{ define "${t}" }}
${a}
{{ end }}`}return r}function J(t){const n=(r,a)=>`{{ define "${a}_NEW_${(0,te.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var be=l(88948),Pt=l(29122),wt=l(15348);function Ue(t,n){(0,Pt.Z)(2,arguments);var r=(0,wt.Z)(n);return(0,be.Z)(t,-r)}var K=l(66698),Ae=l(89050),Nt=l(13393),ie=l(24799),fe=l(46967),Ot=l(72142),Ve=l(79841),N=l(31403),Dt=l(20941),It=l(67487),we=l(40014),Lt=l(29427);const Mt="/api/alertmanager/grafana/config/api/v1/templates/test",$t=Lt.C.injectEndpoints({endpoints:t=>({previewTemplate:t.mutation({query:({template:n,alerts:r,name:a})=>({url:Mt,data:{template:n,alerts:r,name:a},method:"POST"})})})}),{usePreviewTemplateMutation:kt}=$t;var ce=l(69945),re=l(72004),X=l(45849),ee=l(10505),Ce=l(46818),he=l(40106),Fe=l(61860),Be=l(9405),Se=l(19985),_e=l(32436),Wt=l(34719),de=l(35029),Ut=l(14747),Vt=l(30173),Ee=l(61893),Ge=l(38645);function Ft({onSelect:t,isOpen:n,onClose:r}){const a=(0,E.wW)(Bt),[s,c]=(0,e.useState)(),[d,m]=(0,e.useState)(null),{useGetAlertmanagerAlertsQuery:f}=Vt.h,{currentData:u=[],isFetching:p,isError:g}=f({amSourceName:X.GC,filter:{inhibited:!0,silenced:!0,active:!0}}),[h,b]=(0,e.useState)(""),C=(0,e.useMemo)(()=>{const L={};return!p&&u&&u.forEach(w=>{L[w.labels.alertname]||(L[w.labels.alertname]=[]),L[w.labels.alertname].push(w)}),L},[p,u]),R=(0,e.useCallback)(L=>{c(L),m(null)},[]),O=(0,e.useMemo)(()=>{const L=Object.keys(C).filter(v=>v.toLowerCase().includes(h.toLowerCase())),w={};return L.forEach(v=>{w[v]=C[v]}),w},[C,h]);if(g)return null;const y=Object.keys(O||[]),x=({index:L,style:w})=>{if(!O)return null;const v=y[L],$=v===s;return e.createElement("button",{type:"button",title:v,style:w,className:(0,i.cx)(a.rowButton,{[a.rowOdd]:L%2===1,[a.rowSelected]:$}),onClick:()=>R(v)},e.createElement("div",{className:(0,i.cx)(a.ruleTitle,a.rowButtonTitle)},v),e.createElement("div",{className:a.alertFolder},e.createElement(e.Fragment,null,e.createElement(P.J,{name:"folder"})," ",O[v][0].labels.grafana_folder??"")))},j=(L,w)=>{const $=L.map(le=>le.labels).map(Ee.cH),q=(0,Ge.z)($),k=(0,Ge.r)((0,Ee.cH)(w.labels),q);return k.length?(0,Ee.P3)((0,Ee.nW)(k)):(0,Ee.P3)(w.labels)},H=({index:L,style:w})=>{const v=(0,e.useMemo)(()=>s?C[s]:[],[]),$=v[L],q=d?.includes($),k=(0,e.useMemo)(()=>j(v,$),[v,$]),z=()=>{if(q&&d){m(d.filter(le=>le!==$));return}m([...d||[],$])};return e.createElement("button",{type:"button",style:w,className:(0,i.cx)(a.rowButton,a.instanceButton,{[a.rowOdd]:L%2===1,[a.rowSelected]:q}),onClick:z},e.createElement("div",{className:a.rowButtonTitle,title:$.labels.alertname},e.createElement(Fe.u,{placement:"bottom",content:e.createElement("pre",null,JSON.stringify($,null,2)),theme:"info"},e.createElement("div",null,k.map((le,We)=>e.createElement(Wt.V,{key:We,name:le,className:a.tag}))))))},U=()=>{const L=d?.map(w=>({annotations:w.annotations,labels:w.labels,startsAt:w.startsAt,endsAt:w.endsAt}))||[];t(L),se()},se=()=>{c(void 0),m(null),b(""),pe("")},oe=()=>{se(),r()},pe=L=>{b(L)};return e.createElement("div",null,e.createElement(de.u,{title:"Select alert instances",className:a.modal,closeOnEscape:!0,isOpen:n,onDismiss:oe,contentClassName:a.modalContent},e.createElement("div",{className:a.container},e.createElement(Ut.H,{value:h,onChange:pe,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:a.column},p&&e.createElement(V.u,{text:"Loading rules...",className:a.loadingPlaceholder}),!p&&e.createElement(Ae.Z,null,({height:L,width:w})=>e.createElement(_e.t7,{itemSize:50,height:L,width:w,itemCount:y.length},x))),e.createElement("div",{className:a.column},!s&&!p&&e.createElement("div",{className:a.selectedRulePlaceholder},e.createElement("div",null,"Select an alert rule to get a list of available instances")),p&&e.createElement(V.u,{text:"Loading rule...",className:a.loadingPlaceholder}),s&&C[s].length&&!p&&e.createElement(Ae.Z,null,({width:L,height:w})=>e.createElement(_e.t7,{itemSize:32,height:w,width:L,itemCount:C[s].length||0},H)))),e.createElement(de.u.ButtonRow,null,e.createElement(N.zx,{type:"button",variant:"secondary",onClick:oe},"Cancel"),e.createElement(N.zx,{type:"button",variant:"primary",disabled:!(s&&d),onClick:()=>{s&&d&&U()}},"Add alert data to payload"))))}const Bt=t=>{const n=(0,N.gN)(t);return{container:i.css`
      display: grid;
      grid-template-columns: 1fr 1.5fr;
      grid-template-rows: min-content auto;
      gap: ${t.spacing(2)};
      flex: 1;
    `,tag:i.css`
      margin: 5px;
    `,column:i.css`
      flex: 1 1 auto;
    `,alertLabels:i.css`
      overflow-x: auto;
      height: 32px;
    `,ruleTitle:i.css`
      height: 22px;
      font-weight: ${t.typography.fontWeightBold};
    `,rowButton:i.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:i.css`
      overflow-x: auto;
    `,rowSelected:i.css`
      border-color: ${t.colors.primary.border};
    `,rowOdd:i.css`
      background-color: ${t.colors.background.secondary};
    `,instanceButton:i.css`
      display: flex;
      gap: ${t.spacing(1)};
      justify-content: space-between;
      align-items: center;
    `,loadingPlaceholder:i.css`
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    `,selectedRulePlaceholder:i.css`
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      font-weight: ${t.typography.fontWeightBold};
    `,modal:i.css`
      height: 100%;
    `,modalContent:i.css`
      flex: 1;
      display: flex;
      flex-direction: column;
    `,modalAlert:i.css`
      flex-grow: 0;
    `,warnIcon:i.css`
      fill: ${t.colors.warning.main};
    `,labels:i.css`
      justify-content: flex-start;
    `,alertFolder:i.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;
    `}},_t=[{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."}],Gt=[{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."}],zt=[{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."}],Kt=[{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"}],jt=`{
  "summary": "alert summary",
  "description": "alert description"
}
`;var ze=l(42042);function Ht(){const t=(0,E.wW)(Jt),n=e.createElement(Ne,{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:zt});return e.createElement(S.Stack,{gap:2,flexGrow:1},e.createElement(Ne,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:_t,typeRenderer:r=>r==="[]Alert"?e.createElement(ze.z,{content:n},e.createElement("div",{className:t.interactiveType},r)):r==="KeyValue"?e.createElement(ze.z,{content:e.createElement(Qt,null)},e.createElement("div",{className:t.interactiveType},r)):r}))}const Jt=t=>({header:i.css`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `,interactiveType:i.css`
    color: ${t.colors.text.link};
  `});function Ne({dataItems:t,caption:n,typeRenderer:r}){const a=(0,E.wW)(Ke);return e.createElement("table",{className:a.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:c,notes:d},m)=>e.createElement("tr",{key:m},e.createElement("td",null,s),e.createElement("td",null,r?r(c):c),e.createElement("td",null,d)))))}function Qt(){const t=(0,E.wW)(Ke);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,jt)),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,Kt.map(({name:n,args:r,returns:a,notes:s})=>e.createElement("tr",{key:n},e.createElement("td",null,n),e.createElement("td",null,r),e.createElement("td",null,a),e.createElement("td",null,s))))))}const Ke=t=>({table:i.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 Yt=l(72948),je=l(2594),He=l(16808),Je=l(19191);const Zt={annotations:[{key:"",value:""}],labels:[{key:"",value:""}],status:"firing"},Xt=({isOpen:t,onDismiss:n,onAccept:r})=>{const a=(0,E.wW)(qt),[s,c]=(0,e.useState)([]),d=(0,K.cI)({defaultValues:Zt,mode:"onBlur"}),m=d.watch("annotations"),f=d.watch("labels"),[u,p]=(0,e.useState)("firing"),g=()=>{const R={annotations:m.filter(({key:O,value:y})=>!!O&&!!y).reduce((O,{key:y,value:x})=>({...O,[y]:x}),{}),labels:f.filter(({key:O,value:y})=>!!O&&!!y).reduce((O,{key:y,value:x})=>({...O,[y]:x}),{}),startsAt:"2023-04-01T00:00:00Z",endsAt:u==="firing"?(0,be.Z)(new Date,1).toISOString():Ue(new Date,1).toISOString()};c(O=>[...O,R]),d.reset()},h=()=>{r(s),c([]),d.reset(),p("firing")},b=()=>{const R=f.some(y=>y.key!==""&&y.value!==""),O=m.some(y=>y.key!==""&&y.value!=="");return R||O},C=[{label:"Firing",value:"firing"},{label:"Resolved",value:"resolved"}];return e.createElement(de.u,{onDismiss:n,isOpen:t,title:"Add custom alerts"},e.createElement(K.RV,{...d},e.createElement("form",{onSubmit:R=>{R.preventDefault(),R.stopPropagation(),d.reset(),p("firing")}},e.createElement(e.Fragment,null,e.createElement(Yt.Z,null,e.createElement(S.Stack,{direction:"column",gap:1},e.createElement("div",{className:a.section},e.createElement(He.Z,null)),e.createElement("div",{className:a.section},e.createElement(Je.Z,null)),e.createElement("div",{className:a.flexWrapper},e.createElement(je.S,{value:u,options:C,onChange:R=>p(R)}),e.createElement(N.zx,{onClick:g,className:a.onAddButton,icon:"plus-circle",type:"button",variant:"secondary",disabled:!b()},"Add alert data"))))),e.createElement("div",{className:a.onSubmitWrapper}),s.length>0&&e.createElement(S.Stack,{direction:"column",gap:1},e.createElement("h5",null," Review alert data to add to the payload:"),e.createElement("pre",{className:a.result,"data-testid":"payloadJSON"},JSON.stringify(s,null,2))),e.createElement("div",{className:a.onSubmitWrapper},e.createElement(de.u.ButtonRow,null,e.createElement(N.zx,{onClick:h,disabled:s.length===0,className:a.onSubmitButton},"Add alert data to payload"))))))},qt=t=>({section:i.css`
    margin-bottom: ${t.spacing(2)};
  `,onAddButton:i.css`
    flex: none;
    width: fit-content;
    padding-right: ${t.spacing(1)};
    margin-left: auto;
  `,flexWrapper:i.css`
    display: flex;
    flex-direction: row,
    justify-content: space-between;
  `,onSubmitWrapper:i.css`
    display: flex;
    flex-direction: row;
    align-items: baseline;
    justify-content: flex-end;
  `,onSubmitButton:i.css`
    margin-left: ${t.spacing(2)};
  `,result:i.css`
    width: 570px;
    height: 363px;
  `}),en="Reset to default";function tn({payload:t,setPayload:n,defaultPayload:r,setPayloadFormatError:a,payloadFormatError:s,onPayloadError:c}){const d=(0,E.wW)(Qe),m=()=>{n(r)},[f,u]=(0,e.useState)(!1),p=()=>{u(!1)},g=s!==null,h=()=>{try{const x=JSON.parse(t);JSON.stringify([...x]),a(null)}catch(x){throw a(x instanceof Error?x.message:"Invalid JSON."),c(),x}},b=()=>{try{h(),u(!0)}catch{}},C=()=>{try{h(),y(!0)}catch{}},R=x=>{p(),y(!1),n(j=>{const H=JSON.parse(j);return JSON.stringify([...H,...x],void 0,2)})},[O,y]=(0,e.useState)(!1);return e.createElement("div",{className:d.wrapper},e.createElement("div",{className:d.editor},e.createElement("div",{className:d.title},"Payload data",e.createElement(Fe.u,{placement:"top",content:e.createElement(nn,null),theme:"info"},e.createElement(P.J,{name:"info-circle",className:d.tooltip,size:"xl"}))),e.createElement(Ae.Z,{disableHeight:!0},({width:x})=>e.createElement("div",{className:d.editorWrapper},e.createElement(Be.p,{width:x,height:362,language:"json",showLineNumbers:!0,showMiniMap:!1,value:t,readOnly:!1,onBlur:n}))),e.createElement("div",{className:d.buttonsWrapper},e.createElement(N.zx,{type:"button",variant:"secondary",className:d.button,icon:"bell",disabled:g,onClick:C},"Select alert instances"),e.createElement(N.zx,{onClick:b,className:d.button,icon:"plus-circle",type:"button",variant:"secondary",disabled:g},"Add custom alerts"),e.createElement(N.zx,{onClick:m,className:d.button,icon:"arrow-up",type:"button",variant:"destructive"},en),s!==null&&e.createElement(Se.C,{color:"orange",icon:"exclamation-triangle",text:"JSON Error",tooltip:"Fix errors in payload, and click Refresh preview button"}))),e.createElement(Xt,{isOpen:f,onDismiss:p,onAccept:R}),e.createElement(Ft,{onSelect:R,isOpen:O,onClose:()=>y(!1)}))}const nn=()=>{const t=(0,E.wW)(Qe);return e.createElement(Ne,{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:Gt})},Qe=t=>({jsonEditor:i.css`
    width: 100%;
    height: 100%;
  `,buttonsWrapper:i.css`
    margin-top: ${t.spacing(1)};
    display: flex;
    flex-wrap: wrap;
  `,button:i.css`
    flex: none;
    width: fit-content;
    padding-right: ${t.spacing(1)};
    margin-right: ${t.spacing(1)};
    margin-bottom: ${t.spacing(1)};
  `,title:i.css`
    font-weight: ${t.typography.fontWeightBold};
    heigth: 41px;
    padding-top: 10px;
    padding-left: ${t.spacing(2)};
    margin-top: 19px;
  `,wrapper:i.css`
    flex: 1;
    min-width: 450px;
  `,tooltip:i.css`
    padding-left: ${t.spacing(1)};
  `,editorWrapper:i.css`
    width: min-content;
    padding-top: 7px;
  `,editor:i.css`
    display: flex;
    flex-direction: column;
    margin-top: ${t.spacing(-1)};
  `,templateDataDocsHeader:i.css`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `});var me=l(68402);function an(t){const n=t.languages.CompletionItemKind.Function;return[{label:me.AlertmanagerTemplateFunction.toUpper,detail:"function(s string)",kind:n},{label:me.AlertmanagerTemplateFunction.toLower,detail:"function(s string)",kind:n},{label:me.AlertmanagerTemplateFunction.title,documentation:"Capitalizes the first letter of each word",detail:"function(s string)",kind:n},{label:me.AlertmanagerTemplateFunction.join,documentation:{value:"Joins an array of strings using the separator provided."},detail:"function(separator string, s []string)",kind:n},{label:me.AlertmanagerTemplateFunction.match,detail:"function",kind:n},{label:me.AlertmanagerTemplateFunction.safeHtml,detail:"function(pattern, repl, text)",kind:n},{label:me.AlertmanagerTemplateFunction.reReplaceAll,detail:"function(pattern, repl, text)",kind:n},{label:me.AlertmanagerTemplateFunction.stringSlice,detail:"function(s ...string)",kind:n}]}const rn=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,sn=`
[{{.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 }}
`,on=ye("GroupLabels"),ln=ye("CommonLabels"),cn=ye("CommonAnnotations"),dn=ye("Labels"),mn=ye("Annotations");function ye(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function un(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 pn(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 gn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function fn(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 Ye={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:rn},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:sn},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:on},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:ln},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:cn},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:dn},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:mn}};function hn(t){const n=t.languages.CompletionItemKind.Snippet,r=t.languages.CompletionItemInsertTextRule.InsertAsSnippet,{alerts:a,alertDetails:s,groupLabels:c,commonLabels:d,commonAnnotations:m,labels:f,annotations:u}=Ye;return[{label:a.label,documentation:a.description,kind:n,insertText:a.snippet,insertTextRules:r},{label:{label:s.label,detail:"(Alert)"},documentation:s.description,kind:n,insertText:s.snippet,insertTextRules:r},{label:c.label,documentation:c.description,kind:n,insertText:c.snippet,insertTextRules:r},{label:d.label,documentation:d.description,kind:n,insertText:d.snippet,insertTextRules:r},{label:m.label,documentation:m.description,kind:n,insertText:m.snippet,insertTextRules:r},{label:{label:f.label,detail:"(Alert)"},documentation:f.description,kind:n,insertText:f.snippet,insertTextRules:r},{label:{label:u.label,detail:"(Alert)"},documentation:u.description,kind:n,insertText:u.snippet,insertTextRules:r}]}function En(t){const n={triggerCharacters:["."],provideCompletionItems(r,a,s){const c=r.getWordUntilPosition(a),d={startLineNumber:a.lineNumber,endLineNumber:a.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn},m=new vn(t,d);if(!yn(r,a))return m.getSnippetsSuggestions();if(s.triggerKind===t.languages.CompletionTriggerKind.Invoke&&!s.triggerCharacter)return m.getFunctionsSuggestions();const u=r.getWordUntilPosition({lineNumber:a.lineNumber,column:a.column-1});return m.getTemplateDataSuggestions(u.word)}};return t.languages.registerCompletionItemProvider("go-template",n)}function yn(t,n){const r={startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:t.getLineMinColumn(n.lineNumber),endColumn:t.getLineMaxColumn(n.lineNumber)},a='\\{\\{[a-zA-Z0-9._() "]+\\}\\}';return t.findMatches(a,r,!0,!1,null,!0).some(c=>c.range.containsPosition(n))}class vn{constructor(n,r){this.monaco=n,this.range=r,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(hn(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(an(this.monaco)),this.getTemplateDataSuggestions=a=>{switch(a){case"":return this.getCompletionsFromDefinitions(un(this.monaco),pn(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(gn(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(fn(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...a)=>({suggestions:(0,te.concat)(...a).map(c=>bn(c,this.range))})}}function bn({label:t,detail:n,documentation:r,kind:a,insertText:s},c){const d=typeof t=="string"?t:t.label,m=typeof t=="string"?{label:t,description:n}:{...t};return m.description??=n,{label:m,kind:a,insertText:s??d,range:c,documentation:r,detail:n}}const Ze="go-template",An={id:Ze,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(l.bind(l,68402))},Cn=(t,n)=>{const{id:r,loader:a}=n;t.languages.getLanguages().find(c=>c.id===r)||(t.languages.register({id:r}),a().then(c=>{t.languages.setMonarchTokensProvider(r,c.language),t.languages.setLanguageConfiguration(r,c.conf)}))},Xe=t=>{const n=Boolean(t.autoHeight),r=(0,e.useRef)(null),a=s=>{if(n){const c=s.getContentHeight();try{s.layout({height:c,width:NaN})}catch{}}};return(0,e.useEffect)(()=>()=>{r.current?.dispose()},[]),e.createElement(Be.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:a,onBeforeEditorMount:s=>{Cn(s,An),r.current=En(s)},language:Ze})},Sn=Object.freeze({name:"",content:""}),qe=t=>t.pathname.endsWith("/duplicate"),et=`[
  {
    "annotations": {
      "summary": "Instance instance1 has been down for more than 5 minutes"
    },
    "labels": {
      "instance": "instance1"
    },
    "startsAt": "${Ue(new Date,1).toISOString()}"
  }]
`,Oe=({existing:t,alertManagerSourceName:n,config:r,provenance:a})=>{const s=(0,E.wW)(De),c=(0,F.useDispatch)();(0,we.x)(v=>v.unifiedAlerting.saveAMConfig=Ce.oq);const{loading:d,error:m}=(0,ce._)(v=>v.saveAMConfig),f=(0,A.TH)(),u=qe(f),[p,g]=(0,e.useState)(et),[h,b]=(0,e.useState)(null),[C,R]=(0,e.useState)("content"),O=()=>R("preview"),y=v=>{const $=Pe(v.name,v.content),q={...r.template_files,[v.name]:$};t&&t.name!==v.name&&delete q[t.name];const k=[...(r.alertmanager_config.templates??[]).filter(le=>le!==t?.name),v.name],z={template_files:q,alertmanager_config:{...r.alertmanager_config,templates:k}};c((0,re.mM)({alertManagerSourceName:n,newConfig:z,oldConfig:r,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},x=(0,K.cI)({mode:"onSubmit",defaultValues:t??Sn}),{handleSubmit:j,register:H,formState:{errors:U},getValues:se,setValue:oe,watch:pe}=x,L=v=>!r.template_files[v]||t?.name===v?!0:"Another template with this name already exists.",w=n===X.GC;return e.createElement(K.RV,{...x},e.createElement("form",{onSubmit:j(y)},e.createElement("h4",null,t&&!u?"Edit notification template":"Create notification template"),m&&e.createElement(W.b,{severity:"error",title:"Error saving template"},m.message||m?.data?.message||String(m)),a&&e.createElement(he.Xq,{resource:he.Uv.Template}),e.createElement(Nt.C,{disabled:Boolean(a)},e.createElement(ie.g,{label:"Template name",error:U?.name?.message,invalid:!!U.name?.message,required:!0},e.createElement(fe.I,{...H("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:L}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Tn,null),e.createElement("div",{className:s.editorsWrapper},e.createElement("div",{className:s.contentContainer},e.createElement(Ot.J,null,e.createElement(Ve.O,{label:"Content",active:C==="content",onChangeTab:()=>R("content")}),w&&e.createElement(Ve.O,{label:"Preview",active:C==="preview",onChangeTab:()=>R("preview")})),e.createElement("div",{className:s.contentContainerEditor},e.createElement(Ae.Z,null,({width:v})=>e.createElement(e.Fragment,null,C==="content"?e.createElement("div",null,e.createElement(ie.g,{error:U?.content?.message,invalid:!!U.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(Xe,{value:se("content"),width:v,height:363,onBlur:$=>oe("content",$)}))),e.createElement("div",{className:s.buttons},d&&e.createElement(N.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!d&&e.createElement(N.zx,{type:"submit",variant:"primary"},"Save template"),e.createElement(N.Qj,{disabled:d,href:(0,ee.eQ)("alerting/notifications",n),variant:"secondary",type:"button"},"Cancel"))):e.createElement(Nn,{width:v,payload:p,templateName:pe("name"),setPayloadFormatError:b,payloadFormatError:h}))))),w&&e.createElement(tn,{payload:p,setPayload:g,defaultPayload:et,setPayloadFormatError:b,payloadFormatError:h,onPayloadError:O}))),e.createElement(Dt.s,{label:"Data cheat sheet",isOpen:!1,className:s.collapsableSection},e.createElement(Ht,null))))};function Tn(){const t=(0,E.wW)(De);return e.createElement(W.b,{title:"Templating guideline",severity:"info"},e.createElement(S.Stack,{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(N.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(Ye).map(n=>n.label).join(", "))))}function Rn(t){const n=t.filter(s=>s.text.trim().length>0),r=n.length>1,a=s=>{const c=`Preview for ${s.name}:`,d="=".repeat(c.length).concat(">"),m="<".concat("=".repeat(c.length));return r?`${c}
${d}${s.text}${m}
`:`${d}${s.text}${m}
`};return n.map(s=>a(s)).join(`
`)}function xn(t){return t.map(n=>n.name?`ERROR in ${n.name}:
`.concat(`${n.kind}
${n.message}
`):`ERROR:
${n.kind}
${n.message}
`).join(`
`)}const Pn="Preview request failed. Check if the payload data has the correct structure.";function wn(t,n,r){const a=t?Pn:void 0,s=t||Boolean(n),c=n||a,d=r?.results,m=r?.errors,f=d?Rn(d):"",u=m?xn(m):"";return s?c:`${f}
${u}`}function Nn({payload:t,templateName:n,payloadFormatError:r,setPayloadFormatError:a,width:s}){const c=(0,E.wW)(De),{watch:d}=(0,K.Gc)(),m=d("content"),[f,{data:u,isError:p,isLoading:g}]=kt(),h=wn(p,r,u),b=(0,e.useCallback)(()=>{try{const C=JSON.parse(t);JSON.stringify([...C]),f({template:m,alerts:C,name:n}),a(null)}catch(C){a(C instanceof Error?C.message:"Invalid JSON.")}},[m,n,t,a,f]);return(0,e.useEffect)(()=>b(),[b]),e.createElement("div",{style:{width:`${s}px`},className:c.preview.wrapper},g&&e.createElement(e.Fragment,null,e.createElement(It.$,{inline:!0})," Loading preview..."),e.createElement("pre",{className:c.preview.result,"data-testid":"payloadJSON"},h),e.createElement(N.zx,{onClick:b,className:c.preview.button,icon:"arrow-up",type:"button",variant:"secondary"},"Refresh preview"))}const De=t=>({contentContainer:i.css`
    flex: 1;
    margin-bottom: ${t.spacing(6)};
  `,contentContainerEditor:i.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:i.css`
    margin-top: ${t.spacing(2)};
    font-size: ${t.typography.bodySmall.fontSize};
  `,code:i.css`
    color: ${t.colors.text.secondary};
    font-weight: ${t.typography.fontWeightBold};
  `,buttons:i.css`
    display: flex;
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
    margin-top: -7px;
  `,textarea:i.css`
    max-width: 758px;
  `,editWrapper:i.css`
      display: flex;
      width: 100%
      heigth:100%;
      position: relative;
      `,toggle:i.css`
      color: theme.colors.text.secondary,
      marginRight: ${t.spacing(1)}`,preview:{wrapper:i.css`
      display: flex;
      width: 100%
      heigth:100%;
      position: relative;
      flex-direction: column;
      `,result:i.css`
      width: 100%;
      height: 363px;
    `,button:i.css`
      flex: none;
      width: fit-content;
      margin-top: -6px;
    `},collapsableSection:i.css`
    width: fit-content;
  `,editorsWrapper:i.css`
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    gap: ${t.spacing(1)};
  `}),On=({config:t,templateName:n,alertManagerSourceName:r})=>{const a=t.template_files?.[n];if(!a)return e.createElement(W.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,ge.G)(n,Object.keys(t.template_files));return e.createElement(Oe,{alertManagerSourceName:r,config:t,existing:{name:s,content:J(a)}})};function o(t,n,r,a={}){return{propertyName:t,label:n,description:r,element:"input",inputType:"",required:!1,secure:!1,placeholder:"",validationRule:"",showWhen:{field:"",is:""},dependsOn:"",...a}}const Dn=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","")]}),tt=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"})]}),ne=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."),Dn,tt]}),nt=[{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"}),tt]},{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})]}),ne]},{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"}),ne]},{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"})]}),ne]},{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.")]}),ne]},{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" . }}'}),ne]},{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+$|^$)"}),ne]},{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}),ne]},{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" .}}'}),{...ne,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:""}]}),ne]},{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"}),ne]},{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",""),ne,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 Ln(t,n){const r={};let a=1;return[{name:t.name,items:t.grafana_managed_receiver_configs?.map(c=>{const d=String(a++);r[d]=c;const m=n.find(({type:f})=>f===c.type);return Un(d,c,m)})??[]},r]}function Mn(t,n){const r={};let a=1;const s=Object.entries(t).filter(([d])=>d.endsWith("_configs")&&d!=="grafana_managed_receiver_configs").map(([d,m])=>[d.replace("_configs",""),m]).map(([d,m])=>m.map(f=>{const u=String(a++);if(r[u]={type:d,config:f},!n.find(g=>g.type===d))throw new Error(`unknown cloud notifier: ${d}`);return Wn(u,d,f)})).flat();return[{name:t.name,items:s},r]}function $n(t,n,r){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(a=>{const s=n[a.__id];return st(a,r,t.name,s)})}}function kn(t,n){const r={name:t.name};return t.items.forEach(({__id:a,type:s,settings:c,sendResolved:d})=>{const m=ve({...c,send_resolved:d??n.sendResolved}),f=`${s}_configs`;r[f]?r[f].push(m):r[f]=[m]}),r}function at(t,n,r){const a=t.alertmanager_config.receivers??[];if(n.name!==r&&a.find(({name:c})=>c===n.name))throw new Error(`Duplicate receiver name ${n.name}`);if(r&&!a.find(({name:c})=>c===r))throw new Error(`Expected receiver ${r} to exist, but did not find it in the config`);const s={...t,alertmanager_config:{...t.alertmanager_config,receivers:r?a.map(c=>c.name===r?n:c):[...a,n]}};return s.alertmanager_config.route&&r&&n.name!==r&&(s.alertmanager_config.route=rt(s.alertmanager_config.route,r,n.name)),s}function rt(t,n,r){const a={...t};return a.receiver===n&&(a.receiver=r),a.routes&&(a.routes=a.routes.map(s=>rt(s,n,r))),a}function Wn(t,n,r){return{__id:t,type:n,settings:{...r},secureFields:{},secureSettings:{},sendResolved:r.send_resolved}}function Un(t,n,r){const a={__id:t,type:n.type,provenance:n.provenance,secureSettings:{},settings:{...n.settings},secureFields:{...n.secureFields},disableResolveMessage:n.disableResolveMessage};return r?.options.forEach(s=>{s.secure&&a.settings[s.propertyName]&&(delete a.settings[s.propertyName],a.secureFields[s.propertyName]=!0)}),a}function st(t,n,r,a){const s={settings:ve({...a&&a.type===t.type?a.settings??{}:{},...t.settings??{}}),secureSettings:t.secureSettings??{},type:t.type,name:r,disableResolveMessage:t.disableResolveMessage??a?.disableResolveMessage??n.disableResolveMessage};return a&&(s.uid=a.uid),s}function ve(t){return(0,te.isArray)(t)?t.forEach(ve):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,r])=>{r===""||r===null||r===void 0?delete t[n]:ve(r)}),t}var Ie=l(58255);const Vn=({pathPrefix:t,className:n,readOnly:r=!1})=>{const{register:a}=(0,K.Gc)();return e.createElement("div",{className:n},e.createElement(ie.g,{disabled:r},e.createElement(Ie.X,{...a(`${t}sendResolved`),label:"Send resolved",disabled:r,description:"Whether or not to notify about resolved alerts."})))};var Fn=l(60499);const Bn=[];function ot(t){const{name:n,formAPI:r,defaults:a,softDelete:s}=t,{watch:c,getValues:d,reset:m,setValue:f}=r,u=c(n)??a??Bn,p=(0,e.useCallback)(g=>{const h=JSON.parse(JSON.stringify(d())),b=g(u??[]);m((0,te.set)(h,n,b))},[d,n,m,u]);return{fields:u,append:(0,e.useCallback)(g=>p(h=>[...h,g]),[p]),remove:(0,e.useCallback)(g=>{s?f(`${n}.${g}.__deleted`,!0):p(h=>{const b=h.slice();return b.splice(g,1),b})},[p,n,f,s])}}var Te=l(63619),lt=l(8581),_n=l(97379),ae=l(65750);const Gn=({value:t,onChange:n,readOnly:r=!1})=>{const a=(0,E.wW)(zn),[s,c]=(0,e.useState)(it(t));(0,e.useEffect)(()=>c(it(t)),[t]);const d=u=>{n(Kn(u))},m=u=>{const p=s.slice(),g=p.splice(u,1)[0];c(p),g[0]&&d(p)},f=(u,p)=>{const g=s[p],h=s.map((b,C)=>C===p?u:b);c(h),(u[0]||g[0])&&d(h)};return e.createElement("div",null,!!s.length&&e.createElement("table",{className:a.table},e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Value"),!r&&e.createElement("th",null))),e.createElement("tbody",null,s.map(([u,p],g)=>e.createElement("tr",{key:g},e.createElement("td",null,e.createElement(fe.I,{readOnly:r,value:u,onChange:h=>f([h.currentTarget.value,p],g)})),e.createElement("td",null,e.createElement(fe.I,{readOnly:r,value:p,onChange:h=>f([u,h.currentTarget.value],g)})),!r&&e.createElement("td",null,e.createElement(ae.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>m(g)})))))),!r&&e.createElement(N.zx,{className:a.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>c([...s,["",""]])},"Add"))},zn=t=>({addButton:i.css`
    margin-top: ${t.spacing(1)};
  `,table:i.css`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),Kn=t=>{const n={};for(const[r,a]of t)r&&(n[r]=a);return n},it=t=>Object.entries(t??{}),jn=({value:t,onChange:n,readOnly:r=!1})=>{const a=(0,E.wW)(Hn),s=d=>{if(!t)return;const m=t.slice();m.splice(d,1),n(m)},c=(d,m)=>{t&&n(t.map((f,u)=>u===m?d:f))};return e.createElement("div",null,!!t?.length&&t.map((d,m)=>e.createElement("div",{key:m,className:a.row},e.createElement(fe.I,{readOnly:r,value:d,onChange:f=>c(f.currentTarget.value,m)}),!r&&e.createElement(ae.A,{className:a.deleteIcon,icon:"trash-alt",tooltip:"delete",onClick:()=>s(m)}))),!r&&e.createElement(N.zx,{className:a.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},Hn=t=>({row:i.css`
    display: flex;
    flex-direction: row;
    margin-bottom: ${t.spacing(1)};
    align-items: center;
  `,deleteIcon:i.css`
    margin-left: ${t.spacing(1)};
  `,addButton:i.css`
    margin-top: ${t.spacing(1)};
  `});var ct=l(33950);const Le=({label:t,description:n,children:r,className:a,size:s="xl"})=>{const c=(0,E.wW)(Jn),[d,m]=(0,e.useState)(!0),f=()=>m(!d);return e.createElement("div",{className:(0,i.cx)(c.wrapper,a)},e.createElement(ct.U,{className:c.toggle,size:s,onToggle:f,isCollapsed:d,text:t}),n&&e.createElement("p",{className:c.description},n),e.createElement("div",{className:d?c.hidden:c.content},r))},Jn=t=>({wrapper:i.css`
    margin-top: ${t.spacing(1)};
    padding-bottom: ${t.spacing(1)};
  `,toggle:i.css`
    margin: ${t.spacing(1,0)};
    padding: 0;
  `,hidden:i.css`
    display: none;
  `,description:i.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,content:i.css`
    padding-left: ${t.spacing(3)};
  `}),dt=t=>({collapsibleSection:i.css`
    margin: 0;
    padding: 0;
  `,wrapper:i.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:i.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,deleteIcon:i.css`
    position: absolute;
    right: ${t.spacing(1)};
    top: ${t.spacing(1)};
  `,addButton:i.css`
    margin-top: ${t.spacing(1)};
  `}),Qn=({option:t,pathPrefix:n,errors:r,defaultValues:a,readOnly:s=!1})=>{const c=(0,E.wW)(dt),d=`${n}${t.propertyName}`,m=(0,K.Gc)(),{fields:f,append:u,remove:p}=ot({name:d,formAPI:m,defaults:a});return e.createElement("div",{className:c.wrapper},e.createElement(Le,{className:c.collapsibleSection,label:`${t.label} (${f.length})`,description:t.description},(f??a??[]).map((g,h)=>e.createElement("div",{key:h,className:c.wrapper},!s&&e.createElement(ae.A,{"data-testid":`${d}.${h}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>p(h),className:c.deleteIcon}),t.subformOptions?.map(b=>e.createElement(Re,{readOnly:s,defaultValue:g?.[b.propertyName],key:b.propertyName,option:b,pathPrefix:`${d}.${h}.`,error:r?.[h]?.[b.propertyName]})))),!s&&e.createElement(N.zx,{"data-testid":`${d}.add-button`,className:c.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>u({__id:String(Math.random())})},"Add")))},Yn=({option:t,pathPrefix:n,errors:r,defaultValue:a,readOnly:s=!1})=>{const c=(0,E.wW)(dt),d=`${n}${t.propertyName}`,{watch:m}=(0,K.Gc)(),f=m(d),u=f===void 0?a:f,[p,g]=(0,e.useState)(!!u);return e.createElement("div",{className:c.wrapper,"data-testid":`${d}.container`},e.createElement("h6",null,t.label),t.description&&e.createElement("p",{className:c.description},t.description),p&&e.createElement(e.Fragment,null,!s&&e.createElement(ae.A,{"data-testid":`${d}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>g(!1),className:c.deleteIcon}),(t.subformOptions??[]).map(h=>e.createElement(Re,{readOnly:s,defaultValue:a?.[h.propertyName],key:h.propertyName,option:h,pathPrefix:`${d}.`,error:r?.[h.propertyName]}))),!p&&!s&&e.createElement(N.zx,{className:c.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>g(!0),"data-testid":`${d}.add-button`},"Add"))},Re=({option:t,invalid:n,pathPrefix:r,pathSuffix:a="",error:s,defaultValue:c,readOnly:d=!1})=>{const m=`${r}${a}`;return t.element==="subform"?e.createElement(Yn,{readOnly:d,defaultValue:c,option:t,errors:s,pathPrefix:m}):t.element==="subform_array"?e.createElement(Qn,{readOnly:d,defaultValues:c,option:t,pathPrefix:m,errors:s}):e.createElement(ie.g,{label:t.element!=="checkbox"?t.label:void 0,description:t.description||void 0,invalid:!!s,error:s?.message},e.createElement(Zn,{id:`${m}${t.propertyName}`,defaultValue:c,option:t,invalid:n,pathPrefix:m,readOnly:d,pathIndex:r}))},Zn=({option:t,invalid:n,id:r,pathPrefix:a="",pathIndex:s="",readOnly:c=!1})=>{const{control:d,register:m,unregister:f,getValues:u}=(0,K.Gc)(),p=`${a}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{f(p,{keepValue:!1})},[f,p]),t.element){case"checkbox":return e.createElement(Ie.X,{id:r,readOnly:c,disabled:c,className:Xn.checkbox,...m(p),label:t.label,description:t.description});case"input":return e.createElement(fe.I,{id:r,readOnly:c||ea(t,u,s),invalid:n,type:t.inputType,...m(p,{required:qn(t,u,s),validate:g=>t.validationRule!==""?mt(g,t.validationRule):!0,setValueAs:t.setValueAs}),placeholder:t.placeholder});case"select":return e.createElement(Te.g,{render:({field:{onChange:g,ref:h,...b}})=>e.createElement(lt.Ph,{disabled:c,...b,defaultValue:t.defaultValue,options:t.selectOptions??void 0,invalid:n,onChange:C=>g(C.value)}),control:d,name:p});case"textarea":return e.createElement(_n.K,{id:r,readOnly:c,invalid:n,placeholder:t.placeholder,...m(p,{required:t.required?"Required":!1,validate:g=>t.validationRule!==""?mt(g,t.validationRule):!0})});case"string_array":return e.createElement(Te.g,{render:({field:{value:g,onChange:h}})=>e.createElement(jn,{readOnly:c,value:g,onChange:h}),control:d,name:p});case"key_value_map":return e.createElement(Te.g,{render:({field:{value:g,onChange:h}})=>e.createElement(Gn,{readOnly:c,value:g,onChange:h}),control:d,name:p});default:return console.error("Element not supported",t.element),null}},Xn={checkbox:i.css`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},mt=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",qn=(t,n,r)=>{if(!t.dependsOn)return t.required?"Required":!1;if((0,te.isEmpty)(n(`${r}secureFields`))){const a=n(`${r}secureSettings.${t.dependsOn}`);return!Boolean(a)&&t.required?"Required":!1}else return!n(`${r}secureFields.${t.dependsOn}`)&&t.required?"Required":!1},ea=(t,n,r)=>t.dependsOn?(0,te.isEmpty)(n(`${r}secureFields`))?n(`${r}secureSettings.${t.dependsOn}`):n(`${r}secureFields.${t.dependsOn}`):!1;function ut({defaultValues:t,selectedChannelOptions:n,onResetSecureField:r,secureFields:a,errors:s,pathPrefix:c="",readOnly:d=!1}){const{watch:m}=(0,K.Gc)(),f=m();return e.createElement(e.Fragment,null,n.map((u,p)=>{const g=`${u.label}-${p}`,h=c.split("."),b=h.length>=2?f.items[Number(h[1])].settings[u.showWhen.field]:void 0;if(u.showWhen.field&&b!==u.showWhen.is)return null;if(a&&a[u.propertyName])return e.createElement(ie.g,{key:g,label:u.label,description:u.description||void 0},e.createElement(fe.I,{readOnly:!0,value:"Configured",suffix:d?null:e.createElement(N.zx,{onClick:()=>r(u.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const C=(u.secure?s?.secureSettings:s?.settings)?.[u.propertyName],R=t?.settings?.[u.propertyName];return e.createElement(Re,{defaultValue:R,readOnly:d,key:g,error:C,pathPrefix:c,pathSuffix:u.secure?"secureSettings.":"settings.",option:u})}))}function ta({defaultValues:t,pathPrefix:n,onDuplicate:r,onDelete:a,onTest:s,notifiers:c,errors:d,secureFields:m,commonSettingsComponent:f,isEditable:u=!0,isTestable:p}){const g=(0,E.wW)(na),h=k=>`${n}${k}`,{control:b,watch:C,register:R,trigger:O,formState:y,setValue:x}=(0,K.Gc)(),j=C(h("type"))??t.type,{loading:H}=(0,ce._)(k=>k.testReceivers);(0,e.useEffect)(()=>{R(`${n}.__id`),R(`${n}.secureFields`)},[R,n]);const[U,se]=(0,e.useState)(m??{}),oe=k=>{if(U[k]){const z={...m};delete z[k],se(z),x(`${n}.secureFields`,z)}},pe=(0,e.useMemo)(()=>c.map(({name:k,type:z})=>({label:k,value:z})).sort((k,z)=>k.label.localeCompare(z.label)),[c]),L=async()=>{await O(),Object.keys(y.errors).length===0&&s&&s()},w=c.find(({type:k})=>k===j),v=w?.options.filter(k=>k.required),$=w?.options.filter(k=>!k.required),q=`contact-point-type-${n}`;return e.createElement("div",{className:g.wrapper,"data-testid":"item-container"},e.createElement("div",{className:g.topRow},e.createElement("div",null,e.createElement(ie.g,{label:"Integration",htmlFor:q,"data-testid":`${n}type`},e.createElement(Te.g,{name:h("type"),defaultValue:t.type,render:({field:{ref:k,onChange:z,...le}})=>e.createElement(lt.Ph,{disabled:!u,inputId:q,...le,width:37,options:pe,onChange:We=>z(We?.value)}),control:b,rules:{required:!0}}))),e.createElement("div",{className:g.buttons},p&&s&&e.createElement(N.zx,{disabled:H,size:"xs",variant:"secondary",type:"button",onClick:()=>L(),icon:H?"fa fa-spinner":"message"},"Test"),u&&e.createElement(e.Fragment,null,e.createElement(N.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"copy"},"Duplicate"),a&&e.createElement(N.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"trash-alt"},"Delete")))),w&&e.createElement("div",{className:g.innerContent},e.createElement(ut,{defaultValues:t,selectedChannelOptions:v?.length?v:$,secureFields:U,errors:d,onResetSecureField:oe,pathPrefix:n,readOnly:!u}),!!(v?.length&&$?.length)&&e.createElement(Le,{label:`Optional ${w.name} settings`},w.info!==""&&e.createElement(W.b,{title:"",severity:"info"},w.info),e.createElement(ut,{defaultValues:t,selectedChannelOptions:$,secureFields:U,onResetSecureField:oe,errors:d,pathPrefix:n,readOnly:!u})),e.createElement(Le,{label:"Notification settings"},e.createElement(f,{pathPrefix:n,readOnly:!u}))))}const na=t=>({buttons:i.css`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,innerContent:i.css`
    max-width: 536px;
  `,wrapper:i.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:i.css`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  `,channelSettingsHeader:i.css`
    margin-top: ${t.spacing(2)};
  `});function aa({pathPrefix:t}){const{register:n}=(0,K.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function ra(t){if(t)return{...t,items:t.items.map(n=>({...n,settings:{...n.settings,http_config:n.settings?.http_config?sa(n.settings?.http_config):void 0}}))}}function sa(t){return oa(t)?t:{...(0,te.omit)(t,"authorization"),bearer_token:t.authorization.credentials,bearer_token_file:t.authorization.credentials_file}}function oa(t){return["bearer_token","bearer_token_file"].some(n=>n in t)}function pt({config:t,initialValues:n,defaultItem:r,notifiers:a,alertManagerSourceName:s,onSubmit:c,onTestChannel:d,takenReceiverNames:m,commonSettingsComponent:f,isEditable:u,isTestable:p}){const g=(0,Fn.iG)(),h=(0,E.wW)(la),C=ra(n)??{name:"",items:[{...r,__id:String(Math.random())}]},R=(0,K.cI)({defaultValues:JSON.parse(JSON.stringify(C))});(0,we.x)(v=>v.unifiedAlerting.saveAMConfig=Ce.oq);const{loading:O}=(0,ce._)(v=>v.saveAMConfig),{handleSubmit:y,register:x,formState:{errors:j},getValues:H}=R,{fields:U,append:se,remove:oe}=ot({name:"items",formAPI:R,softDelete:!0}),pe=(0,e.useCallback)(v=>m.map($=>$.trim().toLowerCase()).includes(v.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[m]),L=v=>{c({...v,items:v.items.filter($=>!$.__deleted)})},w=()=>{g.error("There are errors in the form. Please correct them and try again!")};return e.createElement(K.RV,{...R},!t.alertmanager_config.route&&e.createElement(W.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:y(L,w)},e.createElement("h4",{className:h.heading},u?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(ie.g,{label:"Name",invalid:!!j.name,error:j.name&&j.name.message,required:!0},e.createElement(fe.I,{readOnly:!u,id:"name",...x("name",{required:"Name is required",validate:{nameIsAvailable:pe}}),width:39,placeholder:"Name"})),U.map((v,$)=>{const q=`items.${$}.`;if(v.__deleted)return e.createElement(aa,{key:v.__id,pathPrefix:q});const k=n?.items.find(({__id:z})=>z===v.__id);return e.createElement(ta,{defaultValues:v,key:v.__id,onDuplicate:()=>{const z=H().items[$];se({...z,__id:String(Math.random())})},onTest:d?()=>{const z=H().items[$];d(z)}:void 0,onDelete:()=>oe($),pathPrefix:q,notifiers:a,secureFields:k?.secureFields,errors:j?.items?.[$],commonSettingsComponent:f,isEditable:u,isTestable:p})}),e.createElement(e.Fragment,null,u&&e.createElement(N.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>se({...r,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:h.buttons},u&&e.createElement(e.Fragment,null,O&&e.createElement(N.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!O&&e.createElement(N.zx,{type:"submit"},"Save contact point")),e.createElement(N.Qj,{disabled:O,variant:"secondary","data-testid":"cancel-button",href:(0,ee.eQ)("alerting/notifications",s)},"Cancel")))))}const la=t=>({heading:i.css`
    margin: ${t.spacing(4,0)};
  `,buttons:i.css`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),gt=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),ft=({existing:t,alertManagerSourceName:n,config:r})=>{const a=(0,F.useDispatch)(),s=(0,X.RY)(n),[c]=(0,e.useMemo)(()=>t?Mn(t,nt):[void 0,{}],[t]),d=u=>{const p=kn(u,gt);a((0,re.mM)({newConfig:at(r,p,t?.name),oldConfig:r,alertManagerSourceName:n,successMessage:t?"Contact point updated.":"Contact point created.",redirectPath:"/alerting/notifications"}))},m=(0,e.useMemo)(()=>r.alertmanager_config.receivers?.map(({name:u})=>u).filter(u=>u!==t?.name)??[],[r,t]),f=!(0,X.RY)(n);return e.createElement(e.Fragment,null,!s&&e.createElement(W.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(pt,{isEditable:f,isTestable:f,config:r,onSubmit:d,initialValues:c,notifiers:nt,alertManagerSourceName:n,defaultItem:gt,takenReceiverNames:m,commonSettingsComponent:Vn}))},ia=({pathPrefix:t,className:n,readOnly:r=!1})=>{const{register:a}=(0,K.Gc)();return e.createElement("div",{className:n},e.createElement(ie.g,null,e.createElement(Ie.X,{...a(`${t}disableResolveMessage`),label:"Disable resolved message",description:"Disable the resolve message [OK] that is sent when alerting state returns to false",disabled:r})))};var ca=l(64353),ht=(t=>(t.predefined="Predefined",t.custom="Custom",t))(ht||{});const da=Object.values(ht).map(t=>({label:t,value:t})),ma={annotations:[{key:"",value:""}],labels:[{key:"",value:""}]},ua=({isOpen:t,onDismiss:n,onTest:r})=>{const[a,s]=(0,e.useState)("Predefined"),c=(0,E.wW)(pa),d=(0,K.cI)({defaultValues:ma,mode:"onBlur"}),m=f=>{if(a==="Custom"){const u={annotations:f.annotations.filter(({key:p,value:g})=>!!p&&!!g).reduce((p,{key:g,value:h})=>({...p,[g]:h}),{}),labels:f.labels.filter(({key:p,value:g})=>!!p&&!!g).reduce((p,{key:g,value:h})=>({...p,[g]:h}),{})};r(u)}else r()};return e.createElement(de.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:c.section},e.createElement(ca._,null,"Notification message"),e.createElement(je.S,{options:da,value:a,onChange:f=>s(f)})),e.createElement(K.RV,{...d},e.createElement("form",{onSubmit:d.handleSubmit(m)},a==="Predefined"&&e.createElement("div",{className:c.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."),a==="Custom"&&e.createElement(e.Fragment,null,e.createElement("div",{className:c.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:c.section},e.createElement(He.Z,null)),e.createElement("div",{className:c.section},e.createElement(Je.Z,null))),e.createElement(de.u.ButtonRow,null,e.createElement(N.zx,{type:"submit"},"Send test notification")))))},pa=t=>({flexRow:i.css`
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: ${t.spacing(1)};
  `,section:i.css`
    margin-bottom: ${t.spacing(2)};
  `}),Me=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),Et=({existing:t,alertManagerSourceName:n,config:r})=>{const a=(0,ce._)(y=>y.grafanaNotifiers),[s,c]=(0,e.useState)(),d=(0,F.useDispatch)();(0,e.useEffect)(()=>{a.result||a.loading||d((0,re.Vj)())},[a,d]);const[m,f]=(0,e.useMemo)(()=>!t||!a.result?[void 0,{}]:Ln(t,a.result),[t,a.result]),u=y=>{const x=$n(y,f,Me);d((0,re.mM)({newConfig:at(r,x,t?.name),oldConfig:r,alertManagerSourceName:X.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},p=y=>{c(y)},g=y=>{if(s){const x=f[s.__id],j=st(s,Me,"test",x),H={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[j]}],alert:y};d((0,re.D8)(H))}},h=(0,e.useMemo)(()=>r.alertmanager_config.receivers?.map(({name:y})=>y).filter(y=>y!==t?.name)??[],[r,t]),b=t?(t.grafana_managed_receiver_configs??[]).some(y=>Boolean(y.provenance)):!1,C=!(0,X.RY)(n),R=C&&!b,O=C||b;return a.result?e.createElement(e.Fragment,null,b&&e.createElement(he.Xq,{resource:he.Uv.ContactPoint}),e.createElement(pt,{isEditable:R,isTestable:O,config:r,onSubmit:u,initialValues:m,onTestChannel:p,notifiers:a.result,alertManagerSourceName:n,defaultItem:Me,takenReceiverNames:h,commonSettingsComponent:ia}),e.createElement(ua,{onDismiss:()=>c(void 0),isOpen:!!s,onTest:y=>g(y)})):e.createElement(V.u,{text:"Loading notifiers..."})},ga=({config:t,receiverName:n,alertManagerSourceName:r})=>{const a=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return a?r===X.GC?e.createElement(Et,{config:t,alertManagerSourceName:r,existing:a}):e.createElement(ft,{config:t,alertManagerSourceName:r,existing:a}):e.createElement(W.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},fa=({config:t,templateName:n,alertManagerSourceName:r})=>{const a=t.template_files?.[n],s=t.template_file_provenances?.[n];return a?e.createElement(Oe,{alertManagerSourceName:r,config:t,existing:{name:n,content:a},provenance:s}):e.createElement(W.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var yt=l(52081);const vt={smtp_require_tls:!0},ha=({config:t,alertManagerSourceName:n})=>{const r=(0,F.useDispatch)();(0,we.x)(p=>p.unifiedAlerting.saveAMConfig=Ce.oq);const{loading:a,error:s}=(0,ce._)(p=>p.saveAMConfig),c=(0,X.RY)(n),d=(0,K.cI)({defaultValues:JSON.parse(JSON.stringify({...vt,...t.alertmanager_config.global??{}}))}),{handleSubmit:m,formState:{errors:f}}=d,u=p=>{r((0,re.mM)({newConfig:{...t,alertmanager_config:{...t.alertmanager_config,global:ve(p)}},oldConfig:t,alertManagerSourceName:n,successMessage:"Global config updated.",redirectPath:(0,ee.eQ)("/alerting/notifications",n)}))};return e.createElement(K.RV,{...d},e.createElement("form",{onSubmit:m(u)},s&&e.createElement(W.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),In.map(p=>e.createElement(Re,{readOnly:c,defaultValue:vt[p.propertyName],key:p.propertyName,option:p,error:f[p.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(yt.Lh,null,!c&&e.createElement(e.Fragment,null,a&&e.createElement(N.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!a&&e.createElement(N.zx,{type:"submit"},"Save global config")),e.createElement(N.Qj,{disabled:a,fill:"outline",variant:"secondary",href:(0,ee.eQ)("alerting/notifications",n)},"Cancel")))))},Ea=({alertManagerSourceName:t,config:n})=>t===X.GC?e.createElement(Et,{alertManagerSourceName:t,config:n}):e.createElement(ft,{alertManagerSourceName:t,config:n}),ya=({config:t,alertManagerSourceName:n})=>e.createElement(Oe,{config:t,alertManagerSourceName:n});var ue=l(51981),va=l(67483),ba=l(77258),bt=l(98102),$e=l(82002),At=l(85655),Ct=l(97953),Aa=l(20194);const Ca={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 Sa(t,n){return t.grafana_managed_receiver_configs?Ra(t.grafana_managed_receiver_configs??[],n):Ta(t)}function Ta(t){return Object.entries(t).filter(([n])=>n!=="grafana_managed_receiver_configs"&&n.endsWith("_configs")).filter(([n,r])=>Array.isArray(r)&&!!r.length).reduce((n,[r,a])=>{const s=r.replace("_configs",""),c=Ca[s]??(0,te.capitalize)(s);return{...n,[c]:(n[c]??0)+(Array.isArray(a)?a.length:1)}},{})}function Ra(t,n){return t.map(r=>r.type).map(r=>n.find(a=>a.type===r)?.name??(0,te.capitalize)(r)).reduce((r,a)=>({...r,[a]:(r[a]??0)+1}),{})}var St=l(53731),xa=l(51947);const Tt=({className:t,title:n,description:r,addButtonLabel:a,addButtonTo:s,children:c,showButton:d=!0})=>{const m=(0,E.wW)(Pa);return e.createElement(S.Stack,{direction:"column",gap:2},e.createElement("div",{className:(0,i.cx)(m.heading,t)},e.createElement("div",null,e.createElement("h4",null,n),e.createElement("div",{className:m.description},r)),d&&e.createElement(xa.Link,{to:s},e.createElement(N.zx,{type:"button",icon:"plus"},a))),c)},Pa=t=>({heading:i.css`
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  `,description:i.css`
    color: ${t.colors.text.secondary};
  `});var ke=l(2390);const wa={[ke.W.OnCall]:"public/img/alerting/oncall_logo.svg",[ke.W.Incident]:"",[ke.W.MachineLearning]:""},Na=({grafanaAppType:t})=>{const n=(0,E.wW)(Oa);return e.createElement("div",{className:n.wrapper},e.createElement(yt.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:wa[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},Oa=t=>({wrapper:i.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 Da=l(52259);function Ia({permissions:t,alertManagerName:n,receiverName:r,onClickDeleteReceiver:a}){return e.createElement(e.Fragment,null,e.createElement(ue.q,{actions:[t.update]},e.createElement(ae.A,{"aria-label":"Edit","data-testid":"edit",to:(0,ee.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(r)}/edit`,n),tooltip:"Edit contact point",icon:"pen"})),e.createElement(ue.q,{actions:[t.delete]},e.createElement(ae.A,{onClick:()=>a(r),tooltip:"Delete contact point",icon:"trash-alt"})))}function La({permissions:t,alertManagerName:n,receiverName:r}){return e.createElement(ue.q,{actions:[t.update]},e.createElement(ae.A,{"data-testid":"view",to:(0,ee.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(r)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function Rt({errorCount:t,errorDetail:n,showErrorCount:r,tooltip:a}){const s=r?`${t} ${T()("error",t)}`:"Error",c=a??n??"Error";return e.createElement(Se.C,{color:"red",icon:"exclamation-circle",text:s,tooltip:c})}function Ma({errorsByNotifier:t,errorDetail:n,lastNotify:r}){const a=t>0,s=xe(r);return a?e.createElement(Rt,{errorCount:t,errorDetail:n,showErrorCount:!1}):s?e.createElement(e.Fragment,null,"No attempts"):e.createElement(Se.C,{color:"green",text:"OK"})}function $a({errorsByReceiver:t,someWithNoAttempt:n}){return t>0?e.createElement(Rt,{errorCount:t,showErrorCount:!0,tooltip:"Expand the contact point to see error details."}):n?e.createElement(e.Fragment,null,"No attempts"):e.createElement(Se.C,{color:"green",text:"OK"})}const ka=t=>{const n=(0,G.V)(t),r=n?.receivers??{},a=Object.keys(r).length>0;return{contactPointsState:n,errorStateAvailable:a}},xe=t=>t==="0001-01-01T00:00:00.000Z";function Wa({lastNotifyDate:t}){return xe(t)?e.createElement(e.Fragment,null,"-"):e.createElement(S.Stack,{alignItems:"center"},e.createElement("div",null,`${(0,va.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(P.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,ba.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const Ua=["","0","0ms","0s","0m","0h","0d","0w","0y"],Va=t=>Ua.includes(t);function Fa({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:a,lastNotify:s}})=>e.createElement(Ma,{errorsByNotifier:a?1:0,errorDetail:a??void 0,lastNotify:s}),size:.5},{id:"name",label:"Name",renderCell:({data:{type:a},id:s})=>e.createElement(e.Fragment,null,`${a}[${s}]`),size:1},{id:"lastNotify",label:"Last delivery attempt",renderCell:({data:{lastNotify:a}})=>e.createElement(Wa,{lastNotifyDate:a}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:a,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,xe(a)&&Va(s)?"-":s),size:1},{id:"sendResolved",label:"Send resolved",renderCell:({data:{sendResolved:a}})=>e.createElement(e.Fragment,null,String(Boolean(a))),size:1}]}const r=Object.entries(t).flatMap(a=>a[1].map((s,c)=>({id:c,data:{type:a[0],lastError:s.lastNotifyAttemptError,lastNotify:s.lastNotifyAttempt,lastNotifyDuration:s.lastNotifyAttemptDuration,sendResolved:s.sendResolved}})));return e.createElement(St.t,{items:r,cols:n()})}const Ba=({config:t,alertManagerName:n})=>{const r=(0,F.useDispatch)(),a=(0,X.RY)(n),s=(0,Ct.Ko)(n),c=(0,ce._)(y=>y.grafanaNotifiers),{contactPointsState:d,errorStateAvailable:m}=ka(n),[f,u]=(0,e.useState)(),[p,g]=(0,e.useState)(!1),h=y=>{(0,Aa.nv)(y,t)?g(!0):u(y)},b=()=>{f&&r((0,re.X4)(f,n)),u(void 0)},C=(0,Da.HU)(t.alertmanager_config.receivers??[]),R=(0,e.useMemo)(()=>C?.map(y=>({id:y.name,data:{name:y.name,types:Object.entries(Sa(y,c.result??[])).map(([x,j])=>j>1?`${x} (${j})`:x),grafanaAppReceiverType:y.grafanaAppReceiverType,provisioned:y.grafana_managed_receiver_configs?.some(x=>x.provenance)}}))??[],[c.result,C]),O=za(n,m,d,h,s,a);return e.createElement(Tt,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!a&&$e.Vt.hasPermission(s.create),addButtonLabel:"Add contact point",addButtonTo:(0,ee.eQ)("/alerting/notifications/receivers/new",n)},e.createElement(St.t,{items:R,cols:O,isExpandable:m,renderExpandedContent:m?({data:{name:y}})=>e.createElement(Fa,{notifiersState:d?.receivers[y]?.notifiers??{}}):void 0}),!!p&&e.createElement(de.u,{isOpen:!0,title:"Cannot delete contact point",onDismiss:()=>g(!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(de.u.ButtonRow,null,e.createElement(N.zx,{variant:"secondary",onClick:()=>g(!1),fill:"outline"},"Close"))),!!f&&e.createElement(bt.s,{isOpen:!0,title:"Delete contact point",body:`Are you sure you want to delete contact point "${f}"?`,confirmText:"Yes, delete",onConfirm:b,onDismiss:()=>u(void 0)}))},_a=(t,n)=>t?.receivers[n]?.errorCount??0,Ga=(t,n)=>{const r=Object.values(t?.receivers[n]?.notifiers??{});return r.length===0||r.flat().some(s=>xe(s.lastNotifyAttempt))};function za(t,n,r,a,s,c){const d=(0,E.wW)(At.D),m=[{id:"name",label:"Contact point name",renderCell:({data:{name:u,provisioned:p}})=>e.createElement(S.Stack,{alignItems:"center"},e.createElement("div",null,u),p&&e.createElement(he.C0,null)),size:1},{id:"type",label:"Type",renderCell:({data:{types:u,grafanaAppReceiverType:p}})=>e.createElement(e.Fragment,null,p?e.createElement(Na,{grafanaAppType:p}):u.join(", ")),size:1}],f={id:"health",label:"Health",renderCell:({data:{name:u}})=>r&&e.createElement($a,{errorsByReceiver:_a(r,u),someWithNoAttempt:Ga(r,u)}),size:1};return[...m,...n?[f]:[],{id:"actions",label:"Actions",renderCell:({data:{provisioned:u,name:p}})=>e.createElement(ue.q,{actions:[s.update,s.delete]},e.createElement("div",{className:d.actionsCell},!c&&!u&&e.createElement(Ia,{permissions:s,alertManagerName:t,receiverName:p,onClickDeleteReceiver:a}),(c||u)&&e.createElement(La,{permissions:s,alertManagerName:t,receiverName:p}))),size:"100px"}]}var Ka=l(80498);const ja=({config:t,alertManagerName:n})=>{const r=(0,F.useDispatch)(),[a,s]=(0,e.useState)({}),c=(0,E.wW)(At.D),d=(0,Ct.Ko)(n),m=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([h,b])=>({name:h,template:b,provenance:(t.template_file_provenances??{})[h]})),[t]),[f,u]=(0,e.useState)(),p=()=>{f&&r((0,re.S6)(f,n)),u(void 0)};return e.createElement(Tt,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,ee.eQ)("/alerting/notifications/templates/new",n),showButton:$e.Vt.hasPermission(d.create)},e.createElement("table",{className:c.table,"data-testid":"templates-table"},e.createElement("colgroup",null,e.createElement("col",{className:c.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(ue.q,{actions:[d.update,d.delete]},e.createElement("th",null,"Actions")))),e.createElement("tbody",null,!m.length&&e.createElement("tr",{className:c.evenRow},e.createElement("td",{colSpan:3},"No templates defined.")),m.map(({name:g,template:h,provenance:b},C)=>{const R=!!a[g];return e.createElement(e.Fragment,{key:g},e.createElement("tr",{key:g,className:C%2===0?c.evenRow:void 0},e.createElement("td",null,e.createElement(ct.U,{isCollapsed:!a[g],onToggle:()=>s({...a,[g]:!R})})),e.createElement("td",null,g," ",b&&e.createElement(he.C0,null)),e.createElement("td",{className:c.actionsCell},b&&e.createElement(ae.A,{to:(0,ee.eQ)(`/alerting/notifications/templates/${encodeURIComponent(g)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!b&&e.createElement(ue.q,{actions:[d.update]},e.createElement(ae.A,{to:(0,ee.eQ)(`/alerting/notifications/templates/${encodeURIComponent(g)}/edit`,n),tooltip:"edit template",icon:"pen"})),$e.Vt.hasPermission(d.create)&&e.createElement(ae.A,{to:(0,ee.eQ)(`/alerting/notifications/templates/${encodeURIComponent(g)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!b&&e.createElement(ue.q,{actions:[d.delete]},e.createElement(ae.A,{onClick:()=>u(g),tooltip:"delete template",icon:"trash-alt"})))),R&&e.createElement("tr",{className:C%2===0?c.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(Ka.C,{label:"Description",horizontal:!0},e.createElement(Xe,{width:"auto",height:"auto",autoHeight:!0,value:h,showLineNumbers:!1,monacoOptions:{readOnly:!0,scrollBeyondLastLine:!1}})))))}))),!!f&&e.createElement(bt.s,{isOpen:!0,title:"Delete template",body:`Are you sure you want to delete template "${f}"?`,confirmText:"Yes, delete",onConfirm:p,onDismiss:()=>u(void 0)}))},Ha=({config:t,alertManagerName:n})=>{const r=n!==X.GC,a=(0,X.RY)(n);return e.createElement(S.Stack,{direction:"column",gap:4},e.createElement(Ba,{config:t,alertManagerName:n}),!a&&e.createElement(ja,{config:t,alertManagerName:n}),r&&e.createElement(ue.q,{actions:[F.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(W.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(N.Qj,{href:(0,ee.eQ)("alerting/notifications/global-config",n),variant:"secondary"},a?"View global config":"Edit global config"))))};var Ja=l(29614),Qa=l(23403);function Ya({errorCount:t}){const n=(0,E.wW)(xt);return e.createElement("div",{className:n.error,"data-testid":"receivers-notification-error"},e.createElement(S.Stack,{alignItems:"flex-end",direction:"column",gap:0},e.createElement(S.Stack,{alignItems:"center",gap:1},e.createElement(P.J,{name:"exclamation-circle"}),e.createElement("div",null,`${t} ${T()("error",t)} with contact points`)),e.createElement("div",null,"Some alert notifications might not be delivered")))}const Za=()=>{const t=(0,Qa.k)("notification"),[n,r]=(0,Ja.k)(t),a=(0,F.useDispatch)(),s=(0,E.wW)(xt),{id:c,type:d}=(0,A.UO)(),m=(0,A.TH)(),f=m.pathname.endsWith("/alerting/notifications"),u=qe(m),p=(0,ce._)(U=>U.amConfigs),{result:g,loading:h,error:b}=n&&p[n]||Ce.oq,C=(0,ce._)(U=>U.grafanaNotifiers),R=f||!g,O=f;(0,e.useEffect)(()=>{n&&R&&a((0,re.Yh)(n))},[n,a,R]),(0,e.useEffect)(()=>{n===X.GC&&!(C.result||C.loading||C.error)&&a((0,re.Vj)())},[n,a,C]);const x=(0,G.V)(n??"")?.errorCount??0,j=!f;let H=Xa(d,c?decodeURIComponent(c):void 0,u);return n?e.createElement(B.J,{pageId:"receivers",pageNav:H},e.createElement("div",{className:s.headingContainer},e.createElement(I.P,{current:n,disabled:j,onChange:r,dataSources:t}),O&&x>0&&e.createElement(Ya,{errorCount:x})),b&&!h&&e.createElement(W.b,{severity:"error",title:"Error loading Alertmanager config"},b.message||"Unknown error."),e.createElement(Y.u,{currentAlertmanager:n}),h&&!g&&e.createElement(V.u,{text:"loading configuration..."}),g&&!b&&e.createElement(A.rs,null,e.createElement(A.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(Ha,{config:g,alertManagerName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(ya,{config:g,alertManagerSourceName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:U})=>U?.params.name&&e.createElement(On,{alertManagerSourceName:n,config:g,templateName:decodeURIComponent(U?.params.name)})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:U})=>U?.params.name&&e.createElement(fa,{alertManagerSourceName:n,config:g,templateName:decodeURIComponent(U?.params.name)})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(Ea,{config:g,alertManagerSourceName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:U})=>U?.params.name&&e.createElement(ga,{alertManagerSourceName:n,config:g,receiverName:decodeURIComponent(U?.params.name)})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(ha,{config:g,alertManagerSourceName:n})))):f?e.createElement(B.J,{pageId:"receivers",pageNav:H},e.createElement(Z.I,{availableAlertManagers:t})):e.createElement(A.l_,{to:"/alerting/notifications"})};function Xa(t,n,r){let a;if(r)return{text:"New template",subTitle:"Create a new template for your notifications"};if(t==="receivers"||t==="templates"){const s=t==="receivers"?"contact point":"notification template";n?a={text:n,subTitle:`Edit the settings for a specific ${s}`}:a={text:`New ${s}`,subTitle:`Create a new ${s} for your notifications`}}else t==="global-config"&&(a={text:"Global config",subTitle:"Manage your global configuration"});return a}const qa=(0,_.Pf)(Za,{style:"page"}),xt=t=>({error:i.css`
    color: ${t.colors.error.text};
  `,headingContainer:i.css`
    display: flex;
    justify-content: space-between;
  `})},96678:(Q,M,l)=>{l.d(M,{V:()=>A});var i=l(37190),D=l(29427),T=l(644);const e=D.C.injectEndpoints({endpoints:S=>({contactPointsState:S.query({queryFn:async({amSourceName:E})=>{try{return{data:await(0,T.QE)(E)}}catch(P){return{error:P}}}})})}),A=S=>{const E={receivers:{},errorCount:0},{currentData:P}=e.useContactPointsStateQuery({amSourceName:S??""},{skip:!S,pollingInterval:i.m4});return P??E}},51981:(Q,M,l)=>{l.d(M,{q:()=>T});var i=l(66111),D=l(82002);const T=({actions:e,children:A,fallback:S=!0})=>e.some(E=>D.Vt.hasAccess(E,S))?i.createElement(i.Fragment,null,A):null},731:(Q,M,l)=>{l.d(M,{u:()=>P});var i=l(9892),D=l(66111),T=l(72648),e=l(45253),A=l(39031),S=l(30173),E=l(45849);function P({currentAlertmanager:V}){const _=(0,T.wW)(W),{useGetAlertmanagerChoiceStatusQuery:F}=S.h,{currentData:G}=F(),I=V===E.GC;if(!(G?.alertmanagersChoice&&[A.TE.External,A.TE.All].includes(G?.alertmanagersChoice))||!I)return null;const Y=G.numExternalAlertmanagers>0;return G.alertmanagersChoice===A.TE.External?D.createElement(e.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.",D.createElement("div",{className:_.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):G.alertmanagersChoice===A.TE.All&&Y?D.createElement(e.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.",D.createElement("div",{className:_.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const W=V=>({adminHint:i.css`
    font-size: ${V.typography.bodySmall.fontSize};
    font-weight: ${V.typography.bodySmall.fontWeight};
  `})},88331:(Q,M,l)=>{l.d(M,{I:()=>E});var i=l(66111),D=l(45253),T=l(29614),e=l(94984);const A=()=>i.createElement(D.b,{title:"No Alertmanager found",severity:"warning"},"We could not find any external Alertmanagers and you may not have access to the built-in Grafana Alertmanager."),S=()=>i.createElement(D.b,{title:"Selected Alertmanager not found. Select a different Alertmanager.",severity:"warning"},"Selected Alertmanager no longer exists or you may not have permission to access it."),E=({availableAlertManagers:P})=>{const[W,V]=(0,T.k)(P),_=P.length>0;return i.createElement("div",null,_?i.createElement(i.Fragment,null,i.createElement(e.P,{onChange:V,dataSources:P}),i.createElement(S,null)):i.createElement(A,null))}},40106:(Q,M,l)=>{l.d(M,{C0:()=>S,Uv:()=>e,Xq:()=>A});var i=l(66111),D=l(45253),T=l(19985),e=(E=>(E.ContactPoint="contact point",E.Template="template",E.MuteTiming="mute timing",E.AlertRule="alert rule",E.RootNotificationPolicy="root notification policy",E))(e||{});const A=({resource:E})=>i.createElement(D.b,{title:`This ${E} cannot be edited through the UI`,severity:"info"},"This ",E," has been provisioned, that means it was created by config. Please contact your server admin to update this ",E,"."),S=()=>i.createElement(T.C,{text:"Provisioned",color:"purple"})},52259:(Q,M,l)=>{l.d(M,{Kt:()=>F,HU:()=>G});var i=l(65583),D=l(54899),T=l(29427);const e=T.C.injectEndpoints({endpoints:I=>({getOnCallIntegrations:I.query({queryFn:async()=>({data:await A()})})})});async function A(){try{return(await(0,i.n)((0,D.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(B=>B.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:S}=e;var E=l(58509),P=l(2390);const W=(I,B)=>B.includes(I),V=(I,B)=>{if(!I.grafana_managed_receiver_configs)return!1;const Y=I.grafana_managed_receiver_configs.length===1,Z=W(I.grafana_managed_receiver_configs[0]?.settings?.url??"",B);return Y&&Z},_=()=>{const{installed:I}=(0,E.n)(P.W.OnCall),{data:B}=S(void 0,{skip:!I});return Z=>{if(I&&V(Z,B??[]))return P.W.OnCall}},F=I=>{const B=_(),Y=Z=>({label:Z.name,value:Z.name,grafanaAppReceiverType:B(Z)});return I.map(Y)},G=I=>{const B=_();return I.map(Y=>({...Y,grafanaAppReceiverType:B(Y)}))}},65750:(Q,M,l)=>{l.d(M,{A:()=>e});var i=l(66111),D=l(61860),T=l(31403);const e=({tooltip:A,icon:S,to:E,target:P,onClick:W,className:V,tooltipPlacement:_="top",...F})=>{const G=typeof A=="string"?A:void 0;return i.createElement(D.u,{content:A,placement:_},E?i.createElement(T.Qj,{variant:"secondary",fill:"text",icon:S,href:E,size:"sm",target:P,...F,"aria-label":G}):i.createElement(T.zx,{className:V,variant:"secondary",fill:"text",size:"sm",icon:S,type:"button",onClick:W,...F,"aria-label":G}))}},38645:(Q,M,l)=>{l.d(M,{r:()=>T,z:()=>e});var i=l(82897),D=l.n(i);function T(A,S){return A.filter(E=>!S.find(P=>JSON.stringify(P)===JSON.stringify(E)))}function e(A){const S=A.flatMap(P=>P);return(0,i.uniqBy)(S.filter(P=>S.filter(V=>(0,i.isEqual)(P,V)).length===Object.keys(A).length),P=>JSON.stringify(P))}},29614:(Q,M,l)=>{l.d(M,{k:()=>E});var i=l(66111),D=l(96044),T=l(58379),e=l(37190),A=l(45849);function S(P){return(0,i.useCallback)(W=>P.map(_=>_.name).includes(W),[P])}function E(P){const[W,V]=(0,D.K)(),_=S(P),F=(0,i.useCallback)(B=>{_(B)&&(B===A.GC?(T.Z.delete(e.de),V({[e.c4]:null})):(T.Z.set(e.de,B),V({[e.c4]:B})))},[V,_]),G=W[e.c4];if(G&&typeof G=="string")return _(G)?[G,F]:[void 0,F];const I=T.Z.get(e.de);return I&&typeof I=="string"&&_(I)?(F(I),[I,F]):_(A.GC)?[A.GC,F]:[void 0,F]}},23403:(Q,M,l)=>{l.d(M,{k:()=>T});var i=l(66111),D=l(45849);function T(e){return(0,i.useMemo)(()=>(0,D.LE)(e),[e])}},85655:(Q,M,l)=>{l.d(M,{D:()=>D});var i=l(9892);const D=T=>({table:i.css`
    width: 100%;
    border-radius: ${T.shape.borderRadius()};
    border: solid 1px ${T.colors.border.weak};
    background-color: ${T.colors.background.secondary};

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

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

    tr {
      height: 38px;
    }
  `,evenRow:i.css`
    background-color: ${T.colors.background.primary};
  `,colExpand:i.css`
    width: 36px;
  `,actionsCell:i.css`
    text-align: right;
    width: 1%;
    white-space: nowrap;

    & > * + * {
      margin-left: ${T.spacing(.5)};
    }
  `})},35918:(Q,M,l)=>{l.d(M,{G:()=>i});function i(D,T){const e=D.replace(/\(copy( [0-9]+)?\)$/,"").trim();let A=`${e} (copy)`;for(let S=2;T.includes(A);S++)A=`${e} (copy ${S})`;return A}}}]);

//# sourceMappingURL=NotificationsListPage.fb1c2bae6997bab62fc0.js.map