"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[6618],{5906:(_,T,o)=>{o.r(T),o.d(T,{default:()=>M});var c=o(68404),A=o(671),b=o(54899),e=o(31403),y=o(52081),S=o(69142),E=o(79396),D=o(77582),P=o(76770),O=o(45984);const M=()=>{const F=(0,P.q)("channels"),[R,I]=(0,c.useState)([]),z=async()=>await(0,b.i)().get("/api/alert-notifications"),[K,se]=(0,A.Z)(z);(0,c.useEffect)(()=>{se().then(G=>{I(G)})},[se]);const ge=G=>{D.h$.publish(new O.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()=>{Ae(G)}}))},Ae=async G=>{await(0,b.i)().delete(`/api/alert-notifications/${G}`);const Ce=await se();I(Ce)};return c.createElement(E.T,{navModel:F},c.createElement(E.T.Contents,null,K.error&&c.createElement("p",null,K.error),!!R.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,R.map(G=>c.createElement("tr",{key:G.id},c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${G.id}/edit`},G.name)),c.createElement("td",{className:"link-td"},c.createElement("a",{href:`alerting/notification/${G.id}/edit`},G.type)),c.createElement("td",{className:"text-right"},c.createElement(y.Lh,{justify:"flex-end"},G.isDefault&&c.createElement(e.zx,{disabled:!0,variant:"secondary",size:"sm"},"default"),c.createElement(e.zx,{variant:"destructive",icon:"times",size:"sm",onClick:()=>{ge(G.id)}})))))))),!(R.length||K.loading)&&c.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"})))}},68732:(_,T,o)=>{o.r(T),o.d(T,{default:()=>pa});var c=o(52423),A=o(64681),b=o.n(A),e=o(68404),y=o(70356),S=o(26418),E=o(72648),D=o(39904),P=o(45253),O=o(61744),U=o(53546),M=o(81168),F=o(37190),R=o(29427),I=o(644);const z=R.C.injectEndpoints({endpoints:t=>({contactPointsState:t.query({queryFn:async({amSourceName:n})=>{try{return{data:await(0,I.QE)(n)}}catch(a){return{error:a}}}})})}),K=t=>{const n={receivers:{},errorCount:0},{currentData:a}=z.useContactPointsStateQuery({amSourceName:t??""},{skip:!t,pollingInterval:F.m4});return a??n};var se=o(94984),ge=o(45524),Ae=o(731),G=o(88331),Ce=o(35918),ee=o(82897);function mt(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 ut(t){const n=(a,r)=>`{{ define "${r}_NEW_${(0,ee.now)()}" }}`;return t.replace(/\{\{\s*define\s*\"(?<defineName>.*)\"\s*\}\}/g,n)}var B=o(59052),pt=o(89050),gt=o(13393),te=o(24799),le=o(46967),N=o(31403),Te=o(40014),ne=o(69945),X=o(72004),H=o(10505),fe=o(46818),ie=o(40106),Ie=o(42042);const ft=[{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."}],ht=[{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."}],Et=[{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"}],yt=`{
  "summary": "alert summary",
  "description": "alert description"
}
`;function vt(){const t=(0,E.wW)(bt),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:ht});return e.createElement(S.Stack,{gap:2,flexGrow:1},e.createElement(Ne,{caption:e.createElement("h4",{className:t.header},"Template Data"),dataItems:ft,typeRenderer:a=>a==="[]Alert"?e.createElement(Ie.z,{content:n},e.createElement("div",{className:t.interactiveType},a)):a==="KeyValue"?e.createElement(Ie.z,{content:e.createElement(At,null)},e.createElement("div",{className:t.interactiveType},a)):a}))}const bt=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 Ne({dataItems:t,caption:n,typeRenderer:a}){const r=(0,E.wW)(we);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 At(){const t=(0,E.wW)(we);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,yt)),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,Et.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 we=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 Ct=o(9405),ae=o(86922);function Tt(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 St=`
{{ range .Alerts }}
  Status: {{ .Status }}
  Starts at: {{ .StartsAt }}
{{ end }}
`,Pt=`
[{{.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 }}
`,Rt=de("GroupLabels"),xt=de("CommonLabels"),Dt=de("CommonAnnotations"),Mt=de("Labels"),Lt=de("Annotations");function de(t){return`
{{ range .${t} }}
  {{ .Name }} = {{ .Value }}
{{ end }}`}function Ot(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 It(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 Nt(t){const n=t.languages.CompletionItemKind.Field;return[{label:"Firing",kind:n,detail:"Alert[]"},{label:"Resolved",kind:n,detail:"Alert[]"}]}function wt(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 $e={alerts:{label:"alertsloop",description:"Renders a loop through alerts",snippet:St},alertDetails:{label:"alertdetails",description:"Renders all information available about the alert",snippet:Pt},groupLabels:{label:"grouplabelsloop",description:"Renders a loop through group labels",snippet:Rt},commonLabels:{label:"commonlabelsloop",description:"Renders a loop through common labels",snippet:xt},commonAnnotations:{label:"commonannotationsloop",description:"Renders a loop through common annotations",snippet:Dt},labels:{label:"labelsloop",description:"Renders a loop through labels",snippet:Mt},annotations:{label:"annotationsloop",description:"Renders a loop through annotations",snippet:Lt}};function $t(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}=$e;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 kt(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 Ut(t,d);if(!Wt(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 Wt(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 Ut{constructor(n,a){this.monaco=n,this.range=a,this.getSnippetsSuggestions=()=>this.getCompletionsFromDefinitions($t(this.monaco)),this.getFunctionsSuggestions=()=>this.getCompletionsFromDefinitions(Tt(this.monaco)),this.getTemplateDataSuggestions=r=>{switch(r){case"":return this.getCompletionsFromDefinitions(Ot(this.monaco),It(this.monaco));case"Alerts":return this.getCompletionsFromDefinitions(Nt(this.monaco));case"GroupLabels":case"CommonLabels":case"CommonAnnotations":case"Labels":case"Annotations":return this.getCompletionsFromDefinitions(wt(this.monaco));default:return{suggestions:[]}}},this.getCompletionsFromDefinitions=(...r)=>({suggestions:(0,ee.concat)(...r).map(i=>Ft(i,this.range))})}}function Ft({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 ke="go-template",_t={id:ke,extensions:[],aliases:[],mimetypes:[],loader:()=>Promise.resolve().then(o.bind(o,86922))},Vt=(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)}))},We=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(Ct.p,{showLineNumbers:!0,showMiniMap:!1,...t,onEditorDidMount:r,onBeforeEditorMount:s=>{Vt(s,_t),a.current=kt(s)},language:ke})},Gt=Object.freeze({name:"",content:""}),Ue=t=>t.pathname.endsWith("/duplicate"),Se=({existing:t,alertManagerSourceName:n,config:a,provenance:r})=>{const s=(0,E.wW)(Fe),i=(0,M.useDispatch)();(0,Te.x)(v=>v.unifiedAlerting.saveAMConfig=fe.oq);const{loading:d,error:u}=(0,ne._)(v=>v.saveAMConfig),f=(0,y.TH)(),m=Ue(f),g=v=>{const w=mt(v.name,v.content),V={...a.template_files,[v.name]:w};t&&t.name!==v.name&&delete V[t.name];const Z=[...(a.alertmanager_config.templates??[]).filter(pe=>pe!==t?.name),v.name],k={template_files:V,alertmanager_config:{...a.alertmanager_config,templates:Z}};i((0,X.mM)({alertManagerSourceName:n,newConfig:k,oldConfig:a,successMessage:"Template saved.",redirectPath:"/alerting/notifications"}))},{handleSubmit:p,register:h,formState:{errors:C},getValues:x,setValue:$}=(0,B.cI)({mode:"onSubmit",defaultValues:t??Gt}),J=v=>!a.template_files[v]||t?.name===v?!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(P.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(gt.C,{disabled:Boolean(r)},e.createElement(te.g,{label:"Template name",error:C?.name?.message,invalid:!!C.name?.message,required:!0},e.createElement(le.I,{...h("name",{required:{value:!0,message:"Required."},validate:{nameIsUnique:J}}),placeholder:"Give your template a name",width:42,autoFocus:!0})),e.createElement(Bt,null),e.createElement("div",{className:s.contentContainer},e.createElement("div",null,e.createElement(te.g,{label:"Content",error:C?.content?.message,invalid:!!C.content?.message,required:!0},e.createElement("div",{className:s.editWrapper},e.createElement(pt.Z,null,({width:v,height:w})=>e.createElement(We,{value:x("content"),width:v,height:w,onBlur:V=>$("content",V)})))),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,H.eQ)("alerting/notifications",n),variant:"secondary",type:"button",fill:"outline"},"Cancel"))),e.createElement(vt,null))))};function Bt(){const t=(0,E.wW)(Fe);return e.createElement(P.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"},"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($e).map(n=>n.label).join(", "))))}const Fe=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;
  `}),Kt=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n];if(!r)return e.createElement(P.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.");const s=(0,Ce.G)(n,Object.keys(t.template_files));return e.createElement(Se,{alertManagerSourceName:a,config:t,existing:{name:s,content:ut(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 zt=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","")]}),_e=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."),zt,_e]}),Ve=[{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"}),_e]},{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]}],jt=[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 Ht(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 Xt(d,i,u)})??[]},a]}function Qt(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 Zt(m,d,f)})).flat();return[{name:t.name,items:s},a]}function Yt(t,n,a){return{name:t.name,grafana_managed_receiver_configs:(t.items??[]).map(r=>{const s=n[r.__id];return Ke(r,a,t.name,s)})}}function Jt(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 Ge(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=Be(s.alertmanager_config.route,a,n.name)),s}function Be(t,n,a){const r={...t};return r.receiver===n&&(r.receiver=a),r.routes&&(r.routes=r.routes.map(s=>Be(s,n,a))),r}function Zt(t,n,a){return{__id:t,type:n,settings:{...a},secureFields:{},secureSettings:{},sendResolved:a.send_resolved}}function Xt(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 Ke(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,ee.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 Pe=o(58255);const qt=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,B.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,{disabled:a},e.createElement(Pe.X,{...r(`${t}sendResolved`),label:"Send resolved",disabled:a,description:"Whether or not to notify about resolved alerts."})))};var en=o(60499);const tn=[];function ze(t){const{name:n,formAPI:a,defaults:r,softDelete:s}=t,{watch:i,getValues:d,reset:u,setValue:f}=a,m=i(n)??r??tn,g=(0,e.useCallback)(p=>{const h=JSON.parse(JSON.stringify(d())),C=p(m??[]);u((0,ee.set)(h,n,C))},[d,n,u,m]);return{fields:m,append:(0,e.useCallback)(p=>g(h=>[...h,p]),[g]),remove:(0,e.useCallback)(p=>{s?f(`${n}.${p}.__deleted`,!0):g(h=>{const C=h.slice();return C.splice(p,1),C})},[g,n,f,s])}}var he=o(63619),je=o(53217),nn=o(97379),Y=o(65750);const an=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,E.wW)(rn),[s,i]=(0,e.useState)(He(t));(0,e.useEffect)(()=>i(He(t)),[t]);const d=m=>{n(on(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],h=s.map((C,x)=>x===g?m:C);i(h),(m[0]||p[0])&&d(h)};return e.createElement("div",null,!!s.length&&e.createElement("table",{className:r.table},e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Name"),e.createElement("th",null,"Value"),!a&&e.createElement("th",null))),e.createElement("tbody",null,s.map(([m,g],p)=>e.createElement("tr",{key:p},e.createElement("td",null,e.createElement(le.I,{readOnly:a,value:m,onChange:h=>f([h.currentTarget.value,g],p)})),e.createElement("td",null,e.createElement(le.I,{readOnly:a,value:g,onChange:h=>f([m,h.currentTarget.value],p)})),!a&&e.createElement("td",null,e.createElement(Y.A,{icon:"trash-alt",tooltip:"delete",onClick:()=>u(p)})))))),!a&&e.createElement(N.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>i([...s,["",""]])},"Add"))},rn=t=>({addButton:c.css`
    margin-top: ${t.spacing(1)};
  `,table:c.css`
    tbody td {
      padding: 0 ${t.spacing(1)} ${t.spacing(1)} 0;
    }
  `}),on=t=>{const n={};for(const[a,r]of t)a&&(n[a]=r);return n},He=t=>Object.entries(t??{}),sn=({value:t,onChange:n,readOnly:a=!1})=>{const r=(0,E.wW)(ln),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(N.zx,{className:r.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>n([...t??[],""])},"Add"))},ln=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 Qe=o(33950);const Re=({label:t,description:n,children:a,className:r,size:s="xl"})=>{const i=(0,E.wW)(cn),[d,u]=(0,e.useState)(!0),f=()=>u(!d);return e.createElement("div",{className:(0,c.cx)(i.wrapper,r)},e.createElement("div",{className:i.heading,onClick:f},e.createElement(Qe.U,{className:i.caret,size:s,onToggle:f,isCollapsed:d}),e.createElement("h6",null,t)),n&&e.createElement("p",{className:i.description},n),e.createElement("div",{className:d?i.hidden:void 0},a))},cn=t=>({wrapper:c.css`
    margin-top: ${t.spacing(1)};
    padding-bottom: ${t.spacing(1)};
  `,caret:c.css`
    margin-left: -${t.spacing(.5)}; // make it align with fields despite icon size
  `,heading:c.css`
    cursor: pointer;
    h6 {
      display: inline-block;
    }
  `,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;
  `}),Ye=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)};
  `}),dn=({option:t,pathPrefix:n,errors:a,defaultValues:r,readOnly:s=!1})=>{const i=(0,E.wW)(Ye),d=`${n}${t.propertyName}`,u=(0,B.Gc)(),{fields:f,append:m,remove:g}=ze({name:d,formAPI:u,defaults:r});return e.createElement("div",{className:i.wrapper},e.createElement(Re,{className:i.collapsibleSection,label:`${t.label} (${f.length})`,description:t.description},(f??r??[]).map((p,h)=>e.createElement("div",{key:h,className:i.wrapper},!s&&e.createElement(Y.A,{"data-testid":`${d}.${h}.delete-button`,icon:"trash-alt",tooltip:"delete",onClick:()=>g(h),className:i.deleteIcon}),t.subformOptions?.map(C=>e.createElement(Ee,{readOnly:s,defaultValue:p?.[C.propertyName],key:C.propertyName,option:C,pathPrefix:`${d}.${h}.`,error:a?.[h]?.[C.propertyName]})))),!s&&e.createElement(N.zx,{"data-testid":`${d}.add-button`,className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>m({__id:String(Math.random())})},"Add")))},mn=({option:t,pathPrefix:n,errors:a,defaultValue:r,readOnly:s=!1})=>{const i=(0,E.wW)(Ye),d=`${n}${t.propertyName}`,{watch:u}=(0,B.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(h=>e.createElement(Ee,{readOnly:s,defaultValue:r?.[h.propertyName],key:h.propertyName,option:h,pathPrefix:`${d}.`,error:a?.[h.propertyName]}))),!g&&!s&&e.createElement(N.zx,{className:i.addButton,type:"button",variant:"secondary",icon:"plus",size:"sm",onClick:()=>p(!0),"data-testid":`${d}.add-button`},"Add"))},Ee=({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(mn,{readOnly:d,defaultValue:i,option:t,errors:s,pathPrefix:u}):t.element==="subform_array"?e.createElement(dn,{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(un,{id:`${u}${t.propertyName}`,defaultValue:i,option:t,invalid:n,pathPrefix:u,readOnly:d,pathIndex:a}))},un=({option:t,invalid:n,id:a,pathPrefix:r="",pathIndex:s="",readOnly:i=!1})=>{const{control:d,register:u,unregister:f,getValues:m}=(0,B.Gc)(),g=`${r}${t.propertyName}`;switch((0,e.useEffect)(()=>()=>{f(g,{keepValue:!1})},[f,g]),t.element){case"checkbox":return e.createElement(Pe.X,{id:a,readOnly:i,disabled:i,className:pn.checkbox,...u(g),label:t.label,description:t.description});case"input":return e.createElement(le.I,{id:a,readOnly:i||fn(t,m,s),invalid:n,type:t.inputType,...u(g,{required:gn(t,m,s),validate:p=>t.validationRule!==""?Je(p,t.validationRule):!0}),placeholder:t.placeholder});case"select":return e.createElement(he.g,{render:({field:{onChange:p,ref:h,...C}})=>e.createElement(je.Ph,{disabled:i,...C,options:t.selectOptions??void 0,invalid:n,onChange:x=>p(x.value)}),control:d,name:g});case"textarea":return e.createElement(nn.K,{id:a,readOnly:i,invalid:n,placeholder:t.placeholder,...u(g,{required:t.required?"Required":!1,validate:p=>t.validationRule!==""?Je(p,t.validationRule):!0})});case"string_array":return e.createElement(he.g,{render:({field:{value:p,onChange:h}})=>e.createElement(sn,{readOnly:i,value:p,onChange:h}),control:d,name:g});case"key_value_map":return e.createElement(he.g,{render:({field:{value:p,onChange:h}})=>e.createElement(an,{readOnly:i,value:p,onChange:h}),control:d,name:g});default:return console.error("Element not supported",t.element),null}},pn={checkbox:c.css`
    height: auto; // native checkbox has fixed height which does not take into account description
  `},Je=(t,n)=>RegExp(n).test(t)?!0:"Invalid format",gn=(t,n,a)=>{if(!t.dependsOn)return t.required?"Required":!1;if((0,ee.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},fn=(t,n,a)=>t.dependsOn?(0,ee.isEmpty)(n(`${a}secureFields`))?n(`${a}secureSettings.${t.dependsOn}`):n(`${a}secureFields.${t.dependsOn}`):!1;function Ze({defaultValues:t,selectedChannelOptions:n,onResetSecureField:a,secureFields:r,errors:s,pathPrefix:i="",readOnly:d=!1}){const{watch:u}=(0,B.Gc)(),f=u();return e.createElement(e.Fragment,null,n.map((m,g)=>{const p=`${m.label}-${g}`,h=i.split("."),C=h.length>=2?f.items[Number(h[1])].settings[m.showWhen.field]:void 0;if(m.showWhen.field&&C!==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(N.zx,{onClick:()=>a(m.propertyName),fill:"text",type:"button",size:"sm"},"Clear")}));const x=(m.secure?s?.secureSettings:s?.settings)?.[m.propertyName],$=t?.settings?.[m.propertyName];return e.createElement(Ee,{defaultValue:$,readOnly:d,key:p,error:x,pathPrefix:i,pathSuffix:m.secure?"secureSettings.":"settings.",option:m})}))}function hn({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,E.wW)(En),h=L=>`${n}${L}`,{control:C,watch:x,register:$,trigger:J,formState:v,setValue:w}=(0,B.Gc)(),V=x(h("type"))??t.type,{loading:Z}=(0,ne._)(L=>L.testReceivers);(0,e.useEffect)(()=>{$(`${n}.__id`),$(`${n}.secureFields`)},[$,n]);const[k,pe]=(0,e.useState)(u??{}),ve=L=>{if(k[L]){const q={...u};delete q[L],pe(q),w(`${n}.secureFields`,q)}},Le=(0,e.useMemo)(()=>i.map(({name:L,type:q})=>({label:L,value:q})).sort((L,q)=>L.label.localeCompare(q.label)),[i]),Oe=async()=>{await J(),Object.keys(v.errors).length===0&&s&&s()},W=i.find(({type:L})=>L===V),j=W?.options.filter(L=>L.required),ce=W?.options.filter(L=>!L.required),be=`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:be,"data-testid":`${n}type`},e.createElement(he.g,{name:h("type"),defaultValue:t.type,render:({field:{ref:L,onChange:q,...ga}})=>e.createElement(je.Ph,{disabled:!m,inputId:be,...ga,width:37,options:Le,onChange:fa=>q(fa?.value)}),control:C,rules:{required:!0}}))),e.createElement("div",{className:p.buttons},g&&s&&e.createElement(N.zx,{disabled:Z,size:"xs",variant:"secondary",type:"button",onClick:()=>Oe(),icon:Z?"fa fa-spinner":"message"},"Test"),m&&e.createElement(e.Fragment,null,e.createElement(N.zx,{size:"xs",variant:"secondary",type:"button",onClick:()=>a(),icon:"copy"},"Duplicate"),r&&e.createElement(N.zx,{"data-testid":`${n}delete-button`,size:"xs",variant:"secondary",type:"button",onClick:()=>r(),icon:"trash-alt"},"Delete")))),W&&e.createElement("div",{className:p.innerContent},e.createElement(Ze,{defaultValues:t,selectedChannelOptions:j?.length?j:ce,secureFields:k,errors:d,onResetSecureField:ve,pathPrefix:n,readOnly:!m}),!!(j?.length&&ce?.length)&&e.createElement(Re,{label:`Optional ${W.name} settings`},W.info!==""&&e.createElement(P.b,{title:"",severity:"info"},W.info),e.createElement(Ze,{defaultValues:t,selectedChannelOptions:ce,secureFields:k,onResetSecureField:ve,errors:d,pathPrefix:n,readOnly:!m})),e.createElement(Re,{label:"Notification settings"},e.createElement(f,{pathPrefix:n,readOnly:!m}))))}const En=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 yn({pathPrefix:t}){const{register:n}=(0,B.Gc)();return(0,e.useEffect)(()=>{n(`${t}.__id`),n(`${t}.__deleted`)},[n,t]),e.createElement(e.Fragment,null)}function Xe({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,en.iG)(),h=(0,E.wW)(vn),C=n||{name:"",items:[{...a,__id:String(Math.random())}]},x=(0,B.cI)({defaultValues:JSON.parse(JSON.stringify(C))});(0,Te.x)(W=>W.unifiedAlerting.saveAMConfig=fe.oq);const{loading:$}=(0,ne._)(W=>W.saveAMConfig),{handleSubmit:J,register:v,formState:{errors:w},getValues:V}=x,{fields:Z,append:k,remove:pe}=ze({name:"items",formAPI:x,softDelete:!0}),ve=(0,e.useCallback)(W=>u.map(j=>j.trim().toLowerCase()).includes(W.trim().toLowerCase())?"Another receiver with this name already exists.":!0,[u]),Le=W=>{i({...W,items:W.items.filter(j=>!j.__deleted)})},Oe=()=>{p.error("There are errors in the form. Please correct them and try again!")};return e.createElement(B.RV,{...x},!t.alertmanager_config.route&&e.createElement(P.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(Le,Oe)},e.createElement("h4",{className:h.heading},m?n?"Update contact point":"Create contact point":"Contact point"),e.createElement(te.g,{label:"Name",invalid:!!w.name,error:w.name&&w.name.message,required:!0},e.createElement(le.I,{readOnly:!m,id:"name",...v("name",{required:"Name is required",validate:{nameIsAvailable:ve}}),width:39,placeholder:"Name"})),Z.map((W,j)=>{const ce=`items.${j}.`;if(W.__deleted)return e.createElement(yn,{key:W.__id,pathPrefix:ce});const be=n?.items.find(({__id:L})=>L===W.__id);return e.createElement(hn,{defaultValues:W,key:W.__id,onDuplicate:()=>{const L=V().items[j];k({...L,__id:String(Math.random())})},onTest:d?()=>{const L=V().items[j];d(L)}:void 0,onDelete:()=>pe(j),pathPrefix:ce,notifiers:r,secureFields:be?.secureFields,errors:w?.items?.[j],commonSettingsComponent:f,isEditable:m,isTestable:g})}),e.createElement(e.Fragment,null,m&&e.createElement(N.zx,{type:"button",icon:"plus",variant:"secondary",onClick:()=>k({...a,__id:String(Math.random())})},"Add contact point integration"),e.createElement("div",{className:h.buttons},m&&e.createElement(e.Fragment,null,$&&e.createElement(N.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!$&&e.createElement(N.zx,{type:"submit"},"Save contact point")),e.createElement(N.Qj,{disabled:$,fill:"outline",variant:"secondary","data-testid":"cancel-button",href:(0,H.eQ)("alerting/notifications",s)},"Cancel")))))}const vn=t=>({heading:c.css`
    margin: ${t.spacing(4,0)};
  `,buttons:c.css`
    margin-top: ${t.spacing(4)};

    & > * + * {
      margin-left: ${t.spacing(1)};
    }
  `}),qe=Object.freeze({__id:"",sendResolved:!0,secureSettings:{},settings:{},secureFields:{},type:"email"}),et=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,M.useDispatch)(),s=(0,Q.RY)(n),[i]=(0,e.useMemo)(()=>t?Qt(t,Ve):[void 0,{}],[t]),d=m=>{const g=Jt(m,qe);r((0,X.mM)({newConfig:Ge(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(P.b,{title:"Info",severity:"info"},"Note that empty string values will be replaced with global defaults where appropriate."),e.createElement(Xe,{isEditable:f,isTestable:f,config:a,onSubmit:d,initialValues:i,notifiers:Ve,alertManagerSourceName:n,defaultItem:qe,takenReceiverNames:u,commonSettingsComponent:qt}))},bn=({pathPrefix:t,className:n,readOnly:a=!1})=>{const{register:r}=(0,B.Gc)();return e.createElement("div",{className:n},e.createElement(te.g,null,e.createElement(Pe.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 ye=o(35029),An=o(64353),Cn=o(2594),Tn=o(16808),Sn=o(19191),tt=(t=>(t.predefined="Predefined",t.custom="Custom",t))(tt||{});const Pn=Object.values(tt).map(t=>({label:t,value:t})),Rn={annotations:[{key:"",value:""}],labels:[{key:"",value:""}]},xn=({isOpen:t,onDismiss:n,onTest:a})=>{const[r,s]=(0,e.useState)("Predefined"),i=(0,E.wW)(Dn),d=(0,B.cI)({defaultValues:Rn,mode:"onBlur"}),u=f=>{if(r==="Custom"){const m={annotations:f.annotations.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:h})=>({...g,[p]:h}),{}),labels:f.labels.filter(({key:g,value:p})=>!!g&&!!p).reduce((g,{key:p,value:h})=>({...g,[p]:h}),{})};a(m)}else a()};return e.createElement(ye.u,{onDismiss:n,isOpen:t,title:"Test contact point"},e.createElement("div",{className:i.section},e.createElement(An._,null,"Notification message"),e.createElement(Cn.S,{options:Pn,value:r,onChange:f=>s(f)})),e.createElement(B.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(Tn.Z,null)),e.createElement("div",{className:i.section},e.createElement(Sn.Z,null))),e.createElement(ye.u.ButtonRow,null,e.createElement(N.zx,{type:"submit"},"Send test notification")))))},Dn=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)};
  `}),xe=Object.freeze({__id:"",secureSettings:{},settings:{},secureFields:{},disableResolveMessage:!1,type:"email"}),nt=({existing:t,alertManagerSourceName:n,config:a})=>{const r=(0,ne._)(v=>v.grafanaNotifiers),[s,i]=(0,e.useState)(),d=(0,M.useDispatch)();(0,e.useEffect)(()=>{r.result||r.loading||d((0,X.Vj)())},[r,d]);const[u,f]=(0,e.useMemo)(()=>!t||!r.result?[void 0,{}]:Ht(t,r.result),[t,r.result]),m=v=>{const w=Yt(v,f,xe);d((0,X.mM)({newConfig:Ge(a,w,t?.name),oldConfig:a,alertManagerSourceName:Q.GC,successMessage:t?"Contact point updated.":"Contact point created",redirectPath:"/alerting/notifications"}))},g=v=>{i(v)},p=v=>{if(s){const w=f[s.__id],V=Ke(s,xe,"test",w),Z={alertManagerSourceName:n,receivers:[{name:"test",grafana_managed_receiver_configs:[V]}],alert:v};d((0,X.D8)(Z))}},h=(0,e.useMemo)(()=>a.alertmanager_config.receivers?.map(({name:v})=>v).filter(v=>v!==t?.name)??[],[a,t]),C=t?(t.grafana_managed_receiver_configs??[]).some(v=>Boolean(v.provenance)):!1,x=!(0,Q.RY)(n),$=x&&!C,J=x||C;return r.result?e.createElement(e.Fragment,null,C&&e.createElement(ie.Xq,{resource:ie.Uv.ContactPoint}),e.createElement(Xe,{isEditable:$,isTestable:J,config:a,onSubmit:m,initialValues:u,onTestChannel:g,notifiers:r.result,alertManagerSourceName:n,defaultItem:xe,takenReceiverNames:h,commonSettingsComponent:bn}),e.createElement(xn,{onDismiss:()=>i(void 0),isOpen:!!s,onTest:v=>p(v)})):e.createElement(O.u,{text:"Loading notifiers..."})},Mn=({config:t,receiverName:n,alertManagerSourceName:a})=>{const r=t.alertmanager_config.receivers?.find(({name:s})=>s===n);return r?a===Q.GC?e.createElement(nt,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(et,{config:t,alertManagerSourceName:a,existing:r}):e.createElement(P.b,{severity:"error",title:"Receiver not found"},"Sorry, this receiver does not seem to exist.")},Ln=({config:t,templateName:n,alertManagerSourceName:a})=>{const r=t.template_files?.[n],s=t.template_file_provenances?.[n];return r?e.createElement(Se,{alertManagerSourceName:a,config:t,existing:{name:n,content:r},provenance:s}):e.createElement(P.b,{severity:"error",title:"Template not found"},"Sorry, this template does not seem to exists.")};var On=o(52081);const at={smtp_require_tls:!0},In=({config:t,alertManagerSourceName:n})=>{const a=(0,M.useDispatch)();(0,Te.x)(g=>g.unifiedAlerting.saveAMConfig=fe.oq);const{loading:r,error:s}=(0,ne._)(g=>g.saveAMConfig),i=(0,Q.RY)(n),d=(0,B.cI)({defaultValues:JSON.parse(JSON.stringify({...at,...t.alertmanager_config.global??{}}))}),{handleSubmit:u,formState:{errors:f}}=d,m=g=>{a((0,X.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(B.RV,{...d},e.createElement("form",{onSubmit:u(m)},s&&e.createElement(P.b,{severity:"error",title:"Error saving receiver"},s.message||String(s)),jt.map(g=>e.createElement(Ee,{readOnly:i,defaultValue:at[g.propertyName],key:g.propertyName,option:g,error:f[g.propertyName],pathPrefix:""})),e.createElement("div",null,e.createElement(On.Lh,null,!i&&e.createElement(e.Fragment,null,r&&e.createElement(N.zx,{disabled:!0,icon:"fa fa-spinner",variant:"primary"},"Saving..."),!r&&e.createElement(N.zx,{type:"submit"},"Save global config")),e.createElement(N.Qj,{disabled:r,fill:"outline",variant:"secondary",href:(0,H.eQ)("alerting/notifications",n)},"Cancel")))))},Nn=({alertManagerSourceName:t,config:n})=>t===Q.GC?e.createElement(nt,{alertManagerSourceName:t,config:n}):e.createElement(et,{alertManagerSourceName:t,config:n}),wn=({config:t,alertManagerSourceName:n})=>e.createElement(Se,{config:t,alertManagerSourceName:n});var oe=o(51981),$n=o(46519),kn=o(38849),De=o(19985),rt=o(98102),Me=o(82002),ot=o(85655),st=o(97953),Wn=o(20194);const Un={pagerduty:"PagerDuty",pushover:"Pushover",slack:"Slack",opsgenie:"OpsGenie",webhook:"Webhook",victorops:"VictorOps",wechat:"WeChat"};function Fn(t,n){return t.grafana_managed_receiver_configs?Vn(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=Un[s]??(0,ee.capitalize)(s);return{...n,[i]:(n[i]??0)+(Array.isArray(r)?r.length:1)}},{})}function Vn(t,n){return t.map(a=>a.type).map(a=>n.find(r=>r.type===a)?.name??(0,ee.capitalize)(a)).reduce((a,r)=>({...a,[r]:(a[r]??0)+1}),{})}var lt=o(53731),Gn=o(16144);const it=({className:t,title:n,description:a,addButtonLabel:r,addButtonTo:s,children:i,showButton:d=!0})=>{const u=(0,E.wW)(Bn);return e.createElement(S.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(Gn.Link,{to:s},e.createElement(N.zx,{type:"button",icon:"plus"},r))),i)},Bn=t=>({heading:c.css`
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  `,description:c.css`
    color: ${t.colors.text.secondary};
  `});var Kn=o(44479),zn=o(52259);function jn({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 Hn({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(De.C,{color:"orange",icon:"exclamation-triangle",text:r,tooltip:n??"Error"})}function Qn({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(De.C,{color:r,text:s,tooltip:""})}function Yn({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(De.C,{color:a,text:r,tooltip:""})}const Jn=t=>{const n=K(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 Zn({lastNotifyDate:t}){return ue(t)?e.createElement(e.Fragment,null,"-"):e.createElement(S.Stack,{alignItems:"center"},e.createElement("div",null,`${(0,$n.CQ)(t).locale("en").fromNow(!0)} ago`),e.createElement(D.J,{name:"clock-nine"}),e.createElement("div",null,`${(0,kn.dq)(t,{format:"YYYY-MM-DD HH:mm:ss"})}`))}const Xn=["","0","0ms","0s","0m","0h","0d","0w","0y"],qn=t=>Xn.includes(t);function ea({notifiersState:t}){function n(){return[{id:"health",label:"Health",renderCell:({data:{lastError:r,lastNotify:s}})=>e.createElement(Qn,{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(Zn,{lastNotifyDate:r}),size:3},{id:"lastNotifyDuration",label:"Last duration",renderCell:({data:{lastNotify:r,lastNotifyDuration:s}})=>e.createElement(e.Fragment,null,ue(r)&&qn(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 ta=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),r=(0,Q.RY)(n),s=(0,st.Ko)(n),i=(0,ne._)(v=>v.grafanaNotifiers),{contactPointsState:d,errorStateAvailable:u}=Jn(n),[f,m]=(0,e.useState)(),[g,p]=(0,e.useState)(!1),h=v=>{(0,Wn.nv)(v,t)?p(!0):m(v)},C=()=>{f&&a((0,X.X4)(f,n)),m(void 0)},x=(0,zn.HU)(t.alertmanager_config.receivers??[]),$=(0,e.useMemo)(()=>x?.map(v=>({id:v.name,data:{name:v.name,types:Object.entries(Fn(v,i.result??[])).map(([w,V])=>V>1?`${w} (${V})`:w),grafanaAppReceiverType:v.grafanaAppReceiverType,provisioned:v.grafana_managed_receiver_configs?.some(w=>w.provenance)}}))??[],[i.result,x]),J=ra(n,u,d,h,s,r);return e.createElement(it,{title:"Contact points",description:"Define where notifications are sent, for example, email or Slack.",showButton:!r&&Me.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:v}})=>e.createElement(ea,{notifiersState:d?.receivers[v]?.notifiers??{}}):void 0}),!!g&&e.createElement(ye.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(ye.u.ButtonRow,null,e.createElement(N.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:C,onDismiss:()=>m(void 0)}))},na=(t,n)=>t?.receivers[n]?.errorCount??0,aa=(t,n)=>{const a=Object.values(t?.receivers[n]?.notifiers??{});return a.length===0||a.flat().some(s=>ue(s.lastNotifyAttempt))};function ra(t,n,a,r,s,i){const d=(0,E.wW)(ot.D),u=[{id:"name",label:"Contact point name",renderCell:({data:{name:m,provisioned:g}})=>e.createElement(S.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(Kn.i,{grafanaAppType:g}):m.join(", ")),size:1}],f={id:"health",label:"Health",renderCell:({data:{name:m}})=>a&&e.createElement(Yn,{errorsByReceiver:na(a,m),someWithNoAttempt:aa(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(jn,{permissions:s,alertManagerName:t,receiverName:g,onClickDeleteReceiver:r}),(i||m)&&e.createElement(Hn,{permissions:s,alertManagerName:t,receiverName:g}))),size:"100px"}]}var oa=o(80498);const sa=({config:t,alertManagerName:n})=>{const a=(0,M.useDispatch)(),[r,s]=(0,e.useState)({}),i=(0,E.wW)(ot.D),d=(0,st.Ko)(n),u=(0,e.useMemo)(()=>Object.entries(t.template_files).map(([h,C])=>({name:h,template:C,provenance:(t.template_file_provenances??{})[h]})),[t]),[f,m]=(0,e.useState)(),g=()=>{f&&a((0,X.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:Me.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:h,provenance:C},x)=>{const $=!!r[p];return e.createElement(e.Fragment,{key:p},e.createElement("tr",{key:p,className:x%2===0?i.evenRow:void 0},e.createElement("td",null,e.createElement(Qe.U,{isCollapsed:!r[p],onToggle:()=>s({...r,[p]:!$})})),e.createElement("td",null,p," ",C&&e.createElement(ie.C0,null)),e.createElement("td",{className:i.actionsCell},C&&e.createElement(Y.A,{to:(0,H.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/edit`,n),tooltip:"view template",icon:"file-alt"}),!C&&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"})),Me.Vt.hasPermission(d.create)&&e.createElement(Y.A,{to:(0,H.eQ)(`/alerting/notifications/templates/${encodeURIComponent(p)}/duplicate`,n),tooltip:"Copy template",icon:"copy"}),!C&&e.createElement(oe.q,{actions:[d.delete]},e.createElement(Y.A,{onClick:()=>m(p),tooltip:"delete template",icon:"trash-alt"})))),$&&e.createElement("tr",{className:x%2===0?i.evenRow:void 0},e.createElement("td",null),e.createElement("td",{colSpan:2},e.createElement(oa.C,{label:"Description",horizontal:!0},e.createElement(We,{width:"auto",height:"auto",autoHeight:!0,value:h,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)}))},la=({config:t,alertManagerName:n})=>{const a=n!==Q.GC,r=(0,Q.RY)(n);return e.createElement(S.Stack,{direction:"column",gap:4},e.createElement(ta,{config:t,alertManagerName:n}),!r&&e.createElement(sa,{config:t,alertManagerName:n}),a&&e.createElement(oe.q,{actions:[M.AccessControlAction.AlertingNotificationsExternalWrite]},e.createElement(P.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,H.eQ)("alerting/notifications/global-config",n),variant:"secondary"},r?"View global config":"Edit global config"))))};var ia=o(29614),ca=o(23403);function da({errorCount:t}){const n=(0,E.wW)(dt);return e.createElement("div",{className:n.warning,"data-testid":"receivers-notification-error"},e.createElement(S.Stack,{alignItems:"flex-end",direction:"column"},e.createElement(S.Stack,{alignItems:"center"},e.createElement(D.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 ma=()=>{const t=(0,ca.k)("notification"),[n,a]=(0,ia.k)(t),r=(0,M.useDispatch)(),s=(0,E.wW)(dt),{id:i,type:d}=(0,y.UO)(),u=(0,y.TH)(),f=u.pathname.endsWith("/alerting/notifications"),m=Ue(u),g=(0,ne._)(k=>k.amConfigs),{result:p,loading:h,error:C}=n&&g[n]||fe.oq,x=(0,ne._)(k=>k.grafanaNotifiers),$=f||!p,J=f;(0,e.useEffect)(()=>{n&&$&&r((0,X.Yh)(n))},[n,r,$]),(0,e.useEffect)(()=>{n===Q.GC&&!(x.result||x.loading||x.error)&&r((0,X.Vj)())},[n,r,x]);const w=K(n??"")?.errorCount??0,V=!f;let Z=ua(d,i?decodeURIComponent(i):void 0,m);return n?e.createElement(ge.J,{pageId:"receivers",pageNav:Z},e.createElement("div",{className:s.headingContainer},e.createElement(se.P,{current:n,disabled:V,onChange:a,dataSources:t}),J&&w>0&&e.createElement(da,{errorCount:w})),C&&!h&&e.createElement(P.b,{severity:"error",title:"Error loading Alertmanager config"},C.message||"Unknown error."),e.createElement(Ae.u,{currentAlertmanager:n}),h&&!p&&e.createElement(O.u,{text:"loading configuration..."}),p&&!C&&e.createElement(y.rs,null,e.createElement(y.AW,{exact:!0,path:"/alerting/notifications"},e.createElement(la,{config:p,alertManagerName:n})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/templates/new"},e.createElement(wn,{config:p,alertManagerSourceName:n})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/templates/:name/duplicate"},({match:k})=>k?.params.name&&e.createElement(Kt,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(k?.params.name)})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/templates/:name/edit"},({match:k})=>k?.params.name&&e.createElement(Ln,{alertManagerSourceName:n,config:p,templateName:decodeURIComponent(k?.params.name)})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/receivers/new"},e.createElement(Nn,{config:p,alertManagerSourceName:n})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/receivers/:name/edit"},({match:k})=>k?.params.name&&e.createElement(Mn,{alertManagerSourceName:n,config:p,receiverName:decodeURIComponent(k?.params.name)})),e.createElement(y.AW,{exact:!0,path:"/alerting/notifications/global-config"},e.createElement(In,{config:p,alertManagerSourceName:n})))):f?e.createElement(ge.J,{pageId:"receivers",pageNav:Z},e.createElement(G.I,{availableAlertManagers:t})):e.createElement(y.l_,{to:"/alerting/notifications"})};function ua(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 pa=(0,U.Pf)(ma,{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:(_,T,o)=>{o.d(T,{h:()=>A});var c=o(29427);const A=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"]})})})},45524:(_,T,o)=>{o.d(T,{J:()=>b});var c=o(68404),A=o(79396);const b=({children:e,pageId:y,pageNav:S,isLoading:E})=>c.createElement(A.T,{pageNav:S,navId:y},c.createElement(A.T.Contents,{isLoading:E},e))},51981:(_,T,o)=>{o.d(T,{q:()=>b});var c=o(68404),A=o(82002);const b=({actions:e,children:y,fallback:S=!0})=>e.some(E=>A.Vt.hasAccess(E,S))?c.createElement(c.Fragment,null,y):null},731:(_,T,o)=>{o.d(T,{u:()=>D});var c=o(52423),A=o(68404),b=o(72648),e=o(45253),y=o(39031),S=o(30173),E=o(45849);function D({currentAlertmanager:O}){const U=(0,b.wW)(P),{useGetAlertmanagerChoiceStatusQuery:M}=S.h,{currentData:F}=M(),R=O===E.GC;if(!(F?.alertmanagersChoice&&[y.TE.External,y.TE.All].includes(F?.alertmanagersChoice))||!R)return null;const z=F.numExternalAlertmanagers>0;return F.alertmanagersChoice===y.TE.External?A.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.",A.createElement("div",{className:U.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):F.alertmanagersChoice===y.TE.All&&z?A.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.",A.createElement("div",{className:U.adminHint},"To change your Alertmanager setup, go to the Alerting Admin page. If you do not have access, contact your Administrator.")):null}const P=O=>({adminHint:c.css`
    font-size: ${O.typography.bodySmall.fontSize};
    font-weight: ${O.typography.bodySmall.fontWeight};
  `})},88331:(_,T,o)=>{o.d(T,{I:()=>E});var c=o(68404),A=o(45253),b=o(29614),e=o(94984);const y=()=>c.createElement(A.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=()=>c.createElement(A.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:D})=>{const[P,O]=(0,b.k)(D),U=D.length>0;return c.createElement("div",null,U?c.createElement(c.Fragment,null,c.createElement(e.P,{onChange:O,dataSources:D}),c.createElement(S,null)):c.createElement(y,null))}},40106:(_,T,o)=>{o.d(T,{C0:()=>S,Uv:()=>e,Xq:()=>y});var c=o(68404),A=o(45253),b=o(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 y=({resource:E})=>c.createElement(A.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=()=>c.createElement(b.C,{text:"Provisioned",color:"purple"})},44479:(_,T,o)=>{o.d(T,{i:()=>E});var c=o(52423),A=o(68404),b=o(72648),e=o(52081),y=o(2390);const S={[y.W.OnCall]:"public/img/alerting/oncall_logo.svg",[y.W.Incident]:"",[y.W.MachineLearning]:""},E=({grafanaAppType:P})=>{const O=(0,b.wW)(D);return A.createElement("div",{className:O.wrapper},A.createElement(e.Lh,{align:"center",spacing:"xs"},A.createElement("img",{src:S[P],alt:"",height:"12px"}),A.createElement("span",null,P)))},D=P=>({wrapper:c.css`
    text-align: left;
    height: 22px;
    display: inline-flex;
    padding: 1px 4px;
    border-radius: 3px;
    border: 1px solid rgba(245, 95, 62, 1);
    color: rgba(245, 95, 62, 1);
    font-weight: ${P.typography.fontWeightRegular};
  `})},52259:(_,T,o)=>{o.d(T,{Kt:()=>M,HU:()=>F});var c=o(3363),A=o(54899),b=o(29427);const e=b.C.injectEndpoints({endpoints:R=>({getOnCallIntegrations:R.query({queryFn:async()=>({data:await y()}),providesTags:["AlertmanagerChoice"]})})});async function y(){try{return(await(0,c.n)((0,A.i)().fetch({url:"/api/plugin-proxy/grafana-oncall-app/api/internal/v1/alert_receive_channels/",showErrorAlert:!1,showSuccessAlert:!1}))).data.map(I=>I.integration_url)}catch{return[]}}const{useGetOnCallIntegrationsQuery:S}=e;var E=o(58509),D=o(2390);const P=(R,I)=>I.includes(R),O=(R,I)=>{if(!R.grafana_managed_receiver_configs)return!1;const z=R.grafana_managed_receiver_configs.length===1,K=P(R.grafana_managed_receiver_configs[0]?.settings?.url??"",I);return z&&K},U=()=>{const{installed:R}=(0,E.n)(D.W.OnCall),{data:I}=S(void 0,{skip:!R});return K=>{if(R&&O(K,I??[]))return D.W.OnCall}},M=R=>{const I=U(),z=K=>({label:K.name,value:K.name,grafanaAppReceiverType:I(K)});return R.map(z)},F=R=>{const I=U();return R.map(z=>({...z,grafanaAppReceiverType:I(z)}))}},65750:(_,T,o)=>{o.d(T,{A:()=>e});var c=o(68404),A=o(61860),b=o(31403);const e=({tooltip:y,icon:S,to:E,target:D,onClick:P,className:O,tooltipPlacement:U="top",...M})=>{const F=typeof y=="string"?y:void 0;return c.createElement(A.u,{content:y,placement:U},E?c.createElement(b.Qj,{variant:"secondary",fill:"text",icon:S,href:E,size:"sm",target:D,...M,"aria-label":F}):c.createElement(b.zx,{className:O,variant:"secondary",fill:"text",size:"sm",icon:S,type:"button",onClick:P,...M,"aria-label":F}))}},29614:(_,T,o)=>{o.d(T,{k:()=>E});var c=o(68404),A=o(96044),b=o(58379),e=o(37190),y=o(45849);function S(D){return(0,c.useCallback)(P=>D.map(U=>U.name).includes(P),[D])}function E(D){const[P,O]=(0,A.K)(),U=S(D),M=(0,c.useCallback)(I=>{U(I)&&(I===y.GC?(b.Z.delete(e.de),O({[e.c4]:null})):(b.Z.set(e.de,I),O({[e.c4]:I})))},[O,U]),F=P[e.c4];if(F&&typeof F=="string")return U(F)?[F,M]:[void 0,M];const R=b.Z.get(e.de);return R&&typeof R=="string"&&U(R)?(M(R),[R,M]):U(y.GC)?[y.GC,M]:[void 0,M]}},23403:(_,T,o)=>{o.d(T,{k:()=>b});var c=o(68404),A=o(45849);function b(e){return(0,c.useMemo)(()=>(0,A.LE)(e),[e])}},58509:(_,T,o)=>{o.d(T,{n:()=>b});var c=o(22350),A=o(13011);function b(e){const{loading:y,error:S,value:E}=(0,c.Z)(()=>(0,A.a)(e,{showErrorAlert:!1})),D=E&&!S&&!y,P=E?.enabled;return y&&!E?{loading:!0}:!D||!P?{loading:!1,installed:!1}:{loading:y,installed:!0,settings:E}}},85655:(_,T,o)=>{o.d(T,{D:()=>A});var c=o(52423);const A=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:(_,T,o)=>{o.d(T,{W:()=>c});var c=(A=>(A.Incident="grafana-incident-app",A.OnCall="grafana-oncall-app",A.MachineLearning="grafana-ml-app",A))(c||{})},35918:(_,T,o)=>{o.d(T,{G:()=>c});function c(A,b){const e=A.replace(/\(copy( [0-9]+)?\)$/,"").trim();let y=`${e} (copy)`;for(let S=2;b.includes(y);S++)y=`${e} (copy ${S})`;return y}}}]);

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