"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 X=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:()=>{X(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:()=>tr});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),X=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,X.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var be=l(88948),wt=l(29122),Nt=l(15348);function Ue(t,n){(0,wt.Z)(2,arguments);var r=(0,Nt.Z)(n);return(0,be.Z)(t,-r)}var K=l(66698),Ae=l(89050),Ot=l(13393),ie=l(24799),fe=l(46967),Dt=l(72142),Ve=l(79841),N=l(31403),It=l(20941),Lt=l(67487),we=l(40014),Mt=l(29427);const $t="/api/alertmanager/grafana/config/api/v1/templates/test",kt=Mt.C.injectEndpoints({endpoints:t=>({previewTemplate:t.mutation({query:({template:n,alerts:r,name:a})=>({url:$t,data:{template:n,alerts:r,name:a},method:"POST"})})})}),{usePreviewTemplateMutation:Wt}=kt;var ce=l(69945),re=l(72004),q=l(45849),te=l(10505),Ce=l(46818),he=l(40106),Fe=l(61860),Be=l(9405),Se=l(19985),_e=l(32436),Ut=l(34719),de=l(35029),Vt=l(14747),Ft=l(30173),Ee=l(61893),Ge=l(38645);function Bt({onSelect:t,isOpen:n,onClose:r}){const a=(0,E.wW)(_t),[s,c]=(0,e.useState)(),[d,m]=(0,e.useState)(null),{useGetAlertmanagerAlertsQuery:f}=Ft.h,{currentData:u=[],isFetching:p,isError:g}=f({amSourceName:q.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),ee=(0,Ge.z)($),k=(0,Ge.r)((0,Ee.cH)(w.labels),ee);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],ee=d?.includes($),k=(0,e.useMemo)(()=>j(v,$),[v,$]),z=()=>{if(ee&&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]:ee}),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(Ut.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(Vt.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 _t=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;
    `}},Gt=[{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."}],zt=[{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."}],Kt=[{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."}],jt=[{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"}],Ht=`{
  "summary": "alert summary",
  "description": "alert description"
}
`;var ze=l(42042);function Jt(){const t=(0,E.wW)(Qt),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:Kt});return e.createElement(S.Stack,{gap:2,flexGrow:1},e.createElement(Ne,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:Gt,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(Yt,null)},e.createElement("div",{className:t.interactiveType},r)):r}))}const Qt=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 Yt(){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,Ht)),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,jt.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 Zt=l(72948),je=l(2594),He=l(16808),Je=l(19191);const Xt={annotations:[{key:"",value:""}],labels:[{key:"",value:""}],status:"firing"},qt=({isOpen:t,onDismiss:n,onAccept:r})=>{const a=(0,E.wW)(en),[s,c]=(0,e.useState)([]),d=(0,K.cI)({defaultValues:Xt,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(Zt.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"))))))},en=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;
  `}),tn="Reset to default";function nn({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(an,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"},tn),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(qt,{isOpen:f,onDismiss:p,onAccept:R}),e.createElement(Bt,{onSelect:R,isOpen:O,onClose:()=>y(!1)}))}const an=()=>{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:zt})},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 rn(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 sn=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,on=`
[{{.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 }}
`,ln=ye("GroupLabels"),cn=ye("CommonLabels"),dn=ye("CommonAnnotations"),mn=ye("Labels"),un=ye("Annotations");function ye(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function pn(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 gn(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 fn(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function hn(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:sn},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:on},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:ln},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:cn},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:dn},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:mn},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:un}};function En(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 yn(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 bn(t,d);if(!vn(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 vn(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 bn{constructor(n,r){this.monaco=n,this.range=r,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(En(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(rn(this.monaco)),this.getTemplateDataSuggestions=a=>{switch(a){case"":return this.getCompletionsFromDefinitions(pn(this.monaco),gn(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(fn(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(hn(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...a)=>({suggestions:(0,X.concat)(...a).map(c=>An(c,this.range))})}}function An({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",Cn={id:Ze,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(l.bind(l,68402))},Sn=(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=>{Sn(s,Cn),r.current=yn(s)},language:Ze})},Tn=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),ee={...r.template_files,[v.name]:$};t&&t.name!==v.name&&delete ee[t.name];const k=[...(r.alertmanager_config.templates??[]).filter(le=>le!==t?.name),v.name],z={template_files:ee,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??Tn}),{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===q.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(Ot.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(Rn,null),e.createElement("div",{className:s.editorsWrapper},e.createElement("div",{className:s.contentContainer},e.createElement(Dt.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,te.eQ)("alerting/notifications",n),variant:"secondary",type:"button"},"Cancel"))):e.createElement(On,{width:v,payload:p,templateName:pe("name"),setPayloadFormatError:b,payloadFormatError:h}))))),w&&e.createElement(nn,{payload:p,setPayload:g,defaultPayload:et,setPayloadFormatError:b,payloadFormatError:h,onPayloadError:O}))),e.createElement(It.s,{label:"Data cheat sheet",isOpen:!1,className:s.collapsableSection},e.createElement(Jt,null))))};function Rn(){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 xn(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 Pn(t){return t.map(n=>n.name?`ERROR in ${n.name}:
`.concat(`${n.kind}
${n.message}
`):`ERROR:
${n.kind}
${n.message}
`).join(`
`)}const wn="Preview request failed. Check if the payload data has the correct structure.";function Nn(t,n,r){const a=t?wn:void 0,s=t||Boolean(n),c=n||a,d=r?.results,m=r?.errors,f=d?xn(d):"",u=m?Pn(m):"";return s?c:`${f}
${u}`}function On({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}]=Wt(),h=Nn(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(Lt.$,{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)};
  `}),Dn=({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 In=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."),In,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" . }}'})]}],Ln=[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 Mn(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 Vn(d,c,m)})??[]},r]}function $n(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 Un(u,d,f)})).flat();return[{name:t.name,items:s},r]}function kn(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 Wn(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 Un(t,n,r){return{__id:t,type:n,settings:{...r},secureFields:{},secureSettings:{},sendResolved:r.send_resolved}}function Vn(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:Fn(t.secureSettings,a?.secureFields),type:t.type,name:r,disableResolveMessage:t.disableResolveMessage??a?.disableResolveMessage??n.disableResolveMessage};return a&&(s.uid=a.uid),s}const ot=t=>(0,X.isNil)(t)||t==="";function ve(t){return(0,X.isArray)(t)?t.forEach(ve):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,r])=>{ot(r)?delete t[n]:ve(r)}),t}function Fn(t={},n={}){return(0,X.omitBy)(t,(r,a)=>ot(r)&&!(a in n))}var Ie=l(58255);const Bn=({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 _n=l(60499);const Gn=[];function lt(t){const{name:n,formAPI:r,defaults:a,softDelete:s}=t,{watch:c,getValues:d,reset:m,setValue:f}=r,u=c(n)??a??Gn,p=(0,e.useCallback)(g=>{const h=JSON.parse(JSON.stringify(d())),b=g(u??[]);m((0,X.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),it=l(8581),zn=l(97379),ae=l(65750);const Kn=({value:t,onChange:n,readOnly:r=!1})=>{const a=(0,E.wW)(jn),[s,c]=(0,e.useState)(ct(t));(0,e.useEffect)(()=>c(ct(t)),[t]);const d=u=>{n(Hn(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"))},jn=t=>({addButton:i.css`
    margin-top: ${t.spacing(1)};
  `,table:i.css`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),Hn=t=>{const n={};for(const[r,a]of t)r&&(n[r]=a);return n},ct=t=>Object.entries(t??{}),Jn=({value:t,onChange:n,readOnly:r=!1})=>{const a=(0,E.wW)(Qn),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"))},Qn=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 dt=l(33950);const Le=({label:t,description:n,children:r,className:a,size:s="xl"})=>{const c=(0,E.wW)(Yn),[d,m]=(0,e.useState)(!0),f=()=>m(!d);return e.createElement("div",{className:(0,i.cx)(c.wrapper,a)},e.createElement(dt.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))},Yn=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)};
  `}),mt=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)};
  `}),Zn=({option:t,pathPrefix:n,errors:r,defaultValues:a,readOnly:s=!1})=>{const c=(0,E.wW)(mt),d=`${n}${t.propertyName}`,m=(0,K.Gc)(),{fields:f,append:u,remove:p}=lt({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")))},Xn=({option:t,pathPrefix:n,errors:r,defaultValue:a,readOnly:s=!1})=>{const c=(0,E.wW)(mt),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(Xn,{readOnly:d,defaultValue:c,option:t,errors:s,pathPrefix:m}):t.element==="subform_array"?e.createElement(Zn,{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(qn,{id:`${m}${t.propertyName}`,defaultValue:c,option:t,invalid:n,pathPrefix:m,readOnly:d,pathIndex:r}))},qn=({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:ea.checkbox,...m(p),label:t.label,description:t.description});case"input":return e.createElement(fe.I,{id:r,readOnly:c||na(t,u,s),invalid:n,type:t.inputType,...m(p,{required:ta(t,u,s),validate:g=>t.validationRule!==""?ut(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(it.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(zn.K,{id:r,readOnly:c,invalid:n,placeholder:t.placeholder,...m(p,{required:t.required?"Required":!1,validate:g=>t.validationRule!==""?ut(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(Kn,{readOnly:c,value:g,onChange:h}),control:d,name:p});default:return console.error("Element not supported",t.element),null}},ea={checkbox:i.css`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},ut=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",ta=(t,n,r)=>{if(!t.dependsOn)return t.required?"Required":!1;if((0,X.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},na=(t,n,r)=>t.dependsOn?(0,X.isEmpty)(n(`${r}secureFields`))?n(`${r}secureSettings.${t.dependsOn}`):n(`${r}secureFields.${t.dependsOn}`):!1;function pt({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 aa({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)(ra),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),ee=`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:ee,"data-testid":`${n}type`},e.createElement(Te.g,{name:h("type"),defaultValue:t.type,render:({field:{ref:k,onChange:z,...le}})=>e.createElement(it.Ph,{disabled:!u,inputId:ee,...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(pt,{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(pt,{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 ra=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 sa({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 oa(t){if(t)return{...t,items:t.items.map(n=>({...n,settings:{...n.settings,http_config:n.settings?.http_config?la(n.settings?.http_config):void 0}}))}}function la(t){return ia(t)?t:{...(0,X.omit)(t,"authorization"),bearer_token:t.authorization?.credentials,bearer_token_file:t.authorization?.credentials_file}}function ia(t){return["bearer_token","bearer_token_file"].some(n=>n in t)}function gt({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,_n.iG)(),h=(0,E.wW)(ca),C=oa(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}=lt({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 ee=`items.${$}.`;if(v.__deleted)return e.createElement(sa,{key:v.__id,pathPrefix:ee});const k=n?.items.find(({__id:z})=>z===v.__id);return e.createElement(aa,{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:ee,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,te.eQ)("alerting/notifications",s)},"Cancel")))))}const ca=t=>({heading:i.css`
    margin: ${t.spacing(4,0)};
  `,buttons:i.css`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),ft=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),ht=({existing:t,alertManagerSourceName:n,config:r})=>{const a=(0,F.useDispatch)(),s=(0,q.RY)(n),[c]=(0,e.useMemo)(()=>t?$n(t,nt):[void 0,{}],[t]),d=u=>{const p=Wn(u,ft);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,q.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(gt,{isEditable:f,isTestable:f,config:r,onSubmit:d,initialValues:c,notifiers:nt,alertManagerSourceName:n,defaultItem:ft,takenReceiverNames:m,commonSettingsComponent:Bn}))},da=({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 ma=l(64353),Et=(t=>(t.predefined="Predefined",t.custom="Custom",t))(Et||{});const ua=Object.values(Et).map(t=>({label:t,value:t})),pa={annotations:[{key:"",value:""}],labels:[{key:"",value:""}]},ga=({isOpen:t,onDismiss:n,onTest:r})=>{const[a,s]=(0,e.useState)("Predefined"),c=(0,E.wW)(fa),d=(0,K.cI)({defaultValues:pa,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(ma._,null,"Notification message"),e.createElement(je.S,{options:ua,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")))))},fa=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"}),yt=({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,{}]:Mn(t,a.result),[t,a.result]),u=y=>{const x=kn(y,f,Me);d((0,re.mM)({newConfig:at(r,x,t?.name),oldConfig:r,alertManagerSourceName:q.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,q.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(gt,{isEditable:R,isTestable:O,config:r,onSubmit:u,initialValues:m,onTestChannel:p,notifiers:a.result,alertManagerSourceName:n,defaultItem:Me,takenReceiverNames:h,commonSettingsComponent:da}),e.createElement(ga,{onDismiss:()=>c(void 0),isOpen:!!s,onTest:y=>g(y)})):e.createElement(V.u,{text:"Loading notifiers..."})},ha=({config:t,receiverName:n,alertManagerSourceName:r})=>{const a=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return a?r===q.GC?e.createElement(yt,{config:t,alertManagerSourceName:r,existing:a}):e.createElement(ht,{config:t,alertManagerSourceName:r,existing:a}):e.createElement(W.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},Ea=({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 vt=l(52081);const bt={smtp_require_tls:!0},ya=({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,q.RY)(n),d=(0,K.cI)({defaultValues:JSON.parse(JSON.stringify({...bt,...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,te.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)),Ln.map(p=>e.createElement(Re,{readOnly:c,defaultValue:bt[p.propertyName],key:p.propertyName,option:p,error:f[p.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(vt.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,te.eQ)("alerting/notifications",n)},"Cancel")))))},va=({alertManagerSourceName:t,config:n})=>t===q.GC?e.createElement(yt,{alertManagerSourceName:t,config:n}):e.createElement(ht,{alertManagerSourceName:t,config:n}),ba=({config:t,alertManagerSourceName:n})=>e.createElement(Oe,{config:t,alertManagerSourceName:n});var ue=l(51981),Aa=l(67483),Ca=l(77258),At=l(98102),$e=l(82002),Ct=l(85655),St=l(97953),Sa=l(20194);const Ta={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 Ra(t,n){return t.grafana_managed_receiver_configs?Pa(t.grafana_managed_receiver_configs??[],n):xa(t)}function xa(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=Ta[s]??(0,X.capitalize)(s);return{...n,[c]:(n[c]??0)+(Array.isArray(a)?a.length:1)}},{})}function Pa(t,n){return t.map(r=>r.type).map(r=>n.find(a=>a.type===r)?.name??(0,X.capitalize)(r)).reduce((r,a)=>({...r,[a]:(r[a]??0)+1}),{})}var Tt=l(53731),wa=l(51947);const Rt=({className:t,title:n,description:r,addButtonLabel:a,addButtonTo:s,children:c,showButton:d=!0})=>{const m=(0,E.wW)(Na);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(wa.Link,{to:s},e.createElement(N.zx,{type:"button",icon:"plus"},a))),c)},Na=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 Oa={[ke.W.OnCall]:"public/img/alerting/oncall_logo.svg",[ke.W.Incident]:"",[ke.W.MachineLearning]:""},Da=({grafanaAppType:t})=>{const n=(0,E.wW)(Ia);return e.createElement("div",{className:n.wrapper},e.createElement(vt.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:Oa[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},Ia=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 La=l(52259);function Ma({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,te.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 $a({permissions:t,alertManagerName:n,receiverName:r}){return e.createElement(ue.q,{actions:[t.update]},e.createElement(ae.A,{"data-testid":"view",to:(0,te.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(r)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function xt({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 ka({errorsByNotifier:t,errorDetail:n,lastNotify:r}){const a=t>0,s=xe(r);return a?e.createElement(xt,{errorCount:t,errorDetail:n,showErrorCount:!1}):s?e.createElement(e.Fragment,null,"No attempts"):e.createElement(Se.C,{color:"green",text:"OK"})}function Wa({errorsByReceiver:t,someWithNoAttempt:n}){return t>0?e.createElement(xt,{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 Ua=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 Va({lastNotifyDate:t}){return xe(t)?e.createElement(e.Fragment,null,"-"):e.createElement(S.Stack,{alignItems:"center"},e.createElement("div",null,`${(0,Aa.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(P.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,Ca.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const Fa=["","0","0ms","0s","0m","0h","0d","0w","0y"],Ba=t=>Fa.includes(t);function _a({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:a,lastNotify:s}})=>e.createElement(ka,{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(Va,{lastNotifyDate:a}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:a,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,xe(a)&&Ba(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(Tt.t,{items:r,cols:n()})}const Ga=({config:t,alertManagerName:n})=>{const r=(0,F.useDispatch)(),a=(0,q.RY)(n),s=(0,St.Ko)(n),c=(0,ce._)(y=>y.grafanaNotifiers),{contactPointsState:d,errorStateAvailable:m}=Ua(n),[f,u]=(0,e.useState)(),[p,g]=(0,e.useState)(!1),h=y=>{(0,Sa.nv)(y,t)?g(!0):u(y)},b=()=>{f&&r((0,re.X4)(f,n)),u(void 0)},C=(0,La.HU)(t.alertmanager_config.receivers??[]),R=(0,e.useMemo)(()=>C?.map(y=>({id:y.name,data:{name:y.name,types:Object.entries(Ra(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=ja(n,m,d,h,s,a);return e.createElement(Rt,{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,te.eQ)("/alerting/notifications/receivers/new",n)},e.createElement(Tt.t,{items:R,cols:O,isExpandable:m,renderExpandedContent:m?({data:{name:y}})=>e.createElement(_a,{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(At.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)}))},za=(t,n)=>t?.receivers[n]?.errorCount??0,Ka=(t,n)=>{const r=Object.values(t?.receivers[n]?.notifiers??{});return r.length===0||r.flat().some(s=>xe(s.lastNotifyAttempt))};function ja(t,n,r,a,s,c){const d=(0,E.wW)(Ct.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(Da,{grafanaAppType:p}):u.join(", ")),size:1}],f={id:"health",label:"Health",renderCell:({data:{name:u}})=>r&&e.createElement(Wa,{errorsByReceiver:za(r,u),someWithNoAttempt:Ka(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(Ma,{permissions:s,alertManagerName:t,receiverName:p,onClickDeleteReceiver:a}),(c||u)&&e.createElement($a,{permissions:s,alertManagerName:t,receiverName:p}))),size:"100px"}]}var Ha=l(80498);const Ja=({config:t,alertManagerName:n})=>{const r=(0,F.useDispatch)(),[a,s]=(0,e.useState)({}),c=(0,E.wW)(Ct.D),d=(0,St.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(Rt,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,te.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(dt.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,te.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,te.eQ)(`/alerting/notifications/templates/${encodeURIComponent(g)}/edit`,n),tooltip:"edit template",icon:"pen"})),$e.Vt.hasPermission(d.create)&&e.createElement(ae.A,{to:(0,te.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(Ha.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(At.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)}))},Qa=({config:t,alertManagerName:n})=>{const r=n!==q.GC,a=(0,q.RY)(n);return e.createElement(S.Stack,{direction:"column",gap:4},e.createElement(Ga,{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,te.eQ)("alerting/notifications/global-config",n),variant:"secondary"},a?"View global config":"Edit global config"))))};var Ya=l(29614),Za=l(23403);function Xa({errorCount:t}){const n=(0,E.wW)(Pt);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 qa=()=>{const t=(0,Za.k)("notification"),[n,r]=(0,Ya.k)(t),a=(0,F.useDispatch)(),s=(0,E.wW)(Pt),{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===q.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=er(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(Xa,{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(Qa,{config:g,alertManagerName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(ba,{config:g,alertManagerSourceName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:U})=>U?.params.name&&e.createElement(Dn,{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(Ea,{alertManagerSourceName:n,config:g,templateName:decodeURIComponent(U?.params.name)})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(va,{config:g,alertManagerSourceName:n})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:U})=>U?.params.name&&e.createElement(ha,{alertManagerSourceName:n,config:g,receiverName:decodeURIComponent(U?.params.name)})),e.createElement(A.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(ya,{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 er(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 tr=(0,_.Pf)(qa,{style:"page"}),Pt=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.3cb32e8ce17dd3b89946.js.map