"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[6618],{5906:(G,S,o)=>{o.r(S),o.d(S,{default:()=>M});var c=o(68404),C=o(671),b=o(54899),e=o(31403),v=o(52081),T=o(69142),h=o(79396),R=o(77582),x=o(76770),w=o(45984);const M=()=>{const U=(0,x.q)("channels"),[P,L]=(0,c.useState)([]),K=async()=>await(0,b.i)().get("/api/alert-notifications"),[z,se]=(0,C.Z)(K);(0,c.useEffect)(()=>{se().then(B=>{L(B)})},[se]);const X=B=>{R.h$.publish(new w.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()=>{be(B)}}))},be=async B=>{await(0,b.i)().delete(`/api/alert-notifications/${B}`);const F=await se();L(F)};return c.createElement(h.T,{navModel:U},c.createElement(h.T.Contents,null,z.error&&c.createElement("p",null,z.error),!!P.length&&c.createElement(c.Fragment,null,c.createElement("div",{className:"page-action-bar"},c.createElement("div",{className:"page-action-bar__spacer"}),c.createElement(e.Qj,{icon:"channel-add",href:"alerting/notification/new"},"New channel")),c.createElement("table",{className:"filter-table filter-table--hover"},c.createElement("thead",null,c.createElement("tr",null,c.createElement("th",{style:{minWidth:"200px"}},c.createElement("strong",null,"Name")),c.createElement("th",{style:{minWidth:"100px"}},"Type"),c.createElement("th",{style:{width:"1%"}}))),c.createElement("tbody",null,P.map(B=>c.createElement("tr",{key:B.id},c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${B.id}/edit`},B.name)),c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${B.id}/edit`},B.type)),c.createElement("td",{className:"text-right"},c.createElement(v.Lh,{justify:"flex-end"},B.isDefault&&c.createElement(e.zx,{disabled:!0,variant:"secondary",size:"sm"},"default"),c.createElement(e.zx,{variant:"destructive",icon:"times",size:"sm",onClick:()=>{X(B.id)}})))))))),!(P.length||z.loading)&&c.createElement(T.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"})))}},61269:(G,S,o)=>{o.r(S),o.d(S,{default:()=>ua});var c=o(9892),C=o(64681),b=o.n(C),e=o(68404),v=o(70356),T=o(26418),h=o(72648),R=o(39904),x=o(45253),w=o(61744),W=o(53546),M=o(81168),U=o(96678),P=o(94984),L=o(45524),K=o(731),z=o(88331),se=o(35918),X=o(82897);function be(t,n){let a=n.trim();if(!a.match(/\{\{\s*define/)){const r=a.split(`
`).map(s=>"  "+s).join(`
`);a=`{{ define "${t}" }}
${r}
{{ end }}`}return a}function B(t){const n=(a,r)=>`{{ define "${r}_NEW_${(0,X.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var F=o(59052),mt=o(89050),ut=o(13393),te=o(24799),le=o(46967),I=o(31403),Ae=o(40014),ne=o(69945),q=o(72004),H=o(10505),ge=o(46818),ie=o(40106),Oe=o(42042);const pt=[{name:"Receiver",type:"string",notes:"Name of the contact point that the notification is being sent to."},{name:"Status",type:"string",notes:"firing if at least one alert is firing, otherwise resolved"},{name:"Alerts",type:"[]Alert",notes:"List of alert objects that are included in this notification."},{name:"Alerts.Firing",type:"[]Alert",notes:"List of firing alerts"},{name:"Alerts.Resolved",type:"[]Alert",notes:"List of resolved alerts"},{name:"GroupLabels",type:"KeyValue",notes:"Labels these alerts were grouped by."},{name:"CommonLabels",type:"KeyValue",notes:"Labels common to all the alerts included in this notification."},{name:"CommonAnnotations",type:"KeyValue",notes:"Annotations common to all the alerts included in this notification."},{name:"ExternalURL",type:"string",notes:"Back link to the Grafana that sent the notification."}],gt=[{name:"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."}],ft=[{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"
}
`;function Et(){const t=(0,h.wW)(yt),n=e.createElement(Ie,{caption:e.createElement("h4",{className:t.header},"Alert template data ",e.createElement("span",null,"Available only when in the context of an Alert (e.g. inside .Alerts loop)")),dataItems:gt});return e.createElement(T.Stack,{gap:2,flexGrow:1},e.createElement(Ie,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:pt,typeRenderer:a=>a==="[]Alert"?e.createElement(Oe.z,{content:n},e.createElement("div",{className:t.interactiveType},a)):a==="KeyValue"?e.createElement(Oe.z,{content:e.createElement(vt,null)},e.createElement("div",{className:t.interactiveType},a)):a}))}const yt=t=>({header:c.css`
    color: ${t.colors.text.primary};

    span {
      color: ${t.colors.text.secondary};
      font-size: ${t.typography.bodySmall.fontSize};
    }
  `,interactiveType:c.css`
    color: ${t.colors.text.link};
  `});function Ie({dataItems:t,caption:n,typeRenderer:a}){const r=(0,h.wW)(Ne);return e.createElement("table",{className:r.table},e.createElement("caption",null,n),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Type"),e.createElement("th",null,"Notes"))),e.createElement("tbody",null,t.map(({name:s,type:i,notes:d},u)=>e.createElement("tr",{key:u},e.createElement("td",null,s),e.createElement("td",null,a?a(i):i),e.createElement("td",null,d)))))}function vt(){const t=(0,h.wW)(Ne);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,ft.map(({name:n,args:a,returns:r,notes:s})=>e.createElement("tr",{key:n},e.createElement("td",null,n),e.createElement("td",null,a),e.createElement("td",null,r),e.createElement("td",null,s))))))}const Ne=t=>({table:c.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 bt=o(9405),ae=o(86922);function At(t){const n=t.languages.CompletionItemKind.Function;return[{label:ae.AlertmanagerTemplateFunction.toUpper,detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.toLower,detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.title,documentation:"Capitalizes the first letter of each word",detail:"function(s string)",kind:n},{label:ae.AlertmanagerTemplateFunction.join,documentation:{value:"Joins an array of strings using the separator provided."},detail:"function(separator string, s []string)",kind:n},{label:ae.AlertmanagerTemplateFunction.match,detail:"function",kind:n},{label:ae.AlertmanagerTemplateFunction.safeHtml,detail:"function(pattern, repl, text)",kind:n},{label:ae.AlertmanagerTemplateFunction.reReplaceAll,detail:"function(pattern, repl, text)",kind:n},{label:ae.AlertmanagerTemplateFunction.stringSlice,detail:"function(s ...string)",kind:n}]}const Ct=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,Tt=`
[{{.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 }}
`,St=de("GroupLabels"),Pt=de("CommonLabels"),Rt=de("CommonAnnotations"),Dt=de("Labels"),xt=de("Annotations");function de(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function Mt(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 Lt(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 Ot(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function It(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 we={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:Ct},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:Tt},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:St},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:Pt},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:Rt},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:Dt},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:xt}};function Nt(t){const n=t.languages.CompletionItemKind.Snippet,a=t.languages.CompletionItemInsertTextRule.InsertAsSnippet,{alerts:r,alertDetails:s,groupLabels:i,commonLabels:d,commonAnnotations:u,labels:f,annotations:m}=we;return[{label:r.label,documentation:r.description,kind:n,insertText:r.snippet,insertTextRules:a},{label:{label:s.label,detail:"(Alert)"},documentation:s.description,kind:n,insertText:s.snippet,insertTextRules:a},{label:i.label,documentation:i.description,kind:n,insertText:i.snippet,insertTextRules:a},{label:d.label,documentation:d.description,kind:n,insertText:d.snippet,insertTextRules:a},{label:u.label,documentation:u.description,kind:n,insertText:u.snippet,insertTextRules:a},{label:{label:f.label,detail:"(Alert)"},documentation:f.description,kind:n,insertText:f.snippet,insertTextRules:a},{label:{label:m.label,detail:"(Alert)"},documentation:m.description,kind:n,insertText:m.snippet,insertTextRules:a}]}function wt(t){const n={triggerCharacters:["."],provideCompletionItems(a,r,s){const i=a.getWordUntilPosition(r),d={startLineNumber:r.lineNumber,endLineNumber:r.lineNumber,startColumn:i.startColumn,endColumn:i.endColumn},u=new kt(t,d);if(!$t(a,r))return u.getSnippetsSuggestions();if(s.triggerKind===t.languages.CompletionTriggerKind.Invoke&&!s.triggerCharacter)return u.getFunctionsSuggestions();const m=a.getWordUntilPosition({lineNumber:r.lineNumber,column:r.column-1});return u.getTemplateDataSuggestions(m.word)}};return t.languages.registerCompletionItemProvider("go-template",n)}function $t(t,n){const a={startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:t.getLineMinColumn(n.lineNumber),endColumn:t.getLineMaxColumn(n.lineNumber)},r='\\{\\{[a-zA-Z0-9._() "]+\\}\\}';return t.findMatches(r,a,!0,!1,null,!0).some(i=>i.range.containsPosition(n))}class kt{constructor(n,a){this.monaco=n,this.range=a,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions(Nt(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(At(this.monaco)),this.getTemplateDataSuggestions=r=>{switch(r){case"":return this.getCompletionsFromDefinitions(Mt(this.monaco),Lt(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(Ot(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(It(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...r)=>({suggestions:(0,X.concat)(...r).map(i=>_t(i,this.range))})}}function _t({label:t,detail:n,documentation:a,kind:r,insertText:s},i){const d=typeof t=="string"?t:t.label,u=typeof t=="string"?{label:t,description:n}:{...t};return u.description??=n,{label:u,kind:r,insertText:s??d,range:i,documentation:a,detail:n}}const $e="go-template",Wt={id:$e,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(o.bind(o,86922))},Ut=(t,n)=>{const{id:a,loader:r}=n;t.languages.getLanguages().find(i=>i.id===a)||(t.languages.register({id:a}),r().then(i=>{t.languages.setMonarchTokensProvider(a,i.language),t.languages.setLanguageConfiguration(a,i.conf)}))},ke=t=>{const n=Boolean(t.autoHeight),a=(0,e.useRef)(null),r=s=>{if(n){const i=s.getContentHeight();try{s.layout({height:i,width:NaN})}catch{}}};return(0,e.useEffect)(()=>()=>{a.current?.dispose()},[]),e.createElement(bt.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:r,onBeforeEditorMount:s=>{Ut(s,Wt),a.current=wt(s)},language:$e})},Ft=Object.freeze({name:"",content:""}),_e=t=>t.pathname.endsWith("/duplicate"),Ce=({existing:t,alertManagerSourceName:n,config:a,provenance:r})=>{const s=(0,h.wW)(We),i=(0,M.useDispatch)();(0,Ae.x)(y=>y.unifiedAlerting.saveAMConfig=ge.oq);const{loading:d,error:u}=(0,ne._)(y=>y.saveAMConfig),f=(0,v.TH)(),m=_e(f),g=y=>{const N=be(y.name,y.content),V={...a.template_files,[y.name]:N};t&&t.name!==y.name&&delete V[t.name];const Z=[...(a.alertmanager_config.templates??[]).filter(pe=>pe!==t?.name),y.name],k={template_files:V,alertmanager_config:{...a.alertmanager_config,templates:Z}};i((0,q.mM)({alertManagerSourceName:n,newConfig:k,oldConfig:a,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},{handleSubmit:p,register:E,formState:{errors:A},getValues:D,setValue:$}=(0,F.cI)({mode:"onSubmit",defaultValues:t??Ft}),J=y=>!a.template_files[y]||t?.name===y?!0:"Another template with this name already exists.";return e.createElement("form",{onSubmit:p(g)},e.createElement("h4",null,t&&!m?"Edit notification template":"Create notification template"),u&&e.createElement(x.b,{severity:"error",title:"Error saving template"},u.message||u?.data?.message||String(u)),r&&e.createElement(ie.Xq,{resource:ie.Uv.Template}),e.createElement(ut.C,{disabled:Boolean(r)},e.createElement(te.g,{label:"Template name",error:A?.name?.message,invalid:!!A.name?.message,required:!0},e.createElement(le.I,{...E("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:J}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Vt,null),e.createElement("div",{className:s.contentContainer},e.createElement("div",null,e.createElement(te.g,{label:"Content",error:A?.content?.message,invalid:!!A.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(mt.Z,null,({width:y,height:N})=>e.createElement(ke,{value:D("content"),width:y,height:N,onBlur:V=>$("content",V)})))),e.createElement("div",{className:s.buttons},d&&e.createElement(I.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!d&&e.createElement(I.zx,{type:"submit",variant:"primary"},"Save template"),e.createElement(I.Qj,{disabled:d,href:(0,H.eQ)("alerting/notifications",n),variant:"secondary",type:"button",fill:"outline"},"Cancel"))),e.createElement(Et,null))))};function Vt(){const t=(0,h.wW)(We);return e.createElement(x.b,{title:"Templating guideline",severity:"info"},e.createElement(T.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(I.Qj,{href:"https://grafana.com/docs/grafana/latest/alerting/manage-notifications/template-notifications/",target:"_blank",icon:"external-link-alt"},"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(we).map(n=>n.label).join(", "))))}const We=t=>({contentContainer:c.css`
    display: flex;
    gap: ${t.spacing(2)};
    flex-direction: row;
    align-items: flex-start;
    flex-wrap: wrap;
    ${t.breakpoints.up("xxl")} {
      flex-wrap: nowrap;
    }
  `,snippets:c.css`
    margin-top: ${t.spacing(2)};
    font-size: ${t.typography.bodySmall.fontSize};
  `,code:c.css`
    color: ${t.colors.text.secondary};
    font-weight: ${t.typography.fontWeightBold};
  `,buttons:c.css`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,textarea:c.css`
    max-width: 758px;
  `,editWrapper:c.css`
    display: block;
    position: relative;
    width: 640px;
    height: 320px;
  `}),Gt=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n];if(!r)return e.createElement(x.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,se.G)(n,Object.keys(t.template_files));return e.createElement(Ce,{alertManagerSourceName:a,config:t,existing:{name:s,content:B(r)}})};var Q=o(45849);function l(t,n,a,r={}){return{propertyName:t,label:n,description:a,element:"input",inputType:"",required:!1,secure:!1,placeholder:"",validationRule:"",showWhen:{field:"",is:""},dependsOn:"",...r}}const Bt=l("basic_auth","Basic auth","Sets the `Authorization` header with the configured username and password. Password and password_file are mutually exclusive.",{element:"subform",subformOptions:[l("username","Username",""),l("password","Password",""),l("password_file","Password file","")]}),Ue=l("tls_config","TLS config","Configures the TLS settings.",{element:"subform",subformOptions:[l("ca_file","CA file","CA certificate to validate the server certificate with."),l("cert_file","Cert file","Certificate for client cert authentication to the server."),l("key_file","Key file","Key file for client cert authentication to the server."),l("server_name","Server name","ServerName extension to indicate the name of the server."),l("insecure_skip_verify","Skip verify","Disable validation of the server certificate.",{element:"checkbox"})]}),re=l("http_config","HTTP Config","Note that `basic_auth`, `bearer_token` and `bearer_token_file` options are mutually exclusive.",{element:"subform",subformOptions:[l("bearer_token","Bearer token","Sets the `Authorization` header with the configured bearer token."),l("bearer_token_file","Bearer token file","Sets the `Authorization` header with the bearer token read from the configured file."),l("proxy_url","Proxy URL","Optional proxy URL."),Bt,Ue]}),Fe=[{name:"Email",description:"Send notification over SMTP",type:"email",info:"",heading:"Email settings",options:[l("to","To","The email address to send notifications to.",{required:!0}),l("from","From","The sender address."),l("smarthost","SMTP host","The SMTP host through which emails are sent."),l("hello","Hello","The hostname to identify to the SMTP server."),l("auth_username","Username","SMTP authentication information"),l("auth_password","Password","SMTP authentication information"),l("auth_secret","Secret","SMTP authentication information"),l("auth_identity","Identity","SMTP authentication information"),l("require_tls","Require TLS","The SMTP TLS requirement",{element:"checkbox"}),l("html","Email HTML body","The HTML body of the email notification.",{placeholder:'{{ template "email.default.html" . }}',element:"textarea"}),l("text","Email text body","The text body of the email notification.",{element:"textarea"}),l("headers","Headers","Further headers email header key/value pairs. Overrides any headers previously set by the notification implementation.",{element:"key_value_map"}),Ue]},{name:"PagerDuty",description:"Send notifications to PagerDuty",type:"pagerduty",info:"",heading:"PagerDuty settings",options:[l("routing_key","Routing key","The PagerDuty integration key (when using PagerDuty integration type `Events API v2`)"),l("service_key","Service key","The PagerDuty integration key (when using PagerDuty integration type `Prometheus`)."),l("url","URL","The URL to send API requests to"),l("client","Client","The client identification of the Alertmanager.",{placeholder:'{{ template "pagerduty.default.client" . }}'}),l("client_url","Client URL","A backlink to the sender of the notification.",{placeholder:'{{ template "pagerduty.default.clientURL" . }}'}),l("description","Description","A description of the incident.",{placeholder:'{{ template "pagerduty.default.description" .}}'}),l("severity","Severity","Severity of the incident.",{placeholder:"error"}),l("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),l("images","Images","Images to attach to the incident.",{element:"subform_array",subformOptions:[l("href","URL","",{required:!0}),l("source","Source","",{required:!0}),l("alt","Alt","",{required:!0})]}),l("links","Links","Links to attach to the incident.",{element:"subform_array",subformOptions:[l("href","URL","",{required:!0}),l("text","Text","",{required:!0})]}),re]},{name:"Pushover",description:"Send notifications to Pushover",type:"pushover",info:"",heading:"Pushover settings",options:[l("user_key","User key","The recipient user\u2019s user key.",{required:!0}),l("token","Token","Your registered application\u2019s API token, see https://pushover.net/app",{required:!0}),l("title","Title","Notification title.",{placeholder:'{{ template "pushover.default.title" . }}'}),l("message","Message","Notification message.",{placeholder:'{{ template "pushover.default.message" . }}'}),l("url","URL","A supplementary URL shown alongside the message.",{placeholder:'{{ template "pushover.default.url" . }}'}),l("priority","Priority","Priority, see https://pushover.net/api#priority",{placeholder:'{{ if eq .Status "firing" }}2{{ else }}0{{ end }}'}),l("retry","Retry","How often the Pushover servers will send the same notification to the user. Must be at least 30 seconds.",{placeholder:"1m"}),l("expire","Expire","How long your notification will continue to be retried for, unless the user acknowledges the notification.",{placeholder:"1h"}),re]},{name:"Slack",description:"Send notifications to Slack",type:"slack",info:"",heading:"Slack settings",options:[l("api_url","Webhook URL","The Slack webhook URL."),l("channel","Channel","The #channel or @user to send notifications to.",{required:!0}),l("icon_emoji","Emoji icon",""),l("icon_url","Icon URL",""),l("link_names","Names link","",{element:"checkbox"}),l("username","Username","",{placeholder:'{{ template "slack.default.username" . }}'}),l("callback_id","Callback ID","",{placeholder:'{{ template "slack.default.callbackid" . }}'}),l("color","Color","",{placeholder:'{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}'}),l("fallback","Fallback","",{placeholder:'{{ template "slack.default.fallback" . }}'}),l("footer","Footer","",{placeholder:'{{ template "slack.default.footer" . }}'}),l("mrkdwn_in","Mrkdwn fields","An array of field names that should be formatted by mrkdwn syntax.",{element:"string_array"}),l("pretext","Pre-text","",{placeholder:'{{ template "slack.default.pretext" . }}'}),l("short_fields","Short fields","",{element:"checkbox"}),l("text","Message body","",{element:"textarea",placeholder:'{{ template "slack.default.text" . }}'}),l("title","Title","",{placeholder:'{{ template "slack.default.title" . }}'}),l("title_link","Title link","",{placeholder:'{{ template "slack.default.titlelink" . }}'}),l("image_url","Image URL",""),l("thumb_url","Thumbnail URL",""),l("actions","Actions","",{element:"subform_array",subformOptions:[l("text","Text","",{required:!0}),l("type","Type","",{required:!0}),l("url","URL","Either url or name and value are mandatory."),l("name","Name",""),l("value","Value",""),l("confirm","Confirm","",{element:"subform",subformOptions:[l("text","Text","",{required:!0}),l("dismiss_text","Dismiss text",""),l("ok_text","OK text",""),l("title","Title","")]}),l("style","Style","")]}),l("fields","Fields","",{element:"subform_array",subformOptions:[l("title","Title","",{required:!0}),l("value","Value","",{required:!0}),l("short","Short","",{element:"checkbox"})]}),re]},{name:"OpsGenie",description:"Send notifications to OpsGenie",type:"opsgenie",info:"",heading:"OpsGenie settings",options:[l("api_key","API key","The API key to use when talking to the OpsGenie API."),l("api_url","API URL","The host to send OpsGenie API requests to."),l("message","Message","Alert text limited to 130 characters."),l("description","Description","A description of the incident.",{placeholder:'{{ template "opsgenie.default.description" . }}'}),l("source","Source","A backlink to the sender of the notification.",{placeholder:'{{ template "opsgenie.default.source" . }}'}),l("details","Details","A set of arbitrary key/value pairs that provide further detail about the incident.",{element:"key_value_map"}),l("tags","Tags","Comma separated list of tags attached to the notifications."),l("note","Note","Additional alert note."),l("priority","Priority","Priority level of alert. Possible values are P1, P2, P3, P4, and P5."),l("responders","Responders","List of responders responsible for notifications.",{element:"subform_array",subformOptions:[l("type","Type",'"team", "user", "escalation" or schedule".',{required:!0}),l("id","ID","Exactly one of these fields should be defined."),l("name","Name","Exactly one of these fields should be defined."),l("username","Username","Exactly one of these fields should be defined.")]}),re]},{name:"VictorOps",description:"Send notifications to VictorOps",type:"victorops",info:"",heading:"VictorOps settings",options:[l("api_key","API key","The API key to use when talking to the VictorOps API."),l("api_url","API URL","The VictorOps API URL."),l("routing_key","Routing key","A key used to map the alert to a team.",{required:!0}),l("message_type","Message type","Describes the behavior of the alert (CRITICAL, WARNING, INFO)."),l("entity_display_name","Entity display name","Contains summary of the alerted problem.",{placeholder:'{{ template "victorops.default.entity_display_name" . }}'}),l("state_message","State message","Contains long explanation of the alerted problem.",{placeholder:'{{ template "victorops.default.state_message" . }}'}),l("monitoring_tool","Monitoring tool","The monitoring tool the state message is from.",{placeholder:'{{ template "victorops.default.monitoring_tool" . }}'}),re]},{name:"Webhook",description:"Send notifications to a webhook",type:"webhook",info:"",heading:"Webhook settings",options:[l("url","URL","The endpoint to send HTTP POST requests to.",{required:!0}),l("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+$|^$)"}),re]},{name:"Discord",description:"Sends notifications to Discord",type:"discord",info:"",heading:"Discord settings",options:[l("title","Title","Templated title of the message",{placeholder:'{{ template "discord.default.title" . }}'}),l("message","Message Content","Mention a group using @ or a user using <@ID> when notifying in a channel",{placeholder:'{{ template "discord.default.message" . }}'}),l("webhook_url","Webhook URL","",{placeholder:"Discord webhook URL",required:!0}),re]}],Kt=[l("smtp_from","SMTP from","The default SMTP From header field."),l("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"),l("smtp_hello","SMTP hello","The default hostname to identify to the SMTP server.",{placeholder:"localhost"}),l("smtp_auth_username","SMTP auth username","SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server."),l("smtp_auth_password","SMTP auth password","SMTP Auth using LOGIN and PLAIN."),l("smtp_auth_identity","SMTP auth identity","SMTP Auth using PLAIN."),l("smtp_auth_secret","SMTP auth secret","SMTP Auth using CRAM-MD5."),l("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"}),l("slack_api_url","Slack API URL",""),l("victorops_api_key","VictorOps API key",""),l("victorops_api_url","VictorOps API URL","",{placeholder:"https://alert.victorops.com/integrations/generic/20131114/alert/"}),l("pagerduty_url","PagerDuty URL","https://events.pagerduty.com/v2/enqueue"),l("opsgenie_api_key","OpsGenie API key",""),l("opsgenie_api_url","OpsGenie API URL","",{placeholder:"https://api.opsgenie.com/"}),l("wechat_api_url","WeChat API URL","",{placeholder:"https://qyapi.weixin.qq.com/cgi-bin/"}),l("wechat_api_secret","WeChat API secret",""),l("wechat_api_corp_id","WeChat API corp id",""),re,l("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 zt(t,n){const a={};let r=1;return[{name:t.name,items:t.grafana_managed_receiver_configs?.map(i=>{const d=String(r++);a[d]=i;const u=n.find(({type:f})=>f===i.type);return Jt(d,i,u)})??[]},a]}function jt(t,n){const a={};let r=1;const s=Object.entries(t).filter(([d])=>d.endsWith("_configs")&&d!=="grafana_managed_receiver_configs").map(([d,u])=>[d.replace("_configs",""),u]).map(([d,u])=>u.map(f=>{const m=String(r++);if(a[m]={type:d,config:f},!n.find(p=>p.type===d))throw new Error(`unknown cloud notifier: ${d}`);return Yt(m,d,f)})).flat();return[{name:t.name,items:s},a]}function Ht(t,n,a){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(r=>{const s=n[r.__id];return Be(r,a,t.name,s)})}}function Qt(t,n){const a={name:t.name};return t.items.forEach(({__id:r,type:s,settings:i,sendResolved:d})=>{const u=me({...i,send_resolved:d??n.sendResolved}),f=`${s}_configs`;a[f]?a[f].push(u):a[f]=[u]}),a}function Ve(t,n,a){const r=t.alertmanager_config.receivers??[];if(n.name!==a&&r.find(({name:i})=>i===n.name))throw new Error(`Duplicate receiver name ${n.name}`);if(a&&!r.find(({name:i})=>i===a))throw new Error(`Expected receiver ${a} to exist, but did not find it in the config`);const s={...t,alertmanager_config:{...t.alertmanager_config,receivers:a?r.map(i=>i.name===a?n:i):[...r,n]}};return s.alertmanager_config.route&&a&&n.name!==a&&(s.alertmanager_config.route=Ge(s.alertmanager_config.route,a,n.name)),s}function Ge(t,n,a){const r={...t};return r.receiver===n&&(r.receiver=a),r.routes&&(r.routes=r.routes.map(s=>Ge(s,n,a))),r}function Yt(t,n,a){return{__id:t,type:n,settings:{...a},secureFields:{},secureSettings:{},sendResolved:a.send_resolved}}function Jt(t,n,a){const r={__id:t,type:n.type,provenance:n.provenance,secureSettings:{},settings:{...n.settings},secureFields:{...n.secureFields},disableResolveMessage:n.disableResolveMessage};return a?.options.forEach(s=>{s.secure&&r.settings[s.propertyName]&&(delete r.settings[s.propertyName],r.secureFields[s.propertyName]=!0)}),r}function Be(t,n,a,r){const s={settings:me({...r&&r.type===t.type?r.settings??{}:{},...t.settings??{}}),secureSettings:t.secureSettings??{},type:t.type,name:a,disableResolveMessage:t.disableResolveMessage??r?.disableResolveMessage??n.disableResolveMessage};return r&&(s.uid=r.uid),s}function me(t){return(0,X.isArray)(t)?t.forEach(me):typeof t=="object"&&t!==null&&Object.entries(t).forEach(([n,a])=>{a===""||a===null||a===void 0?delete t[n]:me(a)}),t}var Te=o(58255);const Zt=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,F.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,{disabled:a},e.createElement(Te.X,{...r(`${t}sendResolved`),label:"Send resolved",disabled:a,description:"Whether or not to notify about resolved alerts."})))};var Xt=o(60499);const qt=[];function Ke(t){const{name:n,formAPI:a,defaults:r,softDelete:s}=t,{watch:i,getValues:d,reset:u,setValue:f}=a,m=i(n)??r??qt,g=(0,e.useCallback)(p=>{const E=JSON.parse(JSON.stringify(d())),A=p(m??[]);u((0,X.set)(E,n,A))},[d,n,u,m]);return{fields:m,append:(0,e.useCallback)(p=>g(E=>[...E,p]),[g]),remove:(0,e.useCallback)(p=>{s?f(`${n}.${p}.__deleted`,!0):g(E=>{const A=E.slice();return A.splice(p,1),A})},[g,n,f,s])}}var fe=o(63619),ze=o(53217),en=o(97379),Y=o(65750);const tn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,h.wW)(nn),[s,i]=(0,e.useState)(je(t));(0,e.useEffect)(()=>i(je(t)),[t]);const d=m=>{n(an(m))},u=m=>{const g=s.slice(),p=g.splice(m,1)[0];i(g),p[0]&&d(g)},f=(m,g)=>{const p=s[g],E=s.map((A,D)=>D===g?m:A);i(E),(m[0]||p[0])&&d(E)};return e.createElement("div",null,!!s.length&&e.createElement("table",{className:r.table},e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Value"),!a&&e.createElement("th",null))),e.createElement("tbody",null,s.map(([m,g],p)=>e.createElement("tr",{key:p},e.createElement("td",null,e.createElement(le.I,{readOnly:a,value:m,onChange:E=>f([E.currentTarget.value,g],p)})),e.createElement("td",null,e.createElement(le.I,{readOnly:a,value:g,onChange:E=>f([m,E.currentTarget.value],p)})),!a&&e.createElement("td",null,e.createElement(Y.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>u(p)})))))),!a&&e.createElement(I.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>i([...s,["",""]])},"Add"))},nn=t=>({addButton:c.css`
    margin-top: ${t.spacing(1)};
  `,table:c.css`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),an=t=>{const n={};for(const[a,r]of t)a&&(n[a]=r);return n},je=t=>Object.entries(t??{}),rn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,h.wW)(on),s=d=>{if(!t)return;const u=t.slice();u.splice(d,1),n(u)},i=(d,u)=>{t&&n(t.map((f,m)=>m===u?d:f))};return e.createElement("div",null,!!t?.length&&t.map((d,u)=>e.createElement("div",{key:u,className:r.row},e.createElement(le.I,{readOnly:a,value:d,onChange:f=>i(f.currentTarget.value,u)}),!a&&e.createElement(Y.A,{className:r.deleteIcon,icon:"trash-alt",tooltip:"delete",onClick:()=>s(u)}))),!a&&e.createElement(I.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},on=t=>({row:c.css`
    display: flex;
    flex-direction: row;
    margin-bottom: ${t.spacing(1)};
    align-items: center;
  `,deleteIcon:c.css`
    margin-left: ${t.spacing(1)};
  `,addButton:c.css`
    margin-top: ${t.spacing(1)};
  `});var He=o(33950);const Se=({label:t,description:n,children:a,className:r,size:s="xl"})=>{const i=(0,h.wW)(sn),[d,u]=(0,e.useState)(!0),f=()=>u(!d);return e.createElement("div",{className:(0,c.cx)(i.wrapper,r)},e.createElement(He.U,{className:i.toggle,size:s,onToggle:f,isCollapsed:d,text:t}),n&&e.createElement("p",{className:i.description},n),e.createElement("div",{className:d?i.hidden:i.content},a))},sn=t=>({wrapper:c.css`
    margin-top: ${t.spacing(1)};
    padding-bottom: ${t.spacing(1)};
  `,toggle:c.css`
    margin: ${t.spacing(1,0)};
    padding: 0;
  `,hidden:c.css`
    display: none;
  `,description:c.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,content:c.css`
    padding-left: ${t.spacing(3)};
  `}),Qe=t=>({collapsibleSection:c.css`
    margin: 0;
    padding: 0;
  `,wrapper:c.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:c.css`
    color: ${t.colors.text.secondary};
    font-size: ${t.typography.size.sm};
    font-weight: ${t.typography.fontWeightRegular};
    margin: 0;
  `,deleteIcon:c.css`
    position: absolute;
    right: ${t.spacing(1)};
    top: ${t.spacing(1)};
  `,addButton:c.css`
    margin-top: ${t.spacing(1)};
  `}),ln=({option:t,pathPrefix:n,errors:a,defaultValues:r,readOnly:s=!1})=>{const i=(0,h.wW)(Qe),d=`${n}${t.propertyName}`,u=(0,F.Gc)(),{fields:f,append:m,remove:g}=Ke({name:d,formAPI:u,defaults:r});return e.createElement("div",{className:i.wrapper},e.createElement(Se,{className:i.collapsibleSection,label:`${t.label} (${f.length})`,description:t.description},(f??r??[]).map((p,E)=>e.createElement("div",{key:E,className:i.wrapper},!s&&e.createElement(Y.A,{"data-testid":`${d}.${E}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>g(E),className:i.deleteIcon}),t.subformOptions?.map(A=>e.createElement(he,{readOnly:s,defaultValue:p?.[A.propertyName],key:A.propertyName,option:A,pathPrefix:`${d}.${E}.`,error:a?.[E]?.[A.propertyName]})))),!s&&e.createElement(I.zx,{"data-testid":`${d}.add-button`,className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>m({__id:String(Math.random())})},"Add")))},cn=({option:t,pathPrefix:n,errors:a,defaultValue:r,readOnly:s=!1})=>{const i=(0,h.wW)(Qe),d=`${n}${t.propertyName}`,{watch:u}=(0,F.Gc)(),f=u(d),m=f===void 0?r:f,[g,p]=(0,e.useState)(!!m);return e.createElement("div",{className:i.wrapper,"data-testid":`${d}.container`},e.createElement("h6",null,t.label),t.description&&e.createElement("p",{className:i.description},t.description),g&&e.createElement(e.Fragment,null,!s&&e.createElement(Y.A,{"data-testid":`${d}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>p(!1),className:i.deleteIcon}),(t.subformOptions??[]).map(E=>e.createElement(he,{readOnly:s,defaultValue:r?.[E.propertyName],key:E.propertyName,option:E,pathPrefix:`${d}.`,error:a?.[E.propertyName]}))),!g&&!s&&e.createElement(I.zx,{className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>p(!0),"data-testid":`${d}.add-button`},"Add"))},he=({option:t,invalid:n,pathPrefix:a,pathSuffix:r="",error:s,defaultValue:i,readOnly:d=!1})=>{const u=`${a}${r}`;return t.element==="subform"?e.createElement(cn,{readOnly:d,defaultValue:i,option:t,errors:s,pathPrefix:u}):t.element==="subform_array"?e.createElement(ln,{readOnly:d,defaultValues:i,option:t,pathPrefix:u,errors:s}):e.createElement(te.g,{label:t.element!=="checkbox"?t.label:void 0,description:t.description||void 0,invalid:!!s,error:s?.message},e.createElement(dn,{id:`${u}${t.propertyName}`,defaultValue:i,option:t,invalid:n,pathPrefix:u,readOnly:d,pathIndex:a}))},dn=({option:t,invalid:n,id:a,pathPrefix:r="",pathIndex:s="",readOnly:i=!1})=>{const{control:d,register:u,unregister:f,getValues:m}=(0,F.Gc)(),g=`${r}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{f(g,{keepValue:!1})},[f,g]),t.element){case"checkbox":return e.createElement(Te.X,{id:a,readOnly:i,disabled:i,className:mn.checkbox,...u(g),label:t.label,description:t.description});case"input":return e.createElement(le.I,{id:a,readOnly:i||pn(t,m,s),invalid:n,type:t.inputType,...u(g,{required:un(t,m,s),validate:p=>t.validationRule!==""?Ye(p,t.validationRule):!0}),placeholder:t.placeholder});case"select":return e.createElement(fe.g,{render:({field:{onChange:p,ref:E,...A}})=>e.createElement(ze.Ph,{disabled:i,...A,options:t.selectOptions??void 0,invalid:n,onChange:D=>p(D.value)}),control:d,name:g});case"textarea":return e.createElement(en.K,{id:a,readOnly:i,invalid:n,placeholder:t.placeholder,...u(g,{required:t.required?"Required":!1,validate:p=>t.validationRule!==""?Ye(p,t.validationRule):!0})});case"string_array":return e.createElement(fe.g,{render:({field:{value:p,onChange:E}})=>e.createElement(rn,{readOnly:i,value:p,onChange:E}),control:d,name:g});case"key_value_map":return e.createElement(fe.g,{render:({field:{value:p,onChange:E}})=>e.createElement(tn,{readOnly:i,value:p,onChange:E}),control:d,name:g});default:return console.error("Element not supported",t.element),null}},mn={checkbox:c.css`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},Ye=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",un=(t,n,a)=>{if(!t.dependsOn)return t.required?"Required":!1;if((0,X.isEmpty)(n(`${a}secureFields`))){const r=n(`${a}secureSettings.${t.dependsOn}`);return!Boolean(r)&&t.required?"Required":!1}else return!n(`${a}secureFields.${t.dependsOn}`)&&t.required?"Required":!1},pn=(t,n,a)=>t.dependsOn?(0,X.isEmpty)(n(`${a}secureFields`))?n(`${a}secureSettings.${t.dependsOn}`):n(`${a}secureFields.${t.dependsOn}`):!1;function Je({defaultValues:t,selectedChannelOptions:n,onResetSecureField:a,secureFields:r,errors:s,pathPrefix:i="",readOnly:d=!1}){const{watch:u}=(0,F.Gc)(),f=u();return e.createElement(e.Fragment,null,n.map((m,g)=>{const p=`${m.label}-${g}`,E=i.split("."),A=E.length>=2?f.items[Number(E[1])].settings[m.showWhen.field]:void 0;if(m.showWhen.field&&A!==m.showWhen.is)return null;if(r&&r[m.propertyName])return e.createElement(te.g,{key:p,label:m.label,description:m.description||void 0},e.createElement(le.I,{readOnly:!0,value:"Configured",suffix:d?null:e.createElement(I.zx,{onClick:()=>a(m.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const D=(m.secure?s?.secureSettings:s?.settings)?.[m.propertyName],$=t?.settings?.[m.propertyName];return e.createElement(he,{defaultValue:$,readOnly:d,key:p,error:D,pathPrefix:i,pathSuffix:m.secure?"secureSettings.":"settings.",option:m})}))}function gn({defaultValues:t,pathPrefix:n,onDuplicate:a,onDelete:r,onTest:s,notifiers:i,errors:d,secureFields:u,commonSettingsComponent:f,isEditable:m=!0,isTestable:g}){const p=(0,h.wW)(fn),E=O=>`${n}${O}`,{control:A,watch:D,register:$,trigger:J,formState:y,setValue:N}=(0,F.Gc)(),V=D(E("type"))??t.type,{loading:Z}=(0,ne._)(O=>O.testReceivers);(0,e.useEffect)(()=>{$(`${n}.__id`),$(`${n}.secureFields`)},[$,n]);const[k,pe]=(0,e.useState)(u??{}),ye=O=>{if(k[O]){const ee={...u};delete ee[O],pe(ee),N(`${n}.secureFields`,ee)}},Me=(0,e.useMemo)(()=>i.map(({name:O,type:ee})=>({label:O,value:ee})).sort((O,ee)=>O.label.localeCompare(ee.label)),[i]),Le=async()=>{await J(),Object.keys(y.errors).length===0&&s&&s()},_=i.find(({type:O})=>O===V),j=_?.options.filter(O=>O.required),ce=_?.options.filter(O=>!O.required),ve=`contact-point-type-${n}`;return e.createElement("div",{className:p.wrapper,"data-testid":"item-container"},e.createElement("div",{className:p.topRow},e.createElement("div",null,e.createElement(te.g,{label:"Integration",htmlFor:ve,"data-testid":`${n}type`},e.createElement(fe.g,{name:E("type"),defaultValue:t.type,render:({field:{ref:O,onChange:ee,...pa}})=>e.createElement(ze.Ph,{disabled:!m,inputId:ve,...pa,width:37,options:Me,onChange:ga=>ee(ga?.value)}),control:A,rules:{required:!0}}))),e.createElement("div",{className:p.buttons},g&&s&&e.createElement(I.zx,{disabled:Z,size:"xs",variant:"secondary",type:"button",onClick:()=>Le(),icon:Z?"fa fa-spinner":"message"},"Test"),m&&e.createElement(e.Fragment,null,e.createElement(I.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"copy"},"Duplicate"),r&&e.createElement(I.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"trash-alt"},"Delete")))),_&&e.createElement("div",{className:p.innerContent},e.createElement(Je,{defaultValues:t,selectedChannelOptions:j?.length?j:ce,secureFields:k,errors:d,onResetSecureField:ye,pathPrefix:n,readOnly:!m}),!!(j?.length&&ce?.length)&&e.createElement(Se,{label:`Optional ${_.name} settings`},_.info!==""&&e.createElement(x.b,{title:"",severity:"info"},_.info),e.createElement(Je,{defaultValues:t,selectedChannelOptions:ce,secureFields:k,onResetSecureField:ye,errors:d,pathPrefix:n,readOnly:!m})),e.createElement(Se,{label:"Notification settings"},e.createElement(f,{pathPrefix:n,readOnly:!m}))))}const fn=t=>({buttons:c.css`
    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `,innerContent:c.css`
    max-width: 536px;
  `,wrapper:c.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:c.css`
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  `,channelSettingsHeader:c.css`
    margin-top: ${t.spacing(2)};
  `});function hn({pathPrefix:t}){const{register:n}=(0,F.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function Ze({config:t,initialValues:n,defaultItem:a,notifiers:r,alertManagerSourceName:s,onSubmit:i,onTestChannel:d,takenReceiverNames:u,commonSettingsComponent:f,isEditable:m,isTestable:g}){const p=(0,Xt.iG)(),E=(0,h.wW)(En),A=n||{name:"",items:[{...a,__id:String(Math.random())}]},D=(0,F.cI)({defaultValues:JSON.parse(JSON.stringify(A))});(0,Ae.x)(_=>_.unifiedAlerting.saveAMConfig=ge.oq);const{loading:$}=(0,ne._)(_=>_.saveAMConfig),{handleSubmit:J,register:y,formState:{errors:N},getValues:V}=D,{fields:Z,append:k,remove:pe}=Ke({name:"items",formAPI:D,softDelete:!0}),ye=(0,e.useCallback)(_=>u.map(j=>j.trim().toLowerCase()).includes(_.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[u]),Me=_=>{i({..._,items:_.items.filter(j=>!j.__deleted)})},Le=()=>{p.error("There are errors in the form. Please correct them and try again!")};return e.createElement(F.RV,{...D},!t.alertmanager_config.route&&e.createElement(x.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:J(Me,Le)},e.createElement("h4",{className:E.heading},m?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(te.g,{label:"Name",invalid:!!N.name,error:N.name&&N.name.message,required:!0},e.createElement(le.I,{readOnly:!m,id:"name",...y("name",{required:"Name is required",validate:{nameIsAvailable:ye}}),width:39,placeholder:"Name"})),Z.map((_,j)=>{const ce=`items.${j}.`;if(_.__deleted)return e.createElement(hn,{key:_.__id,pathPrefix:ce});const ve=n?.items.find(({__id:O})=>O===_.__id);return e.createElement(gn,{defaultValues:_,key:_.__id,onDuplicate:()=>{const O=V().items[j];k({...O,__id:String(Math.random())})},onTest:d?()=>{const O=V().items[j];d(O)}:void 0,onDelete:()=>pe(j),pathPrefix:ce,notifiers:r,secureFields:ve?.secureFields,errors:N?.items?.[j],commonSettingsComponent:f,isEditable:m,isTestable:g})}),e.createElement(e.Fragment,null,m&&e.createElement(I.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>k({...a,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:E.buttons},m&&e.createElement(e.Fragment,null,$&&e.createElement(I.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!$&&e.createElement(I.zx,{type:"submit"},"Save contact point")),e.createElement(I.Qj,{disabled:$,fill:"outline",variant:"secondary","data-testid":"cancel-button",href:(0,H.eQ)("alerting/notifications",s)},"Cancel")))))}const En=t=>({heading:c.css`
    margin: ${t.spacing(4,0)};
  `,buttons:c.css`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),Xe=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),qe=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,M.useDispatch)(),s=(0,Q.RY)(n),[i]=(0,e.useMemo)(()=>t?jt(t,Fe):[void 0,{}],[t]),d=m=>{const g=Qt(m,Xe);r((0,q.mM)({newConfig:Ve(a,g,t?.name),oldConfig:a,alertManagerSourceName:n,successMessage:t?"Contact point updated.":"Contact point created.",redirectPath:"/alerting/notifications"}))},u=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:m})=>m).filter(m=>m!==t?.name)??[],[a,t]),f=!(0,Q.RY)(n);return e.createElement(e.Fragment,null,!s&&e.createElement(x.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(Ze,{isEditable:f,isTestable:f,config:a,onSubmit:d,initialValues:i,notifiers:Fe,alertManagerSourceName:n,defaultItem:Xe,takenReceiverNames:u,commonSettingsComponent:Zt}))},yn=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,F.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,null,e.createElement(Te.X,{...r(`${t}disableResolveMessage`),label:"Disable resolved message",description:"Disable the resolve message [OK] that is sent when alerting state returns to false",disabled:a})))};var Ee=o(35029),vn=o(64353),bn=o(2594),An=o(16808),Cn=o(19191),et=(t=>(t.predefined="Predefined",t.custom="Custom",t))(et||{});const Tn=Object.values(et).map(t=>({label:t,value:t})),Sn={annotations:[{key:"",value:""}],labels:[{key:"",value:""}]},Pn=({isOpen:t,onDismiss:n,onTest:a})=>{const[r,s]=(0,e.useState)("Predefined"),i=(0,h.wW)(Rn),d=(0,F.cI)({defaultValues:Sn,mode:"onBlur"}),u=f=>{if(r==="Custom"){const m={annotations:f.annotations.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:E})=>({...g,[p]:E}),{}),labels:f.labels.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:E})=>({...g,[p]:E}),{})};a(m)}else a()};return e.createElement(Ee.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:i.section},e.createElement(vn._,null,"Notification message"),e.createElement(bn.S,{options:Tn,value:r,onChange:f=>s(f)})),e.createElement(F.RV,{...d},e.createElement("form",{onSubmit:d.handleSubmit(u)},r==="Predefined"&&e.createElement("div",{className:i.section},"You will send a test notification that uses a predefined alert. If you have defined a custom template or message, for better results switch to ",e.createElement("strong",null,"custom")," notification message, from above."),r==="Custom"&&e.createElement(e.Fragment,null,e.createElement("div",{className:i.section},"You will send a test notification that uses the annotations defined below. This is a good option if you use custom templates and messages."),e.createElement("div",{className:i.section},e.createElement(An.Z,null)),e.createElement("div",{className:i.section},e.createElement(Cn.Z,null))),e.createElement(Ee.u.ButtonRow,null,e.createElement(I.zx,{type:"submit"},"Send test notification")))))},Rn=t=>({flexRow:c.css`
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: ${t.spacing(1)};
  `,section:c.css`
    margin-bottom: ${t.spacing(2)};
  `}),Pe=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),tt=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,ne._)(y=>y.grafanaNotifiers),[s,i]=(0,e.useState)(),d=(0,M.useDispatch)();(0,e.useEffect)(()=>{r.result||r.loading||d((0,q.Vj)())},[r,d]);const[u,f]=(0,e.useMemo)(()=>!t||!r.result?[void 0,{}]:zt(t,r.result),[t,r.result]),m=y=>{const N=Ht(y,f,Pe);d((0,q.mM)({newConfig:Ve(a,N,t?.name),oldConfig:a,alertManagerSourceName:Q.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},g=y=>{i(y)},p=y=>{if(s){const N=f[s.__id],V=Be(s,Pe,"test",N),Z={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[V]}],alert:y};d((0,q.D8)(Z))}},E=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:y})=>y).filter(y=>y!==t?.name)??[],[a,t]),A=t?(t.grafana_managed_receiver_configs??[]).some(y=>Boolean(y.provenance)):!1,D=!(0,Q.RY)(n),$=D&&!A,J=D||A;return r.result?e.createElement(e.Fragment,null,A&&e.createElement(ie.Xq,{resource:ie.Uv.ContactPoint}),e.createElement(Ze,{isEditable:$,isTestable:J,config:a,onSubmit:m,initialValues:u,onTestChannel:g,notifiers:r.result,alertManagerSourceName:n,defaultItem:Pe,takenReceiverNames:E,commonSettingsComponent:yn}),e.createElement(Pn,{onDismiss:()=>i(void 0),isOpen:!!s,onTest:y=>p(y)})):e.createElement(w.u,{text:"Loading notifiers..."})},Dn=({config:t,receiverName:n,alertManagerSourceName:a})=>{const r=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return r?a===Q.GC?e.createElement(tt,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(qe,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(x.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},xn=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n],s=t.template_file_provenances?.[n];return r?e.createElement(Ce,{alertManagerSourceName:a,config:t,existing:{name:n,content:r},provenance:s}):e.createElement(x.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var nt=o(52081);const at={smtp_require_tls:!0},Mn=({config:t,alertManagerSourceName:n})=>{const a=(0,M.useDispatch)();(0,Ae.x)(g=>g.unifiedAlerting.saveAMConfig=ge.oq);const{loading:r,error:s}=(0,ne._)(g=>g.saveAMConfig),i=(0,Q.RY)(n),d=(0,F.cI)({defaultValues:JSON.parse(JSON.stringify({...at,...t.alertmanager_config.global??{}}))}),{handleSubmit:u,formState:{errors:f}}=d,m=g=>{a((0,q.mM)({newConfig:{...t,alertmanager_config:{...t.alertmanager_config,global:me(g)}},oldConfig:t,alertManagerSourceName:n,successMessage:"Global config updated.",redirectPath:(0,H.eQ)("/alerting/notifications",n)}))};return e.createElement(F.RV,{...d},e.createElement("form",{onSubmit:u(m)},s&&e.createElement(x.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),Kt.map(g=>e.createElement(he,{readOnly:i,defaultValue:at[g.propertyName],key:g.propertyName,option:g,error:f[g.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(nt.Lh,null,!i&&e.createElement(e.Fragment,null,r&&e.createElement(I.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!r&&e.createElement(I.zx,{type:"submit"},"Save global config")),e.createElement(I.Qj,{disabled:r,fill:"outline",variant:"secondary",href:(0,H.eQ)("alerting/notifications",n)},"Cancel")))))},Ln=({alertManagerSourceName:t,config:n})=>t===Q.GC?e.createElement(tt,{alertManagerSourceName:t,config:n}):e.createElement(qe,{alertManagerSourceName:t,config:n}),On=({config:t,alertManagerSourceName:n})=>e.createElement(Ce,{config:t,alertManagerSourceName:n});var oe=o(51981),In=o(46519),Nn=o(38849),Re=o(19985),rt=o(98102),De=o(82002),ot=o(85655),st=o(97953),wn=o(20194);const $n={pagerduty:"PagerDuty",pushover:"Pushover",slack:"Slack",opsgenie:"OpsGenie",webhook:"Webhook",victorops:"VictorOps",wechat:"WeChat"};function kn(t,n){return t.grafana_managed_receiver_configs?Wn(t.grafana_managed_receiver_configs??[],n):_n(t)}function _n(t){return Object.entries(t).filter(([n])=>n!=="grafana_managed_receiver_configs"&&n.endsWith("_configs")).filter(([n,a])=>Array.isArray(a)&&!!a.length).reduce((n,[a,r])=>{const s=a.replace("_configs",""),i=$n[s]??(0,X.capitalize)(s);return{...n,[i]:(n[i]??0)+(Array.isArray(r)?r.length:1)}},{})}function Wn(t,n){return t.map(a=>a.type).map(a=>n.find(r=>r.type===a)?.name??(0,X.capitalize)(a)).reduce((a,r)=>({...a,[r]:(a[r]??0)+1}),{})}var lt=o(53731),Un=o(16144);const it=({className:t,title:n,description:a,addButtonLabel:r,addButtonTo:s,children:i,showButton:d=!0})=>{const u=(0,h.wW)(Fn);return e.createElement(T.Stack,{direction:"column",gap:2},e.createElement("div",{className:(0,c.cx)(u.heading,t)},e.createElement("div",null,e.createElement("h4",null,n),e.createElement("div",{className:u.description},a)),d&&e.createElement(Un.Link,{to:s},e.createElement(I.zx,{type:"button",icon:"plus"},r))),i)},Fn=t=>({heading:c.css`
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  `,description:c.css`
    color: ${t.colors.text.secondary};
  `});var xe=o(2390);const Vn={[xe.W.OnCall]:"public/img/alerting/oncall_logo.svg",[xe.W.Incident]:"",[xe.W.MachineLearning]:""},Gn=({grafanaAppType:t})=>{const n=(0,h.wW)(Bn);return e.createElement("div",{className:n.wrapper},e.createElement(nt.Lh,{align:"center",spacing:"xs"},e.createElement("img",{src:Vn[t],alt:"",height:"12px"}),e.createElement("span",null,t)))},Bn=t=>({wrapper:c.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 Kn=o(52259);function zn({permissions:t,alertManagerName:n,receiverName:a,onClickDeleteReceiver:r}){return e.createElement(e.Fragment,null,e.createElement(oe.q,{actions:[t.update]},e.createElement(Y.A,{"aria-label":"Edit","data-testid":"edit",to:(0,H.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"Edit contact point",icon:"pen"})),e.createElement(oe.q,{actions:[t.delete]},e.createElement(Y.A,{onClick:()=>r(a),tooltip:"Delete contact point",icon:"trash-alt"})))}function jn({permissions:t,alertManagerName:n,receiverName:a}){return e.createElement(oe.q,{actions:[t.update]},e.createElement(Y.A,{"data-testid":"view",to:(0,H.eQ)(`/alerting/notifications/receivers/${encodeURIComponent(a)}/edit`,n),tooltip:"View contact point",icon:"file-alt"}))}function ct({errorCount:t,errorDetail:n,showErrorCount:a}){const r=a?`${t} ${b()("error",t)}`:"Error";return e.createElement(Re.C,{color:"orange",icon:"exclamation-triangle",text:r,tooltip:n??"Error"})}function Hn({errorsByNotifier:t,errorDetail:n,lastNotify:a}){const r=ue(a)?"orange":"green",s=ue(a)?"No attempts":"OK";return t>0?e.createElement(ct,{errorCount:t,errorDetail:n,showErrorCount:!1}):e.createElement(Re.C,{color:r,text:s,tooltip:""})}function Qn({errorsByReceiver:t,someWithNoAttempt:n}){const a=n?"orange":"green",r=n?"No attempts":"OK";return t>0?e.createElement(ct,{errorCount:t,showErrorCount:!0}):e.createElement(Re.C,{color:a,text:r,tooltip:""})}const Yn=t=>{const n=(0,U.V)(t),a=n?.receivers??{},r=Object.keys(a).length>0;return{contactPointsState:n,errorStateAvailable:r}},ue=t=>t==="0001-01-01T00:00:00.000Z";function Jn({lastNotifyDate:t}){return ue(t)?e.createElement(e.Fragment,null,"-"):e.createElement(T.Stack,{alignItems:"center"},e.createElement("div",null,`${(0,In.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(R.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,Nn.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const Zn=["","0","0ms","0s","0m","0h","0d","0w","0y"],Xn=t=>Zn.includes(t);function qn({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:r,lastNotify:s}})=>e.createElement(Hn,{errorsByNotifier:r?1:0,errorDetail:r??void 0,lastNotify:s}),size:.5},{id:"name",label:"Name",renderCell:({data:{type:r},id:s})=>e.createElement(e.Fragment,null,`${r}[${s}]`),size:1},{id:"lastNotify",label:"Last delivery attempt",renderCell:({data:{lastNotify:r}})=>e.createElement(Jn,{lastNotifyDate:r}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:r,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,ue(r)&&Xn(s)?"-":s),size:1},{id:"sendResolved",label:"Send resolved",renderCell:({data:{sendResolved:r}})=>e.createElement(e.Fragment,null,String(Boolean(r))),size:1}]}const a=Object.entries(t).flatMap(r=>r[1].map((s,i)=>({id:i,data:{type:r[0],lastError:s.lastNotifyAttemptError,lastNotify:s.lastNotifyAttempt,lastNotifyDuration:s.lastNotifyAttemptDuration,sendResolved:s.sendResolved}})));return e.createElement(lt.t,{items:a,cols:n()})}const ea=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),r=(0,Q.RY)(n),s=(0,st.Ko)(n),i=(0,ne._)(y=>y.grafanaNotifiers),{contactPointsState:d,errorStateAvailable:u}=Yn(n),[f,m]=(0,e.useState)(),[g,p]=(0,e.useState)(!1),E=y=>{(0,wn.nv)(y,t)?p(!0):m(y)},A=()=>{f&&a((0,q.X4)(f,n)),m(void 0)},D=(0,Kn.HU)(t.alertmanager_config.receivers??[]),$=(0,e.useMemo)(()=>D?.map(y=>({id:y.name,data:{name:y.name,types:Object.entries(kn(y,i.result??[])).map(([N,V])=>V>1?`${N} (${V})`:N),grafanaAppReceiverType:y.grafanaAppReceiverType,provisioned:y.grafana_managed_receiver_configs?.some(N=>N.provenance)}}))??[],[i.result,D]),J=aa(n,u,d,E,s,r);return e.createElement(it,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!r&&De.Vt.hasPermission(s.create),addButtonLabel:"Add contact point",addButtonTo:(0,H.eQ)("/alerting/notifications/receivers/new",n)},e.createElement(lt.t,{items:$,cols:J,isExpandable:u,renderExpandedContent:u?({data:{name:y}})=>e.createElement(qn,{notifiersState:d?.receivers[y]?.notifiers??{}}):void 0}),!!g&&e.createElement(Ee.u,{isOpen:!0,title:"Cannot delete contact point",onDismiss:()=>p(!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(Ee.u.ButtonRow,null,e.createElement(I.zx,{variant:"secondary",onClick:()=>p(!1),fill:"outline"},"Close"))),!!f&&e.createElement(rt.s,{isOpen:!0,title:"Delete contact point",body:`Are you sure you want to delete contact point "${f}"?`,confirmText:"Yes, delete",onConfirm:A,onDismiss:()=>m(void 0)}))},ta=(t,n)=>t?.receivers[n]?.errorCount??0,na=(t,n)=>{const a=Object.values(t?.receivers[n]?.notifiers??{});return a.length===0||a.flat().some(s=>ue(s.lastNotifyAttempt))};function aa(t,n,a,r,s,i){const d=(0,h.wW)(ot.D),u=[{id:"name",label:"Contact point name",renderCell:({data:{name:m,provisioned:g}})=>e.createElement(T.Stack,{alignItems:"center"},e.createElement("div",null,m),g&&e.createElement(ie.C0,null)),size:1},{id:"type",label:"Type",renderCell:({data:{types:m,grafanaAppReceiverType:g}})=>e.createElement(e.Fragment,null,g?e.createElement(Gn,{grafanaAppType:g}):m.join(", ")),size:1}],f={id:"health",label:"Health",renderCell:({data:{name:m}})=>a&&e.createElement(Qn,{errorsByReceiver:ta(a,m),someWithNoAttempt:na(a,m)}),size:1};return[...u,...n?[f]:[],{id:"actions",label:"Actions",renderCell:({data:{provisioned:m,name:g}})=>e.createElement(oe.q,{actions:[s.update,s.delete]},e.createElement("div",{className:d.actionsCell},!i&&!m&&e.createElement(zn,{permissions:s,alertManagerName:t,receiverName:g,onClickDeleteReceiver:r}),(i||m)&&e.createElement(jn,{permissions:s,alertManagerName:t,receiverName:g}))),size:"100px"}]}var ra=o(80498);const oa=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),[r,s]=(0,e.useState)({}),i=(0,h.wW)(ot.D),d=(0,st.Ko)(n),u=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([E,A])=>({name:E,template:A,provenance:(t.template_file_provenances??{})[E]})),[t]),[f,m]=(0,e.useState)(),g=()=>{f&&a((0,q.S6)(f,n)),m(void 0)};return e.createElement(it,{title:"Notification templates",description:"Create notification templates to customize your notifications.",addButtonLabel:"Add template",addButtonTo:(0,H.eQ)("/alerting/notifications/templates/new",n),showButton:De.Vt.hasPermission(d.create)},e.createElement("table",{className:i.table,"data-testid":"templates-table"},e.createElement("colgroup",null,e.createElement("col",{className:i.colExpand}),e.createElement("col",null),e.createElement("col",null)),e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null),e.createElement("th",null,"Template"),e.createElement(oe.q,{actions:[d.update,d.delete]},e.createElement("th",null,"Actions")))),e.createElement("tbody",null,!u.length&&e.createElement("tr",{className:i.evenRow},e.createElement("td",{colSpan:3},"No templates defined.")),u.map(({name:p,template:E,provenance:A},D)=>{const $=!!r[p];return e.createElement(e.Fragment,{key:p},e.createElement("tr",{key:p,className:D%2===0?i.evenRow:void 0},e.createElement("td",null,e.createElement(He.U,{isCollapsed:!r[p],onToggle:()=>s({...r,[p]:!$})})),e.createElement("td",null,p," ",A&&e.createElement(ie.C0,null)),e.createElement("td",{className:i.actionsCell},A&&e.createElement(Y.A,{to:(0,H.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!A&&e.createElement(oe.q,{actions:[d.update]},e.createElement(Y.A,{to:(0,H.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/edit`,n),tooltip:"edit template",icon:"pen"})),De.Vt.hasPermission(d.create)&&e.createElement(Y.A,{to:(0,H.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!A&&e.createElement(oe.q,{actions:[d.delete]},e.createElement(Y.A,{onClick:()=>m(p),tooltip:"delete template",icon:"trash-alt"})))),$&&e.createElement("tr",{className:D%2===0?i.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(ra.C,{label:"Description",horizontal:!0},e.createElement(ke,{width:"auto",height:"auto",autoHeight:!0,value:E,showLineNumbers:!1,monacoOptions:{readOnly:!0,scrollBeyondLastLine:!1}})))))}))),!!f&&e.createElement(rt.s,{isOpen:!0,title:"Delete template",body:`Are you sure you want to delete template "${f}"?`,confirmText:"Yes, delete",onConfirm:g,onDismiss:()=>m(void 0)}))},sa=({config:t,alertManagerName:n})=>{const a=n!==Q.GC,r=(0,Q.RY)(n);return e.createElement(T.Stack,{direction:"column",gap:4},e.createElement(ea,{config:t,alertManagerName:n}),!r&&e.createElement(oa,{config:t,alertManagerName:n}),a&&e.createElement(oe.q,{actions:[M.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(x.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(I.Qj,{href:(0,H.eQ)("alerting/notifications/global-config",n),variant:"secondary"},r?"View global config":"Edit global config"))))};var la=o(29614),ia=o(23403);function ca({errorCount:t}){const n=(0,h.wW)(dt);return e.createElement("div",{className:n.warning,"data-testid":"receivers-notification-error"},e.createElement(T.Stack,{alignItems:"flex-end",direction:"column"},e.createElement(T.Stack,{alignItems:"center"},e.createElement(R.J,{name:"exclamation-triangle"}),e.createElement("div",{className:n.countMessage},`${t} ${b()("error",t)} with contact points`)),e.createElement("div",null,"Some alert notifications might not be delivered")))}const da=()=>{const t=(0,ia.k)("notification"),[n,a]=(0,la.k)(t),r=(0,M.useDispatch)(),s=(0,h.wW)(dt),{id:i,type:d}=(0,v.UO)(),u=(0,v.TH)(),f=u.pathname.endsWith("/alerting/notifications"),m=_e(u),g=(0,ne._)(k=>k.amConfigs),{result:p,loading:E,error:A}=n&&g[n]||ge.oq,D=(0,ne._)(k=>k.grafanaNotifiers),$=f||!p,J=f;(0,e.useEffect)(()=>{n&&$&&r((0,q.Yh)(n))},[n,r,$]),(0,e.useEffect)(()=>{n===Q.GC&&!(D.result||D.loading||D.error)&&r((0,q.Vj)())},[n,r,D]);const N=(0,U.V)(n??"")?.errorCount??0,V=!f;let Z=ma(d,i?decodeURIComponent(i):void 0,m);return n?e.createElement(L.J,{pageId:"receivers",pageNav:Z},e.createElement("div",{className:s.headingContainer},e.createElement(P.P,{current:n,disabled:V,onChange:a,dataSources:t}),J&&N>0&&e.createElement(ca,{errorCount:N})),A&&!E&&e.createElement(x.b,{severity:"error",title:"Error loading Alertmanager config"},A.message||"Unknown error."),e.createElement(K.u,{currentAlertmanager:n}),E&&!p&&e.createElement(w.u,{text:"loading configuration..."}),p&&!A&&e.createElement(v.rs,null,e.createElement(v.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(sa,{config:p,alertManagerName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(On,{config:p,alertManagerSourceName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:k})=>k?.params.name&&e.createElement(Gt,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(k?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:k})=>k?.params.name&&e.createElement(xn,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(k?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(Ln,{config:p,alertManagerSourceName:n})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:k})=>k?.params.name&&e.createElement(Dn,{alertManagerSourceName:n,config:p,receiverName:decodeURIComponent(k?.params.name)})),e.createElement(v.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(Mn,{config:p,alertManagerSourceName:n})))):f?e.createElement(L.J,{pageId:"receivers",pageNav:Z},e.createElement(z.I,{availableAlertManagers:t})):e.createElement(v.l_,{to:"/alerting/notifications"})};function ma(t,n,a){let r;if(a)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?r={text:n,subTitle:`Edit the settings for a specific ${s}`}:r={text:`New ${s}`,subTitle:`Create a new ${s} for your notifications`}}else t==="global-config"&&(r={text:"Global config",subTitle:"Manage your global configuration"});return r}const ua=(0,W.Pf)(da,{style:"page"}),dt=t=>({warning:c.css`
    color: ${t.colors.warning.text};
  `,countMessage:c.css`
    padding-left: 10px;
  `,headingContainer:c.css`
    display: flex;
    justify-content: space-between;
  `})},30173:(G,S,o)=>{o.d(S,{h:()=>C});var c=o(29427);const C=c.C.injectEndpoints({endpoints:b=>({getAlertmanagerChoiceStatus:b.query({query:()=>({url:"/api/v1/ngalert"}),providesTags:["AlertmanagerChoice"]}),getExternalAlertmanagerConfig:b.query({query:()=>({url:"/api/v1/ngalert/admin_config"}),providesTags:["AlertmanagerChoice"]}),getExternalAlertmanagers:b.query({query:()=>({url:"/api/v1/ngalert/alertmanagers"}),transformResponse:e=>e.data}),saveExternalAlertmanagersConfig:b.mutation({query:e=>({url:"/api/v1/ngalert/admin_config",method:"POST",data:e}),invalidatesTags:["AlertmanagerChoice"]})})})},96678:(G,S,o)=>{o.d(S,{V:()=>v});var c=o(37190),C=o(29427),b=o(644);const e=C.C.injectEndpoints({endpoints:T=>({contactPointsState:T.query({queryFn:async({amSourceName:h})=>{try{return{data:await(0,b.QE)(h)}}catch(R){return{error:R}}}})})}),v=T=>{const h={receivers:{},errorCount:0},{currentData:R}=e.useContactPointsStateQuery({amSourceName:T??""},{skip:!T,pollingInterval:c.m4});return R??h}},51981:(G,S,o)=>{o.d(S,{q:()=>b});var c=o(68404),C=o(82002);const b=({actions:e,children:v,fallback:T=!0})=>e.some(h=>C.Vt.hasAccess(h,T))?c.createElement(c.Fragment,null,v):null},731:(G,S,o)=>{o.d(S,{u:()=>R});var c=o(9892),C=o(68404),b=o(72648),e=o(45253),v=o(39031),T=o(30173),h=o(45849);function R({currentAlertmanager:w}){const W=(0,b.wW)(x),{useGetAlertmanagerChoiceStatusQuery:M}=T.h,{currentData:U}=M(),P=w===h.GC;if(!(U?.alertmanagersChoice&&[v.TE.External,v.TE.All].includes(U?.alertmanagersChoice))||!P)return null;const K=U.numExternalAlertmanagers>0;return U.alertmanagersChoice===v.TE.External?C.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.",C.createElement("div",{className:W.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):U.alertmanagersChoice===v.TE.All&&K?C.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.",C.createElement("div",{className:W.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const x=w=>({adminHint:c.css`
    font-size: ${w.typography.bodySmall.fontSize};
    font-weight: ${w.typography.bodySmall.fontWeight};
  `})},88331:(G,S,o)=>{o.d(S,{I:()=>h});var c=o(68404),C=o(45253),b=o(29614),e=o(94984);const v=()=>c.createElement(C.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."),T=()=>c.createElement(C.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."),h=({availableAlertManagers:R})=>{const[x,w]=(0,b.k)(R),W=R.length>0;return c.createElement("div",null,W?c.createElement(c.Fragment,null,c.createElement(e.P,{onChange:w,dataSources:R}),c.createElement(T,null)):c.createElement(v,null))}},40106:(G,S,o)=>{o.d(S,{C0:()=>T,Uv:()=>e,Xq:()=>v});var c=o(68404),C=o(45253),b=o(19985),e=(h=>(h.ContactPoint="contact point",h.Template="template",h.MuteTiming="mute timing",h.AlertRule="alert rule",h.RootNotificationPolicy="root notification policy",h))(e||{});const v=({resource:h})=>c.createElement(C.b,{title:`This ${h} cannot be edited through the UI`,severity:"info"},"This ",h," has been provisioned, that means it was created by config. Please contact your server admin to update this ",h,"."),T=()=>c.createElement(b.C,{text:"Provisioned",color:"purple"})},52259:(G,S,o)=>{o.d(S,{Kt:()=>M,HU:()=>U});var c=o(65583),C=o(54899),b=o(29427);const e=b.C.injectEndpoints({endpoints:P=>({getOnCallIntegrations:P.query({queryFn:async()=>({data:await v()}),providesTags:["AlertmanagerChoice"]})})});async function v(){try{return(await(0,c.n)((0,C.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(L=>L.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:T}=e;var h=o(58509),R=o(2390);const x=(P,L)=>L.includes(P),w=(P,L)=>{if(!P.grafana_managed_receiver_configs)return!1;const K=P.grafana_managed_receiver_configs.length===1,z=x(P.grafana_managed_receiver_configs[0]?.settings?.url??"",L);return K&&z},W=()=>{const{installed:P}=(0,h.n)(R.W.OnCall),{data:L}=T(void 0,{skip:!P});return z=>{if(P&&w(z,L??[]))return R.W.OnCall}},M=P=>{const L=W(),K=z=>({label:z.name,value:z.name,grafanaAppReceiverType:L(z)});return P.map(K)},U=P=>{const L=W();return P.map(K=>({...K,grafanaAppReceiverType:L(K)}))}},65750:(G,S,o)=>{o.d(S,{A:()=>e});var c=o(68404),C=o(6554),b=o(31403);const e=({tooltip:v,icon:T,to:h,target:R,onClick:x,className:w,tooltipPlacement:W="top",...M})=>{const U=typeof v=="string"?v:void 0;return c.createElement(C.u,{content:v,placement:W},h?c.createElement(b.Qj,{variant:"secondary",fill:"text",icon:T,href:h,size:"sm",target:R,...M,"aria-label":U}):c.createElement(b.zx,{className:w,variant:"secondary",fill:"text",size:"sm",icon:T,type:"button",onClick:x,...M,"aria-label":U}))}},29614:(G,S,o)=>{o.d(S,{k:()=>h});var c=o(68404),C=o(96044),b=o(58379),e=o(37190),v=o(45849);function T(R){return(0,c.useCallback)(x=>R.map(W=>W.name).includes(x),[R])}function h(R){const[x,w]=(0,C.K)(),W=T(R),M=(0,c.useCallback)(L=>{W(L)&&(L===v.GC?(b.Z.delete(e.de),w({[e.c4]:null})):(b.Z.set(e.de,L),w({[e.c4]:L})))},[w,W]),U=x[e.c4];if(U&&typeof U=="string")return W(U)?[U,M]:[void 0,M];const P=b.Z.get(e.de);return P&&typeof P=="string"&&W(P)?(M(P),[P,M]):W(v.GC)?[v.GC,M]:[void 0,M]}},23403:(G,S,o)=>{o.d(S,{k:()=>b});var c=o(68404),C=o(45849);function b(e){return(0,c.useMemo)(()=>(0,C.LE)(e),[e])}},58509:(G,S,o)=>{o.d(S,{n:()=>b});var c=o(22350),C=o(13011);function b(e){const{loading:v,error:T,value:h}=(0,c.Z)(()=>(0,C.a)(e,{showErrorAlert:!1})),R=h&&!T&&!v,x=h?.enabled;return v&&!h?{loading:!0}:!R||!x?{loading:!1,installed:!1}:{loading:v,installed:!0,settings:h}}},85655:(G,S,o)=>{o.d(S,{D:()=>C});var c=o(9892);const C=b=>({table:c.css`
    width: 100%;
    border-radius: ${b.shape.borderRadius()};
    border: solid 1px ${b.colors.border.weak};
    background-color: ${b.colors.background.secondary};

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

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

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

    & > * + * {
      margin-left: ${b.spacing(.5)};
    }
  `})},2390:(G,S,o)=>{o.d(S,{W:()=>c});var c=(C=>(C.Incident="grafana-incident-app",C.OnCall="grafana-oncall-app",C.MachineLearning="grafana-ml-app",C))(c||{})},35918:(G,S,o)=>{o.d(S,{G:()=>c});function c(C,b){const e=C.replace(/\(copy( [0-9]+)?\)$/,"").trim();let v=`${e} (copy)`;for(let T=2;b.includes(v);T++)v=`${e} (copy ${T})`;return v}}}]);

//# sourceMappingURL=NotificationsListPage.7d0b3c8aaa1cb1664107.js.map